Skip to content

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.

model-apps 2.20.0: built-in Dataverse operations, plan assumptions, multi-table lookups, one page-error pattern, Custom API without a flag, and tracked bug fixes (#767)

Akshay Malooa887c53f100f
diff --git a/.github/workflows/model-apps-script-tests.yml b/.github/workflows/model-apps-script-tests.yml
index bc869248c..1f87ecac4 100644
--- a/.github/workflows/model-apps-script-tests.yml
+++ b/.github/workflows/model-apps-script-tests.yml
@@ -55,7 +55,7 @@ on:
permissions:
contents: read
-# A new push to the same PR supersedes the run in flight: without this, all eight jobs of the old run
+# A new push to the same PR supersedes the run in flight: without this, every job of the old run
# kept going to completion for a result nobody reads.
concurrency:
group: model-apps-script-tests-${{ github.event.pull_request.number || github.ref }}
@@ -108,20 +108,26 @@ jobs:
working-directory: plugins/model-apps
run: node scripts/run-tests.js
- # The routing eval's runner launches agent CLIs as child processes, and on Windows
- # those are .cmd shims that must go through cmd.exe (quoting, process-tree kill). Its
- # unit tests drive a fake agent only — no model, no credentials — so run them on every
- # OS here; in the Ubuntu-only eval job below the Windows shim test would always skip.
- - name: run-routing-eval-unit-tests
- shell: bash
- run: node --test evals/model-apps/routing/tests/*.test.js
-
+ # The eval tests and runners, on the same three systems and two Node versions as the plugin's own suite. They read
+ # committed fixtures, which a Windows checkout gives CRLF line ends (core.autocrlf), and the routing runner starts
+ # agent CLIs as child processes, which on Windows are .cmd shims that must go through cmd.exe (quoting, process-tree
+ # kill). Run on Ubuntu and Node 20 alone, a fixture or a grader that broke on another system or Node version passed CI.
test-model-apps-evals:
- name: test-model-apps-evals
- runs-on: ubuntu-latest
+ name: test-model-apps-evals (${{ matrix.os }}, node ${{ matrix.node }})
+ runs-on: ${{ matrix.os }}
timeout-minutes: 10
env:
POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: "1"
+ strategy:
+ fail-fast: false
+ matrix:
+ os:
+ - ubuntu-latest
+ - windows-latest
+ - macos-latest
+ node:
+ - 20
+ - 22
steps:
- name: checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -129,7 +135,7 @@ jobs:
- name: setup-node
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
- node-version: 20
+ node-version: ${{ matrix.node }}
# The eval harness lives at the repo root (evals/model-apps/**) but is
# owned by this plugin, so it is gated by the same path filter. First the
@@ -161,12 +167,23 @@ jobs:
# CI. This job installs them for the test run only, outside the plugin (which ships no dependencies), at
# exact versions, so a new parser release can never turn a green run red without a commit.
test-model-apps-lexer-oracles:
- name: test-model-apps-lexer-oracles
+ name: test-model-apps-lexer-oracles (node ${{ matrix.node }})
runs-on: ubuntu-latest
# The sweeps and the differential take a few minutes on top of the suite.
timeout-minutes: 30
env:
POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: "1"
+ # Both Node versions, on one system. The lexer tells identifier characters by Unicode property escapes
+ # (\p{ID_Continue}), whose tables come with each Node version's JavaScript engine, and the parsers it is compared
+ # with carry tables of their own, so a sweep can judge differently on the other version. Each sweep compares the
+ # lexer and the parsers on the same text, so a system's own differences (line ends of a checkout, paths) reach
+ # both sides alike; the suite's differences between systems are what the matrix job above runs on all three.
+ strategy:
+ fail-fast: false
+ matrix:
+ node:
+ - 20
+ - 22
steps:
- name: checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -174,7 +191,7 @@ jobs:
- name: setup-node
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
- node-version: 20
+ node-version: ${{ matrix.node }}
# `--ignore-scripts` because neither package needs an install script, and `--prefix` under
# RUNNER_TEMP so that nothing lands in the plugin's tree. The version check fails the job if a
diff --git a/.github/workflows/pcf-script-tests.yml b/.github/workflows/pcf-script-tests.yml
index cbbdb719a..acdb4062f 100644
--- a/.github/workflows/pcf-script-tests.yml
+++ b/.github/workflows/pcf-script-tests.yml
@@ -67,19 +67,28 @@ jobs:
- name: run-pcf-script-tests
shell: bash
run: node scripts/run-tests.js
+ # The eval tests and the full eval run, on the same three systems and two Node versions as the script tests: they
+ # read committed control projects, which a Windows checkout gives CRLF line ends (core.autocrlf), through the
+ # plugin's own manifest and source gates. Run on Ubuntu and Node 20 alone, a case that broke on another system or
+ # Node version passed CI.
test-pcf-evals:
- name: test-pcf-evals
- runs-on: ubuntu-latest
+ name: test-pcf-evals (${{ matrix.os }}, node ${{ matrix.node }})
+ runs-on: ${{ matrix.os }}
timeout-minutes: 20
env:
POWER_PLATFORM_SKILLS_TELEMETRY_PCF_OPTOUT: "1"
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, windows-latest, macos-latest]
+ node: [20, 22]
steps:
- name: checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: setup-node
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
- node-version: 20
+ node-version: ${{ matrix.node }}
- name: run-pcf-eval-tests
shell: bash
run: node --test evals/pcf/tests/*.test.js
diff --git a/evals/model-apps/genpage/EVAL_GUIDE.md b/evals/model-apps/genpage/EVAL_GUIDE.md
index e3a0e669c..90505b5bb 100644
--- a/evals/model-apps/genpage/EVAL_GUIDE.md
+++ b/evals/model-apps/genpage/EVAL_GUIDE.md
@@ -75,7 +75,7 @@ Layers 1 and 2 are automated. Layer 3 is human judgment by design — visual qua
- A recorded command is read as text, not as a shell (`lib/evidence-utils.js`, "How the graders read a recorded command"). The verb of `apps.js`, `genpage.js` and `solution-settings.js` is read the way the script reads it — `apps.js --env <url> create` is a `create`, as `apps.js create --env <url>` is; a switch just before the verb is taken to stand alone, an inference made on purpose (the script's own parser would take the verb as the switch's value) — and EVERY run of a script in a call counts, in its text and in an event's `argv`: `apps.js list …; apps.js create …` is a mutation, so it needs the latest successful auth gate, has a result event of its own, and breaks a refusal. The verbs that write are `apps.js create`, `genpage.js add-to-app | remove-from-app | delete` and `solution-settings.js import` (`template` only prints a settings file), beside the upload and the scripts that only write; `pac solution import`, which `solution-settings.js import` falls back to, is one too. Limits, by design: a command line handed to a wrapper as one string (`bash -c '…'`, `cmd /c "…"`, `pwsh -Command "…"`, `eval`) is one quoted word and is not read, a variable, an escape or a line continuation is not followed, and the text of a here-document is read as if it were commands; prose is not told from a command (a log line that names a write after a read is graded as the write); `;`, `&&` and `|` are not told apart, so a write in the same call as its gate is not judged against that gate and the environment compared with the gate is the call's last `--env`; a phase pattern also still matches its older raw-text form, so a run inside a wrapper's string can still credit a phase; and a listing that is not valid JSON lists nothing as an event's result, while on a log's `Result:` line it goes on to the PAC table reader, as before
- Current upload commands use `genpage-upload.js` with file transport; the preservation fixture compares exact approved/forwarded text and before/after name, model and binding sets. `--app-id` is optional for a create — the first page of a new app has none, and no `--add-to-sitemap` — while a create that names an app includes `--add-to-sitemap`, and an update names its app and omits it (the update that completes a create that did not finish is the exception). `forwarded` records what the script hands the page backend: a flag an update leaves out forwards nothing, so the page keeps its own name, model and data sources, and a name with a straight `"`, a `%` or a `$(…)` is stored exactly
- A divergence refusal (`no-base`, `deployed-changed`, `deployed-unreadable`) stops an update before the page backend writes (`ok: false`, no write, no forwarded args). `--overwrite-deployed` needs the `Choice:` line that upload command consumes to be exactly `Choice: Overwrite the deployed changes`. Each `genpage-upload.js` line consumes the pending choice, so one approval does not cover a later upload
-- Custom API discovery/gates/bindings/runtime/update stages agree; optional packaging names every deployed page and preserves failures/read-back evidence
+- Custom API discovery/bindings/runtime/update stages agree; optional packaging names every deployed page and preserves failures/read-back evidence
When successful downloads are recorded, before-page evidence needs one identifiable producing output
directory. Environment/app checks use that producer, not unrelated same-ID downloads elsewhere;
unmatched or ambiguous producers refuse preservation rather than guessing a historical source.
@@ -85,6 +85,7 @@ Layers 1 and 2 are automated. Layer 3 is human judgment by design — visual qua
- An edit keeps what its plan's Preservation Constraints promise: every identifier a constraint quotes in a code span and the downloaded page (`before/`) uses is still used by the edited page (comments do not count). Constraints written only in prose are left to a person
- Sample data handed to `provision-entities.js` is realistic: no lorem ipsum, no placeholder word (`test`, `sample`, `TBD`, `N/A`…) or numbered table name (`Project 1`), and no table whose rows repeat one name
- Per-eval discovery, provisioning, schema and deployment expectations compare structured evidence read by `lib/expectation-evidence.js` — `list-tables`/`list-languages`/the type generator/upload flags and their recorded results, the plan's entity blocks, the entity-creation transactions, and the choice enums in the captured `RuntimeTypes.ts` — on either upload transport. The plugin's own scripts are read as data: `scripts/list-tables.js` (a table exists when `tables` holds its exact logical name; `missing` names the terms with none; a failed read confirms nothing), `scripts/apps.js list` (`apps`), `scripts/genpage.js list` (`pages`, each with its `pageId` and `name`) and `scripts/list-languages.js` (`languages`; it is the only source, so a failed read detects nothing and a `pac model list-languages` after it is not credited). The type generator is `scripts/genpage.js types` and the edit flow's download `scripts/genpage.js download`; a capture made before the scripts records the `pac model list-tables`, `pac model list`, `pac model list-languages`, `pac model genpage list | download | generate-types` forms, and those are read too. The new-app expectations (eval 8) require the plugin's order: the first page uploaded with no app and no `--add-to-sitemap`, then `apps.js create --solution --page-id --publish` (which pins the first page's tables itself, so nothing has to follow it), and every upload after it naming the app it returned — `pac model create` does not satisfy them. These recognizers read a script's verb the way the mutation checks do, so a verb after its flags (`genpage.js --env <url> types …`) counts, and a "types … SKIPPED (mock data)" expectation fails for a run that generated types that way. A listing recorded as the JSON the scripts print — one line, as a parsed result, as text, or as a log's `Result: {…}` line — is read as data (`id`/`pageId`/`appId` and `name`); JSON that does not parse lists nothing, and only output that is not JSON (a PAC table, a log's bullets) goes to the older table reader
+- A newly authored plan's records (evals 26 and 27; `references/plan-schema.md` "Assumptions, data semantics and lookup metadata"): the written plan in required mode, the approved preview the run saved (`fixture.json` `semantics.approvedPlan`) holding the same assumptions, decisions and lookup records field by field, and the run's own `genpage-plan-provenance.js verify --require-assumptions` whose `semanticsHash` is the hash of exactly those records. Eval 26 adds the question it answered (`semantics.interactions`, in order: the planner's `needs_input` with several candidates and no default, the maker's `AskUserQuestion` answer handed back to the planner by question id, the plan approval), the user-confirmed assumption both documents keep for it, the `get-lookup-metadata.js` read made before approval whose successful answer is the saved `lookup-metadata.json` (`semantics.lookupMetadata`) and agrees with every observed lookup record, the lookup typed in `RuntimeTypes.ts` with exactly its recorded targets, and the Phase 5a gate — a passing `--require-observed-lookups --lookup-metadata` verification of these records before the page is written. A declared artifact or event that is missing fails rather than skips. These checks prove that a recorded run agrees with itself, not that a person answered or that the answer is what the request meant; older plans without the records are not graded by them
**Runner:** `evals/model-apps/genpage/run-layer-1.js`
**Library:** `lib/assertions-layer-1.js` (one check function per assertion text)
@@ -104,14 +105,17 @@ Layers 1 and 2 are automated. Layer 3 is human judgment by design — visual qua
- Unsized Fluent icons only (e.g., `AddRegular`, not `Add24Regular`)
- Every icon name in `@fluentui/react-icons` imports appears in `references/verified-icons.txt`
- A `try`/`catch` marker for Dataverse awaits (not proof that every await is enclosed)
+- Whether every failure reaches the page's reporter is not graded yet: no check proves that each DataAPI failure of a page goes through `reportPageError` into a rendered `PageErrorBar` inside `PageErrorBoundary` (`references/rules.md` Critical Rule 22)
- No `TODO`/`FIXME`/`...` placeholders
- Lookup fields use `@OData.Community.Display.V1.FormattedValue` annotations
- `<DataGrid>` usage imports `createTableColumn` + configures `columnSizingOptions` or `resizableColumns`
- Every effective navigation target is checked with the production resolver; current before/after snapshots must differ by exact substitutions only, and only affected pages reupload
- The production `pageStructureProblems` gate rejects truncated modules, including unfinished statements after valid exports
-- The Custom API lifecycle grades actual saved TSX, method/parameter/bound-record parity, sanitized result handling and preservation versus explicit clear
+- The Custom API lifecycle grades actual saved TSX, method/parameter/bound-record parity, sanitized result handling and preservation versus explicit clear. For a clear of a page that binds `WhoAmI` or `RetrieveVersion`, the grader reads the maker's `Clear choice:` line recorded right before each upload the clear covers; it does not check that the choice was made before the edit plan was approved, which the skill requires (`edit-flow.md`, Edit Phase 3).
-Plus per-eval `expectations` for **Phase 5, 5a, 5b and 5c**. `Edit Phase 5` entries remain Layer-1 expectations. The column-name expectations (eval 1's Phase 5b, in both layers, and eval 7's) are graded by `lib/column-contract.js` against the RuntimeTypes.ts a fixture kept: every column a page names in its dataApi calls — a `select` list, an `orderBy` or `filter` expression, the keys of a `createRow`/`updateRow` payload, an options object or select list written as a name it declares, and each `<column>@OData.Community.Display.V1.FormattedValue` key it reads — must be one the schema declares on that table (or a system column every user-owned table has and the type generator does not write, such as `createdon`). A fixture that kept no RuntimeTypes.ts reports `column-name verification requires RuntimeTypes.ts fixture`. Other unregistered expectations are reported as skips, not claimed as coverage. The API request scorer supports literal request objects in named helpers and scalar annotations; it is not a TypeScript compiler or a runtime execution oracle.
+Whether a page applies a style the maker asked for (a plan whose `Styling:` line starts with `Maker-requested:`) is not graded yet.
+
+Plus per-eval `expectations` for **Phase 5, 5a, 5b and 5c**. `Edit Phase 5` entries remain Layer-1 expectations. The column-name expectations (eval 1's Phase 5b, in both layers, and eval 7's) are graded by `lib/column-contract.js` against the RuntimeTypes.ts a fixture kept: every column a page names in its dataApi calls — a `select` list, an `orderBy` or `filter` expression, the keys of a `createRow`/`updateRow` payload, an options object or select list written as a name it declares, and each `<column>@OData.Community.Display.V1.FormattedValue` key it reads — must be one the schema declares on that table (or a system column every user-owned table has and the type generator does not write, such as `createdon`). A fixture that kept no RuntimeTypes.ts reports `column-name verification requires RuntimeTypes.ts fixture`. Lookup-identity use in page code is not graded yet: no check proves that a page reads, filters, retrieves, opens or writes a lookup only through its normalized table-and-id pair (`references/rules.md` Critical Rule 23) — eval 26 grades the question, the lookup metadata and the plan records behind its page, not the page's lookup code. Other unregistered expectations are reported as skips, not claimed as coverage. The API request scorer supports literal request objects in named helpers and scalar annotations; it is not a TypeScript compiler or a runtime execution oracle.
**Structural page checks:** several per-eval expectations are graded from how a page is BUILT rather than whether a word appears in it — eval 4's review step showing every entered field before the submit, and a label on every form field (its own `aria-label`/`aria-labelledby`, or a Fluent `<Field label>` around it); eval 5's components and utilities kept top level (a nested PascalCase component, or a nested function that reads nothing from the one around it, fails; a handler that closes over state does not); eval 12's search box beside a filter toolbar; eval 13's shown text through the `translate` (or `t`) helper; and eval 15's choice values named after the RuntimeTypes.ts member they are. `lib/tsx-structure.js` reads elements, attributes, JSX text and function scopes from the plugin's lexer view, where strings, comments and JSX text are blanked at their offsets, and `lib/page-checks.js` holds the checks; each states what it does not judge, which stays with the Layer 3 rubric. Eval 4's step navigation ("step state management … and Next/Back navigation") is deliberately not graded: whether Next and Back move the step is the value the step's setter receives — an updater can compute the next step and return the old one — which a scan of the page's text cannot prove; it needs data-flow analysis, and the coverage baseline records it as unscored with that reason.
@@ -149,11 +153,11 @@ still refuse lookup provenance.
All eval definitions live in `evals.json` alongside this file. The file contains:
-- `common_workflow_assertions`: **19** registered workflow checks, each passed or explicitly skipped when inapplicable.
+- `common_workflow_assertions`: **18** registered workflow checks, each passed or explicitly skipped when inapplicable.
- `common_code_assertions`: **21** registered code checks.
-- `evals`: **25** prompt definitions, each with `id`, `tier`, `prompt`, `data`, and per-eval `expectations`.
+- `evals`: **27** prompt definitions, each with `id`, `tier`, `prompt`, `data`, and per-eval `expectations`.
-The `data` field specifies scenario assumptions for a manual capture or constructed fixture. The offline harness does not provide responses to `AskUserQuestion` or verify every recorded answer. The corpus contains **33 fixture directories / 37 top-level TSX files**, representing 25 prompt IDs. IDs **none** have no fixture — every registered prompt is executed.
+The `data` field specifies scenario assumptions for a manual capture or constructed fixture. The offline harness does not provide responses to `AskUserQuestion` or verify every recorded answer. The corpus contains **35 fixture directories / 39 top-level TSX files**, representing 27 prompt IDs. IDs **none** have no fixture — every registered prompt is executed.
### Enumerating registered and unmatched checks
@@ -211,7 +215,7 @@ Each eval in `evals.json` has a `tier` field for selective execution.
| Tier | Count | When to run | Eval IDs |
|------|------|-------------|----------|
| `smoke` | 5 | **Every PR** that touches the skill, agents, rules, or evals | 1, 2, 3, 16, 17 |
-| `full` | 17 | Nightly or pre-release; covers core workflows | 4, 5, 6, 7, 8, 9, 11, 13, 15, 18–25 |
+| `full` | 19 | Nightly or pre-release; covers core workflows | 4, 5, 6, 7, 8, 9, 11, 13, 15, 18–27 |
| `stress` | 3 | With full suite; edge cases (auth blockers, plan revisions, filename collisions) | 10, 12, 14 |
**Recommended cadence:**
@@ -235,7 +239,7 @@ A fixture is a folder under `fixtures/<eval-id>-<slug>/` containing the artifact
### Synthetic fixtures
-Hand-built artifacts for specific contracts, not captured agent runs. The seven current additions declare `provenance: "synthetic"`, `contractVersion: 2` and the public skill/reference sections they exercise. They serve as deterministic positive/rejection/recovery controls. Historical synthetics retain their compatibility contract rather than being advertised as current compliant output.
+Hand-built artifacts for specific contracts, not captured agent runs. The current additions declare `provenance: "synthetic"`, `contractVersion: 2` and the public skill/reference sections they exercise. They serve as deterministic positive/rejection/recovery controls. Historical synthetics retain their compatibility contract rather than being advertised as current compliant output.
Pros: deterministic, fast to build, no Dataverse dependency, fully under our control.
Cons: can't catch agent drift (the synthetic fixture is what we *want* the agent to produce, not what it *does*).
@@ -278,6 +282,8 @@ The suite ships both kinds:
| 12 | `12-account-plan-revision` (current plan revision) | — |
| 14 | `14-account-list-edit-collision` (current filename collision) | — |
| 16 | `16-account-list` (current minimal existing-table page) | — |
+| 26 | `26-customer-lookup` (current: an answered account-scope question and the lookup metadata read behind the plan's records; its page normalizes a Customer lookup, which is not graded) | — |
+| 27 | `27-page-error-helper` (current: a newly authored plan with its assumptions; its page follows the page error teaching on a cached read, an awaited read and a Custom API Action, which is not graded) | — |
The mix gives:
- A **green baseline** to catch runner regressions (synthetics)
@@ -290,7 +296,7 @@ The mix gives:
`fixtures/contracts.json` explicitly labels the 13 existing directories as historical contract 1, without rewriting captured content. Raw PAC transport, legacy navigation spelling and missing transport/read-back artifacts are **not** certified as current compliant. Contract 2 uses a per-directory `fixture.json` and `tool-results.json`: one ordered record per command with its own result, plus `artifacts` listing the exact files to load. Artifact paths must stay inside the fixture and be plain files.
-The first seven contract-2 fixtures exercise these current contracts:
+These contract-2 fixtures exercise the current contracts below:
| Fixture | Evidence/check | Negative control in scorer tests |
|---------|----------------|----------------------------------|
@@ -299,10 +305,12 @@ The first seven contract-2 fixtures exercise these current contracts:
| `21-discovery-failure` | Unreadable discovery returns `needs_input`, no setup | Failed discovery followed by connection/reference creation or upload |
| `22-navigation-contract` | Actual before/after TSX and deployed ID map | Unknown/optional-call non-GUID target, runtime override, a `PAGEREF_` token anywhere but a navigation `pageId` — a comment included (the build refuses it), a page the checker cannot read for certain (it refuses every token at or after the first guess and every call that reaches it, a resolved id literal there included), collateral edit or extra reupload |
| `23-worker-completeness` | Failed production gate, fresh regeneration, then upload | Valid export plus unfinished statement, stale/missing write or upload before acceptance |
-| `24-custom-api-lifecycle` | Discovery, re-probe, bare actions, runtime and config stages | Disabled/unreadable gate, invented kind/name/parameter, wrong method/bound record, unsafe response or lost bindings |
+| `24-custom-api-lifecycle` | Discovery, bare actions, runtime and config stages | Invented kind/name/parameter, wrong method/bound record, unsafe response or lost bindings |
| `25-solution-package` | Explicit page IDs, dynamic types, app-first writes and read-back | Omitted page/wrong solution/type/order; invalid ID writes; partial failure reported as success |
+| `26-customer-lookup` | An attended run that asks which opportunities "this account" means (no default) and records the answer as a user-confirmed assumption before approval; lookup records built from the saved `get-lookup-metadata.js` read and gated with `--require-observed-lookups`; `lookup-rows.json` holds synthetic customer values with the state the published normalizer gives each (the page's lookup code is not graded) | A pre-settled default, a missing or unrecorded answer, an approval before the answer; a metadata read that is not the saved file or comes after approval, incomplete targets, a lookup left planned, a one-target type, a gate after generation |
+| `27-page-error-helper` | A newly authored plan whose records equal the approved preview's, verified with `--require-assumptions`; its page follows the page error teaching (not graded) | A plan verified without `--require-assumptions` or a preview whose assumption differs |
-Expected refusals are green **only when the recorded refusal contract is satisfied**. The refusal fixtures of evals 10 and 21, and `3-edit-no-pages-stop`, legitimately contain no generated TSX; Layer 2 grades their failed gate and absence of generation/mutations rather than manufacturing a page. A refusal declares its stage in `fixture.json` (`refusal.stage`): `auth` and `discovery` stop at a failed check-auth.js or list-connections.js result, `custom-api` at a disabled or unreadable feature gate, and `edit-pages` at an app whose `genpage.js list` succeeded with no page to offer — the user is told so and nothing is downloaded, planned or uploaded after the first such listing (a later read does not reset it), and the edit phases that would follow the page choice skip for that run. Fixture 23's rejected snapshot is nested evidence; the top-level page is the accepted regeneration. Expected-failure mutations live in unit tests, never unexplained red corpus directories.
+Expected refusals are green **only when the recorded refusal contract is satisfied**. The refusal fixtures of evals 10 and 21, and `3-edit-no-pages-stop`, legitimately contain no generated TSX; Layer 2 grades their failed gate and absence of generation/mutations rather than manufacturing a page. A refusal declares its stage in `fixture.json` (`refusal.stage`): `auth` and `discovery` stop at a failed check-auth.js or list-connections.js result, and `edit-pages` at an app whose `genpage.js list` succeeded with no page to offer — the user is told so and nothing is downloaded, planned or uploaded after the first such listing (a later read does not reset it), and the edit phases that would follow the page choice skip for that run. Fixture 23's rejected snapshot is nested evidence; the top-level page is the accepted regeneration. Expected-failure mutations live in unit tests, never unexplained red corpus directories.
---
@@ -324,7 +332,7 @@ Exit codes:
```bash
node run-layer-1.js --tier smoke # 8 stored fixtures, 5 prompt definitions
-node run-layer-1.js --tier full # 19 stored fixtures, 17 prompt definitions
+node run-layer-1.js --tier full # 21 stored fixtures, 19 prompt definitions
node run-layer-1.js --tier stress # 6 stored fixtures, 3 prompt definitions
```
@@ -439,18 +447,20 @@ Read this output as:
- **Top of each subtest:** `# Subtest: <fixture-folder-name>` — which fixture is being graded.
- **Per-assertion line:** `ok N - <assertion text>` (pass) or `not ok N - <assertion text>` (fail) or `ok N - <text> # SKIP <reason>` (not applicable).
- **YAML block under `not ok`:** the `reason` field names the offending file and what specifically violated the assertion.
-- **Aggregate:** `ok N - <fixture-name>` (all assertions passed) or `not ok N - <fixture-name>` (at least one fail).
-- **Final summary:** `# tests <N>` / `# pass <N>` / `# fail <N>` / `# skip <N>` / `# fixtures <N> (pass X, fail Y)`.
+- **Aggregate:** `ok N - <fixture-name>` (at least one assertion graded, and none failed), `ok N - <fixture-name> # SKIP no expectation graded` (unscored: every assertion skipped, or there was none — nothing was graded, so it is not a pass) or `not ok N - <fixture-name>` (at least one fail).
+- **Final summary:** `# tests <N>` / `# pass <N>` / `# fail <N>` / `# skip <N>` / `# fixtures <N> (pass X, fail Y)`, then `# unscored fixtures <U>` only when U > 0. An unscored fixture is in neither X nor Y, so X + Y + U = N. The app-builder runner shares this reporter and prints the same lines.
**Skipped vs failed:**
-- `# SKIP <reason>` — the assertion doesn't apply (e.g., "no Dataverse files in this fixture" for a mock-data assertion), or a registered check cannot grade the stored evidence yet (e.g., "column-name verification requires RuntimeTypes.ts fixture"). **Does not fail the fixture.**
-- `not ok` — actual failure. Fixture fails. Exit code becomes 1.
+- `# SKIP <reason>` — the assertion doesn't apply (e.g., "no Dataverse files in this fixture" for a mock-data assertion), or a registered check cannot grade the stored evidence yet (e.g., "column-name verification requires RuntimeTypes.ts fixture"). **Does not fail the fixture** — but a fixture whose every assertion skips is unscored, not passed.
+- `not ok` — actual failure. Fixture fails. Exit code becomes 1. An unscored fixture does not change the exit code.
**Three common skip reasons in our suite:**
1. `no Dataverse files / no <feature> detected` — the fixture doesn't exercise this code path
2. `not graded yet` / `requires RuntimeTypes.ts fixture` — a check that cannot grade the stored evidence: a correct check would fail a historical fixture's real drift, or the capture did not keep what the check reads. `evals/model-apps/tests/eval-coverage-baseline.json` records the reason for each
3. `no check registered for this expectation` — the assertion text in `evals.json` doesn't have a corresponding check in the runner library. Either add the check or accept the skip as documentation-only.
+Custom API support has no feature flag, so no rule grades a `custom-api` gate: a probe of that removed flag, recorded by an older run, is neither required nor refused, and a run that never probes it is not failed for it.
+
---
## Manual grep patterns
@@ -636,7 +646,8 @@ When a new rule is added to `rules.md` or a new phase requirement lands in `SKIL
Currently red: **none**. Every fixture — synthetic and real capture alike — is green under both
runners, and CI runs both runners on every PR that touches `evals/model-apps/**`
-(`.github/workflows/model-apps-script-tests.yml`, job `test-model-apps-evals`).
+(`.github/workflows/model-apps-script-tests.yml`, job `test-model-apps-evals`, on ubuntu, windows and
+macos with Node 20 and 22).
**Aggregate state for CI gating:** every stored fixture must pass. Expected rejection is an explicit
outcome with associated failed-gate/no-mutation evidence, not an excuse for a red fixture. Put bad
diff --git a/evals/model-apps/genpage/evals.json b/evals/model-apps/genpage/evals.json
index c89ca58d3..3c0c52601 100644
--- a/evals/model-apps/genpage/evals.json
+++ b/evals/model-apps/genpage/evals.json
@@ -19,7 +19,6 @@
"Prefix discipline — solution alignment: If the env has a dominant non-system custom prefix (>=50% of custom tables AND >=3 such tables), the planner surfaces this in the solution question and ordered the option whose publisher prefix matches the dominant prefix FIRST as the recommended choice. If the user picks a different-prefix solution, the planner logged a one-line warning before proceeding.",
"Phase 2a: Every applicable auth result is associated with its command; only the latest successful gate authorizes mutations, and final failures halt with bounded retry and advice",
"Phase 1: Failed connector discovery returns needs_input and never creates a connection or reference",
- "Phase 4.6: A populated Custom API plan never discovers, generates or uploads after a disabled or unreadable feature gate",
"Phase 6.7: Packaging uses every deployed page id, the approved solution and discovered component types; invalid identities refuse before writes and results agree with read-back"
],
"common_code_assertions": [
@@ -412,7 +411,7 @@
"Phase 1 (Planner): Plan includes a datetime column for due date",
"Phase 1 (Planner): Solution selection question is asked (because new entity will be created) and recorded in ## Environment",
"Phase 2a: scripts/check-auth.js returns ok:true before entity-builder is invoked",
- "Phase 2b (Entity Builder): cr_ticket is provisioned with choice columns via provision-entities.js input JSON; picklist options include {value,label} pairs",
+ "Phase 2b (Entity Builder): cr_ticket is provisioned with choice columns via provision-entities.js input JSON; each picklist option is written as its label, in the plan's order (numbered 100000000 + index)",
"Phase 2b (Entity Builder): Priority picklist has 4 options starting at 100000000 (Low=100000000, Medium=100000001, High=100000002, Critical=100000003)",
"Phase 2b (Entity Builder): Status picklist has 4 options starting at 100000000",
"Phase 2b (Entity Builder): Solution is specified via provision-entities.js input JSON; verified through ## Environment → Solution: declaration",
@@ -552,8 +551,8 @@
{
"id": 24,
"tier": "full",
- "prompt": "Discover the bound Approve Order Action and global Summary Function, gate generation on Custom API support, use the exact binding names and parameter kinds, then preserve and explicitly clear bindings on separate updates.",
- "data": { "fixture_kind": "synthetic", "custom_api_feature": "enabled", "declared_outputs": { "cnt_ApproveOrder": ["NewStatus"], "cnt_GetOrderSummary": ["Total"] } },
+ "prompt": "Discover the bound Approve Order Action and global Summary Function, use the exact binding names and parameter kinds, then preserve and explicitly clear bindings on separate updates.",
+ "data": { "fixture_kind": "synthetic", "declared_outputs": { "cnt_ApproveOrder": ["NewStatus"], "cnt_GetOrderSummary": ["Total"] } },
"expectations": [
"Phase 5: Custom API discovery, gate, bare bindings, runtime calls and update preservation or explicit clear agree"
]
@@ -566,6 +565,47 @@
"expectations": [
"Phase 6.7: Packaging uses every deployed page id, the approved solution and discovered component types; invalid identities refuse before writes and results agree with read-back"
]
+ },
+ {
+ "id": 26,
+ "tier": "full",
+ "prompt": "Build a Customer Opportunities page for our existing opportunities. Show every opportunity that has a customer, whether an account or a contact, and let me search customer names by substring. From each opportunity I want to open the customer's record, change the opportunity's customer, and see the opportunities for this account.",
+ "data": {
+ "fixture_kind": "synthetic",
+ "question_answers": {
+ "new_or_edit": "Create new page(s)",
+ "data_source": "Dataverse entity: opportunity",
+ "specific_requirements": "Open the customer's record, change the customer, and show the opportunities for this account",
+ "account_scope": "Direct customer"
+ },
+ "app_selection": "user selects an existing app"
+ },
+ "expectations": [
+ "Phase 1 (Planner): The open account-scope question reaches the maker as needs_input with no default, the answer returns to the planner by its question id, and the written plan and the approved preview record it as a user-confirmed assumption before approval",
+ "Phase 1 (Planner): get-lookup-metadata.js reads opportunity's lookups before approval, its successful answer is the saved lookup-metadata.json, and every recorded lookup is observed with the complete targets and concrete paths it read",
+ "Phase 1 (Planner): The newly authored plan records its assumptions and every page's data semantics and lookup metadata, the approved preview carries the same records, and provenance is verified with --require-assumptions",
+ "Phase 4: RuntimeTypes.ts is generated for opportunity and types each recorded lookup's read property with exactly its recorded targets",
+ "Phase 5a: The page is generated only after provenance is verified with --require-assumptions --require-observed-lookups --lookup-metadata on this plan's records",
+ "Phase 5b: Generated .tsx uses only column names verified from RuntimeTypes.ts — no guessed names"
+ ]
+ },
+ {
+ "id": 27,
+ "tier": "full",
+ "prompt": "Build an Order Approvals page for our existing sales orders: list the sales orders, show the one I select, and let me approve it with the existing Approve Order action.",
+ "data": {
+ "fixture_kind": "synthetic",
+ "question_answers": {
+ "new_or_edit": "Create new page(s)",
+ "data_source": "Dataverse entity: salesorder",
+ "specific_requirements": "Approve the selected order with the Approve Order action"
+ },
+ "app_selection": "user selects an existing app",
+ "declared_outputs": { "cnt_ApproveOrder": ["NewStatus"] }
+ },
+ "expectations": [
+ "Phase 1 (Planner): The newly authored plan records its assumptions and every page's data semantics and lookup metadata, the approved preview carries the same records, and provenance is verified with --require-assumptions"
+ ]
}
]
}
diff --git a/evals/model-apps/genpage/fixtures/26-customer-lookup/RuntimeTypes.ts b/evals/model-apps/genpage/fixtures/26-customer-lookup/RuntimeTypes.ts
new file mode 100644
index 000000000..b1fda82d4
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/26-customer-lookup/RuntimeTypes.ts
@@ -0,0 +1,51 @@
+// ---------------- Type Definitions which can be imported from ./RuntimeTypes -------------------------
+export interface TableRegistrations extends BaseTableRegistrations {
+ "opportunity": opportunity,
+}
+export interface EnumRegistrations extends BaseEnumRegistrations {
+ "opportunity-statecode": opportunity_statecode,
+ "opportunity-statuscode": opportunity_statuscode,
+}
+export type opportunity = TableRow<{
+ // Primary Key Column
+ readonly opportunityid: string,
+ readonly createdbyname: string,
+ readonly createdbyyominame: string,
+ _customerid_value: `/account(${string})` | `/contact(${string})`,
+ readonly customeridname: string,
+ readonly customeridyominame: string,
+ description: string,
+ estimatedclosedate: Date,
+ estimatedvalue: number,
+ readonly modifiedbyname: string,
+ readonly modifiedbyyominame: string,
+ name: string,
+ _parentaccountid_value: `/account(${string})`,
+ readonly parentaccountidname: string,
+ readonly parentaccountidyominame: string,
+ _parentcontactid_value: `/contact(${string})`,
+ readonly parentcontactidname: string,
+ readonly parentcontactidyominame: string,
+ statecode: opportunity_statecode,
+ statuscode: opportunity_statuscode,
+}>
+
+const enum opportunity_statecode {
+"Open" = 0,
+"Won" = 1,
+"Lost" = 2,
+}
+const enum opportunity_statuscode {
+"In Progress" = 1,
+"On Hold" = 2,
+"Won" = 3,
+"Canceled" = 4,
+"Out-Sold" = 5,
+}
+
+export interface UxAgentDataApi extends BaseUxAgentDataApi<TableRegistrations, EnumRegistrations> {}
+
+export interface GeneratedComponentProps {
+ dataApi: UxAgentDataApi;
+ pageInput?: PageInput;
+}
diff --git a/evals/model-apps/genpage/fixtures/26-customer-lookup/agent-message.txt b/evals/model-apps/genpage/fixtures/26-customer-lookup/agent-message.txt
new file mode 100644
index 000000000..b6425f2c5
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/26-customer-lookup/agent-message.txt
@@ -0,0 +1 @@
+Created the Customer Opportunities page: every opportunity with an account or contact customer, a search of the loaded rows by customer name, Open customer, Change customer, and one account's own opportunities (its direct customer opportunities, as you chose). Each failure is reported once and shown where it happened.
diff --git a/evals/model-apps/genpage/fixtures/26-customer-lookup/approved-plan.md b/evals/model-apps/genpage/fixtures/26-customer-lookup/approved-plan.md
new file mode 100644
index 000000000..74829e8f5
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/26-customer-lookup/approved-plan.md
@@ -0,0 +1,98 @@
+## Genpage Plan
+
+### Assumptions
+#### A1 — Account opportunities
+- Decision: An account's opportunities are those whose Customer (customerid) is that account — the direct customer relationship. Opportunities whose parent account is the account, and opportunities of the account's contacts, are not included.
+- Alternatives considered: Parent account (parentaccountid); Customer plus contacts (direct account customers and the contact customers linked to the account).
+- Evidence: metadata: opportunity.customerid targets account and contact, and opportunity.parentaccountid targets account (lookup-metadata.json).
+- Resolution: user-confirmed
+- Question: opportunities-account-scope
+- Answer: Direct customer
+
+#### A2 — List order, size and caching
+- Decision: Read the opportunities sorted by name ascending, 50 rows, and de-duplicate and cache that initial read; a failed read is not cached.
+- Alternatives considered: Newest first; more rows; uncached loading.
+- Evidence: default: the request states no order or size, and the page loads on mount, so Critical Rule 15 applies.
+- Resolution: planner-default
+
+#### A3 — Customer search scope
+- Decision: The customer search keeps the loaded opportunities whose customer name contains the search text, ignoring case. It searches the rows on the page, not the server, and its label says so.
+- Alternatives considered: A server search of account names and contact full names through the customerid_account and customerid_contact paths.
+- Evidence: default: the request asks for a substring search of customer names without naming its scope.
+- Resolution: planner-default
+
+#### A4 — Customer choices
+- Decision: Change customer offers the distinct resolved customers of the loaded opportunities, accounts and contacts, each shown with its table so that equal names stay apart. An unresolved customer is not offered.
+- Alternatives considered: A search of every account and contact.
+- Evidence: default: the request asks to change the customer without naming where the choices come from.
+- Resolution: planner-default
+
+### Pages (1 total)
+| Page | File | Purpose | Entities |
+|------|------|---------|----------|
+| Customer Opportunities | customer-lookup.tsx | Browse opportunities with their account or contact customer; open, filter by and change the customer | opportunity |
+
+### Data Semantics
+#### customer-lookup.tsx
+##### R1
+- Kind: relationship
+- Definition: Account opportunities: opportunity.customerid → account, the direct customer. Offered only for an opportunity whose customer normalizes to an account; parentaccountid is not used and contact customers do not roll up. A contact, unset or unresolved customer offers no account view.
+- Source: A1
+
+##### R2
+- Kind: relationship
+- Definition: Customer reference: opportunity.customerid with its complete targets account and contact. Each row's customer is normalized to its actual table and bare id before it is opened or offered as a choice; a change writes the chosen table's qualified reference; an unresolved customer is shown by its label only.
+- Source: User Requirements
+- Requirement quote: open the customer's record, change the opportunity's customer
+
+##### F1
+- Kind: filter
+- Definition: Account opportunities query: opportunity rows with customerid_account/accountid eq the account's bare id, read when the maker asks for one account's opportunities. A refused or failed read is shown as a read error; the predicate is never weakened and nothing is post-filtered.
+- Source: A1
+
+##### F2
+- Kind: filter
+- Definition: Customer search: keep the loaded opportunities whose customer label (the formatted value of _customerid_value) contains the search text, ignoring case; client-side, over the loaded rows only.
+- Source: A3
+- Requirement quote: search customer names by substring
+
+##### F3
+- Kind: filter
+- Definition: All customers: opportunity rows with _customerid_value ne null — a customer of either target, account or contact; no target, owner, state or date restriction.
+- Source: User Requirements
+- Requirement quote: Show every opportunity that has a customer, whether an account or a contact
+
+### Lookup Metadata
+#### customer-lookup.tsx
+| Table | Column | Read property | Targets | Used by | Metadata state |
+|-------|--------|---------------|---------|---------|----------------|
+| opportunity | customerid | _customerid_value | account, contact | R1, R2, F1, F2, F3; customer navigation; customer picker | observed |
+
+| Table | Column | Target | Navigation property | Referenced key |
+|-------|--------|--------|---------------------|----------------|
+| opportunity | customerid | account | customerid_account | accountid |
+| opportunity | customerid | contact | customerid_contact | contactid |
+
+- Evidence: lookup-metadata.json; successful source/target metadata discovery.
+- Read target strategy: normalize the logical-name annotation and qualified prefix; a bare id without target evidence stays unresolved and is shown by its label only — no fallback read.
+
+### Data Strategy
+- Entities needed: opportunity
+- Entities that exist: opportunity
+- Entities to create: none
+- Connector bindings: none
+- Custom API bindings: none
+- Built-in Dataverse operations: none
+- Sample data: not needed (existing table)
+
+### App
+- Using: Sales Hub (11111111-2222-3333-4444-555555555555)
+
+### Solution
+- Default / new
+
+### Localization
+- English only — no localization needed
+
+### Design
+- Default Fluent UI V9 look; the opportunity list with each customer, a search of the loaded rows, open and change the customer, and one account's opportunities; each failure shown in its own error bar
diff --git a/evals/model-apps/genpage/fixtures/26-customer-lookup/customer-lookup.tsx b/evals/model-apps/genpage/fixtures/26-customer-lookup/customer-lookup.tsx
new file mode 100644
index 000000000..027bc0b86
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/26-customer-lookup/customer-lookup.tsx
@@ -0,0 +1,431 @@
+import * as React from 'react';
+import {
+ Button,
+ Dropdown,
+ Field,
+ MessageBar,
+ MessageBarActions,
+ MessageBarBody,
+ Option,
+ SearchBox,
+ Spinner,
+ Text,
+ makeStyles,
+ tokens,
+} from '@fluentui/react-components';
+import { OpenRegular } from '@fluentui/react-icons';
+import type { GeneratedComponentProps, ReadableTableRow, opportunity } from './RuntimeTypes';
+
+type PageErrorKind = 'read' | 'write' | 'indeterminate' | 'network' | 'render';
+type PageErrorView = {
+ operation: string;
+ message: string;
+ fallbackKey: string;
+ code?: string;
+ kind: PageErrorKind;
+ retry?: () => void;
+};
+type PageErrorTelemetry = {
+ trackException?: (error: unknown, properties?: Record<string, unknown>) => void;
+};
+
+// The plan's display name for this page: a fixed literal, not the file name.
+const PAGE_NAME = 'Customer Opportunities';
+
+// The error copy of an English-only page (references/rules.md, "Missing Error Handling").
+const ERROR_COPY: Record<string, string> = {
+ 'error.read': 'Unable to load data. Please try again.',
+ 'error.write': 'The change could not be saved. Refresh before trying again.',
+ 'error.network': 'The request did not go through. You can try again.',
+ 'error.indeterminate': "We couldn't confirm this completed — refresh before retrying.",
+ 'error.render': 'This page hit a problem and could not render. Refresh the page.',
+ 'error.tryAgain': 'Try again',
+};
+
+function translate(key: string): string {
+ return ERROR_COPY[key] || key;
+}
+
+// The page's one error reporter. It logs bounded diagnostics once and returns the view the failed
+// operation stores; it never sets state, never calls retry, and reads only the named fields of a
+// thrown value, each on its own, so a throwing getter leaves that one field empty.
+function reportPageError(
+ pageName: string,
+ operation: string,
+ code: unknown,
+ message: unknown,
+ kind: PageErrorKind,
+ retry?: () => void,
+ appInsights?: PageErrorTelemetry,
+): PageErrorView {
+ const fields: Record<string, unknown> = {};
+ for (const path of ['code', 'errorCode', 'message', 'error.code', 'error.message']) {
+ try {
+ let value: unknown = message;
+ for (const part of path.split('.')) {
+ value = value !== null && typeof value === 'object' ? (value as Record<string, unknown>)[part] : undefined;
+ }
+ fields[path] = value;
+ } catch {
+ fields[path] = undefined;
+ }
+ }
+ let normalizedCode = '';
+ for (const candidate of [code, fields['code'], fields['errorCode'], fields['error.code']]) {
+ const text = typeof candidate === 'string' ? candidate : typeof candidate === 'number' && Number.isFinite(candidate) ? String(candidate) : '';
+ normalizedCode = text.replace(/[\s\u0000-\u001f\u007f-\u009f]+/g, ' ').trim().slice(0, 80);
+ if (normalizedCode) break;
+ }
+ let normalizedMessage = '';
+ for (const candidate of [message, fields['message'], fields['error.message']]) {
+ const line = typeof candidate === 'string' ? candidate.trim().split(/[\r\n\u2028\u2029]/)[0].replace(/[\s\u0000-\u001f\u007f-\u009f]+/g, ' ').trim() : '';
+ if (!line || /^\[object [^\]]*\]$/.test(line) || /^at\s.*(?::\d+:\d+\)?|\((?:native|<anonymous>)\))$/.test(line)) continue;
+ normalizedMessage = line.length > 300 ? line.slice(0, 299) + '\u2026' : line;
+ break;
+ }
+ console.error('[' + String(pageName).replace(/[\r\n\]]/g, '') + '] ' + operation + ' failed', { code: normalizedCode, message: normalizedMessage });
+ const quiet = kind === 'indeterminate' || kind === 'render';
+ const view: PageErrorView = { operation, message: quiet ? '' : normalizedMessage, fallbackKey: 'error.' + kind, kind };
+ if (normalizedCode) view.code = normalizedCode;
+ if (typeof retry === 'function' && (kind === 'read' || kind === 'network')) view.retry = retry;
+ return view;
+}
+
+function PageErrorBar(props: { error: PageErrorView | null }) {
+ const { error } = props;
+ if (!error) return null;
+ return (
+ <MessageBar intent="error">
+ <MessageBarBody>{error.message || translate(error.fallbackKey)}</MessageBarBody>
+ {error.retry && (
+ <MessageBarActions>
+ <Button onClick={error.retry}>{translate('error.tryAgain')}</Button>
+ </MessageBarActions>
+ )}
+ </MessageBar>
+ );
+}
+
+// The page's one class component: it catches a render crash below it and shows a fixed message.
+class PageErrorBoundary extends React.Component<
+ { children: React.ReactNode; appInsights?: PageErrorTelemetry },
+ { failed: boolean }
+> {
+ public state = { failed: false };
+
+ public static getDerivedStateFromError(): { failed: boolean } {
+ return { failed: true };
+ }
+
+ public componentDidCatch(error: Error): void {
+ reportPageError(PAGE_NAME, 'render', undefined, error, 'render');
+ }
+
+ public render(): React.ReactNode {
+ if (this.state.failed) {
+ return (
+ <MessageBar intent="error">
+ <MessageBarBody>{translate('error.render')}</MessageBarBody>
+ </MessageBar>
+ );
+ }
+ return this.props.children;
+ }
+}
+
+// The lookup normalizer of references/rules.md ("Lookup references"), copied unchanged.
+type LookupReference = { table: string; id: string };
+type LookupNormalization =
+ | { state: 'unset' }
+ | { state: 'resolved'; reference: LookupReference }
+ | { state: 'needs-target'; id: string }
+ | { state: 'invalid' };
+
+const LOOKUP_GUID = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
+const LOOKUP_QUALIFIED = /^\/([a-z_][a-z0-9_]*)\(([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})\)$/;
+
+function normalizeLookupReference(
+ row: unknown,
+ property: string,
+ allowedTargets: readonly string[],
+): LookupNormalization {
+ if (typeof row !== 'object' || row === null || Array.isArray(row) || allowedTargets.length === 0) return { state: 'invalid' };
+ const record = row as Record<string, unknown>;
+ if (!Object.prototype.hasOwnProperty.call(record, property)) return { state: 'invalid' };
+ const raw = record[property];
+ if (raw === null) return { state: 'unset' };
+ if (typeof raw !== 'string') return { state: 'invalid' };
+ const value = raw.trim();
+ const qualified = LOOKUP_QUALIFIED.exec(value);
+ if (!qualified && !LOOKUP_GUID.test(value)) return { state: 'invalid' };
+ const prefix = qualified ? qualified[1] : undefined;
+ const id = (qualified ? qualified[2] : value).toLowerCase();
+ if (prefix !== undefined && !allowedTargets.includes(prefix)) return { state: 'invalid' };
+ const annotationKey = `${property}@Microsoft.Dynamics.CRM.lookuplogicalname`;
+ let annotation: string | undefined;
+ if (Object.prototype.hasOwnProperty.call(record, annotationKey)) {
+ const named = record[annotationKey];
+ if (typeof named !== 'string' || !allowedTargets.includes(named)) return { state: 'invalid' };
+ annotation = named;
+ }
+ if (annotation !== undefined && prefix !== undefined && annotation !== prefix) return { state: 'invalid' };
+ const table = annotation ?? prefix ?? (allowedTargets.length === 1 ? allowedTargets[0] : undefined);
+ return table === undefined ? { state: 'needs-target', id } : { state: 'resolved', reference: { table, id } };
+}
+
+type OpportunityRow = ReadableTableRow<opportunity>;
+// A customer the maker can pick: the table is kept with the id, so equal labels — or one GUID — in two tables stay two choices.
+type Picked = { table: 'account' | 'contact'; id: string; label: string };
+
+// Page-scoped window keys (unique per page + query), so the host's double mount shares one read (references/data-caching.md).
+const winAny = window as any;
+const CACHE_KEY = '__ppCustomerOpportunities_opportunityCache';
+const INFLIGHT_KEY = '__ppCustomerOpportunities_opportunityInflight';
+
+const useStyles = makeStyles({
+ root: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: tokens.spacingVerticalM,
+ padding: tokens.spacingHorizontalXL,
+ boxSizing: 'border-box',
+ },
+ item: {
+ display: 'flex',
+ flexWrap: 'wrap',
+ alignItems: 'center',
+ gap: tokens.spacingHorizontalS,
+ },
+ panel: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: tokens.spacingVerticalS,
+ paddingTop: tokens.spacingVerticalM,
+ },
+});
+
+// The customer's label: display text only, never an identity (rules.md DataAPI Rule 12).
+function customerLabel(row: OpportunityRow): string {
+ return String(row['[email protected]'] ?? '');
+}
+
+// One choice per resolved table-and-id pair; an unresolved customer offers none.
+function customerChoice(row: OpportunityRow): Picked | null {
+ const normalized = normalizeLookupReference(row, '_customerid_value', ['account', 'contact']);
+ if (normalized.state !== 'resolved') return null;
+ const reference = normalized.reference;
+ return { table: reference.table === 'account' ? 'account' : 'contact', id: reference.id, label: customerLabel(row) };
+}
+
+function OpportunityItem(props: {
+ row: OpportunityRow;
+ onOpen: (row: OpportunityRow) => void;
+ onAccountView: (row: OpportunityRow) => void;
+ onChangeCustomer: (opportunityId: string) => void;
+}) {
+ const { row } = props;
+ const styles = useStyles();
+ const customer = normalizeLookupReference(row, '_customerid_value', ['account', 'contact']);
+ // An unset, invalid or untargeted customer shows its label and offers nothing that needs its table.
+ if (customer.state !== 'resolved') {
+ return (
+ <div className={styles.item}>
+ <Text weight="semibold">{row.name}</Text>
+ <Text>{customerLabel(row) || 'No customer'}</Text>
+ <Text size={200}>This customer cannot be opened or filtered from this page.</Text>
+ <Button onClick={() => props.onChangeCustomer(row.opportunityid)}>Change customer</Button>
+ </div>
+ );
+ }
+ const reference = customer.reference;
+ return (
+ <div className={styles.item}>
+ <Text weight="semibold">{row.name}</Text>
+ <Text>{customerLabel(row)}</Text>
+ <Button icon={<OpenRegular />} onClick={() => props.onOpen(row)}>Open customer</Button>
+ {reference.table === 'account' && <Button onClick={() => props.onAccountView(row)}>Show this account's opportunities</Button>}
+ <Button onClick={() => props.onChangeCustomer(row.opportunityid)}>Change customer</Button>
+ </div>
+ );
+}
+
+function PageBody(props: GeneratedComponentProps) {
+ const { dataApi, pageInput } = props;
+ void pageInput;
+ const styles = useStyles();
+ const dataReady = !!dataApi;
+ const [reloadKey, setReloadKey] = React.useState(0);
+ // F3: every opportunity that has a customer, of either table, read once and cached (A2).
+ const [{ opportunities, loading, error }, setData] = React.useState<{ opportunities: OpportunityRow[]; loading: boolean; error: PageErrorView | null }>(() => {
+ const cached = winAny[CACHE_KEY] as OpportunityRow[] | undefined;
+ return { opportunities: cached ?? [], loading: cached === undefined, error: null };
+ });
+ // F2: a search of the loaded rows by customer name.
+ const [searchText, setSearchText] = React.useState('');
+ // R1 and F1: the account view (A1 — the direct customer account, no contact roll-up).
+ const [accountView, setAccountView] = React.useState<{ label: string; rows: OpportunityRow[]; loading: boolean; error: PageErrorView | null }>({ label: '', rows: [], loading: false, error: null });
+ const accountRequest = React.useRef(0);
+ const [navigation, setNavigation] = React.useState<{ error: PageErrorView | null }>({ error: null });
+ const [change, setChange] = React.useState<{ opportunityId: string; picked: Picked | null; saving: boolean; error: PageErrorView | null }>({ opportunityId: '', picked: null, saving: false, error: null });
+ const saving = React.useRef(false);
+
+ // "Try again" after a failed load, and the refresh after a customer change: drop the cached rows and read again.
+ function reloadOpportunities() {
+ delete winAny[CACHE_KEY];
+ delete winAny[INFLIGHT_KEY];
+ setData({ opportunities: [], loading: true, error: null });
+ setReloadKey((key) => key + 1);
+ }
+
+ React.useEffect(() => {
+ if (!dataReady) return;
+ const cached = winAny[CACHE_KEY] as OpportunityRow[] | undefined;
+ if (cached !== undefined) {
+ if (opportunities !== cached) setData({ opportunities: cached, loading: false, error: null });
+ return;
+ }
+ let cancelled = false;
+ let inflight = winAny[INFLIGHT_KEY] as Promise<OpportunityRow[]> | undefined;
+ if (!inflight) {
+ inflight = dataApi
+ .queryTable('opportunity', { select: ['opportunityid', 'name', '_customerid_value'], filter: '_customerid_value ne null', orderBy: 'name asc', pageSize: 50 })
+ .then((result: { rows: OpportunityRow[] }) => {
+ winAny[CACHE_KEY] = result.rows;
+ return result.rows;
+ })
+ .finally(() => { if (winAny[INFLIGHT_KEY] === inflight) delete winAny[INFLIGHT_KEY]; });
+ winAny[INFLIGHT_KEY] = inflight;
+ }
+ inflight
+ .then((rows) => { if (!cancelled) setData({ opportunities: rows, loading: false, error: null }); })
+ .catch((failure) => { if (!cancelled) setData({ opportunities: [], loading: false, error: reportPageError(PAGE_NAME, 'loadOpportunities', undefined, failure, 'read', reloadOpportunities) }); });
+ return () => { cancelled = true; };
+ // Readiness and the reload key only — never dataApi (a new reference on every render).
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [dataReady, reloadKey]);
+
+ async function showAccountOpportunities(row: OpportunityRow) {
+ const normalized = normalizeLookupReference(row, '_customerid_value', ['account', 'contact']);
+ if (normalized.state !== 'resolved') return;
+ const reference = normalized.reference;
+ if (reference.table !== 'account') return;
+ const filter = `customerid_account/accountid eq ${reference.id}`;
+ const requestId = ++accountRequest.current;
+ setAccountView({ label: customerLabel(row), rows: [], loading: true, error: null });
+ try {
+ const result = await dataApi.queryTable('opportunity', { select: ['opportunityid', 'name', '_customerid_value'], filter, orderBy: 'name asc', pageSize: 50 });
+ if (requestId !== accountRequest.current) return;
+ setAccountView({ label: customerLabel(row), rows: result.rows, loading: false, error: null });
+ } catch (failure) {
+ if (requestId !== accountRequest.current) return;
+ // A refused typed path stops here as a read failure: the filter is never weakened and nothing is post-filtered.
+ setAccountView({ label: customerLabel(row), rows: [], loading: false, error: reportPageError(PAGE_NAME, 'loadAccountOpportunities', undefined, failure, 'read') });
+ }
+ }
+
+ async function openCustomer(row: OpportunityRow) {
+ const normalized = normalizeLookupReference(row, '_customerid_value', ['account', 'contact']);
+ if (normalized.state !== 'resolved') return;
+ const reference = normalized.reference;
+ setNavigation({ error: null });
+ try {
+ await Xrm.Navigation.navigateTo({ pageType: 'entityrecord', entityName: reference.table, entityId: reference.id });
+ } catch (failure) {
+ setNavigation({ error: reportPageError(PAGE_NAME, 'openCustomerRecord', undefined, failure, 'read') });
+ }
+ }
+
+ async function changeCustomer(opportunityId: string, selected: Picked) {
+ if (saving.current) return;
+ saving.current = true;
+ setChange({ opportunityId, picked: selected, saving: true, error: null });
+ // Pitfall E: the qualified value is built only here, for the table the maker picked.
+ const link: `/account(${string})` | `/contact(${string})` = selected.table === 'account'
+ ? `/account(${selected.id})`
+ : `/contact(${selected.id})`;
+ try {
+ await dataApi.updateRow('opportunity', opportunityId, { _customerid_value: link });
+ setChange({ opportunityId: '', picked: null, saving: false, error: null });
+ reloadOpportunities();
+ } catch (failure) {
+ // A failed write is reported once and never retried: it may have reached the server.
+ setChange({ opportunityId, picked: selected, saving: false, error: reportPageError(PAGE_NAME, 'changeCustomer', undefined, failure, 'write') });
+ } finally {
+ saving.current = false;
+ }
+ }
+
+ const choices = React.useMemo(() => {
+ const seen = new Map<string, Picked>();
+ for (const row of opportunities) {
+ const choice = customerChoice(row);
+ if (choice && !seen.has(`${choice.table}:${choice.id}`)) seen.set(`${choice.table}:${choice.id}`, choice);
+ }
+ return [...seen.values()];
+ }, [opportunities]);
+ const term = searchText.trim().toLowerCase();
+ // F2 searches the loaded rows only — it is not a search of every opportunity on the server.
+ const shown = term ? opportunities.filter((row) => customerLabel(row).toLowerCase().includes(term)) : opportunities;
+
+ return (
+ <div className={styles.root}>
+ <Text as="h1" size={700} weight="semibold">Customer Opportunities</Text>
+ <PageErrorBar error={error} />
+ <PageErrorBar error={navigation.error} />
+ <SearchBox
+ aria-label="Search the loaded opportunities by customer name"
+ placeholder="Search the loaded opportunities by customer name"
+ value={searchText}
+ onChange={(_, data) => setSearchText(data.value ?? '')}
+ />
+ {loading ? <Spinner label="Loading opportunities" /> : shown.map((row) => (
+ <OpportunityItem
+ key={row.opportunityid}
+ row={row}
+ onOpen={(item) => void openCustomer(item)}
+ onAccountView={(item) => void showAccountOpportunities(item)}
+ onChangeCustomer={(opportunityId) => setChange({ opportunityId, picked: null, saving: false, error: null })}
+ />
+ ))}
+ <section className={styles.panel} aria-label="Account opportunities">
+ <PageErrorBar error={accountView.error} />
+ {accountView.loading && <Spinner label="Loading the account's opportunities" />}
+ {accountView.label && !accountView.loading && <Text weight="semibold">{accountView.label}</Text>}
+ {accountView.rows.map((row) => <Text key={row.opportunityid}>{row.name}</Text>)}
+ </section>
+ <PageErrorBar error={change.error} />
+ {change.opportunityId && (
+ <section className={styles.panel} aria-label="Change customer">
+ <Field label="New customer">
+ <Dropdown
+ placeholder="Pick a customer"
+ selectedOptions={change.picked ? [`${change.picked.table}:${change.picked.id}`] : []}
+ onOptionSelect={(_, data) => setChange({ opportunityId: change.opportunityId, picked: choices.find((choice) => `${choice.table}:${choice.id}` === data.optionValue) ?? null, saving: false, error: null })}
+ >
+ {choices.map((choice) => (
+ <Option key={`${choice.table}:${choice.id}`} value={`${choice.table}:${choice.id}`} text={`${choice.label} (${choice.table})`}>
+ {`${choice.label} (${choice.table})`}
+ </Option>
+ ))}
+ </Dropdown>
+ </Field>
+ <Button
+ appearance="primary"
+ disabled={!change.picked || change.saving}
+ onClick={() => { if (change.picked) void changeCustomer(change.opportunityId, change.picked); }}
+ >
+ Save customer
+ </Button>
+ </section>
+ )}
+ </div>
+ );
+}
+
+const GeneratedComponent = (props: GeneratedComponentProps) => (
+ <PageErrorBoundary>
+ <PageBody {...props} />
+ </PageErrorBoundary>
+);
+
+export default GeneratedComponent;
diff --git a/evals/model-apps/genpage/fixtures/26-customer-lookup/fixture.json b/evals/model-apps/genpage/fixtures/26-customer-lookup/fixture.json
new file mode 100644
index 000000000..7db0d4f8e
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/26-customer-lookup/fixture.json
@@ -0,0 +1,31 @@
+{
+ "contractVersion": 2,
+ "provenance": "synthetic",
+ "description": "Constructed trace of a compliant attended create run for eval 26, not an agent capture. An existing table (opportunity) is shown with each opportunity's Customer, a polymorphic lookup to account or contact. \"The opportunities for this account\" has three metadata-backed meanings, so the planner returns needs_input with no default; the maker answers Direct customer, the plan records that answer as a user-confirmed assumption beside three planner defaults, and the approved preview carries the same records. The lookup records come from the saved get-lookup-metadata.js answer and generation is gated by --require-observed-lookups. The page copies the lookup normalizer and the page error block of references/rules.md: it normalizes every customer with its complete targets, filters an account's opportunities through the verified customerid_account path only for an account customer, lists every customer of either table, searches only the loaded rows (and says so), opens and writes the actual table, and reports reads and the write through reportPageError. lookup-rows.json holds synthetic customer values with the state the normalizer gives each.",
+ "contracts": [
+ "plugins/model-apps/skills/genpage/SKILL.md Phase 1: Plan (Steps 1-7) and the needs_input loop",
+ "plugins/model-apps/agents/genpage-planner.md Resolve Data Semantics",
+ "plugins/model-apps/skills/genpage/SKILL.md Phase 5a and 5b: Single-page fast path",
+ "plugins/model-apps/skills/genpage/SKILL.md Phase 6: Deploy and Prompt semantics",
+ "plugins/model-apps/references/plan-schema.md Assumptions, data semantics and lookup metadata",
+ "plugins/model-apps/references/rules.md Critical Rules 22 and 23, Lookup references and Missing Error Handling",
+ "plugins/model-apps/references/data-caching.md Pattern 1"
+ ],
+ "expectedOutcome": "deployed",
+ "toolResults": "tool-results.json",
+ "artifacts": [
+ "prompt.txt",
+ "agent-message.txt",
+ "page-name.txt",
+ "approved-plan.md",
+ "lookup-metadata.json",
+ "semantic-interactions.json",
+ "lookup-rows.json"
+ ],
+ "semantics": {
+ "approvedPlan": "approved-plan.md",
+ "lookupMetadata": "lookup-metadata.json",
+ "interactions": "semantic-interactions.json",
+ "lookupRows": "lookup-rows.json"
+ }
+}
diff --git a/evals/model-apps/genpage/fixtures/26-customer-lookup/genpage-plan.md b/evals/model-apps/genpage/fixtures/26-customer-lookup/genpage-plan.md
new file mode 100644
index 000000000..887dae136
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/26-customer-lookup/genpage-plan.md
@@ -0,0 +1,133 @@
+# Genpage Plan
+
+## User Requirements
+Build a Customer Opportunities page for our existing opportunities. Show every opportunity that has a customer, whether an account or a contact, and let me search customer names by substring. From each opportunity I want to open the customer's record, change the opportunity's customer, and see the opportunities for this account.
+
+- Data source: Dataverse entity opportunity (already exists)
+- Specific requirements: open the customer's record, change the customer, and show the opportunities for this account
+
+## Assumptions
+
+### A1 — Account opportunities
+- Decision: An account's opportunities are those whose Customer (customerid) is that account — the direct customer relationship. Opportunities whose parent account is the account, and opportunities of the account's contacts, are not included.
+- Alternatives considered: Parent account (parentaccountid); Customer plus contacts (direct account customers and the contact customers linked to the account).
+- Evidence: metadata: opportunity.customerid targets account and contact, and opportunity.parentaccountid targets account (lookup-metadata.json).
+- Resolution: user-confirmed
+- Question: opportunities-account-scope
+- Answer: Direct customer
+
+### A2 — List order, size and caching
+- Decision: Read the opportunities sorted by name ascending, 50 rows, and de-duplicate and cache that initial read; a failed read is not cached.
+- Alternatives considered: Newest first; more rows; uncached loading.
+- Evidence: default: the request states no order or size, and the page loads on mount, so Critical Rule 15 applies.
+- Resolution: planner-default
+
+### A3 — Customer search scope
+- Decision: The customer search keeps the loaded opportunities whose customer name contains the search text, ignoring case. It searches the rows on the page, not the server, and its label says so.
+- Alternatives considered: A server search of account names and contact full names through the customerid_account and customerid_contact paths.
+- Evidence: default: the request asks for a substring search of customer names without naming its scope.
+- Resolution: planner-default
+
+### A4 — Customer choices
+- Decision: Change customer offers the distinct resolved customers of the loaded opportunities, accounts and contacts, each shown with its table so that equal names stay apart. An unresolved customer is not offered.
+- Alternatives considered: A search of every account and contact.
+- Evidence: default: the request asks to change the customer without naming where the choices come from.
+- Resolution: planner-default
+
+## Working Directory
+D:/work/customer-opportunities
+
+## Plugin Root
+D:/repo/plugins/model-apps
+
+## Environment
+- URL: https://contoso.crm.dynamics.com
+- App: Sales Hub (11111111-2222-3333-4444-555555555555)
+- Languages: English (1033) only
+- Solution: Default
+- Publisher Prefix: new
+
+## Pages
+| Page | File | Purpose | Entities |
+|------|------|---------|----------|
+| Customer Opportunities | customer-lookup.tsx | Browse opportunities with their account or contact customer; open, filter by and change the customer | opportunity |
+
+## Entity Creation Required
+No entity creation required — all entities already exist.
+
+## Existing Entities
+opportunity
+
+## Connector Bindings
+No connector bindings.
+
+## Custom API Bindings
+No custom API bindings.
+
+## Design Preferences
+- Styling: Default Fluent UI V9 look; makeStyles with tokens, no custom theme
+- Features: An opportunity list with each customer, a search of the loaded rows by customer name, open and change the customer, and one account's opportunities; each failure is shown where it happened, in its own error bar
+- Accessibility: WCAG AA defaults; the search box and both panels have accessible labels
+
+## Relevant Samples
+| Page | Sample | Reason |
+|------|--------|--------|
+| Customer Opportunities | 9-list-with-caching.tsx | Dataverse list with window cache, in-flight de-dupe and a reported load failure |
+| Customer Opportunities | 3-account-crud-dataverse.tsx | A reported write with no retry beside a cached list |
+
+## Per-Page Specifications
+
+### Customer Opportunities
+- **File:** customer-lookup.tsx
+- **Purpose:** Browse opportunities with their account or contact customer; open, filter by and change the customer
+- **Entities:** opportunity
+- **Needs caching:** true
+- **Key Features:** The opportunity list with each customer's name (F3); a search of the loaded rows by customer name (F2); Open customer for a resolved customer (R2); the opportunities of an account customer (R1, F1); Change customer with a picker that keeps each choice's table (R2, A4); separate error bars for the list, the navigation, the account view and the change.
+- **Components:** SearchBox, Button, Dropdown, Option, Field, MessageBar, Spinner, Text; OpenRegular icon.
+- **Layout:** Title, the list and navigation error bars, the search box, the opportunity list, then the account-opportunities panel and the change-customer panel; no viewport units.
+- **Data Binding:** dataApi.queryTable('opportunity') on mount selecting opportunityid, name, _customerid_value with the filter _customerid_value ne null (F3), ordered by name asc, 50 rows, read via result.rows with the window cache and in-flight de-dupe (A2); every customer normalized with normalizeLookupReference(row, '_customerid_value', ['account', 'contact']); the account view's dataApi.queryTable('opportunity') filtered by customerid_account/accountid eq the account's bare id (R1, F1); dataApi.updateRow('opportunity') writes _customerid_value as /account(<id>) or /contact(<id>) for the chosen table (R2).
+- **Interactions:** Typing in the search box filters the loaded rows (F2); Open customer opens the record in its own table with Xrm.Navigation.navigateTo; "Show this account's opportunities" appears only for an account customer; Change customer picks one of the loaded customers and saves once (a double-save latch), then reloads the list; a failed list read offers Try again; a failed account read or navigation is a read error; a failed change is a write with no retry.
+
+#### Data semantics
+
+##### R1
+- Kind: relationship
+- Definition: Account opportunities: opportunity.customerid → account, the direct customer. Offered only for an opportunity whose customer normalizes to an account; parentaccountid is not used and contact customers do not roll up. A contact, unset or unresolved customer offers no account view.
+- Source: A1
+
+##### R2
+- Kind: relationship
+- Definition: Customer reference: opportunity.customerid with its complete targets account and contact. Each row's customer is normalized to its actual table and bare id before it is opened or offered as a choice; a change writes the chosen table's qualified reference; an unresolved customer is shown by its label only.
+- Source: User Requirements
+- Requirement quote: open the customer's record, change the opportunity's customer
+
+##### F1
+- Kind: filter
+- Definition: Account opportunities query: opportunity rows with customerid_account/accountid eq the account's bare id, read when the maker asks for one account's opportunities. A refused or failed read is shown as a read error; the predicate is never weakened and nothing is post-filtered.
+- Source: A1
+
+##### F2
+- Kind: filter
+- Definition: Customer search: keep the loaded opportunities whose customer label (the formatted value of _customerid_value) contains the search text, ignoring case; client-side, over the loaded rows only.
+- Source: A3
+- Requirement quote: search customer names by substring
+
+##### F3
+- Kind: filter
+- Definition: All customers: opportunity rows with _customerid_value ne null — a customer of either target, account or contact; no target, owner, state or date restriction.
+- Source: User Requirements
+- Requirement quote: Show every opportunity that has a customer, whether an account or a contact
+
+#### Lookup metadata
+
+| Table | Column | Read property | Targets | Used by | Metadata state |
+|-------|--------|---------------|---------|---------|----------------|
+| opportunity | customerid | _customerid_value | account, contact | R1, R2, F1, F2, F3; customer navigation; customer picker | observed |
+
+| Table | Column | Target | Navigation property | Referenced key |
+|-------|--------|--------|---------------------|----------------|
+| opportunity | customerid | account | customerid_account | accountid |
+| opportunity | customerid | contact | customerid_contact | contactid |
+
+- Evidence: lookup-metadata.json; successful source/target metadata discovery.
+- Read target strategy: normalize the logical-name annotation and qualified prefix; a bare id without target evidence stays unresolved and is shown by its label only — no fallback read.
diff --git a/evals/model-apps/genpage/fixtures/26-customer-lookup/lookup-metadata.json b/evals/model-apps/genpage/fixtures/26-customer-lookup/lookup-metadata.json
new file mode 100644
index 000000000..8077247a8
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/26-customer-lookup/lookup-metadata.json
@@ -0,0 +1 @@
+{"ok":true,"tables":[{"logicalName":"opportunity","primaryIdAttribute":"opportunityid","primaryNameAttribute":"name","lookups":[{"column":"customerid","readProperty":"_customerid_value","attributeType":"Customer","targets":["account","contact"],"paths":[{"target":"account","navigationProperty":"customerid_account","referencedKey":"accountid","relationship":"opportunity_customer_accounts"},{"target":"contact","navigationProperty":"customerid_contact","referencedKey":"contactid","relationship":"opportunity_customer_contacts"}],"sharedPaths":[]},{"column":"ownerid","readProperty":"_ownerid_value","attributeType":"Owner","targets":["systemuser","team"],"paths":[],"sharedPaths":[{"referencedEntity":"owner","navigationProperty":"ownerid","referencedKey":"ownerid","relationship":"owner_opportunitys"}]},{"column":"parentaccountid","readProperty":"_parentaccountid_value","attributeType":"Lookup","targets":["account"],"paths":[{"target":"account","navigationProperty":"parentaccountid","referencedKey":"accountid","relationship":"opportunity_parent_account"}],"sharedPaths":[]},{"column":"parentcontactid","readProperty":"_parentcontactid_value","attributeType":"Lookup","targets":["contact"],"paths":[{"target":"contact","navigationProperty":"parentcontactid","referencedKey":"contactid","relationship":"opportunity_parent_contact"}],"sharedPaths":[]}]}]}
diff --git a/evals/model-apps/genpage/fixtures/26-customer-lookup/lookup-rows.json b/evals/model-apps/genpage/fixtures/26-customer-lookup/lookup-rows.json
new file mode 100644
index 000000000..a1a9ede95
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/26-customer-lookup/lookup-rows.json
@@ -0,0 +1,160 @@
+{
+ "description": "Synthetic opportunity rows for eval 26, not captured from an environment: the Customer value shapes the page must handle and the state the canonical normalizer of references/rules.md gives each one.",
+ "lookup": {
+ "table": "opportunity",
+ "column": "customerid",
+ "readProperty": "_customerid_value",
+ "targets": [
+ "account",
+ "contact"
+ ]
+ },
+ "rows": [
+ {
+ "case": "account, qualified, with the annotation",
+ "row": {
+ "opportunityid": "0a000001-0000-4000-8000-000000000021",
+ "name": "Fabrikam renewal",
+ "_customerid_value": "/account(a1a1a1a1-0000-4000-8000-000000000001)",
+ "[email protected]": "account",
+ "[email protected]": "Fabrikam"
+ },
+ "expected": {
+ "state": "resolved",
+ "reference": {
+ "table": "account",
+ "id": "a1a1a1a1-0000-4000-8000-000000000001"
+ }
+ }
+ },
+ {
+ "case": "contact, qualified, no annotation",
+ "row": {
+ "opportunityid": "0a000002-0000-4000-8000-000000000022",
+ "name": "Lamna onboarding",
+ "_customerid_value": "/contact(c2c2c2c2-0000-4000-8000-000000000002)",
+ "[email protected]": "Rene Valdes"
+ },
+ "expected": {
+ "state": "resolved",
+ "reference": {
+ "table": "contact",
+ "id": "c2c2c2c2-0000-4000-8000-000000000002"
+ }
+ }
+ },
+ {
+ "case": "contact, bare id, with the annotation",
+ "row": {
+ "opportunityid": "0a000003-0000-4000-8000-000000000023",
+ "name": "Lamna expansion",
+ "_customerid_value": "c2c2c2c2-0000-4000-8000-000000000002",
+ "[email protected]": "contact",
+ "[email protected]": "Rene Valdes"
+ },
+ "expected": {
+ "state": "resolved",
+ "reference": {
+ "table": "contact",
+ "id": "c2c2c2c2-0000-4000-8000-000000000002"
+ }
+ }
+ },
+ {
+ "case": "bare id, no annotation (two targets: no table evidence)",
+ "row": {
+ "opportunityid": "0a000004-0000-4000-8000-000000000024",
+ "name": "Northwind pilot",
+ "_customerid_value": "b3b3b3b3-0000-4000-8000-000000000003",
+ "[email protected]": "Northwind"
+ },
+ "expected": {
+ "state": "needs-target",
+ "id": "b3b3b3b3-0000-4000-8000-000000000003"
+ }
+ },
+ {
+ "case": "explicit null",
+ "row": {
+ "opportunityid": "0a000005-0000-4000-8000-000000000025",
+ "name": "Unassigned lead",
+ "_customerid_value": null
+ },
+ "expected": {
+ "state": "unset"
+ }
+ },
+ {
+ "case": "annotation contradicts the prefix",
+ "row": {
+ "opportunityid": "0a000006-0000-4000-8000-000000000026",
+ "name": "Conflicting evidence",
+ "_customerid_value": "/account(a1a1a1a1-0000-4000-8000-000000000001)",
+ "[email protected]": "contact",
+ "[email protected]": "Fabrikam"
+ },
+ "expected": {
+ "state": "invalid"
+ }
+ },
+ {
+ "case": "annotation names a table outside the targets",
+ "row": {
+ "opportunityid": "0a000007-0000-4000-8000-000000000027",
+ "name": "Foreign table",
+ "_customerid_value": "a1a1a1a1-0000-4000-8000-000000000001",
+ "[email protected]": "lead",
+ "[email protected]": "Fabrikam"
+ },
+ "expected": {
+ "state": "invalid"
+ }
+ },
+ {
+ "case": "plural entity set prefix",
+ "row": {
+ "opportunityid": "0a000008-0000-4000-8000-000000000028",
+ "name": "Plural prefix",
+ "_customerid_value": "/accounts(a1a1a1a1-0000-4000-8000-000000000001)",
+ "[email protected]": "Fabrikam"
+ },
+ "expected": {
+ "state": "invalid"
+ }
+ },
+ {
+ "case": "equal label, account",
+ "row": {
+ "opportunityid": "0a000009-0000-4000-8000-000000000029",
+ "name": "Contoso hardware",
+ "_customerid_value": "/account(b3b3b3b3-0000-4000-8000-000000000003)",
+ "[email protected]": "account",
+ "[email protected]": "Contoso"
+ },
+ "expected": {
+ "state": "resolved",
+ "reference": {
+ "table": "account",
+ "id": "b3b3b3b3-0000-4000-8000-000000000003"
+ }
+ }
+ },
+ {
+ "case": "equal label, contact, and the same GUID as the account above",
+ "row": {
+ "opportunityid": "0a000010-0000-4000-8000-000000000020",
+ "name": "Contoso services",
+ "_customerid_value": "/contact(B3B3B3B3-0000-4000-8000-000000000003)",
+ "[email protected]": "contact",
+ "[email protected]": "Contoso"
+ },
+ "expected": {
+ "state": "resolved",
+ "reference": {
+ "table": "contact",
+ "id": "b3b3b3b3-0000-4000-8000-000000000003"
+ }
+ }
+ }
+ ]
+}
diff --git a/evals/model-apps/genpage/fixtures/26-customer-lookup/page-name.txt b/evals/model-apps/genpage/fixtures/26-customer-lookup/page-name.txt
new file mode 100644
index 000000000..92c6f18b3
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/26-customer-lookup/page-name.txt
@@ -0,0 +1 @@
+Customer Opportunities
diff --git a/evals/model-apps/genpage/fixtures/26-customer-lookup/prompt.txt b/evals/model-apps/genpage/fixtures/26-customer-lookup/prompt.txt
new file mode 100644
index 000000000..a986ad968
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/26-customer-lookup/prompt.txt
@@ -0,0 +1,4 @@
+Build a Customer Opportunities page for our existing opportunities. Show every opportunity that has a customer, whether an account or a contact, and let me search customer names by substring. From each opportunity I want to open the customer's record, change the opportunity's customer, and see the opportunities for this account.
+
+- Data source: Dataverse entity opportunity (already exists)
+- Specific requirements: open the customer's record, change the customer, and show the opportunities for this account
diff --git a/evals/model-apps/genpage/fixtures/26-customer-lookup/semantic-interactions.json b/evals/model-apps/genpage/fixtures/26-customer-lookup/semantic-interactions.json
new file mode 100644
index 000000000..f1618b610
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/26-customer-lookup/semantic-interactions.json
@@ -0,0 +1,26 @@
+[
+ {
+ "type": "needs_input",
+ "event": "planner-discovery",
+ "question": "opportunities-account-scope",
+ "options": [
+ "Parent account",
+ "Direct customer",
+ "Customer plus contacts"
+ ],
+ "defaults": []
+ },
+ {
+ "type": "answer",
+ "event": "planner-answers",
+ "question": "opportunities-account-scope",
+ "selected": "Direct customer",
+ "source": "AskUserQuestion"
+ },
+ {
+ "type": "approval",
+ "preview": "approved-plan.md",
+ "outcome": "approved",
+ "source": "ExitPlanMode"
+ }
+]
diff --git a/evals/model-apps/genpage/fixtures/26-customer-lookup/tool-results.json b/evals/model-apps/genpage/fixtures/26-customer-lookup/tool-results.json
new file mode 100644
index 000000000..0b9354d64
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/26-customer-lookup/tool-results.json
@@ -0,0 +1,452 @@
+[
+ {
+ "id": "manifest",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/generate-page-manifest.js' 'D:/work/customer-opportunities' 'customer-opportunities'",
+ "exitCode": 0,
+ "result": {
+ "workingDir": "D:\\work\\customer-opportunities",
+ "slug": "customer-opportunities",
+ "features": [],
+ "files": {
+ "package.json": {
+ "wrote": true
+ },
+ "genpage.d.ts": {
+ "wrote": true
+ }
+ }
+ }
+ },
+ {
+ "id": "interaction-mode",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/resolve-interaction-mode.js'",
+ "exitCode": 0,
+ "result": {
+ "ok": true,
+ "interactive": true,
+ "reason": "default (attended)"
+ }
+ },
+ {
+ "id": "node-version",
+ "command": "node --version",
+ "exitCode": 0,
+ "result": "v20.20.2"
+ },
+ {
+ "id": "pac-help",
+ "command": "pac help",
+ "exitCode": 0,
+ "result": "Microsoft PowerPlatform CLI Version: 2.11.0"
+ },
+ {
+ "id": "auth-list",
+ "command": "pac auth list",
+ "exitCode": 0,
+ "result": "Index Active Kind Name Friendly Name User Cloud Type Environment Environment Url\n[1] * UNIVERSAL Contoso [email protected] Public User Contoso https://contoso.crm.dynamics.com/"
+ },
+ {
+ "id": "list-languages",
+ "by": "genpage-planner",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/list-languages.js' --env 'https://contoso.crm.dynamics.com'",
+ "exitCode": 0,
+ "result": {
+ "ok": true,
+ "baseLanguage": {
+ "lcid": 1033,
+ "code": "en-US",
+ "name": "English (United States)",
+ "rtl": false
+ },
+ "languages": [
+ {
+ "lcid": 1033,
+ "code": "en-US",
+ "name": "English (United States)",
+ "rtl": false
+ }
+ ],
+ "unmapped": [],
+ "summary": [
+ "1033 en-US — RTL: No"
+ ]
+ }
+ },
+ {
+ "id": "list-tables",
+ "by": "genpage-planner",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/list-tables.js' --env 'https://contoso.crm.dynamics.com' --search 'opportunity' --exact",
+ "exitCode": 0,
+ "result": {
+ "ok": true,
+ "search": [
+ "opportunity"
+ ],
+ "exact": true,
+ "count": 1,
+ "tables": [
+ {
+ "logicalName": "opportunity",
+ "displayName": "Opportunity",
+ "schemaName": "Opportunity",
+ "isCustom": false
+ }
+ ],
+ "missing": []
+ }
+ },
+ {
+ "id": "lookup-metadata",
+ "by": "genpage-planner",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/get-lookup-metadata.js' --env 'https://contoso.crm.dynamics.com' --tables 'opportunity'",
+ "exitCode": 0,
+ "artifact": "lookup-metadata.json",
+ "result": {
+ "ok": true,
+ "tables": [
+ {
+ "logicalName": "opportunity",
+ "primaryIdAttribute": "opportunityid",
+ "primaryNameAttribute": "name",
+ "lookups": [
+ {
+ "column": "customerid",
+ "readProperty": "_customerid_value",
+ "attributeType": "Customer",
+ "targets": [
+ "account",
+ "contact"
+ ],
+ "paths": [
+ {
+ "target": "account",
+ "navigationProperty": "customerid_account",
+ "referencedKey": "accountid",
+ "relationship": "opportunity_customer_accounts"
+ },
+ {
+ "target": "contact",
+ "navigationProperty": "customerid_contact",
+ "referencedKey": "contactid",
+ "relationship": "opportunity_customer_contacts"
+ }
+ ],
+ "sharedPaths": []
+ },
+ {
+ "column": "ownerid",
+ "readProperty": "_ownerid_value",
+ "attributeType": "Owner",
+ "targets": [
+ "systemuser",
+ "team"
+ ],
+ "paths": [],
+ "sharedPaths": [
+ {
+ "referencedEntity": "owner",
+ "navigationProperty": "ownerid",
+ "referencedKey": "ownerid",
+ "relationship": "owner_opportunitys"
+ }
+ ]
+ },
+ {
+ "column": "parentaccountid",
+ "readProperty": "_parentaccountid_value",
+ "attributeType": "Lookup",
+ "targets": [
+ "account"
+ ],
+ "paths": [
+ {
+ "target": "account",
+ "navigationProperty": "parentaccountid",
+ "referencedKey": "accountid",
+ "relationship": "opportunity_parent_account"
+ }
+ ],
+ "sharedPaths": []
+ },
+ {
+ "column": "parentcontactid",
+ "readProperty": "_parentcontactid_value",
+ "attributeType": "Lookup",
+ "targets": [
+ "contact"
+ ],
+ "paths": [
+ {
+ "target": "contact",
+ "navigationProperty": "parentcontactid",
+ "referencedKey": "contactid",
+ "relationship": "opportunity_parent_contact"
+ }
+ ],
+ "sharedPaths": []
+ }
+ ]
+ }
+ ]
+ }
+ },
+ {
+ "id": "list-apps",
+ "by": "genpage-planner",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/apps.js' list --env 'https://contoso.crm.dynamics.com'",
+ "exitCode": 0,
+ "result": {
+ "ok": true,
+ "count": 2,
+ "apps": [
+ {
+ "id": "11111111-2222-3333-4444-555555555555",
+ "name": "Sales Hub",
+ "uniqueName": "SalesHub",
+ "description": "",
+ "published": true,
+ "unpublishedChanges": false
+ },
+ {
+ "id": "44444444-5555-6666-7777-888888888888",
+ "name": "Customer Service Hub",
+ "uniqueName": "CustomerServiceHub",
+ "description": "",
+ "published": true,
+ "unpublishedChanges": false
+ }
+ ]
+ }
+ },
+ {
+ "id": "planner-discovery",
+ "command": "Task genpage-planner (discovery: create, No connector bindings., No custom API bindings.)",
+ "result": {
+ "action": "needs_input",
+ "why": "The possible account relationships select different opportunities.",
+ "questions": [
+ {
+ "id": "opportunities-account-scope",
+ "question": "Which opportunities should this account show?",
+ "options": [
+ {
+ "label": "Parent account",
+ "description": "Filter parentaccountid; metadata targets account."
+ },
+ {
+ "label": "Direct customer",
+ "description": "Filter customerid for account customers; metadata targets account and contact."
+ },
+ {
+ "label": "Customer plus contacts",
+ "description": "Include direct account customers and contact customers linked through the verified contact relationship."
+ }
+ ],
+ "multiSelect": false
+ },
+ {
+ "id": "app",
+ "question": "Which app should the page be added to?",
+ "options": [
+ {
+ "label": "Sales Hub (11111111-2222-3333-4444-555555555555)"
+ },
+ {
+ "label": "Customer Service Hub (44444444-5555-6666-7777-888888888888)"
+ },
+ {
+ "label": "Create a new app"
+ }
+ ],
+ "multiSelect": false
+ }
+ ],
+ "reserved": [
+ "A1"
+ ],
+ "lookupMetadata": "D:/work/customer-opportunities/lookup-metadata.json",
+ "discovered": {
+ "languages": [
+ "English (1033)"
+ ],
+ "existingEntities": [
+ "opportunity"
+ ],
+ "entitiesToCreate": []
+ }
+ }
+ },
+ {
+ "id": "planner-answers",
+ "command": "Task genpage-planner (answers: opportunities-account-scope → Direct customer; app → Sales Hub; lookup-metadata.json)",
+ "result": {
+ "action": "plan",
+ "pages": [
+ {
+ "page": "Customer Opportunities",
+ "file": "customer-lookup.tsx",
+ "entities": [
+ "opportunity"
+ ]
+ }
+ ],
+ "assumptions": [
+ "A1",
+ "A2",
+ "A3",
+ "A4"
+ ],
+ "entityCreationRequired": false,
+ "app": {
+ "name": "Sales Hub",
+ "appId": "11111111-2222-3333-4444-555555555555"
+ }
+ }
+ },
+ {
+ "id": "plan-prepare",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' prepare --plan 'D:/work/customer-opportunities/genpage-plan.md'",
+ "exitCode": 0,
+ "result": {
+ "ok": true,
+ "action": "prepare",
+ "planPath": "D:\\work\\customer-opportunities\\genpage-plan.md",
+ "quarantinedPath": null
+ }
+ },
+ {
+ "id": "save-approved",
+ "command": "Write .approved-genpage-plan.md",
+ "artifact": "approved-plan.md"
+ },
+ {
+ "id": "planner-write",
+ "command": "Task genpage-planner (approved: write genpage-plan.md)",
+ "result": {
+ "action": "written",
+ "plan": "D:/work/customer-opportunities/genpage-plan.md"
+ }
+ },
+ {
+ "id": "plan-verify",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' verify --plan 'D:/work/customer-opportunities/genpage-plan.md' --approved '@D:/work/customer-opportunities/.approved-genpage-plan.md' --require-assumptions",
+ "exitCode": 0,
+ "result": {
+ "ok": true,
+ "action": "verify",
+ "planPath": "D:\\work\\customer-opportunities\\genpage-plan.md",
+ "kind": "create",
+ "targets": [
+ "customer-lookup.tsx"
+ ],
+ "writtenHash": "96ba32971bfd7409cf3580b00d1018755f47f85466b19643f3fe8dcf3382cd35",
+ "semanticsHash": "7c0546b925ec9a8d70a0aa883197403116b8214a708a795ba33e6a84fabb1c97"
+ }
+ },
+ {
+ "id": "generate-types",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage.js' types --env 'https://contoso.crm.dynamics.com' --data-sources 'opportunity' --output-file 'D:/work/customer-opportunities/RuntimeTypes.ts'",
+ "exitCode": 0,
+ "result": {
+ "ok": true,
+ "outputFile": "D:/work/customer-opportunities/RuntimeTypes.ts",
+ "dataSources": [
+ "opportunity"
+ ],
+ "detail": "none",
+ "bytes": 21504
+ }
+ },
+ {
+ "id": "gate-telemetry",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/lib/feature-flags.js' custom-telemetry",
+ "exitCode": 1,
+ "result": "disabled"
+ },
+ {
+ "id": "page-files",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/check-page-files.js' --plan 'D:/work/customer-opportunities/genpage-plan.md'",
+ "exitCode": 0,
+ "result": {
+ "ok": true,
+ "workingDir": "D:\\work\\customer-opportunities",
+ "files": [
+ "customer-lookup.tsx"
+ ],
+ "problems": []
+ }
+ },
+ {
+ "id": "plan-verify-5a",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' verify --plan 'D:/work/customer-opportunities/genpage-plan.md' --approved '@D:/work/customer-opportunities/.approved-genpage-plan.md' --require-assumptions --require-observed-lookups --lookup-metadata 'D:/work/customer-opportunities/lookup-metadata.json'",
+ "exitCode": 0,
+ "result": {
+ "ok": true,
+ "action": "verify",
+ "planPath": "D:\\work\\customer-opportunities\\genpage-plan.md",
+ "kind": "create",
+ "targets": [
+ "customer-lookup.tsx"
+ ],
+ "writtenHash": "96ba32971bfd7409cf3580b00d1018755f47f85466b19643f3fe8dcf3382cd35",
+ "semanticsHash": "7c0546b925ec9a8d70a0aa883197403116b8214a708a795ba33e6a84fabb1c97"
+ }
+ },
+ {
+ "id": "stamp",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-worker-output.js' --stamp --file 'D:/work/customer-opportunities/customer-lookup.tsx'",
+ "exitCode": 0,
+ "result": {
+ "ok": true,
+ "action": "stamp",
+ "filePath": "D:\\work\\customer-opportunities\\customer-lookup.tsx",
+ "existed": false
+ }
+ },
+ {
+ "id": "write-page",
+ "command": "Write customer-lookup.tsx",
+ "artifact": "customer-lookup.tsx"
+ },
+ {
+ "id": "icon-grep",
+ "command": "Grep from \"@fluentui/react-icons\" customer-lookup.tsx; Grep ^OpenRegular$ references/verified-icons.txt",
+ "result": "OpenRegular: verified"
+ },
+ {
+ "id": "border-grep",
+ "command": "Grep ['\"]?borderWidth['\"]?\\s*: customer-lookup.tsx",
+ "result": "no matches"
+ },
+ {
+ "id": "gate",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-worker-output.js' --file 'D:/work/customer-opportunities/customer-lookup.tsx'",
+ "artifact": "customer-lookup.tsx",
+ "exitCode": 0,
+ "result": {
+ "ok": true,
+ "filePath": "D:\\work\\customer-opportunities\\customer-lookup.tsx",
+ "problems": []
+ }
+ },
+ {
+ "id": "write-upload-text",
+ "command": "Write prompt.txt, agent-message.txt, page-name.txt",
+ "artifacts": [
+ "prompt.txt",
+ "agent-message.txt",
+ "page-name.txt"
+ ]
+ },
+ {
+ "id": "create",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-upload.js' --env 'https://contoso.crm.dynamics.com' --app-id '11111111-2222-3333-4444-555555555555' --code-file 'customer-lookup.tsx' --name-file 'page-name.txt' --data-sources 'opportunity' --prompt-file 'prompt.txt' --model 'claude-sonnet-4-6' --agent-message-file 'agent-message.txt' --add-to-sitemap",
+ "exitCode": 0,
+ "result": {
+ "ok": true,
+ "pageId": "cccccccc-dddd-eeee-ffff-000000000026",
+ "appId": "11111111-2222-3333-4444-555555555555",
+ "updated": false
+ }
+ }
+]
diff --git a/evals/model-apps/genpage/fixtures/26-customer-lookup/workflow-log.md b/evals/model-apps/genpage/fixtures/26-customer-lookup/workflow-log.md
new file mode 100644
index 000000000..632ac1534
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/26-customer-lookup/workflow-log.md
@@ -0,0 +1,144 @@
+# Workflow Log — Eval 26: Customer opportunities with normalized lookups (create flow)
+
+Synthetic trace constructed from the current `/genpage` SKILL.md, not a captured agent run.
+Every command below has an ordered result in `tool-results.json`; the semantic question and
+the plan approval are also recorded, in order, in `semantic-interactions.json`. Commands run
+from the working directory, so file arguments are relative to it.
+
+## Phase 0 — Working directory
+- `$ARGUMENTS`: "Build a Customer Opportunities page for our existing opportunities."
+- Working directory created: `mkdir -p 'customer-opportunities'` (kebab-case from "Customer Opportunities")
+- Resolved working directory: D:/work/customer-opportunities
+- Plugin root: D:/repo/plugins/model-apps
+
+## Phase 0.5 — Local-dev manifest
+- Command: `node 'D:/repo/plugins/model-apps/scripts/generate-page-manifest.js' 'D:/work/customer-opportunities' 'customer-opportunities'`
+- Result: exit 0; package.json and genpage.d.ts written; no `--features` (no charts or date/time pickers needed)
+
+## Phase 1 — Plan
+
+### Interaction mode
+- Command: `node 'D:/repo/plugins/model-apps/scripts/resolve-interaction-mode.js'`
+- Result: `{"ok":true,"interactive":true,"reason":"default (attended)"}` — attended run, every gate asked in this loop
+
+### Prereq checks (run separately, not chained)
+- `node --version` → v20.20.2
+- `pac help` → Microsoft PowerPlatform CLI Version: 2.11.0 (> 2.10.0 verified)
+
+### Auth
+- `pac auth list` → one profile, currently active: [email protected]
+- Active environment reported to the user: https://contoso.crm.dynamics.com/
+
+### Create or edit
+- AskUserQuestion: Do you want to create new page(s) or edit an existing page? → Create new page(s)
+
+### Requirements
+- AskUserQuestion: Where should the page get its data? → Dataverse entity: opportunity
+- AskUserQuestion: Any specific requirements for the page? → Open the customer's record, change the customer, and show the opportunities for this account
+
+### Discovery (genpage-planner dispatched via Task as a headless worker)
+- Dispatched `Task genpage-planner` with the requirements, working directory, plugin root, create/edit decision = create, `No connector bindings.` (connectors.json: none — omit --connectors) and `No custom API bindings.`
+- Planner ran `node 'D:/repo/plugins/model-apps/scripts/list-languages.js' --env 'https://contoso.crm.dynamics.com'` → English (1033) only, no RTL language
+- Planner ran `node 'D:/repo/plugins/model-apps/scripts/list-tables.js' --env 'https://contoso.crm.dynamics.com' --search 'opportunity' --exact` → 1 table: `opportunity` (exact logical-name match, nothing in `missing`); no entity creation
+- Planner ran `node 'D:/repo/plugins/model-apps/scripts/get-lookup-metadata.js' --env 'https://contoso.crm.dynamics.com' --tables 'opportunity'` → exit 0; saved verbatim as D:/work/customer-opportunities/lookup-metadata.json: `customerid` targets account and contact, with the concrete paths customerid_account/accountid and customerid_contact/contactid; `parentaccountid` targets account; `parentcontactid` targets contact; `ownerid` targets systemuser and team through a shared path only
+- Planner ran `node 'D:/repo/plugins/model-apps/scripts/apps.js' list --env 'https://contoso.crm.dynamics.com'` → 2 apps: Sales Hub (11111111-2222-3333-4444-555555555555), Customer Service Hub (44444444-5555-6666-7777-888888888888)
+- Data semantics (planner Step 4, "Resolve Data Semantics"): "the opportunities for this account" can mean the parent account, the direct customer, or the customer plus its contacts — three metadata-backed candidates, so the planner asked instead of assuming, with no default; it reserved A1 for the answer and wrote no settled assumption
+- Planner returned `{ "action": "needs_input" }` with two questions: `opportunities-account-scope` (Parent account; Direct customer; Customer plus contacts — no default) and `app`
+
+### Questions (asked here; the planner cannot prompt)
+- AskUserQuestion: Which opportunities should this account show? → Direct customer
+- AskUserQuestion: Which app should the page be added to? (options from `apps.js list`: Sales Hub — 11111111-2222-3333-4444-555555555555; Customer Service Hub — 44444444-5555-6666-7777-888888888888; Create a new app) → Sales Hub (existing app)
+- Re-invoked `Task genpage-planner` with both answers by question id (`opportunities-account-scope` → Direct customer; `app` → Sales Hub), D:/work/customer-opportunities/lookup-metadata.json and everything it returned before; it settled A1 as user-confirmed (Question opportunities-account-scope, Answer Direct customer) and recorded three planner defaults (A2 — order, size and caching; A3 — search scope; A4 — customer choices)
+
+### Solution selection
+- Code-only build (no new entities, existing app) → solution selection question SKIPPED
+- Defaults written to the plan: `Solution: Default`, `Publisher Prefix: new`
+
+### Plan approval
+- The planner returned the proposed plan (1 page: Customer Opportunities on opportunity), its `### Assumptions` first
+- EnterPlanMode called — presented the proposed plan: Assumptions A1–A4 first, then the page list, the Data Semantics (R1, R2, F1, F2, F3) and the Lookup Metadata (opportunity.customerid, observed, targets account and contact)
+- ExitPlanMode → user approved the plan without changes
+- Command: `node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' prepare --plan 'D:/work/customer-opportunities/genpage-plan.md'`
+- Result: `"ok":true`, nothing to quarantine (first run in this folder)
+- Saved the approved plan body verbatim to D:/work/customer-opportunities/.approved-genpage-plan.md (kept here as approved-plan.md)
+- Re-invoked `Task genpage-planner` with the approval outcome, the approved plan body, both answers and all prior discovery; it wrote genpage-plan.md (conforms to references/plan-schema.md, with the same Assumptions and per-page records, and User Requirements exactly the original request)
+- Command: `node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' verify --plan 'D:/work/customer-opportunities/genpage-plan.md' --approved '@D:/work/customer-opportunities/.approved-genpage-plan.md' --require-assumptions`
+- Result: `"ok":true`, kind create, targets [customer-lookup.tsx], writtenHash 96ba32971bfd7409cf3580b00d1018755f47f85466b19643f3fe8dcf3382cd35, semanticsHash 7c0546b925ec9a8d70a0aa883197403116b8214a708a795ba33e6a84fabb1c97
+
+## Phase 2 — Entities
+- SKIPPED: `## Entity Creation Required` is the no-entity sentinel (opportunity exists)
+- check-auth.js and genpage-entity-builder were not invoked (no metadata work)
+- Phase 2c SKIPPED: the plan's one lookup (opportunity.customerid) is already `observed` — no planned lookup to reconcile
+
+## Phase 3 — App
+- SKIPPED app creation: existing app Sales Hub (11111111-2222-3333-4444-555555555555) selected
+
+## Phase 4 — RuntimeTypes
+- `node 'D:/repo/plugins/model-apps/scripts/genpage.js' types --env 'https://contoso.crm.dynamics.com' --data-sources 'opportunity' --output-file 'D:/work/customer-opportunities/RuntimeTypes.ts'`
+- Read RuntimeTypes.ts: verified opportunityid and name, and `_customerid_value` typed `/account(…)` | `/contact(…)` — the same two targets as the plan's lookup record
+
+## Phase 4.5 — Connector bindings
+- SKIPPED: plan says `No connector bindings.` → Connectors: none; no connectors.json, no `--connectors`
+
+## Phase 4.6 — Custom API bindings
+- The plan's `## Custom API Bindings` body is exactly `No custom API bindings.` → no Custom API rows
+
+## Phase 4.6b — Built-in Dataverse operations
+- SKIPPED: the plan has no `## Dataverse Operations` section
+
+## Phase 4.6c — The actions file
+- The desired array is empty: no actions.json, and the create passes no `--actions`
+
+## Phase 4.7 — Page telemetry
+- Command: `node 'D:/repo/plugins/model-apps/scripts/lib/feature-flags.js' custom-telemetry`
+- Result: `disabled` → Telemetry: disabled; the page contains no telemetry calls
+
+## Phase 5a — Plan validation
+- One page row with a matching `### Customer Opportunities` subsection
+- Command: `node 'D:/repo/plugins/model-apps/scripts/check-page-files.js' --plan 'D:/work/customer-opportunities/genpage-plan.md'`
+- Result: `"ok":true` — customer-lookup.tsx is a safe, unique page file
+- Every relationship and filter of the page traces to User Requirements or an assumption: R1 and F1 → A1; R2 and F3 → quoted requirements; F2 → A3 (with its quote)
+- The plan records a lookup, so every lookup must be observed and match the saved metadata read before the page is generated:
+- Command: `node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' verify --plan 'D:/work/customer-opportunities/genpage-plan.md' --approved '@D:/work/customer-opportunities/.approved-genpage-plan.md' --require-assumptions --require-observed-lookups --lookup-metadata 'D:/work/customer-opportunities/lookup-metadata.json'`
+- Result: `"ok":true`, semanticsHash 7c0546b925ec9a8d70a0aa883197403116b8214a708a795ba33e6a84fabb1c97 (unchanged since approval)
+
+## Phase 5b — Single-page fast path
+- Plan has 1 page → inlined the page-builder workflow (no Task dispatch for the page)
+- Data mode: dataverse; Connectors: none; Telemetry: disabled
+- Read D:/repo/plugins/model-apps/references/rules.md, including Critical Rules 22 and 23, "Missing Error Handling" and "Lookup references"
+- Read samples 9-list-with-caching.tsx and 3-account-crud-dataverse.tsx (from `## Relevant Samples`)
+- Needs caching: true → read references/data-caching.md
+- Languages: English only → localization.md not needed
+- Read genpage-plan.md (its Data semantics and Lookup metadata), lookup-metadata.json and RuntimeTypes.ts
+- Command: `node 'D:/repo/plugins/model-apps/scripts/genpage-worker-output.js' --stamp --file 'D:/work/customer-opportunities/customer-lookup.tsx'`
+- Result: `"ok":true`, stamp recorded, no earlier file at the target
+- Wrote customer-lookup.tsx with the file tool: the page error block and the lookup normalizer of rules.md copied unchanged, PageBody inside PageErrorBoundary; the list read (`_customerid_value ne null`) through the window cache and in-flight de-dupe, its rejection reported from the consumer's catch with a retry; every customer normalized with the complete targets account and contact before it is shown as openable, filtered by or offered; the account view only for an account customer, through customerid_account/accountid with the bare id, awaited with a stale-request guard and reported as a read; Open customer with the reference's own table, a rejection reported as a read; Change customer from a picker keyed by table and id, written as the chosen table's qualified value, a failure reported as a write with no retry
+- Icon verification: Grep for `from "@fluentui/react-icons"` → one named import, OpenRegular; Grep of references/verified-icons.txt for `^OpenRegular$` → present
+- Grep `['"]?borderWidth['"]?\s*:` → no matches
+- Command: `node 'D:/repo/plugins/model-apps/scripts/genpage-worker-output.js' --file 'D:/work/customer-opportunities/customer-lookup.tsx'`
+- Result: `"ok":true`, problems [] — complete page accepted
+
+## Phase 6 — Deploy
+- Checked prompt.txt, agent-message.txt and page-name.txt in the working directory: none existed, none is a link
+- Wrote prompt.txt (the full `## User Requirements` body), agent-message.txt and page-name.txt ("Customer Opportunities") with the file tool
+- Command: `node 'D:/repo/plugins/model-apps/scripts/genpage-upload.js' --env 'https://contoso.crm.dynamics.com' --app-id '11111111-2222-3333-4444-555555555555' --code-file 'customer-lookup.tsx' --name-file 'page-name.txt' --data-sources 'opportunity' --prompt-file 'prompt.txt' --model 'claude-sonnet-4-6' --agent-message-file 'agent-message.txt' --add-to-sitemap`
+- Prompt scope: full page description from the plan's `## User Requirements` (create)
+- Result: page-id = cccccccc-dddd-eeee-ffff-000000000026, status = success (`updated: false`, added to the Sales Hub sitemap)
+
+## Phase 6.5 — Navigation fix-up
+- SKIPPED: single page, no PAGEREF_ placeholders
+
+## Phase 7 — Verify in browser
+- AskUserQuestion: Would you like to verify the page(s) in the browser using Playwright? → Skip verification
+
+## Phase 8 — Summary
+
+| Page | File | Entities | Status |
+|------|------|----------|--------|
+| Customer Opportunities | customer-lookup.tsx | opportunity | Deployed |
+
+- App: Sales Hub (11111111-2222-3333-4444-555555555555)
+- Page ID: cccccccc-dddd-eeee-ffff-000000000026
+- Entities created: none
+- Lookups: opportunity.customerid (account, contact), observed
+- Browser verification: skipped
diff --git a/evals/model-apps/genpage/fixtures/27-page-error-helper/actions.json b/evals/model-apps/genpage/fixtures/27-page-error-helper/actions.json
new file mode 100644
index 000000000..d6e1594c8
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/27-page-error-helper/actions.json
@@ -0,0 +1,3 @@
+[
+ { "name": "cnt_ApproveOrder", "isFunction": false, "boundEntityLogicalName": "salesorder", "displayName": "Approve Order", "parameterKinds": { "Comment": "String" } }
+]
diff --git a/evals/model-apps/genpage/fixtures/27-page-error-helper/agent-message.txt b/evals/model-apps/genpage/fixtures/27-page-error-helper/agent-message.txt
new file mode 100644
index 000000000..11f529106
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/27-page-error-helper/agent-message.txt
@@ -0,0 +1 @@
+Created the Order Approvals page: a grid of sales orders, the selected order and an Approve button that runs the Approve Order action. Each failure is reported once and shown where it happened.
\ No newline at end of file
diff --git a/evals/model-apps/genpage/fixtures/27-page-error-helper/approved-plan.md b/evals/model-apps/genpage/fixtures/27-page-error-helper/approved-plan.md
new file mode 100644
index 000000000..8a6b03675
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/27-page-error-helper/approved-plan.md
@@ -0,0 +1,48 @@
+## Genpage Plan
+
+### Assumptions
+#### A1 — Order list scope
+- Decision: List every sales order the user can read, with no added status, owner or date restriction, sorted by name ascending, 50 rows per page.
+- Alternatives considered: Open orders only; the user's own orders; newest first.
+- Evidence: default: the request asks for the sales orders without a restriction.
+- Resolution: planner-default
+
+#### A2 — Initial-load caching
+- Decision: De-duplicate and cache the initial list read.
+- Alternatives considered: Uncached loading.
+- Evidence: default: this page loads on mount, so Critical Rule 15 applies.
+- Resolution: planner-default
+
+### Pages (1 total)
+| Page | File | Purpose | Entities |
+|------|------|---------|----------|
+| Order Approvals | order-approvals.tsx | List sales orders, show the selected one and approve it | salesorder |
+
+### Data Semantics
+#### order-approvals.tsx
+None.
+
+### Lookup Metadata
+#### order-approvals.tsx
+None.
+
+### Data Strategy
+- Entities needed: salesorder
+- Entities that exist: salesorder
+- Entities to create: none
+- Connector bindings: none
+- Custom API bindings: cnt_ApproveOrder (Action, bound to salesorder)
+- Built-in Dataverse operations: none
+- Sample data: not needed (existing table)
+
+### App
+- Using: Sales Hub (11111111-2222-3333-4444-555555555555)
+
+### Solution
+- Default / new
+
+### Localization
+- English only — no localization needed
+
+### Design
+- Default Fluent UI V9 look; an order grid, the selected order and its Approve button; each failure shown in its own error bar
diff --git a/evals/model-apps/genpage/fixtures/27-page-error-helper/custom-api-bindings.md b/evals/model-apps/genpage/fixtures/27-page-error-helper/custom-api-bindings.md
new file mode 100644
index 000000000..92ea17b00
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/27-page-error-helper/custom-api-bindings.md
@@ -0,0 +1,3 @@
+| Name | Kind | Bound Entity | Display Name | Parameters (name: kind) |
+|------|------|--------------|--------------|-------------------------|
+| cnt_ApproveOrder | Action | salesorder | Approve Order | Comment: String |
diff --git a/evals/model-apps/genpage/fixtures/27-page-error-helper/fixture.json b/evals/model-apps/genpage/fixtures/27-page-error-helper/fixture.json
new file mode 100644
index 000000000..087c7089a
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/27-page-error-helper/fixture.json
@@ -0,0 +1,28 @@
+{
+ "contractVersion": 2,
+ "provenance": "synthetic",
+ "description": "Constructed trace of a compliant attended create run for eval 27, not an agent capture. An existing table (salesorder) is shown as an order grid with a selected-order panel and an Approve button bound to the existing cnt_ApproveOrder Custom API Action. The page is built on the page error block of references/rules.md: a cached list read, an awaited read of the selected order and the Action report every failure through reportPageError into a rendered PageErrorBar, inside PageErrorBoundary. The newly authored plan records its assumptions (two planner defaults) and its per-page records (None.), the approved preview carries the same records, and provenance is verified with --require-assumptions.",
+ "contracts": [
+ "plugins/model-apps/skills/genpage/SKILL.md Phase 1: Plan (Steps 1-7, 1b Custom API discovery)",
+ "plugins/model-apps/skills/genpage/SKILL.md Phase 4.6 and 4.6c: Custom API bindings and the actions file",
+ "plugins/model-apps/skills/genpage/SKILL.md Phase 5a and 5b: Single-page fast path",
+ "plugins/model-apps/skills/genpage/SKILL.md Phase 6: Deploy and Prompt semantics",
+ "plugins/model-apps/references/plan-schema.md Assumptions, data semantics and lookup metadata",
+ "plugins/model-apps/references/rules.md Critical Rule 22 and Missing Error Handling",
+ "plugins/model-apps/references/custom-api.md Verified Action pattern",
+ "plugins/model-apps/references/data-caching.md Pattern 1"
+ ],
+ "expectedOutcome": "deployed",
+ "toolResults": "tool-results.json",
+ "artifacts": [
+ "prompt.txt",
+ "agent-message.txt",
+ "page-name.txt",
+ "approved-plan.md",
+ "actions.json",
+ "custom-api-bindings.md"
+ ],
+ "semantics": {
+ "approvedPlan": "approved-plan.md"
+ }
+}
diff --git a/evals/model-apps/genpage/fixtures/27-page-error-helper/genpage-plan.md b/evals/model-apps/genpage/fixtures/27-page-error-helper/genpage-plan.md
new file mode 100644
index 000000000..2871c06ba
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/27-page-error-helper/genpage-plan.md
@@ -0,0 +1,83 @@
+# Genpage Plan
+
+## User Requirements
+Build an Order Approvals page for our existing sales orders: list the sales orders, show the one I select, and let me approve it with the existing Approve Order action.
+
+- Data source: Dataverse entity salesorder (already exists)
+- Specific requirements: approve the selected order with the Approve Order action
+
+## Assumptions
+
+### A1 — Order list scope
+- Decision: List every sales order the user can read, with no added status, owner or date restriction, sorted by name ascending, 50 rows per page.
+- Alternatives considered: Open orders only; the user's own orders; newest first.
+- Evidence: default: the request asks for the sales orders without a restriction.
+- Resolution: planner-default
+
+### A2 — Initial-load caching
+- Decision: De-duplicate and cache the initial list read.
+- Alternatives considered: Uncached loading.
+- Evidence: default: this page loads on mount, so Critical Rule 15 applies.
+- Resolution: planner-default
+
+## Working Directory
+D:/work/order-approvals
+
+## Plugin Root
+D:/repo/plugins/model-apps
+
+## Environment
+- URL: https://contoso.crm.dynamics.com
+- App: Sales Hub (11111111-2222-3333-4444-555555555555)
+- Languages: English (1033) only
+- Solution: Default
+- Publisher Prefix: new
+
+## Pages
+| Page | File | Purpose | Entities |
+|------|------|---------|----------|
+| Order Approvals | order-approvals.tsx | List sales orders, show the selected one and approve it | salesorder |
+
+## Entity Creation Required
+No entity creation required — all entities already exist.
+
+## Existing Entities
+salesorder
+
+## Connector Bindings
+No connector bindings.
+
+## Custom API Bindings
+| Name | Kind | Bound Entity | Display Name | Parameters (name: kind) |
+|------|------|--------------|--------------|-------------------------|
+| cnt_ApproveOrder | Action | salesorder | Approve Order | Comment: String |
+
+## Design Preferences
+- Styling: Default Fluent UI V9 look; makeStyles with tokens, no custom theme
+- Features: Sortable order grid, a panel for the selected order with an approval note and an Approve button; each failure is shown where it happened, in its own error bar
+- Accessibility: WCAG AA defaults; the grid has an accessible label
+
+## Relevant Samples
+| Page | Sample | Reason |
+|------|--------|--------|
+| Order Approvals | 9-list-with-caching.tsx | Dataverse list with window cache, in-flight de-dupe and a reported load failure |
+| Order Approvals | 13-custom-api-invocation.tsx | Bound Custom API Action with the documented result guards and latch |
+
+## Per-Page Specifications
+
+### Order Approvals
+- **File:** order-approvals.tsx
+- **Purpose:** List sales orders, show the selected one and approve it
+- **Entities:** salesorder
+- **Needs caching:** true
+- **Key Features:** Order grid; the selected order's name and status; approval note; Approve button; separate error bars for the list, the selected order and the approval.
+- **Components:** DataGrid (createTableColumn, resizableColumns, columnSizingOptions), Button, Field, Textarea, MessageBar, Spinner, Text; CheckmarkRegular icon.
+- **Layout:** Title, then the order grid, then the selected-order panel; no viewport units.
+- **Data Binding:** dataApi.queryTable('salesorder') on mount selecting salesorderid, name, totalamount, statuscode, ordered by name asc, 50 rows (A1), read via result.rows, with the window cache and in-flight de-dupe (A2); dataApi.retrieveRow('salesorder') for the order the user selects; executeAction cnt_ApproveOrder bound to the selected salesorder with Comment from the note; NewStatus read from res.outputs.
+- **Interactions:** Selecting an order name loads it; Approve calls the Action once (a double-submit latch); an indeterminate result is reported and never retried; only a network result offers Try again; a failed list or order read offers Try again; a failed or rejected approval is a write with no retry.
+
+#### Data semantics
+None.
+
+#### Lookup metadata
+None.
diff --git a/evals/model-apps/genpage/fixtures/27-page-error-helper/order-approvals.tsx b/evals/model-apps/genpage/fixtures/27-page-error-helper/order-approvals.tsx
new file mode 100644
index 000000000..5718aa2f1
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/27-page-error-helper/order-approvals.tsx
@@ -0,0 +1,380 @@
+import * as React from 'react';
+import {
+ Button,
+ DataGrid,
+ DataGridBody,
+ DataGridCell,
+ DataGridHeader,
+ DataGridHeaderCell,
+ DataGridRow,
+ Field,
+ MessageBar,
+ MessageBarActions,
+ MessageBarBody,
+ Spinner,
+ TableCellLayout,
+ Text,
+ Textarea,
+ createTableColumn,
+ makeStyles,
+ tokens,
+} from '@fluentui/react-components';
+import { CheckmarkRegular } from '@fluentui/react-icons';
+import type { GeneratedComponentProps } from './RuntimeTypes';
+
+type PageErrorKind = 'read' | 'write' | 'indeterminate' | 'network' | 'render';
+type PageErrorView = {
+ operation: string;
+ message: string;
+ fallbackKey: string;
+ code?: string;
+ kind: PageErrorKind;
+ retry?: () => void;
+};
+type PageErrorTelemetry = {
+ trackException?: (error: unknown, properties?: Record<string, unknown>) => void;
+};
+
+// The plan's display name for this page: a fixed literal, not the file name.
+const PAGE_NAME = 'Order Approvals';
+
+// The error copy of an English-only page (references/rules.md, "Missing Error Handling").
+const ERROR_COPY: Record<string, string> = {
+ 'error.read': 'Unable to load data. Please try again.',
+ 'error.write': 'The change could not be saved. Refresh before trying again.',
+ 'error.network': 'The request did not go through. You can try again.',
+ 'error.indeterminate': "We couldn't confirm this completed — refresh before retrying.",
+ 'error.render': 'This page hit a problem and could not render. Refresh the page.',
+ 'error.tryAgain': 'Try again',
+};
+
+function translate(key: string): string {
+ return ERROR_COPY[key] || key;
+}
+
+// The page's one error reporter. It logs bounded diagnostics once and returns the view the failed
+// operation stores; it never sets state, never calls retry, and reads only the named fields of a
+// thrown value, each on its own, so a throwing getter leaves that one field empty.
+function reportPageError(
+ pageName: string,
+ operation: string,
+ code: unknown,
+ message: unknown,
+ kind: PageErrorKind,
+ retry?: () => void,
+ appInsights?: PageErrorTelemetry,
+): PageErrorView {
+ const fields: Record<string, unknown> = {};
+ for (const path of ['code', 'errorCode', 'message', 'error.code', 'error.message']) {
+ try {
+ let value: unknown = message;
+ for (const part of path.split('.')) {
+ value = value !== null && typeof value === 'object' ? (value as Record<string, unknown>)[part] : undefined;
+ }
+ fields[path] = value;
+ } catch {
+ fields[path] = undefined;
+ }
+ }
+ let normalizedCode = '';
+ for (const candidate of [code, fields['code'], fields['errorCode'], fields['error.code']]) {
+ const text = typeof candidate === 'string' ? candidate : typeof candidate === 'number' && Number.isFinite(candidate) ? String(candidate) : '';
+ normalizedCode = text.replace(/[\s\u0000-\u001f\u007f-\u009f]+/g, ' ').trim().slice(0, 80);
+ if (normalizedCode) break;
+ }
+ let normalizedMessage = '';
+ for (const candidate of [message, fields['message'], fields['error.message']]) {
+ const line = typeof candidate === 'string' ? candidate.trim().split(/[\r\n\u2028\u2029]/)[0].replace(/[\s\u0000-\u001f\u007f-\u009f]+/g, ' ').trim() : '';
+ if (!line || /^\[object [^\]]*\]$/.test(line) || /^at\s.*(?::\d+:\d+\)?|\((?:native|<anonymous>)\))$/.test(line)) continue;
+ normalizedMessage = line.length > 300 ? line.slice(0, 299) + '\u2026' : line;
+ break;
+ }
+ console.error('[' + String(pageName).replace(/[\r\n\]]/g, '') + '] ' + operation + ' failed', { code: normalizedCode, message: normalizedMessage });
+ const quiet = kind === 'indeterminate' || kind === 'render';
+ const view: PageErrorView = { operation, message: quiet ? '' : normalizedMessage, fallbackKey: 'error.' + kind, kind };
+ if (normalizedCode) view.code = normalizedCode;
+ if (typeof retry === 'function' && (kind === 'read' || kind === 'network')) view.retry = retry;
+ return view;
+}
+
+function PageErrorBar(props: { error: PageErrorView | null }) {
+ const { error } = props;
+ if (!error) return null;
+ return (
+ <MessageBar intent="error">
+ <MessageBarBody>{error.message || translate(error.fallbackKey)}</MessageBarBody>
+ {error.retry && (
+ <MessageBarActions>
+ <Button onClick={error.retry}>{translate('error.tryAgain')}</Button>
+ </MessageBarActions>
+ )}
+ </MessageBar>
+ );
+}
+
+// The page's one class component: it catches a render crash below it and shows a fixed message.
+class PageErrorBoundary extends React.Component<
+ { children: React.ReactNode; appInsights?: PageErrorTelemetry },
+ { failed: boolean }
+> {
+ public state = { failed: false };
+
+ public static getDerivedStateFromError(): { failed: boolean } {
+ return { failed: true };
+ }
+
+ public componentDidCatch(error: Error): void {
+ reportPageError(PAGE_NAME, 'render', undefined, error, 'render');
+ }
+
+ public render(): React.ReactNode {
+ if (this.state.failed) {
+ return (
+ <MessageBar intent="error">
+ <MessageBarBody>{translate('error.render')}</MessageBarBody>
+ </MessageBar>
+ );
+ }
+ return this.props.children;
+ }
+}
+
+type OrderRow = {
+ salesorderid: string;
+ name?: string;
+ totalamount?: number;
+ statuscode?: number;
+ '[email protected]'?: string;
+};
+type ActionResult = { ok: boolean; indeterminate?: boolean; outputs?: Record<string, unknown>; error?: { message: string; code?: string } };
+type ActionApi = {
+ executeAction?: (request: { name: string; parameters?: Record<string, unknown>; boundTo?: { entityName: string; id: string } }) => Promise<ActionResult>;
+};
+
+// Page-scoped window keys (unique per page + query), so the host's double mount shares one read (references/data-caching.md).
+const winAny = window as any;
+const CACHE_KEY = '__ppOrderApprovals_salesorderCache';
+const INFLIGHT_KEY = '__ppOrderApprovals_salesorderInflight';
+
+const useStyles = makeStyles({
+ root: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: tokens.spacingVerticalM,
+ padding: tokens.spacingHorizontalXL,
+ boxSizing: 'border-box',
+ },
+ panel: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: tokens.spacingVerticalS,
+ paddingTop: tokens.spacingVerticalM,
+ },
+});
+
+function PageBody(props: GeneratedComponentProps) {
+ const { dataApi, pageInput } = props;
+ void pageInput;
+ const styles = useStyles();
+ const actionApi = dataApi as unknown as ActionApi;
+ const dataReady = !!dataApi;
+ const [reloadKey, setReloadKey] = React.useState(0);
+ const [{ orders, loading, error }, setData] = React.useState<{ orders: OrderRow[]; loading: boolean; error: PageErrorView | null }>(() => {
+ const cached = winAny[CACHE_KEY] as OrderRow[] | undefined;
+ return { orders: cached ?? [], loading: cached === undefined, error: null };
+ });
+ const [selectedId, setSelectedId] = React.useState<string | null>(null);
+ const [detail, setDetail] = React.useState<{ order: OrderRow | null; loading: boolean; error: PageErrorView | null }>({ order: null, loading: false, error: null });
+ const detailRequest = React.useRef(0);
+ const [note, setNote] = React.useState('');
+ const [approval, setApproval] = React.useState<{ submitting: boolean; status: string; error: PageErrorView | null }>({ submitting: false, status: '', error: null });
+ const pending = React.useRef(false);
+ // The order the approval panel belongs to: its result and its retry are shown only for that order.
+ const approvalFor = React.useRef<string | null>(null);
+
+ function retryLoad() {
+ delete winAny[CACHE_KEY];
+ delete winAny[INFLIGHT_KEY];
+ setData({ orders: [], loading: true, error: null });
+ setReloadKey((key) => key + 1);
+ }
+
+ React.useEffect(() => {
+ if (!dataReady) return;
+ const cached = winAny[CACHE_KEY] as OrderRow[] | undefined;
+ if (cached !== undefined) {
+ if (orders !== cached) setData({ orders: cached, loading: false, error: null });
+ return;
+ }
+ let cancelled = false;
+ let inflight = winAny[INFLIGHT_KEY] as Promise<OrderRow[]> | undefined;
+ if (!inflight) {
+ inflight = dataApi
+ .queryTable('salesorder', { select: ['salesorderid', 'name', 'totalamount', 'statuscode'], orderBy: 'name asc', pageSize: 50 })
+ .then((result: { rows: OrderRow[] }) => {
+ winAny[CACHE_KEY] = result.rows;
+ return result.rows;
+ })
+ .finally(() => { if (winAny[INFLIGHT_KEY] === inflight) delete winAny[INFLIGHT_KEY]; });
+ winAny[INFLIGHT_KEY] = inflight;
+ }
+ inflight
+ .then((rows) => { if (!cancelled) setData({ orders: rows, loading: false, error: null }); })
+ .catch((failure) => { if (!cancelled) setData({ orders: [], loading: false, error: reportPageError(PAGE_NAME, 'loadOrders', undefined, failure, 'read', retryLoad) }); });
+ return () => { cancelled = true; };
+ // Readiness and the reload key only — never dataApi (a new reference on every render).
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [dataReady, reloadKey]);
+
+ function retryDetail() {
+ if (selectedId) void loadOrder(selectedId);
+ }
+
+ async function loadOrder(orderId: string) {
+ const requestId = ++detailRequest.current;
+ setSelectedId(orderId);
+ if (orderId !== approvalFor.current) {
+ // Another order starts a clean approval panel: the previous order's result, and its retry, are cleared.
+ approvalFor.current = orderId;
+ setApproval({ submitting: false, status: '', error: null });
+ setNote('');
+ }
+ setDetail({ order: null, loading: true, error: null });
+ try {
+ const order = await dataApi.retrieveRow('salesorder', { id: orderId, select: ['salesorderid', 'name', 'totalamount', 'statuscode'] });
+ if (requestId !== detailRequest.current) return;
+ setDetail({ order: order as OrderRow, loading: false, error: null });
+ } catch (failure) {
+ if (requestId !== detailRequest.current) return;
+ setDetail({ order: null, loading: false, error: reportPageError(PAGE_NAME, 'loadOrder', undefined, failure, 'read', retryDetail) });
+ }
+ }
+
+ function setApprovalFailure(view: PageErrorView) {
+ setApproval({ submitting: false, status: '', error: view });
+ }
+
+ function retryApprove() {
+ // Re-sends the approval of the order on screen, and only while it is still the one the panel shows.
+ if (selectedId && selectedId === approvalFor.current) void approveOrder(selectedId, note);
+ }
+
+ async function approveOrder(orderId: string, comment: string) {
+ if (typeof actionApi.executeAction !== 'function') return;
+ if (pending.current || !orderId) return;
+ pending.current = true;
+ setApproval({ submitting: true, status: '', error: null });
+ try {
+ const res = await actionApi.executeAction({
+ name: 'cnt_ApproveOrder',
+ parameters: { Comment: comment },
+ boundTo: { entityName: 'salesorder', id: orderId },
+ });
+ if (orderId !== approvalFor.current) return; // another order is on screen: not its answer
+ if (res.indeterminate) { setApprovalFailure(reportPageError(PAGE_NAME, 'approveOrder', res.error?.code, res.error?.message, 'indeterminate')); return; }
+ if (res.error?.code === 'indeterminate') { setApprovalFailure(reportPageError(PAGE_NAME, 'approveOrder', res.error?.code, res.error?.message, 'indeterminate')); return; }
+ if (!res.ok && res.error?.code === 'network') { setApprovalFailure(reportPageError(PAGE_NAME, 'approveOrder', res.error?.code, res.error?.message, 'network', retryApprove)); return; }
+ if (!res.ok) { setApprovalFailure(reportPageError(PAGE_NAME, 'approveOrder', res.error?.code, res.error?.message, 'write')); return; }
+ const newStatus = res.outputs?.NewStatus;
+ setApproval({ submitting: false, status: typeof newStatus === 'string' ? newStatus : '', error: null });
+ } catch (failure) {
+ if (orderId !== approvalFor.current) return;
+ setApprovalFailure(reportPageError(PAGE_NAME, 'approveOrder', undefined, failure, 'write'));
+ } finally {
+ pending.current = false;
+ }
+ }
+
+ const columns = [
+ createTableColumn<OrderRow>({
+ columnId: 'name',
+ renderHeaderCell: () => 'Order',
+ renderCell: (item) => <TableCellLayout>{item.name ?? '—'}</TableCellLayout>,
+ }),
+ createTableColumn<OrderRow>({
+ columnId: 'totalamount',
+ renderHeaderCell: () => 'Total',
+ renderCell: (item) => <TableCellLayout>{item.totalamount ?? '—'}</TableCellLayout>,
+ }),
+ createTableColumn<OrderRow>({
+ columnId: 'statuscode',
+ renderHeaderCell: () => 'Status',
+ renderCell: (item) => <TableCellLayout>{item['[email protected]'] ?? '—'}</TableCellLayout>,
+ }),
+ ];
+
+ return (
+ <div className={styles.root}>
+ <Text as="h1" size={700} weight="semibold">Order Approvals</Text>
+ <PageErrorBar error={error} />
+ {loading ? <Spinner label="Loading orders" /> : (
+ <DataGrid
+ items={orders}
+ columns={columns}
+ getRowId={(row) => row.salesorderid}
+ resizableColumns
+ columnSizingOptions={{
+ name: { defaultWidth: 240, minWidth: 160 },
+ totalamount: { defaultWidth: 140, minWidth: 100 },
+ statuscode: { defaultWidth: 160, minWidth: 120 },
+ }}
+ aria-label="Sales orders"
+ >
+ <DataGridHeader>
+ <DataGridRow>
+ {({ renderHeaderCell }) => <DataGridHeaderCell>{renderHeaderCell()}</DataGridHeaderCell>}
+ </DataGridRow>
+ </DataGridHeader>
+ <DataGridBody<OrderRow>>
+ {({ item }) => (
+ <DataGridRow<OrderRow> key={item.salesorderid}>
+ {({ renderCell, columnId }) => (columnId === 'name' ? (
+ <DataGridCell>
+ <Button appearance="transparent" disabled={approval.submitting} onClick={() => void loadOrder(item.salesorderid)}>{item.name ?? '—'}</Button>
+ </DataGridCell>
+ ) : (
+ <DataGridCell>{renderCell(item)}</DataGridCell>
+ ))}
+ </DataGridRow>
+ )}
+ </DataGridBody>
+ </DataGrid>
+ )}
+ <section className={styles.panel} aria-label="Selected order">
+ <PageErrorBar error={detail.error} />
+ <PageErrorBar error={approval.error} />
+ {detail.loading && <Spinner label="Loading the order" />}
+ {detail.order && (
+ <>
+ <Text weight="semibold">{detail.order.name}</Text>
+ <Text>{detail.order['[email protected]'] ?? ''}</Text>
+ <Field label="Approval note">
+ <Textarea value={note} onChange={(_, data) => setNote(data.value)} />
+ </Field>
+ {approval.status && (
+ <MessageBar intent="success">
+ <MessageBarBody>{`Approved. New status: ${approval.status}.`}</MessageBarBody>
+ </MessageBar>
+ )}
+ <Button
+ appearance="primary"
+ icon={<CheckmarkRegular />}
+ disabled={approval.submitting}
+ onClick={() => void approveOrder(detail.order?.salesorderid ?? '', note)}
+ >
+ Approve order
+ </Button>
+ </>
+ )}
+ </section>
+ </div>
+ );
+}
+
+const GeneratedComponent = (props: GeneratedComponentProps) => (
+ <PageErrorBoundary>
+ <PageBody {...props} />
+ </PageErrorBoundary>
+);
+
+export default GeneratedComponent;
diff --git a/evals/model-apps/genpage/fixtures/27-page-error-helper/page-name.txt b/evals/model-apps/genpage/fixtures/27-page-error-helper/page-name.txt
new file mode 100644
index 000000000..88b9e79f0
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/27-page-error-helper/page-name.txt
@@ -0,0 +1 @@
+Order Approvals
\ No newline at end of file
diff --git a/evals/model-apps/genpage/fixtures/27-page-error-helper/prompt.txt b/evals/model-apps/genpage/fixtures/27-page-error-helper/prompt.txt
new file mode 100644
index 000000000..71776f2a0
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/27-page-error-helper/prompt.txt
@@ -0,0 +1,4 @@
+Build an Order Approvals page for our existing sales orders: list the sales orders, show the one I select, and let me approve it with the existing Approve Order action.
+
+- Data source: Dataverse entity salesorder (already exists)
+- Specific requirements: approve the selected order with the Approve Order action
\ No newline at end of file
diff --git a/evals/model-apps/genpage/fixtures/27-page-error-helper/tool-results.json b/evals/model-apps/genpage/fixtures/27-page-error-helper/tool-results.json
new file mode 100644
index 000000000..3fdec4485
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/27-page-error-helper/tool-results.json
@@ -0,0 +1,381 @@
+[
+ {
+ "id": "manifest",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/generate-page-manifest.js' 'D:/work/order-approvals' 'order-approvals'",
+ "exitCode": 0,
+ "result": {
+ "workingDir": "D:\\work\\order-approvals",
+ "slug": "order-approvals",
+ "features": [],
+ "files": {
+ "package.json": {
+ "wrote": true
+ },
+ "genpage.d.ts": {
+ "wrote": true
+ }
+ }
+ }
+ },
+ {
+ "id": "interaction-mode",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/resolve-interaction-mode.js'",
+ "exitCode": 0,
+ "result": {
+ "ok": true,
+ "interactive": true,
+ "reason": "default (attended)"
+ }
+ },
+ {
+ "id": "node-version",
+ "command": "node --version",
+ "exitCode": 0,
+ "result": "v20.20.2"
+ },
+ {
+ "id": "pac-help",
+ "command": "pac help",
+ "exitCode": 0,
+ "result": "Microsoft PowerPlatform CLI Version: 2.11.0"
+ },
+ {
+ "id": "auth-list",
+ "command": "pac auth list",
+ "exitCode": 0,
+ "result": "Index Active Kind Name Friendly Name User Cloud Type Environment Environment Url\n[1] * UNIVERSAL Contoso [email protected] Public User Contoso https://contoso.crm.dynamics.com/"
+ },
+ {
+ "id": "list-languages",
+ "by": "genpage-planner",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/list-languages.js' --env 'https://contoso.crm.dynamics.com'",
+ "exitCode": 0,
+ "result": {
+ "ok": true,
+ "baseLanguage": {
+ "lcid": 1033,
+ "code": "en-US",
+ "name": "English (United States)",
+ "rtl": false
+ },
+ "languages": [
+ {
+ "lcid": 1033,
+ "code": "en-US",
+ "name": "English (United States)",
+ "rtl": false
+ }
+ ],
+ "unmapped": [],
+ "summary": [
+ "1033 en-US — RTL: No"
+ ]
+ }
+ },
+ {
+ "id": "list-tables",
+ "by": "genpage-planner",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/list-tables.js' --env 'https://contoso.crm.dynamics.com' --search 'salesorder' --exact",
+ "exitCode": 0,
+ "result": {
+ "ok": true,
+ "search": [
+ "salesorder"
+ ],
+ "exact": true,
+ "count": 1,
+ "tables": [
+ {
+ "logicalName": "salesorder",
+ "displayName": "Order",
+ "schemaName": "SalesOrder",
+ "isCustom": false
+ }
+ ],
+ "missing": []
+ }
+ },
+ {
+ "id": "list-apps",
+ "by": "genpage-planner",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/apps.js' list --env 'https://contoso.crm.dynamics.com'",
+ "exitCode": 0,
+ "result": {
+ "ok": true,
+ "count": 2,
+ "apps": [
+ {
+ "id": "11111111-2222-3333-4444-555555555555",
+ "name": "Sales Hub",
+ "uniqueName": "SalesHub",
+ "description": "",
+ "published": true,
+ "unpublishedChanges": false
+ },
+ {
+ "id": "44444444-5555-6666-7777-888888888888",
+ "name": "Customer Service Hub",
+ "uniqueName": "CustomerServiceHub",
+ "description": "",
+ "published": true,
+ "unpublishedChanges": false
+ }
+ ]
+ }
+ },
+ {
+ "id": "planner-discovery",
+ "command": "Task genpage-planner (discovery: create, No connector bindings., No custom API bindings.)",
+ "result": {
+ "action": "custom_api_discovery_required",
+ "intent": "approve the selected sales order with the existing Approve Order action",
+ "resolvedAction": "create",
+ "envUrl": "https://contoso.crm.dynamics.com",
+ "pageTables": "salesorder"
+ }
+ },
+ {
+ "id": "customapi-builder",
+ "command": "Task genpage-customapi-builder (Mode: create, pageTables salesorder)",
+ "result": {
+ "customApiBindings": "custom-api-bindings.md",
+ "actions": "actions.json",
+ "dataverseOperations": "none — not added this run"
+ }
+ },
+ {
+ "id": "builtin-gate",
+ "by": "genpage-customapi-builder",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/lib/feature-flags.js' dataverse-operations",
+ "exitCode": 1,
+ "result": "disabled"
+ },
+ {
+ "id": "custom-api-discovery",
+ "by": "genpage-customapi-builder",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/list-custom-apis.js' 'https://contoso.crm.dynamics.com' --entities 'salesorder'",
+ "exitCode": 0,
+ "result": {
+ "ok": true,
+ "customApis": [
+ {
+ "name": "cnt_ApproveOrder",
+ "displayName": "Approve Order",
+ "isFunction": false,
+ "bindingType": "Entity",
+ "boundEntityLogicalName": "salesorder",
+ "parameterKinds": {
+ "Comment": "String"
+ }
+ }
+ ]
+ }
+ },
+ {
+ "id": "write-bindings",
+ "by": "genpage-customapi-builder",
+ "command": "Write custom-api-bindings.md, actions.json",
+ "artifacts": [
+ "custom-api-bindings.md",
+ "actions.json"
+ ]
+ },
+ {
+ "id": "planner-app",
+ "command": "Task genpage-planner (Custom API Bindings contract: cnt_ApproveOrder; actions.json present)",
+ "result": {
+ "action": "needs_input",
+ "questions": [
+ {
+ "id": "app",
+ "question": "Which app should the page be added to?",
+ "options": [
+ "Sales Hub (11111111-2222-3333-4444-555555555555)",
+ "Customer Service Hub (44444444-5555-6666-7777-888888888888)",
+ "Create a new app"
+ ]
+ }
+ ],
+ "discovered": {
+ "languages": [
+ "English (1033)"
+ ],
+ "existingEntities": [
+ "salesorder"
+ ],
+ "entitiesToCreate": []
+ }
+ }
+ },
+ {
+ "id": "planner-proposal",
+ "command": "Task genpage-planner (answers: create, salesorder, approve with Approve Order, app Sales Hub)",
+ "result": {
+ "action": "plan",
+ "pages": [
+ {
+ "page": "Order Approvals",
+ "file": "order-approvals.tsx",
+ "entities": [
+ "salesorder"
+ ]
+ }
+ ],
+ "assumptions": [
+ "A1",
+ "A2"
+ ],
+ "entityCreationRequired": false,
+ "app": {
+ "name": "Sales Hub",
+ "appId": "11111111-2222-3333-4444-555555555555"
+ }
+ }
+ },
+ {
+ "id": "plan-prepare",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' prepare --plan 'D:/work/order-approvals/genpage-plan.md'",
+ "exitCode": 0,
+ "result": {
+ "ok": true,
+ "action": "prepare",
+ "planPath": "D:\\work\\order-approvals\\genpage-plan.md",
+ "quarantinedPath": null
+ }
+ },
+ {
+ "id": "save-approved",
+ "command": "Write .approved-genpage-plan.md",
+ "artifact": "approved-plan.md"
+ },
+ {
+ "id": "planner-write",
+ "command": "Task genpage-planner (approved: write genpage-plan.md)",
+ "result": {
+ "action": "written",
+ "plan": "D:/work/order-approvals/genpage-plan.md"
+ }
+ },
+ {
+ "id": "plan-verify",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' verify --plan 'D:/work/order-approvals/genpage-plan.md' --approved '@D:/work/order-approvals/.approved-genpage-plan.md' --require-assumptions",
+ "exitCode": 0,
+ "result": {
+ "ok": true,
+ "action": "verify",
+ "planPath": "D:\\work\\order-approvals\\genpage-plan.md",
+ "kind": "create",
+ "targets": [
+ "order-approvals.tsx"
+ ],
+ "writtenHash": "36d395158139cb51e1359e3ba90cc8f21e7ed3b3b3e454289aaa6388353f1310",
+ "semanticsHash": "63d8d19210142a458d55cd6d9181628948d5a3e38cb567807aa0edd7accfd44d"
+ }
+ },
+ {
+ "id": "generate-types",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage.js' types --env 'https://contoso.crm.dynamics.com' --data-sources 'salesorder' --output-file 'D:/work/order-approvals/RuntimeTypes.ts'",
+ "exitCode": 0,
+ "result": {
+ "ok": true,
+ "outputFile": "D:/work/order-approvals/RuntimeTypes.ts",
+ "dataSources": [
+ "salesorder"
+ ],
+ "detail": "none",
+ "bytes": 20480
+ }
+ },
+ {
+ "id": "gate-telemetry",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/lib/feature-flags.js' custom-telemetry",
+ "exitCode": 1,
+ "result": "disabled"
+ },
+ {
+ "id": "page-files",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/check-page-files.js' --plan 'D:/work/order-approvals/genpage-plan.md'",
+ "exitCode": 0,
+ "result": {
+ "ok": true,
+ "workingDir": "D:\\work\\order-approvals",
+ "files": [
+ "order-approvals.tsx"
+ ],
+ "problems": []
+ }
+ },
+ {
+ "id": "plan-verify-5a",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' verify --plan 'D:/work/order-approvals/genpage-plan.md' --approved '@D:/work/order-approvals/.approved-genpage-plan.md' --require-assumptions",
+ "exitCode": 0,
+ "result": {
+ "ok": true,
+ "action": "verify",
+ "planPath": "D:\\work\\order-approvals\\genpage-plan.md",
+ "kind": "create",
+ "targets": [
+ "order-approvals.tsx"
+ ],
+ "writtenHash": "36d395158139cb51e1359e3ba90cc8f21e7ed3b3b3e454289aaa6388353f1310",
+ "semanticsHash": "63d8d19210142a458d55cd6d9181628948d5a3e38cb567807aa0edd7accfd44d"
+ }
+ },
+ {
+ "id": "stamp",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-worker-output.js' --stamp --file 'D:/work/order-approvals/order-approvals.tsx'",
+ "exitCode": 0,
+ "result": {
+ "ok": true,
+ "action": "stamp",
+ "filePath": "D:\\work\\order-approvals\\order-approvals.tsx",
+ "existed": false
+ }
+ },
+ {
+ "id": "write-page",
+ "command": "Write order-approvals.tsx",
+ "artifact": "order-approvals.tsx"
+ },
+ {
+ "id": "icon-grep",
+ "command": "Grep from \"@fluentui/react-icons\" order-approvals.tsx; Grep ^CheckmarkRegular$ references/verified-icons.txt",
+ "result": "CheckmarkRegular: verified"
+ },
+ {
+ "id": "border-grep",
+ "command": "Grep ['\"]?borderWidth['\"]?\\s*: order-approvals.tsx",
+ "result": "no matches"
+ },
+ {
+ "id": "gate",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-worker-output.js' --file 'D:/work/order-approvals/order-approvals.tsx'",
+ "artifact": "order-approvals.tsx",
+ "exitCode": 0,
+ "result": {
+ "ok": true,
+ "filePath": "D:\\work\\order-approvals\\order-approvals.tsx",
+ "problems": []
+ }
+ },
+ {
+ "id": "write-upload-text",
+ "command": "Write prompt.txt, agent-message.txt, page-name.txt",
+ "artifacts": [
+ "prompt.txt",
+ "agent-message.txt",
+ "page-name.txt"
+ ]
+ },
+ {
+ "id": "create",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-upload.js' --env 'https://contoso.crm.dynamics.com' --app-id '11111111-2222-3333-4444-555555555555' --code-file 'order-approvals.tsx' --name-file 'page-name.txt' --data-sources 'salesorder' --actions 'actions.json' --prompt-file 'prompt.txt' --model 'claude-sonnet-4-6' --agent-message-file 'agent-message.txt' --add-to-sitemap",
+ "exitCode": 0,
+ "result": {
+ "ok": true,
+ "pageId": "cccccccc-dddd-eeee-ffff-000000000027",
+ "appId": "11111111-2222-3333-4444-555555555555",
+ "updated": false
+ }
+ }
+]
diff --git a/evals/model-apps/genpage/fixtures/27-page-error-helper/workflow-log.md b/evals/model-apps/genpage/fixtures/27-page-error-helper/workflow-log.md
new file mode 100644
index 000000000..ff5bb3476
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/27-page-error-helper/workflow-log.md
@@ -0,0 +1,148 @@
+# Workflow Log — Eval 27: Order approvals with one error reporter (create flow)
+
+Synthetic trace constructed from the current `/genpage` SKILL.md, not a captured agent run.
+Every command below has an ordered result in `tool-results.json`. Commands run from the
+working directory, so file arguments are relative to it.
+
+## Phase 0 — Working directory
+- `$ARGUMENTS`: "Build an Order Approvals page for our existing sales orders."
+- Working directory created: `mkdir -p 'order-approvals'` (kebab-case from "Order Approvals")
+- Resolved working directory: D:/work/order-approvals
+- Plugin root: D:/repo/plugins/model-apps
+
+## Phase 0.5 — Local-dev manifest
+- Command: `node 'D:/repo/plugins/model-apps/scripts/generate-page-manifest.js' 'D:/work/order-approvals' 'order-approvals'`
+- Result: exit 0; package.json and genpage.d.ts written; no `--features` (no charts or date/time pickers needed)
+
+## Phase 1 — Plan
+
+### Interaction mode
+- Command: `node 'D:/repo/plugins/model-apps/scripts/resolve-interaction-mode.js'`
+- Result: `{"ok":true,"interactive":true,"reason":"default (attended)"}` — attended run, every gate asked in this loop
+
+### Prereq checks (run separately, not chained)
+- `node --version` → v20.20.2
+- `pac help` → Microsoft PowerPlatform CLI Version: 2.11.0 (> 2.10.0 verified)
+
+### Auth
+- `pac auth list` → one profile, currently active: [email protected]
+- Active environment reported to the user: https://contoso.crm.dynamics.com/
+
+### Create or edit
+- AskUserQuestion: Do you want to create new page(s) or edit an existing page? → Create new page(s)
+
+### Requirements
+- AskUserQuestion: Where should the page get its data? → Dataverse entity: salesorder
+- AskUserQuestion: Any specific requirements for the page? → Approve the selected order with the Approve Order action
+
+### Discovery (genpage-planner dispatched via Task as a headless worker)
+- Dispatched `Task genpage-planner` with the requirements, working directory, plugin root, create/edit decision = create, `No connector bindings.` (connectors.json: none — omit --connectors) and `No custom API bindings.` (discovery has not run)
+- Planner ran `node 'D:/repo/plugins/model-apps/scripts/list-languages.js' --env 'https://contoso.crm.dynamics.com'` → English (1033) only, no RTL language
+- Planner ran `node 'D:/repo/plugins/model-apps/scripts/list-tables.js' --env 'https://contoso.crm.dynamics.com' --search 'salesorder' --exact` → 1 table: `salesorder` (exact logical-name match, nothing in `missing`); no entity creation
+- Planner ran `node 'D:/repo/plugins/model-apps/scripts/apps.js' list --env 'https://contoso.crm.dynamics.com'` → 2 apps: Sales Hub (11111111-2222-3333-4444-555555555555), Customer Service Hub (44444444-5555-6666-7777-888888888888)
+- Planner returned `{ "action": "custom_api_discovery_required", "resolvedAction": "create", "pageTables": "salesorder" }`: the request names an existing Approve Order action
+
+### Custom API discovery (genpage-customapi-builder, Mode: create)
+- Dispatched `Task genpage-customapi-builder` with Mode: create, https://contoso.crm.dynamics.com, page tables salesorder, the working directory and the plugin root
+- Builder ran `node 'D:/repo/plugins/model-apps/scripts/lib/feature-flags.js' dataverse-operations` → disabled (no built-in operation is offered)
+- Builder ran `node 'D:/repo/plugins/model-apps/scripts/list-custom-apis.js' 'https://contoso.crm.dynamics.com' --entities 'salesorder'` → cnt_ApproveOrder (Action, bound to salesorder, Comment: String)
+- Builder wrote custom-api-bindings.md (one binding row) and actions.json (a bare array holding that row)
+- Read custom-api-bindings.md; actions.json is a bare JSON array
+
+### Planning with the binding
+- Re-invoked `Task genpage-planner` with the `## Custom API Bindings` contract and the actions.json status; it returned `{ "action": "needs_input" }` for the app choice
+- AskUserQuestion: Which app should the page be added to? (options from `apps.js list`: Sales Hub — 11111111-2222-3333-4444-555555555555; Customer Service Hub — 44444444-5555-6666-7777-888888888888; Create a new app) → Sales Hub (existing app)
+- Data semantics (planner Step 4, "Resolve Data Semantics"): the request asks for the sales orders with no restriction and uses no lookup, so no question was needed; the planner recorded two planner defaults (A1 — no added restriction, name order, 50 rows; A2 — initial-load caching)
+
+### Solution selection
+- Code-only build (no new entities, existing app) → solution selection question SKIPPED
+- Defaults written to the plan: `Solution: Default`, `Publisher Prefix: new`
+
+### Plan approval
+- Re-invoked `Task genpage-planner` with every answer gathered so far; it returned the proposed plan (1 page: Order Approvals on salesorder), its `### Assumptions` first
+- EnterPlanMode called — presented the proposed plan, Assumptions A1 and A2 first, then the page list, Data Semantics (None.) and Lookup Metadata (None.)
+- ExitPlanMode → user approved the plan without changes
+- Command: `node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' prepare --plan 'D:/work/order-approvals/genpage-plan.md'`
+- Result: `"ok":true`, nothing to quarantine (first run in this folder)
+- Saved the approved plan body verbatim to D:/work/order-approvals/.approved-genpage-plan.md (kept here as approved-plan.md)
+- Re-invoked `Task genpage-planner` with the approval outcome, the approved plan body and all prior discovery; it wrote genpage-plan.md (conforms to references/plan-schema.md, with the same Assumptions and per-page records)
+- Command: `node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' verify --plan 'D:/work/order-approvals/genpage-plan.md' --approved '@D:/work/order-approvals/.approved-genpage-plan.md' --require-assumptions`
+- Result: `"ok":true`, kind create, targets [order-approvals.tsx], writtenHash 36d395158139cb51e1359e3ba90cc8f21e7ed3b3b3e454289aaa6388353f1310, semanticsHash 63d8d19210142a458d55cd6d9181628948d5a3e38cb567807aa0edd7accfd44d
+
+## Phase 2 — Entities
+- SKIPPED: `## Entity Creation Required` is the no-entity sentinel (salesorder exists)
+- check-auth.js and genpage-entity-builder were not invoked (no metadata work)
+- Phase 2c SKIPPED: the plan records no lookup
+
+## Phase 3 — App
+- SKIPPED app creation: existing app Sales Hub (11111111-2222-3333-4444-555555555555) selected
+
+## Phase 4 — RuntimeTypes
+- `node 'D:/repo/plugins/model-apps/scripts/genpage.js' types --env 'https://contoso.crm.dynamics.com' --data-sources 'salesorder' --output-file 'D:/work/order-approvals/RuntimeTypes.ts'`
+- Read RuntimeTypes.ts: verified salesorderid, name, totalamount and statuscode
+
+## Phase 4.5 — Connector bindings
+- SKIPPED: plan says `No connector bindings.` → Connectors: none; no connectors.json, no `--connectors`
+
+## Phase 4.6 — Custom API bindings
+- The plan's `## Custom API Bindings` table has one row, cnt_ApproveOrder; the Custom API rows of actions.json match it (name, Action, salesorder, Comment: String)
+
+## Phase 4.6b — Built-in Dataverse operations
+- SKIPPED: the plan has no `## Dataverse Operations` section
+
+## Phase 4.6c — The actions file
+- actions.json is not empty: the create passes `--actions 'D:/work/order-approvals/actions.json'`
+
+## Phase 4.7 — Page telemetry
+- Command: `node 'D:/repo/plugins/model-apps/scripts/lib/feature-flags.js' custom-telemetry`
+- Result: `disabled` → Telemetry: disabled; the page contains no telemetry calls
+
+## Phase 5a — Plan validation
+- One page row with a matching `### Order Approvals` subsection
+- Command: `node 'D:/repo/plugins/model-apps/scripts/check-page-files.js' --plan 'D:/work/order-approvals/genpage-plan.md'`
+- Result: `"ok":true` — order-approvals.tsx is a safe, unique page file
+- The plan's records are complete: Assumptions A1 and A2; Data semantics and Lookup metadata are `None.`
+- Command: `node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' verify --plan 'D:/work/order-approvals/genpage-plan.md' --approved '@D:/work/order-approvals/.approved-genpage-plan.md' --require-assumptions`
+- Result: `"ok":true`, semanticsHash 63d8d19210142a458d55cd6d9181628948d5a3e38cb567807aa0edd7accfd44d (unchanged since approval)
+
+## Phase 5b — Single-page fast path
+- Plan has 1 page → inlined the page-builder workflow (no Task dispatch for the page)
+- Data mode: dataverse; Connectors: none; Telemetry: disabled
+- Read D:/repo/plugins/model-apps/references/rules.md, including Critical Rule 22 and "Missing Error Handling"
+- Read samples 9-list-with-caching.tsx and 13-custom-api-invocation.tsx (from `## Relevant Samples`)
+- Needs caching: true → read references/data-caching.md
+- Custom API binding table → read references/custom-api.md
+- Languages: English only → localization.md not needed
+- Read genpage-plan.md and RuntimeTypes.ts
+- Command: `node 'D:/repo/plugins/model-apps/scripts/genpage-worker-output.js' --stamp --file 'D:/work/order-approvals/order-approvals.tsx'`
+- Result: `"ok":true`, stamp recorded, no earlier file at the target
+- Wrote order-approvals.tsx with the file tool: the page error block of rules.md copied unchanged, PageBody inside PageErrorBoundary; the list read through the window cache and in-flight de-dupe, its rejection reported from the consumer's catch with a retry; the selected order read awaited in a try with a stale-request guard; the Approve Order Action with a double-submit latch, both indeterminate checks before the network check before any other failure, and a rejection reported as a write; the approval belongs to the selected order — another order cannot be selected while it runs, and selecting another order clears its result and its retry
+- Icon verification: Grep for `from "@fluentui/react-icons"` → one named import, CheckmarkRegular; Grep of references/verified-icons.txt for `^CheckmarkRegular$` → present
+- Grep `['"]?borderWidth['"]?\s*:` → no matches
+- Command: `node 'D:/repo/plugins/model-apps/scripts/genpage-worker-output.js' --file 'D:/work/order-approvals/order-approvals.tsx'`
+- Result: `"ok":true`, problems [] — complete page accepted
+
+## Phase 6 — Deploy
+- Checked prompt.txt, agent-message.txt and page-name.txt in the working directory: none existed, none is a link
+- Wrote prompt.txt (the full `## User Requirements` body), agent-message.txt and page-name.txt ("Order Approvals") with the file tool
+- Command: `node 'D:/repo/plugins/model-apps/scripts/genpage-upload.js' --env 'https://contoso.crm.dynamics.com' --app-id '11111111-2222-3333-4444-555555555555' --code-file 'order-approvals.tsx' --name-file 'page-name.txt' --data-sources 'salesorder' --actions 'actions.json' --prompt-file 'prompt.txt' --model 'claude-sonnet-4-6' --agent-message-file 'agent-message.txt' --add-to-sitemap`
+- Prompt scope: full page description from the plan's `## User Requirements` (create)
+- Result: page-id = cccccccc-dddd-eeee-ffff-000000000027, status = success (`updated: false`, added to the Sales Hub sitemap)
+
+## Phase 6.5 — Navigation fix-up
+- SKIPPED: single page, no PAGEREF_ placeholders
+
+## Phase 7 — Verify in browser
+- AskUserQuestion: Would you like to verify the page(s) in the browser using Playwright? → Skip verification
+
+## Phase 8 — Summary
+
+| Page | File | Entities | Status |
+|------|------|----------|--------|
+| Order Approvals | order-approvals.tsx | salesorder | Deployed |
+
+- App: Sales Hub (11111111-2222-3333-4444-555555555555)
+- Page ID: cccccccc-dddd-eeee-ffff-000000000027
+- Entities created: none
+- Custom API bindings: cnt_ApproveOrder
+- Browser verification: skipped
diff --git a/evals/model-apps/genpage/fixtures/README.md b/evals/model-apps/genpage/fixtures/README.md
index fb98c69c7..767165af8 100644
--- a/evals/model-apps/genpage/fixtures/README.md
+++ b/evals/model-apps/genpage/fixtures/README.md
@@ -35,6 +35,13 @@ digits are parsed as the eval id; the slug is purely cosmetic.
- A current synthetic `fixture.json` declares contract version 2, provenance,
source skill/reference sections, ordered `tool-results.json` and artifact paths.
Nested snapshots are evidence, not additional generated pages.
+- A scenario that grades a newly authored plan names its evidence under
+ `fixture.json` `semantics` (each also listed in `artifacts`): `approvedPlan` (the
+ approved preview the run saved), and for eval 26 `lookupMetadata` (the saved
+ `get-lookup-metadata.js` answer), `interactions` (the ordered `needs_input`,
+ answer and approval of its semantic question) and `lookupRows` (synthetic lookup
+ values with the state the published normalizer gives each). Its expectations fail
+ — they do not skip — when a declared key or its file is missing.
## How to capture a real fixture from /genpage
@@ -90,7 +97,7 @@ Two rules for evidence files:
## Current state
-This directory has **33 fixtures, 37 top-level TSX files and 25 represented
+This directory has **35 fixtures, 39 top-level TSX files and 27 represented
prompt IDs**. All are green under both runners. Directories listed in
`contracts.json` are historical contract-1 evidence; every other directory is a
current contract-2 synthetic. Registered prompts with no fixture:
@@ -133,6 +140,8 @@ of step with the fixtures.
| `16-account-list/` | 16 | Current synthetic | green | Minimal single list page over an existing table; code-only, no solution question or auth gate |
| `1-account-cards-verified-columns/` | 1 | Current synthetic | green | Account card gallery over an existing table; keeps the RuntimeTypes.ts it was written against, so every column its dataApi call names is checked against the schema |
| `7-job-candidates-verified-columns/` | 7 | Current synthetic | green | Two new related tables (cr_jobrequisition, cr_candidate with a lookup and a status choice), auth gate, dependency-ordered provisioning, `$parent`/match sample data; keeps the RuntimeTypes.ts it generated, so the page's columns are checked against the schema |
+| `26-customer-lookup/` | 26 | Current synthetic | green | An opportunity's Customer (account or contact) normalized to its own table before it is opened, filtered by or written (the page's lookup code is not graded); the account-scope question asked with no default and its answer recorded as a user-confirmed assumption before approval; the lookup records built from the saved `get-lookup-metadata.js` read, typed in RuntimeTypes.ts and gated with `--require-observed-lookups`; synthetic customer values in `lookup-rows.json` |
+| `27-page-error-helper/` | 27 | Current synthetic | green | A newly authored plan with its assumptions, verified against the approved preview with `--require-assumptions`; its page follows the page error teaching — a cached list read, an awaited record read and a Custom API Action reporting through the canonical reporter inside the boundary — which is not graded |
Historical captures remain compatibility/parser evidence, not proof of today's
file transport, binding preservation or full skill compliance. Their current
diff --git a/evals/model-apps/genpage/lib/action-binding-union.js b/evals/model-apps/genpage/lib/action-binding-union.js
new file mode 100644
index 000000000..cb5b858b0
--- /dev/null
+++ b/evals/model-apps/genpage/lib/action-binding-union.js
@@ -0,0 +1,576 @@
+'use strict';
+// The union of a page's two kinds of `actionBindings` entry, as the evaluators of a Custom API lifecycle compare an `actions.json`, a plan and a page's config.
+//
+// A page holds ONE `actionBindings` array, written whole by `genpage-upload.js --actions` (a full replace: an entry the file leaves out is deleted), and genpage-customapi-builder is
+// its one writer. It holds two partitions:
+// - Custom API rows, from the plan's `## Custom API Bindings` and `list-custom-apis.js` discovery (custom-api-contract.js);
+// - the reviewed built-in Dataverse operations — exactly WhoAmI and RetrieveVersion (plugins/model-apps/scripts/lib/dataverse-operations.js) — from the plan's OPTIONAL
+// `## Dataverse Operations` section and `list-dataverse-operations.js` (this file).
+// A desired array is the Custom API rows first, in their own order, then the built-in projections in catalogue order. Comparing a mixed array with the Custom API partition alone fails
+// it, and passing it by dropping either partition would hide a binding the upload is about to delete — so what is compared is always the whole union.
+//
+// The section, when present, is the exact sentinel `No Dataverse operations.` or the table below — anything else halts:
+// ## Dataverse Operations
+// Verification: environment not-checked, runtime not-checked, privileges not-checked.
+// | Name | Kind | Bound Entity | Display Name | Parameters | Response fields | Invoke |
+// |------|------|--------------|--------------|------------|-----------------|--------|
+// | WhoAmI | Function | (Global) | Current Dataverse identity | (none) | BusinessUnitId, UserId, OrganizationId | button |
+// Every cell is the catalogue's own, so a row is checked against the catalogue and projected by it (toActionBinding), never re-derived from the text.
+const { isDeepStrictEqual } = require('node:util');
+const {
+ AUTHORING_CODES, getDataverseOperationCatalogue, getReviewedDataverseOperation, toActionBinding,
+} = require('../../../../plugins/model-apps/scripts/lib/dataverse-operations.js');
+const { planSection, parseMarkdownRows } = require('./plan-evidence.js');
+const { isGeneration, isUpload, resultObject } = require('./workflow-evidence.js');
+const { uploadChoiceLines, consumedChoice } = require('./upload-contract.js');
+const { actionCalls, groupEnd, literalString, escapeRe, callSites, expressionEnd, forwardedPageBodyOf } = require('./source-evidence.js');
+const { blankNonCodePreservingTemplateExpressions } = require('../../../../plugins/model-apps/scripts/lib/source-literals.js');
+
+const SECTION = 'Dataverse Operations';
+const SENTINEL = 'No Dataverse operations.';
+const VERIFICATION_LINE = 'Verification: environment not-checked, runtime not-checked, privileges not-checked.';
+const COLUMNS = ['Name', 'Kind', 'Bound Entity', 'Display Name', 'Parameters', 'Response fields', 'Invoke'];
+const CATALOGUE_ORDER = getDataverseOperationCatalogue().operations.map((operation) => operation.name);
+
+// The output names each built-in operation's response declares — what a page may read from `res.outputs` of that call.
+const BUILT_IN_OUTPUTS = Object.freeze(Object.fromEntries(getDataverseOperationCatalogue().operations.map((operation) => [operation.name, Object.keys(operation.response.properties)])));
+
+// An entry that names a built-in operation, by its EXACT name (as the catalogue matches it: `whoami` is a Custom API name).
+const isBuiltInBinding = (entry) => Boolean(entry && typeof entry === 'object' && getReviewedDataverseOperation(entry.name));
+
+const isBuiltInGate = (command) => /\bfeature-flags\.js\b[^\n]*\bdataverse-operations\b/.test(command);
+const isBuiltInListing = (command) => /\blist-dataverse-operations\.js\b/.test(command);
+const gateValue = (call) => {
+ const raw = typeof call.result === 'string' ? call.result.trim() : '';
+ return raw === 'enabled' || raw === 'disabled' ? raw : null;
+};
+
+// { customApis, builtIns } of a list, each in the list's own order.
+function partitionBindings(list) {
+ const customApis = [];
+ const builtIns = [];
+ for (const entry of list || []) (isBuiltInBinding(entry) ? builtIns : customApis).push(entry);
+ return { customApis, builtIns };
+}
+
+// The built-in rows a plan authors this run: null when the plan has no `## Dataverse Operations` section (nothing new is authored), [] for the exact sentinel, otherwise the wire rows of
+// its table, in catalogue order. A section that is anything else throws: an evaluator must not read an unreadable selection as "none".
+function plannedBuiltIns(plan) {
+ const body = planSection(plan, SECTION);
+ if (body === null) return null;
+ if (body === SENTINEL) return [];
+ if (body.split(/\r?\n/)[0].trim() !== VERIFICATION_LINE) throw new Error('Dataverse Operations must open with the not-checked verification line or be the exact sentinel');
+ const rows = parseMarkdownRows(body, COLUMNS);
+ if (!rows.length) throw new Error('Dataverse Operations must be the built-in operation table or the exact sentinel');
+ const seen = new Set();
+ const out = rows.map((row) => {
+ const operation = getReviewedDataverseOperation(row.name);
+ if (!operation) throw new Error(AUTHORING_CODES.not_in_catalogue);
+ if (seen.has(operation.name)) throw new Error(AUTHORING_CODES.duplicate_operation);
+ seen.add(operation.name);
+ const expected = {
+ kind: 'Function', 'bound entity': '(Global)', 'display name': operation.displayName, parameters: '(none)',
+ 'response fields': Object.keys(operation.response.properties).join(', '), invoke: 'button',
+ };
+ for (const [cell, value] of Object.entries(expected)) {
+ if (row[cell] !== value) throw new Error(`${operation.name}: the ${cell} cell is not the catalogue's (${AUTHORING_CODES.invalid_operation_contract})`);
+ }
+ return toActionBinding(operation);
+ });
+ const order = out.map((entry) => CATALOGUE_ORDER.indexOf(entry.name));
+ if (order.some((at, i) => i > 0 && at < order[i - 1])) throw new Error('Dataverse Operations rows must be in catalogue order (WhoAmI, then RetrieveVersion)');
+ return out;
+}
+
+// The one desired array: the Custom API rows, then the built-in rows. A name in both, or twice, is no union at all.
+function unionBindings(customApis, builtIns) {
+ const names = new Set();
+ for (const entry of [...customApis, ...builtIns]) {
+ if (names.has(entry.name)) throw new Error(AUTHORING_CODES.duplicate_operation);
+ names.add(entry.name);
+ }
+ return [...customApis, ...builtIns];
+}
+
+// What `list-dataverse-operations.js` offered, by name: the wire projection of each descriptor it listed. A listing that failed, or listed anything but the reviewed pair exactly, offers
+// nothing, and is a problem: an evaluator never projects a row from an altered descriptor (toActionBinding refuses one).
+function listedBuiltIns(calls) {
+ const offered = new Map();
+ const problems = [];
+ for (const call of calls.filter((entry) => isBuiltInListing(entry.command))) {
+ const result = resultObject(call);
+ if (result?.ok !== true || !Array.isArray(result.operations)) {
+ problems.push('built-in operation listing failed or returned an unreadable catalogue');
+ continue;
+ }
+ // Exactly the documented envelope: a field such as `eligible` would claim a check the command does not make.
+ const { ok, catalogueVersion, verification, operations, ...rest } = result;
+ if (ok !== true || catalogueVersion !== 1 || Object.keys(rest).length || verification?.mode !== 'catalogue-only'
+ || ['environment', 'runtime', 'privileges'].some((key) => verification[key] !== 'not-checked')) {
+ problems.push('built-in operation listing claims more than a catalogue-only offer');
+ continue;
+ }
+ if (!isDeepStrictEqual(operations.map((operation) => operation && operation.name), CATALOGUE_ORDER)) {
+ problems.push('built-in operation listing is not exactly the reviewed pair');
+ continue;
+ }
+ for (const operation of operations) {
+ // toActionBinding accepts a listed descriptor only when it is structurally the catalogue's own.
+ try {
+ offered.set(operation.name, toActionBinding(operation));
+ } catch (error) {
+ problems.push(`${operation.name}: listed descriptor is not the reviewed contract (${error.code})`);
+ }
+ }
+ }
+ return { offered, problems };
+}
+
+// The order a NEW actions file keeps: every Custom API row before the first built-in row, and the built-ins in catalogue order.
+function unionOrderProblems(list, label) {
+ const problems = [];
+ const kinds = (list || []).map(isBuiltInBinding);
+ const firstBuiltIn = kinds.indexOf(true);
+ if (firstBuiltIn !== -1 && kinds.slice(firstBuiltIn).includes(false)) problems.push(`${label}: built-in operation rows must follow every Custom API row`);
+ const order = (list || []).filter(isBuiltInBinding).map((entry) => CATALOGUE_ORDER.indexOf(entry.name));
+ if (order.some((at, i) => i > 0 && at <= order[i - 1])) problems.push(`${label}: built-in operation rows must be in catalogue order, each once`);
+ return problems;
+}
+
+// The gate of built-in authoring: `list-dataverse-operations.js` runs only after an ENABLED `dataverse-operations` probe, and a stage that authors a built-in row (`authoring`: the
+// upload ids of the stages that add or replace one) generates and uploads only after a re-probe that is enabled and comes after the listing. A stage that only preserves the rows a page
+// already holds does not consult this gate (a page keeps its bindings whatever the flag says).
+function builtInGateProblems(calls, authoring) {
+ const problems = [];
+ let latest = null;
+ for (const call of calls) {
+ if (isBuiltInGate(call.command)) latest = gateValue(call);
+ else if (isBuiltInListing(call.command) && latest !== 'enabled') problems.push('built-in operation listing ran before an enabled dataverse-operations gate');
+ }
+ const lastBefore = (end, predicate) => {
+ for (let index = end - 1; index >= 0; index -= 1) if (predicate(calls[index].command)) return index;
+ return -1;
+ };
+ for (const uploadId of authoring) {
+ const uploadIndex = calls.findIndex((call) => call.id === uploadId && isUpload(call.command));
+ if (uploadIndex === -1) continue;
+ const gate = lastBefore(uploadIndex, isBuiltInGate);
+ const listing = lastBefore(uploadIndex, isBuiltInListing);
+ const generation = lastBefore(uploadIndex, isGeneration);
+ if (listing === -1) problems.push(`${uploadId}: built-in operation rows were authored without a listing that offered them`);
+ if (gate === -1 || gateValue(calls[gate]) !== 'enabled') problems.push(`${uploadId}: a disabled or unreadable dataverse-operations gate must halt built-in authoring before generation or upload`);
+ else if (gate < listing) problems.push(`${uploadId}: built-in authoring must re-probe the dataverse-operations gate after the listing`);
+ else if (generation !== -1 && gate > generation) problems.push(`${uploadId}: the dataverse-operations re-probe must come before generation`);
+ }
+ return problems;
+}
+
+// A clear (`change: { clear: true }`, an upload of `[]`) empties the WHOLE array. On a page whose before-config holds a built-in row, removing the
+// Custom APIs is not that — it keeps the built-in rows — so a clear needs the maker's clear choice (edit-flow.md, Edit Phase 6), recorded as its
+// own workflow-log line right before the upload it covers:
+// Clear choice: Clear every action binding of page <page-id>, removing WhoAmI and RetrieveVersion
+// <page-id> is that upload's `--page-id` (any case), and the names are exactly the built-ins the page holds, in catalogue order. It is read the
+// way an overwrite choice is (upload-contract.js): a `Clear choice:` line sets the pending answer, a later one replaces it, and the next log line
+// that carries an upload command consumes it. So the answer that counts is the last one before this upload's own log line, it covers that one
+// upload (a retry needs it again), and a choice logged after the upload, for another page, for another set of built-ins, or with anything
+// added to it is no permission. AskUserQuestion exchanges are not read at all: a yes to adding or keeping WhoAmI never authorizes deleting it.
+const CLEAR_CHOICE = 'Clear choice:';
+function clearConfirmationProblems({ workflowLog, uploads, call, pageId, before, label }) {
+ const held = new Set(partitionBindings(before).builtIns.map((entry) => entry.name));
+ if (!held.size) return [];
+ const removed = CATALOGUE_ORDER.filter((name) => held.has(name)).join(' and ');
+ const expected = `${CLEAR_CHOICE} Clear every action binding of page ${pageId}, removing ${removed}`;
+ // Every upload consumes its own log entry, in order, so an entry an earlier upload used can never be reached by this one.
+ const entries = uploadChoiceLines(workflowLog, CLEAR_CHOICE);
+ let consumed = null;
+ for (const upload of uploads) {
+ const choice = consumedChoice(entries, upload.command);
+ if (upload === call) {
+ consumed = choice;
+ break;
+ }
+ }
+ const choice = /^Clear choice: Clear every action binding of page (\S+), removing (.+)$/.exec(consumed || '');
+ const accepted = Boolean(choice) && typeof pageId === 'string' && choice[1].toLowerCase() === pageId.toLowerCase() && choice[2] === removed;
+ return accepted ? [] : [`${label}: clearing every action binding removes ${removed.replace(' and ', ', ')} — only with the maker's clear choice recorded right before this upload: ${expected}`];
+}
+
+// ── The generated call of a NEWLY authored built-in operation (references/dataverse-operations.md, "Generated call") ─────────────────────────────
+// The page source is read, never run (source-evidence.js). A call is held to what the reference requires of it, beside the order every action call
+// keeps (custom-api-contract.js runtimeProblems: presence check on the page's dataApi, failure returned before `res.outputs` is read, sanitized
+// error.message only):
+// - the request is exactly `{ name: 'WhoAmI' }` / `{ name: 'RetrieveVersion' }`, and a presence check that fails RETURNS: no request at all;
+// - the call is user-triggered: its helper is reached only from a button's onClick, through named handlers (or constants that name them) —
+// never from an effect, a memo, a timer or the render itself, never handed to one (`setTimeout(showIdentity, 0)`), a ref or a child, and
+// never by calling itself again;
+// - the button that triggers it is disabled while its call is pending, a separate state per operation; its handler ignores a stale request (a
+// `.current` counter it increments and compares after the await) and catches a rejected promise;
+// - outputs are read only after a non-null, non-array object check, through own-property reads, never from the result root, by a literal member,
+// by a spread, an iteration or JSON.stringify, and nothing of the result is logged, stored, copied, put in a URL or sent — not by the helper or
+// its handlers, and not from the state, ref or variable that keeps it, anywhere on the page (a render, an effect, another handler);
+// - WhoAmI shows all three identifiers or none: one guard that returns tests every one of them with the GUID pattern; RetrieveVersion shows a
+// Version of 1 to 128 characters or nothing; an unexpected shape says the fixed sentence;
+// - a status is never read out of the message's words, and nothing says to deploy a Custom API.
+const GUID_SOURCE = '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$';
+const UNEXPECTED = 'The operation returned an unexpected response. No result was displayed.';
+const UNAVAILABLE = 'The selected operation is unavailable in this environment or player. No fallback was attempted.';
+const IDENTITY_FIELDS = ['UserId', 'BusinessUnitId', 'OrganizationId'];
+const DTO = 'BusinessUnitId|UserId|OrganizationId|Version';
+// What a page must never do with an operation's result: log it, keep it, copy it, put it in a URL, hash it or send it anywhere. LEAKS finds one in
+// a text; SINKS finds each one of a page.
+const LEAK_SOURCE = String.raw`\bconsole\s*\.|\blocalStorage\b|\bsessionStorage\b|\bindexedDB\b|\bclipboard\b|\bappInsights\b|\.track(?:Event|Metric|Trace|Exception|Dependency|PageView)\s*\(|\bURLSearchParams\b|\bhistory\s*\.\s*(?:push|replace)State\b|\blocation\s*\.\s*(?:assign|replace)\s*\(|\blocation\s*\.\s*(?:href|search|hash)\s*=(?!=)|\bwindow\s*\.\s*open\s*\(|\bdocument\s*\.\s*cookie\b|\bfetch\s*\(|\bsendBeacon\b|\bXMLHttpRequest\b|\bWebSocket\b|\bpostMessage\s*\(|\bcrypto\s*\.\s*subtle\b`;
+const LEAKS = new RegExp(LEAK_SOURCE);
+const SINKS = new RegExp(LEAK_SOURCE, 'g');
+// Where a call is not a user's: an effect, a memo, a timer, a frame or a microtask (a hook's type argument list, `useMemo<string>(…)`, included).
+const NOT_A_USER = /\b(?:useEffect|useLayoutEffect|useInsertionEffect|useMemo|setTimeout|setInterval|requestAnimationFrame|queueMicrotask)\s*(?:<(?:[^<>()]|<[^<>()]*>)*>\s*)?\(/g;
+
+// The `if (…)` guards of a text that end in a return: [{ condition }], the condition as raw text.
+function returningGuards(text, mask) {
+ const guards = [];
+ for (const match of mask.matchAll(/\bif\s*\(/g)) {
+ const open = match.index + match[0].length - 1;
+ let close;
+ try { close = groupEnd(mask, open); } catch { continue; }
+ if (/^\s*(?:return\b|\{[^}]*\breturn\b)/.test(mask.slice(close + 1))) guards.push({ condition: text.slice(open + 1, close) });
+ }
+ return guards;
+}
+
+// The declarations a call can sit in: named functions and constants initialized with a function (an arrow, `function`, or a hook that wraps one).
+function functionDeclarations(mask) {
+ const out = [];
+ for (const match of mask.matchAll(/\b(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(/g)) {
+ try {
+ const paramsEnd = groupEnd(mask, match.index + match[0].length - 1);
+ const body = mask.indexOf('{', paramsEnd);
+ if (body !== -1) out.push({ name: match[1], start: match.index, end: groupEnd(mask, body) });
+ } catch { /* not gradeable here; actionCalls refuses it */ }
+ }
+ for (const match of mask.matchAll(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;]+)?=(?!=)\s*/g)) {
+ const start = match.index + match[0].length;
+ let end;
+ try { end = expressionEnd(mask, start); } catch { continue; }
+ if (/=>|^\s*(?:async\s+)?function\b/.test(mask.slice(start, end))) out.push({ name: match[1], start: match.index, end });
+ }
+ return out;
+}
+
+// The constants initialized with something other than a function — `const run = showIdentity;`, `const onIdentity = useCallback(showIdentity, [])`.
+// [{ name, init, end }], `init` where the initializer starts. Which of them only rename a function is decided where a mention is read (aliasAt).
+function aliasDeclarations(mask) {
+ const out = [];
+ for (const match of mask.matchAll(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;]+)?=(?!=)\s*/g)) {
+ const init = match.index + match[0].length;
+ let end;
+ try { end = expressionEnd(mask, init); } catch { continue; }
+ if (!/=>|^\s*(?:async\s+)?function\b/.test(mask.slice(init, end))) out.push({ name: match[1], init, end });
+ }
+ return out;
+}
+
+// Every place a function is named without being called: `setTimeout(fn, 0)`, `onClick={fn}`, `ref={fn}`, `const run = fn`. Not a call `fn(…)`
+// (callSites follows those), not its own declaration, not a member (`x.fn`) and not an object key (`{ fn: … }`).
+function mentions(mask, name) {
+ const out = [];
+ for (const match of mask.matchAll(new RegExp(`(?<![\\w$.])${escapeRe(name)}(?![\\w$])`, 'g'))) {
+ const before = mask.slice(Math.max(0, match.index - 40), match.index);
+ const after = mask.slice(match.index + name.length);
+ if (/^\s*\(/.test(after)) continue;
+ if (/\b(?:function\s*\*?|const|let|var)\s*$/.test(before)) continue;
+ if (/^\s*:(?!:)/.test(after) && /[{,]\s*$/.test(before)) continue;
+ out.push(match.index);
+ }
+ return out;
+}
+
+// The dependency list of a hook — the `[a, b]` of `useEffect(fn, [a, b])`: naming a function there calls nothing. [[open, close]] of each list.
+function dependencyLists(mask) {
+ const out = [];
+ for (const match of mask.matchAll(/\buse(?:Effect|LayoutEffect|InsertionEffect|Memo|Callback)\s*(?:<(?:[^<>()]|<[^<>()]*>)*>\s*)?\(/g)) {
+ const open = match.index + match[0].length - 1;
+ try {
+ const close = groupEnd(mask, open);
+ let comma = -1;
+ for (let i = open + 1; i < close && comma === -1; i += 1) {
+ if ('({['.includes(mask[i])) i = groupEnd(mask, i);
+ else if (mask[i] === ',') comma = i;
+ }
+ if (comma === -1) continue;
+ const start = comma + 1 + mask.slice(comma + 1, close).search(/\S/);
+ if (mask[start] === '[') out.push([start, groupEnd(mask, start)]);
+ } catch { /* not gradeable here; actionCalls refuses it */ }
+ }
+ return out;
+}
+
+// The `{ … }` blocks of a source, [open, close]. A declaration is visible in the innermost one around it (the whole file at the top level).
+function braceBlocks(mask) {
+ const out = [];
+ const stack = [];
+ for (let i = 0; i < mask.length; i += 1) {
+ if (mask[i] === '{') stack.push(i);
+ else if (mask[i] === '}' && stack.length) out.push([stack.pop(), i]);
+ }
+ return out;
+}
+
+// The names that keep a built-in operation's result once its call answers, each with the block it is visible in ({ name, start, end }):
+// - `seeds` — the variable the call's answer is assigned to (`res`);
+// - a variable initialized from a call of the helper or a handler (`const view = await readIdentity(api)`);
+// - the state its setter stores one in (`setIdentity(view)`, with `const [identity, setIdentity] = useState(…)`);
+// - a declared ref or variable one is assigned to (`last.current = view`);
+// - every variable initialized from any of those (`const shown = version.version`) — until nothing new is found.
+// Scoped by block, so a same-named variable of another function holds nothing. A name passed on to a function this does not follow (a prop
+// callback) is not tracked: the page component is the root of what a generated page renders.
+function resultHolders(mask, reached, seeds) {
+ const blocks = braceBlocks(mask);
+ const scopeOf = (at) => blocks.filter(([a, b]) => a < at && at < b).reduce((best, block) => (!best || block[0] > best[0] ? block : best), null) || [0, mask.length];
+ const declarations = [];
+ // `const view = …`, `let last;`, `const [identity, setIdentity] = …`, `const { a, b: c } = …` — each declared local name, and its initializer.
+ for (const match of mask.matchAll(/\b(const|let|var)\s+(\[[^\]]*\]|\{[^}]*\}|[A-Za-z_$][\w$]*)/g)) {
+ const pattern = match[2];
+ const names = /^[[{]/.test(pattern)
+ ? pattern.slice(1, -1).split(',').map((part) => /^\s*(?:\.\.\.)?\s*(?:[A-Za-z_$][\w$]*\s*:\s*)?([A-Za-z_$][\w$]*)/.exec(part)?.[1]).filter(Boolean)
+ : [pattern];
+ const assigned = /^\s*(?::[^=;]+)?=(?!=)\s*/.exec(mask.slice(match.index + match[0].length));
+ let init = -1;
+ let end = -1;
+ if (assigned) {
+ init = match.index + match[0].length + assigned[0].length;
+ try { end = expressionEnd(mask, init); } catch { continue; }
+ }
+ const text = assigned ? mask.slice(init, end) : '';
+ declarations.push({
+ kind: match[1], names, init, end, scope: scopeOf(match.index),
+ isFunction: /=>|^\s*(?:async\s+)?function\b/.test(text),
+ setter: pattern.startsWith('[') && /^\s*(?:React\s*\.\s*)?useState\b/.test(text) ? names[1] || null : null,
+ });
+ }
+ const declared = new Set(declarations.flatMap((d) => d.names));
+ // A JSX attribute (`onClick={…}`) is not an assignment, so a plain name is followed only when `let` or `var` declares it.
+ const reassignable = new Set(declarations.filter((d) => d.kind !== 'const').flatMap((d) => d.names));
+ const scopeOfName = (name, at) => declarations
+ .filter((d) => d.names.includes(name) && d.scope[0] <= at && at <= d.scope[1])
+ .reduce((best, d) => (!best || d.scope[0] > best[0] ? d.scope : best), null) || [0, mask.length];
+ const reachedCalls = [...reached].flatMap((fn) => callSites(mask, fn).map((site) => site.at));
+ const cache = new Map();
+ const mentionsOf = (name) => {
+ if (!cache.has(name)) cache.set(name, mentions(mask, name));
+ return cache.get(name);
+ };
+ const held = [];
+ const carries = (from, to) => reachedCalls.some((at) => at >= from && at < to)
+ || held.some(({ name, start, end }) => mentionsOf(name).some((at) => at >= from && at < to && start < at && at < end));
+ const hold = (name, [start, end]) => {
+ if (held.some((h) => h.name === name && h.start === start && h.end === end)) return false;
+ held.push({ name, start, end });
+ return true;
+ };
+ for (const { name, at } of seeds) hold(name, scopeOf(at));
+ for (let grew = true; grew;) {
+ grew = false;
+ for (const d of declarations) {
+ if (d.init !== -1 && !d.isFunction && !d.setter && carries(d.init, d.end)) for (const name of d.names) grew = hold(name, d.scope) || grew;
+ }
+ for (const d of declarations.filter((entry) => entry.setter)) {
+ for (const site of callSites(mask, d.setter)) {
+ const open = mask.indexOf('(', site.at);
+ let close;
+ try { close = groupEnd(mask, open); } catch { continue; }
+ if (carries(open, close)) grew = hold(d.names[0], d.scope) || grew;
+ }
+ }
+ // An assignment to a ref's `.current`, or to a name `let` or `var` declares (`last = view`).
+ for (const match of mask.matchAll(/(?<![\w$.])([A-Za-z_$][\w$]*)(\s*\.\s*current)?\s*=(?![=>])/g)) {
+ if (!(match[2] ? declared : reassignable).has(match[1]) || /\b(?:const|let|var)\s+$/.test(mask.slice(Math.max(0, match.index - 12), match.index))) continue;
+ const from = match.index + match[0].length;
+ let end;
+ try { end = expressionEnd(mask, from); } catch { continue; }
+ if (carries(from, end)) grew = hold(match[1], scopeOfName(match[1], match.index)) || grew;
+ }
+ }
+ return held;
+}
+
+function builtInRuntimeProblems(code, names) {
+ const problems = [];
+ if (!names.length) return problems;
+ let calls;
+ try { calls = actionCalls(code); } catch (error) { return [`built-in operation calls are not gradeable (${error.message})`]; }
+ const mask = blankNonCodePreservingTemplateExpressions(code);
+ const decls = functionDeclarations(mask);
+ const exported = /\bexport\s+default\s+(?:async\s+)?(?:function\s+)?([A-Za-z_$][\w$]*)/.exec(mask)?.[1];
+ // Where the page renders: the default export, and — under the canonical boundary wrapper, whose default export only renders
+ // `<PageErrorBoundary><PageBody {...props} /></PageErrorBoundary>` — the PageBody it forwards its props to (source-evidence.js).
+ // Unproven, PageBody is followed like any other caller, which still refuses a render-time call, under another message.
+ const renderRoots = new Set([exported, (() => { try { return forwardedPageBodyOf(code)?.scope?.name; } catch { return undefined; } })()].filter(Boolean));
+ const enclosing = (at) => decls.filter((d) => d.start < at && at < d.end).reduce((best, d) => (!best || d.start > best.start ? d : best), null);
+ const ranges = (pattern) => [...mask.matchAll(pattern)].map((m) => {
+ const open = m.index + m[0].length - 1;
+ try { return [open, groupEnd(mask, open)]; } catch { return [open, mask.length]; }
+ });
+ const notAUser = ranges(NOT_A_USER);
+ const clicks = ranges(/\bonClick\s*=\s*\{/g);
+ const dependencies = dependencyLists(mask);
+ const aliases = aliasDeclarations(mask);
+ const within = (list, at) => list.some(([a, b]) => a < at && at < b);
+ // The constant a mention of `fn` names: `const run = fn;` (a cast or `!` allowed) or `const run = useCallback(fn, […])`. Any other initializer
+ // — `store.subscribe(fn)`, `{ go: fn }`, a function that hands it on later — passes it to code this check does not follow.
+ const aliasAt = (at, fn) => {
+ const alias = aliases.filter((d) => d.init <= at && at < d.end).reduce((best, d) => (!best || d.init > best.init ? d : best), null);
+ const holder = enclosing(at);
+ if (!alias || (holder && holder.start > alias.init)) return null;
+ const head = mask.slice(alias.init, at);
+ const tail = mask.slice(at + fn.length, alias.end);
+ const renamed = /^\s*$/.test(head) && /^\s*(?:!\s*)?(?:(?:as|satisfies)\b[\s\S]*)?$/.test(tail);
+ const memoized = /^\s*(?:React\s*\.\s*)?useCallback\s*(?:<(?:[^<>()]|<[^<>()]*>)*>\s*)?\(\s*$/.test(head) && /^\s*[,)]/.test(tail);
+ return renamed || memoized ? alias.name : null;
+ };
+ // A page-wide rule: nothing of a built-in operation's failure tells the maker to deploy a Custom API, and no stack is shown.
+ for (const literal of code.match(/'(?:\\.|[^'\\\n])*'|"(?:\\.|[^"\\\n])*"|`[^`]*`/g) || []) {
+ if (/unavailable|not found|not available|\b404\b/i.test(literal) && /deploy|custom api/i.test(literal)) problems.push('a built-in operation message must not tell the maker to deploy a Custom API');
+ }
+ if (/\.\s*stack\b/.test(mask)) problems.push('a built-in operation failure must not show a stack');
+ const disabledBy = new Map();
+ for (const name of names) {
+ const own = calls.filter((call) => literalString(call.fields.get('name') || '') === name);
+ if (!own.length) continue;
+ for (const call of own) {
+ const at = `${name}`;
+ const helper = call.scope;
+ const result = call.resultName;
+ const prefix = code.slice(helper.start, call.start);
+ const prefixMask = mask.slice(helper.start, call.start);
+ const post = code.slice(call.end + 1, helper.end);
+ const postMask = mask.slice(call.end + 1, helper.end);
+ if ([...call.fields.keys()].join(',') !== 'name') problems.push(`${at}: the request must be exactly { name } — no parameters and no boundTo`);
+ // The presence check must return before the call: a page whose player lacks executeFunction sends nothing.
+ const receiver = call.receiver ? call.receiver.split('.').map(escapeRe).join('\\s*\\??\\.\\s*') : '(?!)';
+ const guard = new RegExp(`\\bif\\s*\\(\\s*typeof\\s+${receiver}\\s*\\??\\.\\s*executeFunction\\s*!==?\\s*(['"])`).exec(prefixMask);
+ let returns = false;
+ if (guard && /^['"]function['"]/.test(prefix.slice(guard.index + guard[0].length - 1))) {
+ try { returns = /^\s*(?:return\b|\{[^}]*\breturn\b)/.test(prefixMask.slice(groupEnd(prefixMask, prefixMask.indexOf('(', guard.index)) + 1)); } catch { returns = false; }
+ }
+ if (!returns) problems.push(`${at}: a failed presence check must return before any request is made`);
+ // User-triggered: every way to the helper starts at a button's onClick. A function is reached by a call (`fn(…)`) or by a mention that hands
+ // it on (`setTimeout(fn, 0)`, `ref={fn}`, `const run = fn`). A mention in a button's onClick is the user's; one in an effect, a memo, a
+ // timer, a frame or a microtask is not, whatever else also calls it; one in a hook's dependency list calls nothing; one that initializes a
+ // constant makes that constant another name for it, followed the same way. Any other mention hands it to code that could call it unclicked.
+ const reached = new Set();
+ const handlers = [];
+ const queue = [helper.name];
+ while (queue.length) {
+ const fn = queue.shift();
+ if (reached.has(fn)) continue;
+ reached.add(fn);
+ const sites = [];
+ for (const site of callSites(mask, fn)) {
+ if (fn === helper.name && site.at > helper.start && site.at < helper.end) problems.push(`${at}: the helper calls itself (an automatic retry)`);
+ else sites.push(site);
+ }
+ let referenced = false;
+ let aliased = false;
+ for (const mention of mentions(mask, fn)) {
+ if (within(dependencies, mention)) continue;
+ if (within(notAUser, mention)) { problems.push(`${at}: handed to an effect, a memo or a timer — a built-in operation is called only when the user clicks its button`); continue; }
+ if (within(clicks, mention)) { referenced = true; continue; }
+ const alias = aliasAt(mention, fn);
+ if (alias) { aliased = true; queue.push(alias); continue; }
+ problems.push(`${at}: ${fn} is handed somewhere other than its button's onClick — a ref, a child or a timer could call it without a click`);
+ }
+ if (!sites.length && !referenced && !aliased) problems.push(`${at}: ${fn} is not reached from a button's onClick`);
+ for (const site of sites) {
+ if (within(notAUser, site.at)) { problems.push(`${at}: called from an effect, a memo or a timer — a built-in operation is called only when the user clicks its button`); continue; }
+ if (within(clicks, site.at)) continue;
+ const outer = enclosing(site.at);
+ if (!outer || renderRoots.has(outer.name)) { problems.push(`${at}: called while the page renders — a built-in operation is called only when the user clicks its button`); continue; }
+ if (outer.name !== helper.name) { handlers.push(outer); queue.push(outer.name); }
+ }
+ }
+ // The button: disabled while pending; a state of its own per operation.
+ for (const [open] of clicks) {
+ const region = mask.slice(open, groupEnd(mask, open));
+ if (![...reached].some((fn) => new RegExp(`(?<![\\w$.])${escapeRe(fn)}(?![\\w$])`).test(region))) continue;
+ const tagStart = mask.lastIndexOf('<', open);
+ let depth = 0;
+ let tagEnd = mask.length;
+ for (let i = tagStart; i < mask.length; i += 1) {
+ if (mask[i] === '{') depth += 1;
+ else if (mask[i] === '}') depth -= 1;
+ else if (mask[i] === '>' && depth === 0 && mask[i - 1] !== '=') { tagEnd = i; break; }
+ }
+ const disabled = /\bdisabled\s*=\s*\{([^}]*)\}/.exec(code.slice(tagStart, tagEnd));
+ if (!disabled) problems.push(`${at}: its button is not disabled while the call is pending`);
+ else disabledBy.set(name, disabled[1].replace(/\s+/g, ''));
+ }
+ const handlerText = handlers.map((h) => code.slice(h.start, h.end)).join('\n');
+ if (!/\+\+\s*[\w$.]+\.current\b|[\w$.]+\.current\s*(?:\+\+|\+=\s*1\b)/.test(handlerText) || !/[!=]==?\s*[\w$.]+\.current\b|[\w$.]+\.current\s*[!=]==?/.test(handlerText)) {
+ problems.push(`${at}: the handler does not ignore a stale request (a .current counter incremented before the call and compared after it)`);
+ }
+ if (!/\bcatch\b/.test(handlerText + prefix + post)) problems.push(`${at}: a rejected call is not caught`);
+ if (LEAKS.test(mask.slice(helper.start, helper.end)) || LEAKS.test(handlers.map((h) => mask.slice(h.start, h.end)).join('\n'))) {
+ problems.push(`${at}: the result must not be logged, stored, copied or sent`);
+ }
+ // …nor anything that keeps it, wherever the page uses that: the state rendered from it, a ref, a variable — at render, in an effect, in
+ // another handler. A sink is the expression a LEAKS match starts, so what it is handed is what it logs, stores, copies or sends.
+ const holders = resultHolders(mask, reached, call.resultName ? [{ name: call.resultName, at: call.start }] : []);
+ for (const sink of mask.matchAll(SINKS)) {
+ let end;
+ try { end = expressionEnd(mask, sink.index); } catch { end = mask.length; }
+ const holder = holders.find(({ name: held, start, end: scopeEnd }) => mentions(mask, held).some((spot) => spot > sink.index && spot < end && start < spot && spot < scopeEnd));
+ if (holder) problems.push(`${at}: a value kept from its result (${holder.name}) must not be logged, stored, copied or sent`);
+ }
+ // Outputs: an object check, own-property reads, never a literal member, the root, a spread, an iteration or a serialization.
+ if (!/\bArray\s*\.\s*isArray\s*\(/.test(postMask) || !/\btypeof\s+[\w$.?]+\s*!==?\s*(['"])object\1/.test(post)) {
+ problems.push(`${at}: res.outputs must be checked to be a non-null, non-array object before it is read (an empty or 204 answer)`);
+ }
+ if (!/\bObject\s*\.\s*prototype\s*\.\s*hasOwnProperty\s*\.\s*call\s*\(|\bObject\s*\.\s*hasOwn\s*\(/.test(mask)) problems.push(`${at}: outputs must be read through own-property checks`);
+ const sources = `(?:${escapeRe(result)}|[\\w$]*[oO]utputs)`;
+ if (new RegExp(`\\b[\\w$]*[oO]utputs\\s*(?:\\?\\.|\\.)\\s*(?:${DTO})\\b`).test(mask)
+ || new RegExp(`\\b[\\w$]*[oO]utputs\\s*(?:\\?\\.)?\\s*\\[\\s*(['"])(?:${DTO})\\1\\s*\\]`).test(code)
+ || new RegExp(`\\{[^{}]*\\b(?:${DTO})\\b[^{}]*\\}\\s*=\\s*[\\w$.?]*[oO]utputs\\b`).test(mask)) {
+ problems.push(`${at}: an output is read as a member instead of through an own-property check`);
+ }
+ if (new RegExp(`\\b${escapeRe(result)}\\s*\\??\\.\\s*(?:${DTO})\\b`).test(mask)
+ || new RegExp(`\\.\\s*(?:${DTO})\\b`).test(mask.slice(helper.start, helper.end))) {
+ problems.push(`${at}: a DTO field is read as a member — from the result root, res.value or a cast — instead of through an own-property check of res.outputs`);
+ }
+ if (new RegExp(`\\.\\.\\.\\s*${sources}\\b|JSON\\s*\\.\\s*stringify\\s*\\(\\s*${sources}\\b|Object\\s*\\.\\s*(?:keys|values|entries)\\s*\\(\\s*${sources}\\b|Object\\s*\\.\\s*assign\\s*\\([^)]*\\b${sources}\\b|\\bfor\\s*\\([^)]*\\bin\\s+${sources}\\b`).test(mask)) {
+ problems.push(`${at}: outputs are spread, iterated or serialized — read the named properties only`);
+ }
+ if (/\.\s*message\s*\??\.\s*(?:includes|match|search|indexOf|startsWith|endsWith|toLowerCase)\s*\(|\.\s*test\s*\(\s*[\w$.?]*\.\s*message\b/.test(postMask)) {
+ problems.push(`${at}: a status must never be read out of the message's words`);
+ }
+ if (!code.includes(UNEXPECTED)) problems.push(`${at}: an unexpected shape must say "${UNEXPECTED}"`);
+ if (/\b404\b/.test(postMask) && !code.includes(UNAVAILABLE)) problems.push(`${at}: an actual 404 must say "${UNAVAILABLE}"`);
+ const guards = returningGuards(post, postMask);
+ if (name === 'WhoAmI') {
+ // All or nothing: the three own-property reads, and ONE returning guard that tests every one of them with the GUID pattern.
+ if (!code.includes(`/${GUID_SOURCE}/`)) problems.push(`${at}: the GUID pattern ${GUID_SOURCE} is not used`);
+ const locals = new Map();
+ for (const field of IDENTITY_FIELDS) {
+ if (!new RegExp(`(['"])${field}\\1`).test(post)) problems.push(`${at}: ${field} is not read`);
+ const local = new RegExp(`\\b(?:const|let)\\s+([A-Za-z_$][\\w$]*)\\s*=[^;\\n]*(['"])${field}\\2`).exec(post);
+ locals.set(field, local ? local[1] : field);
+ }
+ const tested = (condition) => (/\.every\s*\(/.test(condition) && /\.test\s*\(/.test(condition)) || (condition.match(/\.test\s*\(/g) || []).length >= IDENTITY_FIELDS.length;
+ const allOrNothing = guards.some(({ condition }) => tested(condition)
+ && [...locals.values()].every((local) => new RegExp(`(?<![\\w$])${escapeRe(local)}(?![\\w$])`).test(condition)));
+ if (!allOrNothing) problems.push(`${at}: the three identifiers must be shown all or none — one guard that returns must test every one with the GUID pattern`);
+ }
+ if (name === 'RetrieveVersion') {
+ if (!/(['"])Version\1/.test(post)) problems.push(`${at}: Version is not read`);
+ const bounded = guards.some(({ condition }) => /\b128\b/.test(condition) && (/!\s*[A-Za-z_$]/.test(condition) || /\.length\s*(?:<\s*1\b|===?\s*0\b|>=?\s*1\b|>\s*0\b)/.test(condition)));
+ if (!bounded) problems.push(`${at}: Version must be a string of 1 to 128 characters, or nothing is shown`);
+ }
+ }
+ }
+ if (disabledBy.size === 2 && new Set(disabledBy.values()).size === 1) problems.push('each built-in operation needs a pending state of its own: one call must not disable the other\'s button');
+ return [...new Set(problems)];
+}
+
+module.exports = {
+ SECTION, SENTINEL, VERIFICATION_LINE, BUILT_IN_OUTPUTS,
+ isBuiltInBinding, partitionBindings, plannedBuiltIns, unionBindings, listedBuiltIns, unionOrderProblems, builtInGateProblems,
+ clearConfirmationProblems, builtInRuntimeProblems,
+};
diff --git a/evals/model-apps/genpage/lib/assertions-layer-1.js b/evals/model-apps/genpage/lib/assertions-layer-1.js
index 582996b7d..45159fdb4 100644
--- a/evals/model-apps/genpage/lib/assertions-layer-1.js
+++ b/evals/model-apps/genpage/lib/assertions-layer-1.js
@@ -22,14 +22,21 @@ const { navigationProblems, navTargets } = require('./navigation-contract.js');
const { workerProblems } = require('./worker-contract.js');
const { uploadProblems, uploadPreservationProblems } = require('./upload-contract.js');
const { planSection, findMarkdownTable, parseMarkdownRows } = require('./plan-evidence.js');
-const { customApiProblems, customApiGateProblems } = require('./custom-api-contract.js');
+const { gradeCustomApi } = require('./custom-api-contract.js');
+const { plannedBuiltIns } = require('./action-binding-union.js');
const { packagingProblems, isPackaging } = require('./packaging-contract.js');
const { preservationProblems } = require('./preservation-contract.js');
const { columnProblems } = require('./column-contract.js');
const { escapeRe } = require('./source-evidence.js');
const evidence = require('./expectation-evidence.js');
const { blankLiterals } = require('../../../../plugins/model-apps/scripts/lib/source-literals.js');
-const { planTargets } = require('../../../../plugins/model-apps/scripts/genpage-plan-provenance.js');
+const { planTargets, sha256 } = require('../../../../plugins/model-apps/scripts/genpage-plan-provenance.js');
+// The gate provision-entities.js puts its input through, so an input the plugin would refuse is never graded as written right.
+const { validateProvisionInput } = require('../../../../plugins/model-apps/scripts/lib/provision-input.js');
+const {
+ writtenSemanticsProblems, readWrittenSemantics, readPreviewSemantics, requiredContractProblems, compareSemantics, semanticRecord,
+ lookupEvidenceProblems, normalizeValue,
+} = require('../../../../plugins/model-apps/scripts/lib/genpage-plan-semantics.js');
function fail(reason) { return { status: 'fail', reason }; }
function pass() { return { status: 'pass', reason: '' }; }
@@ -130,6 +137,15 @@ function isUnattendedLog(log) {
);
}
+// The unattended plan-approval record (skills/genpage/SKILL.md, unattended table), recognized by its PURPOSE — the words right
+// after the marker — so a semantic default on the same marker never stands in for it:
+// Unattended default: plan approval → approved (unattended mode; all semantic questions resolved)
+// - Unattended default: plan approval -> approved, including explicit optional packaging into ContosoPages.
+// Leading whitespace or a list bullet, either arrow (`→`, or the historical `->`), the whole word `approved`, then nothing, a
+// parenthesized reason or a comma tail. Not matched: `Unattended default: A1 / plan-status → Approved (…)` (an answer), a reason
+// that says "approved plan", `plan approval → auto-approve`.
+const PLAN_APPROVAL_RECORD = /^[ \t]*(?:(?:[-*+]|\d+[.)])[ \t]+)?Unattended default:[ \t]*plan approval[ \t]*(?:→|->)[ \t]*approved(?:[ \t]*\(.*\)|,.*)?[ \t]*\.?[ \t]*\r?$/im;
+
function entitiesNeedCreating(plan) {
const section = planSection(plan, 'Entity Creation Required');
if (!section) return false;
@@ -176,7 +192,12 @@ const REQUIRED_PLAN_SECTIONS = [
'Per-Page Specifications',
];
-const OPTIONAL_PLAN_SECTIONS = new Set(['Solution Packaging']);
+const OPTIONAL_PLAN_SECTIONS = new Set(['Assumptions', 'Dataverse Operations', 'Solution Packaging']);
+
+// The codes of the plan's semantic records (plugins/model-apps/scripts/lib/genpage-plan-semantics.js): a present Assumptions
+// section or per-page Data semantics / Lookup metadata block that the reader refuses. Phase 5a routes them like the page rules —
+// a plan that fails one must not reach the builders.
+const SEMANTIC_CODES = ['invalid-assumptions', 'unknown-assumption', 'missing-semantic-source', 'unmatched-requirement-quote', 'invalid-data-semantics', 'invalid-lookup-metadata'];
const REQUIRED_PER_PAGE_FIELDS = [
'File',
@@ -319,7 +340,7 @@ function validateEntityCreationSection(sectionText, errors) {
}
}
-function validateGenpagePlanSchema(plan) {
+function validateGenpagePlanSchema(plan, { requireSemantics = false } = {}) {
const errors = [];
if (!plan || typeof plan !== 'string') {
return [schemaError('missing-plan', 'genpage-plan.md is empty or missing')];
@@ -345,9 +366,18 @@ function validateGenpagePlanSchema(plan) {
// Solution Packaging is optional and sits between Custom API Bindings and Design Preferences, as in
// references/plan-schema.md. Split at that point by NAME: an index goes stale the moment a required
// section is added before it — which is exactly how Custom API Bindings ended up expected after it.
+ // Dataverse Operations is optional too, and sits right after Custom API Bindings, before Solution
+ // Packaging; either is checked for order only when the plan has it, so a plan without them is unchanged.
+ // Assumptions is optional on read (an older plan has none: "not recorded") and sits right after User Requirements, spliced in
+ // by that name too — adding it only to the optional set would not do: the comparable filter keeps only expected titles, so a
+ // misplaced Assumptions would be dropped from the comparison instead of failing it.
const packagingAt = REQUIRED_PLAN_SECTIONS.indexOf('Design Preferences');
+ const assumptionsAt = REQUIRED_PLAN_SECTIONS.indexOf('User Requirements') + 1;
const expected = [
- ...REQUIRED_PLAN_SECTIONS.slice(0, packagingAt),
+ ...REQUIRED_PLAN_SECTIONS.slice(0, assumptionsAt),
+ ...(observed.includes('Assumptions') ? ['Assumptions'] : []),
+ ...REQUIRED_PLAN_SECTIONS.slice(assumptionsAt, packagingAt),
+ ...(observed.includes('Dataverse Operations') ? ['Dataverse Operations'] : []),
...(observed.includes('Solution Packaging') ? ['Solution Packaging'] : []),
...REQUIRED_PLAN_SECTIONS.slice(packagingAt),
];
@@ -394,6 +424,16 @@ function validateGenpagePlanSchema(plan) {
}
}
+ // Optional: absent is no new built-in authoring. Present, it is the exact sentinel or the catalogue's own table, read by the same rule the
+ // lifecycle evaluator uses (action-binding-union.js) — anything else halts, so an unreadable selection is never read as "none".
+ if (byTitle.has('Dataverse Operations')) {
+ try {
+ plannedBuiltIns(plan);
+ } catch (error) {
+ errors.push(schemaError('invalid-dataverse-operations', `## Dataverse Operations must be the exact sentinel "No Dataverse operations." or the built-in operation table: ${error.message}`, { section: 'Dataverse Operations' }));
+ }
+ }
+
const samplesSection = byTitle.get('Relevant Samples');
if (samplesSection && !findMarkdownTable(samplesSection.content, ['Page', 'Sample', 'Reason'])) {
errors.push(schemaError('missing-samples-table', '## Relevant Samples must contain a table with Page, Sample, and Reason columns', { section: 'Relevant Samples' }));
@@ -431,6 +471,13 @@ function validateGenpagePlanSchema(plan) {
}
}
+ // The semantic records (## Assumptions; per page, #### Data semantics and #### Lookup metadata): validated whenever present, on any
+ // plan — an App Spec projection (`Mode: app-builder`) included, since a mode never waives malformed content — and required of every
+ // page only for a newly authored plan (`requireSemantics`). Absent on an older plan, they are "not recorded" and nothing more.
+ for (const found of writtenSemanticsProblems(plan, { require: requireSemantics })) {
+ errors.push(schemaError(found.code, found.message, { section: found.code === 'invalid-assumptions' ? 'Assumptions' : 'Per-Page Specifications' }));
+ }
+
return errors;
}
@@ -612,7 +659,11 @@ WORKFLOW_ASSERTIONS.set(
// plan/approval context dead code: any `Unattended default:` line containing "approved" —
// e.g. a solution-selection default — satisfied an assertion that claims to check PLAN
// approval. The documented marker is `Unattended default: plan approval → approved (...)`.
- if (!/Unattended default:[^\n]*(plan|approval)[^\n]*approved/i.test(log)) {
+ // Its successor (`plan` or `approval` anywhere before `approved`) was still too loose once runs
+ // record semantic defaults on the same marker: `Unattended default: A1 / plan-status → Approved
+ // (…)` answers a question, and a reason such as "planner default; approved plan" explains one.
+ // So the record is recognized by its own purpose, the words right after the marker.
+ if (!PLAN_APPROVAL_RECORD.test(log)) {
return fail('unattended workflow-log does not record plan approval');
}
return pass();
@@ -747,18 +798,9 @@ WORKFLOW_ASSERTIONS.set(PACKAGING_ASSERTION, ({ fixture }) => {
return gradeEvidence(packagingProblems, fixture);
});
-WORKFLOW_ASSERTIONS.set(
- 'Phase 4.6: A populated Custom API plan never discovers, generates or uploads after a disabled or unreadable feature gate',
- ({ fixture }) => {
- const body = planSection(fixture.genpagePlan, 'Custom API Bindings');
- if (!fixture.manifest?.customApi && (!body || body === 'No custom API bindings.')) return skip('no Custom API lifecycle in this workflow');
- return gradeEvidence(customApiGateProblems, fixture);
- }
-);
-
PHASE_EXPECTATIONS.set(
'Phase 5: Custom API discovery, gate, bare bindings, runtime calls and update preservation or explicit clear agree',
- ({ fixture }) => gradeEvidence(customApiProblems, fixture)
+ ({ fixture }) => gradeCustomApi(fixture)
);
PHASE_EXPECTATIONS.set(
@@ -2107,8 +2149,10 @@ PHASE_EXPECTATIONS.set(
if (!fixture.genpagePlan) return fail('no genpage-plan.md');
// The gate's observable outcome is what is graded: a plan that fails any Phase 5a rule must not
// reach the builders. The rules are the plan-schema validator's (Pages table, page-file targets,
- // one matching Per-Page Specifications subsection per row) plus the at-least-one-page rule.
- const codes = new Set(['missing-pages-table', 'duplicate-page-file', 'invalid-page-file', 'missing-page-spec', 'extra-page-spec', 'page-file-mismatch']);
+ // one matching Per-Page Specifications subsection per row) plus the at-least-one-page rule — and
+ // the plan's semantic records, when it has them: a malformed Assumptions section, a decision whose
+ // source does not resolve, a quote the requirements do not hold or malformed lookup metadata.
+ const codes = new Set(['missing-pages-table', 'duplicate-page-file', 'invalid-page-file', 'missing-page-spec', 'extra-page-spec', 'page-file-mismatch', ...SEMANTIC_CODES]);
const problems = validateGenpagePlanSchema(fixture.genpagePlan).filter((e) => codes.has(e.code)).map((e) => e.message);
if (!pageRowsOf(fixture.genpagePlan).length) problems.unshift('plan has no pages');
if (!problems.length) return pass();
@@ -2486,6 +2530,54 @@ PHASE_EXPECTATIONS.set(
({ fixture }) => picklistResult(fixture, 'ticket', 'status', { count: 4 })
);
+// What the entity-builder handed provision-entities.js for the two choice columns (agents/genpage-entity-builder.md Step 4): each option
+// is its label — a string, or a map of LCID to label — in the plan's order, and that order is what numbers it 100000000 + index. An option
+// written as a {"label", "value"} object is refused by the plugin's own gate ("'label' is not an LCID"), so the gate is asked rather than
+// its rule repeated here. Only the captured input JSON shows how the options were written: a capture made without it is skipped, a
+// current fixture without it fails. Provisioned means APPLIED: without --apply the CLI only plans, writes nothing and answers
+// { "ok": true, "dryRun": true, "plan": [ … ] }
+// so the inputs graded are the ones the applying runs were handed, each of them — never a preview's.
+PHASE_EXPECTATIONS.set(
+ "Phase 2b (Entity Builder): cr_ticket is provisioned with choice columns via provision-entities.js input JSON; each picklist option is written as its label, in the plan's order (numbered 100000000 + index)",
+ ({ fixture }) => {
+ const calls = provisionCalls(fixture).filter((c) => typeof c.flags.input === 'string');
+ if (!calls.length) return fail('provision-entities.js was not run with --input <json>');
+ if (calls.some((c) => !c.call.historical && resultObject(c.call)?.ok !== true)) return fail('a provision-entities.js run did not return ok:true');
+ const applied = calls.filter((c) => c.flags.apply === true && resultObject(c.call)?.dryRun !== true);
+ if (!applied.length) return fail('provision-entities.js was not run with --input <json> --apply');
+ const inputs = [];
+ for (const run of applied) {
+ const name = provisionInputName(run);
+ const input = provisionInput(fixture, run);
+ if (input === null) return currentContract(fixture) ? fail(`${name} was not captured`) : skip(`${name} was not captured`);
+ if (input === undefined) return fail(`${name} is not JSON`);
+ const gate = validateProvisionInput(input);
+ if (!gate.ok) return fail(`provision-entities.js refuses the captured input: ${gate.errors[0]}`);
+ inputs.push(input);
+ }
+ const tickets = inputs.map((input) => (input.entities || []).find((e) => schemaSuffix(e.schemaName) === 'ticket')).filter(Boolean);
+ if (!tickets.length) return fail('provision-input.json does not declare ticket');
+ const block = planEntityBlocks(fixture.genpagePlan).find((b) => b.suffix === 'ticket');
+ // A string option is its label; a language map holds it under one of its languages.
+ const isLabel = (option, label) => (typeof option === 'string' ? option.trim() === label : Object.values(option || {}).some((text) => String(text).trim() === label));
+ for (const ticket of tickets) {
+ for (const name of ['priority', 'status']) {
+ const column = (ticket.columns || []).find((c) => schemaSuffix(c.schemaName) === name);
+ if (!column) return fail(`provision-input.json declares no ticket ${name} column`);
+ if (column.type !== 'Choice') return fail(`ticket ${name} is ${column.type === undefined ? 'untyped' : column.type}, not a Choice column`);
+ const planned = block && block.choices.find((c) => c.suffix === name);
+ if (!planned || !planned.options.length) return fail(`the plan lists no ${name} options to number the input's by`);
+ const labels = [...planned.options].sort((a, b) => a.value - b.value).map((o) => o.label);
+ const options = Array.isArray(column.options) ? column.options : [];
+ if (options.length !== labels.length || options.some((option, i) => !isLabel(option, labels[i]))) {
+ return fail(`ticket ${name} options are ${options.map((o) => JSON.stringify(o)).join(', ')}, but the plan numbers ${labels.join(', ')} from 100000000 in that order`);
+ }
+ }
+ }
+ return pass();
+ }
+);
+
PHASE_EXPECTATIONS.set(
'Phase 2b (Entity Builder): Solution is specified via provision-entities.js input JSON; verified through ## Environment → Solution: declaration',
({ fixture }) => {
@@ -2680,11 +2772,14 @@ function planLookupProblems(plan, child, parent) {
: [`${child} has no lookup relationship to ${parent}`];
}
-// provision-input.json, when captured: the App Spec the entity-builder handed provision-entities.js.
-function provisionInput(fixture) {
- const entry = provisionCalls(fixture).find((c) => typeof c.flags.input === 'string');
- const name = entry ? fileName(String(entry.flags.input).replace(/^@/, '')) : 'provision-input.json';
- const text = artifactOrNull(fixture, name);
+// The file name of the input JSON a provision-entities.js run was handed: `--input @D:/temp/support-tickets/provision-input.json` →
+// provision-input.json (no run: the name the entity-builder writes).
+const provisionInputName = (entry) => (entry ? fileName(String(entry.flags.input).replace(/^@/, '')) : 'provision-input.json');
+
+// provision-input.json, when captured: the App Spec the entity-builder handed provision-entities.js — the input of `entry` (a
+// provisionCalls entry), by default of the first run that names one.
+function provisionInput(fixture, entry = provisionCalls(fixture).find((c) => typeof c.flags.input === 'string')) {
+ const text = artifactOrNull(fixture, provisionInputName(entry));
if (text === null) return null;
try { return JSON.parse(text.replace(/^\uFEFF/, '')); } catch { return undefined; }
}
@@ -3484,6 +3579,294 @@ PHASE_EXPECTATIONS.set(
}
);
+// --- Evals 26 and 27: a newly authored plan's semantic records ----------------------------------
+// A plan written today carries ## Assumptions and, per page, #### Data semantics and #### Lookup metadata (references/plan-schema.md);
+// older stored plans do not, and eval 16's exact-heading list stays as it was. These scenarios grade the new contract directly:
+// the written plan in required mode, the approved preview the run saved (manifest `semantics.approvedPlan`), the two compared
+// field by field the way genpage-plan-provenance.js compares them, and the run's own --require-assumptions verification, whose
+// semanticsHash must be the hash of THIS plan's records. Nothing here is skipped for a missing artifact: a fixture that lost its
+// preview, its records or its verification fails.
+
+// The successful lookup metadata read a scenario declares (manifest `semantics.lookupMetadata`), parsed; null when it declares none.
+function declaredLookupEvidence(fixture) {
+ const name = fixture.manifest?.semantics?.lookupMetadata;
+ if (!name) return null;
+ const text = fixture.artifacts?.[name];
+ if (typeof text !== 'string') return { declaredMissing: name };
+ try { return JSON.parse(text); } catch { return { unreadable: name }; }
+}
+
+function newContractProblems(fixture) {
+ const plan = fixture.genpagePlan;
+ if (!plan) return ['genpage-plan.md not present in fixture'];
+ const problems = validateGenpagePlanSchema(plan, { requireSemantics: true }).map((error) => `genpage-plan.md: ${error.message}`);
+ const previewName = fixture.manifest?.semantics?.approvedPlan;
+ const preview = previewName ? fixture.artifacts?.[previewName] : undefined;
+ if (typeof preview !== 'string') return [...problems, 'the fixture does not carry the approved preview the run verified (fixture.json semantics.approvedPlan)'];
+ const targets = planTargets(plan, { kind: 'create' })?.targets || [];
+ const previewRead = readPreviewSemantics(preview);
+ const writtenRead = readWrittenSemantics(plan);
+ problems.push(...previewRead.problems.map((p) => `the approved preview: ${p.message}`));
+ problems.push(...requiredContractProblems(previewRead, targets, 'the approved preview').map((p) => p.message));
+ const evidence = declaredLookupEvidence(fixture);
+ if (evidence && (evidence.declaredMissing || evidence.unreadable)) problems.push(`the declared lookup metadata ${evidence.declaredMissing || evidence.unreadable} is missing or not JSON`);
+ const promotions = Boolean(evidence && evidence.ok === true);
+ problems.push(...compareSemantics(previewRead, writtenRead, { promotions }).map((p) => `the written plan differs from the approved preview: ${p}`));
+ if (promotions) problems.push(...lookupEvidenceProblems(writtenRead, evidence).map((p) => p.message));
+ const verifies = commandCalls(fixture, PROVENANCE_VERIFY).filter((verify) => REQUIRE_ASSUMPTIONS.test(verify.call.command));
+ if (!verifies.length) problems.push('provenance was never verified with --require-assumptions');
+ const hash = sha256(JSON.stringify(semanticRecord(writtenRead)));
+ for (const verify of verifies) {
+ const result = resultObject(verify.call);
+ if (result?.ok !== true) problems.push(`${verify.call.id || verify.call.command}: the --require-assumptions verification did not pass`);
+ else if (result.semanticsHash !== hash) problems.push(`${verify.call.id || verify.call.command}: its semanticsHash is not the hash of this plan's records`);
+ }
+ return problems;
+}
+
+const REQUIRE_ASSUMPTIONS = /(?:^|\s)--require-assumptions(?=\s|$|['"`])/;
+const NEW_CONTRACT = 'Phase 1 (Planner): The newly authored plan records its assumptions and every page\'s data semantics and lookup metadata, the approved preview carries the same records, and provenance is verified with --require-assumptions';
+PHASE_EXPECTATIONS.set(NEW_CONTRACT, ({ fixture }) => resultOf(newContractProblems(fixture)));
+
+// --- Eval 26: an answered semantic question, the lookup metadata behind the records, the gate before generation ----
+// Each check reads evidence the fixture DECLARES under fixture.json `semantics` — the approved preview, the saved lookup metadata
+// read, the ordered semantic interactions — and fails when the declaration, the artifact or an event it names is gone: a
+// scenario that lost its evidence is a failure, never a skip. What they prove is that the recorded run agrees with itself (the
+// question the planner returned, the answer relayed back by its id, the assumption both documents keep, the approval after it;
+// the metadata read and the records built from it), not that a person answered or that the answer is what the request meant.
+
+const GET_LOOKUP_METADATA = /\bget-lookup-metadata\.js\b/;
+
+// A JSON artifact the fixture declares as fixture.json `semantics.<key>`: { name, value }, or { problem } when it is not declared,
+// not among the artifacts, or not JSON.
+function declaredJson(fixture, key) {
+ const name = fixture.manifest?.semantics?.[key];
+ if (!name) return { problem: `the fixture does not declare its ${key} evidence (fixture.json semantics.${key})` };
+ const text = fixture.artifacts?.[name];
+ if (typeof text !== 'string') return { problem: `the declared ${key} evidence ${name} is not one of the fixture's artifacts` };
+ try { return { name, value: JSON.parse(text) }; } catch { return { problem: `the declared ${key} evidence ${name} is not JSON` }; }
+}
+
+// The lookup rows the written plan records, across its pages (a page with `None.` records none).
+function recordedLookups(read) {
+ return [...read.pages.values()].flatMap((page) => (page.lookups && !page.lookups.sentinel ? [...page.lookups.rows.values()] : []));
+}
+
+const optionLabel = (option) => (typeof option === 'string' ? option : typeof option?.label === 'string' ? option.label : '');
+const sameList = (a, b) => JSON.stringify(a) === JSON.stringify(b);
+
+// The semantic interactions a run records (fixture.json `semantics.interactions`), in order:
+// { "type": "needs_input", "event": "<tool-results id>", "question": "<id>", "options": ["<label>", …], "defaults": [] }
+// { "type": "answer", "event": "<tool-results id>", "question": "<id>", "selected": "<label>", "source": "AskUserQuestion" }
+// { "type": "approval", "preview": "<approved preview artifact>", "outcome": "approved", "source": "ExitPlanMode" }
+// A needs_input is the planner event it names returning that question with those options and defaults (several candidates carry
+// no default). Its answer is one of the options, asked with AskUserQuestion — or, unattended (`"source": "unattended-default"`),
+// the one option the planner marked — and handed back by question id in the later planner event it names. The written plan and
+// the approved preview both record it as the assumption with that Question and Answer (user-confirmed, or unattended-default with
+// its Default record logged). The approval comes last, after every answer: the preview the fixture declares, saved after the
+// answer reached the planner, with the ExitPlanMode approval logged after the question (or the unattended plan-approval record).
+function semanticInteractionProblems(fixture) {
+ const declared = declaredJson(fixture, 'interactions');
+ if (declared.problem) return [declared.problem];
+ if (!Array.isArray(declared.value) || !declared.value.length) return [`${declared.name} must be an ordered array of needs_input, answer and approval entries`];
+ const problems = [];
+ const calls = workflowCalls(fixture);
+ const eventAt = (id) => (typeof id === 'string' ? calls.findIndex((call) => call.id === id) : -1);
+ const log = String(fixture.workflowLog || '');
+ const logAt = (pattern) => { const match = pattern.exec(log); return match ? match.index : -1; };
+ const previewName = fixture.manifest?.semantics?.approvedPlan;
+ const previewText = previewName ? fixture.artifacts?.[previewName] : undefined;
+ const documents = [
+ ['the written plan', readWrittenSemantics(fixture.genpagePlan || '')],
+ ['the approved preview', typeof previewText === 'string' ? readPreviewSemantics(previewText) : null],
+ ];
+ const asked = new Map();
+ const answered = new Map();
+ let approval = null;
+ declared.value.forEach((entry, index) => {
+ const where = `${declared.name} entry ${index + 1}`;
+ if (approval) { problems.push(`${where}: nothing follows the plan approval`); return; }
+ if (entry?.type === 'needs_input') {
+ const at = eventAt(entry.event);
+ const result = at >= 0 ? resultObject(calls[at]) : null;
+ const question = result?.action === 'needs_input' && Array.isArray(result.questions) ? result.questions.find((q) => q?.id === entry.question) : null;
+ if (!question) { problems.push(`${where}: the planner event ${entry.event} did not return ${entry.question} as needs_input`); return; }
+ if (asked.has(entry.question)) { problems.push(`${where}: ${entry.question} is asked twice`); return; }
+ const options = (Array.isArray(question.options) ? question.options : []).map(optionLabel);
+ const defaults = (Array.isArray(question.options) ? question.options : []).filter((option) => option?.default === true).map(optionLabel);
+ if (!sameList(options, entry.options)) problems.push(`${where}: its options are not the ones the planner returned`);
+ if (!sameList(defaults, entry.defaults)) problems.push(`${where}: its defaults are not the ones the planner marked`);
+ if (options.length > 1 && defaults.length) problems.push(`${where}: a question with several candidates carries no default`);
+ asked.set(entry.question, { text: String(question.question || ''), options, defaults, at });
+ } else if (entry?.type === 'answer') {
+ const ask = asked.get(entry.question);
+ if (!ask) { problems.push(`${where}: answers ${entry.question}, which no earlier needs_input asked`); return; }
+ if (answered.has(entry.question)) { problems.push(`${where}: ${entry.question} is answered twice`); return; }
+ if (!ask.options.includes(entry.selected)) problems.push(`${where}: "${entry.selected}" is not one of the options of ${entry.question}`);
+ const at = eventAt(entry.event);
+ if (at <= ask.at) problems.push(`${where}: no planner event after the question carries its answer (event ${entry.event})`);
+ else if (!calls[at].command.includes(entry.question) || !calls[at].command.includes(String(entry.selected))) {
+ problems.push(`${where}: the planner event ${entry.event} does not hand back ${entry.question} → ${entry.selected}`);
+ }
+ let resolution = null;
+ let line = -1;
+ if (entry.source === 'AskUserQuestion') {
+ resolution = 'user-confirmed';
+ if (isUnattendedLog(log)) problems.push(`${where}: an unattended run asks no question`);
+ // - AskUserQuestion: Which opportunities should this account show? → Direct customer
+ line = logAt(new RegExp(`AskUserQuestion:[ \\t]*${escapeRe(ask.text)}[^\\n]*?[ \\t](?:→|->)[ \\t]*${escapeRe(String(entry.selected))}[ \\t]*\\r?$`, 'm'));
+ if (line < 0) problems.push(`${where}: workflow-log.md has no "AskUserQuestion: ${ask.text} → ${entry.selected}"`);
+ } else if (entry.source === 'unattended-default') {
+ resolution = 'unattended-default';
+ if (ask.defaults.length !== 1 || ask.defaults[0] !== entry.selected) problems.push(`${where}: an unattended run may take only the one option the planner marked as the default`);
+ if (!isUnattendedLog(log)) problems.push(`${where}: an attended run asks the maker; it never takes the default`);
+ } else problems.push(`${where}: source must be AskUserQuestion or unattended-default`);
+ for (const [label, read] of documents) {
+ if (!read) { problems.push(`${where}: the fixture does not declare the approved preview (fixture.json semantics.approvedPlan)`); continue; }
+ const assumption = read.assumptions ? [...read.assumptions.entries.values()].find((item) => item.question === entry.question) : undefined;
+ if (!assumption) { problems.push(`${where}: ${label} records no assumption answering ${entry.question}`); continue; }
+ if (assumption.answer !== normalizeValue(String(entry.selected))) problems.push(`${where}: ${label} records ${assumption.id}'s Answer as "${assumption.answer}", not "${entry.selected}"`);
+ if (resolution && assumption.resolution !== resolution) problems.push(`${where}: ${label} records ${assumption.id} as ${assumption.resolution}, not ${resolution}`);
+ if (resolution === 'unattended-default' && label === 'the written plan') {
+ line = assumption.defaultRecord ? log.indexOf(assumption.defaultRecord) : -1;
+ if (line < 0) problems.push(`${where}: workflow-log.md does not hold ${assumption.id}'s Default record`);
+ }
+ }
+ answered.set(entry.question, { at, line });
+ } else if (entry?.type === 'approval') {
+ for (const question of asked.keys()) if (!answered.has(question)) problems.push(`${where}: the plan was approved while ${question} was unanswered`);
+ if (!previewName || entry.preview !== previewName) problems.push(`${where}: the approval names ${entry.preview}, not the approved preview the fixture declares (${previewName || 'none'})`);
+ if (entry.outcome !== 'approved') problems.push(`${where}: outcome must be approved (got ${entry.outcome})`);
+ const saved = previewName ? calls.findIndex((call) => call.artifact === previewName) : -1;
+ const lastAnswer = Math.max(-1, ...[...answered.values()].map((item) => item.at));
+ if (saved < 0) problems.push(`${where}: no event saved the approved preview`);
+ else if (saved < lastAnswer) problems.push(`${where}: the approved preview was saved before the answer reached the planner`);
+ if (entry.source === 'ExitPlanMode') {
+ const approvedAt = logAt(/^[^\n]*\bExitPlanMode\b[^\n]*\bapproved\b/im);
+ if (approvedAt < 0) problems.push(`${where}: workflow-log.md records no ExitPlanMode approval`);
+ else if (approvedAt < Math.max(-1, ...[...answered.values()].map((item) => item.line))) problems.push(`${where}: the plan was approved before the question was answered`);
+ } else if (entry.source === 'unattended-default') {
+ // As in the attended branch: the approval follows every answer's own record in the log (here each Default record),
+ // so an approval logged first — before the semantic default was settled — fails even when the interaction artifact
+ // lists the approval last. The first approval record counts: a later copy does not repair an earlier approval.
+ const approvedAt = logAt(PLAN_APPROVAL_RECORD);
+ if (approvedAt < 0) problems.push(`${where}: workflow-log.md has no unattended plan-approval record`);
+ else if (approvedAt < Math.max(-1, ...[...answered.values()].map((item) => item.line))) problems.push(`${where}: the plan was approved before its unattended default was recorded`);
+ } else problems.push(`${where}: source must be ExitPlanMode or unattended-default`);
+ approval = entry;
+ } else problems.push(`${where}: type must be needs_input, answer or approval`);
+ });
+ if (!asked.size) problems.push(`${declared.name} records no semantic question`);
+ if (!approval) problems.push(`${declared.name} does not end with the plan approval`);
+ return problems;
+}
+
+// The lookup metadata behind the plan's records: a get-lookup-metadata.js read of every table the records name, made before the
+// approved preview was saved, whose successful answer IS the saved artifact; every lookup of an existing table recorded
+// `observed`, its Evidence naming that artifact, and each record agreeing with the read (complete targets, concrete paths).
+function lookupDiscoveryProblems(fixture) {
+ const declared = declaredJson(fixture, 'lookupMetadata');
+ if (declared.problem) return [declared.problem];
+ const written = readWrittenSemantics(fixture.genpagePlan || '');
+ const rows = recordedLookups(written);
+ if (!rows.length) return ['the plan records no lookup, but the scenario relies on one'];
+ const problems = [];
+ if (declared.value?.ok !== true) problems.push(`${declared.name} is not a successful get-lookup-metadata.js answer`);
+ const calls = workflowCalls(fixture);
+ const tables = [...new Set(rows.map((row) => row.table))];
+ const reads = commandCalls(fixture, GET_LOOKUP_METADATA).filter(({ flags }) => tables.every((table) => csvList(flags.tables).includes(table)));
+ const read = reads.find(({ call }) => JSON.stringify(resultObject(call)) === JSON.stringify(declared.value));
+ if (!reads.length) problems.push(`get-lookup-metadata.js never read ${tables.join(', ')}`);
+ else if (!read) problems.push(`no get-lookup-metadata.js answer is the saved ${declared.name}`);
+ const saved = calls.findIndex((call) => call.artifact === fixture.manifest?.semantics?.approvedPlan);
+ if (saved < 0) problems.push('no event saved the approved preview');
+ else if (read && calls.indexOf(read.call) > saved) problems.push('the lookup metadata was read after the plan was approved');
+ const existing = existingEntities(fixture.genpagePlan || '');
+ for (const row of rows) {
+ if (existing.includes(row.table) && row.state !== 'observed') problems.push(`${row.table}.${row.column} is recorded ${row.state}, but ${row.table} exists: its lookup is read before the plan`);
+ }
+ for (const [file, page] of written.pages) {
+ if (page.lookups && !page.lookups.sentinel && !String(page.lookups.evidence || '').includes(declared.name)) problems.push(`${file}: the lookup Evidence does not name ${declared.name}`);
+ }
+ problems.push(...lookupEvidenceProblems(written, declared.value).map((p) => p.message));
+ return problems;
+}
+
+// RuntimeTypes.ts types a lookup's read property as the union of its targets' qualified forms (the type generator's shape):
+// _customerid_value: `/account(${string})` | `/contact(${string})`,
+// Returns the sorted target tables, or null when the table or the property is not declared.
+function runtimeLookupTargets(runtimeTypes, table, readProperty) {
+ const block = new RegExp(`^export type ${escapeRe(table)} = TableRow<\\{\\r?\\n([\\s\\S]*?)^\\}>`, 'm').exec(runtimeTypes);
+ if (!block) return null;
+ const line = new RegExp(`^[ \\t]*(?:readonly[ \\t]+)?${escapeRe(readProperty)}[ \\t]*:([^\\r\\n]*)$`, 'm').exec(block[1]);
+ if (!line) return null;
+ return [...line[1].matchAll(/`\/([a-z_][a-z0-9_]*)\(\$\{string\}\)`/g)].map((match) => match[1]).sort();
+}
+
+function runtimeLookupProblems(fixture) {
+ if (!fixture.runtimeTypes) return ['RuntimeTypes.ts was not captured'];
+ const rows = recordedLookups(readWrittenSemantics(fixture.genpagePlan || ''));
+ if (!rows.length) return ['the plan records no lookup, but the scenario relies on one'];
+ const problems = [];
+ const sources = generateTypesCalls(fixture).flatMap((call) => call.sources);
+ for (const row of rows) {
+ if (!sources.includes(row.table)) problems.push(`genpage.js types was not run for ${row.table}`);
+ const typed = runtimeLookupTargets(fixture.runtimeTypes, row.table, row.readProperty);
+ if (!typed) problems.push(`RuntimeTypes.ts does not declare ${row.table}.${row.readProperty}`);
+ else if (!sameList(typed, [...row.targets].sort())) problems.push(`RuntimeTypes.ts types ${row.table}.${row.readProperty} as ${typed.join(' | ') || 'no table'}, the plan records ${row.targets.join(', ')}`);
+ }
+ return problems;
+}
+
+// SKILL.md Phase 5a's gate for a plan that records a lookup: before the page is generated, a verification with
+// --require-assumptions --require-observed-lookups and the saved --lookup-metadata passes on THIS plan's records (its
+// semanticsHash), and no lookup is still `planned`.
+function observedLookupGateProblems(fixture) {
+ const plan = fixture.genpagePlan;
+ if (!plan) return ['genpage-plan.md not present in fixture'];
+ const written = readWrittenSemantics(plan);
+ const rows = recordedLookups(written);
+ const problems = [];
+ if (!rows.length) problems.push('the plan records no lookup, but the scenario relies on one');
+ for (const row of rows) if (row.state !== 'observed') problems.push(`${row.table}.${row.column} is still ${row.state} when the page is generated`);
+ const declared = declaredJson(fixture, 'lookupMetadata');
+ if (declared.problem) problems.push(declared.problem);
+ const calls = workflowCalls(fixture);
+ const generated = calls.findIndex((call) => isGeneration(call.command));
+ if (generated < 0) problems.push('the page was never generated');
+ const gates = commandCalls(fixture, PROVENANCE_VERIFY).filter(({ call }) => REQUIRE_ASSUMPTIONS.test(call.command)
+ && /--require-observed-lookups\b/.test(call.command) && /--lookup-metadata\b/.test(call.command));
+ if (!gates.length) return [...problems, 'generation was not gated by a verification with --require-assumptions --require-observed-lookups --lookup-metadata'];
+ const hash = sha256(JSON.stringify(semanticRecord(written)));
+ const passed = gates.filter(({ call, flags }) => {
+ const result = resultObject(call);
+ return result?.ok === true && result.semanticsHash === hash && (!declared.name || fileName(flags['lookup-metadata']) === declared.name);
+ });
+ if (!passed.length) problems.push('no observed-lookups verification passed on this plan\'s records with the saved lookup metadata');
+ else if (generated >= 0 && !passed.some(({ call }) => calls.indexOf(call) < generated)) problems.push('the observed-lookups verification ran after the page was generated');
+ return problems;
+}
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 1 (Planner): The open account-scope question reaches the maker as needs_input with no default, the answer returns to the planner by its question id, and the written plan and the approved preview record it as a user-confirmed assumption before approval',
+ ({ fixture }) => resultOf(semanticInteractionProblems(fixture))
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 1 (Planner): get-lookup-metadata.js reads opportunity\'s lookups before approval, its successful answer is the saved lookup-metadata.json, and every recorded lookup is observed with the complete targets and concrete paths it read',
+ ({ fixture }) => resultOf(lookupDiscoveryProblems(fixture))
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 4: RuntimeTypes.ts is generated for opportunity and types each recorded lookup\'s read property with exactly its recorded targets',
+ ({ fixture }) => resultOf(runtimeLookupProblems(fixture))
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 5a: The page is generated only after provenance is verified with --require-assumptions --require-observed-lookups --lookup-metadata on this plan\'s records',
+ ({ fixture }) => resultOf(observedLookupGateProblems(fixture))
+);
+
// --- Eval 3: an app with no pages ---------------------------------------------------------------------
PHASE_EXPECTATIONS.set(
diff --git a/evals/model-apps/genpage/lib/assertions-layer-2.js b/evals/model-apps/genpage/lib/assertions-layer-2.js
index 631d77173..a87f486b3 100644
--- a/evals/model-apps/genpage/lib/assertions-layer-2.js
+++ b/evals/model-apps/genpage/lib/assertions-layer-2.js
@@ -24,7 +24,7 @@ const { blankLiterals, blankNonCodePreservingTemplateExpressions, commentRanges,
const { pageStructureProblems } = require('../../../../plugins/model-apps/scripts/lib/page-structure.js');
const { navigationProblems } = require('./navigation-contract.js');
const { workerProblems } = require('./worker-contract.js');
-const { customApiProblems } = require('./custom-api-contract.js');
+const { gradeCustomApi } = require('./custom-api-contract.js');
const { gradeEvidence } = require('./evidence-utils.js');
const {
reviewSummaryProblems, formFieldLabelProblems, searchAndFilterProblems,
@@ -532,7 +532,7 @@ const PHASE5_EXPECTATIONS = new Map();
PHASE5_EXPECTATIONS.set(
'Phase 5: Custom API discovery, gate, bare bindings, runtime calls and update preservation or explicit clear agree',
- ({ fixture, files }) => gradeEvidence(customApiProblems, { ...fixture, files })
+ ({ fixture, files }) => gradeCustomApi({ ...fixture, files })
);
PHASE5_EXPECTATIONS.set(
diff --git a/evals/model-apps/genpage/lib/column-contract.js b/evals/model-apps/genpage/lib/column-contract.js
index 52c821c09..74dc0c402 100644
--- a/evals/model-apps/genpage/lib/column-contract.js
+++ b/evals/model-apps/genpage/lib/column-contract.js
@@ -160,22 +160,31 @@ function pageStrings(content) {
// The columns an OData $filter or orderBy expression names: `statecode eq 0 and contains(name, 'x')`,
// `name asc, createdon desc`. Quoted values are dropped first, so `name eq 'Open eq'` names only `name`.
-function expressionColumns(text) {
- const bare = String(text).replace(/'[^']*'/g, "''");
+// With `paths` (a scenario's verified lookup paths, see columnProblems), a typed navigation path is read whole first —
+// `customerid_account/accountid ne null`, `contains(customerid_account/name,'x')` — as { via, column }, and taken out of the
+// text, so its target column is never misread as a column of the queried table. Without it the text is read exactly as before.
+function expressionColumns(text, paths) {
+ let bare = String(text).replace(/'[^']*'/g, "''");
const out = [];
+ if (paths) {
+ bare = bare.replace(/(?<![\w/])([A-Za-z_][\w]*)\/([A-Za-z_][\w]*)(?![\w/])/g, (whole, via, column) => {
+ out.push({ via, column });
+ return ' '.repeat(whole.length);
+ });
+ }
for (const m of bare.matchAll(/\b([A-Za-z_][\w]*)\s+(?:eq|ne|gt|ge|lt|le|asc|desc)\b/gi)) out.push(m[1]);
for (const m of bare.matchAll(/\b(?:contains|startswith|endswith)\s*\(\s*([A-Za-z_][\w]*)/gi)) out.push(m[1]);
for (const part of bare.split(',')) {
const only = /^\s*([A-Za-z_][\w]*)\s*$/.exec(part);
if (only) out.push(only[1]);
}
- return out.filter((name) => !/^(?:and|or|not|null|true|false|eq|ne|gt|ge|lt|le|asc|desc)$/i.test(name));
+ return out.filter((name) => typeof name !== 'string' || !/^(?:and|or|not|null|true|false|eq|ne|gt|ge|lt|le|asc|desc)$/i.test(name));
}
-// Every column a page names in its dataApi calls, as { table, column, where }. Arguments, and the
-// declarations a bare name resolves to, are read from the source with its comments blanked, so
-// `select: ['accountid', /* was 'old_name' */ 'name']` names accountid and name only.
-function namedColumns(content) {
+// Every column a page names in its dataApi calls, as { table, column, where } — and, with `paths`, a typed navigation path
+// as { table, column, via, where }. Arguments, and the declarations a bare name resolves to, are read from the source with its
+// comments blanked, so `select: ['accountid', /* was 'old_name' */ 'name']` names accountid and name only.
+function namedColumns(content, paths) {
const { code } = sourceView(content);
const src = withoutComments(content);
const out = [];
@@ -203,24 +212,41 @@ function namedColumns(content) {
for (const column of list ? strings(list) : []) out.push({ table, column, where: `${where} select` });
for (const key of ['orderBy', 'filter']) {
const text = props.has(key) ? stringValue(props.get(key)) : null;
- for (const column of text ? expressionColumns(text) : []) out.push({ table, column, where: `${where} ${key}` });
+ for (const column of text ? expressionColumns(text, paths) : []) {
+ out.push(typeof column === 'string' ? { table, column, where: `${where} ${key}` } : { table, column: column.column, via: column.via, where: `${where} ${key}` });
+ }
}
}
return out;
}
// Returns null when RuntimeTypes.ts registers no table or the page names no column, else a list of problems.
-function columnProblems(files, runtimeTypes) {
+// `context.lookupPaths` (optional) is a scenario's verified lookup metadata — the concrete paths of
+// scripts/get-lookup-metadata.js, [{ table, navigationProperty, target, referencedKey }] — and `context.targetColumns` the target
+// columns verified beside it ({ account: ['name'] }: a target's primary name column a search reads). With it, a typed
+// navigation path in a filter or an orderBy is checked whole: the navigation property must be a verified concrete path of the
+// queried table, and the column after it the target's key, a column RuntimeTypes.ts declares on the target, or one of its
+// verified columns. Without it, nothing changes: a slash in an expression gets no exemption, and its parts are read as before.
+function columnProblems(files, runtimeTypes, context) {
const tables = runtimeTables(runtimeTypes);
if (!tables.size) return null;
const known = (columns, name) => columns.has(name.toLowerCase()) || SYSTEM_COLUMNS.has(name.toLowerCase());
+ const paths = context && Array.isArray(context.lookupPaths) ? context.lookupPaths : null;
+ const targetColumns = (context && context.targetColumns) || {};
const problems = [];
let named = 0;
for (const file of files) {
- for (const { table, column, where } of namedColumns(file.content)) {
+ for (const { table, column, via, where } of namedColumns(file.content, paths)) {
named += 1;
const columns = tables.get(table);
- if (!columns) problems.push(`${file.name}: ${where} reads table ${table}, which RuntimeTypes.ts does not register`);
+ if (via !== undefined) {
+ const path = paths.find((entry) => entry.table === table && entry.navigationProperty === via);
+ const verified = path && (column.toLowerCase() === String(path.referencedKey).toLowerCase()
+ || (tables.get(path.target) && known(tables.get(path.target), column))
+ || (targetColumns[path.target] || []).some((name) => String(name).toLowerCase() === column.toLowerCase()));
+ if (!path) problems.push(`${file.name}: ${where} names ${via}/${column}, which is not a verified navigation path of ${table}`);
+ else if (!verified) problems.push(`${file.name}: ${where} names ${via}/${column}, which is not a verified column of ${path.target}`);
+ } else if (!columns) problems.push(`${file.name}: ${where} reads table ${table}, which RuntimeTypes.ts does not register`);
else if (!known(columns, column)) problems.push(`${file.name}: ${where} names ${column}, which RuntimeTypes.ts does not declare on ${table}`);
}
// A display name read through its annotation: the column before `@` must exist on some registered table.
diff --git a/evals/model-apps/genpage/lib/custom-api-contract.js b/evals/model-apps/genpage/lib/custom-api-contract.js
index dd5611bdc..2a3f2544d 100644
--- a/evals/model-apps/genpage/lib/custom-api-contract.js
+++ b/evals/model-apps/genpage/lib/custom-api-contract.js
@@ -3,21 +3,21 @@
const { isDeepStrictEqual } = require('node:util');
const { PARAMETER_KIND_BY_TYPE } = require('../../../../plugins/model-apps/scripts/list-custom-apis.js');
const { pageStructureProblems } = require('../../../../plugins/model-apps/scripts/lib/page-structure.js');
-const { workflowCalls, isGeneration, isUpload, isMutation, resultObject, unassociatedCallProblems } = require('./workflow-evidence.js');
-const { artifactText, artifactJson, commandInfo, fileName, isGuid, pathKey } = require('./evidence-utils.js');
+const { workflowCalls, isUpload, resultObject, unassociatedCallProblems } = require('./workflow-evidence.js');
+const { artifactText, artifactJson, commandInfo, fileName, isGuid, pathKey, gradeEvidence } = require('./evidence-utils.js');
const { planSection, parseMarkdownRows } = require('./plan-evidence.js');
const { actionCalls, literalString, objectFields, receiverIsDataApi, stringRecordMemberIsInput, escapeRe } = require('./source-evidence.js');
const {
desiredBindings, sameBindings, uploadResultIdentityMatches, beforePageIdentityProblems, sameRecordedEnvironment,
} = require('./upload-contract.js');
+// A page's actionBindings may also hold the reviewed built-in operations (WhoAmI, RetrieveVersion): the union layer owns their plan section, listing, gate and order, and this
+// evaluator compares the WHOLE union — never the Custom API partition alone (action-binding-union.js).
+const {
+ BUILT_IN_OUTPUTS, isBuiltInBinding, partitionBindings, plannedBuiltIns, unionBindings, listedBuiltIns, unionOrderProblems, builtInGateProblems,
+ clearConfirmationProblems, builtInRuntimeProblems,
+} = require('./action-binding-union.js');
const KINDS = new Set(Object.values(PARAMETER_KIND_BY_TYPE));
-const isGate = (command) => /\bfeature-flags\.js\b[^\n]*\bcustom-api\b/.test(command);
-const gateValue = (call) => {
- const raw = typeof call.result === 'string' ? call.result.trim() : '';
- if (raw === 'enabled' || raw === 'disabled') return raw;
- return call.historical ? /(?:\u2192|->|Result:)\s*(enabled|disabled)\b/.exec(call.text || '')?.[1] || null : null;
-};
function planBindings(fixture) {
const body = planSection(fixture.genpagePlan, 'Custom API Bindings');
@@ -26,6 +26,7 @@ function planBindings(fixture) {
const rows = parseMarkdownRows(body, ['Name', 'Kind', 'Bound Entity', 'Display Name', 'Parameters (name: kind)']);
if (!rows.length) throw new Error('Custom API Bindings must be a populated table or the exact no-bindings sentinel');
return rows.map((row) => {
+ if (isBuiltInBinding(row)) throw new Error(`${row.name} is a built-in Dataverse operation: it belongs in ## Dataverse Operations, not the Custom API table`);
if (!['Action', 'Function'].includes(row.kind)) throw new Error(`invalid API kind for ${row.name}`);
const parameterKinds = {};
for (const parameter of row['parameters (name: kind)'].split(',').filter((value) => value.trim())) {
@@ -73,35 +74,66 @@ function discoveredLookupParameters(entry) {
return lookups;
}
-function customApiGateProblems(fixture) {
- const bindings = planBindings(fixture);
- const calls = workflowCalls(fixture);
- const problems = unassociatedCallProblems(fixture);
- let latest = null;
- let gateIndex = -1;
- let discoveryIndex = -1;
- for (const [index, call] of calls.entries()) {
- if (isGate(call.command)) {
- latest = gateValue(call);
- gateIndex = index;
- } else if (/\blist-custom-apis\.js\b/.test(call.command)) {
- if (latest !== 'enabled') problems.push('Custom API discovery ran before an enabled feature gate');
- discoveryIndex = index;
- } else if (bindings.length && (isGeneration(call.command) || isUpload(call.command))) {
- if (latest !== 'enabled') problems.push('disabled or unreadable Custom API gate must halt before generation or upload');
- else if (gateIndex <= discoveryIndex) problems.push('Custom API generation must re-probe the feature gate after planning discovery');
+// A binding a page already holds, as an evaluator compares it: a built-in entry is carried as the page holds it — a legacy one with no isFunction
+// included — so it is never held to the Custom API projection.
+const projectExisting = (entry) => (isBuiltInBinding(entry) ? entry : projectBinding(entry));
+
+// The update stages whose before-config is provably the page they update: the upload names an existing page and returns it, and either the
+// scenario's upload row ties the before-page snapshot to that upload, or an earlier stage of this lifecycle produced that exact read-back for
+// the same page and app. Only these stages' existing bindings count as kept; any other "existing" binding is a claim, not evidence. Returns
+// each stage's before-config bindings, the verified stages, and the identity problems of the others.
+function beforeConfigEvidence(fixture, stages, calls) {
+ const beforeByStage = new Map();
+ const verifiedBefore = new Set();
+ const producedConfigs = new Map();
+ const problems = [];
+ for (const stage of stages) {
+ const uploads = calls.filter((entry) => entry.id === stage.upload && isUpload(entry.command));
+ const call = uploads.length === 1 ? uploads[0] : null;
+ const flags = call ? commandInfo(call).flags : {};
+ const result = call ? resultObject(call) : null;
+ if (stage.beforeConfig) {
+ const config = artifactJson(fixture, stage.beforeConfig);
+ const before = config.actionBindings === undefined ? [] : config.actionBindings;
+ desiredBindings(before, undefined, 'name');
+ for (const binding of before) projectExisting(binding);
+ beforeByStage.set(stage, before);
+ const identityProblems = [];
+ if (!call || !flags['page-id'] || result?.ok !== true || !uploadResultIdentityMatches(flags, result)) {
+ identityProblems.push(`${stage.id}: before-config preservation requires an unambiguous existing update target`);
+ }
+ const rows = fixture.manifest?.uploads;
+ if (rows !== undefined) {
+ const associated = Array.isArray(rows) ? rows.filter((row) => row.event === stage.upload) : [];
+ if (associated.length !== 1) {
+ identityProblems.push(`${stage.id}: before-page identity evidence has no unique upload association`);
+ } else if (call) {
+ identityProblems.push(...beforePageIdentityProblems(fixture, associated[0], call, stage.beforeConfig, stage.afterConfig));
+ }
+ } else {
+ // A prior successful lifecycle stage can associate its exact read-back snapshot with its
+ // result identity. A first-stage arbitrary artifact path cannot establish page ownership.
+ const prior = producedConfigs.get(pathKey(stage.beforeConfig));
+ if (!prior || prior.pageId !== flags['page-id'] || prior.appId !== flags['app-id']) {
+ identityProblems.push(`${stage.id}: before-config lacks same-page/app identity provenance`);
+ } else if (prior.env !== undefined && !sameRecordedEnvironment(prior.env, flags.env)) {
+ identityProblems.push(`${stage.id}: before-config environment differs from the update target`);
+ }
+ }
+ problems.push(...identityProblems);
+ if (!identityProblems.length) verifiedBefore.add(stage);
}
- }
- if (bindings.length && !calls.some((call) => isGate(call.command))) problems.push('Custom API table has no applicable feature gate');
- if (fixture.manifest?.expectedOutcome === 'refused') {
- if (latest === 'enabled' || !bindings.length || (fixture.files || []).length || calls.some((call) => isGeneration(call.command) || isMutation(call))) {
- problems.push('Custom API refusal must have a blocked gate and zero generation or mutations');
+ if (call && result?.ok === true && uploadResultIdentityMatches(flags, result)) {
+ producedConfigs.set(pathKey(stage.afterConfig), { pageId: result.pageId, appId: result.appId, env: flags.env });
}
- if (!/\bhalt(?:ed)?\b|\bneeds_input\b/i.test(fixture.workflowLog || '')) problems.push('Custom API gate refusal did not surface a halt');
}
- return problems;
+ return { beforeByStage, verifiedBefore, problems };
}
+// The Phase 5 rule of both layers. Custom API support has no feature flag any more, so nothing here reads a `custom-api` probe: a recorded
+// one (an older run made it) is neither required nor refused.
+const gradeCustomApi = (fixture) => gradeEvidence(customApiProblems, fixture);
+
function parameterMatches(value, kind, prefix) {
const literal = literalString(value);
const identifier = /^[\w$]+$/.test(value) ? value : null;
@@ -118,7 +150,7 @@ function parameterMatches(value, kind, prefix) {
function existingRecordId(value, prefix, call) {
if (literalString(value) !== null) return false;
return (/^[\w$]+$/.test(value) && parameterMatches(value, 'Guid', prefix))
- || Boolean(call && stringRecordMemberIsInput(call.mask, call.scopes, value, call.start));
+ || Boolean(call && stringRecordMemberIsInput(call.mask, call.scopes, value, call.start, call.code));
}
function lookupParameterProblems(parameters, lookups, operation, prefix, call) {
@@ -144,7 +176,12 @@ function lookupParameterProblems(parameters, lookups, operation, prefix, call) {
return problems;
}
-function runtimeProblems(code, bindings, declaredOutputs, lookupMetadata) {
+// `authoredBuiltIns`: the names of the built-in operations this stage adds or replaces. Only those are held to the catalogue's contract — a Function
+// with no input and no target, its outputs the catalogue's. Every other entry keeps the contract it declares: a Custom API, and a built-in the page
+// already held, a legacy or contradictory one included — an unrelated edit is no permission to reinterpret a preserved call (download and rebuild
+// warn about such an entry instead). A legacy entry may omit `isFunction`, which the runtime enforces only when it is a real boolean, so an omitted
+// kind constrains neither method; omitted `parameterKinds` declare no input.
+function runtimeProblems(code, bindings, declaredOutputs, lookupMetadata, authoredBuiltIns = new Set()) {
const problems = pageStructureProblems(code);
const calls = actionCalls(code);
const known = new Map(bindings.map((binding) => [binding.name, binding]));
@@ -154,12 +191,16 @@ function runtimeProblems(code, bindings, declaredOutputs, lookupMetadata) {
const binding = known.get(name);
if (!binding) { problems.push(`runtime calls unbound or undiscovered Custom API ${name || '(dynamic name)'}`); continue; }
used.add(name);
- if (call.method !== (binding.isFunction ? 'executeFunction' : 'executeAction')) problems.push(`${name}: runtime method disagrees with discovered Action/Function kind`);
+ const canonical = authoredBuiltIns.has(name);
+ const kinds = canonical ? {} : (binding.parameterKinds || {});
+ const isFunction = canonical ? true : binding.isFunction;
+ const isAction = typeof isFunction === 'boolean' ? !isFunction : call.method === 'executeAction';
+ if (typeof isFunction === 'boolean' && call.method !== (isFunction ? 'executeFunction' : 'executeAction')) problems.push(`${name}: runtime method disagrees with discovered Action/Function kind`);
const prefix = code.slice(call.scope.start, call.start);
const prefixMask = call.mask.slice(call.scope.start, call.start);
const post = code.slice(call.end + 1, call.scope.end);
const postMask = call.mask.slice(call.end + 1, call.scope.end);
- if (!receiverIsDataApi(call.mask, call.scopes, call.receiver, call.start)) {
+ if (!receiverIsDataApi(call.mask, call.scopes, call.receiver, call.start, call.code)) {
problems.push(`${name}: ${call.method} is called on ${call.receiver || 'an expression'}, which is not the page's dataApi prop`);
}
// The presence check must test the same object the call uses; a check on another object proves nothing.
@@ -171,16 +212,16 @@ function runtimeProblems(code, bindings, declaredOutputs, lookupMetadata) {
// Sparse declared kinds do not enumerate lookup inputs. Use discovery-only metadata to allow
// their names and enforce required lookups without persisting structural kinds in the binding.
const lookups = lookupMetadata.get(name) || {};
- const allowed = new Set([...Object.keys(binding.parameterKinds), ...Object.keys(lookups)]);
+ const allowed = new Set([...Object.keys(kinds), ...Object.keys(lookups)]);
if ([...parameters.keys()].some((parameter) => !allowed.has(parameter))
- || Object.keys(binding.parameterKinds).some((parameter) => !parameters.has(parameter))) {
+ || Object.keys(kinds).some((parameter) => !parameters.has(parameter))) {
problems.push(`${name}: runtime parameter names differ from the declared kinds and discovered lookups`);
}
- for (const [parameter, kind] of Object.entries(binding.parameterKinds)) {
+ for (const [parameter, kind] of Object.entries(kinds)) {
if (!parameterMatches(parameters.get(parameter) || '', kind, prefix)) problems.push(`${name}.${parameter}: runtime value does not match ${kind}`);
}
problems.push(...lookupParameterProblems(parameters, lookups, name, prefix, call));
- if (binding.boundEntityLogicalName) {
+ if (binding.boundEntityLogicalName && !canonical) {
if (!call.fields.has('boundTo')) problems.push(`${name}: entity-bound operation omits boundTo`);
else {
const bound = objectFields(call.fields.get('boundTo'));
@@ -193,7 +234,8 @@ function runtimeProblems(code, bindings, declaredOutputs, lookupMetadata) {
} else if (call.fields.has('boundTo')) problems.push(`${name}: global operation must omit boundTo`);
const result = call.resultName;
- const ok = new RegExp(`\\bif\\s*\\(\\s*(?:!\\s*${result}\\.ok|${result}\\.ok\\s*===?\\s*false)\\s*\\)\\s*\\{[^}]*\\breturn\\b[^}]*\\}`);
+ // `res.ok !== true` is the stricter spelling of the same refusal (a built-in call's pattern uses it), so it is accepted beside `!res.ok`; the failure must still return before outputs are read.
+ const ok = new RegExp(`\\bif\\s*\\(\\s*(?:!\\s*${result}\\.ok|${result}\\.ok\\s*===?\\s*false|${result}\\.ok\\s*!==?\\s*true)\\s*\\)\\s*\\{[^}]*\\breturn\\b[^}]*\\}`);
const okMatch = ok.exec(postMask);
const outputsAt = postMask.search(new RegExp(`\\b${result}\\.outputs\\b`));
if (!okMatch || outputsAt < 0 || okMatch.index + okMatch[0].length > outputsAt) problems.push(`${name}: response.ok must refuse before outputs are read`);
@@ -201,8 +243,11 @@ function runtimeProblems(code, bindings, declaredOutputs, lookupMetadata) {
problems.push(`${name}: outputs/error handling must use outputs and sanitized error.message only`);
}
const outputs = [...postMask.matchAll(new RegExp(`\\b${result}\\.outputs(?:\\?\\.)?\\.?([A-Za-z_$][\\w$]*)`, 'g'))].map((entry) => entry[1]);
- if (!Array.isArray(declaredOutputs?.[name]) || outputs.some((output) => !declaredOutputs[name].includes(output))) problems.push(`${name}: runtime reads an undeclared output`);
- if (!binding.isFunction) {
+ // A built-in's response is the catalogue's; a preserved one is read against what the scenario declares for it, when it declares anything.
+ const catalogue = Object.hasOwn(BUILT_IN_OUTPUTS, name) ? BUILT_IN_OUTPUTS[name] : undefined;
+ const readable = canonical ? catalogue : (declaredOutputs?.[name] ?? catalogue);
+ if (!Array.isArray(readable) || outputs.some((output) => !readable.includes(output))) problems.push(`${name}: runtime reads an undeclared output`);
+ if (isAction) {
if (!/\bif\s*\(\s*(?:pending\.current|isSubmitting)(?:\s*\|\|[^)]*)?\)\s*(?:return\b|\{\s*return\b)/.test(prefixMask)
|| !/\bpending\.current\s*=\s*true\b|\bsetIsSubmitting\s*\(\s*true\s*\)/.test(prefixMask)
|| !/\bfinally\b[\s\S]*(?:pending\.current\s*=\s*false\b|setIsSubmitting\s*\(\s*false\s*\))/.test(postMask)) {
@@ -217,11 +262,13 @@ function runtimeProblems(code, bindings, declaredOutputs, lookupMetadata) {
}
function customApiProblems(fixture) {
- const problems = customApiGateProblems(fixture);
+ // A logged command with no recorded result is no evidence at all (workflow-evidence.js).
+ const problems = unassociatedCallProblems(fixture);
if (fixture.manifest?.expectedOutcome === 'refused') return problems;
const contract = fixture.manifest?.customApi;
if (!contract?.stages?.length) return [...problems, 'Custom API lifecycle has no source/config stages'];
- const declared = planBindings(fixture);
+ // The whole desired array: the plan's Custom API rows, then its built-in operation rows (none when the plan has no `## Dataverse Operations` section).
+ const declared = unionBindings(planBindings(fixture), plannedBuiltIns(fixture.genpagePlan) || []);
const calls = workflowCalls(fixture);
const discovered = new Map();
const lookupMetadata = new Map();
@@ -233,53 +280,21 @@ function customApiProblems(fixture) {
lookupMetadata.set(entry.name, discoveredLookupParameters(entry));
}
}
- const beforeByStage = new Map();
- const verifiedBefore = new Set();
- const producedConfigs = new Map();
- for (const stage of contract.stages) {
- const uploads = calls.filter((entry) => entry.id === stage.upload && isUpload(entry.command));
- const call = uploads.length === 1 ? uploads[0] : null;
- const flags = call ? commandInfo(call).flags : {};
- const result = call ? resultObject(call) : null;
- if (stage.beforeConfig) {
- const config = artifactJson(fixture, stage.beforeConfig);
- const before = config.actionBindings === undefined ? [] : config.actionBindings;
- desiredBindings(before, undefined, 'name');
- for (const binding of before) projectBinding(binding);
- beforeByStage.set(stage, before);
- const identityProblems = [];
- if (!call || !flags['page-id'] || result?.ok !== true || !uploadResultIdentityMatches(flags, result)) {
- identityProblems.push(`${stage.id}: before-config preservation requires an unambiguous existing update target`);
- }
- const rows = fixture.manifest?.uploads;
- if (rows !== undefined) {
- const associated = Array.isArray(rows) ? rows.filter((row) => row.event === stage.upload) : [];
- if (associated.length !== 1) {
- identityProblems.push(`${stage.id}: before-page identity evidence has no unique upload association`);
- } else if (call) {
- identityProblems.push(...beforePageIdentityProblems(fixture, associated[0], call, stage.beforeConfig, stage.afterConfig));
- }
- } else {
- // A prior successful lifecycle stage can associate its exact read-back snapshot with its
- // result identity. A first-stage arbitrary artifact path cannot establish page ownership.
- const prior = producedConfigs.get(pathKey(stage.beforeConfig));
- if (!prior || prior.pageId !== flags['page-id'] || prior.appId !== flags['app-id']) {
- identityProblems.push(`${stage.id}: before-config lacks same-page/app identity provenance`);
- } else if (prior.env !== undefined && !sameRecordedEnvironment(prior.env, flags.env)) {
- identityProblems.push(`${stage.id}: before-config environment differs from the update target`);
- }
- }
- problems.push(...identityProblems);
- if (!identityProblems.length) verifiedBefore.add(stage);
- }
- if (call && result?.ok === true && uploadResultIdentityMatches(flags, result)) {
- producedConfigs.set(pathKey(stage.afterConfig), { pageId: result.pageId, appId: result.appId, env: flags.env });
- }
- }
+ // A built-in row's fresh evidence is the catalogue listing, projected exactly as the builder must project it (toActionBinding).
+ const listed = listedBuiltIns(calls);
+ problems.push(...listed.problems);
+ for (const [name, row] of listed.offered) discovered.set(name, row);
+ const project = projectExisting;
+ const authoring = contract.stages
+ .filter((stage) => (stage.beforeConfig ? (stage.change?.add || []).some(isBuiltInBinding) : partitionBindings(declared).builtIns.length > 0))
+ .map((stage) => stage.upload);
+ problems.push(...builtInGateProblems(calls, authoring));
+ const { beforeByStage, verifiedBefore, problems: identityProblems } = beforeConfigEvidence(fixture, contract.stages, calls);
+ problems.push(...identityProblems);
const beforeBindings = [...verifiedBefore].flatMap((stage) => beforeByStage.get(stage));
for (const binding of declared) {
const fresh = isDeepStrictEqual(discovered.get(binding.name), binding);
- const existing = beforeBindings.some((before) => isDeepStrictEqual(projectBinding(before), binding));
+ const existing = beforeBindings.some((before) => isDeepStrictEqual(project(before), binding));
if (!fresh && !existing) problems.push(`${binding.name}: plan kind, bound entity or parameter kinds do not match discovery or unchanged before-config evidence`);
}
let previousId = null;
@@ -294,17 +309,24 @@ function customApiProblems(fixture) {
previousId = result?.pageId;
const before = stage.beforeConfig ? beforeByStage.get(stage) : declared;
const desired = stage.beforeConfig ? desiredBindings(before, stage.change, 'name') : declared;
+ if (stage.beforeConfig && stage.change?.clear === true) {
+ problems.push(...clearConfirmationProblems({
+ workflowLog: fixture.workflowLog, uploads: calls.filter((entry) => isUpload(entry.command)), call, pageId: flags['page-id'], before, label: stage.id,
+ }));
+ }
if (stage.beforeConfig && stage.change === undefined && flags.actions) problems.push(`${stage.id}: unchanged APIs must omit --actions`);
if (!stage.beforeConfig || stage.change !== undefined) {
if (!flags.actions || pathKey(flags.actions) !== pathKey(stage.actions) || !sameBindings(artifactJson(fixture, flags.actions), desired, 'name')) {
problems.push(`${stage.id}: actions file must be the full desired bare array, including explicit [] to clear`);
+ } else if (authoring.includes(stage.upload)) {
+ problems.push(...unionOrderProblems(artifactJson(fixture, flags.actions), stage.id));
}
}
const after = artifactJson(fixture, stage.afterConfig).actionBindings;
if (!sameBindings(after, desired, 'name')) problems.push(`${stage.id}: API config read-back loses preservation or explicit-clear intent`);
const authoredNames = new Set((stage.change?.add || []).map((binding) => binding.name));
for (const binding of desired) {
- const projected = projectBinding(binding);
+ const projected = project(binding);
const fresh = isDeepStrictEqual(discovered.get(binding.name), projected);
// Only an exact unchanged stage-before entry has preservation provenance. An explicit
// addition/replacement still needs eligible discovery, even when its name already existed.
@@ -315,11 +337,18 @@ function customApiProblems(fixture) {
const code = artifactText(fixture, stage.source);
const write = calls.slice(0, uploadIndex).filter((entry) => /^Write\s+/.test(entry.command) && fileName(entry.command.slice(6)) === stage.target).at(-1);
if (!write || artifactText(fixture, write.artifact) !== code) problems.push(`${stage.id}: uploaded API source is not the actual preceding generated snapshot`);
- problems.push(...runtimeProblems(code, desired, contract.outputs, lookupMetadata));
+ // The built-ins this stage authors are held to the catalogue's call contract and the generated pattern; a preserved call is kept as it was written.
+ const authoredBuiltIns = !authoring.includes(stage.upload) ? []
+ : (stage.beforeConfig ? (stage.change?.add || []).filter(isBuiltInBinding) : partitionBindings(desired).builtIns).map((binding) => binding.name);
+ problems.push(...runtimeProblems(code, desired, contract.outputs, lookupMetadata, new Set(authoredBuiltIns)));
+ if (authoredBuiltIns.length) problems.push(...builtInRuntimeProblems(code, authoredBuiltIns));
}
const last = contract.stages.at(-1);
if (artifactText(fixture, last.target) !== artifactText(fixture, last.source)) problems.push('final API TSX differs from the final lifecycle stage');
return problems;
}
-module.exports = { customApiProblems, customApiGateProblems };
+// runtimeProblems is exported for the tests that grade whole reference pages — the teaching documents' Custom API pages
+// (tests/page-error-teaching.test.js) and the boundary wrapper's proof (tests/source-evidence.test.js) — with exactly the
+// check the lifecycle scorer applies.
+module.exports = { customApiProblems, gradeCustomApi, runtimeProblems };
diff --git a/evals/model-apps/genpage/lib/page-checks.js b/evals/model-apps/genpage/lib/page-checks.js
index eb28918c7..3aa2f00cf 100644
--- a/evals/model-apps/genpage/lib/page-checks.js
+++ b/evals/model-apps/genpage/lib/page-checks.js
@@ -17,7 +17,7 @@
// label never counts as code, and code is never taken for text. What each one does NOT judge is said
// beside it; a person still judges the rest in the Layer 3 rubric.
-const { sourceView, jsxElements, jsxTextRuns, declarationSource, matchingClose } = require('./tsx-structure.js');
+const { sourceView, jsxElements, jsxTextRuns, declarationSource, matchingClose, withoutComments } = require('./tsx-structure.js');
const { runtimeEnums } = require('./expectation-evidence.js');
const { escapeRe } = require('./source-evidence.js');
@@ -366,33 +366,53 @@ function reviewSummaryProblems(content) {
// (`label={translate('title')}`) is; the same goes for the children of a label element (childrenShowText).
// A spread (`{...props}`) may carry a label the page does not show, so it is not reported. A hidden input
// (`type="hidden"`) is no field. Returns null when the page has no form control.
-// Two known limits, left as they are on purpose (this grades eval evidence; it is no gate a page must pass): an
-// empty value that also holds a comment (`{/* hidden */ null}`, `label={/* none */ ''}`) counts as a label, because
-// STATIC_EMPTY is tested on the source with its comments; and a label element whose text is only character references
-// (`&#84;&#105;&#116;&#108;&#101;`) is not counted, because jsxTextRuns reads a character reference as a space.
+// A comment is no value, so `{/* hidden */ null}` and `label={/* none */ ''}` are no label either (staticallyEmpty);
+// and a character reference is the character it stands for (shownText), so a label written `&#84;&#105;&#116;&#108;&#101;`
+// or `&amp;` names its control, while one of `&nbsp;` or `&#32;` alone does not.
const STATIC_EMPTY = /^\s*(?:(['"`])\s*\1|null|undefined|false)\s*$/;
-const names = (attr) => Boolean(attr) && ((attr.kind === 'string' && attr.value.trim() !== '')
- || (attr.kind === 'expression' && attr.value.trim() !== '' && !STATIC_EMPTY.test(attr.value)));
+// Whether an expression can show nothing once its comments are left out: it is blank, or only '', "", ``, null,
+// undefined or false. The comments are the ones the plugin's lexer finds (withoutComments), so `'/* x */'` stays a string.
+const staticallyEmpty = (expression) => {
+ const bare = withoutComments(expression);
+ return bare.trim() === '' || STATIC_EMPTY.test(bare);
+};
+// JSX text, or a JSX attribute's string, as it is shown, read only to ask whether it shows anything. JSX decodes the
+// character references in both (https://react.github.io/jsx/#sec-jsx-string), as TypeScript and Babel do:
+// `&#<decimal>;` and `&#x<hex>;` (a lower-case x) up to 0x10FFFF, and the HTML 4 names. A reference is text unless
+// the character it stands for is white space: `&#84;` and `&#x54;` are a "T" and `&amp;` an "&", while `&#32;` shows
+// nothing, nor do `&nbsp;`, `&ensp;`, `&emsp;` and `&thinsp;`, the only HTML 4 names of white space. What JSX does not
+// decode is shown as written (`&nosuch;`, `&#X54;`), so it is text. jsxTextRuns reads every reference as a space
+// instead: the translate check counts no reference as a letter, but a label written in references would read as blank.
+const SPACE_REFERENCES = new Set(['nbsp', 'ensp', 'emsp', 'thinsp']);
+const shownText = (text) => String(text).replace(/&(?:#(\d+)|#x([\da-fA-F]+)|([A-Za-z][A-Za-z\d]*));/g, (reference, decimal, hex, name) => {
+ if (name !== undefined) return SPACE_REFERENCES.has(name) ? ' ' : reference;
+ const codePoint = decimal !== undefined ? Number(decimal) : Number.parseInt(hex, 16);
+ return codePoint <= 0x10ffff ? String.fromCodePoint(codePoint) : reference;
+});
+const names = (attr) => Boolean(attr) && ((attr.kind === 'string' && shownText(attr.value).trim() !== '')
+ || (attr.kind === 'expression' && !staticallyEmpty(attr.value)));
-// Whether an element's children can show any text: a run of JSX text that is not blank, or an expression
-// container that is not statically empty, at any depth of the markup inside it. `{null}`, `{''}`,
-// `{undefined}`, `{false}` and a container holding only a comment (`{/* … */}`, blank in the code view)
-// show nothing, and the tags and attributes of nested elements are no text:
+// Whether an element's children can show any text: a run of JSX text that is not blank once its character
+// references are read (shownText), or an expression container that is not statically empty (staticallyEmpty), at
+// any depth of the markup inside it. `{null}`, `{''}`, `{undefined}`, `{false}`, a container holding only a comment
+// (`{/* … */}`) and one of them beside a comment (`{/* hidden */ null}`) show nothing, and the tags and attributes
+// of nested elements are no text:
// <label htmlFor="t">Title</label> shows text
+// <label htmlFor="t">&#84;&#105;&#116;&#108;&#101;</label> shows text ("Title")
// <label htmlFor="t">{translate('title')}</label> may show text (a computed value is not judged)
// <label htmlFor="t"><span>{null}</span></label> shows nothing
function childrenShowText(content, element) {
const { src, code } = sourceView(content);
const from = element.childrenStart;
const to = element.childrenEnd;
- if (jsxTextRuns(content).some((run) => run.start >= from && run.end <= to && run.text.trim() !== '')) return true;
+ if (jsxTextRuns(content).some((run) => run.start >= from && run.end <= to && shownText(src.slice(run.start, run.end)).trim() !== '')) return true;
const nested = jsxElements(content).filter((e) => e.start >= from && e.start < to);
const inTag = (i) => nested.some((e) => (i >= e.start && i < e.openEnd) || (!e.selfClosing && i >= e.childrenEnd && i < e.end));
for (let i = from; i < to; i += 1) {
if (code[i] !== '{' || inTag(i)) continue;
const close = matchingClose(code, i);
if (close < 0 || close > to) return true;
- if (code.slice(i + 1, close).trim() !== '' && !STATIC_EMPTY.test(src.slice(i + 1, close))) return true;
+ if (!staticallyEmpty(src.slice(i + 1, close))) return true;
i = close;
}
return false;
diff --git a/evals/model-apps/genpage/lib/page-error-canonical.js b/evals/model-apps/genpage/lib/page-error-canonical.js
new file mode 100644
index 000000000..9db85b71a
--- /dev/null
+++ b/evals/model-apps/genpage/lib/page-error-canonical.js
@@ -0,0 +1,140 @@
+'use strict';
+// The canonical page error block of references/rules.md ("Missing Error Handling"), read once and kept as canonical
+// lines — comments blanked, each line trimmed, empty lines dropped, line breaks kept: here PageErrorBoundary and its
+// documented `extends Component<…>` form and telemetry hand-off. The boundary-wrapper proof of source-evidence.js compares
+// a page's boundary with these: a wrapper whose boundary is not this class may hand PageBody anything, so it must not prove
+// where the page's dataApi comes from. polymorphic-lookup-contract.js reads its canonical normalizer with the same line and
+// top-level-function readers. Whether a page's failures reach its reporter is not graded (EVAL_GUIDE.md).
+//
+// This module requires nothing from the evaluator modules (source-evidence.js requires it), so either can load first.
+
+const fs = require('node:fs');
+const path = require('node:path');
+const { blankNonCodePreservingTemplateExpressions, commentRanges } = require('../../../../plugins/model-apps/scripts/lib/source-literals.js');
+
+const RULES_PATH = path.join(__dirname, '..', '..', '..', '..', 'plugins', 'model-apps', 'references', 'rules.md');
+const REPORTER = 'reportPageError';
+const BOUNDARY = 'PageErrorBoundary';
+
+// A source's significant lines: comments blanked (the lexer's own ranges, so a `//` inside a string survives), each
+// line trimmed, empty lines dropped. Line breaks are KEPT: they decide automatic semicolon insertion (`return\nview`).
+function canonicalLines(text) {
+ const chars = String(text).replace(/\r\n/g, '\n').split('');
+ for (const { start, end } of commentRanges(chars.join(''))) for (let i = start; i < end; i += 1) if (chars[i] !== '\n') chars[i] = ' ';
+ return chars.join('').split('\n').map((line) => line.trim()).filter(Boolean);
+}
+
+// The index of the bracket closing the one at `open` in a masked source (strings, comments and JSX text blanked).
+function closeOf(mask, open) {
+ const pairs = { '(': ')', '{': '}', '[': ']' };
+ const stack = [];
+ for (let i = open; i < mask.length; i += 1) {
+ if (pairs[mask[i]]) stack.push(pairs[mask[i]]);
+ else if (')}]'.includes(mask[i])) {
+ if (stack.pop() !== mask[i]) throw new Error('unbalanced source');
+ if (!stack.length) return i;
+ }
+ }
+ throw new Error('unbalanced source');
+}
+
+// How many brackets are open at `at`: 0 at the top level of the module.
+function depthAt(mask, at) {
+ let depth = 0;
+ for (let i = 0; i < at; i += 1) {
+ if ('({['.includes(mask[i])) depth += 1;
+ else if (')}]'.includes(mask[i])) depth -= 1;
+ }
+ return depth;
+}
+
+const escapeRe = (text) => String(text).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+
+// `function <name>(…) … { … }` declared at the top level of `code`, as [start, end) offsets; null when absent.
+function topLevelFunction(code, mask, name) {
+ for (const match of mask.matchAll(new RegExp(`\\bfunction\\s+${escapeRe(name)}\\s*\\(`, 'g'))) {
+ if (depthAt(mask, match.index) !== 0) continue;
+ const paramsOpen = match.index + match[0].length - 1;
+ const paramsEnd = closeOf(mask, paramsOpen);
+ const bodyOpen = mask.indexOf('{', paramsEnd);
+ if (bodyOpen < 0) return null;
+ return { start: match.index, bodyOpen, end: closeOf(mask, bodyOpen) + 1 };
+ }
+ return null;
+}
+
+// `class <name> extends …<…> { … }` declared at the top level of `code`, as [start, end) offsets; null when absent.
+function topLevelClass(code, mask, name) {
+ for (const match of mask.matchAll(new RegExp(`\\bclass\\s+${escapeRe(name)}\\s+extends\\b`, 'g'))) {
+ if (depthAt(mask, match.index) !== 0) continue;
+ // The body opens at the first `{` after the closing `>` of the base's type arguments.
+ let i = match.index + match[0].length;
+ let angle = 0;
+ for (; i < mask.length; i += 1) {
+ if (mask[i] === '<') angle += 1;
+ else if (mask[i] === '>' && angle > 0) angle -= 1;
+ else if (mask[i] === '{' && angle === 0) break;
+ else if (mask[i] === '{') i = closeOf(mask, i);
+ }
+ if (i >= mask.length) return null;
+ return { start: match.index, bodyOpen: i, end: closeOf(mask, i) + 1 };
+ }
+ return null;
+}
+
+let blocks = null;
+function ruleBlocks() {
+ if (blocks) return blocks;
+ const rules = fs.readFileSync(RULES_PATH, 'utf8').replace(/\r\n/g, '\n');
+ const start = rules.indexOf('\n### 2. Missing Error Handling\n');
+ if (start < 0) throw new Error('references/rules.md has no "Missing Error Handling" section');
+ const next = rules.indexOf('\n### ', start + 10);
+ const section = rules.slice(start, next < 0 ? rules.length : next);
+ const all = [...section.matchAll(/```tsx\n([\s\S]*?)\n```/g)].map((match) => match[1]);
+ const foundation = all.find((block) => new RegExp(`\\bfunction ${REPORTER}\\(`).test(block));
+ if (!foundation) throw new Error('references/rules.md does not publish the canonical page error block');
+ blocks = { foundation, mask: blankNonCodePreservingTemplateExpressions(foundation) };
+ return blocks;
+}
+
+let boundary = null;
+// PageErrorBoundary: every documented form — `React.Component`/`React.ReactNode` or `Component`/`ReactNode` (a page that
+// imports React by name), and the render-crash report with or without the telemetry hand-off.
+function canonicalBoundaries() {
+ if (boundary) return boundary;
+ const { foundation, mask } = ruleBlocks();
+ const range = topLevelClass(foundation, mask, BOUNDARY);
+ const lines = canonicalLines(foundation.slice(range.start, range.end));
+ const report = "reportPageError(PAGE_NAME, 'render', undefined, error, 'render');";
+ if (!lines.includes(report)) throw new Error('references/rules.md PageErrorBoundary does not report the render crash');
+ const telemetry = lines.map((line) => (line === report ? "reportPageError(PAGE_NAME, 'render', undefined, error, 'render', undefined, this.props.appInsights);" : line));
+ const named = (text) => text.replace(/\bReact\.Component\b/g, 'Component').replace(/\bReact\.ReactNode\b/g, 'ReactNode');
+ boundary = [lines, telemetry].flatMap((form) => [form.join('\n'), named(form.join('\n'))]);
+ return boundary;
+}
+
+// The boundary-wrapper proof (source-evidence.js) holds only a masked source — strings and comments blanked — so it
+// compares the page's boundary with the documented forms masked the same way: the same code, string contents aside (no
+// string decides what the boundary hands its child). The page's PageErrorBoundary must be one top-level class equal to a
+// documented form — one getDerivedStateFromError, one componentDidCatch, one render that returns `this.props.children`,
+// nothing added (a second `render()` overrides the first) — and React and Component must not be names the page binds
+// itself. Returns the class range, or null: a wrapper whose boundary is anything else may hand PageBody any object.
+// Runs of blanks collapse to one, so a string of another length (a blanked `'error.render'`) compares equal.
+const maskedLines = (text) => String(text).split('\n').map((line) => line.trim().replace(/\s+/g, ' ')).filter(Boolean).join('\n');
+let boundaryMasks = null;
+function transparentBoundary(mask) {
+ if (!boundaryMasks) boundaryMasks = canonicalBoundaries().map((form) => maskedLines(blankNonCodePreservingTemplateExpressions(form)));
+ const declarations = mask.match(new RegExp(`\\b(?:function|class|const|let|var)\\s+${BOUNDARY}(?![\\w$])`, 'g')) || [];
+ if (declarations.length !== 1) return null;
+ if (/\b(?:function|class|const|let|var)\s+(?:React|Component)(?![\w$])/.test(mask)) return null;
+ if (/(?<![\w$])(?:React\s*\.\s*)?Component\s*=(?![=>])|(?<![\w$.])React\s*=(?![=>])/.test(mask)) return null;
+ let range;
+ try { range = topLevelClass(mask, mask, BOUNDARY); } catch { return null; }
+ if (!range || !boundaryMasks.includes(maskedLines(mask.slice(range.start, range.end)))) return null;
+ return range;
+}
+
+module.exports = {
+ canonicalLines, closeOf, depthAt, topLevelFunction, topLevelClass, canonicalBoundaries,
+ transparentBoundary,
+};
diff --git a/evals/model-apps/genpage/lib/plan-evidence.js b/evals/model-apps/genpage/lib/plan-evidence.js
index 6d8faa1d1..1bb7e20c3 100644
--- a/evals/model-apps/genpage/lib/plan-evidence.js
+++ b/evals/model-apps/genpage/lib/plan-evidence.js
@@ -1,44 +1,8 @@
'use strict';
-
-function planSection(plan, heading) {
- if (!plan) return null;
- const lines = plan.split('\n');
- const escaped = heading.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
- const startRe = new RegExp(`^##\\s+${escaped}\\s*$`, 'i');
- let i = 0;
- while (i < lines.length && !startRe.test(lines[i])) i++;
- if (i >= lines.length) return null;
- i++;
- const out = [];
- while (i < lines.length && !/^##\s/.test(lines[i])) out.push(lines[i++]);
- return out.join('\n').trim();
-}
-
-function findMarkdownTable(sectionText, requiredColumns) {
- const lines = sectionText.split(/\r?\n/);
- for (let i = 0; i < lines.length; i++) {
- if (!/^\s*\|.*\|\s*$/.test(lines[i])) continue;
- const headers = lines[i].split('|').slice(1, -1).map((header) => header.trim().toLowerCase());
- if (requiredColumns.every((column) => headers.includes(column.toLowerCase()))) {
- return { lineIndex: i, headers, lines: lines.slice(i) };
- }
- }
- return null;
-}
-
-function parseMarkdownRows(sectionText, requiredColumns) {
- const table = findMarkdownTable(sectionText, requiredColumns);
- if (!table) return [];
- const rows = [];
- for (const line of table.lines.slice(2)) {
- if (!/^\s*\|.*\|\s*$/.test(line)) break;
- const cells = line.split('|').slice(1, -1).map((cell) => cell.trim());
- if (cells.length === 0 || cells.every((cell) => cell === '')) continue;
- const row = {};
- for (let i = 0; i < table.headers.length; i++) row[table.headers[i]] = cells[i] || '';
- rows.push(row);
- }
- return rows;
-}
+// The plan-section primitives (planSection, findMarkdownTable, parseMarkdownRows) moved into the plugin unchanged —
+// plugins/model-apps/scripts/lib/plan-sections.js documents the shapes they read — because the plugin's own plan readers use
+// them and shipped code must not import an eval module. Re-exported here, the very same functions, so every evaluator keeps
+// its import path.
+const { planSection, findMarkdownTable, parseMarkdownRows } = require('../../../../plugins/model-apps/scripts/lib/plan-sections.js');
module.exports = { planSection, findMarkdownTable, parseMarkdownRows };
diff --git a/evals/model-apps/genpage/lib/polymorphic-lookup-contract.js b/evals/model-apps/genpage/lib/polymorphic-lookup-contract.js
new file mode 100644
index 000000000..912bd76ce
--- /dev/null
+++ b/evals/model-apps/genpage/lib/polymorphic-lookup-contract.js
@@ -0,0 +1,76 @@
+'use strict';
+// The canonical lookup normalizer of references/rules.md "Lookup references" (Critical Rule 23), read once, and the check that a
+// page's copy of it is that one: declared once at the top level, line for line (comments, indentation and blank lines aside), with
+// its two patterns. tests/polymorphic-lookup-contract.test.js checks copies against it and runs the published block itself on
+// fixture 26's synthetic customer values (lookup-rows.json).
+//
+// What a page then DOES with a lookup — reads, filters, retrieves, navigation and writes through the normalized pair — is not
+// graded. The closed grammar that graded it was withdrawn: its proofs that a reference's table was checked (a guard before the
+// use) and that the normalized pair stayed unchanged could each be satisfied by a page that opens a contact as an account, and a
+// check that can certify such a page is worse than none. evals/model-apps/genpage/EVAL_GUIDE.md says so.
+
+const fs = require('node:fs');
+const path = require('node:path');
+const { blankNonCodePreservingTemplateExpressions } = require('../../../../plugins/model-apps/scripts/lib/source-literals.js');
+const { canonicalLines, topLevelFunction } = require('./page-error-canonical.js');
+
+const RULES_PATH = path.join(__dirname, '..', '..', '..', '..', 'plugins', 'model-apps', 'references', 'rules.md');
+const HEADING = '### Lookup references (Customer, Owner, Regarding and every other lookup)';
+const NORMALIZER = 'normalizeLookupReference';
+const PATTERNS = ['LOOKUP_GUID', 'LOOKUP_QUALIFIED'];
+
+let canonical = null;
+// The canonical normalizer from rules.md: { fn, patterns: Map(name → statement) }, each as its canonical lines.
+function canonicalNormalizer() {
+ if (canonical) return canonical;
+ const rules = fs.readFileSync(RULES_PATH, 'utf8').replace(/\r\n/g, '\n');
+ const start = rules.indexOf(`\n${HEADING}\n`);
+ if (start < 0) throw new Error('references/rules.md has no "Lookup references" section');
+ const rest = rules.slice(start + HEADING.length + 2);
+ const next = rest.search(/\n#{2,3} /);
+ const section = next < 0 ? rest : rest.slice(0, next);
+ const block = [...section.matchAll(/```typescript\n([\s\S]*?)\n```/g)].map((match) => match[1]).find((text) => text.includes(`function ${NORMALIZER}(`));
+ if (!block) throw new Error('references/rules.md does not publish the canonical lookup normalizer');
+ const mask = blankNonCodePreservingTemplateExpressions(block);
+ const range = topLevelFunction(block, mask, NORMALIZER);
+ const patterns = new Map();
+ for (const name of PATTERNS) {
+ const declared = new RegExp(`^const ${name} = .*;$`, 'm').exec(block);
+ if (!declared) throw new Error(`references/rules.md's normalizer block has no ${name}`);
+ patterns.set(name, declared[0].trim());
+ }
+ canonical = { fn: canonicalLines(block.slice(range.start, range.end)).join('\n'), patterns };
+ return canonical;
+}
+
+// How many brackets are open at `at` (0 at the module's top level).
+function depthAt(mask, at) {
+ let depth = 0;
+ for (let i = 0; i < at; i += 1) {
+ if ('({['.includes(mask[i])) depth += 1;
+ else if (')}]'.includes(mask[i])) depth -= 1;
+ }
+ return depth;
+}
+
+// The page's normalizer is the canonical one, declared once at the top level with its two patterns.
+function normalizerProblems(code) {
+ const { fn, patterns } = canonicalNormalizer();
+ const mask = blankNonCodePreservingTemplateExpressions(code);
+ const problems = [];
+ const declarations = [...mask.matchAll(new RegExp(`\\bfunction\\s+${NORMALIZER}\\s*\\(`, 'g'))];
+ const other = new RegExp(`\\b(?:const|let|var)\\s+${NORMALIZER}\\b`).test(mask);
+ if (declarations.length !== 1 || other) return [`the page must declare ${NORMALIZER} once, as the top-level function references/rules.md publishes`];
+ const range = topLevelFunction(code, mask, NORMALIZER);
+ if (!range) return [`${NORMALIZER} must be a top-level function`];
+ if (canonicalLines(code.slice(range.start, range.end)).join('\n') !== fn) problems.push(`${NORMALIZER} is not the canonical normalizer — copy it unchanged from references/rules.md "Lookup references"`);
+ for (const [name, statement] of patterns) {
+ const found = [...mask.matchAll(new RegExp(`\\b(?:const|let|var)\\s+${name}\\b`, 'g'))];
+ const line = found.length === 1 && depthAt(mask, found[0].index) === 0
+ ? code.slice(found[0].index, code.indexOf('\n', found[0].index) < 0 ? code.length : code.indexOf('\n', found[0].index)).trim() : null;
+ if (line !== statement) problems.push(`${name} is not the canonical pattern — copy it unchanged from references/rules.md "Lookup references"`);
+ }
+ return problems;
+}
+
+module.exports = { normalizerProblems, canonicalNormalizer };
diff --git a/evals/model-apps/genpage/lib/reporter.js b/evals/model-apps/genpage/lib/reporter.js
index 38c11173c..9a2fea076 100644
--- a/evals/model-apps/genpage/lib/reporter.js
+++ b/evals/model-apps/genpage/lib/reporter.js
@@ -18,10 +18,19 @@
// ...
// 1..N
//
+// A skip grades nothing, so a fixture passes only when at least one assertion was graded and none failed. A fixture with no graded
+// assertion — every one skipped, or none at all — is UNSCORED: its line takes TAP's skip directive,
+// ok 3 - fixture-3-kept-page # SKIP no expectation graded
+// and it is counted apart from the passed fixtures, so the summary never credits ungraded work as a pass. An unscored fixture does not fail
+// the run (the exit code is non-zero only for a failed fixture).
+//
// Failure diagnostics currently include only `reason:`. Additional fields
// (e.g., `file:`) can be added by extending `assertion()` if needed.
//
-// Aggregate result emitted at the end as `# tests N`, `# pass X`, etc.
+// Aggregate result emitted at the end as `# tests N`, `# pass X`, etc. Release and test tooling parse the
+// `# fixtures N (pass P, fail F)` line, so it keeps that exact form and stays the only line that starts with
+// `# fixtures`; unscored fixtures get one line of their own, `# unscored fixtures U`, written only when U > 0 — a
+// run without one prints exactly what it always printed.
class TapReporter {
constructor(stream = process.stdout) {
@@ -32,6 +41,7 @@ class TapReporter {
this.totalSkip = 0;
this.fixturePass = 0;
this.fixtureFail = 0;
+ this.fixtureUnscored = 0;
this.fixtureIndex = 0;
this.totalFixtures = 0;
}
@@ -77,9 +87,12 @@ class TapReporter {
if (this._currentFail) {
this.fixtureFail += 1;
this.write(`not ok ${this.fixtureIndex} - ${this._currentName}`);
- } else {
+ } else if (this._currentAssertions.some(({ result }) => result.status === 'pass')) {
this.fixturePass += 1;
this.write(`ok ${this.fixtureIndex} - ${this._currentName}`);
+ } else {
+ this.fixtureUnscored += 1;
+ this.write(`ok ${this.fixtureIndex} - ${this._currentName} # SKIP no expectation graded`);
}
this._currentName = null;
this._currentAssertions = [];
@@ -92,6 +105,7 @@ class TapReporter {
this.write(`# fail ${this.totalFail}`);
this.write(`# skip ${this.totalSkip}`);
this.write(`# fixtures ${this.totalFixtures} (pass ${this.fixturePass}, fail ${this.fixtureFail})`);
+ if (this.fixtureUnscored > 0) this.write(`# unscored fixtures ${this.fixtureUnscored}`);
}
get exitCode() {
diff --git a/evals/model-apps/genpage/lib/source-evidence.js b/evals/model-apps/genpage/lib/source-evidence.js
index 16f7723a4..479129091 100644
--- a/evals/model-apps/genpage/lib/source-evidence.js
+++ b/evals/model-apps/genpage/lib/source-evidence.js
@@ -1,6 +1,8 @@
'use strict';
const { blankNonCodePreservingTemplateExpressions } = require('../../../../plugins/model-apps/scripts/lib/source-literals.js');
+const { jsxElements } = require('./tsx-structure.js');
+const { transparentBoundary } = require('./page-error-canonical.js');
function groupEnd(mask, open) {
const pairs = { '(': ')', '{': '}', '[': ']' };
@@ -66,8 +68,9 @@ function objectFields(text) {
return fields;
}
-function actionCalls(code) {
- const mask = blankNonCodePreservingTemplateExpressions(code);
+// The named `function` declarations of a masked source, as the receiver proof reads them: their parameter list and
+// their body's braces.
+function namedScopes(mask) {
const scopes = [];
for (const match of mask.matchAll(/\b(?:async\s+)?function\s+([\w$]+)\s*\(/g)) {
const paramsOpen = match.index + match[0].length - 1;
@@ -75,6 +78,12 @@ function actionCalls(code) {
const body = mask.indexOf('{', paramsEnd);
if (body !== -1) scopes.push({ name: match[1], start: match.index, paramsOpen, paramsEnd, body, end: groupEnd(mask, body) });
}
+ return scopes;
+}
+
+function actionCalls(code) {
+ const mask = blankNonCodePreservingTemplateExpressions(code);
+ const scopes = namedScopes(mask);
const calls = [];
for (const match of mask.matchAll(/\.\s*(executeAction|executeFunction)\s*(?:\?\.\s*)?\(/g)) {
const open = match.index + match[0].length - 1;
@@ -88,7 +97,7 @@ function actionCalls(code) {
// receiver check fails it rather than guessing what it refers to.
const chain = /([A-Za-z_$][\w$]*(?:\s*\??\.\s*[A-Za-z_$][\w$]*)*)\s*\??$/.exec(mask.slice(0, match.index));
const receiver = chain ? normalizeChain(chain[1]) : null;
- calls.push({ method: match[1], start: match.index, end, scope, scopes, receiver, resultName: assignment[1], fields: objectFields(code.slice(open + 1, end)), mask });
+ calls.push({ method: match[1], start: match.index, end, scope, scopes, receiver, resultName: assignment[1], fields: objectFields(code.slice(open + 1, end)), mask, code });
}
return calls;
}
@@ -177,8 +186,13 @@ function callSites(mask, name) {
// function component already has a scope; an arrow component's body is found after its `=>`.
function pageComponent(mask, scopes) {
const exported = /\bexport\s+default\s+(?:async\s+)?(?:function\s+)?([A-Za-z_$][\w$]*)/.exec(mask);
- if (!exported) return null;
- const id = escapeRe(exported[1]);
+ return exported ? componentNamed(mask, scopes, exported[1]) : null;
+}
+
+// The component declared as `name` — `function name(…) {…}` or `const name = (…) => …` — read as pageComponent
+// reads the default export. The FIRST such declaration; forwardedPageBody refuses a name declared twice.
+function componentNamed(mask, scopes, name) {
+ const id = escapeRe(name);
const decl = new RegExp(`(?:\\bfunction\\s+${id}\\s*|\\b(?:const|let|var)\\s+${id}\\s*(?::[^=;]+)?=\\s*(?:async\\s*)?)\\(`).exec(mask);
if (!decl) return null;
const open = decl.index + decl[0].length - 1;
@@ -191,15 +205,131 @@ function pageComponent(mask, scopes) {
if (!arrow) return null;
const body = close + 1 + arrow[0].length;
const end = '({'.includes(mask[body]) ? groupEnd(mask, body) : (mask.indexOf(';', body) + 1 || mask.length);
- scope = { name: exported[1], start: decl.index, paramsOpen: open, paramsEnd: close, body, end };
+ scope = { name, start: decl.index, paramsOpen: open, paramsEnd: close, body, end };
}
return {
scope: { ...scope, isComponent: true },
propsName: pattern ? null : (/^([A-Za-z_$][\w$]*)/.exec(first) || [])[1] || null,
destructured: pattern ? destructuredNames(pattern[1]) : new Map(),
+ declaredAt: decl.index,
+ firstParameter: first,
};
}
+// The canonical page error wrapper (references/rules.md, "Missing Error Handling"):
+// const GeneratedComponent = (props: GeneratedComponentProps) => (
+// <PageErrorBoundary>
+// <PageBody {...props} />
+// </PageErrorBoundary>
+// );
+// export default GeneratedComponent;
+// React renders PageBody with exactly the object the default export received, so PageBody's first parameter IS the page
+// props, and PageBody — not the wrapper — is the component the receiver proofs start from. Only this bounded shape earns
+// that, so nothing but the real props can reach PageBody:
+// - the default export's whole body is that one element: an arrow's expression (parenthesized or not), or a block
+// holding only `return (…);`. Its own first parameter is a plain name the file never assigns again;
+// - the root is PageErrorBoundary, given nothing, or only its telemetry prop (`appInsights={props.appInsights}`), and
+// PageErrorBoundary is the documented class itself (page-error-canonical.js transparentBoundary: one top-level class
+// equal to a documented form, string contents aside), named nowhere but its declaration and this element's two tags
+// — a function or an altered class of that name (a second `render()` overrides the first) could clone its child with
+// another dataApi;
+// - that class extends the page's own React.Component (reactComponentBase): `extends React.Component<…>`, where React is
+// the page's one import binding from 'react' and is otherwise only read through its members — a page-supplied base
+// (a destructured or aliased `Component`, a rebound or patched React) can install an instance `render` that replaces
+// the boundary's child, so the named `extends Component<…>` form proves nothing either;
+// - its one child, and nothing else, is a self-closing PageBody whose only attribute is one spread of that parameter;
+// - PageBody is declared once, at the top level of the module, with a plain first parameter (no destructuring and no
+// default value), and is named nowhere else: a second JSX use, a call or a value hand-off could pass another object.
+// Anything else returns null, and the default export stays the component exactly as before the wrapper existed. A
+// failed proof is not evidence that a call is unrelated: what PageBody then receives is simply unproven. The proof reads
+// the source text as well as its mask (the import's module name is a string the mask blanks): without `code` it fails.
+const PAGE_BODY = 'PageBody';
+const PAGE_ERROR_BOUNDARY = 'PageErrorBoundary';
+function forwardedPageBody(mask, scopes, wrapper, code) {
+ if (typeof code !== 'string' || code.length !== mask.length) return null;
+ const propsName = wrapper?.propsName;
+ if (!propsName || reassigned(mask, propsName)) return null;
+ const { scope } = wrapper;
+ const bodyEnd = '({'.includes(mask[scope.body]) ? scope.end + 1 : scope.end;
+ const inside = jsxElements(mask).filter((element) => element.start >= scope.body && element.end <= bodyEnd);
+ if (!inside.length) return null;
+ const root = inside.reduce((first, element) => (element.start < first.start ? element : first));
+ const around = (mask.slice(scope.body, root.start) + mask.slice(root.end, bodyEnd)).replace(/\s+/g, '');
+ if (!['()', '();', '', ';', '{return();}', '{return()}', '{return;}', '{return}'].includes(around)) return null;
+ if (root.name !== PAGE_ERROR_BOUNDARY || root.selfClosing) return null;
+ const boundary = transparentBoundary(mask);
+ if (!boundary || !reactComponentBase(code, mask, boundary)) return null;
+ if ([...mask.matchAll(new RegExp(`(?<![\\w$.])${PAGE_ERROR_BOUNDARY}(?![\\w$])`, 'g'))].length !== 3) return null;
+ const rootAttrs = [...root.attrs.entries()];
+ if (rootAttrs.length > 1 || (rootAttrs.length === 1 && !(rootAttrs[0][0] === 'appInsights' && rootAttrs[0][1].kind === 'expression'
+ && normalizeChain(rootAttrs[0][1].value) === `${propsName}.appInsights`))) return null;
+ const children = inside.filter((element) => element !== root);
+ if (children.length !== 1) return null;
+ const [child] = children;
+ if (child.name !== PAGE_BODY || !child.selfClosing || child.attrs.size !== 1) return null;
+ const spread = child.attrs.get('...');
+ if (!spread || spread.value.replace(/\s+/g, '') !== `...${propsName}`) return null;
+ if ((mask.slice(root.childrenStart, child.start) + mask.slice(child.end, root.childrenEnd)).trim()) return null;
+ // Named exactly twice: its declaration and the child element. A type position (`typeof PageBody`) counts too, and refuses.
+ if ([...mask.matchAll(new RegExp(`(?<![\\w$.])${PAGE_BODY}(?![\\w$])`, 'g'))].length !== 2) return null;
+ const declarations = mask.match(new RegExp(`\\b(?:function|class|const|let|var)\\s+${PAGE_BODY}(?![\\w$])`, 'g')) || [];
+ if (declarations.length !== 1) return null;
+ const body = componentNamed(mask, scopes, PAGE_BODY);
+ if (!body?.propsName || !new RegExp(`^${escapeRe(body.propsName)}\\s*(?::[^=]*)?$`).test(body.firstParameter.trim())) return null;
+ if (moduleDepth(mask, body.declaredAt) !== 0) return null;
+ return body;
+}
+
+// Does the boundary class at `range` extend the page's own React.Component? Only this bounded form is accepted:
+// import * as React from 'react'; (or `import React from 'react'`, or `import React, { useState } from 'react'`)
+// class PageErrorBoundary extends React.Component<…> { … }
+// with that import the page's only import from 'react', no `require(…)` or `import(…)` that could reach the module another
+// way, and every other mention of React a member read (`React.useState(…)`, `React.ReactNode`, `<React.Fragment>`) — not
+// rebound, shadowed, destructured from or aliased (`const { Component } = React`, `const R = React`, a parameter named
+// React), handed on (`Object.assign(React, …)`), written through (`React.Component = …`), read computed, or reaching
+// `.prototype` or `React.Component` anywhere but the class header. Each of those can give the class another base, whose
+// constructor may install an instance `render` that replaces the boundary's child.
+function reactComponentBase(code, mask, range) {
+ const header = /^class\s+PageErrorBoundary\s+extends\s+(React)\s*\.\s*Component\s*</.exec(mask.slice(range.start));
+ if (!header) return false;
+ const headerAt = range.start + header[0].indexOf('React');
+ if (/(?<![\w$.])require\s*\(|(?<![\w$.])import\s*\(/.test(mask)) return false;
+ // `import <clause> from '<module>'` — the mask keeps the quotes and blanks the module name, so it is read from `code`.
+ const fromReact = [];
+ for (const match of mask.matchAll(/(?<![\w$.])import\b([^;'"]*?)\bfrom\s*(['"])/g)) {
+ const open = match.index + match[0].length - 1;
+ const close = mask.indexOf(match[2], open + 1);
+ if (close < 0 || literalString(code.slice(open, close + 1)) !== 'react') continue;
+ fromReact.push(match);
+ }
+ if (fromReact.length !== 1) return false;
+ const [only] = fromReact;
+ const clause = /^\s*(?:\*\s*as\s+React|React(?:\s*,\s*\{[^{}]*\})?)\s*$/.exec(only[1]);
+ if (!clause) return false;
+ const bindingAt = only.index + 'import'.length + only[1].indexOf('React');
+ for (const mention of mask.matchAll(/(?<![\w$.])React(?![\w$])/g)) {
+ if (mention.index === bindingAt) continue;
+ const rest = mask.slice(mention.index + 'React'.length);
+ const chain = /^(?:\s*\.\s*[A-Za-z_$][\w$]*)+/.exec(rest);
+ if (!chain) return false;
+ const members = chain[0].replace(/\s+/g, '').split('.').filter(Boolean);
+ if (members.includes('prototype') || (members[0] === 'Component' && mention.index !== headerAt)) return false;
+ if (/^\s*(?:(?:\*\*|<<|>>>?|\?\?|\|\||&&|[-+*/%&|^])?=(?![=>])|\+\+|--|\[|\?\.\s*\[)/.test(rest.slice(chain[0].length))) return false;
+ if (/(?:\bdelete|\+\+|--)\s*$/.test(mask.slice(Math.max(0, mention.index - 12), mention.index))) return false;
+ }
+ return true;
+}
+
+// How many brackets are open at `at`: 0 at the top level of the module.
+function moduleDepth(mask, at) {
+ let depth = 0;
+ for (let i = 0; i < at; i += 1) {
+ if ('({['.includes(mask[i])) depth += 1;
+ else if (')}]'.includes(mask[i])) depth -= 1;
+ }
+ return depth;
+}
+
// A declaration's complete initializer, from `start` to the end of its statement: a `;`, a
// top-level `,` (the next declarator) or the end of the enclosing group. A line break ends it too
// unless the next line continues the expression (`|| other`, `as Api`, `.member`).
@@ -489,8 +619,9 @@ function isDataApi(ctx, expr, at, depth = 0) {
// where <props> is the page component's props parameter, a name destructured from those props or
// assigned from such a name (casts allowed), or a parameter of an enclosing helper that every
// outside call fills with one of those. Anything unresolvable fails.
-function sourceContext(mask, scopes) {
- const component = pageComponent(mask, scopes);
+function sourceContext(mask, scopes, code) {
+ const exported = pageComponent(mask, scopes);
+ const component = forwardedPageBody(mask, scopes, exported, code) || exported;
const named = component
? [...scopes.filter((scope) => scope.paramsOpen !== component.scope.paramsOpen), component.scope]
: scopes;
@@ -500,8 +631,19 @@ function sourceContext(mask, scopes) {
return { mask, scopes: all, component };
}
-function receiverIsDataApi(mask, scopes, expr, at) {
- return isDataApi(sourceContext(mask, scopes), expr, at);
+// `code` is the source `mask` was made from (actionCalls returns it as `call.code`); the boundary wrapper's proof needs it,
+// and without it PageBody's props are simply unproven.
+function receiverIsDataApi(mask, scopes, expr, at, code) {
+ return isDataApi(sourceContext(mask, scopes, code), expr, at);
+}
+
+// The PageBody the canonical page error wrapper forwards the page props to (forwardedPageBody), or null when the
+// default export is not exactly that wrapper. The built-in check (action-binding-union.js) asks this for where a page
+// renders, so its render roots and the props the receiver proofs trust are the same proof.
+function forwardedPageBodyOf(code) {
+ const mask = blankNonCodePreservingTemplateExpressions(code);
+ const scopes = namedScopes(mask);
+ return forwardedPageBody(mask, scopes, pageComponent(mask, scopes), code);
}
// Resolve only the identity-preserving forms already understood by the shared evidence reader.
@@ -635,10 +777,10 @@ function recordPropInput(ctx, expr, at, depth = 0) {
// The bounded member form is a named helper's explicit record input, e.g.
// `selectedAccount: { accountid: string }` supplied from the page's props. A local fabricated
// record, an opaque type alias or an arbitrary chain is not evidence that an ID came from an input.
-function stringRecordMemberIsInput(mask, scopes, expr, at) {
+function stringRecordMemberIsInput(mask, scopes, expr, at, code) {
const member = /^([A-Za-z_$][\w$]*)\s*\.\s*([A-Za-z_$][\w$]*)$/.exec(expr.trim());
if (!member) return false;
- const ctx = sourceContext(mask, scopes);
+ const ctx = sourceContext(mask, scopes, code);
// Conservatively refuse recognized writes anywhere on these value paths, including aliased
// helpers declared later in the module. This is not an execution-order or general heap evaluator.
if (recordValueWritten(ctx, member[1], at)) return false;
@@ -657,4 +799,7 @@ function stringRecordMemberIsInput(mask, scopes, expr, at) {
});
}
-module.exports = { groupEnd, literalString, objectFields, actionCalls, receiverIsDataApi, stringRecordMemberIsInput, escapeRe };
+module.exports = {
+ groupEnd, literalString, objectFields, actionCalls, receiverIsDataApi, stringRecordMemberIsInput, escapeRe, callSites, expressionEnd,
+ namedScopes, forwardedPageBodyOf,
+};
diff --git a/evals/model-apps/genpage/lib/tsx-structure.js b/evals/model-apps/genpage/lib/tsx-structure.js
index 6e3695e01..904824143 100644
--- a/evals/model-apps/genpage/lib/tsx-structure.js
+++ b/evals/model-apps/genpage/lib/tsx-structure.js
@@ -473,4 +473,6 @@ function nestedDefinitionProblems(content) {
module.exports = {
sourceView, jsxElements, jsxTextRuns, declarationSource, matchingClose, patternNames,
namedFunctions, nestedDefinitionProblems, withoutComments,
+ // Exported so that a check needing a page's function scopes reads them through this reader instead of a second one.
+ functionScopes,
};
diff --git a/evals/model-apps/genpage/lib/upload-contract.js b/evals/model-apps/genpage/lib/upload-contract.js
index 931805b7a..248fb7a5b 100644
--- a/evals/model-apps/genpage/lib/upload-contract.js
+++ b/evals/model-apps/genpage/lib/upload-contract.js
@@ -19,15 +19,18 @@ const switchOn = (value) => value === true || value === 'true';
// none, so one approval cannot cover a later upload — including a second copy of the same
// command. indexOf would bind every later copy to the first occurrence. A mention of the words
// in an options list, a stop, or a choice logged after the command is not consent.
+// A clear of a page that binds a built-in operation is read the same way, from its own
+// `Clear choice:` lines (action-binding-union.js clearConfirmationProblems), so that one decision
+// never takes the other's slot: an upload that needs both answers carries both.
const DIVERGENCE_CODES = new Set(['no-base', 'deployed-changed', 'deployed-unreadable']);
const OVERWRITE_CHOICE_LINE = 'Choice: Overwrite the deployed changes';
-function uploadChoiceLines(workflowLog) {
+function uploadChoiceLines(workflowLog, prefix = 'Choice:') {
const entries = [];
let pending = null;
for (const line of String(workflowLog || '').split(/\r?\n/)) {
const trimmed = line.trim();
- if (trimmed.startsWith('Choice:')) {
+ if (trimmed.startsWith(prefix)) {
pending = trimmed;
continue;
}
@@ -377,4 +380,5 @@ function uploadPreservationProblems(fixture, mode) {
module.exports = {
uploadProblems, uploadPreservationProblems, uploadTransportProblems, desiredBindings, sameBindings,
uploadResultIdentityMatches, pageIdentityProblems, beforePageIdentityProblems, sameRecordedEnvironment,
+ uploadChoiceLines, consumedChoice,
};
diff --git a/evals/model-apps/genpage/lib/workflow-evidence.js b/evals/model-apps/genpage/lib/workflow-evidence.js
index 5d4d5f7c5..efc2bc237 100644
--- a/evals/model-apps/genpage/lib/workflow-evidence.js
+++ b/evals/model-apps/genpage/lib/workflow-evidence.js
@@ -318,12 +318,6 @@ function refusalProblems(fixture) {
if ((fixture.files || []).length || calls.some((call) => isGeneration(call.command) || isMutation(call))) {
problems.push('refused workflow generated a page or attempted a mutation');
}
- if (stage === 'custom-api') {
- // Loaded only while scoring this refusal to keep the shared evidence primitives independent
- // of the API lifecycle module (which itself consumes those primitives).
- const { customApiGateProblems } = require('./custom-api-contract.js');
- return problems.concat(customApiGateProblems(fixture));
- }
// A run refused at Edit Phase 1b because the chosen app has no generative pages: its "gate" is the empty
// page listing, and an auth call it made on the way (the edit flow captures its environment with
// check-auth.js) must still be well formed.
diff --git a/evals/model-apps/genpage/tests/action-binding-union.test.js b/evals/model-apps/genpage/tests/action-binding-union.test.js
new file mode 100644
index 000000000..7631f57fd
--- /dev/null
+++ b/evals/model-apps/genpage/tests/action-binding-union.test.js
@@ -0,0 +1,651 @@
+'use strict';
+// A page's one `actionBindings` array, as the Custom API lifecycle evaluator compares it when it holds both partitions: a Custom API row and a reviewed built-in operation
+// (WhoAmI). The upload replaces the page's list with the file it is given, so the evaluator compares the WHOLE union — the Custom API rows, then the built-in rows in catalogue
+// order — and the built-in rows must come from an enabled `dataverse-operations` gate, the catalogue listing and the plan's `## Dataverse Operations` table. Dropping either
+// partition, spreading a descriptor onto the wire, reordering, or a built-in name in the Custom API table fails; a later stage that only preserves the page's bindings does not
+// consult the built-in gate. The built-in call is held to the same order as a Custom API call: a failure returns before `res.outputs` is read.
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const { PHASE_EXPECTATIONS, WORKFLOW_ASSERTIONS } = require('../lib/assertions-layer-1.js');
+const { PHASE5_EXPECTATIONS } = require('../lib/assertions-layer-2.js');
+const union = require('../lib/action-binding-union.js');
+const { customApiProblems } = require('../lib/custom-api-contract.js');
+const { getDataverseOperationCatalogue } = require('../../../../plugins/model-apps/scripts/lib/dataverse-operations.js');
+
+const RULE = 'Phase 5: Custom API discovery, gate, bare bindings, runtime calls and update preservation or explicit clear agree';
+const PAGE = '99999999-9999-4999-8999-999999999999';
+const API = { name: 'cnt_ApproveOrder', isFunction: false, boundEntityLogicalName: 'salesorder', displayName: 'Approve Order', parameterKinds: { Comment: 'String', Amount: 'Decimal' } };
+const WHO_AM_I = { name: 'WhoAmI', isFunction: true, displayName: 'Current Dataverse identity', parameterKinds: {} };
+const RETRIEVE_VERSION = { name: 'RetrieveVersion', isFunction: true, displayName: 'Dataverse server version', parameterKinds: {} };
+const listing = () => ({ ok: true, ...structuredClone(getDataverseOperationCatalogue()) });
+
+// The Custom API helper of the existing lifecycle fixture, and a user-triggered WhoAmI helper and button (references/dataverse-operations.md).
+const SOURCE = `
+type ActionResult = { ok: boolean; indeterminate?: boolean; outputs?: Record<string, unknown>; error?: { message: string; code?: string; status?: number } };
+type ActionApi = { executeAction?: (request: unknown) => Promise<ActionResult>; executeFunction?: (request: { name: string }) => Promise<ActionResult> };
+type Pending = { current: boolean };
+type Identity = { userId: string; businessUnitId: string; organizationId: string };
+type IdentityView = { identity?: Identity; message?: string };
+const GUID = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
+const UNEXPECTED = 'The operation returned an unexpected response. No result was displayed.';
+const UNAVAILABLE = 'The selected operation is unavailable in this environment or player. No fallback was attempted.';
+const UNSUPPORTED = 'This page player cannot call built-in operations.';
+const FAILED = 'The operation failed. No result was displayed.';
+async function approveOrder(api: ActionApi, recordId: string, amount: number, pending: Pending) {
+ if (typeof api.executeAction !== 'function') return;
+ if (pending.current || !recordId) return;
+ pending.current = true;
+ try {
+ const res = await api.executeAction({
+ name: 'cnt_ApproveOrder',
+ parameters: { Comment: 'Approved', Amount: amount },
+ boundTo: { entityName: 'salesorder', id: recordId },
+ });
+ if (res.indeterminate) { setError('Refresh before retrying.'); return; }
+ if (!res.ok) { setError(res.error?.message ?? 'Action failed.'); return; }
+ setStatus(res.outputs?.NewStatus);
+ } catch { setError('Network failed.'); }
+ finally { pending.current = false; }
+}
+function ownString(outputs: Record<string, unknown>, field: string): string | undefined {
+ const value = Object.prototype.hasOwnProperty.call(outputs, field) ? outputs[field] : undefined;
+ return typeof value === 'string' ? value : undefined;
+}
+async function readIdentity(api: ActionApi): Promise<IdentityView> {
+ if (typeof api.executeFunction !== 'function') return { message: UNSUPPORTED };
+ const res = await api.executeFunction({ name: 'WhoAmI' });
+ if (res.ok !== true) {
+ return { message: res.error?.status === 404 ? UNAVAILABLE : res.error?.message || FAILED };
+ }
+ const outputs = res.outputs;
+ if (!outputs || typeof outputs !== 'object' || Array.isArray(outputs)) return { message: UNEXPECTED };
+ const userId = ownString(outputs, 'UserId');
+ const businessUnitId = ownString(outputs, 'BusinessUnitId');
+ const organizationId = ownString(outputs, 'OrganizationId');
+ if (![userId, businessUnitId, organizationId].every((id) => typeof id === 'string' && GUID.test(id))) return { message: UNEXPECTED };
+ return { identity: { userId: userId as string, businessUnitId: businessUnitId as string, organizationId: organizationId as string } };
+}
+const GeneratedComponent = (props: Props) => {
+ const { dataApi } = props;
+ const pending = { current: false };
+ const [identity, setIdentity] = React.useState<IdentityView>({});
+ const [identityPending, setIdentityPending] = React.useState(false);
+ const identityRequest = React.useRef(0);
+ const mounted = React.useRef(true);
+ React.useEffect(() => () => { mounted.current = false; }, []);
+ const showIdentity = async () => {
+ if (identityPending) return;
+ const requestId = ++identityRequest.current;
+ setIdentity({});
+ setIdentityPending(true);
+ try {
+ const view = await readIdentity(dataApi);
+ if (mounted.current && requestId === identityRequest.current) setIdentity(view);
+ } catch {
+ if (mounted.current && requestId === identityRequest.current) setIdentity({ message: FAILED });
+ } finally {
+ if (mounted.current && requestId === identityRequest.current) setIdentityPending(false);
+ }
+ };
+ void approveOrder(dataApi, 'record', 1, pending);
+ return (
+ <div>
+ <Button disabled={identityPending} onClick={() => void showIdentity()}>Show my Dataverse identity</Button>
+ {identity.message && <Text>{identity.message}</Text>}
+ {identity.identity && (
+ <div>
+ <Text>Dataverse user id: {identity.identity.userId}</Text>
+ <Text>Business unit id: {identity.identity.businessUnitId}</Text>
+ <Text>Organization id: {identity.identity.organizationId}</Text>
+ <Text>The organization id is not an Entra tenant id.</Text>
+ </div>
+ )}
+ </div>
+ );
+};
+export default GeneratedComponent;
+`;
+
+const PLAN = `## Custom API Bindings
+| Name | Kind | Bound Entity | Display Name | Parameters (name: kind) |
+|------|------|--------------|--------------|-------------------------|
+| cnt_ApproveOrder | Action | salesorder | Approve Order | Comment: String, Amount: Decimal |
+
+## Dataverse Operations
+Verification: environment not-checked, runtime not-checked, privileges not-checked.
+| Name | Kind | Bound Entity | Display Name | Parameters | Response fields | Invoke |
+|------|------|--------------|--------------|------------|-----------------|--------|
+| WhoAmI | Function | (Global) | Current Dataverse identity | (none) | BusinessUnitId, UserId, OrganizationId | button |
+`;
+
+function mixedFixture() {
+ const both = [API, WHO_AM_I];
+ const config = JSON.stringify({ actionBindings: both });
+ return {
+ contractVersion: 2,
+ files: [{ name: 'page.tsx', content: SOURCE }],
+ artifacts: { 'stages/with-api.tsx': SOURCE, 'actions.json': JSON.stringify(both), 'created/config.json': config, 'preserved/config.json': config },
+ genpagePlan: PLAN,
+ workflowLog: 'Custom API and built-in operation lifecycle; latest enabled gates before each authoring generation and upload.',
+ manifest: {
+ customApi: {
+ outputs: { cnt_ApproveOrder: ['NewStatus'] },
+ stages: [
+ { id: 'create', target: 'page.tsx', source: 'stages/with-api.tsx', actions: 'actions.json', afterConfig: 'created/config.json', upload: 'create' },
+ { id: 'preserve', target: 'page.tsx', source: 'stages/with-api.tsx', beforeConfig: 'created/config.json', afterConfig: 'preserved/config.json', upload: 'preserve' },
+ ],
+ },
+ },
+ events: [
+ { id: 'gate-create', command: 'node feature-flags.js custom-api', result: 'enabled' },
+ { id: 'discovery', command: 'node list-custom-apis.js https://contoso.crm.dynamics.com --entities salesorder', result: { ok: true, customApis: [{ ...structuredClone(API), bindingType: 'Entity' }] } },
+ { id: 'builtin-gate', command: 'node feature-flags.js dataverse-operations', result: 'enabled' },
+ { id: 'listing', command: 'node list-dataverse-operations.js', result: listing() },
+ { id: 'gate-generate', command: 'node feature-flags.js custom-api', result: 'enabled' },
+ { id: 'builtin-regate', command: 'node feature-flags.js dataverse-operations', result: 'enabled' },
+ { id: 'write-create', command: 'Write page.tsx', artifact: 'stages/with-api.tsx' },
+ { id: 'create', command: 'node genpage-upload.js --code-file page.tsx --actions actions.json --add-to-sitemap', result: { ok: true, pageId: PAGE } },
+ // An unrelated later edit while built-in authoring is OFF: it preserves the page's bindings (no --actions) and does not halt.
+ { id: 'gate-preserve', command: 'node feature-flags.js custom-api', result: 'enabled' },
+ { id: 'builtin-off', command: 'node feature-flags.js dataverse-operations', result: 'disabled' },
+ { id: 'write-preserve', command: 'Write page.tsx', artifact: 'stages/with-api.tsx' },
+ { id: 'preserve', command: `node genpage-upload.js --page-id ${PAGE} --code-file page.tsx`, result: { ok: true, pageId: PAGE } },
+ ],
+ };
+}
+
+const event = (fixture, id) => fixture.events.find((call) => call.id === id);
+function score(fixture, layer = 1) {
+ const check = (layer === 1 ? PHASE_EXPECTATIONS : PHASE5_EXPECTATIONS).get(RULE);
+ return check({ fixture, files: fixture.files, eval: { id: 24 } });
+}
+const setActions = (fixture, rows) => { fixture.artifacts['actions.json'] = JSON.stringify(rows); };
+const setConfigs = (fixture, rows) => { for (const name of ['created/config.json', 'preserved/config.json']) fixture.artifacts[name] = JSON.stringify({ actionBindings: rows }); };
+
+test('a mixed actions file — a Custom API row and a reviewed built-in — passes as one union in both evaluator layers', () => {
+ for (const layer of [1, 2]) {
+ const result = score(mixedFixture(), layer);
+ assert.equal(result.status, 'pass', `layer ${layer}: ${result.reason}`);
+ }
+});
+
+test('the union is compared whole: dropping either partition, spreading a descriptor or putting a built-in first fails', () => {
+ for (const [label, mutate] of [
+ ['the built-in partition dropped from every file', (f) => { setActions(f, [API]); setConfigs(f, [API]); }],
+ ['the Custom API partition dropped from every file', (f) => { setActions(f, [WHO_AM_I]); setConfigs(f, [WHO_AM_I]); }],
+ ['the built-in row only in actions.json', (f) => { setConfigs(f, [API]); }],
+ ['a descriptor spread onto the wire', (f) => { const rows = [API, { ...WHO_AM_I, bindingType: 'Global', response: listing().operations[0].response }]; setActions(f, rows); setConfigs(f, rows); }],
+ ['the built-in before the Custom API row', (f) => { setActions(f, [WHO_AM_I, API]); }],
+ ['a built-in row with a display name of its own', (f) => { const rows = [API, { ...WHO_AM_I, displayName: 'Who am I' }]; setActions(f, rows); setConfigs(f, rows); }],
+ ['a built-in the plan did not select', (f) => { const rows = [API, WHO_AM_I, RETRIEVE_VERSION]; setActions(f, rows); setConfigs(f, rows); }],
+ ]) {
+ for (const layer of [1, 2]) {
+ const bad = mixedFixture();
+ mutate(bad);
+ assert.equal(score(bad, layer).status, 'fail', `layer ${layer}: ${label}`);
+ }
+ }
+});
+
+test('built-in rows need an enabled dataverse-operations gate, the catalogue listing and a re-probe before an authoring generation and upload — a preserve-only stage does not', () => {
+ assert.equal(score(mixedFixture()).status, 'pass');
+ for (const [label, mutate] of [
+ ['listing after a disabled gate', (f) => { event(f, 'builtin-gate').result = 'disabled'; }],
+ ['no listing', (f) => { f.events = f.events.filter((call) => call.id !== 'listing'); }],
+ ['no re-probe after the listing', (f) => { f.events = f.events.filter((call) => call.id !== 'builtin-regate'); }],
+ ['a disabled re-probe', (f) => { event(f, 'builtin-regate').result = 'disabled'; }],
+ ['an unreadable re-probe', (f) => { event(f, 'builtin-regate').result = 'maybe'; }],
+ ['a failed listing', (f) => { event(f, 'listing').result = { ok: false, error: 'The built-in operation catalogue could not be read. No built-in operations were offered.' }; }],
+ ['a widened listing', (f) => { const result = listing(); result.operations.push({ ...result.operations[0], name: 'CalculateRollupField' }); event(f, 'listing').result = result; }],
+ ['a listing that claims a check', (f) => { event(f, 'listing').result = { ...listing(), eligible: true }; }],
+ ['an altered listed descriptor', (f) => { const result = listing(); result.operations[0].isFunction = false; event(f, 'listing').result = result; }],
+ ]) {
+ const bad = mixedFixture();
+ mutate(bad);
+ assert.equal(score(bad).status, 'fail', label);
+ }
+});
+
+test('the plan section is the exact sentinel or the catalogue\'s own table — anything else halts, and a built-in never sits in the Custom API table', () => {
+ const plan = (rows) => PLAN.replace('| WhoAmI | Function | (Global) | Current Dataverse identity | (none) | BusinessUnitId, UserId, OrganizationId | button |', rows);
+ for (const [label, text] of [
+ ['wrong case', plan('| whoami | Function | (Global) | Current Dataverse identity | (none) | BusinessUnitId, UserId, OrganizationId | button |')],
+ ['an effectful Function', plan('| CalculateRollupField | Function | (Global) | Calculate | (none) | Entity | button |')],
+ ['a display name of its own', plan('| WhoAmI | Function | (Global) | Who am I | (none) | BusinessUnitId, UserId, OrganizationId | button |')],
+ ['an on-load trigger', plan('| WhoAmI | Function | (Global) | Current Dataverse identity | (none) | BusinessUnitId, UserId, OrganizationId | on-load |')],
+ ['no verification line', PLAN.replace('Verification: environment not-checked, runtime not-checked, privileges not-checked.\n', '')],
+ ['prose instead of a table', PLAN.replace(/## Dataverse Operations[\s\S]*$/, '## Dataverse Operations\nWhoAmI, please.\n')],
+ // Moved, not duplicated: the Custom API table states the very row the built-in table would, and is still not where a built-in belongs.
+ ['in the Custom API table', PLAN.replace(/\n## Dataverse Operations[\s\S]*$/, '\n').replace('| cnt_ApproveOrder | Action | salesorder | Approve Order | Comment: String, Amount: Decimal |', '| cnt_ApproveOrder | Action | salesorder | Approve Order | Comment: String, Amount: Decimal |\n| WhoAmI | Function | (Global) | Current Dataverse identity | |')],
+ ]) {
+ const bad = mixedFixture();
+ bad.genpagePlan = text;
+ assert.equal(score(bad).status, 'fail', label);
+ }
+ assert.deepStrictEqual(union.plannedBuiltIns(PLAN), [WHO_AM_I]);
+ assert.deepStrictEqual(union.plannedBuiltIns('## Dataverse Operations\nNo Dataverse operations.\n'), []);
+ assert.equal(union.plannedBuiltIns('## Custom API Bindings\nNo custom API bindings.\n'), null);
+});
+
+test('a built-in call is held to the Custom API order: a failure returns before res.outputs is read, and DTO fields come only from res.outputs', () => {
+ for (const [label, mutate] of [
+ ['outputs read before the success check', (text) => text.replace(' if (res.ok !== true) {\n return { message: res.error?.status === 404 ? UNAVAILABLE : res.error?.message || FAILED };\n }\n const outputs = res.outputs;', ' const outputs = res.outputs;\n if (res.ok !== true) {\n return { message: res.error?.status === 404 ? UNAVAILABLE : res.error?.message || FAILED };\n }')],
+ ['no success check at all', (text) => text.replace('if (res.ok !== true) {', 'if (false) {')],
+ ['outputs from res.value', (text) => text.replace('const outputs = res.outputs;', 'const outputs = res.value;')],
+ ['an undeclared output', (text) => text.replace("ownString(outputs, 'UserId')", 'ownString(outputs, String(res.outputs?.SystemUserName))')],
+ ['raw fault text', (text) => text.replace('res.error?.message || FAILED', 'res.error?.stack || FAILED')],
+ ]) {
+ const bad = mixedFixture();
+ bad.artifacts['stages/with-api.tsx'] = mutate(SOURCE);
+ bad.files[0].content = bad.artifacts['stages/with-api.tsx'];
+ assert.notEqual(bad.artifacts['stages/with-api.tsx'], SOURCE, `${label}: the mutation applies`);
+ assert.equal(score(bad).status, 'fail', label);
+ }
+});
+
+test('union helpers: partition by exact name, one union with no duplicate, and the order a new actions file keeps', () => {
+ assert.deepStrictEqual(union.partitionBindings([API, WHO_AM_I, { name: 'whoami', isFunction: true }, RETRIEVE_VERSION]), {
+ customApis: [API, { name: 'whoami', isFunction: true }], builtIns: [WHO_AM_I, RETRIEVE_VERSION],
+ });
+ assert.deepStrictEqual(union.unionBindings([API], [WHO_AM_I, RETRIEVE_VERSION]), [API, WHO_AM_I, RETRIEVE_VERSION]);
+ assert.throws(() => union.unionBindings([API, WHO_AM_I], [WHO_AM_I]), /Select each built-in operation once/);
+ assert.deepStrictEqual(union.unionOrderProblems([API, WHO_AM_I, RETRIEVE_VERSION], 'a'), []);
+ assert.equal(union.unionOrderProblems([WHO_AM_I, API], 'a').length, 1);
+ assert.equal(union.unionOrderProblems([API, RETRIEVE_VERSION, WHO_AM_I], 'a').length, 1);
+ assert.deepStrictEqual(union.BUILT_IN_OUTPUTS, { WhoAmI: ['BusinessUnitId', 'UserId', 'OrganizationId'], RetrieveVersion: ['Version'] });
+});
+
+// ── The built-in gate at the authoring consumer, and a removal ─────────────────────────────────────────────────────────────────────
+// The page sources of one partition alone, cut from the mixed page: the Custom API helper and its render call, or the WhoAmI helper and its button.
+const APPROVE_HELPER = SOURCE.slice(SOURCE.indexOf('async function approveOrder('), SOURCE.indexOf('function ownString('));
+const CUSTOM_ONLY = SOURCE.replace(SOURCE.slice(SOURCE.indexOf('function ownString('), SOURCE.indexOf('const GeneratedComponent')), '')
+ .replace(/ const \[identity[\s\S]*?\n \};\n/, '')
+ .replace(/ <Button disabled=\{identityPending\}[\s\S]*?\n \)\}\n/, '');
+const BUILT_IN_ONLY = SOURCE.replace(APPROVE_HELPER, '').replace(" void approveOrder(dataApi, 'record', 1, pending);\n", '');
+const SENTINEL_PLAN = PLAN.replace(/## Custom API Bindings[\s\S]*?\n\n## Dataverse Operations/, '## Custom API Bindings\nNo custom API bindings.\n\n## Dataverse Operations');
+const CUSTOM_PLAN = PLAN.replace(/\n## Dataverse Operations[\s\S]*$/, '\n');
+
+// A one-stage create with the rows, the plan and the page given. `customApi` is what an older run's recorded `custom-api` probe printed, or null
+// for a run that never probed it — as no run does now; it decides nothing. Custom API discovery is recorded when `discovery` (by default, whenever a
+// row is a Custom API). `builtIns` is the dataverse-operations gate, and `listing` adds the catalogue listing after it.
+function createFixture({ rows, plan, source, customApi = null, builtIns, listing: listed = builtIns === 'enabled', discovery = rows.some((row) => !union.isBuiltInBinding(row)) }) {
+ const fixture = mixedFixture();
+ fixture.genpagePlan = plan;
+ fixture.files[0].content = source;
+ fixture.artifacts['stages/with-api.tsx'] = source;
+ setActions(fixture, rows);
+ setConfigs(fixture, rows);
+ fixture.manifest.customApi.stages = fixture.manifest.customApi.stages.slice(0, 1);
+ const keep = new Set(['builtin-gate', 'builtin-regate', 'write-create', 'create',
+ ...(customApi === null ? [] : ['gate-create', 'gate-generate']), ...(discovery ? ['discovery'] : []), ...(listed ? ['listing'] : [])]);
+ fixture.events = fixture.events.filter((call) => keep.has(call.id));
+ if (customApi !== null) for (const id of ['gate-create', 'gate-generate']) event(fixture, id).result = customApi;
+ for (const id of ['builtin-gate', 'builtin-regate']) event(fixture, id).result = builtIns;
+ return fixture;
+}
+
+test('only the dataverse-operations gate decides authoring at the consumer: a built-in row needs it ON, and a recorded custom-api probe — enabled, disabled or none — decides nothing', () => {
+ for (const customApi of ['enabled', 'disabled', null]) {
+ const label = `custom-api probe ${customApi === null ? 'never run' : customApi}`;
+ // Built-ins ON: a built-in-only page is authored.
+ assert.equal(score(createFixture({ rows: [WHO_AM_I], plan: SENTINEL_PLAN, source: BUILT_IN_ONLY, customApi, builtIns: 'enabled' })).status, 'pass', label);
+ // Built-ins OFF: a Custom-API-only page is authored, and no built-in row may be.
+ assert.equal(score(createFixture({ rows: [API], plan: CUSTOM_PLAN, source: CUSTOM_ONLY, customApi, builtIns: 'disabled' })).status, 'pass', label);
+ assert.equal(score(createFixture({ rows: [API, WHO_AM_I], plan: PLAN, source: SOURCE, customApi, builtIns: 'disabled', listing: true })).status, 'fail', `${label}: a built-in row authored while its gate is off`);
+ assert.equal(score(createFixture({ rows: [WHO_AM_I], plan: SENTINEL_PLAN, source: BUILT_IN_ONLY, customApi, builtIns: 'disabled', listing: true })).status, 'fail', label);
+ }
+ // Both partitions with the built-in gate ON is the mixed page.
+ assert.equal(score(mixedFixture()).status, 'pass');
+});
+
+test('a built-in-only create binds its rows with --actions whatever a recorded custom-api probe printed, and one that omits --actions fails in both layers', () => {
+ for (const customApi of ['enabled', 'disabled', null]) {
+ for (const layer of [1, 2]) {
+ const bound = score(createFixture({ rows: [WHO_AM_I], plan: SENTINEL_PLAN, source: BUILT_IN_ONLY, customApi, builtIns: 'enabled' }), layer);
+ assert.equal(bound.status, 'pass', `custom-api ${customApi}, layer ${layer}: ${bound.reason}`);
+ const omitted = createFixture({ rows: [WHO_AM_I], plan: SENTINEL_PLAN, source: BUILT_IN_ONLY, customApi, builtIns: 'enabled' });
+ event(omitted, 'create').command = 'node genpage-upload.js --code-file page.tsx --add-to-sitemap';
+ assert.equal(score(omitted, layer).status, 'fail', `custom-api ${customApi}, layer ${layer}: a create without --actions leaves WhoAmI unbound`);
+ }
+ }
+});
+
+// A create whose built-in offer added nothing — the dataverse-operations gate off, or the offer listed and declined — is complete without the
+// call: the planner was told `none — not added this run`, so the plan has no `## Dataverse Operations` section, the actions file no built-in row
+// and the page no such call. The same page with the call left in it fails: the call would have no binding.
+test('a create whose built-in offer added nothing — the gate off, or the offer declined — is graded as a complete page without the call', () => {
+ for (const [label, builtIns, listing] of [['the dataverse-operations gate off', 'disabled', false], ['the offer listed and declined', 'enabled', true]]) {
+ for (const layer of [1, 2]) {
+ const complete = score(createFixture({ rows: [API], plan: CUSTOM_PLAN, source: CUSTOM_ONLY, customApi: 'enabled', builtIns, listing }), layer);
+ assert.equal(complete.status, 'pass', `${label}, layer ${layer}: ${complete.reason}`);
+ const leftIn = score(createFixture({ rows: [API], plan: CUSTOM_PLAN, source: SOURCE, customApi: 'enabled', builtIns, listing }), layer);
+ assert.equal(leftIn.status, 'fail', `${label}, layer ${layer}: a WhoAmI call with no binding`);
+ }
+ }
+});
+
+test('a removal drops only the named entries and needs no built-in gate: WhoAmI out keeps the Custom API, and the reverse', () => {
+ const removal = (removed, kept, source) => {
+ const fixture = mixedFixture();
+ fixture.artifacts['removed-actions.json'] = JSON.stringify(kept);
+ fixture.artifacts['removed/config.json'] = JSON.stringify({ actionBindings: kept });
+ fixture.artifacts['stages/removed.tsx'] = source;
+ fixture.files[0].content = source;
+ fixture.manifest.customApi.stages.push({ id: 'remove', target: 'page.tsx', source: 'stages/removed.tsx', actions: 'removed-actions.json', beforeConfig: 'preserved/config.json', afterConfig: 'removed/config.json', upload: 'remove', change: { remove: removed } });
+ fixture.events.push(
+ { id: 'gate-remove', command: 'node feature-flags.js custom-api', result: 'enabled' },
+ { id: 'write-remove', command: 'Write page.tsx', artifact: 'stages/removed.tsx' },
+ { id: 'remove', command: `node genpage-upload.js --page-id ${PAGE} --code-file page.tsx --actions removed-actions.json`, result: { ok: true, pageId: PAGE } },
+ );
+ return fixture;
+ };
+ // The built-in gate was last probed OFF (the preserve stage): a removal does not consult it.
+ assert.equal(score(removal(['WhoAmI'], [API], CUSTOM_ONLY)).status, 'pass');
+ assert.equal(score(removal(['cnt_ApproveOrder'], [WHO_AM_I], BUILT_IN_ONLY)).status, 'pass');
+ const both = removal(['WhoAmI'], [], CUSTOM_ONLY);
+ assert.equal(score(both).status, 'fail', 'removing WhoAmI must not drop the Custom API too');
+});
+
+// ── Removing every Custom API, and clearing every binding ───────────────────────────────────────────────────────────────────────────
+// A later update of the mixed page: `change` is the maker's intent as the scenario records it, `rows` the actions file uploaded.
+const NO_CALLS = "import * as React from 'react';\nconst GeneratedComponent = () => <div>No server calls.</div>;\nexport default GeneratedComponent;\n";
+function withUpdate(fixture, id, change, rows, source) {
+ fixture.artifacts[`${id}-actions.json`] = JSON.stringify(rows);
+ fixture.artifacts[`${id}/config.json`] = JSON.stringify({ actionBindings: rows });
+ fixture.artifacts[`stages/${id}.tsx`] = source;
+ fixture.files[0].content = source;
+ fixture.manifest.customApi.stages.push({ id, target: 'page.tsx', source: `stages/${id}.tsx`, actions: `${id}-actions.json`, beforeConfig: 'preserved/config.json', afterConfig: `${id}/config.json`, upload: id, change });
+ fixture.events.push(
+ { id: `gate-${id}`, command: 'node feature-flags.js custom-api', result: 'enabled' },
+ { id: `write-${id}`, command: 'Write page.tsx', artifact: `stages/${id}.tsx` },
+ { id, command: `node genpage-upload.js --page-id ${PAGE} --code-file page.tsx --actions ${id}-actions.json`, result: { ok: true, pageId: PAGE } },
+ );
+ return fixture;
+}
+
+test('removing every Custom API of a mixed page keeps WhoAmI — an empty actions file in its place fails in both layers', () => {
+ for (const layer of [1, 2]) {
+ const kept = score(withUpdate(mixedFixture(), 'remove-apis', { remove: ['cnt_ApproveOrder'] }, [WHO_AM_I], BUILT_IN_ONLY), layer);
+ assert.equal(kept.status, 'pass', `layer ${layer}: ${kept.reason}`);
+ const emptied = score(withUpdate(mixedFixture(), 'remove-apis', { remove: ['cnt_ApproveOrder'] }, [], BUILT_IN_ONLY), layer);
+ assert.equal(emptied.status, 'fail', `layer ${layer}: [] deletes WhoAmI`);
+ }
+});
+
+// The clear's own record (edit-flow.md, Edit Phase 6): the maker's answer to the two-option clear question, written as its own workflow-log line
+// right before the upload it covers —
+// Clear choice: Clear every action binding of page <page-id>, removing WhoAmI
+// The last `Clear choice:` line before the log line that carries this upload's exact command is the one that counts, and each upload consumes
+// the choice before it, as an overwrite choice is consumed (upload-contract.js): one choice covers one upload, a later choice replaces an
+// earlier one, and a choice written after the upload, for another page or for another set of built-ins is no permission. A yes to adding or
+// keeping WhoAmI is not a clear choice at all.
+const OTHER_PAGE = '11111111-1111-4111-8111-111111111111';
+const CLEAR_CHOICE = `Clear choice: Clear every action binding of page ${PAGE}, removing WhoAmI`;
+const CLEAR_REFUSED = /^clear: clearing every action binding removes WhoAmI — only with the maker's clear choice recorded right before this upload/;
+// The clear of the mixed page, with `lines` appended to its workflow log; `<upload>` stands for the log line of the clear's upload command and
+// `retry` makes the clear upload twice — a first attempt that failed, then the stage's own upload — both logged with the same command.
+function cleared(lines, { retry = false } = {}) {
+ const fixture = withUpdate(mixedFixture(), 'clear', { clear: true }, [], NO_CALLS);
+ const upload = fixture.events.find((call) => call.id === 'clear');
+ if (retry) fixture.events.splice(fixture.events.indexOf(upload), 0, { id: 'clear-attempt', command: upload.command, result: { ok: false, error: 'The request timed out.' } });
+ fixture.workflowLog = [fixture.workflowLog, ...lines.map((line) => (line === '<upload>' ? `- Command: \`${upload.command}\`` : line))].join('\n');
+ return fixture;
+}
+
+test('clearing every binding of a page that binds WhoAmI needs the clear choice, recorded right before that upload, for that page and every built-in it removes', () => {
+ const asked = 'AskUserQuestion: Clearing every action binding also removes WhoAmI. → Clear every action binding, removing WhoAmI';
+ for (const [label, fixture] of [
+ ['the choice before the upload', cleared([asked, CLEAR_CHOICE, '<upload>'])],
+ ['the choice beside an overwrite choice for the same upload', cleared([CLEAR_CHOICE, 'Choice: Overwrite the deployed changes', '<upload>'])],
+ ['a retried clear with the choice written again', cleared([CLEAR_CHOICE, '<upload>', CLEAR_CHOICE, '<upload>'], { retry: true })],
+ ]) {
+ for (const layer of [1, 2]) {
+ const result = score(fixture, layer);
+ assert.equal(result.status, 'pass', `${label}, layer ${layer}: ${result.reason}`);
+ }
+ }
+ for (const [label, fixture] of [
+ ['no confirmation', cleared(['<upload>'])],
+ ['a yes to adding WhoAmI', cleared(['AskUserQuestion: Add a button for WhoAmI? → Yes', '<upload>'])],
+ ['a yes to keeping WhoAmI', cleared(['AskUserQuestion: Keep the WhoAmI binding? → Yes', '<upload>'])],
+ ['a free-text yes to clearing', cleared(['AskUserQuestion: Clear every action binding? This also removes WhoAmI. → Yes, clear them all', '<upload>'])],
+ ['a clear choice withdrawn before the upload', cleared([CLEAR_CHOICE, 'Clear choice: Keep WhoAmI', '<upload>'])],
+ ['a clear choice written after the upload', cleared(['<upload>', CLEAR_CHOICE])],
+ ['a qualified answer', cleared([`${CLEAR_CHOICE}, but keep WhoAmI`, '<upload>'])],
+ ['a choice for another page', cleared([CLEAR_CHOICE.replace(PAGE, OTHER_PAGE), '<upload>'])],
+ ['a choice for another set of built-ins', cleared([`${CLEAR_CHOICE} and RetrieveVersion`, '<upload>'])],
+ ['one choice for a retried clear', cleared([CLEAR_CHOICE, '<upload>', '<upload>'], { retry: true })],
+ ]) {
+ const problems = customApiProblems(fixture);
+ assert.ok(problems.some((problem) => CLEAR_REFUSED.test(problem)), `${label}: ${JSON.stringify(problems)}`);
+ for (const layer of [1, 2]) assert.equal(score(fixture, layer).status, 'fail', `${label}, layer ${layer}`);
+ }
+ // A page with no built-in row clears as before: the Custom APIs are the whole array, and no choice is asked.
+ const apiOnly = mixedFixture();
+ apiOnly.genpagePlan = CUSTOM_PLAN;
+ for (const call of apiOnly.events.filter((entry) => ['builtin-gate', 'listing', 'builtin-regate'].includes(entry.id))) apiOnly.events.splice(apiOnly.events.indexOf(call), 1);
+ apiOnly.artifacts['stages/with-api.tsx'] = CUSTOM_ONLY;
+ setActions(apiOnly, [API]);
+ setConfigs(apiOnly, [API]);
+ const result = score(withUpdate(apiOnly, 'clear', { clear: true }, [], NO_CALLS));
+ assert.equal(result.status, 'pass', result.reason);
+});
+
+// ── A Custom API removal, and a recorded custom-api probe ──────────────────────────────────────────────────────────────────────────
+// An edit of a downloaded page that binds the Custom API and WhoAmI; `remove` is what the maker asked to remove. Custom API support has no feature
+// flag, so the builder drops each named Custom API row and keeps every other row. `probe` is what an older run's recorded `custom-api` probe
+// printed (none when null, as no run probes it now): it decides nothing — the run is graded the same whatever it says.
+const APP = '88888888-8888-4888-8888-888888888888';
+const CUSTOM_API_PROBE = /\bfeature-flags\.js\b[^\n]*\bcustom-api\b/;
+function removalEdit({ probe = null, remove = ['cnt_ApproveOrder'], change = { remove }, rows, source, actions = true, log = '' }) {
+ const before = [API, WHO_AM_I];
+ const identity = JSON.stringify({ pageId: PAGE, appId: APP });
+ const env = 'https://contoso.crm.dynamics.com';
+ return {
+ contractVersion: 2,
+ files: [{ name: 'page.tsx', content: source }],
+ artifacts: {
+ 'stages/page.tsx': source, 'actions.json': JSON.stringify(rows),
+ 'before/config.json': JSON.stringify({ actionBindings: before }), 'after/config.json': JSON.stringify({ actionBindings: rows }),
+ 'before/page.json': identity, 'after/page.json': identity,
+ },
+ genpagePlan: '## Custom API Bindings\nNo custom API bindings.\n',
+ workflowLog: `An edit that removes ${remove.join(' and ')} from a page that binds a Custom API and WhoAmI.${log ? `\n${log}` : ''}`,
+ manifest: {
+ customApi: {
+ outputs: { cnt_ApproveOrder: ['NewStatus'] },
+ stages: [{ id: 'edit', target: 'page.tsx', source: 'stages/page.tsx', actions: 'actions.json', beforeConfig: 'before/config.json', afterConfig: 'after/config.json', upload: 'edit', change }],
+ },
+ uploads: [{ event: 'edit', mode: 'update', beforeConfig: 'before/config.json', afterConfig: 'after/config.json', beforePage: 'before/page.json', afterPage: 'after/page.json' }],
+ },
+ events: [
+ { id: 'download', command: `node genpage.js download --env ${env} --page-id ${PAGE} --app-id ${APP} --output-directory before`, result: { ok: true, pages: [{ pageId: PAGE }] } },
+ ...(probe === null ? [] : [{ id: 'custom-api-gate', command: 'node feature-flags.js custom-api', result: probe }]),
+ { id: 'builtin-gate', command: 'node feature-flags.js dataverse-operations', result: 'disabled' },
+ { id: 'write', command: 'Write page.tsx', artifact: 'stages/page.tsx' },
+ { id: 'edit', command: `node genpage-upload.js --env ${env} --page-id ${PAGE} --app-id ${APP} --code-file page.tsx${actions ? ' --actions actions.json' : ''}`, result: { ok: true, pageId: PAGE, appId: APP } },
+ ],
+ };
+}
+const both = (fixture, status, label) => {
+ for (const layer of [1, 2]) {
+ const result = score(fixture, layer);
+ assert.equal(result.status, status, `${label}, layer ${layer}: ${result.reason}`);
+ }
+};
+
+test('removing every Custom API of a mixed page removes its row and keeps WhoAmI whatever a recorded custom-api probe printed — the row kept is no removal', () => {
+ for (const probe of [null, 'enabled', 'disabled', 'maybe']) {
+ const label = `custom-api probe ${probe === null ? 'never run' : probe}`;
+ both(removalEdit({ probe, rows: [WHO_AM_I], source: BUILT_IN_ONLY }), 'pass', `${label}: the row removed, WhoAmI kept`);
+ // WhoAmI named in the same removal goes too: every named row goes.
+ both(removalEdit({ probe, remove: ['cnt_ApproveOrder', 'WhoAmI'], rows: [], source: NO_CALLS }), 'pass', `${label}: both named rows removed`);
+ // What the builder once did while custom-api was OFF — keep the row, report the removal as not performed, upload nothing — leaves the
+ // maker's removal undone, and its report excuses nothing.
+ const kept = removalEdit({ probe, rows: [API, WHO_AM_I], source: SOURCE, actions: false, log: 'Custom API removal not performed (custom-api disabled): cnt_ApproveOrder' });
+ const found = customApiProblems(kept);
+ assert.ok(found.some((entry) => /^edit: actions file must be the full desired bare array/.test(entry)), `${label}, the row kept: ${JSON.stringify(found)}`);
+ both(kept, 'fail', `${label}: the row kept`);
+ // Turning the removal into a clear still deletes WhoAmI, which the maker did not name.
+ both(removalEdit({ probe, rows: [], source: NO_CALLS }), 'fail', `${label}: turned into a clear`);
+ }
+});
+
+// The `custom-api` flag was removed (Custom API support is always available), and with it every rule that graded its gate. Older runs recorded
+// the probe, so a probe is neither required nor refused: a run graded with no probe, or with one that printed `disabled` or something unreadable,
+// gets the grade it gets with an `enabled` probe — the discovery, binding, runtime and preservation checks decide it.
+test('no rule grades a custom-api gate: a run with no probe, or with one that printed disabled or something unreadable, grades as one that printed enabled', () => {
+ assert.ok(![...WORKFLOW_ASSERTIONS.keys()].some((key) => /after a disabled or unreadable feature gate/.test(key)), 'the Phase 4.6 gate rule is not registered');
+ const variant = (mutate) => {
+ const fixture = mixedFixture();
+ mutate(fixture.events.filter((call) => CUSTOM_API_PROBE.test(call.command)), fixture);
+ return fixture;
+ };
+ for (const [label, fixture] of [
+ ['an enabled probe (the control)', mixedFixture()],
+ ['no probe at all', variant((probes, fixture) => { fixture.events = fixture.events.filter((call) => !probes.includes(call)); })],
+ ['every probe printed disabled', variant((probes) => { for (const call of probes) call.result = 'disabled'; })],
+ ['every probe unreadable', variant((probes) => { for (const call of probes) call.result = 'maybe'; })],
+ ['discovery after a disabled probe', variant((probes, fixture) => { event(fixture, 'gate-create').result = 'disabled'; })],
+ ]) {
+ assert.deepStrictEqual(customApiProblems(fixture), [], label);
+ both(fixture, 'pass', label);
+ }
+ // What the gate rules once refused is graded on its own evidence now: a create with Custom API rows after a disabled probe passes when its
+ // discovery, bindings and calls agree, and fails when they do not.
+ const created = createFixture({ rows: [API], plan: CUSTOM_PLAN, source: CUSTOM_ONLY, customApi: 'disabled', builtIns: 'disabled' });
+ both(created, 'pass', 'a create after a disabled probe');
+ const undiscovered = createFixture({ rows: [API], plan: CUSTOM_PLAN, source: CUSTOM_ONLY, customApi: 'disabled', builtIns: 'disabled', discovery: false });
+ both(undiscovered, 'fail', 'a create with no discovery');
+});
+
+// A maker who asked for failure telemetry may hand the page's appInsights prop to the canonical reporter (references/rules.md
+// "Missing Error Handling") as its seventh argument. In a built-in operation's helper or handlers that mention is not exempt from
+// the built-in privacy check: no grader proves the report carries only the host's own diagnostics, so the check fails closed and
+// refuses it, as it refuses every other path from a built-in call to telemetry.
+const RULES = require('node:fs').readFileSync(require('node:path').join(__dirname, '..', '..', '..', '..', 'plugins', 'model-apps', 'references', 'rules.md'), 'utf8').replace(/\r\n/g, '\n');
+const SECTION = RULES.slice(RULES.indexOf('\n### 2. Missing Error Handling\n'), RULES.indexOf('\n### 3. '));
+const BLOCKS = [...SECTION.matchAll(/```tsx\n([\s\S]*?)\n```/g)].map((match) => match[1]);
+const FOUNDATION = BLOCKS.find((block) => /\bfunction reportPageError\(/.test(block));
+const TELEMETRY = BLOCKS.find((block) => /appInsights\?\.trackException\?\.\(/.test(block));
+const lines = FOUNDATION.split('\n');
+const anchor = lines.findIndex((line) => /^\s*console\.error\(/.test(line));
+const WITH_TELEMETRY = [...lines.slice(0, anchor + 1), ...TELEMETRY.split('\n'), ...lines.slice(anchor + 1)].join('\n');
+const BODY_AT = WITH_TELEMETRY.indexOf('function PageBody(');
+const WRAPPER_AT = WITH_TELEMETRY.indexOf('const GeneratedComponent = ');
+
+// The request helper sits INSIDE PageBody so it closes over the page's authorized appInsights prop: the seventh argument
+// is then the only appInsights mention in the helper and its handler.
+const AUTHORIZED = `${WITH_TELEMETRY.slice(0, BODY_AT)}type BuiltInResult = { ok: boolean; outputs?: Record<string, unknown>; error?: { message?: string; code?: string; status?: number } };
+type BuiltInApi = { executeFunction?: (request: { name: string }) => Promise<BuiltInResult> };
+type IdentityView = { identity?: { userId: string; businessUnitId: string; organizationId: string }; error?: PageErrorView };
+
+const GUID = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
+
+function ownString(outputs: Record<string, unknown>, field: string): string | undefined {
+ const value = Object.prototype.hasOwnProperty.call(outputs, field) ? outputs[field] : undefined;
+ return typeof value === 'string' ? value : undefined;
+}
+
+function PageBody(props: GeneratedComponentProps & { appInsights?: PageErrorTelemetry }) {
+ const { dataApi, appInsights } = props;
+ const api = dataApi as unknown as BuiltInApi;
+ const mounted = React.useRef(true);
+ React.useEffect(() => () => { mounted.current = false; }, []);
+ const [identityState, setIdentityState] = React.useState<{ pending: boolean; view: IdentityView }>({ pending: false, view: {} });
+ const identityRequest = React.useRef(0);
+
+ async function readIdentity(client: BuiltInApi): Promise<IdentityView> {
+ if (typeof client.executeFunction !== 'function') {
+ const view = reportPageError(PAGE_NAME, 'showIdentity', undefined, 'executeFunction is not available in this player', 'read');
+ view.fallbackKey = 'error.builtinUnsupported';
+ return { error: view };
+ }
+ try {
+ const res = await client.executeFunction({ name: 'WhoAmI' });
+ if (res.ok !== true) {
+ const view = reportPageError(PAGE_NAME, 'showIdentity', res.error?.code, res.error?.message, 'read', undefined, appInsights);
+ const unavailable = typeof res.error?.status === 'number' && res.error.status === 404;
+ view.fallbackKey = unavailable ? 'error.builtinUnavailable' : 'error.builtinFailed';
+ view.message = unavailable ? '' : view.message;
+ return { error: view };
+ }
+ const outputs = res.outputs;
+ if (!outputs || typeof outputs !== 'object' || Array.isArray(outputs)) {
+ const view = reportPageError(PAGE_NAME, 'showIdentity', undefined, 'WhoAmI returned no output object', 'read');
+ view.fallbackKey = 'error.builtinUnexpected';
+ view.message = '';
+ return { error: view };
+ }
+ const userId = ownString(outputs, 'UserId');
+ const businessUnitId = ownString(outputs, 'BusinessUnitId');
+ const organizationId = ownString(outputs, 'OrganizationId');
+ if (![userId, businessUnitId, organizationId].every((id) => typeof id === 'string' && GUID.test(id))) {
+ const view = reportPageError(PAGE_NAME, 'showIdentity', undefined, 'WhoAmI returned an unexpected identity', 'read');
+ view.fallbackKey = 'error.builtinUnexpected';
+ view.message = '';
+ return { error: view };
+ }
+ return { identity: { userId: userId as string, businessUnitId: businessUnitId as string, organizationId: organizationId as string } };
+ } catch (error) {
+ const view = reportPageError(PAGE_NAME, 'showIdentity', undefined, error, 'read');
+ view.fallbackKey = 'error.builtinFailed';
+ view.message = '';
+ return { error: view };
+ }
+ }
+
+ const showIdentity = async () => {
+ if (identityState.pending) return;
+ const requestId = ++identityRequest.current;
+ setIdentityState({ pending: true, view: {} });
+ try {
+ const view = await readIdentity(api);
+ if (mounted.current && requestId === identityRequest.current) setIdentityState({ pending: false, view });
+ } catch (error) {
+ if (mounted.current && requestId === identityRequest.current) setIdentityState({ pending: false, view: { error: reportPageError(PAGE_NAME, 'showIdentity', undefined, error, 'read') } });
+ }
+ };
+
+ return (
+ <div>
+ <Button disabled={identityState.pending} onClick={() => void showIdentity()}>Show my Dataverse identity</Button>
+ <PageErrorBar error={identityState.view.error ?? null} />
+ {identityState.view.identity && <Text>Dataverse user id: {identityState.view.identity.userId}</Text>}
+ </div>
+ );
+}
+
+${WITH_TELEMETRY.slice(WRAPPER_AT)}`;
+
+function swap(source, from, to) {
+ assert.ok(source.includes(from), `the page holds: ${from}`);
+ return source.split(from).join(to);
+}
+
+test('a built-in failure report that hands the page\'s appInsights to the reporter is refused, however it is written', () => {
+ const report = "reportPageError(PAGE_NAME, 'showIdentity', res.error?.code, res.error?.message, 'read', undefined, appInsights);";
+ for (const [label, source] of [
+ ['the canonical read report with the telemetry argument', AUTHORIZED],
+ ['a direct emission beside the report', swap(AUTHORIZED, report, `${report}\n appInsights?.trackException?.(new Error('x'));`)],
+ ['the identity as the message', swap(AUTHORIZED, report, "reportPageError(PAGE_NAME, 'showIdentity', res.error?.code, String(res.outputs?.UserId), 'read', undefined, appInsights);")],
+ ['a retry beside the telemetry', swap(AUTHORIZED, report, "reportPageError(PAGE_NAME, 'showIdentity', res.error?.code, res.error?.message, 'read', showIdentity, appInsights);")],
+ ['an altered reporter', swap(AUTHORIZED, " normalizedMessage = line.length > 300 ? line.slice(0, 299) + '\\u2026' : line;", ' normalizedMessage = line;')],
+ // Record data dressed as host diagnostics: an awaited object built by the page, reported as if the host had returned it.
+ ['diagnostics fabricated from an awaited page value', swap(AUTHORIZED,
+ " const view = reportPageError(PAGE_NAME, 'showIdentity', undefined, error, 'read');",
+ " const fault = await Promise.resolve({ error: { code: 'not_permitted', message: String(props.pageInput?.recordId) } });\n const view = reportPageError(PAGE_NAME, 'showIdentity', fault.error?.code, fault.error?.message, 'read', undefined, appInsights);")],
+ ]) {
+ assert.ok(union.builtInRuntimeProblems(source, ['WhoAmI']).some((problem) => /logged, stored, copied or sent/.test(problem)), label);
+ }
+});
+
+// Under the canonical wrapper the page renders in PageBody, not in the default export, so a call made while PageBody renders is named for
+// what it is — not as PageBody being "handed" to the wrapper that renders it.
+test('a built-in call made while the wrapped PageBody renders is refused as a render-time call', () => {
+ const wrapped = swap(AUTHORIZED, "res.error?.message, 'read', undefined, appInsights);", "res.error?.message, 'read');");
+ assert.deepEqual(union.builtInRuntimeProblems(wrapped, ['WhoAmI']), [], 'neighbour: the wrapped page without the call passes');
+ const rendering = swap(wrapped, ' return (\n <div>\n <Button disabled={identityState.pending}', ' void readIdentity(api);\n return (\n <div>\n <Button disabled={identityState.pending}');
+ const found = union.builtInRuntimeProblems(rendering, ['WhoAmI']);
+ assert.ok(found.some((problem) => /while the page renders/.test(problem)), JSON.stringify(found));
+});
diff --git a/evals/model-apps/genpage/tests/assertions-layer-1.test.js b/evals/model-apps/genpage/tests/assertions-layer-1.test.js
index fd6056e22..894f384d6 100644
--- a/evals/model-apps/genpage/tests/assertions-layer-1.test.js
+++ b/evals/model-apps/genpage/tests/assertions-layer-1.test.js
@@ -1023,6 +1023,44 @@ test('a Custom API Bindings table missing required schema columns is rejected',
assert.equal(errors.filter((e) => e.code === 'missing-customapi-table').length, 1);
});
+// `## Dataverse Operations` is OPTIONAL: absent is no new built-in authoring, and every existing plan stays valid. When present it sits after Custom
+// API Bindings and before Solution Packaging, and is the exact sentinel or the built-in operation table under its not-checked verification line.
+const DATAVERSE_OPERATIONS = '## Dataverse Operations\nVerification: environment not-checked, runtime not-checked, privileges not-checked.\n'
+ + '| Name | Kind | Bound Entity | Display Name | Parameters | Response fields | Invoke |\n|------|------|--------------|--------------|------------|-----------------|--------|\n'
+ + '| WhoAmI | Function | (Global) | Current Dataverse identity | (none) | BusinessUnitId, UserId, OrganizationId | button |\n\n';
+const withOperations = (section, plan = validPlan()) => plan.replace('## Design Preferences', `${section}## Design Preferences`);
+
+test('Dataverse Operations is optional: a plan without it is unchanged, and the sentinel or the table after Custom API Bindings passes', () => {
+ assert.deepEqual(validateGenpagePlanSchema(validPlan()).filter((e) => /dataverse|order/i.test(`${e.code} ${e.section || ''}`)), []);
+ for (const section of [DATAVERSE_OPERATIONS, '## Dataverse Operations\nNo Dataverse operations.\n\n']) {
+ const errors = validateGenpagePlanSchema(withOperations(section));
+ assert.deepEqual(errors.filter((e) => e.code === 'section-order' || e.section === 'Dataverse Operations'), [], JSON.stringify(errors));
+ }
+ // Before Solution Packaging, as references/plan-schema.md orders them.
+ const both = withOperations(`${DATAVERSE_OPERATIONS}## Solution Packaging\n- Solution: ContosoApp\n\n`);
+ assert.deepEqual(validateGenpagePlanSchema(both).filter((e) => e.code === 'section-order'), []);
+});
+
+test('Dataverse Operations out of order, or anything but the sentinel or the table, is refused', () => {
+ const beforeCustomApis = validPlan()
+ .replace('## Custom API Bindings\nNo custom API bindings.\n\n', `${DATAVERSE_OPERATIONS}## Custom API Bindings\nNo custom API bindings.\n\n`);
+ assert.ok(validateGenpagePlanSchema(beforeCustomApis).some((e) => e.code === 'section-order'), 'before Custom API Bindings');
+ const afterPackaging = withOperations(`## Solution Packaging\n- Solution: ContosoApp\n\n${DATAVERSE_OPERATIONS}`);
+ assert.ok(validateGenpagePlanSchema(afterPackaging).some((e) => e.code === 'section-order'), 'after Solution Packaging');
+ for (const [label, section] of [
+ ['empty', '## Dataverse Operations\n\n'],
+ ['prose', '## Dataverse Operations\nAdd WhoAmI.\n\n'],
+ ['no verification line', DATAVERSE_OPERATIONS.replace('Verification: environment not-checked, runtime not-checked, privileges not-checked.\n', '')],
+ ['a leaked delimiter', '## Dataverse Operations\n----- BEGIN DATAVERSE OPERATIONS -----\nNo Dataverse operations.\n----- END DATAVERSE OPERATIONS -----\n\n'],
+ ['a column missing', DATAVERSE_OPERATIONS.replace(' Invoke |', '').replace('--------|\n', '\n').replace(' button |', '')],
+ ['not in the catalogue', DATAVERSE_OPERATIONS.replace('| WhoAmI |', '| whoami |')],
+ ['an on-load trigger', DATAVERSE_OPERATIONS.replace('| button |', '| on-load |')],
+ ]) {
+ const errors = validateGenpagePlanSchema(withOperations(section));
+ assert.ok(errors.some((e) => e.code === 'invalid-dataverse-operations' && e.section === 'Dataverse Operations'), `${label}: ${JSON.stringify(errors)}`);
+ }
+});
+
test('validateGenpagePlanSchema: page file paths must stay inside the working directory', () => {
for (const [file, codePattern] of [
['..\\outside.tsx', /separator|traversal|escape|absolute/i],
@@ -1116,4 +1154,334 @@ test('solutions query: the documented multi-line form (bash `\\` or PowerShell b
// be credited to an earlier dataverse-request.js call.
const unrelated = `${asked}node dataverse-request.js https://contoso.crm.dynamics.com GET 'WhoAmI'\n- solutions were discussed\n`;
assert.equal(check({ fixture: fix({ workflowLog: unrelated }), eval: evalStub(8) }).status, 'fail');
+});
+
+// --- The plan's Assumptions section and per-page semantic records (references/plan-schema.md) ------------------------------------
+
+const GOOD_A1 = [
+ '### A1 — Initial-load caching',
+ '- Decision: De-duplicate and cache the initial list read.',
+ '- Alternatives considered: An empty form with no initial read; uncached loading.',
+ '- Evidence: default: this page loads on mount, so Critical Rule 15 applies.',
+ '- Resolution: planner-default',
+].join('\n');
+const withAssumptions = (body, plan = validPlan()) => plan.replace('## Working Directory', `## Assumptions\n\n${body}\n\n## Working Directory`);
+const SEMANTICS = [
+ '',
+ '#### Data semantics',
+ '',
+ '##### F1',
+ '- Kind: filter',
+ '- Definition: Cards match the account name containing the search text.',
+ '- Source: User Requirements',
+ '- Requirement quote: simple account page',
+ '',
+ '#### Lookup metadata',
+ '',
+ 'None.',
+ '',
+].join('\n');
+const withSemantics = (plan, block = SEMANTICS) => `${plan.trimEnd()}\n${block}`;
+
+test('validateGenpagePlanSchema: a present but malformed Assumptions section fails invalid-assumptions; an absent one keeps the legacy pass', () => {
+ assert.deepEqual(validateGenpagePlanSchema(validPlan()), [], 'neighbour: a legacy plan without the section still passes');
+ for (const [label, body] of [
+ ['missing Resolution', GOOD_A1.replace(/\n- Resolution: planner-default/, '')],
+ ['duplicate id', `${GOOD_A1}\n\n${GOOD_A1}`],
+ ['unknown resolution', GOOD_A1.replace('planner-default', 'assumed')],
+ ['user-confirmed without Question/Answer', GOOD_A1.replace('planner-default', 'user-confirmed')],
+ ['evidence without a metadata:/sample:/default: prefix', GOOD_A1.replace('default: this page', 'this page')],
+ ]) {
+ const errors = validateGenpagePlanSchema(withAssumptions(body));
+ assert.ok(errors.some((error) => error.code === 'invalid-assumptions'), `${label}: ${JSON.stringify(errors)}`);
+ }
+ // Mode never waives malformed content: an App Spec projection with a malformed present section fails too.
+ const appBuilder = validPlan().replace('- Publisher Prefix: new', '- Mode: app-builder\n- Publisher Prefix: new');
+ assert.ok(validateGenpagePlanSchema(withAssumptions('### A1\n- Decision: x', appBuilder)).some((error) => error.code === 'invalid-assumptions'));
+});
+
+test('validateGenpagePlanSchema: Assumptions sits right after User Requirements, by name — misplaced is section-order', () => {
+ assert.deepEqual(validateGenpagePlanSchema(withAssumptions(GOOD_A1)), [], 'neighbour: a valid section in place');
+ assert.deepEqual(validateGenpagePlanSchema(withAssumptions('No assumptions.')), [], 'neighbour: the empty sentinel in place');
+ const misplaced = validPlan().replace('## Entity Creation Required', `## Assumptions\n\n${GOOD_A1}\n\n## Entity Creation Required`);
+ assert.ok(validateGenpagePlanSchema(misplaced).some((error) => error.code === 'section-order'), 'after Pages');
+ const first = validPlan().replace('## User Requirements', `## Assumptions\n\n${GOOD_A1}\n\n## User Requirements`);
+ assert.ok(validateGenpagePlanSchema(first).some((error) => error.code === 'section-order'), 'before User Requirements');
+ const late = validPlan().replace('## Plugin Root', `## Assumptions\n\n${GOOD_A1}\n\n## Plugin Root`);
+ assert.ok(validateGenpagePlanSchema(late).some((error) => error.code === 'section-order'), 'after Working Directory');
+ // The optional sections already placed by name keep their checks beside it.
+ const packaged = withAssumptions(GOOD_A1).replace('## Design Preferences', '## Solution Packaging\n- Package into solution: false\n\n## Design Preferences');
+ assert.deepEqual(validateGenpagePlanSchema(packaged).filter((error) => error.code === 'section-order'), []);
+});
+
+test('validateGenpagePlanSchema: present per-page semantic records are validated against Assumptions and the original requirements', () => {
+ assert.deepEqual(validateGenpagePlanSchema(withSemantics(withAssumptions(GOOD_A1))), [], 'neighbour: a complete record set passes');
+ const codes = (plan) => validateGenpagePlanSchema(plan).map((error) => error.code);
+ assert.deepEqual(codes(withSemantics(withAssumptions(GOOD_A1), SEMANTICS.replace('- Source: User Requirements\n- Requirement quote: simple account page', '- Source: A9'))), ['unknown-assumption']);
+ assert.deepEqual(codes(withSemantics(withAssumptions(GOOD_A1), SEMANTICS.replace('- Source: User Requirements\n', ''))), ['missing-semantic-source']);
+ assert.deepEqual(codes(withSemantics(withAssumptions(GOOD_A1), SEMANTICS.replace('simple account page', 'every account in the tenant'))), ['unmatched-requirement-quote']);
+ assert.ok(codes(withSemantics(withAssumptions(GOOD_A1), SEMANTICS.replace('None.', '| Table | Column |\n|---|---|\n| account | x |'))).every((code) => code === 'invalid-lookup-metadata'));
+ assert.deepEqual(codes(withSemantics(withAssumptions(GOOD_A1), SEMANTICS.replace('##### F1', '##### R1'))), ['invalid-data-semantics']);
+ // Required-new mode: a newly authored plan carries every part; an older plan is not asked to.
+ assert.deepEqual(validateGenpagePlanSchema(validPlan(), { requireSemantics: true }).map((error) => error.code), ['invalid-assumptions', 'invalid-data-semantics', 'invalid-lookup-metadata']);
+ assert.deepEqual(validateGenpagePlanSchema(withSemantics(withAssumptions('No assumptions.'), SEMANTICS.replace(/##### F1[\s\S]*?\n\n#### Lookup/, 'None.\n\n#### Lookup')), { requireSemantics: true }), []);
+});
+
+test('Phase 5a: a plan whose semantic records fail validation must not reach the builders', () => {
+ const check = PHASE_EXPECTATIONS.get('Phase 5a: Orchestrator validates the plan — at least one page, unique filenames, each page has a matching Per-Page Specifications subsection');
+ const built = { files: [{ name: 'account-overview.tsx', content: 'export default function P() { return null; }' }] };
+ assert.equal(check({ fixture: fix({ genpagePlan: withSemantics(withAssumptions(GOOD_A1)), ...built }), eval: evalStub() }).status, 'pass', 'neighbour: valid records');
+ for (const [label, plan] of [
+ ['malformed Assumptions', withSemantics(withAssumptions(GOOD_A1.replace('planner-default', 'assumed')))],
+ ['a dangling assumption', withSemantics(withAssumptions(GOOD_A1), SEMANTICS.replace('- Source: User Requirements\n- Requirement quote: simple account page', '- Source: A9'))],
+ ['a quote the requirements do not hold', withSemantics(withAssumptions(GOOD_A1), SEMANTICS.replace('simple account page', 'all accounts'))],
+ ['malformed lookup metadata', withSemantics(withAssumptions(GOOD_A1), SEMANTICS.replace('None.', 'Customer lookup, see metadata.'))],
+ ]) {
+ const result = check({ fixture: fix({ genpagePlan: plan, ...built }), eval: evalStub() });
+ assert.equal(result.status, 'fail', label);
+ assert.match(result.reason, /fails Phase 5a/, label);
+ }
+});
+
+// The plan-approval record is its own line: the words right after `Unattended default:` are `plan approval`, then an arrow and the
+// whole word `approved`. A semantic default — whose question, answer or reason may say "plan" or "approved" — never stands in for it.
+test('unattended plan approval is recognized only by its dedicated record, never by a semantic default that mentions approval', () => {
+ const check = WORKFLOW_ASSERTIONS.get('Phase 1 (Planner): The plan is presented via EnterPlanMode and user approval is requested');
+ const run = (log) => check({ fixture: fix({ workflowLog: log, genpagePlan: validPlan() }), eval: evalStub() });
+ for (const line of [
+ 'Unattended default: plan approval → approved (unattended mode; all semantic questions resolved)',
+ 'Unattended default: plan approval -> approved (--non-interactive flag)',
+ '- Unattended default: plan approval -> approved',
+ ' * Unattended default: plan approval → approved, including explicit optional packaging into ContosoPages.',
+ ]) {
+ assert.equal(run(`Unattended default: interaction mode → unattended (flag)\n${line}`).status, 'pass', line);
+ }
+ for (const line of [
+ 'Unattended default: A1 / plan-status → Approved (the only status the request names)',
+ 'Unattended default: A2 / opportunities-account-scope → Direct customer account only (planner default; approved plan)',
+ 'Unattended default: solution selection → Default (approval not required; approved by default)',
+ ]) {
+ const result = run(`Unattended default: interaction mode → unattended (flag)\n${line}`);
+ assert.equal(result.status, 'fail', line);
+ assert.match(result.reason, /does not record plan approval/, line);
+ }
+});
+
+// ---------- a newly authored plan's semantic records (evals 26 and 27) ----------
+
+const NEW_CONTRACT = "Phase 1 (Planner): The newly authored plan records its assumptions and every page's data semantics and lookup metadata, the approved preview carries the same records, and provenance is verified with --require-assumptions";
+const { loadFixtures } = require('../lib/fixture-loader.js');
+const scenarioFixture = (id) => {
+ const found = loadFixtures(path.join(__dirname, '..', 'fixtures')).find((fixture) => fixture.id === id);
+ assert.ok(found, `fixture ${id} exists`);
+ return found;
+};
+const gradeNewContract = (fixture) => PHASE_EXPECTATIONS.get(NEW_CONTRACT)({ fixture, eval: { id: fixture.id } });
+// A Windows checkout gives a fixture's text files CRLF line ends (git's core.autocrlf), and the graders read them as they are. A variant below
+// writes its lines with `\n`; `edit` and `asIn` write each `\n` as the line end the fixture's text really has, so a variant is graded in the
+// checkout's own bytes, and `edit` fails when its text is not there: a change that finds nothing would grade the fixture itself, not a variant.
+// `from` may also be a pattern, written with `\r?\n` so that it matches either line end.
+const asIn = (text, lines) => lines.replace(/\r?\n/g, text.includes('\r\n') ? '\r\n' : '\n');
+const edit = (text, from, to) => {
+ const find = typeof from === 'string' ? asIn(text, from) : from;
+ assert.ok(typeof find === 'string' ? text.includes(find) : text.search(find) >= 0, `the fixture's text has ${JSON.stringify(String(find))}`);
+ return text.replace(find, () => asIn(text, to));
+};
+
+test('a newly authored plan passes with its records, the same approved preview and a --require-assumptions verification of exactly those records', () => {
+ const fixture = scenarioFixture(27);
+ assert.deepEqual(gradeNewContract(fixture), { status: 'pass', reason: '' });
+});
+
+test('a newly authored plan without its records, preview or matching verification fails — it never skips', () => {
+ const base = scenarioFixture(27);
+ const variant = (change) => {
+ const copy = structuredClone({ ...base, files: [] });
+ change(copy);
+ return gradeNewContract(copy);
+ };
+ for (const [label, change, reason] of [
+ ['no ## Assumptions in the written plan', (f) => { f.genpagePlan = edit(f.genpagePlan, /\r?\n## Assumptions\r?\n[\s\S]*?\r?\n## Working Directory\r?\n/, '\n## Working Directory\n'); }, /Assumptions/],
+ ['no Data semantics for the page', (f) => { f.genpagePlan = edit(f.genpagePlan, '#### Data semantics\nNone.\n\n', ''); }, /Data semantics/],
+ ['no approved preview declared', (f) => { delete f.manifest.semantics; }, /approved preview/],
+ ['an assumption the preview never showed', (f) => { f.genpagePlan = edit(f.genpagePlan, '- Resolution: planner-default\n\n### A2', '- Resolution: planner-default\n\n### A3 — Extra\n- Decision: Hide archived orders.\n- Alternatives considered: Show them.\n- Evidence: default: none stated.\n- Resolution: planner-default\n\n### A2'); }, /differs from the approved preview/],
+ ['a verification whose hash is another plan\'s', (f) => { for (const event of f.events) if (event.result?.semanticsHash) event.result.semanticsHash = '0'.repeat(64); }, /semanticsHash is not the hash/],
+ ['a verification that failed', (f) => { for (const event of f.events) if (event.result?.semanticsHash) event.result.ok = false; }, /did not pass/],
+ ]) {
+ const result = variant(change);
+ assert.equal(result.status, 'fail', label);
+ assert.match(result.reason, reason, `${label}: ${result.reason}`);
+ }
+});
+
+// ---------- eval 26: the answered question, the lookup metadata behind the records, the types and the gate ----------
+
+const SEMANTIC_QUESTION = 'Phase 1 (Planner): The open account-scope question reaches the maker as needs_input with no default, the answer returns to the planner by its question id, and the written plan and the approved preview record it as a user-confirmed assumption before approval';
+const LOOKUP_DISCOVERY = "Phase 1 (Planner): get-lookup-metadata.js reads opportunity's lookups before approval, its successful answer is the saved lookup-metadata.json, and every recorded lookup is observed with the complete targets and concrete paths it read";
+const LOOKUP_TYPES = "Phase 4: RuntimeTypes.ts is generated for opportunity and types each recorded lookup's read property with exactly its recorded targets";
+const OBSERVED_GATE = "Phase 5a: The page is generated only after provenance is verified with --require-assumptions --require-observed-lookups --lookup-metadata on this plan's records";
+const grade = (text, fixture) => PHASE_EXPECTATIONS.get(text)({ fixture, eval: { id: fixture.id } });
+// A changed copy of fixture 26: the manifest, events, artifacts and documents are cloned, so a variant never leaks into another.
+const variant26 = (change) => {
+ const copy = structuredClone({ ...scenarioFixture(26), files: [] });
+ change(copy);
+ return copy;
+};
+const event26 = (fixture, id) => fixture.events.find((event) => event.id === id);
+const interactions26 = (fixture, change) => {
+ const entries = JSON.parse(fixture.artifacts['semantic-interactions.json']);
+ fixture.artifacts['semantic-interactions.json'] = JSON.stringify(change(entries));
+};
+const moveEvent26 = (fixture, id, after) => {
+ const [moved] = fixture.events.splice(fixture.events.findIndex((event) => event.id === id), 1);
+ fixture.events.splice(fixture.events.findIndex((event) => event.id === after) + 1, 0, moved);
+};
+const assertFails26 = (text, cases) => {
+ for (const [label, change, reason] of cases) {
+ const result = grade(text, variant26(change));
+ assert.equal(result.status, 'fail', label);
+ assert.match(result.reason, reason, `${label}: ${result.reason}`);
+ }
+};
+
+test('eval 26: the answered question, the lookup metadata read, the typed lookup, the gate and the new contract all pass', () => {
+ const fixture = scenarioFixture(26);
+ for (const text of [SEMANTIC_QUESTION, LOOKUP_DISCOVERY, NEW_CONTRACT, LOOKUP_TYPES, OBSERVED_GATE]) {
+ assert.deepEqual(grade(text, fixture), { status: 'pass', reason: '' }, text);
+ }
+});
+
+// The graders read a fixture as the checkout gives it — CRLF line ends on Windows, LF elsewhere — so both scenarios are graded here in each,
+// whichever this checkout gave them: every text the loader read from a file is written with those line ends (the manifest and the events are
+// parsed JSON, with no line ends of their own). Both pass in each, and a variant whose change spans lines fails in each.
+test('eval 26 and 27: the graders give the same verdicts to a fixture with LF and with CRLF line ends', () => {
+ const withLineEnds = (fixture, eol) => {
+ const copy = structuredClone(fixture);
+ const ends = (text) => (typeof text === 'string' ? text.replace(/\r?\n/g, eol) : text);
+ for (const key of ['workflowLog', 'genpagePlan', 'genpageEditPlan', 'runtimeTypes', 'entityCreationLog']) copy[key] = ends(copy[key]);
+ for (const name of Object.keys(copy.artifacts)) copy.artifacts[name] = ends(copy.artifacts[name]);
+ for (const file of copy.files) file.content = ends(file.content);
+ return copy;
+ };
+ const [base26, base27] = [scenarioFixture(26), scenarioFixture(27)];
+ for (const [ends, eol] of [['LF', '\n'], ['CRLF', '\r\n']]) {
+ const fixture = withLineEnds(base26, eol);
+ assert.equal(fixture.genpagePlan.includes('\r\n'), eol === '\r\n', `${ends}: the plan is written with ${ends} line ends`);
+ for (const text of [SEMANTIC_QUESTION, LOOKUP_DISCOVERY, NEW_CONTRACT, LOOKUP_TYPES, OBSERVED_GATE]) {
+ assert.deepEqual(grade(text, fixture), { status: 'pass', reason: '' }, `${ends}: ${text}`);
+ }
+ assert.deepEqual(gradeNewContract(withLineEnds(base27, eol)), { status: 'pass', reason: '' }, `${ends}: eval 27`);
+ const unasked = withLineEnds(base26, eol);
+ unasked.workflowLog = edit(unasked.workflowLog, '- AskUserQuestion: Which opportunities should this account show? → Direct customer\n', '');
+ assert.equal(grade(SEMANTIC_QUESTION, unasked).status, 'fail', `${ends}: the question never asked`);
+ const unrecorded = withLineEnds(base27, eol);
+ unrecorded.genpagePlan = edit(unrecorded.genpagePlan, /\r?\n## Assumptions\r?\n[\s\S]*?\r?\n## Working Directory\r?\n/, '\n## Working Directory\n');
+ assert.equal(gradeNewContract(unrecorded).status, 'fail', `${ends}: no assumptions in the written plan`);
+ }
+});
+
+test('eval 26: a question that was not asked, answered, handed back, recorded or approved in that order fails — it never skips', () => {
+ const SCOPE_LINE = '- AskUserQuestion: Which opportunities should this account show? → Direct customer\n';
+ assertFails26(SEMANTIC_QUESTION, [
+ ['no interactions declared', (f) => { delete f.manifest.semantics.interactions; }, /semantics\.interactions/],
+ ['the answer removed before approval', (f) => interactions26(f, (entries) => entries.filter((entry) => entry.type !== 'answer')), /approved while opportunities-account-scope was unanswered/],
+ ['approval before the answer', (f) => interactions26(f, (entries) => [entries[0], entries[2], entries[1]]), /unanswered/],
+ ['a pre-settled default on a question with three candidates', (f) => {
+ event26(f, 'planner-discovery').result.questions[0].options[1].default = true;
+ interactions26(f, (entries) => { entries[0].defaults = ['Direct customer']; return entries; });
+ }, /several candidates carries no default/],
+ ['the options differ from the planner\'s', (f) => interactions26(f, (entries) => { entries[0].options = ['Direct customer']; return entries; }), /not the ones the planner returned/],
+ ['an answer that is not an option', (f) => interactions26(f, (entries) => { entries[1].selected = 'Every account'; return entries; }), /not one of the options/],
+ ['no AskUserQuestion for it in the log', (f) => { f.workflowLog = edit(f.workflowLog, SCOPE_LINE, ''); }, /AskUserQuestion: Which opportunities should this account show\? → Direct customer/],
+ ['the plan approved before the question was asked', (f) => { f.workflowLog = edit(f.workflowLog, SCOPE_LINE, '') + asIn(f.workflowLog, `\n${SCOPE_LINE}`); }, /approved before the question was answered/],
+ ['an unattended default for a question with no default', (f) => interactions26(f, (entries) => { entries[1].source = 'unattended-default'; return entries; }), /only the one option the planner marked/],
+ ['the answer never handed back to the planner', (f) => interactions26(f, (entries) => { entries[1].event = 'planner-discovery'; return entries; }), /no planner event after the question carries its answer/],
+ ['a re-invocation that does not carry the answer', (f) => { event26(f, 'planner-answers').command = 'Task genpage-planner (answers: app → Sales Hub)'; }, /does not hand back opportunities-account-scope → Direct customer/],
+ ['the written plan records another answer', (f) => { f.genpagePlan = f.genpagePlan.replace('- Answer: Direct customer', '- Answer: Parent account'); }, /the written plan records A1's Answer as "Parent account"/],
+ ['the preview records another answer', (f) => { f.artifacts['approved-plan.md'] = f.artifacts['approved-plan.md'].replace('- Answer: Direct customer', '- Answer: Customer plus contacts'); }, /the approved preview records A1's Answer/],
+ ['no Assumptions in the written plan', (f) => { f.genpagePlan = edit(f.genpagePlan, /\r?\n## Assumptions\r?\n[\s\S]*?\r?\n## Working Directory\r?\n/, '\n## Working Directory\n'); }, /the written plan records no assumption answering opportunities-account-scope/],
+ ['the preview saved before the answer reached the planner', (f) => moveEvent26(f, 'save-approved', 'planner-discovery'), /saved before the answer reached the planner/],
+ ['an approval of another preview', (f) => interactions26(f, (entries) => { entries[2].preview = 'genpage-plan.md'; return entries; }), /not the approved preview the fixture declares/],
+ ]);
+});
+
+test('eval 26: the lookup records must come from a successful lookup metadata read the run saved before approval', () => {
+ const metadata = (f) => JSON.parse(f.artifacts['lookup-metadata.json']);
+ assertFails26(LOOKUP_DISCOVERY, [
+ ['no lookup metadata declared', (f) => { delete f.manifest.semantics.lookupMetadata; }, /semantics\.lookupMetadata/],
+ ['no get-lookup-metadata.js read', (f) => { f.events = f.events.filter((event) => event.id !== 'lookup-metadata'); }, /never read opportunity/],
+ ['a saved file that is not the answer read', (f) => {
+ const changed = metadata(f);
+ changed.tables[0].lookups[0].targets = ['account'];
+ f.artifacts['lookup-metadata.json'] = JSON.stringify(changed);
+ }, /no get-lookup-metadata.js answer is the saved lookup-metadata.json/],
+ ['a failed read', (f) => {
+ const failed = { ok: false, code: 'LOOKUP_RELATIONSHIPS_UNREADABLE', error: 'opportunity: the relationship read was refused' };
+ f.artifacts['lookup-metadata.json'] = JSON.stringify(failed);
+ event26(f, 'lookup-metadata').result = failed;
+ }, /not a successful get-lookup-metadata.js answer/],
+ ['metadata read after the approval', (f) => moveEvent26(f, 'lookup-metadata', 'save-approved'), /read after the plan was approved/],
+ ['a record whose targets are not the complete set read', (f) => { f.genpagePlan = f.genpagePlan.replace('| _customerid_value | account, contact |', '| _customerid_value | account |'); }, /not the complete set read/],
+ ['an existing table\'s lookup left planned', (f) => { f.genpagePlan = f.genpagePlan.replace('customer navigation; customer picker | observed |', 'customer navigation; customer picker | planned |'); }, /recorded planned, but opportunity exists/],
+ ]);
+});
+
+test('eval 26: RuntimeTypes.ts must be generated for the table and type the lookup with exactly the recorded targets', () => {
+ assertFails26(LOOKUP_TYPES, [
+ ['RuntimeTypes.ts not captured', (f) => { f.runtimeTypes = null; }, /RuntimeTypes.ts was not captured/],
+ ['types not generated for opportunity', (f) => { f.events = f.events.filter((event) => event.id !== 'generate-types'); }, /genpage.js types was not run for opportunity/],
+ ['a one-target type', (f) => { f.runtimeTypes = edit(f.runtimeTypes, ' | `/contact(${string})`,\n readonly customeridname', ',\n readonly customeridname'); }, /types opportunity._customerid_value as account, the plan records account, contact/],
+ ['the read property not declared', (f) => { f.runtimeTypes = edit(f.runtimeTypes, /^ {4}_customerid_value:.*\r?\n/m, ''); }, /does not declare opportunity._customerid_value/],
+ ]);
+});
+
+test('eval 26: generation waits for a passing --require-observed-lookups verification of these records — removing the manifest key does not turn it off', () => {
+ const gate = (f) => event26(f, 'plan-verify-5a');
+ assertFails26(OBSERVED_GATE, [
+ ['no gate', (f) => { f.events = f.events.filter((event) => event.id !== 'plan-verify-5a'); }, /not gated by a verification with --require-assumptions --require-observed-lookups --lookup-metadata/],
+ ['the gate after the page was written', (f) => moveEvent26(f, 'plan-verify-5a', 'write-page'), /ran after the page was generated/],
+ ['the gate verified other records', (f) => { gate(f).result = { ...gate(f).result, semanticsHash: '0'.repeat(64) }; }, /no observed-lookups verification passed/],
+ ['the gate failed', (f) => { gate(f).result = { ok: false, action: 'verify', semanticProblems: ['opportunity.customerid is still planned'] }; }, /no observed-lookups verification passed/],
+ ['the gate read another metadata file', (f) => { gate(f).command = gate(f).command.replace('/lookup-metadata.json', '/other-metadata.json'); }, /no observed-lookups verification passed/],
+ ['a lookup still planned', (f) => { f.genpagePlan = f.genpagePlan.replace('customer navigation; customer picker | observed |', 'customer navigation; customer picker | planned |'); }, /opportunity.customerid is still planned/],
+ ['the lookup metadata declaration removed', (f) => { delete f.manifest.semantics.lookupMetadata; }, /semantics\.lookupMetadata/],
+ ]);
+});
+
+test('eval 26: an unattended run that takes the one option the planner marked, hands it back and records it as an unattended default passes — and fails without its record', () => {
+ const RECORD = 'Unattended default: A1 / opportunities-account-scope → Direct customer account only (the request names the direct customer and metadata leaves one matching path)';
+ const unattended = (change = () => {}) => variant26((f) => {
+ event26(f, 'planner-discovery').result.questions[0].options = [{ label: 'Direct customer account only', description: 'The request names the direct customer.', default: true }];
+ event26(f, 'planner-answers').command = 'Task genpage-planner (answers: opportunities-account-scope → Direct customer account only; app → Sales Hub)';
+ interactions26(f, () => [
+ { type: 'needs_input', event: 'planner-discovery', question: 'opportunities-account-scope', options: ['Direct customer account only'], defaults: ['Direct customer account only'] },
+ { type: 'answer', event: 'planner-answers', question: 'opportunities-account-scope', selected: 'Direct customer account only', source: 'unattended-default' },
+ { type: 'approval', preview: 'approved-plan.md', outcome: 'approved', source: 'unattended-default' },
+ ]);
+ const settle = (text) => edit(text, '- Resolution: user-confirmed\n- Question: opportunities-account-scope\n- Answer: Direct customer\n',
+ `- Resolution: unattended-default\n- Question: opportunities-account-scope\n- Answer: Direct customer account only\n- Default record: ${RECORD}\n`);
+ f.genpagePlan = settle(f.genpagePlan);
+ f.artifacts['approved-plan.md'] = settle(f.artifacts['approved-plan.md']);
+ f.workflowLog = edit(edit(f.workflowLog, '- AskUserQuestion: Which opportunities should this account show? → Direct customer\n', `- ${RECORD}\n`),
+ '- ExitPlanMode → user approved the plan without changes\n', '- Unattended default: plan approval → approved (unattended mode; all semantic questions resolved)\n');
+ change(f);
+ });
+ assert.deepEqual(grade(SEMANTIC_QUESTION, unattended()), { status: 'pass', reason: '' });
+ for (const [label, change, reason] of [
+ ['the default record missing from the log', (f) => { f.workflowLog = edit(f.workflowLog, `- ${RECORD}\n`, ''); }, /does not hold A1's Default record/],
+ ['no plan-approval record', (f) => { f.workflowLog = edit(f.workflowLog, '- Unattended default: plan approval → approved (unattended mode; all semantic questions resolved)\n', ''); }, /no unattended plan-approval record/],
+ // The interaction artifact still lists the approval last; only the log says it came first.
+ ['the plan approved in the log before its default was recorded', (f) => {
+ const approval = '- Unattended default: plan approval → approved (unattended mode; all semantic questions resolved)\n';
+ f.workflowLog = asIn(f.workflowLog, approval) + edit(f.workflowLog, approval, '');
+ }, /approved before its unattended default was recorded/],
+ ['a second approval record after an early one', (f) => {
+ f.workflowLog = asIn(f.workflowLog, '- Unattended default: plan approval -> approved\n') + f.workflowLog;
+ }, /approved before its unattended default was recorded/],
+ ['an answer recorded as user-confirmed', (f) => { f.genpagePlan = edit(edit(f.genpagePlan, '- Resolution: unattended-default', '- Resolution: user-confirmed'), `- Default record: ${RECORD}\n`, ''); }, /records A1 as user-confirmed, not unattended-default/],
+ ]) {
+ const result = grade(SEMANTIC_QUESTION, unattended(change));
+ assert.equal(result.status, 'fail', label);
+ assert.match(result.reason, reason, `${label}: ${result.reason}`);
+ }
});
\ No newline at end of file
diff --git a/evals/model-apps/genpage/tests/built-in-operation-pattern.test.js b/evals/model-apps/genpage/tests/built-in-operation-pattern.test.js
new file mode 100644
index 000000000..bb20c151e
--- /dev/null
+++ b/evals/model-apps/genpage/tests/built-in-operation-pattern.test.js
@@ -0,0 +1,387 @@
+'use strict';
+// The generated call of a built-in Dataverse operation, as the evaluator reads a page's source (action-binding-union.js builtInRuntimeProblems).
+//
+// The reference is the pattern plugins/model-apps/references/dataverse-operations.md teaches — read from that document, so the document and the
+// evaluator cannot drift apart. It must pass; and each departure the reference forbids must fail, with the problem that names it: a call on mount
+// or at render, a handler handed to a timer, an effect, a ref or a child (or through an alias), a partial identity, a spread or serialized result,
+// a member read, a read from the root or `res.value`, outputs read before `res.ok`, no object check for an empty answer, an unbounded Version, raw
+// fault text, a status read out of the message, a message that says to deploy a Custom API, a pre-dispatch check that does not return, extra
+// request fields, no disabled button, one shared pending state, no stale request guard, no catch, and a logged result. A whole built-in-only
+// lifecycle through the Phase 5 evaluator passes with it too — and a built-in entry the page already held keeps the contract it declares.
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const { builtInRuntimeProblems } = require('../lib/action-binding-union.js');
+const { customApiProblems } = require('../lib/custom-api-contract.js');
+const { PHASE_EXPECTATIONS } = require('../lib/assertions-layer-1.js');
+const { PHASE5_EXPECTATIONS } = require('../lib/assertions-layer-2.js');
+const { getDataverseOperationCatalogue } = require('../../../../plugins/model-apps/scripts/lib/dataverse-operations.js');
+
+const REFERENCES = path.join(__dirname, '..', '..', '..', '..', 'plugins', 'model-apps', 'references');
+const DOC = path.join(REFERENCES, 'dataverse-operations.md');
+// The document shows the page's helpers, PageBody and boundary wrapper; the rest of the page is the page error block
+// references/rules.md publishes ("Missing Error Handling") — copied unchanged, up to its own example PageBody — which supplies
+// PAGE_NAME, reportPageError, PageErrorBar, PageErrorBoundary and the error copy holding the fixed built-in sentences. The
+// complete page is what the built-in checks read.
+const REFERENCE = (() => {
+ const text = fs.readFileSync(DOC, 'utf8').replace(/\r\n/g, '\n');
+ const section = text.slice(text.indexOf('\n## Generated call\n'));
+ const block = /```tsx\n([\s\S]*?)\n```/.exec(section);
+ assert.ok(block, 'the reference document holds the generated call');
+ const rules = fs.readFileSync(path.join(REFERENCES, 'rules.md'), 'utf8').replace(/\r\n/g, '\n');
+ const errors = rules.slice(rules.indexOf('\n### 2. Missing Error Handling\n'), rules.indexOf('\n### 3. '));
+ const foundation = [...errors.matchAll(/```tsx\n([\s\S]*?)\n```/g)].map((match) => match[1]).find((code) => /\bfunction reportPageError\(/.test(code));
+ assert.ok(foundation, 'rules.md publishes the canonical page error block');
+ return `${foundation.slice(0, foundation.indexOf('function PageBody('))}${block[1]}\n`;
+})();
+const BOTH = ['WhoAmI', 'RetrieveVersion'];
+const problems = (source, names = BOTH) => builtInRuntimeProblems(source, names);
+
+// One textual change to the reference; a change that does not apply is a broken test, not a pass.
+function mutated(find, replace) {
+ assert.ok(REFERENCE.includes(find), `the reference holds: ${find}`);
+ return REFERENCE.replace(find, replace);
+}
+
+test('the reference pattern of the document passes, for each operation alone and for both', () => {
+ assert.deepStrictEqual(problems(REFERENCE), []);
+ assert.deepStrictEqual(problems(REFERENCE, ['WhoAmI']), []);
+ assert.deepStrictEqual(problems(REFERENCE, ['RetrieveVersion']), []);
+});
+
+test('a call that is not the user\'s — on mount, at render, on a timer, in a memo, or a retry of itself — fails', () => {
+ for (const [label, source, reason] of [
+ ['an effect calls it', mutated('React.useEffect(() => () => { mounted.current = false; }, []);', 'React.useEffect(() => { void showIdentity(); return () => { mounted.current = false; }; }, []);'), /effect, a memo or a timer/],
+ ['an effect calls the helper', mutated('React.useEffect(() => () => { mounted.current = false; }, []);', 'React.useEffect(() => { void readIdentity(api); return () => { mounted.current = false; }; }, []);'), /effect, a memo or a timer/],
+ ['the render calls it', mutated(' return (\n <div>', ' void readVersion(api);\n return (\n <div>'), /while the page renders/],
+ ['a timer calls it', mutated(' if (identityState.pending) return;', ' if (identityState.pending) return;\n setTimeout(() => void readIdentity(api), 0);'), /effect, a memo or a timer/],
+ ['a memo calls it', mutated(' const identityRequest = React.useRef(0);', ' const identityRequest = React.useRef(0);\n React.useMemo(() => readIdentity(api), [api]);'), /effect, a memo or a timer/],
+ ['it retries itself', mutated(" const view = reportPageError(PAGE_NAME, 'showIdentity', res.error?.code, res.error?.message, 'read');", " if (res.error?.code === 'network') return readIdentity(api);\n const view = reportPageError(PAGE_NAME, 'showIdentity', res.error?.code, res.error?.message, 'read');"), /calls itself/],
+ ['no button reaches it', mutated('onClick={() => void showVersion()}', 'title="version"'), /not reached from a button/],
+ ]) {
+ const found = problems(source);
+ assert.ok(found.some((p) => reason.test(p)), `${label}: ${JSON.stringify(found)}`);
+ }
+});
+
+// The identity guard of readIdentity, and its object check: one block each that reports the unexpected shape and returns.
+const IDENTITY_GUARD = " if (![userId, businessUnitId, organizationId].every((id) => typeof id === 'string' && GUID.test(id))) {\n const view = reportPageError(PAGE_NAME, 'showIdentity', undefined, 'WhoAmI returned an unexpected identity', 'read');\n view.fallbackKey = 'error.builtinUnexpected';\n view.message = '';\n return { error: view };\n }\n";
+const IDENTITY_OBJECT_CHECK = " if (!outputs || typeof outputs !== 'object' || Array.isArray(outputs)) {\n const view = reportPageError(PAGE_NAME, 'showIdentity', undefined, 'WhoAmI returned no output object', 'read');\n view.fallbackKey = 'error.builtinUnexpected';\n view.message = '';\n return { error: view };\n }\n const userId";
+
+test('outputs are read only after the success check, through own-property reads of a checked object, and shown all or nothing', () => {
+ for (const [label, source, reason] of [
+ ['a partial identity', mutated(" if (![userId, businessUnitId, organizationId].every((id) => typeof id === 'string' && GUID.test(id))) {", ' if (!userId || !GUID.test(userId)) {'), /all or none/],
+ ['the identity is never tested', mutated(IDENTITY_GUARD, ''), /all or none/],
+ ['no object check (an empty or 204 answer)', mutated(IDENTITY_OBJECT_CHECK, ' const userId'), /non-null, non-array object/],
+ ['a member read', mutated("const userId = ownString(outputs, 'UserId');", 'const userId = outputs.UserId as string | undefined;'), /as a member/],
+ ['a destructured read', mutated("const version = ownString(outputs, 'Version');", 'const { Version: version } = outputs as { Version?: string };'), /as a member/],
+ ['a read from the result root', mutated("const userId = ownString(outputs, 'UserId');", "const userId = (res as unknown as { UserId?: string }).UserId ?? ownString(outputs, 'UserId');"), /from the result root/],
+ ['a spread of outputs', mutated(' return { version };', ' return { version, ...outputs };'), /spread, iterated or serialized/],
+ ['a serialized result', mutated(' return { version };', ' return { version: JSON.stringify(res.outputs) };'), /spread, iterated or serialized/],
+ ['an unbounded Version', mutated(' if (!version || version.length > 128) {', ' if (!version) {'), /1 to 128 characters/],
+ ['an empty Version shown', mutated(' if (!version || version.length > 128) {', ' if (version === undefined || version.length > 128) {'), /1 to 128 characters/],
+ ['no unexpected-shape sentence', REFERENCE.replace('The operation returned an unexpected response. No result was displayed.', 'Something went wrong.'), /unexpected shape must say/],
+ ]) {
+ const found = problems(source);
+ assert.ok(found.some((p) => reason.test(p)), `${label}: ${JSON.stringify(found)}`);
+ }
+});
+
+test('a failure shows only sanitized text: no stack, no status read out of the message, no advice to deploy a Custom API', () => {
+ for (const [label, source, reason] of [
+ ['a stack', mutated(" view.fallbackKey = 'error.builtinFailed';\n view.message = '';\n return { error: view };\n }\n}\n\nasync function readVersion(", " view.fallbackKey = 'error.builtinFailed';\n view.message = String((error as Error).stack);\n return { error: view };\n }\n}\n\nasync function readVersion("), /stack/],
+ ['a status from the words', mutated("const unavailable = typeof res.error?.status === 'number' && res.error.status === 404;", "const unavailable = res.error?.message?.includes('404') === true;"), /message's words/],
+ ['a 404 that says to deploy', REFERENCE.replace('The selected operation is unavailable in this environment or player. No fallback was attempted.', 'The selected operation is unavailable. Deploy the Custom API first.'), /deploy a Custom API/],
+ ]) {
+ const found = problems(source);
+ assert.ok(found.some((p) => reason.test(p)), `${label}: ${JSON.stringify(found)}`);
+ }
+});
+
+test('the request is exactly { name }, and a failed presence check returns before any request', () => {
+ for (const [label, source, reason] of [
+ ['parameters', mutated("api.executeFunction({ name: 'WhoAmI' })", "api.executeFunction({ name: 'WhoAmI', parameters: {} })"), /exactly \{ name \}/],
+ ['boundTo', mutated("api.executeFunction({ name: 'RetrieveVersion' })", "api.executeFunction({ name: 'RetrieveVersion', boundTo: { entityName: 'organization', id: 'x' } })"), /exactly \{ name \}/],
+ ['a presence check that does not return', mutated(" if (typeof api.executeFunction !== 'function') {\n const view = reportPageError(PAGE_NAME, 'showIdentity'", " if (typeof api.executeFunction !== 'function') console.warn('unsupported');\n {\n const view = reportPageError(PAGE_NAME, 'showIdentity'"), /return before any request/],
+ ]) {
+ const found = problems(source);
+ assert.ok(found.some((p) => reason.test(p)), `${label}: ${JSON.stringify(found)}`);
+ }
+});
+
+test('each button is disabled while its own call is pending, ignores a stale answer, catches a rejection, and nothing of the result is logged or kept', () => {
+ for (const [label, source, reason] of [
+ ['no disabled button', mutated('<Button disabled={identityState.pending} onClick={() => void showIdentity()}>', '<Button onClick={() => void showIdentity()}>'), /not disabled while the call is pending/],
+ ['one pending state for both', mutated('<Button disabled={versionState.pending} onClick={() => void showVersion()}>', '<Button disabled={identityState.pending} onClick={() => void showVersion()}>'), /pending state of its own/],
+ ['no stale-request guard', mutated(' if (mounted.current && requestId === identityRequest.current) setIdentityState({ pending: false, view });', ' if (mounted.current) setIdentityState({ pending: false, view });')
+ .replace(' const requestId = ++identityRequest.current;\n setIdentityState({ pending: true, view: {} });', ' setIdentityState({ pending: true, view: {} });')
+ .replace(" if (mounted.current && requestId === identityRequest.current) setIdentityState({ pending: false, view: { error: reportPageError(PAGE_NAME, 'showIdentity', undefined, error, 'read') } });", " if (mounted.current) setIdentityState({ pending: false, view: { error: reportPageError(PAGE_NAME, 'showIdentity', undefined, error, 'read') } });"), /stale request/],
+ // Both catches go: the request helper's own and the handler's.
+ ['no catch', mutated(" } catch (error) {\n if (mounted.current && requestId === versionRequest.current) setVersionState({ pending: false, view: { error: reportPageError(PAGE_NAME, 'showVersion', undefined, error, 'read') } });\n }\n };", ' } finally {\n }\n };')
+ .replace(" } catch (error) {\n const view = reportPageError(PAGE_NAME, 'showVersion', undefined, error, 'read');\n view.fallbackKey = 'error.builtinFailed';\n view.message = '';\n return { error: view };\n }\n}", ' } finally {\n }\n}'), /not caught/],
+ ['a logged result', mutated(' const view = await readIdentity(api);', ' const view = await readIdentity(api);\n console.log(view);'), /logged, stored, copied or sent/],
+ ['a stored result', mutated(' return { version };', ' localStorage.setItem(\'version\', version);\n return { version };'), /logged, stored, copied or sent/],
+ ]) {
+ const found = problems(source);
+ assert.ok(found.some((p) => reason.test(p)), `${label}: ${JSON.stringify(found)}`);
+ }
+});
+
+// ── Through the whole Phase 5 evaluator (custom-api-contract.js), in both layers ────────────────────────────────────────────────────────
+const RULE = 'Phase 5: Custom API discovery, gate, bare bindings, runtime calls and update preservation or explicit clear agree';
+const PAGE = '99999999-9999-4999-8999-999999999999';
+const APP = '88888888-8888-4888-8888-888888888888';
+const ENV = 'https://contoso.crm.dynamics.com';
+const ROWS = getDataverseOperationCatalogue().operations.map((operation) => ({ name: operation.name, isFunction: true, displayName: operation.displayName, parameterKinds: {} }));
+const [WHO_AM_I, RETRIEVE_VERSION] = ROWS;
+const TABLE_ROWS = {
+ WhoAmI: '| WhoAmI | Function | (Global) | Current Dataverse identity | (none) | BusinessUnitId, UserId, OrganizationId | button |',
+ RetrieveVersion: '| RetrieveVersion | Function | (Global) | Dataverse server version | (none) | Version | button |',
+};
+// The plan of a run that adds the named built-ins (none: the plan has no `## Dataverse Operations` section).
+const planFor = (names) => `## Custom API Bindings
+No custom API bindings.
+${names.length ? `
+## Dataverse Operations
+Verification: environment not-checked, runtime not-checked, privileges not-checked.
+| Name | Kind | Bound Entity | Display Name | Parameters | Response fields | Invoke |
+|------|------|--------------|--------------|------------|-----------------|--------|
+${names.map((name) => TABLE_ROWS[name]).join('\n')}
+` : ''}`;
+const listingEvent = () => ({ id: 'listing', command: 'node list-dataverse-operations.js', result: { ok: true, ...structuredClone(getDataverseOperationCatalogue()) } });
+const verdicts = (fixture) => [PHASE_EXPECTATIONS, PHASE5_EXPECTATIONS].map((map) => map.get(RULE)({ fixture, files: fixture.files, eval: { id: 24 } }));
+
+// A page that binds only the two built-ins: create with an enabled built-in gate, the listing and a re-probe.
+const fixture = (source) => ({
+ contractVersion: 2,
+ files: [{ name: 'page.tsx', content: source }],
+ artifacts: { 'stages/page.tsx': source, 'actions.json': JSON.stringify(ROWS), 'created/config.json': JSON.stringify({ actionBindings: ROWS }) },
+ genpagePlan: planFor(['WhoAmI', 'RetrieveVersion']),
+ workflowLog: 'Built-in operation create with the gate enabled.',
+ manifest: { customApi: { outputs: {}, stages: [{ id: 'create', target: 'page.tsx', source: 'stages/page.tsx', actions: 'actions.json', afterConfig: 'created/config.json', upload: 'create' }] } },
+ events: [
+ { id: 'custom-api-gate', command: 'node feature-flags.js custom-api', result: 'disabled' },
+ { id: 'builtin-gate', command: 'node feature-flags.js dataverse-operations', result: 'enabled' },
+ listingEvent(),
+ { id: 'builtin-regate', command: 'node feature-flags.js dataverse-operations', result: 'enabled' },
+ { id: 'write', command: 'Write page.tsx', artifact: 'stages/page.tsx' },
+ { id: 'create', command: 'node genpage-upload.js --code-file page.tsx --actions actions.json --add-to-sitemap', result: { ok: true, pageId: PAGE } },
+ ],
+});
+
+// An edit of a downloaded page that already holds `before`. With nothing in `add` it is an unrelated edit: both gates OFF, no `--actions`, the
+// bindings preserved. With rows in `add`, this run adds them (or replaces an entry of the same name, in its place): the built-in gate ON, the
+// listing, a re-probe, and the full array uploaded.
+function editFixture({ before, add = [], source }) {
+ const after = [
+ ...before.map((entry) => add.find((row) => row.name === entry.name) || entry),
+ ...add.filter((row) => !before.some((entry) => entry.name === row.name)),
+ ];
+ const identity = JSON.stringify({ pageId: PAGE, appId: APP });
+ const authoring = add.length > 0;
+ return {
+ contractVersion: 2,
+ files: [{ name: 'page.tsx', content: source }],
+ artifacts: {
+ 'stages/page.tsx': source, 'actions.json': JSON.stringify(after),
+ 'before/config.json': JSON.stringify({ actionBindings: before }), 'after/config.json': JSON.stringify({ actionBindings: after }),
+ 'before/page.json': identity, 'after/page.json': identity,
+ },
+ genpagePlan: planFor(add.map((row) => row.name)),
+ workflowLog: authoring ? 'An edit that adds a built-in operation the maker selected.' : 'An unrelated edit of a page that already binds built-in operations; its bindings are preserved.',
+ manifest: {
+ customApi: {
+ outputs: {},
+ stages: [{
+ id: 'edit', target: 'page.tsx', source: 'stages/page.tsx', beforeConfig: 'before/config.json', afterConfig: 'after/config.json', upload: 'edit',
+ ...(authoring && { actions: 'actions.json', change: { add } }),
+ }],
+ },
+ uploads: [{ event: 'edit', mode: 'update', beforeConfig: 'before/config.json', afterConfig: 'after/config.json', beforePage: 'before/page.json', afterPage: 'after/page.json' }],
+ },
+ events: [
+ { id: 'download', command: `node genpage.js download --env ${ENV} --page-id ${PAGE} --app-id ${APP} --output-directory before`, result: { ok: true, pages: [{ pageId: PAGE }] } },
+ { id: 'custom-api-gate', command: 'node feature-flags.js custom-api', result: 'disabled' },
+ { id: 'builtin-gate', command: 'node feature-flags.js dataverse-operations', result: authoring ? 'enabled' : 'disabled' },
+ ...(authoring ? [listingEvent(), { id: 'builtin-regate', command: 'node feature-flags.js dataverse-operations', result: 'enabled' }] : []),
+ { id: 'write', command: 'Write page.tsx', artifact: 'stages/page.tsx' },
+ { id: 'edit', command: `node genpage-upload.js --env ${ENV} --page-id ${PAGE} --app-id ${APP} --code-file page.tsx${authoring ? ' --actions actions.json' : ''}`, result: { ok: true, pageId: PAGE, appId: APP } },
+ ],
+ };
+}
+
+test('a built-in-only lifecycle with the reference page passes the Phase 5 evaluator in both layers, and the same page reading outputs before success fails', () => {
+ for (const [map, layer] of [[PHASE_EXPECTATIONS, 1], [PHASE5_EXPECTATIONS, 2]]) {
+ const good = fixture(REFERENCE);
+ const result = map.get(RULE)({ fixture: good, files: good.files, eval: { id: 24 } });
+ assert.equal(result.status, 'pass', `layer ${layer}: ${result.reason}`);
+ }
+ const early = mutated(" const res = await api.executeFunction({ name: 'RetrieveVersion' });\n if (res.ok !== true) {", " const res = await api.executeFunction({ name: 'RetrieveVersion' });\n const early = res.outputs;\n if (res.ok !== true) {");
+ const bad = fixture(early);
+ const result = PHASE_EXPECTATIONS.get(RULE)({ fixture: bad, files: bad.files, eval: { id: 24 } });
+ assert.equal(result.status, 'fail');
+ assert.match(result.reason, /RetrieveVersion: response\.ok must refuse before outputs are read/);
+ // The pattern is part of the lifecycle verdict: a page that calls WhoAmI from an effect fails the Phase 5 evaluator itself.
+ const mounted = fixture(mutated('React.useEffect(() => () => { mounted.current = false; }, []);', 'React.useEffect(() => { void showIdentity(); return () => { mounted.current = false; }; }, []);'));
+ for (const map of [PHASE_EXPECTATIONS, PHASE5_EXPECTATIONS]) {
+ const verdict = map.get(RULE)({ fixture: mounted, files: mounted.files, eval: { id: 24 } });
+ assert.equal(verdict.status, 'fail');
+ assert.match(verdict.reason, /WhoAmI: called from an effect, a memo or a timer/);
+ }
+});
+
+// ── A built-in entry the page already held keeps the contract it declares ──────────────────────────────────────────────────────────────
+// Only a built-in this run adds or replaces is held to the catalogue's contract — a Function with no input and no target — and to the generated
+// pattern. An entry downloaded with the page and preserved by an unrelated edit keeps what it declares: an input of its own, or no `isFunction` at
+// all (legacy: the runtime enforces the kind only when it is a real boolean). Its call is still checked against that, as a Custom API's is.
+const LEGACY_WHO_AM_I = { ...WHO_AM_I, displayName: 'Legacy identity', parameterKinds: { Legacy: 'String' } };
+const LEGACY_CALL = mutated("api.executeFunction({ name: 'WhoAmI' })", "api.executeFunction({ name: 'WhoAmI', parameters: { Legacy: 'kept' } })");
+// A call that also reads an output by member — one the catalogue does not list.
+const READS_EXTRA = (source, output) => {
+ const find = "const userId = ownString(outputs, 'UserId');";
+ assert.ok(source.includes(find));
+ return source.replace(find, `const userId = ownString(outputs, 'UserId') ?? String(res.outputs?.${output});`);
+};
+
+test('a preserved built-in entry keeps the contract it declares — an input of its own, or no kind at all — through an unrelated edit with both gates OFF', () => {
+ for (const [label, before, source, outputs = {}] of [
+ ['a declared input and its matching call', [LEGACY_WHO_AM_I, RETRIEVE_VERSION], LEGACY_CALL],
+ ['an output the scenario declares for it', [LEGACY_WHO_AM_I, RETRIEVE_VERSION], READS_EXTRA(LEGACY_CALL, 'Legacy'), { WhoAmI: ['UserId', 'Legacy'] }],
+ ['no isFunction and no parameterKinds', [{ name: 'WhoAmI', displayName: 'Legacy identity' }, RETRIEVE_VERSION], REFERENCE],
+ ['the catalogue projection itself', ROWS, REFERENCE],
+ ]) {
+ const edit = editFixture({ before, source });
+ edit.manifest.customApi.outputs = outputs;
+ for (const [index, result] of verdicts(edit).entries()) {
+ assert.equal(result.status, 'pass', `${label}, layer ${index + 1}: ${result.reason}`);
+ }
+ }
+ // Kept is not unchecked: the call must still agree with what the entry declares.
+ const missingInput = customApiProblems(editFixture({ before: [LEGACY_WHO_AM_I, RETRIEVE_VERSION], source: REFERENCE }));
+ assert.ok(missingInput.includes('WhoAmI: runtime parameter names differ from the declared kinds and discovered lookups'), JSON.stringify(missingInput));
+ const declaredAction = customApiProblems(editFixture({ before: [{ ...WHO_AM_I, isFunction: false }, RETRIEVE_VERSION], source: REFERENCE }));
+ assert.ok(declaredAction.includes('WhoAmI: runtime method disagrees with discovered Action/Function kind'), JSON.stringify(declaredAction));
+});
+
+test('a built-in this run adds or replaces is held to the catalogue\'s contract, beside a preserved legacy entry that keeps its own', () => {
+ // RetrieveVersion added this run; the page's legacy WhoAmI, with an input of its own, stays as it was written.
+ for (const [index, result] of verdicts(editFixture({ before: [LEGACY_WHO_AM_I], add: [RETRIEVE_VERSION], source: LEGACY_CALL })).entries()) {
+ assert.equal(result.status, 'pass', `layer ${index + 1}: ${result.reason}`);
+ }
+ // A WhoAmI this run puts in place of the legacy entry is new authoring: its call takes no input.
+ const replaced = customApiProblems(editFixture({ before: [LEGACY_WHO_AM_I, RETRIEVE_VERSION], add: [WHO_AM_I], source: LEGACY_CALL }));
+ assert.ok(replaced.includes('WhoAmI: runtime parameter names differ from the declared kinds and discovered lookups'), JSON.stringify(replaced));
+ assert.ok(replaced.includes('WhoAmI: the request must be exactly { name } — no parameters and no boundTo'), JSON.stringify(replaced));
+ // On create, an authored call with an input, as an Action, or with a target is refused.
+ for (const [label, source, problem] of [
+ ['an input', LEGACY_CALL, 'WhoAmI: runtime parameter names differ from the declared kinds and discovered lookups'],
+ ['an Action', mutated("api.executeFunction({ name: 'WhoAmI' })", "api.executeAction({ name: 'WhoAmI' })"), 'WhoAmI: runtime method disagrees with discovered Action/Function kind'],
+ ['a target', mutated("api.executeFunction({ name: 'WhoAmI' })", "api.executeFunction({ name: 'WhoAmI', boundTo: { entityName: 'systemuser', id: 'x' } })"), 'WhoAmI: global operation must omit boundTo'],
+ ]) {
+ const found = customApiProblems(fixture(source));
+ assert.ok(found.includes(problem), `${label}: ${JSON.stringify(found)}`);
+ }
+ // A scenario that declares more outputs for WhoAmI does not widen what a NEW call may read: its response is the catalogue's.
+ const widened = fixture(READS_EXTRA(REFERENCE, 'SystemUserName'));
+ widened.manifest.customApi.outputs = { WhoAmI: ['UserId', 'SystemUserName'] };
+ const read = customApiProblems(widened);
+ assert.ok(read.includes('WhoAmI: runtime reads an undeclared output'), JSON.stringify(read));
+});
+
+// ── A handler handed on, not called ──────────────────────────────────────────────────────────────────────────────────────────────────
+// `setTimeout(showIdentity, 0)` names the handler without calling it, and the timer then calls it with no click. Handing a handler or a helper to
+// an effect, a memo, a timer, a frame or a microtask fails, whatever else also calls it — a button included. A constant that names it is another
+// name for it, followed the same way. Any other hand-off (a ref, a child's prop) could call it without a click too. Naming it in the button's own
+// onClick, through an alias the button calls, or in a hook's dependency list calls nothing.
+const BEFORE_RENDER = ' return (\n <div>';
+const atRender = (lines) => mutated(BEFORE_RENDER, `${lines}\n${BEFORE_RENDER}`);
+
+test('a handler or helper handed to an effect, a timer, a frame, a microtask, a ref or a child — or through an alias — fails in both layers, even when its button also calls it', () => {
+ for (const [label, source, reason] of [
+ ['a timer in an effect', atRender(' React.useEffect(() => {\n const timer = setTimeout(showIdentity, 0);\n return () => clearTimeout(timer);\n }, []);'), /^WhoAmI: handed to an effect, a memo or a timer/],
+ ['a frame', atRender(' React.useEffect(() => { requestAnimationFrame(showVersion); }, []);'), /^RetrieveVersion: handed to an effect, a memo or a timer/],
+ ['a microtask at render', atRender(' queueMicrotask(showVersion);'), /^RetrieveVersion: handed to an effect, a memo or a timer/],
+ ['the effect callback itself', atRender(' React.useEffect(showIdentity as unknown as () => void, []);'), /^WhoAmI: handed to an effect, a memo or a timer/],
+ ['an interval of the helper', atRender(' React.useEffect(() => { const id = setInterval(readVersion, 60000, api); return () => clearInterval(id); }, []);'), /^RetrieveVersion: handed to an effect, a memo or a timer/],
+ ['an alias handed to a timer', atRender(' const run = showIdentity;\n React.useEffect(() => { const timer = setTimeout(run, 0); return () => clearTimeout(timer); }, []);'), /^WhoAmI: handed to an effect, a memo or a timer/],
+ ['a ref callback', mutated(' <PageErrorBar error={identityState.view.error ?? null} />', ' <div ref={showIdentity as unknown as React.Ref<HTMLDivElement>} />\n <PageErrorBar error={identityState.view.error ?? null} />'), /^WhoAmI: showIdentity is handed somewhere other than its button's onClick/],
+ ['a child component', mutated(' <PageErrorBar error={versionState.view.error ?? null} />', ' <Watcher onReady={showVersion} />\n <PageErrorBar error={versionState.view.error ?? null} />'), /^RetrieveVersion: showVersion is handed somewhere other than its button's onClick/],
+ ['a subscription, not a rename', atRender(' const unsubscribe = subscribeToRefresh(showIdentity);'), /^WhoAmI: showIdentity is handed somewhere other than its button's onClick/],
+ ['a memo factory with a type argument', atRender(' React.useMemo<Promise<void>>(showVersion, []);'), /^RetrieveVersion: handed to an effect, a memo or a timer/],
+ ]) {
+ const found = problems(source);
+ assert.ok(found.some((p) => reason.test(p)), `${label}: ${JSON.stringify(found)}`);
+ for (const [index, result] of verdicts(fixture(source)).entries()) assert.equal(result.status, 'fail', `${label}, layer ${index + 1}`);
+ }
+ // Naming it calls nothing: in the button's own onClick, through an alias the button calls, a memoized alias, or a hook's dependency list.
+ for (const [label, source] of [
+ ['onClick names the handler', mutated('onClick={() => void showIdentity()}', 'onClick={showIdentity}')],
+ ['an alias the button calls', mutated('onClick={() => void showVersion()}', 'onClick={() => void onVersion()}').replace(BEFORE_RENDER, ` const onVersion = showVersion;\n${BEFORE_RENDER}`)],
+ ['a memoized alias', mutated('onClick={() => void showIdentity()}', 'onClick={onIdentity}').replace(BEFORE_RENDER, ` const onIdentity = React.useCallback(showIdentity, [showIdentity]);\n${BEFORE_RENDER}`)],
+ ['a dependency list', mutated('React.useEffect(() => () => { mounted.current = false; }, []);', 'React.useEffect(() => () => { mounted.current = false; }, [showIdentity]);')],
+ ]) {
+ assert.deepStrictEqual(problems(source), [], label);
+ for (const [index, result] of verdicts(fixture(source)).entries()) assert.equal(result.status, 'pass', `${label}, layer ${index + 1}: ${result.reason}`);
+ }
+});
+
+// ── The result after the helper returns it ──────────────────────────────────────────────────────────────────────────────────────────
+// The handler stores the helper's answer in state (`setIdentityState({ pending: false, view })`), and the page renders that state. Nothing kept
+// from the result — the state, a ref it is written to, a variable initialized from either — may reach a log, storage, the clipboard, a URL,
+// telemetry or the network, wherever on the page that happens: at render, in an effect, in another handler. A sink that carries none of it
+// (telemetry of something else, a log of the request counter, a same-named variable in another function) is not the operation's business.
+test('a value kept from the result — in state, a ref or a variable — logged, stored, copied, put in a URL or sent anywhere on the page fails in both layers', () => {
+ const lastIdentity = (sink) => mutated(' const identityRequest = React.useRef(0);', ' const identityRequest = React.useRef(0);\n const lastIdentity = React.useRef<IdentityView>({});')
+ .replace('setIdentityState({ pending: false, view });\n', 'setIdentityState({ pending: false, view });\n lastIdentity.current = view;\n')
+ .replace(BEFORE_RENDER, `${sink}\n${BEFORE_RENDER}`);
+ for (const [label, source, reason] of [
+ ['the identity state logged at render', atRender(' console.log(identityState.view.identity);'), /^WhoAmI: a value kept from its result \(identityState\) must not be logged, stored, copied or sent/],
+ ['the version logged by an effect', atRender(' React.useEffect(() => { if (versionState.view.version) console.info(versionState.view.version); }, [versionState]);'), /^RetrieveVersion: a value kept from its result \(versionState\)/],
+ ['the identity state stored', atRender(" React.useEffect(() => { localStorage.setItem('me', JSON.stringify(identityState)); }, [identityState]);"), /^WhoAmI: a value kept from its result \(identityState\)/],
+ ['a variable derived from the version, sent to telemetry', atRender(" const shown = versionState.view.version;\n React.useEffect(() => { appInsights.trackEvent({ name: 'Version', properties: { shown } }); }, [shown]);"), /^RetrieveVersion: a value kept from its result \(shown\)/],
+ ['the user id put in the URL', atRender(" React.useEffect(() => { if (identityState.view.identity) history.replaceState(null, '', `?user=${identityState.view.identity.userId}`); }, [identityState]);"), /^WhoAmI: a value kept from its result \(identityState\)/],
+ ['the version sent with fetch', atRender(" React.useEffect(() => { if (versionState.view.version) void fetch('/log', { method: 'POST', body: versionState.view.version }); }, [versionState]);"), /^RetrieveVersion: a value kept from its result \(versionState\)/],
+ ['a copy button of its own', mutated(' <PageErrorBar error={identityState.view.error ?? null} />', " <Button onClick={() => void navigator.clipboard.writeText(identityState.view.identity?.userId ?? '')}>Copy</Button>\n <PageErrorBar error={identityState.view.error ?? null} />"), /^WhoAmI: a value kept from its result \(identityState\)/],
+ ['a ref written from the result, logged at render', lastIdentity(' console.log(lastIdentity.current);'), /^WhoAmI: a value kept from its result \(lastIdentity\)/],
+ ['a module variable assigned the result, logged by an effect', mutated('setVersionState({ pending: false, view });\n', 'setVersionState({ pending: false, view });\n lastVersion = view;\n')
+ .replace('const GeneratedComponent', 'let lastVersion: VersionView | undefined;\n\nconst GeneratedComponent')
+ .replace(BEFORE_RENDER, ` React.useEffect(() => { console.log(lastVersion); }, [versionState]);\n${BEFORE_RENDER}`), /^RetrieveVersion: a value kept from its result \(lastVersion\)/],
+ ]) {
+ const found = problems(source);
+ assert.ok(found.some((p) => reason.test(p)), `${label}: ${JSON.stringify(found)}`);
+ for (const [index, result] of verdicts(fixture(source)).entries()) assert.equal(result.status, 'fail', `${label}, layer ${index + 1}`);
+ }
+ for (const [label, source] of [
+ ['telemetry of something else', atRender(" React.useEffect(() => { appInsights.trackEvent({ name: 'PageViewed', properties: { identity: 'not-recorded' } }); }, []);")],
+ ['a log of the request counter', atRender(" console.debug('identity requests', identityRequest.current);")],
+ ['same-named variables in another function', mutated('async function readVersion(', 'function logRows(view: unknown[]) { const res = view.length; console.log(view.length, res); }\n\nasync function readVersion(')],
+ ['a constant named like the button attribute', atRender(" const onClick = 'tracked';\n console.debug('button', onClick);")],
+ ]) {
+ assert.deepStrictEqual(problems(source), [], label);
+ for (const [index, result] of verdicts(fixture(source)).entries()) assert.equal(result.status, 'pass', `${label}, layer ${index + 1}: ${result.reason}`);
+ }
+});
+
+// ── An edit that adds a built-in operation ────────────────────────────────────────────────────────────────────────────────────────────
+// An edit never visits the create flow's Phase 4.6b, so its own re-probe is what stops an add the flag no longer allows (edit-flow.md, Edit
+// Phase 4): the gate is probed again after the listing — whether the need was asked for up front or found in the planner's clarification, the
+// builder lists the operations first — and before the source is written. A flip to OFF in between, no re-probe, or one after the write fails.
+test('an edit that adds a built-in re-probes the gate after the listing and before the source is written — a flip to OFF, no re-probe, or a late one fails in both layers', () => {
+ const add = () => editFixture({ before: [LEGACY_WHO_AM_I], add: [RETRIEVE_VERSION], source: LEGACY_CALL });
+ for (const [index, result] of verdicts(add()).entries()) assert.equal(result.status, 'pass', `layer ${index + 1}: ${result.reason}`);
+ for (const [label, mutate, reason] of [
+ ['the flag turned off before the source was edited', (f) => { f.events.find((call) => call.id === 'builtin-regate').result = 'disabled'; }, /^edit: a disabled or unreadable dataverse-operations gate must halt built-in authoring/],
+ ['no re-probe after the listing', (f) => { f.events = f.events.filter((call) => call.id !== 'builtin-regate'); }, /^edit: built-in authoring must re-probe the dataverse-operations gate after the listing/],
+ ['a re-probe after the source was written', (f) => {
+ const [regate] = f.events.splice(f.events.findIndex((call) => call.id === 'builtin-regate'), 1);
+ f.events.splice(f.events.findIndex((call) => call.id === 'write') + 1, 0, regate);
+ }, /^edit: the dataverse-operations re-probe must come before generation/],
+ ]) {
+ const bad = add();
+ mutate(bad);
+ const found = customApiProblems(bad);
+ assert.ok(found.some((problem) => reason.test(problem)), `${label}: ${JSON.stringify(found)}`);
+ for (const [index, result] of verdicts(bad).entries()) assert.equal(result.status, 'fail', `${label}, layer ${index + 1}`);
+ }
+});
diff --git a/evals/model-apps/genpage/tests/custom-api-lifecycle.test.js b/evals/model-apps/genpage/tests/custom-api-lifecycle.test.js
index fd1bcaaa1..da2e5490d 100644
--- a/evals/model-apps/genpage/tests/custom-api-lifecycle.test.js
+++ b/evals/model-apps/genpage/tests/custom-api-lifecycle.test.js
@@ -7,6 +7,7 @@ const { loadFixtures } = require('../lib/fixture-loader.js');
const { PHASE_EXPECTATIONS, WORKFLOW_ASSERTIONS } = require('../lib/assertions-layer-1.js');
const { PHASE5_EXPECTATIONS } = require('../lib/assertions-layer-2.js');
const { actionCalls, receiverIsDataApi } = require('../lib/source-evidence.js');
+const { refusalProblems } = require('../lib/workflow-evidence.js');
const RULE = 'Phase 5: Custom API discovery, gate, bare bindings, runtime calls and update preservation or explicit clear agree';
const bindings = [
@@ -98,12 +99,20 @@ function score(fixture, layer = 1) {
return check({ fixture, files: fixture.files, eval: { id: 24 } });
}
-test('custom API gate and bindings match generated runtime calls', () => {
+test('custom API bindings match generated runtime calls, and a recorded custom-api probe decides nothing', () => {
const good = apiFixture();
for (const layer of [1, 2]) assert.equal(score(good, layer).status, 'pass');
+ // Custom API support has no feature flag: whatever an older run's custom-api probe printed — or no probe at all — the run grades the same.
for (const mutate of [
(fixture) => { event(fixture, 'gate-create').result = 'disabled'; },
- (fixture) => { event(fixture, 'gate-preserve').result = 'unreadable'; },
+ (fixture) => { event(fixture, 'gate-generate').result = 'unreadable'; },
+ (fixture) => { fixture.events = fixture.events.filter((call) => !/\bfeature-flags\.js\b[^\n]*\bcustom-api\b/.test(call.command)); },
+ ]) {
+ const probed = apiFixture();
+ mutate(probed);
+ for (const layer of [1, 2]) assert.equal(score(probed, layer).status, 'pass', `layer ${layer}: ${score(probed, layer).reason}`);
+ }
+ for (const mutate of [
(fixture) => { event(fixture, 'discovery').result.ok = false; },
(fixture) => { event(fixture, 'discovery').result.customApis[0].parameterKinds.Amount = 'Boolean'; },
(fixture) => { fixture.artifacts['actions.json'] = JSON.stringify({ actionBindings: bindings }); },
@@ -239,7 +248,8 @@ test('lookup inputs must use the discovered table and an existing record rather
}
});
-test('disabled or unreadable Custom API gates refuse before generation, not as a no-bindings fallback', () => {
+// The `custom-api` gate was removed with its flag, so a refusal can no longer stop at it: a fixture that claims it names no supported stage.
+test('no refusal stops at a custom-api gate any more: a fixture that declares one names an unsupported refusal stage', () => {
for (const result of ['disabled', 'unknown', null]) {
const stopped = apiFixture();
stopped.events = [{ ...stopped.events[0], result }];
@@ -247,28 +257,32 @@ test('disabled or unreadable Custom API gates refuse before generation, not as a
stopped.manifest.expectedOutcome = 'refused';
stopped.manifest.refusal = { stage: 'custom-api' };
stopped.workflowLog = 'Halted before generation: turn the feature back on or re-plan; the gate is disabled or unreadable.';
- assert.equal(score(stopped).status, 'pass', String(result));
- stopped.events.push({ command: 'Write page.tsx', artifact: 'stages/with-api.tsx' });
- assert.equal(score(stopped).status, 'fail');
+ assert.deepStrictEqual(refusalProblems(stopped), ['unsupported refusal stage: custom-api'], String(result));
}
});
-test('Custom API generation re-probes after discovery rather than borrowing the planning gate', () => {
+test('a Custom API create needs no custom-api probe after discovery — or before it', () => {
const good = apiFixture();
assert.equal(score(good).status, 'pass');
good.events = good.events.filter((call) => call.id !== 'gate-generate');
- assert.equal(score(good).status, 'fail');
+ assert.equal(score(good).status, 'pass', 'no re-probe after discovery');
+ good.events = good.events.filter((call) => !/\bfeature-flags\.js\b[^\n]*\bcustom-api\b/.test(call.command));
+ for (const layer of [1, 2]) assert.equal(score(good, layer).status, 'pass', `no probe at all, layer ${layer}`);
});
-test('a populated plan cannot continue the audit disabled-gate probe', () => {
+// A captured run recorded its custom-api probe in the log. The probe is history now: every registered workflow check grades the run the same
+// with that probe printing enabled, printing disabled, or absent — none requires it and none refuses it.
+test('a captured run grades the same in every workflow check whether its recorded custom-api probe printed enabled or disabled, or was never run', () => {
const captured = loadFixtures(path.join(__dirname, '..', 'fixtures')).find((fixture) => fixture.id === 17);
const plan = captured.genpagePlan.replace('No custom API bindings.', apiFixture().genpagePlan.split('## Custom API Bindings\n')[1].trim());
- const text = [...WORKFLOW_ASSERTIONS.keys()].find((key) => key.startsWith('Phase 4.6: A populated Custom API plan'));
- const check = WORKFLOW_ASSERTIONS.get(text);
- const disabled = { ...captured, genpagePlan: plan, workflowLog: 'node feature-flags.js custom-api -> disabled\n' + captured.workflowLog };
- assert.equal(check({ fixture: disabled }).status, 'fail');
- const enabled = { ...disabled, workflowLog: 'node feature-flags.js custom-api -> enabled\n' + captured.workflowLog };
- assert.equal(check({ fixture: enabled }).status, 'pass');
+ const run = (probe) => ({ ...captured, genpagePlan: plan, workflowLog: (probe ? `node feature-flags.js custom-api -> ${probe}\n` : '') + captured.workflowLog });
+ assert.ok(![...WORKFLOW_ASSERTIONS.keys()].some((key) => key.startsWith('Phase 4.6: A populated Custom API plan')), 'the gate rule is not registered');
+ for (const [text, check] of WORKFLOW_ASSERTIONS) {
+ const grade = (probe) => { const result = check({ fixture: run(probe), eval: { id: 17 } }); return `${result.status}: ${result.reason || ''}`; };
+ const enabled = grade('enabled');
+ assert.equal(grade('disabled'), enabled, `${text}: a disabled probe`);
+ assert.equal(grade(null), enabled, `${text}: no probe`);
+ }
});
function selectedRecordLookupFixture(memberType = 'string') {
@@ -485,7 +499,6 @@ test('pre-existing binding preservation never authorizes dropping changing or un
fixture.artifacts['stages/edited.tsx'] = nextSource;
fixture.files[0].content = nextSource;
}],
- ['disabled gate', (fixture) => { event(fixture, 'gate-generate').result = 'disabled'; }],
['changed method on the existing operation', (fixture) => {
const nextSource = fixture.artifacts['stages/edited.tsx'].replace('await api.executeAction({', 'await api.executeFunction({');
fixture.artifacts['stages/edited.tsx'] = nextSource;
@@ -521,7 +534,7 @@ function assertKnownApiReceivers(code) {
const calls = actionCalls(code);
assert.ok(calls.length > 0);
for (const call of calls) {
- assert.equal(receiverIsDataApi(call.mask, call.scopes, call.receiver, call.start), true,
+ assert.equal(receiverIsDataApi(call.mask, call.scopes, call.receiver, call.start, call.code), true,
`${call.scope.name}: record-value evidence must not change the shared dataApi receiver proof`);
}
}
@@ -1056,3 +1069,14 @@ test('before-page download source: recorded destination forms preserve the corre
}
}
});
+
+// The reference-page tests (page-error-teaching.test.js, source-evidence.test.js) assemble a full Action page and grade it
+// with the same runtime check the lifecycle scorer applies. That check must be importable by name: a missing export fails
+// here, never as a TypeError a caller could turn into a skip.
+test('runtimeProblems is exported, and it is the check the lifecycle scorer applies', () => {
+ const { runtimeProblems } = require('../lib/custom-api-contract.js');
+ assert.equal(typeof runtimeProblems, 'function', 'runtimeProblems is exported');
+ assert.deepEqual(runtimeProblems(source, bindings, { cnt_ApproveOrder: ['NewStatus'], cnt_GetOrderSummary: ['Total'] }, new Map()), []);
+ const unguarded = runtimeProblems(source.replace('if (!res.ok)', 'if (false)'), bindings, { cnt_ApproveOrder: ['NewStatus'], cnt_GetOrderSummary: ['Total'] }, new Map());
+ assert.ok(unguarded.some((problem) => /response\.ok must refuse before outputs are read/.test(problem)), JSON.stringify(unguarded));
+});
\ No newline at end of file
diff --git a/evals/model-apps/genpage/tests/fixture-tool-results.test.js b/evals/model-apps/genpage/tests/fixture-tool-results.test.js
index 06a9b86c6..35eb50108 100644
--- a/evals/model-apps/genpage/tests/fixture-tool-results.test.js
+++ b/evals/model-apps/genpage/tests/fixture-tool-results.test.js
@@ -44,8 +44,11 @@ function recordedProbes() {
}
test('feature-flags.js exits 0 for enabled and 1 for disabled (the contract the fixtures record)', () => {
- assert.deepEqual(measuredExit('custom-api', true), { code: 0, out: 'enabled' });
- assert.deepEqual(measuredExit('custom-api', false), { code: 1, out: 'disabled' });
+ // Measured with a flag the script still knows. The fixtures' custom-api probes are older runs' history: that flag was removed, and an
+ // unknown flag reads as disabled whatever its variable says, but the output/exit-code pairing they recorded is the same contract.
+ assert.deepEqual(measuredExit('dataverse-operations', true), { code: 0, out: 'enabled' });
+ assert.deepEqual(measuredExit('dataverse-operations', false), { code: 1, out: 'disabled' });
+ assert.deepEqual(measuredExit('custom-api', true), { code: 1, out: 'disabled' });
});
test('every recorded feature-flag probe pairs its output with the exit code the script returns', () => {
diff --git a/evals/model-apps/genpage/tests/navigation-contract.test.js b/evals/model-apps/genpage/tests/navigation-contract.test.js
index 812aa9a69..38f2290dc 100644
--- a/evals/model-apps/genpage/tests/navigation-contract.test.js
+++ b/evals/model-apps/genpage/tests/navigation-contract.test.js
@@ -6,6 +6,11 @@ const path = require('node:path');
const { ASSERTIONS } = require('../lib/assertions-layer-2.js');
const { PHASE_EXPECTATIONS } = require('../lib/assertions-layer-1.js');
const { loadFixtures } = require('../lib/fixture-loader.js');
+const { setParserCheck } = require('../../../../plugins/model-apps/scripts/lib/typescript-views.js');
+
+// What a guess of the page lexer costs a fixture where the TypeScript parser does not settle it (typescript-views.js in the plugin): the tests that pin it read
+// the page with the lexer alone. With the parser asked, as the build asks it, the same pages are read as TypeScript parses them (the tests after each).
+const lexerAlone = (t) => { setParserCheck(false); t.after(() => setParserCheck(true)); };
const NAV = 'For multi-page builds, cross-page navigation uses quoted `"PAGEREF_<filename>"` placeholders that the orchestrator\'s Phase 6.5 resolves to real GUIDs';
const FIXUP = 'Phase 6.5: Every effective navigation target resolves against the deployed page map; exact substitutions preserve non-navigation bytes and only affected pages reupload';
@@ -169,7 +174,8 @@ test('a PAGEREF_ token no navigation rewrite resolves fails the contract in eith
// The misread pages (tests/helpers/misread-page.js): JavaScript makes the calls, and each page is a way the lexer hides one or reads
// text as one. A fixture holding one is not a page the build would accept, so it fails the contract, the first guess named; with the
// object literal in parentheses the first is read right and passes.
-test('a page the lexer could misread fails the contract, naming the guess, and the parenthesised page passes', () => {
+test('a page the lexer could misread fails the contract, naming the guess, and the parenthesised page passes', (t) => {
+ lexerAlone(t);
const { OBJECT_DIVISION_PAGE, MISREAD_PAGES } = require('../../../../plugins/model-apps/scripts/tests/helpers/misread-page.js');
const make = (code) => ({
contractVersion: 2,
@@ -201,7 +207,8 @@ test('a page the lexer could misread fails the contract, naming the guess, and t
// A resolved page is judged on the same view of the source as the build and verification. An id that lies in a call at or after the first place
// the lexer guessed — or in a call that runs through it — is no evidence of navigation, though it is a deployed id from the page map: the
// source there is not read for certain, and what the call does is not known.
-test('a resolved page whose page id lies in a call the lexer reads only by guess is refused, as verification refuses it', () => {
+test('a resolved page whose page id lies in a call the lexer reads only by guess is refused, as verification refuses it', (t) => {
+ lexerAlone(t);
const { MISREAD_PAGES } = require('../../../../plugins/model-apps/scripts/tests/helpers/misread-page.js');
const make = (code) => ({
contractVersion: 2,
@@ -227,6 +234,21 @@ test('a resolved page whose page id lies in a call the lexer reads only by guess
assert.equal(score(make(`${call}\n`)).status, 'pass');
});
+// The same pages with the parser asked where the lexer guessed, as the build asks it: the misread page is read as TypeScript parses it, its every call
+// resolves, and an id in a call after a place the lexer guessed at is evidence, as verification counts it.
+test('with the parser asked, a page the lexer misreads passes the contract, and an id in a call after a guess is evidence', () => {
+ const { OBJECT_DIVISION_PAGE } = require('../../../../plugins/model-apps/scripts/tests/helpers/misread-page.js');
+ const make = (code, phase) => ({
+ contractVersion: 2,
+ manifest: { navigationPhase: phase, pageMap: IDS },
+ files: [{ name: 'overview.tsx', content: code }, { name: 'pet.tsx', content: '' }, { name: 'pet-gallery.tsx', content: '' }],
+ });
+ assert.equal(score(make(OBJECT_DIVISION_PAGE.replaceAll('PAGEREF_detail', 'PAGEREF_pet'), 'authored')).status, 'pass');
+ const call = `navigateTo({pageType:"generative", pageId:"${IDS.pet}"});`;
+ assert.equal(score(make(`const count = {valueOf(){return 12;}}/2; const half = total / 2;\n${call}\n`, 'resolved')).status, 'pass');
+ assert.equal(score(make(`navigateTo({pageType:"generative", pageId:"${IDS.pet}", data: type/2}); const re = /x/;\n`, 'resolved')).status, 'pass');
+});
+
// Pages the lexer reads right after a line break (ASI): the text of a call in a regex after a prefix `++` is a token no rewrite resolves, so a
// fixture holding it fails the contract, wherever the token sits and with no guess named; a call in a template line that starts with `//` runs,
// so it passes in both phases.
diff --git a/evals/model-apps/genpage/tests/page-error-teaching.test.js b/evals/model-apps/genpage/tests/page-error-teaching.test.js
new file mode 100644
index 000000000..92e7cc732
--- /dev/null
+++ b/evals/model-apps/genpage/tests/page-error-teaching.test.js
@@ -0,0 +1,399 @@
+'use strict';
+// The teaching examples a page builder copies. Each reference shows a whole PageBody (and its top-level helpers) built on
+// the page error block references/rules.md publishes ("Missing Error Handling"); here that block — copied unchanged up to
+// its own example PageBody — and the document's code are put together into the complete page a builder would write, which
+// must transpile with the TypeScript the plugin vendors (a syntax check, not a type check) and, for a Custom API, pass the
+// runtime check of lib/custom-api-contract.js. The built-in operations' generated call is graded the same way in
+// built-in-operation-pattern.test.js. A document that drifts back to a try/catch that sets a string, logs the thrown value
+// or calls trackException itself fails here. Whether a page's failures all reach its reporter is not graded (EVAL_GUIDE.md);
+// the approval tests at the end run the examples' own code.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const { runtimeProblems } = require('../lib/custom-api-contract.js');
+const { loadVendoredTypeScript } = require('../../../../plugins/model-apps/scripts/lib/typescript-compiler.js');
+
+const PLUGIN = path.join(__dirname, '..', '..', '..', '..', 'plugins', 'model-apps');
+const read = (...parts) => fs.readFileSync(path.join(PLUGIN, ...parts), 'utf8').replace(/\r\n/g, '\n');
+const RULES = read('references', 'rules.md');
+const ERRORS = RULES.slice(RULES.indexOf('\n### 2. Missing Error Handling\n'), RULES.indexOf('\n### 3. '));
+const RULE_BLOCKS = [...ERRORS.matchAll(/```tsx\n([\s\S]*?)\n```/g)].map((match) => match[1]);
+const FOUNDATION = RULE_BLOCKS.find((block) => /\bfunction reportPageError\(/.test(block));
+const TELEMETRY = RULE_BLOCKS.find((block) => /appInsights\?\.trackException\?\.\(/.test(block));
+const PREFIX = FOUNDATION.slice(0, FOUNDATION.indexOf('function PageBody('));
+const WRAPPER = FOUNDATION.slice(FOUNDATION.indexOf('const GeneratedComponent = '));
+
+// Fenced blocks, including the ones indented under a list item (their closing fence carries the same indentation).
+const codeBlocks = (text) => [...text.matchAll(/^([ \t]*)```(?:typescript|tsx)\n([\s\S]*?)\n\1```/gm)].map((match) => match[2]);
+// The blocks of a document that hold a whole PageBody.
+const bodies = (text) => codeBlocks(text).filter((code) => /^function PageBody\(/m.test(code));
+// The complete page: the canonical block up to its own example PageBody, the document's code, then the canonical wrapper
+// unless the document shows its own.
+const complete = (code, prefix = PREFIX) => `${prefix}${code}\n\n${/^export default GeneratedComponent;$/m.test(code) ? '' : WRAPPER}\n`;
+// The documented telemetry insertion goes right after the reporter's console.error line.
+function withTelemetry(source) {
+ const lines = source.split('\n');
+ const at = lines.findIndex((line) => /^\s*console\.error\(/.test(line));
+ assert.ok(at > 0 && TELEMETRY, 'rules.md publishes the reporter and its telemetry insertion');
+ return [...lines.slice(0, at + 1), ...TELEMETRY.split('\n'), ...lines.slice(at + 1)].join('\n');
+}
+let typescript;
+function parses(source, label) {
+ typescript ||= loadVendoredTypeScript();
+ const { diagnostics } = typescript.transpileModule(source, {
+ fileName: 'page.tsx',
+ reportDiagnostics: true,
+ compilerOptions: { module: typescript.ModuleKind.CommonJS, target: typescript.ScriptTarget.ES2020, jsx: typescript.JsxEmit.React },
+ });
+ assert.deepEqual((diagnostics || []).map((entry) => typescript.flattenDiagnosticMessageText(entry.messageText, '\n')), [], `${label} parses`);
+}
+// One textual change; a change that does not apply is a broken test, never a pass.
+
+const DOCS = {
+ caching: read('references', 'data-caching.md'),
+ customApi: read('references', 'custom-api.md'),
+ connectors: read('references', 'connectors.md'),
+ localization: read('references', 'localization.md'),
+ telemetry: read('references', 'page-telemetry.md'),
+ builtIns: read('references', 'dataverse-operations.md'),
+ builder: read('agents', 'genpage-page-builder.md'),
+};
+const [CACHE_LIST, CACHE_RECORD] = bodies(DOCS.caching);
+const [ACTION, FUNCTION] = bodies(DOCS.customApi);
+const [CONNECTOR_TABLE, CONNECTOR_OPERATION] = bodies(DOCS.connectors);
+const [SETTINGS] = bodies(DOCS.localization);
+// The telemetry reference also shows the prop declaration around an empty PageBody; its example page is the one that saves.
+const TELEMETRY_SAVE = bodies(DOCS.telemetry).find((code) => /'saveOrder'/.test(code));
+// A localized page keeps the reference's top-level language resolver beside the block.
+const LANGUAGE = codeBlocks(DOCS.localization).find((code) => /^function resolvePageLanguage\(\)/m.test(code));
+const PAGES = {
+ 'data-caching.md Pattern 1 (list)': CACHE_LIST && complete(CACHE_LIST),
+ 'data-caching.md Pattern 2 (detail)': CACHE_RECORD && complete(CACHE_RECORD),
+ 'custom-api.md Action': ACTION && complete(ACTION),
+ 'custom-api.md Function': FUNCTION && complete(FUNCTION),
+ 'connectors.md tabular read': CONNECTOR_TABLE && complete(CONNECTOR_TABLE),
+ 'connectors.md REST operation': CONNECTOR_OPERATION && complete(CONNECTOR_OPERATION),
+ 'localization.md usersettings read': SETTINGS && LANGUAGE && complete(`${LANGUAGE}\n\n${SETTINGS}`),
+ 'page-telemetry.md failed-save report': TELEMETRY_SAVE && complete(TELEMETRY_SAVE, withTelemetry(PREFIX)),
+};
+
+test('each reference shows a complete PageBody built on the page error block, and each whole page parses', () => {
+ assert.ok(FOUNDATION, 'rules.md publishes the canonical page error block');
+ for (const [label, page] of Object.entries(PAGES)) {
+ assert.ok(page, `${label}: the reference shows a whole PageBody built on the page error block`);
+ parses(page, label);
+ }
+});
+
+test('the Custom API Action and Function examples also pass the Custom API runtime check, through the boundary wrapper', () => {
+ const action = { name: 'new_ApproveOrder', isFunction: false, boundEntityLogicalName: 'salesorder', displayName: 'Approve Order', parameterKinds: { Comment: 'String' } };
+ const fn = { name: 'new_GetOrderSummary', isFunction: true, displayName: 'Order summary', parameterKinds: { OrderId: 'Guid' } };
+ assert.deepEqual(runtimeProblems(PAGES['custom-api.md Action'], [action], { new_ApproveOrder: ['NewStatus'] }, new Map()), []);
+ assert.deepEqual(runtimeProblems(PAGES['custom-api.md Function'], [fn], { new_GetOrderSummary: ['Total'] }, new Map()), []);
+ // The order is part of the contract: each guard reports, stores the view and returns before the outputs, a network result
+ // offers the named manual retry and nothing else does.
+ for (const [label, page] of [['Action', PAGES['custom-api.md Action']], ['Function', PAGES['custom-api.md Function']]]) {
+ const guards = ['if (res.indeterminate)', "if (res.error?.code === 'indeterminate')", "if (!res.ok && res.error?.code === 'network')", 'if (!res.ok)', 'res.outputs?.'];
+ const at = guards.map((guard) => page.indexOf(guard));
+ assert.ok(at.every((index, i) => index > 0 && (i === 0 || index > at[i - 1])), `${label}: the guards in order before the outputs (${at})`);
+ }
+ assert.doesNotMatch(DOCS.customApi, /setError\(|res\.error\?\.message \?\? 'The action failed\.'/, 'no string error state is left in the Custom API reference');
+});
+
+test('the telemetry example instruments only the save it was asked about, and only the reporter sends an exception', () => {
+ const page = PAGES['page-telemetry.md failed-save report'];
+ const reports = [...TELEMETRY_SAVE.matchAll(/\breportPageError\(/g)].map((match) => callArguments(TELEMETRY_SAVE, match.index + match[0].length - 1).join(', '));
+ assert.deepEqual(reports, ["PAGE_NAME, 'saveOrder', undefined, error, 'write', undefined, appInsights"], 'one report, the save, carries the appInsights prop');
+ assert.doesNotMatch(TELEMETRY_SAVE, /\.trackException\s*(?:\?\.\s*)?\(/, 'the page never calls trackException itself');
+ assert.doesNotMatch(page.slice(page.indexOf('const GeneratedComponent')), /appInsights=/, 'a save-only request leaves the boundary as it is');
+ // The other GOOD shapes report their failures with no telemetry argument: those requests measure, they do not report failures.
+ const known = DOCS.telemetry.slice(DOCS.telemetry.indexOf('\n## 4. Known-good shapes\n'), DOCS.telemetry.indexOf('\n## 5. Anti-patterns\n'));
+ assert.doesNotMatch(known, /\.trackException\s*(?:\?\.\s*)?\(/, 'no known-good shape calls trackException');
+ for (const code of codeBlocks(known)) {
+ for (const call of code.matchAll(/\breportPageError\(/g)) {
+ const args = callArguments(code, call.index + call[0].length - 1);
+ if (args.includes("'saveOrder'")) continue;
+ assert.ok(args.length === 5, `a report outside the failed-save example hands no retry or telemetry: ${args.join(', ')}`);
+ }
+ }
+ // The trigger row for failures names the reporter, not catch-block trackException calls.
+ const triggers = DOCS.telemetry.slice(DOCS.telemetry.indexOf('\n### Trigger patterns\n'), DOCS.telemetry.indexOf('\n## 2. The API\n'));
+ assert.doesNotMatch(triggers, /`trackException\(err, \{ \.\.\. \}\)` in the relevant `catch` blocks/);
+ assert.match(triggers, /\| "report failed saves" \| the same insertion, and `props\.appInsights` as the seventh argument of the save's reports \*\*only\*\*/);
+});
+
+// A call's top-level argument texts: brackets, strings and template literals are skipped over, so a comma inside them does
+// not split. Enough for the documents' own examples; a malformed call fails the count check below.
+function callArguments(code, open) {
+ const args = [];
+ let depth = 0;
+ let start = open + 1;
+ for (let i = open + 1; i < code.length; i += 1) {
+ const ch = code[i];
+ if (ch === '\'' || ch === '"' || ch === '`') {
+ for (i += 1; i < code.length && code[i] !== ch; i += 1) if (code[i] === '\\') i += 1;
+ } else if ('([{'.includes(ch)) depth += 1;
+ else if (')]}'.includes(ch)) {
+ if (depth === 0) { args.push(code.slice(start, i).trim()); return args; }
+ depth -= 1;
+ } else if (ch === ',' && depth === 0) { args.push(code.slice(start, i).trim()); start = i + 1; }
+ }
+ return null;
+}
+
+test('every reportPageError call the teaching documents show has the five required arguments and a literal kind', () => {
+ const documents = { 'rules.md': RULES, ...Object.fromEntries(Object.entries(DOCS).map(([key, text]) => [key, text])) };
+ let seen = 0;
+ for (const [name, text] of Object.entries(documents)) {
+ for (const code of codeBlocks(text)) {
+ for (const call of code.matchAll(/(?<!function\s)\breportPageError\(/g)) {
+ const args = callArguments(code, call.index + call[0].length - 1);
+ assert.ok(args, `${name}: a reportPageError call closes`);
+ seen += 1;
+ const shown = `${name}: reportPageError(${args.join(', ')})`;
+ assert.ok(args.length >= 5 && args.length <= 7, `${shown} has five to seven arguments`);
+ assert.match(args[4], /^(['"])(?:read|write|indeterminate|network|render)\1$/, `${shown} has a literal kind at index 4`);
+ assert.match(args[1], /^(['"])[A-Za-z][\w]*\1$/, `${shown} names its operation with one stable literal`);
+ if (['write', 'indeterminate', 'render'].includes(args[4].slice(1, -1))) assert.ok(!args[5] || args[5] === 'undefined', `${shown} offers no retry`);
+ }
+ }
+ }
+ assert.ok(seen >= 40, `the documents show the reporter in use (${seen} calls)`);
+});
+
+test('the documents no longer teach a bare try/catch error string or a logged thrown value', () => {
+ assert.doesNotMatch(DOCS.caching, /error: "Unable to load records\."|error: "Unable to load record\."|error: string \| null/);
+ assert.doesNotMatch(DOCS.localization, /console\.error\("Failed to fetch user settings", error\)/);
+ assert.doesNotMatch(DOCS.connectors, /if \(!response\.ok\) \{ return; \}/);
+ assert.doesNotMatch(DOCS.builder, /setError\(|if \(!response\.ok\) \{ return; \}/);
+ for (const [name, text] of Object.entries(DOCS)) {
+ for (const code of codeBlocks(text)) assert.doesNotMatch(code, /console\.(?:error|log|warn)\([^)]*\berror\b\s*\)/, `${name} logs no thrown value`);
+ }
+});
+
+// ---------- the samples a builder is pointed at ----------
+
+const SAMPLES = path.join(PLUGIN, 'samples');
+const sampleFiles = () => fs.readdirSync(SAMPLES).filter((name) => name.endsWith('.tsx')).sort((a, b) => parseInt(a, 10) - parseInt(b, 10));
+
+test('every sample page parses, and each of its reports has the five required arguments and a literal kind', () => {
+ const files = sampleFiles();
+ assert.equal(files.length, 13, 'the thirteen complete sample pages');
+ for (const name of files) {
+ const source = fs.readFileSync(path.join(SAMPLES, name), 'utf8');
+ parses(source, name);
+ for (const call of source.matchAll(/(?<!function\s)\breportPageError\(/g)) {
+ const args = callArguments(source, call.index + call[0].length - 1);
+ assert.ok(args.length >= 5 && /^(['"])(?:read|write|indeterminate|network|render)\1$/.test(args[4]), `${name}: reportPageError(${args.join(', ')})`);
+ }
+ // No sample still keeps a failure as a bare string or logs the thrown value.
+ assert.doesNotMatch(source, /error: string \| null|console\.error\([^)]*\berr\b/, `${name} keeps no string error state`);
+ }
+});
+
+test('the Custom API sample also passes the Custom API runtime check, its Action latched and both results guarded in order', () => {
+ const source = fs.readFileSync(path.join(SAMPLES, '13-custom-api-invocation.tsx'), 'utf8');
+ const bindings = [
+ { name: 'new_GetOrderSummary', isFunction: true, displayName: 'Order summary', parameterKinds: { OrderId: 'Guid' } },
+ { name: 'new_ApproveOrder', isFunction: false, boundEntityLogicalName: 'salesorder', displayName: 'Approve Order', parameterKinds: { Comment: 'String' } },
+ ];
+ assert.deepEqual(runtimeProblems(source, bindings, { new_GetOrderSummary: ['Total', 'Status'], new_ApproveOrder: ['NewStatus'] }, new Map()), []);
+ // Neither the effect nor anything else depends on dataApi or a shape derived from it (Rule 15).
+ assert.doesNotMatch(source, /\[\s*actionApi\b|\bdataApi\s*\]/, 'no dataApi-derived value in a dependency array');
+});
+
+// ---------- an action belongs to the record it was started on ----------
+// Sample 13, the custom-api.md Action page and fixture 27's page are transpiled and run against hook and element
+// stand-ins with deferred fake requests — no React and no browser: the handlers, state updates and effects run as written,
+// which is what decides where a result goes. The record on screen changes while an approval is pending, and after it has
+// failed: a result for the earlier record — its error and its retry — never appears on the later record, and a retry kept
+// from the earlier render sends nothing there. On the record it belongs to, the retry still re-sends that approval.
+function runnablePage(source, exportNames) {
+ typescript ||= loadVendoredTypeScript();
+ const { outputText } = typescript.transpileModule(`${source}\nexport { ${exportNames.join(', ')} };\n`, {
+ fileName: 'page.tsx',
+ compilerOptions: { module: typescript.ModuleKind.CommonJS, target: typescript.ScriptTarget.ES2020, jsx: typescript.JsxEmit.React, esModuleInterop: true },
+ });
+ const cells = [];
+ const effects = [];
+ let cursor = 0;
+ const React = {
+ Component: class { constructor(props) { this.props = props; } },
+ Fragment: 'Fragment',
+ createElement: (type, props, ...children) => ({ type, props: { ...(props || {}), children } }),
+ useState(initial) {
+ const index = cursor++;
+ if (!(index in cells)) cells[index] = typeof initial === 'function' ? initial() : initial;
+ return [cells[index], (next) => { cells[index] = typeof next === 'function' ? next(cells[index]) : next; }];
+ },
+ useRef(initial) {
+ const index = cursor++;
+ if (!(index in cells)) cells[index] = { current: initial };
+ return cells[index];
+ },
+ useEffect(effect, deps) {
+ const index = cursor++;
+ const prior = cells[index];
+ if (!prior || !deps || deps.some((value, i) => value !== prior.deps[i])) {
+ effects.push(() => { prior?.cleanup?.(); cells[index] = { deps, cleanup: effect() }; });
+ }
+ },
+ };
+ const fluent = new Proxy({ makeStyles: () => () => ({}), tokens: new Proxy({}, { get: (_, name) => String(name) }), createTableColumn: (column) => column },
+ { get: (target, name) => (name in target ? target[name] : String(name)) });
+ const icons = new Proxy({}, { get: (_, name) => String(name) });
+ const imports = { react: React, '@fluentui/react-components': fluent, '@fluentui/react-icons': icons, './RuntimeTypes': {} };
+ const module = { exports: {} };
+ new Function('require', 'module', 'exports', 'console', 'window', outputText)(
+ (name) => { assert.ok(name in imports, `unexpected import ${name}`); return imports[name]; },
+ module, module.exports, { error() {} }, {},
+ );
+ return {
+ ...module.exports,
+ render(props) { cursor = 0; return module.exports.PageBody(props); },
+ flush() { for (const effect of effects.splice(0)) effect(); },
+ };
+}
+// The elements of a rendered tree. A DataGrid's render-prop children are expanded the way the grid calls them: the body's
+// for each of the grid's items, a row's (header or body) for its name column.
+function elements(node, out = [], items = []) {
+ if (Array.isArray(node)) { for (const child of node) elements(child, out, items); return out; }
+ if (!node || typeof node !== 'object' || !node.type) return out;
+ out.push(node);
+ const rows = node.type === 'DataGrid' ? node.props.items || [] : items;
+ for (const child of [].concat(node.props.children ?? [])) {
+ if (typeof child !== 'function') { elements(child, out, rows); continue; }
+ if (node.type === 'DataGridBody') for (const item of rows) elements(child({ item }), out, rows);
+ else if (node.type === 'DataGridRow') elements(child({ renderCell: () => null, renderHeaderCell: () => null, columnId: 'name' }), out, rows);
+ }
+ return out;
+}
+const tick = () => new Promise(setImmediate);
+const approvalBar = (page, tree) => elements(tree).find((node) => node.type === page.PageErrorBar && node.props.error?.operation === 'approveOrder');
+const primaryButton = (tree) => elements(tree).find((node) => node.type === 'Button' && node.props.appearance === 'primary');
+// A dataApi whose Action requests wait until the test answers them, in order.
+function deferredActions() {
+ const requests = [];
+ const dataApi = {
+ executeFunction: async () => ({ ok: true, outputs: { Total: 1, Status: 'Pending' } }),
+ executeAction: (request) => new Promise((resolve) => { requests.push({ request, resolve }); }),
+ };
+ return { requests, dataApi };
+}
+const NETWORK = { ok: false, error: { code: 'network', message: 'The request did not leave the client' } };
+const A = '00000000-0000-4000-8000-00000000000a';
+const B = '00000000-0000-4000-8000-00000000000b';
+const RECORD_PAGES = {
+ 'samples/13-custom-api-invocation.tsx': () => read('samples', '13-custom-api-invocation.tsx'),
+ 'custom-api.md Action': () => PAGES['custom-api.md Action'],
+};
+
+test('a late answer for the record the page has left is not shown on the record now on screen, and offers it no retry', async () => {
+ for (const [label, source] of Object.entries(RECORD_PAGES)) {
+ const page = runnablePage(source(), ['PageBody', 'PageErrorBar']);
+ const { requests, dataApi } = deferredActions();
+ const props = (recordId) => ({ dataApi, pageInput: { entityName: 'salesorder', recordId } });
+ page.render(props(A));
+ page.flush();
+ await tick();
+ primaryButton(page.render(props(A))).props.onClick();
+ assert.equal(requests.length, 1, `${label}: the approval of A is sent`);
+ assert.equal(requests[0].request.boundTo.id, A, `${label}: bound to A`);
+ page.render(props(B));
+ page.flush();
+ await tick();
+ page.render(props(B));
+ requests[0].resolve(NETWORK);
+ await tick();
+ assert.equal(approvalBar(page, page.render(props(B))), undefined, `${label}: A's failure is not shown on B`);
+ assert.equal(requests.length, 1, `${label}: nothing more is sent`);
+ }
+});
+
+test('a failure shown for one record is cleared when the page moves to another, and its kept retry sends nothing there', async () => {
+ for (const [label, source] of Object.entries(RECORD_PAGES)) {
+ const page = runnablePage(source(), ['PageBody', 'PageErrorBar']);
+ const { requests, dataApi } = deferredActions();
+ const props = (recordId) => ({ dataApi, pageInput: { entityName: 'salesorder', recordId } });
+ page.render(props(A));
+ page.flush();
+ await tick();
+ primaryButton(page.render(props(A))).props.onClick();
+ requests[0].resolve(NETWORK);
+ await tick();
+ const shown = approvalBar(page, page.render(props(A)));
+ assert.equal(shown?.props.error.kind, 'network', `${label}: the network failure is shown on A`);
+ const keptRetry = shown.props.error.retry;
+ assert.equal(typeof keptRetry, 'function', `${label}: with its manual retry`);
+ page.render(props(B));
+ page.flush();
+ await tick();
+ assert.equal(approvalBar(page, page.render(props(B))), undefined, `${label}: B starts with a clean approval panel`);
+ keptRetry();
+ await tick();
+ assert.equal(requests.length, 1, `${label}: A's retry sends nothing while B is on screen`);
+ // Back on A, the panel is clean too, and a new approval of A goes out bound to A.
+ page.render(props(A));
+ page.flush();
+ await tick();
+ primaryButton(page.render(props(A))).props.onClick();
+ assert.equal(requests.length, 2, `${label}: a new approval is sent`);
+ assert.equal(requests[1].request.boundTo.id, A, `${label}: bound to the record on screen`);
+ }
+});
+
+test('on the record it belongs to, a network failure keeps its manual retry, and the retry re-sends that record\'s approval', async () => {
+ for (const [label, source] of Object.entries(RECORD_PAGES)) {
+ const page = runnablePage(source(), ['PageBody', 'PageErrorBar']);
+ const { requests, dataApi } = deferredActions();
+ const props = (recordId) => ({ dataApi, pageInput: { entityName: 'salesorder', recordId } });
+ page.render(props(A));
+ page.flush();
+ await tick();
+ primaryButton(page.render(props(A))).props.onClick();
+ requests[0].resolve({ ok: false, indeterminate: true, error: { code: 'indeterminate', message: 'timed out after sending' } });
+ await tick();
+ const indeterminate = approvalBar(page, page.render(props(A)));
+ assert.equal(indeterminate?.props.error.kind, 'indeterminate', `${label}: an indeterminate answer stays on its record`);
+ assert.equal(indeterminate.props.error.retry, undefined, `${label}: with no retry`);
+ primaryButton(page.render(props(A))).props.onClick();
+ requests[1].resolve(NETWORK);
+ await tick();
+ approvalBar(page, page.render(props(A))).props.error.retry();
+ await tick();
+ assert.equal(requests.length, 3, `${label}: the retry re-sends`);
+ assert.equal(requests[2].request.boundTo.id, A, `${label}: the approval of the record on screen`);
+ }
+});
+
+test('fixture 27 holds the selected order while an approval runs, and another order clears the approval and its retry', async () => {
+ const source = fs.readFileSync(path.join(__dirname, '..', 'fixtures', '27-page-error-helper', 'order-approvals.tsx'), 'utf8');
+ const page = runnablePage(source, ['PageBody', 'PageErrorBar']);
+ const orders = [A, B].map((salesorderid, i) => ({ salesorderid, name: `Order ${i + 1}`, totalamount: 10, statuscode: 1 }));
+ const { requests, dataApi } = deferredActions();
+ Object.assign(dataApi, {
+ queryTable: async () => ({ rows: orders }),
+ retrieveRow: async (table, { id }) => orders.find((order) => order.salesorderid === id),
+ });
+ const props = { dataApi, pageInput: {} };
+ const orderButton = (tree, name) => elements(tree).find((node) => node.type === 'Button' && node.props.appearance === 'transparent' && [].concat(node.props.children).includes(name));
+ page.render(props);
+ page.flush();
+ await tick();
+ orderButton(page.render(props), 'Order 1').props.onClick();
+ await tick();
+ primaryButton(page.render(props)).props.onClick();
+ assert.equal(requests[0].request.boundTo.id, A, 'the approval of order 1 is sent');
+ assert.equal(orderButton(page.render(props), 'Order 2').props.disabled, true, 'another order cannot be selected while it runs');
+ requests[0].resolve(NETWORK);
+ await tick();
+ const keptRetry = approvalBar(page, page.render(props))?.props.error.retry;
+ assert.equal(typeof keptRetry, 'function', 'order 1 shows its network failure with a retry');
+ orderButton(page.render(props), 'Order 2').props.onClick();
+ await tick();
+ assert.equal(approvalBar(page, page.render(props)), undefined, 'order 2 starts with a clean approval panel');
+ keptRetry();
+ await tick();
+ assert.equal(requests.length, 1, 'order 1\'s retry sends nothing while order 2 is on screen');
+});
\ No newline at end of file
diff --git a/evals/model-apps/genpage/tests/page-expectations.test.js b/evals/model-apps/genpage/tests/page-expectations.test.js
index e59b9bbf4..2da5ce365 100644
--- a/evals/model-apps/genpage/tests/page-expectations.test.js
+++ b/evals/model-apps/genpage/tests/page-expectations.test.js
@@ -161,6 +161,24 @@ test('eval 5: components and utilities are top level; handlers that close over s
};`), []);
});
+// A check that needs a page's function scopes reads them through this export rather than keeping a second scope reader.
+// A missing export must fail here, by name — never surface later as a TypeError a caller turns into a skip — and
+// exporting it changes nothing about the top-level check above.
+test('tsx-structure exports its function scope reader, and the top-level check is unchanged by it', () => {
+ const structure = require('../lib/tsx-structure.js');
+ assert.equal(typeof structure.functionScopes, 'function', 'functionScopes is exported');
+ const code = structure.sourceView(`function load(id: string) { return id; }
+const PageBody = (props: Props) => { const go = async () => { await load('x'); }; return null; };`).code;
+ const scopes = structure.functionScopes(code);
+ assert.deepEqual(scopes.map((scope) => scope.params).sort((a, b) => a.join().localeCompare(b.join())), [[], ['id'], ['props']]);
+ assert.ok(scopes.every((scope) => scope.start < scope.end && code.slice(scope.start, scope.end).trim()), 'each scope is a body range');
+ assert.deepEqual(nestedDefinitionProblems(`function PageBody(props: Props) {
+ const { dataApi } = props;
+ async function save() { await dataApi.createRow('task', {}); }
+ return null;
+}`), [], 'a handler that closes over the props is not a nested utility');
+});
+
// --- Eval 12: the revised plan -----------------------------------------------------------------------
const E12 = '12-account-plan-revision';
@@ -353,6 +371,58 @@ test('eval 4: a label element that shows nothing names no control', () => {
}
});
+// A comment is no value: an expression that is empty once its comments are left out (`{/* hidden */ null}`,
+// `{/* none */ ''}`) names nothing, as an attribute's value and as a label element's child. The comments are the
+// ones the plugin's lexer finds, so comment delimiters inside a string are text, and a value beside a comment counts.
+test('eval 4: an empty value beside a comment is no label', () => {
+ const TITLE = '<Field label="Title">\n <Input\n aria-label="Title"';
+ const fieldLabel = (value) => withPage(E4, 'page.tsx', [TITLE, `<Field label={${value}}>\n <Input`]);
+ const ariaLabel = (value) => withPage(E4, 'page.tsx', [TITLE, `<Field>\n <Input\n aria-label={${value}}`]);
+ const labelled = (label) => withPage(E4, 'page.tsx', [TITLE, `<Field>\n ${label}\n <Input\n id="title"`]);
+ for (const empty of ['/* hidden */ null', "/* none */ ''", 'null /* hidden */', '/* a */ /* b */ undefined', '// none\n false']) {
+ assertFail(grade(LABELS, fieldLabel(empty)), /<Input> has no aria-label, aria-labelledby or label/);
+ assertFail(grade(LABELS, ariaLabel(empty)), /<Input> has no aria-label, aria-labelledby or label/);
+ for (const tag of ['label', 'Label']) {
+ assertFail(grade(LABELS, labelled(`<${tag} htmlFor="title">{${empty}}</${tag}>`)), /<Input> has no aria-label, aria-labelledby or label/);
+ assertFail(grade(LABELS, labelled(`<${tag} htmlFor="title"><span>{${empty}}</span></${tag}>`)), /<Input> has no aria-label, aria-labelledby or label/);
+ }
+ }
+ // An attribute holding only a comment does not compile (an attribute's expression may not be empty); it names nothing either.
+ assertFail(grade(LABELS, ariaLabel('/* none */')), /<Input> has no aria-label, aria-labelledby or label/);
+ for (const shown of ["/* shown */ 'Title'", "translate('title') /* shown */", "'/* not a comment */'", '// a note\n titleLabel']) {
+ assertPass(grade(LABELS, fieldLabel(shown)));
+ assertPass(grade(LABELS, ariaLabel(shown)));
+ assertPass(grade(LABELS, labelled(`<label htmlFor="title">{${shown}}</label>`)));
+ }
+});
+
+// TypeScript and Babel decode a character reference in JSX text and in an attribute's string, so a label written
+// only in references shows the characters they stand for. It names its control unless every reference stands for
+// white space (`&nbsp;`, `&#32;`): that shows nothing, like a literal non-breaking space. A reference JSX does not
+// decode (`&nosuch;`, `&#X54;`) is shown as written.
+test('eval 4: a label written in character references names its control; one of white space does not', () => {
+ const TITLE = '<Field label="Title">\n <Input\n aria-label="Title"';
+ const labelled = (label) => withPage(E4, 'page.tsx', [TITLE, `<Field>\n ${label}\n <Input\n id="title"`]);
+ for (const tag of ['label', 'Label']) {
+ for (const shown of ['&#84;&#105;&#116;&#108;&#101;', '&#x54;', '&amp;', '&eacute;', '&nosuch;', '&#X54;', '<span>&#84;</span>', '&#x54;&#x69;tle', '&nbsp;Title']) {
+ assertPass(grade(LABELS, labelled(`<${tag} htmlFor="title">${shown}</${tag}>`)));
+ }
+ for (const blank of ['&nbsp;', '&#32;', '&#x20;&#160;', '&ensp;&emsp;&thinsp;', ' &nbsp; &#10; ', '<span>&nbsp;</span>']) {
+ assertFail(grade(LABELS, labelled(`<${tag} htmlFor="title">${blank}</${tag}>`)), /<Input> has no aria-label, aria-labelledby or label/);
+ }
+ }
+ const fieldLabel = (value) => withPage(E4, 'page.tsx', [TITLE, `<Field label="${value}">\n <Input`]);
+ const ariaLabel = (value) => withPage(E4, 'page.tsx', [TITLE, `<Field>\n <Input\n aria-label="${value}"`]);
+ for (const blank of ['&nbsp;', '&#32;', '&#xA0;', '\u00a0']) {
+ assertFail(grade(LABELS, fieldLabel(blank)), /<Input> has no aria-label, aria-labelledby or label/);
+ assertFail(grade(LABELS, ariaLabel(blank)), /<Input> has no aria-label, aria-labelledby or label/);
+ }
+ for (const shown of ['&#84;&#105;&#116;&#108;&#101;', '&amp;', 'R&D', '&#X54;']) {
+ assertPass(grade(LABELS, fieldLabel(shown)));
+ assertPass(grade(LABELS, ariaLabel(shown)));
+ }
+});
+
test('eval 13: literal text in a conditional or a template child is hardcoded too', () => {
const child = (expression) => withPage(E13, 'page.tsx', ["<Text>{t('empty')}</Text>", `<Text>{${expression}}</Text>`]);
assertFail(grade(TRANSLATED, child("rows.length ? 'Contacts' : 'No contacts.'")), /hardcoded JSX string '(?:Contacts|No contacts\.)'/);
diff --git a/evals/model-apps/genpage/tests/phase-expectations.test.js b/evals/model-apps/genpage/tests/phase-expectations.test.js
index d538ed0f9..41f3792a8 100644
--- a/evals/model-apps/genpage/tests/phase-expectations.test.js
+++ b/evals/model-apps/genpage/tests/phase-expectations.test.js
@@ -658,6 +658,79 @@ test('eval 15: genpage.js types picks up an enum registration for every planned
assertSkip(grade(text, { ...committed(E15), runtimeTypes: null }), /RuntimeTypes\.ts was not captured/);
});
+// The input JSON as agents/genpage-entity-builder.md Step 4 has the entity-builder write it, for eval 15's plan: each Choice option is its
+// label, in the plan's order. The capture did not keep its input, so the cases below hand it one.
+const TICKET_CHOICES = "Phase 2b (Entity Builder): cr_ticket is provisioned with choice columns via provision-entities.js input JSON; each picklist option is written as its label, in the plan's order (numbered 100000000 + index)";
+function ticketInput(priority = ['Low', 'Medium', 'High', 'Critical'], status = ['Open', 'In Progress', 'Resolved', 'Closed']) {
+ return {
+ solution: { uniqueName: 'Crdec34', publisherPrefix: 'cr' },
+ entities: [{
+ schemaName: 'cr_Ticket', displayName: 'Ticket', pluralName: 'Tickets',
+ primaryAttribute: { schemaName: 'cr_name', displayName: 'Name', maxLength: 100 },
+ columns: [
+ { schemaName: 'cr_Priority', displayName: 'Priority', type: 'Choice', options: priority },
+ { schemaName: 'cr_Status', displayName: 'Status', type: 'Choice', options: status },
+ { schemaName: 'cr_DueDate', displayName: 'Due Date', type: 'DateTime', dateFormat: 'DateOnly' },
+ ],
+ }],
+ relationships: [],
+ };
+}
+const withInput = (input) => ({ ...committed(E15), artifacts: { ...committed(E15).artifacts, 'provision-input.json': typeof input === 'string' ? input : JSON.stringify(input) } });
+
+test('eval 15: the choice options of the input JSON are labels in the plan\'s order, as provision-entities.js takes them', () => {
+ assertPass(grade(TICKET_CHOICES, withInput(ticketInput())));
+ // A label in several languages is a label too.
+ assertPass(grade(TICKET_CHOICES, withInput(ticketInput([{ 1033: 'Low', 1036: 'Bas' }, 'Medium', 'High', 'Critical']))));
+ // The shape the entity-builder page used to show: refused by the plugin's own gate, before anything is written.
+ const labelValue = ticketInput(['Low', 'Medium', 'High', 'Critical'].map((label, i) => ({ label, value: 100000000 + i })));
+ assertFail(grade(TICKET_CHOICES, withInput(labelValue)), /provision-entities\.js refuses the captured input: .*options\[0\]: 'label' is not an LCID/);
+ assertFail(grade(TICKET_CHOICES, withInput(ticketInput(['Medium', 'Low', 'High', 'Critical']))), /ticket priority options are "Medium", "Low", "High", "Critical", but the plan numbers Low, Medium, High, Critical from 100000000/);
+ assertFail(grade(TICKET_CHOICES, withInput(ticketInput(undefined, ['Open', 'Resolved', 'Closed']))), /ticket status options are .*, but the plan numbers Open, In Progress, Resolved, Closed/);
+ const noStatus = ticketInput();
+ noStatus.entities[0].columns.splice(1, 1);
+ assertFail(grade(TICKET_CHOICES, withInput(noStatus)), /declares no ticket status column/);
+ const textStatus = ticketInput();
+ textStatus.entities[0].columns[1] = { schemaName: 'cr_Status', displayName: 'Status', type: 'Text' };
+ assertFail(grade(TICKET_CHOICES, withInput(textStatus)), /ticket status is Text, not a Choice column/);
+ assertFail(grade(TICKET_CHOICES, withInput('{ not json')), /provision-input\.json is not JSON/);
+ assertFail(grade(TICKET_CHOICES, { ...withInput(ticketInput()), workflowLog: committed(E15).workflowLog.replace('--input @D:/temp/support-tickets/provision-input.json ', '') }), /not run with --input <json>/);
+});
+
+test('eval 15: a capture that did not keep its input JSON is skipped, and a current fixture without it fails', () => {
+ assertSkip(grade(TICKET_CHOICES, committed(E15)), /provision-input\.json was not captured/);
+ assertFail(grade(TICKET_CHOICES, { ...committed(E15), contractVersion: 2, manifest: { contractVersion: 2, provenance: 'synthetic' } }), /provision-input\.json was not captured/);
+});
+
+// A table is provisioned by a run that APPLIED its input: provision-entities.js without --apply only plans, writes nothing, and answers
+// { "ok": true, "dryRun": true, "plan": [ … ] }
+// so such a run is no provisioning, however good its input. The input graded is the one the applying run was handed, not a preview's.
+function provisionedBy(events, artifacts) {
+ return { ...committed(E15), contractVersion: 2, manifest: { contractVersion: 2, provenance: 'synthetic' }, artifacts: { ...committed(E15).artifacts, ...artifacts }, events };
+}
+const provisionRun = (id, input, flags, result) => ({ id, command: `node scripts/provision-entities.js --env https://contoso.crm.dynamics.com --input @${input}${flags}`, result });
+
+test('eval 15: a dry run of provision-entities.js provisions nothing, and the input graded is the applying run\'s', () => {
+ const good = JSON.stringify(ticketInput());
+ const labelValue = JSON.stringify(ticketInput(['Low', 'Medium', 'High', 'Critical'].map((label, i) => ({ label, value: 100000000 + i }))));
+ const applied = { ok: true, entities: [{ schemaName: 'cr_Ticket', logicalName: 'cr_ticket', entitySetName: 'cr_tickets' }] };
+ const planned = { ok: true, dryRun: true, plan: [{ step: 'createTable', schemaName: 'cr_Ticket' }] };
+ assertPass(grade(TICKET_CHOICES, provisionedBy([provisionRun('apply', 'provision-input.json', ' --apply', applied)], { 'provision-input.json': good })));
+ // Planned only: no --apply, and the CLI's own dry-run answer.
+ assertFail(grade(TICKET_CHOICES, provisionedBy([provisionRun('plan', 'provision-input.json', '', planned)], { 'provision-input.json': good })),
+ /provision-entities\.js was not run with --input <json> --apply/);
+ // An answer that says it was a dry run is no apply, whatever flags were recorded with it.
+ assertFail(grade(TICKET_CHOICES, provisionedBy([provisionRun('apply', 'provision-input.json', ' --apply', planned)], { 'provision-input.json': good })),
+ /provision-entities\.js was not run with --input <json> --apply/);
+ // A preview with another input file, then the apply: the apply's input decides — either way round.
+ const previewThenApply = [provisionRun('plan', 'preview-input.json', '', planned), provisionRun('apply', 'provision-input.json', ' --apply', applied)];
+ assertPass(grade(TICKET_CHOICES, provisionedBy(previewThenApply, { 'preview-input.json': labelValue, 'provision-input.json': good })));
+ assertFail(grade(TICKET_CHOICES, provisionedBy(previewThenApply, { 'preview-input.json': good, 'provision-input.json': labelValue })),
+ /provision-entities\.js refuses the captured input: .*options\[0\]: 'label' is not an LCID/);
+ // The applying run's input was not kept: a current fixture fails, though the preview's was.
+ assertFail(grade(TICKET_CHOICES, provisionedBy(previewThenApply, { 'preview-input.json': good })), /provision-input\.json was not captured/);
+});
+
// --- Eval 19 -----------------------------------------------------------------------------------
const E19 = '19-add-weather-connector';
diff --git a/evals/model-apps/genpage/tests/polymorphic-lookup-contract.test.js b/evals/model-apps/genpage/tests/polymorphic-lookup-contract.test.js
new file mode 100644
index 000000000..9a8b02070
--- /dev/null
+++ b/evals/model-apps/genpage/tests/polymorphic-lookup-contract.test.js
@@ -0,0 +1,184 @@
+'use strict';
+// The canonical lookup normalizer (lib/polymorphic-lookup-contract.js reads it from references/rules.md and checks a page's copy),
+// the published block run against fixture 26's synthetic customer values, and the typed-path context of the column check
+// (lib/column-contract.js). What a page does with a lookup is not graded (EVAL_GUIDE.md). The page below is assembled from the
+// canonical normalizer and the CORRECT forms of the rules' lookup pitfalls; the rows, tables and paths are synthetic, shaped like
+// get-lookup-metadata.js's answer.
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const { normalizerProblems } = require('../lib/polymorphic-lookup-contract.js');
+const { columnProblems } = require('../lib/column-contract.js');
+
+const RULES = fs.readFileSync(path.join(__dirname, '..', '..', '..', '..', 'plugins', 'model-apps', 'references', 'rules.md'), 'utf8').replace(/\r\n/g, '\n');
+const HEADING = '### Lookup references (Customer, Owner, Regarding and every other lookup)';
+const SECTION = RULES.slice(RULES.indexOf(`\n${HEADING}\n`));
+const NORMALIZER = [...SECTION.matchAll(/```typescript\n([\s\S]*?)\n```/g)].map((match) => match[1]).find((block) => block.includes('function normalizeLookupReference('));
+
+const LOOKUPS = [{
+ table: 'opportunity', column: 'customerid', readProperty: '_customerid_value', targets: ['account', 'contact'],
+ paths: [
+ { target: 'account', navigationProperty: 'customerid_account', referencedKey: 'accountid' },
+ { target: 'contact', navigationProperty: 'customerid_contact', referencedKey: 'contactid' },
+ ],
+}];
+
+const BODY = `
+type Row = Record<string, unknown>;
+type Picked = { table: 'account' | 'contact'; id: string };
+
+function PageBody(props: GeneratedComponentProps) {
+ const { dataApi } = props;
+
+ async function loadAccountOpportunities(row: Row) {
+ const normalized = normalizeLookupReference(row, '_customerid_value', ['account', 'contact']);
+ if (normalized.state !== 'resolved') return;
+ const reference = normalized.reference;
+ if (reference.table !== 'account') return;
+ const filter = \`customerid_account/accountid eq \${reference.id}\`;
+ return dataApi.queryTable('opportunity', { select: ['name', '_customerid_value'], filter });
+ }
+
+ async function loadAll() {
+ return dataApi.queryTable('opportunity', { select: ['name', '_customerid_value'], filter: '_customerid_value ne null' });
+ }
+
+ async function searchAccounts(searchText: string) {
+ const escaped = searchText.replace(/'/g, "''");
+ const filter = \`customerid_account/accountid ne null and contains(customerid_account/name,'\${escaped}')\`;
+ return dataApi.queryTable('opportunity', { select: ['name'], filter });
+ }
+
+ async function openCustomer(row: Row) {
+ const normalized = normalizeLookupReference(row, '_customerid_value', ['account', 'contact']);
+ if (normalized.state !== 'resolved') return;
+ const reference = normalized.reference;
+ await Xrm.Navigation.navigateTo({ pageType: 'entityrecord', entityName: reference.table, entityId: reference.id });
+ }
+
+ async function readCustomer(row: Row) {
+ const normalized = normalizeLookupReference(row, '_customerid_value', ['account', 'contact']);
+ if (normalized.state !== 'resolved') return;
+ const reference = normalized.reference;
+ if (reference.table !== 'account') return;
+ return dataApi.retrieveRow('account', { id: reference.id, select: ['name'] });
+ }
+
+ async function changeCustomer(opportunityId: string, selected: Picked) {
+ const link: \`/account(\${string})\` | \`/contact(\${string})\` = selected.table === 'account'
+ ? \`/account(\${selected.id})\`
+ : \`/contact(\${selected.id})\`;
+ await dataApi.updateRow('opportunity', opportunityId, { _customerid_value: link });
+ }
+
+ async function clearCustomer(opportunityId: string) {
+ await dataApi.updateRow('opportunity', opportunityId, { _customerid_value: null });
+ }
+
+ const label = (row: Row) => String(row['[email protected]'] ?? '');
+ return <div>{label({})}</div>;
+}
+`;
+const PAGE = `import * as React from 'react';\n\n${NORMALIZER}\n${BODY}`;
+
+function swap(source, from, to) {
+ assert.ok(source.includes(from), `the page holds: ${from}`);
+ return source.split(from).join(to);
+}
+
+test('the canonical normalizer passes', () => {
+ assert.ok(NORMALIZER, 'rules.md publishes the normalizer');
+ assert.deepEqual(normalizerProblems(PAGE), []);
+});
+
+test('an altered, missing or duplicated normalizer is not the canonical one', () => {
+ for (const [label, source] of [
+ ['the first target as a fallback', swap(PAGE, '(allowedTargets.length === 1 ? allowedTargets[0] : undefined)', 'allowedTargets[0]')],
+ ['no conflict check', swap(PAGE, " if (annotation !== undefined && prefix !== undefined && annotation !== prefix) return { state: 'invalid' };\n", '')],
+ ['a looser GUID pattern', swap(PAGE, 'const LOOKUP_GUID = /^[0-9a-fA-F]{8}', 'const LOOKUP_GUID = /[0-9a-fA-F]{8}')],
+ ['no normalizer', swap(PAGE, NORMALIZER, '')],
+ ['a second one', `${PAGE}\nfunction normalizeLookupReference(row: unknown) { return { state: 'invalid' }; }\n`],
+ ]) {
+ assert.ok(normalizerProblems(source).length > 0, label);
+ }
+ // Comments and indentation are not substantive.
+ const reindented = swap(PAGE, " const record = row as Record<string, unknown>;", " // the row is an object here\n const record = row as Record<string, unknown>;");
+ assert.deepEqual(normalizerProblems(reindented), []);
+});
+
+// --- the column check's typed-path context ---------------------------------------------------------------------------------------
+
+const RUNTIME_TYPES = `
+export interface TableRegistrations extends BaseTableRegistrations {
+ "opportunity": opportunity,
+ "account": account,
+}
+export type opportunity = TableRow<{
+ readonly opportunityid: string,
+ name: string,
+ _customerid_value: \`/account(\${string})\` | \`/contact(\${string})\`,
+}>
+export type account = TableRow<{
+ readonly accountid: string,
+ name: string,
+}>
+`;
+const PATH_CONTEXT = { lookupPaths: LOOKUPS[0].paths.map((entry) => ({ table: 'opportunity', ...entry })), targetColumns: { account: ['name'] } };
+const filtered = (filter) => [{ name: 'page.tsx', content: `export default function P({ dataApi }) { dataApi.queryTable('opportunity', { select: ['name'], filter: ${JSON.stringify(filter)} }); return null; }` }];
+
+test('with lookup context a typed path is checked whole; without it the column check reads the text exactly as before', () => {
+ assert.deepEqual(columnProblems(filtered('customerid_account/accountid ne null'), RUNTIME_TYPES, PATH_CONTEXT), []);
+ assert.deepEqual(columnProblems(filtered("contains(customerid_account/name,'x')"), RUNTIME_TYPES, PATH_CONTEXT), []);
+ assert.deepEqual(columnProblems(filtered('customerid_contact/contactid ne null'), RUNTIME_TYPES, PATH_CONTEXT), [], 'a target RuntimeTypes does not register is held to its key and verified columns');
+ assert.match(columnProblems(filtered('ownerid_team/teamid ne null'), RUNTIME_TYPES, PATH_CONTEXT)[0], /ownerid_team\/teamid, which is not a verified navigation path of opportunity/);
+ assert.match(columnProblems(filtered('customerid_account/revenue gt 0'), RUNTIME_TYPES, PATH_CONTEXT)[0], /customerid_account\/revenue, which is not a verified column of account/);
+ assert.match(columnProblems(filtered('customerid_contact/fullname ne null'), RUNTIME_TYPES, PATH_CONTEXT)[0], /not a verified column of contact/);
+ // Legacy: no context, no exemption for a slash — its parts are read as columns of the queried table, as before.
+ assert.deepEqual(columnProblems(filtered('customerid_account/accountid ne null'), RUNTIME_TYPES), [
+ "page.tsx: queryTable('opportunity') filter names accountid, which RuntimeTypes.ts does not declare on opportunity",
+ ]);
+ assert.deepEqual(columnProblems(filtered("name eq 'x'"), RUNTIME_TYPES), [], 'neighbour: a plain column');
+ assert.deepEqual(columnProblems(filtered("name eq 'x'"), RUNTIME_TYPES, PATH_CONTEXT), [], 'neighbour: a plain column with context');
+});
+
+// ---------- eval 26's synthetic customer values, run through the published normalizer ----------
+// The fixture's lookup-rows.json holds synthetic Customer values (account and contact, bare and qualified, null, contradictory and
+// foreign evidence, a plural entity set, equal labels, one GUID in two tables), each with the state the normalizer must give it.
+// The trusted helper is the rules.md block itself, transpiled with the TypeScript the plugin vendors and called directly — the
+// fixture's page module is never executed to find out what it means.
+const { loadVendoredTypeScript } = require('../../../../plugins/model-apps/scripts/lib/typescript-compiler.js');
+const FIXTURE_26 = path.join(__dirname, '..', 'fixtures', '26-customer-lookup');
+
+function publishedNormalizer() {
+ const typescript = loadVendoredTypeScript();
+ const { outputText } = typescript.transpileModule(`${NORMALIZER}\nexport { normalizeLookupReference };\n`, {
+ fileName: 'normalizer.ts',
+ compilerOptions: { module: typescript.ModuleKind.CommonJS, target: typescript.ScriptTarget.ES2020 },
+ });
+ const module = { exports: {} };
+ new Function('module', 'exports', 'require', outputText)(module, module.exports, () => { throw new Error('the helper imports nothing'); });
+ return module.exports.normalizeLookupReference;
+}
+
+test('eval 26: every synthetic customer value gets the state lookup-rows.json records, and the resolved ones stay apart by table and id', () => {
+ const normalize = publishedNormalizer();
+ const { lookup, rows } = JSON.parse(fs.readFileSync(path.join(FIXTURE_26, 'lookup-rows.json'), 'utf8'));
+ const metadata = JSON.parse(fs.readFileSync(path.join(FIXTURE_26, 'lookup-metadata.json'), 'utf8'));
+ const recorded = metadata.tables.find((table) => table.logicalName === lookup.table).lookups.find((entry) => entry.column === lookup.column);
+ assert.deepEqual(recorded.targets, lookup.targets, 'the rows are normalized with the complete target set the metadata read');
+ const states = new Set();
+ for (const entry of rows) {
+ assert.deepEqual(normalize(entry.row, lookup.readProperty, lookup.targets), entry.expected, entry.case);
+ states.add(entry.expected.state);
+ }
+ assert.deepEqual([...states].sort(), ['invalid', 'needs-target', 'resolved', 'unset'], 'every state is exercised');
+ // Equal labels, and one GUID in two tables, are different customers: the picker keys them by table and id.
+ const resolved = rows.map((entry) => normalize(entry.row, lookup.readProperty, lookup.targets)).filter((result) => result.state === 'resolved');
+ const keys = new Set(resolved.map(({ reference }) => `${reference.table}:${reference.id}`));
+ const label = (entry) => entry.row['[email protected]'];
+ const contoso = rows.filter((entry) => label(entry) === 'Contoso').map((entry) => normalize(entry.row, lookup.readProperty, lookup.targets));
+ assert.deepEqual(contoso.map(({ reference }) => reference.table), ['account', 'contact']);
+ assert.equal(contoso[0].reference.id, contoso[1].reference.id, 'one GUID in both tables');
+ assert.ok(keys.has(`account:${contoso[0].reference.id}`) && keys.has(`contact:${contoso[1].reference.id}`));
+});
diff --git a/evals/model-apps/genpage/tests/reporter.test.js b/evals/model-apps/genpage/tests/reporter.test.js
new file mode 100644
index 000000000..869d6e45b
--- /dev/null
+++ b/evals/model-apps/genpage/tests/reporter.test.js
@@ -0,0 +1,97 @@
+'use strict';
+// The TAP reporter the genpage runners and the app-builder runner share (lib/reporter.js). An assertion is pass, fail or skip, and a skip grades
+// nothing. So a fixture passes only when at least one of its assertions was graded and none failed; a fixture whose every assertion skipped — or
+// that has none — is unscored: its line carries TAP's `# SKIP` directive, it is counted on a line of its own, and it is never counted as passed.
+// The `# fixtures N (pass P, fail F)` summary keeps its exact form, and a run with no unscored fixture prints exactly what it always printed.
+// The pcf eval runner prints through a byte-for-byte copy of this reporter (evals/pcf/lib/reporter.js); the last test here fails when the two
+// drift apart, so a change to this file takes the copy with it in the same PR (the pcf reporter tests check the same from their side).
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const { TapReporter } = require('../lib/reporter.js');
+
+const PASS = { status: 'pass', reason: '' };
+const SKIP = { status: 'skip', reason: 'not applicable' };
+const FAIL = { status: 'fail', reason: 'broken' };
+
+// Reports `fixtures` — [name, results] pairs — through one reporter, as a runner does; returns its whole output and the reporter.
+function report(fixtures) {
+ let text = '';
+ const reporter = new TapReporter({ write: (chunk) => { text += chunk; } });
+ reporter.start(fixtures.length);
+ for (const [name, results] of fixtures) {
+ reporter.startFixture(name);
+ results.forEach((result, index) => reporter.assertion(`assertion ${index + 1}`, result));
+ reporter.endFixture();
+ }
+ reporter.end();
+ return { text, lines: text.split('\n'), reporter };
+}
+const summary = (lines) => lines.filter((line) => /^# (?:tests|pass|fail|skip|fixtures|unscored)/.test(line));
+
+test('a fixture whose every assertion skipped is unscored: a # SKIP fixture line, its own count, never the passed count, and no failure', () => {
+ const { lines, reporter } = report([['all-skipped', [SKIP, SKIP, SKIP]]]);
+ assert.ok(lines.includes('ok 1 - all-skipped # SKIP no expectation graded'), lines.join('\n'));
+ assert.deepStrictEqual(summary(lines), ['# tests 3', '# pass 0', '# fail 0', '# skip 3', '# fixtures 1 (pass 0, fail 0)', '# unscored fixtures 1']);
+ assert.deepStrictEqual([reporter.fixturePass, reporter.fixtureFail, reporter.fixtureUnscored], [0, 0, 1]);
+ assert.equal(reporter.exitCode, 0);
+});
+
+test('a fixture with no assertion at all is unscored the same way', () => {
+ const { lines, reporter } = report([['empty', []], ['graded', [PASS]]]);
+ assert.ok(lines.includes(' 1..0'), lines.join('\n'));
+ assert.ok(lines.includes('ok 1 - empty # SKIP no expectation graded'), lines.join('\n'));
+ assert.ok(lines.includes('ok 2 - graded'), lines.join('\n'));
+ assert.deepStrictEqual(summary(lines), ['# tests 1', '# pass 1', '# fail 0', '# skip 0', '# fixtures 2 (pass 1, fail 0)', '# unscored fixtures 1']);
+ assert.deepStrictEqual([reporter.fixturePass, reporter.fixtureFail, reporter.fixtureUnscored], [1, 0, 1]);
+ assert.equal(reporter.exitCode, 0);
+});
+
+test('a fixture with one graded assertion and skips beside it still passes; one failed assertion fails a fixture, skips or not', () => {
+ const { lines, reporter } = report([['mixed', [SKIP, PASS, SKIP]], ['failed', [SKIP, FAIL]], ['unscored', [SKIP]]]);
+ assert.ok(lines.includes('ok 1 - mixed'), lines.join('\n'));
+ assert.ok(lines.includes('not ok 2 - failed'), lines.join('\n'));
+ assert.ok(lines.includes('ok 3 - unscored # SKIP no expectation graded'), lines.join('\n'));
+ assert.deepStrictEqual(summary(lines), ['# tests 6', '# pass 1', '# fail 1', '# skip 4', '# fixtures 3 (pass 1, fail 1)', '# unscored fixtures 1']);
+ assert.deepStrictEqual([reporter.fixturePass, reporter.fixtureFail, reporter.fixtureUnscored], [1, 1, 1]);
+ // Only a failed fixture makes the run fail; an unscored one does not.
+ assert.equal(reporter.exitCode, 1);
+});
+
+test('a run with no unscored fixture prints exactly what it always printed, and `# fixtures` stays its one summary line', () => {
+ const { text, lines, reporter } = report([['graded', [PASS, SKIP]], ['broken', [SKIP, FAIL]]]);
+ assert.equal(text, [
+ 'TAP version 13',
+ '1..2',
+ '# Subtest: graded',
+ ' ok 1 - assertion 1',
+ ' ok 2 - assertion 2 # SKIP not applicable',
+ ' 1..2',
+ 'ok 1 - graded',
+ '# Subtest: broken',
+ ' ok 1 - assertion 1 # SKIP not applicable',
+ ' not ok 2 - assertion 2',
+ ' ---',
+ ' reason: "broken"',
+ ' ...',
+ ' 1..2',
+ 'not ok 2 - broken',
+ '# tests 4',
+ '# pass 1',
+ '# fail 1',
+ '# skip 2',
+ '# fixtures 2 (pass 1, fail 1)',
+ '',
+ ].join('\n'));
+ assert.equal(reporter.fixtureUnscored, 0);
+ assert.equal(reporter.exitCode, 1);
+ const unscored = report([['all-skipped', [SKIP]]]).lines;
+ assert.deepStrictEqual(unscored.filter((line) => line.startsWith('# fixtures')), ['# fixtures 1 (pass 0, fail 0)']);
+});
+
+test('the pcf eval runner\'s reporter is this reporter, byte for byte, so it grades and counts as these runners do', () => {
+ const source = fs.readFileSync(path.join(__dirname, '..', 'lib', 'reporter.js'));
+ const copy = fs.readFileSync(path.join(__dirname, '..', '..', '..', 'pcf', 'lib', 'reporter.js'));
+ assert.ok(copy.equals(source), 'evals/pcf/lib/reporter.js differs from evals/model-apps/genpage/lib/reporter.js: change both in the same PR (copy the file over)');
+});
diff --git a/evals/model-apps/genpage/tests/run-layer-1.test.js b/evals/model-apps/genpage/tests/run-layer-1.test.js
index 16d42dc81..125c14757 100644
--- a/evals/model-apps/genpage/tests/run-layer-1.test.js
+++ b/evals/model-apps/genpage/tests/run-layer-1.test.js
@@ -189,3 +189,62 @@ test('runner: emits TAP version 13 and aggregate counts', () => {
fs.rmSync(root, { recursive: true, force: true });
}
});
+
+// ---------- a newly authored plan's semantic records: a real callback and a real exit status ----------
+
+const NEW_CONTRACT = "Phase 1 (Planner): The newly authored plan records its assumptions and every page's data semantics and lookup metadata, the approved preview carries the same records, and provenance is verified with --require-assumptions";
+
+test('runner: fixture 27 grades its newly authored plan, and a copy verified without --require-assumptions fails with exit 1', (t) => {
+ const green = runRunner(['--eval', '27']);
+ assert.equal(green.code, 0, green.stdout + green.stderr);
+ const line = green.stdout.split('\n').find((entry) => entry.includes(NEW_CONTRACT));
+ assert.ok(line && /^\s*ok \d+ - /.test(line) && !/# SKIP/.test(line), `graded and passing, not skipped: ${line}`);
+ const root = mkTempFixturesDir();
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const copy = path.join(root, '27-page-error-helper');
+ fs.cpSync(path.join(__dirname, '..', 'fixtures', '27-page-error-helper'), copy, { recursive: true });
+ const results = path.join(copy, 'tool-results.json');
+ const events = JSON.parse(fs.readFileSync(results, 'utf8'));
+ for (const event of events) event.command = event.command.replace(' --require-assumptions', '');
+ fs.writeFileSync(results, JSON.stringify(events, null, 2));
+ const red = runRunner(['--fixtures', root, '--eval', '27']);
+ assert.equal(red.code, 1, red.stdout);
+ assert.match(red.stdout, /provenance was never verified with --require-assumptions/);
+ // A preview whose assumption differs from the written plan's is not the approval of that plan.
+ fs.writeFileSync(results, JSON.stringify(JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'fixtures', '27-page-error-helper', 'tool-results.json'), 'utf8')), null, 2));
+ const preview = path.join(copy, 'approved-plan.md');
+ fs.writeFileSync(preview, fs.readFileSync(preview, 'utf8').replace('sorted by name ascending, 50 rows per page.', 'sorted by name ascending, 100 rows per page.'));
+ const changed = runRunner(['--fixtures', root, '--eval', '27']);
+ assert.equal(changed.code, 1, changed.stdout);
+ assert.match(changed.stdout, /the written plan differs from the approved preview: .*A1/);
+});
+
+test('runner: fixture 26 grades its answered question, lookup metadata, typed lookup and gate; a copy that drops a declared reference fails with exit 1', (t) => {
+ const green = runRunner(['--eval', '26']);
+ assert.equal(green.code, 0, green.stdout + green.stderr);
+ const graded = [
+ 'The open account-scope question reaches the maker as needs_input',
+ "get-lookup-metadata.js reads opportunity's lookups before approval",
+ NEW_CONTRACT,
+ "RuntimeTypes.ts is generated for opportunity and types each recorded lookup's read property",
+ 'The page is generated only after provenance is verified with --require-assumptions --require-observed-lookups',
+ ];
+ for (const text of graded) {
+ const line = green.stdout.split('\n').find((entry) => entry.includes(text));
+ assert.ok(line && /^\s*ok \d+ - /.test(line) && !/# SKIP/.test(line), `graded and passing, not skipped: ${line}`);
+ }
+ const root = mkTempFixturesDir();
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const copy = path.join(root, '26-customer-lookup');
+ fs.cpSync(path.join(__dirname, '..', 'fixtures', '26-customer-lookup'), copy, { recursive: true });
+ const manifestPath = path.join(copy, 'fixture.json');
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
+ for (const [key, reason] of [['interactions', /does not declare its interactions evidence/], ['lookupMetadata', /does not declare its lookupMetadata evidence/]]) {
+ const changed = structuredClone(manifest);
+ delete changed.semantics[key];
+ fs.writeFileSync(manifestPath, JSON.stringify(changed, null, 2));
+ const red = runRunner(['--fixtures', root, '--eval', '26']);
+ assert.equal(red.code, 1, `${key}: ${red.stdout}`);
+ assert.match(red.stdout, reason);
+ }
+});
\ No newline at end of file
diff --git a/evals/model-apps/genpage/tests/source-evidence.test.js b/evals/model-apps/genpage/tests/source-evidence.test.js
index a4981dbd1..f8b592968 100644
--- a/evals/model-apps/genpage/tests/source-evidence.test.js
+++ b/evals/model-apps/genpage/tests/source-evidence.test.js
@@ -44,7 +44,7 @@ function receiverOk(code) {
const calls = actionCalls(code);
assert.equal(calls.length, 1, code);
const [call] = calls;
- return receiverIsDataApi(call.mask, call.scopes, call.receiver, call.start);
+ return receiverIsDataApi(call.mask, call.scopes, call.receiver, call.start, call.code);
}
const helper = (receiver, params = '', name = 'run') => `async function ${name}(${params}) {
@@ -104,11 +104,11 @@ async function summary(client: ActionApi) {
` + page('props', 'const { dataApi } = props; void approve(dataApi); void summary(dataApi);');
const calls = actionCalls(code);
assert.equal(calls.length, 2);
- for (const call of calls) assert.equal(receiverIsDataApi(call.mask, call.scopes, call.receiver, call.start), true, call.scope.name);
+ for (const call of calls) assert.equal(receiverIsDataApi(call.mask, call.scopes, call.receiver, call.start, call.code), true, call.scope.name);
const mixed = code.replace('void summary(dataApi);', 'void summary(makeClient());');
const [approve, summary] = actionCalls(mixed);
- assert.equal(receiverIsDataApi(approve.mask, approve.scopes, approve.receiver, approve.start), true, 'approve keeps its own provenance');
- assert.equal(receiverIsDataApi(summary.mask, summary.scopes, summary.receiver, summary.start), false, 'summary is filled with another object');
+ assert.equal(receiverIsDataApi(approve.mask, approve.scopes, approve.receiver, approve.start, approve.code), true, 'approve keeps its own provenance');
+ assert.equal(receiverIsDataApi(summary.mask, summary.scopes, summary.receiver, summary.start, summary.code), false, 'summary is filled with another object');
});
test('a receiver binding needs lexical scope and an identity-preserving initializer', () => {
@@ -257,4 +257,212 @@ test('a named helper\u2019s destructured parameter binds its own names', () => {
// The same rule for a helper outside the component.
assert.equal(receiverOk(helper('dataApi', '{ dataApi }: Props') + page('props', 'void run(props);')), true, 'an outer helper');
assert.equal(receiverOk(helper('dataApi', '{ dataApi }: Props') + page('props', 'void run({ dataApi: mockApi });')), false, 'an outer helper, given a mock');
-});
\ No newline at end of file
+});
+
+// The page error contract wraps the page in a render boundary (references/rules.md, "Missing Error Handling"): the default
+// export only forwards its props, unchanged, to the top-level PageBody, which holds the hooks and the dataApi calls:
+// const GeneratedComponent = (props: GeneratedComponentProps) => (
+// <PageErrorBoundary>
+// <PageBody {...props} />
+// </PageErrorBoundary>
+// );
+// React then hands PageBody exactly the page props, so its first parameter is proven to be them — but only through that
+// one bounded shape, never because a function happens to be called PageBody.
+// The forwarding proof also requires PageErrorBoundary to be the documented class itself — a function or an altered class
+// of that name could clone its child with another dataApi — extending the page's own React.Component, so every wrapper below
+// imports React from 'react' and declares that class, copied from references/rules.md.
+const BOUNDARY_CLASS = (() => {
+ const rules = require('node:fs').readFileSync(require('node:path').join(__dirname, '..', '..', '..', '..', 'plugins', 'model-apps', 'references', 'rules.md'), 'utf8').replace(/\r\n/g, '\n');
+ const start = rules.indexOf('class PageErrorBoundary extends React.Component<');
+ return rules.slice(start, rules.indexOf('\n}\n', start) + 3);
+})();
+const body = (inner, { name = 'PageBody', param = 'props' } = {}) => `function ${name}(${param}: GeneratedComponentProps) {
+ ${inner}
+ return null;
+}
+`;
+const wrapper = (jsx, param = 'props') => `import * as React from 'react';
+${BOUNDARY_CLASS}
+const GeneratedComponent = (${param}: GeneratedComponentProps) => (
+ ${jsx}
+);
+export default GeneratedComponent;
+`;
+const CANONICAL = '<PageErrorBoundary>\n <PageBody {...props} />\n </PageErrorBoundary>';
+const DESTRUCTURED = 'const { dataApi } = props;\n void run(dataApi);';
+
+test('the canonical boundary wrapper forwards the page props to PageBody, so its dataApi is the page dataApi', () => {
+ assert.equal(receiverOk(helper('client', 'client') + body(DESTRUCTURED) + wrapper(CANONICAL)), true, 'a helper filled from PageBody');
+ assert.equal(receiverOk(body(`async function approve() {
+ const res = await props.dataApi.executeAction({ name: 'cnt_Approve' });
+ }`) + wrapper(CANONICAL)), true, 'props.dataApi in a handler inside PageBody');
+ assert.equal(receiverOk(helper('client', 'client') + `const PageBody = (pageProps: GeneratedComponentProps) => {
+ const { dataApi } = pageProps;
+ void run(dataApi);
+ return null;
+};
+` + wrapper(CANONICAL)), true, 'an arrow PageBody with its own parameter name');
+ assert.equal(receiverOk(helper('client', 'client') + body(DESTRUCTURED) + `import * as React from 'react';\n` + BOUNDARY_CLASS + `function GeneratedComponent(props: GeneratedComponentProps) {
+ return (
+ <PageErrorBoundary appInsights={props.appInsights}>
+ <PageBody {...props} />
+ </PageErrorBoundary>
+ );
+}
+export default GeneratedComponent;
+`), true, 'a function wrapper, with the boundary given its telemetry prop');
+ // Neighbour: a page without the wrapper keeps the old proof from its default export.
+ assert.equal(receiverOk(helper('client', 'client') + page('props', DESTRUCTURED)), true, 'a page without the wrapper is unchanged');
+ // The same wrapper around a boundary that is not the documented class proves nothing.
+ const bare = wrapper(CANONICAL).replace(BOUNDARY_CLASS, '');
+ assert.equal(receiverOk(helper('client', 'client') + body(DESTRUCTURED) + bare), false, 'no boundary class declared');
+ const cloning = 'function PageErrorBoundary(p: { children: React.ReactElement }) { return React.cloneElement(p.children, { dataApi: mockApi }); }\n';
+ assert.equal(receiverOk(helper('client', 'client') + body(DESTRUCTURED) + cloning + bare), false, 'a PageErrorBoundary function that clones its child');
+ const twice = wrapper(CANONICAL).replace(' public render(): React.ReactNode {', ' public render(): React.ReactNode {\n return React.cloneElement(this.props.children as React.ReactElement, { dataApi: mockApi });\n }\n\n public renderOriginal(): React.ReactNode {');
+ assert.equal(receiverOk(helper('client', 'client') + body(DESTRUCTURED) + twice), false, 'an altered boundary class');
+});
+
+test('anything but the exact forwarding shape leaves PageBody\u2019s props unproven', () => {
+ const run = helper('client', 'client');
+ const refused = {
+ // `PageBody(props)` in the render is an ordinary named call, which the existing proof follows because it does pass the
+ // page props on. Called with anything else, it proves nothing.
+ 'PageBody evaluated in the render with other props': run + body(DESTRUCTURED) + wrapper('<PageErrorBoundary>{PageBody(mockProps)}</PageErrorBoundary>'),
+ 'an extra child prop': run + body(DESTRUCTURED) + wrapper('<PageErrorBoundary><PageBody {...props} dataApi={mockApi} /></PageErrorBoundary>'),
+ 'another spread source': run + body(DESTRUCTURED) + wrapper('<PageErrorBoundary><PageBody {...mockProps} /></PageErrorBoundary>'),
+ 'a second spread': run + body(DESTRUCTURED) + wrapper('<PageErrorBoundary><PageBody {...props} {...mockProps} /></PageErrorBoundary>'),
+ 'a second child': run + body(DESTRUCTURED) + wrapper('<PageErrorBoundary><Header /><PageBody {...props} /></PageErrorBoundary>'),
+ 'the boundary is not the root': run + body(DESTRUCTURED) + wrapper('<div><PageErrorBoundary><PageBody {...props} /></PageErrorBoundary></div>'),
+ 'an unrelated wrapper component': run + body(DESTRUCTURED) + wrapper('<OtherBoundary><PageBody {...props} /></OtherBoundary>'),
+ 'a second caller of PageBody': run + body(DESTRUCTURED) + wrapper(CANONICAL) + 'const Preview = () => <PageBody {...mockProps} />;\n',
+ 'PageBody handed on as a value': run + body(DESTRUCTURED) + wrapper(CANONICAL) + 'const Alias = PageBody;\n',
+ 'two PageBody declarations': run + body(DESTRUCTURED) + body('', { param: 'other' }) + wrapper(CANONICAL),
+ 'a destructured PageBody parameter': run + `function PageBody({ dataApi }: GeneratedComponentProps) {
+ void run(dataApi);
+ return null;
+}
+` + wrapper(CANONICAL),
+ 'the wrapper rebinds its props': run + body(DESTRUCTURED) + `const GeneratedComponent = (props: GeneratedComponentProps) => {
+ props = mockProps;
+ return <PageErrorBoundary><PageBody {...props} /></PageErrorBoundary>;
+};
+export default GeneratedComponent;
+`,
+ 'a boundary given the dataApi': run + body(DESTRUCTURED) + wrapper('<PageErrorBoundary dataApi={props.dataApi}><PageBody {...props} /></PageErrorBoundary>'),
+ 'PageBody nested in the wrapper': run + `const GeneratedComponent = (props: GeneratedComponentProps) => {
+ function PageBody(inner: GeneratedComponentProps) {
+ const { dataApi } = inner;
+ void run(dataApi);
+ return null;
+ }
+ return <PageErrorBoundary><PageBody {...props} /></PageErrorBoundary>;
+};
+export default GeneratedComponent;
+`,
+ };
+ for (const [label, code] of Object.entries(refused)) assert.equal(receiverOk(code), false, label);
+});
+
+// ---------- the boundary wrapper's proof on a whole page (fixture 27) ----------
+// Only the documented boundary class lets PageBody's props be the page props: a PageErrorBoundary function, or a class of
+// that name changed after it was copied, can hand PageBody another object — so neither proves a receiver, and the Custom API
+// runtime check (which reads receivers through this proof) refuses the page.
+test('only the documented boundary class proves where PageBody\'s dataApi comes from: a function or an altered class of that name proves nothing', () => {
+ const fs = require('node:fs');
+ const path = require('node:path');
+ const { forwardedPageBodyOf } = require('../lib/source-evidence.js');
+ const { runtimeProblems } = require('../lib/custom-api-contract.js');
+ const fixture = fs.readFileSync(path.join(__dirname, '..', 'fixtures', '27-page-error-helper', 'order-approvals.tsx'), 'utf8').replace(/\r\n/g, '\n');
+ const counterfeit = "{ dataApi: { executeAction: async () => ({ ok: true, outputs: { NewStatus: 'counterfeit' } }) } }";
+ const classStart = fixture.indexOf('class PageErrorBoundary extends');
+ const classEnd = fixture.indexOf('\n}\n', fixture.indexOf(' public render(): React.ReactNode {', classStart)) + 2;
+ const cases = [
+ ['a PageErrorBoundary function that clones its child with another dataApi', fixture.slice(0, classStart)
+ + `function PageErrorBoundary(props: { children: React.ReactElement }) {\n return React.cloneElement(props.children, ${counterfeit});\n}`
+ + fixture.slice(classEnd)],
+ ['the canonical class with a second render() that clones its child', fixture.slice(0, classEnd - 2)
+ + `\n public render(): React.ReactNode {\n return React.cloneElement(this.props.children as React.ReactElement, ${counterfeit});\n }\n`
+ + fixture.slice(classEnd - 2)],
+ ['the canonical class patched after its declaration', fixture.slice(0, classEnd)
+ + `\nPageErrorBoundary.prototype.render = function render() { return React.cloneElement(this.props.children, ${counterfeit}); };\n`
+ + fixture.slice(classEnd)],
+ ['a page that binds React itself', fixture.slice(0, classStart) + 'const React = { Component: class {} } as any;\n' + fixture.slice(classStart)],
+ ];
+ const approve = (source) => actionCalls(source).filter((call) => call.fields.get('name') === "'cnt_ApproveOrder'");
+ assert.ok(forwardedPageBodyOf(fixture), 'the fixture itself is forwarded');
+ assert.deepEqual(approve(fixture).map((call) => receiverIsDataApi(call.mask, call.scopes, call.receiver, call.start, call.code)), [true]);
+ const bindings = [{ name: 'cnt_ApproveOrder', isFunction: false, displayName: 'Approve Order', boundEntityLogicalName: 'salesorder', parameterKinds: { Comment: 'String' } }];
+ assert.deepEqual(runtimeProblems(fixture, bindings, { cnt_ApproveOrder: ['NewStatus'] }, new Map()), []);
+ for (const [label, source] of cases) {
+ assert.equal(forwardedPageBodyOf(source), null, `${label}: no forwarding proof`);
+ const calls = approve(source);
+ assert.ok(calls.length >= 1, `${label}: the Action call is still read`);
+ assert.ok(calls.every((call) => !receiverIsDataApi(call.mask, call.scopes, call.receiver, call.start, call.code)), `${label}: its receiver is not proven to be the page dataApi`);
+ assert.ok(runtimeProblems(source, bindings, { cnt_ApproveOrder: ['NewStatus'] }, new Map()).some((problem) => /not the page's dataApi prop/.test(problem)), `${label}: the Custom API check refuses it`);
+ }
+ // String contents aside, the class is compared as documented: a translated fallback key still forwards.
+ const renamed = fixture.replace("translate('error.render')", "translate('error.renderx')");
+ assert.notEqual(renamed, fixture);
+ assert.ok(forwardedPageBodyOf(renamed), 'a string does not decide what the boundary forwards');
+});
+
+// The boundary's base is the page's own React.Component, or nothing is proven. A page-supplied `Component` — here the
+// documented named-import class form over a destructured replacement whose constructor installs an instance `render` — gives
+// the boundary another base that clones its child with a counterfeit dataApi; so does any rebound, patched or second React.
+test('PageBody\'s props are proven only when the boundary extends React.Component from the page\'s own react import', () => {
+ const fs = require('node:fs');
+ const path = require('node:path');
+ const { forwardedPageBodyOf } = require('../lib/source-evidence.js');
+ const { runtimeProblems } = require('../lib/custom-api-contract.js');
+ const fixture = fs.readFileSync(path.join(__dirname, '..', 'fixtures', '27-page-error-helper', 'order-approvals.tsx'), 'utf8').replace(/\r\n/g, '\n');
+ const importLine = "import * as React from 'react';\n";
+ assert.ok(fixture.startsWith(importLine), 'the fixture imports React as a namespace');
+ const classStart = fixture.indexOf('class PageErrorBoundary extends');
+ const classEnd = fixture.indexOf('\n}\n', fixture.indexOf(' public render(): React.ReactNode {', classStart)) + 2;
+ const canonicalClass = fixture.slice(classStart, classEnd);
+ const namedClass = canonicalClass.replace(/\bReact\.Component\b/g, 'Component').replace(/\bReact\.ReactNode\b/g, 'ReactNode');
+ const destructuredBase = `const { Component } = {
+ Component: class extends React.Component<any> {
+ constructor(props: any) {
+ super(props);
+ this.render = () => React.cloneElement(this.props.children, {
+ dataApi: { executeAction: async () => ({ ok: true, outputs: { NewStatus: 'counterfeit' } }) },
+ });
+ }
+ },
+};
+`;
+ const beforeClass = (text) => fixture.slice(0, classStart) + text + fixture.slice(classStart);
+ const cases = [
+ ['the named Component form over a destructured, page-supplied base', fixture.slice(0, classStart) + destructuredBase + namedClass + fixture.slice(classEnd)],
+ ['the named Component form, even imported from react', fixture.replace(importLine, "import * as React from 'react';\nimport { Component, ReactNode } from 'react';\n").replace(canonicalClass, namedClass)],
+ ['React aliased', beforeClass('const R = React;\n')],
+ ['React destructured from', beforeClass('const { Component: Base } = React;\n')],
+ ['React shadowed by a parameter', beforeClass('const pick = (React: unknown) => React;\n')],
+ ['React.Component replaced', beforeClass('(React as any).Component = class {};\n')],
+ ['React.Component written through', beforeClass('React.Component = React.PureComponent;\n')],
+ ['React handed to Object.assign', beforeClass('Object.assign(React, {});\n')],
+ ['the base prototype patched', beforeClass("Object.defineProperty(React.Component.prototype, 'props', { set() {} });\n")],
+ ['a second import from react', fixture.replace(importLine, `${importLine}import * as ReactAgain from 'react';\n`)],
+ ['React from another module', fixture.replace(importLine, "import * as React from 'preact/compat';\n")],
+ ['the react module reached with require', beforeClass("Object.assign(require('react').Component.prototype, {});\n")],
+ ['no import of React at all', fixture.replace(importLine, '')],
+ ];
+ const approve = (source) => actionCalls(source).filter((call) => call.fields.get('name') === "'cnt_ApproveOrder'");
+ const bindings = [{ name: 'cnt_ApproveOrder', isFunction: false, displayName: 'Approve Order', boundEntityLogicalName: 'salesorder', parameterKinds: { Comment: 'String' } }];
+ for (const [label, source] of [['the fixture', fixture], ['a default import with named hooks', fixture.replace(importLine, "import React, { useEffect, useState } from 'react';\n")]]) {
+ assert.ok(forwardedPageBodyOf(source), `${label}: forwarded`);
+ assert.deepEqual(approve(source).map((call) => receiverIsDataApi(call.mask, call.scopes, call.receiver, call.start, call.code)), [true], label);
+ assert.deepEqual(runtimeProblems(source, bindings, { cnt_ApproveOrder: ['NewStatus'] }, new Map()), [], label);
+ }
+ for (const [label, source] of cases) {
+ assert.equal(forwardedPageBodyOf(source), null, `${label}: no forwarding proof`);
+ const calls = approve(source);
+ assert.ok(calls.length >= 1, `${label}: the Action call is still read`);
+ assert.ok(calls.every((call) => !receiverIsDataApi(call.mask, call.scopes, call.receiver, call.start, call.code)), `${label}: its receiver is not proven`);
+ assert.ok(runtimeProblems(source, bindings, { cnt_ApproveOrder: ['NewStatus'] }, new Map()).some((problem) => /not the page's dataApi prop/.test(problem)), `${label}: the Custom API check refuses it`);
+ }
+ // Without the source text the proof cannot read the import's module name, so it fails closed.
+ const [call] = approve(fixture);
+ assert.equal(receiverIsDataApi(call.mask, call.scopes, call.receiver, call.start), false, 'no code, no forwarding proof');
+});
diff --git a/evals/model-apps/tests/eval-coverage-baseline.json b/evals/model-apps/tests/eval-coverage-baseline.json
index 7644b9403..126a17e5d 100644
--- a/evals/model-apps/tests/eval-coverage-baseline.json
+++ b/evals/model-apps/tests/eval-coverage-baseline.json
@@ -30,15 +30,15 @@
"status": "deferred",
"text": "Phase 5 (Page Builder): Generated .tsx fetches usersettings via dataApi.retrieveRow and uses formatDate/formatNumber/formatCurrency helpers",
"reason": "Gradeable from the page source, but the only eval-13 fixture, 13-contact-localization, shows real drift: it never reads usersettings and formats nothing through formatDate/formatNumber/formatCurrency (references/localization.md makes the usersettings read mandatory). A correct check fails it, and the runners have no expected-failure mark."
- },
- {
- "eval": 15,
- "status": "deferred",
- "text": "Phase 2b (Entity Builder): cr_ticket is provisioned with choice columns via provision-entities.js input JSON; picklist options include {value,label} pairs",
- "reason": "The expectation names an input shape provision-entities.js refuses: its input validation reads each Choice option as a label (a string, or a map of LCID to label) and rejects a {label, value} object ('label' is not an LCID); values are assigned 100000000 + index. It needs rewording to the label form together with agents/genpage-entity-builder.md Step 4, which documents the same refused shape, and the only eval-15 fixture, 15-support-tickets-real, did not capture its input JSON."
}
],
"neverGraded": [
+ {
+ "runner": "layer-1",
+ "eval": 15,
+ "text": "Phase 2b (Entity Builder): cr_ticket is provisioned with choice columns via provision-entities.js input JSON; each picklist option is written as its label, in the plan's order (numbered 100000000 + index)",
+ "reason": "Graded from the input JSON each applying run of provision-entities.js (--apply; a run without it only plans and provisions nothing) was handed, provision-input.json, which the plugin's own input gate checks, but the only eval-15 fixture, 15-support-tickets-real, is a capture that did not keep that file, so the check skips it. A capture or a synthetic eval-15 fixture that keeps provision-input.json closes it."
+ },
{
"runner": "layer-2",
"eval": null,
diff --git a/evals/pcf/EVAL_GUIDE.md b/evals/pcf/EVAL_GUIDE.md
index 27520d5a3..9b036d7ec 100644
--- a/evals/pcf/EVAL_GUIDE.md
+++ b/evals/pcf/EVAL_GUIDE.md
@@ -91,7 +91,7 @@ node evals\pcf\run-pcf.js --tier full # all cases
node --test evals\pcf\tests\*.test.js
```
-Exit codes match app-builder: `0` all pass, `1` assertion failure, `2` harness or argument error.
+Exit codes match app-builder: `0` no case failed, `1` assertion failure, `2` harness or argument error. A case with nothing graded (below) does not fail the run.
## TAP output
@@ -109,3 +109,14 @@ ok 1 - 001-001-intent-field-clean
# skip 0
# fixtures 8 (pass 8, fail 0)
```
+
+The runner prints through the model-apps eval reporter: `lib/reporter.js` is a byte-for-byte copy of `evals/model-apps/genpage/lib/reporter.js`, and `tests/reporter.test.js` fails when the two differ, so change both together. A skip grades nothing, so a case passes only when at least one of its assertions was graded and none failed. A case with no graded assertion — every assertion skipped (for example `no check registered for this assertion text`), or an empty `assertions` list — is unscored, not passed:
+
+```text
+ok 1 - 001-001-intent-field-clean # SKIP no expectation graded
+...
+# fixtures 8 (pass 7, fail 0)
+# unscored fixtures 1
+```
+
+An unscored case is in neither count of `# fixtures <N> (pass X, fail Y)`; `# unscored fixtures <U>` follows that line only when U > 0, so X + Y + U = N and a run with none prints exactly what it printed before. An unscored case does not change the exit code.
diff --git a/evals/pcf/lib/reporter.js b/evals/pcf/lib/reporter.js
index 38c11173c..9a2fea076 100644
--- a/evals/pcf/lib/reporter.js
+++ b/evals/pcf/lib/reporter.js
@@ -18,10 +18,19 @@
// ...
// 1..N
//
+// A skip grades nothing, so a fixture passes only when at least one assertion was graded and none failed. A fixture with no graded
+// assertion — every one skipped, or none at all — is UNSCORED: its line takes TAP's skip directive,
+// ok 3 - fixture-3-kept-page # SKIP no expectation graded
+// and it is counted apart from the passed fixtures, so the summary never credits ungraded work as a pass. An unscored fixture does not fail
+// the run (the exit code is non-zero only for a failed fixture).
+//
// Failure diagnostics currently include only `reason:`. Additional fields
// (e.g., `file:`) can be added by extending `assertion()` if needed.
//
-// Aggregate result emitted at the end as `# tests N`, `# pass X`, etc.
+// Aggregate result emitted at the end as `# tests N`, `# pass X`, etc. Release and test tooling parse the
+// `# fixtures N (pass P, fail F)` line, so it keeps that exact form and stays the only line that starts with
+// `# fixtures`; unscored fixtures get one line of their own, `# unscored fixtures U`, written only when U > 0 — a
+// run without one prints exactly what it always printed.
class TapReporter {
constructor(stream = process.stdout) {
@@ -32,6 +41,7 @@ class TapReporter {
this.totalSkip = 0;
this.fixturePass = 0;
this.fixtureFail = 0;
+ this.fixtureUnscored = 0;
this.fixtureIndex = 0;
this.totalFixtures = 0;
}
@@ -77,9 +87,12 @@ class TapReporter {
if (this._currentFail) {
this.fixtureFail += 1;
this.write(`not ok ${this.fixtureIndex} - ${this._currentName}`);
- } else {
+ } else if (this._currentAssertions.some(({ result }) => result.status === 'pass')) {
this.fixturePass += 1;
this.write(`ok ${this.fixtureIndex} - ${this._currentName}`);
+ } else {
+ this.fixtureUnscored += 1;
+ this.write(`ok ${this.fixtureIndex} - ${this._currentName} # SKIP no expectation graded`);
}
this._currentName = null;
this._currentAssertions = [];
@@ -92,6 +105,7 @@ class TapReporter {
this.write(`# fail ${this.totalFail}`);
this.write(`# skip ${this.totalSkip}`);
this.write(`# fixtures ${this.totalFixtures} (pass ${this.fixturePass}, fail ${this.fixtureFail})`);
+ if (this.fixtureUnscored > 0) this.write(`# unscored fixtures ${this.fixtureUnscored}`);
}
get exitCode() {
diff --git a/evals/pcf/tests/reporter.test.js b/evals/pcf/tests/reporter.test.js
new file mode 100644
index 000000000..6b0f018e2
--- /dev/null
+++ b/evals/pcf/tests/reporter.test.js
@@ -0,0 +1,130 @@
+'use strict';
+// The TAP reporter of the pcf eval runner (lib/reporter.js, used by run-pcf.js). An assertion is pass, fail or skip, and a skip grades nothing.
+// So a case passes only when at least one of its assertions was graded and none failed; a case whose every assertion skipped — or that has
+// none — is unscored: its line carries TAP's `# SKIP` directive, it is counted on a line of its own, and it is never counted as passed. The
+// `# fixtures N (pass P, fail F)` summary keeps its exact form, and a run with no unscored case prints exactly what it always printed.
+//
+// The reporter is the model-apps eval runners' reporter (evals/model-apps/genpage/lib/reporter.js), copied byte for byte: the last test here
+// fails when the two drift apart, and the model-apps reporter tests check the same from their side.
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+const { TapReporter } = require('../lib/reporter.js');
+
+const EVALS_ROOT = path.join(__dirname, '..');
+const REPO_ROOT = path.join(EVALS_ROOT, '..', '..');
+const RUNNER = path.join(EVALS_ROOT, 'run-pcf.js');
+
+const PASS = { status: 'pass', reason: '' };
+const SKIP = { status: 'skip', reason: 'not applicable' };
+const FAIL = { status: 'fail', reason: 'broken' };
+
+// Reports `fixtures` — [name, results] pairs — through one reporter, as the runner does; returns its whole output and the reporter.
+function report(fixtures) {
+ let text = '';
+ const reporter = new TapReporter({ write: (chunk) => { text += chunk; } });
+ reporter.start(fixtures.length);
+ for (const [name, results] of fixtures) {
+ reporter.startFixture(name);
+ results.forEach((result, index) => reporter.assertion(`assertion ${index + 1}`, result));
+ reporter.endFixture();
+ }
+ reporter.end();
+ return { text, lines: text.split('\n'), reporter };
+}
+const summary = (lines) => lines.filter((line) => /^# (?:tests|pass|fail|skip|fixtures|unscored)/.test(line));
+
+test('a case whose every assertion skipped is unscored: a # SKIP case line, its own count, never the passed count, and no failure', () => {
+ const { lines, reporter } = report([['all-skipped', [SKIP, SKIP, SKIP]]]);
+ assert.ok(lines.includes('ok 1 - all-skipped # SKIP no expectation graded'), lines.join('\n'));
+ assert.deepStrictEqual(summary(lines), ['# tests 3', '# pass 0', '# fail 0', '# skip 3', '# fixtures 1 (pass 0, fail 0)', '# unscored fixtures 1']);
+ assert.deepStrictEqual([reporter.fixturePass, reporter.fixtureFail, reporter.fixtureUnscored], [0, 0, 1]);
+ assert.equal(reporter.exitCode, 0);
+});
+
+test('a case with no assertion at all is unscored the same way', () => {
+ const { lines, reporter } = report([['empty', []], ['graded', [PASS]]]);
+ assert.ok(lines.includes(' 1..0'), lines.join('\n'));
+ assert.ok(lines.includes('ok 1 - empty # SKIP no expectation graded'), lines.join('\n'));
+ assert.ok(lines.includes('ok 2 - graded'), lines.join('\n'));
+ assert.deepStrictEqual(summary(lines), ['# tests 1', '# pass 1', '# fail 0', '# skip 0', '# fixtures 2 (pass 1, fail 0)', '# unscored fixtures 1']);
+ assert.deepStrictEqual([reporter.fixturePass, reporter.fixtureFail, reporter.fixtureUnscored], [1, 0, 1]);
+ assert.equal(reporter.exitCode, 0);
+});
+
+test('a case with one graded assertion and skips beside it still passes; one failed assertion fails a case, skips or not', () => {
+ const { lines, reporter } = report([['mixed', [SKIP, PASS, SKIP]], ['failed', [SKIP, FAIL]], ['unscored', [SKIP]]]);
+ assert.ok(lines.includes('ok 1 - mixed'), lines.join('\n'));
+ assert.ok(lines.includes('not ok 2 - failed'), lines.join('\n'));
+ assert.ok(lines.includes('ok 3 - unscored # SKIP no expectation graded'), lines.join('\n'));
+ assert.deepStrictEqual(summary(lines), ['# tests 6', '# pass 1', '# fail 1', '# skip 4', '# fixtures 3 (pass 1, fail 1)', '# unscored fixtures 1']);
+ assert.deepStrictEqual([reporter.fixturePass, reporter.fixtureFail, reporter.fixtureUnscored], [1, 1, 1]);
+ // Only a failed case makes the run fail; an unscored one does not.
+ assert.equal(reporter.exitCode, 1);
+});
+
+test('a run with no unscored case prints exactly what it always printed, and `# fixtures` stays its one summary line', () => {
+ const { text, reporter } = report([['graded', [PASS, SKIP]], ['broken', [SKIP, FAIL]]]);
+ assert.equal(text, [
+ 'TAP version 13',
+ '1..2',
+ '# Subtest: graded',
+ ' ok 1 - assertion 1',
+ ' ok 2 - assertion 2 # SKIP not applicable',
+ ' 1..2',
+ 'ok 1 - graded',
+ '# Subtest: broken',
+ ' ok 1 - assertion 1 # SKIP not applicable',
+ ' not ok 2 - assertion 2',
+ ' ---',
+ ' reason: "broken"',
+ ' ...',
+ ' 1..2',
+ 'not ok 2 - broken',
+ '# tests 4',
+ '# pass 1',
+ '# fail 1',
+ '# skip 2',
+ '# fixtures 2 (pass 1, fail 1)',
+ '',
+ ].join('\n'));
+ assert.equal(reporter.fixtureUnscored, 0);
+ assert.equal(reporter.exitCode, 1);
+ const unscored = report([['all-skipped', [SKIP]]]).lines;
+ assert.deepStrictEqual(unscored.filter((line) => line.startsWith('# fixtures')), ['# fixtures 1 (pass 0, fail 0)']);
+});
+
+// Through the runner: a case whose assertions name no registered check (each one skips, `no check registered for this assertion text`) and a case
+// with an empty `assertions` list are unscored beside the cases that are graded, and the run still exits 0.
+test('run-pcf.js reports a smoke case with no registered check, and one with no assertion, as unscored beside the graded ones, and exits 0', () => {
+ const data = JSON.parse(fs.readFileSync(path.join(EVALS_ROOT, 'evals.json'), 'utf8'));
+ const smoke = data.evals.filter((ev) => ev.tier === 'smoke');
+ assert.equal(smoke.length, 8, 'the smoke subset the runner test pins');
+ const [unchecked, empty] = smoke;
+ unchecked.assertions = ['no check is registered for this assertion text'];
+ empty.assertions = [];
+ const nameOf = (ev) => `${String(ev.id).padStart(3, '0')}-${ev.fixture || ev.family}`;
+ const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'pcf-eval-unscored-'));
+ try {
+ const copy = path.join(tmpRoot, 'evals.json');
+ fs.writeFileSync(copy, JSON.stringify(data, null, 2));
+ const run = spawnSync(process.execPath, [RUNNER, '--tier', 'smoke', '--evals', copy], { cwd: REPO_ROOT, encoding: 'utf8' });
+ assert.equal(run.status, 0, `an unscored case does not fail the run\nstderr:\n${run.stderr}\nstdout:\n${run.stdout}`);
+ const lines = run.stdout.split(/\r?\n/);
+ assert.ok(lines.includes(`ok 1 - ${nameOf(unchecked)} # SKIP no expectation graded`), run.stdout);
+ assert.ok(lines.includes(`ok 2 - ${nameOf(empty)} # SKIP no expectation graded`), run.stdout);
+ assert.ok(lines.includes(`ok 3 - ${nameOf(smoke[2])}`), run.stdout);
+ assert.deepStrictEqual(lines.filter((line) => /^# (?:fixtures|unscored)/.test(line)), ['# fixtures 8 (pass 6, fail 0)', '# unscored fixtures 2']);
+ } finally {
+ fs.rmSync(tmpRoot, { recursive: true, force: true });
+ }
+});
+
+test('the pcf reporter is the model-apps eval reporter, byte for byte, so the pcf runner grades and counts as those runners do', () => {
+ const copy = fs.readFileSync(path.join(EVALS_ROOT, 'lib', 'reporter.js'));
+ const source = fs.readFileSync(path.join(REPO_ROOT, 'evals', 'model-apps', 'genpage', 'lib', 'reporter.js'));
+ assert.ok(copy.equals(source), 'evals/pcf/lib/reporter.js differs from evals/model-apps/genpage/lib/reporter.js: change both in the same PR (copy the file over)');
+});
diff --git a/plugins/model-apps/.claude-plugin/plugin.json b/plugins/model-apps/.claude-plugin/plugin.json
index 4a4bb71ca..a4e8ff780 100644
--- a/plugins/model-apps/.claude-plugin/plugin.json
+++ b/plugins/model-apps/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "model-apps",
- "version": "2.19.0",
+ "version": "2.20.0",
"description": "Build model-driven Power Apps end to end: /app-builder authors whole apps (tables, relationships, forms, views, charts, security roles, app + sitemap) from a natural-language intent, and /genpage builds generative pages with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI > 2.10.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.",
"author": {
"name": "Microsoft",
diff --git a/plugins/model-apps/.plugin/plugin.json b/plugins/model-apps/.plugin/plugin.json
index 4a4bb71ca..a4e8ff780 100644
--- a/plugins/model-apps/.plugin/plugin.json
+++ b/plugins/model-apps/.plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "model-apps",
- "version": "2.19.0",
+ "version": "2.20.0",
"description": "Build model-driven Power Apps end to end: /app-builder authors whole apps (tables, relationships, forms, views, charts, security roles, app + sitemap) from a natural-language intent, and /genpage builds generative pages with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI > 2.10.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.",
"author": {
"name": "Microsoft",
diff --git a/plugins/model-apps/AGENTS.md b/plugins/model-apps/AGENTS.md
index 300193ae6..6a087d660 100644
--- a/plugins/model-apps/AGENTS.md
+++ b/plugins/model-apps/AGENTS.md
@@ -54,7 +54,7 @@ able to tell what moved from the docs alone):
| [`docs/architecture.md`](docs/architecture.md) | Wiring / flow **diagrams** for both skills (`/genpage` + `/app-builder`) | You change the orchestration, phase pipeline, or how the pieces connect |
| [`docs/app-builder-capabilities.md`](docs/app-builder-capabilities.md) | `/app-builder` **capabilities** — what ships today, with the evidence for each | You ship an app-builder capability |
| [`docs/app-builder-design.md`](docs/app-builder-design.md) | `/app-builder` **design record** — Part I staged-flow architecture (**cited from code by section number — never renumber**), Part II the `--changed-only` contract | You change the staged flow or the partial-apply contract |
-| [`CHANGELOG.md`](CHANGELOG.md) | Keep-a-Changelog — concise bullets (detail lives in PRs/docs) | Any user-visible change |
+| [`CHANGELOG.md`](CHANGELOG.md) | Keep-a-Changelog — at most 300 words per release entry and 45 per bullet, enforced by `scripts/tests/changelog-brevity.test.js`; the reasoning and evidence belong in the PR and `docs/` | Any user-visible change |
| [`references/app-spec-schema.md`](references/app-spec-schema.md) | The App Spec contract (always-present fields) | You change the App Spec shape or validation |
| [`references/app-spec-schema-advanced.md`](references/app-spec-schema-advanced.md) | The conditional App Spec fields (business rules, BPFs, commands, web resources, global choices, dashboards, roleGrants) — split out so the always-read contract stays small | You change one of those features |
@@ -830,7 +830,19 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
failed, the solution is a built-in one) is added exactly as before. A component this run creates is
added directly, except the page manifest: it is persisted through the same check after every page
create and once more at the end, so a first build that deploys pages makes the read too — and still
- adds the manifest, which the solution does not hold yet. What an unchanged rebuild still sends: the
+ adds the manifest, which the solution does not hold yet. **The generative pages join the solution
+ too** (AB#6443257): the add of the app brings its sitemap, never the pages its navigation opens, so a
+ build "in" a solution used to leave its pages out of it. The pages phase reads the page table's
+ component type (`lib/page-solution.js`; allocated per environment) once, before the first page is
+ written — a read that fails halts the phase (`pages-solution-type-unreadable`) with nothing in it
+ written — adds each page it creates with its file rows (AddRequiredComponents), and re-asserts each
+ page it updates through its own membership read of that type, so a page an earlier build made outside
+ the solution joins it and one the solution holds costs no write. Once the pages are written it
+ re-asserts every other page the manifest binds the same way: a changed-only run leaves the pages it did
+ not select as they are, and a navigation target that an earlier attempt of the run made and could not
+ add is one of them — bound now, and not written again — so this is what adds it (one read for all
+ pages; no write for a page the solution holds). A system solution is not added to,
+ and an SDK double with no raw client adds no page. What an unchanged rebuild still sends: the
phase-8 envelope; the SDK's own default-view enrichment (it pushes both generated views of each table
it enriches); the default-form promotion of a table the build owns (`isdefault`); the existing app's
sitemap push with its component pins and publish; the AI-feature setting writes; and each persona
@@ -1107,7 +1119,13 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
English-only behaviour while validation and the design doc still claimed two languages. Everything
that RENDERS or DERIVES FROM a label must go through `labelText()` (never string-interpolate a
label), and anything that resolves an author's reference BY label text must go through
- `labelAliases()` so a reference written in any provisioned language matches. Both live in
+ `labelAliases()` so a reference written in any provisioned language matches. One text naming two
+ options of a column (`ambiguousChoiceAliases()`) is an error when the author cannot see it on the line
+ (one side is a label of several languages that the other does not match in every language, or the two
+ are in different languages) and a warning when they can — two equal plain strings, or two IDENTICAL
+ localized labels (the same text in each of the same languages), the shape a download finds for two
+ options a maker labelled alike: Dataverse fills the base language in with the same text when a label is
+ created in another language only (measured), so they hold two languages each. All three live in
`app-spec.js`; `references/localization.md` is about generated **page** code, a separate concern.
Guarded by `scripts/tests/lcid-real-bundle.test.js`, which drives the REAL vendored bundle — a mock
would keep passing against a bundle that ignored the option.
@@ -1421,7 +1439,15 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
app handler does for its delete, so a page the platform still holds fails the step and keeps its receipt and pending record, and a read that
cannot be made counts as "not proven gone". The SDK's delete sends no `MSCRM.IncludeUnpublished`, and its own notes say a by-id request on a page that was
never published answers 404 without it; measured live, the platform DELETED such a row, so the read-back is insurance against an answer it has not been seen to give.
- Form-only page references are not scanned.
+ **Known limit — a page a form embeds is deleted.** A form can show a generative page through the `MscrmControls.UxAgentControl`
+ control, whose static `RefId` parameter holds the page id, and Dataverse records no dependency for it (measured: the page reported
+ zero dependents and its delete answered 204), so the platform never refuses the delete — and teardown reads no form. A proven page is
+ deleted even while a form (of the app's tables or of any other) still shows it, and that form is left pointing at a page that is gone.
+ So before a teardown with `--apply`, take the page off every form that shows it, or delete those forms; the dry run lists each page it
+ would delete. Teardown does not look for such forms itself, on purpose: a forms read alone cannot prove that no form names a page — that
+ takes every form's FormXML read as one complete document, and a table's absence proven from metadata that can be trusted — and a check
+ that let the delete through on a reply it could not read would promise more than it keeps. Pinned by `teardown-form-embedded-page.test.js`
+ (the delete set of such an app, and no form read).
**An app is TWO rows** — an `appmodule` AND a `sitemaps`
row, with no server-side cascade. The sitemap is linked by a type-62 `appmodulecomponent` on the app's **current**
`appmoduleidunique` layer, not necessarily by equal unique names (first-party and renamed sitemaps may have different names).
@@ -1561,7 +1587,7 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
`readNavigationLanguage`, before the SDK is made). The SDK projects a sitemap in the ONE language
it is constructed with and reads a node's title as empty when it has none in that language, so an SDK
built with no language (1033) wrote `"label": ""` for every area, group and entry of a Spanish-only
- environment. A label is a plain string, as a single-language table label is, and the language is never
+ environment. A navigation label is a plain string, and the language is never
written into the spec: the flag decides what is read, not what is pinned, and a flag that names another
language than the spec on disk pins is refused (`navigation-language-conflict`). When none of the three
gives a language — the base language could not be read — the download stops before it writes anything
@@ -1575,11 +1601,41 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
which that rebuild writes over the right ones. `--verify` makes the same choice. A title a node holds only in
another language is not in the spec, and a rebuild into the same environment leaves it as it is (the rule
for a title the spec does not state, under the sitemap above).
+ **A table, column, option, lookup or alternate-key label held in ONE language keeps that language when it is
+ not the authoring language** (`labelFromDataverse`): it is written as a one-entry LCID map, `{ "3082": "Pedido" }`,
+ so a rebuild stores it in that language — a plain string was stored in the language the rebuild resolves, which
+ put Spanish text in the English label, in a fresh environment that had Spanish as much as in one that had not — and
+ a rebuild into an environment without the language stops at the start of its data model and names it. Measured:
+ Dataverse fills the base language in, with the same text, when a label is created or updated in another language
+ only, so the one language a label holds alone is the environment's base language — and the label keeps it when
+ the download's authoring language is another: a Spanish-only label of a Spanish-base environment downloaded with
+ `--language-code 1033` is `{ "3082": "Pedido" }`, an English-only one of an English-base environment downloaded with
+ `--language-code 3082` is `{ "1033": "Note" }`. A label in
+ the authoring language stays a plain string, so an ordinary download is byte-identical
+ (`download-label-language-real-bundle.test.js`). A lookup's label is left out only where its text is the label a
+ rebuild gives a lookup that sets none, as before, **and** that label is the same in every language — the parent's
+ downloaded label, or a stock parent's label in the authoring language (the one the build reads): an English
+ "Contact" on a lookup to a table labelled only in French "Contact" is carried, in English, where leaving it out
+ rebuilt it in French (`download-lookup-label-language-real-bundle.test.js`). Two inline options a maker labelled
+ alike keep their labels and the column its type when the two labels are identical in every language they hold —
+ as Dataverse holds them (with the base language filled in), and as two equal one-entry maps of one language are —
+ a duplicate the validator warns about, as it does two equal plain strings (`ambiguousChoiceAliases`); options sharing their text in two languages (an
+ English "Open" and a Spanish "Open") can be held only as plain strings, so those options alone are written so and a
+ WARNING names each label that loses its language, every other option keeping its own; any other collision involving
+ a label of several languages still leaves the column untyped, and the untyped-column WARNING names the clash
+ (`'Abierto' names options[0] and options[1]` — the option set WAS read) where it blamed an unreadable option set
+ (`download-option-label-language-real-bundle.test.js`).
+ Global-choice labels stay plain strings (the spec refuses a localized one).
The fetched SDK navigation must agree with the selected current XML's full target multiset:
entities, generative pages, URLs, dashboards and custom pages, including repeated shortcuts.
A missing SDK sitemap or a mismatch is refused with publish-then-download guidance, never emitted
as hidden-table membership or lost Main restrictions. The immutable name is recovered from the
fetched `uniqueName`/`uniquename` before manifest/prefix lookup; an unresolved identity is refused.
+ **An app with no tables downloads too**: one whose navigation holds only generative pages, dashboards or URLs
+ (`apps.js create --page-id` makes one) is written as a spec with `"entities": []`, which the build, `--verify` and
+ teardown take (`lifecycle-no-tables-real-bundle.test.js`). The validator used to refuse every spec with no table, so
+ such a download wrote the page folders and then stopped without a spec or a baseline; it now refuses only a spec with
+ no table and no navigation entry (`at least one entity is required`), before anything is written.
**Round-trip scope (be precise — do not claim "complete"):** tables, sitemap/appShell, generative pages
(with their data sources, model and connector and Custom API bindings),
classic dashboards, icons, and solution round-trip; **forms, views, charts, and commands do NOT yet
@@ -1647,12 +1703,19 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
a non-primary AutoNumber's custom length/format and DateTime behavior are not authorable here.
Dashboard tiles still bind source view/chart ids; moving them to another environment also needs
those artifacts mapped, and removing a pinned source `dashboardId` when creating a new dashboard.
- **Form/view/chart omissions are reported, not silent** (AB#6686423): every deployed form/view/chart is listed in the
+ **Form/view/chart/command omissions are reported, not silent** (AB#6686423): every deployed form/view/chart is listed in the
spec's `descriptionInventory`, and each run prints a note naming the counts, the tables and the
artifacts, plus a `notRoundTripped` block on the JSON result. It is a NOTE, never a gate — every app
has forms and views, so failing the download would break every download, and the omission is not
destructive in the environment the app came from. Do not "fix" this by reconstructing `forms[]`
without also solving the lossy-layout problem above.
+ The **command-bar customisations of the app's tables** are listed the same way (`commands`, by table and button
+ label; `readCommandInventory`): the unmanaged modern commands (`appaction` rows, read by the table's logical name,
+ 20 tables to a request) that are table-scoped or scoped to this app — not another app's, not a Group container, not
+ an inactive row. They used to be named nowhere, so a rebuild in another environment dropped them without a word. A
+ failed read is reported as `commands` under the classes that could not be inventoried, never as "no commands". A
+ command bound to no table (global scope, or an app-scoped command of a bar no table has) is not read: the App Spec's
+ `commands[]` has no form for one either.
**A page's connector and Custom API bindings are in the spec** (`pages[].connectorBindings`,
`pages[].actionBindings`; the format and the rebuild rules are in `references/app-spec-schema.md` →
`pages[]`). The page folder always held the raw lists in its `config.json`, but the spec carried only
@@ -1758,8 +1821,8 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
`note` — in the order the spec lists its pages, names sorted by `compareText`; the block is absent when no page
holds one and nothing was left out. The connection reference and the connection behind it (a user's sign-in, which
stays where it was made), the Custom API (a solution component) and the resources a connector binding points at
- are not App Spec items; the `NOTE:` names the scripts that make each one there. The `custom-api` feature flag
- gates what the `/genpage` agents author, not this: a download and a rebuild carry the bindings a page already
+ are not App Spec items; the `NOTE:` names the scripts that make each one there. The `dataverse-operations` feature
+ flag gates what the `/genpage` agents author, not this: a download and a rebuild carry the bindings a page already
holds. `page-binding-contract.test.js` pins the allowlist, the projection and the merge,
`page-binding-targets.test.js` the reads and the judgement of the environment, `page-bindings.test.js` the
download, the validator, the build's write sites and its check of the environment, and
@@ -1907,10 +1970,10 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
dropped and counted in `droppedSubareas`.
- **`scripts/verify-model-app.js` → `scripts/lib/verify-spec.js`** — read-only reconcile of the App Spec
against what actually deployed; exits non-zero and lists anything missing, catching silent partial
- builds. It validates the spec first under the `deploy` profile, with three compatibility downgrades
- (`relationshipCollisions: 'warn'`, `columnValues: 'warn'` and `fieldOptionKeys: 'warn'`): a spec an earlier release accepted and built — a 1:N and an N:N
+ builds. It validates the spec first under the `deploy` profile, with four compatibility downgrades
+ (`relationshipCollisions: 'warn'`, `columnValues: 'warn'`, `fieldOptionKeys: 'warn'` and `primaryAttributeKeys: 'warn'`): a spec an earlier release accepted and built — a 1:N and an N:N
that share a schema name, an AutoNumber column with no format, a `required` that is not `true`, `false` or `"recommended"`, a key a form's
- `fieldOptions` entry does not take — is verified, with a warning that names the fix, and is never refused before anything is read (the
+ `fieldOptions` entry does not take, a key a table's `primaryAttribute` does not take — is verified, with a warning that names the fix, and is never refused before anything is read (the
build, the lint and the provisioning gate keep these as errors). **Every `WARNING:` line it prints on stderr — those findings, the spec's other warnings, and a page
workspace it could not remove — is also in the result JSON's optional `warnings` array** (the same messages, without the prefix, in the order
printed; left out when there is none, as `unverified` is), so a caller that reads only the JSON loses none of them. It is there on a failed
@@ -1927,7 +1990,12 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
id) AND, best-effort, **content** so an *unapplied edit* is caught (not just a missing artifact): a
view's **column set** (parsed from `layoutxml`; every spec column must be deployed — an extra deployed
column passes by design, so a column REMOVED from the spec, which the additive `reconcileView` leaves
- in place, is not flagged), plus **relationship** and **command-bar existence** (previously unchecked).
+ in place, is not flagged), plus **relationship** and **command-bar existence** (previously unchecked), and
+ each declared **web resource**: it exists and — unless it is `external`, a shared one the build reuses as it finds it —
+ its deployed (published) content is the spec's, byte for byte (`webResourceContentState` in `lib/sdk-build.js`, the comparison
+ the build's reuse line makes): a rebuild never writes the content of a web resource that exists, so an edit that was not
+ recreated fails this check (`web-resource`), a spec content this machine cannot read (a missing `contentPath`, read relative to
+ the spec's folder) is `unverified`, and a run whose build skipped the web-resources phase reports it as phase-skipped.
A relationship is verified by its **identity**, not its name: the answer has to state its schema name, its
type, both its tables and, for a 1:N, its lookup column — for an N:N, its intersect table and the column each
table has in it — and all of them have to match (`compareRelationship`, `lib/relationship-metadata.js`; an N:N's
@@ -2474,8 +2542,13 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
characters long), since the re-run that follows treats the table as an existing one — except for an auto-numbered
name column, which keeps its length, and for 850, which the column comes out as either way. The
build reads only `schemaName`, `displayName`, `autoNumberFormat`, `required` and `maxLength` from
- `primaryAttribute`; any other key inside it is still accepted and ignored (unlike the table level, it has
- no key allow-list).
+ `primaryAttribute`, and those are the only keys it takes (`PRIMARY_ATTRIBUTE_KEYS`, `primaryAttributeKeyProblems` in
+ `lib/app-spec.js`): any other key (`maxlength`, `autonumberFormat`, `requiredLevel`, `type`) used to be accepted and ignored,
+ so the table was made without what it asked, and is now refused, as an unknown table key is — naming the key, the key it most
+ likely meant and the allowed keys — by the build, the plan, the lint and the provision-entities gate (`lib/provision-input.js`,
+ the one rule). Like an unknown `fieldOptions` key, it is a warning in the same words for the structural profile (teardown,
+ preview) and for read-only verification (`primaryAttributeKeys: 'warn'`), which must still read a spec an earlier release
+ built. Pinned by `primary-attribute-keys.test.js`.
- **Primary name column requirement level.** A `required` on `primaryAttribute` (`true` → `ApplicationRequired`, `"recommended"`
→ `Recommended`, `false` → `None`; an omitted one asks nothing) is sent in the table's create as the SDK's
`createTable({ primaryColumnRequired })`. MEASURED on Dataverse 9.2.26101: an auto-numbered name column keeps the level the
@@ -2634,7 +2707,7 @@ The canonical layout of the plugin (architecture **diagrams** live in
AGENTS.md ← Plugin guidance for AI agents (this file)
README.md ← User-facing intro and prereqs
CHANGELOG.md ← Keep-a-Changelog
-feature-flags.json ← Feature flags (custom-api, custom-telemetry)
+feature-flags.json ← Feature flags (custom-telemetry, dataverse-operations)
.claude-plugin/plugin.json ← Legacy plugin metadata mirror
docs/
architecture.md ← Wiring/flow diagrams for BOTH skills (/genpage + /app-builder)
@@ -2646,10 +2719,11 @@ agents/ ← Agent definitions (invoked by skills via Task
genpage-entity-builder.md ← DV entity creation via plugin's Web API scripts (create flow)
genpage-page-builder.md ← Writes one .tsx file; runs in parallel for multi-page (create flow)
genpage-edit-planner.md ← Reads download artifacts, plans edits, writes edit plan (edit flow)
- genpage-customapi-builder.md ← Single owner of the custom-api gate; discovers bound Custom APIs, writes ## Custom API Bindings + actions.json (create & edit flows)
+ genpage-customapi-builder.md ← Single owner of Custom API discovery and the dataverse-operations gate; discovers bound Custom APIs, offers the two built-in operations, writes ## Custom API Bindings (+ dataverse-operations.md) + actions.json (create & edit flows)
references/ ← Shared reference docs
rules.md ← Full code-gen rules, DataAPI types, layout patterns, common errors
custom-api.md ← Dataverse Custom API (Action/Function) invocation contract (loaded when the plan has ## Custom API Bindings)
+ dataverse-operations.md ← Built-in Dataverse operations (WhoAmI, RetrieveVersion): catalogue, consent, wire rows, plan section, button-only call pattern (dataverse-operations gated; loaded when the plan has ## Dataverse Operations)
page-telemetry.md ← props.appInsights page telemetry contract (custom-telemetry gated; loaded only when the maker asked to measure something)
connectors.md ← GenPage connector binding contract and runtime patterns
plan-schema.md ← Schema contract for genpage-plan.md
@@ -2675,11 +2749,13 @@ scripts/
list-connections.js ← Connector discovery: the maker's connections + Dataverse connection references. The connections come from the SDK first (`listConnections`, with the Power Apps service token); `pac connection list --environment <origin>` runs only where the SDK refuses the route — and at once, with no SDK and no token read, for an environment outside the Public cloud, which the SDK has no route for (see "Connections, connector metadata and deployment settings") — and the output says which answered (`connectionsSource`, `connectionsFallback`)
connector.js ← /genpage connector builder: a connector's operations, one operation's parameters and response, a tabular connector's table columns — `operations` and `schema --operation` from the SDK first (an environment outside the Public cloud goes to `pac` at once), `schema --dataset --table` and every SDK refusal through `pac model genpage`; one pure-ASCII JSON line with `source`
create-connection-reference.js ← Creates Dataverse connectionreference rows for connector bindings
- list-custom-apis.js ← Discovers supported public Custom APIs (Global + entity-bound), primitive kinds + separate lookup inputs (custom-api gated)
+ list-custom-apis.js ← Discovers supported public Custom APIs (Global + entity-bound), primitive kinds + separate lookup inputs (no feature gate)
+ list-dataverse-operations.js ← Offers the reviewed built-in operation catalogue (WhoAmI, RetrieveVersion) as one JSON line; no arguments, no environment, no token, no request (dataverse-operations gated, exit 3 when OFF)
list-languages.js ← /genpage planner: the environment's base language and each provisioned language (LCID, culture code, right-to-left) — the SDK's `getEnvironmentLanguages()` over the az-token client, three reads and no write, printed as one pure-ASCII JSON line. The only source: no `pac model list-languages` stands behind it, because every /genpage page operation needs the Azure CLI
- apps.js ← the replacement for `pac model list` and `pac model create` that /genpage and /app-builder run (`pac-replaced-docs.test.js` pins that their text names this script, not the `pac` commands): the environment's model-driven apps and a new app that opens on generative pages, through the bundled SDK. `list` prints each app's id, name, unique name, description and two facts, apart: `published` (it has a row in the published layer: users can open it) and `unpublishedChanges` (it has a saved row that is not published) — drafts included; `pac`'s "(Saved - Not Published)" is neither of them (see the spec section) and never part of the name. `create --name --solution --page-id <guid> [--page-id …] [--unique-name] [--description] [--publish]` makes the app with one area "Main", one group "Pages" and a sub-area per page, titled with the page's stored name; the app and its sitemap join the solution (a system solution such as `Default` holds them already: `systemSolution: true`); it is published only with `--publish`. The default public view of each table the pages read (the tables come from each page's own configuration, the views from the page backend: the definition `placeInApp` pins with) joins the app's components in the create itself — `components.views` of the app the SDK creates, written by the same AddAppComponents that adds the sitemap — as `pac model genpage upload --app-id` pinned them; the output says what was pinned (`dataSources`, `pinnedViews`), a table with no default public view or a page held as raw files is named in `warnings`, and a page that cannot be read refuses the create before the first write. Every check — no page id, a page that does not exist, a solution that does not exist or is managed, a taken unique name, an unreadable base language — is a refusal printed as `{ ok: false, code, error, written: false }` before the first write; a failure after the push began reads the platform back and prints what is actually left of this create (its rows are recognised by their ids, and a row that holds the unique name under another id is named apart)
+ apps.js ← the replacement for `pac model list` and `pac model create` that /genpage and /app-builder run (`pac-replaced-docs.test.js` pins that their text names this script, not the `pac` commands): the environment's model-driven apps and a new app that opens on generative pages, through the bundled SDK. `list` prints each app's id, name, unique name, description and two facts, apart: `published` (it has a row in the published layer: users can open it) and `unpublishedChanges` (it has a saved row that is not published) — drafts included; `pac`'s "(Saved - Not Published)" is neither of them (see the spec section) and never part of the name. `create --name --solution --page-id <guid> [--page-id …] [--unique-name] [--description] [--publish]` makes the app with one area "Main", one group "Pages" and a sub-area per page, titled with the page's stored name; the app, its sitemap and its pages join the solution (`inSolution`: `app`, `sitemap`, `pages`; the add of an app brings its sitemap but never the pages its navigation opens, so each page is added on its own as the page table's component type, read from the environment before the first write — `lib/page-solution.js`, AB#6443257; a system solution such as `Default` holds them already: `systemSolution: true`, and nothing is read for it); it is published only with `--publish`. The default public view of each table the pages read (the tables come from each page's own configuration, the views from the page backend: the definition `placeInApp` pins with) joins the app's components in the create itself — `components.views` of the app the SDK creates, written by the same AddAppComponents that adds the sitemap — as `pac model genpage upload --app-id` pinned them; the output says what was pinned (`dataSources`, `pinnedViews`), a table with no default public view or a page held as raw files is named in `warnings`, and a page that cannot be read refuses the create before the first write. Every check — no page id, a page that does not exist, a solution that does not exist or is managed, a taken unique name, an unreadable base language — is a refusal printed as `{ ok: false, code, error, written: false }` before the first write; a failure after the push began reads the platform back and prints what is actually left of this create (its rows are recognised by their ids, and a row that holds the unique name under another id is named apart)
list-tables.js ← the replacement for `pac model list-tables` (the skills' and agents' text runs this script: `pac-replaced-docs.test.js`): the environment's tables — the SDK's `findTables(term)` for each comma-separated `--search` term, a few reads at a time, joined without repeats; `--exact` keeps the tables whose logical name IS a term and names the terms no table has (`missing`), from one read of every table; `--type custom|standard|all` is `pac`'s own filter, `custom` through the SDK's `customOnly` option. One pure-ASCII JSON line of `{ logicalName, displayName, schemaName, isCustom }` rows. An answer that is no list of tables — a 2xx with no `value` list: a sign-in page, `{}`, `null` — fails `TABLES_UNREADABLE` (exit 1) instead of reading as "no tables, every searched one missing" (`lib/collection-answers.js`)
- add-page-to-solution.js ← Adds GenPages and optional connection references to a solution
+ get-lookup-metadata.js ← /genpage planner: the lookups of the tables a page reads — each column's read property, its COMPLETE target set (the SDK's `fetchEntityMetadata`) and the concrete per-target paths a filter may go through (navigation property and target key, from `readRelationshipsOf`'s lookup-details mode), shared paths such as Owner's `ownerid` kept apart and never a target discriminator (`lib/lookup-metadata.js`). One pure-ASCII JSON line only after every read completed; a missing table, a lookup without targets or a failed or malformed relationship page is `{ ok: false, code, error }` and exit 1, never a shorter candidate list. The planner saves it as `lookup-metadata.json`
+ add-page-to-solution.js ← Adds GenPages and optional connection references to a solution (Phase 6.7 packaging); the app id is optional, so it also adds pages alone — the recovery `genpage-upload.js --solution` names when a page's own add failed (a page is a component of its own: the app is not one of its required components)
solution-settings.js ← Deployment settings: `template` writes the settings file of a solution or a package (pac's own format), `import` imports a package and applies the settings in the same import — the SDK first, `pac solution create-settings` / `import --settings-file` only where it refuses (pac is given a private copy of the settings the run read, owner-only on every platform and removed however the process ends, never the file's path); ExportSolution, StageSolution and ImportSolution are each sent exactly once — but for an ImportSolution the platform refused to start because another operation held its customization lock (HTTP 429 with one of the customization-lock error codes whose documented text is "Cannot start …", or with `0x80071151` and "Cannot start …" words), which is sent again under a new job id once the refused send's job proves that nothing of the package was applied — `importjobs(<id>)` does not exist (404) or, for `0x80071151`, read once at once, is a finished job whose log says the import failed with that error before it processed the solution or any component (`lib/import-job-proof.js`); a job that proves nothing ends the retry with a sentence that says why and what to do, and so does a fifth `0x80071151` refusal, whose job is not read (at most five sends and five minutes in all — asked again after every wait — a `Retry-After` waited whole or the retry ended; `importAttempts` / `importRefusals` in the output) — every text it prints has the settings file's values taken out, and everything it prints or writes the access tokens the run sent (an HTTP 200 can be a failed staging whose message quotes what it was given), and a failed import names its job and the job log's reason; one pure-ASCII JSON line with `source`
provision-entities.js ← CLI wrapper for entity provisioning (solution + data-model + sample-data; --language-code)
provision-solution.js ← Creates a Dataverse solution via the SDK
@@ -2696,10 +2772,10 @@ scripts/
run-tests.js ← one-command plugin + SDK regression runner
smoke-eval.js ← scripted live smoke eval (build → assert → teardown)
generate-page-manifest.js ← Phase 0.5: writes working-dir package.json + genpage.d.ts
- genpage-upload.js ← /genpage: deploy one page through the page backend (prompt passed BY FILE, never composed into a command; a create needs no app — `--app-id` is optional for a create only: a page needs no app, so a create without it is added to no app and makes no app-scoped check; `--add-to-sitemap` and an update still need `--app-id`, and an update must prove the page is in that app's navigation; an update keeps the page's name, model, data sources and bindings unless given; a named app also gets the default views of the tables the page reads pinned into its components; `--add-to-sitemap` titles the page's entry in the environment's base language, which it reads with the backend's `baseLanguage()` before the placement — as `genpage.js add-to-app` does, and so when a later run completes the placement — and a language that cannot be read fails the placement before the app is touched — the page is written and published, the marker says the placement is unfinished, and the report says only what is known: this run changed nothing in the app's navigation (and, when it completes a placement an earlier run began, did not look at what that run saved there, so it never says the page was "NOT added"), nothing guessed in its place (an upload that places no page writes no title and asks the environment nothing); refuses a create whose `makeStyles` writes a Griffel shorthand (`griffel-shorthand`, before anything is read) and an update that ADDS one the deployed page did not already have — one it already had goes ahead with a warning — and, for an update, no-base / deployed-changed / deployed-unreadable unless --overwrite-deployed; the page's text is made from the file's bytes ONCE and that text is what is checked, hashed and written; a failed write is reported with the page's `pageId`, the backend's `outcome` and the SDK's `code`, so a caller can tell "unknown" from "failed"; a write the service throttles is waited out (`lib/throttle-budget.js`), and a wait of more than a few seconds is announced on stderr as `WARNING: …`, never in the result; a page THIS script created and did not finish — its publish failed, or the `--add-to-sitemap` placement did — is finished by running the same command again with `--page-id` added: the base marker beside the code file says `unfinished` for exactly that page, and stands in for the navigation proof an update makes for that page alone; finishing a placement asks the backend to FINISH it — the app is published again even when its saved navigation already names the page, and the marker stays while the app's published navigation can be read and does not show the page (`GENPAGE_APP_PUBLISH_UNPROVEN`, saved: the app's publish is what is left), so a placement that was saved and never published is not reported done; a published navigation that cannot be read at all clears the marker with a warning, since the publish was accepted and keeping the marker would make every later update of the page need `--add-to-sitemap` and publish the app again for as long as that layer stays unreadable)
+ genpage-upload.js ← /genpage: deploy one page through the page backend (prompt passed BY FILE, never composed into a command; a create needs no app — `--app-id` is optional for a create only: a page needs no app, so a create without it is added to no app and makes no app-scoped check; `--add-to-sitemap` and an update still need `--app-id`, and an update must prove the page is in that app's navigation; an update keeps the page's name, model, data sources and bindings unless given; a named app also gets the default views of the tables the page reads pinned into its components; `--add-to-sitemap` titles the page's entry in the environment's base language, which it reads with the backend's `baseLanguage()` before the placement — as `genpage.js add-to-app` does, and so when a later run completes the placement — and a language that cannot be read fails the placement before the app is touched — the page is written and published, the marker says the placement is unfinished, and the report says only what is known: this run changed nothing in the app's navigation (and, when it completes a placement an earlier run began, did not look at what that run saved there, so it never says the page was "NOT added"), nothing guessed in its place (an upload that places no page writes no title and asks the environment nothing); refuses a create whose `makeStyles` writes a Griffel shorthand (`griffel-shorthand`, before anything is read) and an update that ADDS one the deployed page did not already have — one it already had goes ahead with a warning — and, for an update, no-base / deployed-changed / deployed-unreadable unless --overwrite-deployed; the page's text is made from the file's bytes ONCE and that text is what is checked, hashed and written; a failed write is reported with the page's `pageId`, the backend's `outcome` and the SDK's `code`, so a caller can tell "unknown" from "failed"; `--solution <unique name>` (AB#6443257) is the solution the page joins: read before anything is written (a solution that is not there or is managed, or a page table whose component type cannot be read, refuses the upload with nothing made; a system solution is not read), and the page added LAST, once written, published and placed (`solution`, `addedToSolution`, `systemSolution` in the result) — an add that fails is `ok: false` with `code: "solution-add-failed"` and the page's id, naming the `add-page-to-solution.js` command that adds it, never a second create; a create that did not finish joins the solution when the same command, run again with `--page-id`, finishes it; a write the service throttles is waited out (`lib/throttle-budget.js`), and a wait of more than a few seconds is announced on stderr as `WARNING: …`, never in the result; a page THIS script created and did not finish — its publish failed, or the `--add-to-sitemap` placement did — is finished by running the same command again with `--page-id` added: the base marker beside the code file says `unfinished` for exactly that page, and stands in for the navigation proof an update makes for that page alone; finishing a placement asks the backend to FINISH it — the app is published again even when its saved navigation already names the page, and the marker stays while the app's published navigation can be read and does not show the page (`GENPAGE_APP_PUBLISH_UNPROVEN`, saved: the app's publish is what is left), so a placement that was saved and never published is not reported done; a published navigation that cannot be read at all clears the marker with a warning, since the publish was accepted and keeping the marker would make every later update of the page need `--add-to-sitemap` and publish the app again for as long as that layer stays unreadable)
genpage-base.js ← /genpage: record or check the deployed-page base marker next to a page.tsx (#673); `record` needs no `--app-id` — a first page is created before the app that will hold it, and is recorded with the page alone
genpage.js ← /genpage: the page verbs the skills ran through `pac model genpage`, through the page backend and the Azure CLI token — `list`, `download`, `types` (the type generator), `add-to-app`, `remove-from-app` and `delete` (see "The page verbs" under Key Concepts); one pure-ASCII JSON line and exit 0, or a refusal as `{ ok: false, error, code, … }` and exit 1; a mistake in the command line is a usage error: stderr only, stdout empty
- genpage-plan-provenance.js ← /genpage: quarantine a stale plan before the planner writes, then verify the written plan targets the pages the approval named and, for an edit, carries the exact approved change list
+ genpage-plan-provenance.js ← /genpage: quarantine a stale plan before the planner writes, then verify the written plan targets the pages the approval named and, for an edit, carries the exact approved change list; for a create, also that its assumptions, data-semantics decisions and lookup records are the approved ones, field by field (`lib/genpage-plan-semantics.js`) — `--require-assumptions` (a newly authored plan carries them all), `--lookup-metadata <file>` (every observed lookup matches the saved metadata read; a planned one may then be promoted), `--require-observed-lookups` (none still planned before generation); an unknown flag is a usage error (exit 1)
check-page-files.js ← /genpage: pre-dispatch gate — the page file names of the plan's one ## Pages table are safe write targets (lib/page-file-targets.js)
genpage-worker-output.js ← /genpage: accept a parallel worker's page only if complete (default export, balanced, no elided code)
check-griffel-styles.js ← /genpage and /app-builder: a page's `makeStyles` calls hold none of the ten shorthands Griffel's runtime drops (lib/griffel-styles.js; see "Griffel shorthands" below)
@@ -2717,7 +2793,8 @@ scripts/
own-keys.js ← `ownValue(map, key)`: a map keyed by a name a maker writes freely or a service returns (a dashboard's, a page's key, a persona's, a status reason's label) answers only an entry it holds as its OWN — a name can be `__proto__`, `constructor` or `toString`, which a plain object answers with an inherited member. The rule beside it: a map BUILT from such names is a null-prototype object (`Object.create(null)`), so every name, `__proto__` included, is stored as an entry; JSON.stringify writes it as it writes a plain object
lcid-cultures.js ← pure: a Windows language id (LCID) → culture code and right-to-left, from a table of Windows' own culture data (what `pac` printed; the SDK reports numbers only, and no Intl API maps an LCID); a language id with no entry stays numeric and is reported, never guessed (`list-languages.js`)
supported-dependencies.js ← Single source of truth for runtime + dev deps versions
- feature-flags.js ← Feature flag probe with fail-closed fallback + Custom API script backstop
+ feature-flags.js ← Feature flag probe with fail-closed fallback + Custom API and built-in operation script backstops
+ dataverse-operations.js ← The reviewed built-in operation catalogue (frozen, revision 1): exact-name lookup, the four-key actionBindings projection (toActionBinding) and the new-row check; no I/O, not gated
sdk-build.js ← app-builder build engine (idempotent; incl. the pages phase). Every way it pushes or publishes the app is one of `appWriters`, which first awaits `publishTablesBeforeApp` (the one request that publishes, before the app, the tables whose forms or charts its publish ships)
app-components.js ← shared current/published app layers (`currentLayerRows`, and `currentLayerRow` — the authored layer wins — for a listing), component inventory (`readAppComponentInventory`: the download's read, with two opt-ins the build's pre-app proof makes — `savedLayer`, which looks the tables of the form and chart components up in the SAVED layer, and `requireIdentified`, which reads the answer strictly: a row counts for an id the list asked about, two tables for one id or a value no table has make the read incomplete, and a row of the component list that cannot be placed — no record, no GUID objectid, another component type — makes the list unreadable), hidden-table pin/proof, Main-form resolution/membership and push directives, `collectionRows`, the one reader of a paged collection, and `savedPageRows`, the one reader of the generative-page rows in the SAVED layer (RetrieveUnpublishedMultiple, 50 ids a read): a plain read of the page table answers the published layer only, so a page that was created and never published is "not found" by it — `apps.js` and teardown read pages here
solution-membership.js ← one read of a solution's components (the types the build adds, plus its tables: a table held with all its subcomponents vouches for its views, forms and charts, which have no rows of their own), so a rebuild adds just what the solution is not PROVEN to hold; every doubt reads as "add"
@@ -2754,6 +2831,9 @@ scripts/
app-header-text.js ← an app's header texts (`name`, `description`) held to plain text at the HTTP client every SDK is made with (wired in `maker-sdk.js`): a PATCH of an app module row that carries one that is not a string is refused before any byte is sent — `APP_HEADER_NOT_PLAIN_TEXT`, an `SdkError` marked `transient: false` — whether it is the SDK's `patch`, a `patchRaw`, or a PATCH inside a raw change set (`postRaw` / `post` to `$batch`), because the SDK writes every text its workspace copy holds whenever its own comparison read of the header cannot be made (503, 403, a thrown error, an empty 200). The build takes such a text off the copy before its push, so this is the last line of defence, for a push of a copy it did not clean. A batch that names the app module table and cannot be read is refused too. A delegating Proxy: every member it does not judge runs on the client itself. Also how such a text reads in a message (`describeHeldAppText`), which the guard's refusals share
batch-request.js ← a multipart `$batch` REQUEST read the way the service reads it — `readBatchRequest(text, contentType)`: the parts of the boundary the Content-Type declares, a change set one level down, one HTTP request in each part, answered as `{ operations: [{ method, target, contentId, body }] }`, or `{ problem }` for text it cannot read with confidence (cut short, another boundary, a part that is not a request). A body is only ever text: a line in it that looks like a request is not an operation. `app-header-text.js` reads a raw change set with it
throwaway-sdk.js ← `withThrowawaySdk({ env, prefix, httpClient? }, run)`: the bundled SDK, made through `maker-sdk.js`, over a throwaway workspace folder (made by `temp-workspace.js`) that is removed whichever way the run ends (a constructor, a storage or a module that throws included); `run(make)` gets a `make(extra)` for more instances over the same folder and the one client (`make({ languageCode })` is a writer). The one copy of what `apps.js`, `list-tables.js` and `list-languages.js` each wrote out
+ plan-sections.js ← the three Markdown primitives every genpage-plan reader shares (`planSection` — one `## ` section, any letter case; `findMarkdownTable`; `parseMarkdownRows`), moved unchanged from the eval harness, which re-exports them
+ genpage-plan-semantics.js ← the plan's semantic records, read with no I/O (references/plan-schema.md, "Assumptions, data semantics and lookup metadata"): the written plan (`## Assumptions` / `### A<n>`; per page `#### Data semantics` / `##### R<n>`, `F<n>` and `#### Lookup metadata`) and the approval preview at its own levels (`### Assumptions` first, `### Data Semantics` / `### Lookup Metadata` grouped by page file), every entry rule and cross-reference (an assumption that exists, a quote the requirements hold, the exact `Unattended default:` record), the field-by-field comparison `genpage-plan-provenance.js` gates on, and the check of observed lookups against `get-lookup-metadata.js` evidence. Proves structure and agreement, not entailment
+ lookup-metadata.js ← `readLookupMetadata(sdk, tables)`: composes the SDK's `fetchEntityMetadata` (complete lookup targets) with `relationship-metadata.js` `readRelationshipsOf(…, 'ManyToOne', cache, { lookupDetails: true })` (every page; `ReferencedAttribute` and `ReferencingEntityNavigationPropertyName`, which the SDK projection drops) into concrete and shared paths; owns no HTTP. Every incomplete read fails the whole read. A table the environment does not have is `LOOKUP_TABLE_NOT_FOUND`, not the SDK's `CONNECTION_ERROR`: the SDK's own read of the table is the first request made for it, and only a 404 of that read (`genpage-sdk.js` `missingTableOf`, as for `genpage.js types`) or of the lookup-details read says so; any other failure keeps the SDK's code
collection-answers.js ← `requireCollectionAnswers(client, { reads, unreadable })`: the HttpClient the SDK is given, with one addition — a 2xx answer to a read `reads(url)` selects must be a collection (`{ value: [...] }`), or the read throws what `unreadable` says; `unreadableAnswer(error)` finds that error, itself or under the SDK's `ConnectionError`. `guardTableLists(client, makeError)` is its policy for the one read of the environment's table list (`/EntityDefinitions?…`, which only `findTables()` makes), and `maker-sdk.js` applies it to every SDK a script makes: the SDK's `findTables()` is `body.value ?? []`, and the bundle is not edited
temp-workspace.js ← the one maker of the plugin's throwaway workspace folders, and the sweep of the ones a KILLED run left (`makeTempWorkspace(prefix)` in place of `fs.mkdtempSync(path.join(os.tmpdir(), prefix))`, at every entry point that makes an SDK workspace — the page backend, `withThrowawaySdk`, `sdkFirst`, build, download, teardown, verify, the `provision-*` scripts, `ai-preflight`, and `solution-settings`' pac scratch folder). A run killed outright (SIGKILL, "End task", a timeout) never reaches its `finally`, and what it left held the source of every page it read and the environment's address (`solution-settings`' pac scratch folder: a settings template, an exported package or a copy of the settings file, which can hold values; the sweep's note says which a folder held, by its prefix). The folders go together in one folder of the plugin's own, `<temp>/power-platform-skills-model-apps` (`-<uid>` after it on POSIX, where the temp folder is shared). That folder is a courtesy, never a reason for a run to fail: it must be a plain folder that only this user can change — POSIX: owned by the user and writable by no one else; Windows, which tells Node no owner and no permissions: a folder this process MAKES is given an explicit access list before anything is put in it — protected, with only this user, the system and the administrators on it, full control inherited by every workspace and record made inside — and read back, and one that cannot be made so is removed and not used; an EXISTING one is judged by its access list and its owner (`windows-folder-acl.js`) and used only if NO entry of the list, an inherit-only one too, lets anyone else add to it, write to it, delete it or take it over, and the user (or the administrators, who own what an elevated process makes) owns it) — and if it cannot be used, or will not take a new folder (mode 0500, an access list that denies this user; a Windows folder that is being removed refuses a new entry — and its access list cannot be got — for a moment, so the attempt is made again after short pauses, up to six in all, and a folder that is still refusing after the last is not asked again by that process), the workspace is made in the plain temp folder exactly as before, unrecorded and never swept, and an error is reported only when that fails too. Each folder is named for the process that made it (`genpage-4242-AbC123`: the prefix, the pid, `mkdtemp`'s six characters; a prefix that does not end in a hyphen is given one, so that the pid always follows the hyphen a sweep reads it from) and holds an owner record `.owner.json` (`process-owner.js`); the first workspace a process makes sweeps that folder (`sweepDeadWorkspaces`) — only a workspace whose owner is PROVABLY gone is removed (the name's pid must have no process — on Linux a pid that runs is looked into too, since the record's start time can show it was handed out again — and the record must agree with the name; the record is read again, and judged again, just before the removal; what is inside is removed first and the record last, and the record leaves the folder only for as long as the folder itself is being removed — it is renamed out to `<folder>.removing`, which Windows allows even while another process holds it open, and moved back if the folder will not go — and if even that is refused it stays beside the folder, whole, and is never WRITTEN into the folder instead, since a write can be cut off and a damaged record beside the whole one would strand the removal; a sweep that is killed between the move and the removal leaves that file and the empty folder, and the next sweep finishes the removal when the file is a record of the folder's own — its name, a record that names the pid in it, an owner that is gone — and the folder is empty or gone, and leaves anything that does not agree as it is — so a removal that fails, half way or at the very end, leaves a folder still known to be dead and found again by the next sweep (Windows with Node 20 keeps a file that was deleted while open, listed, until the holder lets go, and the folder cannot go meanwhile); at most 100 a run, out of 500 entries looked at: the entries are taken in name order and the next run starts after the last one looked at — a cursor, `.sweep-cursor.json`, one small file in the plugin's folder, written whole and there only while the folder holds more than a run looks at — so that a folder whose first 500 entries must be kept does not hide a dead run's workspace, or a removal a kill left half done, behind them for good), and a folder whose name names a pid that RUNS is not even opened (on Linux its record alone is read, for the start time that can show the pid was handed out again; Linux lets a file another process has open be removed) — on Windows a file that is deleted while another process has it open stays in its folder until that process lets go, so a sweep that read a live run's record could make that run's own removal fail — and the run says so on stderr (`⚠ removed 1 temporary workspace left in … by a run that is no longer running`). A run that may still be going, another machine's, a folder with no readable record (a release before this one's, a damaged record), a link, a file: left as they are. **A path inside a workspace that is given to a program of another make makes the workspace LENT, when it is made** (`makeTempWorkspace(prefix, { lent: true })`, as `solution-settings`' `templateThroughPac` does for pac): on POSIX such a program outlives a run that is killed, so the record — written ONCE, whole, to a file of its own and renamed into place, and never written again — says `lent: true`, and a sweep never takes a lent workspace because its maker is gone: only when its maker is gone AND it is old, neither the folder nor its record written to for seven days (`LENT_KEEP_MS`; pac gets an hour at most). Nothing follows the program or changes the record once it has started (a record that is changed later can be unreadable at that moment), and a record that is unreadable keeps the folder. Every caller that hands a path in a workspace to another program decides that when it makes the workspace. The plugin's folder is removed when the process ends with nothing in it, so a normal run leaves the temp folder as it found it — and so does a run that is cut short by `process.exit` or an error nothing catches (the `exit` event): it first removes the workspaces it made and did not lend that are still there, by the steps of a sweep (what is inside first, the record last), since it never reached the `finally` that would have; a LENT workspace is never taken at the end of the run that lent it, and what is not its own is never touched (`rmdir` takes the folder only when it is empty, and a run that loses the folder between making it and making its workspace in it makes it again); the one caller that removes a lent workspace itself, `solution-settings`, does it in a cleanup it registers with `lib/exit-cleanup.js`, which runs after the maker's listener has found the workspace still in the folder and left the folder, so that cleanup calls `pruneWorkspaceParents()` once its workspace is gone — the same `rmdir`, so a run that is cut short while pac runs leaves no empty plugin folder behind (a signal included: it ends a POSIX process with no `exit` event, and that cleanup is what runs). A POSIX signal is NOT one of these ends — its default action ends the process with no JavaScript run, and a listener, which would, replaces that default action in every script that makes a workspace (a process blocked in a synchronous `az` or `pac` call would no longer end when signalled, and the signal would have to be raised again to keep its status) — so a run that is signalled leaves its workspace for the next run's sweep, as a killed one does; a folder that cannot be used or a record that cannot be written costs the sweep, never the run. The sweep reads only the plugin's own folder, never the temp folder, which can hold hundreds of thousands of entries
process-owner.js ← who made a lock or a workspace, and whether that process is gone — one place for the build lock and the pages lock (`app-operation-lease.js`), the recovery records' writer lease (`record-lease.js`), the temporary workspaces and the snapshot lease's liveness check (`processAlive`, as it always was). `ownerStamp()` is what a maker records (pid, time, host, platform, and on Linux the pid namespace and the process's start time from `/proc`); `ownerState(stamp)` answers `gone` only when the stamp was made on this machine, by this kind of system, in this pid namespace, and no process has the pid (ESRCH) — or, on Linux, a zombie or a process with another start time has it (the pid was handed out again) — `alive` for a process that runs (this one included) and `unknown` for anything else: another machine, a stamp that is missing, damaged or not understood. **On Linux a pid is only a name inside its pid namespace, so the stamp AND the reader must both name theirs (`pid:[…]`, readable and well formed) and name the same one: a side that cannot (a hidden `/proc`: a container, hidepid, a sandbox), or two that cannot, is `unknown`, never "the same pid space".** A recorded `start` that is not `<boot id>:<ticks>` — empty, cut short, damaged inside a record that is still valid JSON — makes the record untrusted (`isOwnerStamp`: kept), and a start read from `/proc` that is not well formed is not compared: only two well-formed starts that differ show a pid handed out again, in the self-pid branch too. `ownerState` is a fact about the maker and only that: a workspace that was handed to a program that outlives its maker is kept by its age instead (`temp-workspace.js`, `lent`). Every doubt keeps; where no start time is cheap to read (Windows, macOS) a pid given to another process makes a dead run look alive, which keeps its lock or folder (the state of things before this module)
@@ -2765,6 +2845,7 @@ scripts/
private-folder.js ← a folder, and a file in it, that only the current user can use — the copy of a settings file that `pac solution import` is given: POSIX modes 0700 and 0600, set and read back; Windows an access list with the current user's SID as its ONE entry (`icacls /reset`, `/inheritance:r`, `/grant:r *<SID>:(OI)(CI)F`, read back as SDDL through `icacls /save`, the file's too before a byte is written; the SDDL aliases of the system accounts are compared as the SIDs they stand for, and `LA`/`LG` — the machine's own Administrator and Guest — only when the machine itself writes the user's SID that way, `spellingOf`), `whoami` and `icacls` looked up in the Windows folder's System32 alone through `process-runner.js`; whatever cannot be set or read back is an error with a `reason` (a tool, a step, a number — never a path or a value) and nothing is written
exit-cleanup.js ← a synchronous cleanup that runs if the process ends while a run's work is going — `process.exit`, an uncaught error, SIGINT, SIGTERM, SIGHUP, SIGBREAK — after which the process ends as it would have: BY the signal on POSIX (raised again once our listeners are off), with STATUS_CONTROL_C_EXIT (0xC000013A, 3221225786) on Windows, where a Ctrl+C is a console event and `process.kill` would end it with the status 1 of a failure; a program that has a handler of its own for the signal — one-shot and self-removing ones included, however they were put on the list — keeps the decision (ours is first in line, so that it sees them all, and stays first: a handler the program PREPENDS later is put behind it again before the call returns, `keepFirst`, which never puts back a cleanup that was released while it was being moved); a KILLED process runs nothing, which is its stated limit
typescript-compiler.js ← loads the vendored TypeScript 5.8.3 compiler (vendor/typescript/) for the SDK's page compile: lazily, once, only after its bytes match PROVENANCE.json
+ typescript-views.js ← the parser check: where the lexer guessed, the lexer's views of a page built from that compiler's parse (no view where it reports a diagnostic, or where another parser reads the page differently or refuses it), read by the navigation oracle and the structure gate alike (`guessedPageViews`) — see "The parser check" below
spec-lint.js / app-spec.js ← App Spec guardrail lint + validation
lookup-labels.js ← a lookup column's default label, environment-facing half: the parent table's label read, the old-default repair's column-label read (one per child table) (the pure rule is `lookupLabelFor`, app-spec.js); `lookup-cell-labels.js` repairs the form cell
view-filter-labels.js ← resolves a view filter's Choice labels against the environment's option metadata; the build's pre-flight (skipped for a spec with a localized label) and views-phase gate, the dry run, verify and lint all use it
@@ -2803,7 +2884,8 @@ scripts/
ai-candidates.js ← selects good-candidate tables for auto row-summary mode
ai-prompt.js ← generates tailored Copilot row-summary prompts
_graph.js ← entity topological ordering (shared by build + teardown)
- system-solutions.js ← built-in system solutions (Active/Default/Basic) — shared by download recovery + teardown skip
+ system-solutions.js ← built-in system solutions (Active/Default/Basic) — shared by download recovery + teardown skip, and by every path that adds pages to a solution (none adds to one of these)
+ page-solution.js ← how a generative page joins a solution (AB#6443257), for every path that makes pages: the page table's component type read from the environment (`EntityDefinitions(LogicalName='uxagentproject')?$select=ObjectTypeCode` — allocated per environment, never a constant), the add with AddRequiredComponents (its file rows come with it), and the unmanaged target solution read before the first write (`SOLUTION_NOT_FOUND` / `SOLUTION_MANAGED`) — used by add-page-to-solution.js, apps.js create, the page backend's `solutionTarget`/`addToSolution` (genpage-upload.js `--solution`) and the build's pages phase
phase-diff.js ← pure spec-diff → changed build phases (advisory diff foundation)
content-hash.js / hash.js ← content-aware phase diff: fold on-disk .tsx/contentPath byte hashes into the diff (changed-only); `recordedContentSha` reads a page's recorded hash back (the build's pages phase compares it with the page's source to tell an unchanged page from a changed one)
classify-changes.js ← changed-only: classify a spec diff → fast (page-content) | full | noop + sticky debt
@@ -2861,7 +2943,7 @@ Agents are invoked by skills via the `Task` tool — they are not user-invocable
| `genpage-page-builder` | `genpage` (create flow) **and** `app-builder` (Phase 1.5) | Generates one complete `.tsx` page from a plan document and schema; runs in parallel with other builders for multi-page requests. `/app-builder` projects its App Spec into that plan format via `scripts/write-page-plan.js` and dispatches this same agent |
| `genpage-edit-planner` | `genpage` (edit flow) | Reads downloaded artifacts as data, gathers changes, presents an edit plan and writes the same approved change list. The plan references prompt.txt without embedding it; the orchestrator applies only verified Requested Changes. |
| `genpage-connector-builder` | `genpage` orchestrator (create **and** edit flows) | Performs connector discovery (connections, connection references, datasets, tables, operations, schema), creates Dataverse connection references, and writes the `## Connector Bindings` contract + `connectors.json`. The orchestrator forwards its output into the planner or edit-planner prompt. |
-| `genpage-customapi-builder` | `genpage` orchestrator (create **and** edit flows) | **Single owner of the custom-api feature gate.** Discovers supported public Dataverse Custom APIs (Global + entity-bound Actions/Functions), primitive declared kinds and separate lookup inputs via `list-custom-apis.js`, and writes the `## Custom API Bindings` contract + primitive-only `actions.json`. The orchestrator forwards its output into the planner or edit-planner prompt. |
+| `genpage-customapi-builder` | `genpage` orchestrator (create **and** edit flows) | **Single owner of Custom API discovery.** Discovers supported public Dataverse Custom APIs (Global + entity-bound Actions/Functions), primitive declared kinds and separate lookup inputs via `list-custom-apis.js`, and writes the `## Custom API Bindings` contract + primitive-only `actions.json`. Also owns the default-off `dataverse-operations` gate: offers the two reviewed built-in Functions (`list-dataverse-operations.js`), writes a selected one's four-key row into the same `actions.json` and `dataverse-operations.md` for the optional `## Dataverse Operations` section. The orchestrator forwards its output into the planner or edit-planner prompt. |
## Key Concepts
@@ -2875,7 +2957,7 @@ Fluent UI V9 styles are Griffel's, and Griffel's runtime silently drops ten shor
- **What it reads.** Every key of every slot's style object at any depth (`':hover'`, `'@media …'`, nested selectors; quoted, spaced, computed-from-a-string and escaped keys; `{ borderColor }` shorthand members; objects written inline in a spread), in code only — the plugin's own lexer (`source-literals.js`) masks strings, comments, templates, regexes and JSX text, so the same names there, and in an inline `style={{ … }}`, are not keys. Slot names are not properties, and an `animationName`'s keyframes are serialized as written, so neither is reported. `makeStyles` is found under its own name, an `import { makeStyles as ms }` alias and a `Fluent.makeStyles` namespace import from `@fluentui/react-components`, `@griffel/react` or `@griffel/core`.
- **`makeResetStyles` is not checked, on purpose.** The work item names it, but `resolveStyleRules` is the only code that consults the unsupported set, and `makeResetStyles` goes through `resolveResetStyleRules`, which writes every key as given (`@griffel/core` 1.19 and 1.20: `makeStyles` drops `borderColor`, `makeResetStyles` emits `border-color:red;`). Refusing a page that works would be a false reject. To check it too, add `['makeResetStyles', { slots: false }]` to `STYLE_FUNCTIONS`.
-- **A style object the check cannot see is a problem, never a pass.** `makeStyles(styles)`, a slot or a selector given a variable (`root: base`, `':hover': hover`), and a spread of anything but an object written inline (`...base`, `...helper()`, `...(a || { … })`) are each `unread-style-object` — the keys behind them may be any of the ten — and the gates treat it as they treat a call the check cannot read: refused on a create or a change, warned for a page sent again as it is. So is a getter that runs, whatever key it defines (`get root() { return … }`, `get color() { … }`, with or without a space after `get`): Griffel calls it as it reads the key and a spread as it copies its object — even one whose value a later definition then replaces — and its body is code the check does not read, which may return anything and rewrite or delete what Griffel reads after it; a getter that never runs (replaced in its own object before anything reads it, or inherited under an own key) is not reported, and nor is one whose object never reaches Griffel (in a value a later definition replaces, in a prototype a spread does not copy, in an animation's keyframes), though a spread or Griffel may run it — its own object is all it can change there. Code that writes shared state (`Object.prototype.borderWidth = …`, a property of an import, a variable) changes what every object holds, as a statement anywhere else in the page could; no check of the style objects can see it, and this one does not follow it, wherever it runs (a getter's body, a Proxy's trap or a `toString` Griffel calls on a fallback value, a template's substitution) — the gate checks what a page asks Griffel for, not code written to get past it. So is a computed key the check cannot read as one string (`[key]`, `['border' + 'Width']`), which may name one of the ten or a selector — unless it is a template whose text before its first `${` no one of the ten begins with (`--${name}`, `& .${className}`, `@media (min-width: ${width}px)`), in which case its start tells what it is, and the object under one that starts as Griffel's nested keys do (`:`, `[`, `>`, `&`, `@`) is read. What a spread or a prototype (`__proto__: { … }`) brings into an object is read at that object's level — slots beside slots — and the object is resolved as JavaScript resolves it: a key's last definition is the property, own keys hide inherited ones, a spread copies only its object's own keys, and a key is the string JavaScript makes of it (a CR LF or a lone CR written in a template is one LF, however the file ends its lines; U+2028 and U+2029 stay as written), so a definition that provably never reaches Griffel is not checked, while one that may (a spread a condition chooses, a key computed at run time) is. A function member ends where its body closes, not at a comma of its type parameters or return type. Read in full: an object literal, or object literals chosen by a condition (`c && { … }`, `c ? { … } : { … }`), through parentheses, a non-null `!` and `as`/`satisfies` with a type the check reads — `as const`, or a type name with or without type arguments (no page wrote a cast in `makeStyles` at all); a keyword or literal type (`number`, `null`, `this`, …) ends at its word, so a `<` after it is a comparison; any other type leaves the value unread, so a type is never read as a value — for a slot, a selector, a spread and the call's own argument alike. Each `<` is matched to its `>` once per page (matchAngles), so a page of casts is read in linear time. Past 64 levels of nesting a value is unread and an object is reported as nested too deep, so a pathological page gets an answer rather than an exhausted stack. A number is read as a key (`{ 0: { … } }` is a slot), and a slot called `animationName` is a slot: only an `animationName` inside a style object holds keyframes. Spread without reading, alone or chosen by a condition, only as a value import from a Griffel module that the page never declares again (a read after `=` or `typeof` is not a declaration; an arrow parameter is), and only by the helper's own export names (`STYLE_HELPERS`: Griffel's 23 `shorthands` helpers and Fluent's 17 `typographyStyles` entries — never a name they inherit, since `shorthands.constructor(x)` is `Object(x)` and hands x back unexpanded; and `shorthands.transition` only where it builds its own array — any number of arguments but one, none of them a spread, or one array, string or number written in place — since given one array it returns what that array's own `reduce` returns): Fluent's `shorthands.*(…)` (it writes the longhands) and `typographyStyles.*` (font longhands only). Measured before the rule: no page among the samples, eval fixtures and pages generated on real environments (59 distinct) wrote a style object anywhere but inline, computed a key or wrote a getter, and the only spreads were `shorthands.*(…)`.
+- **A style object the check cannot see is a problem, never a pass.** `makeStyles(styles)`, a slot or a selector given a variable (`root: base`, `':hover': hover`), and a spread of anything but an object written inline (`...base`, `...helper()`, `...(a || { … })`) are each `unread-style-object` — the keys behind them may be any of the ten — and the gates treat it as they treat a call the check cannot read: refused on a create or a change, warned for a page sent again as it is. That holds for a `const` too, on purpose — one written once at the top of the page and used by the styles alone included (`const base = { … };` then `makeStyles({ root: base })`, `{ ...base }`, `{ base }`): a fail-closed limit. Reading such a constant where it is used would need the order in which the page's code runs, which its text does not show (a `makeStyles` call in a function declared below the constant runs when the page calls it, and a page transpiled to `var` that calls it before the constant is initialized hands Griffel `undefined`), and a bound on what reading every use costs (constants spread twice into the next double it at each step) — a reading that tried accepted such pages and took exponential time. Write the style object in place — in the call, the slot, the selector or the spread (`makeStyles({ root: { … } })`) — as the message says (`griffel-styles.test.js` pins the limit). So is a getter that runs, whatever key it defines (`get root() { return … }`, `get color() { … }`, with or without a space after `get`): Griffel calls it as it reads the key and a spread as it copies its object — even one whose value a later definition then replaces — and its body is code the check does not read, which may return anything and rewrite or delete what Griffel reads after it; a getter that never runs (replaced in its own object before anything reads it, or inherited under an own key) is not reported, and nor is one whose object never reaches Griffel (in a value a later definition replaces, in a prototype a spread does not copy, in an animation's keyframes), though a spread or Griffel may run it — its own object is all it can change there. Code that writes shared state (`Object.prototype.borderWidth = …`, a property of an import, a variable) changes what every object holds, as a statement anywhere else in the page could; no check of the style objects can see it, and this one does not follow it, wherever it runs (a getter's body, a Proxy's trap or a `toString` Griffel calls on a fallback value, a template's substitution) — the gate checks what a page asks Griffel for, not code written to get past it. So is a computed key the check cannot read as one string (`[key]`, `['border' + 'Width']`), which may name one of the ten or a selector — unless it is a template whose text before its first `${` no one of the ten begins with (`--${name}`, `& .${className}`, `@media (min-width: ${width}px)`), in which case its start tells what it is, and the object under one that starts as Griffel's nested keys do (`:`, `[`, `>`, `&`, `@`) is read. What a spread or a prototype (`__proto__: { … }`) brings into an object is read at that object's level — slots beside slots — and the object is resolved as JavaScript resolves it: a key's last definition is the property, own keys hide inherited ones, a spread copies only its object's own keys, and a key is the string JavaScript makes of it (a CR LF or a lone CR written in a template is one LF, however the file ends its lines; U+2028 and U+2029 stay as written), so a definition that provably never reaches Griffel is not checked, while one that may (a spread a condition chooses, a key computed at run time) is. A function member ends where its body closes, not at a comma of its type parameters or return type. Read in full: an object literal, or object literals chosen by a condition (`c && { … }`, `c ? { … } : { … }`), through parentheses, a non-null `!` and `as`/`satisfies` with a type the check reads — `as const`, or a type name with or without type arguments (no page wrote a cast in `makeStyles` at all); a keyword or literal type (`number`, `null`, `this`, …) ends at its word, so a `<` after it is a comparison; any other type leaves the value unread, so a type is never read as a value — for a slot, a selector, a spread and the call's own argument alike. Each `<` is matched to its `>` once per page (matchAngles), so a page of casts is read in linear time. Past 64 levels of nesting a value is unread and an object is reported as nested too deep, so a pathological page gets an answer rather than an exhausted stack. A number is read as a key (`{ 0: { … } }` is a slot), and a slot called `animationName` is a slot: only an `animationName` inside a style object holds keyframes. Spread without reading, alone or chosen by a condition, only as a value import from a Griffel module that the page never declares again (a read after `=` or `typeof` is not a declaration; an arrow parameter is), and only by the helper's own export names (`STYLE_HELPERS`: Griffel's 23 `shorthands` helpers and Fluent's 17 `typographyStyles` entries — never a name they inherit, since `shorthands.constructor(x)` is `Object(x)` and hands x back unexpanded; and `shorthands.transition` only where it builds its own array — any number of arguments but one, none of them a spread, or one array, string or number written in place — since given one array it returns what that array's own `reduce` returns): Fluent's `shorthands.*(…)` (it writes the longhands) and `typographyStyles.*` (font longhands only). Measured before the rule: no page among the samples, eval fixtures and pages generated on real environments (59 distinct) wrote a style object anywhere but inline, computed a key or wrote a getter, and the only spreads were `shorthands.*(…)`.
- **Lexer uncertainty fails closed**, as in the navigation oracle: a call that reaches the first place the lexer guessed what a `/` or `<` is — or a `makeStyles(` in the text after it, which a wrong guess may have blanked — comes back as an `unverifiable-style-call` problem with the remedy; a call that never closes is `unbalanced-style-call`. No committed page hits a guess (`source-literals.test.js`), so this costs a realistic page nothing.
- **What the gates hold a page to.** The check is held against what a run is about to *ship*. A page deployed by an earlier release of the plugin — whose only guard was a grep for `borderWidth`, so `borderColor` under `:hover` passed — can already carry a key Griffel drops, and it renders without it today. Sending the same bytes again ships nothing new, and refusing them would stop a rebuild (or a one-line edit) over a defect the maker did not touch, with only one way through: edit the page, and writing the longhands *changes how it renders* (those declarations never applied; deleting the key keeps today's look). So every refusal and warning says both: *deleting a key changes nothing on screen; writing the longhands makes the style start to render*.
- **The build** holds no copy of what is deployed (and never downloads a page just for this), so it decides from the page's standing, in the pre-write scan, for each page the run uploads. A page that does not exist yet (`keyToId` has no id for it: it is *created*) and a page that exists but whose source no longer hashes to the `__contentSha` that `last-applied.json` recorded for it at the last apply (*changed*) are held to the check — `pages-griffel-shorthand`, before anything is written. A page whose source hashes to that record (*unchanged*), or that has no record (*unrecorded*), is sent as it is, and the build warns (`opts.warn`) with file:line:column and both remedies. The record is `last-applied.json` read as `opts.baselineSpec` — written by every successful full or changed-only apply and by download, and returned only for this app **in this environment** (`readBaseline`; a snapshot written before it carried those stamps is no baseline), the same hashes the changed-only flow compares. For a page an apply sent, the hash recorded is of the source the pages phase *read and checked* (`created.pageSourceShas`), not of the file when the baseline is written as the build ends: a page a maker saved while the build ran reads as *changed* on the next build, where re-hashing the files would have recorded the edit as applied and let a new key through on a warning. Every page is written as the text the scan read — the SDK takes a page's text, so there is no file for a later save to reach — and a page saved after the scan does not ship: the next build checks it, because the record holds the source that was checked and the file no longer matches it. A page a changed-only run did not send keeps the record it had (with none, the hash of its file as it is). *Unrecorded* — a new, moved or cleared workspace, another environment, or an apply that predates the record — fails **open** on purpose: the release before this check built such pages with the CSS silently dropped, so refusing one now would regress a rebuild that used to complete. The cost is that an edit that adds a key to an unrecorded page is warned about, not stopped, until a build has recorded it; a page that does not exist is always held, record or not.
@@ -2892,6 +2974,12 @@ The DataAPI (`props.dataApi`) provides typed CRUD operations against Dataverse t
TypeScript type definitions generated from Dataverse metadata. Contains entity types, enum registrations, and the `GeneratedComponentProps` interface. Generated by `scripts/genpage.js types` (the SDK's generator; see "The page verbs" below) before code generation to ensure correct column names.
+The generated `UxAgentDataApi` does not declare `setPageOutput`, the method a page opened as a dialog returns its value with
+(AB#6757591): the runtime has it, and a direct call fails type checking. `references/rules.md` ("Dialog output") gives the narrow
+typed intersection that type-checks. `scripts/tests/genpage-dialog-output.test.js` generates the types with the vendored SDK,
+type-checks the rule's own snippets against them with the vendored TypeScript, and fails when the SDK starts to declare the method,
+so the rule can then say to call it directly. The fix belongs in the SDK's shared data API contract (`setPageOutput(value: unknown): void`).
+
### The page verbs (`scripts/genpage.js`)
What the skills ran through `pac model genpage` — the listing, the download, the type generator, the placement of a page in an app — and what they had no verb for at all (taking a page out of an app, deleting it) is one script, `node scripts/genpage.js <command> --env <envUrl> [flags]`, over the page backend (`lib/genpage-sdk.js`) and the Azure CLI token every script here reads with. Every command prints ONE line of pure-ASCII JSON and exits 0, or exits 1 with `{ "ok": false, "error", "code", … }` — with `pageId`, `appId`, `outcome` (`nothing` or `unknown`: what a failed write can have done), `apps` (the apps a delete was refused for), `saved` (a placement or removal that was saved and not published), `fileRows` and `conversationMessages` (what a delete that was not confirmed would remove) and `table` (the table `types` found the environment does not have) when they are known; the message is on stderr too, and so are the warnings (`⚠ …`). A mistake in the command line itself — an unknown command or flag, a missing, blank or repeated value, an id that is no GUID, an origin that is no Dataverse origin, a bare switch given a value — is not a result: stderr names it with the usage, stdout stays empty, the exit is 1, and nothing was read or made.
@@ -2915,8 +3003,7 @@ What the skills ran through `pac model genpage` — the listing, the download, t
## Feature Flags
Unreleased functionality can ship behind committed, **default-OFF** feature flags while
-dependencies roll out. **Supported public Custom API discovery now ships ON**, with the gate
-retained as an explicit opt-out. OFF stops new discovery/authoring; unrelated edits preserve
+dependencies roll out. OFF stops new discovery/authoring; unrelated edits preserve
existing page bindings, not silently clear them. The mechanism lives in `scripts/lib/feature-flags.js` with the committed
values in `feature-flags.json` at the plugin root.
@@ -2925,16 +3012,20 @@ Flipping is reversible in one line if the rollout turns out to be incomplete in
deleting the gate in the same change that enables the feature leaves no way back except a
revert. Once a release has shipped with the flag on and no rollback was needed, remove it —
a permanently-on gate is dead weight that still has to be probed, branched on and reasoned
-about at every call site.
+about at every call site. When a flag is removed, nothing may ask for it any more: an unknown
+flag reads as disabled, so a probe left behind would turn the feature off.
-Connector authoring no longer has a feature flag (the feature itself is in public preview). The
-remaining flags are `custom-api` (**ON**) and `custom-telemetry` (**OFF**).
+Connector authoring no longer has a feature flag (the feature itself is in public preview), and
+neither does Custom API support: `custom-api` shipped ON in 2.18.0 and 2.19.0 with its platform
+dependencies live in every region, so it was removed — Custom API discovery, authoring and upload
+are always available, and `GENPAGE_ENABLE_CUSTOM_API` is ignored. The remaining flags are
+`custom-telemetry` (**OFF**) and `dataverse-operations` (**OFF**).
-- **Source of truth:** `feature-flags.json` (e.g. `{ "custom-api": true }`). Flip a
+- **Source of truth:** `feature-flags.json` (e.g. `{ "dataverse-operations": false }`). Flip a
flag to `true` in a one-line PR once its dependencies are GA in PROD, then remove
it in a follow-up that deletes its gates.
- **Precedence (highest first):** env var `GENPAGE_ENABLE_<FLAG>` (e.g.
- `GENPAGE_ENABLE_CUSTOM_API=0` to opt out for a single run) → committed
+ `GENPAGE_ENABLE_DATAVERSE_OPERATIONS=1` to opt in for a single run) → committed
`feature-flags.json` → default `false`
(fail-closed). This mirrors the telemetry opt-out env-over-config convention.
- **LLM gate:** skill/agent markdown probes a flag with
@@ -2945,10 +3036,10 @@ remaining flags are `custom-api` (**ON**) and `custom-telemetry` (**OFF**).
Flags are catalogued with that metadata in the `FLAGS` map in `feature-flags.js`
(the committed `feature-flags.json` carries only the on/off value). Unknown flags
are disabled even when a matching env var is set.
-- **Script backstop:** Custom API entrypoints call the shared
- `exitIfCustomApiDisabled()` helper (DRY — no inlined gate) and fail closed with
- exit 3 when OFF: `list-custom-apis.js`. Connector scripts have no feature-flag
- backstop because connector authoring is always on.
+- **Script backstop:** `list-dataverse-operations.js` calls the shared
+ `exitIfDataverseOperationsDisabled()` helper (DRY — no inlined gate) and fails closed with exit 3
+ when OFF (its stderr line is constant and is made blocking before the exit). Connector and
+ Custom API scripts have no feature-flag backstop because both are always on.
- **Validation:** `KNOWN_FLAGS` + `validateFlags()` warn on unknown keys / non-boolean
values in the committed file (so a typo can't silently do nothing, or — after a flip
to `true` — accidentally enable the wrong thing).
@@ -2961,22 +3052,30 @@ only the per-feature specifics are tabled below:
never gate inline.
2. **Scripts** — each entry-point script calls the shared `exitIf<Feature>Disabled()` helper (DRY —
never an inlined gate) and fails closed with exit 3 when OFF.
-3. **Deploy** — the SKILL phase **re-probes** the flag. A populated Custom API table under an
- OFF probe halts before generation; a missing/malformed section halts too. Only the exact
- `No custom API bindings.` sentinel means none, never a fallback that clears existing bindings.
+3. **Deploy** — the SKILL phase **re-probes** the flag. A populated plan section under an OFF
+ probe halts before generation; a missing/malformed section halts too. Only the feature's exact
+ sentinel means none, never a fallback that clears existing bindings.
4. **ALM** — solution packaging honours the flag (or documents why it needs no gate).
5. **Codegen** — `genpage-page-builder` emits feature code **only** when the plan carries an actual
binding table, never on an absent/sentinel section.
-| | `custom-api` | `custom-telemetry` |
+| | `custom-telemetry` | `dataverse-operations` |
|---|---|---|
-| **Committed default** | ON (`GENPAGE_ENABLE_CUSTOM_API=0` opts out) | OFF |
-| **Owner agent** | `genpage-customapi-builder` | none — codegen-only |
-| **Plan section** | `## Custom API Bindings` | none — driven by the maker request, not the plan |
-| **Gated scripts** | `list-custom-apis.js` | none |
-| **Deploy phase** | SKILL Phase 4.6 | SKILL Phase 4.7 (probe only) |
-| **ALM** | none needed — `config.json`'s `actionBindings` travels inside the page's `uxagentprojectfile` rows automatically (the Custom APIs themselves are a separate deployment prerequisite, bound by name) | none — telemetry rides the host runtime, nothing is packaged |
-| **Emits** | `executeAction` / `executeFunction` / `listBoundActions` | `props.appInsights` calls (`trackEvent` / `trackMetric` / `trackTrace` / `trackException` / `trackDependency` / `startTrack` / `stopTrack`) |
+| **Committed default** | OFF | OFF (`GENPAGE_ENABLE_DATAVERSE_OPERATIONS=1` opts in) |
+| **Owner agent** | none — codegen-only | `genpage-customapi-builder` (the same one writer of `actions.json`) |
+| **Plan section** | none — driven by the maker request, not the plan | `## Dataverse Operations` — OPTIONAL; absent means no new built-in operation |
+| **Gated scripts** | none | `list-dataverse-operations.js` |
+| **Deploy phase** | SKILL Phase 4.7 (probe only) | SKILL Phase 4.6b — only for an add/replace; a preserve never consults it (an edit re-probes in edit-flow.md, Edit Phase 4); SKILL Phase 4.6c then decides once, from both partitions, whether a create passes `--actions` |
+| **ALM** | none — telemetry rides the host runtime, nothing is packaged | none — the built-in operations are the platform's own; nothing to deploy |
+| **Emits** | `props.appInsights` calls (`trackEvent` / `trackMetric` / `trackTrace` / `trackException` / `trackDependency` / `startTrack` / `stopTrack`) | `executeFunction({ name: 'WhoAmI' \| 'RetrieveVersion' })` from a button only |
+
+Custom API support, with no flag, keeps the rest of that pattern: `genpage-customapi-builder` is
+its one owner (discovery through `list-custom-apis.js`, the `## Custom API Bindings` section and
+`actions.json`), SKILL Phase 4.6 checks the plan section before generation (only the exact
+`No custom API bindings.` sentinel means none), `config.json`'s `actionBindings` travels inside the
+page's `uxagentprojectfile` rows for ALM (the Custom APIs themselves are a separate deployment
+prerequisite, bound by name), and the page builder emits `executeAction` / `executeFunction` /
+`listBoundActions` only for an actual binding table.
At Phase 4.7 the `/genpage` orchestrator probes and passes the verbatim result as
`Telemetry: enabled|disabled` in every page-builder dispatch — **that dispatch value wins over
@@ -2993,14 +3092,23 @@ asked to measure or track something. `enabled` is permission, not instruction.
Feature dependencies remain separate from their committed defaults:
-- **`custom-api` (ON)** — the AIBuilder CoderAgent action prompt, the shared `pai-gen-ux-action-runtime`
+- **Custom API support (no flag)** — the AIBuilder CoderAgent action prompt, the shared `pai-gen-ux-action-runtime`
plus the UCI and Controls host runtimes, the page `actionBindings` the plugin writes into `config.json`
- (through the SDK: `genpage-upload.js --actions`, and the build), and the `GenUxPluginActionAllowList` ECS setting.
+ (through the SDK: `genpage-upload.js --actions`, and the build), and the `GenUxPluginActionAllowList` ECS setting —
+ live in every region, which is why the `custom-api` flag was removed.
Note the maker-facing name is "Custom API" while the shipped wire contract stays
`actionBindings` / `executeAction` (see `references/custom-api.md`).
- **`custom-telemetry` (OFF)** — the page telemetry facade in the UCI host runtime, the GenUX
authoring control (power-platform-ux), the AIBuilder CoderAgent telemetry prompt, and the
`GenUxEnableCustomTelemetry` ECS setting (see `references/page-telemetry.md`).
+- **`dataverse-operations` (OFF)** — a host runtime that implements `executeFunction`, the page
+ `actionBindings` the plugin writes into `config.json`, and the `GenUxPluginActionAllowList`
+ ECS setting. Its offer is a fixed, reviewed catalogue of exactly `WhoAmI` and
+ `RetrieveVersion` (`scripts/lib/dataverse-operations.js`), not a check of the environment:
+ availability, player support and the user's privileges are reported as not checked. It never
+ decides Custom API discovery, gates offering and authoring only, and never strips or repairs a
+ binding a page holds; download and rebuild recognise the two exact names whatever it says (see
+ `references/dataverse-operations.md`).
Custom API discovery selects public Global APIs and the page's entity-bound APIs in one inline
request, including request and response types. It excludes collection-bound APIs and APIs with
@@ -3020,11 +3128,12 @@ or replacements still need fresh eligible discovery.
## TSX source lexer — known limits
**`scripts/lib/source-literals.js` — known limits.** It is a hand-rolled TSX lexer, not a
-parser. The plugin does ship the TypeScript compiler (`scripts/vendor/typescript/`), but only the SDK's page
-compile loads it, and lazily: unpacking it takes ~15 ms and evaluating it ~200 ms, with ~20 MB of heap
+parser. The plugin does ship the TypeScript compiler (`scripts/vendor/typescript/`), and the SDK's page
+compile loads it, lazily: unpacking it takes ~15 ms and evaluating it ~200 ms, with ~20 MB of heap
(`lib/typescript-compiler.js`) — more than a hook that runs after every code write (`hooks/validate-icon-imports.js`, a
-new process each time) or a gate that reads a page before it is deployed should pay, so those read source with
-this lexer. It tracks
+new process each time) or a gate that reads a page before it is deployed should pay on every page, so those read source with
+this lexer, and the navigation oracle and the structure gate ask the parser only about a page on which the lexer guessed (the parser
+check, under "Residual limits" below). It tracks
code / line comment / block comment / string / template / regex / JSX tag / JSX text, and
backs the page structural gate (`lib/page-structure.js`, shared by `promote-intent-pages.js` and
`genpage-worker-output.js`) plus the eval's effect scoper. It also
@@ -3088,26 +3197,43 @@ Where TypeScript reads `(…)` as a function type is its own rule (`isUnambiguou
is one, `(A | B)` is not, and nor is a parenthesised object type whose key is an index signature's or a mapped
type's — `({ [key: string]: T })`, `({ [K in keyof T]: boolean })` — since that key holds no expression and so
makes no binding pattern, where `({ [key]: v })` and `({ [K in T]: v })` do), and a return type nested deeper than
-any page (200 levels) is refused rather than read. **Known limit:** a default value in a binding pattern of a
-function type's parameter is passed over to the next `,` or closing bracket at its own level, and the comma between
-a generic call's type arguments is taken for one (`({ a = f<T, U>() }) => R`): the pattern then reads as none, the
-parentheses as a parenthesised type and the function type's `=>` as the arrow, so a write cut right after such a
-return type (`export default <T,>(p: T): ({ a = f<T,T>() }) => T`) is accepted — the page compile refuses it
-(TypeScript: `'=>' expected`), and `source-literals.test.js` pins it. With the call in parentheses the cut is refused.
-**Known limits, refused although TypeScript parses them** (both rare; 2.18.0 refused every synchronous generic-arrow
-default export, so neither is a regression there; it did admit the `async` forms of both — it took any `async` arrow
-text with an `=>` and something after it — and those are now refused too), pinned in `source-literals.test.js`:
-- a mapped type whose key type is in parentheses, inside a parenthesised return type — `(p): ({ [K in (keyof T)]: boolean }) => …`,
- and so `((keyof T))`, `(keyof T) as K` and a parenthesised conditional key type. The key's reading takes any group in
- parentheses for an operand, so `K in (keyof T)` reads as an expression, the braces as a binding pattern, the parentheses
- as a function type's parameters and the arrow as that function type's, and the page as cut off. Write `[K in keyof T]`,
- drop the parentheses around the return type (`(p): { [K in (keyof T)]: boolean } => …`), or name the type with a type
- alias (`type Flags<T> = { [K in (keyof T)]: boolean }`, then `(p): Flags<T> => …`);
-- a return type that is a function type whose parameter has a computed key the reading does not know — one that starts with
- a regular expression, `({ [/key/.source]: value }: Record<string, T>) => …` — and whose own return type starts with a
- leading `|` (`=> | typeof value | null`). The key is taken for no expression, the parentheses for a parenthesised type,
- the function type's `=>` for the arrow, and the `|` after it begins no body. Drop the leading `|`, write the key as a name
- or a string, or name the function type with a type alias.
+any page (200 levels) is refused rather than read. A default value in a binding pattern of a function type's
+parameter is passed over to the `,` or closing bracket that ends it, a generic call's type arguments included: where
+TypeScript's parser takes a list of types after an operand (`parseTypeArgumentsInExpression`: types between `<` and
+`>`, then a `(`, a template, or the end of the value), the comma between them is the call's
+(`({ a = f<T, U>() }) => R`), the pattern is read, the parentheses hold a function type's parameters, and a write cut
+right after such a function type (`export default <T,>(p: T): ({ a = f<T,T>() }) => T`) is refused as TypeScript
+refuses it (`'=>' expected`). The types are read strictly, each with what its groups hold; anything else between the
+angle brackets is a comparison, as TypeScript reads it, and the value ends at its first comma. That reading only ever
+refuses more: where it changes what a default value holds, the page must be complete read to the first comma as well
+(`genericArrowIsComplete`), because the lexer cannot see a value that TypeScript or Babel refuses in a parameter (`f<T, U>(010)`,
+`await f<T, U>()`).
+**Known limits** (rare, pinned in `source-literals.test.js`, each checked against TypeScript's parser and Babel's): a type
+argument that the strict reading does not read — a function type, an object type with members, a template literal type, an
+import type — leaves the default value read to its first comma, so a write cut right after a function type whose parameter
+has `{ a = f<(x: T) => U, V>() }` is accepted (the page compile refuses it); a function type whose parameter's default
+passes over a generic call's type arguments and whose own return type begins with a `|` (`({ a = f<T, U>() }: R) => | X |
+null => …`) is refused although TypeScript parses it, as it was before the type arguments were read.
+**Refused on purpose — fail-closed readings** (rare; each turns away pages TypeScript and Babel parse, because reading them
+as the parsers do would accept a page on the strength of tokens the gate does not check as the parsers do — a reading that
+tried let pages through that TypeScript or Babel refuses, so it is not made):
+- a mapped type whose key type is in parentheses (or brackets) and whose member type is a name, inside a parenthesised
+ return type — `(p): ({ [K in (keyof T)]: boolean }) => …`, and so `((keyof T))`, `(keyof T) as K`, `[keyof T]`, a
+ parenthesised conditional key type — sync and async. The key's reading takes any group for an operand, so `K in (keyof T)`
+ reads as an expression, the braces as a binding pattern, the parentheses as a function type's parameters and the arrow as
+ that function type's, and the page as cut off; by the same reading the page that only such a function type takes
+ (`… => | T | U => …`) is accepted, and the page compile refuses it. Both parsers try that binding pattern first and drop it
+ because `(keyof T)` is no expression; telling the two apart for certain needs every token of the key and member types
+ checked as they check it (an escaped keyword, a legacy octal number, a string escape). Write the key type without its
+ parentheses (`[K in keyof T]`), drop the parentheses around the return type (`(p): { [K in (keyof T)]: boolean } => …`),
+ or name the type with a type alias (`type Flags<T> = { [K in (keyof T)]: boolean }`, then `(p): Flags<T> => …`);
+- a return type that is a function type whose parameter has a computed key that starts with a regular expression —
+ `({ [/key/.source]: value }: Record<string, T>) => …` — and whose own return type starts with a `|` (`=> | typeof value |
+ null`). The key is taken for no expression, the parentheses for a parenthesised type, the function type's `=>` for the
+ arrow, and the `|` after it begins no body; by the same reading a write cut right after such a function type is accepted
+ (the page compile refuses it). Reading the key as an expression would accept such a page whatever the regular
+ expression's flags are, and Babel refuses an unknown, repeated or clashing flag (`/k/gg`, `/k/uv`) that TypeScript's
+ parser takes. Drop the leading `|`, write the key as a name or a string, or name the function type with a type alias.
The export pattern once took no `<` after `default`, and every such page was refused as having no default export.
And `endsMidStatement` catches the cuts that leave every bracket balanced: the
lexer reports when a file stops inside a string, template, comment or JSX element, and a file
@@ -3185,7 +3311,9 @@ rejected a complete page saved with CRLF endings.
stray scan, promotion, the page build and the eval scorer, so nothing about comments is left for them to
disagree about.
- **The trust frontier.** The lexer has no parser, so some of what it decides is a guess: whether a `/` is a
- regex or a division, whether a `<` opens an element, how a JSX tag with type arguments is scanned. Where a
+ regex or a division, whether a `<` opens an element, how a JSX tag with type arguments is scanned. (Where it guesses, the oracle asks the TypeScript
+ parser and, where that parses the page, reads it as the parser does, with no frontier — the parser check, under "Residual limits" below; what
+ follows is the frontier where the parser does not answer.) Where a
guess is wrong it blanks real code or reads text as code, and from there on the mask is not what the page
means. `blankNonCodePreservingTemplateExpressions(code, { onAmbiguity })` reports each such decision as data —
`(at, kind)`, the offset of the `/`, `<` or construct — and the tokenization is **byte-identical** with or
@@ -3604,7 +3732,8 @@ rejected a complete page saved with CRLF endings.
the generator, and fix the rule. **The oracle tests skip themselves where the variable is not set** (`TYPESCRIPT_ORACLE_PATH`, `BABEL_ORACLE_PATH`, `BASE_LIB_PATH`) **and fail where it is set and the package or the lexer cannot be loaded**
(`tests/helpers/typescript-oracle.js` throws), so a wrong path or a renamed file cannot turn the job green without running them. The CI job `test-model-apps-lexer-oracles` (`.github/workflows/model-apps-script-tests.yml`) installs
TypeScript 5.8.3 and `@babel/parser` 7.29.7 under `$RUNNER_TEMP` — outside the plugin, which ships no dependency, with `--ignore-scripts`, at exact versions — fetches the lexer of the 2.13.0 release by its commit hash, sets
- the three variables, and runs `node scripts/run-tests.js`. A new TypeScript release can change what a sweep judges: raise the pin in the same change, and run the sweeps.
+ the three variables, and runs `node scripts/run-tests.js`, on Ubuntu with Node 20 and with Node 22: the lexer reads identifier characters by
+ Unicode property escapes, whose tables come with each Node version's engine. A new TypeScript release can change what a sweep judges: raise the pin in the same change, and run the sweeps.
- **The residual net does not depend on the lexer, and has no exemption.** After forward resolution the
RESOLVED source is read again — the copy can read differently from the source, because each token became a
longer page id, which can move a `(` out of the look-behind — as plain text: any `PAGEREF_` token left in it
@@ -3668,7 +3797,33 @@ corpus — keep it, and add to it rather than around it. The worker-output gate
only) run the same kind of corpus: every committed page must pass them, because a false reject
there throws away a good page or blocks a pattern the page builder was told to copy.
-Residual limits, accepted deliberately:
+Residual limits, accepted deliberately — **of the lexer alone**. Where the lexer guesses, the gates now ask the TypeScript parser, which settles
+every guess it can vouch for (the parser check, below), so what follows is what a page costs where the parser does not answer: a page TypeScript does not
+parse, a page another reader reads differently or refuses (a JSX attribute string after trivia, grammar only TypeScript's parser takes), and the lexer's
+own tests, which run without the parser (`MODEL_APPS_LEXER_ALONE=1`, or `setParserCheck(false)` in `lib/typescript-views.js`).
+- **The parser check (`lib/typescript-views.js`).** Where the lexer reported a guess (`onAmbiguity`), the navigation oracle
+ (`pageref-resolver.js`, `lexNavigation`) and the structure gate (`page-structure.js`) ask the TypeScript compiler the pages are compiled with
+ (`lib/typescript-compiler.js`, 5.8.3, loaded lazily: ~200 ms and ~20 MB once per process, paid only by a page that hit a guess; the views of the last
+ few texts are kept, since a build reads one page several times). Where it parses the page with no diagnostic, the page is read from the views built
+ from its tokens — the lexer's own literal and executable views, character for character (strings, templates, regexes, JSX text and comments blanked
+ as the lexer blanks them, a template's substitutions code in the executable view with `;` for the `}` that closes one), with its comments and the ends
+ of its regexes and JSX tags — and nothing in the page is a guess any more: no frontier, no call refused for standing after one, and the structure
+ checks (`hasDefaultExport`, `hasUnbalancedBrackets`, `endsMidStatement`, `findElisionMarker`, the markdown fence) read the parser's views, which
+ they take as an optional argument. So `interface Api { <U>(x: U): U; }` no longer reads as a cut, a navigation call after an `angle`, `generic`,
+ `newline`, `operator`, `keyword`, `brace` or `paren` guess resolves, and so do JSX text with a `//` note and a later line that starts with a `/`, a
+ class head with a function expression or an object literal for its base, and type parameters on a method named by a keyword (`in<U>(y): void`,
+ `get<T>(…)`). Where the parser reports a diagnostic, the lexer's views and frontier stand, as before. They stand too where another reader — Babel's
+ parser, esbuild — reads the page differently or refuses it, which the parse itself tells (`readAnotherWay`), not the lexer, whose earlier misread
+ can hide what comes after it: a JSX attribute string after trivia that holds a backslash (TypeScript reads it with escapes, Babel and esbuild end it
+ at another quote, so a call after it can be code to one and a comment to the other), and grammar TypeScript's parser takes and leaves to its checker
+ — a word strict code reserves or a reserved word used as a name (`await`, `yield`, `let`, `static`, `type X = if`), a JSDoc type, a predicate
+ outside a return type, `readonly` before a type that is no array or tuple, an empty list of type arguments. One function decides this for both
+ consumers (`guessedPageViews`), so the navigation oracle and the structure gate never read a page differently. Off, the check only refuses
+ more. `parser-check.test.js` holds it: the views equal the lexer's on every page the lexer reads with no guess (the committed pages and every
+ generated valid page — over 40,000), the structure checks agree on them, every valid page TypeScript parses resolves its call with the data after
+ it untouched (and, with `BABEL_ORACLE_PATH` set, Babel reads the same calls on every guessed page the parser vouches for), the pages built to make
+ the lexer misread make every call they made with its page id when run, and the cases where the parser does not answer — a misread followed by an
+ attribute string after trivia among them — keep the lexer's reading for both consumers.
- **`<` disambiguation is TypeScript's own rule for `.tsx`, which is structural, not semantic.** Where an
assignment expression starts, a `<` opens a generic arrow's type parameters only by the rule above (a `,`, an
`=`, or `extends` and a token that is not `=`, `>` or `/`); anything else is an element — and after a unary or
@@ -4014,7 +4169,7 @@ Dataverse simply are not in it.
| Hatch | Use for | Examples in tree |
|---|---|---|
-| `dataverseRequest()` in `lib/dataverse-auth.js` (and the `dataverse-request.js` CLI) | Dataverse surfaces the SDK does not model at all | `WhoAmI` (`check-auth.js`), `customapis` (`list-custom-apis.js`), `connectionreferences` (`create-connection-reference.js`), solution-component adds (`add-page-to-solution.js`) |
+| `dataverseRequest()` in `lib/dataverse-auth.js` (and the `dataverse-request.js` CLI) | Dataverse surfaces the SDK does not model at all | `WhoAmI` (`check-auth.js` — an authentication probe, never a page's built-in operation binding), `customapis` (`list-custom-apis.js`), `connectionreferences` (`create-connection-reference.js`), solution-component adds (`add-page-to-solution.js`) |
| The raw `httpClient` from `createAzHttpClient` | A surface the SDK *does* touch but whose response it **projects away** | **No caller today.** The one that existed — `entityPrivileges` in `verify-model-app.js` — is gone: the SDK had no privilege READ at all, and `fetchEntityMetadata` drops `Privileges` permanently by design, so the check composed its own `EntityDefinitions(...)?$select=Privileges` request. The vendored bundle now carries `getEntityPrivileges`, and the reader takes it. The hatch stays documented because the *category* recurs; opening it again needs the same justification |
**Prefer `dataverseRequest()` over the raw client.** It already handles the API path, auth, headers
@@ -4102,7 +4257,16 @@ NODE20_BIN=/path/to/node20/bin node scripts/run-tests.js --with-sdk /path/to/pow
The suite runs in a temporary folder of its own (TEMP, TMP and TMPDIR point into it), and the run
FAILS when a test leaves a file or folder in it, naming what was left: a test removes everything it
makes. `scripts/tests/helpers/temp-dirs.js` (`makeTempDir`) is the shared way — require it at the top
- of the test file, and the folders it makes are removed after the file's last test. The folder the suite
+ of the test file, and the folders it makes are removed after the file's last test. Every test file of the
+ run shares that folder, and so the folder `lib/temp-workspace.js` makes the throwaway workspaces in, which
+ each process removes when it ends with nothing left in it; on Windows a folder being removed refuses a new
+ workspace for a moment, and under load for longer than the maker waits, so the workspace goes to the plain
+ temporary folder, as the code allows. A test file that checks WHERE a workspace is made therefore requires
+ `scripts/tests/helpers/own-temp-folder.js` first: it then works in a temporary folder of its own inside the
+ suite's, which the end of the file removes when it is empty (and leaves, for the run to name, when it is not).
+ That folder's name is short whatever the file is called — `own-<first letter of each word of the file's
+ name>-<4 hex digits of a hash of it>-<random>`, 22 characters at most — because a workspace is two levels
+ below it and Windows refuses `fs.mkdtempSync` a folder path of 248 characters or more. The folder the suite
runs in is the plugin's own, so the run FAILS too, naming the folder, when a test makes a
`.maker-workspace` there that was not there before the run (a build opens `<app folder>/.maker-workspace`
unless it is given a workspace, so a test must never hand a build `process.cwd()`; `sdk-build.test.js`
@@ -4122,7 +4286,9 @@ NODE20_BIN=/path/to/node20/bin node scripts/run-tests.js --with-sdk /path/to/pow
contract), plus the runners (`node evals/model-apps/genpage/run-layer-{1,2}.js --tier smoke`,
`node evals/model-apps/app-builder/run-app-builder.js`). See `## Eval Suite` below. CI's
`test-model-apps-evals` job runs the eval tests AND all three runners (genpage Layer 1/2, app-builder)
- over every committed fixture — offline, no org — so a fixture that falls out of step fails the PR.
+ over every committed fixture — offline, no org — on ubuntu × windows × macos and Node 20 × 22, as the
+ plugin suite runs (a Windows checkout gives the fixtures CRLF line ends), so a fixture that falls out of
+ step fails the PR.
**The vendored SDK lives in a separate repo.** The Dataverse mechanics are in
`power-platform-ux` (Azure DevOps `msazure/OneAgile`), package `packages/cds-maker-sdk`. This plugin
@@ -5509,6 +5675,20 @@ layers are automated (TAP v13 runners); Layer 3 is manual.
are not told apart, so the environment a write is compared with its gate by is the call's last `--env`; the
phase expectations count a call once and read its text, not its `argv`. `tests/script-verbs.test.js` pins
the reading and these limits.
+- **The plan-record contracts are graded from shared modules, never copies; page error handling and lookup use in
+ page code are not graded.** Whether every failure of a page reaches its reporter (Critical Rule 22) is not graded:
+ the evaluator that graded it was withdrawn because its proofs matched names instead of lexical scope and could pass
+ pages whose failures never reach a rendered error. The boundary wrapper's provenance proof (`lib/source-evidence.js`,
+ `lib/page-error-canonical.js`) stays, failing closed.
+ `lib/polymorphic-lookup-contract.js` only reads the canonical normalizer of rules.md "Lookup references" (Critical
+ Rule 23) and checks a copy of it; what a page does with a lookup is not graded — the grammar that graded it was
+ withdrawn because its table-check and unchanged-pair proofs could pass a page that opens a contact as an account.
+ `lib/column-contract.js` can read a typed `<navigation>/<column>` path whole with a run's lookup metadata as context;
+ no registered check passes it that context now. The plan's records are read by the plugin's own
+ `scripts/lib/genpage-plan-semantics.js`. Fixture 26 (an answered account-scope question and the lookup metadata
+ behind its plan) and fixture 27 (a newly authored plan with its assumptions; its page follows the page error
+ teaching) are the current scenarios; their declared evidence (`fixture.json` `semantics`) is
+ required, so a missing artifact fails rather than skips.
Run on every PR that touches the skill, agents, rules, or evals:
diff --git a/plugins/model-apps/CHANGELOG.md b/plugins/model-apps/CHANGELOG.md
index 97792fcb1..bd7dcd9d8 100644
--- a/plugins/model-apps/CHANGELOG.md
+++ b/plugins/model-apps/CHANGELOG.md
@@ -5,1449 +5,384 @@ All notable changes to the **model-apps** plugin.
Entries are deliberately short: what changed and why it matters to you. The reasoning,
evidence and trade-offs behind a change live in its PR, in `docs/`, or in the linked issue.
+## [2.20.0]
+
+The bundled SDK is unchanged (power-platform-ux a3443479).
+
+### Added
+
+- **`/genpage` can offer WhoAmI and RetrieveVersion** (flag `dataverse-operations`, off by default), bound only by explicit
+ selection and called only from a button; `list-dataverse-operations.js` does not check the environment.
+- **Plans keep what you asked for apart from what the planner assumed** (`## Assumptions`, shown first at approval) and ask
+ when a relationship or filter is unclear (#671).
+- **Lookups to more than one table** (Customer, Owner, Regarding): plans record each lookup's targets; pages normalize bare or
+ table-qualified values (#672).
+- **Pages report errors one way**: one reporter, a localized Fluent message bar and a render boundary; manual retry only for safe
+ reads (#674).
+
+### Changed
+
+- **Custom API support has no feature flag**; `GENPAGE_ENABLE_CUSTOM_API` is ignored.
+- **An edit asks before clearing built-in bindings, ahead of planning**, and a create that adds none stops offering them.
+- **Rebuilds and downloads tell built-in operations apart from Custom APIs.**
+- **A style you ask for replaces the default look** (AB#6320143).
+- **`primaryAttribute` refuses a key the build does not read**, naming the key it meant.
+- **Verify fails when an owned web resource's deployed content differs or is missing**; rebuilds report it without overwriting.
+
+### Fixed
+
+- `/genpage` adds pages to the solution you chose (AB#6443257), documents `setPageOutput` (AB#6757591) and finds the
+ inputs another page accepts (AB#6247727).
+- An app with no tables downloads and builds; a one-language label keeps its language; options labelled alike keep their column's
+ type; the loss report names command-bar buttons.
+- The entity-builder writes Choice options as labels.
+- The page check reads more valid pages; teardown still deletes a page a form embeds (now documented).
+- Evals: an ungraded fixture is not counted as passed; the label check reads comments and character references.
## [2.19.0]
-The bundled SDK is unchanged (power-platform-ux a3443479, as in 2.18.0). A `--changed-only` apply no longer stops over the bindings of
-a deployed page it leaves alone, a regression of 2.18.0. Two applies of one app no longer run at once in one workspace, the pages lock
-no longer depends on how the app's name is spelled, and a new table's column or status reason that Dataverse refuses moments after the
-table's create is sent again once a read proves it missing. A name such as `__proto__` or `constructor` works like any other name, a
-key over another key's columns stops the build instead of being skipped when the platform answers in English, and a generated page whose
-default export is a generic arrow function is accepted. The token guard also takes out the base64 of each part of a token and reads
-the bytes the plugin's file writers are given, and the genpage evals grade 17 more of their expectations.
+The bundled SDK is unchanged (power-platform-ux a3443479, as in 2.18.0).
### Changed
-- **The genpage evals now grade 17 of the 23 expectations their coverage baseline recorded as ungraded** (#688). A wizard's review
- step and its field labels, components kept at the top level, a search box beside a filter toolbar, shown text through the translate
- helper, choice values named after their RuntimeTypes.ts members, the columns a page's data calls name (against the RuntimeTypes.ts
- the run kept, for evals 1 and 7), an edit that keeps what its plan's Preservation Constraints quote and one that stops when the app
- lists no pages, realistic sample data, and for eval 10 the exact search for its table, its signed-out and WhoAmI 403 blockers shown
- verbatim, and an identity warning shown before the run goes on to the entity-builder, are now checked against the stored evidence.
- Six synthetic fixtures were added for them, and the Layer-1 smoke tier replays eight fixtures, none failing (#630). The six still
- ungraded each have their reason in the baseline: eval 4's Next/Back navigation (proving that a button moves the step needs data-flow
- analysis), three that a correct check would fail on drift the captured fixtures really show (evals 2 and 13, and the batched-state
- rule), eval 15's (it names an input shape `provision-entities.js` refuses) and eval 6's (a person judges it). Two limits of the
- label check are kept: it counts a label whose empty value holds a comment (`{/* hidden */ null}`), and it does not count one written
- only in character references (`&#84;&#105;…`).
+- **The genpage evals grade 17 of the 23 expectations their coverage baseline recorded as ungraded** (#688); the six still ungraded
+ have their reason in the baseline.
### Fixed
-- **A `--changed-only` apply no longer stops over the bindings of a deployed page it leaves alone — a regression of 2.18.0.** It
- checked the connector and Custom API bindings of every page another page navigates to, as if it might create each one, so a conflict
- on a page it leaves alone (`pages-binding-reference-conflict`) stopped the edit of another page. It creates such a page only when
- the page is missing, so it now leaves out a navigation target its last apply recorded as deployed, and checks the changed pages and
- every other target; a recorded target that was deleted since is checked in the pages step, before it is created again. Each binding
- name is read once per attempt: such a target adds no read of a name a changed page shares, and the names only it states are read in
- a query of their own. A full build checks every page, as before.
-- **Two applies of one app no longer run at the same time in one workspace.** Two overlapping builds of one app each looked for what
- was missing and created it — measured, two generated app icons in the solution. A second `--apply` of the app in that workspace — a
- full build, its data stage or a `--changed-only` run — is now refused at once, before it sends a request: `build-locked`, on stderr
- (`another build may be applying '<app>' in this workspace`), exit 1 and no JSON on stdout. Run it again once the first has finished.
- A lock is taken over only from a build proven no longer running, never for its age. Not covered: builds in two workspaces or on two
- machines, a build of an earlier release (finish those first), and a teardown, download, `/genpage` or `apps.js` command run beside
- an apply.
-- **The pages lock no longer depends on how the app's name is spelled.** On a case-sensitive file system `Contoso_App` and
- `contoso_app` took two locks, so two builds of one app could deploy its pages at once. The lock now ignores case, and the lock file
- earlier releases take is still taken too, so a build of an earlier release that spells the app the same way is still kept out of the
- pages step; one that spells it differently is not.
-- **A column or status reason that Dataverse refuses moments after its new table's create no longer stops the first build.** On a
- Spanish environment such a create was refused with HTTP 400 `0x80040216` ("An unexpected error occurred.") or `0x80090457` ("… does
- not exist"), and the next run succeeded. For a table the run has just created, the build now reads whether the column or status
- reason is there and adopts it when it is, and sends it again only once a usable read proves it missing, within about a minute per
- table; a status reason refused this way is added at the end of the data-model step. Any other refusal, and a refusal for a table
- that already existed, is handled as before; a check that runs out stops the build with the original refusal and says to run the
- build again.
-- **An alternate key over the columns of another key stops the build whatever language the platform answers in** (`0x80060894`).
- Dataverse allows one key per set of columns. When the platform's message was in English, the build skipped such a key as if it already
- existed — it was never created, and verification then reported it missing — and when the message was in another language it stopped
- with the platform's raw error. That is the language of the platform's message, not of the build or the environment: an environment
- whose only language is Spanish answered in English. The build now reads the table's keys after that refusal: it skips the key only
- when the key over those columns is the declared one, and otherwise stops, naming the existing key and its columns and what to do —
- declare that key's name or delete it if it is a leftover, keep one of two keys the spec declares over the same columns, or first
- reconcile a key whose columns are not those the spec declares for it. When the read cannot tell, the build stops with the platform's
- error.
-- **A name that is also a built-in JavaScript property name works like any other name.** `__proto__`, `constructor`, `toString`,
- `hasOwnProperty` and the like can name a dashboard, a persona, a business process flow or a status reason, and `constructor` a page
- key. A dashboard called `__proto__` in the navigation stopped the app step; a new app whose navigation held a page keyed `constructor`
- stopped at the pages step, after the app was created; a persona called `__proto__` named by a flow's or a form's security roles
- stopped the security phase; a sample record could be created with the default status when such a status reason's value had not been
- captured; and such names were left out of the build result and the changed-only snapshot. The App Spec check and the provisioning
- input check refuse a column type such as `constructor` or `toString` as unknown, and the App Spec check reports a form whose table is
- called `constructor` or `__proto__` instead of stopping with a TypeError.
-- **A generated page whose default export is a generic arrow function is accepted.** `export default <T,>(props: Props<T>) => …` —
- with a constraint, a `const` type parameter, a default or a return type — compiles, but `/genpage`'s worker-output check and
- `/app-builder`'s page promotion refused it as having "no complete default export". A default export that TypeScript reads as a JSX
- element (`export default <div/>`, or `<T>(x) => x` in a `.tsx` file) is still refused, and so is a generic arrow cut off before its
- body — now an `async` one too, which was let through when cut inside its type parameters, right after a return type that is itself a
- function type, or with no body after its arrow. Two rare return types that TypeScript parses are refused, and so are their `async`
- forms, which 2.18.0 let through: a mapped type whose key type is in parentheses inside a parenthesised return type
- (`(p): ({ [K in (keyof T)]: boolean }) => …`), and a function type whose parameter has a computed key starting with a regular
- expression and whose own return type starts with `|`. Write the key type without its parentheses or drop the leading `|`, or name
- the type with a type alias. A page cut off right after a function-type return type whose parameter's default value holds a generic
- call (`({ a = f<T, U>() }) => R`) passes this check; the deploy compile refuses it.
-- **The stop for a page manifest whose publication could not be confirmed says what the next build does.** It said that build writes
- the manifest again by its id; that build keeps the published copy when the copy already holds the content, and otherwise writes it
- again by id. The message for a spec web resource and for the generated app icon is unchanged.
-- **An access token is also kept out of the base64 of each of its parts, and out of the bytes the plugin's file writers are given**
- (#757). The base64 of each part of 24 characters or more is taken out like the token — standard and URL-safe, at each of the three
- byte alignments — and what `writeFileSafe`, `appendFileSafe` and `writeFileAtomic` are given as bytes (a Buffer, a typed array or a
- DataView, or a string written as hex, base64 or base64url) is read too, a hit masked with `*` so the file keeps its length. After a
- nested write and the write around it are both refused, the next write keeps the escape context of the last accepted output, so JSON
- written in pieces stays JSON. Still left: a piece shorter than 24 characters, the middle piece of a token written in three or more
- writes, a short piece on the far side of an escape split between two writes, base64 of a piece that is not a whole part, a token
- split between two appends to a file, a token another process obtained, and a file written other than through the plugin's writers.
- pcf's copy of the module takes out the same spellings and keeps the same escape context.
+- **A `--changed-only` apply no longer stops over the bindings of a deployed page it leaves alone**
+ (`pages-binding-reference-conflict`), a regression of 2.18.0.
+- **Two applies of one app no longer run at once in one workspace**: a second `--apply` is refused before any request
+ (`build-locked`, exit 1); rerun once the first finishes. The pages lock now ignores the app name's case.
+- **A new table's column or status reason refused just after the table's create no longer stops the first build**
+ (`0x80040216`, `0x80090457`): it is sent again only once a read proves it missing.
+- **An alternate key over another key's columns (`0x80060894`) stops the build whatever language the platform answers in**, unless
+ the existing key is the declared one; in English it was skipped, never created.
+- **Built-in JavaScript property names (`__proto__`, `constructor`, `toString`, …) work like any other name** for a dashboard,
+ persona, business process flow or status reason, and `constructor` for a page key.
+- **A generated page whose default export is a generic arrow function is accepted.** The `async` forms of two rare return types
+ that 2.18.0 let through are now refused; name such a type with a type alias.
+- The stop for an unconfirmed page manifest now says correctly what the next build does.
+- **A token the process obtained is also kept out of the base64 of each part of 24 or more characters and of bytes given to the
+ plugin's file writers** (#757), unless split between two appends; pcf's copy of the module covers the same spellings.
## [2.18.0]
-The bundled SDK is updated to power-platform-ux a3443479. An app whose sitemap's unique name is not the app's — first-party apps
-such as Sales Hub have one — is now read with its navigation (#746), and a web resource write is confirmed by reading back what was
-published. A new app whose navigation holds only generative pages can now be built, a download carries each page's connector and
-Custom API bindings and much more of each table's schema into the App Spec, and verify checks declared status reasons and alternate
-keys. Supported public Custom APIs are discovered by default. The HTTP client no longer re-sends a publish the customization lock
-refused, a web resource or dashboard that a stopped build left behind is finished by the next build instead of made again, and an
-unknown key in a form's `fieldOptions` is refused instead of ignored. An access token is now also kept out of bytes, out of its
-other spellings, and out of text cut short or split between two writes.
+The bundled SDK is updated to power-platform-ux a3443479.
### Added
-- **A new app whose navigation holds only generative pages is built.** Dataverse refuses to create a sitemap with no entry, so the
- build refused such a spec before writing anything (`app-navigation-empty`), and lint warned about it. The build now creates the
- pages first and then the app, with the pages already in its first sitemap — the order `apps.js create --page-id` uses: the app step
- says `created after its pages`, and the app's create is reported in the app-shell phase. A build that stops between the pages and
- the app is finished by running it again (the pages are adopted by their creation receipts, not created twice), and a teardown
- removes the pages it made. An app that exists is not affected, and its requests are unchanged. A run that cannot create the pages
- first — no pages phase, a `--changed-only` re-upload, a page entry whose page the run does not build — still refuses, and says
- which.
-- **A download writes each generative page's connector and Custom API bindings into the App Spec, and a rebuild writes them back**
- (`pages[].connectorBindings`, `pages[].actionBindings`). A copy of a spec rebuilt in another environment used to create its pages
- without them. A list is written into the spec only whole, and only when every property is a documented one and every value has a
- shape known to be safe — an identifier, a GUID, a plain name or label, a canonical `http(s)` URL with no user-info, query or
- fragment, nothing shaped like a token, and for a Custom API only the ten primitive parameter kinds the runtime binds. Any other list
- is left out of the spec, named by page, list, entry and property (never by a value), and stays on the page; a spec that states one
- is refused. A secret written as plain words in a label cannot be told from a label. A list the spec does not state is not sent, so
- the page keeps its own, and `[]` clears it. When a page already holds what the spec states and this workspace has a usable record
- of its last publish, the build neither writes nor publishes it; a record from before the spec stated the lists counts only once
- the page's published copy is read and found to hold them, and with no usable record the page is published (not written), as an
- unchanged page always was. Before it writes anything (and in a dry run), a build reads the target environment's connection
- references and Custom APIs, and the definition of a custom connector whose operations a binding calls: it stops
- (`pages-binding-reference-conflict`, never retried) at a connection reference of that name for another connector; it names a
- reference or Custom API that is not there, a reference with no connection, an operation the custom connector there does not
- define, and a Custom API of the other kind or bound to another table. A read that fails, a reference row that does not say — in a
- form the build can read — its connector, its connection or its custom connector, and a definition it cannot read are reported as
- not checked, never as compatible; a Custom API row is taken as it reads (a kind it does not state counts as an Action, a table it
- does not state as Global). A throttle wait the run's budget refuses during these reads stops the build before it writes. The
- download's `pageBindings` result and a `NOTE:` on stderr list what the target must already have: the connection references and
- their connections, the Custom APIs and the service resources the bindings point at.
-- **A download keeps much more of each table's schema**: Text format and length, Memo length, Integer range and format, Decimal and
- Double range and precision, Money range, Boolean labels, DateTime format, AutoNumber masks, and the primary name column's length
- (written even at 100, so a fresh build corrects an environment that overrides it; a lookup to that table made before the correction
- keeps the overridden length on its name column) and mask; custom unmanaged Active and Inactive status reasons with their values and
- colors, labelled in the download's authoring language; alternate keys with their columns and labels; solution and global-choice
- display names; dashboard tile sizes; and a table's own unmanaged SVG icon, carried as `external: true` so a teardown of the
- downloaded spec never deletes it. Values equal to the build's defaults are left out. A Money column's precision is kept only when it
- follows the transaction currency, the only kind the build creates; for another source the download says so and leaves it out. A
- detail it cannot read is named on stderr without dropping the column or table or guessing a default, and a status reason with no
- label in the authoring language is named and left out. It is still not a clone: Boolean defaults, column capabilities, BigInt
- ranges, DateTime behavior, script resources, raster, foreign or managed table icons, `roleGrants[]` and `sampleData` are not
- carried. The download reads once more per table for its status reasons, once per column type present (Text, Memo, Integer, Decimal,
- Double, DateTime) and once per icon it captures, plus one lookup of the web-resource table's entity set name before the first icon
- when that name is not yet known.
-- **Verification checks declared status reasons and alternate keys** — `verify-model-app.js`, and the verification a build runs (with
- `--verify`, and on every build that applies a spec's generative pages). A status reason passes when the table holds its label
- under the state the build gives it and at the value the spec pins, if it pins one; a state the answer does not give readably
- fails. An alternate key passes when a key of its name is over exactly its columns, in any order. Each is one read, made only for a
- table that declares one. A build therefore now fails its verification, as it does for any other artifact, when the environment
- holds a declared reason or key differently — a reason renamed in Maker, say, which a rebuild does not rename back — or the read
- fails.
+- **A new app whose navigation holds only generative pages is built** (no longer `app-navigation-empty`).
+- **A download writes a generative page's `pages[].connectorBindings` and `pages[].actionBindings` into the App Spec; a
+ rebuild writes them back**; a conflicting connection reference stops the build (`pages-binding-reference-conflict`).
+- **A download keeps much more table schema** (formats, ranges, status reasons, alternate keys, icons), still not a clone.
+- **Verification checks declared status reasons and alternate keys**; a build now fails verification when the environment holds one
+ differently.
### Changed
-- **The bundled SDK is updated (power-platform-ux a3443479).** What a maker can see of it:
- - a web resource create, and an update that writes content, read the published content back once their publish succeeds (one
- read), and fail with `WEB_RESOURCE_UNVERIFIED`, naming the row (which exists), when the publish fails (nothing is read back then)
- or the content read back is missing, unreadable or not what was written (see Fixed for how a build recovers);
- - a publish is never sent again by the SDK, except when SQL rolled it back as a deadlock victim;
- - an edit of an Active business process flow that the customization lock refuses is sent again, unchanged and with its original
- version check, for up to three minutes of waits, where it failed at once: another maker's edit in between makes it fail rather
- than be overwritten;
- - an app's sitemap is found by the SiteMap component on the app's current layer, not by the app's unique name (see Fixed). The link
- is checked when an app is read — before and after its sitemap is read — and again before the app is written; each check is two
- reads (the app's current layer and its SiteMap component) where a read of an app made one name lookup, and deleting an app also
- reads which apps use its sitemap;
- - an app create whose rollback the customization lock is shown to have refused or interrupted now names the lock as the reason — the
- partial app kept because its rollback deleted nothing, or its removal unconfirmed because the rollback may not have run — and says
- to check, once the lock frees, that its rows exist and are the create's own before removing them; a rollback answer that does not
- show the lock, and other rollback outcomes, read as before.
-- **The HTTP client sends a publish (`PublishXml`, `PublishAllXml`) once.** It sent one again after a 429, 500, 502, 503 or 504 or a
- reset or timed-out connection, up to six sends; measured under the customization lock, a refused publish is no proof that nothing
- changed, and an accepted re-send published old content. A publish is still sent again after a 401 (with a new token) and after a
- 429 of the service protection limits, waited out as before. A deadlock victim is sent again by one layer only — the SDK for its own
- publishes, the plugin for its table and app publishes — after 1, 2 and 4 seconds, four sends at most. pcf's copy of the client
- changes the same way.
-- **Supported public Custom APIs are discovered by default** (`GENPAGE_ENABLE_CUSTOM_API=0` opts out for a run; a missing or
- unreadable flag configuration still turns it off). `list-custom-apis.js` returns, in one request, the public Global APIs and the
- public APIs bound to the page's tables; it leaves out private APIs, APIs bound to a table collection, and APIs with an Entity or
- EntityCollection input or output. It refuses, rather than returning an empty or partial list, an API list, privacy flag, parameter
- or response type, or lookup detail it cannot read — the metadata its eligibility checks need — and an answer or expansion whose
- completeness it cannot prove (a continuation, or the platform's 5,000-row cap); the other fields of an API's own row are not
- checked. This is Custom API discovery, not support for other Dataverse actions and functions. The page builders invoke a Function
- automatically only when its read semantics are known — GET alone does not prove it harmless — and otherwise only on the user's
- action.
-- **A rebuild no longer re-sends a status reason, an alternate key or an Integer format the environment already holds.** It reads a
- table's status reasons once — after every labelled create, so the read cannot strip a later create's other-language labels — and
- inserts only a reason whose value, state, label and color are not all there; it takes the keys from the table read it already
- makes; and it reads an existing Integer column's format before updating it. Anything it cannot prove is written as before. A table
- icon is still assigned and its table published on every build, as before: a saved name does not prove its last publish completed.
-- **Teardown says it keeps the publisher.** It never deletes the solution's publisher (the build reuses one by prefix, and other
- solutions may share it); its closing summary now says so in one line.
-- **The design document shows a role grant the build refuses as refused.** A `roleGrants[]` entry that does not name exactly one
- role (`role` and `roleId` both, or neither) is shown in `model-app-plan.md` and the `write-app-spec-doc.js` warnings in lint's
- words, instead of as privileges the build would add.
-- **Lint warns on `ai.summaries.tables.<table>.prompt`**, a key the build never reads, and names the one that holds a row summary's
- prompt (`instruction`); renaming it does not enable a summary.
-- **The genpage eval's offline Custom API check follows the new contract.** It accepts a lookup passed as `{ entityName, id }` with
- no declared kind when its id is a string the page already holds, and refuses an invented or numeric id, a missing required lookup
- and a parameter discovery did not return; a binding an edited page already held is accepted unchanged only for that same page, and
- the page's earlier copy is judged by the download that saved it, not by another download of that page.
+- **Bundled SDK**: a web resource write is read back once published (`WEB_RESOURCE_UNVERIFIED` if not confirmed).
+- **The HTTP client sends a publish once**; a 401 and a service-protection 429 still retry. pcf's copy matches.
+- **Supported public Custom APIs are discovered by default**; `GENPAGE_ENABLE_CUSTOM_API=0` opts out for a run.
### Fixed
-- **A download of an app whose sitemap's unique name is not the app's no longer fails on its sitemap** (#746). The SDK looked the
- sitemap up by the app's unique name, found none, and the download failed with advice to publish the app, which did not help. The
- sitemap is now the one the app's SiteMap component names. An app with no such component falls back to the sitemap of its name
- only when no other live app uses that sitemap; otherwise the download returns `ok: false` and writes nothing. Deleting an app
- whose sitemap another live app uses is refused, and so is a push of an app that was linked to another sitemap since it was read
- (read it again). A build still adds a sitemap to the spec's solution only when it carries the app's unique name, as the sitemaps
- the build creates do.
-- **A web resource whose publication could not be confirmed is recovered by its id on the next build**, not reused with stale
- content or created a second time. At each place the build writes one — the spec's web resources, the generated app icon and the
- page manifest — it records the row's id in the workspace (`web-resource-unconfirmed.*.json`), adds the row to the solution, and
- stops saying the write is unconfirmed, not lost. The next run on that workspace — or the build's own retry — writes a spec web
- resource's or the icon's content again by that id, publishes it and checks what was published; it writes the page manifest again
- only when the manifest's published copy is not already what the run wants, and otherwise keeps it as it is. Either way the row
- joins the solution and the record is cleared, and pages already created are adopted, not created twice. A row of that name the
- record does not hold is reused as before, and a recorded id now under another name, or a recorded name now under another id,
- stops recovery without touching the other row. When the record cannot be saved, the build does not retry on its own. The
- workspace-reset advice keeps these records. Builds that share a workspace keep each other's entries: each change is made under a
- short lock to the record as it is then, and a clear removes only the write its build verified, so a later unconfirmed write of the
- same row stays for the next run. A note is not made when another build has meanwhile recorded another row under that name, or holds
- the lock for more than about a second; that is said once, as when the record cannot be saved. Not covered: a process killed while
- the SDK publishes, and another workspace.
-- **A dashboard a build created and then stopped before adding to the app's solution joins the solution on the next build.** A build
- killed between the create and the add, one whose create's answer was lost, or one whose add and undo both failed left a row outside
- the solution. The next build reused that row without adding it to the solution — or created a second dashboard if its name lookup
- missed the row — and teardown kept it. The build now records the id it creates the dashboard with (`dashboard-creation.*.json`)
- before the create; the next build reads that id in the saved layer and adds the same dashboard to the solution. Anything it cannot
- prove — another kind of row, a rename, both the sent and the reported id answering, an add refused — stops the step with nothing
- added, deleted or created, and it never asks to delete a dashboard that may be another app's. The record never adopts a namesake,
- teardown never reads it, and the workspace-reset advice keeps it. Builds that share a workspace keep each other's entries: each
- change is made under a short lock to the record as it is then and compares both ids. When recovery reads every recorded id as absent
- and its clear then finds that another build changed the entry, it stops before creating a dashboard and asks for another run. A note
- refused because another build changed the entry or held the lock for more than about a second is said once, and that build goes on
- without the record. A first build and an unchanged rebuild send what they sent before. Not covered: a dashboard created before this
- release or from another workspace, and an entry another build cleared after this build read it (the lock covers the record, not two
- builds' dashboard steps).
-- **An unknown key in a form's `fieldOptions` entry is refused instead of ignored.** A misspelling such as `readOnlyy` or `colSpan`
- passed validation and was dropped by the build, so the option was never applied. Lint, a dry run and a build now refuse it before
- any write, naming the form, table, field and key, the option it most likely meant, and the keys an entry takes (`readOnly`,
- `hidden`, `after`, `colspan`, `rowspan`); an entry takes no `name`, because its key names the field. A spec an earlier release
- built with such a key can still be torn down and previewed, and `verify-model-app.js` verifies it with a warning.
-- **A Custom API with a lookup parameter is no longer bound in a way the runtime drops.** Discovery declared a lookup as
- `EntityReference`, a kind the runtime does not take, so it dropped the whole binding. A lookup is now passed as
- `{ entityName, id }` and kept out of the declared kinds; its name, whether it is required and its table are kept for the author in
- a separate `lookupParameters` list, which is never written to the page.
-- **A teardown run again no longer reports what was already gone as deleted.** A default-view reset with no default view, a
- relationship the SDK does not find, a table its read did not list and a global choice answered 404 now read `(not found)` and are
- counted so. In any teardown, a relationship from a table to itself, which its table's delete takes with it, now reads
- `(not found)` on its own step. The deletes sent and the exit status are unchanged.
-- **A download no longer carries the relationship a File or Image column brings** (`FileAttachment_<table>_<column>`), nor warns
- that its name lacks the publisher prefix, nor reads the `fileattachment` table for it: the column makes it again on a rebuild.
- Other relationships of those tables are kept.
-- **An access token the process obtained is also kept out of bytes, out of its other spellings, and out of text cut short or split
- between two writes.** Bytes a script writes to stdout or stderr (a Buffer, or text written as base64 or hex) are read too, and a
- token there is masked with `*` byte for byte, so framed output keeps its length. The token's base64 (standard and URL-safe),
- percent-encoded and HTML spellings are taken out like the token itself. A piece of the token of 24 characters or more is taken out
- where `util.inspect`'s `... N more characters` or an ellipsis cut the text, at the end of a write that begins the token, and at the
- start of one that ends it; an escape split between two writes stays whole, so JSON written in two pieces is still JSON. Still left:
- a piece shorter than 24 characters, the middle piece of a token written in three or more writes, a piece shorter than 24 characters
- on the far side of an escape split between two writes, base64 of a part of the token, and bytes written to a file. pcf's copy of
- the module changes the same way.
-- The capabilities document no longer says that a download leaves `relationships[]` out (#567).
-- **A rebuild no longer stops at something that already exists when the platform answers in another language, nor at a 1:N
- relationship it did not see before creating it.** The build read only English words in an "already exists" answer, and the platform
- can word that answer in the caller's language: on a Spanish environment the refusal of an alternate key the build could not prove
- from its table read came back in Spanish, and the data-model phase stopped. A status reason, a column of a table whose columns could
- not be read, or a table found only after its create stopped the same way wherever its refusal was worded in another language (on
- that environment those came back in English). Each of those creates now also recognises the answer by its error code, which is the
- same in every language (`0x80060893` key, `0x80044310` status reason, `0x80047013`/`0x80060304` column,
- `0x80044363`/`0x8009050d`/`0x8004700b` table); a table is still reused only when it is read back. The create of an existing 1:N
- relationship was answered `0x80072551` ("NavigationPropertyName … is not unique within an entity"), which no release recognised, so
- a 1:N the build did not see before creating it stopped the build in every language. The build now reads that relationship and reuses
- it only when the read proves it is the declared one; another relationship, or one the read cannot prove, still stops the build (the
- reference's code for a taken relationship name, `0x8004432B`, leads to the same read). The codes add to the existing rules — a 409
- and the English wording are still recognised whatever code the answer carries — and a code of another create, a generic code or a
- code the message only quotes does not count by itself.
-- **Teardown removes a published app whose navigation names a sitemap that no longer exists, once it reaches the app.** Before 2.18.0,
- tearing down one app could delete a sitemap another app shared, leaving that app's SiteMap component pointing at nothing. 2.17.0
- then deleted such an app on its own (no sitemap had the app's name); the component-aware delete in 2.18.0 refused it with "… was not
- returned by the unpublished-aware read … Retry.", which no retry could pass. Teardown now reads the app's row version, proves that
- sitemap gone — by its id, in the published and the saved layer, with no other app's navigation naming it and the link unchanged —
- and deletes the app on its own: the delete is conditioned on that version and touches no sitemap, and the app is then read back
- gone. When it cannot prove that, or when the app was never published, it refuses with what it found and asks you to delete the app
- in Power Apps and run the teardown again; when the app changed while it was proving it, it deletes nothing and asks you to run the
- teardown again. An app with live generative pages still stops earlier, at the page check, because its pages are proven from the
- navigation that is gone; delete such an app in Power Apps, then run the teardown again.
+- **A download of an app whose sitemap's unique name is not the app's no longer fails on its sitemap** (#746).
+- **A web resource or dashboard a stopped build left behind is finished by the workspace's next build**
+ (`web-resource-unconfirmed.*.json`, `dashboard-creation.*.json`).
+- **An unknown key in a form's `fieldOptions` entry is refused instead of ignored.**
+- **A Custom API lookup parameter is passed as `{ entityName, id }`.**
+- **A token the process obtained is also kept out of bytes written to stdout or stderr, its base64, percent-encoded and HTML
+ spellings, and pieces of 24 or more characters cut by an ellipsis or split between two writes**; pcf's module copy matches.
+- **A rebuild no longer stops at something that already exists when answered in another language, nor at an unseen 1:N
+ relationship** (`0x80072551`).
+- **Teardown removes a published app whose navigation names a sitemap that no longer exists.**
## [2.17.0]
-The bundled SDK is updated to power-platform-ux d603c799. Dashboard tiles the spec does not size now show their charts and lists, a
-download keeps File and Image columns and a table's plural, and an alternate key in several languages over a new table's name column
-no longer stops the first build. A relationship is reused or verified only when the environment states its whole identity, an import
-refused because another import or a publish was running is sent again when its job proves nothing started, and the five minutes a run
-allows itself for a throttled service now bound all of its waiting. An access token is kept out of everything a script writes, and a
-large result is no longer cut short on Linux and macOS. `--verify` settles a form's captions in another language from one translation
-export and puts its warnings in its result JSON, and lint no longer calls an app with no personas administrator-only.
-
-### Added
-
-- **A cross-feature regression matrix.** One App Spec with every feature an offline fake can model faithfully (all column types, a
- Customer column, a global choice, status reasons, an alternate key, 1:N, self and N:N relationships, views, a chart, Main, Quick
- Create and Quick View forms, a dashboard, web resources, commands, a generative page, navigation, app settings, sample data, a
- persona and a role grant) is built, rebuilt unchanged, downloaded, verified and torn down over the bundled SDK and a stateful fake
- Dataverse that refuses every read it does not model and applies every query option it accepts. Every phase's writes and publishes
- are pinned, its reads are under a budget, the download is compared with the authored spec, and every phase is proven to leave the
- content of everything that was already in the environment as it was. Beside it, tests pin that dry runs and the teardown preview
- write nothing, downloads are stable, a rebuild without `--publish`, rebuilding a downloaded spec in place, verify naming what was
- deleted in Maker and a rebuild restoring it, a build or a teardown that fails part way finishing when run again, and a teardown of a
- downloaded spec keeping every table, relationship, global choice and row. The three files take about 7–12 s each.
+The bundled SDK is updated to power-platform-ux d603c799.
### Changed
-- **The bundled SDK is updated (power-platform-ux d603c799).** What a maker can see of it:
- - an app's header write carries only the texts that changed: an edit of the description does not send the name again (and the
- reverse), and a routing-description edit sends neither text — another writer's unpublished description is no longer sent again;
- - a row-summary lookup that answers something that cannot be read as a list of rows is an error: a first row that is no row, or a
- template row without a GUID id, stops the build (it used to read as "no row summary yet" and publish a model, or as "no
- template"), and teardown says the lookup failed instead of reporting "nothing to remove";
- - the Command Designer change merged since ccf2c1a1 does not reach the plugin: the commands phase writes what it wrote. The SDK's
- PCF control registration, which the plugins never called, is no longer in the bundle.
-- **A name or description that is localized (or otherwise not plain text) holds back only its own edit.** The other text and an
- `app.aiDescription` are now applied and written alone, where one such text held the whole header back and a changed plain text
- beside it was reported as not applied. The text is taken off the app copy before it is pushed, so it is never sent — even when the
- SDK's own read of the header fails, which used to stop the build with `APP_HEADER_NOT_PLAIN_TEXT`.
-- **An environment without the row-summary AI template skips the row summaries on the SDK's answer alone.** The build no longer reads
- the template list a second time before it skips (one warning, nothing written, as before); an answer the SDK cannot read stops the
- build with the SDK's own error, and a throttled or interrupted read is still run again.
-- **Teardown reports a row summary from what the SDK says it did**: `✓ row summary <table> (1 deleted)` when one was removed,
- `⊘ … (not found)` when the table had none (also an environment with no AI skill table), `kept` with the SDK's words when the removal
- or its lookup failed — with no read of the plugin's own.
-- **`verify-model-app.js` puts its warnings in the result JSON, and prints the result as pure ASCII.** Every `WARNING:` line it prints on
- stderr is now also in an optional `warnings` array of the result — the same messages, in the order printed, left out when there is
- none — when the verification passes, fails, or the spec is refused; it changes neither `ok` nor the exit status. A refused spec now
- prints the warnings it also has. A character beyond ASCII in the result (an em dash, a Spanish label) is a `\uXXXX` escape that any
- JSON parser reads back as the original text, so Windows PowerShell 5.1 can no longer garble it. stderr is unchanged.
-- **A new table that no persona and no `roleGrants[]` entry grants a privilege on is a warning** ("no access declared", in lint and in
- the design document's `warnings`); a covering grant satisfies it, and `--strict` fails on it like on any warning.
-- **`write-app-spec-doc.js --env` reads, read-only, the roles the app has associated with it** and lists them beside the privileges the
- spec grants. It finds an app that was saved and never published, matches a role to a persona or a `roleGrants[]` entry by id where
- the spec gives one and otherwise by name as "may be" (role names repeat across business units; every candidate is listed), and says
- "not checked" — never "no roles" — for a refused read or an answer that is no list of roles. It calls an app administrator-only
- only when the environment shows it and no persona gets the app. The command never fails because of the read.
-- **A build that is throttled for more than five minutes in all now stops with `throttle-budget-exhausted`** once the five minutes are
- spent and it has something left to write (it used to finish after waiting out the HTTP client's own re-sends on top of the budget);
- running the same command again later continues from there. See Fixed.
-- **`/genpage`, `/app-builder` and the six `genpage-*` agents say what they are not for**: a generic or standalone React or web app,
- Power Pages, canvas apps, Power Automate, and a request that rules out Power Platform, Dataverse and model-driven apps.
- `/app-builder`'s description lost process detail no request routes on, to stay under GitHub Copilot's 1,024-character limit; every
- capability and trigger phrase stayed.
-- **The routing eval has 35 cases (15 added)** — requests that say outright they are not for Power Platform, a plain web app in the
- stack `/genpage` is written in, a Power Apps code app, and positives that carry a "not" about the other skill — and **reports the
- decision of the agent's first turn beside its grade** (`first turn: … · later: …`; `initial` / `delayed` / `turn` in `--out`). The
- grade is unchanged: the first model-apps skill the agent asks for, at any turn.
-- `references/agent-interaction-contract.md` explains that declaring a tool in both naming schemes makes a host recognize it, not
- deliver it, and a test fails an agent that names `TaskCreate`/`TaskUpdate` without saying what to do when there is no task tool.
-- A download's warning for a failed label read now says which read failed — the table's own, or its columns' — and only what that read
- carries; the table read's warning also says the table's plural is not written.
+- **Bundled SDK (d603c799)**: an app header write sends only changed texts, and an unreadable row-summary lookup is an error. A
+ localized app name or description holds back only its own edit.
+- `verify-model-app.js` also returns its warnings in the result JSON, printed as pure ASCII.
+- Lint warns when no persona or `roleGrants[]` entry grants a new table; `write-app-spec-doc.js --env` lists the app's associated roles.
+- `/genpage`, `/app-builder` and the `genpage-*` agents say what they are not for.
### Fixed
-- **Dashboard tiles show their charts and lists.** A tile the spec did not size was built one row tall, which the app draws as the
- tile's title bar alone. An unsized tile is now one column by 12 rows, the most common height of the platform's own chart and list
- tiles, so two of them share a row; a tile's `colspan` and `rowspan` still win. A rebuild reuses a dashboard that exists and does not
- resize its tiles: re-create one an earlier version built under a new `name`, or resize its tiles in the dashboard designer. The App
- Spec reference said the default was 1x4; it now states the size and how tiles fill the dashboard's two-column grid.
-- **A relationship is no longer taken for the declared one on its name alone.** The build skips the create of an existing relationship
- — and the dry run says `= reuse`, and `verify-model-app.js` passes it — only when the environment's answer states its whole identity:
- schema name, type, both tables and, for a 1:N, the lookup column, for an N:N the intersect table and the column each table has in it.
- An answer that left a part out used to count as "nothing contradicts". Now the build reads the relationship itself and halts, leaving
- it as it is, when that read is incomplete too; the dry run shows `? unknown`; verify fails the check and names what the answer
- lacked. An N:N whose spec names an `intersectEntityName` is refused (`relationship-name-taken`, with the way to reuse it) when the
- relationship under that name sits on another intersect table. Complete answers behave as before.
-- **The five minutes a run allows itself for a throttled service now bound all the waiting it does for a throttle.** The HTTP client's
- own re-sends of a throttled read, publish, delete or column create kept a schedule of their own outside the budget; the client now
- draws every wait it takes after an HTTP 429 from the same budget in the build and the page upload. It waits what `Retry-After` asks,
- counts requests throttled together once, and announces a wait of more than five seconds on stderr. A wait that does not fit is not
- taken: the throttled answer comes back as it came, and the build stops with `throttle-budget-exhausted`, which says what the service
- asked, before its next write. A 5xx, a reset connection and the re-send of a deadlock victim are not throttling and keep their own
- schedule; every other script (and the pcf plugin's copy of the client) waits as it always did.
-- **A refused throttle wait stops the build before it writes again, not only the request.** No later step that would write starts — a
- refused column change set is no longer followed by one request per column — and the build stops with `throttle-budget-exhausted`
- instead of finishing as a success. A step that only reads to find it has nothing to do still runs, so a rebuild that has nothing left
- to write after a refused best-effort read finishes, with the refusal's warning on stderr. A throttled read before an update, or of a
- page an earlier build started creating, that the budget has no room for is the throttle's refusal, not "could not read page" and not
- a conflict that asks the maker to delete a record. The client's stderr line for such a request no longer says to run the same
- command again; after a page upload's create, the result names the page and the command (`--page-id <id>`) that finishes it.
-- **A refused throttle wait no longer leaves a new table's name column at the platform's default length.** The build skipped the
- length update of the next table owed one and forgot it, so a later run could not set it and an alternate key over that column was
- refused for its size on every run. Every owed length is now set whatever the budget has refused; a key waiting for it is made by the
- next run, which the halt asks for.
-- **Verify no longer calls a published dashboard "not published" for a user whose own UI language is the organization's second one.**
- When the published read carries more than one language and the saved and published rows answer the same `@odata.etag`, the two reads
- are compared in everything but their captions; any other difference is still a change. A dashboard saved and not published, a row
- that answers no token, and a base-language user's read are decided as before.
-- **A generative page whose class has a class expression for its base, and one that has a field named `new` before a method, are read
- instead of refused** (2.15.0 refused them with the guess `generic`). Still refused, naming the guess: a function expression or an
- object literal for the base, type arguments after a class expression, more than four class expressions nested in each other's heads,
- and a `new` that no member of a class begins; parenthesise the base, as before.
-- **Lint and the design document no longer call an app administrator-only because `personas[]` is empty** (AB#6770008). A spec that
- authors no role says nothing about who can open an app that already exists — an extension of such an app leaves `personas[]` out on
- purpose — yet lint said the app "opens only for system administrators", steering authors to redefine their existing roles. Both now
- say what the spec authors; a spec that carries what a download writes (`app.uniqueName`, a page or dashboard id) is told the app
- already exists and keeps its roles. The document follows each persona's `appAccess`.
-- A rebuild of an app whose name (or description) is held as one text per language writes a changed description (or name) instead of
- reporting it as not applied.
-- **`solution-settings.js import` sends an import again that the platform refused because another import or a publish was running.**
- The platform answers such an import with HTTP 429 and `0x80071151` ("Cannot start another [Import] because there is a previous
- [Import] running …"), which the retry did not know, so the maker had to run it again by hand. The code alone does not say that nothing
- started, so the refused send's import job is read once, and the import is sent again — after waits of 10, 20, 40 and 60 seconds (or a
- longer `Retry-After`), at most five sends in five minutes, the budget checked again after each wait — only when the job does not exist
- or is finished and its log says the import failed with that error before it processed the solution or any component. A job that
- proves nothing is not sent again: the failure says why and to look the import job up (`importjobs(<id>)` or the solution history)
- before importing again. A resend's output says how each refusal was proven (`importRefusals[].proof`). When the fifth send is refused
- too, the failure no longer says to run the import again; it says what to check first. The retry for the lock codes is unchanged.
-- **`--verify` no longer lists a form's tab and section captions as unverified just because the form read does not return their
- language** (Spanish captions in an English-language organization): they are read from one translation export of the app's solution,
- matched by the id of each tab and section, so a right caption passes and a stale, missing or empty one is reported. The export is one
- request (several seconds, more as the solution grows), made only when such a caption exists, shared by every form of the run and never
- sent twice. When it fails or cannot be read with certainty — its archive must be self-consistent and its labels sheet exactly the
- platform's shape — the captions stay unverified, with the reason, as before.
-- **An alternate key labelled in several languages over a new table's name column and another column no longer stops the first
- build** where the platform makes the name column 850 characters long (HTTP 400 `0x80060895`, "Index size exceeded the size limit of
- 1700 bytes"). For such a key only, the build reads the column's length once (a typed `MaxLength` read, no labels); where the key cannot
- fit beside it but can at the length the spec asks, it is made after the length step, with both labels, instead of in the run after.
- The key's size is counted from its columns as the build creates them (an `AutoNumber` column, like one with no `type`, is created 100
- characters long whatever `maxLength` it carries). Every other key keeps its place. The warnings and the stop
- (`alt-key-name-length-not-set`) now name the platform's measured limit of 1,700 bytes (they said 900) and no longer promise that
- running the build again creates a key: a key proven too large at the asked length is said to be so, with its size and what to change;
- otherwise they say a run again may create it, that this is not certain, and what to compare if it is refused again. They no longer
- suggest labelling the key in one language. The stop's code, retry behaviour and exit status are unchanged.
-- **An access token the process obtained no longer reaches anything a script writes, whatever text carries it.** A service that rejects a
- token may repeat it — whole or by a part, folded onto several lines, with a JSON escape or a backslash left in it — in a diagnostic,
- and a change set refused as a whole is answered HTTP 200, so the token could reach an error message, a warning, the journal or a file.
- Every token the process obtains is now kept out of stdout and stderr (colour output included), what Node prints when an error ends a
- script, the build's journal and status file, the baseline and snapshot, downloads and generated files, and every file of the SDK's
- workspace; the token reads `<token>` and the text around it is unchanged. Answers themselves are never rewritten, so the strict
- `$batch` readers decide a page write's resend on the same bytes as before. A text that could not be checked is not written.
-- **pcf: the push receipt no longer carries the access token** a refused confirmation read quoted, and every file the SDK writes into a
- push's workspace goes through the same guard.
-- **A download keeps File and Image columns.** Both report the Dataverse type "Virtual", so every download left them out without a word
- and a rebuild elsewhere lost them. They now come back typed, with `maxSizeKb` when it is not the build's default (10240 KB) and
- `isPrimaryImage` for a table's primary image. The table's own image and the platform's companion columns are not written, a column of
- another type the App Spec cannot express is named in a warning, and a size read that fails or answers short is reported — per read, and
- per column for a short answer. Only a table with such a column costs a read more (one per type).
-- **A download keeps a table's plural when a rebuild would not derive it**: "Tag Catalog" for "Tag" was left out, so a rebuild into
- another environment named the table "Tags". A plural that is the display name plus "s" is still left out, so the download of an
- ordinary table is unchanged.
-- **A large result or message is no longer cut short on Linux and macOS when a script prints it and exits at once.** Node writes to a
- pipe asynchronously there and `process.exit` did not wait, so an agent could receive a multi-megabyte answer, listing, auth check,
- validation report or error as a text that ended mid-string. Every printer that ends the process — `emitResult`, the printer of an
- uncaught error, each script's own result printer (`check-auth.js`, `dataverse-request.js`, `genpage-plan-provenance.js`,
- `promote-intent-pages.js`, `check-page-files.js`, …), usage errors, last-resort error handlers, the hooks' messages and the warnings
- a script prints right before its result — now makes its writes blocking first. What is printed and every exit status are unchanged,
- and Windows was never affected; as on Windows, a reader that stops reading now holds the script at its last write instead of
- receiving a truncated text.
-- The page-builder worker, the planners and the entity builder no longer tell the agent to call `TaskCreate` with no alternative: a
- host can hand a subagent no task tool, so the agent tracks its task with `TaskCreate`/`TaskUpdate` or `todo` when it has one, and
- otherwise says so and tracks it in plain words; `/genpage` does not treat a worker without a task tool as a failed worker.
-- The routing eval no longer ends a trial before the agent it killed has exited (an `EBUSY` on Windows), and two tests no longer
- assert a time limit that failed on a busy machine (the shared telemetry spawn test, and the test that ending a verify pass's page
- reads does not wait for a read in flight).
+- **Dashboard tiles show their charts and lists**: an unsized tile is now 1 column × 12 rows; a rebuild does not resize existing
+ tiles.
+- A relationship is reused or verified only when the environment states its whole identity; an N:N name on another intersect table
+ is refused (`relationship-name-taken`).
+- All throttle waits share the run's five-minute budget; past it, the build stops with `throttle-budget-exhausted` before its next
+ write — run it again to continue.
+- `solution-settings.js import` resends an import refused with `0x80071151` (another import or publish running) when its job proves
+ nothing started.
+- `--verify` checks localized tab and section captions from one translation export.
+- A multilingual alternate key over a new table's name column no longer stops the first build (`0x80060895`).
+- **An access token the process obtained no longer reaches the text a script writes**: output, the journal, files, the SDK
+ workspace. pcf: the push receipt no longer carries one a refused read quoted, and push-workspace files are guarded too.
+- A download keeps File and Image columns (`maxSizeKb`, `isPrimaryImage`) and a table's plural.
+- Large results are no longer cut short on Linux and macOS.
+- Lint no longer calls an app with no personas administrator-only (AB#6770008).
## [2.16.0]
-The bundled SDK is updated to power-platform-ux ccf2c1a1, and a new table's primary (name) column is now created required when the
-spec says so. The spec gate refuses two values the build used to misread — an `AutoNumber` column without a format and a `required`
-that is not `true`, `false` or `"recommended"` — before anything is written, and `--verify` of an app an earlier release built only
-warns about them. Navigation titles survive a download and rebuild on an environment whose base language is not English. Teardown
-keeps what only a kept table blocks instead of reporting the platform's refusals, and a run cut short removes its temporary folders.
+The bundled SDK is updated to power-platform-ux ccf2c1a1. A new table's primary column is created required when the spec says so,
+and navigation titles survive a download and rebuild in any base language.
### Changed
-- **A download reads the environment's base language** (one more read, made only when the spec on disk pins no `languageCode` and
- `--language-code` — new on `download-model-app.js`, read-time only — is not given) and reads the navigation titles in that
- language. When it cannot establish the language it stops without writing anything (`navigation-language-unknown`) instead of
- guessing 1033: run it again, or pass `--language-code <lcid>`. A language other than the base language given that way must be
- given to the build and to `verify-model-app.js` too, or pinned as the spec's `languageCode`. On a bilingual environment whose base
- language is not 1033, dashboard tile names are read in the base language.
-
-- **The bundled SDK is updated (power-platform-ux ccf2c1a1).** What a maker can see of it:
- - a business process flow edit the flow cannot hold (a binding with no value, `required` on a step that has no slot for it) fails
- with a message instead of reporting success, and a flow's security that names an access level its table cannot grant is
- refused before any role is written;
- - a command bar control copied with another control's id fails the push instead of overwriting that control;
- - a generative page whose source holds text that only looks like an import of `./RuntimeTypes` (in a string, a template or a
- comment) is refused with a message that names that text's line and column;
- - an answer that lacks the rows or the record it should carry is an error, not an empty result;
- - a workspace copy that an interrupted build of an earlier release left with edits it never pushed is refused at its next push
- and asks for the documented reset (a copy without such edits is simply read again);
- - a dashboard tile that hosts a custom control (the Power Apps grid control, say) is still left out of a download, named in its
- warning, and out of `--verify`: the SDK now reads such a tile as a list or a chart, and the plugin tells it apart by its
- control, so it is never written into `dashboards[]` as a plain tile.
-- **An `AutoNumber` column without a usable `autoNumberFormat` is refused when the spec is validated** — by the build and by the
- input gate of `provision-entities.js` that `/genpage` and `/app-builder` go through — before anything is written. The SDK no longer
- creates such a column (it made a plain text column), so the build would have stopped at it after the solution and the tables were
- made. The error names the table and the column and both ways out: a format such as `"C-{SEQNUM:5}"`, or `type: "Text"` for a
- plain text column — which is also what such a column an earlier release built is. A blank format, or one that is not a string, is
- refused the same way. A primary name column without `autoNumberFormat` is still a plain text name column.
-- **A column's — or the primary name column's — `required` must be `true`, `false` or `"recommended"`.** Every other value
- (`"ApplicationRequired"`, `"true"`, `"required"`, `"Recommended"`, `1`, `null`) was read as "not required": a new column was
- created not required, and an existing column was written down to None, demoting one a maker had made Business Required. It is now
- refused at validation, naming the table, the column and the value and what to write instead; leaving `required` out still leaves
- an existing column as it is. Both rules are warnings, not errors, for `verify-model-app.js` — which creates and changes nothing —
- so an app built from a spec an earlier release accepted can still be verified, and teardown still accepts such a spec.
-- **The forms phase writes the order of every Main form it orders, the first of a table included.** The SDK now creates a form with
- no form order (it wrote `Order="0"`), so on the build that creates a table's Main forms the first of them is written once more. A
- rebuild finds every order in place and writes none.
-- **An environment without the row-summary AI template skips the row summaries with one warning.** The SDK now looks the template
- up before it writes anything and refuses an environment that has none (it published a model that named no template and let the
- platform answer). The build confirms that the template list is empty with one read of its own before it skips — a list it
- cannot read as a list of templates stops the build as before — and a throttled or interrupted confirmation read is retried like any
- other read the build makes.
+- **A download reads the environment's base language** for navigation titles: `download-model-app.js --language-code <lcid>` is
+ new, and a language it cannot establish stops it with `navigation-language-unknown`.
+- **Bundled SDK (ccf2c1a1)**: a business process flow edit the flow cannot hold, or a command bar control copied with another
+ control's id, fails instead of passing; an answer missing its rows is an error.
+- **An `AutoNumber` column without a usable `autoNumberFormat` is refused when the spec is validated**: give a format such as
+ `"C-{SEQNUM:5}"`, or use `type: "Text"`.
+- **A column's `required` must be `true`, `false` or `"recommended"`**; any other value is refused (`verify-model-app.js` only
+ warns).
+- The forms phase writes the order of every Main form it orders; an environment without the row-summary AI template skips row
+ summaries with one warning.
### Fixed
-- **A `required` on a new table's primary (name) column is applied when the table is created.** The create sent the name column as
- not required — a plain text name column is stored not required whatever the create asks — and the build still reported
- `required <table>.<column> (applied on create)`; only a rebuild set it. The table's create now asks for the level, the SDK reads
- it back and sets it with one update, and the build says it was applied only when the SDK confirms it for a table the build saw
- created. When the level cannot be confirmed the table still exists: the build stops once (or, for a table found after the answer
- to its create was lost, or whose columns could not be read, warns and goes on), and running it again finds the table and sets the
- level. The table is never created twice.
-- **Navigation titles survive a download and rebuild on an environment whose base language is not 1033** (a Spanish-only one, say).
- The download read every title in 1033, a language such an environment does not hold, so it wrote an empty `label`/`title` for every
- area, group and entry, and a rebuild of that spec cleared the titles; on a bilingual environment with another base language it
- wrote the English titles, which a rebuild then wrote over the base-language ones. The download now reads them in the language a
- rebuild resolves (see Changed).
-- **A rebuild never clears a navigation title the spec does not state.** An area or a group without a title in the spec keeps the
- title it has, and so does an entry, unless the baseline shows the spec used to state one (then the title is removed, as before); a
- stated title is applied as before. An empty group (or area) of a spec an earlier release wrote is matched to the environment's one
- empty group; where more than one could be meant, none is paired by position and the build names each title it does not keep.
-- **Teardown no longer reports a row summary it did not delete.** A table with none reads `⊘ row summary <table> (not found)`
- instead of `✓ … (1 deleted)`, and the closing counts follow. A lookup or a removal that fails is said on the step's line and
- counted as kept, never as a deletion; it still does not fail the teardown.
-- **Teardown keeps what only a kept table blocks, instead of reporting the platform's refusals.** When a business rule could not be
- deleted, teardown keeps its table until a re-run (the rule's activated copy can only be deleted while the table exists), but it
- still tried the deletes that follow the tables — the table's icon web resource and a global choice one of its columns binds,
- which the platform refuses while the table exists, and a relationship from the table to itself, which it refuses while the table
- still holds something that refers to its lookup — so one failure was reported as up to four. Those steps are
- now kept with the table, each a `(kept — …)` skip that names it, and the re-run deletes them once the table goes. The run still
- ends as a failure and keeps the solution. The dependency is read from the spec, so an icon or a binding made by hand in the
- environment is still tried and refused as before. A rule whose deactivation succeeded and whose delete failed stays deactivated
- until the re-run.
-- **A run cut short by `process.exit` or an error nothing catches removes the workspaces it made and did not lend, and then the
- plugin's temporary folder (`power-platform-skills-model-apps`) when it is empty**, instead of leaving both for the next run. A
- POSIX signal still ends a run as before, and the next run's sweep removes what it left.
-- The plan document shows a `"recommended"` column as recommended, not required.
-- The test suite no longer leaves `plugins/model-apps/.maker-workspace` behind, and `scripts/run-tests.js` fails a run that makes
- one there (removing it only when it is empty).
+- A `required` primary name column is applied when its table is created.
+- Navigation titles survive a download and rebuild when the base language is not 1033, and a rebuild never clears a title the spec
+ does not state unless the baseline shows the spec used to state one.
+- Teardown no longer reports a row summary it did not delete, and keeps what only a kept table blocks instead of reporting the
+ platform's refusals.
+- A run ended by `process.exit` or an uncaught error removes the workspaces it made and did not lend, then the plugin's temporary
+ folder (`power-platform-skills-model-apps`) if empty; after a POSIX signal, the next run's sweep does.
+- The plan shows a `"recommended"` column as recommended, and the test suite leaves no `.maker-workspace` behind.
## [2.15.0]
-Generative pages, the environment's apps and tables, connections, connector metadata and deployment settings now go through the
-bundled SDK instead of the PAC CLI, so `az` is needed for every Dataverse call, pages included. `pac` is left for signing in and
-choosing the environment, a tabular connector's tables and their columns, and the fallbacks where the SDK has no route or refuses
-— connections, connector metadata and deployment settings — which say so in their output. A page can be created before the app
-that holds it, a rebuild publishes only the pages that changed, and teardown finds a page that was never published. A rebuild now
-also applies a changed app name and description and a business process flow's stage edits, the build's automatic retry follows what
-the service answered, not the names a maker chose, and the next run releases the pages lock and removes the temporary folders a
-killed run leaves behind.
+Most `pac` commands move to the bundled SDK, which needs `az`.
### Added
-- **`scripts/apps.js list` and `scripts/list-tables.js`: the environment's apps and tables through the bundled SDK, in place of
- `pac model list` and `pac model list-tables`.** `apps.js list` prints every model-driven app, drafts included, with its id, name,
- unique name, description and two facts, apart: whether it is published (users can open it) and whether it has unpublished changes
- — `pac model list`'s "(Saved - Not Published)" was neither (a managed app an import brought in carried it although it is live; a
- published app with a saved edit did not). Its name and description are the app's saved layer's, what a maker sees in the designer:
- a published app with a rename not yet published is listed by its new name, which users see only after a publish (`pac model list`
- printed the published name). `list-tables.js` prints the tables a comma-separated `--search` names — the same tables
- as `pac model list-tables` — with `--exact`, only those whose logical name is a
- term, listing the terms that have no table, and with `--type custom|standard|all` only the custom or the standard ones.
-- **`scripts/apps.js create` makes an app that opens on generative pages, in place of `pac model create`.** It takes the pages
- (`--page-id`, required: Dataverse refuses an app whose navigation group is empty, and an empty group is what `pac model create`
- made), as one area "Main" and one group "Pages" with a sub-area per page, pins the default public view of each table the pages
- read, adds the app and its sitemap to the solution, and publishes only with `--publish`. Every check — no page, a page or a
- solution that does not exist, a managed solution, a unique name already taken — refuses before anything is written, and says why;
- a run that fails after the push began reads the platform back and says what is actually left. Titles are written in the
- environment's base language, the icon is the system's default one, and the app gets the new header and navigation setting, which
- `pac model create` did not write.
-- **`scripts/genpage.js`: the page verbs the skills ran through `pac model genpage` — `list`, `download`, `types` (the type
- generator), `add-to-app` — and two they had no verb for, `remove-from-app` and `delete`.** One pure-ASCII JSON line per command,
- exit 0 or 1; a mistake in the command line is a usage error with nothing on stdout. `list` shows every page of the environment,
- drafts included (with `--app-id`, an app's published navigation, or its saved one with `--include-unpublished`). `download` reads
- every page before it writes, so a page that cannot be read leaves the folder as it was, and writes the page's own bytes — no byte
- order mark, no line break appended, no `page.js`, all of which `pac` wrote; `--app-id` is optional. `types` is the SDK's
- RuntimeTypes generator, so its file is not byte for byte `pac`'s; a table the environment does not have is
- `GENPAGE_TABLE_NOT_FOUND`. `add-to-app` puts the page in an app's navigation with the default views of its tables, publishes the
- app and checks the page shows in it; run again, it finishes a placement that was saved and never published. `remove-from-app`
- takes the entry out, publishes the app (an app that was never published too, with a warning) and checks the page is gone, and
- refuses to leave an app with no navigation entry unless `--allow-empty-navigation` says that is meant. Neither adds anything else
- to the app: the SDK's push of an app also adds every active Main form, public view and chart of each table its navigation opens —
- those a maker took out of the app included — so the plugin limits that push to the views the edit pins. `delete` says what it
- would remove — the page, its file rows, its conversation messages (`GENPAGE_DELETE_NOT_CONFIRMED`) — and removes it, with its
- conversation, only when `--allow-destructive` says that is meant; it refuses while any app's navigation, published or saved, names
- the page, naming the apps (`GENPAGE_IN_APP`). The build's and the upload's messages that sent you to Maker or to a `pac` command
- (a page another app holds, a page that could not be placed) now print the `genpage.js` command that does it.
-- **`scripts/connector.js` and `scripts/solution-settings.js`, in place of the `pac model genpage` connector verbs and
- `pac solution create-settings` / `import --settings-file`.** `connector.js` lists a connector's operations, and reads one
- operation's parameters and response or a tabular connector's table columns. `solution-settings.js template` writes the
- deployment-settings file for a solution or a package, in `pac`'s own format, so settings files you already have keep working;
- `import` imports a package and applies the settings in the same import. Both print one JSON line that says whether the bundled SDK
- or `pac` answered.
+- `scripts/apps.js list`/`create` and `scripts/list-tables.js` (`--search`, `--exact`, `--type`) replace
+ `pac model list`/`create`/`list-tables`; `create` needs `--page-id`; `--publish` publishes.
+- `scripts/genpage.js` replaces `pac model genpage`: `list` (`--include-unpublished`), `download`, `types`
+ (`GENPAGE_TABLE_NOT_FOUND`), `add-to-app`, and new `remove-from-app` (`--allow-empty-navigation`) and `delete`
+ (`--allow-destructive`; `GENPAGE_DELETE_NOT_CONFIRMED`, `GENPAGE_IN_APP`).
+- `scripts/connector.js` (`schema --dataset --table` still asks `pac`) and `scripts/solution-settings.js` (`template`,
+ `import`) replace `pac`'s connector and settings commands.
### Changed
-- **Every generative-page operation goes through the SDK** (`scripts/lib/genpage-sdk.js`): `genpage-upload.js`, the build's pages
- phase, verify, download and teardown. No script runs a page verb of `pac model genpage` any more, so there is no `pac` process to
- time out or parse for a page (`POWER_PLATFORM_SKILLS_PAC_TIMEOUT_MS` is no longer read), and **`az` is now needed to deploy a
- page**, not only to create entities. Verify reads page code in-process, four pages at a time; a command that could not remove the
- temporary folder it read page source into says so instead of reporting success.
-- **A page is compiled by the bundled SDK, with the TypeScript 5.8.3 compiler the plugin now ships**, in place of the transpile `pac`
- made when it uploaded one. The compiler is the official `typescript` package's `lib/typescript.js`, minified and brotli-compressed
- (`scripts/vendor/typescript/`, ~0.8 MB, with its Apache-2.0 license and notices): the SDK compiles a page itself whenever a push
- changes it and accepts only the TypeScript version the maker portal compiles with, and a plugin install has no `node_modules`. It is
- unpacked and run (about 0.2 s) only when a page is compiled, and its bytes are checked against the recorded hash first. As in the
- portal this is a transpile, not a type check — a page with a type error still deploys — and a page that does not parse, has no
- default export or imports a value `RuntimeTypes` does not hold is refused by the SDK before anything is written.
-- **A page write is one atomic change set, and says what it did and nothing more.** A create mints its id first, so an unknown
- outcome is settled by reading that id (sent once more under the same id only when nothing landed: never a second page); "nothing
- was written" is said only when the SDK refused the write before sending it or the service answered 4xx, and any other failure at
- or after the send is `unknown`, the error carrying `outcome` and `pageId`. A write the service throttles (HTTP 429) has written
- nothing: it is waited out and sent again — up to six sends, on the HTTP client's schedule or, when the answer's `Retry-After` asks
- for longer, for the whole of that wait, as long as it fits the run's five-minute throttle budget — and an edited page that someone
- saved during the wait is refused, not overwritten; one that outlasts the waits ends the write, and the build runs it again like
- any transient failure, within the same budget. A change set the service refuses as a whole is read by the part that failed — a 429
- is waited out, a 400, 403 or 404 is final — but only when the answer is complete and every part in it is accounted for; any other
- answer proves nothing and stays `unknown`. An update writes only what differs, so leaving out `--model`, `--name` or
- `--data-sources` keeps the page's own (`pac` blanked the model and renamed the page to its navigation title; 2.14.0 re-sent both
- and warned when it could not), and a page whose content is unchanged is written nowhere and records no prompt (the upload script
- still publishes it).
-- **A page is stored exactly as written**: nothing is appended, one leading BOM is dropped, a file that is not UTF-8 is refused, and
- a `"` in a page name is kept (`genpage-upload.js` no longer refuses it; spec-lint still warns about one, and now says why: a page
- an earlier release created holds it as `\"` until a build rewrites its name).
-- **`genpage-upload.js` creates a page without `--app-id`** — a page needs no app, and a new app cannot be created empty, so the
- first page comes first (`genpage-base.js record` takes a page with no app too). Such a create adds the page to no app and its base
- marker names none; the first update that names the app the page was placed in goes ahead once that app's navigation lists the
- page. `--add-to-sitemap` and updates still need `--app-id`, and with it the default views of the tables the page reads are pinned
- into the app (as `pac` did). The entry `--add-to-sitemap` adds to the navigation is titled in the environment's base language, as
- `genpage.js add-to-app` titles it. A page it created but could not finish (its publish failed, or the placement it was asked for
- did) is finished by running the same command again with `--page-id` added. A failed write reports the page's id, `outcome` and the
- SDK's `code`, and a placement that was saved with only its app publish left is reported as that.
-- **A rebuild does not publish a page that is already up to date.** 2.14.0 re-uploaded and re-published every page of a full rebuild
- (through `pac`), a `PublishXml` of several seconds per page each time. A page that already holds what the spec asks for is not
- written, but the server cannot say whether an earlier run's publish of it finished, so the build keeps a record in its workspace
- (`page-published.<hash>.json`) of the content each page was published with and of the versions of its file rows and of the page's
- own row, which holds its name. The versions are recorded only once the build has read the page's published copy back — its source,
- settings and compiled output — between two reads of them that agree, so a page another writer published over in the moments after
- the build's own publish is not recorded as the build's. A page's publish is skipped only while it holds that content and its rows,
- read now, are exactly the recorded set at the recorded versions. Anything else publishes: a new or changed page, one saved by a
- run whose publish failed or was not proven, one changed or published from another workspace, machine or Maker since, a failed read
- of the versions, a missing or damaged record (so the first build in a workspace publishes each page once). What the proof cannot
- see is a file other than the source, the settings and the compiled output — the first prompt, say — changed and published from
- elsewhere just before the build first reads the versions.
-- **A create the build could not account for is remembered, and what it finds is checked against what was sent.** The build writes
- down the id it minted for a page, with its name and a hash of the source it sends (a `pending` record in the workspace), before it
- sends the create. If the answer never arrived and the page could not be read back, the next build resumes that create under the
- same id — never a second page — and adopts a page it finds only when it holds a name and a source a create under the id sent;
- anything else is a conflict. A record is kept until evidence settles it (the page adopted, or deleted by teardown), never because
- a listing did not show the page, so a page that lands late is reported and found by teardown, and teardown's `--clear-workspace`
- refuses while one is unsettled. A request still in flight when its page is deleted can make the page again, and nothing names it
- (no client can cancel one). A halt that asks for a manual workspace reset now says to keep the `page-ownership.*.json` records
- beside `last-applied.json` and `destructive-approval.json`: they are the only trace of a page that may still land.
-- **The build pins the default views of the tables its pages read** into the app's components once the pages are written (`pac` did
- this on every upload): one app operation for all of them, which adds those views and nothing else (the SDK's push of an app would
- also put back every active Main form, public view and chart of the tables its navigation opens, those a maker took out of the app
- included), nothing written when every view is already pinned, and a failure to pin is a warning.
-- **Waiting out a throttled service has one budget per run: five minutes.** The page writes and the build's own re-runs of a phase
- share it. The wait the service asks for (`Retry-After`) is honoured whole and carried from a page write to the build, a wait of
- more than five seconds is announced on stderr, and a wait that does not fit stops the build with a `throttle-budget-exhausted`
- halt that says what the service asked: running the same command again later continues. The HTTP client's own re-sends of a
- throttled read or publish keep their own schedule and are not counted in it.
-- **Connections, connector metadata and deployment settings are read through the bundled SDK**, with your Azure CLI sign-in
- (connections and connector metadata also use an Azure CLI token for the Power Apps service, sent only to that service's hosts and
- never printed). `pac` is asked only where the SDK has
- no route or refuses: an environment in the Test cloud or any other cloud the SDK does not read connections in (these go to `pac`
- with no SDK attempt first), a token the service refused (401 or 403), an environment the service does not tie to the organization,
- a service that has been switched off, a connector definition the SDK does not project, a package whose staging answer the SDK
- cannot read (`template` also when the platform will not stage it; an import it will not stage fails, naming the dependencies it
- is missing, and is not retried by `pac`), a settings file that uses a feature only `pac` applies, no Azure CLI token for the
- Power Apps service, a settings template of a package with no `--env` (nothing to stage it in, so `pac` reads the zip offline), and
- a tabular connector's table columns (`connector.js schema --dataset --table`; the SDK reads them only through a client the plugin
- cannot build). The output says so (`connectionsSource` and `connectionsFallback` in `list-connections.js`; `source` and
- `fallback` in the others; the last two of these say `source: "pac"` and carry no `fallback`); any other failure is reported with
- the SDK's own code and never answered by `pac`. A tabular connector's tables are still listed by `pac` itself; no script does it.
- A connector whose Swagger puts parameters on a path item now reads through the SDK, with them merged into each operation's own.
-- **A `pac` fallback is time-bounded and prints only why it failed.** A read gets three minutes and an import an hour (fixed;
- `pac connection list` had no limit in 2.14.0). A call that runs out of time ends `pac` and the processes in its tree and says what
- it confirmed — "`pac` and every process that held its output were stopped", or that something `pac` started "may still be running"
- — and a failure shows `pac`'s error without its sign-in banner and version lines. The folder a fallback works in (the package the
- SDK exported, `pac`'s template, a copy of the settings) is removed with the retries a Windows lock needs; one that stays is a
- warning that names it, with the files in it that can hold values emptied first (`emptied, so it keeps no value`, or
- `it could not be emptied either, so it may still hold values`). What the SDK warned of before it refused — a staged copy it could
- not delete — stays in `warnings` whether `pac` then succeeds or fails, and also when `template`'s final write of `--out` fails.
-- **`list-connections.js` checks the environment URL before it runs anything, and prints one JSON line for every failure**, as
- `connector.js` and `solution-settings.js` do: `{ ok: false, error, code }` in pure ASCII on stdout, the message still on stderr,
- exit 1 (in 2.14.0 a failure was a message on stderr alone). `code` is there when the error has one (the SDK's errors do; a `pac`
- failure and a bad environment URL do not). A `pac` listing that fails after the SDK refused carries the SDK's reason as
- `connectionsFallback`, as a listing `pac` gave does. A usage error (no URL, an unknown flag) is still the problem on stderr alone.
-- **The `solution-settings.js import` defaults are `pac`'s**: nothing unmanaged is overwritten, no workflows or plug-ins are
- activated, nothing is published afterwards. The solution actions that can run for minutes (`ExportSolution`, `StageSolution`,
- `ImportSolution`) get an hour and are sent once: a gateway's 502, 504 or 401 for an import the platform accepted is not answered
- with a second import. The one exception is an import the platform refused to start because a publish or another import holds the
- environment's customization lock (HTTP 429 with one of the codes `0x8004F061` to `0x8004F064` and `0x8004F067`): it is sent again
- under a new import job id once `importjobs(<id>)` of the refused send answers 404, which proves it never started, after 10, 20, 40
- and 60 seconds or the longer `Retry-After` the platform asks for — at most five sends within five minutes of the first refusal,
- never one early — and the output names the job that ran (`importJobId`), `importAttempts` and each refused send (`importRefusals`).
- Every other answer is sent once, the solution-concurrency `0x80071151` included. That is the answer measured for an import that met
- another import or a publish (its words begin "Cannot start the requested operation [Import]"), and that import's job existed by
- then, so nothing proves it did not start: the maker runs it again once the other operation has finished. A failed import names its
- job and, when the request was sent, the reason the job's log gives. When `pac` does the import it is given a copy of the settings
- the run read, not the file's path, so a file saved while the package stages is neither applied nor printed; the copy is in a folder
- only the current user can read, checked before a byte is written (`PAC_SETTINGS_COPY_FAILED` otherwise), and is removed on every
- outcome and when the run is ended by Ctrl+C, a closed terminal or an uncaught error — a cancelled run still ends as cancelled (on
- Windows with `0xC000013A`, not 1).
- `template` does not replace an existing `--out` file unless `--force` is given (`pac` replaced it silently, and every value
- already filled in with it) — not even one that appears while it works — so it needs a file system that can make a hard link (NTFS,
- ext4, APFS): on one that cannot (a FAT or exFAT volume, some network shares) it refuses with `IO_ERROR` and says that `--force`,
- which needs no link, writes there. If the temporary name it wrote the file under cannot be removed, the run still succeeds, with a
- warning that names the leftover (the next run refuses the file as a hard link).
-- **What the settings file holds is kept out of what `solution-settings.js` prints** — an error, a warning, a job log, a message
- `pac` printed — wherever a text quotes it as written or in a JSON, XML or URL escape, with white space collapsed and in any case.
- A text that quotes a secret is withheld whole, whatever its length; a connection id and a value the package defines as not secret
- are replaced by `<redacted>`. A variable counts as a secret when the package defines it as one (a `TypeId` of Secret in the file
- can only add that, never take it away). For a variable the package was not read for (`pac` importing, an entry the package does
- not define) a value of six characters or more is treated as a secret, and a shorter one withholds a text only where the text has
- it as a whole word. What is not caught: a value quoted in part, hashed, base64-encoded, written as an HTML entity beyond XML's
- five, normalized in its Unicode by a service, or nested in more than three levels of encoding; a value of fewer than six
- characters that is known not to be a secret, which is printed wherever a text quotes it; and a value of fewer than six characters
- with no recorded type that a text glues to letters, digits, marks or underscores or writes inside an escape the sanitizer does not
- read. A token the run sent is never printed or written — it is taken out of both output streams, the file `template` writes and
- the note a process that is ending leaves — and a variable's value is passed through exactly as written, white space included.
-- **The bundled cds-maker-sdk is current.** Through it: a business-rule or classic-workflow delete the platform rolled back (HTTP
- 500, transaction not started) is re-sent, bound to the version the build read; a business process flow write waits out the
- platform's lock on the flow instead of failing; a choice read that returns options with no label is treated as incomplete metadata
- (`genpage.js types` stops and says to retry); a business rule with no action step is refused for that (`business-rule-NO_ACTION`)
- before anything is written; and a table's metadata comes back in one order on every read and every machine — columns by logical
- name; relationships one-to-many, then many-to-one, then many-to-many, each by schema name, related table and related column — so
- the copy the build keeps in its workspace no longer changes just because the platform listed the same relationships in another
- order.
-- **Two rare page shapes that 2.14.0 resolved are now refused, naming the guess `generic`**: a class whose base is itself a class
- expression, used as a value before a method (`{ a: class extends class {} {}, m() { … } }`), and a class field named `new` with a
- method on the next line. Both are refused, never misread. Parenthesising the class expression (`extends (class {})`), or ending
- the field with `;` or naming it otherwise, avoids the refusal.
-- **The eval graders read the new scripts the way the scripts read their arguments.** A run of `apps.js`, `genpage.js` or
- `solution-settings.js` is read with its verb where the script takes it — after its flags too (`apps.js --env <url> create` is a
- `create`) — and every run in one shell call counts, so a read followed by a write is graded as the write;
- `solution-settings.js import` is a write. The graders still read recorded text, not a shell: a command line handed to a wrapper
- (`bash -c '…'`), a here-document and variables are documented limits.
+- `POWER_PLATFORM_SKILLS_PAC_TIMEOUT_MS` is no longer read.
+- `genpage-upload.js` creates pages without `--app-id` (not for `--add-to-sitemap` or updates); updates omitting `--model`,
+ `--name` or `--data-sources` keep the page's own; workspace resets should keep `page-ownership.*.json`,
+ `last-applied.json`, `destructive-approval.json`.
+- Throttling waits stop after five minutes per run (`throttle-budget-exhausted`).
+- `solution-settings.js import` keeps `pac`'s defaults and reports `importJobId`, `importAttempts`, `importRefusals`; a
+ settings copy not made private fails (`PAC_SETTINGS_COPY_FAILED`). `template` overwrites `--out` only with `--force`
+ (`IO_ERROR` without hard links); output redacts quoted settings values.
+- **Not redacted**: values partly quoted, hashed, base64-encoded, Unicode-normalized, nested over three encodings or written with
+ HTML entities beyond XML's five; non-secret values under six characters; untyped ones under six glued to letters, digits,
+ marks or underscores or inside an undecoded escape.
+- `pac` fallbacks are time-bounded and labelled (`source`/`fallback`, `connectionsSource`/`connectionsFallback`);
+ `list-connections.js` failures print `{ok: false, error, code}`.
+- Bundled cds-maker-sdk updated; it refuses a rule with no action (`business-rule-NO_ACTION`). Two rare page shapes are
+ refused (`generic`, `identifier`).
### Removed
-- `scripts/lib/genpage-cli.js`, the wrapper around the `pac model genpage` page verbs, with its time limits.
-- **`/genpage`'s fallback to `pac model list-languages`.** Every `/genpage` page operation goes through the SDK and needs the Azure
- CLI, so a failed language read now ends language detection instead of being retried with `pac`.
+- `scripts/lib/genpage-cli.js`; `/genpage`'s fallback to `pac model list-languages`.
### Fixed
-- **Teardown deletes a generative page that was created and never published, with its conversation.** 2.14.0 read pages from the
- published layer only, so a page its build created and no publish ever finished (a build stopped after the create, a publish that
- was refused) was "not found": teardown kept the page and its conversation and dropped its record. It also deleted only the page
- row, and the conversation messages, which do not cascade, stayed behind for every page it did delete. Teardown now reads the saved
- layer, deletes the conversation with the page (a history it cannot fully remove is a warning that names the messages) and matches
- a page the build made by the name its receipt recorded as well as by the spec's current name.
-- **Teardown deletes the pages of an app that was created and never published, and proves a page by the entries of the app's
- navigation.** 2.14.0 read the app's navigation from its published layer, and an app nobody published (a build stopped before its
- publish, an app saved and left) has none, so its pages were proven by this workspace's records alone: a page only the app's
- navigation named was kept, and the app and its sitemap — the only proof of it — were then deleted. Teardown now reads such an
- app's saved navigation. A page is proven by an entry of the navigation, never by the text of the XML, read by one strict XML
- reader: a page named only in a comment, a CDATA section, a processing instruction or another attribute's value is not proven, a
- single-quoted `GenPageId` is, and a sitemap that is not one well-formed XML document keeps every page, and the app, for a re-run.
- A page another app still references is refused by the platform and kept.
-- **Teardown keeps a table whose business rule it could not delete.** A rule is two rows — its definition and the activated copy the
- platform makes of it — and the copy can be deleted only while its table exists. When a rule's delete failed (an HTTP 500 "There is
- no active transaction.", say), 2.14.0 went on and deleted the table, which left the copy behind for good, and the re-run reported
- success. The table is now kept — `table <name> (kept — business rule(s) on it could not be deleted (…), …)`, counted as kept in the
- summary — until a re-run deletes the rule first, then the table. Teardown deactivates a rule before it deletes it, so a rule whose
- deactivation succeeded and whose delete failed stays deactivated until then; one whose deactivation failed too stays as it was. A
- reused or system table keeps its own reason, and the failed delete is still sent once. What depends on the
- kept table — its icon web resource, a global choice its columns bind, a relationship to itself — can fail to delete in the same run
- and is reported too, until the re-run removes the table.
-- **The connection list and the connector commands are pinned to the environment.** 2.14.0 ran `pac connection list`, and told the
- agent to run `list-connector-operations` and `get-connector-schema`, without `--environment`, so they answered for the active
- organization of `pac`'s auth profile — not necessarily the environment being built — and a settings import bound to one of those
- connections failed with `ConnectionNotFound`. `list-connections.js` and the `pac` fallbacks now pass `--environment`, and
- `/genpage` is told to pass it to `list-connector-tables` too.
-- **A read that spans more than one page follows the platform's continuation link.** The link is absolute and was requested as a
- path under the API root (HTTP 404), so a result longer than one page — an app's components, the saved sitemaps, the apps never
- published — was reported as unverifiable instead of read. A refused read now names the URL and carries the platform's own message.
-- **A new app whose navigation Dataverse would refuse stops the build before it writes anything.** A new app is created before its
- pages exist, with its navigation minus the `page` entries, and Dataverse refuses to create a sitemap with no non-empty area
- holding a non-empty group, so a spec whose navigation was only pages, or had `areas: []`, an area with no group, a group with no
- entry or no `appShell` at all, passed validation and stopped at the app step, after the solution, tables, views and forms were
- written. The build now refuses such a spec for a new app up front: the dry run marks the app step as one that would stop the build
- and asks for the steps marked `?` to be fixed rather than applied, and `--apply` halts (`app-navigation-empty`) before its first
- write, saying what to add — a new app needs one entry that is not a page. An existing app is not refused for a navigation of pages
- only (its pages are written into it once they exist) or for one with no entry at all: Dataverse accepts an empty navigation when
- an app's sitemap is updated, so the build goes on and warns that the app is left with none. A spec with no `appShell.areas` is
- refused for every app. `lint-app-spec` warns about a navigation a new app cannot be built from; validation is unchanged.
-- **An alternate key over a new table's name column is made after the column's length is set, so the first build succeeds.** Some
- environments make a new name column 850 characters long whatever length the table's create asks for, and Dataverse refuses a key
- over it (a key holds at most 900 bytes, 2 for each character of text); 2.14.0 set the length as the last step of the data model,
- after the key, so only a second run made the key. A key over the name column of a table the build creates, in a spec that gives
- `primaryAttribute.maxLength`, whose label goes out in one language (a string, or a map that names one language), now waits for
- that step — the dry run lists it there — and is not sent when the step failed: the build stops with a message that names the
- length and the cause (`alt-key-name-length-not-set`) instead of the platform's refusal. The build runs that stop again exactly when
- the length step's failure is one it runs again — a throttled or unavailable service, a timeout or a reset, or a lock, a SQL timeout,
- a concurrent operation or a deadlock the service names by its code — and never because of the key's name; the warning for the length
- says the build stops at that key. A key labelled in several languages is still made before the length is set — setting it reads the
- column with its labels, which would cost a multi-language create its other languages — so where the platform refuses it the build
- warns, naming the key and its languages, and says to run the build again (the length is set as it stops) or to label the key in one
- language. A key in a spec that gives no length keeps its place: give `maxLength` for a name column you key.
-- **After the build's automatic retry of a transient failure, a table the failed attempt created gets the name column length that
- attempt could not set — and only that table.** When the attempt's own length step failed too, 2.14.0's retry found the table and
- left its name column as it was, without a word. The length is now carried to the retry, as the publishes an attempt owes are, set
- at the end of the retry's data-model phase and reported as owed (`owed by the attempt that created the table`). It is read and
- written by the MetadataIds of the table and of its name column, so a table another maker deleted and made again while the build
- waited is left as it is, with a warning, never shortened. A length no attempt got as far as setting is tried once more when no
- retry follows. A later run still leaves an existing table's name column alone.
-- **An unreadable table list is a failure in every script, not "no tables".** The bundled SDK reads a 2xx answer with no `value` list
- — a sign-in or proxy page, `{}`, `null` — as an environment with no tables, and the scripts turned that into decisions: the build
- created a table that exists, the teardown skipped its system-table check (and, where every answer was such a page, reported a table
- deleted that nothing deleted), the flow name check saw no clash, the verifier reported every declared table missing, and
- `list-tables.js --exact` named every searched table missing. The table-list read is now held to being a list for every SDK the
- plugin makes (`TABLES_UNREADABLE`), so each fails with that reason: the build, which reads each table by name and turns to the list
- only when that read is not conclusive, stops at the first table whose existence it cannot establish instead of creating it
- (`table-list-unreadable`, which it does not run again: a run a moment later reads the same answer), keeping what its earlier steps
- wrote (the solution, a global choice, the tables before it), and its dry run says `unknown`; the teardown deletes no table (its
- other steps still run), the flow name check warns that it could not be made, the verify fails, and `list-tables.js`
- exits 1. `{ "value": [] }` is still an empty answer, and no request is added or changed.
-- **A rebuild applies a changed app name and description.** 2.14.0 set them when the app was created and never again. A rebuild now
- writes a changed, non-blank `app.name` / `app.description` to the existing app on the push it already makes for the navigation;
- nothing is written when they already match, a spec that leaves them out never blanks them, and the unique name never changes. The
- icon is still set only when the app is created: a different `app.icon` is reported as not applied. Two cases keep the existing
- text and warn that it was not applied while the rest of the build goes ahead: an app that was never published (publish it in Power
- Apps and re-run), and a name or description held as one text per language — the SDK writes both in one request, so while either is
- held that way the header is not edited at all, and a changed plain text beside it and an `app.aiDescription` are reported as not
- applied too. Nothing that is not plain text is ever sent: the SDK also writes the header it holds whenever its own read of it
- fails, so the plugin's HTTP client refuses that write and the build stops with `APP_HEADER_NOT_PLAIN_TEXT` before anything is
- sent; running it again normally succeeds.
-- **A rebuild applies the business process flow stage edits that cannot move a record.** 2.14.0 reused an existing flow as it was. A
- stage added or renamed, and a step added, renamed, rebound to another column, made required or optional, or moved, are now written
- in place in one push (an active flow stays active; every stage keeps its id). An edit that would remove a stage or a step, reorder
- the stages, or that cannot be told from a removal, is refused with the reason and the ways forward: no stage or step edit is
- applied, and the requested Active/Draft state is handled independently. An edit the SDK refuses — adding, removing or reordering
- the stages of a flow that holds a branch, or the steps of a stage that holds an action — is reported as not applied.
-- **`readOnly` and `hidden` reach every cell of a field.** A field a deployed form holds more than once — in two sections, or in the
- form's header, footer or a tab's own header or footer — got the flag on its first cell only, so the other stayed editable or
- visible. Each cell now gets it, with the rest of the cell left as it was, and `--verify` checks each one.
-- **`--verify` compares tab and section labels, per language, in the language the build wrote them.** 2.14.0 used a label only to
- find its tab or section and never compared it, so a relabel that never reached the published form passed. A tab or section label
- the spec writes is now compared with the published form in the build's authoring language (a label map at each language it
- declares); a relabel that never reached the published form, or a caption the published form lacks, fails the check, and a
- translation in another language never stands in for it. `verify-model-app.js` takes the build's `--language-code` (and the build's
- own `--verify` is told the language it used), so a form built in a language other than the organization's verifies. What cannot be
- compared is listed as `unverified`, neither passed nor failed, with the reason and what to do (`unverified` changes neither `ok`
- nor the exit status): a label whose language cannot be established (the organization cannot be read, and nothing else says it),
- and a label in a language that no label of the form's read is in, when the read carries labels in other languages (a form whose
- read carries no label at all still fails the captions the spec declares). The platform decides which languages' labels the form
- read returns: a form built and published with Spanish captions in an English-language organization reads back with every label in
- English, so its stored Spanish captions are listed, to be checked in Power Apps with that language, not failed. A label map is
- compared at the languages the read carries and listed for the others; a caption in a language the read carries is compared
- strictly, and a stale one fails.
-- **Verify no longer calls a published dashboard "not published" in an environment with a second language.** `verify-model-app.js`
- and the build's `--verify` check a dashboard's tiles only when the saved layer they are read from is the published dashboard, and
- 2.14.0 compared the two FormXML reads as text. Where another language is provisioned beside the base one, the saved read carries a
- label in it in every cell and the published read does not, so a dashboard nothing had changed since its publish was listed as
- having changes that are not published (unverified), and every job whose surface it is failed with it. The two reads are now
- compared without the labels of a language the published read carries none of; a tile, a cell, an attribute, any other text, a
- label in a language it carries, and a FormXML that is not one well-formed XML document are still changes. That is what a user whose
- own language is the organization's base language reads. For a user whose language is the other one, the platform's published read
- carries both languages and can word a caption differently from the saved read, so the dashboard stays unverified for that user, as
- before: never passed without being proven.
-- **A label saved and not published on a form the app holds, or is about to hold, is no longer held back by the app's publish.**
- Dataverse leaves a saved form's label changes out of the published form when a publish that names only the app comes first,
- whoever saved them, and 2.14.0 published before the app only the tables whose existing views and forms the build reconciled. With
- `--publish` the build now publishes, in one request before the first thing that writes or publishes the app — its create, its
- sitemap or routing-description push, the pages finalizer, the repair of a default view the app lost (which a changed-only
- re-upload of a page can make on its own) and the publish phase — the tables whose views and forms it reconciled, the tables of the
- charts it wrote, the tables whose Main forms its write adds to the app and, for an app that already exists, the tables of the form
- and chart components the app's saved component list names, whether or not the spec names them (a form a maker added in the
- designer and never published included). The tables whose Main forms a write adds are those of the navigation it sends: the spec's
- for the build's own create and sitemap pushes, so the first build and the build that first pins a form are covered too; the app's
- own on the server for a push that only carries the routing description; none for the repair of a default view, whose push adds the
- view and no form. A table the app is not known to hold a form or chart of — one only declared, only the target of a lookup column,
- only read by a page, or only pinned in `app.tables` — is not published by it, so what a maker left unfinished there stays
- unfinished. If the app's components cannot be read completely and unambiguously, the build publishes only the tables it changed
- and those its write adds forms of, and says which read failed. A rebuild of an app whose views or forms exist still sends the same
- three publishes; a build that reconciled nothing — a first build, say — sends one more when it has something to name, and so does
- a changed-only re-upload that has to put a default view back (the tables, before the app). A chart's description now goes out with
- its table before the app's publish instead of after it.
-- **A refused publish before the app, and a build that stops before its publish phase, say what they leave unpublished.** When the
- request above is refused the build goes on — a refusal of the publish of the tables it reconciled still stops it before the app,
- as in 2.14.0 — and says that its protection did not apply, what it saved on those tables (a chart's description included, which
- Dataverse may or may not hold back: that was not measured), and, apart from that, that a label saved on a form the app holds there
- may have been left out by the app's publish and may need to be saved again. A build that stops before its publish phase, after
- publishing what it had deferred, reads the saved layer of the forms, views and charts of the spec's tables (the tables its pages
- read included) and lists those still saved and not published, or says it could not read them and names the tables to publish.
- Columns and other kinds of change are not read, and a halt after the publish phase says nothing of the kind.
-- **The build runs itself again for what the service answered, not for the names a maker chose.** 2.14.0 decided whether a halt was
- transient from its whole message, and a message quotes what a maker named, so a page, view, role, flow or table called "SQL
- Timeout …" (or `contoso_customizationlockexception`) made a halt the build cannot change — a navigation-parity or `PAGEREF_` halt,
- a 403 — run every earlier phase again, up to three more times. The decision now reads the failure's structure: a throttle (429),
- an unavailable service (502, 503, 504), a timeout or a reset of the connection, and the conditions the service names by the error
- code of its answer — a customization or solution lock, a SQL timeout, a concurrent operation, the lag of a column the spec
- creates, and a SQL deadlock (the generic SQL error whose last SQL number is 1205) — are run again; any other status (a 400, 401,
- 403, 404, 409, 412 or 500), a refusal of the spec, an identity or ownership conflict, a removal that needs approval, a
- prerequisite, a held pages lock and a local file error are reported once, whatever the answer's words. A failed publish of a
- table's default views is judged by the status of the answer it embeds, not by the table's name.
-- **The HTTP client sends a failed request again only for a failure that can pass.** 2.14.0's client sent a request that got no
- answer up to six times whatever the reason, so a certificate that does not verify, an unknown host or a refused connection cost
- six attempts and their back-off before the error. It now sends again only for a reset, a timeout, an aborted connection, an answer
- cut off or a temporary failure of name resolution, read from Node's own error code (from the failure's words only when there is
- none), and never for a certificate that does not verify, whatever names it quotes.
-- **A build that was killed while it wrote pages no longer leaves its pages lock in the way.** A build killed outright ("End task",
- an agent's timeout, a power cut) cannot remove its `pages-<app>.lock`, and 2.14.0 stopped every later build of that app at the
- pages phase (`pages-locked`) until the file was deleted by hand. The lock now records who took it — the process, the machine and,
- on Linux, the pid namespace and the process's start time — and the next build releases it, and says so, when it can prove that
- owner is gone: on this machine, no such process or one that started at another time (on Linux only when both pid namespaces can be
- read and are the same). A lock whose owner may be running, is on another machine or has a record that cannot be read is refused as
- before, and no lock is ever taken for its age.
-- **A killed run's temporary workspace no longer stays in the OS temp folder.** The workspaces the page backend and the other
- scripts make for the SDK hold the source of every page read and the environment's address, and were removed only when the run
- ended normally. They are now made, with a record of who made them, in one folder of the plugin's own in the temp folder
- (`power-platform-skills-model-apps`, with `-<uid>` after it on Linux and macOS), and the first workspace a later run makes removes
- those of runs that are provably gone, saying on stderr what they held, and finishes a removal a killed run began. A run looks at
- no more than 500 entries of that folder and the next one carries on where it stopped, so entries that must be kept never hide the
- ones behind them. A workspace given to `pac` is marked as lent when it is made and is taken only once its maker is gone and it has
- not been written to for a week. On Windows the plugin's folder is given an access list of its own — this user, the system and the
- administrators — and a folder that was already there is used only when no one else can change it; where that cannot be shown, the
- workspace is made in the temp folder as before: the plugin's folder is never a reason for a run to fail. A normal run leaves the
- temp folder as it found it.
-- **A Dataverse failure can no longer carry the access token into what a script prints.** The Azure CLI-token client takes the token
- (whole, or any of its segments of 24 characters or more) out of every answer that is not a success, and out of a transport
- failure's text, before the SDK quotes it; `dataverseRequest()` takes it out of what a failure repeats. A successful answer is
- never altered.
-- **`/genpage`'s upload counts a style shorthand as already deployed only where the deployed page had it.** 2.14.0 counted a key as
- inherited when the deployed page had the same key and value anywhere, so an edit that moved `borderColor: red` to another slot,
- hook or arm of a condition — where Griffel drops it just the same — was only warned about. A key is now inherited only with the
- same value in the same slot of the same `makeStyles` hook (proved by the name it is bound to) and the same arm of every condition;
- anything else is new, and refused as one. A key in a hook the page does not prove by name (written inside a function, passed as an
- argument, exported as the default, or bound to a name two hooks share) is new on an edit too: delete it, or write the longhands.
-- **A rebuild no longer warns about the icon the platform gives a page entry.** A generative page entry the spec gives no icon gets
- the platform's default page icon, and every rebuild of an app with a page then said it had kept the environment's `vectorIcon`
- because it had changed there since the spec was last applied. That default is no longer taken for a maker's change; an icon a
- maker chose is still kept and reported, and an icon the spec names is written over the default.
-- **A type whose members start like an element's head no longer has the data after it rewritten.** `<in U>(y)`, `<public U>(y)`,
- `<const in U>(y)` and `<>(y)` in an interface, an object type or a function type (`callback: <in U>(y: U) => void`), and a method
- named `delete`, `typeof`, `void` or `instanceof` that has type parameters (`delete<T>(url: string): Promise<T>`) — also after a
- modifier or an accessor word, a decorator or a line break, with a type parameter written with a Unicode escape, and in the braces
- of a class or an interface whose heritage ends in a call — were read as JSX elements whose text ran on to the next closing tag, so
- a `navigateTo({… PAGEREF_…})` text in a later string, template, comment or regular expression could be rewritten. They are now
- read as the type parameters they are wherever the text after the list shows it. Where a string, template, comment or regular
- expression could hide the closing tag, so that the two readings may end the head in different places, the page is refused naming
- the guess (`generic`), like any call signature; so is a page whose syntax the reader cannot read with confidence — a function
- type's parameter list it cannot read to its end (`generic`), or a name written with an escape (`identifier`). An element after
- `void`, `typeof` or `delete`, and one whose text starts with a parenthesis and holds a comment (`return <>(y); // note</>;`), is
- read for certain in more places — the bodies of functions, methods and decorated members, after `return`, after a `,` in
- parentheses, after a word that takes an operand and a line break — so those pages resolve.
-- **More pages that 2.13.0 resolved and 2.14.0 refused resolve again: JSX text whose line before a `//` note is left open
- (`[ // note`, `m? = // note`, `f(a = // note`) and a later line that starts with a `/`.** The regular expression that line would
- open is read: where it does not close on its line, ends at the closing tag's own `/` with nothing after the tag that an operand
- could start, or closes right before it, no type can have the text and only the element compiles. A closing tag that an operand may
- follow, and a path with a `/` of its own and text after it, are still refused (both readings compile, or only a parser tells them
- apart): put the call before the text, or write the line with one name before the `//`.
-- **A download writes the same files for the same app, and keeps each page's key.** 2.14.0 wrote the pages and several lists in the
- order the file system or Dataverse gave them, and sorted others by the host's locale, so two downloads of one app could differ;
- and a page's key was minted in that order, so two pages whose names make one slug (`Work_Order`, `Work Order`) could swap keys
- between downloads, and a copy of the spec deployed to another environment then updated the wrong pages. The pages, the description
- inventory, the tables an app holds beyond its navigation, the Main-form names of `app.mainForms` and the `notRoundTripped` notes
- are now written in a fixed order, compared by code units and never by the host's locale (the pages by name, then id). A page's key
- comes from the app's page manifest, then from the key an earlier download of the same app gave it (the `app-spec.json` already in
- `--out`, used only when its `app.uniqueName` is this app's), and only a page with neither gets a fresh key, minted in page-id
- order. When that earlier spec gives one key to two pages, or one page two keys, for a page the manifest does not bind, the
- download stops before it writes anything (`page-keys-ambiguous`, naming the pages and keys): correct the file and download again,
- or pass the new `--reset-page-keys` to give exactly those pages fresh keys. Download into the same working folder every time.
-- **The eval graders count `pac solution import` as a write, and read a listing kept as text.** 2.14.0's graders did not count
- `pac solution import` as a write, so an import escaped the auth-gate and refusal checks, and read a listing recorded as the JSON
- text a command printed — a string result, or a log's `Result:` line — as a PAC table, one row named after the start of the JSON.
- Such a listing is now read as the data it is, and a PAC table still goes to the table reader.
+- New apps need a non-page navigation entry (`app-navigation-empty`); a new table's single-language
+ name-column keys wait for `primaryAttribute.maxLength` (`alt-key-name-length-not-set`); unreadable table lists fail
+ (`TABLES_UNREADABLE`, `table-list-unreadable`).
+- Rebuilds apply changed `app.name`/`app.description` (re-run if `APP_HEADER_NOT_PLAIN_TEXT` halts); `--verify` compares
+ tab/section labels (`verify-model-app.js --language-code`).
+- Dataverse failures no longer carry the access token into script output.
+- Downloads keep page keys (`page-keys-ambiguous`, `--reset-page-keys`).
## [2.14.0]
-The Notes timeline renders, a related-records grid can be placed where you want it, lookups are labelled with the table
-they point to, and view filters resolve choice labels against the environment. Generative pages are checked for style
-shorthands their styling engine drops, their `pac` calls are time-bounded, and more navigation-call shapes build while a
-few that were misread are now refused. The bundled SDK is current, an unchanged rebuild sends a fraction of the writes it
-used to, builds send fewer requests, and verify, download and `check-auth` do more of their work in parallel.
+The Notes timeline renders and unchanged rebuilds send far fewer writes.
### Added
-- **`subgrids[]` placement** (AB#6651699). An entry takes `tab`, `column`, `after` and `before`, to put a related-records
- grid between sections, in a tab of its own, or in a form column. A rebuild moves a grid an earlier release appended
- after the Notes section so it sits beside its section; only the grid moves, and fields the same build adds still land
- in their own sections. `--verify` checks the placement, and the wireframe and the plan show it. Listing a table twice
- in `subgrids[]` is an error when an entry places it, and a warning otherwise (only one grid per relationship is built).
-- **`primaryAttribute.maxLength`** (a whole number from 1 to 850) sets a new table's name column; it was ignored before.
- Without it the table is created exactly as before, asking 100 characters for the name column, so the name column comes
- out as it did before on every environment. An existing table's name column is never changed; a length the platform did
- not apply is set as the last step of the data model, or reported as a failed step.
+- **`subgrids[]` placement** (AB#6651699): `tab`, `column`, `after` and `before` place a related-records grid; a rebuild moves grids
+ earlier releases appended after Notes.
+- **`primaryAttribute.maxLength`** (1–850) sets a new table's name column; it was ignored before.
### Changed
-- **The bundled cds-maker-sdk is current.** Through it:
- - a Main form create whose answer was lost on the network is recognised when the retry is answered 412, and adopted
- when it is exactly what the build sent, instead of halting with "already exists" until the workspace is reset (other
- form types, and a retry answered otherwise, still halt as before);
- - a form, publisher or view create that a database deadlock rolled back is re-sent by the SDK as well, beyond the
- build's own re-sends, and so is an app delete that met the platform's search-index race;
- - a form or dashboard id that belongs to the other kind of record is refused when it is read, written or deleted, with
- a message that says what it found, and a push can no longer change a form's type;
- - the routing description of an existing app is saved only on top of the version the build read, so a failed read can
- no longer overwrite someone else's change (the app's name, description and icon are set when it is created);
- - reads of tables, columns, relationships and choices ask Dataverse for its latest definition (`Consistency: Strong`),
- which costs each such read about 10% more;
- - removing a row summary whose AI model another component still uses keeps the model and succeeds.
-- **`/genpage` finds the environment's languages with a plugin script.** Instead of `pac model list-languages` it reads
- the base language and every provisioned language with your Azure CLI sign-in and reports each language's code and
- whether it is written right-to-left; a language the plugin does not recognise keeps its number and is flagged, never
- guessed. Without a usable Azure CLI sign-in, `/genpage` falls back to `pac model list-languages`, now pinned to the
- environment it plans for with `--environment` (2.13.0 asked pac's active environment), and says so.
-- **An app folder stays with the environment it was built against.** A build from a folder built against another
- environment stops before writing anything, names both environments and lists the ways forward, including the folder a
- teardown would clear. The same environment under its `.api.` host name is reported as such, with the host to run again
- with. A dry run never takes over the folder, and verifying an app on its own (`verify-model-app.js`) no longer opens the
- app folder's workspace, so it can check any environment the app is deployed to and leaves the folder untouched.
-- **AI features saved before the app is published** are published and then proved, instead of written twice; one still
- not in force is reported `NOT YET PUBLISHED`, never applied.
-- **An unchanged rebuild sends far fewer writes.** Views and forms the spec authors are no longer re-sent when they have
- not changed, the solution's membership is read once so only the components it lacks are added, and with `--publish` the
- tables a rebuild touched are published together instead of once per view and form (on a sample app with every
- artifact type: 25 writes instead of 59, 3 publishes instead of 10; the generated default views, the default form, app
- settings, role privileges and the app's navigation are still written on every rebuild). The tables of the existing
- views and forms a rebuild reconciles are published before the app is, because publishing the app first would leave
- any new labels on them unpublished; if that publish is refused, the build stops before writing the app (and runs again
- at once when the refusal is transient). When a publish fails or cannot be confirmed, the warning names the views,
- forms and charts on each table that are saved but not live — the generated default views and what a first build
- created included — instead of a bare form, view or chart id.
-- **Faster runs.** Verify runs its checks four at a time and downloads page code in one `pac` run per 25 pages;
- `check-auth --env` runs its probes together; download reads each table's labels, option sets and relationships in
- parallel (the files it writes are the ones a read of one table at a time writes); teardown publishes all default-view
- resets once; a new table's ordinary columns (up to 25) are created in one request after the table instead of one
- request each, column for column as before — if the platform refuses that request nothing is created by it and the
- build creates them one by one, with a warning that says why; a request refused because the table is still busy (HTTP
- 429) is sent again first, and one whose answer was lost is checked against the table before anything is created again.
- A verify that fails ends any `pac` run it started and removes its temporary download folder.
-- **Generative-page `pac` calls are time-bounded, and a page upload whose outcome is unknown is not retried.** A `pac model genpage`
- call (list, download, upload) that outlives its budget (`POWER_PLATFORM_SKILLS_PAC_TIMEOUT_MS`) is stopped together
- with everything it started — on Linux and macOS each process only after its start time is read again, which makes ending an
- unrelated process that took over the id of one that exited far less likely (not impossible). A timed-out update says it may
- have landed and how to check; so does an update that fails, which is no longer retried — `pac` can fail while publishing,
- after it has written the page and recorded its prompt, so a retry could record the prompt a second time — unless `pac`
- refused its own arguments or files. A timed-out create says the page may exist, or that it was created as `<id>` when `pac`
- printed the id, and how to finish it. A create whose outcome is not known to be nothing — it timed out, failed after
- `pac` printed its id, or left a page in the listing — is never sent again, not even by the build's own retry of a
- transient failure; a create that failed outright and left nothing behind is retried as before.
-- **Updating a generative page also checks the other apps' unpublished navigation** — each app's saved navigation and
- apps that were never published, including a sitemap linked to an app by its name. A page one of them holds stops the
- update and names the app; a never-published app with no navigation does not. The check runs again right before the
- first page is written in place and once after the last: a page another app takes in while the build runs stops it
- before any page it began with is updated in place, or, if it lands while the pages upload, is reported with the app that holds it.
- A page the build itself created is left out of both.
-- **The record of what a build applied is the page source it read and checked**, so a page saved while a build runs is
- checked by the next build instead of being found unchanged.
-- **More pages with a hint in parentheses resolve their navigation calls.** JSX text in parentheses that holds an `=`, a
- `[` or an `@` followed by a `/`, a `<` or a back-tick — `<p>(a = b/c)</p>`, ``<p>(x = y, `code`)</p>``,
- `<p>(@user/repo)</p>` — or that has a link on the next line, is read as the element it is in, so the navigation call
- after it resolves where 2.13.0 refused the page; such text no longer needs the expression container 2.13.0 suggested.
- `return (navigateTo)({ … })` builds too.
-- **A few pages that 2.13.0 resolved are now refused, naming the guess `generic`.** This happens where such a hint stands
- where a member of a type could also begin — after `return`, `?` or another keyword, or after a separator — and one of
- its lines ends unfinished before a `//` note (an open bracket, an `=` or an operator), with a later line that starts
- with `/`: the text up to that `/` can also start a type whose regular expression holds the element's closing tag.
- 2.13.0 took the end of the note for the token before the `/`; the build now refuses instead of guessing. Moving the
- navigation call before the hint, or ending the line with a word before the `//`, avoids the refusal. The same applies
- to an element whose text holds a nested element with a quote, a back-tick or `//`, followed by a string that holds the
- element's closing tag.
+- The bundled cds-maker-sdk is current.
+- **A build stops before writing when the app folder was built against another environment.**
+- An AI feature not yet in force is reported `NOT YET PUBLISHED`.
+- **`/genpage` reads languages with your Azure CLI sign-in**, falling back to `pac model list-languages --environment`.
+- **Generative-page `pac` calls are time-bounded** (`POWER_PLATFORM_SKILLS_PAC_TIMEOUT_MS`); an upload with an unknown
+ outcome is not retried; an update stops if another app's unpublished navigation holds the page.
+- **Parenthesised JSX text no longer needs 2.13.0's expression container**, but a few pages 2.13.0 resolved are
+ refused, naming the guess `generic`: move the navigation call before the text or end its unfinished line with a word
+ before `//`.
### Fixed
-- **The Notes timeline renders** ([#680]). It is written the way Dynamics shows it — control id `notescontrol` in a tall
- cell over the empty rows it spans — instead of a one-row cell that published but never appeared. A full build (not
- `--changed-only`) repairs an older Notes section in place, after taking out of it any field the layout removes or places
- elsewhere; a timeline you resized is left alone, and a section still holding a control the build does not move is left
- and reported. `--verify` fails a form whose timeline would not render and says what to do: run a full build where the
- build takes the stray fields out itself, which control to move in the maker where it does not — and where it cannot
- tell (a field placed on the form more than once, or anchored to one) it says so.
-- **Lookup columns are labelled with the parent table's display name** (AB#6691205). A relationship with no
- `lookup.displayName` now labels the lookup column — and the form field that carries it — "Project" instead of the
- logical name `new_project`: from the declared parent table, else from the environment (an `existing: true` `incident`
- is "Case"), in every language the label is written in. A rebuild relabels a column or form field still carrying the old
- default — each cell of a field the form holds more than once; it never changes a label you set. A download leaves out a
- label equal to that default.
-- **View filters resolve choice labels against the environment** (AB#6691114), including a column of an existing table
- the spec does not declare (`account.industrycode`) and a global choice that already existed, instead of being sent to
- Dataverse as text or as the spec's own position number. A label that matches no option stops the build, listing the
- valid ones, before any view is written (and before anything is written where the environment already shows it; a spec
- with a localized label is checked after its tables and columns are written). An option a maker renamed still resolves
- to the spec's number, as in 2.13.0, now with a warning; the build stops instead where the environment shows the options
- are numbered otherwise — for example options inserted into the spec after the column was built, which 2.13.0 silently
- bound to whichever option held that number — and says why. A view that already exists keeps its filters; where 2.13.0
- built one on an option the environment numbers otherwise, `--verify` now reports it.
-- **Quick View sections stay one column**, as Quick Create sections already did. A field-heavy Quick View section got two
- columns, which the platform refuses for this form type, and the build failed part-way.
-- **A page keyed like a Windows device name** (`con`, `nul`, `aux`, `com1`, …) is handed to `pac` as a file: the build's
- copy of each page it uploads is named `page-<key>.tsx`, which Windows never reads as a device, where 2.13.0 named a
- navigation page's copy `<key>.tsx`.
-- **Generative pages are checked for the style shorthands Griffel drops** (AB#6691124): `all`, `borderColor`,
- `borderStyle`, `borderWidth`, `borderBlock*` and `borderInline*` in `makeStyles`, which deployed silently without their
- style. A build stops before the pages phase writes anything for a page it creates or whose source changed since the
- last recorded build, and only warns for a page it sends again unchanged; `/genpage` refuses a create, or an update that
- adds such a key or changes its value. `node scripts/check-griffel-styles.js --file <page.tsx>` lists each key and the
- longhands to write. A style object the check cannot see — passed in (`makeStyles(styles)`), given to a slot or a
- selector as a variable, or spread in (`...base`) — is reported too, and so are a key computed from an expression
- (`[key]: …`) and a getter that runs on a style object (`get color() { … }`), whose code the check does not read;
- all are held like a call the check cannot read, and Fluent's own `shorthands.*(…)` helpers and
- `typographyStyles.*` entries may be spread (`shorthands.transition` with one argument only as an array, a string or
- a number written in place). What is uploaded is what was checked: the build sends every page from a copy of
- the bytes it checked, and `genpage-upload.js` reads the page once and uploads a copy of those bytes, so a save to the
- file while either runs is not sent unchecked. `genpage-upload.js` no longer takes `--compiled-code-file`, whose
- JavaScript `pac` would deploy instead of the checked page.
-- **A `PAGEREF_` token in a string, template or regular expression of a page's types is no longer rewritten** in shapes
- 2.13.0 misread: a nested element in a parameter default or a computed name whose text holds a quote, a back-tick or
- `//` (two on one line included); a regular expression on the line after a `//` note that follows an open bracket, an
- `=` or an operator in a type; and an accessor whose computed name holds one (`get [a, // note`, a line break, then
- `/…/]()`). Such a page is now refused, naming the guess, instead of being deployed with the string changed.
-- **Connector discovery reads `pac connection list` as `pac` prints it**: an environment with no connections reads as
- empty, and output the reader does not recognise is refused instead of being read as empty.
-- **`dataverse-request.js` keeps its path under the Web API root** ([#705]). A path whose `..` segments — written
- plainly, percent-encoded or joined by an encoded slash — would leave `/api/data/v9.2/` is refused before a token is
- read.
-
-[#680]: https://github.com/microsoft/power-platform-skills/issues/680
-[#705]: https://github.com/microsoft/power-platform-skills/issues/705
+- **The Notes timeline renders** ([#680]); a full build (not `--changed-only`) repairs an older Notes section.
+- **Lookup labels default to the parent table's display name** (AB#6691205) without `lookup.displayName`; a rebuild relabels only
+ the old default.
+- **View filters resolve choice labels against the environment** (AB#6691114); unknown labels or numbering mismatches stop the build.
+- **Style shorthands Griffel drops** (`all`, `borderColor`, `borderStyle`, `borderWidth`, `borderBlock*`,
+ `borderInline*`) stop the build and `/genpage` for a new or changed page (AB#6691124);
+ `node scripts/check-griffel-styles.js --file <page.tsx>` lists the longhands.
+- **`genpage-upload.js` no longer takes `--compiled-code-file`.**
+- **`dataverse-request.js` refuses a path whose `..` segments, plain or encoded, would leave `/api/data/v9.2/`**
+ ([#705]).
+- A `PAGEREF_` token 2.13.0 misread in a page's types refuses the page; connector discovery refuses unrecognised
+ `pac connection list` output.
## [2.13.0]
-An app's hidden tables and its list of Main forms now survive a download and rebuild, and
-relationships that share a name are caught. A generative page edited in the maker portal is no longer
-overwritten silently, and page cleanup removes only pages this workspace can prove it created. Spec
-sources and output files stay inside the folders you name, and a few transient platform responses
-are now retried without risking a duplicate. A generative page's navigation tokens are rewritten only
-where the build reads its code for certain.
+Hidden tables and Main forms survive a download and rebuild.
### Added
-- **`app.tables`** — tables that belong to the app outside its navigation (AB#6603388). A download
- writes them, so a rebuild keeps them. A build adds them as app components, and `--verify` checks
- the published app. A hidden table owned by another solution is listed here only, never in
- `entities[]`.
-- **`app.mainForms`** — for each navigation table, the Main forms the app offers, by name. The build
- resolves each name before any app write, and refuses one that is ambiguous, inactive or missing. The
- platform only adds forms to an app, so an existing app keeps a form it already offered: the build
- warns, and `--verify` names the form and the Maker step that removes it. A download writes the list
- when the app offers only some of a table's forms.
-- A download that writes either field sets `minimumPluginVersion` to 2.13.0, and lint warns when a
- spec uses one without that floor.
+- **`app.tables`** (AB#6603388): the app's tables outside its navigation; a hidden table another solution owns goes only here, never
+ in `entities[]`.
+- **`app.mainForms`**: each navigation table's Main forms, by name. An existing app keeps forms it already offers;
+ `--verify` names the Maker step that removes one.
+- A download writing either field sets `minimumPluginVersion` to 2.13.0.
### Changed
-- **A generative page update checks the deployed page first** ([#673]). An upload records a base
- marker beside the code file (hashes and ids only). An update stops when there is no base, when the
- deployed page changed since the base (it writes a copy and a line summary), or when the deployed
- page cannot be read. Pass `--overwrite-deployed` only after choosing to replace the maker's changes;
- `/genpage` asks first and stops when nobody can answer.
-- **Page cleanup acts only on pages this app can prove are its own**: a local receipt written when
- the build created the page, or the app's navigation, published or saved. A page that only the stored
- page manifest lists is kept and reported; when the proof cannot be read, the app is left intact for a
- re-run. `--clear-workspace` refuses while a receipt remains. A rebuild updates a page only when the
- app's published navigation or a receipt proves it; a page only in the saved navigation asks you to
- publish the app first.
-- **An uncertain page create stops.** When a create fails or reports no page id but a new page
- appeared, the build lists each candidate's name and creation time instead of adopting one. A create
- that left no page is retried as before.
-- **A business rule or AI model that only shares a name is reported, not deleted.** Cleanup removes
- only the records this build created.
-- **Edit plans treat earlier prompts as data.** The edit planner no longer copies them into the plan,
- and the written plan must carry the same ordered change list the user approved.
-- **Navigation tokens are rewritten only where the build reads the code for certain.** A `PAGEREF_`
- token is allowed only as the double-quoted `pageId` of a `navigateTo` call whose options object is
- written inline, optionally followed by `as const`, `as Name` or `satisfies Name`. A token anywhere
- else — a comment included — halts the build with the rule quoted. Where code before a call can be
- read two ways (a `/` or `<` that may begin a regular expression, a JSX element or a type), calls after
- it are not rewritten: the build halts naming the line, the reason and what to change. A page that
- still holds a token after resolution is refused before anything is uploaded.
-- **Download writes a `PAGEREF_` token back only where a rebuild accepts it.** Otherwise the page
- keeps its ids, and the download warns, naming each line.
-- **Build and download skip an unused identity read** after a successful sign-in check: one cold
- Azure CLI start less per run.
+- **A generative page update stops** when there is no base marker, the deployed page changed, or it cannot be read
+ ([#673]); `--overwrite-deployed` replaces the maker's changes.
+- **Cleanup removes only pages proven this app's own** (a receipt or its navigation) **and records this build
+ created**; `--clear-workspace` refuses while a receipt remains. Publish the app before a rebuild updates a page only
+ in its saved navigation.
+- An uncertain page create stops, and edit plans treat earlier prompts as data.
+- **A `PAGEREF_` token is allowed only as the double-quoted `pageId` of a `navigateTo` call with inline options**
+ (optionally `as const`, `as Name` or `satisfies Name`); anywhere else, comments included, it halts the build.
### Fixed
-- **Relationships that share a schema name are caught.** A 1:N and an N:N between the same two tables
- derived the same name, so the N:N was skipped as if it existed and `--verify` passed. Validation now
- asks for an explicit `schemaName`. The build reuses an existing name only for the same type, ends and
- lookup, and `--verify` checks a relationship's type and ends. A download keeps a deployed name that
- differs from the default.
-- **A field placed with `fieldOptions.after` no longer overflows its row.** A row that would be too
- wide moves its trailing cells to rows directly below, and a row an earlier release left overfull is
- repaired once. A new field lands at its listed position. All moves of one placement are written in
- one update, so a failure leaves the old layout, never half of the new one. `--verify` fails a form
- that repeats a cell or control id.
-- **A view rejected for a lookup the build just created is retried.** Right after a relationship is
- created, a view that uses its lookup can be refused for a column the server cannot see yet. The build
- now retries that, but only for columns it creates; an undeclared column still stops at once.
-- **A parallel phase that fails waits for its other writes** before it reports. The retry used to run
- while a write was still pending, created the same view again, and then stopped on the duplicate.
-- **A response cut off mid-way is never re-sent as a create.** It used to leave the request waiting
- forever, or be retried; a create in that state is now reported as possibly applied rather than sent
- again and duplicated.
-- **Output files stay in the folders you name.** Download, build, verify and the spec document refuse
- a link or junction at an output name and write through a temporary file and a rename.
-- **Spec sources stay in the app folder.** A web resource's `contentPath` and a page's code file must
- be a regular file inside the app folder; a link that leads out is refused before anything is written.
- A `contentPath` behind inline content is not read, so it is not checked, and teardown accepts an
- older spec's path.
-- **An app missing from its solution is re-added.** A build that stopped after creating its app left
- the app outside its solution, and a re-run did not add it back. The app now joins its solution right
- after it is created, and every rebuild re-adds it.
-- **A navigation literal inside an expression is no longer rewritten.** A `pageId` such as
- `"PAGEREF_detail".slice(8)` halts as malformed instead of having its literal replaced, which changed
- what the expression computes.
-- **A string continued with a backslash at a CRLF line end** is read as one string, so a valid page is
- no longer refused.
-- **A `PAGEREF_` token inside a regular expression, a string or a comment is no longer rewritten in
- rare shapes the check used to misread.** These are:
- - an element right after a `/`;
- - an element whose text opens with a parenthesis and whose attribute value ends in a backslash;
- - an element written as an attribute value (`x=<B/>`);
- - a self-closing tag with white space between its `/` and `>` (`<B / >`);
- - a closing tag that holds a comment with a `>` in it;
- - a regular expression whose flags spell a keyword (`/x/in`);
- - an `if` or `while` whose keyword is separated from its `(` by U+0085 or U+200B, which TypeScript
- treats as white space;
- - a generic generator function, `function* <T>(…)`;
- - a generic call signature with no return type (`interface I { <T>(x) }`);
- - a generic call signature followed by a member name quoted right after `public`, `private` or
- `protected` (`public'…'`), or by a regular expression right after `implements`;
- - a generic call signature whose parameter list holds a default value, a computed name, a decorator,
- an import type, an accessor's body or a type parameter's constraint (`<T>(a = /[)]/)`), or a
- template nested in another or holding JSX;
- - a type parameter whose constraint is a regular expression (`<T extends /…/>`), which begins like
- the self-closing tag `<T extends />`;
- - a `#!` line at the start of the page.
-
- Such a page now halts, naming the line. So does an attribute value written after white space that
- follows its `=` and holds a backslash, which TypeScript and other compilers end in different places;
- an element whose first attribute is named `extends` and closes at once (`<T extends />`); and JSX
- text that opens with a parenthesis and holds an `=`, a `[` or an `@` (or, rarely, a type keyword
- such as `import`) followed by a `/`, a `<` or a back-tick before its `)`
- (`<p>(a = b/c)</p>`), which a call signature's parameter list can share; write such text inside an
- expression container (`<p>{"(a = b/c)"}</p>`) to keep the page building.
-- **A navigation call after a generic generator function (`function* <T>(…)`) is now found.** The build
- refused such a page with a navigation parity mismatch.
-- **Connector discovery refuses output it cannot read.** Text on stderr after a successful exit, a
- line before the table header other than PAC's sign-in banner, a header that is not a known column
- set, a lone carriage return, or a row whose id is not a connection id no longer reads as an empty
- or extra connection.
-- **Packaging checks a connection reference's id before any write.** A `connectionreferenceid` that is
- not a GUID is refused before anything is added to the solution.
-- **Nested navigation calls are read in linear time.** 512 nested calls took 0.55 s to check and now
- take 5 ms; 8,192 nested malformed values took 143 s and now take about 0.1 s.
-- Samples 9 and 10 use the double-quoted `PAGEREF_` form the build accepts.
-
-[#673]: https://github.com/microsoft/power-platform-skills/issues/673
+- **Relationships that would share a schema name** (a 1:N and an N:N between the same tables) need an explicit
+ `schemaName`.
+- **Spec sources and outputs stay in your folders**: `contentPath` and page code files must be regular files in the app
+ folder; links and junctions at output names are refused.
+- **`fieldOptions.after` no longer overflows a row**; `--verify` fails a form that repeats a cell or control id.
+- A rebuild re-adds an app missing from its solution.
+- JSX text such as `<p>(a = b/c)</p>` halts; write it as `<p>{"(a = b/c)"}</p>`.
+- Packaging refuses a non-GUID `connectionreferenceid`, and connector discovery refuses output it cannot read.
## [2.12.1]
-- **Usage telemetry is on.** The plugin sends a `skill_started` event when a skill starts, routed to
- the collector for your cloud; an unrecognised cloud sends nothing. Org and tenant ids are sent, never
- the user's id. Turn it off with `/model-apps:telemetry off`, or set
- `POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT=1` for automation.
+- **Usage telemetry is on**: a `skill_started` event when a skill starts, routed to your cloud's
+ collector (an unrecognised cloud sends nothing). Org and tenant ids are sent, never the user's id.
+ Turn it off with `/model-apps:telemetry off`, or `POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT=1`
+ for automation.
## [2.12.0]
-Fixes from a retest of 2.11.0: an existing form converges to its layout's order and `--verify` checks
-more of it, a generative page keeps its name and model on update, and several readers refuse output
-they cannot read instead of guessing. A `--publish` build publishes in fewer requests, with the refreshed
-vendored SDK.
+Fixes from a retest of 2.11.0, faster `--publish` builds, and a refreshed vendored SDK.
### Added
-- **`pages[].model`** — the model id a generative page was generated with. A download writes it and
- the build sends it with every upload.
-- **`POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS`** — how long an Azure CLI call may take (default 60 s).
+- **`pages[].model`**: the model a generative page was generated with; a download writes it and
+ every upload sends it.
+- **`POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS`**: how long an Azure CLI call may take (default 60 s).
### Changed
-- **Faster `--publish` builds.** The final publish sends every table and the app in one request,
- and the enriched default views wait for it instead of publishing each table on the way: on a
- three-table app, 8 publishes became 3 and the build took 152 s instead of 172 s. A build that stops
- before its end still publishes the default views it had enriched, once no automatic retry follows.
- A failed publish of them is now a warning naming the re-run, like any other, rather than a stop
- before the forms are built; a default view someone edits while the build writes it now stops the
- build, as any concurrent edit does, instead of being skipped.
-- **The vendored SDK is refreshed.** A build that changes an app's routing description no longer
- stops with `app-header-unpublished` when the app holds an unpublished change to its name or
- descriptions: it saves alongside that change. Only a never-published app must be published first,
- and a concurrent edit is reported as one. On an org whose base language is not English, a new app
- gets its System Administrator role, and the inactive default view is enriched too.
+- **Faster `--publish` builds**: tables and the app publish in one final request. A failed
+ default-view publish is a warning naming the re-run, not a stop; a default view edited mid-build
+ stops the build.
+- **The vendored SDK is refreshed**: an unpublished name or description change no longer stops a
+ build with `app-header-unpublished` (a never-published app must still be published first), and a
+ new app on a non-English org gets its System Administrator role.
### Fixed
-- **A field moved into a narrower section fits it.** Moved without a `colspan`, a two-column field
- kept its width in a one-column section, and the build wrote a layout `--verify` then failed. It
- keeps its width only where it fits, and is narrowed — and reported — where it does not.
-- **Tabs and sections are put in the layout's order** on an existing form, with the fewest moves. A
- build used to create and move them but never reorder them, and a new tab placed between existing
- ones took over the next one, which then came back as a duplicate.
-- **`--verify` checks more of a form**: tab expanded and visible state, form-column widths, section
- visibility and label display, fields' `hidden` and `readOnly` (an auto layout's too, failing a
- flagged field the form no longer carries), and the order of tabs and sections. A form that differed
- in any of these passed. It also reads a field's state, span and section from the field itself, never
- from a quick view bound to the same lookup. Lint warns when an auto layout flags a field it does not
- place, since the build never applies that flag.
-- **A generative page keeps its name and model on update.** An update without a name renamed the
- page to its navigation title, and one without `--model` stored the model empty. `genpage-upload`
- now reads both from the deployed page and sends them again (a name a `pac.cmd` shim cannot receive
- is left out, with a warning), and a download → rebuild keeps the model. A name with a straight
- double quote is refused — pac stores each one as `\"`, in the navigation title too — and
- `/app-builder` lints one in `pages[].name`. A download no longer copies pac's backslashes into
- `pages[].name`, where each rebuild added another.
-- **Generative-page navigation parsing** is linear — a 2.5 KB page of nested template literals took
- 1.4 s, and a long comment inside one navigation call seconds more — and no longer rewrites a name
- that only resembles a navigation call, misses an optional call (`?.`), misreads a property override
- or a Unicode line terminator, or reads a word in a comment as a property.
-- **Adding pages to a solution checks every id first.** A malformed page id was refused only after
- the app had been added; nothing is added now until the app and page ids are valid, and a repeated
- id is sent once.
-- **Connector discovery refuses output it cannot read** — a warning, a changed format — instead of
- reporting no connections, rejects malformed identifiers, and no longer reads a table's dashed
- separator as a connection. The connector agent never creates a connection after a failed discovery.
-- **A slow Azure CLI or PAC is reported as slow.** A token request that ran out of time was reported
- as `az` missing or signed out; it is now `az_timeout`, with the time it was given and a longer budget
- to try — never more than the 15-minute maximum. A `pac org who` slower than its fixed 60 s is
- `pac_timeout`, to retry, not `pac_not_logged_in`.
-- **Lint no longer warns about a view, chart or form name used on two tables** — only a repeat on
- one table collides.
-- **A re-run of a failed teardown finds the generative pages it left.** When teardown could not delete
- a page, or could not read which pages the app authored, it still deleted the page manifest — the
- only record of them — so a re-run reported success and the pages stayed behind. The manifest and the
- solution are now kept until the pages step succeeds.
-- **`capture-fixture.js` no longer passes an eval it could not verify.** A runner that exited with an
- error but no failing assertion, or reported no assertions at all, was summarized as clean; each is
- now listed as a failure, with the runner's exit code.
+- **Forms converge to their layout**: a moved field is narrowed, and reported, where it does not fit
+ its new section; an existing form's tabs and sections follow the layout's order.
+- **`--verify` checks more of a form**: tab and section state and order, column widths, and fields'
+ `hidden` and `readOnly`.
+- **A generative page keeps its name and model on update**: `genpage-upload` re-sends both from the
+ deployed page. A name with a straight double quote is refused, and a download no longer adds
+ backslashes to `pages[].name`.
+- **Stricter readers**: generative-page navigation parsing is linear and misreads less, adding pages
+ to a solution checks every id first, and connector discovery refuses output it cannot read.
+- **Timeouts are named**: a slow token request is `az_timeout`, a slow `pac org who` is
+ `pac_timeout`, not a sign-in error.
+- **A re-run of a failed teardown finds the generative pages it left**, and lint no longer flags a
+ name reused on another table.
+- **`capture-fixture.js` no longer passes an eval it could not verify.**
## [2.11.0]
-AI features are written with each setting's own values, rebuilding an existing app no longer
-rewrites its navigation, a table opens with the form the spec makes its default, and the vendored
-SDK is refreshed.
+AI feature values, navigation and default-form fixes, and a refreshed SDK.
### Added
-- **`entities[].mainFormOrder`** (AB#6736948) — a table's Main forms in the order they are offered,
- first to last; the first is the one the table opens with. Works on existing tables.
+- **`entities[].mainFormOrder`** (AB#6736948): a table's Main forms in offer order; the table opens
+ with the first. Works on existing tables.
### Fixed
-- **A table opens with its default form** (AB#6736948). What opens is decided by the order of a
- table's Main forms, not the default flag, and new forms all share one position — so a table with
- several Main forms could open with an alternate one. The build now also puts the default form
- first, and `--verify` checks the order. `isDefault` on an existing table used to be ignored; a form
- the build adds to an existing table now goes after its other Main forms.
-- **A teardown no longer stops when Dataverse is busy.** A delete refused with 429 (another
- customization still running) is re-sent like other throttled requests; the solution delete that
- ends a teardown used to fail and leave the solution behind.
-- **Download reads what is deployed.** It no longer reads through the folder's `.maker-workspace`,
- where a copy an interrupted build left could make it fail or return edits never deployed.
-- **Rebuilding an existing app keeps its navigation as it is** (AB#6726727). Every nav entry was
- rewritten as a new one, so an unrelated edit turned a designer-made dashboard entry's icon into a
- placeholder and dropped its other settings. Entries now keep their id and everything the spec does
- not describe; dashboard entries carry the designer's launcher Url, and `--verify` fails one without
- it.
-- **A nav title or icon changed in the designer after a download is kept**, with a warning, instead of
- being reverted by the stale spec. Download records the spec as a baseline for that environment.
-- **A dashboard renamed in the designer** is reused by the id a download now records
- (`dashboards[].dashboardId`); it used to be recreated under the old name.
-- **AI feature values** (AB#6714731). `true` wrote `1` outside the form-fill family: *Off* for
- natural-language grid search and M365 Copilot, *Auto* for NL charts, and `--verify` expected the
- same. `true` now writes `2` (*On*) for every feature, so the next build of an AI-enabled app turns
- NL grid search back on. `false` writes that setting's *Off*: `1`, or `0` for NL charts.
-- **`ai-preflight`** no longer shows ✓ for an app with M365 Copilot off, and reports NL charts' *Auto*
- as the platform default rather than on.
-- **`appShell` keys the build does not read are errors** ([#631]). A `title` on an area or group (they
- take `label`) used to deploy an untitled one while lint, the build and `--verify` passed.
-- **A SQL deadlock no longer fails a delete or a build.** A request SQL rolled back as a deadlock
- victim is re-sent (up to three times): a record delete, or an app delete's change set, by the
- plugin; a read, an app create or a publish by the refreshed SDK. A build that halts on one runs
- again like one that halts on a SQL timeout; a teardown used to stop on it.
+- **A table opens with its default form** (AB#6736948): the build puts the default form first,
+ honours `isDefault` on an existing table, and `--verify` checks the order.
+- **Rebuilding an existing app keeps its navigation** (AB#6726727): entries keep their id and
+ everything the spec does not describe, and dashboard entries carry the designer's launcher Url.
+- **Designer edits after a download are kept**: a changed nav title or icon stays (with a warning),
+ and a renamed dashboard is reused by `dashboards[].dashboardId`.
+- **AI feature values** (AB#6714731): `true` now writes `2` (*On*) for every feature; rebuilding an
+ AI-enabled app turns NL grid search back on.
+- **`ai-preflight`** no longer shows ✓ with M365 Copilot off, and reports NL charts' *Auto* as the
+ platform default.
+- **`appShell` keys the build does not read are errors** ([#631]), e.g. a `title` on an area or
+ group, which take `label`.
+- **Busy and deadlocked requests are re-sent**: a 429 on a delete no longer stops a teardown, and a
+ SQL deadlock (up to three retries) no longer fails a delete or build.
+- **Download reads what is deployed**, not a copy an interrupted build left in `.maker-workspace`.
### Changed
-- **The vendored SDK is refreshed.** A workspace saved by an earlier version is re-read on the next
- build; a copy an interrupted build left holding unpushed edits halts it and names the step to take.
- A remedy that asks you to clear `.maker-workspace` now says to stop other runs on it first and to
- keep `last-applied.json` and `destructive-approval.json`.
-- **An explicit `false` for NL grid search or M365** now writes *Off* (`1`) instead of the platform
- default (`0`). A spec that omits `m365` still leaves it at `0`.
-
-[#631]: https://github.com/microsoft/power-platform-skills/issues/631
+- **The vendored SDK is refreshed.** A leftover copy with unpushed edits halts the build; a remedy
+ to clear `.maker-workspace` says to stop other runs first and keep `last-applied.json` and
+ `destructive-approval.json`.
+- **An explicit `false`** writes that setting's *Off*: `1` (for NL grid search and M365, instead of
+ the platform default `0`), or `0` for NL charts. A spec that omits `m365` still leaves it at `0`.
## [2.10.0]
-Connector authoring loses its feature flag, `--allow-destructive` removes only what a maker was
-shown, and the vendored SDK is refreshed.
+Connector authoring loses its flag, `--allow-destructive` removes only what was shown, and the SDK
+is refreshed.
### Changed
-- **The `connectors` feature flag is removed**, with `GENPAGE_ENABLE_CONNECTORS`: it was on by default
- for a release with no rollback needed. Connector authoring stays in public preview. An unknown flag
- now stays off even when a matching env var is set.
-- **Faster preflight and `/genpage` updates.** `check-auth` overlaps its CLI cold starts (24–32 s →
- 16–19 s on Windows), scripts reuse one `az` token per process, and an update's two target checks
- run together (10.6 s → 5.6 s).
-- **The vendored SDK is refreshed.** *Contains data* and *does not contain data* conditions in
- business rules are sent in the shape the platform's designer writes, and the bundle stays under 1 MB.
+- **The `connectors` feature flag is removed**, with `GENPAGE_ENABLE_CONNECTORS`; connector
+ authoring stays in public preview. An unknown flag now stays off even when a matching env var is
+ set.
+- **Faster preflight and `/genpage` updates** (overlapped CLI cold starts, one `az` token per
+ process).
+- **The vendored SDK is refreshed**: business-rule *contains data* and *does not contain data*
+ conditions are sent in the designer's shape.
### Fixed
-- **`--allow-destructive` removes only what a maker was shown.** A refusal records its list in
- `.maker-workspace/destructive-approval.json`; the approved re-run halts, naming the new ones, if
- anything else would now be removed.
-- **`prune: false` forms** no longer report, or demand approval for, removals that never happen.
-- **Switching a table's default Main form** clears the old default; verify fails while two hold it.
-- **Row-spanning cells** count wherever the build fits a layout, and a removed field no longer leaves
- an empty form row.
+- **`--allow-destructive` removes only what a maker was shown**: a refusal records its list in
+ `.maker-workspace/destructive-approval.json`; an approved re-run halts if anything else would be
+ removed.
+- **Forms**: `prune: false` no longer reports or demands approval for removals that never happen;
+ switching the default Main form clears the old one; row-spanning cells count in every layout fit,
+ and a removed field leaves no empty row.
- **A `/genpage` update must name the page's own app**; another app's id used to rename the page.
-- **Non-ASCII text** split across response or hook chunks is no longer turned into U+FFFD.
- **pac on Windows**: a path ending in `\` no longer swallows the next argument, and a malformed page
- listing or page id is no longer trusted.
-- **Navigation keys**: a quoted key resolves like a bare one, a duplicated key counts where it takes
+ listing or id is not trusted.
+- **Navigation keys**: a quoted key resolves like a bare one, a duplicate counts where it takes
effect, and a target a later spread could replace is refused.
- **Downloads** refuse a malformed page `dataSources`, keep a page prompt's exact text, and read past
1,000 components.
-- **The version check** no longer fetches your project's repository.
+- **Non-ASCII text** split across chunks no longer becomes U+FFFD, and the version check no longer
+ fetches your repository.
### Removed
@@ -1455,95 +390,51 @@ shown, and the vendored SDK is refreshed.
### Documentation
-- Corrected what a rebuild re-applies to existing artifacts, what `--verify` proves (it does not catch
- a removed view column), and BPF security-role grants. A page's connector and Custom API bindings
- survive only a same-environment rebuild. The telemetry disclosure matches its shared source again.
+- Corrected what a rebuild re-applies, what `--verify` proves, and BPF security-role grants; a
+ page's connector and Custom API bindings survive only a same-environment rebuild.
## [2.9.0]
-A dry run that says what an apply would really do, sample data that can express a hierarchy, and
-downloads that round-trip Choice columns.
-
### Added
-- **`app.aiDescription`**, a routing description agents read to choose between sibling apps
- ([#583]). It is written, downloaded and verified; leave it out and the deployed value is untouched.
-- **`personas[].excludes[]`** records what an app deliberately leaves out ([#583]).
-- **Richer form layouts**: multi-column tabs, cell `colspan`/`rowspan`, and
- `expanded`/`visible`/`showLabel`.
-- **A live dry run** marks each item create, reuse or unknown ([#559]); `--no-live-plan` keeps the
+- **`app.aiDescription`** routes agents between sibling apps; **`personas[].excludes[]`** records what
+ an app leaves out ([#583]).
+- **Form layouts**: multi-column tabs, cell `colspan`/`rowspan`, `expanded`/`visible`/`showLabel`.
+- **A live dry run** marks items create, reuse or unknown ([#559]); `--no-live-plan` keeps the
offline listing.
-- **Hierarchies in sample data**: `$parent` may target the row's own table ([#544]), and
- `$parent.lookup` is now required when two relationships connect the same pair.
+- **Sample-data hierarchies**: `$parent` may target the row's own table ([#544]); `$parent.lookup` is
+ now required when two relationships connect the same pair.
- **`minimumPluginVersion`** refuses a spec newer than the plugin.
-- **The vendored SDK uses injected storage** (`createNodeWorkspaceStorage`), a breaking change only
- for library callers.
+- **The vendored SDK uses injected storage** (`createNodeWorkspaceStorage`): breaking for library
+ callers only.
### Changed
-- **`/app-builder` is GA**; `--changed-only` stays experimental and off by default.
-- **Connector authoring is on by default** (public preview); the `connectors` flag stays for one
- release as a rollback switch.
-- **The App Spec schema is split** (the always-read half is 82 KB, down from 105 KB), and every script
- shares one CLI flag contract.
-- **`write-page-plan.js` no longer takes `--out`**; it writes only a plain file in the working
- directory.
+- **`/app-builder` is GA**; `--changed-only` stays experimental, off by default. **Connector
+ authoring is on by default** (public preview); the `connectors` flag stays one release.
+- **`write-page-plan.js` no longer takes `--out`**: it writes only a plain working-directory file.
### Fixed
-- **Forms**: an explicit layout reshapes a form instead of flattening it ([#575]); a named section
- moves to the tab the spec puts it in; spans converge against the live grid ([#581]) without breaking
- a maker's row-spanning layout; the wireframe shows `hidden` and `readOnly` fields ([#591]).
-- **Business rules**: `dataType` reaches Dataverse as a real type. Rebuild any app whose
- `businessRules[]` were built on an earlier release.
-- **Verify** checks form layout, sort precedence, sitemap-table membership, the default Main form,
- view filters and app roles, and judges spans by the build's own rules.
-- **`/genpage`** deploys through the quoting-safe upload path ([#589]), keeps multi-line prompts
- ([#565]) and a page's bindings on update, refuses to update a page that does not exist, runs only
- the approved plan ([#585]), catches truncated pages, and checks page file names before any worker
- writes ([#588]).
-- **Page listings, page ids and PAC errors** are parsed strictly, so a page name cannot forge a
- listing and PAC's real error is reported.
-- **Icons and navigation calls are checked from code, not prose** ([#585], [#588]), and right-to-left
- layout follows PAC's RTL column rather than a fixed list of languages ([#585]).
-- **Downloads** round-trip Choice columns ([#564]), relationships ([#567]) and page table bindings,
- invent no columns ([#574]), pass their own lint ([#572]), and pick an app's solution
- deterministically ([#587]).
-- **Dashboards**: same-named charts on different tables no longer cross-wire a tile, and a dashboard
- belongs to an app through its solution ([#586]).
-- **Teardown and workspaces**: `--clear-workspace` deletes only a real workspace; teardown stops when
- the app delete fails, keeps a downloaded spec's relationships and choices and any security role whose
- sharing check cannot be read, and fences in-flight `--changed-only` runs ([#587]).
-- **Links**: `generate-page-manifest --force` refuses to write through a symlink or hard link, and
- `genpage-upload.js` refuses an input file that is a link, a hard link or a folder.
-- **Writes**: a slow one is waited for (up to 5 minutes) rather than re-sent.
-- **Validation**: a mistyped flag fails instead of changing the command, and sample data is checked
- before anything deploys.
-- **The vendored SDK is refreshed** (including `@xmldom/xmldom` 0.8.15); an app with an unpublished
- sitemap edit can now be torn down.
+- **Business rules**: `dataType` reaches Dataverse as a real type; rebuild any app whose
+ `businessRules[]` were built before 2.9.0.
+- **Forms** take an explicit layout's shape ([#575]) and spans ([#581]); the wireframe shows `hidden`
+ and `readOnly` fields ([#591]).
+- **`/genpage`** uses the quoting-safe upload path ([#589]), keeps multi-line prompts ([#565]) and
+ bindings on update, runs only the approved plan ([#585]) and checks page file names first ([#588]).
+- **Downloads** round-trip Choice columns ([#564]) and relationships ([#567]), invent no columns
+ ([#574]) and pass their own lint ([#572]).
+- **Dashboards** belong to an app through its solution ([#586]).
+- **Safety**: `--clear-workspace` deletes only a real workspace; teardown stops when the app delete fails ([#587]) and keeps
+ a downloaded spec's relationships and choices and any security role whose sharing check cannot be read;
+ `generate-page-manifest --force` and `genpage-upload.js` refuse links.
+- **The vendored SDK is refreshed** (`@xmldom/xmldom` 0.8.15).
### Known limitations
-- **Choice option values do not round-trip**: labels and order do, and a fresh rebuild re-bases the
- values to `100000000 + index`.
-- **An existing view's authored filters and sort are not re-applied** by a rebuild.
+- **Choice option values do not round-trip** (a rebuild re-bases them to `100000000 + index`); a
+ rebuild skips existing views' authored filters and sort.
-[#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
-[#583]: https://github.com/microsoft/power-platform-skills/issues/583
-[#585]: https://github.com/microsoft/power-platform-skills/issues/585
-[#586]: https://github.com/microsoft/power-platform-skills/issues/586
-[#587]: https://github.com/microsoft/power-platform-skills/issues/587
-[#588]: https://github.com/microsoft/power-platform-skills/issues/588
-[#589]: https://github.com/microsoft/power-platform-skills/issues/589
-[#591]: https://github.com/microsoft/power-platform-skills/issues/591
## [2.7.1]
Three defects an author hits before reaching an environment, and a session-start warning.
@@ -1562,16 +453,10 @@ Three defects an author hits before reaching an environment, and a session-start
value now warns.
- **No more `hooks.json: unknown key "_comment"` warning** at session start ([#555], [#558]).
-[#542]: https://github.com/microsoft/power-platform-skills/issues/542
-[#545]: https://github.com/microsoft/power-platform-skills/issues/545
-[#546]: https://github.com/microsoft/power-platform-skills/issues/546
-[#555]: https://github.com/microsoft/power-platform-skills/issues/555
-[#558]: https://github.com/microsoft/power-platform-skills/issues/558
-[#560]: https://github.com/microsoft/power-platform-skills/issues/560
## [2.7.0]
-Multi-language Dataverse labels, granting access on roles this spec does not own, and the
-app-builder defects found while rebuilding a real app into a second environment.
+Multi-language Dataverse labels, granting access on roles this spec does not own, and app-builder
+fixes from rebuilding a real app into a second environment.
### Added
@@ -1604,30 +489,24 @@ app-builder defects found while rebuilding a real app into a second environment.
- **SDK uptake `cds-maker-sdk 331b9f56`** for the platform halves of these fixes.
- **Two label rules are relaxed**: a blank plain label is accepted, and a duplicate plain option
label warns.
-- **The role-privilege read uses the SDK's `getEntityPrivileges`**, with no behaviour change.
### Known limitations
- **A single-language label loses its LCID on download.** Pin `languageCode` before a
cross-organization rebuild.
-[#537]: https://github.com/microsoft/power-platform-skills/issues/537
-[#513]: https://github.com/microsoft/power-platform-skills/issues/513
## [2.6.1]
+
### Fixed
-- **A table key the build cannot honour now fails instead of being dropped** ([#537]).
- `entities[].languageCode` and `entities[].localizedLabels` validated clean and were then silently
- ignored, so asking for one table in Spanish produced a successful build with the request gone.
- Unknown table keys are now rejected and the error names what to write instead. (2.7.0 adds
- multi-language labels as an LCID map on the label field itself.)
+- **A table key the build cannot honour now fails instead of being dropped** ([#537]):
+ `entities[].languageCode` and `entities[].localizedLabels` used to validate clean and then be
+ silently ignored. Unknown table keys are rejected, and the error names what to write instead.
- **The `languageCode` error says what to write** — a concrete LCID, and an explicit rejection of a
language tag, which would otherwise build every label in the wrong language.
- **A non-string `entities[].schemaName` is an error, not a raw `TypeError`** that discarded every
other problem found so far.
-[#537]: https://github.com/microsoft/power-platform-skills/issues/537
-
## [2.6.0]
Business process flows, plus an SDK uptake that changes how business rules fail on an environment
@@ -1635,37 +514,32 @@ that cannot host them.
### Added
-- **`businessProcessFlows[]` — guided, staged processes on a table.** Ordered stages with steps bound
- to that table's columns, activated on create. v1 is single-entity and linear — branching, stage
+- **`businessProcessFlows[]`: guided, staged processes on a table.** Ordered stages with steps bound
+ to that table's columns, activated on create. v1 is single-entity and linear; branching, stage
actions and role grants ([#513]) are rejected rather than silently dropped.
### Changed
-- **A business rule is validated before it is written.** A rule the SDK's compiler cannot understand
+- **A business rule is validated before it is written.** One the SDK's compiler cannot understand
used to deploy as an empty rule that never fires; the build now runs the designer's own validator
and fails with its findings.
### Fixed
-- **A build no longer halts on an environment that cannot host business rules** — those rules are
- skipped with a warning again, which matters because such environments are the common case.
+- **A build no longer halts on an environment that cannot host business rules**: those rules are
+ skipped with a warning again.
- **A failed push reports the SDK's own reason** instead of always blaming a concurrent Maker edit,
and a `VERSION_CONFLICT` still tells you to re-download.
-- **Download round-trips `app.newLook` and `app.headerNavigationRefresh`** ([#514]) — a rebuild
- elsewhere previously produced a classic-shell app with nothing reporting the loss.
-- **`views[].columns` rejects a non-string entry** ([#525]). An object reached the view's fetchxml as
- `[object object]` and left behind a view row that could not be read or deleted, so every later
- build failed the same way.
-- **A business process flow whose derived unique name is already taken is refused up front** — that
- name becomes a *table* name on activation, so a flow named after its own table collided silently.
+- **Download round-trips `app.newLook` and `app.headerNavigationRefresh`** ([#514]); a rebuild
+ elsewhere used to produce a classic-shell app without reporting the loss.
+- **`views[].columns` rejects a non-string entry** ([#525]), which used to leave a view row that
+ could not be read or deleted, so every later build failed.
+- **A business process flow whose derived unique name is already taken is refused up front**: that
+ name becomes a *table* name on activation.
- **A reused business rule rejoins its solution on every build**, so it travels on export/import.
- **A non-string table reference is rejected instead of coerced** (`charts[].entity`, a subgrid's
`childEntity`, a sitemap subarea's `entity`, a dashboard tile's `entity`).
-[#513]: https://github.com/microsoft/power-platform-skills/issues/513
-[#514]: https://github.com/microsoft/power-platform-skills/issues/514
-[#525]: https://github.com/microsoft/power-platform-skills/issues/525
-
## [2.5.1]
SDK uptake. Adds per-form security roles and three column capabilities; **business rules now require
@@ -1702,12 +576,6 @@ an environment that supports them**.
license is skipped.
- **A missing `appShell` or a malformed `businessRules`** is a validation error, not a crash.
-[#478]: https://github.com/microsoft/power-platform-skills/issues/478
-[#481]: https://github.com/microsoft/power-platform-skills/issues/481
-[#493]: https://github.com/microsoft/power-platform-skills/issues/493
-[#494]: https://github.com/microsoft/power-platform-skills/issues/494
-[#495]: https://github.com/microsoft/power-platform-skills/issues/495
-[#496]: https://github.com/microsoft/power-platform-skills/issues/496
## [2.5.0]
Takes up the current maker SDK, adds modern-shell and navigation controls, labels Dataverse
@@ -1748,10 +616,6 @@ and jobs-to-be-done checkable.
- **A classic dashboard's tiles are not recovered on download**; the download fails unless
`--allow-lossy-download` accepts that loss.
-[#430]: https://github.com/microsoft/power-platform-skills/issues/430
-[#447]: https://github.com/microsoft/power-platform-skills/issues/447
-[#455]: https://github.com/microsoft/power-platform-skills/issues/455
-[#456]: https://github.com/microsoft/power-platform-skills/issues/456
## [2.4.2]
Fixes a malformed app module: generated apps did not actually contain their tables.
@@ -1760,16 +624,16 @@ Fixes a malformed app module: generated apps did not actually contain their tabl
- **Generated apps contained an invalid `entity` table component instead of their real tables**
(ADO 6612527), which also broke unrelated app-processing paths. Tables are now pinned by OData
- **reference** — the only form that can also express an abstract table such as `activitypointer`.
-- **An unresolvable table halts the build, naming it.** One bad component fails the whole
- `AddAppComponents` call, so a silently-skipped table used to empty the app's component list.
-- **App components are read back and verified after the write** — the write returned 204 for every
- corrupt app, and `ValidateApp` reported success too.
+ **reference**.
+- **An unresolvable table halts the build, naming it**; a silently skipped one used to empty the
+ app's component list.
+- **App components are read back and verified after the write**; the write and `ValidateApp` both
+ reported success for a corrupt app.
### Known limitations
-- **Download still drops entity components not in the sitemap** (ADO 6603388) — the hidden component
- it describes could not be constructed live, so the download-side fix is unverified.
+- **Download still drops entity components not in the sitemap** (ADO 6603388); the download-side
+ fix is unverified.
## 2.4.1
@@ -1778,23 +642,20 @@ any skill's public surface.
### Fixed
-- **AI app features had no effect on a newly built app** — an app-scope setting write is a no-op
- until the app is published, so the build wrote nothing while reporting success. **`--verify` passed
- when they were never applied**; it now proves an app-scope override row, because reading the
- setting back falls through to the environment value.
+- **AI app features had no effect on a newly built app**: an app-scope setting write is a no-op
+ until the app is published, yet the build reported success. **`--verify` passed anyway**; it now
+ proves an app-scope override row.
- **`ai.appFeatures` accepts non-boolean values** such as `2` ("on for everyone").
- **Download invented primary-name columns**, **replaced the solution's publisher prefix with
`new`**, and **dropped tables with no sitemap entry** — all three now read from Dataverse.
-- **Teardown could permanently burn an app's unique name** — an app is two rows with no server-side
- cascade, so deleting only the app module stranded the sitemap and reserved its name forever. Both
- rows are now deleted atomically in one OData `$batch`.
+- **Teardown could permanently burn an app's unique name** by stranding its sitemap; the app module
+ and its sitemap are now deleted atomically in one OData `$batch`.
### Changed
- Re-vendored `cds-maker-sdk`. An injected `HttpClient` must now implement `postRaw` for the atomic
`$batch`.
-- **model-apps now runs in CI** (ubuntu × windows × macos, Node 20 × 22, plus the offline evals) —
- previously every test workflow was scoped to another plugin, so this suite never ran on a PR.
+- **model-apps now runs in CI** (ubuntu × windows × macos, Node 20 × 22, plus the offline evals).
## 2.4.0
@@ -1803,48 +664,34 @@ local-dev ergonomics, sample coverage, and an automated eval suite. No breaking
### Added
-- **`/app-builder` (Preview)** — natural-language intent → deployed model-driven app: tables,
- columns, relationships, adaptive forms with sub-grids, views, charts, dashboards, generative
- pages, app + sitemap, and sample data, via the headless vendored `cds-maker-sdk`.
-- **Jobs-to-be-done drive the design** — authoring starts by asking who uses the app and what each
- of them needs to get done, *before* the data model.
-- **Security roles per persona (`personas[]`)** — one role per persona, sized to the privileges its
- jobs declare, associated with the app so it opens for non-admins.
-- **`model-app-plan.md`** — a readable, regenerable design document rendered from the spec, plus
- design-gap warnings at the lint gate.
-- **Table icons are described before they are drawn** — each table proposes what its glyph will
- *depict* in plain language, shown for approval before any SVG is authored.
-- **AI-first features** (`ai` block) — form fill, NL search, NL charts, M365 Copilot and row
+- **`/app-builder` (Preview)**: natural-language intent → deployed model-driven app (tables, forms,
+ views, charts, dashboards, generative pages, app + sitemap, sample data) via the headless vendored
+ `cds-maker-sdk`.
+- **Security roles per persona (`personas[]`)**, sized to each persona's jobs and associated with the
+ app so it opens for non-admins.
+- **`model-app-plan.md`**, a design document rendered from the spec, and **`scripts/preview-app.js`**
+ to review the design before building.
+- **AI-first features** (`ai` block): form fill, NL search, NL charts, M365 Copilot and row
summaries, admin-gated by a preflight.
-- **`--changed-only` partial apply (Preview, off by default)** — a page-only `.tsx` edit re-runs just
- the pages phase; anything else falls back to a full build.
-- **`scripts/preview-app.js`** to review the whole design before building.
+- **`--changed-only` partial apply (Preview, off by default)**: a page-only `.tsx` edit re-runs just
+ the pages phase.
### Changed
-- **Edits are first-class**: forms and views update in place, a form edit can *remove* a field, a
- built main form becomes the entity default, and editing an existing app updates the sitemap for
- page-less apps too.
-- **Identity is unambiguous** — forms resolve by `(entity, name, type)`, views by `entity|name`, and
- an app round-trips by its real `uniquename`, so a rebuild cannot duplicate or cross-wire.
-- **Page generation reuses the `/genpage` worker** through a plan adapter, so an intent page can no
- longer silently fail to become `.tsx`.
-- Re-vendored `cds-maker-sdk` (pagination, quick create, idempotent global choice, authored column
- width, shared input-safety boundaries).
+- **Edits are first-class**: forms and views update in place, a form edit can *remove* a field, and
+ a built main form becomes the entity default.
+- **Identity is unambiguous**: forms resolve by `(entity, name, type)`, views by `entity|name`, and
+ an app by its real `uniquename`, so a rebuild cannot duplicate or cross-wire.
+- Re-vendored `cds-maker-sdk`; page generation reuses the `/genpage` worker.
### Fixed
-- **Teardown removes everything the app owns** — icon and app-icon web resources are removed, cascade
- failures are reported rather than silently orphaning rows, and reused/system tables are skipped
- with a reason. The **publisher** is deliberately left behind: it can own other solutions, so
- removing it is not this app's decision.
-- **Exported solutions are self-contained** — the app icon and sitemap are added to the solution.
-- **The Dataverse token is never sent to another origin** — the HTTP client refuses any request
- outside the absolute `https` org URL.
-- **A lossy download fails instead of reporting success** (`--allow-lossy-download` opts in), and
- **CLI flags fail loudly** — notably `--apply --only` with no phase list used to run a *full* apply.
-- Assorted: relationships to system tables, classic dashboard round-trip, AI row summaries, and
- sub-grid `targetEntity`.
+- **Teardown removes everything the app owns** and reports cascade failures; reused/system tables
+ are skipped. The **publisher** is deliberately left behind: it can own other solutions.
+- **Exported solutions are self-contained**, and **the Dataverse token is never sent to another
+ origin**.
+- **A lossy download fails** (`--allow-lossy-download` opts in), and **CLI flags fail loudly**:
+ `--apply --only` with no phase list used to run a *full* apply.
### Removed
@@ -1853,8 +700,8 @@ local-dev ergonomics, sample coverage, and an automated eval suite. No breaking
### Known limitations
-- **App EDIT does not re-pin a new chart** as an explicit app component — a chart added to an
- existing app needs a manual pin or a rebuild.
+- **App EDIT does not re-pin a new chart**: a chart added to an existing app needs a manual pin or a
+ rebuild.
## 2.3.0 — 2026-07-23
@@ -1864,20 +711,18 @@ Plugin observability and authoring guardrails. No breaking changes.
- **Anonymous 1DS telemetry** (default-on, ships `disabled` until provisioned) with a local
diagnostic mirror, a `/model-apps:telemetry on|off|status` control skill, and a CI opt-out via
- `POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT=1`. Fail-closed throughout, and carries **no
- user-level identifier**.
+ `POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT=1`. Fail-closed, with **no user-level
+ identifier**.
- **PostToolUse validators**, including a `@fluentui/react-icons` allowlist check that blocks a
hallucinated icon name at write time.
-- **PreToolUse write-safety guard** — flags writes outside the cwd during an active genpage session
- only, so a globally-installed plugin never interferes with unrelated work.
+- **PreToolUse write-safety guard**: flags writes outside the cwd, only during an active genpage
+ session.
### Fixed
-- **Generated-page double-fetch / render flash on open.** The webplayer host double-mounts a page and
- `dataApi` is a new reference each render, so a `useEffect` dep on it re-fires forever. Guidance and
- every exemplar now use an in-flight-promise de-dupe plus a window cache; `dataApi` is forbidden in
- any dependency array.
-- **Playwright MCP launcher** — exports `launch()` per the `.mcp.json` contract, avoids the npx
+- **Generated-page double-fetch / render flash on open**: guidance and every exemplar de-dupe
+ in-flight fetches with a window cache, and `dataApi` is forbidden in any dependency array.
+- **Playwright MCP launcher** exports `launch()` per the `.mcp.json` contract, avoids the npx
first-run prompt hang, and quotes config paths so Windows paths with spaces work.
## 2.2.0
@@ -1900,7 +745,6 @@ Local-dev ergonomics, sample coverage, and an automated eval suite. No breaking
- **`queryTable` returns a `DataTable`, not an array** — 7 samples and fixtures iterated the result
directly, producing `X.map is not a function` at runtime.
-
## 2.1.0 — 2026-05-13
Replaces the Dataverse MCP server + Python SDK fallback with Node.js Web API scripts. Adds solution
@@ -1960,3 +804,44 @@ Major refactor of `/genpage` into an agent-orchestrated architecture.
PageInput support, FluentProvider flicker fix, lookup `$select` rule, data caching pattern. See git
history for details.
+
+[#680]: https://github.com/microsoft/power-platform-skills/issues/680
+[#705]: https://github.com/microsoft/power-platform-skills/issues/705
+[#673]: https://github.com/microsoft/power-platform-skills/issues/673
+[#631]: https://github.com/microsoft/power-platform-skills/issues/631
+[#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
+[#583]: https://github.com/microsoft/power-platform-skills/issues/583
+[#585]: https://github.com/microsoft/power-platform-skills/issues/585
+[#586]: https://github.com/microsoft/power-platform-skills/issues/586
+[#587]: https://github.com/microsoft/power-platform-skills/issues/587
+[#588]: https://github.com/microsoft/power-platform-skills/issues/588
+[#589]: https://github.com/microsoft/power-platform-skills/issues/589
+[#591]: https://github.com/microsoft/power-platform-skills/issues/591
+[#542]: https://github.com/microsoft/power-platform-skills/issues/542
+[#545]: https://github.com/microsoft/power-platform-skills/issues/545
+[#546]: https://github.com/microsoft/power-platform-skills/issues/546
+[#555]: https://github.com/microsoft/power-platform-skills/issues/555
+[#558]: https://github.com/microsoft/power-platform-skills/issues/558
+[#560]: https://github.com/microsoft/power-platform-skills/issues/560
+[#537]: https://github.com/microsoft/power-platform-skills/issues/537
+[#513]: https://github.com/microsoft/power-platform-skills/issues/513
+[#514]: https://github.com/microsoft/power-platform-skills/issues/514
+[#525]: https://github.com/microsoft/power-platform-skills/issues/525
+[#478]: https://github.com/microsoft/power-platform-skills/issues/478
+[#481]: https://github.com/microsoft/power-platform-skills/issues/481
+[#493]: https://github.com/microsoft/power-platform-skills/issues/493
+[#494]: https://github.com/microsoft/power-platform-skills/issues/494
+[#495]: https://github.com/microsoft/power-platform-skills/issues/495
+[#496]: https://github.com/microsoft/power-platform-skills/issues/496
+[#430]: https://github.com/microsoft/power-platform-skills/issues/430
+[#447]: https://github.com/microsoft/power-platform-skills/issues/447
+[#455]: https://github.com/microsoft/power-platform-skills/issues/455
+[#456]: https://github.com/microsoft/power-platform-skills/issues/456
diff --git a/plugins/model-apps/README.md b/plugins/model-apps/README.md
index fe8e14403..db952b057 100644
--- a/plugins/model-apps/README.md
+++ b/plugins/model-apps/README.md
@@ -41,52 +41,56 @@ no timeout setting, for pages.
## Feature flags (defaults and overrides)
Some capabilities ship **OFF by default** while their cross-repo dependencies roll
-out to production. **Supported public Custom API discovery is ON by default**; custom
-telemetry remains OFF. An explicit Custom API opt-out stops new discovery/authoring without
-clearing existing bindings during unrelated edits. Flags are catalogued (with lifecycle
-status) in `scripts/lib/feature-flags.js`; their on/off value lives in
-`feature-flags.json` at the plugin root.
+out to production: custom telemetry and built-in Dataverse operation authoring are OFF.
+Flags are catalogued (with lifecycle status) in `scripts/lib/feature-flags.js`; their on/off
+value lives in `feature-flags.json` at the plugin root.
| Flag | Status | Default | Enables | Depends on |
|---|---|---|---|---|
-| `custom-api` | in-progress | ON | Calling a supported public Dataverse Custom API Action or Function from a generated page (`executeAction` / `executeFunction` / `listBoundActions`) | the action prompt and host runtimes, revision-bound `actionBindings`, environment governance and the signed-in user's privileges |
| `custom-telemetry` | in-progress | OFF | A generated page reporting its own events, metrics, traces and exceptions to your Application Insights resource via `props.appInsights` | the page telemetry facade in the UCI host runtime, the GenUX authoring control, the AIBuilder telemetry prompt, and the `GenUxEnableCustomTelemetry` setting — all live in PROD |
+| `dataverse-operations` | experimental | OFF | Offering two reviewed built-in Dataverse Functions, WhoAmI and RetrieveVersion, as explicitly selected, button-only page calls (`executeFunction`); `scripts/list-dataverse-operations.js` lists them without contacting the environment | a host runtime that implements `executeFunction`, the page `actionBindings` the plugin writes, and the `GenUxPluginActionAllowList` setting; the environment, the page player and the signed-in user's permissions are not checked — see [the built-in operations reference](references/dataverse-operations.md) |
Connector authoring is in **public preview** and no longer has a feature flag. Connector discovery, binding, deploy, and ALM packaging are always available when the required PAC and host capabilities are present.
+Custom API support has no feature flag either: calling a supported public Dataverse Custom API
+Action or Function from a generated page (`executeAction` / `executeFunction` /
+`listBoundActions`) is always available. `GENPAGE_ENABLE_CUSTOM_API` is ignored — `0` no longer
+turns Custom API discovery off, and there is nothing to turn on. The host runtimes,
+revision-bound `actionBindings`, environment governance and the signed-in user's privileges
+still apply.
+
**See the current state** (status, whether each flag is on, and why):
```bash
node scripts/lib/feature-flags.js --list
```
-**Disable Custom API discovery for a single run** via an environment variable (highest precedence):
+**Turn a flag on for a single run** via an environment variable (highest precedence):
```powershell
# Windows (PowerShell)
-$env:GENPAGE_ENABLE_CUSTOM_API = "0"
+$env:GENPAGE_ENABLE_DATAVERSE_OPERATIONS = "1"
```
```bash
# macOS / Linux (bash)
-export GENPAGE_ENABLE_CUSTOM_API=0
+export GENPAGE_ENABLE_DATAVERSE_OPERATIONS=1
```
-**Disable it persistently** by changing its committed value in `feature-flags.json`:
+**Turn it on persistently** by changing its committed value in `feature-flags.json`:
```json
-{ "custom-api": false }
+{ "dataverse-operations": true }
```
Precedence is **env var → `feature-flags.json` → default OFF** for missing/unset
-configuration (fail-closed); it does not override Custom API's committed ON default.
-Use `GENPAGE_ENABLE_CUSTOM_API=1` to explicitly enable a run. Host capabilities and server
-governance still apply; enabling discovery grants no new privileges.
+configuration (fail-closed). Host capabilities and server governance still apply; turning a
+flag on grants no new privileges.
The env var name is always `GENPAGE_ENABLE_` plus the flag name in upper case, with
-`-` turned into `_` (`custom-api` → `GENPAGE_ENABLE_CUSTOM_API`), and unknown flags stay disabled even if
-a matching env var is set.
+`-` turned into `_` (`dataverse-operations` → `GENPAGE_ENABLE_DATAVERSE_OPERATIONS`), and unknown
+flags stay disabled even if a matching env var is set.
-Discovery omits private APIs and APIs with Entity/EntityCollection inputs or outputs.
+Custom API discovery omits private APIs and APIs with Entity/EntityCollection inputs or outputs.
Lookup input names stay available to the author separately from the primitive-only wire
`parameterKinds`; see [the Custom API contract](references/custom-api.md).
diff --git a/plugins/model-apps/agents/genpage-customapi-builder.md b/plugins/model-apps/agents/genpage-customapi-builder.md
index 3a87be3d7..705196bd1 100644
--- a/plugins/model-apps/agents/genpage-customapi-builder.md
+++ b/plugins/model-apps/agents/genpage-customapi-builder.md
@@ -1,10 +1,11 @@
---
name: genpage-customapi-builder
description: >-
- Owns ALL GenPage Dataverse Custom API (plug-in) work: it is the single owner of the
- custom-api feature-flag gate, discovers the Custom APIs a page can bind to (Global and
- entity-bound Actions/Functions) plus their declared request-parameter kinds, and produces
- the ## Custom API Bindings contract. Invoked only by the top-level genpage orchestrator from
+ Owns ALL GenPage Dataverse Custom API (plug-in) work: it discovers the Custom APIs a page
+ can bind to (Global and entity-bound Actions/Functions) plus their declared request-parameter
+ kinds, and produces the ## Custom API Bindings contract. It also owns the dataverse-operations
+ gate and the offer of the two reviewed built-in Dataverse Functions (WhoAmI, RetrieveVersion),
+ and is the one writer of actions.json. Invoked only by the top-level genpage orchestrator from
BOTH the create and edit flows; never invoked by planners or directly by users.
Works only on generative pages in a Power Apps model-driven app. Never use it for
a generic React or web app, or when the user rules out Power Platform, Dataverse,
@@ -57,8 +58,8 @@ server-side plug-in logic a maker authored in the environment; each is either an
(POST; called with `dataApi.executeAction`) or a **Function** (GET; called with
`dataApi.executeFunction`). Preserve that method fidelity, but require known read semantics
before invoking a Function automatically on mount or a filter change: GET alone does not prove
-an operation is harmless. You are the **single owner** of Custom API discovery and the
-feature gate. Planners must not invoke you directly; they have no `Task` tool, and nested
+an operation is harmless. You are the **single owner** of Custom API discovery and of the
+`dataverse-operations` gate. Planners must not invoke you directly; they have no `Task` tool, and nested
`Task` calls cannot safely host your user-facing Custom API selection prompts. The top-level
`/genpage` orchestrator dispatches you from BOTH flows so the gate and the discovery logic
live in exactly one place.
@@ -96,10 +97,14 @@ You will be invoked via `Task` with a prompt that includes:
**add**, **replace**, or **remove** a Custom API call.
- **Existing bindings** (`edit` only) — the current `config.json.actionBindings` array read
from the deployed page.
+- **Built-in operation need** — present when a planner returned
+ `dataverse_operation_discovery_required` (alone or with `custom_api_discovery_required`; you
+ are dispatched once for both): the maker's own words naming WhoAmI or RetrieveVersion, or the
+ generic identity/version need, and whether it is an add, a replace or a remove.
## Outputs (the contract with your callers)
-Write both of these into the working directory, then return a one-line summary:
+Write both of these into the working directory (and the third when it applies), then return a one-line summary:
1. **`custom-api-bindings.md`** — a markdown fragment whose entire body is the value of the
plan's `## Custom API Bindings` section. It is **either** the exact literal
@@ -110,39 +115,37 @@ Write both of these into the working directory, then return a one-line summary:
`[]` when there are none. Never the `{ "actionBindings": [...] }` object wrapper — that is
the deployed page `config.json` shape, which the upload writes for you. The file is named
`actions.json` because it matches the runtime wire contract (`actionBindings`) and the
- upload's `--actions` flag; see the "Vocabulary" note in `custom-api.md`.
+ upload's `--actions` flag; see the "Vocabulary" note in `custom-api.md`. You are its ONE
+ writer: it holds the Custom API rows and the built-in operation rows together.
+3. **`dataverse-operations.md`** — only when this run adds or replaces a built-in operation:
+ the body of the plan's optional `## Dataverse Operations` section (Step 5).
Log every command you run (with its purpose) into the working directory's `workflow-log.md`.
-## Step 1 — Feature gate (you own it; run it FIRST, always)
+## Step 1 — The `dataverse-operations` gate (you own it; run it FIRST, always)
-Probe the flag before ANY discovery, for both create and edit:
+Probe it before ANY discovery or offer, for both create and edit. It decides the built-in branch
+(Step 2b) only: being off never stops Custom API discovery, never ends this run early, and never
+writes `[]` over bindings a page keeps.
```powershell
-node "${PLUGIN_ROOT}/scripts/lib/feature-flags.js" custom-api
+node "${PLUGIN_ROOT}/scripts/lib/feature-flags.js" dataverse-operations
```
-Record the result in `workflow-log.md` (e.g. `feature-flags.js custom-api → disabled`).
+Record the result in `workflow-log.md` (e.g. `feature-flags.js dataverse-operations → disabled`).
-Custom API discovery is **enabled by default**. `GENPAGE_ENABLE_CUSTOM_API=0` explicitly
-disables it; a missing/unreadable feature config still fails closed.
+Custom API support has no feature flag: discovery, authoring and upload are always available, so
+run Step 2 whenever the intent needs a Custom API. Runtime capabilities, environment governance
+and the signed-in user's privileges are still required.
-**If it prints `disabled` (exit 1)** — Custom API support is disabled for this run:
+**`dataverse-operations`** ships OFF. While it prints `disabled`, offer no built-in operation,
+do not run `list-dataverse-operations.js`, and add no built-in row; built-in rows a page already
+holds are preserved like any other binding. If the maker affirmatively asked for WhoAmI or
+RetrieveVersion, relay the script's gate line and add exactly: `This does not mean the
+environment lacks these operations, and the remedy is not a Custom API wrapper. No new built-in
+binding was added.` — for those two names only.
-- Do **not** run `list-custom-apis.js` or any other discovery.
-- **create:** write `custom-api-bindings.md` containing exactly `No custom API bindings.` and
- `actions.json` containing `[]`. Return `custom-api disabled — no bindings`.
-- **edit:** the feature is OFF, so you must **not add or discover** new bindings. **Preserve**
- the existing bindings passed to you: write them unchanged to `actions.json` (bare array) and
- reproduce them in `custom-api-bindings.md`. Return
- `custom-api disabled — existing bindings preserved, none added`.
-
-Only when it prints `enabled` (exit 0) do you continue to Step 2. The committed flag remains
-in `plugins/model-apps/feature-flags.json` as a reversible default; an explicit
-`GENPAGE_ENABLE_CUSTOM_API=1` can enable a single run. Runtime capabilities, environment
-governance and the signed-in user's privileges are still required.
-
-## Step 2 — Discovery (enabled only)
+## Step 2 — Discovery
Enumerate supported **public** Custom APIs — Global APIs plus those bound to the
page's table(s). Private APIs, collection-bound APIs, and APIs with Entity/EntityCollection
@@ -170,6 +173,48 @@ the manifest fails closed with `not_bound`, and a wrong parameter kind corrupts
If `list-custom-apis.js` returns no API matching the intent, do **not** fabricate one: leave it
out and tell the caller the operation was not found (the page then simply omits that call).
+## Step 2b — Built-in Dataverse operations (`dataverse-operations` enabled only)
+
+Two built-in Functions, **WhoAmI** and **RetrieveVersion**, can be offered beside — never inside —
+the Custom APIs. They are not Custom APIs: no `customapi` row describes them, so
+`list-custom-apis.js` never lists them and a Custom API wrapper is never their remedy. The full
+contract is `${PLUGIN_ROOT}/references/dataverse-operations.md`; read it before this step.
+
+Run the listing only when this run needs an explanation or an add/replace offer (the
+orchestrator forwarded `dataverse_operation_discovery_required`, or the edit intent adds or
+replaces one) — never for an unrelated edit:
+
+```powershell
+node "${PLUGIN_ROOT}/scripts/list-dataverse-operations.js"
+```
+
+It takes no environment and reads nothing from it. Exit 3 (flag off) or exit 1 offers
+**nothing** — never a guessed or widened list. Exit 0 prints the reviewed catalogue with
+`verification` all `not-checked`: an offer, not a check that the environment, its player or the
+user can make the call.
+
+- **Selection is consent; a mention is not.** An affirmative "add a button that calls WhoAmI",
+ or the maker's explicit answer to a picker that offered it, selects it — do not ask again. A
+ mention, question, quotation, negation ("do not add WhoAmI") or removal is not an addition.
+ A generic need ("show who I am") with no affirmative name: return `needs_input` with the two
+ operations and the offer text from the reference. Silence is never selection; unattended, no
+ answer is not consent.
+- **Exact names only.** Any other name — another case, a namespace, a prefix, an effectful
+ Function such as `CalculateRollupField`, an Action, a record- or set-bound operation — is
+ refused with `not_in_catalogue` and its fixed message; never probe it and never echo it.
+- **Same name as a Custom API.** If this run's Custom API discovery returned the same exact
+ unique name, bind neither silently: return `needs_input`; the maker may select that Custom API
+ row explicitly.
+- **Button only.** A request to call it on load, on a filter, by polling or in the background is
+ refused with `explicit_trigger_required`; add no binding and no substitute call until the
+ maker accepts a button. The refusal is not completion.
+
+A selected operation's wire row is its four-key projection — `name`, `isFunction` (`true`),
+`displayName` and `parameterKinds` (`{}`) copied from the listed operation. Never copy
+`bindingType`, `parameters`, `response`, `outputPrivacy`, `invocation` or
+`requiresExplicitSelection`: a key outside the binding properties leaves the page's whole list
+out of an App Spec.
+
## Step 3 — Kind and binding fidelity (every selected API)
For each API the page will call, carry these through EXACTLY as discovered — they are the
@@ -205,14 +250,35 @@ Start from the **existing bindings** you were given and apply the edit intent:
- **Replace:** discover the supported replacement (Steps 2–3) and swap it in by `name`.
If discovery fails or finds no supported replacement, report it; do not silently drop the old binding.
- **Remove:** drop the named binding(s).
+- **Remove every Custom API:** drop each Custom API row and keep every built-in row byte for
+ byte (`WhoAmI`, `RetrieveVersion`, exact names): `custom-api-bindings.md` is then
+ `No custom API bindings.` and `actions.json` holds the built-in rows. "Clear the Custom APIs" is
+ this removal, never a clear; only the maker's clear choice, asked before any binding is reconciled
+ (edit-flow.md, Edit Phase 3) and recorded again right before each upload it authorizes,
+ permits `[]`.
- Use ONLY names, kinds, bound entities, and parameter kinds you discovered this run or that
were in the existing bindings. Never fabricate.
- New discovery eligibility is not retroactive cleanup: preserve unrelated existing bindings
verbatim even if they are private or no longer eligible for new discovery.
+- **Built-in rows follow the same intents** (`references/dataverse-operations.md` → the edit
+ intent table): a preserve keeps them verbatim — never add `isFunction`, a canonical label or
+ `parameterKinds` to a legacy entry; add/replace needs the `dataverse-operations` gate ON and
+ the maker's selection; remove drops only the named entries (built-ins and Custom APIs alike);
+ clear-all is `[]` only after the maker's clear choice, which names the built-ins it removes
+ (asked before any binding is reconciled: edit-flow.md, Edit Phase 3). An edit
+ whose page already binds WhoAmI or RetrieveVersion with no preserve evidence for it halts:
+ missing evidence is not permission to delete the call.
## Step 5 — Write outputs
-Write the final binding set to both output files (see "Outputs"):
+Compose **one** full desired array after both branches have finished — never a partial file
+from one of them: the Custom API rows first, in their existing order, then the new built-in
+rows in catalogue order (WhoAmI, then RetrieveVersion). Each new built-in row must be exactly the
+four-key projection of the listed operation; if any is not, or a name appears twice
+(`duplicate_operation`), write **nothing** and return the refusal — the page stays as it is.
+Do not create `actions.json` before the `dataverse-operations` probe (Step 1).
+
+Write the final binding set to the output files (see "Outputs"):
- **When there are bindings:** `custom-api-bindings.md` contains the table below;
`actions.json` contains the equivalent bare JSON array.
@@ -253,8 +319,28 @@ Write the final binding set to both output files (see "Outputs"):
`parameterKinds` and optional `boundEntityLogicalName` only. Do not copy the full discovery
entry: `bindingType` and `lookupParameters` are not `actions.json` fields.
-- **When there are none:** `custom-api-bindings.md` contains exactly `No custom API bindings.`
- and `actions.json` contains `[]`.
+- **When there are no Custom API bindings:** `custom-api-bindings.md` contains exactly
+ `No custom API bindings.`; `actions.json` holds the built-in rows the page keeps or this run
+ adds, and `actions.json` is `[]` only when no row of either kind remains.
+
+- **Built-in operations added or replaced this run:** also write `dataverse-operations.md`,
+ whose entire body is the plan's `## Dataverse Operations` section — the verification line and
+ one row per selected operation, in catalogue order, every cell the catalogue's own:
+
+ ```markdown
+ Verification: environment not-checked, runtime not-checked, privileges not-checked.
+ | Name | Kind | Bound Entity | Display Name | Parameters | Response fields | Invoke |
+ |------|------|--------------|--------------|------------|-----------------|--------|
+ | WhoAmI | Function | (Global) | Current Dataverse identity | (none) | BusinessUnitId, UserId, OrganizationId | button |
+ ```
+
+ Write it **only** for a current-run add/replace. A `dataverse-operations.md` left by an earlier
+ run is not this run's selection. When this run adds none — the `dataverse-operations` gate is
+ off, or the maker declined the offer or selected neither — say `dataverse-operations.md: none —
+ not added this run` with the reason (`gate off` or `none selected`): the orchestrator forwards
+ that outcome, never a contract, so the planner completes its plan without the call instead of
+ asking for this offer again. Built-in rows never go into `custom-api-bindings.md`.
-Return a concise summary: mode, gate result, and the `name`s of the bindings written (or
-"none").
+Return a concise summary: mode, the `dataverse-operations` gate result, the `name`s of the
+Custom API bindings and of the built-in operations written (or "none"), and whether
+`dataverse-operations.md` was written this run (or `none — not added this run` and why).
diff --git a/plugins/model-apps/agents/genpage-edit-planner.md b/plugins/model-apps/agents/genpage-edit-planner.md
index cbbe81480..674044720 100644
--- a/plugins/model-apps/agents/genpage-edit-planner.md
+++ b/plugins/model-apps/agents/genpage-edit-planner.md
@@ -188,10 +188,12 @@ at a time (you are headless — see the interaction contract below):
> **Custom API changes** (Dataverse Action/Function / plug-in logic):
> Do **not** run Custom API discovery here — the orchestrator delegates that to the
-> `genpage-customapi-builder` agent (which owns the `custom-api` feature gate).
+> `genpage-customapi-builder` agent (which owns Custom API discovery).
>
> - **Preserving or clearing** existing Custom API bindings needs no discovery: capture it
-> in the plan's `### Custom API Changes` and continue.
+> in the plan's `### Custom API Changes` and continue. Clearing the Custom APIs of a page that
+> also binds a built-in operation removes each Custom API row and keeps the built-in calls and
+> bindings; clearing those too is the **clear all** below.
> - **Adding or replacing** a Custom API call that the orchestrator did not already discover
> — i.e. the need surfaced in *your* clarification, so your prompt carries the "preserve"
> action and `none — omit --actions` — you must **stop and return**
@@ -207,6 +209,37 @@ at a time (you are headless — see the interaction contract below):
> page whose Custom API calls have **no deployed binding**. The orchestrator will run
> discovery and re-invoke you with a real Custom API contract and upload-file status.
+> **Built-in Dataverse operations** (`WhoAmI`, `RetrieveVersion`; see
+> `${PLUGIN_ROOT}/references/dataverse-operations.md`): they share `actionBindings` with the
+> Custom APIs but are not Custom APIs, and `genpage-customapi-builder` owns their
+> `dataverse-operations` gate. Classify the intent from this page's `config.json.actionBindings`
+> and the request, and record it in the plan as `{ intent, selected, beforeNames, provenance }`
+> (`provenance` is `before-config` or `current-run-selection`):
+>
+> - **preserve** (an unrelated change) — no gate, no discovery; the existing calls and bindings
+> stay exactly as they are (upload omits `--actions`). A table carried for preservation while
+> the flag is off is not new authoring and does not halt.
+> - **add / replace** — only on the maker's affirmative request or picker answer (a mention, a
+> question or "do not add" is not one): stop and return
+> `{ "action": "dataverse_operation_discovery_required", "intent": "<the maker's words>",
+> "resolvedAction": "edit", "envUrl": "<the environment URL you were given>" }` unless your
+> prompt carries this run's built-in operation contract (the body of the builder's
+> `dataverse-operations.md` between `----- BEGIN/END DATAVERSE OPERATIONS -----` lines); add or
+> replace only the operations that block lists. When your prompt says `none — not added this
+> run`, the builder added none: plan the edit without that call and do not signal again. A call on load, on a
+> filter or in the background is refused (`explicit_trigger_required`): only a button.
+> - **remove** — drop only the named calls and bindings; nothing else.
+> - **clear all** — only when your prompt carries the maker's clear choice `Clear choice: Clear every
+> action binding of page <page-id>, removing <names>`, which names the built-in bindings it removes.
+> The orchestrator asks it before any binding is reconciled and before this plan (edit-flow.md, Edit
+> Phase 3); a yes to adding or keeping one is not that choice. On `Clear choice: Keep <names>` there
+> is no clear: keep the built-in calls — their handlers, buttons and UI — and their bindings, and
+> plan at most the removal of the Custom APIs. When a clear surfaces in your own clarification and
+> your prompt carries no clear choice, do **not** write the plan: stop and return
+> `{ "action": "clear_choice_required", "names": "<the built-in operations the page holds>" }`.
+> - If the page already binds WhoAmI or RetrieveVersion and you cannot tell the intent, halt
+> with `needs_input`: missing preserve evidence is not permission to delete the call.
+
Mark "Analyze existing page" task complete.
## Step 3 — Hand the Edit Plan Back for Approval
@@ -235,6 +268,11 @@ Return this plan to the orchestrator, which presents it with `EnterPlanMode`:
- [none | add <operation> | replace <name> with <operation> | remove <name>]
(the orchestrator delegates any add/replace/remove to genpage-customapi-builder)
+### Built-in Operation Changes
+- [none | preserve | add WhoAmI / RetrieveVersion (button) | remove <name> | clear all (confirmed)]
+ with `{ intent, selected, beforeNames, provenance }`
+ (the orchestrator delegates any add/replace to genpage-customapi-builder)
+
### Preservation Constraints
- [What must remain unchanged — feature preservation, specific behaviors]
@@ -293,7 +331,11 @@ Write `genpage-edit-plan.md` to the working directory root (NOT inside the
## Design Notes
<Styling, accessibility, or behavior guidance the orchestrator should follow
- when applying the changes.>
+ when applying the changes. When the maker asks to restyle the page — a
+ screenshot, a website to match, a description — write the style as a line
+ that starts with `Maker-requested:` and gives the concrete values, as
+ references/plan-schema.md says for `Styling:`; it wins over the page's
+ current look (references/rules.md → Maker-requested styling).>
## Relevant Samples
<Optional. If a sample from ${PLUGIN_ROOT}/samples/ would help the
diff --git a/plugins/model-apps/agents/genpage-entity-builder.md b/plugins/model-apps/agents/genpage-entity-builder.md
index 16799b2a6..238dd82a2 100644
--- a/plugins/model-apps/agents/genpage-entity-builder.md
+++ b/plugins/model-apps/agents/genpage-entity-builder.md
@@ -216,7 +216,9 @@ check is best-effort: if that read fails, provisioning proceeds unchanged.
A `⚠ could not determine the organization's base language …` warning on stderr
means discovery failed and 1033 was assumed — pass the flag explicitly.
-The input JSON follows the App Spec format. Build it with:
+The input JSON follows the App Spec format — the keys of `entities[]` and `relationships[]` in
+`${PLUGIN_ROOT}/references/app-spec-schema.md` — and `provision-entities.js` validates it with the same
+rules, so a key it does not take is refused before anything is written. Build it with:
```json
{
@@ -228,20 +230,18 @@ The input JSON follows the App Spec format. Build it with:
{
"schemaName": "${PREFIX}_<TableSuffixPascal>",
"displayName": "<Display Name>",
- "pluralDisplayName": "<Display Plural>",
+ "pluralName": "<Display Plural>",
"description": "<description>",
- "primaryNameAttribute": {
+ "primaryAttribute": {
"schemaName": "${PREFIX}_name",
"displayName": "<Primary Name Display>",
"maxLength": 100
},
- "attributes": [
+ "columns": [
{
"schemaName": "${PREFIX}_<columnSuffix>",
"displayName": "<Column Display>",
- "type": "<AppSpecType>",
- "requiredLevel": "None",
- ...typeSpecificProperties
+ "type": "<App Spec Type>"
}
]
}
@@ -249,19 +249,21 @@ The input JSON follows the App Spec format. Build it with:
"relationships": [
{
"type": "OneToMany",
- "referencedEntity": "${PREFIX}_<parentSuffix>",
- "referencingEntity": "${PREFIX}_<childSuffix>",
+ "referenced": "${PREFIX}_<parentSuffix>",
+ "referencing": "${PREFIX}_<childSuffix>",
"lookup": {
"schemaName": "${PREFIX}_<LookupSuffixPascal>",
- "displayName": "<Lookup Display>",
- "requiredLevel": "None"
- },
- "cascadeDelete": "RemoveLink"
+ "displayName": "<Lookup Display>"
+ }
}
]
}
```
+Give each column the properties its type takes (the table below). A column the plan marks
+**Required: yes** gets `"required": true` (`"recommended"` for a recommended one); leave `required`
+out of the others. A lookup is not a column: declare it as a relationship (below).
+
### Type Mapping (Plan → App Spec)
Map the column types from the plan's `## Entity Creation Required` section to
@@ -269,16 +271,21 @@ App Spec types:
| Plan Type | App Spec Type | Additional Properties |
|-----------|---------------|----------------------|
-| `string` | `Text` | `maxLength`, `format` (e.g., `"Email"`) |
-| `int`, `integer` | `Integer` | `min`, `max` |
-| `decimal` | `Decimal` | `precision`, `min`, `max` |
-| `money` | `Money` | `precision`, `min`, `max` |
-| `memo` | `Memo` | `maxLength`, `format` (e.g., `"TextArea"`) |
-| `datetime` | `DateTime` | `format` (e.g., `"DateOnly"`), `behavior` |
-| `boolean` | `Boolean` | `defaultValue`, `trueLabel`, `falseLabel` |
-| `picklist` | `Choice` | `options: [{"label": "...", "value": 100000000}, ...]` |
-
-For Choice columns, each option's value is `100000000 + index` (0-based).
+| `string` | `Text` | `maxLength`, `format` (`Text`, `Email`, `Url` or `Phone`) |
+| `int`, `integer` | `Integer` | `minValue`, `maxValue` |
+| `decimal` | `Decimal` | `precision`, `minValue`, `maxValue` |
+| `money` | `Money` | `precision`, `minValue`, `maxValue` |
+| `memo` | `Memo` | `maxLength` |
+| `datetime` | `DateTime` | `dateFormat` (`DateOnly` or `DateAndTime`) |
+| `boolean` | `Boolean` | `defaultValue` (true or false), `trueLabel`, `falseLabel` |
+| `picklist` | `Choice` | `options`: the option labels in the plan's order, e.g. `["Low", "Medium", "High"]` |
+
+For Choice columns, each option is its **label**: a string, or — for a label in several languages — a
+map of LCID to label such as `{"1033": "Low", "1036": "Bas"}`. Never write an option as a
+`{"label", "value"}` object: `provision-entities.js` refuses that shape before anything is written
+(`'label' is not an LCID`). The values are not written either: the options are numbered
+`100000000 + index` (0-based) in the order given — the values the plan's `Choice Columns` lists — so keep
+the plan's order.
### Relationship Mapping
@@ -287,17 +294,19 @@ For Choice columns, each option's value is `100000000 + index` (0-based).
```json
{
"type": "OneToMany",
- "referencedEntity": "${PREFIX}_<parentTableSuffix>",
- "referencingEntity": "${PREFIX}_<childTableSuffix>",
+ "referenced": "${PREFIX}_<parentTableSuffix>",
+ "referencing": "${PREFIX}_<childTableSuffix>",
"lookup": {
"schemaName": "${PREFIX}_<LookupSuffixPascal>",
- "displayName": "<Lookup Display Name>",
- "requiredLevel": "None"
- },
- "cascadeDelete": "RemoveLink"
+ "displayName": "<Lookup Display Name>"
+ }
}
```
+`referenced` is the parent (the "one" side) and `referencing` the child that gets the lookup column. The
+input has no cascade setting, so a relationship is created with Dataverse's default cascade behaviour; if
+the plan's `Cascade` column asks for another, say so in your result so that it can be set in Power Apps.
+
**N:N relationships:**
```json
diff --git a/plugins/model-apps/agents/genpage-page-builder.md b/plugins/model-apps/agents/genpage-page-builder.md
index 30bb3d676..41e6fdb2a 100644
--- a/plugins/model-apps/agents/genpage-page-builder.md
+++ b/plugins/model-apps/agents/genpage-page-builder.md
@@ -84,6 +84,10 @@ call `props.dataApi.executeAction` / `executeFunction` **even in `mock` data mod
Global Function that computes a value). Never fabricate a Custom API name, parameter, or
parameter kind; use only the plan's `## Custom API Bindings` values.
+**Built-in Dataverse operations** (`WhoAmI`, `RetrieveVersion`) are decided by the plan's
+OPTIONAL `## Dataverse Operations` table alone — never by the Custom API table, and never by a
+maker's mention. Absent, or exactly `No Dataverse operations.`, means none.
+
## Step 1 — Read the Plan Document
Read `genpage-plan.md` at the path provided in your invocation prompt.
@@ -95,9 +99,20 @@ Locate and extract:
- The **Per-Page Specification** subsection for your assigned page (purpose, entities,
features, components, layout, data binding, interactions)
-- The **Design Preferences** section (styling, features, accessibility notes)
+- The **Design Preferences** section (styling, features, accessibility notes). A `Styling:` line
+ that starts with `Maker-requested:` is the maker's own look, and it wins over the default
+ model-driven styling. Apply every value it gives, as `references/rules.md` → *Maker-requested
+ styling* says. Keep the default tokens only for what it does not set.
- The **Environment** section (languages for localization)
- The **Relevant Samples** table (which sample to read for your page)
+- Your page's **`#### Data semantics`** and **`#### Lookup metadata`**, and the **`## Assumptions`** entries
+ they cite (when the plan has them). Implement exactly the relationships and filters they record — the
+ `Data Binding` and `Interactions` refer to them by id — and add no unrecorded predicate, relationship or
+ roll-up. Each lookup record gives the column's read property, its **complete** target set and the concrete
+ paths you may filter through. A plan without these sections is an older plan ("not recorded"): if your page
+ needs a target-dependent lookup action (filtering by a target, opening, retrieving or writing a
+ multi-target lookup's record) whose targets the plan does not record, stop and report the missing fact —
+ never guess the targets or take the first one.
## Step 2 — Read RuntimeTypes.ts (Data mode: dataverse only)
@@ -217,6 +232,20 @@ table, **stop and report it instead of writing the page**: the orchestrator halt
plan before dispatch, so reaching you means the plan is broken, and treating it as "no
Custom APIs" would silently drop an approved binding.
+Only when the plan has a `## Dataverse Operations` section holding the built-in operation table
+(the not-checked verification line and a `| Name | Kind | …` header with at least one row) do you
+also read:
+
+```
+${PLUGIN_ROOT}/references/dataverse-operations.md
+```
+
+and generate its **button-only** pattern ("Generated call") for exactly the rows of that table —
+each an `executeFunction({ name })` behind its own button, never on mount, at render, in a
+`useEffect`, on a filter or on a timer. An absent section, or exactly `No Dataverse
+operations.`, means no built-in operation: emit no such call. On an edit that preserves the page's
+bindings, keep an existing built-in call exactly as it is written.
+
Only when your dispatch says **`Telemetry: enabled`** *and* the maker's own request
asks to measure, track, monitor, or diagnose something do you instrument the page and
also read:
@@ -276,10 +305,17 @@ rules.md:
### Component Structure
+Every page — Dataverse or mock — renders inside the page error boundary (rules.md Critical Rule 22):
+copy the page error block of `rules.md` → *Common Errors* → *Missing Error Handling* **unchanged** (set
+`PAGE_NAME` to the plan's display name for this page — a fixed literal, never the file name), put the
+page itself in a top-level `PageBody`, and export the wrapper below. A reporter that is reformatted,
+renamed or "improved" is not the canonical one: copy its lines as they are.
+
**Data mode = `dataverse`** — import types from RuntimeTypes:
```typescript
-import {useEffect, useState} from 'react';
+import * as React from 'react';
+import { Button, MessageBar, MessageBarActions, MessageBarBody } from '@fluentui/react-components';
import type {
TableRow,
DataColumnValue,
@@ -292,23 +328,38 @@ import type {
// Additional imports: @fluentui/react-components, @fluentui/react-icons, d3, etc.
+// The page error block of rules.md "Missing Error Handling", copied unchanged: the PageErrorKind,
+// PageErrorView and PageErrorTelemetry types, PAGE_NAME, the error copy and translate,
+// reportPageError, PageErrorBar and PageErrorBoundary
+
// Utility functions as separate top-level functions
// Sub-components as separate top-level functions
-const GeneratedComponent = (props: GeneratedComponentProps) => {
+function PageBody(props: GeneratedComponentProps) {
const { dataApi, pageInput } = props;
- // Component implementation
+ // Component implementation: hooks, state and handlers
}
+const GeneratedComponent = (props: GeneratedComponentProps) => (
+ <PageErrorBoundary>
+ <PageBody {...props} />
+ </PageErrorBoundary>
+);
+
export default GeneratedComponent;
```
**Data mode = `mock`** — do NOT import from `./RuntimeTypes` (it isn't generated
for mock pages and the import would fail at build time). Define minimal local
-types instead and skip the dataApi-typed imports:
+types instead and skip the dataApi-typed imports. A mock page has no data call
+to report, but its boundary still reports a render crash, so it copies the
+block's types, `PAGE_NAME`, error copy, `translate`, `reportPageError` and
+`PageErrorBoundary` unchanged — but not the block's `./RuntimeTypes` import —
+and leaves out `PageErrorBar` when nothing renders one:
```typescript
-import {useEffect, useState} from 'react';
+import * as React from 'react';
+import { MessageBar, MessageBarBody } from '@fluentui/react-components';
// Additional imports: @fluentui/react-components, @fluentui/react-icons, d3, etc.
@@ -317,11 +368,20 @@ type Props = {
pageInput?: { id?: string };
};
-const GeneratedComponent = (props: Props) => {
+// The page error block of rules.md "Missing Error Handling" (its types, PAGE_NAME, the error copy and
+// translate, reportPageError and PageErrorBoundary), copied unchanged
+
+function PageBody(props: Props) {
const { pageInput } = props;
// Component implementation with inline mock data
}
+const GeneratedComponent = (props: Props) => (
+ <PageErrorBoundary>
+ <PageBody {...props} />
+ </PageErrorBoundary>
+);
+
export default GeneratedComponent;
```
@@ -348,7 +408,9 @@ export default GeneratedComponent;
- **No external libraries** — only React, Fluent UI V9, approved Fluent icons, D3.js for charts
(see `references/supported-dependencies.md`; `scripts/lib/supported-dependencies.js`
is the source of truth for the generated package names, versions, and feature gates)
-- **makeStyles with tokens** — no inline styles for static values
+- **makeStyles with tokens** — no inline styles for static values. Tokens are the default look:
+ a `Maker-requested:` style in the plan's Design Preferences replaces them for the values it sets
+ (see Step 1)
```typescript
const useStyles = makeStyles({
container: {
@@ -360,13 +422,26 @@ export default GeneratedComponent;
```
- **Responsive design** — flexbox, relative units, never `100vh`/`100vw`
- **WCAG AA accessibility** — ARIA labels, keyboard navigation, semantic HTML
-- **Error handling** — all async `dataApi` calls wrapped in try-catch
+- **Error handling** — every failed data operation goes through the page's one `reportPageError`
+ with its five required arguments — `reportPageError(PAGE_NAME, '<operation>', code, error, '<kind>')`,
+ the operation one stable literal, the code `res.error?.code` or `undefined`, the message the caught
+ `error` or `res.error?.message`, the kind a literal (`'read'` for a read or a rejected navigation,
+ `'write'` for a write, `'indeterminate'` / `'network'` only for those Custom API results) — and the view
+ it returns goes into that operation's state in the same update, rendered by `PageErrorBar` — placed in the
+ final returned JSX, outside any condition (it shows nothing until there is an error). Retry only
+ a read or a Custom API `network` result, through a named function the user presses; never retry a write
+ or an indeterminate result. A null lookup, zero rows or an absent optional value is not a failure.
+ The page renders inside `PageErrorBoundary`. See rules.md Critical Rule 22 and *Missing Error Handling*.
- **No telemetry by default** — never emit `props.appInsights` calls unless your dispatch says `Telemetry: enabled` **and** the maker asked to measure or track something. Absence of a request means zero telemetry, not "instrument the obvious things". See references/page-telemetry.md.
- **Lookup fields** — read display names via `@OData.Community.Display.V1.FormattedValue`; *set* a lookup on create/update with `_<field>_value: "/logicalSingular(guid)"`, never `@odata.bind` (the DataAPI silently drops it → orphaned row). See rules.md DataAPI Rule 13.
+- **Lookup references** — a lookup's `_<field>_value` may be a bare GUID or `/<table>(<guid>)`. Copy `normalizeLookupReference` unchanged from rules.md → *Lookup references*, pass it the column's complete target set from the plan's `#### Lookup metadata`, and use only a resolved pair: `reference.id` (bare) for filters, `retrieveRow({ id })` and `entityId`, `reference.table` for the target. Filter a target through a typed path only when the plan records that concrete path; write the table the user selected, kept with its id (pitfall E). Never infer a table from a label, the first target or a navigation name.
+- **Traceability** — every relationship and every filter the page applies comes from the plan's `## User Requirements` or a recorded `## Assumptions` entry, as its `#### Data semantics` states; introduce no unrecorded business predicate, relationship or roll-up.
- **All hooks above early returns** — every `useMemo`/`useState`/`useEffect`/`useCallback` must precede any loading/empty `return`, or detail pages crash with React error #310 on first open. See rules.md Critical Rule 19.
- **Entity logical names** — singular lowercase (e.g., `"account"`)
- **No placeholders** — no TODOs, no ellipses, no "implement later" comments
-- **Top-level functions** — components and utilities as separate top-level functions, no nesting
+- **Top-level functions** — components and utilities as separate top-level functions, no nesting; the
+ page's one class is `PageErrorBoundary` (rules.md Critical Rule 3). Handlers and loaders that close over
+ a component's state stay inside that component.
- **Icons** — unsized variants only (e.g., `AddRegular` not `Add24Regular`)
- **No FluentProvider** — already provided at root
- **No createTheme/mergeThemes/useTheme** — these don't exist in Fluent UI V9
@@ -390,7 +465,10 @@ export default GeneratedComponent;
identity. Using it emits `PAGEREF_page`, which fails nav parity and halts the build.
Pass any custom identifier in `data:` (never `recordId`); it arrives on the target
- as `pageInput?.data?.<field>`. Example:
+ as `pageInput?.data?.<field>`. When the target is a page that this plan does not build, pass what
+ that page reads, in the place it reads it (rules.md **Page Input > What another page accepts**): its
+ `pageInput.data` keys in `data`, and — only when it reads `pageInput.recordId` or
+ `pageInput.entityName` — `recordId` and `entityName` at the top level of the call. Never guessed names. Example:
```typescript
Xrm.Navigation.navigateTo({
pageType: "generative",
@@ -485,8 +563,9 @@ connector field name, parameter name, or response field name that is not in the
plan. Read
`${PLUGIN_ROOT}/references/connectors.md` and emit connector calls with the
verified runtime patterns below. Connector methods are optional at runtime, so
-every call must be presence-checked and wrapped in `try`/`catch` with a graceful
-empty or error state.
+every call must be presence-checked and awaited in a `try` whose `catch` reports
+the failure through `reportPageError` into the panel's error state, beside its
+graceful empty state.
Connector rows are not covered by RuntimeTypes. Before using
`queryConnectorTable`, declare an inline row interface from the plan's discovered
@@ -513,7 +592,9 @@ schema. Before calling `executeConnectorOperation`, declare the response
interface from the plan and mark every response field optional. Build the
parameter object from discovered parameters plus maker-provided values; never
invent parameter or response field names. Check `response.ok` before casting or
-using the body:
+using the body, and report a failed response even though nothing was thrown — its
+envelope carries no message, so pass none and the bar shows its fallback copy
+(`connectors.md` has the whole `PageBody`):
```typescript
type WeatherResponse = { temperature?: number; conditions?: string; humidity?: number };
@@ -523,11 +604,18 @@ const parameters: { Location: string; units?: string } = { Location: 'Seattle',
```typescript
const connectorApi = dataApi as unknown as { executeConnectorOperation?: (connectorLogicalName: string, operationName: string, parameters: Record<string, unknown>) => Promise<{ ok: boolean; body: unknown }>; };
if (typeof connectorApi.executeConnectorOperation !== 'function') { return; }
-const response = await connectorApi.executeConnectorOperation('new_uxtest_msnweather', 'CurrentWeather', parameters);
-if (!response.ok) { return; }
-const weather = response.body as WeatherResponse;
+try {
+ const response = await connectorApi.executeConnectorOperation('new_uxtest_msnweather', 'CurrentWeather', parameters);
+ if (!response.ok) { setWeather({ weather: null, error: reportPageError(PAGE_NAME, 'loadWeather', undefined, undefined, 'read', retryWeather) }); return; }
+ setWeather({ weather: response.body as WeatherResponse, error: null });
+} catch (error) {
+ setWeather({ weather: null, error: reportPageError(PAGE_NAME, 'loadWeather', undefined, error, 'read', retryWeather) });
+}
```
+`'read'` and a retry fit `CurrentWeather` because it only reads. An operation the plan does not record
+as a read is `'write'`, with no retry.
+
### Custom API invocation (Dataverse Actions & Functions)
When the plan has `## Custom API Bindings`, the page may invoke Dataverse Custom APIs on the
@@ -542,6 +630,11 @@ there. The methods are optional at runtime, so every call must be presence-check
each **Action** against double-submit, read results from `res.outputs` (never `res.value`),
surface only the sanitized `res.error?.message`, and **never auto-retry** an `indeterminate`
result (only `error.code === 'network'` is safely retryable, via a manual "Try again").
+Every failed result and every rejection goes through `reportPageError` with a literal kind, in
+this order: `res.indeterminate`, then `res.error?.code === 'indeterminate'` (both
+`'indeterminate'`), then a `network` result (`'network'`, with the named manual retry), then any
+other failure (`'write'` for an Action) — each reports, stores the view and returns before
+`res.outputs` is read.
Match the call to the row's `Kind`: an **Action** row uses `executeAction`; a **Function** row
uses `executeFunction`. Calling the wrong one is rejected with `wrong_operation_kind`.
@@ -553,16 +646,44 @@ equals that table; for a `(Global)` row, omit `boundTo` entirely.
```typescript
const actionApi = dataApi as unknown as { executeAction?: (request: { name: string; parameters?: Record<string, unknown>; boundTo?: { entityName: string; id: string } }) => Promise<{ ok: boolean; indeterminate?: boolean; outputs?: Record<string, unknown>; error?: { message: string; code?: string } }>; };
-if (typeof actionApi.executeAction !== 'function' || isSubmitting) { return; } // presence-check + double-submit guard
-setIsSubmitting(true);
+if (typeof actionApi.executeAction !== 'function' || pending.current) { return; } // presence-check + double-submit guard
+pending.current = true;
+const recordId = pageInput.recordId; // the record this approval is for
+setApproval({ pending: true, status: '', error: null });
try {
- const res = await actionApi.executeAction({ name: 'new_ApproveOrder', parameters: { Comment: comment, Amount: amount }, boundTo: { entityName: pageInput.entityName, id: pageInput.recordId } });
- if (res.indeterminate) { setError("We couldn't confirm this completed — refresh before retrying."); return; }
- if (!res.ok) { setError(res.error?.message ?? 'The action failed.'); return; }
- const { NewStatus } = res.outputs as { NewStatus: string };
-} finally { setIsSubmitting(false); }
+ const res = await actionApi.executeAction({ name: 'new_ApproveOrder', parameters: { Comment: comment, Amount: amount }, boundTo: { entityName: pageInput.entityName, id: recordId } });
+ if (recordId !== approvalFor.current) return; // the page moved to another record: not its answer
+ if (res.indeterminate) { setActionFailure(reportPageError(PAGE_NAME, 'approveOrder', res.error?.code, res.error?.message, 'indeterminate')); return; }
+ if (res.error?.code === 'indeterminate') { setActionFailure(reportPageError(PAGE_NAME, 'approveOrder', res.error?.code, res.error?.message, 'indeterminate')); return; }
+ if (!res.ok && res.error?.code === 'network') { setActionFailure(reportPageError(PAGE_NAME, 'approveOrder', res.error?.code, res.error?.message, 'network', retryApprove)); return; }
+ if (!res.ok) { setActionFailure(reportPageError(PAGE_NAME, 'approveOrder', res.error?.code, res.error?.message, 'write')); return; }
+ const status = res.outputs?.NewStatus;
+ setApproval({ pending: false, status: typeof status === 'string' ? status : '', error: null });
+} catch (error) {
+ if (recordId !== approvalFor.current) return;
+ setActionFailure(reportPageError(PAGE_NAME, 'approveOrder', undefined, error, 'write'));
+} finally { pending.current = false; }
```
+`setActionFailure(view)` stores the view and `pending: false` in one update; `retryApprove` calls the
+handler again when the user presses "Try again". The approval belongs to the record it was started on:
+`approvalFor` (a ref) holds the record the panel shows, a record change clears the approval state — its
+error and its retry — and an answer that arrives after the page moved on is ignored, so `retryApprove`
+re-sends only while that same record is shown. custom-api.md has the whole `PageBody`.
+
+### Built-in Dataverse operations (WhoAmI, RetrieveVersion)
+
+For each row of the plan's `## Dataverse Operations` table, copy the "Generated call" pattern of
+`${PLUGIN_ROOT}/references/dataverse-operations.md`: a presence-checked
+`executeFunction({ name: 'WhoAmI' })` / `executeFunction({ name: 'RetrieveVersion' })` with no
+`parameters` and no `boundTo`, called only from that operation's own button; `res.ok !== true`
+returns before `res.outputs` is read; outputs are read only as own properties of a checked
+object, all or nothing (three GUIDs, or a `Version` of 1 to 128 characters), never logged,
+stored, spread or serialized. A failure is reported through `reportPageError` as a `'read'` with no
+retry, and its view — never the result — is what the request helper returns. An actual 404 says the
+operation is unavailable — never that a Custom API must be deployed. Never retrieve the `systemuser`,
+`businessunit` or `organization` row, and never copy an identity the auth preflight printed into the page.
+
## Step 6 — Write the .tsx File
Write the complete `.tsx` file to the working directory at the target file path.
diff --git a/plugins/model-apps/agents/genpage-planner.md b/plugins/model-apps/agents/genpage-planner.md
index 635a07ffd..817ce11b5 100644
--- a/plugins/model-apps/agents/genpage-planner.md
+++ b/plugins/model-apps/agents/genpage-planner.md
@@ -94,7 +94,9 @@ outcomes — because the eval harness greps the log for these tokens. Concretely
unattended, never write the literal attended markers `AskUserQuestion:`,
`EnterPlanMode called`, or `ExitPlanMode called` — not even in explanatory
prose such as "was not called". Record only
- `Unattended default: <question> → <answer> (<reason>)`. The evaluator treats
+ `Unattended default: <question> → <answer> (<reason>)` — for a data-semantics
+ question, `Unattended default: <assumption id> / <question id> → <answer> (<reason>)`,
+ whose reason never contains the word "approved". The evaluator treats
those attended markers as real invocations.
- The PAC CLI version output is recorded explicitly (the assertion checks
for `> 2.10.0`-shaped text — `PAC CLI Version 2.10.x` is the canonical
@@ -234,6 +236,18 @@ other source: there is none. Fixing the cause is the maker's (`az login` with th
4. **"Any specific requirements?"** — styling, features (search, filtering, sorting),
accessibility, responsive behavior, interactions
+ **A look of the maker's own wins over the default model-driven look.** The maker can attach a
+ screenshot or mockup, name a website to match, or describe the style. Turn the request into
+ concrete values and write them in the plan's `## Design Preferences` as a `Styling:` line that
+ starts with `Maker-requested:`. Give each color as a hex value with its role (primary, accent,
+ background, text), the font family with a fallback, the corner radius, the density, the borders
+ and shadows, and how buttons, cards and tables look. Then add `(from: screenshot)`,
+ `(from: website <url>)` or `(from: description)`. Read a screenshot or a website for these values.
+ If you cannot open a website, ask the maker for a screenshot or for its colors and fonts. Do not
+ assume them. If part of the request cannot be matched (`references/rules.md` → *Maker-requested
+ styling*, "What cannot be matched"), say so in the plan. When the maker asks for no look, write
+ the defaults (`Fluent UI V9 defaults`).
+
**Skip logic:**
- If the user provided a description with the `/genpage` command, skip question 2.
- If the description already specifies a data source, skip question 3.
@@ -386,8 +400,8 @@ Two cases:
the builder against exactly those. Return this only after your auth/environment and entity
detection steps have run, so all three values are real.
-`genpage-customapi-builder` remains the single owner of the `custom-api` feature gate, Custom
-API discovery, and the binding contract. When the orchestrator forwards results it provides:
+`genpage-customapi-builder` remains the single owner of Custom API discovery and the binding
+contract. When the orchestrator forwards results it provides:
- `custom-api-bindings.md` — the exact body for the plan's `## Custom API Bindings` section
(either `No custom API bindings.` or the binding table).
@@ -399,6 +413,29 @@ Read `custom-api-bindings.md` and splice its contents verbatim into the
If the request implies **no** server-side Custom API operation (plain Dataverse CRUD and/or
mock data only), write `## Custom API Bindings` as exactly `No custom API bindings.`.
+### Built-in Dataverse Operation Detection (handled by the orchestrator, not by you)
+
+Two **built-in** Dataverse Functions — `WhoAmI` (the signed-in user's identifiers) and
+`RetrieveVersion` (the server's version) — can be offered to a page. They are not Custom APIs
+and never go into `## Custom API Bindings`. Do **not** probe the `dataverse-operations` flag, run
+`list-dataverse-operations.js`, or decide a binding yourself; `genpage-customapi-builder` owns
+the gate, the offer and the maker's selection (`references/dataverse-operations.md`).
+
+- When the maker affirmatively asks for one of them, or asks for the identity or server version
+ the page should show, return `{ "action": "dataverse_operation_discovery_required", "intent":
+ "<the maker's words>", "resolvedAction": "create" | "edit", "envUrl": "<the environment you
+ resolved>" }` — or include it beside `custom_api_discovery_required` when both are needed; the
+ orchestrator dispatches the builder once. A mere mention, a question, or "do not add" is not a
+ request. The `whoAmI` your auth preflight runs is neither signal.
+- When your prompt carries a `## Dataverse Operations` block from this run's builder, copy it
+ verbatim into the plan's `## Dataverse Operations` section, right after
+ `## Custom API Bindings` — never re-derive or edit it. Without one, write no such section: it
+ is optional, and absent means no new built-in operation.
+- When your prompt says `none — not added this run`, the builder was already dispatched for the
+ request and added none — its `dataverse-operations` gate is off, or the maker declined the
+ offer or selected neither. Plan the page without that call, write no `## Dataverse Operations`
+ section, and do not signal again: the request is complete without it.
+
### App Detection
Run:
@@ -518,6 +555,91 @@ the user before continuing:
> "Heads up — env has `<detectedPrefix>_*` tables but you chose `<chosenPrefix>`.
> New tables won't match the prefix of your existing work."
+### Resolve Data Semantics (after Entity Detection, before the plan)
+
+Metadata can list the relationships a request **could** use; it cannot say which one the maker meant. Before
+you hand the plan back, settle every relationship and filter each page will use, and record what you decided
+that the request did not state.
+
+**1. Read the lookup metadata** of every existing table a page reads through a lookup (a join, a filter, a
+navigation to the referenced record, a picker that writes one), and of the target tables whose columns an
+approved filter or search needs (their primary name column):
+
+```powershell
+node "${PLUGIN_ROOT}/scripts/get-lookup-metadata.js" --env '<envUrl>' --tables '<table1>,<table2>'
+```
+
+Exit 0 prints one JSON line, `{ "ok": true, "tables": [ { "logicalName", "primaryIdAttribute",
+"primaryNameAttribute", "lookups": [ { "column", "readProperty", "attributeType", "targets", "paths",
+"sharedPaths" } ] } ] }`, only after every read completed. Save it verbatim as
+`<working-dir>/lookup-metadata.json` and carry it across re-invocations. `targets` is each lookup's
+**complete** target set; `paths` are the concrete per-target navigation paths a filter may use;
+`sharedPaths` (Owner's `ownerid`, for one) are never a target discriminator — do not invent a path such as
+`ownerid_team`. Any non-zero exit (`{ "ok": false, "code", "error" }`) means discovery failed: report it and
+stop, or ask for a supported alternative — never read a failure as "no candidates" or "one candidate". A table
+this run will create has no metadata yet: record its lookups as `planned` (below).
+
+**2. Ask rather than assume** when the meaning is open. Return the existing `needs_input` request — the
+orchestrator asks and re-invokes you — never a log line in place of the question:
+
+| Situation | Decision |
+|---|---|
+| Explicit lookup and predicate, valid in metadata | Record the stated meaning; do not ask again. |
+| Several relationships can implement "opportunities for this account" | Ask which lookup, and whether contacts roll up; show each source column and its complete targets. No default. |
+| "Recent", "open", "my" or another unresolved column, value or range | Ask, offering the discovered fields and choice values. Metadata alone cannot choose the business predicate. |
+| Unqualified list, no restriction requested | Add no active-only, owner-only or date restriction; record that no extra restriction is added. |
+| Explicit direct-relationship intent, exactly one valid candidate, no open target or roll-up choice, but the mapping still needs confirming | Ask with exactly one option marked `"default": true`; settle it only after the answer returns. |
+| Unstated layout, sort, page size or the mandatory initial-read cache | Record a visible `planner-default`; ask nothing. |
+| Failed or partial metadata | Stop, or ask for a supported alternative. |
+
+A question with several candidates carries no default:
+
+```json
+{ "action": "needs_input",
+ "why": "The possible account relationships select different opportunities.",
+ "questions": [ { "id": "opportunities-account-scope",
+ "question": "Which opportunities should this account show?",
+ "options": [
+ { "label": "Parent account", "description": "Filter parentaccountid; metadata targets account." },
+ { "label": "Direct customer", "description": "Filter customerid for account customers; metadata targets account and contact." },
+ { "label": "Customer plus contacts", "description": "Include direct account customers and contact customers linked through the verified contact relationship." } ],
+ "multiSelect": false } ] }
+```
+
+Only a sole candidate that implements an already explicit meaning is marked as the default:
+
+```json
+{ "action": "needs_input",
+ "why": "Confirm the sole metadata-backed direct relationship implementing the requested scope.",
+ "questions": [ { "id": "opportunities-account-scope",
+ "question": "Use the direct account-customer relationship, excluding contact roll-up?",
+ "options": [ { "label": "Direct customer account only",
+ "description": "The request excludes contact roll-up and metadata leaves exactly this matching path.",
+ "default": true } ],
+ "multiSelect": false } ] }
+```
+
+Return the metadata you read and the assumption ids you reserved alongside the request. On re-invocation, bind
+the returned answer to the same question id and candidates, and only then write the settled assumption. In an
+unattended run the orchestrator answers with the marked default and records
+`Unattended default: <assumption id> / <question id> → <answer> (<reason>)` — copy that line into the
+assumption's `Default record`. A question with no marked default halts an unattended run; plan approval never
+answers a semantic question. Whether a phrase entails a filter, and whether a default is genuinely safe, is
+your judgment: the validators prove the records' shape and consistency, not that judgment.
+
+**3. Record the result** in the plan (`references/plan-schema.md`, "Assumptions, data semantics and lookup
+metadata"): one `## Assumptions` entry per decision the request did not state (exactly `No assumptions.` when
+there is none); per page, its `#### Data semantics` (`R<n>`/`F<n>` decisions, each citing its assumption or
+quoting the requirement — `None.` when there is none) and its `#### Lookup metadata` (complete targets,
+uses, `observed` with concrete paths from `lookup-metadata.json`, or `planned` for a table not created yet —
+`None.` when the page uses no lookup). Keep `## User Requirements` exactly the original request.
+
+**4. Reconcile after provisioning.** When the orchestrator re-invokes you with `Lookup reconciliation:` and a
+fresh `lookup-metadata.json` (after Phase 2 created the tables), promote each `planned` lookup whose source
+column and complete target set the read confirms to `observed` and add its measured paths — change nothing
+else. If the read disagrees (another target set, no such column), do not rewrite the plan: return a revised
+plan for approval, naming the difference.
+
## Step 5 — Hand the Plan Back for Approval
If you have a task tool (`TaskCreate`, or `todo`), create tasks; if you have none, skip this
@@ -532,17 +654,42 @@ plan mode does not reach the user from a subagent.
```
## Genpage Plan
+### Assumptions
+#### A1 — [title]
+- Decision: [what the plan does]
+- Alternatives considered: [the other candidates]
+- Evidence: [metadata: … | sample: … | default: …]
+- Resolution: [user-confirmed | planner-default | unattended-default]
+[- Question / - Answer / - Default record, exactly as the plan will carry them]
+[or exactly: No assumptions.]
+
### Pages (N total)
| Page | File | Purpose | Entities |
|------|------|---------|----------|
| [Name] | [name].tsx | [one-line description] | [entity1, entity2] |
+### Data Semantics
+#### [name].tsx
+##### R1
+- Kind: relationship
+- Definition: [source column, target scope, predicate and value source, null and roll-up behaviour]
+- Source: [A1, or User Requirements with a - Requirement quote:]
+[or exactly: None.]
+
+### Lookup Metadata
+#### [name].tsx
+| Table | Column | Read property | Targets | Used by | Metadata state |
+|-------|--------|---------------|---------|---------|----------------|
+| [source table] | [lookup column] | _[column]_value | [complete target set] | [decision ids; purposes] | [observed / planned] |
+[the concrete path table, the - Evidence: and - Read target strategy: lines, as in the plan — or exactly: None.]
+
### Data Strategy
- Entities needed: [list]
- Entities that exist: [list]
- Entities to create: [list — with columns, types, relationships, choices]
- Connector bindings: [ready-to-bind connectionreference logical names, or "none"]
- Custom API bindings: [bound Custom API names (Action/Function), or "none"]
+- Built-in Dataverse operations: [the WhoAmI / RetrieveVersion rows this run's builder selected, each a user-triggered button with availability, runtime and privileges not checked — or "none"]
- Sample data: will ask after entity creation
### App
@@ -560,6 +707,11 @@ plan mode does not reach the user from a subagent.
- [styling preferences, features, accessibility notes from requirements]
```
+The preview shows `### Assumptions` **first**, so the maker sees what was assumed before the page list, and
+carries the same records the plan will (`references/plan-schema.md`, at the preview's own heading levels; a
+page's records are grouped under its file). The provenance gate compares them field by field with the
+written plan, so write them unchanged in Step 6.
+
The orchestrator calls `ExitPlanMode` to request user approval and tells you the
outcome when it re-invokes you.
@@ -581,7 +733,10 @@ ${PLUGIN_ROOT}/references/plan-schema.md
```
Read that file before writing the plan. Every required section must be present with
-the exact heading. Page filenames in the `## Pages` table must be unique, and use only letters,
+the exact heading. Write `## Assumptions` right after `## User Requirements`, and in each page's
+specification its `#### Data semantics` and `#### Lookup metadata` after the bullet fields: the records
+the maker approved, unchanged — only their heading levels differ from the preview's. Keep
+`## User Requirements` the original request, byte for byte; a later answer belongs in an assumption. Page filenames in the `## Pages` table must be unique, and use only letters,
digits, `-`, `_` and `.` — kebab-case such as `project-overview.tsx`, never a space or a shell
character: the dispatch gate refuses any other name, and the build halts.
@@ -621,6 +776,15 @@ layouts, 2-wizard-multi-step.tsx for wizards, 12-dialog-form-overlay.tsx for any
page with a modal/dialog — create/edit forms, confirm-delete, detail-in-a-dialog).
Do NOT list reference docs as samples — only files under `samples/`.
+For a page that navigates to an existing page that this plan does not build (a page of the chosen
+app, by its page id), read what that page accepts before you plan the call. Follow
+`${PLUGIN_ROOT}/references/rules.md` → **Page Input > What another page accepts**: download the page
+into `<working-dir>/targets` with `genpage.js download` and read its `pageInput` reads. Then write
+in the page's **Interactions** the target's page id, the exact `data` keys it reads (each with the
+type it converts the value to), and whether it reads record context (`pageInput.recordId`,
+`pageInput.entityName`), which the call passes at the top level, not in `data`. If it reads neither,
+write that it takes no input. The page-builder uses what you wrote and never guesses it.
+
### CRITICAL — Pre-write validation pass
Before calling `Write` to save `genpage-plan.md`, scan the in-memory document
@@ -636,6 +800,9 @@ and verify the prefix discipline:
2. If any value fails, do NOT write the plan. Rewrite the offending values to
their bare suffix form and re-validate. Only write once all values pass.
+3. Every relationship and every server-side or client-side filter used in `## Per-Page Specifications` traces to the user's stated text in `## User Requirements` or a named `## Assumptions` entry. The builder introduces no unrecorded business predicate, relationship or roll-up.
+ Validation proves structure, ID resolution, quote presence and agreement with approved structured decisions. It does not prove natural-language entailment, judge materiality, or discover arbitrary contradictory prose. Those remain planner/reviewer responsibilities, supplemented by scenario-specific code checks.
+
This is a hard gate. If you can't produce a valid plan after one rewrite,
abort and report the offending name to the user — better to fail loudly than
let the entity-builder construct a wrong-prefix name and silently corrupt the
diff --git a/plugins/model-apps/docs/app-builder-capabilities.md b/plugins/model-apps/docs/app-builder-capabilities.md
index 1a8628fe5..3cced7e73 100644
--- a/plugins/model-apps/docs/app-builder-capabilities.md
+++ b/plugins/model-apps/docs/app-builder-capabilities.md
@@ -145,7 +145,7 @@ apart deliberately.
`None` — 6/6.
### App shell & navigation — ✅ verified live
-- App module + sitemap; **multi-area sitemaps** — every `appShell.areas[]` maps to its own `<Area>` (icon + groups + subareas; order follows array order). The app is **self-contained for export/import**: its **sitemap** is added to the solution (componenttype 62), and its **tile icon** is an in-solution web resource — `app.icon` (a declared image web resource) or a generated default SVG — never an arbitrary external/managed icon.
+- App module + sitemap; **multi-area sitemaps** — every `appShell.areas[]` maps to its own `<Area>` (icon + groups + subareas; order follows array order). The app is **self-contained for export/import**: its **sitemap** is added to the solution (componenttype 62), each **generative page** the build writes or keeps joins it too (as the page table's own component type, read from the environment — offline-tested; the add of the app never brings the pages), and its **tile icon** is an in-solution web resource — `app.icon` (a declared image web resource) or a generated default SVG — never an arbitrary external/managed icon.
- **App membership (offline-tested; reference transport measured):** `app.tables` preserves hidden
table components independently of navigation; `app.mainForms` selects active Main forms by name.
Create is exact for Main membership; updates stop adding excluded forms but never remove existing
diff --git a/plugins/model-apps/docs/architecture.md b/plugins/model-apps/docs/architecture.md
index 6b5feb7de..3d4e9f50d 100644
--- a/plugins/model-apps/docs/architecture.md
+++ b/plugins/model-apps/docs/architecture.md
@@ -124,7 +124,7 @@ Key sections the orchestrator and other agents rely on:
| Section | Read by | Purpose |
|---------|---------|---------|
-| `## Environment` (Solution + Publisher Prefix) | entity-builder | Solution scoping + prefix construction |
+| `## Environment` (Solution + Publisher Prefix) | entity-builder, orchestrator (Phase 6) | Solution scoping + prefix construction; the solution the new app and every page this run creates join |
| `## Entity Creation Required` | orchestrator (Phase 2 gate) + entity-builder | Whether to invoke entity-builder; what to create |
| `## Existing Entities` | orchestrator (Phase 4) | Which entities feed `genpage.js types` |
| `## Pages` | orchestrator (Phase 5) | How many builders to dispatch; target filenames |
diff --git a/plugins/model-apps/feature-flags.json b/plugins/model-apps/feature-flags.json
index 61cd44768..878863559 100644
--- a/plugins/model-apps/feature-flags.json
+++ b/plugins/model-apps/feature-flags.json
@@ -1,5 +1,5 @@
{
- "_comment": "Feature flags for the /genpage skill. Custom API discovery is enabled by default; custom telemetry remains off. Environment overrides take precedence and unknown or missing flags fail closed.",
- "custom-api": true,
- "custom-telemetry": false
+ "_comment": "Feature flags for the /genpage skill. Custom telemetry and built-in Dataverse operation authoring are off. Custom API support has no flag: it is always available. Environment overrides take precedence and unknown or missing flags fail closed.",
+ "custom-telemetry": false,
+ "dataverse-operations": false
}
diff --git a/plugins/model-apps/references/app-spec-schema-advanced.md b/plugins/model-apps/references/app-spec-schema-advanced.md
index 433aec0f4..4069dc875 100644
--- a/plugins/model-apps/references/app-spec-schema-advanced.md
+++ b/plugins/model-apps/references/app-spec-schema-advanced.md
@@ -41,7 +41,10 @@ Reference from a column via `"globalChoice": "new_priority"` (built before the c
- Built **before** forms and added to the solution; reference one from a form `events[]` handler.
- **Content edits are NOT applied on rebuild.** Like commands, the phase is discover-then-skip: a web
resource that already exists is reused as-is, so changing `content` and rebuilding deploys nothing
- and the old script keeps running. Delete the web resource (or tear down) and rebuild to change it —
+ and the old script keeps running. The build says so: it compares the deployed content with the spec's,
+ and when they differ its line reads `(exists — reuse; its deployed content differs from the spec's …)`
+ and a warning names the web resource; verify fails its `web-resource` check for the same reason (an
+ `external` entry is checked only for existence). Delete the web resource (or tear down) and rebuild to change it —
note it cannot be deleted while a command or form handler still references it.
- **An unconfirmed first write is different from an ordinary content edit.** A
`WEB_RESOURCE_UNVERIFIED` halt names the existing row; it does not mean the resource was lost.
diff --git a/plugins/model-apps/references/app-spec-schema.md b/plugins/model-apps/references/app-spec-schema.md
index d4426d137..1450eb574 100644
--- a/plugins/model-apps/references/app-spec-schema.md
+++ b/plugins/model-apps/references/app-spec-schema.md
@@ -70,7 +70,10 @@ sample data (incl. multi-parent junction links + status reasons), and publish.
(png/jpg/gif/svg/ico in `webResources[]`) so the app is **self-contained** on export/import.
**Omit it** and the build generates a simple default SVG icon **inside the solution** — either
way the app never depends on an arbitrary external/managed icon (which would fail to import into
- a new environment). The app's **sitemap** is also added to the solution automatically.
+ a new environment). The app's **sitemap** is also added to the solution automatically, and so is every
+ **generative page** the build writes or keeps (a changed-only run asserts the pages it leaves as they are
+ too): the add of the app brings its sitemap but never the pages its
+ navigation opens, so each page is added on its own (a system solution such as `Default` holds them already).
**The icon is set when the app is created, and a rebuild cannot change it** (the platform stores it once): when
`app.icon` names a web resource that is not the icon the app has, the build warns that it was **not applied** —
change it in the app designer, or point `app.icon` at the web resource the app already uses. A spec with no
@@ -307,11 +310,40 @@ An `entities[].localizedLabels` key is therefore **not** a supported shape.
**Referencing a localized label.** Anywhere the spec names an artifact by its label — `sampleData`
choosing a Choice option, or `personas[].jobs[].surfaces[]` naming a screen — **any** of its
-languages resolves to the same artifact. One option, one value, several names.
+languages resolves to the same artifact. One option, one value, several names. So one text must not
+name two options of a column: validation **refuses** it when you cannot see it on the line — one of the
+two is a label of several languages the other does not match in every language, or they are in different
+languages (`"Open"` beside `{ "3082": "Open" }`) — and **warns** when you can: two equal plain strings, or
+two identical localized labels, the same text in each of the same languages (`{ "1036": "Ouvert" }` twice,
+or `{ "1033": "Abierto", "3082": "Abierto" }` twice — how Dataverse holds two options labelled "Abierto" in
+Spanish on an English environment: it fills the base language in with the same text). Dataverse allows
+that duplicate; a reference to the text resolves to the first of the two.
**Round-trip.** `download-model-app` reconstructs localized labels from Dataverse: a table, plural,
-column or option labelled in several languages comes back as a map, and one labelled in a single
-language comes back as a plain string (so no existing spec changes shape). The download emits
+column, lookup, alternate key or option labelled in several languages comes back as a map. One labelled
+in a single language comes back as a plain string when that language is the download's authoring
+language (`--language-code`, else the `languageCode` the spec already on disk pins, else the environment's
+base language — so no ordinary spec changes shape), and as a **one-entry map** when it is another:
+`{ "3082": "Pedido" }` for a table labelled only in Spanish, the base language of its environment,
+downloaded in English with `--language-code 1033`; `{ "1033": "Note" }` for an English-only column of an
+English environment downloaded with `--language-code 3082`. (Dataverse fills the base language in, with the
+same text, when a label is created in another language only, so the one language a label holds alone is the
+environment's base language.) A plain string is written in the language a rebuild resolves, so that label used to
+come back as an English label with Spanish text; a map keeps its language, and a rebuild into an
+environment that does not have it stops at the start of its data model and names it (see the rule above)
+instead. Every plain label in a downloaded spec is in the authoring language, as its navigation titles
+are: a rebuild into an environment whose base language is another writes them in that one, unless the
+spec pins `languageCode` or the build is given `--language-code`. Two Choice options a maker labelled with
+the same text keep their labels, and the column its type, when the two labels are identical in every language
+they hold (a duplicate validation warns about) — the way Dataverse holds them; when the text is in two
+languages — an English `"Open"` on one option, a Spanish `"Open"` on another — the spec can hold those two
+options only as plain strings, so they alone are written that way, and the download warns that their labels
+could not keep their language. A clash the spec cannot hold at all — two labels of several languages that
+differ in some language, so which option the text means depends on the language — leaves the column without
+a type, and the download's warning names the clash. A lookup that sets no
+label is labelled like the table it points at (see `lookup.displayName` below), so the download leaves a
+lookup's label out only when that label is the lookup's own, language for language: an English `"Contact"`
+on a lookup to a table labelled only in French `"Contact"` is written out. The download emits
`pluralName` alongside a localized `displayName`, so its own output re-validates, and beside a plain one
whenever it is not the `"<displayName>s"` a rebuild would derive — `"Tag Catalog"` for `"Tag"` comes back,
`"Tags"` does not (it is the default).
@@ -363,7 +395,8 @@ maker typed in the UI**.
reconstruct as rebuildable spec (`solution`, `entities[]`, `entities[].columns[]`, `dashboards[]`).
Views, charts, forms, business rules and global choices are not fully reconstructed yet, so their
deployed descriptions are exposed under `descriptionInventory` for inspection only rather than as
-partial rebuildable artifacts. Null or absent Dataverse descriptions are omitted, never written as
+partial rebuildable artifacts (the command-bar buttons of the app's tables are listed there too, by
+table and label). Null or absent Dataverse descriptions are omitted, never written as
`""`.
**Rebuild behaviour:** a description is written at CREATE, and is additionally **reconciled on an
@@ -400,6 +433,14 @@ difference and the next full build restores the spec's value (a `--changed-only`
spec with its last snapshot, not with the deployed row, so it does not notice).
## entities[]
+
+**An app with no tables of its own** — one whose navigation holds only generative pages, dashboards over
+tables the environment already has, or URLs (an app made with `apps.js create --page-id` is one) — is a
+valid spec with `"entities": []`. The build makes it (a navigation of pages only is built pages first), and
+`download-model-app.js`, `--verify` and teardown take it as they take any other spec. A spec with no table
+**and** no navigation entry has nothing to build an app from, and is refused: `at least one entity is
+required`.
+
```jsonc
{
"schemaName": "new_ticket", // publisher-prefixed; logical name is its lowercase
@@ -469,7 +510,10 @@ spec with its last snapshot, not with the deployed row, so it does not notice).
plus `statusReasons` / `alternateKeys` / `mainFormOrder`. Anything else — a misspelled `pluralname`, or a
`languageCode` / `localizedLabels` asking for a per-table language or a parallel label block —
fails validation naming the alternative, rather than validating clean and being dropped from the
- build.
+ build. **`primaryAttribute` takes exactly `schemaName`, `displayName`, `autoNumberFormat`, `required`
+ and `maxLength`** — the same rule one level down: a `maxlength`, `autonumberFormat`, `requiredLevel` or
+ `type` there is refused, naming the key it most likely meant (the name column is always text, so it has
+ no `type`).
- **Column `type`:** `Text · Memo · Choice · MultiChoice · Boolean · Money · DateTime ·
Integer · BigInt · Decimal · Double · File · Image · AutoNumber · Customer`.
**Lookups are NOT columns** — declare a `OneToMany` relationship instead.
@@ -1619,8 +1663,10 @@ custom control), but the spec validator emits a warning.
An unreadable proof or failed record write leaves the app intact. A retry uses those records even
when `pages[]` is empty and the app has already gone. Proven pages still undeleted keep their records,
manifest and solution and prevent a successful result. Only completed deletion or confirmed absence
- consumes the records. Form-only references are not scanned; platform sitemap dependencies remain an
- additional safeguard, not proof that no form embeds the page.
+ consumes the records. **Known limit:** a page a **form** still embeds (the `MscrmControls.UxAgentControl`
+ control, whose `RefId` holds the page id) is deleted anyway — the platform records no dependency for it, and
+ teardown reads no form — and the form is left pointing at a page that is gone. Take the page off such forms (or
+ delete them) before tearing the app down; the dry run lists every page it would delete.
- **Workspace clearing preserves ownership.** `--clear-workspace` refuses while any unconsumed local
ownership record remains, including other apps/environments. The refusal names each record file.
Teardown consumes a record when it deletes or confirms the page's absence; a record whose page
@@ -1727,12 +1773,19 @@ custom control), but the spec validator emits a warning.
only through a custom connector's definition (its `connector` row), which is the environment's own and can be
another version than the page was made with; a reference whose custom connector lookup is absent, null or not a
GUID — which a connector the platform publishes also has — is not proof of which connector defines them.
+ - **built-in operations** — an `actionBindings` entry named exactly `WhoAmI` or `RetrieveVersion` is a reviewed
+ built-in Dataverse Function, not a Custom API (`references/dataverse-operations.md`): it is left out of the
+ `customapi` read (a page that binds only them reads no `customapi` row), never called missing, and said as NOT
+ CHECKED — its availability in the environment or player and the signed-in user's permissions; one whose
+ declarations do not explicitly say "unbound Function, no inputs" draws a `dataverse-operation-shape` warning and
+ is written as the spec states it. A download names them under `pageBindings.neededInTarget.dataverseOperations`,
+ never under `customApis`: there is nothing to deploy. Any other spelling (`whoami`) is a Custom API name.
`/app-builder` never authors these lists — it writes no connector or Custom API code — so they come from a page
a download read. A page you reset to `source.kind: "intent"` to regenerate it is generated without connector
- code: delete its bindings from the spec too, or it keeps bindings its code no longer uses. The `custom-api`
- feature flag gates what the `/genpage` agents author, not the download or the rebuild of bindings a page
- already holds.
+ code: delete its bindings from the spec too, or it keeps bindings its code no longer uses. The
+ `dataverse-operations` feature flag gates what the `/genpage` agents author, not the download or the rebuild
+ of bindings a page already holds.
- **Safety HALTs (pages phase).** The build halts on identity/safety violations rather than
proceeding with potentially wrong state:
- `pages-identity-conflict` — spec `pageId` and manifest disagree on a key, or a duplicate id is
@@ -1868,6 +1921,15 @@ custom control), but the spec validator emits a warning.
```
- Shared styling tokens threaded to every page so generated pages look consistent with each other
and the model-driven shell (both Fluent UI V9). Unknown keys are rejected.
+- **`style`** *(optional)* — the maker's own look, in words, when they ask for one: a screenshot or
+ mockup read into colors and fonts, a website to match, or a description (`"navy #0b2545 primary,
+ gold #c9a227 accent, warm white #faf7f0 background, Georgia headings, 2px corners (from:
+ screenshot)"`). Give concrete values: hex colors with their roles, a font with a fallback, corner
+ radius, density. It wins over the default model-driven look: the page plan carries it as a
+ `Styling:` line that starts with `Maker-requested:`, and every page applies it
+ (`references/rules.md` → *Maker-requested styling*, which also says what a page cannot match).
+ Omit it to keep the default look. It must be a non-empty string. It is stored in the app's page
+ manifest with the rest of `design`, so a download keeps it.
- During **generate-pages** the design contract is passed to each headless `page-builder` agent
so all generated `.tsx` files apply the same Fluent UI V9 token set (accent color, density,
corner radius, dark-mode policy). Run `node scripts/preview-app.js @<dir>/app-spec.json` to
diff --git a/plugins/model-apps/references/connectors.md b/plugins/model-apps/references/connectors.md
index 210758b77..c544190eb 100644
--- a/plugins/model-apps/references/connectors.md
+++ b/plugins/model-apps/references/connectors.md
@@ -80,7 +80,15 @@ connector it is for) is said by name as not checked.
- Always cast `dataApi` to an optional connector-method shape.
- Always presence-check the method before calling it.
-- Always wrap calls in `try`/`catch` and set a graceful empty/error state.
+- Always await calls in a `try` whose `catch` reports the failure through the page's
+ `reportPageError` (rules.md → *Missing Error Handling*) into the panel's error state, rendered
+ by `PageErrorBar` beside a graceful empty state. A failed operation response (`!response.ok`)
+ is a failure too, though nothing was thrown: report it before reading `response.body`. Its
+ envelope carries no message or code, so pass none — never invent an `error.code` — and the bar
+ shows its fixed fallback copy.
+- Classify the kind from the plan, never from the response: a `queryConnectorTable` read, or an
+ operation the plan records as a read, is `'read'` and may offer a named manual retry; any other
+ operation is `'write'`, with no retry.
- Never guess a logical name, dataset, table GUID, operation name, field name,
parameter name, or response field name. Use the plan's `## Connector Bindings`
values only.
@@ -144,10 +152,72 @@ const parameters: { Location: string; units?: string } = { Location: 'Seattle',
## Verified tabular pattern
+A complete `PageBody` for a list read on mount, built on the page error block of rules.md. A
+connector read is a real host read, so it uses the in-flight de-dupe and cache of
+`references/data-caching.md` (Pattern 1), with keys unique to the page and the connector query:
+
```typescript
-const connectorApi = dataApi as unknown as { queryConnectorTable?: (connectorLogicalName: string, dataset: string, table: string, options: Record<string, unknown>) => Promise<{ rows: Row[] }>; };
-if (typeof connectorApi.queryConnectorTable !== 'function') { return; }
-const result = await connectorApi.queryConnectorTable('new_uxtest_sharepoint', 'https://host.sharepoint.com/sites/x', '<list-guid>', { top: 50 });
+type DocumentRow = { ID?: number; Title?: string; Modified?: string };
+type ConnectorTableApi = {
+ queryConnectorTable?: (connectorLogicalName: string, dataset: string, table: string, options: Record<string, unknown>) => Promise<{ rows: DocumentRow[] }>;
+};
+
+const winAny = window as any;
+const CACHE_KEY = '__ppTeamDocuments_documentsCache';
+const INFLIGHT_KEY = '__ppTeamDocuments_documentsInflight';
+
+function PageBody(props: GeneratedComponentProps) {
+ const { dataApi, pageInput } = props;
+ void pageInput;
+ const connectorApi = dataApi as unknown as ConnectorTableApi;
+ const dataReady = !!dataApi;
+ const [reloadKey, setReloadKey] = React.useState(0);
+ const [{ documents, loading, error }, setData] = React.useState<{ documents: DocumentRow[]; loading: boolean; error: PageErrorView | null }>(() => {
+ const cached = winAny[CACHE_KEY] as DocumentRow[] | undefined;
+ return { documents: cached ?? [], loading: cached === undefined, error: null };
+ });
+
+ function retryLoad() {
+ delete winAny[CACHE_KEY];
+ delete winAny[INFLIGHT_KEY];
+ setReloadKey((key) => key + 1);
+ }
+
+ React.useEffect(() => {
+ if (!dataReady) return;
+ // An older runtime without the method has no connector data to show: an empty list, not a failure.
+ if (typeof connectorApi.queryConnectorTable !== 'function') { setData({ documents: [], loading: false, error: null }); return; }
+ const cached = winAny[CACHE_KEY] as DocumentRow[] | undefined;
+ if (cached !== undefined) {
+ if (documents !== cached) setData({ documents: cached, loading: false, error: null });
+ return;
+ }
+ let cancelled = false;
+ let inflight = winAny[INFLIGHT_KEY] as Promise<DocumentRow[]> | undefined;
+ if (!inflight) {
+ inflight = connectorApi
+ .queryConnectorTable('new_uxtest_sharepoint', 'https://contoso.sharepoint.com/sites/docs', '<list-guid>', { top: 50 })
+ .then((result) => {
+ winAny[CACHE_KEY] = result.rows;
+ return result.rows;
+ })
+ .finally(() => { if (winAny[INFLIGHT_KEY] === inflight) delete winAny[INFLIGHT_KEY]; });
+ winAny[INFLIGHT_KEY] = inflight;
+ }
+ inflight
+ .then((rows) => { if (!cancelled) setData({ documents: rows, loading: false, error: null }); })
+ .catch((failure) => { if (!cancelled) setData({ documents: [], loading: false, error: reportPageError(PAGE_NAME, 'loadDocuments', undefined, failure, 'read', retryLoad) }); });
+ return () => { cancelled = true; };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [dataReady, reloadKey]);
+
+ return (
+ <div>
+ <PageErrorBar error={error} />
+ {loading ? <Spinner label="Loading documents" /> : documents.map((row) => <Text key={String(row.ID)}>{row.Title}</Text>)}
+ </div>
+ );
+}
```
Use this for connectors exposed as tables/lists. The `dataset` and `table`
@@ -155,10 +225,45 @@ arguments come from `## Connector Bindings` (`Dataset` and `Tables (GUIDs)`).
## Verified REST/action pattern
+A complete `PageBody` for an operation the user starts. `CurrentWeather` only reads, so its
+failure is a `'read'` with a named retry; an operation the plan does not record as a read is a
+`'write'` with no retry.
+
```typescript
-const connectorApi = dataApi as unknown as { executeConnectorOperation?: (connectorLogicalName: string, operationName: string, parameters: Record<string, unknown>) => Promise<{ ok: boolean; body: unknown }>; };
-if (typeof connectorApi.executeConnectorOperation !== 'function') { return; }
-const response = await connectorApi.executeConnectorOperation('new_uxtest_msnweather', 'CurrentWeather', { Location: 'Seattle', units: 'C' });
+type WeatherResponse = { temperature?: number; conditions?: string; humidity?: number };
+type ConnectorOperationApi = {
+ executeConnectorOperation?: (connectorLogicalName: string, operationName: string, parameters: Record<string, unknown>) => Promise<{ ok: boolean; body: unknown }>;
+};
+
+function PageBody(props: GeneratedComponentProps) {
+ const { dataApi, pageInput } = props;
+ void pageInput;
+ const connectorApi = dataApi as unknown as ConnectorOperationApi;
+ const [weather, setWeather] = React.useState<{ weather: WeatherResponse | null; error: PageErrorView | null }>({ weather: null, error: null });
+
+ function retryWeather() {
+ void loadWeather();
+ }
+
+ async function loadWeather() {
+ if (typeof connectorApi.executeConnectorOperation !== 'function') return;
+ try {
+ const response = await connectorApi.executeConnectorOperation('new_uxtest_msnweather', 'CurrentWeather', { Location: 'Seattle', units: 'C' });
+ if (!response.ok) { setWeather({ weather: null, error: reportPageError(PAGE_NAME, 'loadWeather', undefined, undefined, 'read', retryWeather) }); return; }
+ setWeather({ weather: response.body as WeatherResponse, error: null });
+ } catch (error) {
+ setWeather({ weather: null, error: reportPageError(PAGE_NAME, 'loadWeather', undefined, error, 'read', retryWeather) });
+ }
+ }
+
+ return (
+ <div>
+ <PageErrorBar error={weather.error} />
+ <Button onClick={() => void loadWeather()}>Show the weather</Button>
+ {weather.weather?.conditions && <Text>{weather.weather.conditions}</Text>}
+ </div>
+ );
+}
```
Use this for REST-style connector operations. Check `response.ok` before reading
diff --git a/plugins/model-apps/references/custom-api.md b/plugins/model-apps/references/custom-api.md
index 598b0c2ef..2b82e1495 100644
--- a/plugins/model-apps/references/custom-api.md
+++ b/plugins/model-apps/references/custom-api.md
@@ -6,10 +6,9 @@ token** (no broker, no impersonation). The `name` string a page passes to
`dataApi.executeAction` / `executeFunction` **MUST** equal an `actionBindings[].name` value
in the page `config.json`, and that Custom API must exist in the target environment.
-> **Custom API discovery is enabled by default**, with a retained `custom-api` feature flag.
-> Set `GENPAGE_ENABLE_CUSTOM_API=0` to opt out. Unknown flags and missing/unreadable config
-> still fail closed. When OFF, no new Custom API bindings or calls are authored; unrelated
-> edits preserve existing bindings unchanged. The `genpage-customapi-builder` agent owns this gate.
+> **Custom API support has no feature flag.** Discovery, authoring and upload are always
+> available; the `custom-api` flag that once gated them was removed, and
+> `GENPAGE_ENABLE_CUSTOM_API` is ignored. The `genpage-customapi-builder` agent owns discovery.
> **Vocabulary.** Makers author **Custom APIs** (the Dataverse `customapi` artifact); each is
> either an **Action** (POST; call with `executeAction`) or a **Function** (GET;
@@ -19,6 +18,11 @@ in the page `config.json`, and that Custom API must exist in the target environm
> `--actions`. So the maker-facing skill says "Custom API" while the wire format stays
> `actionBindings` — the two describe the same thing at different layers.
+> **Two `actionBindings` names are not Custom APIs.** Exactly `WhoAmI` and `RetrieveVersion`
+> are reviewed built-in Dataverse Functions behind their own default-off
+> `dataverse-operations` flag: discovery here never lists them, and a missing Custom API row
+> is never their problem. See `references/dataverse-operations.md`.
+
## Binding shape: `actions.json` (array) vs page `config.json` (object)
The skill writes a **bare JSON array** of bindings to working-dir `actions.json`.
@@ -87,8 +91,7 @@ a spec that states one is refused (see `references/app-spec-schema.md` → `page
itself never reads or writes the spec. The spec carries the list and not the Custom APIs it names: each must
already exist in the environment you rebuild into, deployed in a solution. A rebuild reads the environment's Custom
APIs before it writes and says by name one that is not there, one that is the other kind (Action or Function) and
-one bound to another table; it does not stop for them. The `custom-api` flag gates what the `/genpage` agents
-author, not this.
+one bound to another table; it does not stop for them.
An App Spec must not declare `EntityReference`, `Entity` or `EntityCollection`. A downloaded list
holding an unsupported declared kind is left out whole and reported by place and property, never
@@ -149,9 +152,10 @@ See <https://learn.microsoft.com/power-apps/developer/data-platform/reference/en
- Always cast `dataApi` to the optional action-method shape and **presence-check** the method
before calling it — the methods are absent on older runtimes.
-- **Actions may mutate: guard against double-submit.** Keep an `isSubmitting` flag per
- action-triggering control; disable it while a call is in flight; never fire a second
- `executeAction` for the same trigger before the first resolves.
+- **Actions may mutate: guard against double-submit.** Keep a synchronous latch per
+ action-triggering control (`pending.current`, set before the call and reset in `finally`, as in
+ the pattern below) or an `isSubmitting` flag; disable the control while a call is in flight;
+ never fire a second `executeAction` for the same trigger before the first resolves.
- **Functions use GET, not a proof of harmless behavior.** Automatic mount/filter invocation
requires author-known read semantics for the selected Custom API. Otherwise require an explicit
user trigger and prevent overlapping submissions; still avoid pointless fetches and ignore stale responses.
@@ -164,10 +168,16 @@ See <https://learn.microsoft.com/power-apps/developer/data-platform/reference/en
- **Read outputs from `res.outputs`, never `res.value`.**
- **Never surface raw fault text.** On `res.ok === false`, show only the SANITIZED
`res.error?.message` in a message bar. Never render stack traces or plug-in fault detail.
+ Every failed result and every rejection goes through the page's `reportPageError`
+ (rules.md → *Missing Error Handling*) with the result's `res.error?.code` and
+ `res.error?.message` — never the result itself — and a literal kind; `PageErrorBar` shows
+ the view it returns.
- **Never auto-retry.** `res.indeterminate` (timeout after dispatch — the server may have
committed) must never be retried automatically; ask the user to refresh. Only
`res.error?.code === 'network'` is safely retryable (the request never left the client), and
- even then only via a manual "Try again". Do not confuse the two.
+ even then only via a manual "Try again". Do not confuse the two. Check both indeterminate
+ forms first — `res.indeterminate`, then `res.error?.code === 'indeterminate'` — then
+ `network`, then any other failure, each reporting and returning before `res.outputs` is read.
- **Never guess** a name, parameter name, or output field. Use only the plan's
`## Custom API Bindings` values and the declared parameter/output names.
- Keep non-action pages unchanged; only emit action code when the plan has action bindings.
@@ -213,37 +223,135 @@ Teach every one; a page that mishandles a code degrades badly.
## Verified Action pattern (may mutate; double-submit guarded)
+A complete `PageBody` for a bound Action, built on the page error block of rules.md (which supplies
+`PAGE_NAME`, `reportPageError`, `PageErrorBar`, the boundary and the default export). The handler is a
+named function inside `PageBody` because it closes over state; `setActionFailure` stores the view and
+`pending: false` in one update; `retryApprove` is passed, never called, and only for a `network` result.
+The approval belongs to the record it was started on: `approvalFor` holds the record the panel shows, a
+record change clears the panel — and with it any retry — and an answer that arrives after the page moved
+to another record is ignored, so a retry can only ever re-send the approval of the record on screen.
+
```typescript
-const actionApi = dataApi as unknown as { executeAction?: (request: { name: string; parameters?: Record<string, unknown>; boundTo?: { entityName: string; id: string } }) => Promise<{ ok: boolean; indeterminate?: boolean; outputs?: Record<string, unknown>; error?: { message: string; code?: string } }>; };
-if (typeof actionApi.executeAction !== 'function') { return; } // presence-check; hide/disable the trigger
-if (isSubmitting) { return; } // double-submit guard
-setIsSubmitting(true);
-try {
- const res = await actionApi.executeAction({
- name: 'new_ApproveOrder',
- parameters: { Comment: comment, Amount: amount }, // types match parameterKinds
- boundTo: { entityName: pageInput.entityName, id: pageInput.recordId }, // REQUIRED: entity-bound
- });
- if (res.indeterminate) { setError("We couldn't confirm this completed — refresh before retrying."); return; }
- if (!res.ok) { setError(res.error?.message ?? 'The action failed.'); return; } // sanitized only
- const { NewStatus } = res.outputs as { NewStatus: string }; // read from outputs, never value
-} finally {
- setIsSubmitting(false);
+type ActionResult = { ok: boolean; indeterminate?: boolean; outputs?: Record<string, unknown>; error?: { message: string; code?: string } };
+type ActionApi = {
+ executeAction?: (request: { name: string; parameters?: Record<string, unknown>; boundTo?: { entityName: string; id: string } }) => Promise<ActionResult>;
+};
+
+function PageBody(props: GeneratedComponentProps) {
+ const { dataApi, pageInput } = props;
+ const actionApi = dataApi as unknown as ActionApi;
+ const currentRecord = pageInput?.recordId ?? '';
+ const [comment, setComment] = React.useState('');
+ const [approval, setApproval] = React.useState<{ pending: boolean; status: string; error: PageErrorView | null }>({ pending: false, status: '', error: null });
+ const pending = React.useRef(false); // double-submit latch
+ const approvalFor = React.useRef(currentRecord); // the record the approval panel belongs to
+
+ // Another record starts a clean panel: the previous record's result, and its retry, are cleared.
+ React.useEffect(() => {
+ approvalFor.current = currentRecord;
+ setApproval({ pending: false, status: '', error: null });
+ }, [currentRecord]);
+
+ function setActionFailure(view: PageErrorView) {
+ setApproval({ pending: false, status: '', error: view });
+ }
+
+ function retryApprove() {
+ if (currentRecord && currentRecord === approvalFor.current) void approveOrder(currentRecord, comment); // only while this record is shown
+ }
+
+ async function approveOrder(recordId: string, note: string) {
+ if (typeof actionApi.executeAction !== 'function') return; // presence-check; hide/disable the trigger
+ if (pending.current || !recordId) return; // double-submit guard
+ pending.current = true;
+ setApproval({ pending: true, status: '', error: null });
+ try {
+ const res = await actionApi.executeAction({
+ name: 'new_ApproveOrder',
+ parameters: { Comment: note }, // types match parameterKinds
+ boundTo: { entityName: 'salesorder', id: recordId }, // REQUIRED: entity-bound
+ });
+ if (recordId !== approvalFor.current) return; // the page moved on: not this record's answer
+ if (res.indeterminate) { setActionFailure(reportPageError(PAGE_NAME, 'approveOrder', res.error?.code, res.error?.message, 'indeterminate')); return; }
+ if (res.error?.code === 'indeterminate') { setActionFailure(reportPageError(PAGE_NAME, 'approveOrder', res.error?.code, res.error?.message, 'indeterminate')); return; }
+ if (!res.ok && res.error?.code === 'network') { setActionFailure(reportPageError(PAGE_NAME, 'approveOrder', res.error?.code, res.error?.message, 'network', retryApprove)); return; }
+ if (!res.ok) { setActionFailure(reportPageError(PAGE_NAME, 'approveOrder', res.error?.code, res.error?.message, 'write')); return; }
+ const status = res.outputs?.NewStatus; // read from outputs, never value
+ setApproval({ pending: false, status: typeof status === 'string' ? status : '', error: null });
+ } catch (error) {
+ if (recordId !== approvalFor.current) return;
+ setActionFailure(reportPageError(PAGE_NAME, 'approveOrder', undefined, error, 'write'));
+ } finally {
+ pending.current = false;
+ }
+ }
+
+ return (
+ <div>
+ <PageErrorBar error={approval.error} />
+ <Input aria-label="Comment" value={comment} onChange={(_, data) => setComment(data.value)} />
+ <Button appearance="primary" disabled={approval.pending} onClick={() => void approveOrder(currentRecord, comment)}>Approve</Button>
+ {approval.status && <Text>{approval.status}</Text>}
+ </div>
+ );
}
```
-For a **Global** action, omit `boundTo` entirely.
+The order is the contract: both indeterminate forms first (`'indeterminate'`, no retry — the server may
+have committed), then `network` (`'network'`, the named manual retry), then any other failure
+(`'write'`, no retry), each storing its view and returning before `res.outputs` is read; a rejection is
+a `'write'` too. Each kind is a literal — never a ternary. For a **Global** action, omit `boundTo`
+entirely.
## Function pattern (known read semantics required before automatic invocation)
+A complete `PageBody` for a Function the plan records as a read: a failure is a `'read'` with a named
+reload. A Function whose side effects are not established is a `'write'` with no retry, called only
+from a button with the Action's overlap guard.
+
```typescript
-const actionApi = dataApi as unknown as { executeFunction?: (request: { name: string; parameters?: Record<string, unknown> }) => Promise<{ ok: boolean; outputs?: Record<string, unknown>; error?: { message: string; code?: string } }>; };
-if (typeof actionApi.executeFunction !== 'function') { return; }
-const res = await actionApi.executeFunction({ name: 'new_GetOrderSummary', parameters: { OrderId: orderId } });
-if (!res.ok) { setError(res.error?.message ?? 'Could not load the summary.'); return; }
-const { Total, Status } = res.outputs as { Total: number; Status: string };
-```
+type FunctionResult = { ok: boolean; indeterminate?: boolean; outputs?: Record<string, unknown>; error?: { message: string; code?: string } };
+type FunctionApi = {
+ executeFunction?: (request: { name: string; parameters?: Record<string, unknown> }) => Promise<FunctionResult>;
+};
+
+function PageBody(props: GeneratedComponentProps) {
+ const { dataApi, pageInput } = props;
+ const functionApi = dataApi as unknown as FunctionApi;
+ const [summary, setSummary] = React.useState<{ total: number | null; error: PageErrorView | null }>({ total: null, error: null });
+ function setSummaryFailure(view: PageErrorView) {
+ setSummary({ total: null, error: view });
+ }
+
+ function retrySummary() {
+ void loadSummary(pageInput?.recordId ?? '');
+ }
+
+ async function loadSummary(orderId: string) {
+ if (typeof functionApi.executeFunction !== 'function') return;
+ try {
+ const res = await functionApi.executeFunction({ name: 'new_GetOrderSummary', parameters: { OrderId: orderId } });
+ if (res.indeterminate) { setSummaryFailure(reportPageError(PAGE_NAME, 'loadSummary', res.error?.code, res.error?.message, 'indeterminate')); return; }
+ if (res.error?.code === 'indeterminate') { setSummaryFailure(reportPageError(PAGE_NAME, 'loadSummary', res.error?.code, res.error?.message, 'indeterminate')); return; }
+ if (!res.ok && res.error?.code === 'network') { setSummaryFailure(reportPageError(PAGE_NAME, 'loadSummary', res.error?.code, res.error?.message, 'network', retrySummary)); return; }
+ if (!res.ok) { setSummaryFailure(reportPageError(PAGE_NAME, 'loadSummary', res.error?.code, res.error?.message, 'read', retrySummary)); return; }
+ const total = res.outputs?.Total;
+ setSummary({ total: typeof total === 'number' ? total : null, error: null });
+ } catch (error) {
+ setSummaryFailure(reportPageError(PAGE_NAME, 'loadSummary', undefined, error, 'read', retrySummary));
+ }
+ }
+
+ return (
+ <div>
+ <PageErrorBar error={summary.error} />
+ <Button onClick={() => void loadSummary(pageInput?.recordId ?? '')}>Show summary</Button>
+ {summary.total !== null && <Text>{summary.total}</Text>}
+ </div>
+ );
+}
+```
## Optional discovery: `listBoundActions`
`dataApi.listBoundActions?.()` returns the operations THIS PAGE is bound to (`name`,
diff --git a/plugins/model-apps/references/data-caching.md b/plugins/model-apps/references/data-caching.md
index a26726f71..358d29c8e 100644
--- a/plugins/model-apps/references/data-caching.md
+++ b/plugins/model-apps/references/data-caching.md
@@ -37,7 +37,15 @@ the fix lives on `window`:
and return visits read the cache: no re-fetch, no spinner.
Always use a **single batched state object** (`{ records, loading, error }`) and
-one `setData(...)` call to avoid intermediate renders in React 17.
+one `setData(...)` call to avoid intermediate renders in React 17. `error` is the
+`PageErrorView | null` that the page's `reportPageError` returns (rules.md →
+*Missing Error Handling*), never a string, and a `PageErrorBar` renders it. A
+rejected read is reported and shown — it is never written to the cache, so the
+next mount or "Try again" reads again.
+
+Both patterns below are a complete `PageBody`: put it, with its module-level keys,
+into the page error block of rules.md (which supplies `PAGE_NAME`,
+`reportPageError`, `PageErrorBar`, the boundary and the default export).
## Pattern 1 — List / array cache
@@ -55,57 +63,76 @@ const winAny = window as any;
const CACHE_KEY = "__ppMyEntityCache";
const INFLIGHT_KEY = "__ppMyEntityInflight";
-// In component:
-const dataReady = !!dataApi; // the host may hand `dataApi` after first render
-const [{ records, loading, error }, setData] = useState<{
- records: MyRow[];
- loading: boolean;
- error: string | null;
-}>(() => {
- const cached = winAny[CACHE_KEY] as MyRow[] | undefined;
- return { records: cached ?? [], loading: cached === undefined, error: null };
-});
-
-useEffect(() => {
- if (!dataReady) return; // wait until the host hands us the DataAPI
-
- // Read the AUTHORITATIVE window cache (never a module-local snapshot): the
- // other mount may have resolved it between this mount's render and this
- // effect, and a module re-eval can leave a local copy stale. Sync state on a
- // hit (reference compare avoids a redundant render) so we never stick on the
- // spinner and we pick up an invalidated/replaced array.
- const cached = winAny[CACHE_KEY] as MyRow[] | undefined;
- if (cached !== undefined) {
- if (records !== cached) setData({ records: cached, loading: false, error: null });
- return;
- }
- let cancelled = false;
-
- // De-dupe the host double-mount: share ONE in-flight promise on `window` so a
- // racing second mount awaits it instead of firing a duplicate query.
- let inflight = winAny[INFLIGHT_KEY] as Promise<MyRow[]> | undefined;
- if (!inflight) {
- inflight = dataApi
- .queryTable("myentity", { select: ["name", "statuscode"] }) // VERIFIED columns
- .then((result: { rows: MyRow[] }) => {
- winAny[CACHE_KEY] = result.rows; // window = source of truth
- return result.rows;
- })
- // Clear only if still ours — a concurrent refresh may have replaced
- // this entry with a newer promise we must not delete.
- .finally(() => { if (winAny[INFLIGHT_KEY] === inflight) delete winAny[INFLIGHT_KEY]; });
- winAny[INFLIGHT_KEY] = inflight;
+function PageBody(props: GeneratedComponentProps) {
+ const { dataApi, pageInput } = props;
+ void pageInput;
+ const dataReady = !!dataApi; // the host may hand `dataApi` after first render
+ const [reloadKey, setReloadKey] = React.useState(0);
+ const [{ records, loading, error }, setData] = React.useState<{
+ records: MyRow[];
+ loading: boolean;
+ error: PageErrorView | null;
+ }>(() => {
+ const cached = winAny[CACHE_KEY] as MyRow[] | undefined;
+ return { records: cached ?? [], loading: cached === undefined, error: null };
+ });
+
+ // "Try again" after a failed load: drop the failed in-flight entry and run the effect again.
+ function retryLoad() {
+ delete winAny[CACHE_KEY];
+ delete winAny[INFLIGHT_KEY];
+ setReloadKey((key) => key + 1);
}
- inflight
- .then((rows) => { if (!cancelled) setData({ records: rows, loading: false, error: null }); })
- .catch(() => { if (!cancelled) setData({ records: [], loading: false, error: "Unable to load records." }); });
-
- return () => { cancelled = true; };
- // Depend on readiness only — NOT `dataApi` (a new ref each render would
- // re-fire this effect every render). `dataReady` flips false->true once.
- // eslint-disable-next-line react-hooks/exhaustive-deps
-}, [dataReady]);
+ React.useEffect(() => {
+ if (!dataReady) return; // wait until the host hands us the DataAPI
+
+ // Read the AUTHORITATIVE window cache (never a module-local snapshot): the
+ // other mount may have resolved it between this mount's render and this
+ // effect, and a module re-eval can leave a local copy stale. Sync state on a
+ // hit (reference compare avoids a redundant render) so we never stick on the
+ // spinner and we pick up an invalidated/replaced array.
+ const cached = winAny[CACHE_KEY] as MyRow[] | undefined;
+ if (cached !== undefined) {
+ if (records !== cached) setData({ records: cached, loading: false, error: null });
+ return;
+ }
+ let cancelled = false;
+
+ // De-dupe the host double-mount: share ONE in-flight promise on `window` so a
+ // racing second mount awaits it instead of firing a duplicate query.
+ let inflight = winAny[INFLIGHT_KEY] as Promise<MyRow[]> | undefined;
+ if (!inflight) {
+ inflight = dataApi
+ .queryTable("myentity", { select: ["myentityid", "name", "statuscode"] }) // VERIFIED columns
+ .then((result: { rows: MyRow[] }) => {
+ winAny[CACHE_KEY] = result.rows; // window = source of truth
+ return result.rows;
+ })
+ // Clear only if still ours — a concurrent refresh may have replaced
+ // this entry with a newer promise we must not delete.
+ .finally(() => { if (winAny[INFLIGHT_KEY] === inflight) delete winAny[INFLIGHT_KEY]; });
+ winAny[INFLIGHT_KEY] = inflight;
+ }
+
+ inflight
+ .then((rows) => { if (!cancelled) setData({ records: rows, loading: false, error: null }); })
+ // Reported once and shown; the cache is never written with a failure.
+ .catch((failure) => { if (!cancelled) setData({ records: [], loading: false, error: reportPageError(PAGE_NAME, "loadRecords", undefined, failure, "read", retryLoad) }); });
+
+ return () => { cancelled = true; };
+ // Depend on readiness only — NOT `dataApi` (a new ref each render would
+ // re-fire this effect every render). `dataReady` flips false->true once.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [dataReady, reloadKey]);
+
+ return (
+ <div>
+ <PageErrorBar error={error} />
+ {loading ? <Spinner label="Loading" /> : records.map((row) => <Text key={row.myentityid}>{row.name}</Text>)}
+ </div>
+ );
+}
```
## Pattern 2 — Detail / per-record Map cache
@@ -121,61 +148,79 @@ const _detailCache: Map<string, MyRow> =
const _detailInflight: Map<string, Promise<MyRow>> =
winAny.__ppMyEntityDetailInflight ?? (winAny.__ppMyEntityDetailInflight = new Map());
-// In component:
-const recordId = pageInput?.recordId;
-const dataReady = !!dataApi && !!recordId;
-const cachedRecord = recordId ? (_detailCache.get(recordId) ?? null) : null;
-
-const [{ record, loading, error }, setData] = useState(() => ({
- record: cachedRecord,
- loading: !!recordId && cachedRecord === null,
- error: null as string | null,
-}));
-
-useEffect(() => {
- if (!dataReady) return;
- const id = recordId as string;
-
- // Sync from the authoritative window Map on a hit — the other mount may have
- // resolved it between this mount's render and this effect, or `recordId` may
- // have changed in place. Reference compare avoids a redundant render.
- const hit = _detailCache.get(id);
- if (hit !== undefined) {
- if (record !== hit) setData({ record: hit, loading: false, error: null });
- return;
- }
- let cancelled = false;
-
- // Share one in-flight fetch per recordId across concurrent mounts.
- let pending = _detailInflight.get(id);
- if (!pending) {
- pending = dataApi
- .retrieveRow("myentity", { id, select: ["name", "statuscode"] }) // VERIFIED columns
- .then((row: MyRow) => { _detailCache.set(id, row); return row; })
- // Delete only if still ours (a concurrent refresh may have replaced it).
- .finally(() => { if (_detailInflight.get(id) === pending) _detailInflight.delete(id); });
- _detailInflight.set(id, pending);
- }
-
- pending
- .then((row) => { if (!cancelled) setData({ record: row, loading: false, error: null }); })
- .catch(() => { if (!cancelled) setData({ record: null, loading: false, error: "Unable to load record." }); });
-
- return () => { cancelled = true; };
- // Readiness + recordId only — never `dataApi`.
- // eslint-disable-next-line react-hooks/exhaustive-deps
-}, [dataReady, recordId]);
+function PageBody(props: GeneratedComponentProps) {
+ const { dataApi, pageInput } = props;
+ const recordId = pageInput?.recordId;
+ const dataReady = !!dataApi && !!recordId;
+ const cachedRecord = recordId ? (_detailCache.get(recordId) ?? null) : null;
+
+ const [{ record, loading, error }, setData] = React.useState<{
+ record: MyRow | null;
+ loading: boolean;
+ error: PageErrorView | null;
+ }>(() => ({
+ record: cachedRecord,
+ loading: !!recordId && cachedRecord === null,
+ error: null,
+ }));
+
+ React.useEffect(() => {
+ if (!dataReady) return;
+ const id = recordId as string;
+
+ // Sync from the authoritative window Map on a hit — the other mount may have
+ // resolved it between this mount's render and this effect, or `recordId` may
+ // have changed in place. Reference compare avoids a redundant render.
+ const hit = _detailCache.get(id);
+ if (hit !== undefined) {
+ if (record !== hit) setData({ record: hit, loading: false, error: null });
+ return;
+ }
+ let cancelled = false;
+
+ // Share one in-flight fetch per recordId across concurrent mounts.
+ let pending = _detailInflight.get(id);
+ if (!pending) {
+ pending = dataApi
+ .retrieveRow("myentity", { id, select: ["name", "statuscode"] }) // VERIFIED columns
+ .then((row: MyRow) => { _detailCache.set(id, row); return row; })
+ // Delete only if still ours (a concurrent refresh may have replaced it).
+ .finally(() => { if (_detailInflight.get(id) === pending) _detailInflight.delete(id); });
+ _detailInflight.set(id, pending);
+ }
+
+ pending
+ .then((row) => { if (!cancelled) setData({ record: row, loading: false, error: null }); })
+ .catch((failure) => { if (!cancelled) setData({ record: null, loading: false, error: reportPageError(PAGE_NAME, "loadRecord", undefined, failure, "read") }); });
+
+ return () => { cancelled = true; };
+ // Readiness + recordId only — never `dataApi`.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [dataReady, recordId]);
+
+ return (
+ <div>
+ <PageErrorBar error={error} />
+ {loading ? <Spinner label="Loading" /> : record && <Text>{record.name}</Text>}
+ </div>
+ );
+}
```
-
## Cache invalidation and manual refresh
After a mutation (create/update/delete), or when a manual refresh control fires,
evict the relevant cache(s) **and any in-flight promise** before refetching, then
bump a `reloadKey` state so the effect re-runs. Clear the in-flight entry too —
-otherwise the effect reuses the stale pending promise instead of fetching fresh:
+otherwise the effect reuses the stale pending promise instead of fetching fresh.
+A write that fails is reported as `'write'` (no retry) and evicts nothing:
```typescript
-await dataApi.updateRow("myentity", recordId, changes);
+try {
+ await dataApi.updateRow("myentity", recordId, changes);
+} catch (error) {
+ setSave({ saving: false, error: reportPageError(PAGE_NAME, "saveRecord", undefined, error, "write") });
+ return;
+}
const w = window as any;
// Detail: evict just the one row + its in-flight entry.
@@ -190,6 +235,18 @@ delete w.__ppMyEntityInflight;
setReloadKey((k) => k + 1); // add `reloadKey` to the effect's dep array
```
+// Detail: evict just the one row + its in-flight entry.
+_detailCache.delete(recordId);
+_detailInflight.delete(recordId);
+
+// List: evict the whole array + its in-flight promise so the next mount refetches.
+delete w.__ppMyEntityCache;
+delete w.__ppMyEntityInflight;
+
+// Then trigger a re-run (readiness dep won't change, so use an explicit key):
+setReloadKey((k) => k + 1); // add `reloadKey` to the effect's dep array
+```
+
When a page has a manual refresh button or a `reloadKey`, add it to the effect's
dependency array alongside `dataReady` (e.g. `[dataReady, reloadKey]`).
@@ -230,6 +287,9 @@ if (!inflight) {
The reason this is identical to Dataverse caching is the host behavior, not the
backend: the double-mount re-runs any on-mount effect, and a connector call is a
real network read with the same duplicate-request and spinner-flash failure mode.
+The consumer is Pattern 1's too: `inflight.then(…).catch(…)` on the same binding,
+whose `catch` reports `reportPageError(PAGE_NAME, "loadDocuments", undefined, failure, "read", retryLoad)`
+into the panel's state and never writes the cache.
## Scope — de-dupe always, cache when it helps
diff --git a/plugins/model-apps/references/dataverse-operations.md b/plugins/model-apps/references/dataverse-operations.md
new file mode 100644
index 000000000..79eb108d8
--- /dev/null
+++ b/plugins/model-apps/references/dataverse-operations.md
@@ -0,0 +1,432 @@
+# Built-in Dataverse operations (WhoAmI, RetrieveVersion)
+
+A generative page can call exactly two **built-in** Dataverse operations — `WhoAmI` and
+`RetrieveVersion` — as explicitly selected, user-triggered Functions. They reuse the page's
+`actionBindings` and `dataApi.executeFunction`, but they are **not Custom APIs**: they are
+messages the platform defines, not rows of the `customapi` table, so Custom API discovery
+(`list-custom-apis.js`) never finds them and a Custom API wrapper is never their remedy.
+
+> **Behind a default-off flag.** `dataverse-operations` ships **OFF**. Set
+> `GENPAGE_ENABLE_DATAVERSE_OPERATIONS=1` for a run (or `"dataverse-operations": true` in
+> `plugins/model-apps/feature-flags.json`). The flag gates **offering and authoring new**
+> bindings only: it never strips, repairs or revokes a binding a page already has, and it is not
+> the platform's runtime switch. The `genpage-customapi-builder` agent owns the gate.
+
+## The catalogue
+
+The offer is a fixed, reviewed catalogue (`scripts/lib/dataverse-operations.js`, revision 1),
+not a check of the environment. Growing it is a reviewed code change, never a setting.
+
+| Name | Kind | Parameters | Response | Display name |
+|------|------|------------|----------|--------------|
+| `WhoAmI` | Function, unbound (Global) | none | `WhoAmIResponse`: `BusinessUnitId`, `UserId`, `OrganizationId` (each `Edm.Guid`) | Current Dataverse identity |
+| `RetrieveVersion` | Function, unbound (Global) | none | `RetrieveVersionResponse`: `Version` (`Edm.String`) | Dataverse server version |
+
+They retrieve the signed-in user's identity and the server's version
+(<https://learn.microsoft.com/power-apps/developer/data-platform/webapi/reference/whoami>,
+<https://learn.microsoft.com/power-apps/developer/data-platform/webapi/reference/retrieveversion>).
+Nothing here claims they have no audit side effect.
+
+**Why nothing else is offered.** "Function" or "GET" does not make an operation harmless:
+`CalculateRollupField` and `IncrementKnowledgeArticleViewCount` are Functions that change data.
+Record-bound Functions add overloads, record identity and authorization outputs; `QualifyLead`,
+Actions and classic process actions mutate business data and need confirmation and ownership
+rules; set-bound operations have no invocation shape in the page runtime. Each is separate work,
+so this catalogue refuses them all (`not_in_catalogue`) and never probes them.
+
+## The flag and Custom API discovery
+
+Custom API support has no flag: Custom API discovery, authoring and upload are always available.
+The `dataverse-operations` flag decides the built-in offer only, and never Custom API discovery:
+
+| `dataverse-operations` | What is offered |
+|---|---|
+| off (shipped default) | Custom APIs only |
+| on | both, as two labelled sources; only affirmative selections are written |
+
+## Listing: `list-dataverse-operations.js`
+
+```powershell
+node "${PLUGIN_ROOT}/scripts/list-dataverse-operations.js"
+```
+
+No arguments and no options: it takes no environment, reads no token and sends no request.
+
+| Exit | When | stdout | stderr |
+|---|---|---|---|
+| 3 | flag OFF (even with a bad argument) | empty | `Dataverse built-in operation authoring is disabled (feature flag "dataverse-operations" is OFF). Set GENPAGE_ENABLE_DATAVERSE_OPERATIONS=1 to offer WhoAmI and RetrieveVersion. Existing bindings are preserved; runtime governance and user privileges still apply.` |
+| 1 | any argument | empty | `Usage: node scripts/list-dataverse-operations.js` |
+| 1 | the catalogue cannot be read, or is not exactly the reviewed pair | empty | `The built-in operation catalogue could not be read. No built-in operations were offered.` |
+| 0 | otherwise | one JSON line | — |
+
+The success body is `{ "ok": true, "catalogueVersion": 1, "verification": { "mode":
+"catalogue-only", "environment": "not-checked", "runtime": "not-checked", "privileges":
+"not-checked" }, "operations": [ … ] }`, each operation `{ name, displayName, isFunction: true,
+bindingType: "Global", parameters: [], parameterKinds: {}, response: { typeName, properties },
+outputPrivacy, invocation: "user-triggered", requiresExplicitSelection: true }`. Listing is an
+offer, not a check: whether the environment or its page player has the operation, and whether
+the signed-in user may call it, is **not checked** — a page's first call can answer 404. Run it
+only when this run needs an explanation or an add/replace offer — never for an upload, a code
+generation, a download, a rebuild or an unrelated edit.
+
+## Selection is consent; a mention is not
+
+- An **affirmative** "add a button that calls WhoAmI", or an explicit answer to a picker that
+ offered the operation, selects it. Do not ask again.
+- A mention, a question, a quotation, a negation ("do **not** add WhoAmI") or a removal is
+ **not** an addition. "Explain WhoAmI" writes no binding.
+- A generic need ("show who I am", "show the server version") with no affirmative name returns
+ `needs_input` with the offer below. Silence is never selection, and an unattended run never
+ treats "no answer" as consent: a request or spec counts only when the interaction contract
+ recorded that explicit intent.
+- The selected names and where they came from stay in this run's orchestration context — never
+ on the wire, never in a consent file.
+
+When the two are offered, say:
+
+> These are two reviewed built-in Dataverse Functions, not Custom APIs discovered in this
+> environment. Their availability, player support and your permissions have not been checked.
+> Select either explicitly to add a user-triggered call. WhoAmI returns your Dataverse user,
+> business-unit and organization identifiers.
+
+When the maker affirmatively asked for WhoAmI or RetrieveVersion and the flag is OFF, relay the
+script's gate line, write no new built-in row, and add: `This does not mean the environment lacks
+these operations, and the remedy is not a Custom API wrapper. No new built-in binding was
+added.` Say that only for these two names, and never echo an unknown name back.
+
+| Case | Code | Message |
+|---|---|---|
+| Any other name: wrong case, namespace, prefix, private or unadvertised message | `not_in_catalogue` | `Only WhoAmI and RetrieveVersion are offered by this feature. Other Dataverse operations require separately reviewed support.` |
+| An effectful Function, a record-bound Function, `QualifyLead`, an Action, a classic process action, a set-bound operation | `not_in_catalogue` | the same message (see "Why nothing else is offered") |
+| A new row with a false, absent or non-boolean kind, a bound target or inputs | `invalid_operation_contract` | `The selected built-in operation must be an explicitly declared, unbound Function with no inputs.` |
+| A name twice, or contradictory rows, in the desired array | `duplicate_operation` | `Select each built-in operation once; duplicate bindings are not supported.` |
+| A row about to be written with no affirmative selection | `selection_required` | `Select a built-in operation explicitly before generating its binding or call.` |
+| A call on mount, a poll, a filter or a background call | `explicit_trigger_required` | `This version supports user-triggered built-in operation calls only.` No binding and no substitute call is added until the maker accepts a button; the refusal is not completion. |
+| The catalogue cannot be read | `catalogue_unavailable` | the listing's exit-1 line |
+
+These are authoring codes, not player `error.code` values, and they never restrict the Custom
+API path. If this run's Custom API discovery returned a Custom API with the **same exact unique
+name**, the built-in choice is ambiguous: bind neither silently; the maker may select that
+Custom API row explicitly. When that discovery did not run, do not claim the name is free.
+
+The platform still decides every call, and nothing here reads or changes its governance: a
+player without `executeFunction` (unsupported-player guidance, no second transport); the
+`DisableGenUxPluginActionsRuntime` switch; the page's bound manifest; the
+`GenUxPluginActionAllowList` (empty or unset allows every **bound** name — it is not
+discovery); the kind and target in the manifest; the signed-in user's own Dataverse privileges
+(no grant, no impersonation, no privilege probe). A guard that refuses before the transport
+sends no request.
+
+## The binding and `actions.json`
+
+A built-in row is the four-key projection of its descriptor — never the descriptor itself
+(`bindingType`, `parameters`, `response` and the rest would leave the page's whole list out of
+an App Spec):
+
+```json
+{ "name": "WhoAmI", "isFunction": true, "displayName": "Current Dataverse identity", "parameterKinds": {} }
+```
+
+`RetrieveVersion` differs only in `name` and `displayName` (`Dataverse server version`).
+`actions.json` stays one bare array with one writer (`genpage-customapi-builder`): the Custom API
+rows first, in their existing order, then the new built-in rows in catalogue order. Every new
+row must be exactly that projection; one refusal, or a duplicate name, stops the whole write and
+leaves the page untouched. `--actions` is a **full replace** — pass it only when the desired set
+changed, and never as a partial file.
+
+| Edit intent | Gate | `--actions` | Page source |
+|---|---|---|---|
+| preserve (an unrelated edit) | not consulted | omitted | keep existing call text as it is |
+| add / replace | must be ON | the full desired array | the button pattern below, for the new names only |
+| remove | not consulted | the array minus the named entries | delete those calls only |
+| clear all | after the maker's clear choice, asked before any binding is reconciled or the plan is approved, which names the built-ins it removes | `[]` | delete every call |
+| none, on create | n/a | omitted unless Custom APIs changed | no built-in call |
+| none, on an edit whose page already binds one | n/a | not passed | halt: no preserve evidence is no permission to delete the call |
+
+Removing every Custom API is a remove of each Custom API row: the built-in rows stay, byte for
+byte, and the file is never `[]` while one remains — a removal is never turned into a clear. Only
+the maker's clear choice empties the array: asked
+with two options before any binding is reconciled and before the plan is approved — so before the
+source is edited — and recorded then and again right before each upload it covers as `Clear
+choice: Clear every action binding of page <page-id>, removing <names>`. On `Keep <names>` the
+built-in calls and their bindings stay, and a yes to adding or keeping an operation never empties it.
+
+A gate flipped OFF between planning and generation of an add/replace halts: no `actions.json`
+is written, no `--actions` is passed, and `[]` is never written in its place (`[]` is only an
+explicit clear-all). A preserved entry is never upgraded: an omitted `isFunction`, another
+display label or an omitted `parameterKinds` stays as the page holds it.
+
+## The plan section
+
+`## Dataverse Operations` is **optional**. When present it sits after `## Custom API Bindings`
+and before `## Solution Packaging`, and it is either the exact sentinel `No Dataverse
+operations.` or this table — anything else halts. Absent means no new authoring.
+
+```markdown
+## Dataverse Operations
+Verification: environment not-checked, runtime not-checked, privileges not-checked.
+| Name | Kind | Bound Entity | Display Name | Parameters | Response fields | Invoke |
+|------|------|--------------|--------------|------------|-----------------|--------|
+| WhoAmI | Function | (Global) | Current Dataverse identity | (none) | BusinessUnitId, UserId, OrganizationId | button |
+| RetrieveVersion | Function | (Global) | Dataverse server version | (none) | Version | button |
+```
+
+Rows are in catalogue order and every cell is the catalogue's own; `Invoke` is always `button`.
+The builder writes `dataverse-operations.md` only for an add/replace of the current run (a file
+left by an earlier run is no evidence); the planner copies it verbatim and never re-derives it.
+When a run asked for one and the builder adds none — its gate is off, or the maker declined the
+offer or selected neither — it reports `dataverse-operations.md: none — not added this run`. The
+orchestrator forwards that outcome, never a contract, to the create or edit planner, which
+completes its plan without the call and does not ask for the offer again.
+
+## Generated call
+
+Only for a current-run add/replace, and only from a button. Never in a `useEffect`, at render,
+in a filter, on a timer or on mount — and never hand its handler or helper to one
+(`setTimeout(showIdentity, 0)`), to a `ref` or to a child component: only the button's
+`onClick` names it.
+
+The block below is the page's `PageBody` with its two request helpers. It is built on the page
+error block of rules.md → *Missing Error Handling*, copied unchanged — `PAGE_NAME`,
+`reportPageError`, `PageErrorBar`, the boundary and the error copy, whose `error.builtin*` keys
+hold the fixed sentences this page shows.
+
+```tsx
+type BuiltInResult = { ok: boolean; outputs?: Record<string, unknown>; error?: { message?: string; code?: string; status?: number } };
+type BuiltInApi = { executeFunction?: (request: { name: string }) => Promise<BuiltInResult> };
+type IdentityView = { identity?: { userId: string; businessUnitId: string; organizationId: string }; error?: PageErrorView };
+type VersionView = { version?: string; error?: PageErrorView };
+
+const GUID = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
+
+// An output only when it is the object's OWN string property.
+function ownString(outputs: Record<string, unknown>, field: string): string | undefined {
+ const value = Object.prototype.hasOwnProperty.call(outputs, field) ? outputs[field] : undefined;
+ return typeof value === 'string' ? value : undefined;
+}
+
+async function readIdentity(api: BuiltInApi): Promise<IdentityView> {
+ if (typeof api.executeFunction !== 'function') {
+ const view = reportPageError(PAGE_NAME, 'showIdentity', undefined, 'executeFunction is not available in this player', 'read');
+ view.fallbackKey = 'error.builtinUnsupported';
+ view.message = '';
+ return { error: view };
+ }
+ try {
+ const res = await api.executeFunction({ name: 'WhoAmI' });
+ if (res.ok !== true) {
+ const view = reportPageError(PAGE_NAME, 'showIdentity', res.error?.code, res.error?.message, 'read');
+ const unavailable = typeof res.error?.status === 'number' && res.error.status === 404;
+ view.fallbackKey = unavailable ? 'error.builtinUnavailable' : 'error.builtinFailed';
+ view.message = unavailable ? '' : view.message;
+ return { error: view };
+ }
+ const outputs = res.outputs;
+ if (!outputs || typeof outputs !== 'object' || Array.isArray(outputs)) {
+ const view = reportPageError(PAGE_NAME, 'showIdentity', undefined, 'WhoAmI returned no output object', 'read');
+ view.fallbackKey = 'error.builtinUnexpected';
+ view.message = '';
+ return { error: view };
+ }
+ const userId = ownString(outputs, 'UserId');
+ const businessUnitId = ownString(outputs, 'BusinessUnitId');
+ const organizationId = ownString(outputs, 'OrganizationId');
+ if (![userId, businessUnitId, organizationId].every((id) => typeof id === 'string' && GUID.test(id))) {
+ const view = reportPageError(PAGE_NAME, 'showIdentity', undefined, 'WhoAmI returned an unexpected identity', 'read');
+ view.fallbackKey = 'error.builtinUnexpected';
+ view.message = '';
+ return { error: view };
+ }
+ return { identity: { userId: userId as string, businessUnitId: businessUnitId as string, organizationId: organizationId as string } };
+ } catch (error) {
+ const view = reportPageError(PAGE_NAME, 'showIdentity', undefined, error, 'read');
+ view.fallbackKey = 'error.builtinFailed';
+ view.message = '';
+ return { error: view };
+ }
+}
+
+async function readVersion(api: BuiltInApi): Promise<VersionView> {
+ if (typeof api.executeFunction !== 'function') {
+ const view = reportPageError(PAGE_NAME, 'showVersion', undefined, 'executeFunction is not available in this player', 'read');
+ view.fallbackKey = 'error.builtinUnsupported';
+ view.message = '';
+ return { error: view };
+ }
+ try {
+ const res = await api.executeFunction({ name: 'RetrieveVersion' });
+ if (res.ok !== true) {
+ const view = reportPageError(PAGE_NAME, 'showVersion', res.error?.code, res.error?.message, 'read');
+ const unavailable = typeof res.error?.status === 'number' && res.error.status === 404;
+ view.fallbackKey = unavailable ? 'error.builtinUnavailable' : 'error.builtinFailed';
+ view.message = unavailable ? '' : view.message;
+ return { error: view };
+ }
+ const outputs = res.outputs;
+ if (!outputs || typeof outputs !== 'object' || Array.isArray(outputs)) {
+ const view = reportPageError(PAGE_NAME, 'showVersion', undefined, 'RetrieveVersion returned no output object', 'read');
+ view.fallbackKey = 'error.builtinUnexpected';
+ view.message = '';
+ return { error: view };
+ }
+ const version = ownString(outputs, 'Version');
+ if (!version || version.length > 128) {
+ const view = reportPageError(PAGE_NAME, 'showVersion', undefined, 'RetrieveVersion returned an unexpected version', 'read');
+ view.fallbackKey = 'error.builtinUnexpected';
+ view.message = '';
+ return { error: view };
+ }
+ return { version };
+ } catch (error) {
+ const view = reportPageError(PAGE_NAME, 'showVersion', undefined, error, 'read');
+ view.fallbackKey = 'error.builtinFailed';
+ view.message = '';
+ return { error: view };
+ }
+}
+
+function PageBody(props: GeneratedComponentProps) {
+ const { dataApi, pageInput } = props;
+ void pageInput;
+ const api = dataApi as unknown as BuiltInApi;
+ const mounted = React.useRef(true);
+ React.useEffect(() => () => { mounted.current = false; }, []);
+
+ const [identityState, setIdentityState] = React.useState<{ pending: boolean; view: IdentityView }>({ pending: false, view: {} });
+ const identityRequest = React.useRef(0);
+ const showIdentity = async () => {
+ if (identityState.pending) return;
+ const requestId = ++identityRequest.current;
+ setIdentityState({ pending: true, view: {} });
+ try {
+ const view = await readIdentity(api);
+ if (mounted.current && requestId === identityRequest.current) setIdentityState({ pending: false, view });
+ } catch (error) {
+ if (mounted.current && requestId === identityRequest.current) setIdentityState({ pending: false, view: { error: reportPageError(PAGE_NAME, 'showIdentity', undefined, error, 'read') } });
+ }
+ };
+
+ const [versionState, setVersionState] = React.useState<{ pending: boolean; view: VersionView }>({ pending: false, view: {} });
+ const versionRequest = React.useRef(0);
+ const showVersion = async () => {
+ if (versionState.pending) return;
+ const requestId = ++versionRequest.current;
+ setVersionState({ pending: true, view: {} });
+ try {
+ const view = await readVersion(api);
+ if (mounted.current && requestId === versionRequest.current) setVersionState({ pending: false, view });
+ } catch (error) {
+ if (mounted.current && requestId === versionRequest.current) setVersionState({ pending: false, view: { error: reportPageError(PAGE_NAME, 'showVersion', undefined, error, 'read') } });
+ }
+ };
+
+ return (
+ <div>
+ <Button disabled={identityState.pending} onClick={() => void showIdentity()}>Show my Dataverse identity</Button>
+ <PageErrorBar error={identityState.view.error ?? null} />
+ {identityState.view.identity && (
+ <div>
+ <Text>Dataverse user id: {identityState.view.identity.userId}</Text>
+ <Text>Business unit id: {identityState.view.identity.businessUnitId}</Text>
+ <Text>Organization id: {identityState.view.identity.organizationId}</Text>
+ <Text>The organization id is not an Entra tenant id.</Text>
+ </div>
+ )}
+ <Button disabled={versionState.pending} onClick={() => void showVersion()}>Show the Dataverse server version</Button>
+ <PageErrorBar error={versionState.view.error ?? null} />
+ {versionState.view.version && <Text>Server version: {versionState.view.version}</Text>}
+ </div>
+ );
+}
+
+const GeneratedComponent = (props: GeneratedComponentProps) => (
+ <PageErrorBoundary>
+ <PageBody {...props} />
+ </PageErrorBoundary>
+);
+export default GeneratedComponent;
+```
+
+What the pattern holds, in this order:
+
+1. The request is exactly `{ name: 'WhoAmI' }` or `{ name: 'RetrieveVersion' }`: no
+ `parameters`, no `boundTo`, the unqualified name, on the page's own `dataApi` after a
+ presence check that **returns** — a player without `executeFunction` sends nothing and gets
+ no second transport, raw URL or token; it shows `This page player cannot call built-in
+ Dataverse operations.`
+2. A result whose `ok` is not `true` is reported — `reportPageError(PAGE_NAME, '<operation>',
+ res.error?.code, res.error?.message, 'read')`, a read with **no retry** — and the helper returns
+ that view as `{ error }` **before** `res.outputs` is read; a failed result that happens to carry
+ output-shaped data shows none of it, and the result itself is never handed to the reporter. The
+ bar shows the sanitized `error.message`, or the fixed `The operation failed. No result was
+ displayed.` An **actual** HTTP 404 on the result (a numeric `status` of 404) shows `The selected
+ operation is unavailable in this environment or player. No fallback was attempted.` and keeps the
+ binding; a status is never read out of the message's words, and no message suggests deploying a
+ Custom API. The current model-driven player passes no HTTP status to the page: a 404, a 403, a 429
+ and a network failure all arrive as its own sanitized message, so in practice the page shows that
+ message and cannot tell an unavailable operation from a refused one.
+3. Only then `res.outputs` — a non-null object that is not an array (an empty or 204 answer is
+ `{}`) — and only through own-property reads. Never the result root, `res.value`, `res.body`
+ or fault details; never a spread, an iteration or `JSON.stringify` of it; any other property
+ is ignored.
+4. All or nothing: WhoAmI shows its three identifiers only when every one is an own string
+ matching the GUID pattern (no UUID-version check); RetrieveVersion shows `Version` only when
+ it is an own string of 1 to 128 characters. Anything else is reported with a fixed diagnostic —
+ never the outputs — and shows `The operation returned an unexpected response. No result was
+ displayed.`
+5. A rejected promise is caught — in the helper, and again in the handler — and reported as a read
+ with no retry; it shows bounded guidance, never a stack. A timeout or a
+ `network` code is **not** proof the request never left the client or was cancelled, and the
+ host does not cancel a timed-out GET: the pending button is disabled, which is not a claim
+ that the request stopped. The page never retries — a retry is the user's next click. The
+ current player's own transport can re-send a request once after a connection reset, so a
+ click that failed may still have reached the service (both operations only read).
+6. Each operation has its own pending state, request counter and error view: a new click clears
+ that operation's previous result and error, a stale or unmounted answer is ignored, and the other
+ operation's button, result and error stay as they are.
+Labels are "Dataverse user id", "Business unit id" and "Organization id", with the line "The
+organization id is not an Entra tenant id." A version is an opaque string, not a feature test.
+
+## Privacy
+
+WhoAmI answers the signed-in user's identifiers. Show them only as escaped text in the current
+page, as the feature the maker asked for. Never log, store (`localStorage`, `sessionStorage`),
+copy, put in a URL, send to telemetry or hash them; never join them to business records or use
+them as a client-side authorization; never retrieve the `systemuser`, `businessunit` or
+`organization` row behind them; never copy the identity an auth preflight printed into page
+source. Binding WhoAmI is not permission to call it for analytics. Results stay in component
+memory, and the same holds for everything that keeps them — the state the page renders from, a
+ref, a variable derived from either — wherever the page uses it: at render, in an effect or in
+another handler.
+
+A failure is the one thing of a built-in call that is logged: `reportPageError` logs the host's
+bounded error code and sanitized message, never the result or an identifier. Only when the maker
+asked to report failures and the dispatch says `Telemetry: enabled` may the page pass its
+`props.appInsights` to that reporter as the seventh argument of these read reports
+(`references/page-telemetry.md`); the reporter then sends a fixed `<operation> failed` error and a
+recognized code — nothing of the result.
+
+## Download and rebuild
+
+The flag does not gate either, and neither refuses for it. An **exact** catalogue name is a
+built-in (wrong case is a Custom API name):
+
+- **download** names it under `pageBindings.neededInTarget.dataverseOperations`, never under
+ `customApis`, and says there is nothing to deploy: the binding is carried as the page holds it
+ (not repaired) and its availability and contract are not certified. A parameter map does not
+ turn the name into a Custom API. A list holding an unsafe field is still left out whole.
+- **rebuild** leaves it out of the `customapi` read, before the names are folded in case (a page
+ that binds only built-ins reads no `customapi` row). It says each such binding was **not
+ checked** — `These are reviewed built-in operation names; their availability in this
+ environment or player and the signed-in user's permissions were not checked.` — and never
+ "missing". A binding of that name that does not explicitly declare an unbound Function with no
+ inputs gets a `dataverse-operation-shape` warning (an omitted legacy declaration is told apart
+ from a contradiction) and is written as the spec states it.
+
+## Compatibility
+
+The wire shape is unchanged, so no migration and no `minimumPluginVersion` bump. Model-apps
+2.17, 2.18 and 2.19 do not offer these operations. In 2.18 and 2.19, download and rebuild still
+describe them as Custom APIs; they do not strip a valid binding. 2.17's download and rebuild carry
+no page bindings. A hand-written page or a hand-written `actions.json` is outside this catalogue:
+`genpage-upload.js --actions` writes the array it is given and resolves no name.
diff --git a/plugins/model-apps/references/localization.md b/plugins/model-apps/references/localization.md
index b6b5485a6..d59c33d17 100644
--- a/plugins/model-apps/references/localization.md
+++ b/plugins/model-apps/references/localization.md
@@ -23,25 +23,40 @@ Only apply localization when `scripts/list-languages.js` (run by the planner dur
### Language Detection
-Detect the user's UI language at component mount using the Xrm global context:
+Detect the user's UI language from the Xrm global context, in a **top-level** function: the page's
+error bar and render boundary (`references/rules.md`, "Missing Error Handling") are top-level
+components that translate their copy too, and a value kept in a component's closure is out of their
+reach.
```typescript
-const language = React.useMemo(() => {
- const uiLanguageId = (typeof Xrm !== "undefined" &&
- Xrm.Utility?.getGlobalContext()?.userSettings?.languageId) || 1033;
- const langMap: Record<number, { code: string; name: string; isRtl: boolean }> = {
- // One entry per language in the plan's `## Environment` → `Languages` line, e.g.
- // English (1033, en-US); Arabic (Saudi Arabia) (1025, ar-SA) — RTL
- // becomes 1033: { code: "en-US", name: "English", isRtl: false } and
- // 1025: { code: "ar-SA", name: "Arabic (Saudi Arabia)", isRtl: true }.
- // `isRtl` is true exactly where the line carries `— RTL` (see RTL Layout Support) — never from memory.
- // A language the plan lists with no code has nothing to key a translation by: it gets no entry, and the
- // fallback below serves that user in English.
- };
- return langMap[uiLanguageId] || { code: "en-US", name: "English", isRtl: false };
-}, []);
+type PageLanguage = { code: string; name: string; isRtl: boolean };
+// One entry per language in the plan's `## Environment` → `Languages` line, e.g.
+// English (1033, en-US); Arabic (Saudi Arabia) (1025, ar-SA) — RTL
+// becomes the two entries below. `isRtl` is true exactly where the line carries `— RTL` (see RTL
+// Layout Support) — never from memory. A language the plan lists with no code has nothing to key a
+// translation by: it gets no entry, and the fallback below serves that user in English.
+const PAGE_LANGUAGES: Record<number, PageLanguage> = {
+ 1033: { code: "en-US", name: "English", isRtl: false },
+ 1025: { code: "ar-SA", name: "Arabic (Saudi Arabia)", isRtl: true },
+};
+const DEFAULT_LANGUAGE: PageLanguage = { code: "en-US", name: "English", isRtl: false };
+
+// Hook-free, so it is safe anywhere — even in the render boundary's fallback. A host without Xrm,
+// or one that throws, gets English instead of a second crash.
+function resolvePageLanguage(): PageLanguage {
+ try {
+ const uiLanguageId = (typeof Xrm !== "undefined" &&
+ Xrm.Utility?.getGlobalContext()?.userSettings?.languageId) || 1033;
+ return PAGE_LANGUAGES[uiLanguageId] || DEFAULT_LANGUAGE;
+ } catch {
+ return DEFAULT_LANGUAGE;
+ }
+}
```
+In the page component, read it once for the layout direction:
+`const language = React.useMemo(() => resolvePageLanguage(), []);`
+
### Translation Dictionary
Create a translations dictionary with entries for every language detected in Step 2. All user-visible text must come from this dictionary — **NEVER hardcode display text in JSX**.
@@ -54,18 +69,30 @@ const translations: Record<string, Record<string, string>> = {
title: "Dashboard",
save: "Save",
cancel: "Cancel",
+ // The page error keys (references/rules.md, "Missing Error Handling") belong here too, in
+ // every language; a localized page has no separate English ERROR_COPY.
+ "error.read": "Unable to load data. Please try again.",
+ "error.write": "The change could not be saved. Refresh before trying again.",
+ "error.network": "The request did not go through. You can try again.",
+ "error.indeterminate": "We couldn't confirm this completed — refresh before retrying.",
+ "error.render": "This page hit a problem and could not render. Refresh the page.",
+ "error.tryAgain": "Try again",
// ... all user-visible strings
},
"ar-SA": {
title: "لوحة القيادة",
save: "حفظ",
cancel: "إلغاء",
+ // ... every key above, translated
},
// ... one entry per detected language
};
-const translate = (key: string): string =>
- translations[language.code]?.[key] || translations["en-US"]?.[key] || key;
+// Top level, so PageErrorBar and PageErrorBoundary use it as well as the page component.
+function translate(key: string): string {
+ const language = resolvePageLanguage();
+ return translations[language.code]?.[key] || translations["en-US"]?.[key] || key;
+}
```
Usage: `<Text>{translate("title")}</Text>` — never `<Text>Dashboard</Text>`.
@@ -111,6 +138,12 @@ const isRtlLocale = (code: string): boolean => {
Retrieve these columns: `uilanguageid`, `localeid`, `decimalsymbol`, `numberseparator`, `currencysymbol`, `dateformatstring`, `dateseparator`.
+A failed read is reported through the page's `reportPageError` (rules.md → *Missing Error
+Handling*) as a `'read'` and shown in the page's `PageErrorBar` — never logged as the thrown value.
+The page still renders: the formatting helpers below fall back to the browser's locale. The block
+below is a complete `PageBody` on the page error block; the language resolver, the dictionary and
+`translate` above stay top level.
+
```typescript
// Cache user settings on `window` + de-dupe the host double-mount so we retrieve
// them once (see references/data-caching.md). Keyed globally — settings are
@@ -119,42 +152,57 @@ const winAny = window as unknown as Record<string, unknown>;
const SETTINGS_KEY = "__ppUserSettings";
const SETTINGS_INFLIGHT = "__ppUserSettingsInflight";
-const [userSettings, setUserSettings] = React.useState<any>(
- () => (winAny[SETTINGS_KEY] as any) ?? null,
-);
-const dataReady = !!dataApi; // never depend on `dataApi` itself — see Rule 15
-
-React.useEffect(() => {
- if (!dataReady) return;
- if (winAny[SETTINGS_KEY] !== undefined) { setUserSettings(winAny[SETTINGS_KEY]); return; }
- const currentUserId = (typeof Xrm !== "undefined" &&
- Xrm.Utility?.getGlobalContext()?.userSettings?.userId)
- ?.replace("{", "").replace("}", "");
- if (!currentUserId) return;
- let cancelled = false;
-
- // Share one in-flight fetch across the two host mounts.
- let pending = winAny[SETTINGS_INFLIGHT] as Promise<any> | undefined;
- if (!pending) {
- pending = dataApi.retrieveRow("usersettings" as any, {
- id: currentUserId,
- select: ["uilanguageid", "localeid", "decimalsymbol", "numberseparator",
- "currencysymbol", "dateformatstring", "dateseparator"] as any,
- })
- .then((settings: any) => { winAny[SETTINGS_KEY] = settings; return settings; })
- .finally(() => { if (winAny[SETTINGS_INFLIGHT] === pending) delete winAny[SETTINGS_INFLIGHT]; });
- winAny[SETTINGS_INFLIGHT] = pending;
- }
- pending
- .then((settings: any) => { if (!cancelled) setUserSettings(settings); })
- .catch((error: any) => { if (!cancelled) console.error("Failed to fetch user settings", error); });
-
- return () => { cancelled = true; };
- // eslint-disable-next-line react-hooks/exhaustive-deps
-}, [dataReady]);
+function PageBody(props: GeneratedComponentProps) {
+ const { dataApi, pageInput } = props;
+ void pageInput;
+ const language = React.useMemo(() => resolvePageLanguage(), []);
+ const [{ userSettings, settingsError }, setSettings] = React.useState<{ userSettings: any; settingsError: PageErrorView | null }>(
+ () => ({ userSettings: (winAny[SETTINGS_KEY] as any) ?? null, settingsError: null }),
+ );
+ const dataReady = !!dataApi; // never depend on `dataApi` itself — see Rule 15
+
+ React.useEffect(() => {
+ if (!dataReady) return;
+ if (winAny[SETTINGS_KEY] !== undefined) {
+ if (userSettings !== winAny[SETTINGS_KEY]) setSettings({ userSettings: winAny[SETTINGS_KEY], settingsError: null });
+ return;
+ }
+ const currentUserId = (typeof Xrm !== "undefined" &&
+ Xrm.Utility?.getGlobalContext()?.userSettings?.userId)
+ ?.replace("{", "").replace("}", "");
+ if (!currentUserId) return;
+ let cancelled = false;
+
+ // Share one in-flight fetch across the two host mounts.
+ let pending = winAny[SETTINGS_INFLIGHT] as Promise<any> | undefined;
+ if (!pending) {
+ pending = dataApi.retrieveRow("usersettings" as any, {
+ id: currentUserId,
+ select: ["uilanguageid", "localeid", "decimalsymbol", "numberseparator",
+ "currencysymbol", "dateformatstring", "dateseparator"] as any,
+ })
+ .then((settings: any) => { winAny[SETTINGS_KEY] = settings; return settings; })
+ .finally(() => { if (winAny[SETTINGS_INFLIGHT] === pending) delete winAny[SETTINGS_INFLIGHT]; });
+ winAny[SETTINGS_INFLIGHT] = pending;
+ }
+ pending
+ .then((settings: any) => { if (!cancelled) setSettings({ userSettings: settings, settingsError: null }); })
+ // Reported once, never the thrown value; a failure is never cached as settings.
+ .catch((error: unknown) => { if (!cancelled) setSettings({ userSettings: null, settingsError: reportPageError(PAGE_NAME, "loadUserSettings", undefined, error, "read") }); });
+
+ return () => { cancelled = true; };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [dataReady]);
+
+ return (
+ <div dir={language.isRtl ? "rtl" : "ltr"}>
+ <PageErrorBar error={settingsError} />
+ <Text>{translate("title")}</Text>
+ </div>
+ );
+}
```
-
-Provide formatting helpers that use these settings. **NEVER hardcode date formats or currency symbols.**
+Provide formatting helpers that use these settings, inside `PageBody` beside the settings state. **NEVER hardcode date formats or currency symbols.**
**CRITICAL rules for formatting:**
- Do NOT use `Intl.NumberFormat` with a hardcoded currency code as the primary formatter — always use the helpers below that read from `usersettings`.
diff --git a/plugins/model-apps/references/page-telemetry.md b/plugins/model-apps/references/page-telemetry.md
index 9feecf8af..e8eeffad6 100644
--- a/plugins/model-apps/references/page-telemetry.md
+++ b/plugins/model-apps/references/page-telemetry.md
@@ -53,7 +53,8 @@ Match on intent, not exact wording.
| Maker says something like... | Add |
|---|---|
| "track when a user completes a task" | `trackEvent('TaskCompleted', { ... })` in the completion handler |
-| "log errors to App Insights" / "report failures" | `trackException(err, { ... })` in the relevant `catch` blocks |
+| "log errors to App Insights" / "report failures" | the failure-telemetry lines inserted into the page's `reportPageError` (rules.md → *Missing Error Handling*), and `props.appInsights` as the **seventh argument** of every data failure's report; render crashes too, through the boundary (section 3) |
+| "report failed saves" | the same insertion, and `props.appInsights` as the seventh argument of the save's reports **only** — never the loads' and never the boundary's |
| "measure how many records load" | `trackMetric('AccountsLoaded', rows.length)` after the load resolves |
| "track which filters users apply" | `trackEvent('FilterApplied', { ... }, { throttle: { key: 'FilterApplied', windowMs: 1000 } })` |
| "track searches as the user types" | debounce at the source, then `trackEvent('Searched', { count }, { throttle: ... })` |
@@ -66,6 +67,15 @@ Counter-examples that **do not** authorize instrumentation: "show a chart of sal
region", "display the record count", "add a KPI tile", "show an error message if the
save fails", "add a retry button", "make the page load fast".
+**Failures are reported in one place.** Every page reports its failures through its one
+`reportPageError` (rules.md, Critical Rule 22) whether or not telemetry is on. A request to
+report failures does not add `trackException` calls to catch blocks: it inserts the documented
+lines into that reporter and hands `props.appInsights` to exactly the reports the request
+covers. The reporter sends a new `<operation> failed` error with `outcome`, `category`,
+`source` and a recognized `statusCode` — never the thrown value, the host's message, a row, a
+lookup or an identity. A request that asks only for success events ("track when a user completes
+a task") leaves the reporter and the boundary as they are.
+
---
## 2. The API
@@ -120,7 +130,7 @@ export interface GenUXTelemetryCallOptions {
* Do NOT await these calls and do NOT wrap them in try/catch.
*/
export interface IGenUXPageAppInsightsTelemetry {
- /** Report a caught error. Prefer this over trackTrace inside a catch block. */
+ /** Report a failure. A page calls it ONLY from inside its reportPageError (rules.md, "Missing Error Handling"). */
trackException(error: unknown, properties?: GenUXTelemetryProperties, options?: GenUXTelemetryCallOptions): void;
/** Report a diagnostic message. Use sparingly. */
@@ -153,20 +163,26 @@ carries the prop, because the generated `RuntimeTypes.ts` may predate it:
```typescript
type PageTelemetry = {
trackEvent(name: string, properties?: Record<string, unknown>, options?: unknown): void;
- trackException(error: unknown, properties?: Record<string, unknown>, options?: unknown): void;
trackMetric(name: string, value: number, properties?: Record<string, unknown>, options?: unknown): void;
startTrack(name: string): void;
stopTrack(name: string, properties?: Record<string, unknown>, options?: unknown): void;
};
-const GeneratedComponent = (props: GeneratedComponentProps & { appInsights?: PageTelemetry }) => {
+function PageBody(props: GeneratedComponentProps & { appInsights?: PageTelemetry }) {
const { dataApi, pageInput, appInsights } = props;
// ...
-};
+}
+
+const GeneratedComponent = (props: GeneratedComponentProps & { appInsights?: PageTelemetry }) => (
+ <PageErrorBoundary>
+ <PageBody {...props} />
+ </PageErrorBoundary>
+);
```
-Only declare the methods the page actually calls. On a page you are **not**
-instrumenting, add none of this - the signature stays exactly
+Only declare the methods the page actually calls. `trackException` is not one of them: the
+reporter's own `PageErrorTelemetry` type declares it, because only the reporter calls it. On a
+page you are **not** instrumenting, add none of this - the signatures stay exactly
`(props: GeneratedComponentProps)`.
---
@@ -217,16 +233,20 @@ justify adding telemetry on their own.
but is still worth measuring (typing in a search box, dragging a slider, applying
filters), you **must** pass the throttle option with a stable, distinct `key` per
call site: `{ throttle: { key: 'ordersSearch', windowMs: 1000 } }`.
-- **Prefer `trackException` in catch blocks over `trackTrace`.** Reserve it for
- errors genuinely worth surfacing - a failed save, a failed load, a rejected
- request. Do **not** call it for expected empty states (a query returning zero rows,
- an optional lookup finding nothing) or for validation the user is expected to hit;
- those are normal outcomes, not failures.
-- **Instrument the error boundary.** If the page has a React error boundary - or you
- add one for resilience - call
- `appInsights?.trackException(error, { category: 'errorBoundary' })` from its
- `componentDidCatch`. A render crash is the single most valuable error to report,
- and it never reaches a `catch` block.
+- **Failures go through `reportPageError` only.** Never call `trackException` — or
+ `trackTrace` — in a `catch` block or anywhere else yourself. Insert the documented
+ telemetry lines into the page's reporter (right after its `console.error` line) and pass
+ `props.appInsights` as the seventh argument of exactly the reports the request covers:
+ `reportPageError(PAGE_NAME, 'saveOrder', undefined, error, 'write', undefined, props.appInsights)`.
+ Do **not** report expected empty states (a query returning zero rows, an optional lookup
+ finding nothing) or validation the user is expected to hit; those are normal outcomes, not
+ failures, and they never reach the reporter.
+- **The boundary reports render crashes only when the request covers them.** A render crash
+ never reaches a `catch` block, so a request to report failures generally covers it: then
+ render `<PageErrorBoundary appInsights={props.appInsights}>` and make its `componentDidCatch`
+ report `reportPageError(PAGE_NAME, 'render', undefined, error, 'render', undefined, this.props.appInsights)`
+ (rules.md shows both). A request about one operation ("report failed saves") leaves the
+ boundary as it is.
- **`trackTrace`** is for a diagnostic breadcrumb at a key decision point in
genuinely complex logic (which branch a multi-step flow took, why a fallback
engaged). Do not narrate ordinary control flow with it.
@@ -250,55 +270,82 @@ justify adding telemetry on their own.
Shape references for pages whose maker **asked** to track or measure something - not
a default template. Note how few calls even an intentionally instrumented page makes.
+Each page is built on the page error block of rules.md: its failures are reported through
+`reportPageError` either way, and only an authorized request hands that reporter
+`props.appInsights`.
+
+A whole `PageBody` for "report failed saves": the reporter carries the inserted telemetry
+lines, the save's two reports pass `appInsights` as the seventh argument, and nothing else is
+instrumented — not the load, not the boundary.
```tsx
-// GOOD: one page-level load event, emitted once, with a count and a duration.
-const GeneratedComponent = (props: GeneratedComponentProps & { appInsights?: PageTelemetry }) => {
+type OrderRow = { orderid: string; name: string };
+type PageTelemetry = { trackEvent(name: string, properties?: Record<string, unknown>, options?: unknown): void };
+
+function PageBody(props: GeneratedComponentProps & { appInsights?: PageTelemetry }) {
const { dataApi, pageInput, appInsights } = props;
- const [orders, setOrders] = useState<TableRow[]>([]);
-
- useEffect(() => {
- let cancelled = false;
- appInsights?.startTrack('OrdersLoad');
- (async () => {
- try {
- const result = await dataApi.queryTable('order', { select: ['name', 'statuscode'], pageSize: 50 });
- if (cancelled) {
- return;
- }
- setOrders(result.rows);
- // stopTrack reports the elapsed time for you - do not compute it yourself.
- appInsights?.stopTrack('OrdersLoad', { outcome: 'success', entityName: 'order', count: result.rows.length });
- } catch (error) {
- // A catch block is the single highest-value place to instrument.
- appInsights?.stopTrack('OrdersLoad', { outcome: 'failure', entityName: 'order' });
- appInsights?.trackException(error, { entityName: 'order', category: 'grid', source: 'pageLoad' });
- }
- })();
- return () => {
- cancelled = true;
- };
- // Never put dataApi in a dependency array - see rules.md Rule 15.
- }, []);
+ void pageInput;
+ const [name, setName] = React.useState('');
+ const [save, setSave] = React.useState<{ saving: boolean; error: PageErrorView | null }>({ saving: false, error: null });
+ const pending = React.useRef(false);
+
+ async function saveOrder() {
+ if (pending.current) return;
+ pending.current = true;
+ setSave({ saving: true, error: null });
+ try {
+ await dataApi.createRow('order', { name });
+ setSave({ saving: false, error: null });
+ } catch (error) {
+ // The one call that reaches Application Insights for this failure: the reporter sends
+ // `saveOrder failed` with approved properties only — never `error` itself.
+ setSave({ saving: false, error: reportPageError(PAGE_NAME, 'saveOrder', undefined, error, 'write', undefined, appInsights) });
+ } finally {
+ pending.current = false;
+ }
+ }
- // ...
-};
+ return (
+ <div>
+ <PageErrorBar error={save.error} />
+ <Input aria-label="Order name" value={name} onChange={(_, data) => setName(data.value)} />
+ <Button appearance="primary" disabled={save.saving || !name.trim()} onClick={() => void saveOrder()}>Save order</Button>
+ </div>
+ );
+}
+```
-// GOOD: a completed user action, instrumented on BOTH the success and failure paths.
-const handleSubmit = async (): Promise<void> => {
+Handler shapes for other requests. Each sits inside `PageBody`, which destructures
+`appInsights` from its props:
+
+```tsx
+// GOOD: "how long saving takes" - one timed operation, stopped on BOTH paths. The failure is
+// reported without telemetry: this request measures a duration, it does not ask to report failures.
+async function submitOrder(): Promise<void> {
+ appInsights?.startTrack('OrderSubmit');
+ try {
+ await dataApi.createRow('order', values);
+ // stopTrack reports the elapsed time for you - do not compute it yourself.
+ appInsights?.stopTrack('OrderSubmit', { outcome: 'success', entityName: 'order' });
+ setSubmit({ submitting: false, error: null });
+ } catch (error) {
+ appInsights?.stopTrack('OrderSubmit', { outcome: 'failure', entityName: 'order' });
+ setSubmit({ submitting: false, error: reportPageError(PAGE_NAME, 'submitOrder', undefined, error, 'write') });
+ }
+}
+
+// GOOD: "log when a form is submitted" - an event on BOTH the success and failure paths. The
+// event names the outcome; it carries no error, and the failure goes to the reporter as usual.
+async function handleSubmit(): Promise<void> {
try {
const recordId = await dataApi.createRow('order', values);
- appInsights?.trackEvent('OrderSubmitted', {
- outcome: 'success',
- entityName: 'order',
- recordId,
- source: 'toolbar',
- });
+ appInsights?.trackEvent('OrderSubmitted', { outcome: 'success', entityName: 'order', recordId, source: 'toolbar' });
+ setSubmit({ submitting: false, error: null });
} catch (error) {
appInsights?.trackEvent('OrderSubmitted', { outcome: 'failure', entityName: 'order', source: 'toolbar' });
- appInsights?.trackException(error, { entityName: 'order', category: 'form' });
+ setSubmit({ submitting: false, error: reportPageError(PAGE_NAME, 'submitOrder', undefined, error, 'write') });
}
-};
+}
// GOOD: a rapid-fire call site MUST pass a throttle with a stable key.
const handleSearchChange = (value: string): void => {
@@ -310,27 +357,16 @@ const handleSearchChange = (value: string): void => {
{ throttle: { key: 'ordersSearch', windowMs: 1000 } }
);
};
-
-// GOOD: an error boundary reports render crashes, which never reach a catch block.
-class PageErrorBoundary extends React.Component<{ appInsights?: PageTelemetry }, { hasError: boolean }> {
- public state = { hasError: false };
-
- public static getDerivedStateFromError(): { hasError: boolean } {
- return { hasError: true };
- }
-
- public componentDidCatch(error: Error): void {
- this.props.appInsights?.trackException(error, { category: 'errorBoundary', source: 'render' });
- }
-
- public render(): React.ReactNode {
- return this.state.hasError ? <div>Something went wrong.</div> : this.props.children;
- }
-}
```
----
+For "report failures" (every failure), insert the reporter's telemetry lines, pass
+`props.appInsights` as the seventh argument of every data failure's report, and instrument the
+boundary as rules.md shows: `<PageErrorBoundary appInsights={props.appInsights}>` in the default
+export, and `reportPageError(PAGE_NAME, 'render', undefined, error, 'render', undefined, this.props.appInsights)`
+in its `componentDidCatch`. A render crash never reaches a `catch` block, so the boundary is
+the only place it can be reported.
+---
## 5. Anti-patterns
```tsx
@@ -381,6 +417,19 @@ if (rows.length === 0) {
appInsights?.trackException(new Error('No orders found'), { entityName: 'order' });
}
+// BAD: a trackException of its own in a catch block. It sends the thrown value - which can
+// carry record text - and bypasses the page's reporter. Report through reportPageError, which
+// alone calls trackException, and only with a fixed `<operation> failed` error.
+try {
+ await dataApi.createRow('order', values);
+} catch (error) {
+ appInsights?.trackException(error, { entityName: 'order', category: 'form' });
+}
+
+// BAD: a save-only request ("report failed saves") spread to the load and the boundary.
+// A narrow request stays narrow: only the save's reports get `appInsights`.
+reportPageError(PAGE_NAME, 'loadOrders', undefined, failure, 'read', retryLoad, appInsights);
+
// BAD: an un-throttled rapid call site.
const onSliderChange = (v: number): void => appInsights?.trackMetric('SliderValue', v);
diff --git a/plugins/model-apps/references/plan-schema.md b/plugins/model-apps/references/plan-schema.md
index 67a07bd0f..21eb6654c 100644
--- a/plugins/model-apps/references/plan-schema.md
+++ b/plugins/model-apps/references/plan-schema.md
@@ -25,7 +25,25 @@ same relative position so downstream parsers can find them predictably:
# Genpage Plan
## User Requirements
-[The original user requirements passed to the planner]
+[The original user requirements passed to the planner — verbatim, never rewritten]
+
+## Assumptions
+[Every newly authored standalone `/genpage` create plan writes this section. Exactly:]
+No assumptions.
+
+[or one entry per decision the planner made that the request did not state — relationships, target or
+roll-up scope, server or client filters, default sort, paging limits, initial-read caching, material page
+behaviour (not every CSS token):]
+
+### A1 — [short title]
+- Decision: [what the plan does]
+- Alternatives considered: [the other candidates]
+- Evidence: [metadata: … | sample: … | default: …]
+- Resolution: [user-confirmed | planner-default | unattended-default]
+- Question: [the question's id — user-confirmed and unattended-default only]
+- Answer: [the actual answer — user-confirmed and unattended-default only]
+- Default record: [unattended-default only — the exact line logged in workflow-log.md:
+ Unattended default: A1 / <question id> → <answer> (<reason>)]
## Working Directory
[Absolute path where .tsx files and RuntimeTypes.ts should be written]
@@ -58,8 +76,8 @@ planner picks them by asking the user (when metadata work is needed) or by
writing the safe defaults `Solution: Default` + `Publisher Prefix: new` (when
no question is needed). They are never omitted.
-Why mandatory: `apps.js create --solution <name>` takes the solution the new app and its
-sitemap are added to, and has no "active solution" fallback — a missing `--solution` is a usage
+Why mandatory: `apps.js create --solution <name>` takes the solution the new app, its
+sitemap and its pages are added to, and has no "active solution" fallback — a missing `--solution` is a usage
error. Always writing the field eliminates a fragile conditional branch in the orchestrator.
Downstream consumers honour them:
@@ -67,7 +85,9 @@ Downstream consumers honour them:
so newly-created tables/columns/relationships land in that solution. It also
uses `Publisher Prefix` to build schema names (e.g. `<prefix>_Candidate`).
- The orchestrator (skill) passes `--solution <Solution>` to `apps.js create`
- when provisioning a new model-driven app.
+ when provisioning a new model-driven app, and to every `genpage-upload.js`
+ create, so each page this run makes joins that solution too (a page joins no
+ solution on its own, and the app's add never brings the pages it shows).
## Pages
| Page | File | Purpose | Entities |
@@ -155,6 +175,20 @@ fabricated. Persisted (via `genpage-upload.js --actions`) into config.json's `ac
| new_ApproveOrder | Action | salesorder | Approve Order | Comment: String, Amount: Decimal |
| new_GetOrderSummary | Function | (Global) | Get Order Summary | OrderId: Guid |
+## Dataverse Operations
+[OPTIONAL section — present ONLY when this run's genpage-customapi-builder added or replaced a
+built-in Dataverse operation (WhoAmI, RetrieveVersion; see references/dataverse-operations.md).
+Absent means no new built-in operation. When present it is either exactly:]
+No Dataverse operations.
+
+[or the builder's `dataverse-operations.md` body, copied verbatim: the verification line, then one
+row per selected operation in catalogue order, every cell the catalogue's own. `Invoke` is always
+`button`. These rows are never Custom APIs and never go into `## Custom API Bindings`.]
+Verification: environment not-checked, runtime not-checked, privileges not-checked.
+| Name | Kind | Bound Entity | Display Name | Parameters | Response fields | Invoke |
+|------|------|--------------|--------------|------------|-----------------|--------|
+| WhoAmI | Function | (Global) | Current Dataverse identity | (none) | BusinessUnitId, UserId, OrganizationId | button |
+
## Solution Packaging
[OPTIONAL section — include ONLY when packaging into a solution. Omit it entirely
to skip packaging; when absent, the orchestrator skips Phase 6.7. This section is
@@ -165,7 +199,12 @@ connector bindings." sentinel).]
- Connection references: [comma-separated connectionreference logical names to include, or "none"]
## Design Preferences
-- Styling: [user's styling preferences — colors, theme, visual aesthetic]
+- Styling: [EITHER `Maker-requested: <the look as concrete values — each color as a hex value with
+ its role (primary, accent, background, text), the font family with a fallback, corner radius,
+ density, borders and shadows, and the component treatments> (from: screenshot | website <url> |
+ description)` when the maker asked for a look of their own — a screenshot or mockup, a website to
+ match, or a description; OR the model-driven defaults (`Fluent UI V9 defaults`, plus any
+ preference that does not replace that look) when they did not]
- Features: [specific features mentioned — search, filtering, sorting, navigation, etc.]
- Accessibility: [any specific accessibility requirements beyond WCAG AA defaults]
@@ -192,18 +231,111 @@ connector bindings." sentinel).]
- **Data Binding:** [how data flows — queryTable, retrieveRow, mock arrays]
- **Interactions:** [click handlers, drag-drop, navigation, etc.]
+#### Data semantics
+[Every relationship and every server-side or client-side filter this page uses — the internal source-row
+and target-resolution filters included. Exactly `None.` when the page has none:]
+
+##### R1
+- Kind: relationship
+- Definition: [source column, target scope, predicate and value source, null and roll-up behaviour]
+- Source: [A1 — the assumption that settled it]
+
+##### F1
+- Kind: filter
+- Definition: [what rows the filter keeps]
+- Source: User Requirements
+- Requirement quote: [the words of ## User Requirements that state it]
+
+#### Lookup metadata
+[Every lookup a join, a filter, a target-dependent navigation or a write uses, single-target ones included.
+Exactly `None.` when the page uses none:]
+
+| Table | Column | Read property | Targets | Used by | Metadata state |
+|-------|--------|---------------|---------|---------|----------------|
+| [source table] | [lookup column] | _[column]_value | [the COMPLETE target set] | [decision ids; purposes] | [observed / planned] |
+
+| Table | Column | Target | Navigation property | Referenced key |
+|-------|--------|--------|---------------------|----------------|
+| [source table] | [lookup column] | [target] | [concrete navigation property] | [target key] |
+
+- Evidence: [lookup-metadata.json; successful source/target metadata discovery — or "planned: <table> is created in Phase 2"]
+- Read target strategy: normalize the logical-name annotation and qualified prefix; use the metadata-backed
+ fallback only for a bare id with missing target evidence.
+
### [Page Name]
[Repeat the above block once per page in the Pages table]
```
---
+## Assumptions, data semantics and lookup metadata
+
+A plan states what the maker asked for in `## User Requirements` — kept **byte for byte** as the original
+request, never rewritten — and everything the planner decided on its own in `## Assumptions`, so the approval
+gate shows which details are guesses. A later clarification answer is recorded in an assumption, not added to
+the requirements (or to the first upload's prompt).
+
+**`## Assumptions` entries** (`### A<n> — <title>`):
+
+- Ids are unique `A1`, `A2`, … — stable across revisions, not necessarily contiguous.
+- `Decision`, `Alternatives considered`, `Evidence` and `Resolution` are required, each once and non-empty.
+ `Evidence` starts with `metadata:`, `sample:` or `default:`. A sample proves an observed shape, not the
+ intended business scope or a lookup's complete target set.
+- `Resolution` is `user-confirmed` (the maker answered: `Question` and the actual `Answer` are required),
+ `planner-default` (no question was asked, so neither appears) or `unattended-default` (an unattended run
+ took the option the planner marked as the default: `Question`, `Answer` and `Default record` are required).
+ An automatic pick is never `user-confirmed`.
+- `Default record` is the exact line the run logged: `Unattended default: <assumption id> / <question id> →
+ <answer> (<reason>)` — the answer word for word, a reason that never contains the word "approved" (that word
+ belongs to the separate plan-approval record).
+- A question still waiting for its answer is a pending interaction, not an assumption: an entry is written
+ only after the answer returns.
+- A value may continue on indented lines. Values are compared after line endings, continuation whitespace and
+ Unicode normalization; case and wording are substantive. Any other line, field or nested heading is refused.
+
+**`#### Data semantics`** (inside each `### <Page Name>`, after its bullet fields): entries are `##### R<n>`
+(`Kind: relationship`) and `##### F<n>` (`Kind: filter`) — level five, never level three, which would read as
+another page. `Definition` records the source column, the target scope, the predicate and value source, and
+material null or roll-up behaviour. `Source` is one assumption id or exactly `User Requirements`; the latter
+also needs a `Requirement quote` that the original requirements contain (whitespace aside). A decision that
+is only partly stated cites its assumption rather than the user's broad phrase. The page's `Data Binding` and
+`Interactions` refer to these ids and add no unrecorded predicate.
+
+**`#### Lookup metadata`**: one row per lookup a join, a filter, a target-dependent navigation or a write
+uses — single-target lookups included. `Targets` is the lookup's **complete** set from metadata, never the
+subset a page shows; `Read property` is `_<column>_value`; `Used by` names decision ids and declared purposes
+(customer navigation, customer picker). The path table lists only **concrete** paths read from metadata
+(`scripts/get-lookup-metadata.js`): a shared path such as Owner's `ownerid` is never a target discriminator,
+and no path is invented. Write exactly `None.` when the page uses no lookup.
+
+**Planned and observed.** A lookup on a table this run creates is recorded `planned`, with no paths. After
+Phase 2 the orchestrator reads its metadata (`get-lookup-metadata.js`, saved as `lookup-metadata.json`) and
+re-invokes the planner, which may only promote a matching record to `observed` and add its measured paths —
+never change its column, target set, uses, a decision or an assumption. A difference needs new approval.
+
+**The approval preview** carries the same records at its own levels: `### Assumptions` **first** (entries
+`#### A<n> — <title>`, or `No assumptions.`), then `### Pages (N total)`, then `### Data Semantics` and
+`### Lookup Metadata`, each grouped under `#### <page file>` (records, or `None.`), then the existing Data
+Strategy, App, Solution, Localization and Design sections. `scripts/genpage-plan-provenance.js verify`
+compares the two documents' records field by field (never a whole-document hash): a written plan whose
+assumptions, decisions or lookup records differ from the approved ones — or that has the contract where the
+preview has none, or the reverse — fails even when its page files match. `--require-assumptions` requires the
+whole contract of a newly authored plan; `--lookup-metadata <file>` checks every observed lookup against the
+saved metadata read (and lets a planned one be promoted); `--require-observed-lookups` refuses a lookup still
+planned before generation.
+
+An older plan without these sections is **not recorded**, not "everything was stated": it stays valid. A
+present section that is malformed fails whatever the plan's `Mode` — an App Spec projection included.
+
+---
+
## Section Semantics
| Section | Consumers | Rules |
|---------|-----------|-------|
| `# Genpage Plan` | N/A | Title only, no content |
-| `## User Requirements` | Orchestrator — used as the `--prompt` value on the **first** `genpage-upload.js` upload (the create) for each new page only. Subsequent uploads (Phase 6.5 PAGEREF re-upload, Phase 7.5 fix re-deploy, edit flow) use delta prompts, NOT this field. | Verbatim user input |
+| `## User Requirements` | Orchestrator — used as the `--prompt` value on the **first** `genpage-upload.js` upload (the create) for each new page only. Subsequent uploads (Phase 6.5 PAGEREF re-upload, Phase 7.5 fix re-deploy, edit flow) use delta prompts, NOT this field. | Verbatim user input — never rewritten; later answers go to `## Assumptions` |
+| `## Assumptions` | Orchestrator (approval, shown first), page-builder, provenance verify | Optional on read; written by every new standalone create plan: entries or exactly "No assumptions." (see above) |
| `## Working Directory` | All downstream agents | Absolute path, forward slashes on Windows |
| `## Plugin Root` | Page-builder (to Read references/samples) | Absolute path |
| `## Environment` | Orchestrator | URL, app decision, languages |
@@ -212,10 +344,11 @@ connector bindings." sentinel).]
| `## Existing Entities` | Orchestrator (for `genpage.js types --data-sources`) | Comma-separated logical names |
| `## Connector Bindings` | Planner, page-builder, orchestrator deploy | Exact literal "No connector bindings." when empty; logical names must match Dataverse connectionreferences; tabular bindings must include discovered optional `Fields`; REST/action bindings must include discovered `Parameters` and `Response` |
| `## Custom API Bindings` | Planner, page-builder, orchestrator deploy | Exact literal "No custom API bindings." when empty; names must match existing Dataverse Custom APIs (`customapi.uniquename`); entity-bound rows carry the bound table (else `(Global)`); every row carries its discovered `Parameters` kinds |
+| `## Dataverse Operations` | Planner, page-builder, orchestrator deploy (Phase 4.6b) | Optional; absent = no new built-in operation. Exact literal "No Dataverse operations." or the builder's table under its not-checked verification line; only `WhoAmI` / `RetrieveVersion`, catalogue cells, `Invoke` = `button` |
| `## Solution Packaging` | Orchestrator (Phase 6.7) | Opt-in; absent = skip |
-| `## Design Preferences` | Page-builder | Prose, free-form |
+| `## Design Preferences` | Page-builder | Prose, free-form; a `Styling:` line that starts with `Maker-requested:` wins over the default look (`references/rules.md` → *Maker-requested styling*) |
| `## Relevant Samples` | Page-builder (for Read path resolution) | Sample filename must match a file in `${PLUGIN_ROOT}/samples/` |
-| `## Per-Page Specifications` | Page-builder | Each page gets one `### [Page Name]` subsection matching the Pages table |
+| `## Per-Page Specifications` | Page-builder | Each page gets one `### [Page Name]` subsection matching the Pages table; a new plan also gives each its `#### Data semantics` and `#### Lookup metadata` (entries or exactly "None.") |
---
@@ -228,8 +361,12 @@ Before the orchestrator fans out to builders in Phase 5, it should verify:
- [ ] If `## Pages` contains Dataverse entities, `## Existing Entities` is non-empty OR `## Entity Creation Required` is non-empty
- [ ] Every non-empty `## Connector Bindings` logical name matches an existing `connectionreference` in the selected environment
- [ ] Every non-empty `## Custom API Bindings` name matches an existing `customapi` (uniquename) in the selected environment; entity-bound rows carry the bound table and every row its parameter kinds
+- [ ] A `## Dataverse Operations` section, when present, is the exact sentinel or the built-in table (WhoAmI / RetrieveVersion only); its names are never checked against `customapi`
- [ ] Every tabular connector binding records discovered `Fields`; generated connector row interfaces must mark every field optional
- [ ] Every REST/action connector binding records discovered `Parameters` and `Response`; generated request/response interfaces must be built from those schemas only
+- [ ] Every relationship and every server-side or client-side filter used in `## Per-Page Specifications` traces to the user's stated text in `## User Requirements` or a named `## Assumptions` entry. The builder introduces no unrecorded business predicate, relationship or roll-up.
+ Validation proves structure, ID resolution, quote presence and agreement with approved structured decisions. It does not prove natural-language entailment, judge materiality, or discover arbitrary contradictory prose. Those remain planner/reviewer responsibilities, supplemented by scenario-specific code checks.
+- [ ] Every lookup a page record uses names its complete metadata target set, and is `observed` before generation (`genpage-plan-provenance.js verify --require-observed-lookups --lookup-metadata <working-dir>/lookup-metadata.json`)
If validation fails, the orchestrator should surface a clear error to the user rather
than dispatching builders that will fail silently.
diff --git a/plugins/model-apps/references/rules.md b/plugins/model-apps/references/rules.md
index e510feb49..2f9274fd4 100644
--- a/plugins/model-apps/references/rules.md
+++ b/plugins/model-apps/references/rules.md
@@ -8,11 +8,11 @@ Comprehensive rules for generating generative page code. Read this file during c
1. **React 17 + TypeScript**: All code must use React 17 with TypeScript
2. **Fluent UI V9**: Use `@fluentui/react-components` (DatePicker from `@fluentui/react-datepicker-compat`, TimePicker from `@fluentui/react-timepicker-compat` — both require `mountNode` prop)
-3. **Single File**: All code (components, utilities) in one file; each as separate top-level function (no nesting)
+3. **Single File**: All code (components, utilities) in one file; each as separate top-level function (no nesting). The one exception is a single top-level React class, `PageErrorBoundary` (Rule 22). Event handlers and loaders that close over a component's state stay inside that component, as before — they are not nested components or free-standing utilities. No new library or runtime dependency.
4. **Limited Imports**: Only React, Fluent UI V9, FluentUI icons, and D3.js for charts
5. **DataAPI**: ONLY use when explicit TableRegistrations provided; otherwise use mocked data
6. **Entity Logical Names**: Use singular lowercase (e.g., `"account"` not `"accounts"`)
-7. **Styling**: Use `makeStyles` with tokens; avoid inline styles except for dynamic values
+7. **Styling**: Use `makeStyles` with tokens; avoid inline styles except for dynamic values. Tokens give the default model-driven look. When the plan's `## Design Preferences` → `Styling:` starts with `Maker-requested:`, apply that style instead — see **Layout and Styling > Maker-requested styling**
8. **Responsive Design**: Use flexbox and relative units; NEVER use `100vh`/`100vw`
9. **Icons — verified names only**: Import from `@fluentui/react-icons`; use unsized variants only (e.g., `AddRegular` not `Add24Regular`). Icon names are frequently hallucinated — names like `MedicalRegular`, `PawRegular`, `AnimalRabbitRegular`, `BirdRegular` do not exist. **Always Read `${PLUGIN_ROOT}/references/verified-icons.txt`** (~5000 names) and cross-check every icon import against that list. After writing, Grep your own output for `from "@fluentui/react-icons"` and verify each named import. If an icon you want is not in the list, pick the closest semantic substitute that is. Never guess a name.
10. **No External Libraries**: No routing libraries (React Router) or assumptions of implicit dependencies
@@ -27,6 +27,8 @@ Comprehensive rules for generating generative page code. Read this file during c
19. **All hooks above every early return — no conditional hook calls**: Detail/record pages crash with **minified React error #310** ("rendered more/fewer hooks than the previous render") on the *first* open of a record, then work on the second click. Cause: a hook — usually a `useMemo` deriving chart points or display rows from loaded data — sits *below* a loading/empty early return (`if (data.loading) return <Spinner/>`). On the first render data is still loading, the component early-returns and never reaches that `useMemo` (fewer hooks); when data arrives it renders past the return and calls the extra hook → the hook count differs between renders → #310. The "works the second time" intermittency (the cached render skips the loading branch) is the signature of this bug. **Fix:** place every `useMemo`/`useState`/`useEffect`/`useCallback` **above all early returns**, and make derived memos tolerate not-yet-loaded data (read from an always-initialized value, e.g. `data.rows ?? []`). Early returns are fine — they just must come *after* the last hook call. This is the React rules of hooks: never call a hook below a conditional `return`.
20. **Never put `...` alone on a line**: Write the spread/rest token and its operand together (`...rows`, not `...` followed by `rows` on the next line).
21. **End final type-argument statements with `;`**: If the file's last statement ends in a type argument list (`Page<string>`, `Array<Row>`), terminate it with a semicolon.
+22. **Consistent errors**: Route failed data operations through the page's single top-level `reportPageError`, retain bounded code and message diagnostics, and put its returned view in the operation's error state. Render errors as escaped Fluent MessageBar text with localized application fallbacks. Offer manual retry only for proven-safe reads or the documented pre-dispatch Custom API network result; never retry an indeterminate result automatically. Wrap PageBody in the page's one top-level React PageErrorBoundary. Instrument only explicitly authorized failure sites, only through the helper. Expected null/empty states are not failures. See “Missing Error Handling” for the canonical patterns and the static check's declared limits.
+23. **Lookup identities**: A lookup reference is a validated table-and-bare-id pair, not its label or the first metadata target. Normalize bare GUID and `/<table>(<guid>)` read values using the logical-name annotation and/or qualified prefix, checking both against metadata and rejecting conflicts. Use the bare id for filters, retrieval and navigation; rebuild the qualified value only for writes. Record every lookup used by a join/filter and its complete target set in Per-Page Specifications. Ask about unresolved relationship/filter meaning; never broaden a failed typed query. Unresolved references cannot trigger target-dependent actions. See **DataAPI Rules > Lookup references** for the canonical `normalizeLookupReference` and the five WRONG/CORRECT pairs.
---
@@ -68,10 +70,12 @@ matching flag: `charts` adds `d3` and `@types/d3`, `datepicker` adds
## Component Structure
-Standard component pattern:
+Standard component pattern — the exported component only mounts the page inside its error
+boundary (Critical Rule 22); the page itself lives in `PageBody`:
```typescript
-import {useEffect, useState} from 'react';
+import * as React from 'react';
+import { MessageBar, MessageBarBody } from '@fluentui/react-components';
import type {
TableRow,
DataColumnValue,
@@ -84,18 +88,31 @@ import type {
// Additional imports: @fluentui/react-components, @fluentui/react-icons, @fluentui/react-datepicker-compat, d3
+// The page error block of "Missing Error Handling" (Common Errors), copied unchanged: the PageErrorKind,
+// PageErrorView and PageErrorTelemetry types, PAGE_NAME, the error copy and translate, reportPageError,
+// PageErrorBar and PageErrorBoundary
+
// Utility functions as separate top-level functions
// Sub-components as separate top-level functions
-const GeneratedComponent = (props: GeneratedComponentProps) => {
+function PageBody(props: GeneratedComponentProps) {
const { dataApi, pageInput } = props;
- // Component implementation
+ // Component implementation: hooks, state and handlers; every failed data operation goes through reportPageError
}
+const GeneratedComponent = (props: GeneratedComponentProps) => (
+ <PageErrorBoundary>
+ <PageBody {...props} />
+ </PageErrorBoundary>
+);
+
export default GeneratedComponent;
```
+`GeneratedComponent` passes its props to `PageBody` unchanged and does nothing else; never call
+`PageBody(props)` as a function. `PageErrorBoundary` is the page's one class component.
+
---
## Layout and Styling
@@ -103,7 +120,7 @@ export default GeneratedComponent;
### Design Principles
- Follow Microsoft Fluent Design System principles
- Use sentence case for all text
-- Use theme tokens (e.g., `tokens.spacingVerticalXL`, `tokens.colorNeutralBackground1`)
+- Use theme tokens (e.g., `tokens.spacingVerticalXL`, `tokens.colorNeutralBackground1`) — the default look when the maker asked for no style of their own
- `makeStyles` for styling; inline styles only for dynamic values
- Group content in sections for visual separation
@@ -163,6 +180,62 @@ const useStyles = makeStyles({
- If the mockup conflicts with accessibility or responsive design requirements, prioritize accessibility while staying as close to the visual design as possible
- Translate design elements to equivalent Fluent UI components (e.g., custom buttons -> Fluent Button with appropriate styling)
+### Maker-requested styling
+
+When the maker asks for a look of their own, that style wins over the default model-driven look.
+The maker can give a screenshot or mockup to follow, an existing website to match, or a description
+("navy and gold, serif headings, square corners"). The planner writes the style into
+`## Design Preferences` as a `Styling:` line that starts with `Maker-requested:` and gives concrete
+values. Apply each value. Do not fall back to the default tokens for a value that the style sets:
+
+- **Colors.** Build a theme from the stated colors over `webLightTheme` (or `webDarkTheme` for a dark
+ style). Apply it with the `themeToVars` two-div wrapper (see **Special Patterns > Dark Mode
+ Toggle**), so every Fluent component on the page uses the colors: `colorBrandBackground`,
+ `colorBrandForeground1`, `colorNeutralBackground1`, `colorNeutralForeground1`, and so on. Set
+ `color: tokens.colorNeutralForeground1` on the page root, so that inherited text follows the
+ theme (see the inherited-text note under **Dark Mode Toggle**). Use the same hex values in
+ `makeStyles` for the elements that the theme does not reach.
+- **Typography.** Set `fontFamily` on the page root to the stated font, with fallbacks that the
+ user's device has (for example `"Georgia, 'Times New Roman', serif"`). Set heading sizes and
+ weights in `makeStyles`.
+- **Shape and density.** Set the stated corner radius, spacing, borders and shadows in `makeStyles`.
+ For borders, write the longhands (see **Styling gotchas**).
+- **What the style does not set** keeps the default tokens, so the page stays consistent.
+
+```typescript
+import { webLightTheme } from "@fluentui/react-components";
+
+// Maker-requested: navy #0b2545 primary, gold #c9a227 accent, warm white #faf7f0 background, Georgia headings, 2px corners.
+const brandTheme = {
+ ...webLightTheme,
+ colorBrandBackground: "#0b2545",
+ colorBrandBackgroundHover: "#13315c",
+ colorBrandForeground1: "#0b2545",
+ colorNeutralBackground1: "#faf7f0",
+ borderRadiusMedium: "2px",
+};
+// In the component: the outer div sets the variables, the inner div reads them.
+// <div style={{ ...themeToVars(brandTheme), height: "100%", overflow: "hidden" }}>
+// <div className={styles.root}>{/* … */}</div>
+// </div>
+```
+
+**What cannot be matched.** Tell the maker when the request needs one of these:
+
+- A page is one `.tsx` file that uses React, Fluent UI V9, Fluent icons and D3. It cannot load a
+ stylesheet, a CSS file, a web font, an image or a script from another site, and it cannot use
+ another component library. The page rebuilds the widgets of a website with Fluent components that
+ are styled to match. It does not copy them.
+- A font that is not installed on the user's device shows its fallback. Name the closest common
+ font, and a fallback.
+- Only the page's own area gets the style. The app header, the navigation and the command bar around
+ the page keep the look of the app. The page must not style `body` or anything outside its root.
+- A screenshot is matched by eye. The layout, the colors and the type are close, not exact to the pixel.
+- Contrast stays at WCAG AA. If a requested pair of colors fails, use the nearest color that passes,
+ and tell the maker.
+
+**No style asked for:** keep the model-driven defaults (Fluent UI tokens and the default theme).
+
---
## Accessibility
@@ -267,6 +340,61 @@ const [lat] = useState(toNumberOrDefault(pageInput?.data?.latitude, 0));
const [lng] = useState(toNumberOrDefault(pageInput?.data?.longitude, 0));
```
+### What another page accepts (read it before you pass it data)
+
+The platform shows no list of the inputs a page takes. A page's inputs are the values its own source
+reads from its `pageInput` prop, and they are of two kinds, which travel in different places of the
+`navigateTo` call:
+
+| The target reads | Kind | Pass it in `navigateTo` as |
+|---|---|---|
+| `pageInput.data.<key>` | a data key | `data: { <key>: <value> }` |
+| `pageInput.recordId` | record context | `recordId: <the record's id>`, at the top level beside `pageId` — not in `data` |
+| `pageInput.entityName` | record context | `entityName: "<the table's logical name>"`, at the top level — not in `data` |
+
+Before a page navigates to a page that this plan does not build, find out what that page reads:
+
+1. **A page of an app that `/app-builder` built:** its App Spec declares its data keys as
+ `pages[].pageInput.data` (each key with its type). The producing page declares the same keys in
+ `navigatesTo[].data`. `download-model-app.js` writes both into the spec from the app's page manifest.
+ The spec declares no record context: to know whether the page reads `pageInput.recordId` or
+ `pageInput.entityName`, read its source as in 2.
+2. **Any other page** (a `/genpage` page, or a page made in Maker): download it into a folder of its
+ own. Do not use the working directory, and record no base marker, because this is a read:
+
+ ```powershell
+ node "${PLUGIN_ROOT}/scripts/genpage.js" download --env '<envUrl>' --page-id '<target-page-id>' --output-directory '<working-dir>/targets'
+ ```
+
+ Then search `<working-dir>/targets/<target-page-id>/page.tsx` for `pageInput`, and write down each
+ read with its path:
+ - Each key read from `pageInput.data` is a data key: `pageInput?.data?.accountId`,
+ `pageInput?.data?.["account-id"]`, or a key read from a variable that holds `pageInput.data`. Note
+ how the page converts each value (for example `toNumberOrDefault(...)` or `=== "true"`), and send a
+ value of that type.
+ - A read of `pageInput.recordId` or `pageInput.entityName` (also `const { recordId, entityName } =
+ pageInput`) is record context. Pass both at the top level of the call: the record's id, and the
+ logical name of its table.
+
+Pass each input in the place the target reads it, with the same name: data keys in `data`, record
+context at the top level. Do not move one into the other: a target that reads `pageInput.recordId` gets
+nothing from `data: { recordId }`, and one that reads `pageInput.data.accountId` gets nothing from
+`recordId`. (When you write both pages, put a custom identifier in `data` — see **Passing a record ID
+between pages**. A page that already exists is called the way it reads its input.) Values in `data` are
+primitives. The target ignores a key it does not read, so a guessed name fails silently. A page that
+reads neither kind takes no input: navigate to it with its `pageId` alone.
+
+Example — a target that reads record context and one data key, and the call that feeds it:
+
+```typescript
+// The target's page.tsx reads:
+const accountId = pageInput?.recordId; // record context
+const table = pageInput?.entityName; // record context
+const view = pageInput?.data?.view; // a data key
+// So the caller passes the record context at the top level, and the data key in data:
+Xrm.Navigation.navigateTo({ pageType: "generative", pageId: targetPageId, entityName: "account", recordId: selectedAccountId, data: { view: "summary" } });
+```
+
---
## Special Patterns
@@ -338,7 +466,9 @@ xrm.Navigation.navigateTo({ pageType: "generative", pageId: targetPageId, entity
**CRITICAL — never use `pageType: "entityrecord"` or `pageType: "entitylist"` to navigate to another generative page.** Those open the standard OOB form/list, not the custom page. Always use `pageType: "generative"` with the target page's GUID.
-**Passing a record ID between pages:** Always put custom identifiers in `data`, not `recordId`. `recordId` is reserved for standard Dataverse record context (used by OOB forms/views); values placed there may not arrive reliably on the receiving genpage. Use `data: { accountId: selectedId }` and read it as `pageInput?.data?.accountId` on the target page. Never rely on `recordId` as the delivery channel for a custom ID.
+**Passing a record ID between pages:** Always put custom identifiers in `data`, not `recordId`. `recordId` is reserved for standard Dataverse record context (used by OOB forms/views); values placed there may not arrive reliably on the receiving genpage. Use `data: { accountId: selectedId }` and read it as `pageInput?.data?.accountId` on the target page. Never rely on `recordId` as the delivery channel for a custom ID. This is how to write the pages of this plan; a page this plan does not build may already read `pageInput.recordId` and `pageInput.entityName`, and is called the way it reads them (see **Page Input > What another page accepts**).
+
+**Passing data to a page this plan does not build:** first read the keys that page accepts — see **Page Input > What another page accepts**. Never guess the names.
**Receiving navigation state:** On any page reachable via `navigateTo` (e.g., a detail page, or an explorer page the user navigates back to), initialize shared UI state — dark mode toggle, active filters, selected view — from `pageInput.data` first. URL params are a valid secondary source (e.g., for bookmarked URLs or direct links), but `pageInput.data` takes priority because `navigateTo` does not populate URL params. Pattern:
@@ -477,7 +607,7 @@ Two host behaviors make a naive on-mount fetch run more than once:
- **Never put `dataApi` in a dependency array** (`useEffect`/`useMemo`/`useCallback`) and never `useCallback` a fetch function — the host hands a new `dataApi` ref every render, so it re-fires the effect each render. Depend on a **readiness boolean** (`const dataReady = !!dataApi;`) plus `recordId`/`reloadKey` as needed.
- **Scope each `window` key by page + query** (include the page name, e.g. `__ppAccountOverview_accountCache`), not just the entity — two pages querying the same entity with different `select`/`filter` must not share a cache or in-flight entry.
- Seed initial `useState` from the `window` cache so the second mount paints final content with no spinner.
-- Use a single batched state object (`{ records, loading, error }`) — separate `setState` calls in async functions produce intermediate renders in React 17.
+- Use a single batched state object (`{ records, loading, error }`) — separate `setState` calls in async functions produce intermediate renders in React 17. `error` is the `PageErrorView | null` that `reportPageError` returns (see **Common Errors > Missing Error Handling**), never a string.
- For detail pages, key both the cache and the in-flight map by `recordId` (`Map<string, ...>` on `window`).
- On mutation or manual refresh, clear the cache **and** the in-flight promise before refetching.
@@ -563,7 +693,7 @@ return (
9. **Check TableRegistrations** - Only use tables defined in TableRegistrations interface
10. **Follow dataApi_definition** - Use the DataAPI interfaces defined below
11. **queryTable returns `{ rows: T[] }`, NOT a raw array** — `dataApi.queryTable()` returns a `DataTable<T>` object with `.rows`, `.hasMoreRows`, and `.loadMoreRows()`. Always access the records via `result.rows`. `retrieveRow()` returns the row object directly (no wrapper).
-12. **Lookup display-name fields cannot be in $select** - Any field ending in `name` or `yominame` that corresponds to a Foreign Key column (e.g., `primarycontactidname`, `parentaccountidname`, `regardingobjectidname`, `owneridname`, `createdbyname`) is an OData annotation, not a selectable column. This applies to **every** such field in the schema, not just the example. Select the FK column (e.g., `_primarycontactid_value`) and read the display name from its `@OData.Community.Display.V1.FormattedValue` annotation instead:
+12. **Lookup display-name fields cannot be in $select** - Any field ending in `name` or `yominame` that corresponds to a Foreign Key column (e.g., `primarycontactidname`, `parentaccountidname`, `regardingobjectidname`, `owneridname`, `createdbyname`) is an OData annotation, not a selectable column. This applies to **every** such field in the schema, not just the example. Select the FK column (e.g., `_primarycontactid_value`) and read the display name from its `@OData.Community.Display.V1.FormattedValue` annotation instead (the label is display text only — to filter, retrieve or open the referenced record, see **Lookup references** below):
```typescript
@@ -575,7 +705,7 @@ select: ["subject", "_regardingobjectid_value"]
const name = row["_regardingobjectid_value@OData.Community.Display.V1.FormattedValue"];
```
-13. **Setting a lookup on create/update — use `_<field>_value`, never `@odata.bind`** - To *write* a lookup via `createRow`/`updateRow`, set the FK key `_<field>_value` to a string of the form `/<entityLogicalNameSingular>(<guid>)` — singular logical name (e.g. `/account(<id>)`, `/systemuser(<id>)`). Clear it with `_<field>_value: null`. The writable row type in RuntimeTypes proves the shape — the FK column is typed as a template literal, e.g. `` _primarycontactid_value: `/contact(${string})` ``. **The trap:** the raw Dataverse Web API binds lookups with `"<PascalCaseNavProp>@odata.bind": "/<entitySetPlural>(<id>)"`. The DataAPI **silently ignores** any `@odata.bind` key (unknown property → dropped, no error) and creates the row **orphaned**, with the lookup null. Symptom: `createRow` resolves with no error, but the row isn't linked, so a child list filtered by that parent stays empty — looks like "the write didn't save." Don't mix the conventions: **DataAPI → `_field_value: "/logicalSingular(id)"`**; `@odata.bind` + `/setPlural(id)` is for raw Web API only.
+13. **Setting a lookup on create/update — use `_<field>_value`, never `@odata.bind`** - To *write* a lookup via `createRow`/`updateRow`, set the FK key `_<field>_value` to a string of the form `/<entityLogicalNameSingular>(<guid>)` — singular logical name (e.g. `/account(<id>)`, `/systemuser(<id>)`). Clear it with `_<field>_value: null`. The writable row type in RuntimeTypes proves the shape — the FK column is typed as a template literal, e.g. `` _primarycontactid_value: `/contact(${string})` ``. **The trap:** the raw Dataverse Web API binds lookups with `"<PascalCaseNavProp>@odata.bind": "/<entitySetPlural>(<id>)"`. The DataAPI **silently ignores** any `@odata.bind` key (unknown property → dropped, no error) and creates the row **orphaned**, with the lookup null. Symptom: `createRow` resolves with no error, but the row isn't linked, so a child list filtered by that parent stays empty — looks like "the write didn't save." Don't mix the conventions: **DataAPI → `_field_value: "/logicalSingular(id)"`**; `@odata.bind` + `/setPlural(id)` is for raw Web API only. On a lookup with more than one target (Customer, Owner, Regarding) the table you write is the one the user selected, kept with its id — see **Lookup references**, pitfall E.
```typescript
// WRONG — DataAPI silently drops @odata.bind → row created with null lookup (orphaned)
@@ -586,6 +716,153 @@ await dataApi.createRow("task", { subject: "Call", _regardingobjectid_value: `/a
await dataApi.updateRow("task", id, { _regardingobjectid_value: null }); // clear it
```
+### Lookup references (Customer, Owner, Regarding and every other lookup)
+
+A lookup's `_<field>_value` is a **reference** — a table and a bare id — not its label and not the first table its column can point to. Rules 12 and 13 cover the label and the write format; this section covers reading, filtering, retrieving, navigating and choosing the table to write.
+
+**What a read returns.** On a row returned by `queryTable` or `retrieveRow`, a lookup value may be a **bare GUID** or a **qualified value `/<table>(<guid>)`**. The current player has been live-verified to return the qualified form — beside a `<property>@Microsoft.Dynamics.CRM.lookuplogicalname` annotation naming the same table — for Customer lookups (both account- and contact-valued rows) and for user-owned Owner lookups. The service itself sends a bare GUID, and another player or version may pass it through, so handle both shapes everywhere. Single-target lookups, team-owned rows, Regarding and `loadMoreRows` pages were not part of that verification. A filter compares the **bare** id — `_parentcustomerid_value eq <guid>` selects the row, and the qualified value is refused with HTTP 400 — and `retrieveRow({ id })` takes the bare id (the player refuses a qualified one before sending it). Background: [lookup property data](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/query/select-columns#lookup-property-data), [multi-table lookups](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/web-api-navigation-properties#multi-table-lookups), [filtering on lookup values](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/query/filter-rows#filter-using-lookup-column-property-values).
+
+**Normalize before you consume.** Copy this helper **unchanged** into the page, at the top level beside the other helpers, and pass every lookup value through it before you filter, retrieve, compare or navigate. Take `property` and `allowedTargets` from the plan's `#### Lookup metadata` record for that column — `allowedTargets` is its **complete** target set, never a subset you chose — never from user input.
+
+```typescript
+type LookupReference = { table: string; id: string };
+type LookupNormalization =
+ | { state: 'unset' }
+ | { state: 'resolved'; reference: LookupReference }
+ | { state: 'needs-target'; id: string }
+ | { state: 'invalid' };
+
+const LOOKUP_GUID = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
+const LOOKUP_QUALIFIED = /^\/([a-z_][a-z0-9_]*)\(([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})\)$/;
+
+function normalizeLookupReference(
+ row: unknown,
+ property: string,
+ allowedTargets: readonly string[],
+): LookupNormalization {
+ if (typeof row !== 'object' || row === null || Array.isArray(row) || allowedTargets.length === 0) return { state: 'invalid' };
+ const record = row as Record<string, unknown>;
+ if (!Object.prototype.hasOwnProperty.call(record, property)) return { state: 'invalid' };
+ const raw = record[property];
+ if (raw === null) return { state: 'unset' };
+ if (typeof raw !== 'string') return { state: 'invalid' };
+ const value = raw.trim();
+ const qualified = LOOKUP_QUALIFIED.exec(value);
+ if (!qualified && !LOOKUP_GUID.test(value)) return { state: 'invalid' };
+ const prefix = qualified ? qualified[1] : undefined;
+ const id = (qualified ? qualified[2] : value).toLowerCase();
+ if (prefix !== undefined && !allowedTargets.includes(prefix)) return { state: 'invalid' };
+ const annotationKey = `${property}@Microsoft.Dynamics.CRM.lookuplogicalname`;
+ let annotation: string | undefined;
+ if (Object.prototype.hasOwnProperty.call(record, annotationKey)) {
+ const named = record[annotationKey];
+ if (typeof named !== 'string' || !allowedTargets.includes(named)) return { state: 'invalid' };
+ annotation = named;
+ }
+ if (annotation !== undefined && prefix !== undefined && annotation !== prefix) return { state: 'invalid' };
+ const table = annotation ?? prefix ?? (allowedTargets.length === 1 ? allowedTargets[0] : undefined);
+ return table === undefined ? { state: 'needs-target', id } : { state: 'resolved', reference: { table, id } };
+}
+```
+
+What each state means for the page:
+
+- **`resolved`** — a validated pair. Use `reference.id` for filters, `retrieveRow({ id })`, comparisons and `entityId`, and `reference.table` for the target. Only a write rebuilds `/<table>(<id>)` (pair E).
+- **`unset`** — an explicit `null`: the row has no link. A normal empty state, not an error.
+- **`needs-target`** — a valid bare id with no table evidence on a lookup that has more than one target. Show the label with target-dependent actions disabled; a separate, user-started "Resolve reference" may run the bounded resolution read described below.
+- **`invalid`** — a missing or malformed value, or contradictory evidence (a prefix or annotation outside the targets, or the two disagreeing). Show the label with target-dependent actions disabled. Never resolve it by any fallback.
+
+The helper never infers a table from the FormattedValue, from a GUID being unique, from the order of the targets, or from the `@Microsoft.Dynamics.CRM.associatednavigationproperty` annotation (Owner's is the shared `ownerid`; never split a navigation name on `_` to find a table). It holds no hook, state, I/O, logging or retry. Do not log during render.
+
+#### Five pitfalls, WRONG and CORRECT
+
+The examples use a Customer lookup (`opportunity.customerid` → account, contact). Use the names your schema and the plan's lookup record verify, adapted to the column's actual target set.
+
+**A. Read and consume a normalized identity.**
+
+```typescript
+// WRONG: today's qualified read value is neither a filter operand nor a retrieveRow id.
+const customerId = row['_customerid_value'];
+const filter = `_customerid_value eq ${customerId}`;
+await dataApi.retrieveRow('account', { id: customerId });
+
+// CORRECT: normalize before consuming; this branch requires a resolved pair.
+const normalized = normalizeLookupReference(row, '_customerid_value', ['account', 'contact']);
+if (normalized.state !== 'resolved') return;
+const reference = normalized.reference;
+// reference.id is bare; reference.table is metadata-validated, not assumed account.
+```
+
+Retrieve only a target table registered in this page's verified schema, using its actual table and `reference.id`. Display the FormattedValue, never the raw or normalized id. An account-specific predicate must still constrain the target as in B and C: extracting the bare id alone is not a target scope.
+
+**B. Select the relationship and roll-up meaning before generating a filter.**
+
+```typescript
+// WRONG: silently deciding what "opportunities for this account" means.
+filter: `_parentaccountid_value eq ${accountId}`
+
+// CORRECT only after the plan's assumption chose direct Customer-to-account and metadata verified the path.
+filter: `customerid_account/accountid eq ${reference.id}`
+```
+
+The CORRECT branch also requires `reference.table === 'account'`. If the maker chose `parentaccountid`, use it instead. Rolling up rows whose customer is one of the account's contacts is a separate recorded decision that needs the contact-to-account relationship — never an `or` across both columns. A GUID operand is validated, bare and unquoted.
+
+**C. Non-id filters and name searches do not implicitly select a target.**
+
+```typescript
+// WRONG for an account-only view: includes contact customers too.
+filter: '_customerid_value ne null'
+
+// CORRECT for that approved view, with the metadata-supplied concrete path.
+filter: 'customerid_account/accountid ne null'
+
+// CORRECT account-only name search: the target's name column is verified separately.
+const escaped = searchText.replace(/'/g, "''");
+const filter = `customerid_account/accountid ne null and contains(customerid_account/name,'${escaped}')`;
+```
+
+Matching the formatted label alone is also WRONG as an account discriminator. Never filter on annotation keys or on invented lookup-name columns. For a view that explicitly covers every target, `_customerid_value ne null` is correct. A label search across all targets is allowed only when it is described as a search of the loaded rows, not of all matches or totals. If the service refuses a typed path, stop the operation and report a read failure — never post-filter the first page and present it as complete.
+
+**D. Navigate to the resolved target with the bare id.**
+
+```typescript
+// WRONG: a Customer row may refer to a contact, and its raw value may be qualified.
+await Xrm.Navigation.navigateTo({ pageType: 'entityrecord', entityName: 'account', entityId: row['_customerid_value'] });
+
+// CORRECT after the resolved-state guard:
+await Xrm.Navigation.navigateTo({ pageType: 'entityrecord', entityName: reference.table, entityId: reference.id });
+```
+
+An unset, invalid or needs-target reference cannot call navigation. Catch a rejected `navigateTo` and call `reportPageError(PAGE_NAME, 'openCustomerRecord', undefined, error, 'read')`. Never build a raw URL or infer the target from a label or from the metadata order.
+
+**E. Write the selected target; rebuild the qualified form only at the write boundary.**
+
+```typescript
+// WRONG: the contact selected by the maker becomes an account link.
+await dataApi.updateRow('opportunity', opportunityId, { _customerid_value: `/account(${selected.id})` });
+
+// CORRECT after validating selected.table and its bare id against the picker target union:
+const link: `/account(${string})` | `/contact(${string})` = selected.table === 'account'
+ ? `/account(${selected.id})`
+ : `/contact(${selected.id})`;
+await dataApi.updateRow('opportunity', opportunityId, { _customerid_value: link });
+```
+
+The two-way formatter is legal only after every selection outside account and contact has been rejected. Keep the table in the picker's state, even for equal labels or for one GUID in two tables. Clear the link with `_customerid_value: null` — never an empty string, a plural entity set or `@odata.bind`. Honor read-only fields; no automatic Owner reassignment is introduced. The source row's `opportunityId` is a validated bare id too. A failed write calls `reportPageError(PAGE_NAME, 'changeCustomer', undefined, error, 'write')` with **no retry argument**: never retry an unknown outcome automatically. Custom API lookup inputs keep their own `{ entityName, id }` contract.
+
+#### When a bare id has no table evidence
+
+Today's qualified values normally resolve with no extra read even when the annotation is absent. The following applies **only** to `needs-target` — never to `invalid` evidence:
+
+1. Prefer a target already proven by the exact typed source-relationship query that returned this same source row and value.
+2. For Owner, use the verified `_owninguser_value` / `_owningteam_value` only when both were loaded, exactly one is non-null, and its **normalized** bare id equals the owner value's id (normalize each with its own target set — a raw string comparison is wrong when one is qualified). Missing or malformed values, both or neither non-null, or a mismatch stay unresolved. Never build an owner navigation path.
+3. Otherwise, for an explicitly opened row and a bounded approved target subset, query the **source table** restricted by its primary key and a concrete target navigation predicate, with `pageSize: 1` — for a Customer account test, `opportunityid eq <source id> and customerid_account/accountid eq <bare lookup id>`; the contact test uses the verified contact path. Only one successful exact match proves the target.
+4. Never retrieve account, then contact, by the same GUID and keep the first that succeeds. Zero or several matches, or unavailable discriminators, mean unresolved. A refused query is an error — report it with `reportPageError(…, 'read')` — never zero matches, a cached unknown, a weakened predicate or a raw `fetch`.
+
+Use the page's existing in-flight de-duplication and cache rules for these reads. Cache a successful resolution by source table, source row id, lookup column and value snapshot — not by the lookup GUID alone — and invalidate it on a lookup write or a refresh. A missing-evidence unknown may be remembered for that snapshot; a thrown read is never cached as unknown, no match, rows or success. Ignore a stale or unmounted result. Regarding follows the same algorithm: never fan out across its targets on mount.
+
+**Failures.** A requested resolution, read or navigation that fails is reported as `'read'`; a failed lookup write as `'write'` with no retry. Pass the thrown error or a fixed diagnostic `Error` — never a row, a reference pair or a returned success payload. The four states above are classifications, not error kinds.
+
### DataGrid Requirements
- Import `createTableColumn` from Fluent UI V9
- Define all columns using `createTableColumn`
@@ -633,6 +910,39 @@ What you can rely on from RuntimeTypes:
- `BaseUxAgentDataApi<TR, ER>` — the dataApi interface with `createRow`,
`updateRow`, `deleteRow`, `retrieveRow`, `queryTable`, `getChoices`
+### Dialog output (`setPageOutput`)
+
+A page opened as a dialog can return a value to the page that opened it. The runtime's data API
+has `setPageOutput(value: unknown): void`. It stores the value and does **not** close the dialog.
+Then `Xrm.Navigation.navigateBack()` closes the dialog, and the caller's `navigateTo` promise
+resolves with `{ returnValue: <the value> }`. A dialog closed without `setPageOutput` gives
+`returnValue: undefined`. The method is synchronous: do not `await` it.
+
+The generated `RuntimeTypes.ts` does **not** declare `setPageOutput`, so
+`dataApi.setPageOutput(...)` fails type checking with "Property 'setPageOutput' does not exist on
+type 'UxAgentDataApi'". Use this narrow typed intersection. Do not use `any`, and do not change
+`RuntimeTypes.ts`:
+
+```typescript
+// In the dialog page: return the selection, then close.
+const outputApi = dataApi as typeof dataApi & { setPageOutput(value: unknown): void };
+if (typeof outputApi.setPageOutput === "function") outputApi.setPageOutput({ action: "selected", accountId: selectedId });
+(window as any).Xrm.Navigation.navigateBack();
+```
+
+```typescript
+// In the calling page: open the dialog (target 2) and read what it returned.
+const result = await (window as any).Xrm.Navigation.navigateTo(
+ { pageType: "generative", pageId: targetPageId, data: { mode: "pick" } },
+ { target: 2, position: 1, width: { value: 50, unit: "%" } },
+);
+const output = result?.returnValue; // undefined when the dialog was closed without an output
+```
+
+The caller reads `returnValue` as an `unknown`: check its shape before you use it. Call
+`setPageOutput` only in a page that is opened as a dialog, and only when the user completes the
+dialog's action. Do not call it on mount.
+
### Connector DataAPI (optional — only when the plan has Connector Bindings)
When the plan's `## Connector Bindings` is non-empty, the page may call Power
@@ -695,8 +1005,11 @@ const contactName = row["[email protected]
const choices = await dataApi.getChoices("table1-status");
```
-For lookups: `_<field>_value` is the GUID — never display it. Always read the
-paired `[email protected]` for the label.
+For lookups: a `_<field>_value` read value may be a bare GUID or `/<table>(<guid>)` — the current player has
+been verified to return the qualified form for Customer and user-owned Owner lookups. Never display it: read the
+paired `[email protected]` for the label. Before filtering, retrieving or
+navigating, normalize it with `normalizeLookupReference`, which validates the annotation and the prefix against
+the column's metadata targets and returns the table and the bare id (see "Lookup references" under DataAPI Rules).
---
@@ -720,21 +1033,261 @@ import { processData } from "@package";
```
### 2. Missing Error Handling
-Always wrap async dataApi calls in try-catch.
-```typescript
-// Error: Unhandled promise rejection
-const data = await dataApi.queryTable("table1", {});
-
-// Fix: Wrap in try-catch
-try {
- const data = await dataApi.queryTable("table1", {});
- setRecords(data.rows);
-} catch (error) {
- console.error("Failed to load data:", error);
- setErrorMessage("Unable to load data. Please try again.");
+A `try`/`catch` that logs the thrown value and sets an ad-hoc string is not enough: it logs whatever
+record text the host put in the message, drops the error code, and leaves each page reporting
+failures its own way. Every failed data operation goes through the page's one top-level
+`reportPageError`, the view it returns goes into that operation's error state, and `PageErrorBar`
+renders it. The whole page renders inside one `PageErrorBoundary`.
+
+Copy the block below unchanged — the reporter, the error copy, the bar, the boundary and the
+default export — and set `PAGE_NAME` to the plan's display name for the page (a fixed literal,
+never the file name). `PageBody` is where the page itself lives: its hooks, state and handlers.
+Render each operation's `<PageErrorBar error={…} />` in the component's final returned JSX, outside any
+condition, ternary or list: the bar shows nothing until there is an error, and a bar that may not render
+cannot show one.
+`reportPageError(pageName, operation, code, message, kind, retry?, appInsights?)` takes five
+required arguments:
+
+- `operation` — one stable literal per logical operation (`'loadAccounts'`, `'createAccount'`),
+ shared by its success and failure branches; never built from a record.
+- `code` — the host's error code when a returned result carries one (`res.error?.code`), otherwise
+ `undefined`.
+- `message` — the result's `res.error?.message`, or the caught value itself (`error`). Never pass
+ the result object, its outputs, a row, a lookup reference or an identity, and never change the
+ result's `error` or the caught value (assign, write a field, alias) before reporting it.
+- `kind` — a string literal the caller decides from the operation, never from the code or the
+ wording:
+
+| Operation or result | `kind` | `retry` (sixth argument) |
+|---|---|---|
+| `queryTable`, `retrieveRow`, `getChoices`, `queryConnectorTable`, `listBoundActions`; a rejected navigation | `'read'` | a named reload, or none |
+| `createRow`, `updateRow`, `deleteRow`, `executeAction`; a connector operation not known to be a read | `'write'` | none |
+| a Custom API result with `res.indeterminate` or `res.error?.code === 'indeterminate'` (check both first) | `'indeterminate'` | none |
+| a failed Custom API result with `res.error?.code === 'network'`, after both indeterminate checks | `'network'` | a named manual retry only |
+| a WhoAmI or RetrieveVersion failure | `'read'` | none |
+| a render crash (the boundary) | `'render'` | none |
+
+The reporter logs one line, `[<page name>] <operation> failed` with `{ code, message }` (the code at
+most 80 characters, the message its first line and at most 300), and returns
+`{ operation, message, fallbackKey, code?, kind, retry? }`. It reads only `code`, `errorCode`,
+`message`, `error.code` and `error.message` of a thrown value, never logs the value itself, never
+sets state and never calls `retry`. An indeterminate or render failure shows only its fixed copy and
+never offers a retry, whatever its code says. Nothing retries automatically: a retry is a button the
+user presses.
+
+Store the view in the same single state update as the operation's other results (Critical Rule 14):
+error state is `PageErrorView | null`, never a string. Only that operation's own success, or an
+explicit dismissal, clears it — another operation's success must not erase it. A failed form stays
+visible; a failed list may show the error above its empty state. A null lookup, zero rows or an
+absent optional value is a normal state, not a failure. The boundary catches render crashes only —
+not rejected promises or event handlers — and has no reset; never call `PageBody(props)` yourself.
+
+```tsx
+import * as React from 'react';
+import { Button, Input, MessageBar, MessageBarActions, MessageBarBody } from '@fluentui/react-components';
+import type { GeneratedComponentProps } from './RuntimeTypes';
+
+type PageErrorKind = 'read' | 'write' | 'indeterminate' | 'network' | 'render';
+type PageErrorView = {
+ operation: string;
+ message: string;
+ fallbackKey: string;
+ code?: string;
+ kind: PageErrorKind;
+ retry?: () => void;
+};
+type PageErrorTelemetry = {
+ trackException?: (error: unknown, properties?: Record<string, unknown>) => void;
+};
+
+// The plan's display name for this page: a fixed literal, not the file name.
+const PAGE_NAME = 'Account Overview';
+
+// The error copy of an English-only page. A localized page keeps these keys in its translations
+// dictionary instead (references/localization.md). Keep the built-in keys only on a page that calls
+// WhoAmI or RetrieveVersion.
+const ERROR_COPY: Record<string, string> = {
+ 'error.read': 'Unable to load data. Please try again.',
+ 'error.write': 'The change could not be saved. Refresh before trying again.',
+ 'error.network': 'The request did not go through. You can try again.',
+ 'error.indeterminate': "We couldn't confirm this completed — refresh before retrying.",
+ 'error.render': 'This page hit a problem and could not render. Refresh the page.',
+ 'error.tryAgain': 'Try again',
+ 'error.builtinFailed': 'The operation failed. No result was displayed.',
+ 'error.builtinUnavailable': 'The selected operation is unavailable in this environment or player. No fallback was attempted.',
+ 'error.builtinUnexpected': 'The operation returned an unexpected response. No result was displayed.',
+ 'error.builtinUnsupported': 'This page player cannot call built-in Dataverse operations.',
+};
+
+function translate(key: string): string {
+ return ERROR_COPY[key] || key;
+}
+
+// The page's one error reporter. It logs bounded diagnostics once and returns the view the failed
+// operation stores; it never sets state, never calls retry, and reads only the named fields of a
+// thrown value, each on its own, so a throwing getter leaves that one field empty.
+function reportPageError(
+ pageName: string,
+ operation: string,
+ code: unknown,
+ message: unknown,
+ kind: PageErrorKind,
+ retry?: () => void,
+ appInsights?: PageErrorTelemetry,
+): PageErrorView {
+ const fields: Record<string, unknown> = {};
+ for (const path of ['code', 'errorCode', 'message', 'error.code', 'error.message']) {
+ try {
+ let value: unknown = message;
+ for (const part of path.split('.')) {
+ value = value !== null && typeof value === 'object' ? (value as Record<string, unknown>)[part] : undefined;
+ }
+ fields[path] = value;
+ } catch {
+ fields[path] = undefined;
+ }
+ }
+ let normalizedCode = '';
+ for (const candidate of [code, fields['code'], fields['errorCode'], fields['error.code']]) {
+ const text = typeof candidate === 'string' ? candidate : typeof candidate === 'number' && Number.isFinite(candidate) ? String(candidate) : '';
+ normalizedCode = text.replace(/[\s\u0000-\u001f\u007f-\u009f]+/g, ' ').trim().slice(0, 80);
+ if (normalizedCode) break;
+ }
+ let normalizedMessage = '';
+ for (const candidate of [message, fields['message'], fields['error.message']]) {
+ const line = typeof candidate === 'string' ? candidate.trim().split(/[\r\n\u2028\u2029]/)[0].replace(/[\s\u0000-\u001f\u007f-\u009f]+/g, ' ').trim() : '';
+ if (!line || /^\[object [^\]]*\]$/.test(line) || /^at\s.*(?::\d+:\d+\)?|\((?:native|<anonymous>)\))$/.test(line)) continue;
+ normalizedMessage = line.length > 300 ? line.slice(0, 299) + '\u2026' : line;
+ break;
+ }
+ console.error('[' + String(pageName).replace(/[\r\n\]]/g, '') + '] ' + operation + ' failed', { code: normalizedCode, message: normalizedMessage });
+ const quiet = kind === 'indeterminate' || kind === 'render';
+ const view: PageErrorView = { operation, message: quiet ? '' : normalizedMessage, fallbackKey: 'error.' + kind, kind };
+ if (normalizedCode) view.code = normalizedCode;
+ if (typeof retry === 'function' && (kind === 'read' || kind === 'network')) view.retry = retry;
+ return view;
+}
+
+function PageErrorBar(props: { error: PageErrorView | null }) {
+ const { error } = props;
+ if (!error) return null;
+ return (
+ <MessageBar intent="error">
+ <MessageBarBody>{error.message || translate(error.fallbackKey)}</MessageBarBody>
+ {error.retry && (
+ <MessageBarActions>
+ <Button onClick={error.retry}>{translate('error.tryAgain')}</Button>
+ </MessageBarActions>
+ )}
+ </MessageBar>
+ );
+}
+
+// The page's one class component: it catches a render crash below it and shows a fixed message.
+class PageErrorBoundary extends React.Component<
+ { children: React.ReactNode; appInsights?: PageErrorTelemetry },
+ { failed: boolean }
+> {
+ public state = { failed: false };
+
+ public static getDerivedStateFromError(): { failed: boolean } {
+ return { failed: true };
+ }
+
+ public componentDidCatch(error: Error): void {
+ reportPageError(PAGE_NAME, 'render', undefined, error, 'render');
+ }
+
+ public render(): React.ReactNode {
+ if (this.state.failed) {
+ return (
+ <MessageBar intent="error">
+ <MessageBarBody>{translate('error.render')}</MessageBarBody>
+ </MessageBar>
+ );
+ }
+ return this.props.children;
+ }
+}
+
+function PageBody(props: GeneratedComponentProps) {
+ const { dataApi } = props;
+ const [name, setName] = React.useState('');
+ const [save, setSave] = React.useState<{ saving: boolean; error: PageErrorView | null }>({ saving: false, error: null });
+ const pending = React.useRef(false);
+
+ async function createAccount() {
+ if (pending.current) return;
+ pending.current = true;
+ setSave({ saving: true, error: null });
+ try {
+ await dataApi.createRow('account', { name });
+ setSave({ saving: false, error: null });
+ } catch (error) {
+ setSave({ saving: false, error: reportPageError(PAGE_NAME, 'createAccount', undefined, error, 'write') });
+ } finally {
+ pending.current = false;
+ }
+ }
+
+ return (
+ <div>
+ <PageErrorBar error={save.error} />
+ <Input aria-label="Account name" value={name} onChange={(_, data) => setName(data.value)} />
+ <Button appearance="primary" disabled={save.saving || !name.trim()} onClick={() => void createAccount()}>
+ Create account
+ </Button>
+ </div>
+ );
}
+
+const GeneratedComponent = (props: GeneratedComponentProps) => (
+ <PageErrorBoundary>
+ <PageBody {...props} />
+ </PageErrorBoundary>
+);
+
+export default GeneratedComponent;
```
+The boundary uses `React.Component`; on a page that imports React only by name, import `Component`
+and `ReactNode` from `'react'` and write `extends Component<…>`. On a page where no operation passes
+a retry, leave out the bar's `error.retry` part and the `MessageBarActions` import.
+
+**Failure telemetry** — only when the dispatch says `Telemetry: enabled` **and** the maker asked to
+report failures (`references/page-telemetry.md`). Insert these lines immediately after the
+reporter's `console.error` line, and pass `props.appInsights` as the seventh argument only at the
+call sites the request covers (render crashes: `<PageErrorBoundary appInsights={props.appInsights}>`
+and `reportPageError(PAGE_NAME, 'render', undefined, error, 'render', undefined, this.props.appInsights)`
+in `componentDidCatch`). It sends a new `<operation> failed` error with approved properties only —
+never the thrown value, host text, a row or an identity — and a recognized code (a documented
+Custom API code or a Dataverse `0x` error code) as `statusCode`; any other code stays in the log.
+
+```tsx
+ appInsights?.trackException?.(new Error(operation + ' failed'), {
+ outcome: 'failure',
+ category: kind === 'render' ? 'errorBoundary' : 'page',
+ source: operation,
+ ...(/^(?:wrong_operation_kind|invalid_parameter|invalid_bound_to|not_bound|not_permitted|not_enabled|indeterminate|network|0x[0-9a-fA-F]{8})$/.test(normalizedCode) ? { statusCode: normalizedCode } : {}),
+ });
+```
+
+**The complete shape of each operation** — each reference shows a whole `PageBody` built on this block:
+a cached on-mount read (`references/data-caching.md`), a Custom API Action and Function
+(`references/custom-api.md`), the two built-in operations (`references/dataverse-operations.md`),
+connector reads and operations (`references/connectors.md`), the usersettings read of a localized page
+(`references/localization.md`) and authorized failure telemetry (`references/page-telemetry.md`). Several
+reads that load together either go through named helpers that each catch, report and return
+`{ error }` — awaited with `Promise.all`, then one state update — or through `Promise.allSettled` with a
+`status === 'rejected'` branch that reports each item's `reason` before the one update. A single `catch`
+around `Promise.all` hides every failure after the first.
+
+**What the eval check reads, and what it does not.** The eval suite does not grade a page's error handling
+yet: no check proves that every failure of a page reaches `reportPageError`, that the view it returns reaches a
+rendered `PageErrorBar`, that a request is current, or that a retry is safe. Write each page to this section
+as it stands — the block copied unchanged, each report a statement of its failure path's own block, a literal
+kind that matches what failed — including `loadMoreRows` failures.
+
### 3. Inline Styles Instead of makeStyles
Use `makeStyles` with tokens.
```typescript
diff --git a/plugins/model-apps/samples/1-account-grid.tsx b/plugins/model-apps/samples/1-account-grid.tsx
index 09d0a7b78..c159d3df2 100644
--- a/plugins/model-apps/samples/1-account-grid.tsx
+++ b/plugins/model-apps/samples/1-account-grid.tsx
@@ -1,5 +1,112 @@
import React, { useState } from "react";
-import { DataGrid, DataGridHeader, DataGridBody, DataGridRow, DataGridCell, DataGridHeaderCell, TableCellLayout, createTableColumn, Text, Input } from "@fluentui/react-components";
+import { DataGrid, DataGridHeader, DataGridBody, DataGridRow, DataGridCell, DataGridHeaderCell, TableCellLayout, createTableColumn, Text, Input, MessageBar, MessageBarBody } from "@fluentui/react-components";
+
+// ---------- Page errors ----------
+// The page error block of references/rules.md ("Missing Error Handling"), copied unchanged: every failed data
+// operation goes through reportPageError, PageErrorBar shows the view it returns, and the page renders inside
+// PageErrorBoundary.
+
+type PageErrorKind = 'read' | 'write' | 'indeterminate' | 'network' | 'render';
+type PageErrorView = {
+ operation: string;
+ message: string;
+ fallbackKey: string;
+ code?: string;
+ kind: PageErrorKind;
+ retry?: () => void;
+};
+type PageErrorTelemetry = {
+ trackException?: (error: unknown, properties?: Record<string, unknown>) => void;
+};
+
+// The plan's display name for this page: a fixed literal, not the file name.
+const PAGE_NAME = 'Account Grid';
+
+// The error copy of an English-only page. A localized page keeps these keys in its translations dictionary instead.
+const ERROR_COPY: Record<string, string> = {
+ 'error.read': 'Unable to load data. Please try again.',
+ 'error.write': 'The change could not be saved. Refresh before trying again.',
+ 'error.network': 'The request did not go through. You can try again.',
+ 'error.indeterminate': "We couldn't confirm this completed — refresh before retrying.",
+ 'error.render': 'This page hit a problem and could not render. Refresh the page.',
+ 'error.tryAgain': 'Try again',
+};
+
+function translate(key: string): string {
+ return ERROR_COPY[key] || key;
+}
+
+// The page's one error reporter. It logs bounded diagnostics once and returns the view the failed
+// operation stores; it never sets state, never calls retry, and reads only the named fields of a
+// thrown value, each on its own, so a throwing getter leaves that one field empty.
+function reportPageError(
+ pageName: string,
+ operation: string,
+ code: unknown,
+ message: unknown,
+ kind: PageErrorKind,
+ retry?: () => void,
+ appInsights?: PageErrorTelemetry,
+): PageErrorView {
+ const fields: Record<string, unknown> = {};
+ for (const path of ['code', 'errorCode', 'message', 'error.code', 'error.message']) {
+ try {
+ let value: unknown = message;
+ for (const part of path.split('.')) {
+ value = value !== null && typeof value === 'object' ? (value as Record<string, unknown>)[part] : undefined;
+ }
+ fields[path] = value;
+ } catch {
+ fields[path] = undefined;
+ }
+ }
+ let normalizedCode = '';
+ for (const candidate of [code, fields['code'], fields['errorCode'], fields['error.code']]) {
+ const text = typeof candidate === 'string' ? candidate : typeof candidate === 'number' && Number.isFinite(candidate) ? String(candidate) : '';
+ normalizedCode = text.replace(/[\s\u0000-\u001f\u007f-\u009f]+/g, ' ').trim().slice(0, 80);
+ if (normalizedCode) break;
+ }
+ let normalizedMessage = '';
+ for (const candidate of [message, fields['message'], fields['error.message']]) {
+ const line = typeof candidate === 'string' ? candidate.trim().split(/[\r\n\u2028\u2029]/)[0].replace(/[\s\u0000-\u001f\u007f-\u009f]+/g, ' ').trim() : '';
+ if (!line || /^\[object [^\]]*\]$/.test(line) || /^at\s.*(?::\d+:\d+\)?|\((?:native|<anonymous>)\))$/.test(line)) continue;
+ normalizedMessage = line.length > 300 ? line.slice(0, 299) + '\u2026' : line;
+ break;
+ }
+ console.error('[' + String(pageName).replace(/[\r\n\]]/g, '') + '] ' + operation + ' failed', { code: normalizedCode, message: normalizedMessage });
+ const quiet = kind === 'indeterminate' || kind === 'render';
+ const view: PageErrorView = { operation, message: quiet ? '' : normalizedMessage, fallbackKey: 'error.' + kind, kind };
+ if (normalizedCode) view.code = normalizedCode;
+ if (typeof retry === 'function' && (kind === 'read' || kind === 'network')) view.retry = retry;
+ return view;
+}
+
+// The page's one class component: it catches a render crash below it and shows a fixed message.
+class PageErrorBoundary extends React.Component<
+ { children: React.ReactNode; appInsights?: PageErrorTelemetry },
+ { failed: boolean }
+> {
+ public state = { failed: false };
+
+ public static getDerivedStateFromError(): { failed: boolean } {
+ return { failed: true };
+ }
+
+ public componentDidCatch(error: Error): void {
+ reportPageError(PAGE_NAME, 'render', undefined, error, 'render');
+ }
+
+ public render(): React.ReactNode {
+ if (this.state.failed) {
+ return (
+ <MessageBar intent="error">
+ <MessageBarBody>{translate('error.render')}</MessageBarBody>
+ </MessageBar>
+ );
+ }
+ return this.props.children;
+ }
+}
type Account = { id: string; name: string; address1_city: string; address1_stateorprovince: string; address1_postalcode: string; address1_country: string; telephone1: string; };
@@ -11,7 +118,12 @@ const sampleAccounts: Account[] = [
{ id: "5", name: "Initech", address1_city: "Phoenix", address1_stateorprovince: "AZ", address1_postalcode: "85001", address1_country: "USA", telephone1: "333-333-3333" },
];
-const GeneratedComponent = () => {
+// Mock page: no RuntimeTypes import (not generated for mock pages), so it declares its own props.
+type Props = { dataApi?: unknown; pageInput?: { id?: string } };
+
+function PageBody(props: Props) {
+ const { pageInput } = props;
+ void pageInput;
const [accounts] = useState<Account[]>(sampleAccounts);
const [filterText, setFilterText] = useState("");
const filteredAccounts = accounts.filter(acc => {
@@ -56,6 +168,12 @@ const GeneratedComponent = () => {
</div>
</div>
);
-};
+}
+
+const GeneratedComponent = (props: Props) => (
+ <PageErrorBoundary>
+ <PageBody {...props} />
+ </PageErrorBoundary>
+);
export default GeneratedComponent;
diff --git a/plugins/model-apps/samples/10-detail-with-pageinput.tsx b/plugins/model-apps/samples/10-detail-with-pageinput.tsx
index 4ce159fd5..6574c0e3c 100644
--- a/plugins/model-apps/samples/10-detail-with-pageinput.tsx
+++ b/plugins/model-apps/samples/10-detail-with-pageinput.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState } from 'react';
+import React, { useEffect, useState } from 'react';
import type {
TableRow,
ReadableTableRow,
@@ -12,9 +12,128 @@ import {
Button,
Card,
Divider,
+ MessageBar,
+ MessageBarBody,
} from '@fluentui/react-components';
import { ArrowLeftRegular } from '@fluentui/react-icons';
+// ---------- Page errors ----------
+// The page error block of references/rules.md ("Missing Error Handling"), copied unchanged: every failed data
+// operation goes through reportPageError, PageErrorBar shows the view it returns, and the page renders inside
+// PageErrorBoundary.
+
+type PageErrorKind = 'read' | 'write' | 'indeterminate' | 'network' | 'render';
+type PageErrorView = {
+ operation: string;
+ message: string;
+ fallbackKey: string;
+ code?: string;
+ kind: PageErrorKind;
+ retry?: () => void;
+};
+type PageErrorTelemetry = {
+ trackException?: (error: unknown, properties?: Record<string, unknown>) => void;
+};
+
+// The plan's display name for this page: a fixed literal, not the file name.
+const PAGE_NAME = 'Contact Detail';
+
+// The error copy of an English-only page. A localized page keeps these keys in its translations dictionary instead.
+const ERROR_COPY: Record<string, string> = {
+ 'error.read': 'Unable to load data. Please try again.',
+ 'error.write': 'The change could not be saved. Refresh before trying again.',
+ 'error.network': 'The request did not go through. You can try again.',
+ 'error.indeterminate': "We couldn't confirm this completed — refresh before retrying.",
+ 'error.render': 'This page hit a problem and could not render. Refresh the page.',
+ 'error.tryAgain': 'Try again',
+};
+
+function translate(key: string): string {
+ return ERROR_COPY[key] || key;
+}
+
+// The page's one error reporter. It logs bounded diagnostics once and returns the view the failed
+// operation stores; it never sets state, never calls retry, and reads only the named fields of a
+// thrown value, each on its own, so a throwing getter leaves that one field empty.
+function reportPageError(
+ pageName: string,
+ operation: string,
+ code: unknown,
+ message: unknown,
+ kind: PageErrorKind,
+ retry?: () => void,
+ appInsights?: PageErrorTelemetry,
+): PageErrorView {
+ const fields: Record<string, unknown> = {};
+ for (const path of ['code', 'errorCode', 'message', 'error.code', 'error.message']) {
+ try {
+ let value: unknown = message;
+ for (const part of path.split('.')) {
+ value = value !== null && typeof value === 'object' ? (value as Record<string, unknown>)[part] : undefined;
+ }
+ fields[path] = value;
+ } catch {
+ fields[path] = undefined;
+ }
+ }
+ let normalizedCode = '';
+ for (const candidate of [code, fields['code'], fields['errorCode'], fields['error.code']]) {
+ const text = typeof candidate === 'string' ? candidate : typeof candidate === 'number' && Number.isFinite(candidate) ? String(candidate) : '';
+ normalizedCode = text.replace(/[\s\u0000-\u001f\u007f-\u009f]+/g, ' ').trim().slice(0, 80);
+ if (normalizedCode) break;
+ }
+ let normalizedMessage = '';
+ for (const candidate of [message, fields['message'], fields['error.message']]) {
+ const line = typeof candidate === 'string' ? candidate.trim().split(/[\r\n\u2028\u2029]/)[0].replace(/[\s\u0000-\u001f\u007f-\u009f]+/g, ' ').trim() : '';
+ if (!line || /^\[object [^\]]*\]$/.test(line) || /^at\s.*(?::\d+:\d+\)?|\((?:native|<anonymous>)\))$/.test(line)) continue;
+ normalizedMessage = line.length > 300 ? line.slice(0, 299) + '\u2026' : line;
+ break;
+ }
+ console.error('[' + String(pageName).replace(/[\r\n\]]/g, '') + '] ' + operation + ' failed', { code: normalizedCode, message: normalizedMessage });
+ const quiet = kind === 'indeterminate' || kind === 'render';
+ const view: PageErrorView = { operation, message: quiet ? '' : normalizedMessage, fallbackKey: 'error.' + kind, kind };
+ if (normalizedCode) view.code = normalizedCode;
+ if (typeof retry === 'function' && (kind === 'read' || kind === 'network')) view.retry = retry;
+ return view;
+}
+
+function PageErrorBar(props: { error: PageErrorView | null }) {
+ const { error } = props;
+ if (!error) return null;
+ return (
+ <MessageBar intent="error">
+ <MessageBarBody>{error.message || translate(error.fallbackKey)}</MessageBarBody>
+ </MessageBar>
+ );
+}
+
+// The page's one class component: it catches a render crash below it and shows a fixed message.
+class PageErrorBoundary extends React.Component<
+ { children: React.ReactNode; appInsights?: PageErrorTelemetry },
+ { failed: boolean }
+> {
+ public state = { failed: false };
+
+ public static getDerivedStateFromError(): { failed: boolean } {
+ return { failed: true };
+ }
+
+ public componentDidCatch(error: Error): void {
+ reportPageError(PAGE_NAME, 'render', undefined, error, 'render');
+ }
+
+ public render(): React.ReactNode {
+ if (this.state.failed) {
+ return (
+ <MessageBar intent="error">
+ <MessageBarBody>{translate('error.render')}</MessageBarBody>
+ </MessageBar>
+ );
+ }
+ return this.props.children;
+ }
+}
+
// Sample: detail page receiving pageInput from a sibling list page.
// Demonstrates:
// - pageInput.entityName + pageInput.recordId derived SYNCHRONOUSLY from
@@ -27,6 +146,8 @@ import { ArrowLeftRegular } from '@fluentui/react-icons';
// detail-page pattern) so the host double-mount fetches once and return
// visits render instantly; readiness-only deps (never `dataApi`)
// - Lookup formatted-value access via @OData.Community.Display.V1.FormattedValue
+// - Rule 22: a failed read goes through reportPageError and PageErrorBar; the page
+// renders inside PageErrorBoundary
type ContactRow = TableRow<{
readonly contactid: string;
@@ -92,12 +213,6 @@ const useStyles = makeStyles({
textAlign: 'center',
color: tokens.colorNeutralForeground2,
},
- errorBanner: {
- padding: tokens.spacingHorizontalM,
- backgroundColor: tokens.colorStatusDangerBackground2,
- color: tokens.colorStatusDangerForeground2,
- borderRadius: tokens.borderRadiusMedium,
- },
divider: {
marginTop: tokens.spacingVerticalM,
marginBottom: tokens.spacingVerticalM,
@@ -118,7 +233,7 @@ const Field = (props: { label: string; value?: string | null }) => {
// ---------- Component ----------
-const GeneratedComponent = (props: GeneratedComponentProps) => {
+function PageBody(props: GeneratedComponentProps) {
const { dataApi, pageInput } = props;
const styles = useStyles();
@@ -143,7 +258,7 @@ const GeneratedComponent = (props: GeneratedComponentProps) => {
// on frame 0, not a blank page that flips to a spinner.
// Pre-warm `record` from the cache if we have it (return visits = instant).
const cached = cache.get(recordId);
- const [data, setData] = useState<{ record: ReadableContact | null; loading: boolean; error: string | null }>(
+ const [data, setData] = useState<{ record: ReadableContact | null; loading: boolean; error: PageErrorView | null }>(
() => ({
record: cached ?? null,
loading: cached === undefined,
@@ -193,10 +308,10 @@ const GeneratedComponent = (props: GeneratedComponentProps) => {
pending
.then((row) => { if (!cancelled) setData({ record: row, loading: false, error: null }); })
- .catch((err) => {
+ .catch((failure) => {
if (cancelled) return;
- const message = err instanceof Error ? err.message : 'Failed to load contact.';
- setData({ record: null, loading: false, error: message });
+ // Reported once — bounded code and message, never the thrown value; never cached.
+ setData({ record: null, loading: false, error: reportPageError(PAGE_NAME, 'loadContact', undefined, failure, 'read') });
});
return () => { cancelled = true; };
@@ -242,11 +357,7 @@ const GeneratedComponent = (props: GeneratedComponentProps) => {
</Text>
</header>
- {data.error && (
- <div role="alert" className={styles.errorBanner}>
- {data.error}
- </div>
- )}
+ <PageErrorBar error={data.error} />
{row && (
<Card className={styles.card}>
@@ -266,6 +377,12 @@ const GeneratedComponent = (props: GeneratedComponentProps) => {
)}
</div>
);
-};
+}
+
+const GeneratedComponent = (props: GeneratedComponentProps) => (
+ <PageErrorBoundary>
+ <PageBody {...props} />
+ </PageErrorBoundary>
+);
export default GeneratedComponent;
diff --git a/plugins/model-apps/samples/11-kanban-with-dnd.tsx b/plugins/model-apps/samples/11-kanban-with-dnd.tsx
index 3e3ff9e52..75009e808 100644
--- a/plugins/model-apps/samples/11-kanban-with-dnd.tsx
+++ b/plugins/model-apps/samples/11-kanban-with-dnd.tsx
@@ -19,6 +19,123 @@ import {
} from '@fluentui/react-icons';
import { GeneratedComponentProps, Task } from './RuntimeTypes';
+// ---------- Page errors ----------
+// The page error block of references/rules.md ("Missing Error Handling"), copied unchanged: every failed data
+// operation goes through reportPageError, PageErrorBar shows the view it returns, and the page renders inside
+// PageErrorBoundary.
+
+type PageErrorKind = 'read' | 'write' | 'indeterminate' | 'network' | 'render';
+type PageErrorView = {
+ operation: string;
+ message: string;
+ fallbackKey: string;
+ code?: string;
+ kind: PageErrorKind;
+ retry?: () => void;
+};
+type PageErrorTelemetry = {
+ trackException?: (error: unknown, properties?: Record<string, unknown>) => void;
+};
+
+// The plan's display name for this page: a fixed literal, not the file name.
+const PAGE_NAME = 'Task Board';
+
+// The error copy of an English-only page. A localized page keeps these keys in its translations dictionary instead.
+const ERROR_COPY: Record<string, string> = {
+ 'error.read': 'Unable to load data. Please try again.',
+ 'error.write': 'The change could not be saved. Refresh before trying again.',
+ 'error.network': 'The request did not go through. You can try again.',
+ 'error.indeterminate': "We couldn't confirm this completed — refresh before retrying.",
+ 'error.render': 'This page hit a problem and could not render. Refresh the page.',
+ 'error.tryAgain': 'Try again',
+};
+
+function translate(key: string): string {
+ return ERROR_COPY[key] || key;
+}
+
+// The page's one error reporter. It logs bounded diagnostics once and returns the view the failed
+// operation stores; it never sets state, never calls retry, and reads only the named fields of a
+// thrown value, each on its own, so a throwing getter leaves that one field empty.
+function reportPageError(
+ pageName: string,
+ operation: string,
+ code: unknown,
+ message: unknown,
+ kind: PageErrorKind,
+ retry?: () => void,
+ appInsights?: PageErrorTelemetry,
+): PageErrorView {
+ const fields: Record<string, unknown> = {};
+ for (const path of ['code', 'errorCode', 'message', 'error.code', 'error.message']) {
+ try {
+ let value: unknown = message;
+ for (const part of path.split('.')) {
+ value = value !== null && typeof value === 'object' ? (value as Record<string, unknown>)[part] : undefined;
+ }
+ fields[path] = value;
+ } catch {
+ fields[path] = undefined;
+ }
+ }
+ let normalizedCode = '';
+ for (const candidate of [code, fields['code'], fields['errorCode'], fields['error.code']]) {
+ const text = typeof candidate === 'string' ? candidate : typeof candidate === 'number' && Number.isFinite(candidate) ? String(candidate) : '';
+ normalizedCode = text.replace(/[\s\u0000-\u001f\u007f-\u009f]+/g, ' ').trim().slice(0, 80);
+ if (normalizedCode) break;
+ }
+ let normalizedMessage = '';
+ for (const candidate of [message, fields['message'], fields['error.message']]) {
+ const line = typeof candidate === 'string' ? candidate.trim().split(/[\r\n\u2028\u2029]/)[0].replace(/[\s\u0000-\u001f\u007f-\u009f]+/g, ' ').trim() : '';
+ if (!line || /^\[object [^\]]*\]$/.test(line) || /^at\s.*(?::\d+:\d+\)?|\((?:native|<anonymous>)\))$/.test(line)) continue;
+ normalizedMessage = line.length > 300 ? line.slice(0, 299) + '\u2026' : line;
+ break;
+ }
+ console.error('[' + String(pageName).replace(/[\r\n\]]/g, '') + '] ' + operation + ' failed', { code: normalizedCode, message: normalizedMessage });
+ const quiet = kind === 'indeterminate' || kind === 'render';
+ const view: PageErrorView = { operation, message: quiet ? '' : normalizedMessage, fallbackKey: 'error.' + kind, kind };
+ if (normalizedCode) view.code = normalizedCode;
+ if (typeof retry === 'function' && (kind === 'read' || kind === 'network')) view.retry = retry;
+ return view;
+}
+
+function PageErrorBar(props: { error: PageErrorView | null }) {
+ const { error } = props;
+ if (!error) return null;
+ return (
+ <MessageBar intent="error">
+ <MessageBarBody>{error.message || translate(error.fallbackKey)}</MessageBarBody>
+ </MessageBar>
+ );
+}
+
+// The page's one class component: it catches a render crash below it and shows a fixed message.
+class PageErrorBoundary extends React.Component<
+ { children: React.ReactNode; appInsights?: PageErrorTelemetry },
+ { failed: boolean }
+> {
+ public state = { failed: false };
+
+ public static getDerivedStateFromError(): { failed: boolean } {
+ return { failed: true };
+ }
+
+ public componentDidCatch(error: Error): void {
+ reportPageError(PAGE_NAME, 'render', undefined, error, 'render');
+ }
+
+ public render(): React.ReactNode {
+ if (this.state.failed) {
+ return (
+ <MessageBar intent="error">
+ <MessageBarBody>{translate('error.render')}</MessageBarBody>
+ </MessageBar>
+ );
+ }
+ return this.props.children;
+ }
+}
+
// Sample: kanban board with native HTML5 drag-and-drop.
// Demonstrates:
// - Rule: no external DnD library (no react-dnd / @dnd-kit / react-beautiful-dnd)
@@ -29,7 +146,8 @@ import { GeneratedComponentProps, Task } from './RuntimeTypes';
// In Progress=3, Completed=5 — Dataverse defaults for the `task` entity;
// see task_statuscode in RuntimeTypes)
// - Page-scoped window cache (window.__ppTaskBoard_taskCache) + in-flight de-dupe
-// - Realistic empty / loading / error states
+// - Realistic empty / loading / error states: a failed load or move goes through
+// reportPageError and PageErrorBar (Rule 22), and the board stays on screen
// - Logical CSS properties (paddingInline, paddingBlock, marginInlineStart)
// - Unsized Fluent icons (ClipboardTaskRegular, PlayRegular, CheckmarkCircleRegular)
// - export default GeneratedComponent and pageInput destructured
@@ -123,7 +241,7 @@ const useStyles = makeStyles({
// ---------- Component ----------
-const GeneratedComponent = (props: GeneratedComponentProps) => {
+function PageBody(props: GeneratedComponentProps) {
const { dataApi, pageInput } = props;
void pageInput; // board does not consume incoming pageInput
const styles = useStyles();
@@ -137,7 +255,7 @@ const GeneratedComponent = (props: GeneratedComponentProps) => {
// async callbacks, so one object + one setData avoids intermediate renders).
// Lazy-init from the window cache so the host's second mount paints tasks
// immediately instead of flashing the spinner (see references/data-caching.md).
- const [{ tasks, loading, error }, setData] = React.useState<{ tasks: Task[]; loading: boolean; error: string | null }>(
+ const [{ tasks, loading, error }, setData] = React.useState<{ tasks: Task[]; loading: boolean; error: PageErrorView | null }>(
() => {
const cached = winAny[CACHE_KEY] as Task[] | undefined;
return { tasks: cached ?? [], loading: cached === undefined, error: null };
@@ -181,7 +299,7 @@ const GeneratedComponent = (props: GeneratedComponentProps) => {
pending
.then((rows) => { if (!cancelled) setData({ tasks: rows, loading: false, error: null }); })
- .catch((e) => { if (!cancelled) setData((prev) => ({ ...prev, loading: false, error: e instanceof Error ? e.message : String(e) })); });
+ .catch((failure) => { if (!cancelled) setData({ tasks: [], loading: false, error: reportPageError(PAGE_NAME, 'loadTasks', undefined, failure, 'read') }); });
return () => { cancelled = true; };
// Readiness only — never `dataApi`. See Rule 15.
@@ -233,16 +351,17 @@ const GeneratedComponent = (props: GeneratedComponentProps) => {
try {
await dataApi.updateRow('task', taskId, { statuscode: targetStatus });
- } catch (err) {
- setData((prev) => ({ ...prev, tasks: prevTasks, error: err instanceof Error ? err.message : String(err) }));
+ } catch (failure) {
+ // A failed move is a write: the card goes back, the failure is reported once, and nothing retries it.
+ setData({ tasks: prevTasks, loading: false, error: reportPageError(PAGE_NAME, 'moveTask', undefined, failure, 'write') });
winAny[CACHE_KEY] = prevTasks;
+ return;
}
+ // A move that succeeds clears an earlier failed move's error — and only that operation's error.
+ setData((prev) => (prev.error?.operation === 'moveTask' ? { ...prev, error: null } : prev));
};
if (loading) return <Spinner label="Loading tasks..." />;
- if (error) return (
- <MessageBar intent="error"><MessageBarBody>{error}</MessageBarBody></MessageBar>
- );
return (
<div className={styles.root}>
@@ -251,6 +370,8 @@ const GeneratedComponent = (props: GeneratedComponentProps) => {
<Text size={500} weight="semibold">Task Board ({tasks.length})</Text>
</div>
+ <PageErrorBar error={error} />
+
<div className={styles.board}>
{COLUMNS.map((col) => {
const items = tasks.filter((t) => t.statuscode === col.key);
@@ -309,6 +430,12 @@ const GeneratedComponent = (props: GeneratedComponentProps) => {
</div>
</div>
);
-};
+}
+
+const GeneratedComponent = (props: GeneratedComponentProps) => (
+ <PageErrorBoundary>
+ <PageBody {...props} />
+ </PageErrorBoundary>
+);
export default GeneratedComponent;
diff --git a/plugins/model-apps/samples/12-dialog-form-overlay.tsx b/plugins/model-apps/samples/12-dialog-form-overlay.tsx
index b68ed4bbb..f9e76c495 100644
--- a/plugins/model-apps/samples/12-dialog-form-overlay.tsx
+++ b/plugins/model-apps/samples/12-dialog-form-overlay.tsx
@@ -33,9 +33,118 @@ import {
makeStyles,
tokens,
shorthands,
+ MessageBar,
+ MessageBarBody,
} from "@fluentui/react-components";
import { AddRegular, EditRegular, DeleteRegular, DismissRegular } from "@fluentui/react-icons";
+// ---------- Page errors ----------
+// The page error block of references/rules.md ("Missing Error Handling"), copied unchanged: every failed data
+// operation goes through reportPageError, PageErrorBar shows the view it returns, and the page renders inside
+// PageErrorBoundary.
+
+type PageErrorKind = 'read' | 'write' | 'indeterminate' | 'network' | 'render';
+type PageErrorView = {
+ operation: string;
+ message: string;
+ fallbackKey: string;
+ code?: string;
+ kind: PageErrorKind;
+ retry?: () => void;
+};
+type PageErrorTelemetry = {
+ trackException?: (error: unknown, properties?: Record<string, unknown>) => void;
+};
+
+// The plan's display name for this page: a fixed literal, not the file name.
+const PAGE_NAME = 'Projects';
+
+// The error copy of an English-only page. A localized page keeps these keys in its translations dictionary instead.
+const ERROR_COPY: Record<string, string> = {
+ 'error.read': 'Unable to load data. Please try again.',
+ 'error.write': 'The change could not be saved. Refresh before trying again.',
+ 'error.network': 'The request did not go through. You can try again.',
+ 'error.indeterminate': "We couldn't confirm this completed — refresh before retrying.",
+ 'error.render': 'This page hit a problem and could not render. Refresh the page.',
+ 'error.tryAgain': 'Try again',
+};
+
+function translate(key: string): string {
+ return ERROR_COPY[key] || key;
+}
+
+// The page's one error reporter. It logs bounded diagnostics once and returns the view the failed
+// operation stores; it never sets state, never calls retry, and reads only the named fields of a
+// thrown value, each on its own, so a throwing getter leaves that one field empty.
+function reportPageError(
+ pageName: string,
+ operation: string,
+ code: unknown,
+ message: unknown,
+ kind: PageErrorKind,
+ retry?: () => void,
+ appInsights?: PageErrorTelemetry,
+): PageErrorView {
+ const fields: Record<string, unknown> = {};
+ for (const path of ['code', 'errorCode', 'message', 'error.code', 'error.message']) {
+ try {
+ let value: unknown = message;
+ for (const part of path.split('.')) {
+ value = value !== null && typeof value === 'object' ? (value as Record<string, unknown>)[part] : undefined;
+ }
+ fields[path] = value;
+ } catch {
+ fields[path] = undefined;
+ }
+ }
+ let normalizedCode = '';
+ for (const candidate of [code, fields['code'], fields['errorCode'], fields['error.code']]) {
+ const text = typeof candidate === 'string' ? candidate : typeof candidate === 'number' && Number.isFinite(candidate) ? String(candidate) : '';
+ normalizedCode = text.replace(/[\s\u0000-\u001f\u007f-\u009f]+/g, ' ').trim().slice(0, 80);
+ if (normalizedCode) break;
+ }
+ let normalizedMessage = '';
+ for (const candidate of [message, fields['message'], fields['error.message']]) {
+ const line = typeof candidate === 'string' ? candidate.trim().split(/[\r\n\u2028\u2029]/)[0].replace(/[\s\u0000-\u001f\u007f-\u009f]+/g, ' ').trim() : '';
+ if (!line || /^\[object [^\]]*\]$/.test(line) || /^at\s.*(?::\d+:\d+\)?|\((?:native|<anonymous>)\))$/.test(line)) continue;
+ normalizedMessage = line.length > 300 ? line.slice(0, 299) + '\u2026' : line;
+ break;
+ }
+ console.error('[' + String(pageName).replace(/[\r\n\]]/g, '') + '] ' + operation + ' failed', { code: normalizedCode, message: normalizedMessage });
+ const quiet = kind === 'indeterminate' || kind === 'render';
+ const view: PageErrorView = { operation, message: quiet ? '' : normalizedMessage, fallbackKey: 'error.' + kind, kind };
+ if (normalizedCode) view.code = normalizedCode;
+ if (typeof retry === 'function' && (kind === 'read' || kind === 'network')) view.retry = retry;
+ return view;
+}
+
+// The page's one class component: it catches a render crash below it and shows a fixed message.
+class PageErrorBoundary extends React.Component<
+ { children: React.ReactNode; appInsights?: PageErrorTelemetry },
+ { failed: boolean }
+> {
+ public state = { failed: false };
+
+ public static getDerivedStateFromError(): { failed: boolean } {
+ return { failed: true };
+ }
+
+ public componentDidCatch(error: Error): void {
+ reportPageError(PAGE_NAME, 'render', undefined, error, 'render');
+ }
+
+ public render(): React.ReactNode {
+ if (this.state.failed) {
+ return (
+ <MessageBar intent="error">
+ <MessageBarBody>{translate('error.render')}</MessageBarBody>
+ </MessageBar>
+ );
+ }
+ return this.props.children;
+ }
+}
+
interface Project {
id: string;
name: string;
@@ -179,7 +288,7 @@ function ConfirmDeleteDialog({
// signature so the sample is copy/paste-safe for real /genpage output.
type Props = { dataApi?: unknown; pageInput?: { id?: string } };
-const GeneratedComponent = (props: Props) => {
+function PageBody(props: Props) {
const { pageInput } = props; // always destructure pageInput, even when unused
void pageInput;
const styles = useStyles();
@@ -262,6 +371,12 @@ const GeneratedComponent = (props: Props) => {
/>
</div>
);
-};
+}
+
+const GeneratedComponent = (props: Props) => (
+ <PageErrorBoundary>
+ <PageBody {...props} />
+ </PageErrorBoundary>
+);
export default GeneratedComponent;
diff --git a/plugins/model-apps/samples/13-custom-api-invocation.tsx b/plugins/model-apps/samples/13-custom-api-invocation.tsx
index 81793da77..60d661135 100644
--- a/plugins/model-apps/samples/13-custom-api-invocation.tsx
+++ b/plugins/model-apps/samples/13-custom-api-invocation.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState } from 'react';
+import React, { useEffect, useRef, useState } from 'react';
import type { GeneratedComponentProps } from './RuntimeTypes';
import {
makeStyles,
@@ -10,18 +10,145 @@ import {
Field,
Textarea,
MessageBar,
+ MessageBarActions,
MessageBarBody,
} from '@fluentui/react-components';
+// ---------- Page errors ----------
+// The page error block of references/rules.md ("Missing Error Handling"), copied unchanged: every failed data
+// operation goes through reportPageError, PageErrorBar shows the view it returns, and the page renders inside
+// PageErrorBoundary.
+
+type PageErrorKind = 'read' | 'write' | 'indeterminate' | 'network' | 'render';
+type PageErrorView = {
+ operation: string;
+ message: string;
+ fallbackKey: string;
+ code?: string;
+ kind: PageErrorKind;
+ retry?: () => void;
+};
+type PageErrorTelemetry = {
+ trackException?: (error: unknown, properties?: Record<string, unknown>) => void;
+};
+
+// The plan's display name for this page: a fixed literal, not the file name.
+const PAGE_NAME = 'Order Approval';
+
+// The error copy of an English-only page. A localized page keeps these keys in its translations dictionary instead.
+const ERROR_COPY: Record<string, string> = {
+ 'error.read': 'Unable to load data. Please try again.',
+ 'error.write': 'The change could not be saved. Refresh before trying again.',
+ 'error.network': 'The request did not go through. You can try again.',
+ 'error.indeterminate': "We couldn't confirm this completed — refresh before retrying.",
+ 'error.render': 'This page hit a problem and could not render. Refresh the page.',
+ 'error.tryAgain': 'Try again',
+};
+
+function translate(key: string): string {
+ return ERROR_COPY[key] || key;
+}
+
+// The page's one error reporter. It logs bounded diagnostics once and returns the view the failed
+// operation stores; it never sets state, never calls retry, and reads only the named fields of a
+// thrown value, each on its own, so a throwing getter leaves that one field empty.
+function reportPageError(
+ pageName: string,
+ operation: string,
+ code: unknown,
+ message: unknown,
+ kind: PageErrorKind,
+ retry?: () => void,
+ appInsights?: PageErrorTelemetry,
+): PageErrorView {
+ const fields: Record<string, unknown> = {};
+ for (const path of ['code', 'errorCode', 'message', 'error.code', 'error.message']) {
+ try {
+ let value: unknown = message;
+ for (const part of path.split('.')) {
+ value = value !== null && typeof value === 'object' ? (value as Record<string, unknown>)[part] : undefined;
+ }
+ fields[path] = value;
+ } catch {
+ fields[path] = undefined;
+ }
+ }
+ let normalizedCode = '';
+ for (const candidate of [code, fields['code'], fields['errorCode'], fields['error.code']]) {
+ const text = typeof candidate === 'string' ? candidate : typeof candidate === 'number' && Number.isFinite(candidate) ? String(candidate) : '';
+ normalizedCode = text.replace(/[\s\u0000-\u001f\u007f-\u009f]+/g, ' ').trim().slice(0, 80);
+ if (normalizedCode) break;
+ }
+ let normalizedMessage = '';
+ for (const candidate of [message, fields['message'], fields['error.message']]) {
+ const line = typeof candidate === 'string' ? candidate.trim().split(/[\r\n\u2028\u2029]/)[0].replace(/[\s\u0000-\u001f\u007f-\u009f]+/g, ' ').trim() : '';
+ if (!line || /^\[object [^\]]*\]$/.test(line) || /^at\s.*(?::\d+:\d+\)?|\((?:native|<anonymous>)\))$/.test(line)) continue;
+ normalizedMessage = line.length > 300 ? line.slice(0, 299) + '\u2026' : line;
+ break;
+ }
+ console.error('[' + String(pageName).replace(/[\r\n\]]/g, '') + '] ' + operation + ' failed', { code: normalizedCode, message: normalizedMessage });
+ const quiet = kind === 'indeterminate' || kind === 'render';
+ const view: PageErrorView = { operation, message: quiet ? '' : normalizedMessage, fallbackKey: 'error.' + kind, kind };
+ if (normalizedCode) view.code = normalizedCode;
+ if (typeof retry === 'function' && (kind === 'read' || kind === 'network')) view.retry = retry;
+ return view;
+}
+
+function PageErrorBar(props: { error: PageErrorView | null }) {
+ const { error } = props;
+ if (!error) return null;
+ return (
+ <MessageBar intent="error">
+ <MessageBarBody>{error.message || translate(error.fallbackKey)}</MessageBarBody>
+ {error.retry && (
+ <MessageBarActions>
+ <Button onClick={error.retry}>{translate('error.tryAgain')}</Button>
+ </MessageBarActions>
+ )}
+ </MessageBar>
+ );
+}
+
+// The page's one class component: it catches a render crash below it and shows a fixed message.
+class PageErrorBoundary extends React.Component<
+ { children: React.ReactNode; appInsights?: PageErrorTelemetry },
+ { failed: boolean }
+> {
+ public state = { failed: false };
+
+ public static getDerivedStateFromError(): { failed: boolean } {
+ return { failed: true };
+ }
+
+ public componentDidCatch(error: Error): void {
+ reportPageError(PAGE_NAME, 'render', undefined, error, 'render');
+ }
+
+ public render(): React.ReactNode {
+ if (this.state.failed) {
+ return (
+ <MessageBar intent="error">
+ <MessageBarBody>{translate('error.render')}</MessageBarBody>
+ </MessageBar>
+ );
+ }
+ return this.props.children;
+ }
+}
+
// Sample: Dataverse Custom API (plug-in) invocation from a form-embedded page.
-// Demonstrates (see references/custom-api.md — gated behind the `custom-api` feature flag):
+// Demonstrates (see references/custom-api.md):
// - Presence-checking optional dataApi methods before wiring a trigger (cast to an
// optional action-method shape; the methods are absent on older runtimes)
-// - A read-only FUNCTION on mount (executeFunction) — no double-submit guard needed
-// - An entity-bound ACTION (executeAction) with boundTo derived from pageInput, and a
-// double-submit guard so a mutating call can't fire twice
-// - Result handling per the contract: read res.outputs (never res.value), surface only the
-// sanitized res.error.message, and NEVER auto-retry an indeterminate result
+// - A FUNCTION the plan records as a read runs on mount (executeFunction) — no double-submit
+// guard needed — and a stale answer for an earlier record is ignored
+// - An entity-bound ACTION (executeAction) with boundTo from the record the page is on, and a
+// double-submit latch so a mutating call can't fire twice
+// - The approval belongs to the record it was started on: when the page moves to another record
+// its result and its retry are cleared, and a late answer for the earlier record is ignored
+// - Result handling per the contract, in order: res.indeterminate, then an `indeterminate`
+// code (never retried), then `network` (a manual "Try again"), then any other failure — each
+// reported through reportPageError and shown by PageErrorBar before res.outputs is read
// - Only `network` is safely retryable (the request never left the client)
// Custom API names, parameters, and output fields come from the plan's `## Custom API
// Bindings` — never guessed. Here: new_GetOrderSummary (Function) + new_ApproveOrder (Action,
@@ -86,7 +213,7 @@ const useStyles = makeStyles({
},
});
-const GeneratedComponent = (props: GeneratedComponentProps) => {
+function PageBody(props: GeneratedComponentProps) {
const { dataApi, pageInput } = props;
const styles = useStyles();
@@ -100,76 +227,107 @@ const GeneratedComponent = (props: GeneratedComponentProps) => {
const canReadSummary = typeof actionApi.executeFunction === 'function';
const canApprove = typeof actionApi.executeAction === 'function';
- const [summary, setSummary] = useState<OrderSummary | null>(null);
- const [loadingSummary, setLoadingSummary] = useState<boolean>(canReadSummary);
- const [summaryError, setSummaryError] = useState<string | null>(null);
+ // One state object per operation (Rule 14): its result, its pending flag and its error view.
+ const [summaryState, setSummaryState] = useState<{ summary: OrderSummary | null; loading: boolean; error: PageErrorView | null }>(
+ () => ({ summary: null, loading: canReadSummary && !!recordId, error: null }),
+ );
+ const summaryRequest = useRef(0); // the latest summary request; an older answer is ignored
const [reason, setReason] = useState<string>('');
- const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
- const [approveMessage, setApproveMessage] = useState<{ intent: 'success' | 'warning' | 'error'; text: string } | null>(null);
- const [canRetry, setCanRetry] = useState<boolean>(false);
+ const [approval, setApproval] = useState<{ submitting: boolean; status: string; error: PageErrorView | null }>({ submitting: false, status: '', error: null });
+ const pending = useRef(false); // double-submit latch: set before the call, reset in finally
+ // The record the approval panel belongs to. An approval's result — and the retry it carries — is shown only
+ // for the record it was started on: another record clears the panel, and a late answer for the record the
+ // page has left is ignored, so nothing on this record can approve a record the maker is not looking at.
+ const approvalFor = useRef(recordId);
- // FUNCTION: read-only, safe to run on mount and whenever the record changes. No double-submit
- // guard — a function never mutates. Ignore a stale response instead of blocking concurrent reads.
- useEffect(() => {
- if (!canReadSummary || !recordId) {
- setSummary(null);
- setLoadingSummary(false);
- return;
- }
- let cancelled = false;
- setLoadingSummary(true);
- setSummaryError(null);
- (async () => {
- const res = await actionApi.executeFunction!({
+ function setSummaryFailure(view: PageErrorView) {
+ setSummaryState({ summary: null, loading: false, error: view });
+ }
+
+ function setApprovalFailure(view: PageErrorView) {
+ setApproval({ submitting: false, status: '', error: view });
+ }
+
+ function retrySummary() {
+ if (recordId) void loadSummary(recordId);
+ }
+
+ function retryApprove() {
+ // Re-sends this record's approval, and only while the page still shows this record.
+ if (recordId && recordId === approvalFor.current) void approve(recordId, reason);
+ }
+
+ // FUNCTION: the plan records it as a read, so it may run on mount and whenever the record changes.
+ async function loadSummary(orderId: string) {
+ if (typeof actionApi.executeFunction !== 'function') return;
+ const requestId = ++summaryRequest.current;
+ setSummaryState({ summary: null, loading: true, error: null });
+ try {
+ const res = await actionApi.executeFunction({
name: 'new_GetOrderSummary',
- parameters: { OrderId: recordId }, // GUID-formatted string, matching the declared kind
+ parameters: { OrderId: orderId }, // GUID-formatted string, matching the declared kind
});
- if (cancelled) return;
- if (!res.ok) {
- setSummaryError(res.error?.message ?? 'Could not load the order summary.'); // sanitized only
- setLoadingSummary(false);
- return;
- }
- const { Total, Status } = res.outputs as OrderSummary; // read from outputs, never `value`
- setSummary({ Total, Status });
- setLoadingSummary(false);
- })();
- return () => {
- cancelled = true;
- };
- }, [actionApi, canReadSummary, recordId]);
+ if (requestId !== summaryRequest.current) return; // a newer request owns the state
+ if (res.indeterminate) { setSummaryFailure(reportPageError(PAGE_NAME, 'loadSummary', res.error?.code, res.error?.message, 'indeterminate')); return; }
+ if (res.error?.code === 'indeterminate') { setSummaryFailure(reportPageError(PAGE_NAME, 'loadSummary', res.error?.code, res.error?.message, 'indeterminate')); return; }
+ if (!res.ok && res.error?.code === 'network') { setSummaryFailure(reportPageError(PAGE_NAME, 'loadSummary', res.error?.code, res.error?.message, 'network', retrySummary)); return; }
+ if (!res.ok) { setSummaryFailure(reportPageError(PAGE_NAME, 'loadSummary', res.error?.code, res.error?.message, 'read', retrySummary)); return; }
+ const total = res.outputs?.Total; // read from outputs, never `value`
+ const status = res.outputs?.Status;
+ setSummaryState({ summary: { Total: typeof total === 'number' ? total : 0, Status: typeof status === 'string' ? status : '' }, loading: false, error: null });
+ } catch (error) {
+ if (requestId !== summaryRequest.current) return;
+ setSummaryFailure(reportPageError(PAGE_NAME, 'loadSummary', undefined, error, 'read', retrySummary));
+ }
+ }
// ACTION: may mutate, so guard against double-submit and require boundTo (this operation is
- // bound to `salesorder`; its entityName must match the record the page is on).
- const approve = async () => {
- if (!canApprove || isSubmitting || !entityName || !recordId) return;
- setIsSubmitting(true);
- setApproveMessage(null);
- setCanRetry(false);
+ // bound to `salesorder`; the page only offers it on a sales order form).
+ async function approve(orderId: string, note: string) {
+ if (typeof actionApi.executeAction !== 'function') return;
+ if (pending.current) return;
+ pending.current = true;
+ setApproval({ submitting: true, status: '', error: null });
try {
- const res = await actionApi.executeAction!({
+ const res = await actionApi.executeAction({
name: 'new_ApproveOrder',
- parameters: { Comment: reason },
- boundTo: { entityName, id: recordId },
+ parameters: { Comment: note },
+ boundTo: { entityName: 'salesorder', id: orderId },
});
- if (res.indeterminate) {
- // Never auto-retry — the server may have committed it. Ask the user to refresh.
- setApproveMessage({ intent: 'warning', text: "We couldn't confirm the approval completed — refresh before retrying." });
- return;
- }
- if (!res.ok) {
- setApproveMessage({ intent: 'error', text: res.error?.message ?? 'The approval failed.' });
- // Only a `network` failure is safely retryable: the request never left the client.
- setCanRetry(res.error?.code === 'network');
- return;
- }
- const { NewStatus } = res.outputs as { NewStatus: string };
- setApproveMessage({ intent: 'success', text: `Order approved. New status: ${NewStatus}.` });
+ // The page moved to another record while this ran: the answer is not that record's to show.
+ if (orderId !== approvalFor.current) return;
+ // Never auto-retry an indeterminate result — the server may have committed it.
+ if (res.indeterminate) { setApprovalFailure(reportPageError(PAGE_NAME, 'approveOrder', res.error?.code, res.error?.message, 'indeterminate')); return; }
+ if (res.error?.code === 'indeterminate') { setApprovalFailure(reportPageError(PAGE_NAME, 'approveOrder', res.error?.code, res.error?.message, 'indeterminate')); return; }
+ // Only a `network` failure is safely retryable: the request never left the client.
+ if (!res.ok && res.error?.code === 'network') { setApprovalFailure(reportPageError(PAGE_NAME, 'approveOrder', res.error?.code, res.error?.message, 'network', retryApprove)); return; }
+ if (!res.ok) { setApprovalFailure(reportPageError(PAGE_NAME, 'approveOrder', res.error?.code, res.error?.message, 'write')); return; }
+ const newStatus = res.outputs?.NewStatus;
+ setApproval({ submitting: false, status: typeof newStatus === 'string' ? newStatus : '', error: null });
+ } catch (error) {
+ if (orderId !== approvalFor.current) return;
+ setApprovalFailure(reportPageError(PAGE_NAME, 'approveOrder', undefined, error, 'write'));
} finally {
- setIsSubmitting(false); // never leave the button stuck disabled
+ pending.current = false; // never leave the latch stuck
}
- };
+ }
+
+ useEffect(() => {
+ // A new record starts a clean approval panel: the previous record's result, and its retry, go. An
+ // approval still running for that record keeps the latch until it answers; its answer is ignored.
+ approvalFor.current = recordId;
+ setApproval({ submitting: false, status: '', error: null });
+ }, [recordId]);
+
+ useEffect(() => {
+ if (!canReadSummary || !recordId) return;
+ void loadSummary(recordId);
+ // An answer that arrives after the record changed, or after unmount, is ignored.
+ return () => { summaryRequest.current += 1; };
+ // The record only — never `dataApi` or the action shape derived from it (a new ref each render). See Rule 15.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [canReadSummary, recordId]);
if (entityName !== 'salesorder' || !recordId) {
return (
@@ -183,53 +341,54 @@ const GeneratedComponent = (props: GeneratedComponentProps) => {
<div className={styles.root}>
<Card className={styles.card}>
<Text as="h2" size={600} weight="semibold">Order summary</Text>
- {loadingSummary ? (
+ <PageErrorBar error={summaryState.error} />
+ {summaryState.loading ? (
<div className={styles.spinnerWrap}>
<Spinner labelPosition="below" label="Loading summary…" />
</div>
- ) : summaryError ? (
- <MessageBar intent="error"><MessageBarBody>{summaryError}</MessageBarBody></MessageBar>
- ) : summary ? (
+ ) : summaryState.summary ? (
<div className={styles.summaryGrid}>
<Text className={styles.label}>Total</Text>
- <Text>{summary.Total}</Text>
+ <Text>{summaryState.summary.Total}</Text>
<Text className={styles.label}>Status</Text>
- <Text>{summary.Status}</Text>
+ <Text>{summaryState.summary.Status}</Text>
</div>
- ) : (
+ ) : !canReadSummary ? (
<Text>Order summary is unavailable on this runtime.</Text>
- )}
+ ) : null}
</Card>
<Card className={styles.card}>
<Text as="h2" size={600} weight="semibold">Approve order</Text>
- {approveMessage && (
- <MessageBar intent={approveMessage.intent}>
- <MessageBarBody>{approveMessage.text}</MessageBarBody>
+ <PageErrorBar error={approval.error} />
+ {approval.status && (
+ <MessageBar intent="success">
+ <MessageBarBody>{`Order approved. New status: ${approval.status}.`}</MessageBarBody>
</MessageBar>
)}
<Field label="Approval note">
<Textarea
value={reason}
onChange={(_e, d) => setReason(d.value)}
- disabled={!canApprove || isSubmitting}
+ disabled={!canApprove || approval.submitting}
placeholder="Optional note recorded with the approval"
/>
</Field>
<div className={styles.actions}>
- <Button appearance="primary" onClick={approve} disabled={!canApprove || isSubmitting}>
- {isSubmitting ? 'Approving…' : 'Approve order'}
+ <Button appearance="primary" onClick={() => void approve(recordId, reason)} disabled={!canApprove || approval.submitting}>
+ {approval.submitting ? 'Approving…' : 'Approve order'}
</Button>
- {canRetry && (
- <Button appearance="secondary" onClick={approve} disabled={isSubmitting}>
- Try again
- </Button>
- )}
{!canApprove && <Text>Approval isn't available on this runtime.</Text>}
</div>
</Card>
</div>
);
-};
+}
+
+const GeneratedComponent = (props: GeneratedComponentProps) => (
+ <PageErrorBoundary>
+ <PageBody {...props} />
+ </PageErrorBoundary>
+);
export default GeneratedComponent;
diff --git a/plugins/model-apps/samples/2-wizard-multi-step.tsx b/plugins/model-apps/samples/2-wizard-multi-step.tsx
index 75a147e91..bbb2fa2d2 100644
--- a/plugins/model-apps/samples/2-wizard-multi-step.tsx
+++ b/plugins/model-apps/samples/2-wizard-multi-step.tsx
@@ -1,7 +1,119 @@
import React, { useState } from 'react';
-import { Button, Text, RadioGroup, Radio, Divider, ProgressBar, tokens } from '@fluentui/react-components';
+import { Button, Text, RadioGroup, Radio, Divider, ProgressBar, tokens, MessageBar, MessageBarBody } from '@fluentui/react-components';
-const GeneratedComponent = () => {
+// ---------- Page errors ----------
+// The page error block of references/rules.md ("Missing Error Handling"), copied unchanged: every failed data
+// operation goes through reportPageError, PageErrorBar shows the view it returns, and the page renders inside
+// PageErrorBoundary.
+
+type PageErrorKind = 'read' | 'write' | 'indeterminate' | 'network' | 'render';
+type PageErrorView = {
+ operation: string;
+ message: string;
+ fallbackKey: string;
+ code?: string;
+ kind: PageErrorKind;
+ retry?: () => void;
+};
+type PageErrorTelemetry = {
+ trackException?: (error: unknown, properties?: Record<string, unknown>) => void;
+};
+
+// The plan's display name for this page: a fixed literal, not the file name.
+const PAGE_NAME = 'Compliance Wizard';
+
+// The error copy of an English-only page. A localized page keeps these keys in its translations dictionary instead.
+const ERROR_COPY: Record<string, string> = {
+ 'error.read': 'Unable to load data. Please try again.',
+ 'error.write': 'The change could not be saved. Refresh before trying again.',
+ 'error.network': 'The request did not go through. You can try again.',
+ 'error.indeterminate': "We couldn't confirm this completed — refresh before retrying.",
+ 'error.render': 'This page hit a problem and could not render. Refresh the page.',
+ 'error.tryAgain': 'Try again',
+};
+
+function translate(key: string): string {
+ return ERROR_COPY[key] || key;
+}
+
+// The page's one error reporter. It logs bounded diagnostics once and returns the view the failed
+// operation stores; it never sets state, never calls retry, and reads only the named fields of a
+// thrown value, each on its own, so a throwing getter leaves that one field empty.
+function reportPageError(
+ pageName: string,
+ operation: string,
+ code: unknown,
+ message: unknown,
+ kind: PageErrorKind,
+ retry?: () => void,
+ appInsights?: PageErrorTelemetry,
+): PageErrorView {
+ const fields: Record<string, unknown> = {};
+ for (const path of ['code', 'errorCode', 'message', 'error.code', 'error.message']) {
+ try {
+ let value: unknown = message;
+ for (const part of path.split('.')) {
+ value = value !== null && typeof value === 'object' ? (value as Record<string, unknown>)[part] : undefined;
+ }
+ fields[path] = value;
+ } catch {
+ fields[path] = undefined;
+ }
+ }
+ let normalizedCode = '';
+ for (const candidate of [code, fields['code'], fields['errorCode'], fields['error.code']]) {
+ const text = typeof candidate === 'string' ? candidate : typeof candidate === 'number' && Number.isFinite(candidate) ? String(candidate) : '';
+ normalizedCode = text.replace(/[\s\u0000-\u001f\u007f-\u009f]+/g, ' ').trim().slice(0, 80);
+ if (normalizedCode) break;
+ }
+ let normalizedMessage = '';
+ for (const candidate of [message, fields['message'], fields['error.message']]) {
+ const line = typeof candidate === 'string' ? candidate.trim().split(/[\r\n\u2028\u2029]/)[0].replace(/[\s\u0000-\u001f\u007f-\u009f]+/g, ' ').trim() : '';
+ if (!line || /^\[object [^\]]*\]$/.test(line) || /^at\s.*(?::\d+:\d+\)?|\((?:native|<anonymous>)\))$/.test(line)) continue;
+ normalizedMessage = line.length > 300 ? line.slice(0, 299) + '\u2026' : line;
+ break;
+ }
+ console.error('[' + String(pageName).replace(/[\r\n\]]/g, '') + '] ' + operation + ' failed', { code: normalizedCode, message: normalizedMessage });
+ const quiet = kind === 'indeterminate' || kind === 'render';
+ const view: PageErrorView = { operation, message: quiet ? '' : normalizedMessage, fallbackKey: 'error.' + kind, kind };
+ if (normalizedCode) view.code = normalizedCode;
+ if (typeof retry === 'function' && (kind === 'read' || kind === 'network')) view.retry = retry;
+ return view;
+}
+
+// The page's one class component: it catches a render crash below it and shows a fixed message.
+class PageErrorBoundary extends React.Component<
+ { children: React.ReactNode; appInsights?: PageErrorTelemetry },
+ { failed: boolean }
+> {
+ public state = { failed: false };
+
+ public static getDerivedStateFromError(): { failed: boolean } {
+ return { failed: true };
+ }
+
+ public componentDidCatch(error: Error): void {
+ reportPageError(PAGE_NAME, 'render', undefined, error, 'render');
+ }
+
+ public render(): React.ReactNode {
+ if (this.state.failed) {
+ return (
+ <MessageBar intent="error">
+ <MessageBarBody>{translate('error.render')}</MessageBarBody>
+ </MessageBar>
+ );
+ }
+ return this.props.children;
+ }
+}
+
+// Mock page: no RuntimeTypes import (not generated for mock pages), so it declares its own props.
+type Props = { dataApi?: unknown; pageInput?: { id?: string } };
+
+function PageBody(props: Props) {
+ const { pageInput } = props;
+ void pageInput;
const [currentStep, setCurrentStep] = useState(0);
const [responses, setResponses] = useState({
signatureQuestion1: '',
@@ -80,7 +192,7 @@ const GeneratedComponent = () => {
</div>
</div>
);
-};
+}
const SignatureStep = ({ responses, setResponses }: { responses: any; setResponses: any }) => (
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
@@ -187,4 +299,10 @@ const ConfirmationStep = ({ responses }: { responses: any }) => (
</div>
);
+const GeneratedComponent = (props: Props) => (
+ <PageErrorBoundary>
+ <PageBody {...props} />
+ </PageErrorBoundary>
+);
+
export default GeneratedComponent;
diff --git a/plugins/model-apps/samples/3-account-crud-dataverse.tsx b/plugins/model-apps/samples/3-account-crud-dataverse.tsx
index a3f7cd415..adf56b877 100644
--- a/plugins/model-apps/samples/3-account-crud-dataverse.tsx
+++ b/plugins/model-apps/samples/3-account-crud-dataverse.tsx
@@ -11,6 +11,8 @@ import {
DataGridHeaderCell,
TableCellLayout,
createTableColumn,
+ MessageBar,
+ MessageBarBody,
} from "@fluentui/react-components";
import type {
GeneratedComponentProps,
@@ -20,6 +22,123 @@ import type {
QueryTableOptions,
} from "./RuntimeTypes";
+// ---------- Page errors ----------
+// The page error block of references/rules.md ("Missing Error Handling"), copied unchanged: every failed data
+// operation goes through reportPageError, PageErrorBar shows the view it returns, and the page renders inside
+// PageErrorBoundary.
+
+type PageErrorKind = 'read' | 'write' | 'indeterminate' | 'network' | 'render';
+type PageErrorView = {
+ operation: string;
+ message: string;
+ fallbackKey: string;
+ code?: string;
+ kind: PageErrorKind;
+ retry?: () => void;
+};
+type PageErrorTelemetry = {
+ trackException?: (error: unknown, properties?: Record<string, unknown>) => void;
+};
+
+// The plan's display name for this page: a fixed literal, not the file name.
+const PAGE_NAME = 'Accounts';
+
+// The error copy of an English-only page. A localized page keeps these keys in its translations dictionary instead.
+const ERROR_COPY: Record<string, string> = {
+ 'error.read': 'Unable to load data. Please try again.',
+ 'error.write': 'The change could not be saved. Refresh before trying again.',
+ 'error.network': 'The request did not go through. You can try again.',
+ 'error.indeterminate': "We couldn't confirm this completed — refresh before retrying.",
+ 'error.render': 'This page hit a problem and could not render. Refresh the page.',
+ 'error.tryAgain': 'Try again',
+};
+
+function translate(key: string): string {
+ return ERROR_COPY[key] || key;
+}
+
+// The page's one error reporter. It logs bounded diagnostics once and returns the view the failed
+// operation stores; it never sets state, never calls retry, and reads only the named fields of a
+// thrown value, each on its own, so a throwing getter leaves that one field empty.
+function reportPageError(
+ pageName: string,
+ operation: string,
+ code: unknown,
+ message: unknown,
+ kind: PageErrorKind,
+ retry?: () => void,
+ appInsights?: PageErrorTelemetry,
+): PageErrorView {
+ const fields: Record<string, unknown> = {};
+ for (const path of ['code', 'errorCode', 'message', 'error.code', 'error.message']) {
+ try {
+ let value: unknown = message;
+ for (const part of path.split('.')) {
+ value = value !== null && typeof value === 'object' ? (value as Record<string, unknown>)[part] : undefined;
+ }
+ fields[path] = value;
+ } catch {
+ fields[path] = undefined;
+ }
+ }
+ let normalizedCode = '';
+ for (const candidate of [code, fields['code'], fields['errorCode'], fields['error.code']]) {
+ const text = typeof candidate === 'string' ? candidate : typeof candidate === 'number' && Number.isFinite(candidate) ? String(candidate) : '';
+ normalizedCode = text.replace(/[\s\u0000-\u001f\u007f-\u009f]+/g, ' ').trim().slice(0, 80);
+ if (normalizedCode) break;
+ }
+ let normalizedMessage = '';
+ for (const candidate of [message, fields['message'], fields['error.message']]) {
+ const line = typeof candidate === 'string' ? candidate.trim().split(/[\r\n\u2028\u2029]/)[0].replace(/[\s\u0000-\u001f\u007f-\u009f]+/g, ' ').trim() : '';
+ if (!line || /^\[object [^\]]*\]$/.test(line) || /^at\s.*(?::\d+:\d+\)?|\((?:native|<anonymous>)\))$/.test(line)) continue;
+ normalizedMessage = line.length > 300 ? line.slice(0, 299) + '\u2026' : line;
+ break;
+ }
+ console.error('[' + String(pageName).replace(/[\r\n\]]/g, '') + '] ' + operation + ' failed', { code: normalizedCode, message: normalizedMessage });
+ const quiet = kind === 'indeterminate' || kind === 'render';
+ const view: PageErrorView = { operation, message: quiet ? '' : normalizedMessage, fallbackKey: 'error.' + kind, kind };
+ if (normalizedCode) view.code = normalizedCode;
+ if (typeof retry === 'function' && (kind === 'read' || kind === 'network')) view.retry = retry;
+ return view;
+}
+
+function PageErrorBar(props: { error: PageErrorView | null }) {
+ const { error } = props;
+ if (!error) return null;
+ return (
+ <MessageBar intent="error">
+ <MessageBarBody>{error.message || translate(error.fallbackKey)}</MessageBarBody>
+ </MessageBar>
+ );
+}
+
+// The page's one class component: it catches a render crash below it and shows a fixed message.
+class PageErrorBoundary extends React.Component<
+ { children: React.ReactNode; appInsights?: PageErrorTelemetry },
+ { failed: boolean }
+> {
+ public state = { failed: false };
+
+ public static getDerivedStateFromError(): { failed: boolean } {
+ return { failed: true };
+ }
+
+ public componentDidCatch(error: Error): void {
+ reportPageError(PAGE_NAME, 'render', undefined, error, 'render');
+ }
+
+ public render(): React.ReactNode {
+ if (this.state.failed) {
+ return (
+ <MessageBar intent="error">
+ <MessageBarBody>{translate('error.render')}</MessageBarBody>
+ </MessageBar>
+ );
+ }
+ return this.props.children;
+ }
+}
+
// Module-level key aliases — VALUES live on `window` (single source of truth) so
// they survive the host double-mount on open and back-navigation, and stay
// coherent across module re-evaluation. See references/data-caching.md.
@@ -27,18 +146,24 @@ const CACHE_KEY = "__ppAccountCrud_accountCache";
const INFLIGHT_KEY = "__ppAccountCrud_accountInflight";
const winAny = window as unknown as Record<string, unknown>;
-const GeneratedComponent = ({ dataApi }: GeneratedComponentProps) => {
+function PageBody(props: GeneratedComponentProps) {
+ const { dataApi, pageInput } = props;
+ void pageInput; // the list takes no input; destructure it anyway, per the rules
const dataReady = !!dataApi;
// Single batched fetch state (Rule 14 — React 17 doesn't batch setState in
// async callbacks, so one object + one setData avoids intermediate renders).
// `loading` also gates mutations until the initial load resolves, so a
// create/update can't race an in-flight first fetch (stale-write the cache).
- const [{ accounts, loading }, setData] = useState<{ accounts: ReadableTableRow<account>[]; loading: boolean }>(
+ // `error` is the list's own PageErrorView (Rule 22), never a string.
+ const [{ accounts, loading, error }, setData] = useState<{ accounts: ReadableTableRow<account>[]; loading: boolean; error: PageErrorView | null }>(
() => {
const cached = winAny[CACHE_KEY] as ReadableTableRow<account>[] | undefined;
- return { accounts: cached ?? [], loading: cached === undefined };
+ return { accounts: cached ?? [], loading: cached === undefined, error: null };
},
);
+ // The save keeps its own pending flag and error view, so loading the list never
+ // clears a failed save, and a save never clears a failed load.
+ const [save, setSave] = useState<{ saving: boolean; error: PageErrorView | null }>({ saving: false, error: null });
const [selectedAccount, setSelectedAccount] = useState<ReadableTableRow<account> | null>(null);
const [formData, setFormData] = useState<WritableTableRow<account>>({
name: "",
@@ -57,7 +182,7 @@ const GeneratedComponent = ({ dataApi }: GeneratedComponentProps) => {
// another mount's fetch is resolving doesn't stay stuck on the old list.
const cached = winAny[CACHE_KEY] as ReadableTableRow<account>[] | undefined;
if (cached !== undefined) {
- if (accounts !== cached || loading) setData({ accounts: cached, loading: false });
+ if (accounts !== cached || loading) setData({ accounts: cached, loading: false, error: null });
return;
}
let cancelled = false;
@@ -81,8 +206,9 @@ const GeneratedComponent = ({ dataApi }: GeneratedComponentProps) => {
}
inflight
- .then((rows) => { if (!cancelled) setData({ accounts: rows, loading: false }); })
- .catch((err) => { if (!cancelled) { console.error("Failed to load accounts", err); setData((prev) => ({ ...prev, loading: false })); } });
+ .then((rows) => { if (!cancelled) setData({ accounts: rows, loading: false, error: null }); })
+ // Reported once (bounded code and message, never the thrown value) and never cached.
+ .catch((failure) => { if (!cancelled) setData({ accounts: [], loading: false, error: reportPageError(PAGE_NAME, "loadAccounts", undefined, failure, "read") }); });
return () => { cancelled = true; };
// Readiness only — never `dataApi` (new ref each render). See Rule 15.
@@ -94,12 +220,21 @@ const GeneratedComponent = ({ dataApi }: GeneratedComponentProps) => {
};
const handleAddOrUpdate = async () => {
- if (loading) return; // don't mutate while the initial load is still in flight
- if (selectedAccount) {
- await dataApi.updateRow("account", selectedAccount.accountid, formData);
- } else {
- await dataApi.createRow("account", formData);
+ if (loading || save.saving) return; // don't mutate while the initial load is still in flight, or twice
+ setSave({ saving: true, error: null });
+ try {
+ if (selectedAccount) {
+ await dataApi.updateRow("account", selectedAccount.accountid, formData);
+ } else {
+ await dataApi.createRow("account", formData);
+ }
+ } catch (failure) {
+ // The form keeps what was typed. A failed write is reported once and never retried:
+ // the save may or may not have reached the server.
+ setSave({ saving: false, error: reportPageError(PAGE_NAME, "saveAccount", undefined, failure, "write") });
+ return;
}
+ setSave({ saving: false, error: null });
// Refresh list — evict the stale cache and publish the refetch as the
// shared in-flight promise, so a mount that happens WHILE this refresh is
// pending awaits THIS query instead of returning the stale cache. Mirrors
@@ -115,18 +250,21 @@ const GeneratedComponent = ({ dataApi }: GeneratedComponentProps) => {
.then((result) => { winAny[CACHE_KEY] = result.rows; return result.rows; })
.finally(() => { if (winAny[INFLIGHT_KEY] === refetch) delete winAny[INFLIGHT_KEY]; });
winAny[INFLIGHT_KEY] = refetch;
- const rows = await refetch;
- setData({ accounts: rows, loading: false });
- // Reset form
- setFormData({
- name: "",
- address1_city: "",
- address1_stateorprovince: "",
- address1_postalcode: "",
- address1_country: "",
- telephone1: "",
- });
- setSelectedAccount(null);
+ refetch
+ .then((rows) => {
+ setData({ accounts: rows, loading: false, error: null });
+ // Reset form
+ setFormData({
+ name: "",
+ address1_city: "",
+ address1_stateorprovince: "",
+ address1_postalcode: "",
+ address1_country: "",
+ telephone1: "",
+ });
+ setSelectedAccount(null);
+ })
+ .catch((failure) => { setData({ accounts: [], loading: false, error: reportPageError(PAGE_NAME, "loadAccounts", undefined, failure, "read") }); });
};
const handleRowSelect = (account: ReadableTableRow<account>) => {
@@ -200,19 +338,21 @@ const GeneratedComponent = ({ dataApi }: GeneratedComponentProps) => {
<Text as="h2" size={500} block weight="semibold">
Account Form
</Text>
+ <PageErrorBar error={save.error} />
<Input aria-label="Account Name" placeholder="Enter account name" value={formData.name || ""} onChange={(e, data) => handleInputChange("name", data.value)} />
<Input aria-label="City" placeholder="Enter city" value={formData.address1_city || ""} onChange={(e, data) => handleInputChange("address1_city", data.value)} />
<Input aria-label="State" placeholder="Enter state" value={formData.address1_stateorprovince || ""} onChange={(e, data) => handleInputChange("address1_stateorprovince", data.value)} />
<Input aria-label="Zip" placeholder="Enter zip code" value={formData.address1_postalcode || ""} onChange={(e, data) => handleInputChange("address1_postalcode", data.value)} />
<Input aria-label="Country" placeholder="Enter country" value={formData.address1_country || ""} onChange={(e, data) => handleInputChange("address1_country", data.value)} />
<Input aria-label="Phone" placeholder="Enter phone number" value={formData.telephone1 || ""} onChange={(e, data) => handleInputChange("telephone1", data.value)} />
- <Button style={{ width: "100%", marginTop: "12px" }} appearance="primary" onClick={handleAddOrUpdate} disabled={loading}>
+ <Button style={{ width: "100%", marginTop: "12px" }} appearance="primary" onClick={handleAddOrUpdate} disabled={loading || save.saving}>
{selectedAccount ? "Update Account" : "Add Account"}
</Button>
</section>
{/* Grid */}
<section style={{ flex: "2 1 400px", minWidth: "300px", display: "flex", flexDirection: "column" }} aria-label="Accounts data grid section">
+ <PageErrorBar error={error} />
<div style={{ flex: 1, minHeight: 0 }}>
<DataGrid
items={accounts}
@@ -244,6 +384,12 @@ const GeneratedComponent = ({ dataApi }: GeneratedComponentProps) => {
</div>
</div>
);
-};
+}
+
+const GeneratedComponent = (props: GeneratedComponentProps) => (
+ <PageErrorBoundary>
+ <PageBody {...props} />
+ </PageErrorBoundary>
+);
export default GeneratedComponent;
diff --git a/plugins/model-apps/samples/4-file-upload.tsx b/plugins/model-apps/samples/4-file-upload.tsx
index fa04489ea..0c0652af4 100644
--- a/plugins/model-apps/samples/4-file-upload.tsx
+++ b/plugins/model-apps/samples/4-file-upload.tsx
@@ -1,7 +1,119 @@
import React, { useRef, useState } from "react";
-import { Button, Text, tokens } from "@fluentui/react-components";
+import { Button, Text, tokens, MessageBar, MessageBarBody } from "@fluentui/react-components";
-const GeneratedComponent = () => {
+// ---------- Page errors ----------
+// The page error block of references/rules.md ("Missing Error Handling"), copied unchanged: every failed data
+// operation goes through reportPageError, PageErrorBar shows the view it returns, and the page renders inside
+// PageErrorBoundary.
+
+type PageErrorKind = 'read' | 'write' | 'indeterminate' | 'network' | 'render';
+type PageErrorView = {
+ operation: string;
+ message: string;
+ fallbackKey: string;
+ code?: string;
+ kind: PageErrorKind;
+ retry?: () => void;
+};
+type PageErrorTelemetry = {
+ trackException?: (error: unknown, properties?: Record<string, unknown>) => void;
+};
+
+// The plan's display name for this page: a fixed literal, not the file name.
+const PAGE_NAME = 'File Upload';
+
+// The error copy of an English-only page. A localized page keeps these keys in its translations dictionary instead.
+const ERROR_COPY: Record<string, string> = {
+ 'error.read': 'Unable to load data. Please try again.',
+ 'error.write': 'The change could not be saved. Refresh before trying again.',
+ 'error.network': 'The request did not go through. You can try again.',
+ 'error.indeterminate': "We couldn't confirm this completed — refresh before retrying.",
+ 'error.render': 'This page hit a problem and could not render. Refresh the page.',
+ 'error.tryAgain': 'Try again',
+};
+
+function translate(key: string): string {
+ return ERROR_COPY[key] || key;
+}
+
+// The page's one error reporter. It logs bounded diagnostics once and returns the view the failed
+// operation stores; it never sets state, never calls retry, and reads only the named fields of a
+// thrown value, each on its own, so a throwing getter leaves that one field empty.
+function reportPageError(
+ pageName: string,
+ operation: string,
+ code: unknown,
+ message: unknown,
+ kind: PageErrorKind,
+ retry?: () => void,
+ appInsights?: PageErrorTelemetry,
+): PageErrorView {
+ const fields: Record<string, unknown> = {};
+ for (const path of ['code', 'errorCode', 'message', 'error.code', 'error.message']) {
+ try {
+ let value: unknown = message;
+ for (const part of path.split('.')) {
+ value = value !== null && typeof value === 'object' ? (value as Record<string, unknown>)[part] : undefined;
+ }
+ fields[path] = value;
+ } catch {
+ fields[path] = undefined;
+ }
+ }
+ let normalizedCode = '';
+ for (const candidate of [code, fields['code'], fields['errorCode'], fields['error.code']]) {
+ const text = typeof candidate === 'string' ? candidate : typeof candidate === 'number' && Number.isFinite(candidate) ? String(candidate) : '';
+ normalizedCode = text.replace(/[\s\u0000-\u001f\u007f-\u009f]+/g, ' ').trim().slice(0, 80);
+ if (normalizedCode) break;
+ }
+ let normalizedMessage = '';
+ for (const candidate of [message, fields['message'], fields['error.message']]) {
+ const line = typeof candidate === 'string' ? candidate.trim().split(/[\r\n\u2028\u2029]/)[0].replace(/[\s\u0000-\u001f\u007f-\u009f]+/g, ' ').trim() : '';
+ if (!line || /^\[object [^\]]*\]$/.test(line) || /^at\s.*(?::\d+:\d+\)?|\((?:native|<anonymous>)\))$/.test(line)) continue;
+ normalizedMessage = line.length > 300 ? line.slice(0, 299) + '\u2026' : line;
+ break;
+ }
+ console.error('[' + String(pageName).replace(/[\r\n\]]/g, '') + '] ' + operation + ' failed', { code: normalizedCode, message: normalizedMessage });
+ const quiet = kind === 'indeterminate' || kind === 'render';
+ const view: PageErrorView = { operation, message: quiet ? '' : normalizedMessage, fallbackKey: 'error.' + kind, kind };
+ if (normalizedCode) view.code = normalizedCode;
+ if (typeof retry === 'function' && (kind === 'read' || kind === 'network')) view.retry = retry;
+ return view;
+}
+
+// The page's one class component: it catches a render crash below it and shows a fixed message.
+class PageErrorBoundary extends React.Component<
+ { children: React.ReactNode; appInsights?: PageErrorTelemetry },
+ { failed: boolean }
+> {
+ public state = { failed: false };
+
+ public static getDerivedStateFromError(): { failed: boolean } {
+ return { failed: true };
+ }
+
+ public componentDidCatch(error: Error): void {
+ reportPageError(PAGE_NAME, 'render', undefined, error, 'render');
+ }
+
+ public render(): React.ReactNode {
+ if (this.state.failed) {
+ return (
+ <MessageBar intent="error">
+ <MessageBarBody>{translate('error.render')}</MessageBarBody>
+ </MessageBar>
+ );
+ }
+ return this.props.children;
+ }
+}
+
+// Mock page: no RuntimeTypes import (not generated for mock pages), so it declares its own props.
+type Props = { dataApi?: unknown; pageInput?: { id?: string } };
+
+function PageBody(props: Props) {
+ const { pageInput } = props;
+ void pageInput;
const fileInputRef = useRef<HTMLInputElement>(null); // Ref for hidden file input
const [uploadedFiles, setUploadedFiles] = useState<File[]>([]); // State for uploaded files
@@ -77,6 +189,12 @@ const GeneratedComponent = () => {
)}
</div>
);
-};
+}
+
+const GeneratedComponent = (props: Props) => (
+ <PageErrorBoundary>
+ <PageBody {...props} />
+ </PageErrorBoundary>
+);
export default GeneratedComponent;
diff --git a/plugins/model-apps/samples/5-navigation-sidebar.tsx b/plugins/model-apps/samples/5-navigation-sidebar.tsx
index 16d4d0358..624007bde 100644
--- a/plugins/model-apps/samples/5-navigation-sidebar.tsx
+++ b/plugins/model-apps/samples/5-navigation-sidebar.tsx
@@ -1,5 +1,112 @@
import React, { useState } from 'react';
-import { Button, Text, tokens } from '@fluentui/react-components';
+import { Button, Text, tokens, MessageBar, MessageBarBody } from '@fluentui/react-components';
+
+// ---------- Page errors ----------
+// The page error block of references/rules.md ("Missing Error Handling"), copied unchanged: every failed data
+// operation goes through reportPageError, PageErrorBar shows the view it returns, and the page renders inside
+// PageErrorBoundary.
+
+type PageErrorKind = 'read' | 'write' | 'indeterminate' | 'network' | 'render';
+type PageErrorView = {
+ operation: string;
+ message: string;
+ fallbackKey: string;
+ code?: string;
+ kind: PageErrorKind;
+ retry?: () => void;
+};
+type PageErrorTelemetry = {
+ trackException?: (error: unknown, properties?: Record<string, unknown>) => void;
+};
+
+// The plan's display name for this page: a fixed literal, not the file name.
+const PAGE_NAME = 'Navigation Sidebar';
+
+// The error copy of an English-only page. A localized page keeps these keys in its translations dictionary instead.
+const ERROR_COPY: Record<string, string> = {
+ 'error.read': 'Unable to load data. Please try again.',
+ 'error.write': 'The change could not be saved. Refresh before trying again.',
+ 'error.network': 'The request did not go through. You can try again.',
+ 'error.indeterminate': "We couldn't confirm this completed — refresh before retrying.",
+ 'error.render': 'This page hit a problem and could not render. Refresh the page.',
+ 'error.tryAgain': 'Try again',
+};
+
+function translate(key: string): string {
+ return ERROR_COPY[key] || key;
+}
+
+// The page's one error reporter. It logs bounded diagnostics once and returns the view the failed
+// operation stores; it never sets state, never calls retry, and reads only the named fields of a
+// thrown value, each on its own, so a throwing getter leaves that one field empty.
+function reportPageError(
+ pageName: string,
+ operation: string,
+ code: unknown,
+ message: unknown,
+ kind: PageErrorKind,
+ retry?: () => void,
+ appInsights?: PageErrorTelemetry,
+): PageErrorView {
+ const fields: Record<string, unknown> = {};
+ for (const path of ['code', 'errorCode', 'message', 'error.code', 'error.message']) {
+ try {
+ let value: unknown = message;
+ for (const part of path.split('.')) {
+ value = value !== null && typeof value === 'object' ? (value as Record<string, unknown>)[part] : undefined;
+ }
+ fields[path] = value;
+ } catch {
+ fields[path] = undefined;
+ }
+ }
+ let normalizedCode = '';
+ for (const candidate of [code, fields['code'], fields['errorCode'], fields['error.code']]) {
+ const text = typeof candidate === 'string' ? candidate : typeof candidate === 'number' && Number.isFinite(candidate) ? String(candidate) : '';
+ normalizedCode = text.replace(/[\s\u0000-\u001f\u007f-\u009f]+/g, ' ').trim().slice(0, 80);
+ if (normalizedCode) break;
+ }
+ let normalizedMessage = '';
+ for (const candidate of [message, fields['message'], fields['error.message']]) {
+ const line = typeof candidate === 'string' ? candidate.trim().split(/[\r\n\u2028\u2029]/)[0].replace(/[\s\u0000-\u001f\u007f-\u009f]+/g, ' ').trim() : '';
+ if (!line || /^\[object [^\]]*\]$/.test(line) || /^at\s.*(?::\d+:\d+\)?|\((?:native|<anonymous>)\))$/.test(line)) continue;
+ normalizedMessage = line.length > 300 ? line.slice(0, 299) + '\u2026' : line;
+ break;
+ }
+ console.error('[' + String(pageName).replace(/[\r\n\]]/g, '') + '] ' + operation + ' failed', { code: normalizedCode, message: normalizedMessage });
+ const quiet = kind === 'indeterminate' || kind === 'render';
+ const view: PageErrorView = { operation, message: quiet ? '' : normalizedMessage, fallbackKey: 'error.' + kind, kind };
+ if (normalizedCode) view.code = normalizedCode;
+ if (typeof retry === 'function' && (kind === 'read' || kind === 'network')) view.retry = retry;
+ return view;
+}
+
+// The page's one class component: it catches a render crash below it and shows a fixed message.
+class PageErrorBoundary extends React.Component<
+ { children: React.ReactNode; appInsights?: PageErrorTelemetry },
+ { failed: boolean }
+> {
+ public state = { failed: false };
+
+ public static getDerivedStateFromError(): { failed: boolean } {
+ return { failed: true };
+ }
+
+ public componentDidCatch(error: Error): void {
+ reportPageError(PAGE_NAME, 'render', undefined, error, 'render');
+ }
+
+ public render(): React.ReactNode {
+ if (this.state.failed) {
+ return (
+ <MessageBar intent="error">
+ <MessageBarBody>{translate('error.render')}</MessageBarBody>
+ </MessageBar>
+ );
+ }
+ return this.props.children;
+ }
+}
const sections = ['Home', 'About', 'Contact'];
const subsectionsMap: Record<string, string[]> = {
@@ -8,7 +115,12 @@ const subsectionsMap: Record<string, string[]> = {
Contact: ['Contact Subsection 1', 'Contact Subsection 2', 'Contact Subsection 3'],
};
-const GeneratedComponent = () => {
+// Mock page: no RuntimeTypes import (not generated for mock pages), so it declares its own props.
+type Props = { dataApi?: unknown; pageInput?: { id?: string } };
+
+function PageBody(props: Props) {
+ const { pageInput } = props;
+ void pageInput;
const [activeSection, setActiveSection] = useState('Home');
const [activeSubsection, setActiveSubsection] = useState('');
@@ -134,6 +246,12 @@ const GeneratedComponent = () => {
</div>
</div>
);
-};
+}
+
+const GeneratedComponent = (props: Props) => (
+ <PageErrorBoundary>
+ <PageBody {...props} />
+ </PageErrorBoundary>
+);
export default GeneratedComponent;
diff --git a/plugins/model-apps/samples/6-comprehensive-form.tsx b/plugins/model-apps/samples/6-comprehensive-form.tsx
index c9c4f8e7b..0433b6e27 100644
--- a/plugins/model-apps/samples/6-comprehensive-form.tsx
+++ b/plugins/model-apps/samples/6-comprehensive-form.tsx
@@ -1,9 +1,116 @@
import React, { useEffect, useState, useCallback, useRef } from 'react';
-import { Checkbox, Combobox, Field, Input, makeStyles, Option, Radio, RadioGroup, Slider, SpinButton, Switch, Textarea, tokens, Button, Text, Caption1, Subtitle1, Body1, MessageBar, useId as useFluentId, mergeClasses } from "@fluentui/react-components";
+import { Checkbox, Combobox, Field, Input, makeStyles, Option, Radio, RadioGroup, Slider, SpinButton, Switch, Textarea, tokens, Button, Text, Caption1, Subtitle1, Body1, MessageBar, useId as useFluentId, mergeClasses, MessageBarBody } from "@fluentui/react-components";
import { DatePicker } from "@fluentui/react-datepicker-compat";
import { TimePicker } from "@fluentui/react-timepicker-compat";
import { CheckmarkCircleFilled, ErrorCircleFilled } from "@fluentui/react-icons";
+// ---------- Page errors ----------
+// The page error block of references/rules.md ("Missing Error Handling"), copied unchanged: every failed data
+// operation goes through reportPageError, PageErrorBar shows the view it returns, and the page renders inside
+// PageErrorBoundary.
+
+type PageErrorKind = 'read' | 'write' | 'indeterminate' | 'network' | 'render';
+type PageErrorView = {
+ operation: string;
+ message: string;
+ fallbackKey: string;
+ code?: string;
+ kind: PageErrorKind;
+ retry?: () => void;
+};
+type PageErrorTelemetry = {
+ trackException?: (error: unknown, properties?: Record<string, unknown>) => void;
+};
+
+// The plan's display name for this page: a fixed literal, not the file name.
+const PAGE_NAME = 'User Information Form';
+
+// The error copy of an English-only page. A localized page keeps these keys in its translations dictionary instead.
+const ERROR_COPY: Record<string, string> = {
+ 'error.read': 'Unable to load data. Please try again.',
+ 'error.write': 'The change could not be saved. Refresh before trying again.',
+ 'error.network': 'The request did not go through. You can try again.',
+ 'error.indeterminate': "We couldn't confirm this completed — refresh before retrying.",
+ 'error.render': 'This page hit a problem and could not render. Refresh the page.',
+ 'error.tryAgain': 'Try again',
+};
+
+function translate(key: string): string {
+ return ERROR_COPY[key] || key;
+}
+
+// The page's one error reporter. It logs bounded diagnostics once and returns the view the failed
+// operation stores; it never sets state, never calls retry, and reads only the named fields of a
+// thrown value, each on its own, so a throwing getter leaves that one field empty.
+function reportPageError(
+ pageName: string,
+ operation: string,
+ code: unknown,
+ message: unknown,
+ kind: PageErrorKind,
+ retry?: () => void,
+ appInsights?: PageErrorTelemetry,
+): PageErrorView {
+ const fields: Record<string, unknown> = {};
+ for (const path of ['code', 'errorCode', 'message', 'error.code', 'error.message']) {
+ try {
+ let value: unknown = message;
+ for (const part of path.split('.')) {
+ value = value !== null && typeof value === 'object' ? (value as Record<string, unknown>)[part] : undefined;
+ }
+ fields[path] = value;
+ } catch {
+ fields[path] = undefined;
+ }
+ }
+ let normalizedCode = '';
+ for (const candidate of [code, fields['code'], fields['errorCode'], fields['error.code']]) {
+ const text = typeof candidate === 'string' ? candidate : typeof candidate === 'number' && Number.isFinite(candidate) ? String(candidate) : '';
+ normalizedCode = text.replace(/[\s\u0000-\u001f\u007f-\u009f]+/g, ' ').trim().slice(0, 80);
+ if (normalizedCode) break;
+ }
+ let normalizedMessage = '';
+ for (const candidate of [message, fields['message'], fields['error.message']]) {
+ const line = typeof candidate === 'string' ? candidate.trim().split(/[\r\n\u2028\u2029]/)[0].replace(/[\s\u0000-\u001f\u007f-\u009f]+/g, ' ').trim() : '';
+ if (!line || /^\[object [^\]]*\]$/.test(line) || /^at\s.*(?::\d+:\d+\)?|\((?:native|<anonymous>)\))$/.test(line)) continue;
+ normalizedMessage = line.length > 300 ? line.slice(0, 299) + '\u2026' : line;
+ break;
+ }
+ console.error('[' + String(pageName).replace(/[\r\n\]]/g, '') + '] ' + operation + ' failed', { code: normalizedCode, message: normalizedMessage });
+ const quiet = kind === 'indeterminate' || kind === 'render';
+ const view: PageErrorView = { operation, message: quiet ? '' : normalizedMessage, fallbackKey: 'error.' + kind, kind };
+ if (normalizedCode) view.code = normalizedCode;
+ if (typeof retry === 'function' && (kind === 'read' || kind === 'network')) view.retry = retry;
+ return view;
+}
+
+// The page's one class component: it catches a render crash below it and shows a fixed message.
+class PageErrorBoundary extends React.Component<
+ { children: React.ReactNode; appInsights?: PageErrorTelemetry },
+ { failed: boolean }
+> {
+ public state = { failed: false };
+
+ public static getDerivedStateFromError(): { failed: boolean } {
+ return { failed: true };
+ }
+
+ public componentDidCatch(error: Error): void {
+ reportPageError(PAGE_NAME, 'render', undefined, error, 'render');
+ }
+
+ public render(): React.ReactNode {
+ if (this.state.failed) {
+ return (
+ <MessageBar intent="error">
+ <MessageBarBody>{translate('error.render')}</MessageBarBody>
+ </MessageBar>
+ );
+ }
+ return this.props.children;
+ }
+}
+
const useStyles = makeStyles({
container: { display: "flex", flexDirection: "column", gap: tokens.spacingVerticalXL, padding: tokens.spacingHorizontalM, maxWidth: "800px", margin: "0 auto", width: "100%", boxSizing: "border-box", height: '100%', overflowY: 'auto', "@media (max-width: 768px)": { padding: tokens.spacingHorizontalS, gap: tokens.spacingVerticalL }, "@media (max-width: 480px)": { padding: tokens.spacingHorizontalXS } },
formSection: { display: "flex", flexDirection: "column", gap: tokens.spacingVerticalL, padding: tokens.spacingHorizontalL, borderRadius: tokens.borderRadiusMedium, border: `1px solid ${tokens.colorNeutralStroke2}`, backgroundColor: tokens.colorNeutralBackground1, "@media (max-width: 768px)": { padding: tokens.spacingHorizontalM }, "@media (max-width: 480px)": { padding: tokens.spacingHorizontalS } },
@@ -38,7 +145,12 @@ const FormSection: React.FC<FormSectionProps> = ({ title, description, children,
);
};
-const GeneratedComponent: React.FC = () => {
+// Mock page: no RuntimeTypes import (not generated for mock pages), so it declares its own props.
+type Props = { dataApi?: unknown; pageInput?: { id?: string } };
+
+function PageBody(props: Props) {
+ const { pageInput } = props;
+ void pageInput;
const styles = useStyles();
const containerRef = useRef<HTMLDivElement>(null);
const [formData, setFormData] = useState<FormData>({ textInput: "", textArea: "", comboboxValue: "", spinButtonValue: 0, checkboxChecked: false, sliderValue: 25, switchEnabled: false, radioSelection: "", email: "", phone: "", dateOfBirth: null, preferredContactTime: "" });
@@ -161,6 +273,12 @@ const GeneratedComponent: React.FC = () => {
{Object.keys(errors).length > 0 && <div className={styles.validationSummary} role="alert" aria-live="polite" aria-label="Form validation errors"><Text weight="semibold" style={{ color: tokens.colorPaletteRedForeground1 }}>Please correct the following errors:</Text><ul style={{ margin: `${tokens.spacingVerticalXS} 0`, paddingLeft: tokens.spacingHorizontalM }}>{Object.entries(errors).map(([field, error]) => (<li key={field} style={{ color: tokens.colorPaletteRedForeground1 }}><Caption1>{error}</Caption1></li>))}</ul></div>}
</div>
);
-};
+}
+
+const GeneratedComponent = (props: Props) => (
+ <PageErrorBoundary>
+ <PageBody {...props} />
+ </PageErrorBoundary>
+);
export default GeneratedComponent;
diff --git a/plugins/model-apps/samples/7-responsive-cards.tsx b/plugins/model-apps/samples/7-responsive-cards.tsx
index b79cc2028..36692ce90 100644
--- a/plugins/model-apps/samples/7-responsive-cards.tsx
+++ b/plugins/model-apps/samples/7-responsive-cards.tsx
@@ -1,6 +1,113 @@
import React from 'react';
-import { makeStyles, tokens, Button, Text, Caption1, Subtitle1, Body1, mergeClasses, Card, CardHeader, useId } from '@fluentui/react-components';
-import { MoreHorizontal20Regular } from '@fluentui/react-icons';
+import { makeStyles, tokens, Button, Text, Caption1, Subtitle1, Body1, mergeClasses, Card, CardHeader, useId, MessageBar, MessageBarBody } from '@fluentui/react-components';
+import { MoreHorizontalRegular } from '@fluentui/react-icons';
+
+// ---------- Page errors ----------
+// The page error block of references/rules.md ("Missing Error Handling"), copied unchanged: every failed data
+// operation goes through reportPageError, PageErrorBar shows the view it returns, and the page renders inside
+// PageErrorBoundary.
+
+type PageErrorKind = 'read' | 'write' | 'indeterminate' | 'network' | 'render';
+type PageErrorView = {
+ operation: string;
+ message: string;
+ fallbackKey: string;
+ code?: string;
+ kind: PageErrorKind;
+ retry?: () => void;
+};
+type PageErrorTelemetry = {
+ trackException?: (error: unknown, properties?: Record<string, unknown>) => void;
+};
+
+// The plan's display name for this page: a fixed literal, not the file name.
+const PAGE_NAME = 'Responsive Cards';
+
+// The error copy of an English-only page. A localized page keeps these keys in its translations dictionary instead.
+const ERROR_COPY: Record<string, string> = {
+ 'error.read': 'Unable to load data. Please try again.',
+ 'error.write': 'The change could not be saved. Refresh before trying again.',
+ 'error.network': 'The request did not go through. You can try again.',
+ 'error.indeterminate': "We couldn't confirm this completed — refresh before retrying.",
+ 'error.render': 'This page hit a problem and could not render. Refresh the page.',
+ 'error.tryAgain': 'Try again',
+};
+
+function translate(key: string): string {
+ return ERROR_COPY[key] || key;
+}
+
+// The page's one error reporter. It logs bounded diagnostics once and returns the view the failed
+// operation stores; it never sets state, never calls retry, and reads only the named fields of a
+// thrown value, each on its own, so a throwing getter leaves that one field empty.
+function reportPageError(
+ pageName: string,
+ operation: string,
+ code: unknown,
+ message: unknown,
+ kind: PageErrorKind,
+ retry?: () => void,
+ appInsights?: PageErrorTelemetry,
+): PageErrorView {
+ const fields: Record<string, unknown> = {};
+ for (const path of ['code', 'errorCode', 'message', 'error.code', 'error.message']) {
+ try {
+ let value: unknown = message;
+ for (const part of path.split('.')) {
+ value = value !== null && typeof value === 'object' ? (value as Record<string, unknown>)[part] : undefined;
+ }
+ fields[path] = value;
+ } catch {
+ fields[path] = undefined;
+ }
+ }
+ let normalizedCode = '';
+ for (const candidate of [code, fields['code'], fields['errorCode'], fields['error.code']]) {
+ const text = typeof candidate === 'string' ? candidate : typeof candidate === 'number' && Number.isFinite(candidate) ? String(candidate) : '';
+ normalizedCode = text.replace(/[\s\u0000-\u001f\u007f-\u009f]+/g, ' ').trim().slice(0, 80);
+ if (normalizedCode) break;
+ }
+ let normalizedMessage = '';
+ for (const candidate of [message, fields['message'], fields['error.message']]) {
+ const line = typeof candidate === 'string' ? candidate.trim().split(/[\r\n\u2028\u2029]/)[0].replace(/[\s\u0000-\u001f\u007f-\u009f]+/g, ' ').trim() : '';
+ if (!line || /^\[object [^\]]*\]$/.test(line) || /^at\s.*(?::\d+:\d+\)?|\((?:native|<anonymous>)\))$/.test(line)) continue;
+ normalizedMessage = line.length > 300 ? line.slice(0, 299) + '\u2026' : line;
+ break;
+ }
+ console.error('[' + String(pageName).replace(/[\r\n\]]/g, '') + '] ' + operation + ' failed', { code: normalizedCode, message: normalizedMessage });
+ const quiet = kind === 'indeterminate' || kind === 'render';
+ const view: PageErrorView = { operation, message: quiet ? '' : normalizedMessage, fallbackKey: 'error.' + kind, kind };
+ if (normalizedCode) view.code = normalizedCode;
+ if (typeof retry === 'function' && (kind === 'read' || kind === 'network')) view.retry = retry;
+ return view;
+}
+
+// The page's one class component: it catches a render crash below it and shows a fixed message.
+class PageErrorBoundary extends React.Component<
+ { children: React.ReactNode; appInsights?: PageErrorTelemetry },
+ { failed: boolean }
+> {
+ public state = { failed: false };
+
+ public static getDerivedStateFromError(): { failed: boolean } {
+ return { failed: true };
+ }
+
+ public componentDidCatch(error: Error): void {
+ reportPageError(PAGE_NAME, 'render', undefined, error, 'render');
+ }
+
+ public render(): React.ReactNode {
+ if (this.state.failed) {
+ return (
+ <MessageBar intent="error">
+ <MessageBarBody>{translate('error.render')}</MessageBarBody>
+ </MessageBar>
+ );
+ }
+ return this.props.children;
+ }
+}
const useStyles = makeStyles({
container: { display: 'flex', flexDirection: 'column', gap: tokens.spacingVerticalXXL, padding: tokens.spacingHorizontalM, width: '100%', boxSizing: 'border-box', '@media (max-width: 768px)': { padding: tokens.spacingHorizontalS } },
@@ -31,13 +138,18 @@ const ResponsiveCard: React.FC<{ appearance?: 'filled' | 'filled-alternative' |
const handleKeyDown = React.useCallback((e: React.KeyboardEvent) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); handleCardClick(); } }, [handleCardClick]);
return (
<Card appearance={appearance} className={mergeClasses(styles.card, className)} onClick={handleCardClick} onKeyDown={handleKeyDown} tabIndex={0} role="button" aria-labelledby={ariaLabelledBy} aria-describedby={ariaDescribedBy} id={cardId}>
- <CardHeader image={<div className={styles.logo} role="img" aria-label="Application logo">📱</div>} header={<Text as="h3" className={styles.cardHeader} block>Mobile App</Text>} description={<Caption1 className={styles.cardCaption} block>Development Team</Caption1>} action={<Button appearance="transparent" icon={<MoreHorizontal20Regular />} aria-label="More options for Mobile App" onClick={(e) => { e.stopPropagation(); console.log('More options clicked'); }} />} />
+ <CardHeader image={<div className={styles.logo} role="img" aria-label="Application logo">📱</div>} header={<Text as="h3" className={styles.cardHeader} block>Mobile App</Text>} description={<Caption1 className={styles.cardCaption} block>Development Team</Caption1>} action={<Button appearance="transparent" icon={<MoreHorizontalRegular />} aria-label="More options for Mobile App" onClick={(e) => { e.stopPropagation(); console.log('More options clicked'); }} />} />
<div className={styles.cardContent}><Text block>A comprehensive mobile application that provides seamless user experience across all devices with responsive design and accessibility features built-in.</Text></div>
</Card>
);
};
-const ResponsiveCardShowcase: React.FC = () => {
+// Mock page: no RuntimeTypes import (not generated for mock pages), so it declares its own props.
+type Props = { dataApi?: unknown; pageInput?: { id?: string } };
+
+function PageBody(props: Props) {
+ const { pageInput } = props;
+ void pageInput;
const styles = useStyles();
const sections = [
{ id: 'filled', title: 'Filled Cards (Default)', description: 'Standard card style with filled background. Use for most card designs with clear visual separation.', appearance: 'filled' as const },
@@ -59,6 +171,12 @@ const ResponsiveCardShowcase: React.FC = () => {
})}
</div>
);
-};
+}
+
+const GeneratedComponent = (props: Props) => (
+ <PageErrorBoundary>
+ <PageBody {...props} />
+ </PageErrorBoundary>
+);
-export default ResponsiveCardShowcase;
+export default GeneratedComponent;
diff --git a/plugins/model-apps/samples/8-dashboard-with-charts.tsx b/plugins/model-apps/samples/8-dashboard-with-charts.tsx
index e1bc18dec..05bea6174 100644
--- a/plugins/model-apps/samples/8-dashboard-with-charts.tsx
+++ b/plugins/model-apps/samples/8-dashboard-with-charts.tsx
@@ -5,6 +5,8 @@ import {
Text,
Card,
CardHeader,
+ MessageBar,
+ MessageBarBody,
} from '@fluentui/react-components';
import {
ArrowTrendingRegular,
@@ -13,6 +15,113 @@ import {
} from '@fluentui/react-icons';
import * as d3 from 'd3';
+// ---------- Page errors ----------
+// The page error block of references/rules.md ("Missing Error Handling"), copied unchanged: every failed data
+// operation goes through reportPageError, PageErrorBar shows the view it returns, and the page renders inside
+// PageErrorBoundary.
+
+type PageErrorKind = 'read' | 'write' | 'indeterminate' | 'network' | 'render';
+type PageErrorView = {
+ operation: string;
+ message: string;
+ fallbackKey: string;
+ code?: string;
+ kind: PageErrorKind;
+ retry?: () => void;
+};
+type PageErrorTelemetry = {
+ trackException?: (error: unknown, properties?: Record<string, unknown>) => void;
+};
+
+// The plan's display name for this page: a fixed literal, not the file name.
+const PAGE_NAME = 'Sales Dashboard';
+
+// The error copy of an English-only page. A localized page keeps these keys in its translations dictionary instead.
+const ERROR_COPY: Record<string, string> = {
+ 'error.read': 'Unable to load data. Please try again.',
+ 'error.write': 'The change could not be saved. Refresh before trying again.',
+ 'error.network': 'The request did not go through. You can try again.',
+ 'error.indeterminate': "We couldn't confirm this completed — refresh before retrying.",
+ 'error.render': 'This page hit a problem and could not render. Refresh the page.',
+ 'error.tryAgain': 'Try again',
+};
+
+function translate(key: string): string {
+ return ERROR_COPY[key] || key;
+}
+
+// The page's one error reporter. It logs bounded diagnostics once and returns the view the failed
+// operation stores; it never sets state, never calls retry, and reads only the named fields of a
+// thrown value, each on its own, so a throwing getter leaves that one field empty.
+function reportPageError(
+ pageName: string,
+ operation: string,
+ code: unknown,
+ message: unknown,
+ kind: PageErrorKind,
+ retry?: () => void,
+ appInsights?: PageErrorTelemetry,
+): PageErrorView {
+ const fields: Record<string, unknown> = {};
+ for (const path of ['code', 'errorCode', 'message', 'error.code', 'error.message']) {
+ try {
+ let value: unknown = message;
+ for (const part of path.split('.')) {
+ value = value !== null && typeof value === 'object' ? (value as Record<string, unknown>)[part] : undefined;
+ }
+ fields[path] = value;
+ } catch {
+ fields[path] = undefined;
+ }
+ }
+ let normalizedCode = '';
+ for (const candidate of [code, fields['code'], fields['errorCode'], fields['error.code']]) {
+ const text = typeof candidate === 'string' ? candidate : typeof candidate === 'number' && Number.isFinite(candidate) ? String(candidate) : '';
+ normalizedCode = text.replace(/[\s\u0000-\u001f\u007f-\u009f]+/g, ' ').trim().slice(0, 80);
+ if (normalizedCode) break;
+ }
+ let normalizedMessage = '';
+ for (const candidate of [message, fields['message'], fields['error.message']]) {
+ const line = typeof candidate === 'string' ? candidate.trim().split(/[\r\n\u2028\u2029]/)[0].replace(/[\s\u0000-\u001f\u007f-\u009f]+/g, ' ').trim() : '';
+ if (!line || /^\[object [^\]]*\]$/.test(line) || /^at\s.*(?::\d+:\d+\)?|\((?:native|<anonymous>)\))$/.test(line)) continue;
+ normalizedMessage = line.length > 300 ? line.slice(0, 299) + '\u2026' : line;
+ break;
+ }
+ console.error('[' + String(pageName).replace(/[\r\n\]]/g, '') + '] ' + operation + ' failed', { code: normalizedCode, message: normalizedMessage });
+ const quiet = kind === 'indeterminate' || kind === 'render';
+ const view: PageErrorView = { operation, message: quiet ? '' : normalizedMessage, fallbackKey: 'error.' + kind, kind };
+ if (normalizedCode) view.code = normalizedCode;
+ if (typeof retry === 'function' && (kind === 'read' || kind === 'network')) view.retry = retry;
+ return view;
+}
+
+// The page's one class component: it catches a render crash below it and shows a fixed message.
+class PageErrorBoundary extends React.Component<
+ { children: React.ReactNode; appInsights?: PageErrorTelemetry },
+ { failed: boolean }
+> {
+ public state = { failed: false };
+
+ public static getDerivedStateFromError(): { failed: boolean } {
+ return { failed: true };
+ }
+
+ public componentDidCatch(error: Error): void {
+ reportPageError(PAGE_NAME, 'render', undefined, error, 'render');
+ }
+
+ public render(): React.ReactNode {
+ if (this.state.failed) {
+ return (
+ <MessageBar intent="error">
+ <MessageBarBody>{translate('error.render')}</MessageBarBody>
+ </MessageBar>
+ );
+ }
+ return this.props.children;
+ }
+}
+
// Sample: dashboard layout with KPI summary cards + two D3 charts.
// Demonstrates:
// - Rule 9: unsized icons (ArrowTrendingRegular, not ArrowTrending24Regular)
@@ -285,7 +394,7 @@ const CustomerSegmentsChart = () => {
// ---------- Main component ----------
-const GeneratedComponent = (props: { dataApi?: unknown; pageInput?: { data?: Record<string, unknown> } }) => {
+function PageBody(props: { dataApi?: unknown; pageInput?: { data?: Record<string, unknown> } }) {
const { pageInput } = props;
// pageInput is destructured per rules but unused on a mock dashboard.
void pageInput;
@@ -330,6 +439,12 @@ const GeneratedComponent = (props: { dataApi?: unknown; pageInput?: { data?: Rec
</section>
</div>
);
-};
+}
+
+const GeneratedComponent = (props: { dataApi?: unknown; pageInput?: { data?: Record<string, unknown> } }) => (
+ <PageErrorBoundary>
+ <PageBody {...props} />
+ </PageErrorBoundary>
+);
export default GeneratedComponent;
diff --git a/plugins/model-apps/samples/9-list-with-caching.tsx b/plugins/model-apps/samples/9-list-with-caching.tsx
index d8dc236f1..81098b890 100644
--- a/plugins/model-apps/samples/9-list-with-caching.tsx
+++ b/plugins/model-apps/samples/9-list-with-caching.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState } from 'react';
+import React, { useEffect, useState } from 'react';
import type {
TableRow,
ReadableTableRow,
@@ -19,9 +19,134 @@ import {
TableCellLayout,
createTableColumn,
SearchBox,
+ MessageBar,
+ MessageBarBody,
+ MessageBarActions,
} from '@fluentui/react-components';
import { SearchRegular } from '@fluentui/react-icons';
+// ---------- Page errors ----------
+// The page error block of references/rules.md ("Missing Error Handling"), copied unchanged: every failed data
+// operation goes through reportPageError, PageErrorBar shows the view it returns, and the page renders inside
+// PageErrorBoundary.
+
+type PageErrorKind = 'read' | 'write' | 'indeterminate' | 'network' | 'render';
+type PageErrorView = {
+ operation: string;
+ message: string;
+ fallbackKey: string;
+ code?: string;
+ kind: PageErrorKind;
+ retry?: () => void;
+};
+type PageErrorTelemetry = {
+ trackException?: (error: unknown, properties?: Record<string, unknown>) => void;
+};
+
+// The plan's display name for this page: a fixed literal, not the file name.
+const PAGE_NAME = 'Contacts';
+
+// The error copy of an English-only page. A localized page keeps these keys in its translations dictionary instead.
+const ERROR_COPY: Record<string, string> = {
+ 'error.read': 'Unable to load data. Please try again.',
+ 'error.write': 'The change could not be saved. Refresh before trying again.',
+ 'error.network': 'The request did not go through. You can try again.',
+ 'error.indeterminate': "We couldn't confirm this completed — refresh before retrying.",
+ 'error.render': 'This page hit a problem and could not render. Refresh the page.',
+ 'error.tryAgain': 'Try again',
+};
+
+function translate(key: string): string {
+ return ERROR_COPY[key] || key;
+}
+
+// The page's one error reporter. It logs bounded diagnostics once and returns the view the failed
+// operation stores; it never sets state, never calls retry, and reads only the named fields of a
+// thrown value, each on its own, so a throwing getter leaves that one field empty.
+function reportPageError(
+ pageName: string,
+ operation: string,
+ code: unknown,
+ message: unknown,
+ kind: PageErrorKind,
+ retry?: () => void,
+ appInsights?: PageErrorTelemetry,
+): PageErrorView {
+ const fields: Record<string, unknown> = {};
+ for (const path of ['code', 'errorCode', 'message', 'error.code', 'error.message']) {
+ try {
+ let value: unknown = message;
+ for (const part of path.split('.')) {
+ value = value !== null && typeof value === 'object' ? (value as Record<string, unknown>)[part] : undefined;
+ }
+ fields[path] = value;
+ } catch {
+ fields[path] = undefined;
+ }
+ }
+ let normalizedCode = '';
+ for (const candidate of [code, fields['code'], fields['errorCode'], fields['error.code']]) {
+ const text = typeof candidate === 'string' ? candidate : typeof candidate === 'number' && Number.isFinite(candidate) ? String(candidate) : '';
+ normalizedCode = text.replace(/[\s\u0000-\u001f\u007f-\u009f]+/g, ' ').trim().slice(0, 80);
+ if (normalizedCode) break;
+ }
+ let normalizedMessage = '';
+ for (const candidate of [message, fields['message'], fields['error.message']]) {
+ const line = typeof candidate === 'string' ? candidate.trim().split(/[\r\n\u2028\u2029]/)[0].replace(/[\s\u0000-\u001f\u007f-\u009f]+/g, ' ').trim() : '';
+ if (!line || /^\[object [^\]]*\]$/.test(line) || /^at\s.*(?::\d+:\d+\)?|\((?:native|<anonymous>)\))$/.test(line)) continue;
+ normalizedMessage = line.length > 300 ? line.slice(0, 299) + '\u2026' : line;
+ break;
+ }
+ console.error('[' + String(pageName).replace(/[\r\n\]]/g, '') + '] ' + operation + ' failed', { code: normalizedCode, message: normalizedMessage });
+ const quiet = kind === 'indeterminate' || kind === 'render';
+ const view: PageErrorView = { operation, message: quiet ? '' : normalizedMessage, fallbackKey: 'error.' + kind, kind };
+ if (normalizedCode) view.code = normalizedCode;
+ if (typeof retry === 'function' && (kind === 'read' || kind === 'network')) view.retry = retry;
+ return view;
+}
+
+function PageErrorBar(props: { error: PageErrorView | null }) {
+ const { error } = props;
+ if (!error) return null;
+ return (
+ <MessageBar intent="error">
+ <MessageBarBody>{error.message || translate(error.fallbackKey)}</MessageBarBody>
+ {error.retry && (
+ <MessageBarActions>
+ <Button onClick={error.retry}>{translate('error.tryAgain')}</Button>
+ </MessageBarActions>
+ )}
+ </MessageBar>
+ );
+}
+
+// The page's one class component: it catches a render crash below it and shows a fixed message.
+class PageErrorBoundary extends React.Component<
+ { children: React.ReactNode; appInsights?: PageErrorTelemetry },
+ { failed: boolean }
+> {
+ public state = { failed: false };
+
+ public static getDerivedStateFromError(): { failed: boolean } {
+ return { failed: true };
+ }
+
+ public componentDidCatch(error: Error): void {
+ reportPageError(PAGE_NAME, 'render', undefined, error, 'render');
+ }
+
+ public render(): React.ReactNode {
+ if (this.state.failed) {
+ return (
+ <MessageBar intent="error">
+ <MessageBarBody>{translate('error.render')}</MessageBarBody>
+ </MessageBar>
+ );
+ }
+ return this.props.children;
+ }
+}
+
// Sample: list page with data fetching (Rule 15).
// Demonstrates:
// - Rule 14: SINGLE batched setData({records, loading, error}) — no separate setState
@@ -31,6 +156,8 @@ import { SearchRegular } from '@fluentui/react-icons';
// - Cross-page navigation via Xrm.Navigation.navigateTo to a sibling generative page
// - PAGEREF_ placeholder for the detail page (multi-page-build pattern)
// - DataGrid with createTableColumn + columnSizingOptions
+// - Rule 22: a failed load goes through reportPageError, is never cached, and
+// PageErrorBar shows it with a manual "Try again"; the page renders inside PageErrorBoundary
type ContactRow = TableRow<{
readonly contactid: string;
@@ -75,31 +202,35 @@ const useStyles = makeStyles({
justifyContent: 'center',
padding: tokens.spacingVerticalXXL,
},
- errorBanner: {
- padding: tokens.spacingHorizontalM,
- backgroundColor: tokens.colorStatusDangerBackground2,
- color: tokens.colorStatusDangerForeground2,
- borderRadius: tokens.borderRadiusMedium,
- },
});
// ---------- Component ----------
-const GeneratedComponent = (props: GeneratedComponentProps) => {
+function PageBody(props: GeneratedComponentProps) {
const { dataApi, pageInput } = props;
void pageInput; // list page doesn't take input; destructure anyway per rules
const styles = useStyles();
- const [data, setData] = useState<{ records: ReadableContact[]; loading: boolean; error: string | null }>(
+ // `error` is the view reportPageError returns, rendered by PageErrorBar — never a string.
+ const [data, setData] = useState<{ records: ReadableContact[]; loading: boolean; error: PageErrorView | null }>(
() => {
const cached = winAny[CACHE_KEY] as ReadableContact[] | undefined;
return { records: cached ?? [], loading: cached === undefined, error: null };
},
);
const [search, setSearch] = useState('');
+ const [reloadKey, setReloadKey] = useState(0);
const dataReady = !!dataApi;
+ // "Try again" after a failed load: drop the failed in-flight entry and run the effect again.
+ function retryLoad() {
+ delete winAny[CACHE_KEY];
+ delete winAny[INFLIGHT_KEY];
+ setData({ records: [], loading: true, error: null });
+ setReloadKey((key) => key + 1);
+ }
+
useEffect(() => {
if (!dataReady) return; // wait until the host hands us the DataAPI
@@ -135,17 +266,18 @@ const GeneratedComponent = (props: GeneratedComponentProps) => {
inflight
.then((rows) => { if (!cancelled) setData({ records: rows, loading: false, error: null }); })
- .catch((err) => {
+ .catch((failure) => {
if (cancelled) return;
- const message = err instanceof Error ? err.message : 'Failed to load contacts.';
- setData({ records: [], loading: false, error: message });
+ // Reported once — bounded code and message, never the thrown value — and shown with a retry.
+ // A rejection is never written to the cache, so "Try again" reads again.
+ setData({ records: [], loading: false, error: reportPageError(PAGE_NAME, 'loadContacts', undefined, failure, 'read', retryLoad) });
});
return () => { cancelled = true; };
// Depend on readiness only — never `dataApi` (new ref each render would
// re-fire this effect on every render). See Rule 15.
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [dataReady]);
+ }, [dataReady, reloadKey]);
const filtered = data.records.filter((c) => {
if (!search) return true;
@@ -220,11 +352,7 @@ const GeneratedComponent = (props: GeneratedComponentProps) => {
/>
</header>
- {data.error && (
- <div role="alert" className={styles.errorBanner}>
- {data.error}
- </div>
- )}
+ <PageErrorBar error={data.error} />
<DataGrid
items={filtered}
@@ -264,6 +392,12 @@ const GeneratedComponent = (props: GeneratedComponentProps) => {
</DataGrid>
</div>
);
-};
+}
+
+const GeneratedComponent = (props: GeneratedComponentProps) => (
+ <PageErrorBoundary>
+ <PageBody {...props} />
+ </PageErrorBoundary>
+);
export default GeneratedComponent;
diff --git a/plugins/model-apps/scripts/add-page-to-solution.js b/plugins/model-apps/scripts/add-page-to-solution.js
index 41536ad9e..917892b8d 100644
--- a/plugins/model-apps/scripts/add-page-to-solution.js
+++ b/plugins/model-apps/scripts/add-page-to-solution.js
@@ -12,10 +12,16 @@
// `import --settings` applies it; `pac solution create-settings` and `pac solution import
// --settings-file` are only its fallback).
// Both are custom tables whose ObjectTypeCode varies by environment, so their
-// component types are discovered from EntityDefinitions before any mutation.
+// component types are discovered from EntityDefinitions before any mutation
+// (lib/page-solution.js holds the read, and how a page is added, for every path that adds one).
+//
+// The app id is optional: with none, only the pages (and connection references) are added. That is how a page made into
+// an app that is not the run's own — or one whose add failed after it was made — joins a solution: a page is a component of
+// its own, and an app is not one of its required components (the app's navigation names the page, not the reverse), so adding
+// the app too would put an app the maker did not ask for into the solution.
//
// Usage:
-// node add-page-to-solution.js <envUrl> <solutionUniqueName> <appId>
+// node add-page-to-solution.js <envUrl> <solutionUniqueName> [<appId>]
// [--page-ids <uxagentprojectId1,uxagentprojectId2>]
// [--connection-refs <logicalName1,logicalName2>]
//
@@ -31,8 +37,8 @@ const {
const { odataLit } = require('./lib/odata');
const { FORM_GUID_RE } = require('./lib/app-spec');
const { makeWritesBlocking } = require('./lib/output-redaction.js');
+const { UXAGENTPROJECT_LOGICAL_NAME, PAGE_ADD_REQUIRED_COMPONENTS, componentTypePath, componentTypeOf } = require('./lib/page-solution.js');
const APPMODULE_COMPONENT_TYPE = 80;
-const UXAGENTPROJECT_LOGICAL_NAME = 'uxagentproject';
const CONNECTION_REFERENCE_LOGICAL_NAME = 'connectionreference';
async function addComponent(envUrl, solutionUniqueName, componentId, componentType, addRequired) {
@@ -47,14 +53,9 @@ async function addComponent(envUrl, solutionUniqueName, componentId, componentTy
}
async function resolveEntityComponentType(envUrl, logicalName) {
- const path = `EntityDefinitions(LogicalName='${odataLit(logicalName)}')?$select=ObjectTypeCode`;
- const res = await dataverseRequest(envUrl, 'GET', path);
+ const res = await dataverseRequest(envUrl, 'GET', componentTypePath(logicalName));
ensureOk(res, `Resolve component type for ${logicalName}`);
- const componentType = Number(res.data?.ObjectTypeCode);
- if (!Number.isInteger(componentType) || componentType <= 0) {
- throw new Error(`Entity '${logicalName}' did not return a valid ObjectTypeCode`);
- }
- return componentType;
+ return componentTypeOf(res.data, logicalName);
}
async function resolveConnectionReferences(envUrl, refs) {
@@ -83,7 +84,7 @@ async function resolveConnectionReferences(envUrl, refs) {
async function main() {
const argv = process.argv.slice(2);
const { positional, flags } = parseArgs(argv);
- const USAGE = 'Usage: node add-page-to-solution.js <envUrl> <solutionUniqueName> <appId> [--page-ids <id1,id2>] [--connection-refs <logicalName1,logicalName2>]';
+ const USAGE = 'Usage: node add-page-to-solution.js <envUrl> <solutionUniqueName> [<appId>] [--page-ids <id1,id2>] [--connection-refs <logicalName1,logicalName2>]';
// Both flags are comma-joined id lists. A bare one would become boolean `true`, and `true.split`
// is a TypeError mid-way through packaging rather than a usage error before it.
const flagError = validateFlags(argv, {
@@ -95,7 +96,8 @@ async function main() {
process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);
process.exit(1);
}
- if (positional.length < 3) {
+ // The app is optional, but something has to be named to add: an app, pages, or connection references.
+ if (positional.length < 2 || (positional.length < 3 && !flags['page-ids'] && !flags['connection-refs'])) {
process.stderr.write(USAGE + '\n');
process.exit(1);
}
@@ -126,13 +128,18 @@ async function main() {
// Dataverse only at its own AddSolutionComponent — after the app had been added — so the run failed
// with the solution holding the app but not its page.
const malformed = [
- ...(FORM_GUID_RE.test(appId) ? [] : [`app id '${appId}'`]),
+ ...(appId === undefined || FORM_GUID_RE.test(appId) ? [] : [`app id '${appId}'`]),
...pageIds.filter((id) => !FORM_GUID_RE.test(id)).map((id) => `page id '${id}'`),
];
if (malformed.length) {
emitResult(false, new Error(`Not a GUID: ${malformed.join(', ')}. Nothing was added to ${solutionUniqueName}.`));
return;
}
+ // A list that holds only separators (`--page-ids ,`) names nothing, and with no app that is a run with nothing to do: said, not reported as done.
+ if (appId === undefined && !pageIds.length && !refs.length) {
+ emitResult(false, new Error(`Nothing to add: name an app, --page-ids or --connection-refs. Nothing was added to ${solutionUniqueName}.`));
+ return;
+ }
try {
// ObjectTypeCode for custom tables is allocated per environment. Resolve both
// types before the first AddSolutionComponent so a metadata failure leaves the
@@ -148,15 +155,19 @@ async function main() {
: [];
// The appmodule (type 80) with AddRequiredComponents=true pulls the sitemap and
- // appmodulecomponent, but NOT the GenPage — the page is added explicitly below.
- await addComponent(envUrl, solutionUniqueName, appId, APPMODULE_COMPONENT_TYPE, true);
- added.push({ type: 'appmodule', id: appId });
+ // appmodulecomponent, but NOT the GenPage — the page is added explicitly below. When an app is
+ // named it goes first, so a run that stops part-way never leaves pages in the solution without
+ // the app whose navigation opens them.
+ if (appId !== undefined) {
+ await addComponent(envUrl, solutionUniqueName, appId, APPMODULE_COMPONENT_TYPE, true);
+ added.push({ type: 'appmodule', id: appId });
+ }
// Add each GenPage (uxagentproject) explicitly. AddRequiredComponents
// pulls its uxagentprojectfile rows — including config.json with the
// connectorBindings that must travel with the page.
for (const pageId of pageIds) {
- await addComponent(envUrl, solutionUniqueName, pageId, pageComponentType, true);
+ await addComponent(envUrl, solutionUniqueName, pageId, pageComponentType, PAGE_ADD_REQUIRED_COMPONENTS);
added.push({ type: 'uxagentproject', id: pageId });
}
diff --git a/plugins/model-apps/scripts/apps.js b/plugins/model-apps/scripts/apps.js
index ce25ec97b..cb6c5ef9e 100644
--- a/plugins/model-apps/scripts/apps.js
+++ b/plugins/model-apps/scripts/apps.js
@@ -38,15 +38,17 @@
// first page (it needs no app), then create the app with it.
//
// Nothing is written until every check has passed, and each check that fails says why: no --page-id, a page id that is not
-// a page in the environment, a solution that does not exist (or is managed, and takes no new components), a unique name
+// a page in the environment, a solution that does not exist (or is managed, and takes no new components), a page table whose
+// solution component type the environment cannot say (it is read only for a solution that is not a system one), a unique name
// that is taken (by an app, or by a site map an app was deleted without), a name or unique name the platform would refuse.
// A refusal prints { ok: false, code, error, written: false } and exits 1.
//
// Writes, in order: the app row and its sitemap (the SDK's create and push — which also pin the sitemap as an app
// component, give the app the System Administrator role so it can be opened, and write one app setting: see below), then the app
-// (component 80) and its sitemap (62) join the solution — adding the app module alone leaves its sitemap only in the default
-// solution — and, only with --publish, the publish. A system solution (Default, Active, Basic) holds every component already, so
-// nothing is added to it: the output says `systemSolution: true`, and `inSolution` is empty, which is not a failure.
+// (component 80), its sitemap (62) and each of its pages join the solution — adding the app module alone leaves its sitemap only in
+// the default solution, and neither the app's add nor the sitemap's brings the pages its navigation opens (lib/page-solution.js says
+// how a page is added, and why) — and, only with --publish, the publish. A system solution (Default, Active, Basic) holds every
+// component already, so nothing is added to it: the output says `systemSolution: true`, and `inSolution` is empty, which is not a failure.
//
// The app setting. The SDK's create makes every new app with the new header and navigation ON (`headerAndNavigationRefresh` is
// true unless the definition says false; a public preview) and writes that as the app setting HeaderAndNavigationRefresh = 2:
@@ -103,7 +105,7 @@
// --env the environment's https origin, e.g. https://contoso.crm.dynamics.com
// --search list: keeps the apps whose name or unique name holds the text (any letter case)
// --name create: the app's display name (at most 100 characters)
-// --solution create: the UNIQUE name of an existing unmanaged solution; the app and its sitemap join it
+// --solution create: the UNIQUE name of an existing unmanaged solution; the app, its sitemap and its pages join it
// --page-id create: a generative page's id; repeat it, or comma-separate, for more pages (their order is the navigation's)
// --unique-name create: the app's unique name, instead of the derived one
// --description create: the app's description (at most 2000 characters)
@@ -113,7 +115,7 @@
// list { "ok": true, "count": 1, "apps": [ { "id": "11111111-…", "name": "Contoso Sales", "uniqueName": "contoso_sales",
// "description": "", "published": true, "unpublishedChanges": false } ] } `unpublishedChanges` is null when the platform did not say
// create { "ok": true, "appId": "22222222-…", "uniqueName": "account_metrics_1a2b3c4d", "name": "Account Metrics", "published": false,
-// "unpublishedChanges": true, "solution": "ContosoCore", "addedToSolution": true, "inSolution": ["app", "sitemap"],
+// "unpublishedChanges": true, "solution": "ContosoCore", "addedToSolution": true, "inSolution": ["app", "sitemap", "pages"],
// "sitemapId": "33333333-…", "languageCode": 1033,
// "navigation": { "area": "Main", "group": "Pages", "pages": [ { "pageId": "44444444-…", "title": "Overview" } ] },
// "dataSources": ["account"], "pinnedViews": ["55555555-…"] }
@@ -143,8 +145,9 @@
// for. A read-back that cannot be made keeps what the run knows. A push the SDK reported as saved (stage "solution" or "publish")
// wrote both rows, and a row that a read found before a later read failed is there, so "written" is true then, with "left" saying what
// is known and null for the rest; "written" is null only when nothing is known to exist, and then "left" is absent (nothing was read)
-// or has a false and a null. `inSolution` is each of "app" and "sitemap" as it joined (a failure between the two has ["app"];
-// `addedToSolution` is true only when both did), `systemSolution` is as for a success, and the SDK's `warnings`, if it gave any, are
+// or has a false and a null. `inSolution` is each of "app", "sitemap" and "pages" as it joined, in that order ("pages" once every page
+// has: a failure among the pages has ["app", "sitemap"], and adding them again is safe — a component the solution holds already is
+// accepted); `addedToSolution` is true only when all three did, `systemSolution` is as for a success, and the SDK's `warnings`, if it gave any, are
// also written to stderr.
// a failure before the push (in the workspace only this run sees): the same as a refusal, "written": false
//
@@ -157,6 +160,7 @@ const { withThrowawaySdk } = require('./lib/throwaway-sdk.js');
const { pushFailed } = require('./lib/entity-provision.js');
const { collectionRows, currentLayerRow, savedPageRows } = require('./lib/app-components.js');
const { isRestrictedSolution } = require('./lib/system-solutions.js');
+const { readTargetSolution, readPageComponentType, pageComponent } = require('./lib/page-solution.js');
const { odataLit } = require('./lib/odata.js');
const { genPageSubArea } = require('./lib/genpage-subarea.js');
const { makeGenpageSdk, unescapePacName } = require('./lib/genpage-sdk.js');
@@ -369,24 +373,8 @@ function inputRefusal(args) {
return null;
}
-/** The unmanaged solution named `uniqueName`, as the platform spells it; throws a Refusal when there is none. */
-async function readSolution(sdk, uniqueName) {
- const rows = await sdk.queryRecords('solution', {
- select: ['solutionid', 'uniquename', 'friendlyname', 'ismanaged'],
- filter: `uniquename eq '${odataLit(uniqueName)}'`,
- top: 1,
- });
- const solution = rows && rows[0];
- if (!solution) {
- throw new Refusal('SOLUTION_NOT_FOUND',
- `There is no solution with the unique name '${uniqueName}' in this environment. --solution takes a solution's unique name, not its display name; `
- + 'create the solution first (provision-solution.js) if it should exist.');
- }
- if (solution.ismanaged === true) {
- throw new Refusal('SOLUTION_MANAGED', `The solution '${solution.uniquename}' is managed, and a managed solution takes no new components. Use an unmanaged solution.`);
- }
- return { uniqueName: solution.uniquename || uniqueName };
-}
+// The unmanaged solution named `uniqueName`, as the platform spells it, is read by lib/page-solution.js `readTargetSolution` — the one reading
+// genpage-upload.js --solution shares — which refuses, with SOLUTION_NOT_FOUND or SOLUTION_MANAGED, before anything is written.
// The generative pages named by `ids`, as { id (lower-case), title } in the order of `ids`; a Refusal names every id that is no page.
// The SDK reads the same collection to check a sitemap's pages when the app is pushed, and refuses a missing one then, but without saying
@@ -517,11 +505,14 @@ async function createApp(args, httpClient, seams = {}) {
let writer;
try {
const readSdk = make();
- const solution = await readSolution(readSdk, args.solution);
+ const solution = await readTargetSolution(readSdk, args.solution);
+ // The pages join the solution with the app (writeApp), as components of the page table's own type, which the environment allocates: read here, with the
+ // checks, so an environment that cannot say it refuses the create before anything is written. A system solution takes no add, so it needs no type.
+ const pageComponentType = isRestrictedSolution(solution.uniqueName) ? null : await readPageComponentType(readSdk.dataverse);
const pages = await readPages(readSdk, args.pageIds);
const uniqueName = args.uniqueName !== undefined ? args.uniqueName : deriveUniqueName(args.name, seams.randomHex);
await assertUniqueNameFree(readSdk, uniqueName);
- plan = { solution, pages, uniqueName, languageCode: await readBaseLanguage(readSdk) };
+ plan = { solution, pageComponentType, pages, uniqueName, languageCode: await readBaseLanguage(readSdk) };
// Last of the reads: a page whose configuration cannot be read refuses the create like any other check, with nothing written.
plan.pins = await readViewPins(args.env, httpClient, pages, seams.makeGenpageSdk || makeGenpageSdk);
// The titles are written in the language the SDK instance is made with, which is why the writer is not the instance that read. It is made
@@ -592,17 +583,17 @@ async function readLeftovers(sdk, { uniqueName, sitemapId, appId, stage }) {
}
async function writeApp(sdk, args, plan, sitemapId) {
- const { solution, pages, uniqueName, languageCode, pins } = plan;
+ const { solution, pageComponentType, pages, uniqueName, languageCode, pins } = plan;
const systemSolution = isRestrictedSolution(solution.uniqueName);
// What the run has done, for the output. `pushBegan`: the first request that can write has been sent, so something may exist, and a failure from
- // then on reads the platform back. `inSolution` is each component as its AddSolutionComponent lands, so a failure between the two says which of
- // them is in the solution; `warnings` are the SDK's notes on the push.
+ // then on reads the platform back. `inSolution` is each component as its AddSolutionComponent lands — "pages" once every page has — so a failure
+ // part-way says which of them is in the solution; `warnings` are the SDK's notes on the push.
const made = { pushBegan: false, appId: undefined, inSolution: [], published: false, warnings: [] };
- const bothInSolution = () => made.inSolution.includes('app') && made.inSolution.includes('sitemap');
+ const allInSolution = () => ['app', 'sitemap', 'pages'].every((joined) => made.inSolution.includes(joined));
// What the output says about the solution, on a success as on a failure. A system solution (Default, Active, Basic) holds every component already,
// so nothing is added to it and `inSolution` stays empty; `systemSolution` says that is why, which an empty list alone reads as the app being left out.
const solutionFacts = () => ({
- addedToSolution: bothInSolution(),
+ addedToSolution: allInSolution(),
inSolution: [...made.inSolution],
...(systemSolution ? { systemSolution: true } : {}),
});
@@ -635,6 +626,10 @@ async function writeApp(sdk, args, plan, sitemapId) {
made.inSolution.push('app');
await sdk.addSolutionComponent({ componentId: sitemapId, componentType: COMPONENT_TYPE_SITEMAP, solutionUniqueName: solution.uniqueName });
made.inSolution.push('sitemap');
+ // The pages last, in the navigation's order: the app's add brings its sitemap, and nothing brings the pages the sitemap opens. A solution that holds the
+ // app without them exports a navigation that opens pages the target environment does not have.
+ for (const page of pages) await sdk.addSolutionComponent(pageComponent(page.id, pageComponentType, solution.uniqueName));
+ made.inSolution.push('pages');
}
if (args.publish) {
diff --git a/plugins/model-apps/scripts/build-model-app.js b/plugins/model-apps/scripts/build-model-app.js
index 9f824676f..b6365298d 100644
--- a/plugins/model-apps/scripts/build-model-app.js
+++ b/plugins/model-apps/scripts/build-model-app.js
@@ -831,8 +831,9 @@ async function buildModelAppHeld(spec, opts, deps, v, buildLease) {
// at all) fails the same way on every run after the first.
// The language the build wrote its labels in goes too: the flag it was given and what its SDK was made for. A build run with
// `--language-code` in an organization whose base language is another one publishes its captions in the flag's language, and a
- // verify that does not know it holds them to the organization's and reports the captions it was just given as missing.
- const vr = await deps.verify(spec, { environmentSkipped: r.skipped, phases: opts.phases, baselineSpec: opts.baselineSpec, languageCode: opts.languageCode, preResolvedLanguageCode: opts.preResolvedLanguageCode });
+ // verify that does not know it holds them to the organization's and reports the captions it was just given as missing. And the app
+ // folder, from which a web resource's `contentPath` is read to compare its deployed content (verify-spec.js, the web-resource check).
+ const vr = await deps.verify(spec, { environmentSkipped: r.skipped, phases: opts.phases, baselineSpec: opts.baselineSpec, languageCode: opts.languageCode, preResolvedLanguageCode: opts.preResolvedLanguageCode, appDir: opts.appDir });
const present = vr.checks.length - vr.missing.length;
log(`\n${vr.ok ? '✓ verify PASS' : `✗ verify FAIL — ${vr.missing.length} missing`} (${present}/${vr.checks.length} present)`);
// Named explicitly rather than folded into the pass, so a green verify never reads as
diff --git a/plugins/model-apps/scripts/download-model-app.js b/plugins/model-apps/scripts/download-model-app.js
index 8267b66a3..0ac789506 100644
--- a/plugins/model-apps/scripts/download-model-app.js
+++ b/plugins/model-apps/scripts/download-model-app.js
@@ -43,7 +43,8 @@ const { fetchSitemap, sitemapGenPages, appNavigationMatchesSitemap } = require('
const { isRestrictedSolution } = require('./lib/system-solutions.js');
const { isPlatformIconRef, webResourceNameFromRef, validateAppSpec, normalizeLanguageCode, isLocalizedLabelMap, derivedPluralName, ambiguousChoiceAliases, relationshipSchemaName, manyToManySchemaName, dashboardNameKey, PAGE_MODEL_RE, sitemapEntityTables, lookupLabelFor, isOldLookupColumnLabel } = require('./lib/app-spec.js');
const { PAGE_BINDINGS, pageBindingsProblem, statableBindings, bindingProblemText } = require('./lib/page-bindings.js');
-const { labelsByLcid, sameLabel } = require('./lib/lookup-labels.js');
+const { getReviewedDataverseOperation } = require('./lib/dataverse-operations.js');
+const { labelsByLcid, pickLabel, sameLabel } = require('./lib/lookup-labels.js');
const { odataGuid } = require('./lib/ai-app-settings.js');
const { APP_COMPONENT_ENTITY_SOURCES, appComponentEntities, appComponentRows, currentAppLayer, readAppComponentInventory, downloadAppMainForms, setAppMembershipFloor } = require('./lib/app-components.js');
const { mapLimit, DEFAULT_MAX_SIZE_KB } = require('./lib/entity-provision.js');
@@ -356,7 +357,7 @@ async function readRelationshipMetadataForTable(sdk, logical, mediaKeys) {
return { logical, rows, rowsFailure, lookups, manyToManyRows, manyToManyFailure };
}
-async function readRelationships(sdk, logicals, publisherPrefix, warn, { prefixUnknown = false, entities = [], concurrency } = {}) {
+async function readRelationships(sdk, logicals, publisherPrefix, warn, { prefixUnknown = false, entities = [], concurrency, languageCode } = {}) {
concurrency = validatedDownloadConcurrency(concurrency);
const inApp = new Set((logicals || []).map((l) => String(l).toLowerCase()));
const lc = (s) => String(s || '').toLowerCase();
@@ -401,21 +402,44 @@ async function readRelationships(sdk, logicals, publisherPrefix, warn, { prefixU
// is nothing to compare it with (no downloaded tables passed, or a stock parent whose label was not read):
// omitting is a claim about what a rebuild writes.
// * a parent IN the app: its downloaded displayName, string or map, compared whole;
- // * a STOCK parent: its label in the one language the lookup's label is written in, because that is the
- // language a rebuild writes it in;
+ // * a STOCK parent: its label in the one language the lookup's label is written in;
// * the OLD DEFAULT an earlier build left on the column — the parent's logical name — is omitted too. It is an
// identifier, never a label anyone chose, and an explicit label is never repaired on a
// rebuild: writing it out would carry the defect through download -> edit -> rebuild for good,
// where leaving it out lets the rebuild repair it (the data-model phase's lookup label repair). The
// lookup's own name is NOT one: that is what the SDK left on a form FIELD it could not resolve, and no
// build ever wrote it on a column, so a column carrying it is somebody's label and is carried.
- const omitsDefaultLabel = (referenced, lookupLabel, rawLookupLabel) => {
+ // Those comparisons are made on the label's TEXT, the shape every download wrote before a label held in one language other than the
+ // authoring one kept its language (labelFromDataverse), and a parent in the app is compared the same way (singleLanguageText). But a
+ // label is a language too, and equal text no longer proves the label a rebuild writes: an English "Contact" on a lookup to a table
+ // labelled only in French "Contact" is rebuilt as the French label it inherits, and a French "Utilisateur" on a lookup to `systemuser`
+ // as the English "User" the build reads. So when the authoring language is known, a label is left out only where the text comparison
+ // leaves it out AND the label a rebuild writes is this one, language for language (rebuildsAs). Requiring both never leaves out a label
+ // that was carried before, and every label that is carried keeps its language. With no authoring language every label is written
+ // without its language, as before, so the text comparison alone decides, as before.
+ const authoring = normalizeLanguageCode(languageCode);
+ // What a rebuild writes on a lookup that sets no label, as { LCID: text } — the label the build sends (lookupLabelFor) in the language
+ // it sends it in (lib/entity-provision.js, relationships): a parent in the app gives its downloaded displayName, a map as it is and a
+ // plain string in the authoring language (the language a rebuild of this spec resolves, labelFromDataverse); a stock parent gives the
+ // label the build reads for it in that language (pickLabel, as lib/lookup-labels.js makeTableLabelReader reads it), written in that
+ // language — assuming, as the text comparison always has, that the target labels its stock tables as this environment does. Undefined
+ // for a name derived from the table's (lookupLabelFor's last step), which is no label a lookup holds.
+ const rebuildsAs = (referenced, stockRaw) => {
+ const live = stockRaw ? pickLabel(stockRaw, authoring) : null;
+ const would = lookupLabelFor({ entities }, { referenced }, { liveReferencedLabel: live || undefined });
+ if (would.source !== 'table' && would.source !== 'environment') return undefined;
+ return isLocalizedLabelMap(would.label) ? would.label : { [String(authoring)]: would.label };
+ };
+ const omitsDefaultLabel = (referenced, rawLookupLabel) => {
+ const lookupLabel = labelFromDataverse(rawLookupLabel);
if (isOldLookupColumnLabel({ referenced }, lookupLabel)) return true;
const lookupLanguages = Object.keys(labelsByLcid(rawLookupLabel));
const stockRaw = stockLabels.get(lc(referenced));
const live = stockRaw && lookupLanguages.length === 1 ? labelsByLcid(stockRaw)[lookupLanguages[0]] : undefined;
const would = lookupLabelFor({ entities }, { referenced }, { liveReferencedLabel: live });
- return (would.source === 'table' || would.source === 'environment') && sameLabel(lookupLabel, would.label);
+ const sameText = (would.source === 'table' || would.source === 'environment') && sameLabel(lookupLabel, singleLanguageText(would.label));
+ if (!sameText || !authoring) return sameText;
+ return sameLabel(labelsByLcid(rawLookupLabel), rebuildsAs(referenced, stockRaw));
};
const media = mediaRelationshipKeys(entities);
@@ -463,8 +487,9 @@ async function readRelationships(sdk, logicals, publisherPrefix, warn, { prefixU
seen.add(key);
const a = lookups.get(attr);
const lookup = { schemaName: (a && a.SchemaName) || r.ReferencingAttribute };
- const displayName = a && labelFromDataverse(a.DisplayName);
- if (displayName && !omitsDefaultLabel(referenced, displayName, a.DisplayName)) lookup.displayName = displayName;
+ // The label written keeps a language other than the authoring one (labelFromDataverse); whether it is left out is omitsDefaultLabel's.
+ const displayName = a && labelFromDataverse(a.DisplayName, languageCode);
+ if (displayName && !omitsDefaultLabel(referenced, a.DisplayName)) lookup.displayName = displayName;
// Keep the deployed name whenever it is not the one this prefix would generate. Omitting a
// foreign name used to rename it onto the generated default; the rebuild then created under
// that name, the CREATE failed because the lookup already existed, and the name search found
@@ -716,6 +741,42 @@ async function rowsByIds(sdk, set, idField, ids, select, mapRow) {
return out;
}
+// The command-bar customisations of the app's tables: the modern commands (`appaction` rows) a rebuild into another environment drops,
+// because a download does not reconstruct `commands[]` (a deployed bar holds what the spec's buttons cannot state — Power Fx actions and
+// visibility, classic-rule visibility, buttons migrated from the classic ribbon). They are listed so the not-round-tripped report names
+// them as it names forms, views and charts; nothing is written from them.
+//
+// Read by `contextvalue`, the logical name of the table a table-bound command is on (the column the teardown scopes these rows by), 20
+// tables to a request, and only UNMANAGED rows: a managed command ships with its solution and exists wherever that is installed. A row
+// is this app's when it is TABLE-scoped (no app: every app that shows the table renders it) or scoped to THIS app; one scoped to another
+// app is that app's. A Group row (type 3) is a container whose buttons are rows of their own, and an inactive row is not rendered. A row
+// is answered as
+// { "appactionid": "<guid>", "name": "contoso_Escalate!<hex>", "buttonlabeltext": "Escalate", "contextvalue": "contoso_project",
+// "type": 0, "statecode": 0, "_appmoduleid_value": null }
+// See https://learn.microsoft.com/power-apps/developer/data-platform/reference/entities/appaction and
+// https://learn.microsoft.com/power-apps/maker/model-driven-apps/commanding-scopes
+async function readCommandInventory(sdk, appId, tables) {
+ const app = odataGuid(appId).toLowerCase();
+ const names = [...new Set((tables || []).map((t) => String(t || '').toLowerCase()).filter(Boolean))].sort(compareText);
+ const out = [];
+ for (let i = 0; i < names.length; i += 20) {
+ const onTables = names.slice(i, i + 20).map((t) => `contextvalue eq '${t.replace(/'/g, "''")}'`).join(' or ');
+ const rows = await sdk.queryRecords('appaction', {
+ select: ['appactionid', 'name', 'buttonlabeltext', 'contextvalue', 'type', 'statecode', '_appmoduleid_value'],
+ filter: `ismanaged eq false and (${onTables})`,
+ paginate: true,
+ });
+ for (const r of rows || []) {
+ if (!r || !r.appactionid) continue;
+ const owner = odataGuid(r._appmoduleid_value).toLowerCase();
+ if ((owner && owner !== app) || Number(r.type) === 3 || Number(r.statecode) === 1) continue;
+ const label = typeof r.buttonlabeltext === 'string' && r.buttonlabeltext.trim() ? r.buttonlabeltext : r.name;
+ out.push({ id: r.appactionid, name: label, entity: String(r.contextvalue || '').toLowerCase() });
+ }
+ }
+ return out;
+}
+
// Read the two app-shell settings the BUILD writes but the download previously dropped, so a
// downloaded spec round-trips them instead of silently reverting an app to the classic shell when it
// is rebuilt into a fresh environment (#514).
@@ -777,13 +838,15 @@ async function readAppShellSettings(sdk, appId) {
return out;
}
-async function readDescriptionInventory(sdk, appId, solutionScope, referencedGlobalChoices, componentInventory) {
+async function readDescriptionInventory(sdk, appId, solutionScope, referencedGlobalChoices, componentInventory, { tables } = {}) {
// `incomplete[]` records an artifact class whose read FAILED. Without it the whole app-component
// block shared one broad catch, so a 403 on `systemform` left `forms: []` — indistinguishable from
// an app with no forms, which is EXACTLY the reported bug (AB#6686423) reappearing inside the fix
- // for it. It is a sibling key for the same reason `roleRestrictedForms` is: only the five
- // whitelisted keys reach `app-spec.json`, so this informs the CLI without changing the spec shape.
- const inventory = { views: [], charts: [], forms: [], businessRules: [], globalChoices: [], roleRestrictedForms: [], incomplete: [] };
+ // for it. It is a sibling key for the same reason `roleRestrictedForms` is: only the whitelisted
+ // keys reach `app-spec.json`, so this informs the CLI without changing the spec shape.
+ //
+ // `tables` are the app's tables, whose command bars are inventoried (readCommandInventory); a caller that names none reads none.
+ const inventory = { views: [], charts: [], forms: [], businessRules: [], globalChoices: [], commands: [], roleRestrictedForms: [], incomplete: [] };
const fail = (kind, err) => inventory.incomplete.push({ kind, reason: (err && err.message) ? String(err.message).slice(0, 200) : 'read failed' });
try {
const layer = componentInventory ? componentInventory.layer : await currentAppLayer(sdk.dataverse, appId);
@@ -961,10 +1024,19 @@ async function readDescriptionInventory(sdk, appId, solutionScope, referencedGlo
fail('globalChoices', err);
}
+ // A failed read is UNKNOWN, never "the app has no commands" — the same rule as every class above.
+ if (Array.isArray(tables)) {
+ try {
+ inventory.commands.push(...await readCommandInventory(sdk, appId, tables));
+ } catch (err) {
+ fail('commands', err);
+ }
+ }
+
// Ordered here, once, for everything that reads the inventory — the spec's `descriptionInventory`, the not-round-tripped report
// and the role-restriction warning. The rows are in the order Dataverse answered, which differs between two reads of one app; by
// table, then name, then id (compareArtifacts) they do not.
- for (const key of ['views', 'charts', 'forms', 'businessRules', 'roleRestrictedForms']) inventory[key].sort(compareArtifacts);
+ for (const key of ['views', 'charts', 'forms', 'businessRules', 'commands', 'roleRestrictedForms']) inventory[key].sort(compareArtifacts);
inventory.globalChoices.sort((a, b) => compareText(a.name, b.name));
inventory.incomplete.sort((a, b) => compareText(a.kind, b.kind) || compareText(a.reason, b.reason));
return Object.fromEntries(Object.entries(inventory).filter(([, value]) => value.length));
@@ -1092,7 +1164,7 @@ function bindingNames(list, identity) {
}
// What the connector and Custom API bindings of the pages a download read come to, and what a rebuild into ANOTHER environment still cannot bring:
-// { pages: [{ key, name, connectorBindings?: [name…], actionBindings?: [name…] }], notCarried?: [{ key, name, field, reason }], neededInTarget: { connectionReferences?, customApis?, serviceResources? }, note }
+// { pages: [{ key, name, connectorBindings?: [name…], actionBindings?: [name…] }], notCarried?: [{ key, name, field, reason }], neededInTarget: { connectionReferences?, customApis?, dataverseOperations?, serviceResources? }, note }
// or null when no page holds a binding or lost one. `pages` are the pages whose bindings are in the spec, in the order the spec lists its pages, each with the names its bindings go by (identifiers: a list is
// in the spec only when every value in it has a safe shape, page-bindings.js); `notCarried` the lists a page holds that the spec cannot state (`unkept`, from parseDownloadedPages), each with the place and the
// vetted property that kept it out, never a value — a rebuild into this environment leaves those as they are, and a rebuild into another does not carry them.
@@ -1101,12 +1173,16 @@ function bindingNames(list, identity) {
// - a connector binding names a CONNECTION REFERENCE by its logical name. The reference is a Dataverse row that points at a connection, and a connection holds a user's sign-in, so it stays in the environment
// that made it; the page resolves the reference by name, which is how the page itself can travel (https://learn.microsoft.com/power-apps/maker/data-platform/create-connection-reference);
// - a Custom API binding names a Custom API by its unique name. A Custom API is a solution component, not an App Spec item (https://learn.microsoft.com/power-apps/developer/data-platform/custom-api);
+// - a binding whose name is EXACTLY WhoAmI or RetrieveVersion names a reviewed built-in Dataverse operation (lib/dataverse-operations.js), not a Custom API: it is a message the platform defines, so there
+// is nothing to deploy, and `dataverseOperations` names it apart from `customApis` — a legacy or contradictory entry too (a parameter map does not make the name a Custom API). The binding is carried
+// as the page holds it, not repaired, and nothing says the operation is available in another environment, its player or to its users: that is not certified. Any other spelling is a Custom API name;
// - what a connector binding points at inside the service — `dataset`, `tables`: a SharePoint site and its list ids, say — is written as the page holds it, and means something in another environment only if the same
// resources are there. `serviceResources` names the connection references whose bindings carry one.
function pageBindingsReport(pages, unkept) {
const held = [];
const references = new Set();
const apis = new Set();
+ const builtIns = new Set();
const service = new Set();
const nonEmpty = (list) => Array.isArray(list) && list.length > 0;
for (const page of pages || []) {
@@ -1125,7 +1201,9 @@ function pageBindingsReport(pages, unkept) {
entry.actionBindings = bindingNames(page.actionBindings, PAGE_BINDINGS.actionBindings);
for (const binding of page.actionBindings) {
const name = binding && typeof binding.name === 'string' ? binding.name.trim() : '';
- if (name) apis.add(name);
+ // The exact name, as the catalogue matches it (`whoami` is a Custom API name).
+ if (binding && getReviewedDataverseOperation(binding.name)) builtIns.add(binding.name);
+ else if (name) apis.add(name);
}
}
held.push(entry);
@@ -1143,11 +1221,14 @@ function pageBindingsReport(pages, unkept) {
neededInTarget: {
...(references.size ? { connectionReferences: sorted(references) } : {}),
...(apis.size ? { customApis: sorted(apis) } : {}),
+ ...(builtIns.size ? { dataverseOperations: sorted(builtIns) } : {}),
...(service.size ? { serviceResources: sorted(service) } : {}),
},
note: 'The spec states these bindings, so a rebuild writes them onto each page in any environment. A rebuild cannot create what they name — the connection references and the connections behind them, the Custom APIs, and the '
+ 'service resources a connector binding points at — so each must already exist in the environment you rebuild into. A rebuild reads them there before it writes a page: it stops, before writing anything, at a connection '
- + 'reference that is for another connector, and says by name each reference and Custom API that is not there, a reference that has no connection, and an operation a custom connector there does not define.',
+ + 'reference that is for another connector, and says by name each reference and Custom API that is not there, a reference that has no connection, and an operation a custom connector there does not define.'
+ + (builtIns.size ? ' The built-in Dataverse operations (dataverseOperations) are not solution components and there is nothing to make for them: their bindings are preserved as the page holds them, not repaired, '
+ + 'and whether an environment, its page player and the signed-in user can call them, or whether a binding matches the reviewed contract, is not certified.' : ''),
};
}
@@ -1169,6 +1250,9 @@ function pageBindingsNote(report) {
if (needed.customApis) {
lines.push(` - Custom API(s) ${list(needed.customApis)}: a Custom API is a solution component, not an App Spec item — deploy it there first (list-custom-apis.js lists what an environment has); one bound to a table needs that table there too`);
}
+ if (needed.dataverseOperations) {
+ lines.push(` - built-in Dataverse operation(s) ${list(needed.dataverseOperations)}: an operation the platform defines, not a solution component, so there is nothing to make for it — the binding is carried as the page holds it, not repaired, and whether that environment, its page player and the signed-in user can call it is not certified (a rebuild reads nothing for it)`);
+ }
if (needed.serviceResources) {
lines.push(` - what the connector bindings of ${list(needed.serviceResources)} point at inside the service (dataset, tables: a SharePoint site and list ids, for example) is written as it is here, and works there only if the same resources exist`);
}
@@ -1584,8 +1668,9 @@ function optionSetFromRow(row) {
// `labelFromDataverse` reads only `LocalizedLabels`, so a Label carrying just
// a `UserLocalizedLabel` falls back to the single-string unwrap rather than emitting `undefined`,
// which would fail validation with "options[i] must be a non-empty string".
-function localizedSpecLabel(label) {
- const localized = labelFromDataverse(label);
+// `languageCode` is the download's authoring language (labelFromDataverse).
+function localizedSpecLabel(label, languageCode) {
+ const localized = labelFromDataverse(label, languageCode);
return localized !== undefined ? localized : descriptionFromDataverse(label);
}
@@ -1725,15 +1810,14 @@ function notRoundTrippedSummary(inventory) {
// `entityScoped: false` for global choices because they are ORG-wide: grouping one under a table
// would invent a relationship the platform does not have.
//
- // ⚠ `commands[]` is missing from this list for a different reason, and it is a KNOWN gap rather
- // than an oversight: `readDescriptionInventory` never collects commands, so there is no count to
- // report. Adding the class here would emit a permanent "0 commands" that reads as "this app has
- // none" — the exact false reassurance the `incomplete` channel exists to avoid. Inventory them
- // first, then add the class.
+ // `commands` are the command-bar customisations of the app's tables (readCommandInventory). They were
+ // missing until the download read them: a class with no read behind it would have reported a permanent
+ // "0 commands", the false reassurance the `incomplete` channel exists to avoid.
const CLASSES = [
{ key: 'forms', label: 'form', entityScoped: true },
{ key: 'views', label: 'view', entityScoped: true },
{ key: 'charts', label: 'chart', entityScoped: true },
+ { key: 'commands', label: 'command', entityScoped: true },
{ key: 'businessRules', label: 'business rule', entityScoped: true },
{ key: 'globalChoices', label: 'global choice', entityScoped: false },
];
@@ -1864,11 +1948,36 @@ function untypedColumnNames(entities) {
return out;
}
+// The warnings for the columns captured WITHOUT a type (`untyped`, untypedColumnNames). `clashes` maps
+// the ones left untyped because one text names two of their options in a way the App Spec refuses
+// (entityFromMetadata's `labelClashes`) to that clash, e.g.
+// "contoso_item.contoso_stage" -> "'Abierto' names options[0] and options[1]"
+// Their option sets WERE read, so they are named with the clash: the warning for every other column
+// says the likeliest cause is an option set that could not be read, which sent a maker to download
+// again — and a download made again captures a clash the same way. Every other column keeps that
+// warning word for word. Returns the lines to write, each ending in a newline.
+function untypedColumnWarnings(untyped, clashes = new Map()) {
+ const lines = [];
+ const unexplained = untyped.filter((name) => !clashes.has(name));
+ const clashed = untyped.filter((name) => clashes.has(name));
+ if (unexplained.length) {
+ lines.push(`WARNING: ${unexplained.length} column(s) were captured WITHOUT a type (${unexplained.join(', ')}) — most likely Choice/MultiChoice columns whose option set could not be read. Rebuilding this spec into an environment that already has the table is unaffected, but rebuilding into a FRESH environment would create them as single-line Text. Add the type and options[] (or a globalChoice reference) by hand before a cross-environment rebuild.\n`);
+ }
+ if (clashed.length) {
+ lines.push(`WARNING: ${clashed.length} Choice/MultiChoice column(s) were captured WITHOUT a type because one text names two of their options (${clashed.map((name) => `${name}: ${clashes.get(name)}`).join('; ')}) and their two labels differ in at least one language, so the line does not show which option the text means and the App Spec refuses it. Their option sets were read: a download made again captures them the same way. Rebuilding this spec into an environment that already has the table is unaffected, but rebuilding into a FRESH environment would create them as single-line Text. Rename one of those options in Maker and download again, or add the type and options[] by hand before a cross-environment rebuild.\n`);
+ }
+ return lines;
+}
+
// `unexpressible`, when given, is an array this fills with the attributes left out because the App Spec has no type for them although
// nothing shows they were not authored (`{ table, column, typeName }`), so the caller can name them (see the end of the filter).
// `incomplete`, when given, is filled with the File and Image columns written without detail an answered read should have carried
// (`{ table, column, type, missing }`, missingMediaDetail), so the caller can name those too.
-function entityFromMetadata(meta, logical, { unexpressible, incomplete, schemaOmissions = [], languageCode } = {}) {
+// `languageLost`, when given, is filled with the inline Choice option labels written without the one language they hold
+// (`{ table, column, option, label, languageCode }`, see the option screen below), so the caller can name them.
+// `labelClashes`, when given, is filled with the Choice columns left untyped because one text names two of their options in a way
+// the App Spec refuses (`{ table, column, clashes: [{ alias, first, second }] }`, the same screen), so the caller names the clash.
+function entityFromMetadata(meta, logical, { unexpressible, incomplete, schemaOmissions = [], languageCode, languageLost, labelClashes } = {}) {
const primary = meta && (meta.primaryNameAttribute || meta.primaryNameLogicalName);
const attrs = Array.isArray(meta && meta.attributes) ? meta.attributes : (Array.isArray(meta && meta.Attributes) ? meta.Attributes : []);
const primaryLower = String(primary || '').toLowerCase();
@@ -2034,20 +2143,54 @@ function entityFromMetadata(meta, logical, { unexpressible, incomplete, schemaOm
// `runDownload` validates before writing and returns on failure, so emitting such a set aborted
// the ENTIRE app's download, and `--allow-lossy-download` does not bypass that gate. Refusing to
// type just this column falls back to the untyped warning that already exists for an unreadable
- // label, which is what the download did before types were carried at all.
+ // label, which is what the download did before types were carried at all — named with the clash
+ // (`labelClashes`), because this option set WAS read.
//
// The shared `ambiguousChoiceAliases` is reused rather than reimplemented, so this screen and
- // the validator can never disagree about what "ambiguous" means.
- const inlineOptions = optionSet && !(optionSet.isGlobal && optionSet.name)
- ? optionSet.options.map(localizedSpecLabel)
- : null;
- const inlineIsAmbiguous = inlineOptions ? ambiguousChoiceAliases(inlineOptions).some((c) => c.hidden) : false;
+ // the validator can never disagree about what "ambiguous" means. Two options labelled alike are not
+ // ambiguous in its sense when their labels are identical in every language they hold — the shape
+ // Dataverse stores for them (it fills the base language in with the same text) — so such a column
+ // keeps its type and options, with the duplicate warning the validator gives two equal plain strings.
+ //
+ // Options held in one language other than the authoring one come back as one-entry LCID maps
+ // (labelFromDataverse). Two of them sharing their text in the SAME language are a duplicate the
+ // validator warns about, as it does two plain strings, so they keep their language. One that shares
+ // its text with an option in ANOTHER language — a plain label (the authoring language) or a one-entry
+ // map of another — is a collision the validator refuses, which would leave the column untyped. Only
+ // the one-entry maps of such a collision are written as the plain strings an earlier download wrote
+ // (a visible duplicate, which the validator only warns about), and each is reported in `languageLost`,
+ // because a rebuild labels it in the language it resolves rather than its own; every other option
+ // keeps its language. A collision involving a label of several languages that is not identical to the
+ // other has no plain-string form: the column is left untyped, as before, and the clash is reported.
+ const inlineLabels = (lcid) => optionSet.options.map((l) => localizedSpecLabel(l, lcid));
+ const hiddenCollision = (options) => ambiguousChoiceAliases(options).some((c) => c.hidden);
+ let inlineOptions = optionSet && !(optionSet.isGlobal && optionSet.name) ? inlineLabels(languageCode) : null;
+ let lostLanguages = [];
+ if (inlineOptions && hiddenCollision(inlineOptions)) {
+ const hidden = new Set(ambiguousChoiceAliases(inlineOptions).filter((c) => c.hidden).map((c) => c.alias));
+ const lost = [];
+ const flattened = inlineOptions.map((label, i) => {
+ const keys = isLocalizedLabelMap(label) ? Object.keys(label) : [];
+ if (keys.length !== 1 || !hidden.has(label[keys[0]])) return label;
+ lost.push({ option: i, label: label[keys[0]], languageCode: Number(keys[0]) });
+ return label[keys[0]];
+ });
+ if (!hiddenCollision(flattened)) {
+ inlineOptions = flattened;
+ lostLanguages = lost;
+ }
+ }
+ const inlineIsAmbiguous = inlineOptions ? hiddenCollision(inlineOptions) : false;
const usableOptionSet = inlineIsAmbiguous ? null : optionSet;
const specType = TYPES_NEEDING_COMPANION_DATA.has(mapped) && !usableOptionSet ? undefined : mapped;
const choice = !usableOptionSet ? {}
: (usableOptionSet.isGlobal && usableOptionSet.name
? { globalChoice: usableOptionSet.name }
: { options: inlineOptions });
+ if (schemaName && Array.isArray(languageLost)) for (const l of lostLanguages) languageLost.push({ table: logical, column: schemaName, ...l });
+ if (inlineIsAmbiguous && schemaName && Array.isArray(labelClashes)) {
+ labelClashes.push({ table: logical, column: schemaName, clashes: ambiguousChoiceAliases(inlineOptions).filter((c) => c.hidden).map(({ alias, first, second }) => ({ alias, first, second })) });
+ }
if ((specType === 'File' || specType === 'Image') && schemaName && Array.isArray(incomplete)) {
const missing = missingMediaDetail(meta, a, specType);
if (missing.length) incomplete.push({ table: logical, column: schemaName, type: specType, missing });
@@ -2068,7 +2211,7 @@ function entityFromMetadata(meta, logical, { unexpressible, incomplete, schemaOm
// tail would then emit that raw object as the column's displayName, producing a spec that fails
// its own validation with "'LocalizedLabels' is not an LCID". Omitting the label entirely is the
// right answer: Dataverse has none either.
- ...(columnDisplayName(a) !== undefined ? { displayName: columnDisplayName(a) } : {}),
+ ...(columnDisplayName(a, languageCode) !== undefined ? { displayName: columnDisplayName(a, languageCode) } : {}),
...(specType ? { type: specType } : {}),
...choice,
...columnOptionFields(a, specType),
@@ -2078,20 +2221,29 @@ function entityFromMetadata(meta, logical, { unexpressible, incomplete, schemaOm
}).filter((c) => c.schemaName);
// Table label + plural. When the table carries more than one language, BOTH must round-trip and
// `pluralName` becomes required (validateAppSpec refuses to derive a plural from a label map), so
- // the plural is emitted whenever the display name is localized.
- const displayName = labelFromDataverse(meta && meta.DisplayName);
- const pluralName = labelFromDataverse(meta && meta.DisplayCollectionName);
+ // the plural is emitted whenever the display name is localized. A label held in one language other
+ // than the authoring one keeps its language as a one-entry map (labelFromDataverse).
+ const displayName = labelFromDataverse(meta && meta.DisplayName, languageCode);
+ let pluralName = labelFromDataverse(meta && meta.DisplayCollectionName, languageCode);
// The primary column's own label. It is EXCLUDED from `columns[]` (it is declared separately as
// `primaryAttribute`), so its label has to be read from the un-filtered attribute list here —
// otherwise a table whose primary column is called "Order Title" / "Título del pedido" downloads
// as the hardcoded "Name", and a fresh-environment rebuild loses both the real label and its
// translations. `'Name'` remains the fallback for a metadata read that carried no label at all.
const primaryAttr = primaryLower ? attrs.find((a) => String((a && (a.logicalName || a.LogicalName || a.schemaName || a.SchemaName)) || '').toLowerCase() === primaryLower) : null;
- const primaryLabel = columnDisplayName(primaryAttr);
+ const primaryLabel = columnDisplayName(primaryAttr, languageCode);
const tableSchemaName = (meta && (meta.schemaName || meta.logicalName)) || logical;
const tableLabel = displayName !== undefined ? displayName : ((meta && meta.displayName) || logical);
+ // A display name kept in its one language as a map needs a plural beside it (validateAppSpec). When the table has no plural label to
+ // read, it is the plural a rebuild of the plain label derived before — derivedPluralName — in that same language, so the text a rebuild
+ // writes is what it always was and only its language is right.
+ const singleLanguage = isLocalizedLabelMap(displayName) && Object.keys(displayName).length === 1;
+ if (pluralName === undefined && singleLanguage) {
+ const [lcid] = Object.keys(displayName);
+ pluralName = { [lcid]: derivedPluralName({ schemaName: tableSchemaName, displayName: displayName[lcid] }) };
+ }
const statusReasons = statusReasonsFromOptions(meta && meta.statusOptions, { customTable: !meta || meta.isCustomEntity !== false, languageCode, omitted: schemaOmissions });
- const alternateKeys = alternateKeysFromMetadata(meta && meta.Keys, localizedSpecLabel, schemaOmissions);
+ const alternateKeys = alternateKeysFromMetadata(meta && meta.Keys, (label) => localizedSpecLabel(label, languageCode), schemaOmissions);
return {
schemaName: tableSchemaName,
displayName: tableLabel,
@@ -2395,27 +2547,38 @@ async function readMediaColumns(sdk, logical, attributes, concurrency) {
// { "Label": "Línea base", "LanguageCode": 3082 }],
// "UserLocalizedLabel": { "Label": "Baseline", "LanguageCode": 1033 } }
//
-// Returns a plain STRING when the table is labelled in one language, and an LCID map only when there
-// are genuinely two or more. That asymmetry is deliberate: emitting `{ "1033": "Baseline" }` for
-// every single-language table would change the shape of every spec this tool has ever written, for
-// no gain, and would make every download diff noisy. Returns undefined when there is nothing usable,
-// so a caller can fall back to the SDK's flattened `displayName` rather than write an empty label.
+// Returns an LCID map when there are genuinely two or more languages. A label in ONE language is a
+// plain STRING when that language is `languageCode` — the download's authoring language (the
+// `--language-code` flag, else the spec's own pin, else the environment's base language: the language
+// a rebuild of this spec resolves, the one the navigation titles are read in) — and a ONE-ENTRY map,
+// `{ "3082": "Pedido" }`, when it is another. A plain string is written by a rebuild in the language
+// that rebuild resolves, so dropping the LCID of a label held in another language stored Spanish text
+// as the English label, in this environment as in any other. Keeping the plain string for the
+// authoring language keeps every ordinary download byte-identical (a single-language table's labels
+// are all in it) and keeps the spec consistent: every plain label in it is in that one language. A
+// caller with no `languageCode` gets the plain string, as before. Returns undefined when there is
+// nothing usable, so a caller can fall back to the SDK's flattened `displayName` rather than write an
+// empty label.
+//
+// A rebuild into an environment whose base language is not the authoring language still writes the
+// plain labels in ITS language — as it writes the navigation titles — unless the spec pins
+// `languageCode` (or the build is given `--language-code`); a one-entry map needs its language
+// provisioned there, and the build stops at the start of its data-model phase when it is not.
//
-// ⚠ KNOWN LIMITATION, accepted rather than overlooked: the LCID of a SINGLE label is not preserved.
-// A table labelled only in 3082 downloads as a plain string, and a rebuild applies it at the target
-// build's resolved language — correct when rebuilding into the same organization (its base language
-// is the same), wrong when rebuilding into one with a different base, where Spanish text is stored
-// as an English label. Fixing it means threading the org's base language into this pure function and
-// emitting a one-entry map whenever the two differ, which changes the emitted shape for a case that
-// is currently indistinguishable from the common one. `download` also deliberately never pins the
-// org's LCID into the spec (that would make the spec non-portable), so there is no existing signal
-// to key off. Pin `languageCode` in the spec before a cross-organization rebuild.
-function labelFromDataverse(value) {
+// MEASURED: Dataverse fills the base language in, with the same text, when a label is created or
+// updated in another language only, so the one language a label holds alone is the environment's
+// base language — the map is written when the authoring language is another (`--language-code`, or
+// the spec's pin): `{ "1033": "Note" }` for an English-only column read with `--language-code 3082`.
+function labelFromDataverse(value, languageCode) {
if (!value || typeof value !== 'object') return undefined;
const rows = Array.isArray(value.LocalizedLabels) ? value.LocalizedLabels : [];
const usable = rows.filter((l) => l && typeof l.Label === 'string' && l.Label.trim() && Number.isInteger(Number(l.LanguageCode)) && Number(l.LanguageCode) > 0);
if (!usable.length) return undefined;
- if (usable.length === 1) return usable[0].Label;
+ if (usable.length === 1) {
+ const only = Number(usable[0].LanguageCode);
+ const authoring = normalizeLanguageCode(languageCode);
+ return authoring && only !== authoring ? { [String(only)]: usable[0].Label } : usable[0].Label;
+ }
const out = {};
// NOT sorted, deliberately: V8 orders integer-like object keys ASCENDING regardless of insertion
// order, so `JSON.stringify` of this map is already deterministic and two downloads of the same
@@ -2425,11 +2588,20 @@ function labelFromDataverse(value) {
return out;
}
+// The text of a label held in one language, whichever shape it is written in — a plain string, or the one-entry map a label in a language
+// other than the authoring one is written as (labelFromDataverse). Any other label — a map of several languages — is returned as it is.
+function singleLanguageText(label) {
+ if (!isLocalizedLabelMap(label)) return label;
+ const values = Object.values(label);
+ return values.length === 1 ? values[0] : label;
+}
+
// The App Spec `displayName` for one downloaded column, or undefined when Dataverse has no usable
// label. GUARANTEES a string or an LCID map — never a raw Dataverse Label object, which would emit a
// spec that fails its own validation. See the call site for the live-measured shape that motivated it.
-function columnDisplayName(a) {
- const localized = labelFromDataverse(a && a.DisplayName);
+// `languageCode` is the download's authoring language (labelFromDataverse).
+function columnDisplayName(a, languageCode) {
+ const localized = labelFromDataverse(a && a.DisplayName, languageCode);
if (localized !== undefined) return localized;
// The SDK's `fetchEntityMetadata` projection already flattens this one to a string.
if (typeof (a && a.displayName) === 'string' && a.displayName.trim()) return a.displayName;
@@ -2972,6 +3144,11 @@ async function runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossy
const incompleteMediaColumns = [];
// Columns left out because the App Spec has no type for them (entityFromMetadata's `unexpressible`), of the tables the spec keeps.
const unexpressibleColumns = [];
+ // Choice option labels written without the one language they hold (entityFromMetadata's `languageLost`), of the tables the spec keeps.
+ const optionLanguageLosses = [];
+ // Choice columns left untyped because one text names two of their options (entityFromMetadata's `labelClashes`), of the tables the
+ // spec keeps: `<table>.<column>` -> the clash, which untypedColumnWarnings names in place of an unreadable option set.
+ const labelClashColumns = new Map();
// Shared option sets bound by a downloaded column, keyed by lower-cased name so a set used by
// several tables is declared once.
const globalChoiceDecls = new Map();
@@ -2982,6 +3159,8 @@ async function runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossy
const leftOut = [];
const shortOf = [];
const schemaOmissions = [];
+ const lostLabels = [];
+ const clashedColumns = [];
// A metadata READ failure is not the same as metadata that reports no primary name, and it must
// not be swallowed: a 429/503 on a sitemap table used to drop it silently, leaving its subarea
// behind so validation later complained about a "sitemap subArea references unknown entity" —
@@ -2994,7 +3173,7 @@ async function runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossy
if (meta && meta.optionSetReadFailed) optionSetReadFailures.set(logical, meta.optionSetReadFailed);
for (const [type, reason] of Object.entries((meta && meta.mediaReadFailures) || {})) if (mediaReadFailures[type]) mediaReadFailures[type].set(logical, reason);
collectGlobalChoices(meta, globalChoiceDecls);
- e = entityFromMetadata(meta, logical, { unexpressible: leftOut, incomplete: shortOf, schemaOmissions, languageCode });
+ e = entityFromMetadata(meta, logical, { unexpressible: leftOut, incomplete: shortOf, schemaOmissions, languageCode, languageLost: lostLabels, labelClashes: clashedColumns });
if (meta && typeof meta.IconVectorName === 'string' && meta.IconVectorName.trim()) tableVectorIcons.set(logical, meta.IconVectorName);
const missingSchema = [...((meta && meta.schemaReadFailures) || []), ...schemaOmissions];
if (missingSchema.length) schemaReadFailures.set(logical, missingSchema.join('; '));
@@ -3020,6 +3199,10 @@ async function runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossy
entities.push(e);
for (const c of leftOut) unexpressibleColumns.push(`${e.schemaName}.${c.column} (${c.typeName})`);
for (const c of shortOf) incompleteMediaColumns.push({ name: `${e.schemaName}.${c.column}`, missing: c.missing });
+ for (const l of lostLabels) optionLanguageLosses.push(`${e.schemaName}.${l.column} options[${l.option}] '${l.label}' (${l.languageCode})`);
+ for (const c of clashedColumns) {
+ labelClashColumns.set(`${e.schemaName}.${c.column}`, c.clashes.map((x) => `'${x.alias}' names options[${x.first}] and options[${x.second}]`).join(', '));
+ }
}
const withReason = (list) => list.map((l) => (metadataErrors.has(l) ? `${l} (metadata read failed: ${metadataErrors.get(l)})` : l)).join(', ');
if (noPrimaryName.length) {
@@ -3067,11 +3250,10 @@ async function runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossy
// the read did not return (see the failure warning above), or an attribute type the spec cannot
// declare. Rebuilding into an org that ALREADY has the table reuses the column and this is inert;
// rebuilding into a FRESH org creates it as Text, because the data-model phase falls back to
- // `c.type || 'Text'`. That silent downgrade is why this is announced by name.
+ // `c.type || 'Text'`. That silent downgrade is why this is announced by name — and with its cause
+ // where the download knows it: one text naming two of its options (untypedColumnWarnings).
const untyped = untypedColumnNames(entities);
- if (untyped.length) {
- process.stderr.write(`WARNING: ${untyped.length} column(s) were captured WITHOUT a type (${untyped.join(', ')}) — most likely Choice/MultiChoice columns whose option set could not be read. Rebuilding this spec into an environment that already has the table is unaffected, but rebuilding into a FRESH environment would create them as single-line Text. Add the type and options[] (or a globalChoice reference) by hand before a cross-environment rebuild.\n`);
- }
+ for (const line of untypedColumnWarnings(untyped, labelClashColumns)) process.stderr.write(line);
// A File or Image column whose read failed is still in the spec, typed, but without what that read carries — so a rebuild into a
// FRESH environment makes it at the build's default size (and an image not asked to be the table's primary one) instead of as it is
// here. Said per READ, with the reason, as the option-set failure is: the read is what is re-runnable, and the File read failing
@@ -3100,6 +3282,13 @@ async function runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossy
if (unexpressibleColumns.length) {
process.stderr.write(`WARNING: ${unexpressibleColumns.length} column(s) have a type the App Spec cannot express and were left out of the spec (${unexpressibleColumns.join(', ')}). Rebuilding this spec into an environment that already has the table leaves them as they are, but rebuilding into a FRESH environment would not create them: add them there in Maker after the rebuild.\n`);
}
+ // A Choice option labelled in one language other than the authoring one, whose text another option of its column holds in another
+ // language (entityFromMetadata's `languageLost`): the spec can hold the two only as plain strings, which a rebuild labels in the language
+ // it resolves, so each label that loses its language is named rather than moved without a word. A rebuild into an environment that
+ // already has the column leaves its options as they are.
+ if (optionLanguageLosses.length) {
+ process.stderr.write(`WARNING: the language of ${optionLanguageLosses.length} Choice option label(s) could not be kept (${optionLanguageLosses.join(', ')}): each shares its text with another option of its column in another language, which the App Spec can hold only as plain strings, so rebuilding into a FRESH environment labels them in the language the build resolves. Rename one of those options in Maker and download again, or relabel them in Maker after the rebuild.\n`);
+ }
// App identity comes from the app's REAL, immutable uniquename (`appUnique`, captured from Dataverse as
// `appmodule.uniquename`; guaranteed present here because runDownload bails at the sitemap gate above).
@@ -3219,7 +3408,7 @@ async function runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossy
try {
const rel = await readRelationships(sdk, allLogicals, solution.publisherPrefix, (m) => {
process.stderr.write(`WARNING: ${m}\n`);
- }, { prefixUnknown, entities, concurrency });
+ }, { prefixUnknown, entities, concurrency, languageCode });
relationships = rel.relationships;
relationshipsSkipped = rel.skipped;
} catch (e) {
@@ -3265,7 +3454,7 @@ async function runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossy
const scope = solutionUnreadable
? new Error(`the solutions this app belongs to could not be read (${solutionUnreadable})`)
: (solutionCandidates || solution.uniqueName);
- capturedInventory = await readDescriptionInventory(sdk, appId, scope, referenced, componentInventory);
+ capturedInventory = await readDescriptionInventory(sdk, appId, scope, referenced, componentInventory, { tables: [...allLogicals, ...appTables] });
return capturedInventory;
},
};
@@ -3562,4 +3751,4 @@ if (require.main === module) {
main().catch((err) => emitResult(false, err));
}
-module.exports = { untypedColumnNames, collectGlobalChoices, finalizeGlobalChoices, roundTrippedAware, isRoleRestrictedFormXml, notRoundTrippedSummary, notRoundTrippedWarning, relationshipsSkippedWarning, labelFromDataverse, columnDisplayName, resolveAppId, collectSitemap, appComponentEntities, parseDownloadedPages, pageBindingsReport, pageBindingsNote, readPreviousPageKeys, assignPageKeys, missingDownloads, entityFromMetadata, readEntityWithDescriptions, readDescriptionInventory, readAppShellSettings, iconWebResources, readDashboards, readRelationships, droppedSubareaCount, recoverAppSolution, runDownload, preserveAuthoredLanguageCode, makeDownloadSdk, compareText, main };
+module.exports = { untypedColumnNames, untypedColumnWarnings, collectGlobalChoices, finalizeGlobalChoices, roundTrippedAware, isRoleRestrictedFormXml, notRoundTrippedSummary, notRoundTrippedWarning, relationshipsSkippedWarning, labelFromDataverse, columnDisplayName, resolveAppId, collectSitemap, appComponentEntities, parseDownloadedPages, pageBindingsReport, pageBindingsNote, readPreviousPageKeys, assignPageKeys, missingDownloads, entityFromMetadata, readEntityWithDescriptions, readDescriptionInventory, readAppShellSettings, iconWebResources, readDashboards, readRelationships, droppedSubareaCount, recoverAppSolution, runDownload, preserveAuthoredLanguageCode, makeDownloadSdk, compareText, main };
diff --git a/plugins/model-apps/scripts/genpage-plan-provenance.js b/plugins/model-apps/scripts/genpage-plan-provenance.js
index 0878d723f..6c0a191d0 100644
--- a/plugins/model-apps/scripts/genpage-plan-provenance.js
+++ b/plugins/model-apps/scripts/genpage-plan-provenance.js
@@ -10,6 +10,10 @@
// existing afterwards means this invocation wrote it.
// 2. `verify` proves the written file targets exactly what the approved plan named and,
// for an edit, contains the same ordered change list.
+// 3. For a create plan, `verify` also compares the semantic records both documents carry — what was assumed, each page's
+// relationship and filter decisions, the lookups it uses (lib/genpage-plan-semantics.js) — and, with
+// `--require-assumptions`, requires them of a newly authored plan; with `--lookup-metadata <file>` it checks the observed
+// lookups against the saved metadata read, and with `--require-observed-lookups` no lookup may still be planned.
//
// Why not a hash of the whole approved body: the planner hands back a PREVIEW for approval and then
// writes a DIFFERENT document. The preview is
@@ -26,6 +30,9 @@ const path = require('node:path');
const { pagesTables } = require('./lib/page-file-targets.js');
const { sha256 } = require('./lib/hash.js');
const { makeWritesBlocking } = require('./lib/output-redaction.js');
+const {
+ readWrittenSemantics, readPreviewSemantics, hasSemanticContract, requiredContractProblems, compareSemantics, lookupEvidenceProblems, semanticRecord,
+} = require('./lib/genpage-plan-semantics.js');
// What a plan document targets.
// create: the Pages table's File column — `## Pages` in the written plan, `### Pages (N total)`
@@ -256,7 +263,72 @@ function planKindOf(planPath) {
return null;
}
-function verifyPlanProvenance({ planPath, approvedPlan }) {
+// The semantic records of a create plan (references/plan-schema.md: ## Assumptions, and per page Data semantics and Lookup
+// metadata), compared between the approved preview and the written plan by lib/genpage-plan-semantics.js — structured fields by id,
+// never a whole-document hash, for the reason above. Same page files are not enough: a changed assumption, decision or lookup scope
+// is something the maker did not approve. Returns { problems, hash }.
+// - Either document carrying any part of the contract requires its counterpart in the other: one-sided is never "older plan".
+// - requireAssumptions (a newly authored plan): both documents carry Assumptions and, for every page, Data semantics and Lookup
+// metadata — so leaving the contract out of both cannot evade the comparison.
+// - lookupMetadataPath: the successful get-lookup-metadata.js answer saved after provisioning. Every `observed` lookup of the
+// written plan must match it, and only with it may a lookup approved as `planned` be written `observed` with its measured
+// paths (the post-provision reconciliation). It is read here, never fetched: this gate does no network I/O.
+// - requireObservedLookups (before generation): no lookup is still `planned`, which needs that evidence.
+function createSemanticsProblems({ approvedPlan, written, targets, requireAssumptions, requireObservedLookups, lookupMetadataPath }) {
+ const approvedRead = readPreviewSemantics(approvedPlan);
+ const writtenRead = readWrittenSemantics(written);
+ const problems = [
+ ...approvedRead.problems.map((p) => `the approved plan: ${p.message}`),
+ ...writtenRead.problems.map((p) => `the written plan: ${p.message}`),
+ ];
+ for (const file of approvedRead.pages.keys()) {
+ if (!targets.includes(file)) problems.push(`the approved plan records ${file}, which is not one of its pages`);
+ }
+ for (const [file, page] of writtenRead.pages) {
+ if ((page.semantics !== null || page.lookups !== null) && !targets.includes(file)) problems.push(`the written plan records ${file}, which is not one of its pages`);
+ }
+ if (requireAssumptions) {
+ problems.push(...requiredContractProblems(approvedRead, targets, 'the approved plan').map((p) => p.message));
+ problems.push(...requiredContractProblems(writtenRead, targets, 'the written plan').map((p) => p.message));
+ }
+ // "Read" and "valid" are kept apart from the value: a file holding JSON `null` (or `false`, `0`, `[]`) was read and is
+ // validated like any other answer — it is not "no evidence supplied". Only evidence that validated authorizes a
+ // `planned` → `observed` promotion, and --require-observed-lookups needs exactly that, not merely a path.
+ let evidence;
+ let evidenceRead = false;
+ let evidenceValid = false;
+ if (lookupMetadataPath) {
+ try {
+ const file = path.resolve(lookupMetadataPath);
+ if (!fs.lstatSync(file).isFile()) throw new Error(`${file} is not a regular file (a link, junction or folder)`);
+ evidence = JSON.parse(fs.readFileSync(file, 'utf8'));
+ evidenceRead = true;
+ } catch (e) {
+ problems.push(`could not read the lookup metadata evidence: ${e.message}`);
+ }
+ if (evidenceRead) {
+ const evidenceProblems = lookupEvidenceProblems(writtenRead, evidence).map((p) => p.message);
+ problems.push(...evidenceProblems);
+ evidenceValid = evidenceProblems.length === 0;
+ }
+ }
+ if (requireObservedLookups) {
+ if (!lookupMetadataPath) problems.push('--require-observed-lookups needs --lookup-metadata <path>: the successful lookup metadata read');
+ else if (!evidenceValid) problems.push('--require-observed-lookups needs lookup metadata evidence that is a successful get-lookup-metadata.js answer every observed lookup matches');
+ for (const [file, page] of writtenRead.pages) {
+ for (const row of page.lookups && !page.lookups.sentinel ? page.lookups.rows.values() : []) {
+ if (row.state !== 'observed') problems.push(`${file} ${row.table}.${row.column} is still planned: read its metadata after provisioning and reconcile the plan before generation`);
+ }
+ }
+ }
+ problems.push(...compareSemantics(approvedRead, writtenRead, { promotions: evidenceValid }));
+ const contract = hasSemanticContract(approvedRead) || hasSemanticContract(writtenRead);
+ return { problems, hash: contract ? sha256(JSON.stringify(semanticRecord(writtenRead))) : null };
+}
+
+const SEMANTIC_OPTIONS = ['requireAssumptions', 'requireObservedLookups', 'lookupMetadataPath'];
+
+function verifyPlanProvenance({ planPath, approvedPlan, requireAssumptions = false, requireObservedLookups = false, lookupMetadataPath = null }) {
if (!planPath) return { ok: false, error: '--plan is required' };
if (approvedPlan == null) return { ok: false, error: '--approved is required' };
const absPlanPath = path.resolve(planPath);
@@ -270,6 +342,17 @@ function verifyPlanProvenance({ planPath, approvedPlan }) {
error: 'the approved plan body names no pages — save the plan body the planner returned for approval (its Pages table, or the Current State file of an edit) as the --approved file',
};
}
+ // The semantic records are a create plan's; an edit plan keeps its own change-list comparison and is never verified against them.
+ const options = { requireAssumptions, requireObservedLookups, lookupMetadataPath };
+ if (approved.kind === 'edit' && SEMANTIC_OPTIONS.some((name) => options[name])) {
+ return {
+ ok: false,
+ action: 'verify',
+ planPath: absPlanPath,
+ approvedTargets: approved.targets,
+ error: 'the semantic options (--require-assumptions, --require-observed-lookups, --lookup-metadata) apply to a create plan; an edit plan is verified by its change list',
+ };
+ }
// The file this certifies must be the one written in place: a link would have it vouch for a
// document that lives somewhere else.
let entry;
@@ -321,17 +404,49 @@ function verifyPlanProvenance({ planPath, approvedPlan }) {
}
changesHash = sha256(JSON.stringify(approvedChanges));
}
- return { ok: true, action: 'verify', planPath: absPlanPath, kind: approved.kind, targets: approved.targets, writtenHash, ...(changesHash ? { changesHash } : {}) };
+ let semanticsHash;
+ if (approved.kind === 'create') {
+ const semantic = createSemanticsProblems({ approvedPlan, written, targets: approved.targets, requireAssumptions, requireObservedLookups, lookupMetadataPath });
+ if (semantic.problems.length) {
+ const more = semantic.problems.length > 1 ? ` (and ${semantic.problems.length - 1} more)` : '';
+ return {
+ ok: false, action: 'verify', planPath: absPlanPath, approvedTargets: approved.targets, writtenTargets: actual.targets, writtenHash,
+ semanticProblems: semantic.problems,
+ error: `the written plan's semantic records are not the approved ones: ${semantic.problems[0]}${more}`,
+ };
+ }
+ semanticsHash = semantic.hash || undefined;
+ }
+ return {
+ ok: true, action: 'verify', planPath: absPlanPath, kind: approved.kind, targets: approved.targets, writtenHash,
+ ...(changesHash ? { changesHash } : {}), ...(semanticsHash ? { semanticsHash } : {}),
+ };
}
+const USAGE = 'Usage: node genpage-plan-provenance.js prepare --plan <path> OR verify --plan <path> --approved @<approved-plan-file> '
+ + '[--require-assumptions] [--require-observed-lookups --lookup-metadata <lookup-metadata.json>]';
+const VALUE_FLAGS = ['plan', 'approved', 'lookup-metadata'];
+const BOOLEAN_FLAGS = ['require-assumptions', 'require-observed-lookups'];
+
+// `prepare --plan <path>` / `verify --plan <path> --approved @<file> [--require-assumptions] [--require-observed-lookups]
+// [--lookup-metadata <path>]`. Every flag is declared: an unknown one — `--require-assumption`, a typo that would otherwise drop
+// the gate it names without a word — a stray word, or a boolean flag given a value is a usage error (`usage` set), never ignored.
+// A value flag takes the next word whatever it is, as before, so a missing --plan value still reads as "--plan is required".
function parseArgv(argv) {
const out = { command: argv[0] || '' };
for (let i = 1; i < argv.length; i += 1) {
const key = argv[i];
- if (!key.startsWith('--')) continue;
- out[key.slice(2)] = argv[i + 1];
+ if (!key.startsWith('--')) { out.usage = out.usage || `unexpected argument '${key}'`; continue; }
+ const name = key.slice(2);
+ if (BOOLEAN_FLAGS.includes(name)) { out[name] = true; continue; }
+ if (!VALUE_FLAGS.includes(name)) { out.usage = out.usage || `unknown flag ${key}`; continue; }
+ if (name === 'lookup-metadata' && (argv[i + 1] === undefined || argv[i + 1].startsWith('--'))) { out.usage = out.usage || '--lookup-metadata needs a path'; continue; }
+ out[name] = argv[i + 1];
i += 1;
}
+ if (out.command === 'prepare' && [...BOOLEAN_FLAGS, 'lookup-metadata', 'approved'].some((name) => out[name] !== undefined)) {
+ out.usage = out.usage || 'prepare takes --plan only';
+ }
return out;
}
@@ -347,25 +462,35 @@ function readApproved(value) {
function main() {
const args = parseArgv(process.argv.slice(2));
let result;
- if (args.command === 'prepare') {
+ let usage = false;
+ if (args.usage) {
+ result = { ok: false, error: `${args.usage} — ${USAGE}` };
+ usage = true;
+ } else if (args.command === 'prepare') {
result = preparePlanProvenance({ planPath: args.plan });
} else if (args.command === 'verify') {
let approvedPlan;
try {
approvedPlan = readApproved(args.approved);
- result = verifyPlanProvenance({ planPath: args.plan, approvedPlan });
+ result = verifyPlanProvenance({
+ planPath: args.plan,
+ approvedPlan,
+ requireAssumptions: args['require-assumptions'] === true,
+ requireObservedLookups: args['require-observed-lookups'] === true,
+ lookupMetadataPath: args['lookup-metadata'] || null,
+ });
} catch (e) {
result = { ok: false, action: 'verify', error: `could not read the approved plan: ${e.message}` };
}
} else {
- result = { ok: false, error: 'Usage: node genpage-plan-provenance.js prepare --plan <path> OR verify --plan <path> --approved @<approved-plan-file>' };
+ result = { ok: false, error: USAGE };
}
// A mismatch carries both change lists whole, and the process exits right after the write: it is made blocking
// first, or a pipe on Linux and macOS takes only what fits at once (lib/output-redaction.js).
makeWritesBlocking(process.stdout, process.stderr);
process.stdout.write(JSON.stringify(result) + '\n');
- process.exit(result.ok ? 0 : (args.command === 'prepare' || args.command === 'verify' ? 3 : 1));
+ process.exit(result.ok ? 0 : (!usage && (args.command === 'prepare' || args.command === 'verify') ? 3 : 1));
}
if (require.main === module) main();
diff --git a/plugins/model-apps/scripts/genpage-upload.js b/plugins/model-apps/scripts/genpage-upload.js
index 9d36b87e6..557adb6f1 100644
--- a/plugins/model-apps/scripts/genpage-upload.js
+++ b/plugins/model-apps/scripts/genpage-upload.js
@@ -44,6 +44,16 @@
// `--prompt` / `--agent-message` are accepted for short, shell-safe text, but `--prompt-file` is
// the documented path precisely because it cannot be mangled by a shell. `--compiled-code-file` is
// refused (see main): the page is compiled from the checked `--code-file` itself.
+//
+// `--solution <unique name>` is the solution the page joins (AB#6443257). A page made through the SDK joins none on its own, and nothing
+// else brings it into one — the add of an app brings its sitemap, never the pages its navigation opens — so a run that was given a
+// solution and made pages left them out of it. The solution is read BEFORE anything is written (a name that is no unmanaged solution, or
+// an environment that cannot say the page table's component type, refuses the upload with nothing made), and the page is added LAST,
+// once it is written, published and placed: the result then says `solution` and `addedToSolution: true`. A system solution (Default,
+// Active, Basic) holds every component already, so it is neither read nor added to (`addedToSolution: false`, `systemSolution: true`).
+// An add that fails is a failure (exit 1, `code: "solution-add-failed"`, the page's id): the page works and is not in the solution, and
+// the error names the one command that adds it (add-page-to-solution.js) — never a second create. An update may name it too: the page
+// then joins the solution once it is saved, which is how a create that did not finish, run again with `--page-id`, still joins it.
const fs = require('node:fs');
const path = require('node:path');
const { parseArgs, validateFlags, emitResult } = require('./lib/dataverse-auth.js');
@@ -58,7 +68,7 @@ const { makeWritesBlocking } = require('./lib/output-redaction.js');
const KNOWN = ['env', 'app-id', 'code-file', 'compiled-code-file', 'page-id', 'name', 'name-file',
'data-sources', 'clear-data-sources', 'prompt', 'prompt-file', 'agent-message', 'agent-message-file',
- 'model', 'connectors', 'actions', 'add-to-sitemap', 'overwrite-deployed'];
+ 'model', 'connectors', 'actions', 'add-to-sitemap', 'overwrite-deployed', 'solution'];
// Bare switches; every other flag carries a value.
const SWITCHES = ['add-to-sitemap', 'clear-data-sources', 'overwrite-deployed'];
const NEED_VALUE = KNOWN.filter((f) => !SWITCHES.includes(f));
@@ -66,7 +76,7 @@ const NEED_VALUE = KNOWN.filter((f) => !SWITCHES.includes(f));
const USAGE = 'Usage: node scripts/genpage-upload.js --env <orgUrl> --code-file <path> '
+ '--prompt-file <path> --agent-message-file <path> [--app-id <guid>] [--page-id <guid>] [--name-file <path> | --name <text>] '
+ '[--data-sources <csv>] [--clear-data-sources] [--model <id>] '
- + '[--connectors <path>] [--actions <path>] [--add-to-sitemap] [--overwrite-deployed]'
+ + '[--connectors <path>] [--actions <path>] [--add-to-sitemap] [--overwrite-deployed] [--solution <unique name>]'
+ ' (--app-id is required with --page-id and with --add-to-sitemap; --page-id alone finishes a page this tool created and did not finish)';
// The skill writes these inputs — the prompt, agent-message and page-name files, connectors.json, actions.json —
@@ -431,6 +441,20 @@ async function deploy(context) {
// The page's id as soon as it is known, kept outside the write's try: an update names it up front, and a create learns it from the backend — from its answer, or from the
// error it raises once it has sent (`pageId`). Whatever fails after that, the failure carries it.
let knownPageId = flags['page-id'] || null;
+ // The solution the page joins (--solution), read before anything is read for the update or written: a name that is no unmanaged solution, or an environment that
+ // cannot say the page table's component type, refuses the upload with nothing made. A system solution is not read (the backend answers it from its name).
+ let solutionTarget = null;
+ if (typeof flags.solution === 'string' && flags.solution.trim()) {
+ try {
+ solutionTarget = await genpage.solutionTarget(flags.solution);
+ } catch (e) {
+ return done(false, {
+ ok: false,
+ ...(e && typeof e.code === 'string' && e.code ? { code: e.code } : {}),
+ error: `nothing was written: the solution ${JSON.stringify(flags.solution.trim())} the page is to join cannot be used — ${(e && e.message) || e}`,
+ });
+ }
+ }
if (flags['page-id']) {
// An UPDATE must have a target that EXISTS, and it must be in the app it names: updating a real page through the wrong app would write
// the page and attach its tables to an app that does not hold it. The page read is the existence proof — a page that is not there is a
@@ -685,6 +709,26 @@ async function deploy(context) {
warnings.push(`could not clear the base marker's unfinished state (${(e && e.message) || e}) — running the same command with --page-id ${pageId} completes the page again, which changes nothing`);
}
}
+ // The solution the page joins, last: the page is written, published and placed by now, so an add that fails leaves a page that works and is not in the
+ // solution. That is a failure, said with the one command that adds the page — never a second create, which would make a second page.
+ let solutionFacts = {};
+ if (solutionTarget) {
+ const where = solutionTarget.uniqueName;
+ try {
+ const joined = await genpage.addToSolution(pageId, solutionTarget);
+ solutionFacts = { solution: where, addedToSolution: !!(joined && joined.added), ...(solutionTarget.systemSolution ? { systemSolution: true } : {}) };
+ } catch (e) {
+ const placedText = placement && placement.added && placement.added.length ? ` and placed in app ${flags['app-id']}'s navigation` : '';
+ return done(false, {
+ ...failed(`page ${pageId} was ${creating ? 'created' : 'saved'} and published${placedText}, but it was NOT added to solution ${where}: ${(e && e.message) || e}. `
+ + `Do not create it again: add it with node scripts/add-page-to-solution.js ${flags.env} ${where} --page-ids ${pageId} (a page the solution already holds is accepted, so running it again changes nothing).`),
+ code: 'solution-add-failed',
+ solution: where,
+ addedToSolution: false,
+ ...(warnings.length ? { warnings } : {}),
+ });
+ }
+ }
return done(true, {
ok: true,
pageId,
@@ -693,6 +737,7 @@ async function deploy(context) {
updated: !!flags['page-id'],
...(written && written.unchanged ? { unchanged: true } : {}),
...(placement && placement.added && placement.added.length ? { addedToSitemap: true } : {}),
+ ...solutionFacts,
...(warnings.length ? { warnings } : {}),
});
} catch (e) {
diff --git a/plugins/model-apps/scripts/get-lookup-metadata.js b/plugins/model-apps/scripts/get-lookup-metadata.js
new file mode 100644
index 000000000..082339a35
--- /dev/null
+++ b/plugins/model-apps/scripts/get-lookup-metadata.js
@@ -0,0 +1,115 @@
+#!/usr/bin/env node
+'use strict';
+// get-lookup-metadata: the lookup columns of the tables a generative page reads, each with its COMPLETE target set and the concrete
+// paths a page can filter a target through — what the genpage planner records in a page's `#### Lookup metadata` (and saves as
+// `lookup-metadata.json` in its working folder), so neither the planner nor the page builder guesses a lookup's targets or a
+// navigation path. Read-only: it composes the SDK's table metadata with the lookup-details relationship read (lib/lookup-metadata.js
+// says how, and why a shared path such as Owner's `ownerid` is never a target discriminator).
+//
+// Like every script here it emits no telemetry of its own, prints no token and no row data.
+//
+// Usage: node scripts/get-lookup-metadata.js --env <envUrl> --tables '<table1>,<table2>'
+// --env the environment's https origin, e.g. https://contoso.crm.dynamics.com
+// --tables one table logical name or several, comma-separated (spaces around a name are dropped; a name given twice is read once)
+//
+// Output (stdout, one pure-ASCII JSON line), exit 0 — only after every table and every relationship page was read:
+// { "ok": true, "tables": [ { "logicalName": "opportunity", "primaryIdAttribute": "opportunityid", "primaryNameAttribute": "name",
+// "lookups": [ { "column": "customerid", "readProperty": "_customerid_value", "attributeType": "Customer",
+// "targets": ["account", "contact"],
+// "paths": [ { "target": "account", "navigationProperty": "customerid_account", "referencedKey": "accountid",
+// "relationship": "opportunity_customer_accounts" }, … ],
+// "sharedPaths": [] }, … ] } ] }
+// A failed or incomplete read: { "ok": false, "error": "<message>", "code": "<code>" } on stdout and the message on stderr, exit 1 —
+// never an empty or shorter candidate list. Codes: LOOKUP_TABLE_NOT_FOUND (the environment has no table of that name), LOOKUP_METADATA_INCOMPLETE,
+// LOOKUP_RELATIONSHIPS_UNREADABLE, or the SDK's own (CONNECTION_ERROR for any other refused request, and when the Azure CLI cannot give a token).
+//
+// Exit codes: 0 read; 1 usage error (stderr names the flag and the usage, stdout stays empty) or a failure to read.
+
+const { parseArgs, validateFlags, emitResult, requireDataverseOrigin } = require('./lib/dataverse-auth.js');
+const { withThrowawaySdk } = require('./lib/throwaway-sdk.js');
+const { makeWritesBlocking } = require('./lib/output-redaction.js');
+const { readLookupMetadata } = require('./lib/lookup-metadata.js');
+
+const USAGE = "Usage: node scripts/get-lookup-metadata.js --env <envUrl> --tables '<table1>,<table2>'";
+
+/**
+ * The names of a --tables value: its comma-separated pieces, trimmed and lower-cased, the empty ones dropped and a name given twice kept
+ * once, in the order first met.
+ * @param {string} text
+ * @returns {string[]}
+ */
+function tableNames(text) {
+ const names = [];
+ for (const piece of String(text).split(',')) {
+ const name = piece.trim().toLowerCase();
+ if (name && !names.includes(name)) names.push(name);
+ }
+ return names;
+}
+
+/**
+ * Reads the lookups of `tables` through the vendored SDK.
+ * @param {string} env - a Dataverse https origin
+ * @param {{ tables: string[] }} args
+ * @param {object} [httpClient] - the SDK's HttpClient; the az-token one for `env` when omitted (a test seam)
+ */
+async function readLookups(env, { tables }, httpClient) {
+ return withThrowawaySdk({ env, httpClient, prefix: 'get-lookup-metadata-' }, async (make) => {
+ const sdk = make();
+ // fetchEntityMetadata keeps what it read in the SDK's workspace, which must exist first: a local folder, no request.
+ await sdk.initWorkspace();
+ return readLookupMetadata(sdk, tables);
+ });
+}
+
+function usageError(message) {
+ makeWritesBlocking(process.stdout, process.stderr);
+ process.stderr.write(`✗ ${message}\n${USAGE}\n`);
+ process.exit(1);
+}
+
+async function main() {
+ const argv = process.argv.slice(2);
+ const { positional, flags } = parseArgs(argv);
+ const flagError = validateFlags(argv, { known: ['env', 'tables'], needValue: ['env', 'tables'] });
+ if (flagError) usageError(flagError);
+ if (positional.length) usageError(`unexpected argument '${positional[0]}'`);
+ if (!flags.env) usageError('--env is required');
+ if (!flags.tables) usageError('--tables is required');
+ let env;
+ try {
+ env = requireDataverseOrigin(flags.env);
+ } catch (err) {
+ usageError(err.message);
+ }
+ const tables = tableNames(flags.tables);
+ if (!tables.length) usageError(`--tables '${flags.tables}' names no table`);
+ const invalid = tables.find((name) => !/^[a-z_][a-z0-9_]*$/.test(name));
+ if (invalid) usageError(`--tables: '${invalid}' is not a table logical name`);
+
+ // emitResult() ends the process, so the read's outcome is settled first and emitted outside the try: an exit inside it would be caught
+ // as a failure of the read.
+ let result;
+ let failure;
+ try {
+ result = await readLookups(env, { tables });
+ } catch (err) {
+ failure = err;
+ }
+ if (failure) {
+ const code = failure && typeof failure.code === 'string' ? failure.code : undefined;
+ emitResult(false, { ok: false, error: String((failure && failure.message) || failure), ...(code ? { code } : {}) }, { ascii: true });
+ return;
+ }
+ emitResult(true, result, { ascii: true });
+}
+
+module.exports = { readLookups, tableNames };
+
+if (require.main === module) {
+ main().catch((err) => {
+ makeWritesBlocking(process.stdout, process.stderr);
+ process.stderr.write(`Error: ${err.message}\n`);
+ process.exit(1);
+ });
+}
diff --git a/plugins/model-apps/scripts/lib/app-spec.js b/plugins/model-apps/scripts/lib/app-spec.js
index f5d88f181..128325632 100644
--- a/plugins/model-apps/scripts/lib/app-spec.js
+++ b/plugins/model-apps/scripts/lib/app-spec.js
@@ -8,6 +8,7 @@ const { isMainForm, selectDefaultForm, ordersByHand } = require('./form-order.js
const { AUTO_TAB_NAME, AUTO_SECTION_NAME, placementOf, resolvePlacement } = require('./form-subgrid-placement.js');
const { PAGE_BINDINGS, pageBindingsProblem, statedPageBindings, statableBinding, bindingProblemText } = require('./page-bindings.js');
const { nearestName } = require('./nearest-name.js');
+const { navigationHolds } = require('./app-navigation.js');
// URL scheme allowlist for spec-supplied URLs that the built app will RENDER (iframe dashboard tiles,
// sitemap URL subareas). Only http(s) is allowed — a `javascript:`, `data:`, `vbscript:`, or `file:`
@@ -858,6 +859,45 @@ const ENTITY_KEY_HINTS = Object.assign(Object.create(null), {
localizedLabels: ' — write the LCID map on the label FIELD itself (e.g. "displayName": { "1033": "Baseline", "3082": "Línea base" }), not in a separate per-table block; see references/app-spec-schema.md → "Localized labels"',
});
+// The keys of a table's `primaryAttribute`: exactly what the build reads from it — the name column's schema name and label for the
+// table's create, its number format (autoNumberFormat), its level (required) and its length (maxLength) — and what a download writes
+// (primaryColumnOptionFields). The same rule as ENTITY_KEYS one level down: any other key used to validate clean and be ignored, so a
+// `maxlength`, an `autonumberFormat` or a `requiredLevel` made the table without the length, the format or the level its author wrote.
+// Frozen, in the order the messages list them.
+const PRIMARY_ATTRIBUTE_KEYS = Object.freeze(['schemaName', 'displayName', 'autoNumberFormat', 'required', 'maxLength']);
+
+// What to write instead, for a key a near spelling cannot explain. Prototype-less for the reason ENTITY_KEY_HINTS is: the lookup key
+// comes from the spec. `type` is the one most likely to look harmless — the name column has no type to choose, so `"AutoNumber"` there
+// made a plain text name.
+const PRIMARY_ATTRIBUTE_KEY_HINTS = Object.assign(Object.create(null), {
+ requiredLevel: ' — the level is \'required\': true, "recommended" or false',
+ type: " — the primary name column is always a single line of text: leave 'type' out (for an auto-numbered name, give 'autoNumberFormat')",
+});
+
+// The findings for the keys of one table's `primaryAttribute`, each with `label` (how the caller names the table) in front: one per
+// unknown key, naming the key it most likely meant (a written hint first, then the shared single-edit matcher, which also settles a
+// casing slip such as `maxlength`) and the allowed keys. Nothing for a value that is not a plain object — the caller's
+// `primaryAttribute.schemaName` check already reports that, and `Object.keys('x')` would turn it into a bogus "unknown key '0'".
+// The ONE rule behind both gates — validateAppSpec and the provision-entities input validator — so that neither accepts what the other
+// refuses. Enumerating is guarded because the object comes from the caller, and a validator RETURNS problems rather than throw them.
+function primaryAttributeKeyProblems(primaryAttribute, label) {
+ if (!primaryAttribute || typeof primaryAttribute !== 'object' || Array.isArray(primaryAttribute)) return [];
+ let keys;
+ try {
+ keys = Object.keys(primaryAttribute);
+ } catch {
+ return [`${label}: primaryAttribute could not be inspected — enumerating its keys threw`];
+ }
+ const hintFor = (key) => {
+ if (PRIMARY_ATTRIBUTE_KEY_HINTS[key]) return PRIMARY_ATTRIBUTE_KEY_HINTS[key];
+ const near = nearestName(key, PRIMARY_ATTRIBUTE_KEYS.map((k) => k.toLowerCase()));
+ const meant = near && PRIMARY_ATTRIBUTE_KEYS.find((k) => k.toLowerCase() === near);
+ return meant ? ` — did you mean '${meant}'?` : '';
+ };
+ return keys.filter((key) => !PRIMARY_ATTRIBUTE_KEYS.includes(key))
+ .map((key) => `${label}: unknown key '${key}' on primaryAttribute${hintFor(key)} (allowed: ${PRIMARY_ATTRIBUTE_KEYS.join(', ')})`);
+}
+
// The most characters a table's primary name column may be asked for. A single line of text elsewhere in a table takes up
// to 4,000, but the name column of a table does not: asked for more than 850 in a table create that also carried other columns, the
// platform refuses it — HTTP 400, "The maximum length of Primary attribute 'new_name' is 4000. The maximum allowed limit
@@ -1279,20 +1319,46 @@ function labelAliases(value) {
// Returns the offending aliases so the error can name them, each flagged `hidden` when at least one
// side is a LOCALIZED label — that is the case the author cannot see by reading the line, and the
// only one severe enough to fail a spec that provisioned correctly before this rule existed.
+//
+// One localized shape is NOT hidden: two labels that are IDENTICAL — the same text in each of the
+// same languages, whether one language or several:
+// [ { "1036": "Ouvert" }, { "1036": "Ouvert" } ]
+// [ { "1033": "Abierto", "3082": "Abierto" }, { "1033": "Abierto", "3082": "Abierto" } ]
+// The two lines read alike, so this is the duplicate `["Ouvert", "Ouvert"]` is, in stated languages,
+// and it is reported the same way (a warning). It is what a download finds for two options a maker
+// labelled alike, which Dataverse allows: in one language other than the download's authoring one,
+// or — as Dataverse holds them, MEASURED — in two, because it fills the environment's base language
+// in with the same text when a label is created in another language only. Refusing it made the
+// download write the labels as plain strings, which a rebuild labels in another language, or leave
+// the column untyped, which a rebuild into a fresh environment makes a text column. A map beside a
+// plain string, or beside a map that differs from it in any language, still names two options in a
+// way the line does not show, and stays hidden.
+//
+// One clash per text: a label that holds one text in several languages names it once.
function ambiguousChoiceAliases(options) {
+ const list = options || [];
const seen = new Map(); // alias -> { index, localized }
const clashes = [];
- (options || []).forEach((label, i) => {
+ list.forEach((label, i) => {
const localized = isLocalizedLabelMap(label);
- for (const alias of labelAliases(label)) {
+ for (const alias of new Set(labelAliases(label))) {
const prior = seen.get(alias);
- if (prior && prior.index !== i) clashes.push({ alias, first: prior.index, second: i, hidden: localized || prior.localized });
+ if (prior && prior.index !== i) clashes.push({ alias, first: prior.index, second: i, hidden: (localized || prior.localized) && !identicalLocalizedLabels(label, list[prior.index]) });
else if (!prior) seen.set(alias, { index: i, localized });
}
});
return clashes;
}
+// Are two labels the same LOCALIZED label: both maps, keyed by the same canonical LCIDs, with the same
+// text at each? A map with a key that is no canonical LCID is never the same (validateLabel refuses it).
+function identicalLocalizedLabels(a, b) {
+ if (!isLocalizedLabelMap(a) || !isLocalizedLabelMap(b)) return false;
+ const keys = Object.keys(a);
+ if (keys.length !== Object.keys(b).length || localizedLabelLcids(a).length !== keys.length) return false;
+ return keys.every((k) => Object.prototype.hasOwnProperty.call(b, k) && a[k] === b[k]);
+}
+
// Reject a LOCALIZED label on a global choice. AB#6686428.
//
// Not a validation nicety: Dataverse ACCEPTS the multi-language payload and stores only the base
@@ -2488,6 +2554,11 @@ function validateAppSpec(spec, opts = {}) {
// structural profile (teardown, preview) takes it as a warning in the same words, and so does read-only verification, which keeps the
// deploy profile and passes `fieldOptionKeys: 'warn'`, as it passes `columnValues: 'warn'`. Nothing else about the entry moves.
const fieldOptionKeyFindings = profile === 'structural' || opts.fieldOptionKeys === 'warn' ? warnings : errors;
+ // Where an unknown key of a table's `primaryAttribute` goes (primaryAttributeKeyProblems), by the same arrangement as fieldOptions keys
+ // above: the build ignores such a key, so every profile that builds or plans a build keeps it an error, while a release before the check
+ // accepted and built a spec carrying one — so the structural profile and read-only verification (`primaryAttributeKeys: 'warn'`) take it
+ // as a warning in the same words.
+ const primaryAttributeKeyFindings = profile === 'structural' || opts.primaryAttributeKeys === 'warn' ? warnings : errors;
if (!VALIDATION_PROFILES.includes(profile)) {
return { ok: false, errors: [`unknown validation profile '${profile}' (valid: ${VALIDATION_PROFILES.join(', ')})`], warnings };
}
@@ -2665,6 +2736,7 @@ function validateAppSpec(spec, opts = {}) {
if (!e.primaryAttribute || !e.primaryAttribute.schemaName) {
errors.push(`entity ${e.schemaName}: primaryAttribute.schemaName required`);
}
+ primaryAttributeKeyFindings.push(...primaryAttributeKeyProblems(e.primaryAttribute, `entity ${e.schemaName}`));
// The length of the table's name column, asked for when the table is created (an existing table's column is left as it
// is).
if (e.primaryAttribute && typeof e.primaryAttribute === 'object') {
@@ -2777,8 +2849,12 @@ function validateAppSpec(spec, opts = {}) {
}
}
}
- if (!entityNames.size) {
- errors.push('at least one entity is required');
+ // A spec with no table is an app only when its navigation shows something else: generative pages, dashboards over tables
+ // the environment already has, or URLs. Such an app is real — `apps.js create --page-id` makes one, and the build makes one
+ // from a navigation of pages only by creating the pages first (app-navigation.js) — so a download of it must give a spec the
+ // build takes. Without a table AND without a navigation entry there is nothing to build an app from.
+ if (!entityNames.size && !navigationHolds(spec).entries) {
+ errors.push('at least one entity is required — or, for an app with no tables, an entry in appShell (a page, a dashboard or a URL)');
}
// Web resources (optional — JS/HTML/CSS shipped for form logic).
const WEB_RESOURCE_KINDS = new Set(['js', 'html', 'css', 'xml', 'png', 'jpg', 'gif', 'xsl', 'ico', 'svg', 'resx']);
@@ -4107,8 +4183,11 @@ function validateAppSpec(spec, opts = {}) {
if (typeof spec.design !== 'object' || spec.design === null || Array.isArray(spec.design)) {
errors.push('design must be an object');
} else {
- const allowed = new Set(['accentColor', 'density', 'cornerRadius', 'darkMode', 'layout']);
+ const allowed = new Set(['accentColor', 'density', 'cornerRadius', 'darkMode', 'layout', 'style']);
for (const k of Object.keys(spec.design)) if (!allowed.has(k)) errors.push(`design: unknown key '${k}' (allowed: ${[...allowed].join(', ')})`);
+ // `style` is the maker's own look in words (a screenshot read into colors and fonts, a website to match, a description), which the page plan
+ // carries as a `Maker-requested:` styling line that wins over the default look (lib/page-plan.js designPreferences). Text, or it says nothing.
+ if (spec.design.style !== undefined && (typeof spec.design.style !== 'string' || !spec.design.style.trim())) errors.push('design.style must be a non-empty string: the look the maker asked for, in words');
}
}
// Security personas (optional; additive — validated on v1 and v2 specs). Each persona authors ONE
@@ -4574,6 +4653,8 @@ module.exports = {
ENTITY_KEYS,
invalidLanguageCodeMessage,
ENTITY_KEY_HINTS,
+ PRIMARY_ATTRIBUTE_KEYS,
+ primaryAttributeKeyProblems,
DIRECT_ENTRY_BEHAVIORS,
COLUMN_VISUALIZATIONS,
INTEGER_FORMATS,
diff --git a/plugins/model-apps/scripts/lib/dataverse-operations.js b/plugins/model-apps/scripts/lib/dataverse-operations.js
new file mode 100644
index 000000000..c5afb480a
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/dataverse-operations.js
@@ -0,0 +1,158 @@
+'use strict';
+// The reviewed catalogue of BUILT-IN Dataverse operations a generative page may bind: exactly WhoAmI and RetrieveVersion.
+//
+// WHY A FIXED CATALOGUE, AND WHAT IT DOES NOT CLAIM. Custom API discovery (list-custom-apis.js) reads the `customapi` table, and these two are
+// not rows of it: they are messages the platform defines, described only in the service's $metadata document (many megabytes — about 19.6 MB was
+// measured on one environment), and even that document would not prove that the page's player supports a call or that the signed-in user may make
+// it. So nothing here asks an environment anything. The two entries were checked against their documented contracts, and every answer says what
+// was NOT checked: the environment, the player runtime and the user's privileges (VERIFICATION). Listing an operation is an offer, not a check
+// that the environment has it — a page's first call can still answer 404 — and growing the set is a reviewed code change, never a setting.
+// WhoAmI https://learn.microsoft.com/power-apps/developer/data-platform/webapi/reference/whoami
+// -> WhoAmIResponse { BusinessUnitId, UserId, OrganizationId: Edm.Guid }
+// RetrieveVersion https://learn.microsoft.com/power-apps/developer/data-platform/webapi/reference/retrieveversion
+// -> RetrieveVersionResponse { Version: Edm.String }
+// Both are unbound Functions with no parameters. "Function" (a GET) is not what admits them: CalculateRollupField and
+// IncrementKnowledgeArticleViewCount are Functions too, and they change data. They were admitted because each only retrieves the caller's identity
+// or the server's version. Actions, record- and set-bound operations and every other message stay out (references/dataverse-operations.md says why).
+//
+// WHY ONLY FOUR KEYS LEAVE THIS MODULE FOR A PAGE. A page's `actionBindings` entry is the wire object toActionBinding builds:
+// { "name": "WhoAmI", "isFunction": true, "displayName": "Current Dataverse identity", "parameterKinds": {} }
+// A descriptor carries more (`bindingType`, `parameters`, `response`, `outputPrivacy`, `invocation`, `requiresExplicitSelection`), and a page
+// list that holds a key outside the documented binding properties is left out of an App Spec WHOLE, with its unrelated Custom API entries
+// (lib/page-bindings.js, statableBindings). So a descriptor is never spread onto the wire, and the wire entry is built from the catalogue's own
+// values, never from the object a caller handed in.
+//
+// Recognition is not gated by the "dataverse-operations" feature flag: a download or a rebuild classifies a carried binding by name whatever the
+// flag says, and neither authors one. The flag gates OFFERING the catalogue (list-dataverse-operations.js) and authoring new bindings.
+const { isDeepStrictEqual } = require('node:util');
+
+// The catalogue's own revision, not the plugin's version: it changes only when the set or a contract changes.
+const CATALOGUE_VERSION = 1;
+
+// Freezes `value` and everything under it, so no caller can widen or alter what a later caller reads.
+function deepFreeze(value) {
+ if (value && typeof value === 'object' && !Object.isFrozen(value)) {
+ Object.freeze(value);
+ for (const key of Object.keys(value)) deepFreeze(value[key]);
+ }
+ return value;
+}
+
+const VERIFICATION = deepFreeze({ mode: 'catalogue-only', environment: 'not-checked', runtime: 'not-checked', privileges: 'not-checked' });
+
+// The descriptors, in catalogue order. `parameters: []` is "no inputs" — unlike a Custom API's empty `parameterKinds`, which can sit beside
+// lookup inputs (list-custom-apis.js lookupParameters) — and `parameterKinds: {}` is the wire map that says the same. `outputPrivacy` names what
+// a result reveals: WhoAmI answers the signed-in user's identifiers, so a page shows them only as the maker-requested feature, never logs them.
+const OPERATIONS = deepFreeze([
+ {
+ name: 'WhoAmI',
+ displayName: 'Current Dataverse identity',
+ isFunction: true,
+ bindingType: 'Global',
+ parameters: [],
+ parameterKinds: {},
+ response: {
+ typeName: 'Microsoft.Dynamics.CRM.WhoAmIResponse',
+ properties: { BusinessUnitId: 'Edm.Guid', UserId: 'Edm.Guid', OrganizationId: 'Edm.Guid' },
+ },
+ outputPrivacy: 'identity',
+ invocation: 'user-triggered',
+ requiresExplicitSelection: true,
+ },
+ {
+ name: 'RetrieveVersion',
+ displayName: 'Dataverse server version',
+ isFunction: true,
+ bindingType: 'Global',
+ parameters: [],
+ parameterKinds: {},
+ response: {
+ typeName: 'Microsoft.Dynamics.CRM.RetrieveVersionResponse',
+ properties: { Version: 'Edm.String' },
+ },
+ outputPrivacy: 'service-version',
+ invocation: 'user-triggered',
+ requiresExplicitSelection: true,
+ },
+]);
+
+const CATALOGUE = deepFreeze({ catalogueVersion: CATALOGUE_VERSION, verification: VERIFICATION, operations: OPERATIONS });
+const REVIEWED_OPERATION_NAMES = deepFreeze(OPERATIONS.map((operation) => operation.name));
+// A Map, not an object: a name is looked up as data, so `__proto__`, `constructor` or `toString` finds nothing rather than an inherited member.
+const BY_NAME = new Map(OPERATIONS.map((operation) => [operation.name, operation]));
+
+// The authoring codes and their fixed sentences. They are what an authoring step says when it refuses; none is a player `error.code`, none
+// restricts the Custom API path, and none quotes the text it refused (a name a maker typed can be anything).
+const AUTHORING_CODES = deepFreeze({
+ not_in_catalogue: 'Only WhoAmI and RetrieveVersion are offered by this feature. Other Dataverse operations require separately reviewed support.',
+ invalid_operation_contract: 'The selected built-in operation must be an explicitly declared, unbound Function with no inputs.',
+ duplicate_operation: 'Select each built-in operation once; duplicate bindings are not supported.',
+ selection_required: 'Select a built-in operation explicitly before generating its binding or call.',
+ explicit_trigger_required: 'This version supports user-triggered built-in operation calls only.',
+ catalogue_unavailable: 'The built-in operation catalogue could not be read. No built-in operations were offered.',
+});
+
+function authoringError(code) {
+ const error = new Error(AUTHORING_CODES[code]);
+ error.code = code;
+ return error;
+}
+
+const isPlainEntry = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
+
+/**
+ * The frozen descriptor of a reviewed operation, for an EXACT name only — no case, prefix, namespace or display-name folding — or null.
+ * @param {unknown} name
+ * @returns {object|null}
+ */
+function getReviewedDataverseOperation(name) {
+ return typeof name === 'string' ? BY_NAME.get(name) || null : null;
+}
+
+/**
+ * The whole catalogue, frozen: { catalogueVersion, verification, operations: [WhoAmI, RetrieveVersion] }. A caller passes the authoring gate
+ * before it offers any of it.
+ */
+function getDataverseOperationCatalogue() {
+ return CATALOGUE;
+}
+
+/**
+ * The `actionBindings` wire entry of a reviewed operation: a fresh object of exactly four keys, built from the catalogue. It accepts only a
+ * descriptor structurally equal to the current canonical one — an altered descriptor is refused, not repaired — and throws an Error with a
+ * fixed `code` and message otherwise. It checks no gate and no selection: its caller must already hold an enabled gate and the maker's
+ * affirmative selection of this operation. Discovery never calls it.
+ */
+function toActionBinding(descriptor) {
+ if (!isPlainEntry(descriptor)) throw authoringError('invalid_operation_contract');
+ const canonical = getReviewedDataverseOperation(descriptor.name);
+ if (!canonical) throw authoringError('not_in_catalogue');
+ if (!isDeepStrictEqual(descriptor, canonical)) throw authoringError('invalid_operation_contract');
+ return { name: canonical.name, isFunction: canonical.isFunction, displayName: canonical.displayName, parameterKinds: {} };
+}
+
+/**
+ * Whether `entry` is a NEWLY AUTHORED wire row of a reviewed operation: exactly the four keys toActionBinding gives it, with the catalogue's
+ * values — `isFunction: true`, no bound target, no inputs, no other property. { ok: true } or { ok: false, code, message }. It is not used to
+ * judge or repair a binding a page already holds: a preserved or downloaded entry stays as it is.
+ */
+function validateReviewedDataverseBinding(entry) {
+ if (!isPlainEntry(entry)) return refusal('invalid_operation_contract');
+ const canonical = getReviewedDataverseOperation(entry.name);
+ if (!canonical) return refusal('not_in_catalogue');
+ return isDeepStrictEqual(entry, toActionBinding(canonical)) ? { ok: true } : refusal('invalid_operation_contract');
+}
+
+function refusal(code) {
+ return { ok: false, code, message: AUTHORING_CODES[code] };
+}
+
+module.exports = {
+ CATALOGUE_VERSION,
+ REVIEWED_OPERATION_NAMES,
+ AUTHORING_CODES,
+ getReviewedDataverseOperation,
+ getDataverseOperationCatalogue,
+ toActionBinding,
+ validateReviewedDataverseBinding,
+};
diff --git a/plugins/model-apps/scripts/lib/feature-flags.js b/plugins/model-apps/scripts/lib/feature-flags.js
index d086c5a91..0abf7521f 100644
--- a/plugins/model-apps/scripts/lib/feature-flags.js
+++ b/plugins/model-apps/scripts/lib/feature-flags.js
@@ -8,14 +8,17 @@
// Until ALL of them are live in PROD, the skill must behave exactly as it did before
// the capability existed. A committed, default-OFF flag lets us merge the skill code
// ahead of release and flip it on in a follow-up (or per-run via env var) once
-// its dependencies are available. Custom API discovery now ships ON; the retained
-// flag remains an explicit opt-out, not a change to the generic fail-closed fallback.
+// its dependencies are available.
//
// A flag is flipped to `true` FIRST and removed in a later change, not both at once.
// Flipping is reversible in one line if the rollout turns out to be incomplete in some
// tenant; deleting the gate in the same change that enables the feature leaves no way
// back except a revert. Once a release has shipped with the flag on and no rollback was
// needed, remove it so unknown flags fail closed instead of staying permanently probed.
+// `custom-api` went that way: on by default since 2.18.0, with its platform dependencies
+// live in every region, it was removed, so Custom API discovery, authoring and upload are
+// always available and GENPAGE_ENABLE_CUSTOM_API no longer means anything. Nothing may ask
+// for it any more: as an unknown flag it would read as disabled.
//
// Precedence (highest first), mirroring the telemetry opt-out convention in
// AGENTS.md where an env var overrides committed config:
@@ -40,19 +43,6 @@ const FLAGS_PATH = path.resolve(__dirname, '..', '..', 'feature-flags.json');
// feature-flags.json only carries the on/off value; this catalog carries the
// metadata (what it enables, what it depends on, how to turn it on).
const FLAGS = {
- 'custom-api': {
- status: 'in-progress',
- summary:
- 'GenPage Dataverse Custom API (plug-in) invocation, enabled by default for supported public APIs — calling an Action or Function ' +
- 'from a generated page via dataApi.executeAction / executeFunction / listBoundActions, gated by ' +
- "the page's revision-bound actionBindings manifest.",
- dependencies:
- 'the AIBuilder CoderAgent action prompt, the shared pai-gen-ux-action-runtime plus the UCI ' +
- 'and Controls host runtimes, the page `actionBindings` the plugin writes into config.json ' +
- '(through the SDK, from genpage-upload.js --actions and the build), and the ' +
- 'GenUxPluginActionAllowList ECS setting — all live in PROD.',
- enableEnv: 'GENPAGE_ENABLE_CUSTOM_API=1',
- },
'custom-telemetry': {
status: 'in-progress',
summary:
@@ -65,6 +55,17 @@ const FLAGS = {
'GenUxEnableCustomTelemetry ECS setting — all live in PROD.',
enableEnv: 'GENPAGE_ENABLE_CUSTOM_TELEMETRY=1',
},
+ 'dataverse-operations': {
+ status: 'experimental',
+ summary:
+ 'Built-in Dataverse operation authoring — offers exactly WhoAmI and RetrieveVersion, two reviewed unbound Functions with no ' +
+ 'inputs, as explicitly selected, user-triggered page bindings called with dataApi.executeFunction. The offer comes from a ' +
+ 'fixed catalogue: it does not check the environment, the player runtime or the signed-in user privileges.',
+ dependencies:
+ 'the shared pai-gen-ux-action-runtime and a host runtime that implements executeFunction, the page `actionBindings` ' +
+ 'the plugin writes into config.json (genpage-upload.js --actions), and the GenUxPluginActionAllowList ECS setting.',
+ enableEnv: 'GENPAGE_ENABLE_DATAVERSE_OPERATIONS=1',
+ },
};
// Flag names the skill knows about, derived from the catalog. Used to validate the
@@ -85,7 +86,7 @@ function parseBool(value) {
return null;
}
-// 'custom-api' -> GENPAGE_ENABLE_CUSTOM_API. Non-alphanumeric runs in a flag name
+// 'dataverse-operations' -> GENPAGE_ENABLE_DATAVERSE_OPERATIONS. Non-alphanumeric runs in a flag name
// collapse to a single '_' so multi-word flags still map to a legal env var name.
function envVarName(flag) {
return 'GENPAGE_ENABLE_' + String(flag).toUpperCase().replace(/[^A-Z0-9]+/g, '_');
@@ -105,7 +106,7 @@ function readFlagsFile(flagsPath) {
/**
* Returns whether a named feature flag is enabled.
*
- * @param {string} flag Flag name (e.g. 'custom-api').
+ * @param {string} flag Flag name (e.g. 'dataverse-operations').
* @param {object} [opts]
* @param {NodeJS.ProcessEnv} [opts.env] Env source (defaults to process.env).
* @param {object} [opts.flags] Pre-loaded flags map (skips file read).
@@ -125,23 +126,21 @@ function isEnabled(flag, opts = {}) {
return flags[flag] === true;
}
-function isCustomApiEnabled(opts) {
- return isEnabled('custom-api', opts);
+// The built-in operation gate: it decides the offer and the authoring of WhoAmI and RetrieveVersion only (references/dataverse-operations.md).
+function isDataverseOperationsEnabled(opts) {
+ return isEnabled('dataverse-operations', opts);
}
-// Fail-closed gate shared by every Custom API (Dataverse Action/Function) script entry
-// point: exit 3 = "feature off", distinct from 1 = runtime/usage error, so a caller can tell
-// "not released" from "it broke". Centralizing it (instead of each script inlining the same
-// `if (!isCustomApiEnabled()) exit 3`) keeps the disabled message and exit code consistent and
-// prevents drift. `exit`/`write` are injectable for unit testing.
-function exitIfCustomApiDisabled(opts = {}) {
+// The fail-closed gate for list-dataverse-operations.js: exit 3 = "feature off", with one constant line. The line goes to stderr and the
+// process ends at once, so the write is made blocking first — on Linux and macOS a pipe's writes are otherwise queued and the exit cuts them off
+// (output-redaction.js). `exit`/`write` are injectable for unit testing.
+function exitIfDataverseOperationsDisabled(opts = {}) {
+ if (isDataverseOperationsEnabled(opts)) return undefined;
+ require('./output-redaction.js').makeWritesBlocking(process.stderr);
const exit = opts.exit || process.exit;
const write = opts.write || ((s) => process.stderr.write(s));
- if (!isCustomApiEnabled(opts)) {
- write(customApiDisabledMessage() + '\n');
- return exit(3);
- }
- return undefined;
+ write(dataverseOperationsDisabledMessage() + '\n');
+ return exit(3);
}
// Returns the effective state of every known flag plus where the value came from
@@ -178,24 +177,21 @@ function validateFlags(flags) {
return warnings;
}
-// Standard operator-facing message printed when a Custom API entrypoint is invoked while
-// the flag is OFF. Centralized so every Custom API script speaks with one voice about why it
-// stopped and how to turn the feature on.
-function customApiDisabledMessage() {
+// The one line list-dataverse-operations.js prints when the built-in operation gate is OFF. Byte-stable: the skill text quotes it, and a test
+// reads it through a pipe. It says what OFF does NOT mean — existing bindings stay, and the platform's own governance still decides a call.
+function dataverseOperationsDisabledMessage() {
return (
- 'Dataverse Custom API support is disabled (feature flag "custom-api" is OFF). ' +
- 'Discovery is enabled by default; GENPAGE_ENABLE_CUSTOM_API=0 explicitly disables it. ' +
- 'To enable for a single run set GENPAGE_ENABLE_CUSTOM_API=1, or set "custom-api" to true in ' +
- 'plugins/model-apps/feature-flags.json. Runtime capabilities, environment governance and ' +
- 'the signed-in user privileges still apply.'
+ 'Dataverse built-in operation authoring is disabled (feature flag "dataverse-operations" is OFF). ' +
+ 'Set GENPAGE_ENABLE_DATAVERSE_OPERATIONS=1 to offer WhoAmI and RetrieveVersion. ' +
+ 'Existing bindings are preserved; runtime governance and user privileges still apply.'
);
}
module.exports = {
isEnabled,
- isCustomApiEnabled,
- customApiDisabledMessage,
- exitIfCustomApiDisabled,
+ isDataverseOperationsEnabled,
+ dataverseOperationsDisabledMessage,
+ exitIfDataverseOperationsDisabled,
describe,
validateFlags,
envVarName,
diff --git a/plugins/model-apps/scripts/lib/genpage-plan-semantics.js b/plugins/model-apps/scripts/lib/genpage-plan-semantics.js
new file mode 100644
index 000000000..afca92ab8
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/genpage-plan-semantics.js
@@ -0,0 +1,670 @@
+'use strict';
+// The plan's semantic contract (references/plan-schema.md), read without any I/O: what was assumed rather than stated, the
+// relationship and filter decisions each page makes, and the lookups it relies on. Two documents carry it, at different heading
+// levels, and each is read by its own reader — never by planSection, which knows level-two sections only:
+//
+// written plan (genpage-plan.md) approval preview (the body the maker approved)
+// ## Assumptions ### Assumptions (first, before ### Pages)
+// ### A1 — Opportunity relationship #### A1 — Opportunity relationship
+// - Decision: … - Decision: …
+// ## Per-Page Specifications ### Data Semantics
+// ### <Page Name> (its - **File:** names #### <page file>
+// #### Data semantics the page) ##### R<n> or F<n>
+// ##### R<n> or F<n> ### Lookup Metadata
+// #### Lookup metadata #### <page file>
+// | Table | Column | Read property | Targets | Used by | Metadata state |
+//
+// Entry grammar (both documents): `- <Field>: <value>` bullets, a value continued on indented lines (a blank line ends it).
+// Values are compared after Unicode NFC and whitespace collapsing only — case and wording are substantive. Anything the grammar
+// does not name (another field, a prose line, a nested heading, a second section of the same name) is an error, never skipped:
+// a skipped line is an approved decision nobody can see. Empty sections hold an exact sentinel (`No assumptions.`, `None.`).
+//
+// What this proves is structure, identifiers, sources, quotes and agreement between the approved and the written records. It
+// does not prove that a quote entails a predicate, that a decision is material, or that prose elsewhere does not contradict it.
+
+const path = require('node:path');
+const { planSection } = require('./plan-sections.js');
+
+const ASSUMPTION_ID = /^A[1-9][0-9]*$/;
+const DECISION_ID = /^([RF])[1-9][0-9]*$/;
+const QUESTION_ID = /^[^\s/()]+$/;
+// The repository's logical-name shape (lib/app-components.js TABLE_NAME): lower case letters, digits, underscores, not a digit first.
+const LOGICAL_NAME = /^[a-z_][a-z0-9_]*$/;
+// A navigation property keeps its schema casing (`parentcustomerid_account`, `cr123_ProjectId`).
+const NAVIGATION_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
+const RESOLUTIONS = ['user-confirmed', 'planner-default', 'unattended-default'];
+const EVIDENCE = /^(?:metadata|sample|default):\s*\S/;
+const ASSUMPTION_FIELDS = ['Decision', 'Alternatives considered', 'Evidence', 'Resolution', 'Question', 'Answer', 'Default record'];
+const DECISION_FIELDS = ['Kind', 'Definition', 'Source', 'Requirement quote'];
+const LOOKUP_BULLETS = ['Evidence', 'Read target strategy'];
+const LOOKUP_COLUMNS = ['table', 'column', 'read property', 'targets', 'used by', 'metadata state'];
+const PATH_COLUMNS = ['table', 'column', 'target', 'navigation property', 'referenced key'];
+const NO_ASSUMPTIONS = 'No assumptions.';
+const NONE = 'None.';
+const KIND_OF = { R: 'relationship', F: 'filter' };
+
+function problem(code, message) {
+ return { code, message };
+}
+
+// What a value is compared as: NFC, every run of whitespace one space, trimmed. Case and wording are kept.
+function normalizeValue(value) {
+ return String(value ?? '').normalize('NFC').replace(/\s+/g, ' ').trim();
+}
+
+// An ATX heading: `### A1 — Opportunity relationship` → { level: 3, title: 'A1 — Opportunity relationship' }.
+function heading(line) {
+ const match = /^(#{1,6})[ \t]+(.*?)[ \t]*$/.exec(line);
+ return match && match[2] ? { level: match[1].length, title: match[2] } : null;
+}
+
+// Every heading of exactly `level` among `lines`, each with its body: the lines up to the next heading at `level` or shallower.
+function sectionsAt(lines, level) {
+ const out = [];
+ for (let i = 0; i < lines.length; i += 1) {
+ const found = heading(lines[i]);
+ if (!found || found.level !== level) continue;
+ let end = i + 1;
+ while (end < lines.length) {
+ const next = heading(lines[end]);
+ if (next && next.level <= level) break;
+ end += 1;
+ }
+ out.push({ title: found.title, index: i, body: lines.slice(i + 1, end) });
+ }
+ return out;
+}
+
+// A bounded body split at its headings of `level`: { lead, blocks: [{ title, body }] }. A heading of any other level stays in the
+// body it falls in, where the grammar refuses it.
+function blocksAt(lines, level) {
+ const lead = [];
+ const blocks = [];
+ let current = null;
+ for (const line of lines) {
+ const found = heading(line);
+ if (found && found.level === level) {
+ current = { title: found.title, body: [] };
+ blocks.push(current);
+ continue;
+ }
+ (current ? current.body : lead).push(line);
+ }
+ return { lead, blocks };
+}
+
+const meaningful = (lines) => lines.map((line) => line.trim()).filter(Boolean);
+
+// The `- Field: value` bullets of an entry body, by canonical field name. A value may continue on indented lines; a blank line ends
+// it. An unknown field, a repeated one, a nested heading or any other line is reported through `fail` and read as nothing.
+// - Evidence: metadata: customerid targets account, contact;
+// parentaccountid targets account.
+// is Evidence = "metadata: customerid targets account, contact; parentaccountid targets account."
+function entryFields(body, known, label, fail) {
+ const fields = new Map();
+ let last = null;
+ for (const raw of body) {
+ if (!raw.trim()) { last = null; continue; }
+ if (heading(raw)) { fail(`${label}: unexpected heading "${raw.trim()}"`); last = null; continue; }
+ const bullet = /^[-*][ \t]+([^:\n]+?)[ \t]*:[ \t]*(.*)$/.exec(raw);
+ if (bullet) {
+ const name = known.find((field) => field.toLowerCase() === bullet[1].trim().toLowerCase());
+ if (!name) { fail(`${label}: unrecognized field "${bullet[1].trim()}"`); last = null; continue; }
+ if (fields.has(name)) { fail(`${label}: duplicate field "${name}"`); last = null; continue; }
+ fields.set(name, bullet[2]);
+ last = name;
+ continue;
+ }
+ if (last && /^[ \t]+\S/.test(raw)) { fields.set(last, `${fields.get(last)} ${raw.trim()}`); continue; }
+ fail(`${label}: unrecognized line "${raw.trim().slice(0, 80)}"`);
+ last = null;
+ }
+ for (const [name, value] of fields) fields.set(name, normalizeValue(value));
+ return fields;
+}
+
+// A page file as the Pages table and planTargets spell it: backticks dropped, `.` segments removed (`./a.tsx` is `a.tsx`).
+function pageFileKey(text) {
+ const bare = String(text || '').trim().replace(/^`(.*)`$/, '$1').trim();
+ return bare ? path.posix.normalize(bare) : '';
+}
+
+const quoteless = (text) => text.replace(/^(["'“‘])(.*)(["'”’])$/u, (all, open, inner, close) => (
+ (open === '"' && close === '"') || (open === "'" && close === "'") || (open === '“' && close === '”') || (open === '‘' && close === '’') ? inner : all));
+
+// The assumption entries of a section body (written: level 3 under `## Assumptions`; preview: level 4 under `### Assumptions`):
+// { sentinel, entries: Map(id → entry) }. Entry rules (references/plan-schema.md "## Assumptions"):
+// - ids `A<n>`, unique; Decision, Alternatives considered, Evidence and Resolution present and non-empty;
+// - Evidence starts with `metadata:`, `sample:` or `default:`;
+// - Resolution `user-confirmed` (needs Question and Answer), `planner-default` (no question asked, so neither, and no Default record)
+// or `unattended-default` (Question, Answer and the exact Default record line, below).
+function readAssumptions(body, level, where, problems) {
+ const fail = (message) => problems.push(problem('invalid-assumptions', message));
+ const { lead, blocks } = blocksAt(body, level);
+ const leadText = meaningful(lead);
+ const entries = new Map();
+ if (!blocks.length) {
+ if (leadText.length === 1 && leadText[0] === NO_ASSUMPTIONS) return { sentinel: true, entries };
+ fail(`${where} must hold "${'#'.repeat(level)} A1 — …" entries or exactly "${NO_ASSUMPTIONS}"`);
+ return { sentinel: false, entries };
+ }
+ if (leadText.length) fail(`${where} has text before its first entry: "${leadText[0].slice(0, 80)}"`);
+ for (const block of blocks) {
+ const title = /^(A[1-9][0-9]*)(?:[ \t]+[—–-][ \t]+(\S.*))?$/.exec(block.title.trim());
+ if (!title) { fail(`${where}: "${'#'.repeat(level)} ${block.title}" is not an assumption id (A1, A2, …)`); continue; }
+ const id = title[1];
+ const label = `${where} ${id}`;
+ if (entries.has(id)) { fail(`${where}: duplicate assumption id ${id}`); continue; }
+ const fields = entryFields(block.body, ASSUMPTION_FIELDS, label, fail);
+ const entry = {
+ id,
+ title: normalizeValue(title[2] || ''),
+ decision: fields.get('Decision'),
+ alternatives: fields.get('Alternatives considered'),
+ evidence: fields.get('Evidence'),
+ resolution: fields.get('Resolution'),
+ question: fields.get('Question'),
+ answer: fields.get('Answer'),
+ defaultRecord: fields.get('Default record'),
+ };
+ for (const field of ['Decision', 'Alternatives considered', 'Evidence', 'Resolution']) {
+ if (!fields.get(field)) fail(`${label}: missing ${field}`);
+ }
+ for (const field of ['Question', 'Answer', 'Default record']) {
+ if (fields.has(field) && !fields.get(field)) fail(`${label}: ${field} is empty`);
+ }
+ if (entry.evidence && !EVIDENCE.test(entry.evidence)) fail(`${label}: Evidence must start with "metadata:", "sample:" or "default:"`);
+ if (entry.resolution && !RESOLUTIONS.includes(entry.resolution)) {
+ fail(`${label}: Resolution must be ${RESOLUTIONS.join(', ')} (got "${entry.resolution}")`);
+ }
+ if (entry.question && !QUESTION_ID.test(entry.question)) fail(`${label}: Question must be the question's id (got "${entry.question}")`);
+ if (entry.resolution === 'user-confirmed' || entry.resolution === 'unattended-default') {
+ if (!entry.question) fail(`${label}: a ${entry.resolution} assumption needs the Question it answered`);
+ if (!entry.answer) fail(`${label}: a ${entry.resolution} assumption needs the actual Answer`);
+ }
+ if (entry.resolution === 'planner-default' && (entry.question || entry.answer)) {
+ fail(`${label}: a planner-default assumption asked no question — an answered one is user-confirmed or unattended-default`);
+ }
+ if (entry.resolution === 'unattended-default') {
+ const why = defaultRecordProblem(entry);
+ if (why) fail(`${label}: ${why}`);
+ } else if (entry.defaultRecord) {
+ fail(`${label}: only an unattended-default assumption carries a Default record`);
+ }
+ entries.set(id, entry);
+ }
+ return { sentinel: false, entries };
+}
+
+// The Default record of an unattended-default assumption is the exact line the run logged in workflow-log.md:
+// Unattended default: A1 / opportunities-account-scope → Direct customer account only (the request excludes contact roll-up)
+// — this entry's id, its Question, its Answer word for word, either arrow (`→`, or the historical `->`), and a non-empty reason
+// in parentheses that does not contain the word "approved": that word is reserved for the separate plan-approval record
+// (`Unattended default: plan approval → approved (…)`), which a semantic default must never be mistaken for.
+function defaultRecordProblem(entry) {
+ if (!entry.defaultRecord) return 'an unattended-default assumption needs its Default record';
+ if (!entry.question || !entry.answer) return null;
+ const record = entry.defaultRecord;
+ const head = ['→', '->'].map((arrow) => normalizeValue(`Unattended default: ${entry.id} / ${entry.question} ${arrow} ${entry.answer} (`))
+ .find((prefix) => record.startsWith(prefix));
+ if (!head) return `the Default record must read "Unattended default: ${entry.id} / ${entry.question} → ${entry.answer} (<reason>)"`;
+ const rest = record.slice(head.length);
+ if (!rest.endsWith(')') || !rest.slice(0, -1).trim()) return 'the Default record must end with its reason in parentheses';
+ if (/\bapproved\b/i.test(rest.slice(0, -1))) return 'the Default record\'s reason must not contain the word "approved" (reserved for plan approval)';
+ return null;
+}
+// The relationship and filter decisions of one page (written: level 5 under `#### Data semantics`; preview: level 5 under the page's
+// `#### <file>` in `### Data Semantics`): { sentinel, entries: Map(id → decision) }. Ids are page-local `R<n>` (Kind relationship)
+// and `F<n>` (Kind filter); Source is one assumption id or exactly `User Requirements`, which also needs a Requirement quote.
+// The cross-references (an assumption that exists, a quote found in the requirements) are checked by the caller, which knows both.
+function readDecisions(body, where, problems) {
+ const fail = (message) => problems.push(problem('invalid-data-semantics', message));
+ const { lead, blocks } = blocksAt(body, 5);
+ const leadText = meaningful(lead);
+ const entries = new Map();
+ if (!blocks.length) {
+ if (leadText.length === 1 && leadText[0] === NONE) return { sentinel: true, entries };
+ fail(`${where} must hold "##### R1" / "##### F1" entries or exactly "${NONE}"`);
+ return { sentinel: false, entries };
+ }
+ if (leadText.length) fail(`${where} has text before its first entry: "${leadText[0].slice(0, 80)}"`);
+ for (const block of blocks) {
+ const id = block.title.trim();
+ const shape = DECISION_ID.exec(id);
+ if (!shape) { fail(`${where}: "##### ${block.title}" is not a decision id (R1, F1, …)`); continue; }
+ const label = `${where} ${id}`;
+ if (entries.has(id)) { fail(`${where}: duplicate decision id ${id}`); continue; }
+ const fields = entryFields(block.body, DECISION_FIELDS, label, fail);
+ const decision = {
+ id,
+ kind: fields.get('Kind'),
+ definition: fields.get('Definition'),
+ source: fields.get('Source'),
+ quote: fields.has('Requirement quote') ? quoteless(fields.get('Requirement quote')) : undefined,
+ };
+ if (decision.kind !== KIND_OF[shape[1]]) fail(`${label}: Kind must be "${KIND_OF[shape[1]]}" for an ${shape[1]} id (got "${decision.kind || ''}")`);
+ if (!decision.definition) fail(`${label}: missing Definition`);
+ if (!decision.source) {
+ problems.push(problem('missing-semantic-source', `${label}: missing Source — one assumption id or exactly "User Requirements"`));
+ } else if (decision.source !== 'User Requirements' && !ASSUMPTION_ID.test(decision.source)) {
+ problems.push(problem('missing-semantic-source', `${label}: Source must be one assumption id or exactly "User Requirements" (got "${decision.source}")`));
+ }
+ entries.set(id, decision);
+ }
+ return { sentinel: false, entries };
+}
+
+// Splits a `| a | b |` line into its trimmed cells, or null for a line that is not a table row.
+function tableCells(line) {
+ return /^\s*\|.*\|\s*$/.test(line) ? line.trim().slice(1, -1).split('|').map((cell) => cell.trim()) : null;
+}
+const isDelimiter = (cells) => cells.length > 0 && cells.every((cell) => /^:?-{3,}:?$/.test(cell));
+
+// The lookup records of one page (written: under `#### Lookup metadata`; preview: under the page's `#### <file>` in
+// `### Lookup Metadata`), exactly the shape references/plan-schema.md documents:
+// | Table | Column | Read property | Targets | Used by | Metadata state |
+// |-------|--------|---------------|---------|---------|----------------|
+// | opportunity | customerid | _customerid_value | account, contact | R<n>, F<n>; customer navigation | observed |
+//
+// | Table | Column | Target | Navigation property | Referenced key |
+// |-------|--------|--------|---------------------|----------------|
+// | opportunity | customerid | account | customerid_account | accountid |
+//
+// - Evidence: lookup-metadata.json; successful source/target metadata discovery.
+// - Read target strategy: normalize the logical-name annotation and qualified prefix; …
+// or exactly `None.`. Returns { sentinel, rows: Map('table|column' → row), paths: Map('table|column|target' → path), evidence,
+// strategy }. Targets is the complete allowed set; Used by names decisions (R<n>/F<n>, checked by the caller) and declared purposes;
+// Metadata state is `planned` (a table not created yet — no paths) or `observed`.
+function readLookups(body, where, problems) {
+ const fail = (message) => problems.push(problem('invalid-lookup-metadata', message));
+ const result = { sentinel: false, rows: new Map(), paths: new Map(), evidence: undefined, strategy: undefined };
+ const text = meaningful(body);
+ if (text.length === 1 && text[0] === NONE) return { ...result, sentinel: true };
+ if (!text.length) { fail(`${where} must hold the lookup table or exactly "${NONE}"`); return result; }
+ const tables = [];
+ const bulletLines = [];
+ for (let i = 0; i < body.length; i += 1) {
+ const cells = tableCells(body[i]);
+ if (!cells) { bulletLines.push(body[i]); continue; }
+ const next = i + 1 < body.length ? tableCells(body[i + 1]) : null;
+ if (!next || !isDelimiter(next)) { fail(`${where}: a table row outside a table: "${body[i].trim().slice(0, 80)}"`); continue; }
+ const table = { headers: cells.map((cell) => cell.toLowerCase()), rows: [] };
+ i += 2;
+ while (i < body.length && tableCells(body[i])) {
+ const row = tableCells(body[i]);
+ if (isDelimiter(row)) fail(`${where}: a second delimiter row inside a table`);
+ else table.rows.push(row);
+ i += 1;
+ }
+ i -= 1;
+ tables.push(table);
+ }
+ const sameColumns = (headers, wanted) => headers.length === wanted.length && wanted.every((column) => headers.includes(column));
+ const lookupTables = tables.filter((table) => sameColumns(table.headers, LOOKUP_COLUMNS));
+ const pathTables = tables.filter((table) => sameColumns(table.headers, PATH_COLUMNS));
+ for (const table of tables) {
+ if (!lookupTables.includes(table) && !pathTables.includes(table)) fail(`${where}: a table with columns ${table.headers.join(', ')} is not a lookup or path table`);
+ }
+ if (lookupTables.length !== 1) fail(`${where} must hold exactly one lookup table (Table, Column, Read property, Targets, Used by, Metadata state)`);
+ if (pathTables.length > 1) fail(`${where} must hold at most one path table (Table, Column, Target, Navigation property, Referenced key)`);
+ const cell = (table, row, column) => normalizeValue(row[table.headers.indexOf(column)] ?? '');
+ for (const table of lookupTables.slice(0, 1)) {
+ for (const raw of table.rows) {
+ const row = {
+ table: cell(table, raw, 'table'),
+ column: cell(table, raw, 'column'),
+ readProperty: cell(table, raw, 'read property'),
+ targets: cell(table, raw, 'targets').split(',').map((target) => target.trim()).filter(Boolean),
+ usedBy: cell(table, raw, 'used by').split(/[;,]/).map((item) => normalizeValue(item)).filter(Boolean),
+ state: cell(table, raw, 'metadata state'),
+ };
+ const key = `${row.table}|${row.column}`;
+ const label = `${where} ${row.table}.${row.column}`;
+ if (raw.length !== table.headers.length) fail(`${label}: the row has ${raw.length} cells, the table ${table.headers.length} columns`);
+ if (!LOGICAL_NAME.test(row.table) || !LOGICAL_NAME.test(row.column)) fail(`${label}: Table and Column must be logical names`);
+ if (row.readProperty !== `_${row.column}_value`) fail(`${label}: Read property must be _${row.column}_value`);
+ if (!row.targets.length) fail(`${label}: Targets must list the lookup's complete target set`);
+ if (row.targets.some((target) => !LOGICAL_NAME.test(target))) fail(`${label}: every target must be a table logical name`);
+ if (new Set(row.targets).size !== row.targets.length) fail(`${label}: a target is listed twice`);
+ if (!row.usedBy.length) fail(`${label}: Used by must name the decisions or purposes that use the lookup`);
+ if (row.state !== 'planned' && row.state !== 'observed') fail(`${label}: Metadata state must be planned or observed (got "${row.state}")`);
+ if (result.rows.has(key)) fail(`${where}: ${row.table}.${row.column} is listed twice`);
+ else result.rows.set(key, row);
+ }
+ if (!table.rows.length) fail(`${where}: the lookup table has no rows — write exactly "${NONE}" when the page uses no lookup`);
+ }
+ for (const table of pathTables.slice(0, 1)) {
+ for (const raw of table.rows) {
+ const entry = {
+ table: cell(table, raw, 'table'),
+ column: cell(table, raw, 'column'),
+ target: cell(table, raw, 'target'),
+ navigation: cell(table, raw, 'navigation property'),
+ key: cell(table, raw, 'referenced key'),
+ };
+ const label = `${where} ${entry.table}.${entry.column} → ${entry.target}`;
+ const lookup = result.rows.get(`${entry.table}|${entry.column}`);
+ if (!lookup) fail(`${label}: the path names a lookup the lookup table does not list`);
+ else if (!lookup.targets.includes(entry.target)) fail(`${label}: ${entry.target} is not one of the lookup's targets`);
+ else if (lookup.state !== 'observed') fail(`${label}: a planned lookup has no measured path yet`);
+ if (!NAVIGATION_NAME.test(entry.navigation)) fail(`${label}: Navigation property must be a navigation property name`);
+ if (!LOGICAL_NAME.test(entry.key)) fail(`${label}: Referenced key must be the target's key column`);
+ const key = `${entry.table}|${entry.column}|${entry.target}`;
+ if (result.paths.has(key)) fail(`${label}: the path is listed twice`);
+ else result.paths.set(key, entry);
+ }
+ }
+ const bullets = entryFields(bulletLines, LOOKUP_BULLETS, where, fail);
+ result.evidence = bullets.get('Evidence');
+ result.strategy = bullets.get('Read target strategy');
+ if (result.rows.size && !result.evidence) fail(`${where}: missing "- Evidence:" — the metadata read the records come from`);
+ if (result.rows.size && !result.strategy) fail(`${where}: missing "- Read target strategy:"`);
+ return result;
+}
+// Cross-references within one document: a decision's assumption exists; a `User Requirements` source carries a Requirement quote
+// that the original requirements contain (after the same NFC and whitespace normalization, case kept); every decision a lookup
+// is Used by exists on that page. `requirements` is null for the preview, which does not carry the requirements text: its records
+// must equal the written plan's, which is checked against them.
+function crossCheck(read, requirements, problems) {
+ const assumed = read.assumptions ? read.assumptions.entries : new Map();
+ const text = requirements === null ? null : normalizeValue(requirements);
+ for (const [file, page] of read.pages) {
+ const decisions = page.semantics ? page.semantics.entries : new Map();
+ for (const decision of decisions.values()) {
+ const label = `${file} ${decision.id}`;
+ if (decision.source && ASSUMPTION_ID.test(decision.source) && !assumed.has(decision.source)) {
+ problems.push(problem('unknown-assumption', `${label}: Source ${decision.source} is not an entry of Assumptions`));
+ }
+ if (decision.source === 'User Requirements' && !decision.quote) {
+ problems.push(problem('unmatched-requirement-quote', `${label}: a User Requirements source needs a Requirement quote`));
+ }
+ if (decision.quote !== undefined && text !== null && !text.includes(normalizeValue(decision.quote))) {
+ problems.push(problem('unmatched-requirement-quote', `${label}: the Requirement quote "${decision.quote.slice(0, 80)}" is not in User Requirements`));
+ }
+ }
+ for (const row of page.lookups ? page.lookups.rows.values() : []) {
+ for (const item of row.usedBy) {
+ if (DECISION_ID.test(item) && !decisions.has(item)) {
+ problems.push(problem('invalid-lookup-metadata', `${file} ${row.table}.${row.column}: Used by names ${item}, which the page's Data semantics does not define`));
+ }
+ }
+ }
+ }
+}
+
+// The written plan's semantic records: { problems, assumptions: null | { sentinel, entries }, pages: Map(file → { page,
+// semantics: null | …, lookups: null | … }), requirements }. null means "not recorded" — an older plan — never "none".
+// Pages are keyed by their `- **File:** <file>` bullet, the name the approval preview groups them by.
+function readWrittenSemantics(plan) {
+ const lines = String(plan ?? '').replace(/\r\n?/g, '\n').split('\n');
+ const problems = [];
+ const read = { problems, assumptions: null, pages: new Map(), requirements: planSection(lines.join('\n'), 'User Requirements') ?? '' };
+ const level2 = sectionsAt(lines, 2);
+ const assumptionSections = level2.filter((section) => section.title.trim().toLowerCase() === 'assumptions');
+ if (assumptionSections.length > 1) problems.push(problem('invalid-assumptions', 'the plan has more than one ## Assumptions section'));
+ if (assumptionSections.length) read.assumptions = readAssumptions(assumptionSections[0].body, 3, '## Assumptions', problems);
+ const specs = level2.filter((section) => section.title.trim().toLowerCase() === 'per-page specifications');
+ const blocks = specs.flatMap((section) => sectionsAt(section.body, 3));
+ const contract = read.assumptions !== null || blocks.some((block) => sectionsAt(block.body, 4)
+ .some((sub) => ['data semantics', 'lookup metadata'].includes(sub.title.trim().toLowerCase())));
+ if (specs.length > 1 && contract) problems.push(problem('invalid-data-semantics', 'the plan has more than one ## Per-Page Specifications section'));
+ const fileLines = (block) => block.body.map((line) => /^\s*[-*]\s+\*\*File:\*\*\s*(.*?)\s*$/i.exec(line)).filter(Boolean).map((match) => pageFileKey(match[1]));
+ if (contract) {
+ // A plan carrying the contract has ONE specification per page. A second block with the same title or file — with or
+ // without records of its own, before or after the one that has them — is refused here, before the legacy branch below
+ // skips a block without records: the schema reader keeps the LAST block of a title and this reader the first with
+ // records, so two authoritative blocks would otherwise be certified as one approved page. An older plan (no contract)
+ // keeps its absence-only reading.
+ const titles = new Set();
+ const named = new Set();
+ for (const block of specs.length ? sectionsAt(specs[0].body, 3) : []) {
+ const title = block.title.trim().toLowerCase();
+ if (titles.has(title)) problems.push(problem('invalid-data-semantics', `### ${block.title}: the plan has another page specification with this title`));
+ titles.add(title);
+ for (const file of new Set(fileLines(block).filter(Boolean))) {
+ if (named.has(file)) problems.push(problem('invalid-data-semantics', `### ${block.title}: another page specification has the file ${file}`));
+ named.add(file);
+ }
+ }
+ }
+ for (const block of specs.length ? sectionsAt(specs[0].body, 3) : []) {
+ const subs = sectionsAt(block.body, 4);
+ const semantics = subs.filter((sub) => sub.title.trim().toLowerCase() === 'data semantics');
+ const lookups = subs.filter((sub) => sub.title.trim().toLowerCase() === 'lookup metadata');
+ const files = fileLines(block);
+ const where = `### ${block.title}`;
+ if (!semantics.length && !lookups.length) {
+ if (files.length === 1 && files[0] && !read.pages.has(files[0])) read.pages.set(files[0], { page: block.title, semantics: null, lookups: null });
+ continue;
+ }
+ if (files.length !== 1 || !files[0]) {
+ problems.push(problem('invalid-data-semantics', `${where}: a page with Data semantics or Lookup metadata needs exactly one - **File:** line`));
+ continue;
+ }
+ if (read.pages.has(files[0]) && (read.pages.get(files[0]).semantics !== null || read.pages.get(files[0]).lookups !== null)) {
+ problems.push(problem('invalid-data-semantics', `${where}: another page specification has the file ${files[0]}`));
+ continue;
+ }
+ if (semantics.length > 1) problems.push(problem('invalid-data-semantics', `${where} has more than one #### Data semantics`));
+ if (lookups.length > 1) problems.push(problem('invalid-lookup-metadata', `${where} has more than one #### Lookup metadata`));
+ read.pages.set(files[0], {
+ page: block.title,
+ semantics: semantics.length ? readDecisions(semantics[0].body, `${where} #### Data semantics`, problems) : null,
+ lookups: lookups.length ? readLookups(lookups[0].body, `${where} #### Lookup metadata`, problems) : null,
+ });
+ }
+ crossCheck(read, read.requirements, problems);
+ return read;
+}
+
+// The approval preview's semantic records, the same shape as readWrittenSemantics, from its own level-three sections. Assumptions
+// is the preview's FIRST section — the maker reads what was assumed before the page list — and Data Semantics and Lookup Metadata
+// follow `### Pages`, grouped under `#### <page file>`.
+function readPreviewSemantics(preview) {
+ const lines = String(preview ?? '').replace(/\r\n?/g, '\n').split('\n');
+ const problems = [];
+ const read = { problems, assumptions: null, pages: new Map(), requirements: null };
+ const level3 = sectionsAt(lines, 3);
+ const named = (title) => level3.filter((section) => section.title.trim().toLowerCase() === title);
+ const [assumptions, semantics, lookups] = ['assumptions', 'data semantics', 'lookup metadata'].map(named);
+ const pagesAt = level3.findIndex((section) => /^pages\b/i.test(section.title.trim()));
+ if (assumptions.length > 1) problems.push(problem('invalid-assumptions', 'the preview has more than one ### Assumptions section'));
+ if (semantics.length > 1) problems.push(problem('invalid-data-semantics', 'the preview has more than one ### Data Semantics section'));
+ if (lookups.length > 1) problems.push(problem('invalid-lookup-metadata', 'the preview has more than one ### Lookup Metadata section'));
+ if (assumptions.length) {
+ if (level3[0] !== assumptions[0]) problems.push(problem('invalid-assumptions', 'the preview must present ### Assumptions first, before ### Pages'));
+ read.assumptions = readAssumptions(assumptions[0].body, 4, '### Assumptions', problems);
+ }
+ const page = (file) => {
+ if (!read.pages.has(file)) read.pages.set(file, { page: file, semantics: null, lookups: null });
+ return read.pages.get(file);
+ };
+ for (const [sections, key, title, code, reader] of [
+ [semantics, 'semantics', 'Data Semantics', 'invalid-data-semantics', readDecisions],
+ [lookups, 'lookups', 'Lookup Metadata', 'invalid-lookup-metadata', readLookups],
+ ]) {
+ if (!sections.length) continue;
+ const at = level3.indexOf(sections[0]);
+ if (pagesAt < 0 || at < pagesAt) problems.push(problem(code, `the preview's ### ${title} must follow its ### Pages table`));
+ const { lead, blocks } = blocksAt(sections[0].body, 4);
+ if (meaningful(lead).length) problems.push(problem(code, `### ${title} has text before its first "#### <page file>" group`));
+ if (!blocks.length) problems.push(problem(code, `### ${title} must group its records under "#### <page file>" headings`));
+ for (const block of blocks) {
+ const file = pageFileKey(block.title);
+ const where = `### ${title} #### ${block.title.trim()}`;
+ if (page(file)[key] !== null) { problems.push(problem(code, `### ${title} lists ${file} twice`)); continue; }
+ page(file)[key] = reader(block.body, where, problems);
+ }
+ }
+ const lookupsAt = lookups.length ? level3.indexOf(lookups[0]) : -1;
+ const semanticsAt = semantics.length ? level3.indexOf(semantics[0]) : -1;
+ if (lookupsAt >= 0 && semanticsAt > lookupsAt) problems.push(problem('invalid-lookup-metadata', 'the preview\'s ### Lookup Metadata must follow its ### Data Semantics'));
+ crossCheck(read, null, problems);
+ return read;
+}
+
+// Whether a read carries any part of the new contract. A document without any of it is an older plan: "not recorded".
+function hasSemanticContract(read) {
+ return read.assumptions !== null || [...read.pages.values()].some((page) => page.semantics !== null || page.lookups !== null);
+}
+
+// What a newly authored plan must also have (the `--require-assumptions` mode): the Assumptions section, and for every page file
+// named, its Data semantics and Lookup metadata (entries or the `None.` sentinel).
+function requiredContractProblems(read, files, label) {
+ const problems = [];
+ if (read.assumptions === null) problems.push(problem('invalid-assumptions', `${label} has no Assumptions section (write "${NO_ASSUMPTIONS}" when nothing was assumed)`));
+ for (const file of files) {
+ const page = read.pages.get(file);
+ if (!page || page.semantics === null) problems.push(problem('invalid-data-semantics', `${label}: ${file} has no Data semantics (write "${NONE}" when it has no relationship or filter)`));
+ if (!page || page.lookups === null) problems.push(problem('invalid-lookup-metadata', `${label}: ${file} has no Lookup metadata (write "${NONE}" when it uses no lookup)`));
+ }
+ return problems;
+}
+// The records a document approves, as plain data in a fixed order — what compareSemantics compares and semanticsHash hashes.
+function semanticRecord(read) {
+ const byNumber = (a, b) => Number(a.id.slice(1)) - Number(b.id.slice(1)) || a.id.localeCompare(b.id);
+ const assumptions = read.assumptions === null ? null : (read.assumptions.sentinel ? NO_ASSUMPTIONS
+ : [...read.assumptions.entries.values()].sort(byNumber).map((entry) => ({ ...entry })));
+ const pages = {};
+ for (const file of [...read.pages.keys()].sort()) {
+ const page = read.pages.get(file);
+ if (page.semantics === null && page.lookups === null) continue;
+ pages[file] = {
+ semantics: page.semantics === null ? null : (page.semantics.sentinel ? NONE : [...page.semantics.entries.values()].sort(byNumber).map((d) => ({ ...d }))),
+ lookups: page.lookups === null ? null : (page.lookups.sentinel ? NONE : {
+ rows: [...page.lookups.rows.values()].map((row) => ({ ...row, targets: [...row.targets].sort(), usedBy: [...row.usedBy].sort() }))
+ .sort((a, b) => `${a.table}|${a.column}`.localeCompare(`${b.table}|${b.column}`)),
+ paths: [...page.lookups.paths.values()].map((entry) => ({ ...entry }))
+ .sort((a, b) => `${a.table}|${a.column}|${a.target}`.localeCompare(`${b.table}|${b.column}|${b.target}`)),
+ strategy: page.lookups.strategy,
+ }),
+ };
+ }
+ return { assumptions, pages };
+}
+
+const ASSUMPTION_LABELS = { title: 'title', decision: 'Decision', alternatives: 'Alternatives considered', evidence: 'Evidence', resolution: 'Resolution', question: 'Question', answer: 'Answer', defaultRecord: 'Default record' };
+const DECISION_LABELS = { kind: 'Kind', definition: 'Definition', source: 'Source', quote: 'Requirement quote' };
+const same = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
+const describe = (value) => (value === null ? 'not recorded' : value === NO_ASSUMPTIONS || value === NONE ? `"${value}"` : 'recorded');
+
+// What the written plan changed from the approved preview, as sentences (empty when it changed nothing it may not). Every
+// assumption by id, every decision by page file and id, every lookup by table and column: an addition, an omission or a changed
+// field needs new approval even when the page files are the same. The one change allowed is the post-provision reconciliation
+// (references/plan-schema.md "Lookup metadata"): with `promotions` (successful lookup-metadata evidence, checked separately), a
+// lookup approved as `planned` may be written as `observed` and gain its measured paths — never another column, target set or use.
+function compareSemantics(approvedRead, writtenRead, { promotions = false } = {}) {
+ const approved = semanticRecord(approvedRead);
+ const written = semanticRecord(writtenRead);
+ const out = [];
+ if (!Array.isArray(approved.assumptions) || !Array.isArray(written.assumptions)) {
+ if (!same(approved.assumptions, written.assumptions)) out.push(`Assumptions: approved ${describe(approved.assumptions)}, written ${describe(written.assumptions)}`);
+ } else {
+ const before = new Map(approved.assumptions.map((entry) => [entry.id, entry]));
+ const after = new Map(written.assumptions.map((entry) => [entry.id, entry]));
+ for (const id of new Set([...before.keys(), ...after.keys()])) {
+ if (!after.has(id)) { out.push(`Assumptions: ${id} was approved but is not written`); continue; }
+ if (!before.has(id)) { out.push(`Assumptions: ${id} is written but was not approved`); continue; }
+ const changed = Object.keys(ASSUMPTION_LABELS).filter((field) => !same(before.get(id)[field], after.get(id)[field]));
+ if (changed.length) out.push(`Assumptions: ${id} changed its ${changed.map((field) => ASSUMPTION_LABELS[field]).join(', ')}`);
+ }
+ }
+ for (const file of new Set([...Object.keys(approved.pages), ...Object.keys(written.pages)])) {
+ const a = approved.pages[file] || { semantics: null, lookups: null };
+ const w = written.pages[file] || { semantics: null, lookups: null };
+ if (!Array.isArray(a.semantics) || !Array.isArray(w.semantics)) {
+ if (!same(a.semantics, w.semantics)) out.push(`${file} Data semantics: approved ${describe(a.semantics)}, written ${describe(w.semantics)}`);
+ } else {
+ const before = new Map(a.semantics.map((d) => [d.id, d]));
+ const after = new Map(w.semantics.map((d) => [d.id, d]));
+ for (const id of new Set([...before.keys(), ...after.keys()])) {
+ if (!after.has(id)) { out.push(`${file} Data semantics: ${id} was approved but is not written`); continue; }
+ if (!before.has(id)) { out.push(`${file} Data semantics: ${id} is written but was not approved`); continue; }
+ const changed = Object.keys(DECISION_LABELS).filter((field) => !same(before.get(id)[field], after.get(id)[field]));
+ if (changed.length) out.push(`${file} Data semantics: ${id} changed its ${changed.map((field) => DECISION_LABELS[field]).join(', ')}`);
+ }
+ }
+ if (a.lookups === null || w.lookups === null || a.lookups === NONE || w.lookups === NONE) {
+ if (!same(a.lookups, w.lookups)) out.push(`${file} Lookup metadata: approved ${describe(a.lookups)}, written ${describe(w.lookups)}`);
+ continue;
+ }
+ if (!same(a.lookups.strategy, w.lookups.strategy)) out.push(`${file} Lookup metadata: the Read target strategy changed`);
+ const before = new Map(a.lookups.rows.map((row) => [`${row.table}.${row.column}`, row]));
+ const after = new Map(w.lookups.rows.map((row) => [`${row.table}.${row.column}`, row]));
+ for (const key of new Set([...before.keys(), ...after.keys()])) {
+ if (!after.has(key)) { out.push(`${file} Lookup metadata: ${key} was approved but is not written`); continue; }
+ if (!before.has(key)) { out.push(`${file} Lookup metadata: ${key} is written but was not approved`); continue; }
+ const was = before.get(key);
+ const is = after.get(key);
+ const changed = [['readProperty', 'Read property'], ['targets', 'Targets'], ['usedBy', 'Used by']].filter(([field]) => !same(was[field], is[field]));
+ if (changed.length) out.push(`${file} Lookup metadata: ${key} changed its ${changed.map(([, label]) => label).join(', ')}`);
+ const promoted = was.state === 'planned' && is.state === 'observed';
+ if (was.state !== is.state && !(promoted && promotions)) {
+ out.push(`${file} Lookup metadata: ${key} was approved ${was.state} and is written ${is.state}${promoted ? ' without successful lookup metadata evidence' : ''}`);
+ }
+ const pathsOf = (record) => record.lookups.paths.filter((entry) => `${entry.table}.${entry.column}` === key);
+ if (!(promoted && promotions) && !same(pathsOf(a), pathsOf(w))) out.push(`${file} Lookup metadata: the paths of ${key} changed`);
+ }
+ }
+ return out;
+}
+
+// Checks every `observed` lookup of the written plan against the successful JSON answer of scripts/get-lookup-metadata.js:
+// { "ok": true, "tables": [ { "logicalName": "opportunity", "lookups": [ { "column": "customerid", "readProperty": "_customerid_value",
+// "targets": ["account", "contact"], "paths": [ { "target": "account", "navigationProperty": "customerid_account",
+// "referencedKey": "accountid" } ], "sharedPaths": [ … ] } ] } ] }
+// The column must be a lookup of that table with the same read property and the SAME COMPLETE target set, and every path the plan
+// records must be one of the concrete paths read (a shared path such as Owner's `ownerid` is not a target discriminator). A bare
+// `observed` claim with no such answer, a failed answer, or any mismatch is a problem: no network I/O happens here.
+function lookupEvidenceProblems(writtenRead, evidence) {
+ const fail = (message) => problem('invalid-lookup-metadata', message);
+ if (!evidence || typeof evidence !== 'object' || evidence.ok !== true || !Array.isArray(evidence.tables)) {
+ return [fail('the lookup metadata evidence is not a successful get-lookup-metadata.js answer ({ "ok": true, "tables": [...] })')];
+ }
+ const tables = new Map(evidence.tables.filter((table) => table && typeof table.logicalName === 'string').map((table) => [table.logicalName, table]));
+ const out = [];
+ for (const [file, page] of writtenRead.pages) {
+ if (!page.lookups || page.lookups.sentinel) continue;
+ for (const row of page.lookups.rows.values()) {
+ if (row.state !== 'observed') continue;
+ const label = `${file} ${row.table}.${row.column}`;
+ const table = tables.get(row.table);
+ const lookup = table && Array.isArray(table.lookups) ? table.lookups.find((entry) => entry && entry.column === row.column) : null;
+ if (!lookup) { out.push(fail(`${label}: the lookup metadata evidence has no such lookup`)); continue; }
+ if (lookup.readProperty !== row.readProperty) out.push(fail(`${label}: the evidence reads it as ${lookup.readProperty}, the plan as ${row.readProperty}`));
+ const read = Array.isArray(lookup.targets) ? [...lookup.targets].sort() : [];
+ if (!same(read, [...row.targets].sort())) out.push(fail(`${label}: the plan's targets (${row.targets.join(', ')}) are not the complete set read (${read.join(', ')})`));
+ for (const entry of page.lookups.paths.values()) {
+ if (entry.table !== row.table || entry.column !== row.column) continue;
+ const measured = (Array.isArray(lookup.paths) ? lookup.paths : []).find((candidate) => candidate && candidate.target === entry.target);
+ if (!measured || measured.navigationProperty !== entry.navigation || measured.referencedKey !== entry.key) {
+ out.push(fail(`${label} → ${entry.target}: the path ${entry.navigation} / ${entry.key} is not a concrete path the evidence read`));
+ }
+ }
+ }
+ }
+ return out;
+}
+
+// The written plan's semantic problems for the schema validator: what readWrittenSemantics found, and — when `require` is set
+// (a newly authored plan) — the parts a new plan must have for each of its pages.
+function writtenSemanticsProblems(plan, { require = false } = {}) {
+ const read = readWrittenSemantics(plan);
+ const problems = [...read.problems];
+ if (require) problems.push(...requiredContractProblems(read, [...read.pages.keys()], 'the plan'));
+ return problems;
+}
+
+module.exports = {
+ NO_ASSUMPTIONS,
+ NONE,
+ normalizeValue,
+ readWrittenSemantics,
+ readPreviewSemantics,
+ hasSemanticContract,
+ requiredContractProblems,
+ semanticRecord,
+ compareSemantics,
+ lookupEvidenceProblems,
+ writtenSemanticsProblems,
+};
diff --git a/plugins/model-apps/scripts/lib/genpage-sdk.js b/plugins/model-apps/scripts/lib/genpage-sdk.js
index bb685c10c..d3c7c837b 100644
--- a/plugins/model-apps/scripts/lib/genpage-sdk.js
+++ b/plugins/model-apps/scripts/lib/genpage-sdk.js
@@ -14,6 +14,8 @@
// genpage.runtimeTypes(dataSources, options) the RuntimeTypes text a page is authored against -> a string
// genpage.defaultViews(tables) the default public view of each table -> { views: [{ table, viewId }], warnings }
// genpage.baseLanguage() the environment's base language (an LCID)
+// genpage.solutionTarget(uniqueName) the solution a page is to join, read before the page is written -> { uniqueName, systemSolution, componentType? }
+// genpage.addToSolution(pageId, target) the page (and its file rows) into that solution -> { added }
// genpage.fileVersions(pageIds) the versionnumber of every file row of each page, from one plain read -> { ok, versions: Map<pageId, Map<fileRowId, version> | null>, error }
// genpage.projectVersions(pageIds) the versionnumber of each page's own row, from one plain read -> { ok, versions: Map<pageId, version | null>, error }
// genpage.publishedDiffers(pageId, args, expected) what a page's PUBLISHED copy differs from `args` (and its compiled output from `expected.runtimeSha256`) in, read back with plain reads -> { ok, differing: [field…], fingerprint, error }
@@ -45,6 +47,8 @@ const { sha256 } = require('./hash.js');
const { withCause } = require('./retry-policy.js');
const { makeThrottleBudget, waitDoesNotFit, spentNote } = require('./throttle-budget.js');
const { mergeBindings } = require('./page-bindings.js');
+const { isRestrictedSolution } = require('./system-solutions.js');
+const { readTargetSolution, readPageComponentType, pageComponent } = require('./page-solution.js');
const GUID_RE = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
@@ -99,6 +103,7 @@ const messageOf = (error) => String((error && error.message) || error);
// (`…(LogicalName='account')/Attributes/…`), from another path, or for a table nobody asked for (one a lookup column points at) is something else — a column read that raced a change, a proxy, a table the caller
// cannot see — and is left as the SDK's own error, as is any other status.
// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/query-metadata-web-api (a table's definition is read at EntityDefinitions(LogicalName='…'))
+// The lookup discovery (lib/lookup-metadata.js) tells a missing table with it too: GENPAGE_TABLE_NOT_FOUND here, LOOKUP_TABLE_NOT_FOUND there.
function missingTableOf(error, askedFor) {
if (!error || error.statusCode !== 404 || typeof error.url !== 'string') return null;
const named = /\/EntityDefinitions\(LogicalName='([A-Za-z0-9_]+)'\)(?:\?|$)/.exec(error.url);
@@ -1613,6 +1618,32 @@ function makeGenpageSdk(env, deps = {}) {
return (await (await getSdk()).getEnvironmentLanguages()).baseLanguage;
},
+ // The solution a page is to join (`genpage-upload.js --solution`), read BEFORE the page is written, so a name that is no unmanaged solution — or a page table whose
+ // component type the environment cannot say — refuses the upload with nothing made (lib/page-solution.js: why a page is added explicitly, and how).
+ // -> { uniqueName, systemSolution: true } a system solution (Default, Active, Basic): it holds every component already, so nothing is read and nothing will be added
+ // -> { uniqueName, systemSolution: false, componentType } the unmanaged solution, as the platform spells its name, and the page table's component type
+ // It throws, with a code: SOLUTION_NOT_FOUND, SOLUTION_MANAGED, GENPAGE_COMPONENT_TYPE_UNRESOLVED, or the SDK's own for a read that failed.
+ async solutionTarget(uniqueName) {
+ const name = String(uniqueName === undefined || uniqueName === null ? '' : uniqueName).trim();
+ if (!name) throw genpageError('a solution is named by its unique name, and none was given', { code: 'SOLUTION_NOT_FOUND', outcome: 'nothing' });
+ if (isRestrictedSolution(name)) return { uniqueName: name, systemSolution: true };
+ const sdk = await getSdk();
+ const solution = await readTargetSolution(sdk, name);
+ return { uniqueName: solution.uniqueName, systemSolution: false, componentType: await readPageComponentType(sdk.dataverse) };
+ },
+
+ // Adds the page to the solution `target` names (solutionTarget's answer): the page's own row, and with it its file rows (AddRequiredComponents). A system solution
+ // is not added to. A component the solution holds already is accepted by the platform, so adding a page twice changes nothing. -> { added: true | false }
+ async addToSolution(pageId, target) {
+ const id = guidOf(pageId, 'page');
+ if (!target || target.systemSolution) return { added: false };
+ if (!Number.isInteger(target.componentType) || target.componentType <= 0) {
+ throw genpageError(`page ${id} cannot be added to solution ${target.uniqueName}: the page table's component type is not known`, { code: 'GENPAGE_COMPONENT_TYPE_UNRESOLVED', outcome: 'nothing', pageId: id });
+ }
+ await (await getSdk()).addSolutionComponent(pageComponent(id, target.componentType, target.uniqueName));
+ return { added: true };
+ },
+
// The versionnumber of EVERY file row of each page — what the build's publish record compares (lib/page-publish-records.js has the measured facts and why this read is the plain one). A page is a
// `uxagentprojects` row and its `uxagentprojectfiles` rows; one plain query per PAGE_VERSION_CHUNK pages, followed to its last page:
// GET /uxagentprojectfiles?$select=uxagentprojectfileid,versionnumber,_uxagentprojectid_value&$filter=_uxagentprojectid_value eq <id> or _uxagentprojectid_value eq <id>
@@ -1808,7 +1839,7 @@ function makeGenpageSdk(env, deps = {}) {
// The operations are counted while they run: what release() waits for on an SDK it does not own. A closed backend refuses them in getSdk,
// which the two listings reach inside their own try — a listing never rejects (a listing that cannot be read is `{ ok: false, error }`, and a
// caller decides between creating a page and reusing one on that), so on a closed backend it answers exactly that.
- for (const name of ['enumerateEnv', 'enumeratePages', 'read', 'create', 'update', 'placeInApp', 'removeFromApp', 'describe', 'delete', 'runtimeTypes', 'defaultViews', 'baseLanguage', 'fileVersions', 'projectVersions', 'publishedDiffers']) {
+ for (const name of ['enumerateEnv', 'enumeratePages', 'read', 'create', 'update', 'placeInApp', 'removeFromApp', 'describe', 'delete', 'runtimeTypes', 'defaultViews', 'baseLanguage', 'solutionTarget', 'addToSolution', 'fileVersions', 'projectVersions', 'publishedDiffers']) {
const operation = api[name];
api[name] = (...args) => {
const run = operation(...args);
@@ -1902,4 +1933,5 @@ async function appsNaming(sdk, pageId) {
module.exports = {
makeGenpageSdk, unescapePacName, suppliedButBlank, sourceText, dataSourcesOf, promptTranscript, configJson, pageFolderFiles,
genPagesOfSiteMap, entityTablesOfSiteMap, writeOutcome, PRE_WRITE_REFUSALS, genpageError, holdsWhatWasSent, describeDivergence, contentFingerprint, watchThrottles, GUID_RE,
+ missingTableOf,
};
diff --git a/plugins/model-apps/scripts/lib/hydrate-spec.js b/plugins/model-apps/scripts/lib/hydrate-spec.js
index 630f019e6..86cdcdb4f 100644
--- a/plugins/model-apps/scripts/lib/hydrate-spec.js
+++ b/plugins/model-apps/scripts/lib/hydrate-spec.js
@@ -90,7 +90,7 @@ function withDescription(obj, rawDescription) {
function sanitizeDescriptionInventory(inv) {
if (!inv || typeof inv !== 'object' || Array.isArray(inv)) return undefined;
const out = {};
- for (const key of ['views', 'charts', 'forms', 'businessRules', 'globalChoices']) {
+ for (const key of ['views', 'charts', 'forms', 'businessRules', 'globalChoices', 'commands']) {
if (!Array.isArray(inv[key])) continue;
out[key] = inv[key].map((item) => {
const { Description, description, ...rest } = item || {};
@@ -246,8 +246,9 @@ async function hydrateSpec(read) {
//
// All four survive on the live app — a rebuild into the SAME environment preserves them — but are
// absent from the downloaded spec, so edit them in Maker or a fresh spec. This is no longer
- // silent: every deployed form/view/chart is listed in `descriptionInventory` below, and
- // `download-model-app` reports the omission by class and table on every run (AB#6686423).
+ // silent: every deployed form/view/chart, and every command-bar customisation of the app's tables,
+ // is listed in `descriptionInventory` below, and `download-model-app` reports the omission by class
+ // and table on every run (AB#6686423).
charts: [],
forms: [],
commands: [],
diff --git a/plugins/model-apps/scripts/lib/lookup-metadata.js b/plugins/model-apps/scripts/lib/lookup-metadata.js
new file mode 100644
index 000000000..6f2ba7213
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/lookup-metadata.js
@@ -0,0 +1,157 @@
+'use strict';
+// Lookup discovery for the genpage planner (scripts/get-lookup-metadata.js): for each table a page reads, its lookup columns with
+// their COMPLETE target sets and the concrete paths a page can filter a target through. It composes two existing readers and owns
+// no HTTP of its own:
+// - the SDK's fetchEntityMetadata(table) — the source of each lookup's identity and complete `targets` (the SDK reads them from
+// the table's LookupAttributeMetadata cast), the table's primary id and name columns, and nothing guessed from a name;
+// - lib/relationship-metadata.js readRelationshipsOf(…, 'ManyToOne', cache, { lookupDetails: true }) — every page of the
+// table's ManyToOne relationships with the target key and the navigation property, which the SDK's projection drops. When the
+// SDK projects ReferencingAttribute and ReferencingEntityNavigationPropertyName on its relationship rows, that read can go.
+//
+// A path is CONCRETE — a target discriminator a page may filter through (`customerid_account/accountid eq <id>`) — only when one
+// relationship of the lookup column reaches that target and its navigation property belongs to no other target. Anything else is
+// a SHARED path, listed separately and never used to pick a target: Owner's `ownerid` (one navigation property, a relationship to
+// the abstract `owner` table, which is in no lookup's targets), a navigation property two targets share, or a target reached twice.
+// Nothing here manufactures a path (`ownerid_team`, `ownerid_systemuser`) or splits a navigation name on `_` to find a table.
+//
+// Every failure is a failure of the whole read — a missing table, a lookup without targets, an attribute inventory that cannot be
+// complete (no primary id column, or a relationship column it does not list or does not classify), a refused or malformed
+// relationship page — so a caller never receives a shorter candidate list as if it were complete.
+
+const { readRelationshipsOf } = require('./relationship-metadata.js');
+const { missingTableOf } = require('./genpage-sdk.js');
+
+// The attribute types that are lookups (AttributeTypeCode names, as the SDK projects them).
+// https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/attributetypecode
+const LOOKUP_TYPES = new Set(['Lookup', 'Customer', 'Owner']);
+// Every AttributeTypeCode name a metadata read can state (same page). The SDK projects a missing raw AttributeType as 'Unknown',
+// which is none of them, so a column it names must not be read as "not a lookup".
+const ATTRIBUTE_TYPES = new Set(['BigInt', 'Boolean', 'CalendarRules', 'Customer', 'DateTime', 'Decimal', 'Double', 'EntityName',
+ 'Integer', 'Lookup', 'ManagedProperty', 'Memo', 'Money', 'Owner', 'PartyList', 'Picklist', 'State', 'Status', 'String',
+ 'Uniqueidentifier', 'Virtual']);
+// The types whose metadata is a LookupAttributeMetadata and so may carry Targets: the three lookups, and a party list (not a
+// lookup this reader lists). Targets on any other type contradict its classification.
+const TARGET_TYPES = new Set([...LOOKUP_TYPES, 'PartyList']);
+const LOGICAL_NAME = /^[a-z_][a-z0-9_]*$/;
+
+function lookupError(code, message) {
+ const error = new Error(message);
+ error.code = code;
+ return error;
+}
+
+/**
+ * A table's lookups from its SDK metadata and its lookup-details relationship rows.
+ * @param {object} metadata - fetchEntityMetadata's answer: { logicalName, primaryIdAttribute, primaryNameAttribute, attributes: [{ logicalName, attributeType, targets? }] }
+ * @param {object[]} rows - readRelationshipsOf lookup-details rows: { schemaName, referencedEntity, referencingAttribute, referencedAttribute, navigationProperty }
+ */
+function tableLookups(metadata, rows) {
+ const table = String(metadata.logicalName || '').toLowerCase();
+ const attributes = Array.isArray(metadata.attributes) ? metadata.attributes : [];
+ // The SDK cannot say its attribute inventory is complete: it maps an absent `Attributes` expansion to [] and a missing
+ // PrimaryIdAttribute to '', and it does not follow an `[email protected]` continuation. So completeness is
+ // established here from what must be in it — the table's primary id column, and the referencing column of every
+ // ManyToOne relationship the separately paged relationship read returned (every lookup has one) — and a gap fails
+ // the whole read rather than becoming a shorter list a planner reads as "no lookup".
+ const inventory = new Set(attributes.filter(Boolean).map((attribute) => String(attribute.logicalName || '').toLowerCase()));
+ const primaryId = String(metadata.primaryIdAttribute || '').toLowerCase();
+ if (!LOGICAL_NAME.test(primaryId) || !inventory.has(primaryId)) {
+ throw lookupError('LOOKUP_METADATA_INCOMPLETE', `${table}: the metadata read did not state the table's primary id column among its attributes`);
+ }
+ // A relationship column is classified, too: an unknown or malformed type (the SDK's 'Unknown' for a missing AttributeType),
+ // or Targets on a type that cannot carry them, is an incomplete answer — never a column silently left out as "not a lookup".
+ // A known non-lookup type without Targets is kept out of the lookups as before.
+ const byColumn = new Map(attributes.filter(Boolean).map((attribute) => [String(attribute.logicalName || '').toLowerCase(), attribute]));
+ for (const row of rows) {
+ const column = String(row.referencingAttribute || '').toLowerCase();
+ if (!inventory.has(column)) {
+ throw lookupError('LOOKUP_METADATA_INCOMPLETE', `${table}: relationship ${row.schemaName || '?'} references ${column || '?'}, which the attribute inventory does not list — an incomplete attribute read`);
+ }
+ const attribute = byColumn.get(column);
+ const type = attribute.attributeType;
+ if (typeof type !== 'string' || !ATTRIBUTE_TYPES.has(type)) {
+ throw lookupError('LOOKUP_METADATA_INCOMPLETE', `${table}.${column}: relationship ${row.schemaName || '?'} references it, but the metadata read did not classify it (attribute type ${JSON.stringify(type ?? null)})`);
+ }
+ if (!TARGET_TYPES.has(type) && Array.isArray(attribute.targets) && attribute.targets.length) {
+ throw lookupError('LOOKUP_METADATA_INCOMPLETE', `${table}.${column}: the metadata read classifies it as ${type}, yet states lookup targets for it`);
+ }
+ }
+ const lookups = [];
+ for (const attribute of attributes) {
+ if (!attribute || !LOOKUP_TYPES.has(attribute.attributeType)) continue;
+ const column = String(attribute.logicalName || '').toLowerCase();
+ const targets = Array.isArray(attribute.targets) ? attribute.targets.map((target) => String(target).toLowerCase()) : [];
+ // The SDK fills `targets` from a separate cast read and leaves them out when that read fails, so a lookup without them is an
+ // incomplete answer, never a lookup with no targets.
+ if (!LOGICAL_NAME.test(column) || !targets.length || targets.some((target) => !LOGICAL_NAME.test(target))) {
+ throw lookupError('LOOKUP_METADATA_INCOMPLETE', `${table}.${column || '?'}: the metadata read did not state the lookup's targets`);
+ }
+ const own = rows.filter((row) => String(row.referencingAttribute || '').toLowerCase() === column);
+ const byNavigation = new Map();
+ for (const row of own) byNavigation.set(row.navigationProperty, (byNavigation.get(row.navigationProperty) || 0) + 1);
+ const paths = [];
+ const sharedPaths = [];
+ for (const row of own) {
+ const target = String(row.referencedEntity || '').toLowerCase();
+ const entry = { navigationProperty: row.navigationProperty, referencedKey: String(row.referencedAttribute || '').toLowerCase(), relationship: row.schemaName };
+ const concrete = targets.includes(target)
+ && own.filter((other) => String(other.referencedEntity || '').toLowerCase() === target).length === 1
+ && byNavigation.get(row.navigationProperty) === 1;
+ if (concrete) paths.push({ target, ...entry });
+ else sharedPaths.push({ referencedEntity: target, ...entry });
+ }
+ const byText = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
+ paths.sort((a, b) => byText(a.target, b.target));
+ sharedPaths.sort((a, b) => byText(a.navigationProperty, b.navigationProperty) || byText(a.referencedEntity, b.referencedEntity));
+ lookups.push({ column, readProperty: `_${column}_value`, attributeType: attribute.attributeType, targets, paths, sharedPaths });
+ }
+ lookups.sort((a, b) => (a.column < b.column ? -1 : a.column > b.column ? 1 : 0));
+ return {
+ logicalName: table,
+ primaryIdAttribute: primaryId,
+ primaryNameAttribute: metadata.primaryNameAttribute || '',
+ lookups,
+ };
+}
+
+/**
+ * Reads the lookups of `tables` through an SDK instance (its fetchEntityMetadata, and its `dataverse` client for the relationship read).
+ * @param {object} sdk - a maker SDK instance
+ * @param {string[]} tables - table logical names
+ * @returns {Promise<{ ok: true, tables: object[] }>} - throws an Error with a `code` on any failure
+ */
+async function readLookupMetadata(sdk, tables) {
+ if (!Array.isArray(tables) || !tables.length) throw lookupError('LOOKUP_TABLES_REQUIRED', 'name at least one table');
+ const cache = new Map();
+ const out = [];
+ for (const name of tables) {
+ const table = String(name).toLowerCase();
+ if (!LOGICAL_NAME.test(table)) throw lookupError('LOOKUP_TABLE_NAME_INVALID', `'${name}' is not a table logical name`);
+ let metadata;
+ try {
+ metadata = await sdk.fetchEntityMetadata(table);
+ } catch (err) {
+ // The SDK's own read of the table is the first request made for it, so a table the environment does not have fails THERE, before the
+ // relationship read below could say so. Dataverse answers that read (measured live)
+ // GET …/api/data/v9.0/EntityDefinitions(LogicalName='opportunity')?$select=…&$expand=Attributes(…)
+ // 404 {"error":{"code":"0x80060888","message":"EntityMetadata With Id = LogicalName='opportunity' does not exist."}}
+ // and the SDK throws that as its ConnectionError — code CONNECTION_ERROR, which points a planner at sign-in, not at the table's name.
+ // Only a 404 of that read, for this table, is the table's absence (missingTableOf reads the error's statusCode and url, never the
+ // platform's words, as `genpage.js types` does); any other failure — another status, a request below the table, a transport failure
+ // or a missing token (the SDK's statusCode 0) — keeps the SDK's own code.
+ if (missingTableOf(err, [table]) === null) throw err;
+ throw lookupError('LOOKUP_TABLE_NOT_FOUND', `${table}: the environment has no table with this logical name — ${err.message}`);
+ }
+ if (!metadata || String(metadata.logicalName || '').toLowerCase() !== table || !Array.isArray(metadata.attributes)) {
+ throw lookupError('LOOKUP_METADATA_INCOMPLETE', `${table}: the metadata read did not answer for this table`);
+ }
+ const relationships = await readRelationshipsOf(sdk.dataverse, table, 'ManyToOne', cache, { lookupDetails: true });
+ if (!relationships.ok) {
+ throw lookupError(relationships.tableMissing ? 'LOOKUP_TABLE_NOT_FOUND' : 'LOOKUP_RELATIONSHIPS_UNREADABLE', `${table}: ${relationships.error}`);
+ }
+ out.push(tableLookups(metadata, relationships.rows));
+ }
+ return { ok: true, tables: out };
+}
+
+module.exports = { readLookupMetadata, tableLookups, LOOKUP_TYPES };
diff --git a/plugins/model-apps/scripts/lib/page-binding-targets.js b/plugins/model-apps/scripts/lib/page-binding-targets.js
index e8a3f8cc6..20e7dfa66 100644
--- a/plugins/model-apps/scripts/lib/page-binding-targets.js
+++ b/plugins/model-apps/scripts/lib/page-binding-targets.js
@@ -16,9 +16,17 @@
// there can be another version than the page was made with: that one is read, and an operation it does not define is a warning — the call fails, it does not reach another service.
// A read that fails is said — the bindings were not checked — and never read as "nothing is there"; a row that answers without a column the check needs (successful but incomplete) is said the same way, as
// not checked, and never read as "compatible". Nothing is refused without evidence that contradicts the binding.
+//
+// BUILT-IN OPERATIONS. Two `actionBindings` names are not Custom APIs at all: WhoAmI and RetrieveVersion, the reviewed built-in Dataverse operations (lib/dataverse-operations.js). They are
+// messages the platform defines, not rows of `customapi`, so reading `customapi` for them could only answer "not there" and send the author to deploy what cannot be deployed. A binding whose name
+// is EXACTLY one of them leaves the Custom API read — before the names are folded in case and cut into requests, so `whoami` beside `WhoAmI` is still read under its own spelling — and nothing is
+// read in its place: whether the environment or its page player offers the operation, and whether the signed-in user may call it, is said as NOT CHECKED, never as "compatible". A binding of that
+// name whose own declarations do not explicitly say "an unbound Function with no inputs" is a warning, and it is written as the spec states it: never repaired, and never refused. Any other
+// spelling (`whoami`, `Microsoft.Dynamics.CRM.WhoAmI`) and any other operation is a Custom API name, read and judged as one.
const { odataLit } = require('./odata.js');
const { normalizePageSource } = require('./app-spec.js');
const { PAGE_BINDINGS, statedPageBindings } = require('./page-bindings.js');
+const { getReviewedDataverseOperation } = require('./dataverse-operations.js');
// A filter is bounded: the names of a long list are read in requests of this many, not in one URL.
const CHUNK = 25;
@@ -93,11 +101,14 @@ function pagesLeftOutAsDeployed(spec, changedOnly) {
}
// The names the pages state for one kind of binding: each once, as the first page spells it (the service compares them without regard to case, and the match here is made in lower case).
+// A built-in operation's binding names no `customapi` row (see the header), so it is left out of the Custom API names — first, before the folding: WhoAmI and whoami would otherwise fold to one
+// name, and the one read would be WhoAmI's, leaving whoami unread.
function namesOf(pages, kind) {
const identity = PAGE_BINDINGS[kind];
const names = new Map();
for (const page of pages) {
for (const entry of page[kind] || []) {
+ if (kind === 'actionBindings' && isBuiltInOperation(entry)) continue;
const name = entry && typeof entry[identity] === 'string' ? entry[identity].trim() : '';
if (name && !names.has(name.toLowerCase())) names.set(name.toLowerCase(), name);
}
@@ -105,6 +116,9 @@ function namesOf(pages, kind) {
return [...names.values()];
}
+// Whether an `actionBindings` entry names a reviewed built-in operation — by its EXACT name, as the catalogue matches it: `whoami` is a Custom API name.
+const isBuiltInOperation = (entry) => Boolean(entry && typeof entry === 'object' && getReviewedDataverseOperation(entry[PAGE_BINDINGS.actionBindings]));
+
async function readNamed(provision, entity, select, column, names) {
const rows = [];
for (let at = 0; at < names.length; at += CHUNK) {
@@ -194,7 +208,8 @@ function bindingReads() {
// customConnectorId the lower-cased GUID in `_customconnectorid_value`; absent, null or not a GUID leaves it out. A null lookup is NOT proof that the connector is not a custom one — a reference
// made through the Web API can leave it unset — so the operations through such a reference are reported as not checked, not as defined
// SUCCESSFUL BUT INCOMPLETE: a read that answers 200 with a row that lacks a column is as much "not known" as a read that fails. Nothing here infers compatibility from a value that is not there.
-// apis Map<lower-cased unique name, { isFunction, boundEntity? }> of the Custom APIs (`customapi` rows) — or null likewise
+// apis Map<lower-cased unique name, { isFunction, boundEntity? }> of the Custom APIs (`customapi` rows) — or null likewise, and null when every action binding names a built-in operation,
+// which is not read (see the header)
// definitions Map<custom connector id, Set<operation id> | { problem }> (readDefinitions) of the custom connectors a binding that calls operations goes through — or null when there is none
// problems { references?, apis? }: why a read failed, as the service said it. A failed read does not stop the other, and is never an empty answer.
// unread { references?, apis? }: Map<lower-cased name, why> — present only beside answered names, which only an attempt's LATER check meets (below): the names an earlier read of the attempt could not
@@ -284,12 +299,42 @@ const joined = (names) => names.map(shown).join(', ');
const plural = (names, one, many) => (names.length === 1 ? one : many);
const pagesWords = (pages) => `${plural(pages, 'page', 'pages')} ${pages.map((page) => quoted(page.name)).join(', ')}`;
+// What is said of every built-in operation a page binds, after its name: nothing in the environment was read for it (see the header).
+const BUILT_IN_UNCHECKED = 'These are reviewed built-in operation names; their availability in this environment or player and the signed-in user\'s permissions were not checked.';
+// What is said of one whose declarations do not explicitly match the reviewed contract. It promises no runtime answer: whatever the player does with such a binding is the player's.
+const BUILT_IN_SHAPE = 'This binding does not explicitly match the reviewed unbound, zero-input Function contract. It was preserved; invocation may fail.';
+
+// How a built-in operation's binding departs from "an unbound Function with no inputs", or null when it states exactly that. The binding is a spec's, held to the shapes a spec states
+// (lib/page-bindings.js): `isFunction` a boolean, `boundEntityLogicalName` an identifier, `parameterKinds` a map of primitive kinds — or absent. An ABSENT declaration is what a binding written
+// before the declarations were required looks like (`{ "name": "WhoAmI" }`), and it is said apart from a declaration that CONTRADICTS the contract — an Action, a bound table, inputs.
+// { declaration: 'omitted' | 'contradicted', words } e.g. words: "declares inputs (Target, Depth)"
+function builtInShape(entry) {
+ const contradicted = [];
+ const omitted = [];
+ if (entry.isFunction === undefined) omitted.push(['its kind', 'isFunction']);
+ else if (entry.isFunction === false) contradicted.push('an Action (isFunction: false)');
+ else if (entry.isFunction !== true) contradicted.push('a kind that is not a Function');
+ if (text(entry.boundEntityLogicalName)) contradicted.push(`a bound table (${shown(entry.boundEntityLogicalName)})`);
+ const kinds = entry.parameterKinds;
+ if (kinds === undefined) omitted.push(['its inputs', 'parameterKinds']);
+ else if (!kinds || typeof kinds !== 'object' || Array.isArray(kinds)) contradicted.push('inputs');
+ else if (Object.keys(kinds).length) contradicted.push(`inputs (${joined(Object.keys(kinds))})`);
+ if (!contradicted.length && !omitted.length) return null;
+ const and = (parts) => (parts.length < 3 ? parts.join(' and ') : `${parts.slice(0, -1).join(', ')} and ${parts.at(-1)}`);
+ const said = [];
+ if (contradicted.length) said.push(`declares ${and(contradicted)}`);
+ if (omitted.length) said.push(`does not declare ${omitted.map(([what]) => what).join(' or ')} (${omitted.map(([, key]) => key).join(', ')})`);
+ return { declaration: contradicted.length ? 'contradicted' : 'omitted', words: said.join(', and ') };
+}
+
// What `targets` says of the bindings `pages` state: { findings, unchecked }.
// findings [{ severity: 'refuse' | 'warn', kind, page: { key, name }, text, … }], a page at a time, in the order a page lists its bindings: its connector conflicts, the references it has none of, the references it
-// has with no connection, the operations a custom connector there does not define, the Custom APIs it has none of, the Custom APIs that are not as the binding says. `refuse` is a connector conflict
-// and nothing else: a binding that is refused is not judged further.
+// has with no connection, the operations a custom connector there does not define, the Custom APIs it has none of, the Custom APIs that are not as the binding says, and the built-in
+// operations whose declarations do not explicitly match their contract (`dataverse-operation-shape`, with `binding` and `declaration`: 'omitted' or 'contradicted'). `refuse` is a connector
+// conflict and nothing else: a binding that is refused is not judged further.
// unchecked [{ what, text }] for what could not be checked, and why: a page at a time, what its references' rows did not say (their connector, whether they have a connection, which custom connector they
-// are for), then the operations of a binding whose custom connector's definition could not be read, and the names of its bindings an earlier read of the attempt could not read (`unread`);
+// are for), then the operations of a binding whose custom connector's definition could not be read, and the names of its bindings an earlier read of the attempt could not read (`unread`),
+// then the built-in operations it binds ({ what: 'Dataverse operations', page, names, text }: nothing is read for them);
// then each read that failed. Missing evidence is never a finding and never "compatible".
function judgeBindingTargets(pages, targets) {
const findings = [];
@@ -306,7 +351,10 @@ function judgeBindingTargets(pages, targets) {
for (const page of pages) {
const at = { key: page.key, name: page.name };
const connectors = (page.connectorBindings || []).filter((entry) => nameOf(entry, PAGE_BINDINGS.connectorBindings));
- const actions = (page.actionBindings || []).filter((entry) => nameOf(entry, PAGE_BINDINGS.actionBindings));
+ const named = (page.actionBindings || []).filter((entry) => nameOf(entry, PAGE_BINDINGS.actionBindings));
+ // A built-in operation's binding is judged apart: no row was read for it (readBindingTargets), so it is never "missing" and never compared with one.
+ const builtIns = named.filter(isBuiltInOperation);
+ const actions = named.filter((entry) => !isBuiltInOperation(entry));
const missingReferences = [];
const disconnected = [];
const undefinedOperations = [];
@@ -425,10 +473,25 @@ function judgeBindingTargets(pages, targets) {
}
for (const mismatch of mismatches) findings.push({ severity: 'warn', kind: 'api-mismatch', page: at, binding: mismatch.binding, text: mismatch.text });
for (const [why, names] of apisUnread) unchecked.push({ what: 'Custom APIs', text: `could not read this environment's Custom APIs (${shown(why)}), so ${plural(names, 'Custom API binding', 'Custom API bindings')} ${names.map(quoted).join(', ')} of page ${quoted(page.name)} ${plural(names, 'was', 'were')} not checked against them` });
+ if (builtIns.length) {
+ for (const entry of builtIns) {
+ const shape = builtInShape(entry);
+ if (shape) {
+ findings.push({
+ severity: 'warn', kind: 'dataverse-operation-shape', page: at, binding: entry.name, declaration: shape.declaration,
+ text: `page ${quoted(page.name)}: built-in operation binding ${quoted(entry.name)} ${shape.words}. ${BUILT_IN_SHAPE}`,
+ });
+ }
+ }
+ const names = [...new Set(builtIns.map((entry) => entry.name))];
+ unchecked.push({ what: 'Dataverse operations', page: at, names, text: `page ${quoted(page.name)} binds the built-in ${plural(names, 'operation', 'operations')} ${joined(names)}. ${BUILT_IN_UNCHECKED}` });
+ }
}
const unread = (what, kind, problem, listed) => {
if (!problem) return;
- const affected = pages.filter((page) => (page[kind] || []).some((entry) => nameOf(entry, PAGE_BINDINGS[kind])));
+ // A page whose action bindings are all built-in operations had nothing in the Custom API read, so a failed read is not said of it.
+ const read = (entry) => nameOf(entry, PAGE_BINDINGS[kind]) && !(kind === 'actionBindings' && isBuiltInOperation(entry));
+ const affected = pages.filter((page) => (page[kind] || []).some(read));
if (affected.length) unchecked.push({ what, text: `could not read this environment's ${what} (${shown(problem)}), so the ${listed} of ${pagesWords(affected)} were not checked against them` });
};
unread('connection references', 'connectorBindings', targets.problems && targets.problems.references, 'connector bindings');
diff --git a/plugins/model-apps/scripts/lib/page-plan.js b/plugins/model-apps/scripts/lib/page-plan.js
index d213b02ec..48a380cc0 100644
--- a/plugins/model-apps/scripts/lib/page-plan.js
+++ b/plugins/model-apps/scripts/lib/page-plan.js
@@ -166,9 +166,11 @@ function navTargets(p) {
// Project the App Spec's `design` contract into the plan's `## Design Preferences` section.
//
// The canonical field set is fixed and validated (app-spec.js rejects unknown keys):
-// `accentColor`, `density`, `cornerRadius`, `darkMode`, `layout`. These are the tokens the user
+// `accentColor`, `density`, `cornerRadius`, `darkMode`, `layout`, `style`. The first five are tokens the user
// approved during authoring, so every generated page must apply them — a page that ignores them is
-// visually inconsistent with the rest of the app and with the model-driven shell.
+// visually inconsistent with the rest of the app and with the model-driven shell. `style` is the maker's own
+// look in words (AB#6320143): it leads the line as `Maker-requested:`, which the page-builder applies instead of
+// the default model-driven look (references/rules.md, "Maker-requested styling"); without it the pages keep that look.
// Values are sanitised because `design` is author-supplied (and download-derived on an edit).
function designPreferences(design) {
const d = design && typeof design === 'object' ? design : {};
@@ -180,13 +182,16 @@ function designPreferences(design) {
]
.filter(([, v]) => v != null && String(v).trim())
.map(([label, v]) => `${label}: ${mdText(v)}`);
+ const style = typeof d.style === 'string' ? mdText(d.style) : '';
return {
// Always name Fluent UI V9 — it is the required component library, not a preference — then
// append the approved tokens so the worker has a single authoritative styling line.
- styling: tokens.length
- ? `Fluent UI V9 tokens — ${tokens.join('; ')}`
- : 'Fluent UI V9 defaults; clean, content-first layout',
+ styling: style
+ ? `Maker-requested: ${style}${tokens.length ? ` (Fluent UI V9 components; also ${tokens.join('; ')})` : ' (Fluent UI V9 components)'}`
+ : tokens.length
+ ? `Fluent UI V9 tokens — ${tokens.join('; ')}`
+ : 'Fluent UI V9 defaults; clean, content-first layout',
layout: d.layout ? `${mdText(d.layout)} layout, responsive` : null,
features: 'Search, sorting and filtering where the page lists records',
accessibility: 'WCAG AA (ARIA labels, keyboard navigation, semantic HTML)',
diff --git a/plugins/model-apps/scripts/lib/page-solution.js b/plugins/model-apps/scripts/lib/page-solution.js
new file mode 100644
index 000000000..e0b1faa79
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/page-solution.js
@@ -0,0 +1,91 @@
+'use strict';
+// A generative page in a solution: the one definition of how a page joins one, shared by every path that makes pages —
+// add-page-to-solution.js (an app and its pages, packaged), apps.js create (an app made around its pages), genpage-upload.js
+// --solution (through the page backend, lib/genpage-sdk.js) and the build's pages phase (lib/sdk-build.js).
+//
+// A page is a `uxagentproject` row, and a solution holds it as a component of that table. It is a custom table, so its component
+// type is the table's ObjectTypeCode, which Dataverse allocates per environment: it is read, never written down as a constant.
+// GET EntityDefinitions(LogicalName='uxagentproject')?$select=ObjectTypeCode
+// { "@odata.context": "…/$metadata#EntityDefinitions(ObjectTypeCode)/$entity", "ObjectTypeCode": 10372, "MetadataId": "…" }
+// A page is added with AddRequiredComponents=true: measured live (add-page-to-solution.js), that brings its uxagentprojectfile rows —
+// config.json with the page's bindings among them — so the page travels whole. Nothing else brings a page into a solution: the add of
+// an app brings its sitemap and its app components, never the pages its navigation opens, and a page made by the SDK carries no
+// solution of its own. So a run that was given a solution and made a page left that page out of it unless it added the page
+// explicitly (AB#6443257). A system solution (Default, Active, Basic: lib/system-solutions.js) holds every component already, so no
+// caller adds to one.
+// See: https://learn.microsoft.com/power-apps/developer/data-platform/webapi/reference/addsolutioncomponent
+// See: https://learn.microsoft.com/power-apps/developer/data-platform/reference/entities/solutioncomponent
+const { odataLit } = require('./odata.js');
+
+const UXAGENTPROJECT_LOGICAL_NAME = 'uxagentproject';
+// AddRequiredComponents for a page: true, so its file rows come with it (above).
+const PAGE_ADD_REQUIRED_COMPONENTS = true;
+
+// The metadata read that answers a table's component type, below the API root (no leading slash: `dataverseRequest` takes it so).
+function componentTypePath(logicalName) {
+ return `EntityDefinitions(LogicalName='${odataLit(logicalName)}')?$select=ObjectTypeCode`;
+}
+
+// The ObjectTypeCode of a metadata answer: a positive whole number, or an error — a type that is not one would add the page as some
+// other component, or as nothing at all.
+function componentTypeOf(body, logicalName) {
+ const componentType = Number(body && body.ObjectTypeCode);
+ if (!Number.isInteger(componentType) || componentType <= 0) {
+ throw Object.assign(new Error(`Entity '${logicalName}' did not return a valid ObjectTypeCode`), { code: 'GENPAGE_COMPONENT_TYPE_UNRESOLVED' });
+ }
+ return componentType;
+}
+
+// A generative page's component type, read through the SDK's own Dataverse client (`sdk.dataverse`). Its `get` answers
+// `{ status, headers, body }` and does not throw for an HTTP failure, so the status is checked here. It throws when the type cannot be
+// read: a page cannot be added to a solution without it, and a caller reports that rather than leave the page out quietly.
+async function readPageComponentType(client) {
+ if (!client || typeof client.get !== 'function') {
+ throw Object.assign(new Error('the solution component type of a generative page cannot be read: no Dataverse client to read it with'), { code: 'GENPAGE_COMPONENT_TYPE_UNRESOLVED' });
+ }
+ const res = await client.get(`/${componentTypePath(UXAGENTPROJECT_LOGICAL_NAME)}`);
+ const status = res && res.status;
+ if (!(status >= 200 && status < 300)) {
+ const said = res && res.body && res.body.error && res.body.error.message;
+ throw Object.assign(new Error(`the solution component type of a generative page could not be read (HTTP ${status === undefined ? 'no answer' : status}${said ? `: ${said}` : ''})`), { code: 'GENPAGE_COMPONENT_TYPE_UNRESOLVED', ...(status === undefined ? {} : { statusCode: status }) });
+ }
+ return componentTypeOf(res.body, UXAGENTPROJECT_LOGICAL_NAME);
+}
+
+// The options the SDK's `addSolutionComponent` takes for one page.
+function pageComponent(pageId, componentType, solutionUniqueName) {
+ return { componentId: pageId, componentType, solutionUniqueName, addRequiredComponents: PAGE_ADD_REQUIRED_COMPONENTS };
+}
+
+// The unmanaged solution named `uniqueName`, as the platform spells it: the solution an app or a page is to join. Read before anything is
+// written, so a name that is no unmanaged solution refuses the run with nothing made. Throws, with a code, when there is no such
+// solution (SOLUTION_NOT_FOUND: the name given may be the display name) or it is managed (SOLUTION_MANAGED: a managed solution takes no
+// new components). `sdk` is anything with the SDK's `queryRecords`; its answer is a list of rows:
+// [ { "solutionid": "…", "uniquename": "ContosoCore", "friendlyname": "Contoso Core", "ismanaged": false } ]
+async function readTargetSolution(sdk, uniqueName) {
+ const rows = await sdk.queryRecords('solution', {
+ select: ['solutionid', 'uniquename', 'friendlyname', 'ismanaged'],
+ filter: `uniquename eq '${odataLit(uniqueName)}'`,
+ top: 1,
+ });
+ const solution = rows && rows[0];
+ if (!solution) {
+ throw Object.assign(new Error(
+ `There is no solution with the unique name '${uniqueName}' in this environment. --solution takes a solution's unique name, not its display name; `
+ + 'create the solution first (provision-solution.js) if it should exist.'), { code: 'SOLUTION_NOT_FOUND' });
+ }
+ if (solution.ismanaged === true) {
+ throw Object.assign(new Error(`The solution '${solution.uniquename}' is managed, and a managed solution takes no new components. Use an unmanaged solution.`), { code: 'SOLUTION_MANAGED' });
+ }
+ return { uniqueName: solution.uniquename || uniqueName };
+}
+
+module.exports = {
+ UXAGENTPROJECT_LOGICAL_NAME,
+ PAGE_ADD_REQUIRED_COMPONENTS,
+ componentTypePath,
+ componentTypeOf,
+ readPageComponentType,
+ pageComponent,
+ readTargetSolution,
+};
diff --git a/plugins/model-apps/scripts/lib/page-structure.js b/plugins/model-apps/scripts/lib/page-structure.js
index 7b5c053a0..e0181cd47 100644
--- a/plugins/model-apps/scripts/lib/page-structure.js
+++ b/plugins/model-apps/scripts/lib/page-structure.js
@@ -9,41 +9,53 @@
// the elision-marker check and the fence check on BLANKED source were added to one gate and had to be
// found missing from the other. A page one gate refuses, the other now refuses too, with the same words.
//
-// Deliberately NOT a type check. The plugin does ship the TypeScript compiler, but for the SDK's page compile alone, which loads it
-// lazily (~0.2 s: lib/typescript-compiler.js) — more than a gate on one page file should pay — and that compile is a transpile, not
-// a type check, so a type error is not caught at deploy either. This catches the realistic worker failures —
-// an empty file, a truncated write, prose instead of code, elided code.
+// Deliberately NOT a type check. The plugin ships the TypeScript compiler for the SDK's page compile, which loads it lazily (~0.2 s: lib/typescript-compiler.js) —
+// more than a gate on every page file should pay — so the page is read by the lexer, and the parser is asked only about a page on which the lexer guessed
+// (parsedViews, below); and that compile is a transpile, not a type check, so a type error is not caught at deploy either. This catches the realistic worker
+// failures — an empty file, a truncated write, prose instead of code, elided code.
//
// Every check runs over literal-blanked source (see source-literals.js). A substring search, even over
// a copy that keeps ordinary string bodies, accepted prose that merely MENTIONS an export:
// /* export default */ -> accepted
// const prose = "export default GeneratedComponent"; -> accepted
const { blankLiterals, endsMidStatement, findElisionMarker, hasDefaultExport, hasUnbalancedBrackets, trimTrivia, WS } = require('./source-literals.js');
+const { guessedPageViews } = require('./typescript-views.js');
// A line that opens a markdown fence, after the white space TypeScript skips (source-literals.js, isTrivia): U+0085 and the zero-width space before a fence are white space to it.
const MARKDOWN_FENCE = new RegExp(`^${WS}*(\`\`\`|~~~)`, 'm');
+// Where the lexer guessed what a construct is (source-literals.js, `onAmbiguity`), its view of the page may be wrong from there on — an interface's generic call
+// signature, `interface Api { <U>(x: U): U; }`, reads to it as an element whose text runs to the end of the file, and a complete page as cut off. So where it
+// guessed, the page is read as the TypeScript parser reads it (typescript-views.js: the same views, built from the parse), when the parser reports no diagnostic;
+// where it does report one, or did not need to be asked, the lexer's views stand — and so they do where another reader reads the page differently or refuses it
+// (a JSX attribute string after trivia, grammar only TypeScript's parser takes), decided by guessedPageViews exactly as the navigation oracle decides it. Every
+// check is the same either way: only the views they read differ.
+function parsedViews(text) {
+ return guessedPageViews(text).views;
+}
+
function pageStructureProblems(code) {
const text = String(code == null ? '' : code);
if (!trimTrivia(text)) return ['file is empty'];
+ const views = parsedViews(text);
const problems = [];
// hasDefaultExport also refuses a file cut off INSIDE its export (`export default function P(props)`
// with no body), so the message says so: the fix is to write the whole page, not to add an export.
- if (!hasDefaultExport(text)) {
+ if (!hasDefaultExport(text, views)) {
problems.push('no complete default export — no real `export default` (or `export { X as default }`), '
+ 'or the file ends inside it, so the host cannot mount the page');
}
- if (hasUnbalancedBrackets(text)) problems.push('unbalanced brackets — the file looks truncated');
+ if (hasUnbalancedBrackets(text, views)) problems.push('unbalanced brackets — the file looks truncated');
// A cut that leaves every bracket balanced: inside JSX, a template or a comment, or after `a +`.
- if (endsMidStatement(text)) problems.push('stops mid-statement — the file looks truncated');
+ if (endsMidStatement(text, views)) problems.push('stops mid-statement — the file looks truncated');
// A worker that answers in prose usually still opens a fence, and a real .tsx never has one in CODE.
// Both CommonMark fence markers count. On the blanked source, a fence inside a template literal (a page
// rendering markdown help) is data, while a fence wrapping the file is code-position text.
- if (MARKDOWN_FENCE.test(blankLiterals(text))) {
+ if (MARKDOWN_FENCE.test(views ? views.literal : blankLiterals(text))) {
problems.push('contains a markdown code fence — the worker returned prose, not a module');
}
// Elided code (`// TODO: …`, `// ...`, "omitted for brevity"), the same rule the genpage evals apply.
- const elision = findElisionMarker(text);
+ const elision = findElisionMarker(text, views);
if (elision) problems.push(`contains ${elision} — the page is incomplete`);
return problems;
}
diff --git a/plugins/model-apps/scripts/lib/pageref-resolver.js b/plugins/model-apps/scripts/lib/pageref-resolver.js
index dfce5bd56..b1c800375 100644
--- a/plugins/model-apps/scripts/lib/pageref-resolver.js
+++ b/plugins/model-apps/scripts/lib/pageref-resolver.js
@@ -1,5 +1,6 @@
'use strict';
-const { blankNonCodePreservingTemplateExpressions, isTrivia, isLineTerminator } = require('./source-literals.js');
+const { isTrivia, isLineTerminator } = require('./source-literals.js');
+const { guessedPageViews } = require('./typescript-views.js');
// Pure STRUCTURAL resolver for generative-page cross-page navigation. Authors emit a link as a stable
// symbolic token — pageId: "PAGEREF_<key>" — because the real GenPageId is minted by the server at
@@ -683,12 +684,16 @@ function tokenRange(tokens, from, to) {
// the lexer takes the regex reading, and where that is wrong it blanks code up to the next `/` and reads on in the wrong state. The same
// holds for every guess the lexer makes, and nothing short of a parser can tell which was wrong, so nothing at or after the earliest is
// trusted: pageRefTokens marks every token there, strayPageRefs reports each, and no consumer rewrites a call that reaches it.
+// So where the lexer guessed, the parser is asked (typescript-views.js): the TypeScript compiler the pages are compiled with, which settles every guess. Where it
+// parses the page with no diagnostic, the mask is the one built from its parse — the lexer's own format, character for character (a test holds the two equal on
+// every page the lexer reads with no guess) — and nothing in the page is a guess any more: there is no frontier. Where it reports a diagnostic, the lexer's mask and
+// frontier stand; and so they do where another reader reads the page differently or refuses it (a JSX attribute string after trivia, which TypeScript reads with
+// escapes and other compilers without, so they end it at different quotes; grammar only TypeScript's parser takes), told from the parse itself by
+// guessedPageViews, which the structure gate (page-structure.js) asks too.
function lexNavigation(src) {
- let frontier = null;
- const mask = blankNonCodePreservingTemplateExpressions(src, {
- onAmbiguity: (at, kind) => { if (!frontier || at < frontier.at) frontier = { at, kind }; },
- });
- return { mask, tokens: pageRefTokens(src, frontier), frontier };
+ const { keep, frontier, views } = guessedPageViews(src);
+ if (views !== null) return { mask: views.keep, tokens: pageRefTokens(src, null), frontier: null };
+ return { mask: keep, tokens: pageRefTokens(src, frontier), frontier };
}
// Everything the oracle reads from one source, computed once: the classified targets (in source order), the tokens and the frontier. A
diff --git a/plugins/model-apps/scripts/lib/plan-sections.js b/plugins/model-apps/scripts/lib/plan-sections.js
new file mode 100644
index 000000000..1729c844e
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/plan-sections.js
@@ -0,0 +1,60 @@
+'use strict';
+// The three Markdown primitives every reader of a genpage plan shares: one `## <heading>` section, the first table that has
+// the named columns, and that table's rows. They lived in the eval harness (evals/model-apps/genpage/lib/plan-evidence.js,
+// which re-exports them from here unchanged); the plugin's own plan readers need them too (lib/genpage-plan-semantics.js),
+// and shipped code must not import an eval module.
+//
+// The shapes they read, from references/plan-schema.md:
+// ## Pages
+// | Page | File | Purpose | Entities |
+// |------|------|---------|----------|
+// | Account Overview | account-overview.tsx | Show account highlights | account |
+//
+// planSection(plan, 'Pages') is the text between that heading and the next `## ` heading, trimmed; the heading matches whatever
+// its letter case, and only at level two — a `### Pages (2 total)` preview heading is not one (genpage-plan-semantics.js reads the
+// preview's own levels). findMarkdownTable(text, ['Page', 'File']) is the first `| … |` line whose cells include every named
+// column (letter case ignored) with the lines from it on; parseMarkdownRows(text, columns) is that table's rows below its
+// delimiter row, keyed by the lower-cased header, up to the first line that is not a `| … |` row. An all-empty row is skipped.
+
+function planSection(plan, heading) {
+ if (!plan) return null;
+ const lines = plan.split('\n');
+ const escaped = heading.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ const startRe = new RegExp(`^##\\s+${escaped}\\s*$`, 'i');
+ let i = 0;
+ while (i < lines.length && !startRe.test(lines[i])) i++;
+ if (i >= lines.length) return null;
+ i++;
+ const out = [];
+ while (i < lines.length && !/^##\s/.test(lines[i])) out.push(lines[i++]);
+ return out.join('\n').trim();
+}
+
+function findMarkdownTable(sectionText, requiredColumns) {
+ const lines = sectionText.split(/\r?\n/);
+ for (let i = 0; i < lines.length; i++) {
+ if (!/^\s*\|.*\|\s*$/.test(lines[i])) continue;
+ const headers = lines[i].split('|').slice(1, -1).map((header) => header.trim().toLowerCase());
+ if (requiredColumns.every((column) => headers.includes(column.toLowerCase()))) {
+ return { lineIndex: i, headers, lines: lines.slice(i) };
+ }
+ }
+ return null;
+}
+
+function parseMarkdownRows(sectionText, requiredColumns) {
+ const table = findMarkdownTable(sectionText, requiredColumns);
+ if (!table) return [];
+ const rows = [];
+ for (const line of table.lines.slice(2)) {
+ if (!/^\s*\|.*\|\s*$/.test(line)) break;
+ const cells = line.split('|').slice(1, -1).map((cell) => cell.trim());
+ if (cells.length === 0 || cells.every((cell) => cell === '')) continue;
+ const row = {};
+ for (let i = 0; i < table.headers.length; i++) row[table.headers[i]] = cells[i] || '';
+ rows.push(row);
+ }
+ return rows;
+}
+
+module.exports = { planSection, findMarkdownTable, parseMarkdownRows };
diff --git a/plugins/model-apps/scripts/lib/provision-input.js b/plugins/model-apps/scripts/lib/provision-input.js
index 374b23b0f..8abf7ba32 100644
--- a/plugins/model-apps/scripts/lib/provision-input.js
+++ b/plugins/model-apps/scripts/lib/provision-input.js
@@ -5,7 +5,7 @@
// App-Spec subset: { solution, entities, relationships, globalChoices?, sampleData? }.
// Entities carry FULL schema names (e.g. cr_candidate), not bare suffixes.
-const { TYPE_MAP, normalizeLanguageCode, validateLabel, validateChoiceOptionLabels, isLocalizedLabelMap, labelIsMissing, rejectLocalizedGlobalChoice, validateSampleDataRows, ENTITY_KEYS, ENTITY_KEY_HINTS, invalidLanguageCodeMessage, relationshipNameCollisions, relationshipCollisionMessage, primaryNameLengthProblem, autoNumberFormatProblem, requiredValueProblem } = require('./app-spec.js');
+const { TYPE_MAP, normalizeLanguageCode, validateLabel, validateChoiceOptionLabels, isLocalizedLabelMap, labelIsMissing, rejectLocalizedGlobalChoice, validateSampleDataRows, ENTITY_KEYS, ENTITY_KEY_HINTS, invalidLanguageCodeMessage, relationshipNameCollisions, relationshipCollisionMessage, primaryNameLengthProblem, autoNumberFormatProblem, requiredValueProblem, primaryAttributeKeyProblems } = require('./app-spec.js');
// Validates provision-entities input. Returns { ok, errors }.
function validateProvisionInput(input) {
@@ -132,6 +132,9 @@ function validateProvisionInput(input) {
} else if (!e.primaryAttribute.schemaName || typeof e.primaryAttribute.schemaName !== 'string') {
errors.push(`entity '${e.schemaName}': primaryAttribute.schemaName is required and must be a string`);
}
+ // A key the build does not read from the name column is refused here as validateAppSpec refuses it, by the one rule: this gate is
+ // the only one /genpage passes through, and without it a `maxlength` or `requiredLevel` created the table without what it asked.
+ errors.push(...primaryAttributeKeyProblems(e.primaryAttribute, `entity '${e.schemaName}'`));
// The length of the name column goes into BOTH table creates as the request's MaxLength, so a value the platform would
// refuse — or a string, which it would be sent as — has to stop here, before the solution is written. It is the rule
// validateAppSpec applies (one function), because this gate is the only one /genpage and /app-builder pass through.
diff --git a/plugins/model-apps/scripts/lib/relationship-metadata.js b/plugins/model-apps/scripts/lib/relationship-metadata.js
index 2de52406b..5fd5fc060 100644
--- a/plugins/model-apps/scripts/lib/relationship-metadata.js
+++ b/plugins/model-apps/scripts/lib/relationship-metadata.js
@@ -50,6 +50,20 @@ const COLLECTION = {
},
};
+// The lookup-details read of a table's ManyToOne relationships (scripts/get-lookup-metadata.js, lib/lookup-metadata.js): the
+// default select plus the two scalars that say how a page reaches each target of a lookup — the target's key and the
+// navigation property of the referencing table. Still scalars only (no DisplayName / LocalizedLabels), and still no derived
+// ReferencingEntity (the collection is scoped to it; selecting it without a cast is a 400):
+// GET /EntityDefinitions(LogicalName='opportunity')/ManyToOneRelationships?$select=SchemaName,ReferencedEntity,ReferencingAttribute,
+// ReferencedAttribute,ReferencingEntityNavigationPropertyName
+// → 200 { "value": [ { "SchemaName": "opportunity_customer_accounts", "ReferencedEntity": "account", "ReferencingAttribute": "customerid",
+// "ReferencedAttribute": "accountid", "ReferencingEntityNavigationPropertyName": "customerid_account" }, … ],
+// "@odata.nextLink": "…" (when the platform pages the answer) }
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/onetomanyrelationshipmetadata
+// The SDK's fetchEntityMetadata projection keeps ReferencedEntity and ReferencedAttribute of these rows but neither the source
+// lookup column nor the navigation property, so this supplemental read exists; an SDK projection that carried both would retire it.
+const LOOKUP_DETAILS_SELECT = 'SchemaName,ReferencedEntity,ReferencingAttribute,ReferencedAttribute,ReferencingEntityNavigationPropertyName';
+
function lc(v) {
return String(v || '').toLowerCase();
}
@@ -125,9 +139,13 @@ function mapCollectionRow(raw, kind, entityLogical) {
};
}
-async function readRelationshipsOf(client, entityLogical, kind, cache) {
+async function readRelationshipsOf(client, entityLogical, kind, cache, options) {
const spec = COLLECTION[kind];
if (!spec) return { ok: false, status: 0, error: `unknown relationship kind '${kind}'` };
+ if (options && options.lookupDetails) {
+ if (kind !== 'ManyToOne') return { ok: false, status: 0, error: `lookup details are read from ManyToOne relationships, not '${kind}'` };
+ return readLookupDetails(client, lc(entityLogical), cache);
+ }
const logical = lc(entityLogical);
// A plan probes many relationships on the same tables. Keyed by table and kind so the typed
// probe and the case-insensitive fallback share one read.
@@ -152,6 +170,70 @@ async function readRelationshipsOf(client, entityLogical, kind, cache) {
return finish({ ok: true, rows: value.filter(Boolean).map((raw) => mapCollectionRow(raw, kind, logical)) });
}
+// readRelationshipsOf's lookup-details mode, for lookup discovery only. Differences from the default read, each deliberate:
+// - every page of the collection is read (lib/app-components.js collectionRows: absolute continuations through getAbsolute, a
+// repeated or malformed link and a failed or malformed page refused), because a lookup's candidate paths are proven complete
+// only by the whole answer — one failed page fails the read, never a shorter list;
+// - a 404 for the table is a FAILURE (`tableMissing: true` beside `ok: false`): the default read's "no such table, no
+// relationships" answer would let discovery report a lookup with no targets;
+// - every row must state the two added scalars, as non-empty strings: a service that omitted them would otherwise shrink the
+// candidate paths silently;
+// - its own cache key (`|lookup-details`), so a cached default read can never answer as a detailed one, or the reverse.
+// The answer is converted here as the default read's is: the service's own message from either envelope (`error` or `Error`),
+// its OData error riding along as `answered`.
+async function readLookupDetails(client, logical, cache) {
+ const cacheKey = cache && `${logical}|ManyToOne|lookup-details`;
+ if (cacheKey && cache.has(cacheKey)) return cache.get(cacheKey);
+ const finish = (result) => {
+ if (cacheKey) cache.set(cacheKey, result);
+ return result;
+ };
+ // Required here rather than at the top: only lookup discovery pages a relationship collection, and the default read's callers
+ // (the build, verify) need not load the app-component readers for it.
+ const { collectionRows } = require('./app-components.js');
+ // The last answer collectionRows was given, so a refusal is reported in the platform's words (both envelopes) and with its code.
+ let last = null;
+ const settle = async (request) => {
+ try {
+ last = (await request()) || { status: 0, body: null };
+ } catch (err) {
+ last = { status: (err && (err.statusCode || err.status)) || 0, body: null, thrown: err };
+ }
+ return last;
+ };
+ const recording = {
+ get: (p) => settle(() => (client && typeof client.get === 'function' ? client.get(p) : Promise.reject(new Error('no metadata client')))),
+ ...(client && typeof client.getAbsolute === 'function' ? { getAbsolute: (url) => settle(() => client.getAbsolute(url)) } : {}),
+ ...(client && typeof client.apiUrl === 'function' ? { apiUrl: (p) => client.apiUrl(p) } : {}),
+ };
+ const path = `/EntityDefinitions(LogicalName='${odataLit(logical)}')/${COLLECTION.ManyToOne.segment}?$select=${LOOKUP_DETAILS_SELECT}`;
+ let rows;
+ try {
+ rows = await collectionRows(recording, path, `the ManyToOne relationships of ${logical}`, { code: 'LOOKUP_RELATIONSHIPS_UNREADABLE' });
+ } catch (err) {
+ const refused = last && (last.thrown || !last.status || last.status < 200 || last.status >= 300);
+ const status = last ? last.status : 0;
+ const result = withAnswer({ ok: false, status, error: refused ? errorMessage(last) : String((err && err.message) || err) }, refused ? answeredOf(last) : undefined);
+ if (status === 404) result.tableMissing = true;
+ return finish(result);
+ }
+ const mapped = [];
+ for (const raw of rows) {
+ const row = raw && typeof raw === 'object' ? raw : {};
+ const missing = ['SchemaName', 'ReferencedEntity', 'ReferencingAttribute', 'ReferencedAttribute', 'ReferencingEntityNavigationPropertyName']
+ .filter((field) => typeof row[field] !== 'string' || !row[field]);
+ if (missing.length) {
+ return finish({ ok: false, status: last ? last.status : 200, error: `a ManyToOne relationship of ${logical} (${row.SchemaName || 'unnamed'}) does not state ${missing.join(', ')}` });
+ }
+ mapped.push({
+ ...mapCollectionRow(row, 'ManyToOne', logical),
+ referencedAttribute: row.ReferencedAttribute,
+ navigationProperty: row.ReferencingEntityNavigationPropertyName,
+ });
+ }
+ return finish({ ok: true, rows: mapped });
+}
+
function castKind(body) {
const type = String((body && body.RelationshipType) || '');
const odata = String((body && body['@odata.type']) || '');
diff --git a/plugins/model-apps/scripts/lib/sdk-build.js b/plugins/model-apps/scripts/lib/sdk-build.js
index 0d83683c0..436fa7f2a 100644
--- a/plugins/model-apps/scripts/lib/sdk-build.js
+++ b/plugins/model-apps/scripts/lib/sdk-build.js
@@ -143,6 +143,7 @@ const { tableRefs, pinAppTables, publishAppComponents, resolveMainForms, appComp
const { appWriteTables, appPushTables, preAppTables, publishTablesXml, readSavedNotPublished, describeSavedNotPublished, readAppFormChartTables, describePreAppRefusal, describeUnreadAppComponents } = require('./table-publish.js');
const { hasUnsyncedEdits } = require('./unsynced-edits.js');
const { createSolutionMembership, ensureSolutionComponent } = require('./solution-membership.js');
+const { readPageComponentType, pageComponent } = require('./page-solution.js');
const { openUnconfirmedWebResources } = require('./web-resource-records.js');
const { openDashboardCreations } = require('./dashboard-creation-records.js');
const { ownValue } = require('./own-keys.js');
@@ -603,6 +604,27 @@ function webResourceOpts(wr, appDir) {
return o;
}
+// How the spec's web resource `wr` compares with the content an environment holds for it — `deployed`, the base64 text a read of
+// `webresourceset` answers in `content` (the published layer, for a plain read):
+// { state: 'same' } the bytes the build would write are the deployed bytes
+// { state: 'differs' } they are not
+// { state: 'unknown', reason } one side cannot be read: the spec's source (a contentPath that is not there), or an answer with no content
+// The bytes are the ones the SDK sends — `contentBase64` as given, `content` as UTF-8 (webResourceOpts) — and compares when it reads a write back
+// to confirm it, so a web resource an earlier build wrote from the same spec compares the same. The ONE comparison behind the build's reuse line
+// and verify's web-resource check, so the two cannot disagree about whether an edit was deployed.
+function webResourceContentState(wr, appDir, deployed) {
+ if (typeof deployed !== 'string') return { state: 'unknown', reason: 'the environment answered no content' };
+ let options;
+ try {
+ options = webResourceOpts(wr, appDir);
+ } catch (err) {
+ const source = typeof wr.contentPath === 'string' && wr.content === undefined && wr.contentBase64 === undefined ? `contentPath ${JSON.stringify(wr.contentPath)}: ` : '';
+ return { state: 'unknown', reason: `the spec's content could not be read (${source}${(err && err.message) || err})` };
+ }
+ const wanted = options.contentBase64 !== undefined ? Buffer.from(String(options.contentBase64), 'base64') : Buffer.from(String(options.content), 'utf8');
+ return { state: Buffer.from(deployed, 'base64').equals(wanted) ? 'same' : 'differs' };
+}
+
// --- the ordered plan (dry-run + totals) -----------------------------------------------
function planFor(spec, opts) {
const has = (p) => !opts.phases || opts.phases.includes(p);
@@ -3356,6 +3378,10 @@ async function runSdkBuildPhases(spec, opts, owed) {
// in the solution). Built before forms so a form event handler can bind its library.
// One that an earlier run of this build created or wrote and could not confirm was published (WEB_RESOURCE_UNVERIFIED,
// recorded in the workspace) is not reused: its content is written again by id (writeOwnedWebResource).
+ // The reuse writes nothing — the phase is discover-then-skip, like charts, command bars and dashboards, whose lines say their
+ // edits are not applied — but it is not silent about the content: the row's deployed (published) content is read with its id and
+ // compared with what the spec would write (webResourceContentState), and a difference is said in the skip line and as a warning.
+ // An `external` web resource is a shared one the build reuses as it finds it, so its content is not the spec's to compare.
if (has('web-resources')) {
for (const wr of spec.webResources || []) {
const recordedId = unconfirmedWebResources.idOf(wr.name);
@@ -3365,10 +3391,23 @@ async function runSdkBuildPhases(spec, opts, owed) {
});
continue;
}
- const existing = await provision.queryRecords('webresource', { select: ['webresourceid'], filter: `name eq '${odataLit(wr.name)}'`, top: 1 });
+ // The row as a plain read answers it (its published layer):
+ // GET /webresourceset?$select=webresourceid,content&$filter=name eq 'contoso_/scripts/form.js'&$top=1
+ // { "value": [ { "webresourceid": "…", "content": "dmFyIEZvcm0gPSB7…" } ] }
+ const existing = await provision.queryRecords('webresource', { select: ['webresourceid', 'content'], filter: `name eq '${odataLit(wr.name)}'`, top: 1 });
if (existing && existing[0] && existing[0].webresourceid) {
result.created.webResources[wr.name] = existing[0].webresourceid;
- runner.skip('web-resources', `web resource ${wr.name} (exists — reuse)`);
+ const compared = wr.external === true ? null : webResourceContentState(wr, opts.appDir, existing[0].content);
+ if (compared && compared.state === 'differs') {
+ runner.skip('web-resources', `web resource ${wr.name} (exists — reuse; its deployed content differs from the spec's: content edits aren't applied on rebuild, recreate to change)`);
+ if (typeof opts.warn === 'function') {
+ opts.warn(`web resource ${wr.name}: its deployed content differs from the spec's and is left as it is — a rebuild does not write the content of a web resource that exists; delete it (or tear the app down) and build again to deploy the spec's content`);
+ }
+ } else if (compared && compared.state === 'unknown') {
+ runner.skip('web-resources', `web resource ${wr.name} (exists — reuse; its content was not compared: ${compared.reason})`);
+ } else {
+ runner.skip('web-resources', `web resource ${wr.name} (exists — reuse)`);
+ }
continue;
}
await runner.run('web-resources', `web resource ${wr.name} (${wr.type || 'js'})`, async () => {
@@ -7123,6 +7162,41 @@ async function runSdkBuildPhases(spec, opts, owed) {
// After the whole scan, so a build that halts on a later page says only why it halted. Nothing has been written yet, and the pages that are warned about are sent as they are.
if (typeof opts.warn === 'function') for (const warning of griffelWarnings) opts.warn(warning);
+ // THE SOLUTION HOLDS THE PAGES TOO (AB#6443257). Every other component the build makes joins the spec's solution, but a page joins one only when it is added
+ // explicitly — the add of the app brings its sitemap, never the pages its navigation opens (lib/page-solution.js) — so a build made "in" a solution left
+ // its pages out of it, and the solution exported an app whose navigation opens pages the target environment does not have. A page this run CREATES is
+ // added as soon as it is made; one it UPDATES is re-asserted, as every component the build reuses is (lib/solution-membership.js): a page an earlier build
+ // made outside the solution, or whose add failed, joins it now, and one the solution is proven to hold costs a read and no write. A page the run KEEPS without
+ // writing it — a changed-only run leaves the pages it did not select as they are — is re-asserted the same way once the pages are written (the page manifest
+ // step, below). The add brings the page's file rows with it (AddRequiredComponents). The page table's component type is the environment's: read HERE, before
+ // the first page is written, so an environment that cannot say it halts the phase with nothing in it written. A system solution holds every component already
+ // and is not added to.
+ const pagesJoinSolution = !!(sol && sol.uniqueName) && !isRestrictedSolution(sol.uniqueName) && implemented.some(uploadedThisRun)
+ // An SDK with no raw client to read with is a test double, as everywhere in this file: the real one always has it, so there is no type to read and no page is added.
+ && !!(provision.dataverse && typeof provision.dataverse.get === 'function');
+ let pageComponentType = null;
+ let pageMembers = null;
+ const pagesInSolution = new Set();
+ if (pagesJoinSolution) {
+ try {
+ pageComponentType = await readPageComponentType(provision.dataverse);
+ } catch (e) {
+ throw new BuildHalt(`could not read the solution component type of a generative page, so the pages cannot join solution ${sol.uniqueName} — nothing in the pages phase was written: ${(e && e.message) || e}`, { phase: 'pages', code: 'pages-solution-type-unreadable', recoverable: true, ...retryFrom(e) });
+ }
+ pageMembers = createSolutionMembership({ read: provision, solutionUniqueName: sol.uniqueName, componentTypes: [pageComponentType] });
+ }
+ // `created`: a page this run has just made cannot already be a member, so it is added without the membership read.
+ const pageIntoSolution = async (pageId, { created }) => {
+ if (!pagesJoinSolution) return;
+ const id = String(pageId).toLowerCase();
+ if (pagesInSolution.has(id)) return;
+ if (created || !(await pageMembers.has(id, pageComponentType))) {
+ await provision.addSolutionComponent(pageComponent(id, pageComponentType, sol.uniqueName));
+ pageMembers.note(id, pageComponentType);
+ }
+ pagesInSolution.add(id);
+ };
+
const mintedKeys = new Set();
const deployment = new Map(); // key -> resolved code (nav sources only)
// What a page write answered. The SDK's warnings, and a publish it could not prove, go to the build's log; a page that was SAVED but could not be
@@ -7264,6 +7338,7 @@ async function runSdkBuildPhases(spec, opts, owed) {
mintedKeys.add(key);
await persistNow();
await afterWrite(p, 'created', up, fields);
+ await pageIntoSolution(up.pageId, { created: true });
}
const navSources = new Map();
for (const p of implemented) if ((p.navigatesTo || []).length) navSources.set(keyOf(p), { code: sourceByKey.get(keyOf(p)) });
@@ -7374,6 +7449,7 @@ async function runSdkBuildPhases(spec, opts, owed) {
result.created.pageSourceShas[key] = scannedSha.get(key);
await persistNow(); // manifest carries this id BEFORE the next create (crash-safety, design §9)
await afterWrite(p, requestedId ? 'updated' : 'created', up, fields);
+ await pageIntoSolution(up.pageId, { created: !requestedId });
return up.pageId;
});
}
@@ -7385,8 +7461,18 @@ async function runSdkBuildPhases(spec, opts, owed) {
// (removal-only / detach) run — there is no page identity to record, and writing an empty manifest
// would needlessly create/update the web resource. The scan/create/upload steps above are already
// no-ops when spec.pages is empty (they iterate over spec.pages / implemented).
+ // The solution holds every page the manifest binds, not only the pages this run wrote (AB#6443257). A changed-only run writes the pages it selected
+ // and leaves the rest as they are — their content is the maker's to keep — but not out of the solution: a navigation target an earlier attempt of the
+ // run made, and whose add was refused or never sent, is bound by its creation receipt now and not written again, so nothing else would add it, and the
+ // build's retry, which keeps the selection, would succeed with that page outside the solution. Each such page is asserted as a page the run updates is
+ // (pageIntoSolution): the one read of the solution's pages answers all of them, and only a page the solution is not proven to hold is added, as a full
+ // build adds it. A page this run wrote was asserted then, and costs nothing here; a run that writes no page asserts none.
if ((spec.pages || []).length) {
- await runner.run('pages', `page manifest ${manifestResourceName(appUnique)}`, async () => { await persistNow(); return manifestResourceName(appUnique); });
+ await runner.run('pages', `page manifest ${manifestResourceName(appUnique)}`, async () => {
+ await persistNow();
+ for (const p of implemented) if (keyToId.has(keyOf(p))) await pageIntoSolution(keyToId.get(keyOf(p)), { created: false });
+ return manifestResourceName(appUnique);
+ });
}
// (6) Finalize the sitemap (the true commit point — only after all resolved uploads succeed). For a
// page-backed app this writes the resolved GenPage SubAreas. For an EXISTING app the app-shell
@@ -8252,4 +8338,4 @@ async function runSdkBuildPhases(spec, opts, owed) {
return result;
}
-module.exports = { runSdkBuild, publishTargets, partialEnrichment, settleOwedPublishes, collectOwedPublishes, settleOwedLengths, normalizeFormId, planFor, annotateLivePlan, resolvePhases, PHASES, BuildHalt, SDK_COLUMN_TYPE, viewDef, defaultViewColumns, subgridLabel, enrichesDefaultViews, dashboardsInSolution, findDashboardsByName, findPinnedDashboard, artifactIdentityQuery, resolveExistingFormId, FORM_TYPE_CODE, chartDef, dashboardTileOpts, dashboardComponent, compileFormIntent, formFieldLogicals, appDef, appUniqueName, applyAppAiDescription, haltOnUnpublishedAppHeader, pushAppHeader, commandsByEntity, commandDef, businessRuleDef, businessRuleFilter, bpfDef, bpfFilter, webResourceOpts, WEB_RESOURCE_KINDS, FORM_EVENTS, acquireAppPagesLease, personaRoleSpecFor, resolveRoleBusinessUnit, roleBuClause, roleGrantLabel, resolveRoleGrantTarget, existingAppSitemapIsWritten, pagesFirstRule, applyAppHeader, applyAppHeaderText, warnAppIconNotApplied, inspectBpfStages, applyBpfStages, refuseUnpushedAppCopy, assertAuthorizedSitemapRewrite, reconciledPublishHalt };
+module.exports = { runSdkBuild, publishTargets, partialEnrichment, settleOwedPublishes, collectOwedPublishes, settleOwedLengths, normalizeFormId, planFor, annotateLivePlan, resolvePhases, PHASES, BuildHalt, SDK_COLUMN_TYPE, viewDef, defaultViewColumns, subgridLabel, enrichesDefaultViews, dashboardsInSolution, findDashboardsByName, findPinnedDashboard, artifactIdentityQuery, resolveExistingFormId, FORM_TYPE_CODE, chartDef, dashboardTileOpts, dashboardComponent, compileFormIntent, formFieldLogicals, appDef, appUniqueName, applyAppAiDescription, haltOnUnpublishedAppHeader, pushAppHeader, commandsByEntity, commandDef, businessRuleDef, businessRuleFilter, bpfDef, bpfFilter, webResourceOpts, webResourceContentState, WEB_RESOURCE_KINDS, FORM_EVENTS, acquireAppPagesLease, personaRoleSpecFor, resolveRoleBusinessUnit, roleBuClause, roleGrantLabel, resolveRoleGrantTarget, existingAppSitemapIsWritten, pagesFirstRule, applyAppHeader, applyAppHeaderText, warnAppIconNotApplied, inspectBpfStages, applyBpfStages, refuseUnpushedAppCopy, assertAuthorizedSitemapRewrite, reconciledPublishHalt };
diff --git a/plugins/model-apps/scripts/lib/source-literals.js b/plugins/model-apps/scripts/lib/source-literals.js
index 7ccd3bcf7..e159051b8 100644
--- a/plugins/model-apps/scripts/lib/source-literals.js
+++ b/plugins/model-apps/scripts/lib/source-literals.js
@@ -4077,8 +4077,10 @@ const EXPORTED_MEMBER_CHAIN = new RegExp(String.raw`^([\p{ID_Start}$_][\p{ID_Con
const PARENTHESISED_FUNCTION_OR_CLASS = new RegExp(String.raw`^\(${WS}*(?:async${WS}+)?(?:function|class)\b`);
const RETURN_TYPE_COLON = new RegExp(String.raw`^${WS}*:`);
const DANGLING_CAST = new RegExp(String.raw`(?<![\p{ID_Continue}$])(?:as|satisfies|keyof)${WS}*$`, 'u');
-function hasDefaultExport(code) {
- const bare = blankLiterals(code);
+function hasDefaultExport(code, views = null) {
+ // `views`, when given, are a parser's views of the page in this file's format (typescript-views.js in model-apps: page-structure.js passes them where the lexer
+ // guessed): its literal view stands for blankLiterals(code).
+ const bare = views && typeof views.literal === 'string' ? views.literal : blankLiterals(code);
if (NAMED_DEFAULT_EXPORT.test(bare)) return true;
// Any complete one will do: TypeScript overloads declare the signature(s) before the body —
// export default function f(x: string): string;
@@ -4200,15 +4202,26 @@ function genericArrowIsComplete(rest) {
if (open.kind !== '(') return false;
const parametersEnd = typeGroupEnd(rest, open.start);
if (parametersEnd === -1) return false;
+ // Where reading a generic call's type arguments in a default value changes the reading (returnTypeEnd, defaultValueEnd), the page must be complete both ways: that
+ // reading finds the cut right after a function type with such a parameter (`({ a = f<T, U>() }) => T`), and only ever refuses more — a value that TypeScript reads
+ // and Babel refuses (`await f<T, U>()` in a parameter, `f<T, U>(010)`) cannot make a page pass that the reading to the first `,` refused.
+ const options = { typeArgumentsInDefaults: true };
+ if (!arrowFollows(rest, parametersEnd, options)) return false;
+ if (options.typeArgumentsRead && !arrowFollows(rest, parametersEnd, { typeArgumentsInDefaults: false })) return false;
+ // The body is taken as written, as any exported expression is (its brackets are checked separately), unless the file stops at a token that needs more: `p +`, `p as`.
+ return !DANGLING_TAIL.test(rest) && !DANGLING_CAST.test(rest);
+}
+
+// Whether the arrow's `=>` and a body follow the parameter list that ends at `parametersEnd` in `rest` — at once, or after a return type read to its end (returnTypeEnd,
+// with `options`).
+function arrowFollows(rest, parametersEnd, options) {
let arrow = typeTokenAt(rest, parametersEnd);
if (arrow.kind === ':') {
- const returnEnd = returnTypeEnd(rest, arrow.end);
+ const returnEnd = returnTypeEnd(rest, arrow.end, options);
if (returnEnd === -1) return false;
arrow = typeTokenAt(rest, returnEnd);
}
- if (arrow.kind !== '=>' || !startsArrowBody(typeTokenAt(rest, arrow.end))) return false;
- // The body is taken as written, as any exported expression is (its brackets are checked separately), unless the file stops at a token that needs more: `p +`, `p as`.
- return !DANGLING_TAIL.test(rest) && !DANGLING_CAST.test(rest);
+ return arrow.kind === '=>' && startsArrowBody(typeTokenAt(rest, arrow.end));
}
// What begins an arrow's body: a block, or what begins an expression — a name, any word but those that only begin a statement (a keyword that begins an expression, `this`,
@@ -4318,8 +4331,14 @@ const RETURN_TYPE_DEPTH = 200;
// type, `(p): (A | B) => …` a parenthesised type and then the arrow, and `(p): ({ a: T }) => p` a function type that takes the arrow's `=>` (an error);
// - type arguments, `[`, `extends`, `is` and an assertion's name continue a type only on its line; a function or constructor type after `|` or `&` is an error (TS1385, TS1388);
// - the JSDoc forms TypeScript's parser takes in a .tsx file and only its checker refuses (`?T`, `T?`, `!T`, `T!`, `*`, `function(…): T`) are read too.
-function returnTypeEnd(src, from) {
+// `options.typeArgumentsInDefaults` (true unless false) says whether a generic call's type arguments in a default value are passed over (defaultValueEnd), and
+// `options.typeArgumentsRead` is set where that changed what a default value holds.
+function returnTypeEnd(src, from, options = {}) {
+ if (options.typeArgumentsInDefaults === undefined) options.typeArgumentsInDefaults = true;
let depth = 0;
+ // Above zero while a type is read STRICTLY (typeArgumentsInExpressionEnd): a group in it — parentheses, brackets, braces, angle brackets — is read, not passed over
+ // whole; what this reading does not read through (a function type's parameters, an object type with members, a template, an import type) ends it with -1.
+ let strictly = 0;
const at = (k) => typeTokenAt(src, k);
const isWord = (token, text) => token.kind === 'word' && token.text === text;
// isIdentifier: a word that is no reserved word, nor `await`, which parseExportAssignment makes a keyword in an export.
@@ -4349,7 +4368,7 @@ function returnTypeEnd(src, from) {
// parseType: a function or constructor type, or a union and, on its line, `extends` and the rest of a conditional type — where conditional types are allowed: not in the
// `extends` clause of one (`noConditional`).
const type = (k, noConditional) => nested(() => {
- if (startsFunctionType(k)) return functionType(k);
+ if (startsFunctionType(k)) return strictly ? -1 : functionType(k);
const end = unionOrIntersection(k, '|', noConditional);
if (end === -1 || noConditional) return end;
const ext = at(end);
@@ -4390,9 +4409,8 @@ function returnTypeEnd(src, from) {
return after.kind === ')' && at(after.end).kind === '=>';
};
// parseObjectBindingPattern and parseArrayBindingPattern, whose `{` or `[` is at `open`: the index just past the pattern, or -1 where it does not parse with no error. A
- // default value is passed over to the `,` or the bracket that ends it (defaultValueEnd) — a known limit: the comma between a generic call's type arguments,
- // `{ a = f<T, U>() }`, is taken for the end of the value, the pattern reads as none, and a write cut right after a function type with such a parameter is accepted
- // (AGENTS.md, "TSX source lexer — known limits"; the page compile refuses it).
+ // default value is passed over to the `,` or the bracket that ends it (defaultValueEnd), a generic call's type arguments included: the comma in `{ a = f<T, U>() }` is
+ // the call's, the pattern is read, and a write cut right after a function type with such a parameter has no arrow.
const bindingPatternEnd = (open) => nested(() => {
const object = src[open] === '{';
const closer = object ? '}' : ']';
@@ -4441,7 +4459,13 @@ function returnTypeEnd(src, from) {
// parenthesised type and the arrow, where `({ [key]: v }) => …` and `({ [K in T]: v }) => …` (`K in T` is an expression) hold a function type's parameters. The
// expression is read only as far as that needs — operands, prefix and binary operators, `?` and `:`, member access, calls, indexes, `!`, type arguments where they close and
// what follows can follow them (canFollowTypeArgumentsInExpression), and a type after `as` or `satisfies` — and what it does not know (an arrow, `function`, a regex, JSX)
- // is taken for no expression: a type then, never a function type's parameters, so the reading can let a page TypeScript refuses through but never refuse one it parses.
+ // is taken for no expression: a type then, never a function type's parameters.
+ // Two readings here part from TypeScript's on purpose, rare known limits (AGENTS.md, "TSX source lexer — known limits"; pinned in source-literals.test.js): a group
+ // counts as an operand whatever it holds, so `K in (keyof T)` reads as an expression and `({ [K in (keyof T)]: boolean })` as a function type's parameters, where
+ // TypeScript reads a parenthesised mapped type; and a key that starts with a regular expression (`[/key/.source]`) is taken for no expression, where TypeScript reads
+ // one. Reading either as TypeScript does would turn a refusal into an acceptance on the strength of tokens this reading does not check as the parsers do — an escaped
+ // keyword, a legacy octal number or a string escape in the mapped type, a regular expression's flags (Babel refuses an unknown or repeated one that TypeScript's parser
+ // takes) — and a page either parser refuses would pass.
const computedKeyIsExpression = (open) => {
const close = typeGroupEnd(src, open);
if (close === -1) return false;
@@ -4500,7 +4524,18 @@ function returnTypeEnd(src, from) {
}
}
};
+ // A default value, from right after its `=` at `k`: the index of the `,` or the `closer` that ends it at its own level, or -1. A group in brackets, a string and a
+ // template are passed over whole, and so is a list of type arguments after an operand where TypeScript's parser takes one — `{ a = f<T, U>() }` holds one default, whose
+ // `,` is no element's (typeArgumentsInExpressionEnd) — unless `options.typeArgumentsInDefaults` is false: the value then ends at its first `,`, as JavaScript reads it.
+ // Where the two readings part, `options.typeArgumentsRead` says so (genericArrowIsComplete).
const defaultValueEnd = (k, closer) => {
+ const plain = defaultValueEndReading(k, closer, false);
+ if (!options.typeArgumentsInDefaults) return plain;
+ const read = defaultValueEndReading(k, closer, true);
+ if (read !== plain) options.typeArgumentsRead = true;
+ return read;
+ };
+ const defaultValueEndReading = (k, closer, typeArguments) => {
for (let j = k; j < src.length; j += 1) {
const c = src[j];
if (c === ',' || c === closer) return j;
@@ -4513,9 +4548,58 @@ function returnTypeEnd(src, from) {
if (end === -1) return -1;
j = end - 1;
} else if (c === ')' || c === ']' || c === '}') return -1;
+ else if (typeArguments && c === '<' && operandEndsBefore(k, j)) {
+ const end = typeArgumentsInExpressionEnd(j, closer);
+ if (end !== -1) j = end - 1;
+ }
}
return -1;
};
+ // Whether the text of a default value from `from` to the `<` at `at` ends in an operand that type arguments may follow (parseMemberExpressionRest and
+ // parseCallExpressionRest try them after one): a name — or a keyword read as a property name after a `.`, or one that is a value — a number, a string, a template, or a
+ // `)` or `]`. After an operator, `as`, `satisfies`, `await` or `yield` a `<` begins an element, a generic arrow or a type, and nothing is passed over.
+ const operandEndsBefore = (from, at) => {
+ let p = at - 1;
+ while (p >= from && isTrivia(src[p])) p -= 1;
+ if (p < from) return false;
+ const c = src[p];
+ if (c === ')' || c === ']' || c === '"' || c === "'" || c === '`') return true;
+ if (!/[\p{ID_Continue}$\u200c\u200d]/u.test(c)) return false;
+ let w = p;
+ while (w > from && /[\p{ID_Continue}$\u200c\u200d]/u.test(src[w - 1])) w -= 1;
+ const word = src.slice(w, p + 1);
+ let q = w - 1;
+ while (q >= from && isTrivia(src[q])) q -= 1;
+ if (q >= from && src[q] === '.') return true;
+ if (/^[0-9]/.test(word)) return true;
+ if ((RESERVED_WORDS.has(word) || word === 'const') && !['this', 'null', 'true', 'false', 'super'].includes(word)) return false;
+ return !['as', 'satisfies', 'await', 'yield'].includes(word);
+ };
+ // parseTypeArgumentsInExpression, from the `<` at `open` in a default value that `closer` ends: types with a `,` between them and maybe after the last, each read
+ // strictly to its end (TypeScript keeps a list whose types hold an error, and the pattern then fails: only a list it parses whole is passed over), the `>`, then what
+ // lets the list stand — a `(` (a call), a template (a tagged one), or the `,` or the `closer` that ends the value (an instantiation expression:
+ // canFollowTypeArgumentsInExpression takes a token that starts no expression). The index just past the `>`, or -1 where the parser would read a comparison, or this
+ // reading cannot say: the value is then read as before, to the first `,` at its level.
+ const typeArgumentsInExpressionEnd = (open, closer) => {
+ strictly += 1;
+ try {
+ let next = at(open + 1);
+ for (;;) {
+ const end = type(next.start, false);
+ if (end === -1) return -1;
+ next = at(end);
+ if (next.kind === ',') {
+ next = at(next.end);
+ if (next.kind !== '>') continue;
+ }
+ if (next.kind !== '>') return -1;
+ const after = at(next.end);
+ return after.kind === '(' || after.kind === 'template' || after.kind === ',' || after.kind === closer ? next.end : -1;
+ }
+ } finally {
+ strictly -= 1;
+ }
+ };
// parseFunctionOrConstructorType: [`abstract`] [`new`] [type parameters] parameters `=>` and a return type.
const functionType = (k) => {
let token = at(k);
@@ -4562,7 +4646,7 @@ function returnTypeEnd(src, from) {
if (token.newline) return end;
if (token.kind === '!') end = token.end;
else if (token.kind === '?' && !startsType(token.end, 0)) end = token.end;
- else if (token.kind === '[') end = typeGroupEnd(src, token.start);
+ else if (token.kind === '[') end = strictly ? strictBracketEnd(token, true) : typeGroupEnd(src, token.start);
else return end;
}
return -1;
@@ -4584,8 +4668,10 @@ function returnTypeEnd(src, from) {
const token = at(k);
switch (token.kind) {
case 'word': return wordType(token, k);
- case 'string': case 'template': case 'number': case '*': return token.end;
- case '{': case '[': case '(': return typeGroupEnd(src, token.start);
+ case 'string': case 'number': case '*': return token.end;
+ // A template's substitutions are blank here, so a strict reading cannot say what they hold.
+ case 'template': return strictly ? -1 : token.end;
+ case '{': case '[': case '(': return strictly ? strictGroupEnd(token) : typeGroupEnd(src, token.start);
// reScanAsteriskEqualsToken and reScanQuestionToken: `*=` is a `*` and then `=`, `??` two `?`.
case '*=': return token.start + 1;
case '??': return jsdocNullable(token.start + 1);
@@ -4616,6 +4702,7 @@ function returnTypeEnd(src, from) {
// parseJSDocFunctionType: `function(…)` and maybe `: type`; `function` alone is a name.
const open = at(token.end);
if (open.kind !== '(') return token.end;
+ if (strictly) return -1;
const end = typeGroupEnd(src, open.start);
return end !== -1 && at(end).kind === ':' ? typeOrPredicate(at(end).end) : end;
}
@@ -4655,8 +4742,8 @@ function returnTypeEnd(src, from) {
const typeArgumentsOnLine = (end, required) => {
const open = at(end);
if (open.kind !== '<' || open.newline) return end;
- const close = typeAnglesEnd(src, open.start);
- return close !== -1 ? close : required ? -1 : end;
+ const close = strictly ? strictTypeArgumentsEnd(open) : typeAnglesEnd(src, open.start);
+ return close !== -1 ? close : required || strictly ? -1 : end;
};
// parseTypeQuery, after `typeof`: a name, then type arguments on its line.
const typeQuery = (k) => {
@@ -4665,11 +4752,50 @@ function returnTypeEnd(src, from) {
};
// parseImportType, from its `import`: `import(…)`, then maybe `.` and a name, then type arguments on the line.
const importType = (k) => {
+ if (strictly) return -1;
const open = at(at(k).end);
let end = open.kind === '(' ? typeGroupEnd(src, open.start) : -1;
if (end !== -1 && at(end).kind === '.') end = entityName(at(end).end);
return end === -1 ? -1 : typeArgumentsOnLine(end, true);
};
+ // The strict readings of a group (`strictly` above zero), each the index just past it where TypeScript parses the whole of it, or -1. parseParenthesizedType: a type and
+ // the `)`. parseTupleType (`index` false): no element, or types with a `,` between them and maybe after the last (a named or rest element is not read). An array or an
+ // indexed access after a type (`index` true): nothing, or one type. parseTypeLiteral: `{}` alone. parseTypeArgumentsOfTypeReference: types with a `,` between them and
+ // maybe after the last, then the `>` (TypeScript parses `[A, B,]` and `T<U,>`).
+ const strictGroupEnd = (token) => {
+ if (token.kind === '(') {
+ const end = type(token.end, false);
+ return end !== -1 && at(end).kind === ')' ? at(end).end : -1;
+ }
+ if (token.kind === '[') return strictBracketEnd(token, false);
+ const close = at(token.end);
+ return close.kind === '}' ? close.end : -1;
+ };
+ const strictBracketEnd = (token, index) => {
+ let next = at(token.end);
+ if (next.kind === ']') return next.end;
+ for (;;) {
+ const end = type(next.start, false);
+ if (end === -1) return -1;
+ next = at(end);
+ if (next.kind === ']') return next.end;
+ if (index || next.kind !== ',') return -1;
+ next = at(next.end);
+ if (next.kind === ']') return next.end;
+ }
+ };
+ const strictTypeArgumentsEnd = (open) => {
+ let next = at(open.end);
+ for (;;) {
+ const end = type(next.start, false);
+ if (end === -1) return -1;
+ next = at(end);
+ if (next.kind === '>') return next.end;
+ if (next.kind !== ',') return -1;
+ next = at(next.end);
+ if (next.kind === '>') return next.end;
+ }
+ };
return typeOrPredicate(from);
}
@@ -4836,8 +4962,8 @@ function hasDeclarationBody(rest, from) {
* and `/\(/` do not count). `<` / `>` are never counted: JSX and TypeScript generics make them
* legitimately unbalanced.
*/
-function hasUnbalancedBrackets(code) {
- const bare = blankLiterals(code);
+function hasUnbalancedBrackets(code, views = null) {
+ const bare = views && typeof views.literal === 'string' ? views.literal : blankLiterals(code);
const stack = [];
const pairs = { ')': '(', ']': '[', '}': '{' };
for (const ch of bare) {
@@ -4861,7 +4987,12 @@ const DANGLING_TAIL = new RegExp(String.raw`(?:=>|\?\.|[.,?:=&|^~*%<]|(?<!\+)\+|
* export default () => <div>Loading const note = `unfinished const total = count *
* so hasUnbalancedBrackets cannot see these cuts. A complete module ends in plain code.
*/
-function endsMidStatement(code) {
+function endsMidStatement(code, views = null) {
+ // A parser's views (see hasDefaultExport) come from a parse with no diagnostic, which stops inside no string, template, comment or JSX element; what is left to
+ // ask is the token the file ends on, read from its literal view and the ends of its regexes and JSX tags.
+ if (views && typeof views.literal === 'string') {
+ return DANGLING_TAIL.test(views.literal) || hasDanglingFinalOperator(views.literal.split(''), views.regexEnds, views.jsxTagEnds);
+ }
const src = String(code || '');
const out = src.split('');
const regexEnds = new Set();
@@ -4917,9 +5048,11 @@ const BARE_ELLIPSIS_LINE = new RegExp(String.raw`^${WS_SINGLE_LINE}*(\.\.\.|…)
* @param {string} code
* @returns {string|null}
*/
-function findElisionMarker(code) {
+function findElisionMarker(code, views = null) {
const src = String(code || '');
- for (const { text } of commentRanges(src)) {
+ // A parser's views (see hasDefaultExport) carry the page's comments and its executable view.
+ const parsed = views && typeof views.keep === 'string' && Array.isArray(views.comments);
+ for (const { text } of parsed ? views.comments : commentRanges(src)) {
// The comment without its delimiters, or a JSDoc block's leading `*` on each line — so
// /**
// * TODO implement save
@@ -4943,7 +5076,7 @@ function findElisionMarker(code) {
// always fails closed as a placeholder. The text alone cannot reliably distinguish every legal
// multiline spread/rest from an elided block without a full parser, so generated code must write
// the spread and operand together: `...rows`, not `...` followed by `rows` on the next line.
- if (bareEllipsisElidesCode(blankNonCodePreservingTemplateExpressions(src))) return 'a bare `...` line standing in for code';
+ if (bareEllipsisElidesCode(parsed ? views.keep : blankNonCodePreservingTemplateExpressions(src))) return 'a bare `...` line standing in for code';
return null;
}
diff --git a/plugins/model-apps/scripts/lib/typescript-compiler.js b/plugins/model-apps/scripts/lib/typescript-compiler.js
index 9e96b3768..c6ade41c0 100644
--- a/plugins/model-apps/scripts/lib/typescript-compiler.js
+++ b/plugins/model-apps/scripts/lib/typescript-compiler.js
@@ -8,10 +8,10 @@
// brotli-compressed (scripts/vendor/typescript/, built by _vendor-build/build-typescript.js; PROVENANCE.json pins the npm
// tarball, the source file and every derived hash).
//
-// Loaded LAZILY, once per process, and only when a page is compiled: unpacking takes ~15 ms and evaluating ~200 ms, with
-// ~20 MB of heap, which a run that compiles nothing should not pay. The unpacked bytes are checked against the provenance
-// before they are evaluated: a vendored file that was edited, truncated or swapped fails closed with its hash, rather than
-// compiling pages with an unknown compiler.
+// Loaded LAZILY, once per process, and only when a page is compiled — or read by the parser check (typescript-views.js), which asks it about a page on which the
+// lexer guessed: unpacking takes ~15 ms and evaluating ~200 ms, with ~20 MB of heap, which a run that compiles nothing and meets no such page should not pay. The
+// unpacked bytes are checked against the provenance before they are evaluated: a vendored file that was edited, truncated or swapped fails closed with its hash,
+// rather than compiling pages with an unknown compiler.
//
// Evaluated in THIS realm as the body of a function — the file is a plain script whose top-level `var ts` then becomes the
// function's local, returned to the caller — rather than in a separate `vm` context: objects from another realm would make
diff --git a/plugins/model-apps/scripts/lib/typescript-views.js b/plugins/model-apps/scripts/lib/typescript-views.js
new file mode 100644
index 000000000..7460b9544
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/typescript-views.js
@@ -0,0 +1,220 @@
+'use strict';
+// The two views of a page that the lexer gives (source-literals.js: blankLiterals and blankNonCodePreservingTemplateExpressions), built from TypeScript's own parse of
+// the page — so that a reading the lexer had to guess at can be checked against the parser's (pageref-resolver.js, lexNavigation).
+//
+// WHY. The lexer has no parser, so some of what it decides is a guess (a `/` after a `}`, a `<` that opens an element or type parameters, …), and it says where
+// (`onAmbiguity`). Where a guess was wrong, its view of the page — which characters are code, which are a string's, a comment's, a regex's or JSX text — is wrong
+// from there on, so the navigation oracle trusts nothing at or after the first guess. A parser settles every one of those guesses, and the plugin ships one: the
+// TypeScript compiler the pages are compiled with (typescript-compiler.js, 5.8, the version the maker portal compiles with). It is loaded lazily, and only for a
+// page on which the lexer guessed — pages that do are rare, so the cost (~200 ms and ~20 MB once per process, a few milliseconds a page) is paid by those alone.
+//
+// WHAT IT BUILDS. The same two views the lexer builds, character for character, from the tokens of TypeScript's parse (every token of the tree, read with the
+// compiler's `getChildren`, and the comments in the trivia before each one):
+// - a string's body is blanked between its quotes (a JSX attribute's too); a template's text and its `${` and `}` are blanked, and its substitutions are code in
+// the executable view (`keep`), where the `}` that closes one becomes `;`, and blank in the literal view; a regex's body is blanked between its slashes, its
+// flags kept; JSX text is blanked; a comment, and a hashbang at offset 0, are blanked;
+// - blanking writes a space for every character but a line terminator, which stays.
+// Where TypeScript reports any parse diagnostic, or its parse cannot be read (an exception), there is no view: the page is not one the parser vouches for.
+//
+// WHERE TYPESCRIPT IS NOT THE ONLY READER. Other tools read a page too — Babel's parser and esbuild compile TSX — and TypeScript's parser is more lenient than the
+// language, and than theirs, in a few places. There the parse vouches for nothing either, and the lexer's reading (its frontier) stands, for every consumer alike —
+// told from the parse itself, not from the lexer, whose earlier misread can hide what comes after it:
+// - a JSX attribute string after trivia (`x= '…'`) that holds a backslash: TypeScript scans it as a JavaScript string, with escapes — it scans a JSX string, with none,
+// only where the quote follows the `=` at once (scanJsxAttributeValue) — and Babel and esbuild as a JSX string, so the two end it at different quotes and read
+// different code after it: `<C x= '\'/>;//' />; navigateTo(…)` holds a call to TypeScript, and a comment to Babel;
+// - grammar the parser takes and leaves to the checker, which Babel's parser refuses: a word that strict code reserves used as a name (`await`, `yield`, `let`,
+// `static`, … — a module is strict code; https://tc39.es/ecma262/#sec-keywords-and-reserved-words) or a reserved word used as one (`type X = if`), outside the
+// places a keyword may name something (a property, a member, a JSX tag: isIdentifierName); a JSDoc type (`?T`, `T!`, `*`); a type predicate outside a return
+// type (`asserts x`); `readonly` before a type that is no array or tuple; and an empty list of type arguments or type parameters (`A<>`).
+const { loadVendoredTypeScript } = require('./typescript-compiler.js');
+const { blankNonCodePreservingTemplateExpressions, isLineTerminator } = require('./source-literals.js');
+
+// The views of the last sources asked about: the oracle lexes one source several times per call (resolve, stray, residual), and each would parse it again.
+const CACHE_LIMIT = 8;
+const cache = new Map();
+
+// The tests that hold the LEXER to its own rules — what it reads for certain, what it reports as a guess, and what a guess costs a page when nothing else can
+// settle it — read pages with the lexer alone: they turn the parser off for their process (`setParserCheck(false)`), or for a script they run, with
+// MODEL_APPS_LEXER_ALONE=1 in its environment. Everything else runs with it on. Off, the gates only refuse more: the lexer's guesses stand, as they did.
+let parserCheck = process.env.MODEL_APPS_LEXER_ALONE !== '1';
+function setParserCheck(enabled) {
+ parserCheck = Boolean(enabled);
+}
+
+/**
+ * The lexer's two views of `src`, built from TypeScript's parse of it as a `.tsx` file, or null where TypeScript reports a parse diagnostic or cannot be loaded.
+ * @param {string} src
+ * @param {{ ts?: object }} [options] `ts`: a TypeScript namespace to parse with (a test seam; the vendored compiler otherwise)
+ * @returns {null | { literal: string, keep: string, comments: Array<{ start: number, end: number, text: string }>, regexEnds: Set<number>, jsxTagEnds: Set<number> }}
+ */
+function typescriptViews(src, { ts = null } = {}) {
+ if (!ts && !parserCheck) return null;
+ const text = String(src == null ? '' : src);
+ if (!ts && cache.has(text)) return cache.get(text);
+ let views = null;
+ try {
+ views = buildViews(ts || loadVendoredTypeScript(), text);
+ } catch {
+ // Fail closed: a compiler that cannot be loaded (its provenance check failed) or a parse that cannot be walked vouches for nothing, and the lexer's guesses stand.
+ views = null;
+ }
+ if (!ts) {
+ if (cache.size >= CACHE_LIMIT) cache.delete(cache.keys().next().value);
+ cache.set(text, views);
+ }
+ return views;
+}
+
+function buildViews(ts, src) {
+ const sf = ts.createSourceFile('page.tsx', src, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+ if (sf.parseDiagnostics.length > 0) return null;
+ const literal = src.split('');
+ const keep = src.split('');
+ // What the lexer reports besides its views, for the structure gate (page-structure.js): every comment (commentRanges), the closing `/` of every regex and the `>` of
+ // every JSX tag (endsMidStatement: a file may end on one of those, and on no other `/` or `>`).
+ const comments = [];
+ const regexEnds = new Set();
+ const jsxTagEnds = new Set();
+ const blank = (from, to, views) => {
+ for (let k = from; k < to; k += 1) {
+ if (isLineTerminator(src[k])) continue;
+ for (const view of views) view[k] = ' ';
+ }
+ };
+ const both = [literal, keep];
+ // A comment can stand in the trivia of more than one leaf of the tree (an empty list of type arguments starts where the next token's trivia does), so each is
+ // taken once.
+ const seen = new Set();
+ const comment = (from, to) => {
+ if (seen.has(from)) return;
+ seen.add(from);
+ blank(from, to, both);
+ comments.push({ start: from, end: to, text: src.slice(from, to) });
+ };
+ // A hashbang is trivia to TypeScript's scanner to the end of its line, and the comment ranges below begin after it.
+ if (src.startsWith('#!')) {
+ let end = 2;
+ while (end < src.length && !isLineTerminator(src[end])) end += 1;
+ comment(0, end);
+ }
+ const JSX_TAGS = new Set([ts.SyntaxKind.JsxOpeningElement, ts.SyntaxKind.JsxClosingElement, ts.SyntaxKind.JsxSelfClosingElement, ts.SyntaxKind.JsxOpeningFragment,
+ ts.SyntaxKind.JsxClosingFragment]);
+ // Set where the parse holds what another reader reads differently or refuses (WHERE TYPESCRIPT IS NOT THE ONLY READER, above): the parse then vouches for nothing.
+ let otherReaders = false;
+ const visit = (node) => {
+ // JSDoc is held as a child of the node it documents and is also the leading trivia of its first token, where it is blanked as the comment it is.
+ if (otherReaders || ts.isJSDoc(node)) return;
+ if (readAnotherWay(ts, src, sf, node)) {
+ otherReaders = true;
+ return;
+ }
+ const children = node.getChildren(sf);
+ if (children.length > 0 && !ts.isToken(node)) {
+ for (const child of children) visit(child);
+ return;
+ }
+ token(node);
+ };
+ const token = (node) => {
+ const start = node.getStart(sf);
+ // The comments in the trivia before the token: those on the line of the token before it (TypeScript's "trailing" ranges) and those after a line break (its
+ // "leading" ones) — getLeadingCommentRanges alone starts collecting only at a line break. A JSX text token has no trivia: its own text, a `//` in it included,
+ // is text.
+ if (node.pos < start && node.kind !== ts.SyntaxKind.JsxText && node.kind !== ts.SyntaxKind.JsxTextAllWhiteSpaces) {
+ for (const range of [...(ts.getTrailingCommentRanges(src, node.pos) || []), ...(ts.getLeadingCommentRanges(src, node.pos) || [])]) {
+ if (range.end <= start) comment(range.pos, range.end);
+ }
+ }
+ const end = node.end;
+ if (node.kind === ts.SyntaxKind.GreaterThanToken && node.parent && JSX_TAGS.has(node.parent.kind)) jsxTagEnds.add(start);
+ switch (node.kind) {
+ case ts.SyntaxKind.StringLiteral:
+ case ts.SyntaxKind.NoSubstitutionTemplateLiteral:
+ blank(start + 1, end - 1, both);
+ break;
+ case ts.SyntaxKind.TemplateHead:
+ // `text${`: the text and the `${` are blank in both views; the substitution after it is code in `keep`.
+ blank(start + 1, end, both);
+ break;
+ case ts.SyntaxKind.TemplateMiddle:
+ case ts.SyntaxKind.TemplateTail: {
+ // `}text${` or `}text\``: the `}` that closes a substitution is `;` in `keep` (so two substitutions with only text between them cannot read as one call).
+ literal[start] = ' ';
+ keep[start] = ';';
+ blank(start + 1, node.kind === ts.SyntaxKind.TemplateTail ? end - 1 : end, both);
+ break;
+ }
+ case ts.SyntaxKind.RegularExpressionLiteral: {
+ const close = src.lastIndexOf('/', end - 1);
+ blank(start + 1, close, both);
+ regexEnds.add(close);
+ break;
+ }
+ case ts.SyntaxKind.JsxText:
+ case ts.SyntaxKind.JsxTextAllWhiteSpaces:
+ blank(start, end, both);
+ break;
+ default:
+ break;
+ }
+ };
+ visit(sf);
+ if (otherReaders) return null;
+ // A template's substitutions are code only in `keep`: in the literal view the whole of a template between its back-ticks is blank.
+ const templates = (node) => {
+ if (node.kind === ts.SyntaxKind.TemplateExpression || node.kind === ts.SyntaxKind.TemplateLiteralType) {
+ blank(node.getStart(sf) + 1, node.end - 1, [literal]);
+ return;
+ }
+ ts.forEachChild(node, templates);
+ };
+ templates(sf);
+ comments.sort((a, b) => a.start - b.start);
+ return { literal: literal.join(''), keep: keep.join(''), comments, regexEnds, jsxTagEnds };
+}
+
+// Whether `node` of the parse of `src` is read another way, or refused, by another reader (WHERE TYPESCRIPT IS NOT THE ONLY READER, above).
+function readAnotherWay(ts, src, sf, node) {
+ const kind = node.kind;
+ const SK = ts.SyntaxKind;
+ if (kind === SK.StringLiteral && node.parent && node.parent.kind === SK.JsxAttribute && node.parent.initializer === node) {
+ // `x='…'` (the quote right after the `=`) is a JSX string to every reader; a comment cannot end in `=`, so a `=` right before the quote is the attribute's.
+ const start = node.getStart(sf);
+ return src[start - 1] !== '=' && src.slice(start, node.end).includes('\\');
+ }
+ if (kind === SK.Identifier) {
+ // identifierToKeywordKind: the keyword the name spells, written with an escape or not (`\u0061wait` is `await`).
+ const keyword = ts.identifierToKeywordKind(node);
+ if (keyword === undefined || ts.isIdentifierName(node)) return false;
+ return (keyword >= SK.FirstReservedWord && keyword <= SK.LastReservedWord) || (keyword >= SK.FirstFutureReservedWord && keyword <= SK.LastFutureReservedWord)
+ || keyword === SK.AwaitKeyword;
+ }
+ // A JSDoc type outside a JSDoc comment (visit does not enter those): JSDocAllType, JSDocNullableType and the rest, which only TypeScript parses in a .tsx file.
+ if (kind >= SK.FirstJSDocNode && kind <= SK.LastJSDocNode) return true;
+ if (kind === SK.TypePredicate) return !(node.parent && ts.isFunctionLike(node.parent) && node.parent.type === node);
+ if (kind === SK.TypeOperator && node.operator === SK.ReadonlyKeyword) return !ts.isArrayTypeNode(node.type) && !ts.isTupleTypeNode(node.type);
+ return (node.typeArguments !== undefined && node.typeArguments !== null && node.typeArguments.length === 0)
+ || (node.typeParameters !== undefined && node.typeParameters !== null && node.typeParameters.length === 0);
+}
+
+/**
+ * The lexer's executable view of `src` and its first guess (`onAmbiguity`: { at, kind }, or null), and — where it guessed — the parser's views of the page
+ * (typescriptViews), which settle the guess: null where the lexer did not guess, where it guessed a JSX attribute string after trivia (no parser settles that one), and
+ * where typescriptViews has none. The one place the navigation oracle (pageref-resolver.js) and the structure gate (page-structure.js) decide which reading stands,
+ * so the two never decide it differently.
+ * @param {string} src
+ * @returns {{ keep: string, frontier: null | { at: number, kind: string }, views: null | object }}
+ */
+function guessedPageViews(src) {
+ let frontier = null;
+ let jsxAttribute = false;
+ const keep = blankNonCodePreservingTemplateExpressions(src, {
+ onAmbiguity: (at, kind) => {
+ if (kind === 'jsx-attribute') jsxAttribute = true;
+ if (!frontier || at < frontier.at) frontier = { at, kind };
+ },
+ });
+ return { keep, frontier, views: frontier !== null && !jsxAttribute ? typescriptViews(src) : null };
+}
+
+module.exports = { typescriptViews, guessedPageViews, setParserCheck };
diff --git a/plugins/model-apps/scripts/lib/verify-spec.js b/plugins/model-apps/scripts/lib/verify-spec.js
index 73812e271..875438d21 100644
--- a/plugins/model-apps/scripts/lib/verify-spec.js
+++ b/plugins/model-apps/scripts/lib/verify-spec.js
@@ -14,7 +14,7 @@ const { sitemapEntityTables } = require('./app-spec.js');
const { decodeXmlEntities, liveNavEntries, XML_TAG, XML_ATTR } = require('./sitemap-pages.js');
const { normalizePageSource, relationshipSchemaName, manyToManySchemaName, SDK_ROLE_MARKER, canonicalPersonaName, bpfUniqueName, BPF_ROLE_ACCESS, generatedTabName, generatedSectionName, formColumnsOf, formLayoutNames, subgridRelationshipName, normalizeLanguageCode, isLocalizedLabelMap } = require('./app-spec.js');
const { sameRelationship, compareRelationship, describeRelationship, describeIncomplete } = require('./relationship-metadata.js');
-const { resolveExistingFormId, resolveRoleBusinessUnit, roleBuClause, appUniqueName, businessRuleFilter, bpfFilter, viewDef, dashboardsInSolution, findDashboardsByName, findPinnedDashboard } = require('./sdk-build.js');
+const { resolveExistingFormId, resolveRoleBusinessUnit, roleBuClause, appUniqueName, businessRuleFilter, bpfFilter, viewDef, dashboardsInSolution, findDashboardsByName, findPinnedDashboard, webResourceContentState } = require('./sdk-build.js');
const { DASHBOARD_LAUNCHER_URL, isDashboardLauncherUrl, subAreaTargetKey, specSubAreaTargetKey, specSubAreas, chromeByTargetKey, keepsLiveValue } = require('./sitemap-merge.js');
// Recorded on an icon check the build's keep rule satisfies (keepsLiveValue, sitemap-merge.js).
const KEPT_BY_DESIGNER = 'kept as the environment has it: changed in the designer since the spec\u2019s baseline, which the spec still matches';
@@ -1267,6 +1267,35 @@ async function verifySpec(spec, read, opts = {}) {
});
}
+ // Web resources: each declared one exists and — unless it is `external`, a shared web resource the build reuses as it finds it and never
+ // writes — holds the content the spec gives it, compared exactly as the build compares it (webResourceContentState, sdk-build.js). A
+ // rebuild never writes the content of a web resource that exists (references/app-spec-schema-advanced.md), so a content edit that was not
+ // recreated would otherwise verify PASS while the old script runs. Best-effort like the command check: only when the reader can read a web
+ // resource (`webResource(name)` -> { id, content } or null). A read that fails is a failed check, as there; a spec content this machine
+ // cannot read (a contentPath that is not there) decides nothing, so it is unverified; and a web resource whose phase the build did not
+ // run is reported as phase-skipped, as a business rule is.
+ if (typeof read.webResource === 'function') {
+ const webResourcesPhaseRan = !ranPhases || ranPhases.has('web-resources');
+ plan.each(spec.webResources || [], async ({ add, phaseSkipped, unverified }, resources) => {
+ for (const wr of resources) {
+ if (!wr || typeof wr.name !== 'string' || !wr.name) continue;
+ if (!webResourcesPhaseRan) { phaseSkipped.push(`web-resource:${wr.name}`); continue; }
+ let row;
+ try {
+ row = await read.webResource(wr.name);
+ } catch (err) {
+ add('web-resource', wr.name, false, `could not be read: ${(err && err.message) || err}`);
+ continue;
+ }
+ if (!row) { add('web-resource', wr.name, false, 'not found'); continue; }
+ if (wr.external === true) { add('web-resource', wr.name, true); continue; }
+ const compared = webResourceContentState(wr, opts.appDir, row.content);
+ if (compared.state === 'unknown') { unverified.push(`web-resource:${wr.name} (its content was not compared: ${compared.reason})`); continue; }
+ add('web-resource', wr.name, compared.state === 'same', compared.state === 'same' ? '' : "its deployed content differs from the spec's — a rebuild does not write the content of a web resource that exists; delete it (or tear the app down) and build again to deploy it");
+ }
+ });
+ }
+
// Business rules. A rule that EXISTS is not a rule that RUNS: a Draft (statecode 0) rule is inert,
// and a duplicate means the same logic fires twice. Both are states the BUILD can legitimately end
// in without failing — activation is best-effort, and the SDK's fallback can leave a duplicate it
diff --git a/plugins/model-apps/scripts/list-custom-apis.js b/plugins/model-apps/scripts/list-custom-apis.js
index a9d621a4a..428f1e0de 100644
--- a/plugins/model-apps/scripts/list-custom-apis.js
+++ b/plugins/model-apps/scripts/list-custom-apis.js
@@ -33,7 +33,6 @@ const {
validateFlags,
emitResult,
} = require('./lib/dataverse-auth');
-const { exitIfCustomApiDisabled } = require('./lib/feature-flags');
const { odataLit } = require('./lib/odata');
const { makeWritesBlocking } = require('./lib/output-redaction.js');
@@ -219,10 +218,9 @@ function supportsApiParameters(api, envUrl) {
}
async function main() {
- // Feature gate first (fail closed) — see lib/feature-flags.js. Exit 3 = "feature off", distinct
- // from 1 = runtime/usage error, so a caller can tell "not released" from "it broke".
- exitIfCustomApiDisabled();
-
+ // No feature gate: Custom API discovery is always available. The `custom-api` flag that once
+ // gated it here (exit 3 while OFF) was removed after releases shipped with it on, so
+ // GENPAGE_ENABLE_CUSTOM_API is ignored.
const argv = process.argv.slice(2);
const { positional, flags } = parseArgs(argv);
const USAGE = 'Usage: node list-custom-apis.js <envUrl> [--entities <logicalName1,logicalName2>]';
diff --git a/plugins/model-apps/scripts/list-dataverse-operations.js b/plugins/model-apps/scripts/list-dataverse-operations.js
new file mode 100644
index 000000000..952b3b477
--- /dev/null
+++ b/plugins/model-apps/scripts/list-dataverse-operations.js
@@ -0,0 +1,117 @@
+#!/usr/bin/env node
+'use strict';
+// Lists the BUILT-IN Dataverse operations a generative page may bind — exactly WhoAmI and RetrieveVersion — from the reviewed catalogue in
+// lib/dataverse-operations.js. The genpage-customapi-builder agent offers them to the maker beside (not inside) the Custom APIs that
+// list-custom-apis.js discovers, and writes a binding only for an operation the maker selects.
+//
+// It asks the environment NOTHING: no token, no request, no $metadata read, so it takes no environment URL. The catalogue is what is offered, not
+// a check that an environment has an operation, that the page player can call it, or that the signed-in user may — every answer says so
+// (`verification`), and a page's first call can still answer 404. See references/dataverse-operations.md.
+//
+// Usage:
+// node scripts/list-dataverse-operations.js (no arguments and no options)
+//
+// Exit status, stdout and stderr — checked in this order:
+// 3 feature flag "dataverse-operations" is OFF (also when an argument was given): stdout empty; stderr the one gate line
+// (lib/feature-flags.js dataverseOperationsDisabledMessage).
+// 1 an argument was given: stdout empty; stderr "Usage: node scripts/list-dataverse-operations.js".
+// 1 the catalogue could not be read, or is not exactly the reviewed pair: stdout empty; stderr
+// "The built-in operation catalogue could not be read. No built-in operations were offered."
+// 0 stdout one JSON line:
+// { "ok": true, "catalogueVersion": 1,
+// "verification": { "mode": "catalogue-only", "environment": "not-checked", "runtime": "not-checked", "privileges": "not-checked" },
+// "operations": [ { "name": "WhoAmI", "displayName": "Current Dataverse identity", "isFunction": true, "bindingType": "Global",
+// "parameters": [], "parameterKinds": {},
+// "response": { "typeName": "Microsoft.Dynamics.CRM.WhoAmIResponse",
+// "properties": { "BusinessUnitId": "Edm.Guid", "UserId": "Edm.Guid", "OrganizationId": "Edm.Guid" } },
+// "outputPrivacy": "identity", "invocation": "user-triggered", "requiresExplicitSelection": true },
+// { "name": "RetrieveVersion", …, "response": { "typeName": "Microsoft.Dynamics.CRM.RetrieveVersionResponse",
+// "properties": { "Version": "Edm.String" } }, "outputPrivacy": "service-version", … } ] }
+// Only `name`, `isFunction`, `displayName` and `parameterKinds` of an operation ever go into a page's actionBindings (lib/dataverse-operations.js
+// toActionBinding); the other members describe the operation to the author.
+const { makeWritesBlocking } = require('./lib/output-redaction.js');
+const { exitIfDataverseOperationsDisabled } = require('./lib/feature-flags.js');
+
+const USAGE = 'Usage: node scripts/list-dataverse-operations.js';
+const CATALOGUE_UNAVAILABLE = 'The built-in operation catalogue could not be read. No built-in operations were offered.';
+
+// The pair this command may offer, held here as well as in the catalogue: a catalogue that answers anything else — a third operation, another
+// order or spelling, a weakened contract — is a failure of the producer, and the command offers NOTHING rather than a partial or widened list.
+const REVIEWED_PAIR = ['WhoAmI', 'RetrieveVersion'];
+const DESCRIPTOR_KEYS = ['name', 'displayName', 'isFunction', 'bindingType', 'parameters', 'parameterKinds', 'response', 'outputPrivacy', 'invocation', 'requiresExplicitSelection'];
+const VERIFICATION_KEYS = ['mode', 'environment', 'runtime', 'privileges'];
+
+const isEntry = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
+const sameKeys = (value, keys) => isEntry(value) && Object.keys(value).length === keys.length && keys.every((key) => Object.prototype.hasOwnProperty.call(value, key));
+
+// The operation as this command prints it — its own copy, members in the documented order — or null when it is not a reviewed, unbound,
+// zero-input Function offered for a user-triggered call that the maker must select.
+function offered(operation, name) {
+ if (!sameKeys(operation, DESCRIPTOR_KEYS) || operation.name !== name) return null;
+ const { response } = operation;
+ if (operation.isFunction !== true || operation.bindingType !== 'Global' || operation.invocation !== 'user-triggered' || operation.requiresExplicitSelection !== true) return null;
+ if (!Array.isArray(operation.parameters) || operation.parameters.length !== 0 || !sameKeys(operation.parameterKinds, [])) return null;
+ if (typeof operation.displayName !== 'string' || !operation.displayName || typeof operation.outputPrivacy !== 'string' || !operation.outputPrivacy) return null;
+ if (!sameKeys(response, ['typeName', 'properties']) || typeof response.typeName !== 'string' || !isEntry(response.properties)) return null;
+ const properties = Object.entries(response.properties);
+ if (!properties.length || properties.some(([, type]) => typeof type !== 'string' || !/^Edm\.[A-Za-z]+$/.test(type))) return null;
+ return {
+ name: operation.name,
+ displayName: operation.displayName,
+ isFunction: true,
+ bindingType: 'Global',
+ parameters: [],
+ parameterKinds: {},
+ response: { typeName: response.typeName, properties: Object.fromEntries(properties) },
+ outputPrivacy: operation.outputPrivacy,
+ invocation: 'user-triggered',
+ requiresExplicitSelection: true,
+ };
+}
+
+// The success body, or null when the catalogue cannot be loaded or is not exactly the reviewed pair. The module is loaded here, after the gate
+// and the arguments, so a disabled run never depends on it.
+function listing() {
+ let catalogue;
+ try {
+ catalogue = require('./lib/dataverse-operations.js').getDataverseOperationCatalogue();
+ } catch {
+ return null;
+ }
+ if (!sameKeys(catalogue, ['catalogueVersion', 'verification', 'operations']) || catalogue.catalogueVersion !== 1) return null;
+ const { verification, operations } = catalogue;
+ if (!sameKeys(verification, VERIFICATION_KEYS) || verification.mode !== 'catalogue-only'
+ || ['environment', 'runtime', 'privileges'].some((key) => verification[key] !== 'not-checked')) return null;
+ if (!Array.isArray(operations) || operations.length !== REVIEWED_PAIR.length) return null;
+ const listed = operations.map((operation, index) => offered(operation, REVIEWED_PAIR[index]));
+ if (listed.some((operation) => operation === null)) return null;
+ return {
+ ok: true,
+ catalogueVersion: 1,
+ verification: { mode: 'catalogue-only', environment: 'not-checked', runtime: 'not-checked', privileges: 'not-checked' },
+ operations: listed,
+ };
+}
+
+function main(argv) {
+ // Every path below writes and then ends the process at once: on Linux and macOS a pipe's writes are queued, and the exit would cut them off.
+ makeWritesBlocking(process.stdout, process.stderr);
+ exitIfDataverseOperationsDisabled();
+ if (argv.length) {
+ process.stderr.write(`${USAGE}\n`);
+ process.exit(1);
+ }
+ const body = listing();
+ if (!body) {
+ process.stderr.write(`${CATALOGUE_UNAVAILABLE}\n`);
+ process.exit(1);
+ }
+ process.stdout.write(`${JSON.stringify(body)}\n`);
+ process.exit(0);
+}
+
+if (require.main === module) {
+ main(process.argv.slice(2));
+}
+
+module.exports = { USAGE, CATALOGUE_UNAVAILABLE, REVIEWED_PAIR };
diff --git a/plugins/model-apps/scripts/tests/add-page-to-solution.test.js b/plugins/model-apps/scripts/tests/add-page-to-solution.test.js
index 909e64ecd..a46dc81b7 100644
--- a/plugins/model-apps/scripts/tests/add-page-to-solution.test.js
+++ b/plugins/model-apps/scripts/tests/add-page-to-solution.test.js
@@ -7,6 +7,8 @@ const { spawnSync } = require('node:child_process');
const scriptPath = path.join(__dirname, '..', 'add-page-to-solution.js');
const scriptSrc = fs.readFileSync(scriptPath, 'utf8');
+// How a page joins a solution — the read of its component type and its add — is lib/page-solution.js, shared by every path that adds a page.
+const pageSolutionSrc = fs.readFileSync(path.join(__dirname, '..', 'lib', 'page-solution.js'), 'utf8');
test('adds appmodule (80) with required components', () => {
assert.match(scriptSrc, /APPMODULE_COMPONENT_TYPE\s*=\s*80/);
@@ -15,12 +17,13 @@ test('adds appmodule (80) with required components', () => {
test('discovers connection-reference component type from environment metadata', () => {
assert.match(scriptSrc, /connectionreferences\?\$filter=connectionreferencelogicalname/);
- assert.match(scriptSrc, /EntityDefinitions\(LogicalName=/);
+ assert.match(scriptSrc, /componentTypePath\(logicalName\)/);
+ assert.match(pageSolutionSrc, /EntityDefinitions\(LogicalName=/);
assert.match(scriptSrc, /CONNECTION_REFERENCE_LOGICAL_NAME\s*=\s*'connectionreference'/);
});
test('discovers the GenPage component type from environment metadata', () => {
- assert.match(scriptSrc, /UXAGENTPROJECT_LOGICAL_NAME\s*=\s*'uxagentproject'/);
+ assert.match(pageSolutionSrc, /UXAGENTPROJECT_LOGICAL_NAME\s*=\s*'uxagentproject'/);
assert.match(scriptSrc, /flags\['page-ids'\]/);
});
@@ -125,8 +128,8 @@ test('discovers environment-specific component types for GenPages and connection
});
test('the appmodule is packaged BEFORE any page or connection reference', async () => {
- // Order is load-bearing: adding a uxagentproject to a solution the app is not yet in produces a
- // solution whose page has no owning app.
+ // Order is load-bearing when an app is named: a run that stops part-way must never leave pages in the
+ // solution without the app whose navigation opens them.
const { cli, calls } = harness({ argv: [ENV, 'sol', APP, '--page-ids', P1, '--connection-refs', 'new_sp'] });
await cli.main();
const types = calls.filter((c) => c.path === 'AddSolutionComponent').map((c) => c.body.ComponentType);
@@ -322,3 +325,38 @@ test('the stable app component type and dynamic entity names are pinned', () =>
assert.equal(UXAGENTPROJECT_LOGICAL_NAME, 'uxagentproject');
assert.equal(CONNECTION_REFERENCE_LOGICAL_NAME, 'connectionreference');
});
+
+// --- Pages with no app -------------------------------------------------------
+//
+// A page made into an app that is not the run's own (an app that already existed), or one whose add failed after the page was made, joins the
+// solution on its own: a page is a component of its own, and the app is not one of its required components (the app's navigation names the page,
+// not the other way round). Adding the app as well would put another maker's app into the solution.
+
+test('with no app id, --page-ids adds the pages alone — each as the page table\u2019s type, with its files — and no app', async () => {
+ const { cli, calls, emitted } = harness({ argv: [ENV, 'sol', '--page-ids', `${P1},${P2}`] });
+ await cli.main();
+ assert.equal(emitted.length, 1);
+ assert.equal(emitted[0].ok, true);
+ const adds = calls.filter((c) => c.path === 'AddSolutionComponent').map((c) => [c.body.ComponentId, c.body.ComponentType, c.body.AddRequiredComponents, c.body.SolutionUniqueName]);
+ assert.deepEqual(adds, [[P1, 10372, true, 'sol'], [P2, 10372, true, 'sol']]);
+ assert.deepEqual(emitted[0].payload.added, [{ type: 'uxagentproject', id: P1 }, { type: 'uxagentproject', id: P2 }]);
+});
+
+test('with no app id and nothing to add, the run is a usage error: an app, a page or a connection reference is needed', async () => {
+ const res = spawnSync(process.execPath, [scriptPath, ENV, 'sol'], { encoding: 'utf8' });
+ assert.equal(res.status, 1);
+ assert.match(res.stderr, /Usage:/);
+ assert.equal(res.stdout, '');
+ // A list of separators names nothing: refused, with nothing read or written.
+ const { cli, calls, emitted } = harness({ argv: [ENV, 'sol', '--page-ids', ','] });
+ await cli.main();
+ assert.equal(emitted[0].ok, false);
+ assert.match(emitted[0].payload.message, /Nothing to add: name an app, --page-ids or --connection-refs\. Nothing was added to sol\./);
+ assert.deepEqual(calls, []);
+});
+
+test('an app id given as the third argument is still added first, before its pages', async () => {
+ const { cli, calls } = harness({ argv: [ENV, 'sol', APP, '--page-ids', P1] });
+ await cli.main();
+ assert.deepEqual(calls.filter((c) => c.path === 'AddSolutionComponent').map((c) => c.body.ComponentType), [80, 10372]);
+});
diff --git a/plugins/model-apps/scripts/tests/ambiguity-sweep.test.js b/plugins/model-apps/scripts/tests/ambiguity-sweep.test.js
index ea3404d06..ab0460d03 100644
--- a/plugins/model-apps/scripts/tests/ambiguity-sweep.test.js
+++ b/plugins/model-apps/scripts/tests/ambiguity-sweep.test.js
@@ -27,6 +27,9 @@ const { loadTypescriptOracle, loadBabelOracle, loadBaseLexer } = require('./help
const { tokenVocabulary, programsFor, cleanSourceFile, readingAt, isElement, REGEX_BODY, AFTER_WITH_CALL, CONTINUATIONS, FRAMES, PRODUCER_FRAMES, TRIVIA_SEPARATORS, SIGNATURE_FRAMES, SIGNATURE_ENDINGS, HIDING_ENDINGS, CERTAIN_ELEMENTS, GUESSED_ELEMENTS, HIDDEN_TEXT_ELEMENTS, UNREAD_LIST_ELEMENTS, MEMBER_ELEMENT_FRAMES, NO_MEMBER_ELEMENT_FRAMES, valuedKeywordElements, DECOYS, signaturePages, elementPages, ELEMENT_FRAMES, elementPage, signaturePage, failingLists, LEFT_LISTS, EXACT_DEFAULTS, defaultLists, exactDefaultLists, commentedDefaultLists, commentedConstraintLists, commentedMemberEndings, commentedArrowContinuations, PROSE_SHAPED_LINES, PROSE_OPEN_LINES, PROSE_HIDING_ELEMENTS, PROSE_HIDING_ENDINGS, PROSE_TYPE_ENDINGS, proseElements, KEYWORD_SIGNATURE_HEADS, KEYWORD_HEAD_ELEMENTS, KEYWORD_HIDING_ELEMENTS } = require('./helpers/angle-frames.js');
const { AMBIGUITY_KINDS, blankNonCodePreservingTemplateExpressions } = require('../lib/source-literals.js');
const { extractNavTargets, resolvePageRefs, strayPageRefs, navMalformedRefs, reverseResolveNavIdsReport, navigationFrontier } = require('../lib/pageref-resolver.js');
+// These tests hold the lexer to its own rules — what it reads for certain, what it reports as a guess, and what a guess costs a page — so they read pages with
+// the lexer alone. Where the lexer guesses, the gates ask the TypeScript parser (typescript-views.js), which parser-check.test.js tests.
+require('../lib/typescript-views.js').setParserCheck(false);
const { LONG_KEY, MISREAD_PAGES, ELEMENT_AFTER_OPERATOR_PAGES, ELEMENT_LOOKALIKE_PAGES, FUNCTION_TYPE_PAGES } = require('./helpers/misread-page.js');
const { ANY_SPACE } = require('./helpers/jsx-element-fuzz.js');
const { numberedMemberPages, nestedTextPages, expressionLinePages, literalTagPages, nestedSoupPages, nestedCodePages, nestedTagPages, nestedPairPages, taggedStringPages, importTypePages, accessorNamePages } = require('./helpers/hidden-closing-pages.js');
diff --git a/plugins/model-apps/scripts/tests/app-navigation-build.test.js b/plugins/model-apps/scripts/tests/app-navigation-build.test.js
index 92bfc0f06..9cff2d613 100644
--- a/plugins/model-apps/scripts/tests/app-navigation-build.test.js
+++ b/plugins/model-apps/scripts/tests/app-navigation-build.test.js
@@ -637,21 +637,24 @@ const GOLDEN = {
applyNewTable: { calls: 14, sha: '8d09d30f974d3189825ec14438bdf6d1c00eb75b42088816b4b2bd6edd180d3b' },
applyNewUrl: { calls: 14, sha: 'c90699cef67fb3ec65692205fe42d3c8fe69e0018b96841cbc72c7b8e350a9e9' },
dryLive: { calls: 2, sha: '4234a3bee2b8281a5346821c9eae1218743fae1213c841574d43e43b08e23698' },
- applyNewBesidePages: { calls: 28, sha: '8ed8cfad18ed2b5eb59b29bc1ab9a9d023ad9c30ec8c7a69efe714ef14e7ab78' },
+ // Every build that writes a page adds it to the spec's solution (AB#6443257): one read of the page table's component type before the first page is written, and one AddSolutionComponent per
+ // page the build creates, after the page is written and recorded — in each sequence below that writes pages. Recaptured with that change and nothing else in a sequence moved.
+ applyNewBesidePages: { calls: 30, sha: '817f417836351b9077436fedc2061c778c6caeeead08e4f878e7d01a6b992711' },
// An EXISTING app now takes a changed name and description, so its fetched copy is read once more to compare them: one `getArtifact`
// (a read of the workspace copy — no request to the environment) after the sitemap write. Captured again with the fake's deployed
// app carrying the spec's own header; no other call of the sequence differs, and a new app's is exactly what it was.
- applyExistingBesidePages: { calls: 29, sha: '789bf9a2cdcc1c653fe49a6ff3f363ce73e7d9c255e916a5d810b74f57dd25e3' },
+ applyExistingBesidePages: { calls: 31, sha: 'daca63f3da7fa82a237370ec34a1946d827262939fd9b2d963c88fb0068bc6f7' },
// The same one added read (see above), here before the app step's own push of its sitemap and header.
applyExistingAppStep: { calls: 24, sha: 'c57951fa58f2709965565258ed26693f6567e067b3b0099f36f4e8a59a237749' },
// An EXISTING app whose navigation is pages only — the whole build of it, and its dry run — captured on 2.17.0 with these fakes, before a NEW
// app of pages only could be built: that build's order (pages first) must leave every request of an app that exists as it was.
- applyExistingPagesOnly: { calls: 32, sha: '6ea352b91cba2f7af9d8f4ee784e9bf36cad729705a3965424c0b24f14029cfb' },
- applyExistingPagesInTwoAreas: { calls: 32, sha: '130729c40df45020333dbc83b2d1b25244797a218276aa4dc8ef7ebf9c362515' },
- applyExistingPagesBesideEmpty: { calls: 30, sha: '5948d0defa335ed58e1a54c498e9a92687663cbc35ae3bf60b65f187192589a5' },
+ // Its pages joining the solution are the only requests added since (see above).
+ applyExistingPagesOnly: { calls: 35, sha: '02cbecf7957c95084ffeadb18665c5248de44d190225e0ea05ce58cc9ff6e6e6' },
+ applyExistingPagesInTwoAreas: { calls: 35, sha: '0ccc11e4fa14c99305d09ab13a7f7d7b025d305a6b4918d103b6d4ec1529289d' },
+ applyExistingPagesBesideEmpty: { calls: 32, sha: '22632dff788436d328cd5bbe83d10fd791bf37035d6c66f682e7f4a2ba3c686b' },
dryExistingPagesOnly: { calls: 2, sha: '4234a3bee2b8281a5346821c9eae1218743fae1213c841574d43e43b08e23698' },
// A NEW app whose navigation is pages only, built by creating its pages first (no earlier release built one): every request of that order.
- applyNewPagesOnly: { calls: 23, sha: '6a994ff4984da4a8d32c695a547ec037279af8c2d6ba0713b00bbf06dd0eecb1' },
+ applyNewPagesOnly: { calls: 26, sha: 'd061c6447aadc8645249fa60d1bcd865c6429fdd3ff3ae7f16960b29ea3446c9' },
};
const calledSameAs = (calls, golden, what) => {
@@ -694,7 +697,7 @@ test('a valid navigation — with pages beside the entry, a new app and an exist
});
// The order a NEW app of pages only is built in, request by request: the check's read and the app step's (no app), the icon, the pages — each create
-// recorded in the manifest, which joins the solution — and then the app, ONE create whose push carries the whole navigation, joining the solution with
+// recorded in the manifest, which joins the solution, and each page joining it too — and then the app, ONE create whose push carries the whole navigation, joining the solution with
// its sitemap. No navigation is rewritten afterwards. (The page backend's own requests are its fake's, not the SDK's: they are not among these.)
test('a new app whose navigation is pages only is built with exactly these requests: the pages first, then one create of the app', async () => {
const shape = shapeNamed('a navigation of pages only');
@@ -705,7 +708,8 @@ test('a new app whose navigation is pages only is built with exactly these reque
assert.deepStrictEqual(env.calls.map(([name, kind]) => (name === 'queryRecords' || name === 'findArtifact' || name === 'createArtifact' || name === 'pushArtifact' ? `${name}(${kind})` : name)), [
'findArtifact(app)', 'queryRecords(solution)', 'queryRecords(publisher)', 'createSolution', 'queryRecords(organization)', 'dataverse.get', 'createTable',
'queryRecords(webresource)', 'createWebResource', 'addSolutionComponent', 'findArtifact(app)',
- 'queryRecords(webresource)', 'createWebResource', 'queryRecords(solution)', 'addSolutionComponent', 'updateWebResource', 'addSolutionComponent', 'addSolutionComponent',
+ // The page table's component type is read before the first page is written; each page joins the solution once it is written and recorded.
+ 'queryRecords(webresource)', 'dataverse.get', 'createWebResource', 'queryRecords(solution)', 'addSolutionComponent', 'addSolutionComponent', 'updateWebResource', 'addSolutionComponent', 'addSolutionComponent', 'addSolutionComponent',
'createArtifact(app)', 'pushArtifact(app)', 'addSolutionComponent', 'queryRecords(sitemap)', 'addSolutionComponent',
]);
calledSameAs(env.calls, GOLDEN.applyNewPagesOnly, 'new app, pages only');
diff --git a/plugins/model-apps/scripts/tests/app-spec-keys.test.js b/plugins/model-apps/scripts/tests/app-spec-keys.test.js
index cd4dc17dc..ef38e8a9f 100644
--- a/plugins/model-apps/scripts/tests/app-spec-keys.test.js
+++ b/plugins/model-apps/scripts/tests/app-spec-keys.test.js
@@ -63,6 +63,17 @@ test('spec.design accepts known keys and rejects unknown ones', () => {
assert.ok(validateAppSpec(bad, { profile: 'plan' }).errors.some((e) => /design: unknown key 'accent'/.test(e)));
});
+test('spec.design.style — the maker\u2019s own look in words — is a known key, and must be text that says something', () => {
+ const s = base();
+ s.design = { style: 'navy #0b2545 primary, gold #c9a227 accent, Georgia headings (from: website)', accentColor: '#0b2545' };
+ assert.strictEqual(validateAppSpec(s, { profile: 'plan' }).ok, true, JSON.stringify(validateAppSpec(s, { profile: 'plan' }).errors));
+ for (const style of ['', ' ', 42, ['navy'], { primary: '#0b2545' }, null]) {
+ const bad = base();
+ bad.design = { style };
+ assert.ok(validateAppSpec(bad, { profile: 'plan' }).errors.includes('design.style must be a non-empty string: the look the maker asked for, in words'), JSON.stringify(style));
+ }
+});
+
// Edge cases of navigatesTo, pageInput and design validation --------------------------
test('navigatesTo entry with a missing or non-string targetKey errors (isV2)', () => {
diff --git a/plugins/model-apps/scripts/tests/app-spec-without-tables.test.js b/plugins/model-apps/scripts/tests/app-spec-without-tables.test.js
new file mode 100644
index 000000000..54a1dadaf
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/app-spec-without-tables.test.js
@@ -0,0 +1,79 @@
+'use strict';
+// An App Spec with no tables of its own. A model-driven app need not have one: its navigation can hold only generative pages (an app
+// `apps.js create --page-id` makes), dashboards over tables the environment already has, or URLs. The validator used to refuse every
+// such spec with `at least one entity is required`, in every profile — so the download of such an app wrote its page folders and then
+// stopped without a spec, and no build could make one. A spec is now refused for that only when it has no table AND no navigation entry,
+// which is a spec with nothing to build an app from. The build, the download, verify and teardown of such an app are driven over the
+// real bundle in lifecycle-no-tables-real-bundle.test.js.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const { validateAppSpec, VALIDATION_PROFILES } = require('../lib/app-spec.js');
+
+const REFUSAL = /^at least one entity is required/;
+const oneGroup = (...subAreas) => ({ areas: [{ label: 'Main', groups: [{ label: 'Pages', subAreas }] }] });
+const base = (extra = {}) => ({
+ schemaVersion: 2,
+ solution: { uniqueName: 'ContosoPages', displayName: 'Contoso Pages', publisherPrefix: 'contoso' },
+ app: { name: 'Account Metrics', description: 'Metrics over accounts.' },
+ entities: [],
+ ...extra,
+});
+
+// Every profile a caller validates with: the build's deploy, plan and design, teardown's structural, and the download's plan for a spec
+// it reconstructed from a deployed app.
+const PROFILES = [...VALIDATION_PROFILES.map((profile) => ({ profile })), { profile: 'plan', reconstructed: true }];
+const errorsOf = (spec, opts) => validateAppSpec(JSON.parse(JSON.stringify(spec)), opts).errors;
+
+// The shapes a download writes for an app with no table: a page reading a table the environment has; a dashboard over one, bound by the
+// ids the download read; a URL.
+const VALID = {
+ 'a navigation of one generative page': base({
+ pages: [{ key: 'overview', name: 'Overview', pageId: '7c9e6679-7425-40de-944b-e07fc1f90ae7', dataSources: ['account'], source: { kind: 'tsx', codeFile: 'pages/7c9e6679-7425-40de-944b-e07fc1f90ae7/page.tsx' } }],
+ appShell: oneGroup({ page: 'overview', title: 'Overview' }),
+ }),
+ 'a navigation of one dashboard over a table the environment has': base({
+ dashboards: [{ name: 'Account overview', dashboardId: '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d', tiles: [{ type: 'list', name: 'Accounts', entity: 'account', viewId: '00000000-0000-0000-00aa-000010001001' }] }],
+ appShell: oneGroup({ dashboard: 'Account overview', title: 'Overview' }),
+ }),
+ 'a navigation of one URL': base({ appShell: oneGroup({ url: 'https://contoso.example/help', title: 'Help' }) }),
+};
+
+for (const [name, spec] of Object.entries(VALID)) {
+ test(`an app with no tables is a valid spec in every profile: ${name}`, () => {
+ for (const opts of PROFILES) assert.deepEqual(errorsOf(spec, opts), [], JSON.stringify(opts));
+ });
+}
+
+// NEIGHBOURS: what the rule still refuses, and what it does not hide.
+
+test('a spec with no table and no navigation entry is still refused, in every profile, and the refusal names the way out', () => {
+ const shapes = {
+ 'no appShell': base(),
+ 'appShell.areas is empty': base({ appShell: { areas: [] } }),
+ 'an area with no group': base({ appShell: { areas: [{ label: 'Main', groups: [] }] } }),
+ 'a group with no entry': base({ appShell: oneGroup() }),
+ 'no entities key at all': (() => { const s = base({ appShell: { areas: [] } }); delete s.entities; return s; })(),
+ };
+ for (const [name, spec] of Object.entries(shapes)) {
+ for (const opts of PROFILES) {
+ const refusals = errorsOf(spec, opts).filter((e) => REFUSAL.test(e));
+ assert.equal(refusals.length, 1, `${name} ${JSON.stringify(opts)}`);
+ assert.match(refusals[0], /an app with no tables, an entry in appShell \(a page, a dashboard or a URL\)/);
+ }
+ }
+});
+
+test('a navigation entry the spec cannot resolve is still an entry: the spec is not refused for having no table, and the entry\u2019s own error is reported', () => {
+ // An entry that names a page the spec does not declare, or a table it does not declare, counts as an entry here (there is something
+ // in the navigation), and the navigation's own errors say what is wrong with it.
+ const undeclaredPage = errorsOf(base({ appShell: oneGroup({ page: 'missing', title: 'Missing' }) }), { profile: 'deploy' });
+ assert.ok(!undeclaredPage.some((e) => REFUSAL.test(e)), JSON.stringify(undeclaredPage));
+ assert.ok(undeclaredPage.some((e) => /missing/.test(e)), JSON.stringify(undeclaredPage));
+ const undeclaredTable = errorsOf(base({ appShell: oneGroup({ entity: 'account', title: 'Accounts' }) }), { profile: 'deploy' });
+ assert.ok(undeclaredTable.some((e) => e === "sitemap subArea references unknown entity 'account'"), JSON.stringify(undeclaredTable));
+});
+
+test('a spec with a table needs no navigation, as before: a data-only spec is valid', () => {
+ const dataOnly = base({ entities: [{ schemaName: 'contoso_item', displayName: 'Item', primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name' }, columns: [] }] });
+ for (const opts of PROFILES) assert.deepEqual(errorsOf(dataOnly, opts), [], JSON.stringify(opts));
+});
diff --git a/plugins/model-apps/scripts/tests/apps-real-bundle.test.js b/plugins/model-apps/scripts/tests/apps-real-bundle.test.js
index 6421b59f1..4b27c0d71 100644
--- a/plugins/model-apps/scripts/tests/apps-real-bundle.test.js
+++ b/plugins/model-apps/scripts/tests/apps-real-bundle.test.js
@@ -184,6 +184,7 @@ test('REAL BUNDLE: create without --publish writes the app, its sitemap and the
'POST appsettings',
'POST AddSolutionComponent',
'POST AddSolutionComponent',
+ 'POST AddSolutionComponent',
]);
assert.deepStrictEqual(org.unexpected, []);
assert.deepStrictEqual(org.state.publishes, [], 'the SDK published nothing inside the create');
@@ -214,9 +215,9 @@ test('REAL BUNDLE: create --publish adds exactly one PublishXml, naming the app,
const names = org.writeNames();
assert.deepStrictEqual(names.filter((n) => n === 'POST PublishXml'), ['POST PublishXml']);
assert.strictEqual(names[names.length - 1], 'POST PublishXml', 'the last write');
- // The sequence, in order: the app row, the sitemap, the app and the sitemap into the solution, the publish.
+ // The sequence, in order: the app row, the sitemap, the app, the sitemap and the page into the solution, the publish.
const key = names.filter((n) => ['POST appmodules', 'POST sitemaps', 'POST AddSolutionComponent', 'POST PublishXml'].includes(n));
- assert.deepStrictEqual(key, ['POST appmodules', 'POST sitemaps', 'POST AddSolutionComponent', 'POST AddSolutionComponent', 'POST PublishXml']);
+ assert.deepStrictEqual(key, ['POST appmodules', 'POST sitemaps', 'POST AddSolutionComponent', 'POST AddSolutionComponent', 'POST AddSolutionComponent', 'POST PublishXml']);
assert.deepStrictEqual(org.state.publishes, [result.appId], 'the publish names the app');
assert.strictEqual(org.state.apps[0].componentstate, 0, 'the app is now published');
assert.strictEqual(result.published, true);
@@ -227,11 +228,11 @@ test('REAL BUNDLE: create --publish adds exactly one PublishXml, naming the app,
assert.ok(firstWrite >= 6, 'the script asked about the solution, the pages, the unique name and the language first');
});
-test('REAL BUNDLE: what the platform holds after a create — the app row, the sitemap\u2019s name and id, and the solution\u2019s two components', async () => {
+test('REAL BUNDLE: what the platform holds after a create — the app row, the sitemap\u2019s name and id, and the solution\u2019s three components', async () => {
const org = orgWithPages();
const result = await createApp(args({ description: 'KPIs for the team', publish: true }), client(org), seams);
assert.deepStrictEqual(Object.keys(result).sort(), ['addedToSolution', 'appId', 'dataSources', 'inSolution', 'languageCode', 'name', 'navigation', 'ok', 'pinnedViews', 'published', 'sitemapId', 'solution', 'uniqueName', 'unpublishedChanges']);
- assert.deepStrictEqual([result.published, result.unpublishedChanges, result.inSolution], [true, false, ['app', 'sitemap']]);
+ assert.deepStrictEqual([result.published, result.unpublishedChanges, result.inSolution], [true, false, ['app', 'sitemap', 'pages']]);
assert.strictEqual(result.uniqueName, 'account_metrics_1a2b3c4d');
assert.match(result.appId, GUID);
assert.match(result.sitemapId, GUID);
@@ -254,9 +255,12 @@ test('REAL BUNDLE: what the platform holds after a create — the app row, the s
assert.deepStrictEqual(org.state.components, [
{ solution: 'ContosoCore', objectid: result.appId, type: 80 },
{ solution: 'ContosoCore', objectid: result.sitemapId, type: 62 },
+ // The page, as a component of the page table's type the environment answered (lib/page-solution.js), with its files: AddRequiredComponents.
+ { solution: 'ContosoCore', objectid: PAGE_A, type: 10372 },
]);
const addComponent = org.requests.filter((r) => r.path === '/AddSolutionComponent').map((r) => r.body);
- assert.ok(addComponent.every((b) => b.AddRequiredComponents === false && b.SolutionUniqueName === 'ContosoCore'));
+ assert.deepStrictEqual(addComponent.map((b) => b.AddRequiredComponents), [false, false, true]);
+ assert.ok(addComponent.every((b) => b.SolutionUniqueName === 'ContosoCore'));
});
const SUB_AREA = /<SubArea\b[^>]*>/g;
@@ -337,8 +341,8 @@ test('REAL BUNDLE: create reads each page\'s tables and their default public vie
const components = JSON.stringify(bodies[0]).toLowerCase();
for (const view of [VIEW_ACCOUNT, VIEW_CONTACT]) assert.ok(components.includes(view), `AddAppComponents names the view ${view}: ${components}`);
assert.ok(components.includes(result.sitemapId), 'and the sitemap');
- // The same writes as a create with no views: nothing was added to the sequence.
- assert.deepStrictEqual(org.writeNames(), ['POST appmodules', 'POST sitemaps', 'POST AddAppComponents', 'POST appmodules/appmoduleroles_association/$ref', 'POST appsettings', 'POST AddSolutionComponent', 'POST AddSolutionComponent']);
+ // The same writes as a create with no views: nothing was added to the sequence (the solution adds are the app, its sitemap and its two pages).
+ assert.deepStrictEqual(org.writeNames(), ['POST appmodules', 'POST sitemaps', 'POST AddAppComponents', 'POST appmodules/appmoduleroles_association/$ref', 'POST appsettings', 'POST AddSolutionComponent', 'POST AddSolutionComponent', 'POST AddSolutionComponent', 'POST AddSolutionComponent']);
assert.deepStrictEqual(org.unexpected, []);
});
@@ -407,7 +411,7 @@ test('REAL BUNDLE: two apps of one display name get two unique names, and the se
assert.strictEqual(org.state.apps.length, 2, 'the refused create wrote nothing');
});
-test('REAL BUNDLE: a system solution gets no AddSolutionComponent, and a normal one gets both, case aside', async () => {
+test('REAL BUNDLE: a system solution gets no AddSolutionComponent, and a normal one gets the app, its sitemap and its page, case aside', async () => {
const system = createFakeAppsOrg({ solutions: [{ solutionid: '11111111-1111-4111-8111-111111111111', uniquename: 'Default', friendlyname: 'Default Solution', ismanaged: false }], pages: [{ id: PAGE_A, name: 'Overview' }] });
const r = await createApp(args({ solution: 'default', publish: true }), client(system));
assert.strictEqual(r.ok, true, JSON.stringify(r));
@@ -415,8 +419,26 @@ test('REAL BUNDLE: a system solution gets no AddSolutionComponent, and a normal
assert.ok(!system.writeNames().includes('POST AddSolutionComponent'));
const org = orgWithPages();
const lower = await createApp(args({ solution: 'CONTOSOCORE' }), client(org));
- assert.deepStrictEqual([lower.solution, lower.addedToSolution, lower.inSolution, org.state.components.length], ['ContosoCore', true, ['app', 'sitemap'], 2]);
+ assert.deepStrictEqual([lower.solution, lower.addedToSolution, lower.inSolution, org.state.components.length], ['ContosoCore', true, ['app', 'sitemap', 'pages'], 3]);
assert.ok(!('systemSolution' in lower), 'a solution of the author\u2019s own is not a system solution');
+ assert.ok(!system.requests.some((req) => /EntityDefinitions\(LogicalName='uxagentproject'\)/.test(req.path)), 'a system solution needs no page type: it is not read');
+});
+
+// The add of an app brings its sitemap, never the pages its navigation opens (AB#6443257): each page is added on its own, as a component of the type the environment
+// allocates for the page table — read, not assumed — and with its required components, which are its file rows.
+test('REAL BUNDLE: each page joins the solution after the app and its sitemap, as the page table\u2019s own component type with its files — the request the platform is sent', async () => {
+ const org = orgWithPages({ pageType: 10399 });
+ const result = await createApp(args({ pageIds: [PAGE_B, PAGE_A] }), client(org), seams);
+ assert.strictEqual(result.ok, true, JSON.stringify(result));
+ const typeRead = org.requests.findIndex((req) => req.method === 'GET' && req.path === "/EntityDefinitions(LogicalName='uxagentproject')?$select=ObjectTypeCode");
+ assert.ok(typeRead >= 0 && typeRead < org.requests.findIndex((req) => req.method !== 'GET'), 'the type is read, before the first write');
+ const adds = org.requests.filter((req) => req.path === '/AddSolutionComponent').map((req) => req.body);
+ assert.deepStrictEqual(adds.slice(2), [
+ { ComponentId: PAGE_B, ComponentType: 10399, SolutionUniqueName: 'ContosoCore', AddRequiredComponents: true },
+ { ComponentId: PAGE_A, ComponentType: 10399, SolutionUniqueName: 'ContosoCore', AddRequiredComponents: true },
+ ]);
+ assert.deepStrictEqual(adds.slice(0, 2).map((b) => b.ComponentType), [80, 62], 'the app and its sitemap first');
+ assert.deepStrictEqual(org.unexpected, []);
});
// --- create: refusals write nothing ------------------------------------------------------------------------------------
@@ -801,14 +823,14 @@ test('REAL BUNDLE: the SDK\u2019s own warning on the push — the role it could
assert.match(result.warnings[0], /^App roles: could not associate the 'System Administrator' role with the app .*role association refused.*not be visible or playable until a role is granted access to it\.$/);
});
-test('REAL BUNDLE: a publish the platform refuses fails at the publish stage with the app and its sitemap already in the solution, and the app still a draft', async () => {
+test('REAL BUNDLE: a publish the platform refuses fails at the publish stage with the app, its sitemap and its page already in the solution, and the app still a draft', async () => {
const org = orgWithPages({ answer: (req) => (req.path === '/PublishXml' ? json(400, { error: { code: '0x80040E14', message: 'another publish is running' } }) : undefined) });
const result = await createApp(args({ publish: true }), client(org), seams);
assert.strictEqual(result.ok, false);
assert.deepStrictEqual([result.written, result.stage, result.addedToSolution, result.published, result.unpublishedChanges], [true, 'publish', true, false, true]);
- assert.deepStrictEqual(result.inSolution, ['app', 'sitemap']);
+ assert.deepStrictEqual(result.inSolution, ['app', 'sitemap', 'pages']);
assert.match(result.error, /another publish is running/);
- assert.deepStrictEqual(org.state.components.map((c) => c.type), [80, 62]);
+ assert.deepStrictEqual(org.state.components.map((c) => c.type), [80, 62, 10372]);
});
test('REAL BUNDLE: a publish the platform took while its answer was lost reads as published — the read-back, not the failure, says what is there', async () => {
@@ -845,7 +867,7 @@ test('REAL BUNDLE: the SDK writes the app setting HeaderAndNavigationRefresh = 2
assert.ok(org.requests.some((r) => r.method === 'GET' && /^\/appsettings\/Microsoft\.Dynamics\.CRM\.RetrieveUnpublishedMultiple\(\)\?/.test(r.path)));
// Written unpublished; the app's publish publishes it with the app.
assert.deepStrictEqual(org.state.appSettings.map((s) => [s.parentappmoduleid, s.value, s.published]), [[result.appId, '2', true]]);
- assert.deepStrictEqual(org.state.components.map((c) => c.type), [80, 62], 'the setting is not added to the solution: only the app and its sitemap are');
+ assert.deepStrictEqual(org.state.components.map((c) => c.type), [80, 62, 10372], 'the setting is not added to the solution: only the app, its sitemap and its page are');
});
test('REAL BUNDLE: a draft app made by the script has its setting only in the unpublished layer: a plain read of the settings finds none, the unpublished-aware read finds it', async () => {
@@ -940,10 +962,10 @@ test('END TO END: create --publish prints one JSON line, exits 0, and the platfo
assert.strictEqual(r.lines.length, 1);
const result = JSON.parse(r.lines[0]);
assert.strictEqual(result.ok, true);
- assert.deepStrictEqual([result.published, result.unpublishedChanges, result.inSolution], [true, false, ['app', 'sitemap']]);
+ assert.deepStrictEqual([result.published, result.unpublishedChanges, result.inSolution], [true, false, ['app', 'sitemap', 'pages']]);
assert.deepStrictEqual(result.navigation.pages.map((p) => p.title), ['Overview', 'Details']);
const writes = writesOf(r);
- assert.deepStrictEqual(writes.filter((w) => /appmodules$|sitemaps$|AddSolutionComponent|PublishXml/.test(w)), ['POST appmodules', 'POST sitemaps', 'POST AddSolutionComponent', 'POST AddSolutionComponent', 'POST PublishXml']);
+ assert.deepStrictEqual(writes.filter((w) => /appmodules$|sitemaps$|AddSolutionComponent|PublishXml/.test(w)), ['POST appmodules', 'POST sitemaps', 'POST AddSolutionComponent', 'POST AddSolutionComponent', 'POST AddSolutionComponent', 'POST AddSolutionComponent', 'POST PublishXml']);
});
test('END TO END: a refusal prints its { ok: false, code } line, the reason on stderr, exits 1 — and nothing was written', () => {
diff --git a/plugins/model-apps/scripts/tests/apps.test.js b/plugins/model-apps/scripts/tests/apps.test.js
index 61462c488..c7cea0ff7 100644
--- a/plugins/model-apps/scripts/tests/apps.test.js
+++ b/plugins/model-apps/scripts/tests/apps.test.js
@@ -33,6 +33,8 @@ const world = (overrides = {}) => ({
language: 1033,
push: { type: 'app', id: APP_ID, saved: true, shipped: false, publish: { kind: 'notRequested' } },
publishResult: { type: 'app', id: APP_ID, shipped: false, publish: { kind: 'submitted' } },
+ // The ObjectTypeCode of the page table (`uxagentproject`), which the environment allocates; `null`: its metadata cannot be read (HTTP 503).
+ pageType: 10372,
...overrides,
});
const appRow = (overrides = {}) => ({ appmoduleid: '77777777-7777-4777-8777-777777777777', name: 'Contoso Sales', uniquename: 'contoso_sales', description: null, componentstate: 0, ...overrides });
@@ -86,6 +88,12 @@ async function run(argv, w = world(), hooks = {}, deps = {}) {
const name = /sitemapnameunique eq '([^']*)'/.exec(p);
return answer(sitemapsNow().filter((s) => name && s.sitemapnameunique.toLowerCase() === name[1].toLowerCase()));
}
+ // The page table's component type, as the platform answers it: { "ObjectTypeCode": 10372, … }. The SDK's client answers an HTTP failure, it does not throw it.
+ if (p === "/EntityDefinitions(LogicalName='uxagentproject')?$select=ObjectTypeCode") {
+ return w.pageType === null
+ ? { status: 503, headers: {}, body: { error: { code: '0x80040216', message: 'the metadata service is busy' } } }
+ : { status: 200, headers: {}, body: { ObjectTypeCode: w.pageType, MetadataId: '66666666-6666-4666-8666-666666666666' } };
+ }
throw new Error(`unexpected read ${p}`);
},
},
@@ -232,6 +240,7 @@ async function run(argv, w = world(), hooks = {}, deps = {}) {
}
const CREATE = ['create', '--env', ENV, '--name', 'Account Metrics', '--solution', 'ContosoCore', '--page-id', PAGE_A];
+const BOTH_PAGES_IN_SOLUTION = ['create', '--env', ENV, '--name', 'Two Pages', '--solution', 'ContosoCore', '--page-id', `${PAGE_A},${PAGE_B}`];
const without = (argv, flag) => { const i = argv.indexOf(flag); return i === -1 ? argv : [...argv.slice(0, i), ...argv.slice(i + 2)]; };
// --- the command line ------------------------------------------------------------------------------------------
@@ -525,7 +534,7 @@ test('the throwaway workspace is removed after a list, after one that failed, an
// --- create: the writes ------------------------------------------------------------------------------------------
-test('create reads, then writes in order — the app and its sitemap, the app and the sitemap into the solution — and publishes only with --publish', async () => {
+test('create reads, then writes in order — the app and its sitemap, the app, the sitemap and the page into the solution — and publishes only with --publish', async () => {
const r = await run(CREATE, world({ language: 3082 }));
assert.strictEqual(r.exitCode, 0, r.stderr);
// Every read comes before the first write, and the reads are the ones the checks need.
@@ -533,13 +542,14 @@ test('create reads, then writes in order — the app and its sitemap, the app an
assert.ok(r.events.slice(0, firstWrite).every((e) => e.type !== 'write'));
assert.deepStrictEqual(r.events.filter((e) => e.type === 'read').map((e) => e.what.replace(/\?.*$/, '')), [
'queryRecords solution',
+ "/EntityDefinitions(LogicalName='uxagentproject')",
'/uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()',
'resolveArtifact app',
'/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()',
'queryRecords organization',
`genpage describe ${PAGE_A}`,
]);
- assert.deepStrictEqual(r.writeNames, ['initWorkspace', 'createArtifact', 'pushArtifact', 'addSolutionComponent', 'addSolutionComponent']);
+ assert.deepStrictEqual(r.writeNames, ['initWorkspace', 'createArtifact', 'pushArtifact', 'addSolutionComponent', 'addSolutionComponent', 'addSolutionComponent']);
assert.ok(!r.writeNames.includes('publishArtifact'), 'no publish without --publish');
// Two SDKs over one workspace: the first reads, in no particular language; the second writes, in the environment's base language.
@@ -566,6 +576,7 @@ test('create reads, then writes in order — the app and its sitemap, the app an
assert.deepStrictEqual(adds, [
{ componentId: APP_ID, componentType: 80, solutionUniqueName: 'ContosoCore' },
{ componentId: def.sitemapId, componentType: 62, solutionUniqueName: 'ContosoCore' },
+ { componentId: PAGE_A, componentType: 10372, solutionUniqueName: 'ContosoCore', addRequiredComponents: true },
]);
assert.deepStrictEqual(r.payload, {
ok: true,
@@ -576,7 +587,7 @@ test('create reads, then writes in order — the app and its sitemap, the app an
unpublishedChanges: true,
solution: 'ContosoCore',
addedToSolution: true,
- inSolution: ['app', 'sitemap'],
+ inSolution: ['app', 'sitemap', 'pages'],
sitemapId: def.sitemapId,
languageCode: 3082,
navigation: { area: 'Main', group: 'Pages', pages: [{ pageId: PAGE_A, title: 'Overview' }] },
@@ -590,8 +601,8 @@ test('create reads, then writes in order — the app and its sitemap, the app an
test('create --publish publishes the app last, once, by the id the push answered with, and reports it published with nothing left unpublished', async () => {
const r = await run([...CREATE, '--publish']);
assert.strictEqual(r.exitCode, 0, r.stderr);
- assert.deepStrictEqual(r.writeNames, ['initWorkspace', 'createArtifact', 'pushArtifact', 'addSolutionComponent', 'addSolutionComponent', 'publishArtifact']);
- assert.deepStrictEqual(r.writes[5].detail, { type: 'app', id: APP_ID });
+ assert.deepStrictEqual(r.writeNames, ['initWorkspace', 'createArtifact', 'pushArtifact', 'addSolutionComponent', 'addSolutionComponent', 'addSolutionComponent', 'publishArtifact']);
+ assert.deepStrictEqual(r.writes[6].detail, { type: 'app', id: APP_ID });
assert.strictEqual(r.def.published, false, 'still created as a draft: the explicit publish is what ships it');
assert.deepStrictEqual([r.payload.published, r.payload.unpublishedChanges], [true, false], 'a publish takes the saved row into the published layer');
});
@@ -729,7 +740,7 @@ test('a system solution (Default, Active, Basic) holds every component already:
}
// A solution of the author's own is added to, and is not a system solution.
const own = await run(CREATE);
- assert.deepStrictEqual([own.payload.addedToSolution, own.payload.inSolution], [true, ['app', 'sitemap']]);
+ assert.deepStrictEqual([own.payload.addedToSolution, own.payload.inSolution], [true, ['app', 'sitemap', 'pages']]);
assert.ok(!('systemSolution' in own.payload), 'the flag is there only when it is true');
});
@@ -740,6 +751,60 @@ test('a failure after the push into a system solution says the same: nothing was
assert.deepStrictEqual([r.payload.stage, r.payload.addedToSolution, r.payload.inSolution, r.payload.systemSolution], ['publish', false, [], true]);
});
+// --- create: the pages join the solution with the app (AB#6443257) ------------------------------------------------------------
+// The add of an app brings its sitemap, never the pages its navigation opens, so an app made around pages "into" a solution left the pages out of it: the solution then
+// exported an app whose navigation opens pages the target environment does not have. Each page is added explicitly, as a component of the page table's own type, which
+// the environment allocates and is read — never assumed — before anything is written.
+
+test('create adds every page it opens on to the solution, after the app and its sitemap, as a component of the page table\u2019s type read from the environment, bringing its files with it', async () => {
+ const r = await run(BOTH_PAGES_IN_SOLUTION, world({ pageType: 10380 }));
+ assert.strictEqual(r.exitCode, 0, r.stderr);
+ const adds = r.writes.filter((e) => e.what === 'addSolutionComponent').map((e) => e.detail);
+ assert.deepStrictEqual(adds, [
+ { componentId: APP_ID, componentType: 80, solutionUniqueName: 'ContosoCore' },
+ { componentId: r.def.sitemapId, componentType: 62, solutionUniqueName: 'ContosoCore' },
+ { componentId: PAGE_A, componentType: 10380, solutionUniqueName: 'ContosoCore', addRequiredComponents: true },
+ { componentId: PAGE_B, componentType: 10380, solutionUniqueName: 'ContosoCore', addRequiredComponents: true },
+ ]);
+ assert.deepStrictEqual(r.held.map((h) => [h.componentId, h.componentType]), [[APP_ID, 80], [r.def.sitemapId, 62], [PAGE_A, 10380], [PAGE_B, 10380]], 'what the solution now holds');
+ assert.deepStrictEqual([r.payload.addedToSolution, r.payload.inSolution], [true, ['app', 'sitemap', 'pages']]);
+ // The type is read once, with the checks, before the first write.
+ const typeReads = r.events.filter((e) => e.type === 'read' && /EntityDefinitions/.test(e.what));
+ assert.strictEqual(typeReads.length, 1);
+ assert.ok(r.events.indexOf(typeReads[0]) < r.events.findIndex((e) => e.type === 'write'), 'read before anything is written');
+});
+
+test('a page that cannot join the solution fails the create at the solution stage: the app and its sitemap joined, the pages did not, and nothing is published', async () => {
+ const r = await run([...BOTH_PAGES_IN_SOLUTION, '--publish'], world(), { addSolutionComponent: (o) => { if (o.componentId === PAGE_B) throw new Error('the page could not be added'); } });
+ assert.strictEqual(r.exitCode, 1);
+ assert.deepStrictEqual(r.payload, draftLeft(r, { error: 'the page could not be added', stage: 'solution', addedToSolution: false, inSolution: ['app', 'sitemap'] }));
+ assert.deepStrictEqual(r.held.map((h) => h.componentId), [APP_ID, r.def.sitemapId, PAGE_A], 'the first page joined before the second failed');
+ assert.ok(!r.writeNames.includes('publishArtifact'), 'a publish is never attempted over a half-joined solution');
+});
+
+test('the page table\u2019s component type is read before anything is written: an environment that cannot answer it refuses the create, with nothing made', async () => {
+ const r = await run(CREATE, world({ pageType: null }));
+ assert.strictEqual(r.exitCode, 1);
+ assert.strictEqual(r.payload.code, 'GENPAGE_COMPONENT_TYPE_UNRESOLVED');
+ assert.match(r.payload.error, /the solution component type of a generative page could not be read \(HTTP 503: the metadata service is busy\)/);
+ assert.strictEqual(r.payload.written, false);
+ assert.deepStrictEqual(r.writes, []);
+ // An answer that holds no usable type is refused the same way: a page added under a wrong type joins as some other component, or as nothing.
+ for (const pageType of [0, -5, 'abc', 1.5]) {
+ const odd = await run(CREATE, world({ pageType }));
+ assert.strictEqual(odd.payload.code, 'GENPAGE_COMPONENT_TYPE_UNRESOLVED', String(pageType));
+ assert.deepStrictEqual(odd.writes, [], String(pageType));
+ }
+});
+
+test('a system solution needs no add and no read of the page table\u2019s type: the create is made exactly as before', async () => {
+ const r = await run(['create', '--env', ENV, '--name', 'A', '--solution', 'Default', '--page-id', PAGE_A], world({ solutions: [solution({ uniquename: 'Default' })], pageType: null }));
+ assert.strictEqual(r.exitCode, 0, r.stderr);
+ assert.ok(!r.events.some((e) => e.type === 'read' && /EntityDefinitions/.test(e.what)), 'the type is not read');
+ assert.deepStrictEqual(r.writeNames, ['initWorkspace', 'createArtifact', 'pushArtifact']);
+ assert.deepStrictEqual([r.payload.addedToSolution, r.payload.inSolution, r.payload.systemSolution], [false, [], true]);
+});
+
test('the SDK\u2019s notes on a push that succeeded are in the output and on stderr, not lost', async () => {
const w = world({ push: { type: 'app', id: APP_ID, saved: true, publish: { kind: 'notRequested' }, warnings: ['App roles: could not associate the System Administrator role with the app.'] } });
const r = await run(CREATE, w);
@@ -772,8 +837,8 @@ test('create pins the default public view of every table the pages read — each
assert.deepStrictEqual(reads.slice(-3), [`genpage describe ${PAGE_A}`, `genpage describe ${PAGE_B}`, 'genpage defaultViews']);
assert.deepStrictEqual(r.events.find((e) => e.what === 'genpage defaultViews').detail, ['account', 'contact', 'task']);
assert.ok(r.events.findIndex((e) => e.what === 'genpage defaultViews') < r.events.findIndex((e) => e.what === 'initWorkspace'), 'before the first write');
- // The views are part of the create's one push: no later write adds them.
- assert.deepStrictEqual(r.writeNames, ['initWorkspace', 'createArtifact', 'pushArtifact', 'addSolutionComponent', 'addSolutionComponent']);
+ // The views are part of the create's one push: no later write adds them (the adds after it are the app, its sitemap and its two pages joining the solution).
+ assert.deepStrictEqual(r.writeNames, ['initWorkspace', 'createArtifact', 'pushArtifact', 'addSolutionComponent', 'addSolutionComponent', 'addSolutionComponent', 'addSolutionComponent']);
});
test('the page backend the create reads the tables through is the page backend\'s own, made once for the environment, and disposed — bounded — whichever way the create ends', async () => {
@@ -1143,7 +1208,7 @@ test('a push the SDK reported as saved wrote both rows, so a read-back that cann
const failedPublish = world({ publishResult: { type: 'app', id: APP_ID, shipped: false, publish: { kind: 'failed', error: new Error('another publish is running') } } });
for (const [stage, w, argv, error, joined] of [
['solution', world(), CREATE, 'the app could not be added', []],
- ['publish', failedPublish, [...CREATE, '--publish'], 'another publish is running', ['app', 'sitemap']],
+ ['publish', failedPublish, [...CREATE, '--publish'], 'another publish is running', ['app', 'sitemap', 'pages']],
]) {
let armed = false;
const r = await run(argv, w, {
@@ -1163,7 +1228,7 @@ test('a push the SDK reported as saved wrote both rows, so a read-back that cann
left: { app: true, sitemap: true },
lookFor: { uniqueName: r.payload.uniqueName, appId: APP_ID, sitemapId: r.def.sitemapId },
readBackError: refused.message,
- addedToSolution: joined.length === 2,
+ addedToSolution: joined.length === 3,
inSolution: joined,
}, stage);
assert.ok(!('published' in r.payload), `${stage}: the platform could not be asked, so nothing is said of whether the app is published`);
@@ -1215,7 +1280,7 @@ test('a failure between the two solution adds says which component is in the sol
const r = await run([...CREATE, '--publish'], world(), { addSolutionComponent: () => { adds += 1; if (adds === 2) throw new Error('the sitemap could not be added'); } });
assert.strictEqual(r.exitCode, 1);
assert.deepStrictEqual(r.payload, draftLeft(r, { error: 'the sitemap could not be added', stage: 'solution', addedToSolution: false, inSolution: ['app'] }));
- // What the platform holds: the app joined the solution, its sitemap did not. `addedToSolution` is true only when both did.
+ // What the platform holds: the app joined the solution, its sitemap did not (nor its page). `addedToSolution` is true only when all of them did.
assert.deepStrictEqual(r.held, [{ componentId: APP_ID, componentType: 80, solution: 'ContosoCore' }]);
assert.ok(!r.writeNames.includes('publishArtifact'), 'a publish is never attempted over a half-joined solution');
assert.strictEqual(r.writeNames.filter((n) => n === 'addSolutionComponent').length, 2);
@@ -1228,12 +1293,12 @@ test('a failure of the app\u2019s own add leaves nothing in the solution, and sa
assert.strictEqual(r.writeNames.filter((n) => n === 'addSolutionComponent').length, 1, 'the sitemap is not tried after the app failed');
});
-test('a publish the SDK reports as failed is a failure at the publish stage, the app and its sitemap already in the solution, and still a draft', async () => {
+test('a publish the SDK reports as failed is a failure at the publish stage, the app, its sitemap and its page already in the solution, and still a draft', async () => {
const w = world({ publishResult: { type: 'app', id: APP_ID, shipped: false, publish: { kind: 'failed', error: Object.assign(new Error('another publish is running'), { code: 'CONNECTION_ERROR' }) } } });
const r = await run([...CREATE, '--publish'], w);
assert.strictEqual(r.exitCode, 1);
- assert.deepStrictEqual(r.payload, draftLeft(r, { code: 'CONNECTION_ERROR', error: 'another publish is running', stage: 'publish', addedToSolution: true, inSolution: ['app', 'sitemap'] }));
- assert.deepStrictEqual(r.held.map((component) => component.componentType), [80, 62]);
+ assert.deepStrictEqual(r.payload, draftLeft(r, { code: 'CONNECTION_ERROR', error: 'another publish is running', stage: 'publish', addedToSolution: true, inSolution: ['app', 'sitemap', 'pages'] }));
+ assert.deepStrictEqual(r.held.map((component) => component.componentType), [80, 62, 10372]);
});
test('a publish the SDK reports as failed that the platform in fact took is published — the read-back, not the SDK\u2019s word, says what is there', async () => {
@@ -1244,7 +1309,7 @@ test('a publish the SDK reports as failed that the platform in fact took is publ
return { publish: { kind: 'failed', error: new Error('the publish was submitted but could not be confirmed') } };
},
});
- assert.deepStrictEqual(r.payload, draftLeft(r, { error: 'the publish was submitted but could not be confirmed', stage: 'publish', addedToSolution: true, inSolution: ['app', 'sitemap'], published: true, unpublishedChanges: false }));
+ assert.deepStrictEqual(r.payload, draftLeft(r, { error: 'the publish was submitted but could not be confirmed', stage: 'publish', addedToSolution: true, inSolution: ['app', 'sitemap', 'pages'], published: true, unpublishedChanges: false }));
});
test('the SDK\u2019s notes on the push are kept when the run fails after it — in the output and on stderr — at the solution stage, the publish stage and for a push not saved', async () => {
diff --git a/plugins/model-apps/scripts/tests/build-lease-real-bundle.test.js b/plugins/model-apps/scripts/tests/build-lease-real-bundle.test.js
index 66a2881e9..34298ab98 100644
--- a/plugins/model-apps/scripts/tests/build-lease-real-bundle.test.js
+++ b/plugins/model-apps/scripts/tests/build-lease-real-bundle.test.js
@@ -174,7 +174,8 @@ test('a teardown deletes the one generated icon its lookup answers ($top=1) —
// What a build that runs alone sends, by `METHOD entity set` — ids, keys and queries left out — as the build sent it before the lease (2.18.0),
// for the first build and an unchanged rebuild of the same spec. The lease is a file in the workspace: a build that meets no other sends exactly
-// this, and a request the lease added would show here.
+// this, and a request the lease added would show here. Since then the build's own verify reads each web resource the spec declares, with
+// its content (one GET /webresourceset in each run: the spec declares one).
const ALONE = {
build: {
'GET /appmodulecomponents': 5,
@@ -195,7 +196,7 @@ const ALONE = {
'GET /sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()': 1,
'GET /solutions': 2,
'GET /systemforms': 1,
- 'GET /webresourceset': 2,
+ 'GET /webresourceset': 3,
'GET /webresourceset()': 2,
'POST /AddAppComponents': 1,
'POST /AddSolutionComponent': 4,
@@ -227,7 +228,7 @@ const ALONE = {
'GET /systemforms': 1,
'GET /systemforms/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()': 1,
'GET /uxagentprojects': 1,
- 'GET /webresourceset': 3,
+ 'GET /webresourceset': 4,
'PATCH /sitemaps()': 1,
'POST /AddAppComponents': 1,
'POST /PublishXml': 3,
diff --git a/plugins/model-apps/scripts/tests/build-model-app.test.js b/plugins/model-apps/scripts/tests/build-model-app.test.js
index 1660c91c9..4029172f3 100644
--- a/plugins/model-apps/scripts/tests/build-model-app.test.js
+++ b/plugins/model-apps/scripts/tests/build-model-app.test.js
@@ -2513,7 +2513,7 @@ test('the verify options carry the ACTUAL phase list, not a constant', () => {
// Asserted on the SOURCE because the value has to be the caller's own `opts.phases`: a test that
// merely passes a phase list through would still accept `phases: PHASES`.
const src = fs.readFileSync(path.join(__dirname, '..', 'build-model-app.js'), 'utf8');
- assert.match(src, /deps\.verify\(spec, \{ environmentSkipped: r\.skipped, phases: opts\.phases(, baselineSpec: opts\.baselineSpec)?(, languageCode: opts\.languageCode, preResolvedLanguageCode: opts\.preResolvedLanguageCode)? \}\)/,
+ assert.match(src, /deps\.verify\(spec, \{ environmentSkipped: r\.skipped, phases: opts\.phases(, baselineSpec: opts\.baselineSpec)?(, languageCode: opts\.languageCode, preResolvedLanguageCode: opts\.preResolvedLanguageCode)?(, appDir: opts\.appDir)? \}\)/,
'verify must receive the invocation\'s OWN phases — a constant re-breaks the --changed-only fast path');
});
@@ -2581,8 +2581,11 @@ test('the build hands verify the language it wrote its labels in', async () => {
await buildModelApp(desk, { apply: true, env: 'https://x', verify: true, preResolvedLanguageCode: 1031 }, { sdk, verify });
assert.strictEqual(received.languageCode, undefined);
assert.strictEqual(received.preResolvedLanguageCode, 1031);
- // The rest of the options are exactly what they were.
- assert.deepStrictEqual(Object.keys(received).sort(), ['baselineSpec', 'environmentSkipped', 'languageCode', 'phases', 'preResolvedLanguageCode']);
+ // The rest of the options are exactly what they were, and the app folder, from which verify reads a web resource's contentPath to
+ // compare its deployed content.
+ assert.deepStrictEqual(Object.keys(received).sort(), ['appDir', 'baselineSpec', 'environmentSkipped', 'languageCode', 'phases', 'preResolvedLanguageCode']);
+ await buildModelApp(desk, { apply: true, env: 'https://x', verify: true, appDir: path.join(__dirname, '..', '..', 'samples') }, { sdk, verify });
+ assert.strictEqual(received.appDir, path.join(__dirname, '..', '..', 'samples'), 'the folder the build read the spec\'s sources from');
});
test('verify NARRATES what it could not verify beside its PASS — it is neither a pass nor a failure — and the result carries it', async () => {
@@ -2702,6 +2705,7 @@ test('main changed-only full-fast-noop cycle uses the real flow', async () => {
const os = require('node:os');
const { loadCli } = require('./helpers/cli-harness.js');
const { makeSimpleMockSdk } = require('./helpers/mock-sdk.js');
+ const { withPageType, PAGE_TYPE } = require('./helpers/page-component-type.js');
const snapshotStore = require('../lib/apply-snapshot-store.js');
const { sha256 } = require('../lib/hash.js');
const genpageSdk = require('../lib/genpage-sdk.js');
@@ -2784,7 +2788,8 @@ test('main changed-only full-fast-noop cycle uses the real flow', async () => {
assert.ok(row, `web resource ${id} exists`);
row.content = Buffer.from(o.content, 'utf8').toString('base64');
};
- sdk.dataverse = { get: async (url) => {
+ // The page table's component type is answered first: the build's pages join the spec's solution (lib/page-solution.js).
+ sdk.dataverse = { get: withPageType(async (url) => {
// The shared-page scan lists the apps that were never published: the one app here is published, so it is the only row.
if (url.startsWith('/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()')) {
return { status: 200, body: { value: state.app ? [{ appmoduleid: state.app.id, appmoduleidunique: appUniqueValue, uniquename: spec.app.uniqueName, componentstate: 0 }] : [] } };
@@ -2793,7 +2798,7 @@ test('main changed-only full-fast-noop cycle uses the real flow', async () => {
return state.table && !url.includes("LogicalName='entity'")
? { status: 200, body: { LogicalName: state.table.logicalName, EntitySetName: state.table.entitySetName } }
: { status: 404, body: {} };
- } };
+ }) };
sdk.queryRecords = async (set, o = {}) => {
const filter = o.filter || '';
if (set === 'appmodule') {
@@ -2946,8 +2951,13 @@ test('main changed-only full-fast-noop cycle uses the real flow', async () => {
assert.strictEqual(fast.verify.ok, true);
assert.deepStrictEqual(fast.changedOnly.pageKeys, ['overview']);
assert.deepStrictEqual(uploads, [{ name: 'Overview', pageId: pageIds.Overview, requestedId: pageIds.Overview, code: deployedCode }]);
- assert.ok(writes.every((w) => w.method === 'updateWebResource' || (w.method === 'addSolutionComponent' && w.args[0].componentType === 61)),
- `fast apply writes only the page manifest, never the data model or sitemap: ${JSON.stringify(writes)}`);
+ // Each page is re-asserted in the spec's solution, as the manifest is: the one the fast apply writes, and the one it leaves as it is (sdk-build.js, the page manifest
+ // step), which gets the add and no write. This double keeps no solution, so none of them is found there and each is added.
+ assert.ok(writes.every((w) => w.method === 'updateWebResource' || (w.method === 'addSolutionComponent' && (w.args[0].componentType === 61
+ || (w.args[0].componentType === PAGE_TYPE && [pageIds.Overview, pageIds.Detail].includes(w.args[0].componentId))))),
+ `fast apply writes only the page manifest and the solution membership of the app's pages, never the data model or sitemap: ${JSON.stringify(writes)}`);
+ assert.deepStrictEqual(writes.filter((w) => w.method === 'addSolutionComponent' && w.args[0].componentType === PAGE_TYPE).map((w) => [w.args[0].componentId, w.args[0].addRequiredComponents]),
+ [[pageIds.Overview, true], [pageIds.Detail, true]], 'both pages are in the spec\'s solution, with their files: the changed one as it is written, the other once the pages are');
const eligible = snapshotStore.readSnapshot(workspaceDir);
assert.strictEqual(eligible.eligible, true);
assert.notStrictEqual(eligible.generation, baseline.generation);
diff --git a/plugins/model-apps/scripts/tests/changelog-brevity.test.js b/plugins/model-apps/scripts/tests/changelog-brevity.test.js
new file mode 100644
index 000000000..039056c5a
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/changelog-brevity.test.js
@@ -0,0 +1,339 @@
+'use strict';
+// Keeps CHANGELOG.md short, and the links at its end whole.
+//
+// WHY: the file promises, in its own header, entries that are "deliberately short: what changed and why it
+// matters to you", and AGENTS.md (Documentation Map) puts the reasoning, the evidence and the trade-offs in
+// the PR and in docs/. Nothing held the file to that promise, and it grew to some 180 KB, one release alone
+// near 9,000 words: more than a reader looking for "what changed for me" will read. This test makes the
+// promise a rule:
+// * a release entry holds at most 300 words, from its `## ` heading (counted) to the next one;
+// * a bullet holds at most 45 words, its marker and its continuation lines included.
+// A word is a whitespace-separated token, the unit the limits were set in: `--allow-lossy-download` is one
+// word, and so is a bullet's `-`. Link reference definitions (`[#680]: https://...`) are not counted. The
+// older entries have unbracketed headings (`## 2.4.1`, `## 2.0.0 - 2026-05-12`), so every level-2 heading
+// starts an entry, not only `## [x.y.z]`; the header above the first one is not an entry.
+//
+// It also keeps the link reference definitions honest. The file keeps them in one block at its end, far
+// from the text that uses them, so a slip there is easy to miss: a `[#nnn]` with no definition renders as
+// literal brackets, a definition nothing uses is dead weight, and a label defined twice silently uses the
+// first definition. See https://spec.commonmark.org/0.31.2/#link-reference-definitions
+// A bracketed version heading (`## [2.20.0]`) is a reference only if a definition exists: Keep a Changelog
+// brackets version headings whether or not it links them (https://keepachangelog.com/en/1.1.0/).
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+
+const CHANGELOG = path.join(__dirname, '..', '..', 'CHANGELOG.md');
+const MAX_ENTRY_WORDS = 300;
+const MAX_BULLET_WORDS = 45;
+
+// CommonMark line shapes, read one line at a time (https://spec.commonmark.org/0.31.2/):
+// ATX heading `## [2.20.0]`, `### Fixed` (up to three spaces of indent, then 1-6 `#`)
+// definition `[#680]: https://github.com/...` (a label, a colon, then a destination)
+// fence three or more backticks or tildes; nothing inside is read as Markdown. A fence
+// may be indented: inside a list item it sits at the item's content column.
+// thematic break `---`, `***`, `- - -`
+// list item `- text`, `* text`, `+ text`, `1. text`, `1) text`
+const HEADING = /^ {0,3}(#{1,6})(?:[ \t]|$)/;
+const DEFINITION = /^ {0,3}\[([^\]]+)\]:[ \t]*\S/;
+const FENCE = /^([ \t]*)(`{3,}|~{3,})/;
+const THEMATIC_BREAK = /^ {0,3}([-*_])(?:[ \t]*\1){2,}[ \t]*$/;
+const LIST_ITEM = /^[ \t]*(?:[-*+]|\d{1,9}[.)])[ \t]+\S/;
+// A line indented at least two columns belongs to the list item above it (its content starts after `- `).
+const INDENTED = /^(?: {2,}|\t)/;
+
+const countWords = (text) => text.split(/\s+/).filter(Boolean).length;
+// Labels match case-insensitively, with inner white space collapsed (CommonMark "matching" of labels).
+const normalizeLabel = (label) => label.trim().replace(/\s+/g, ' ').toLowerCase();
+const preview = (text) => {
+ const flat = text.replace(/\s+/g, ' ').trim();
+ return flat.length > 60 ? `${flat.slice(0, 60).trimEnd()}...` : flat;
+};
+
+// Code spans hold literal text: `[#nnn]` or `personas[]` inside backticks is no link. Blank each span out
+// with spaces, keeping newlines, so the offsets of what is left still map to their lines. A span opens and
+// closes with backtick runs of the same length and may cross a line break.
+const blankCodeSpans = (text) => text.replace(/(?<!`)(`+)(?!`)[\s\S]*?(?<!`)\1(?!`)/g, (span) => span.replace(/[^\n]/g, ' '));
+
+// Bracketed labels in prose, as CommonMark reads them:
+// [text](url) inline link: no reference
+// [text][label] full reference: `label`
+// [label][] collapsed reference: `label`
+// [label] shortcut reference: `label`
+// \[text] escaped: no reference
+function labelsIn(text) {
+ const found = [];
+ for (const match of text.matchAll(/(\\?)!?\[([^\[\]]+)\](?:(\()|\[([^\[\]]*)\])?/g)) {
+ if (match[1] || match[3]) continue;
+ found.push({ label: match[4] ? match[4] : match[2], index: match.index });
+ }
+ return found;
+}
+
+function parseChangelog(text) {
+ const lines = text.replace(/\r\n?/g, '\n').split('\n');
+ const entries = [];
+ const definitions = [];
+ const prose = [];
+ const headingLabels = [];
+ let entry = null;
+ let bullet = null;
+ let afterBlank = false;
+ let fence = null;
+
+ // Adds a line to the bullet that owns it: its words count toward the bullet's limit.
+ const extend = (item, line) => {
+ item.text += ` ${line.trim()}`;
+ item.words += countWords(line);
+ };
+
+ lines.forEach((line, index) => {
+ const lineNumber = index + 1;
+ if (fence) {
+ // A line indented less than the list item ends the item, and with it a fence the item held but did not
+ // close (CommonMark closes a container's open blocks with it); that line is then read as usual.
+ if (fence.owner && line.trim() && !INDENTED.test(line)) {
+ fence = null;
+ bullet = null;
+ }
+ }
+ if (fence) {
+ // Inside a fence nothing is Markdown, but every word still counts: toward the entry, and toward the
+ // list item when the fence is part of one (an indented example under a bullet). Without that, a code
+ // block inside a bullet would carry any number of words past the bullet limit.
+ if (entry) entry.words += countWords(line);
+ if (fence.owner) extend(fence.owner, line);
+ if (new RegExp(`^[ \\t]*${fence.marker[0] === '`' ? '`' : '~'}{${fence.marker.length},}[ \\t]*$`).test(line)) {
+ bullet = fence.owner;
+ fence = null;
+ afterBlank = false;
+ }
+ return;
+ }
+ const opening = line.match(FENCE);
+ if (opening) {
+ // An indented fence under an open bullet is a block of that list item; an unindented one ends the list.
+ const owner = bullet && INDENTED.test(line) ? bullet : null;
+ fence = { marker: opening[2], owner };
+ bullet = null;
+ if (entry) entry.words += countWords(line);
+ if (owner) extend(owner, line);
+ return;
+ }
+ const definition = line.match(DEFINITION);
+ if (definition) {
+ definitions.push({ label: definition[1], line: lineNumber });
+ bullet = null;
+ return;
+ }
+ const heading = line.match(HEADING);
+ if (heading && heading[1].length === 2) {
+ entry = { heading: line.trim(), line: lineNumber, words: 0, bullets: [] };
+ entries.push(entry);
+ }
+ if (entry) entry.words += countWords(line);
+ if (heading) {
+ for (const { label } of labelsIn(blankCodeSpans(line))) headingLabels.push({ label, line: lineNumber });
+ bullet = null;
+ afterBlank = false;
+ return;
+ }
+ prose.push({ text: line, line: lineNumber });
+ if (!line.trim()) {
+ afterBlank = true;
+ return;
+ }
+ if (THEMATIC_BREAK.test(line)) {
+ bullet = null;
+ } else if (LIST_ITEM.test(line)) {
+ bullet = entry ? { line: lineNumber, text: line.trim(), words: countWords(line) } : null;
+ if (bullet) entry.bullets.push(bullet);
+ } else if (bullet && (!afterBlank || INDENTED.test(line))) {
+ // A continuation line, or after a blank line an indented one: a list item's later paragraph.
+ extend(bullet, line);
+ } else {
+ bullet = null;
+ }
+ afterBlank = false;
+ });
+
+ // Prose is scanned as one text so that a code span crossing a line break is still blanked out whole.
+ const joined = blankCodeSpans(prose.map((p) => p.text).join('\n'));
+ const starts = [];
+ let offset = 0;
+ for (const p of prose) {
+ starts.push(offset);
+ offset += p.text.length + 1;
+ }
+ const lineAt = (index) => {
+ let i = starts.length - 1;
+ while (i > 0 && starts[i] > index) i--;
+ return prose[i].line;
+ };
+ const references = labelsIn(joined).map(({ label, index }) => ({ label, line: lineAt(index) }));
+ return { entries, definitions, references, headingLabels };
+}
+
+const nameOf = (entry) => entry.heading.replace(/^#+\s*/, '');
+
+function limitProblems(parsed) {
+ const entries = parsed.entries
+ .filter((e) => e.words > MAX_ENTRY_WORDS)
+ .map((e) => `${nameOf(e)} (line ${e.line}): ${e.words} words, over the ${MAX_ENTRY_WORDS} a release entry may hold`);
+ const bullets = parsed.entries.flatMap((e) => e.bullets
+ .filter((b) => b.words > MAX_BULLET_WORDS)
+ .map((b) => `${nameOf(e)} (line ${b.line}): a bullet of ${b.words} words, over ${MAX_BULLET_WORDS}: "${preview(b.text)}"`));
+ return { entries, bullets };
+}
+
+function referenceProblems(parsed) {
+ const problems = [];
+ const defined = new Map();
+ for (const d of parsed.definitions) {
+ const key = normalizeLabel(d.label);
+ if (defined.has(key)) problems.push(`[${d.label}] (line ${d.line}): defined again; line ${defined.get(key).line} already defines it`);
+ else defined.set(key, d);
+ }
+ const used = new Set();
+ for (const r of parsed.references) {
+ const key = normalizeLabel(r.label);
+ if (defined.has(key)) used.add(key);
+ else problems.push(`[${r.label}] (line ${r.line}): no link reference definition; add one to the block at the end of the file, or escape the brackets`);
+ }
+ for (const h of parsed.headingLabels) if (defined.has(normalizeLabel(h.label))) used.add(normalizeLabel(h.label));
+ for (const [key, d] of defined) if (!used.has(key)) problems.push(`[${d.label}] (line ${d.line}): defined but never used; remove it`);
+ return problems;
+}
+
+const parsed = parseChangelog(fs.readFileSync(CHANGELOG, 'utf8'));
+
+test('CHANGELOG.md: every release entry is at most 300 words (the detail belongs in the PR and in docs/)', () => {
+ assert.ok(parsed.entries.length > 0, 'CHANGELOG.md has no `## ` release heading');
+ const { entries } = limitProblems(parsed);
+ assert.deepEqual(entries, [], `Release entries over ${MAX_ENTRY_WORDS} words:\n${entries.join('\n')}`);
+});
+
+test('CHANGELOG.md: every bullet is at most 45 words', () => {
+ assert.ok(parsed.entries.some((e) => e.bullets.length > 0), 'CHANGELOG.md has no bullet');
+ const { bullets } = limitProblems(parsed);
+ assert.deepEqual(bullets, [], `Bullets over ${MAX_BULLET_WORDS} words:\n${bullets.join('\n')}`);
+});
+
+test('CHANGELOG.md: every [label] has a link reference definition, and every definition is used and defined once', () => {
+ assert.ok(parsed.definitions.length > 0, 'CHANGELOG.md has no link reference definition');
+ const problems = referenceProblems(parsed);
+ assert.deepEqual(problems, [], `Link reference problems:\n${problems.join('\n')}`);
+});
+
+// The reader itself, on small texts, so a change to it cannot quietly make the checks above pass by reading
+// less (no entries, no bullets, no references) than the file holds.
+test('the reader: every level-2 heading starts an entry, bracketed or not; the header above the first is none', () => {
+ const p = parseChangelog('# Changelog\n\nIntro words that belong to no entry.\n\n## [1.1.0]\n\n- one two\n\n## 1.0.0 \u2014 2026-01-01\n\n### Fixed\n\nText.\n');
+ assert.deepEqual(p.entries.map((e) => [e.heading, e.line, e.words]), [['## [1.1.0]', 5, 5], ['## 1.0.0 \u2014 2026-01-01', 9, 7]]);
+});
+
+test('the reader: a bullet counts its marker and continuation lines, an indented later paragraph, and a nested item is a bullet of its own', () => {
+ const text = [
+ '## [1.0.0]',
+ '',
+ '- alpha beta',
+ ' gamma',
+ ' - nested one',
+ '',
+ '- second item',
+ 'lazily continued',
+ '',
+ ' another paragraph of it',
+ '1. third',
+ '',
+ 'A paragraph after the list.',
+ '',
+ '[#1]: https://example.com/1',
+ '',
+ '---',
+ '',
+ ].join('\r\n');
+ const p = parseChangelog(text);
+ assert.deepEqual(p.entries[0].bullets.map((b) => [b.line, b.words]), [[3, 4], [5, 3], [7, 9], [11, 2]]);
+ // 2 (heading) + 4 + 3 + 9 + 2 + 5 (the paragraph) + 1 (`---`); the definition is not counted.
+ assert.equal(p.entries[0].words, 26);
+ assert.deepEqual(p.definitions, [{ label: '#1', line: 15 }]);
+});
+
+test('the reader: an entry over 300 words and a bullet over 45 are each reported with their entry and the start of the text', () => {
+ const longBullet = `- ${Array.from({ length: 45 }, (_, i) => `w${i}`).join(' ')}`;
+ const okBullet = `- ${Array.from({ length: 44 }, (_, i) => `w${i}`).join(' ')}`;
+ const p = parseChangelog(['## [2.0.0]', '', longBullet, '', '## 1.0.0', '', okBullet, '', Array.from({ length: 254 }, () => 'x').join(' '), ''].join('\n'));
+ assert.deepEqual(p.entries.map((e) => e.words), [48, 301]);
+ const { entries, bullets } = limitProblems(p);
+ assert.deepEqual(entries, ['1.0.0 (line 5): 301 words, over the 300 a release entry may hold']);
+ assert.deepEqual(bullets, ['[2.0.0] (line 3): a bullet of 46 words, over 45: "- w0 w1 w2 w3 w4 w5 w6 w7 w8 w9 w10 w11 w12 w13 w14 w15 w16..."']);
+});
+
+test('the reader: a reference is a [label] in prose, not in a code span, an inline link or an escape, and a version heading uses a definition only if one exists', () => {
+ const text = [
+ '## [2.0.0]',
+ '',
+ '- Uses [#1], `[#2]` and `personas[]` in code, [a link](https://example.com), [text][#3], [#4][] and \\[#5].',
+ '- A span that crosses a line ``[#6]',
+ ' still [code]`` here, and [#7] has no definition.',
+ '',
+ '## [1.0.0]',
+ '',
+ '[#1]: https://example.com/1',
+ '[#3]: https://example.com/3',
+ '[#4]: https://example.com/4',
+ '[#8]: https://example.com/8',
+ '[#1]: https://example.com/1-again',
+ '[1.0.0]: https://example.com/compare',
+ ].join('\n');
+ const p = parseChangelog(text);
+ assert.deepEqual(p.references.map((r) => [r.label, r.line]), [['#1', 3], ['#3', 3], ['#4', 3], ['#7', 5]]);
+ assert.deepEqual(referenceProblems(p), [
+ '[#1] (line 13): defined again; line 9 already defines it',
+ '[#7] (line 5): no link reference definition; add one to the block at the end of the file, or escape the brackets',
+ '[#8] (line 12): defined but never used; remove it',
+ ]);
+});
+
+test('the reader: a fenced block inside a list item counts toward that bullet, and nothing in a fence is read as Markdown', () => {
+ const text = [
+ '## [99.0.0]',
+ '',
+ '- Migration example.',
+ ' ```text',
+ ` ${Array.from({ length: 45 }, (_, i) => `w${i}`).join(' ')}`,
+ ' ```',
+ '- Short item.',
+ '',
+ ' ~~~',
+ ' - not a bullet',
+ ' ## not a heading',
+ ' [#9]: not a definition',
+ ' see [#9]',
+ ' ~~~',
+ '',
+ ].join('\n');
+ const p = parseChangelog(text);
+ // 3 (`- Migration example.`) + 2 fence lines + 45; and 3 + 2 fence lines + 14 for the block after the blank line.
+ assert.deepEqual(p.entries[0].bullets.map((b) => [b.line, b.words]), [[3, 50], [7, 19]]);
+ assert.equal(p.entries[0].words, 71);
+ assert.equal(p.entries.length, 1);
+ assert.deepEqual([p.definitions, p.references], [[], []]);
+ const { bullets } = limitProblems(p);
+ assert.equal(bullets.length, 1);
+ assert.match(bullets[0], /^\[99\.0\.0\] \(line 3\): a bullet of 50 words, over 45: "- Migration example\. ```text w0 w1/);
+});
+
+test('the reader: an unindented fence is no part of the list above it, and a line indented less than an item closes a fence it left open', () => {
+ const after = parseChangelog(['## [1.0.0]', '', '- item one', '```', 'code words here', '```', 'after the fence', ''].join('\n'));
+ assert.deepEqual(after.entries[0].bullets.map((b) => [b.line, b.words]), [[3, 3]]);
+ assert.equal(after.entries[0].words, 13);
+ const open = parseChangelog(['## [1.0.0]', '', '- item', ' ```', ' code', '## 0.9.0', '', '- other', ''].join('\n'));
+ assert.deepEqual(open.entries.map((e) => [e.heading, e.words, e.bullets.map((b) => [b.line, b.words])]), [
+ ['## [1.0.0]', 6, [[3, 4]]],
+ ['## 0.9.0', 4, [[8, 2]]],
+ ]);
+});
diff --git a/plugins/model-apps/scripts/tests/dataverse-operations-docs.test.js b/plugins/model-apps/scripts/tests/dataverse-operations-docs.test.js
new file mode 100644
index 000000000..8d02452c5
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/dataverse-operations-docs.test.js
@@ -0,0 +1,359 @@
+'use strict';
+// The documents that teach the agents the two built-in Dataverse operations (WhoAmI, RetrieveVersion) say what the code does — and keep saying it.
+//
+// The agents act on these words, not on the code: the builder must probe the one gate left, `dataverse-operations` (Custom API support has no
+// flag, and the gate being off never ends its run or writes [] over a page's kept bindings), offer only the listing's catalogue and only on an
+// affirmative selection, project the four-key row, and write the optional plan section only for a selection of this run; the planners signal and
+// never probe; the orchestrator re-probes before an add/replace and halts rather than clearing; the page builder emits a button-only call;
+// download and rebuild relay the not-checked words. The reference quotes the fixed sentences the code prints, so a change on either side fails
+// here.
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const { AUTHORING_CODES } = require('../lib/dataverse-operations.js');
+const { dataverseOperationsDisabledMessage } = require('../lib/feature-flags.js');
+const { USAGE, CATALOGUE_UNAVAILABLE } = require('../list-dataverse-operations.js');
+
+const PLUGIN = path.join(__dirname, '..', '..');
+const read = (...parts) => fs.readFileSync(path.join(PLUGIN, ...parts), 'utf8').replace(/\r\n/g, '\n');
+// Markdown wraps prose at any space; a sentence is looked for with its line breaks and quote markers folded away.
+const squash = (text) => text.replace(/\n>\s?/g, '\n').replace(/\s+/g, ' ');
+// A document is long: a failed match names the pattern, never prints the whole text.
+const has = (text, pattern) => assert.ok(pattern.test(text), `the document says ${pattern}`);
+const NOT_CHECKED = 'These are reviewed built-in operation names; their availability in this environment or player and the signed-in user\'s permissions were not checked.';
+const NO_WRAPPER = 'This does not mean the environment lacks these operations, and the remedy is not a Custom API wrapper. No new built-in binding was added.';
+
+test('the reference quotes every fixed sentence the code prints: the gate line, the usage and catalogue lines, each authoring code, and the not-checked sentence', () => {
+ const reference = squash(read('references', 'dataverse-operations.md'));
+ for (const sentence of [dataverseOperationsDisabledMessage(), USAGE, CATALOGUE_UNAVAILABLE, NOT_CHECKED, NO_WRAPPER, ...Object.values(AUTHORING_CODES)]) {
+ assert.ok(reference.includes(sentence), `references/dataverse-operations.md quotes: ${sentence}`);
+ }
+ for (const code of Object.keys(AUTHORING_CODES).filter((key) => key !== 'catalogue_unavailable')) assert.ok(reference.includes(`\`${code}\``), code);
+ has(reference, /These are two reviewed built-in Dataverse Functions, not Custom APIs discovered in this environment\. Their availability, player support and your permissions have not been checked\./);
+});
+
+test('the reference says why nothing beyond the pair is offered, and that the offer is not a check', () => {
+ const reference = squash(read('references', 'dataverse-operations.md'));
+ for (const name of ['CalculateRollupField', 'IncrementKnowledgeArticleViewCount', 'QualifyLead']) assert.ok(reference.includes(name), name);
+ has(reference, /"Function" or "GET" does not make an operation harmless/);
+ has(reference, /Record-bound Functions add overloads/);
+ has(reference, /set-bound operations have no invocation shape/);
+ has(reference, /Listing is an offer, not a check/);
+ has(reference, /a page's first call can answer 404/);
+ has(reference, /`genpage-upload\.js --actions` writes the array it is given and resolves no name/);
+ has(reference, /2\.17, 2\.18 and 2\.19 do not offer these operations/);
+});
+
+// Custom API support has no feature flag any more, so the builder probes one gate: `dataverse-operations`, which decides the built-in branch only.
+test('the builder probes the dataverse-operations gate alone — Custom API support has no flag, and the gate being off never ends the run or writes [] over kept bindings — and owns the offer, the selection and the one actions.json', () => {
+ const builder = squash(read('agents', 'genpage-customapi-builder.md'));
+ has(builder, /## Step 1 — The `dataverse-operations` gate \(you own it; run it FIRST, always\)/);
+ has(builder, /```powershell node "\$\{PLUGIN_ROOT\}\/scripts\/lib\/feature-flags\.js" dataverse-operations ```/);
+ assert.ok(!/feature-flags\.js" custom-api/.test(builder), 'no custom-api probe is left');
+ has(builder, /It decides the built-in branch \(Step 2b\) only: being off never stops Custom API discovery, never ends this run early, and never writes `\[\]` over bindings a page keeps\./);
+ has(builder, /Custom API support has no feature flag: discovery, authoring and upload are always available, so run Step 2 whenever the intent needs a Custom API\./);
+ assert.ok(!/`actions\.json` containing `\[\]`\. Return `custom-api disabled/.test(builder), 'the old early return is gone');
+ has(builder, /list-dataverse-operations\.js/);
+ has(builder, /Selection is consent; a mention is not\./);
+ has(builder, /Never copy `bindingType`, `parameters`, `response`, `outputPrivacy`, `invocation` or `requiresExplicitSelection`/);
+ has(builder, /Compose \*\*one\*\* full desired array after both branches have finished — never a partial file/);
+ has(builder, /the Custom API rows first, in their existing order, then the new built-in rows in catalogue order/);
+ has(builder, /write \*\*nothing\*\* and return the refusal/);
+ has(builder, /Write it \*\*only\*\* for a current-run add\/replace/);
+ assert.ok(builder.includes(NO_WRAPPER), 'the gate-off sentence for the two names');
+ // The Custom API contract it already had stays.
+ has(builder, /never copy `lookupParameters` into `actions\.json`/i);
+ has(builder, /the working-dir binding file for `genpage-upload\.js --actions`/);
+});
+
+test('the planners signal and never probe; the plan section is optional and sits after Custom API Bindings, before Solution Packaging', () => {
+ const planner = squash(read('agents', 'genpage-planner.md'));
+ has(planner, /"action": "dataverse_operation_discovery_required"/);
+ has(planner, /Do \*\*not\*\* probe the `dataverse-operations` flag, run `list-dataverse-operations\.js`, or decide a binding yourself/);
+ has(planner, /The `whoAmI` your auth preflight runs is neither signal\./);
+ const editPlanner = squash(read('agents', 'genpage-edit-planner.md'));
+ has(editPlanner, /"action": "dataverse_operation_discovery_required"/);
+ has(editPlanner, /\{ intent, selected, beforeNames, provenance \}/);
+ has(editPlanner, /missing preserve evidence is not permission to delete the call/);
+ const schema = read('references', 'plan-schema.md');
+ const at = (heading) => schema.indexOf(`\n${heading}\n`);
+ assert.ok(at('## Custom API Bindings') < at('## Dataverse Operations') && at('## Dataverse Operations') < at('## Solution Packaging'), 'template order');
+ has(squash(schema), /OPTIONAL section — present ONLY when this run's genpage-customapi-builder added or replaced a built-in Dataverse operation/);
+ has(schema, /\| `## Dataverse Operations` \| Planner, page-builder, orchestrator deploy \(Phase 4\.6b\) \| Optional; absent = no new built-in operation\./);
+});
+
+test('the orchestrator dispatches the builder once, re-probes before an add/replace, and halts instead of clearing; the edit flow keeps a preserve away from the gate', () => {
+ const skill = squash(read('skills', 'genpage', 'SKILL.md'));
+ has(skill, /dispatches that same builder \*\*once\*\* for both needs/);
+ has(skill, /### Phase 4\.6b: Built-in Dataverse Operations \(Conditional\)/);
+ has(skill, /\*\*If it prints `disabled`:\*\* halt before page generation\. Write no replacement `actions\.json`, pass no `--actions`, and never write `\[\]` in its place/);
+ has(skill, /a preserve-only edit never consults this gate/);
+ has(skill, /Compare only the \*\*Custom API rows\*\* of `actions\.json` with this table/);
+ has(skill, /A file left by an earlier run is not forwarded\./);
+ const editFlow = squash(read('skills', 'genpage', 'edit-flow.md'));
+ has(editFlow, /\| preserve \(an unrelated edit\) \| not consulted \| omit \|/);
+ has(editFlow, /\| none, but the page binds one \| n\/a \| do not pass \| halt/);
+ has(editFlow, /`\[\]` is passed only for a clear-all the maker chose \(the clear choice below\) — never because the `dataverse-operations` gate turned off/);
+});
+
+test('the page builder emits a button-only call from the reference, only for the plan\'s table; download, rebuild and /app-builder relay the not-checked words', () => {
+ const pageBuilder = squash(read('agents', 'genpage-page-builder.md'));
+ has(pageBuilder, /\$\{PLUGIN_ROOT\}\/references\/dataverse-operations\.md/);
+ has(pageBuilder, /\*\*button-only\*\* pattern \("Generated call"\)/);
+ has(pageBuilder, /never on mount, at render, in a `useEffect`, on a filter or on a timer/);
+ has(pageBuilder, /`res\.ok !== true` returns before `res\.outputs` is read/);
+ const reference = read('references', 'dataverse-operations.md');
+ const pattern = /```tsx\n([\s\S]*?)\n```/.exec(reference.slice(reference.indexOf('## Generated call')))[1];
+ assert.ok(!/useEffect\(\(\) => \{[^}]*read(?:Identity|Version)|console\.|localStorage|JSON\.stringify/.test(pattern), 'the reference pattern never calls on mount, logs, stores or serializes');
+ has(squash(read('references', 'custom-api.md')), /Two `actionBindings` names are not Custom APIs\.\*\* Exactly `WhoAmI` and `RetrieveVersion`/);
+ const appBuilder = squash(read('skills', 'app-builder', 'SKILL.md'));
+ has(appBuilder, /`neededInTarget\.dataverseOperations` \(nothing to deploy\)/);
+ assert.ok(appBuilder.includes(NOT_CHECKED), 'app-builder relays the rebuild\'s sentence');
+ assert.ok(squash(read('references', 'app-spec-schema.md')).includes('`pageBindings.neededInTarget.dataverseOperations`'));
+});
+
+test('AGENTS.md lists the flags left — dataverse-operations OFF with its owner, plan section, gated script and deploy phase — and says Custom API support has none', () => {
+ const agents = squash(read('AGENTS.md'));
+ has(agents, /The remaining flags are `custom-telemetry` \(\*\*OFF\*\*\) and `dataverse-operations` \(\*\*OFF\*\*\)\./);
+ has(agents, /neither does Custom API support: `custom-api` shipped ON in 2\.18\.0 and 2\.19\.0 with its platform dependencies live in every region, so it was removed — Custom API discovery, authoring and upload are always available, and `GENPAGE_ENABLE_CUSTOM_API` is ignored\./);
+ has(agents, /\| \| `custom-telemetry` \| `dataverse-operations` \|/);
+ assert.ok(!/\| `custom-api` \|/.test(agents), 'the flag table has no custom-api column');
+ has(agents, /\| \*\*Gated scripts\*\* \| none \| `list-dataverse-operations\.js` \|/);
+ has(agents, /\| \*\*Deploy phase\*\* \| SKILL Phase 4\.7 \(probe only\) \| SKILL Phase 4\.6b/);
+ has(agents, /Custom API support, with no flag, keeps the rest of that pattern: `genpage-customapi-builder` is its one owner/);
+ has(agents, /Connector and Custom API scripts have no feature-flag backstop because both are always on\./);
+ has(agents, /list-dataverse-operations\.js ← /);
+ has(agents, /dataverse-operations\.js ← The reviewed built-in operation catalogue/);
+});
+
+// The text between one heading and the next, so a recipe is looked for in the phase that runs it.
+const section = (text, from, to) => {
+ const start = text.indexOf(from);
+ assert.ok(start !== -1, `the document has ${from}`);
+ const end = to ? text.indexOf(to, start + from.length) : text.length;
+ assert.ok(end !== -1, `the document has ${to} after ${from}`);
+ return squash(text.slice(start, end));
+};
+
+test('removing every Custom API keeps the built-in rows — `[]` only clears a page with none, or after a confirmation that names each built-in — in the edit planning and deploy recipes, Phase 6 and the builder', () => {
+ const edit = read('skills', 'genpage', 'edit-flow.md');
+ const planning = section(edit, '## Edit Phase 3:', '## Edit Phase 4:');
+ const deploy = section(edit, '## Edit Phase 6:', '## Edit Phase 7:');
+ for (const [phase, text] of [['planning', planning], ['deploy', deploy]]) {
+ // The old recipes wrote `[]` for a Custom-API-only intent, which deletes the built-in rows of a mixed page.
+ assert.ok(!/\*\*Clear all Custom APIs:\*\* write `\[\]`/.test(text), `${phase}: no [] recipe for clearing the Custom APIs`);
+ assert.ok(!/\*\*Remove every Custom API:\*\* write `\[\]`/.test(text), `${phase}: no [] recipe for removing every Custom API`);
+ has(text, /\*\*Remove every Custom API:\*\*[^*]*every built-in operation row \(`WhoAmI`, `RetrieveVersion`\) stays, byte for byte/);
+ has(text, /\*\*Clear every action binding:\*\*[^*]*only when the page holds no built-in operation row, or after the maker's clear choice naming each one it removes/);
+ }
+ has(planning, /On a page that binds one, invoke the builder the same way, with the remove intent naming every Custom API row/);
+ has(deploy, /never `\[\]` while a built-in row remains/);
+ const skill = section(read('skills', 'genpage', 'SKILL.md'), '### Phase 6: Deploy', '**Deploy through `scripts/genpage-upload.js`.**');
+ assert.ok(!/write `\[\]` and pass it to clear all `actionBindings`\./.test(skill), 'Phase 6: the unqualified [] clear is gone');
+ has(skill, /removing every Custom API keeps them/);
+ const builder = section(read('agents', 'genpage-customapi-builder.md'), '## Step 4');
+ has(builder, /\*\*Remove every Custom API:\*\* drop each Custom API row and keep every built-in row byte for byte/);
+ has(builder, /`actions\.json` is `\[\]` only when no row of either kind remains/);
+ has(squash(read('agents', 'genpage-edit-planner.md')), /Clearing the Custom APIs of a page that also binds a built-in operation removes each Custom API row and keeps the built-in calls and bindings/);
+ has(squash(read('references', 'dataverse-operations.md')), /Removing every Custom API is a remove of each Custom API row: the built-in rows stay, byte for byte/);
+});
+
+// A create that binds only built-in operations, followed through the create flow's own words: Phase 4.6 governs the Custom API rows only and
+// probes no flag (Custom API support has none), Phase 4.6b's gate comes next, then one decision writes and passes the whole array — so the
+// built-in rows are bound.
+test('a built-in-only create passes --actions: Phase 4.6 governs Custom API rows only and probes no flag, and one decision after Phase 4.6b writes and passes the array', () => {
+ const skill = read('skills', 'genpage', 'SKILL.md');
+ const customGate = section(skill, '### Phase 4.6:', '### Phase 4.6b:');
+ // The sentinel continues, adding no Custom API row — not a ban on the whole actions file.
+ assert.ok(!/Do not create or pass `actions\.json`/.test(customGate), 'Phase 4.6: no ban on the whole actions file');
+ assert.ok(!/never add `--actions` on upload/.test(customGate), 'Phase 4.6: no ban on --actions');
+ has(customGate, /Custom API support has no feature flag, so there is nothing to probe here\./);
+ assert.ok(!/feature-flags\.js|If it prints `disabled`/.test(customGate), 'Phase 4.6: no probe and no disabled branch');
+ // The sentinel continues with no Custom API rows — not "no actions".
+ assert.ok(!/continue with no actions/.test(customGate), 'Phase 4.6: not "no actions"');
+ has(customGate, /continue with no Custom API rows only when its body is exactly `No custom API bindings\.`/);
+ has(customGate, /This phase governs the Custom API rows only/);
+ // Phase 4.6b's gate, then one decision.
+ const decision = section(skill, '### Phase 4.6c:', '### Phase 4.7:');
+ has(decision, /Decide once, after Phase 4\.6 and Phase 4\.6b/);
+ has(decision, /Then the create passes `--actions '<working-dir>\/actions\.json'`: a page that binds only built-in operations is created with them bound\./);
+ assert.ok(!/custom-api/.test(decision), 'the decision waits for no custom-api flag');
+ has(decision, /\*\*Empty:\*\* the create passes no `--actions`/);
+ // The upload follows that decision, not Phase 4.6 alone.
+ const deploy = section(skill, '### Phase 6: Deploy', '### Phase 6.5:');
+ assert.ok(!/`--actions` line when Phase 4\.6 did not write `actions\.json`/.test(deploy), 'Phase 6: the omission is not keyed to Phase 4.6');
+ assert.ok(!/or Phase 4\.6 wrote `<working-dir>\/actions\.json`/.test(deploy), 'Phase 6: passing is not keyed to Phase 4.6');
+ has(deploy, /the `--actions` line when Phase 4\.6c decided an empty array/);
+ has(deploy, /pass `actions\.json` with `--actions` when Phase 4\.6c decided so/);
+ has(deploy, /The same rule applies to `--actions` for the page's `actionBindings` — Custom API and built-in rows alike/);
+ assert.ok(!/whatever the `custom-api` flag says/.test(deploy), 'Phase 6: no custom-api flag is left to ignore');
+});
+
+// An edit runs its own eight phases; the create flow's Phase 4.6b is never visited. So the edit flow itself must take the edit planner's signal,
+// forward this run's built-in contract through every planner round, and re-probe the gate before it applies an add or replace — the three ways
+// a built-in operation arrives in an edit: asked for up front, found in the planner's clarification, and the flag turned off in between.
+test('the edit flow handles the built-in signal, forwards this run\'s contract through every planner round, and re-probes the gate before applying an add or replace', () => {
+ const edit = read('skills', 'genpage', 'edit-flow.md');
+ const intent = section(edit, '## Edit Phase 3:', '## Edit Phase 4:');
+ const planning = section(edit, '## Edit Phase 4:', '## Edit Phase 5:');
+ const apply = section(edit, '## Edit Phase 5:', '## Edit Phase 6:');
+ const deploy = section(edit, '## Edit Phase 6:', '## Edit Phase 7:');
+ // Asked for up front: the builder runs before planning, and what it wrote this run goes to the planner.
+ assert.ok(!/Phase 4\.6b re-probes it/.test(intent), 'the edit table does not send an edit to the create flow\'s Phase 4.6b');
+ has(intent, /\| add \/ replace \| must be ON \(the builder probes it; Edit Phase 4 re-probes it before Edit Phase 5\)/);
+ has(intent, /Keep what that dispatch wrote this run — the body of `<working-dir>\/dataverse-operations\.md` and `<working-dir>\/actions\.json` — for the edit planner/);
+ has(planning, /The built-in operation contract: the full body of `<working-dir>\/dataverse-operations\.md`, between `----- BEGIN\/END DATAVERSE OPERATIONS -----` delimiters, only when this run's builder wrote it/);
+ has(planning, /The `actionBindings` upload file status \(Custom API and built-in rows alike\)/);
+ // Found in clarification: the planner's signal is handled here, and the refreshed contract goes back to it.
+ has(planning, /\*\*If the planner returns `\{ "action": "dataverse_operation_discovery_required", … \}`\*\*/);
+ has(planning, /Dispatch `genpage-customapi-builder` once with \*\*Mode: `edit`\*\*/);
+ has(planning, /re-invoke the edit planner with this run's `dataverse-operations\.md` body as the built-in operation contract and `<working-dir>\/actions\.json` as the upload file status/);
+ has(planning, /- \*\*`\{ "action": "dataverse_operation_discovery_required", … \}`\*\* — handled above\./);
+ // A builder that adds nothing does not send the planner back into the same signal.
+ has(planning, /re-invoke the planner with the built-in operation intent `none — not added this run` and no contract, so it plans the edit without that call/);
+ has(squash(read('agents', 'genpage-edit-planner.md')), /When your prompt says `none — not added this run`, the builder added none: plan the edit without that call and do not signal again/);
+ has(planning, /every prior discovery \(connector, Custom API and built-in operation contracts, and their upload file status; entities\)/);
+ // Turned off in between: the edit intent selects a re-probe right before the source is edited, and OFF halts without touching the bindings.
+ has(planning, /node "\$\{PLUGIN_ROOT\}\/scripts\/lib\/feature-flags\.js" dataverse-operations/);
+ has(planning, /the edit intent, not a plan heading, selects this probe/);
+ has(planning, /\*\*If it prints `disabled`:\*\* halt before Edit Phase 5 edits the source\. Write no replacement `actions\.json`, pass no `--actions`, and never write `\[\]` in its place/);
+ has(planning, /A preserve, a remove or a confirmed clear never runs this probe/);
+ has(apply, /`\$\{PLUGIN_ROOT\}\/references\/dataverse-operations\.md` — when the approved edit adds or replaces a built-in operation/);
+ assert.ok(!/Phase 4\.6b halts instead/.test(deploy), 'deploy: the edit\'s own re-probe halts, not the create flow\'s');
+ has(deploy, /the Edit Phase 4 re-probe halts instead/);
+ has(deploy, /Omit `--actions` when the page's `actionBindings` are unchanged \(Custom API and built-in rows alike\)\./);
+ // The create flow routes an edit to these phases and says so.
+ const skill = read('skills', 'genpage', 'SKILL.md');
+ has(section(skill, '## Edit Flow'), /Edit Phase 4 handles `dataverse_operation_discovery_required`, forwards this run's built-in operation contract through every planner round, and re-probes `dataverse-operations` before an add or replace is applied — the create flow's Phase 4\.6b is not visited/);
+ has(section(skill, '#### 1c.', '#### Invocation prompt'), /In an edit, Edit Phase 4 of edit-flow\.md handles this signal/);
+ // The edit planner takes the forwarded block as this run's selection; AGENTS.md names the edit's own re-probe.
+ has(squash(read('agents', 'genpage-edit-planner.md')), /unless your prompt carries this run's built-in operation contract \(the body of the builder's `dataverse-operations\.md` between `----- BEGIN\/END DATAVERSE OPERATIONS -----` lines\)/);
+ has(squash(read('AGENTS.md')), /an edit re-probes in edit-flow\.md, Edit Phase 4/);
+});
+
+// A clear of a page that binds a built-in operation deletes it, so its permission is one fixed record the evaluator can tie to the upload it
+// covers — the maker's answer to a two-option question, written again right before that upload — never a yes found anywhere in the log.
+test('a clear of a page that binds a built-in needs the maker\'s clear choice, recorded again right before each upload it covers — never a yes to adding or keeping one', () => {
+ const edit = read('skills', 'genpage', 'edit-flow.md');
+ const deploy = section(edit, '## Edit Phase 6:', '## Edit Phase 7:');
+ has(deploy, /\*\*The clear choice, recorded for each upload\.\*\* A clear of a page that binds a built-in operation is the maker's choice from Edit Phase 3 \(or from the edit planner's `clear_choice_required`\), made before any binding was reconciled and before the plan was approved\./);
+ has(deploy, /Right before each upload it authorizes, record the confirmed clear again as its own line in `workflow-log\.md`/);
+ has(deploy, /Clear choice: Clear every action binding of page <page-id>, removing <names>/);
+ has(deploy, /Only that line, for this page and every built-in operation it holds, permits `\[\]`, and it covers that one upload: write it again before a retry/);
+ has(deploy, /`Clear choice: Keep <names>`, a yes to adding or keeping an operation, an answer with conditions, or a choice written after the upload is no permission/);
+ has(deploy, /\*\*Unattended:\*\* do not clear/);
+ has(section(read('agents', 'genpage-customapi-builder.md'), '## Step 4'), /only the maker's clear choice, asked before any binding is reconciled \(edit-flow\.md, Edit Phase 3\) and recorded again right before each upload it authorizes, permits `\[\]`/);
+ const reference = squash(read('references', 'dataverse-operations.md'));
+ has(reference, /\| clear all \| after the maker's clear choice, asked before any binding is reconciled or the plan is approved, which names the built-ins it removes \| `\[\]` \| delete every call \|/);
+ has(reference, /recorded then and again right before each upload it covers as `Clear choice: Clear every action binding of page <page-id>, removing <names>`/);
+ has(section(read('skills', 'genpage', 'SKILL.md'), '### Phase 6: Deploy', '**Deploy through `scripts/genpage-upload.js`.**'), /only after the maker's clear choice naming each one, asked before any binding is reconciled or the plan is approved \(edit-flow\.md, Edit Phase 3\) and recorded again right before the upload/);
+});
+
+// The clear choice decides what the edit removes, so it is asked before anything is removed: before Edit Phase 3 reconciles a binding, before the
+// edit planner plans and the maker approves the plan, and so before Edit Phase 5 edits the source. Asked after that, a `Keep` would come too late —
+// the calls and their buttons would already be gone, and nothing puts them back. A clear the planner's clarification turns up is asked the same
+// way, before the plan is approved; the deploy step only records the confirmed answer again for each upload.
+test('the clear choice is asked first — before any binding is reconciled and before the plan is approved — and on Keep the built-in calls and bindings stay', () => {
+ const edit = read('skills', 'genpage', 'edit-flow.md');
+ const phase3 = edit.slice(edit.indexOf('## Edit Phase 3:'), edit.indexOf('## Edit Phase 4:'));
+ const asked = phase3.indexOf('**The clear choice — asked first.**');
+ assert.ok(asked !== -1, 'Edit Phase 3 asks the clear choice');
+ for (const recipe of ['> **Connectors are owned by', '> **Custom APIs are owned by', '> **Built-in Dataverse operations']) {
+ assert.ok(phase3.indexOf(recipe) !== -1 && asked < phase3.indexOf(recipe), `the clear choice is asked before ${recipe}`);
+ }
+ const intent = squash(phase3);
+ has(intent, /\*\*The clear choice — asked first\.\*\* A request to clear every action binding of a page whose `actionBindings` holds a built-in operation row \(`WhoAmI`, `RetrieveVersion`\) deletes those operations too, so the maker chooses before anything else in this edit: before any binding is reconciled \(below\), before the edit planner runs and the plan is approved \(Edit Phase 4\), and before Edit Phase 5 touches the source/);
+ has(intent, /Ask with `AskUserQuestion` with exactly two options — `Clear every action binding, removing <names>` and `Keep <names>`/);
+ has(intent, /Clear choice: Clear every action binding of page <page-id>, removing <names>/);
+ has(intent, /\*\*Keep:\*\* there is no clear\. Neither the built-in calls — their handlers, buttons and UI — nor their bindings are removed/);
+ has(intent, /\*\*Unattended:\*\* do not clear and ask nothing; stop before any binding or source changes/);
+ has(intent, /Silence is never a clear\./);
+ has(intent, /\| clear all \| after the maker's clear choice, asked first \(above\), which names the built-ins removed \| `\[\]` \| delete every call \|/);
+ // Planning gets the answer; a clear found in the planner's clarification is asked before the plan is approved.
+ const planning = section(edit, '## Edit Phase 4:', '## Edit Phase 5:');
+ has(planning, /The clear choice from Edit Phase 3, when one was asked: its `Clear choice:` line, verbatim/);
+ has(planning, /\*\*If the planner returns `\{ "action": "clear_choice_required", … \}`\*\*/);
+ has(planning, /The plan is approved only after the maker chose, so the source is never edited before that choice\./);
+ has(planning, /- \*\*`\{ "action": "clear_choice_required", … \}`\*\* — handled above\./);
+ has(planning, /every prior discovery \(connector, Custom API and built-in operation contracts, and their upload file status; entities\), the clear choice, and every answer already gathered/);
+ // Deploy records the answer again; it never asks the question.
+ const deploy = section(edit, '## Edit Phase 6:', '## Edit Phase 7:');
+ assert.ok(!/exactly two options/.test(deploy), 'Edit Phase 6 does not ask the clear question');
+ has(deploy, /Never ask it for the first time here — the source was edited in Edit Phase 5/);
+ // The edit planner plans a clear only on a forwarded choice, keeps everything on Keep, and asks for the choice rather than planning without it.
+ const editPlanner = squash(read('agents', 'genpage-edit-planner.md'));
+ has(editPlanner, /\*\*clear all\*\* — only when your prompt carries the maker's clear choice `Clear choice: Clear every action binding of page <page-id>, removing <names>`/);
+ has(editPlanner, /On `Clear choice: Keep <names>` there is no clear: keep the built-in calls — their handlers, buttons and UI — and their bindings/);
+ has(editPlanner, /"action": "clear_choice_required"/);
+ // No document still asks the choice in the deploy phase.
+ for (const [name, text] of [
+ ['edit-flow.md', squash(edit)],
+ ['genpage-edit-planner.md', editPlanner],
+ ['genpage-customapi-builder.md', squash(read('agents', 'genpage-customapi-builder.md'))],
+ ['SKILL.md', squash(read('skills', 'genpage', 'SKILL.md'))],
+ ['dataverse-operations.md', squash(read('references', 'dataverse-operations.md'))],
+ ]) {
+ assert.ok(!/clear choice[^.]*\(?(?:edit-flow\.md,? )?Edit Phase 6\b/.test(text), `${name}: the clear choice is not placed in Edit Phase 6`);
+ }
+});
+
+// A create that asks for WhoAmI or RetrieveVersion sends the planner's signal to the builder once. When the builder adds none — its gate is off,
+// or the maker declined the offer or selected neither — it writes no `dataverse-operations.md`, and the maker's request still reads as the same
+// signal. So the builder reports that outcome in so many words, the orchestrator forwards it to every later planner round, and the planner
+// completes the plan without the call instead of asking for the offer again: the edit flow's `none — not added this run`, now in the create flow.
+test('a create whose built-in offer adds nothing — the gate off, or the offer declined — forwards `none — not added this run`, and the planner completes without the call instead of signalling again', () => {
+ const builder = section(read('agents', 'genpage-customapi-builder.md'), '## Step 5');
+ has(builder, /When this run adds none — the `dataverse-operations` gate is off, or the maker declined the offer or selected neither — say `dataverse-operations\.md: none — not added this run` with the reason \(`gate off` or `none selected`\)/);
+ has(builder, /the orchestrator forwards that outcome, never a contract, so the planner completes its plan without the call instead of asking for this offer again/);
+ has(builder, /whether `dataverse-operations\.md` was written this run \(or `none — not added this run` and why\)/);
+ assert.ok(!/so the orchestrator forwards nothing/.test(builder), 'the builder no longer tells the orchestrator to forward nothing');
+ const skill = read('skills', 'genpage', 'SKILL.md');
+ const offer = section(skill, '#### 1c.', '#### Invocation prompt');
+ has(offer, /When it reports `dataverse-operations\.md: none — not added this run` — its `dataverse-operations` gate is off, or the maker declined the offer or selected neither — there is no built-in contract/);
+ has(offer, /forward the outcome `none — not added this run` \(never a contract\) to the planner in this and every later round/);
+ has(offer, /so the builder is not dispatched a second time for the same request/);
+ const prompt = section(skill, '#### Invocation prompt', '### Phase 2:');
+ has(prompt, /the outcome `none — not added this run` when this run's builder was dispatched for one and added none \(1c\)/);
+ has(prompt, /\[Only when this run's builder added none:\] Built-in Dataverse operations: `none — not added this run`\./);
+ has(prompt, /plan the page without that call, write no `## Dataverse Operations` section, and do not return `dataverse_operation_discovery_required` again/);
+ has(squash(read('agents', 'genpage-planner.md')), /When your prompt says `none — not added this run`, the builder was already dispatched for the request and added none — its `dataverse-operations` gate is off, or the maker declined the offer or selected neither\. Plan the page without that call, write no `## Dataverse Operations` section, and do not signal again/);
+ has(squash(read('references', 'dataverse-operations.md')), /it reports `dataverse-operations\.md: none — not added this run`\. The orchestrator forwards that outcome, never a contract, to the create or edit planner, which completes its plan without the call and does not ask for the offer again/);
+ // The edit flow's own rule stays as it was.
+ has(squash(read('agents', 'genpage-edit-planner.md')), /When your prompt says `none — not added this run`, the builder added none: plan the edit without that call and do not signal again/);
+ has(section(read('skills', 'genpage', 'edit-flow.md'), '## Edit Phase 4:', '## Edit Phase 5:'), /re-invoke the planner with the built-in operation intent `none — not added this run` and no contract/);
+});
+
+// Custom API support has no feature flag any more, so nothing keeps a Custom API row back: a removal always removes. The builder drops the named
+// rows, every recipe uploads the array it wrote, and no document a run follows still teaches the OFF branch — a removal "not performed
+// (custom-api disabled)", an upload that omits --actions because the flag kept the rows, or a plan that waits for the flag. (A file name such as
+// `custom-api-bindings.md` or `custom-api.md` is not the flag.)
+const FLAG_BRANCH = /`custom-api`|\bcustom-api (?:OFF|ON|off|on|disabled|enabled|flag|gate|feature)\b|removal not performed|waits for the flag|GENPAGE_ENABLE_CUSTOM_API/;
+test('a Custom API removal always removes — no flag keeps a row back: the builder drops the named rows, every recipe uploads what it wrote, and no recipe keeps an OFF branch', () => {
+ const builder = read('agents', 'genpage-customapi-builder.md');
+ const reconcile = section(builder, '## Step 4', '## Step 5');
+ has(reconcile, /- \*\*Remove:\*\* drop the named binding\(s\)\. - \*\*Remove every Custom API:\*\* drop each Custom API row and keep every built-in row byte for byte/);
+ has(section(builder, '## Step 5'), /Return a concise summary: mode, the `dataverse-operations` gate result, the `name`s of the Custom API bindings and of the built-in operations written \(or "none"\), and whether `dataverse-operations\.md` was written this run/);
+ const edit = read('skills', 'genpage', 'edit-flow.md');
+ const planning = section(edit, '## Edit Phase 3:', '## Edit Phase 4:');
+ has(planning, /The builder discovers and returns the updated set\./);
+ has(planning, /It drops those rows and nothing else, and writes the remaining rows to `actions\.json` and `No custom API bindings\.` to `custom-api-bindings\.md`; pass `--actions` on upload\./);
+ has(planning, /A clear is the maker's own request for an empty array: on a page with no built-in row that is what removing every Custom API means, as before\./);
+ const deploy = section(edit, '## Edit Phase 6:', '## Edit Phase 7:');
+ has(deploy, /Include `--actions '<working-dir>\/actions\.json'` in the upload — a full replace that also deletes any binding left out of the file\./);
+ has(deploy, /On a page that binds one, upload the `actions\.json` the builder wrote \(the built-in rows\) with `--actions` — never `\[\]` while a built-in row remains\./);
+ has(squash(read('references', 'dataverse-operations.md')), /Removing every Custom API is a remove of each Custom API row: the built-in rows stay, byte for byte, and the file is never `\[\]` while one remains — a removal is never turned into a clear\./);
+ // Planning describes the builder's output as it is: no Custom API row when the page needs none, and the built-in rows a maker selected.
+ has(section(read('skills', 'genpage', 'SKILL.md'), '#### 1b.', '#### 1c.'), /The builder remains the single owner of Custom API discovery, which has no feature flag: it writes `No custom API bindings\.` and no Custom API row when the page needs no Custom API \(`actions\.json` is then `\[\]`, unless built-in operation rows were selected — 1c\)/);
+ for (const parts of [
+ ['agents', 'genpage-customapi-builder.md'], ['agents', 'genpage-planner.md'], ['agents', 'genpage-edit-planner.md'], ['agents', 'genpage-page-builder.md'],
+ ['skills', 'genpage', 'SKILL.md'], ['skills', 'genpage', 'edit-flow.md'], ['references', 'dataverse-operations.md'], ['references', 'app-spec-schema.md'],
+ ]) {
+ const text = squash(read(...parts));
+ const match = text.match(FLAG_BRANCH);
+ assert.equal(match, null, `${parts.join('/')} still says: ${match && text.slice(Math.max(0, match.index - 80), match.index + 80)}`);
+ }
+ // Where the flag was announced, the documents now say it is gone and the variable is ignored.
+ has(squash(read('references', 'custom-api.md')), /\*\*Custom API support has no feature flag\.\*\* Discovery, authoring and upload are always available; the `custom-api` flag that once gated them was removed, and `GENPAGE_ENABLE_CUSTOM_API` is ignored\./);
+ has(squash(read('README.md')), /Custom API support has no feature flag either: calling a supported public Dataverse Custom API Action or Function from a generated page \(`executeAction` \/ `executeFunction` \/ `listBoundActions`\) is always available\. `GENPAGE_ENABLE_CUSTOM_API` is ignored — `0` no longer turns Custom API discovery off, and there is nothing to turn on\./);
+});
diff --git a/plugins/model-apps/scripts/tests/dataverse-operations-real-bundle.test.js b/plugins/model-apps/scripts/tests/dataverse-operations-real-bundle.test.js
new file mode 100644
index 000000000..3077996c3
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/dataverse-operations-real-bundle.test.js
@@ -0,0 +1,143 @@
+'use strict';
+// The two reviewed built-in Dataverse operations (WhoAmI, RetrieveVersion) as page bindings through the REAL vendored SDK, over the stateful fake of the tables behind a page
+// (helpers/fake-genpage-server.js).
+//
+// What only the real bundle can say: the four-key entries lib/dataverse-operations.js projects (toActionBinding), written beside an unrelated Custom API binding, are persisted in the page's
+// config.json exactly — no property added, none dropped, the order kept — they are read back the same, a download states the whole list in the spec (no descriptor key reached the wire, so the
+// list is not left out) and names them apart from the Custom APIs, and a rebuild that sends back what the download stated writes nothing. This proves persistence, not the player: no call of
+// either operation is made or simulated here.
+const { test } = require('node:test');
+const assert = require('node:assert');
+const fs = require('node:fs');
+const path = require('node:path');
+const { makeGenpageSdk, pageFolderFiles } = require('../lib/genpage-sdk.js');
+const { statedPageBindings } = require('../lib/app-spec.js');
+const { getReviewedDataverseOperation, toActionBinding } = require('../lib/dataverse-operations.js');
+const { parseDownloadedPages, pageBindingsReport, pageBindingsNote } = require('../download-model-app.js');
+const { FakeGenPageServer, INSTANCE, ACCOUNT_TABLE, appTransport } = require('./helpers/fake-genpage-server.js');
+const { makeTempDir } = require('./helpers/temp-dirs.js');
+
+const SOURCE = "import * as React from 'react';\nexport default function Page() { return <div>Operations</div>; }\n";
+const APPROVE = { name: 'contoso_ApproveOrder', isFunction: false, boundEntityLogicalName: 'account', displayName: 'Approve order', parameterKinds: { Comment: 'String' } };
+const BINDINGS = [APPROVE, toActionBinding(getReviewedDataverseOperation('WhoAmI')), toActionBinding(getReviewedDataverseOperation('RetrieveVersion'))];
+
+function makeServer() {
+ const server = new FakeGenPageServer();
+ server.serveTable(ACCOUNT_TABLE);
+ return server;
+}
+
+async function withBackend(server, fn, { apps = false } = {}) {
+ // A delete scans every app's navigation for the page first, so a cleanup runs over the fake's app tables too (appTransport).
+ const genpage = makeGenpageSdk(INSTANCE, { httpClient: apps ? appTransport(server).http : server.http() });
+ try {
+ return await fn(genpage);
+ } finally {
+ await genpage.dispose();
+ }
+}
+
+// What a download makes of a page the backend read: the folder it writes, read back as the spec's page entry.
+function downloaded(page, unkept = []) {
+ const root = makeTempDir('dv-ops-real-');
+ const dir = path.join(root, page.id);
+ fs.mkdirSync(dir, { recursive: true });
+ for (const [name, text] of Object.entries(pageFolderFiles(page))) fs.writeFileSync(path.join(dir, name), text, 'utf8');
+ const [entry] = parseDownloadedPages(root, root, null, [], [], unkept);
+ return entry;
+}
+
+const rows = (server, id) => Object.fromEntries(server.filesOf(id).map((f) => [f.filename, server.fileText(f.id)]));
+const changeWrites = (server) => server.writes().filter((w) => !/PublishXml/.test(w));
+
+test('REAL BUNDLE: both built-in projections beside a Custom API are persisted exactly, read back, stated whole by a download, and a rebuild of what it stated writes nothing', async () => {
+ assert.deepStrictEqual(BINDINGS.slice(1), [
+ { name: 'WhoAmI', isFunction: true, displayName: 'Current Dataverse identity', parameterKinds: {} },
+ { name: 'RetrieveVersion', isFunction: true, displayName: 'Dataverse server version', parameterKinds: {} },
+ ]);
+ const server = makeServer();
+ await withBackend(server, async (genpage) => {
+ const made = await genpage.create({ name: 'Operations', source: SOURCE, dataSources: ['account'], model: 'gpt-4.1', actionBindings: BINDINGS, prompt: 'Show who I am', agentMessage: 'Shown' });
+ const id = made.pageId;
+ // Persisted: the page's own config.json row holds the list exactly, in its order, with nothing added.
+ const config = JSON.parse(rows(server, id)['config.json']);
+ assert.deepStrictEqual(config.actionBindings, BINDINGS);
+ assert.deepStrictEqual(config.actionBindings.map((entry) => Object.keys(entry)), [
+ ['name', 'isFunction', 'boundEntityLogicalName', 'displayName', 'parameterKinds'],
+ ['name', 'isFunction', 'displayName', 'parameterKinds'],
+ ['name', 'isFunction', 'displayName', 'parameterKinds'],
+ ]);
+ // Read back the same.
+ const page = await genpage.read(id);
+ assert.deepStrictEqual(page.actionBindings, BINDINGS);
+ // Downloaded: the whole list is stated (a descriptor key on the wire would have left it out), and the report names the built-ins apart from the Custom API.
+ const unkept = [];
+ const entry = downloaded(page, unkept);
+ assert.deepStrictEqual(unkept, []);
+ assert.deepStrictEqual(entry.actionBindings, BINDINGS);
+ const report = pageBindingsReport([{ ...entry, key: 'operations', name: 'Operations' }], unkept);
+ assert.deepStrictEqual(report.neededInTarget, { customApis: ['contoso_ApproveOrder'], dataverseOperations: ['RetrieveVersion', 'WhoAmI'] });
+ assert.doesNotMatch(pageBindingsNote(report).split('\n').find((line) => /built-in Dataverse operation/.test(line)), /deploy/i);
+ // Rebuilt from what the download stated: nothing changes, so nothing is written.
+ const before = rows(server, id);
+ server.requests.length = 0;
+ const out = await genpage.update(id, { source: SOURCE, name: 'Operations', dataSources: entry.dataSources, model: entry.model, ...statedPageBindings(entry), prompt: 'again', agentMessage: 'again' });
+ assert.strictEqual(out.unchanged, true);
+ assert.deepStrictEqual(changeWrites(server), [], 'the page already holds what the spec states');
+ assert.deepStrictEqual(rows(server, id), before);
+ });
+});
+
+test('REAL BUNDLE: an update that leaves the list out keeps the page\'s built-in bindings — nothing strips, repairs or reorders them — and a legacy entry is carried as it is', async () => {
+ const legacy = [APPROVE, { name: 'WhoAmI' }];
+ const server = makeServer();
+ await withBackend(server, async (genpage) => {
+ const made = await genpage.create({ name: 'Legacy', source: SOURCE, dataSources: ['account'], model: 'gpt-4.1', actionBindings: legacy, prompt: 'p', agentMessage: 'r' });
+ // An unrelated edit: the update states no action list, so the page keeps its own.
+ await genpage.update(made.pageId, { source: SOURCE.replace('Operations', 'Operations!'), name: 'Legacy', dataSources: ['account'], model: 'gpt-4.1', prompt: 'edit', agentMessage: 'edited' });
+ assert.deepStrictEqual(JSON.parse(rows(server, made.pageId)['config.json']).actionBindings, legacy, 'no isFunction, display name or parameterKinds added');
+ const entry = downloaded(await genpage.read(made.pageId));
+ assert.deepStrictEqual(entry.actionBindings, legacy);
+ assert.deepStrictEqual(pageBindingsReport([{ ...entry, key: 'legacy', name: 'Legacy' }], []).neededInTarget, { customApis: ['contoso_ApproveOrder'], dataverseOperations: ['WhoAmI'] });
+ });
+});
+
+// ── Cleanup of a page that binds them, as a live check must prove it ─────────────────────────────────────────────────────────────────
+// What a create answers is the page's identity, not an inventory: its file rows and conversation messages exist although the answer names none of
+// them. So a cleanup starts from the page id, reads what the page holds (describe), deletes through the supported path, and reads every class back —
+// and a child that survives keeps the cleanup incomplete, whatever the page's own read says.
+test('REAL BUNDLE: a cleanup inventories a page\'s children by reading them, not from the create\'s answer, and proves each absent by reading it back', async () => {
+ const server = makeServer();
+ await withBackend(server, async (genpage) => {
+ const made = await genpage.create({ name: 'Operations', source: SOURCE, dataSources: ['account'], model: 'gpt-4.1', actionBindings: BINDINGS, prompt: 'Show who I am', agentMessage: 'Shown' });
+ const id = made.pageId;
+ // The answer carries no list of the rows it made…
+ assert.ok(!['files', 'fileRows', 'conversation', 'conversationMessages', 'messages'].some((key) => Object.hasOwn(made, key)), JSON.stringify(Object.keys(made)));
+ // …and yet there are some: an omitted field is no evidence that nothing was made.
+ assert.ok(server.filesOf(id).length > 0 && server.messagesOf(id).length > 0, 'the page has file rows and a conversation');
+ const inventory = await genpage.describe(id);
+ assert.ok(inventory.fileRows > 0 && inventory.conversationMessages === server.messagesOf(id).length, JSON.stringify(inventory));
+ const removed = await genpage.delete(id, { allowDestructive: true });
+ assert.deepStrictEqual([removed.deleted, removed.verified, removed.historyRemoved], [true, true, true]);
+ // ALL ABSENT only by reads, class by class.
+ assert.deepStrictEqual([server.filesOf(id).length, server.messagesOf(id).length], [0, 0]);
+ await assert.rejects(genpage.describe(id), (error) => error.code === 'GENPAGE_NOT_FOUND');
+ }, { apps: true });
+});
+
+test('REAL BUNDLE: a child the delete could not remove keeps the cleanup incomplete — the page reads as gone, its conversation does not', async () => {
+ const server = makeServer();
+ await withBackend(server, async (genpage) => {
+ const made = await genpage.create({ name: 'Operations', source: SOURCE, dataSources: ['account'], model: 'gpt-4.1', actionBindings: BINDINGS, prompt: 'Show who I am', agentMessage: 'Shown' });
+ const id = made.pageId;
+ const messages = server.messagesOf(id).length;
+ assert.ok(messages > 0);
+ // The service refuses every delete of a conversation message: the page goes, its history stays.
+ server.failOn = (method, path) => (method === 'DELETE' && /^\/agentconversationmessages\(/.test(path) ? 403 : undefined);
+ const removed = await genpage.delete(id, { allowDestructive: true });
+ assert.strictEqual(removed.verified, true, 'the page itself reads as gone');
+ assert.strictEqual(removed.historyRemoved, false, 'and the result does not claim its history went with it');
+ assert.ok(removed.warnings.some((warning) => /conversation history was not fully removed|may remain/.test(warning)), JSON.stringify(removed.warnings));
+ assert.strictEqual(server.messagesOf(id).length, messages, 'a known child remains: the cleanup is not all absent until it is resolved and removed');
+ }, { apps: true });
+});
diff --git a/plugins/model-apps/scripts/tests/dataverse-operations.test.js b/plugins/model-apps/scripts/tests/dataverse-operations.test.js
new file mode 100644
index 000000000..1ec4aac0c
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/dataverse-operations.test.js
@@ -0,0 +1,230 @@
+'use strict';
+// lib/dataverse-operations.js: the reviewed catalogue of built-in Dataverse operations a generative page may bind — exactly WhoAmI and
+// RetrieveVersion — and the one projection of a descriptor onto the four-key `actionBindings` wire entry.
+//
+// What these pin: a name is recognized only by an exact match (no case, prefix, namespace or display-name folding, and no inherited name such as
+// `__proto__`); a caller cannot widen or alter what a later caller reads; the wire entry has exactly the four keys a page list may state, so a
+// built-in beside a Custom API leaves the list statable (a spread descriptor would leave the whole list out of an App Spec); an altered
+// descriptor is refused, never repaired; and a refusal names a fixed code and a fixed sentence, never the text it was given.
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const ops = require('../lib/dataverse-operations.js');
+const { statableBindings } = require('../lib/page-bindings.js');
+
+const WHO_AM_I = {
+ name: 'WhoAmI',
+ displayName: 'Current Dataverse identity',
+ isFunction: true,
+ bindingType: 'Global',
+ parameters: [],
+ parameterKinds: {},
+ response: {
+ typeName: 'Microsoft.Dynamics.CRM.WhoAmIResponse',
+ properties: { BusinessUnitId: 'Edm.Guid', UserId: 'Edm.Guid', OrganizationId: 'Edm.Guid' },
+ },
+ outputPrivacy: 'identity',
+ invocation: 'user-triggered',
+ requiresExplicitSelection: true,
+};
+const RETRIEVE_VERSION = {
+ name: 'RetrieveVersion',
+ displayName: 'Dataverse server version',
+ isFunction: true,
+ bindingType: 'Global',
+ parameters: [],
+ parameterKinds: {},
+ response: {
+ typeName: 'Microsoft.Dynamics.CRM.RetrieveVersionResponse',
+ properties: { Version: 'Edm.String' },
+ },
+ outputPrivacy: 'service-version',
+ invocation: 'user-triggered',
+ requiresExplicitSelection: true,
+};
+const VERIFICATION = { mode: 'catalogue-only', environment: 'not-checked', runtime: 'not-checked', privileges: 'not-checked' };
+const NOT_IN_CATALOGUE = 'Only WhoAmI and RetrieveVersion are offered by this feature. Other Dataverse operations require separately reviewed support.';
+const INVALID_CONTRACT = 'The selected built-in operation must be an explicitly declared, unbound Function with no inputs.';
+const CUSTOM_API_ROW = { name: 'new_ApproveOrder', isFunction: false, boundEntityLogicalName: 'salesorder', displayName: 'Approve Order', parameterKinds: { Comment: 'String' } };
+
+// Every own object and array under `value`, so a test can hold each of them to being frozen.
+function everyObject(value, out = []) {
+ if (value && typeof value === 'object') {
+ out.push(value);
+ for (const key of Object.keys(value)) everyObject(value[key], out);
+ }
+ return out;
+}
+
+test('the catalogue is revision 1, catalogue-only, and holds exactly WhoAmI then RetrieveVersion with their reviewed contracts', () => {
+ const catalogue = ops.getDataverseOperationCatalogue();
+ assert.deepStrictEqual(Object.keys(catalogue), ['catalogueVersion', 'verification', 'operations']);
+ assert.equal(catalogue.catalogueVersion, 1);
+ assert.deepStrictEqual(catalogue.verification, VERIFICATION);
+ assert.deepStrictEqual(catalogue.operations, [WHO_AM_I, RETRIEVE_VERSION]);
+ // The descriptor's own key order is the order the listing prints.
+ assert.deepStrictEqual(Object.keys(catalogue.operations[0]), Object.keys(WHO_AM_I));
+ assert.equal(ops.CATALOGUE_VERSION, 1);
+ assert.deepStrictEqual(ops.REVIEWED_OPERATION_NAMES, ['WhoAmI', 'RetrieveVersion']);
+});
+
+test('an exact name finds its frozen descriptor; anything else — case, spacing, namespace, prefix, display name, an inherited name, a non-string — finds nothing', () => {
+ assert.deepStrictEqual(ops.getReviewedDataverseOperation('WhoAmI'), WHO_AM_I);
+ assert.deepStrictEqual(ops.getReviewedDataverseOperation('RetrieveVersion'), RETRIEVE_VERSION);
+ for (const name of [
+ 'whoami', 'WHOAMI', 'Whoami', ' WhoAmI', 'WhoAmI ', 'WhoAmI\n', 'Microsoft.Dynamics.CRM.WhoAmI', 'mscrm.WhoAmI', 'WhoAm', 'WhoAmIResponse', 'WhoAmI()',
+ 'Who*', '*', '%', '', 'retrieveversion', 'RetrieveVersions', 'Microsoft.Dynamics.CRM.RetrieveVersion', 'Current Dataverse identity', 'Dataverse server version',
+ '__proto__', 'constructor', 'toString', 'hasOwnProperty', 'valueOf', 'CalculateRollupField', 'IncrementKnowledgeArticleViewCount', 'QualifyLead',
+ 'RetrieveUserPrivileges', 'new_ApproveOrder',
+ ]) {
+ assert.equal(ops.getReviewedDataverseOperation(name), null, JSON.stringify(name));
+ }
+ for (const value of [undefined, null, 0, 42, true, {}, [], ['WhoAmI'], { name: 'WhoAmI' }, { toString: () => 'WhoAmI' }, Object('WhoAmI'), Symbol('WhoAmI')]) {
+ assert.equal(ops.getReviewedDataverseOperation(value), null, String(typeof value));
+ }
+});
+
+test('no caller can widen or alter what a later caller reads: the catalogue and every descriptor are frozen through and through', () => {
+ const catalogue = ops.getDataverseOperationCatalogue();
+ for (const object of everyObject(catalogue)) assert.ok(Object.isFrozen(object), `frozen: ${JSON.stringify(object).slice(0, 60)}`);
+ assert.throws(() => { catalogue.operations.push({ ...WHO_AM_I, name: 'CalculateRollupField' }); }, TypeError);
+ assert.throws(() => { catalogue.operations[0].isFunction = false; }, TypeError);
+ assert.throws(() => { catalogue.operations[0].parameterKinds.Target = 'String'; }, TypeError);
+ assert.throws(() => { catalogue.operations[1].response.properties.Extra = 'Edm.String'; }, TypeError);
+ assert.throws(() => { catalogue.verification.environment = 'checked'; }, TypeError);
+ assert.throws(() => { ops.getReviewedDataverseOperation('WhoAmI').parameters.push('x'); }, TypeError);
+ assert.deepStrictEqual(ops.getDataverseOperationCatalogue().operations, [WHO_AM_I, RETRIEVE_VERSION]);
+ assert.equal(ops.getReviewedDataverseOperation('CalculateRollupField'), null);
+});
+
+test('toActionBinding gives a fresh four-key wire entry built from the catalogue, never the descriptor spread onto the wire', () => {
+ for (const [descriptor, displayName] of [[WHO_AM_I, 'Current Dataverse identity'], [RETRIEVE_VERSION, 'Dataverse server version']]) {
+ const canonical = ops.getReviewedDataverseOperation(descriptor.name);
+ for (const input of [canonical, structuredClone(descriptor), JSON.parse(JSON.stringify(descriptor))]) {
+ const wire = ops.toActionBinding(input);
+ assert.deepStrictEqual(Object.keys(wire), ['name', 'isFunction', 'displayName', 'parameterKinds']);
+ assert.deepStrictEqual(wire, { name: descriptor.name, isFunction: true, displayName, parameterKinds: {} });
+ assert.equal(Object.isFrozen(wire), false, 'the caller owns the result');
+ // Mutating one result changes neither the catalogue nor the next result.
+ wire.parameterKinds.Injected = 'String';
+ wire.displayName = 'changed';
+ assert.deepStrictEqual(ops.toActionBinding(input), { name: descriptor.name, isFunction: true, displayName, parameterKinds: {} });
+ assert.deepStrictEqual(ops.getReviewedDataverseOperation(descriptor.name), descriptor);
+ }
+ }
+});
+
+test('toActionBinding refuses an altered descriptor or an unknown name with a fixed code and sentence, and never echoes what it was given', () => {
+ const altered = [
+ (d) => { d.displayName = 'Who am I'; },
+ (d) => { d.isFunction = false; },
+ (d) => { delete d.isFunction; },
+ (d) => { d.isFunction = 'true'; },
+ (d) => { d.bindingType = 'Entity'; },
+ (d) => { d.boundEntityLogicalName = 'account'; },
+ (d) => { d.parameters = [{ name: 'Target', type: 'String' }]; },
+ (d) => { d.parameterKinds = { Target: 'String' }; },
+ (d) => { d.response.properties.Extra = 'Edm.String'; },
+ (d) => { d.response.typeName = 'Microsoft.Dynamics.CRM.OtherResponse'; },
+ (d) => { d.outputPrivacy = 'none'; },
+ (d) => { d.invocation = 'on-load'; },
+ (d) => { d.requiresExplicitSelection = false; },
+ (d) => { d.ghp_SecretLookingKey0123456789abcdefABCDEF = 'x'; },
+ (d) => { delete d.response; },
+ ];
+ for (const [index, alter] of altered.entries()) {
+ const descriptor = structuredClone(WHO_AM_I);
+ alter(descriptor);
+ assert.throws(() => ops.toActionBinding(descriptor), (error) => {
+ assert.equal(error.code, 'invalid_operation_contract', `altered ${index}`);
+ assert.equal(error.message, INVALID_CONTRACT);
+ return true;
+ });
+ }
+ for (const input of [
+ { ...structuredClone(WHO_AM_I), name: 'whoami' },
+ { ...structuredClone(WHO_AM_I), name: 'CalculateRollupField' },
+ { ...structuredClone(WHO_AM_I), name: 'contoso_ghp_0123456789abcdefABCDEF0123456789' },
+ { name: '__proto__' }, {},
+ ]) {
+ assert.throws(() => ops.toActionBinding(input), (error) => {
+ assert.equal(error.code, 'not_in_catalogue');
+ assert.equal(error.message, NOT_IN_CATALOGUE);
+ assert.doesNotMatch(String(error.stack), /ghp_|whoami\b|CalculateRollupField/);
+ return true;
+ });
+ }
+ for (const input of [null, undefined, 'WhoAmI', ['WhoAmI'], [WHO_AM_I], 7]) {
+ assert.throws(() => ops.toActionBinding(input), (error) => {
+ assert.equal(error.code, 'invalid_operation_contract', JSON.stringify(input));
+ assert.equal(error.message, INVALID_CONTRACT);
+ return true;
+ });
+ }
+});
+
+test('validateReviewedDataverseBinding accepts exactly the projection of a reviewed operation and refuses everything else a new row could hold', () => {
+ for (const descriptor of [WHO_AM_I, RETRIEVE_VERSION]) {
+ const row = ops.toActionBinding(descriptor);
+ assert.deepStrictEqual(ops.validateReviewedDataverseBinding(row), { ok: true });
+ assert.deepStrictEqual(ops.validateReviewedDataverseBinding(JSON.parse(JSON.stringify(row))), { ok: true });
+ }
+ const contract = { ok: false, code: 'invalid_operation_contract', message: INVALID_CONTRACT };
+ const row = () => ops.toActionBinding(WHO_AM_I);
+ for (const [label, entry] of [
+ ['isFunction false', { ...row(), isFunction: false }],
+ ['isFunction absent', (({ isFunction, ...rest }) => rest)(row())],
+ ['isFunction not a boolean', { ...row(), isFunction: 'true' }],
+ ['a bound target', { ...row(), boundEntityLogicalName: 'systemuser' }],
+ ['a parameter', { ...row(), parameterKinds: { Target: 'Guid' } }],
+ ['parameterKinds absent', (({ parameterKinds, ...rest }) => rest)(row())],
+ ['a display name that is not the catalogue\'s', { ...row(), displayName: 'Who am I' }],
+ ['descriptor keys on the wire', { ...row(), bindingType: 'Global' }],
+ ['the whole descriptor', structuredClone(WHO_AM_I)],
+ ['an unknown wire key', { ...row(), extra: true }],
+ ['an own __proto__ key', JSON.parse('{"name":"WhoAmI","isFunction":true,"displayName":"Current Dataverse identity","parameterKinds":{},"__proto__":{}}')],
+ ['not an object', 'WhoAmI'],
+ ['an array', [row()]],
+ ['null', null],
+ ]) {
+ assert.deepStrictEqual(ops.validateReviewedDataverseBinding(entry), contract, label);
+ }
+ for (const name of ['whoami', 'Microsoft.Dynamics.CRM.WhoAmI', 'CalculateRollupField', 'QualifyLead', '__proto__', '']) {
+ assert.deepStrictEqual(ops.validateReviewedDataverseBinding({ ...row(), name }),
+ { ok: false, code: 'not_in_catalogue', message: NOT_IN_CATALOGUE }, name);
+ }
+});
+
+test('a built-in projected by toActionBinding beside a Custom API keeps the page list statable; the same descriptor spread onto the wire leaves the WHOLE list out', () => {
+ const composed = [CUSTOM_API_ROW, ops.toActionBinding(WHO_AM_I), ops.toActionBinding(RETRIEVE_VERSION)];
+ const kept = statableBindings('actionBindings', composed);
+ assert.equal(kept.problem, null);
+ assert.deepStrictEqual(kept.stated, composed);
+ // What a composer that spreads the descriptor writes: the unrelated Custom API row is lost from the spec with it.
+ const spread = [CUSTOM_API_ROW, { ...ops.getReviewedDataverseOperation('WhoAmI') }];
+ const lost = statableBindings('actionBindings', spread);
+ assert.equal(lost.stated, null);
+ assert.equal(lost.problem.entry, 1);
+});
+
+test('the authoring codes are fixed sentences that name no environment, and the catalogue is not gated by the feature flag', () => {
+ assert.deepStrictEqual(Object.keys(ops.AUTHORING_CODES).sort(), [
+ 'catalogue_unavailable', 'duplicate_operation', 'explicit_trigger_required', 'invalid_operation_contract', 'not_in_catalogue', 'selection_required',
+ ]);
+ assert.equal(ops.AUTHORING_CODES.not_in_catalogue, NOT_IN_CATALOGUE);
+ assert.equal(ops.AUTHORING_CODES.invalid_operation_contract, INVALID_CONTRACT);
+ assert.equal(ops.AUTHORING_CODES.duplicate_operation, 'Select each built-in operation once; duplicate bindings are not supported.');
+ assert.equal(ops.AUTHORING_CODES.selection_required, 'Select a built-in operation explicitly before generating its binding or call.');
+ assert.equal(ops.AUTHORING_CODES.explicit_trigger_required, 'This version supports user-triggered built-in operation calls only.');
+ assert.equal(ops.AUTHORING_CODES.catalogue_unavailable, 'The built-in operation catalogue could not be read. No built-in operations were offered.');
+ assert.ok(Object.isFrozen(ops.AUTHORING_CODES));
+ // Recognition is not gated: download and rebuild classify carried names whatever the flag says.
+ const before = process.env.GENPAGE_ENABLE_DATAVERSE_OPERATIONS;
+ try {
+ process.env.GENPAGE_ENABLE_DATAVERSE_OPERATIONS = '0';
+ assert.deepStrictEqual(ops.getReviewedDataverseOperation('WhoAmI'), WHO_AM_I);
+ assert.deepStrictEqual(ops.toActionBinding(WHO_AM_I).name, 'WhoAmI');
+ } finally {
+ if (before === undefined) delete process.env.GENPAGE_ENABLE_DATAVERSE_OPERATIONS;
+ else process.env.GENPAGE_ENABLE_DATAVERSE_OPERATIONS = before;
+ }
+});
diff --git a/plugins/model-apps/scripts/tests/download-command-inventory-real-bundle.test.js b/plugins/model-apps/scripts/tests/download-command-inventory-real-bundle.test.js
new file mode 100644
index 000000000..87be22b42
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/download-command-inventory-real-bundle.test.js
@@ -0,0 +1,110 @@
+'use strict';
+// The command-bar customisations of an app's tables in the download's "not round-tripped" report — over the REAL vendored SDK, the
+// plugin's own HTTP client and the stateful fake Dataverse the lifecycle tests share (helpers/fake-lifecycle-org.js).
+//
+// A download does not reconstruct `commands[]`, and its report of what it leaves out named forms, views, charts, business rules and
+// global choices but never a command: nothing read them. A rebuild of the spec in another environment then made the app without its
+// command-bar buttons, and nothing had said so. The download now reads the modern commands (`appaction` rows) of the app's tables and
+// names the ones that are the app's — table-scoped, or scoped to this app; unmanaged; not a Group container; active — by table and label,
+// in its NOTE, in `notRoundTripped` and in the spec's `descriptionInventory`. A read that fails is reported as a class that could not be
+// inventoried, never as "no commands". The cases pin what it names and leaves out, the one read it adds, and the failure.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const path = require('node:path');
+const { makeTempDir } = require('./helpers/temp-dirs.js');
+const { createLifecycleOrg } = require('./helpers/fake-lifecycle-org.js');
+const { createLifecycleHarness, seedForeignWork, appUniqueName, FOREIGN } = require('./helpers/lifecycle-harness.js');
+const { validateAppSpec } = require('../lib/app-spec.js');
+
+const spec = {
+ schemaVersion: 2,
+ solution: { uniqueName: 'ContosoTickets', displayName: 'Contoso Tickets', publisherPrefix: 'contoso' },
+ app: { name: 'Tickets' },
+ entities: [{ schemaName: 'contoso_ticket', displayName: 'Ticket', primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name' }, columns: [] }],
+ webResources: [{ name: 'contoso_ticket.js', displayName: 'Ticket Scripts', type: 'js', content: 'var Ticket = { escalate: function () {} };' }],
+ commands: [{ entity: 'contoso_ticket', label: 'Escalate', location: 'MainTab', library: 'contoso_ticket.js', function: 'Ticket.escalate' }],
+ appShell: { areas: [{ label: 'Work', groups: [{ label: 'Tickets', subAreas: [{ entity: 'contoso_ticket', title: 'Tickets' }] }] }] },
+};
+
+const ran = (step, label) => {
+ assert.ok(step, `${label} ran`);
+ if (step.error) throw step.error;
+ assert.deepEqual(step.unexpected, [], `every request ${label} sent is one the fake models`);
+ return step;
+};
+
+// The environment, with the app built and then commands made in Maker beside the build's: one scoped to this app, and the ones that are
+// not the app's — another app's, a managed one, one on a table the app does not hold, an inactive one, and a Group container. `refuse`
+// answers the next reads of appactions with a 403.
+async function environment() {
+ const org = createLifecycleOrg();
+ await seedForeignWork(org);
+ const seen = { refuseCommands: false };
+ const request = async (req) => {
+ if (seen.refuseCommands && req.method === 'GET' && /\/appactions\?/.test(req.url)) {
+ return { statusCode: 403, headers: { 'content-type': 'application/json; odata.metadata=minimal' }, body: JSON.stringify({ error: { code: '0x80040220', message: 'Principal user is missing prvReadAppAction privilege.' } }) };
+ }
+ return org.request(req);
+ };
+ const root = makeTempDir('download-commands-');
+ const harness = createLifecycleHarness({ ...org, request }, root);
+ const build = ran(await harness.measure(() => harness.build(spec)), 'the build');
+ assert.equal(build.value.result.ok, true, JSON.stringify(build.value.result.errors));
+ const app = org.find('appmodules', (a) => a.uniquename === appUniqueName(spec))[0];
+ const inMaker = async (row) => {
+ const res = await org.request({ url: `${org.API}/appactions`, method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ context: 1, location: 0, type: 0, uniquename: `contoso_${row.name}`, ...row }) });
+ assert.ok(res.statusCode < 300, `${res.statusCode}: ${res.body}`);
+ };
+ await inMaker({ name: 'approve', buttonlabeltext: 'Approve', contextvalue: 'contoso_ticket', '[email protected]': `/appmodules(${app.appmoduleid})` });
+ await inMaker({ name: 'otherapp', buttonlabeltext: 'Other app only', contextvalue: 'contoso_ticket', '[email protected]': `/appmodules(${FOREIGN.app})` });
+ await inMaker({ name: 'managed', buttonlabeltext: 'Shipped with a solution', contextvalue: 'contoso_ticket', ismanaged: true });
+ await inMaker({ name: 'widget', buttonlabeltext: 'On another table', contextvalue: 'fabrikam_widget' });
+ await inMaker({ name: 'retired', buttonlabeltext: 'Retired', contextvalue: 'contoso_ticket', statecode: 1, statuscode: 2 });
+ await inMaker({ name: 'group', grouptitle: 'Actions', contextvalue: 'contoso_ticket', type: 3 });
+ return { org, root, harness, seen };
+}
+let envP;
+const env = () => envP || (envP = environment());
+const appactionReads = (org, mark, end) => org.requests.slice(mark, end).filter((r) => r.method === 'GET' && /^\/appactions\?/.test(r.path));
+
+test('commands: the download names the command-bar buttons that are the app\u2019s — table-scoped or this app\u2019s — and no other', async () => {
+ const e = await env();
+ const out = path.join(e.root, 'download');
+ const s = ran(await e.harness.measure(() => e.harness.download(appUniqueName(spec), out)), 'the download');
+ const { emitted, stderr, spec: downloaded } = s.value;
+ assert.equal(emitted.ok, true, JSON.stringify(emitted));
+ assert.deepEqual(s.writes, {}, 'a download writes nothing to the environment');
+ const summary = emitted.payload.notRoundTripped;
+ assert.deepEqual(summary.classes.find((c) => c.kind === 'commands'), { kind: 'commands', count: 2, label: 'command' });
+ assert.deepEqual(summary.entities.find((x) => x.entity === 'contoso_ticket').commands, ['Approve', 'Escalate']);
+ assert.ok(!summary.incomplete, JSON.stringify(summary.incomplete));
+ assert.deepEqual((downloaded.descriptionInventory.commands || []).map((c) => `${c.entity}: ${c.name}`), ['contoso_ticket: Approve', 'contoso_ticket: Escalate'], 'the spec lists them, as the NOTE says');
+ assert.match(stderr, /NOTE: this download does not reconstruct forms\[\], views\[\], commands\[\]/);
+ assert.match(stderr, /contoso_ticket — .*commands: Approve, Escalate/);
+ assert.deepEqual(downloaded.commands, [], 'and the spec still carries none');
+ assert.deepEqual(validateAppSpec(downloaded, { profile: 'plan', reconstructed: true }).errors, []);
+ // One read of the app's tables' commands, unmanaged only, by table.
+ const reads = appactionReads(e.org, s.mark, s.end);
+ assert.equal(reads.length, 1);
+ const query = new URL(reads[0].path, e.org.origin).searchParams;
+ assert.equal(query.get('$filter'), "ismanaged eq false and (contextvalue eq 'contoso_ticket')");
+ assert.equal(query.get('$select'), 'appactionid,name,buttonlabeltext,contextvalue,type,statecode,_appmoduleid_value');
+});
+
+test('commands: a read of the commands that fails is reported as a class the download could not inventory — never as "no commands" — and the download goes on', async () => {
+ const e = await env();
+ e.seen.refuseCommands = true;
+ try {
+ const s = ran(await e.harness.measure(() => e.harness.download(appUniqueName(spec), path.join(e.root, 'refused'))), 'the download');
+ const { emitted, stderr, spec: downloaded } = s.value;
+ assert.equal(emitted.ok, true, 'the inventory is a report, never a gate');
+ const summary = emitted.payload.notRoundTripped;
+ assert.ok(!summary.classes.some((c) => c.kind === 'commands'));
+ assert.deepEqual(summary.incomplete.map((i) => i.kind), ['commands']);
+ assert.match(summary.incomplete[0].reason, /403|prvReadAppAction/);
+ assert.match(stderr, /could NOT be inventoried[\s\S]*commands — /);
+ assert.equal((downloaded.descriptionInventory || {}).commands, undefined);
+ } finally {
+ e.seen.refuseCommands = false;
+ }
+});
diff --git a/plugins/model-apps/scripts/tests/download-label-language-real-bundle.test.js b/plugins/model-apps/scripts/tests/download-label-language-real-bundle.test.js
new file mode 100644
index 000000000..42c3f11cc
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/download-label-language-real-bundle.test.js
@@ -0,0 +1,147 @@
+'use strict';
+// The LANGUAGE of a label held in one language only, through download and rebuild — over the REAL vendored SDK, the plugin's own HTTP
+// client and the stateful fake Dataverse the lifecycle tests share (helpers/fake-lifecycle-org.js, which stores each label under the LCID
+// it was sent with, as Dataverse does).
+//
+// A download writes a label as a plain string, and a rebuild writes a plain string in the language IT resolves. A label the source holds
+// in one language only came back as a plain string whatever that language was, so a table labelled only in Spanish, downloaded from an
+// environment whose base language is English, was rebuilt with its Spanish text as the ENGLISH label — in a fresh environment that had
+// Spanish as much as in one that had not. The download now writes such a label as a one-entry LCID map when its language is not the
+// download's authoring language (labelFromDataverse in download-model-app.js), and these cases pin, by what the target environment holds:
+// * the download keeps the Spanish labels in Spanish and the English one as the plain string it always was;
+// * a rebuild into a fresh environment that has Spanish stores them in Spanish;
+// * a rebuild into a fresh environment without Spanish stops at the start of its data model and names the language (the build's
+// existing guard), where it used to store them as English;
+// * a rebuild into the same environment writes no label;
+// * a download with --language-code 3082, rebuilt with it (as the flag requires), keeps the ENGLISH label in English.
+// The fake stores a label in exactly the languages it was sent in, which lets the first cases hold a label in Spanish alone on an
+// English-base environment. Dataverse does not (measured): it fills the base language in, with the same text, when a label is created
+// in another language only, so on a live environment the one language a label holds alone is the base language, and the change shows
+// as the last case does — a label held only in the base language, downloaded with --language-code naming another.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const path = require('node:path');
+const { makeTempDir } = require('./helpers/temp-dirs.js');
+const { createLifecycleOrg } = require('./helpers/fake-lifecycle-org.js');
+const { createLifecycleHarness, appUniqueName } = require('./helpers/lifecycle-harness.js');
+const { validateAppSpec } = require('../lib/app-spec.js');
+
+const es = (text) => ({ 3082: text });
+// A table labelled in Spanish only — its name, plural, primary column, a column, a choice's options and its lookup to a stock table —
+// beside one column labelled in English, built in an environment whose base language is English and which has Spanish too.
+const spec = {
+ schemaVersion: 2,
+ solution: { uniqueName: 'ContosoPedidos', displayName: 'Contoso Pedidos', publisherPrefix: 'contoso' },
+ app: { name: 'Pedidos' },
+ entities: [{
+ schemaName: 'contoso_pedido', displayName: es('Pedido'), pluralName: es('Pedidos'),
+ primaryAttribute: { schemaName: 'contoso_name', displayName: es('Nombre') },
+ columns: [
+ { schemaName: 'contoso_importe', displayName: es('Importe'), type: 'Integer' },
+ { schemaName: 'contoso_estado', displayName: es('Estado'), type: 'Choice', options: [es('Abierto'), es('Cerrado')] },
+ { schemaName: 'contoso_nota', displayName: 'Note', type: 'Text' },
+ ],
+ }],
+ relationships: [{ type: 'OneToMany', referenced: 'account', referencing: 'contoso_pedido', lookup: { schemaName: 'contoso_cliente', displayName: es('Cliente') } }],
+ appShell: { areas: [{ label: 'Work', groups: [{ label: 'Orders', subAreas: [{ entity: 'contoso_pedido', title: 'Pedidos' }] }] }] },
+};
+const BILINGUAL = { baseLanguage: 1033, provisionedLanguages: [1033, 3082] };
+
+const ran = (step, label) => {
+ assert.ok(step, `${label} ran`);
+ if (step.error) throw step.error;
+ assert.deepEqual(step.unexpected, [], `every request ${label} sent is one the fake models`);
+ return step;
+};
+
+// What an environment holds of the table's labels, each as `<LCID>:<text>` per language it holds.
+function labelsOf(org) {
+ const table = org.metadata.tables.get('contoso_pedido');
+ const held = (label) => (label ? label.LocalizedLabels.map((l) => `${l.LanguageCode}:${l.Label}`).join(' ') : null);
+ const column = (name) => table.Attributes.get(name);
+ return {
+ table: held(table.DisplayName),
+ plural: held(table.DisplayCollectionName),
+ primary: held(column('contoso_name').DisplayName),
+ importe: held(column('contoso_importe').DisplayName),
+ estado: held(column('contoso_estado').DisplayName),
+ options: column('contoso_estado').OptionSet.Options.map((o) => held(o.Label)),
+ nota: held(column('contoso_nota').DisplayName),
+ cliente: held(column('contoso_cliente').DisplayName),
+ };
+}
+const SPANISH_AND_ONE_ENGLISH = {
+ table: '3082:Pedido', plural: '3082:Pedidos', primary: '3082:Nombre', importe: '3082:Importe', estado: '3082:Estado',
+ options: ['3082:Abierto', '3082:Cerrado'], nota: '1033:Note', cliente: '3082:Cliente',
+};
+
+// The source environment with the app built in it, and the spec a download of it writes (with --language-code when `languageCode`).
+async function downloaded(languageCode) {
+ const org = createLifecycleOrg(BILINGUAL);
+ const root = makeTempDir('label-language-');
+ const harness = createLifecycleHarness(org, root);
+ const build = ran(await harness.measure(() => harness.build(spec)), 'the source build');
+ assert.equal(build.value.result.ok, true, JSON.stringify(build.value.result.errors));
+ assert.deepEqual(labelsOf(org), SPANISH_AND_ONE_ENGLISH, 'the source holds each label in its one language');
+ const out = path.join(root, 'download');
+ const download = ran(await harness.measure(() => harness.download(appUniqueName(spec), out, { languageCode })), 'the download');
+ assert.equal(download.value.emitted.ok, true, JSON.stringify(download.value.emitted));
+ return { org, root, harness, out, spec: download.value.spec };
+}
+let englishP;
+const english = () => englishP || (englishP = downloaded());
+const rebuiltInFresh = async (source, options, languageCode) => {
+ const fresh = createLifecycleOrg(options);
+ const target = createLifecycleHarness(fresh, path.join(source.root, `fresh-${(options.provisionedLanguages || []).join('-')}-${languageCode || 'base'}`));
+ return { fresh, step: await target.measure(() => target.build(source.spec, languageCode ? { languageCode } : {})) };
+};
+
+test('label language: a download keeps a label held only in Spanish in Spanish, and the English one as the plain string it always was', async () => {
+ const { spec: got } = await english();
+ const table = got.entities.find((e) => e.schemaName === 'contoso_pedido');
+ const column = (name) => table.columns.find((c) => c.schemaName === name);
+ assert.deepEqual(
+ { table: table.displayName, plural: table.pluralName, primary: table.primaryAttribute.displayName, importe: column('contoso_importe').displayName, estado: column('contoso_estado').displayName, options: column('contoso_estado').options, nota: column('contoso_nota').displayName, cliente: got.relationships.find((r) => r.referenced === 'account').lookup.displayName },
+ { table: es('Pedido'), plural: es('Pedidos'), primary: es('Nombre'), importe: es('Importe'), estado: es('Estado'), options: [es('Abierto'), es('Cerrado')], nota: 'Note', cliente: es('Cliente') },
+ );
+ assert.deepEqual(validateAppSpec(got, { profile: 'plan', reconstructed: true }).errors, []);
+});
+
+test('label language: rebuilt into a fresh environment that has Spanish, every label is stored in its own language — not the Spanish text as English', async () => {
+ const { fresh, step } = await rebuiltInFresh(await english(), BILINGUAL);
+ ran(step, 'the fresh build');
+ assert.equal(step.value.result.ok, true, JSON.stringify(step.value.result.errors));
+ assert.deepEqual(labelsOf(fresh), SPANISH_AND_ONE_ENGLISH);
+});
+
+test('label language: rebuilt into a fresh environment without Spanish, the build stops before its data model and names the language', async () => {
+ const { fresh, step } = await rebuiltInFresh(await english(), { baseLanguage: 1033, provisionedLanguages: [1033] });
+ assert.deepEqual(step.unexpected, []);
+ const said = step.error ? step.error.message : JSON.stringify(step.value && step.value.result);
+ assert.match(said, /not provisioned in this organization: 3082/, 'the language it lacks is named');
+ // The build's language guard stands at the start of the data-model phase, after the solution phase has made the solution and its
+ // publisher: no table, column or app is written — no Spanish text is stored as an English label.
+ assert.deepEqual(Object.keys(step.writes).sort(), ['POST publishers', 'POST solutions']);
+ assert.equal(fresh.metadata.tables.get('contoso_pedido'), undefined);
+});
+
+test('label language: rebuilt into the same environment, the downloaded spec writes no label', async () => {
+ const source = await english();
+ const step = ran(await source.harness.measure(() => source.harness.build(source.spec, { appFolder: source.out, workspace: path.join(source.out, '.maker-workspace') })), 'the rebuild');
+ assert.equal(step.value.result.ok, true, JSON.stringify(step.value.result.errors));
+ assert.deepEqual(Object.keys(step.writes).filter((write) => /EntityDefinitions|OptionSet|InsertOptionValue|UpdateOptionValue/.test(write)), [], 'no table, column or option is written');
+ assert.deepEqual(labelsOf(source.org), SPANISH_AND_ONE_ENGLISH);
+});
+
+test('label language: downloaded with --language-code 3082 and rebuilt with it, the English label stays English', async () => {
+ // The flag decides the authoring language: the Spanish labels are plain strings (the build writes them in Spanish, as the flag must be
+ // given to it too), and the English one keeps its language.
+ const source = await downloaded(3082);
+ const table = source.spec.entities.find((e) => e.schemaName === 'contoso_pedido');
+ assert.equal(table.displayName, 'Pedido');
+ assert.deepEqual(table.columns.find((c) => c.schemaName === 'contoso_nota').displayName, { 1033: 'Note' });
+ const { fresh, step } = await rebuiltInFresh(source, BILINGUAL, 3082);
+ ran(step, 'the fresh build');
+ assert.equal(step.value.result.ok, true, JSON.stringify(step.value.result.errors));
+ assert.deepEqual(labelsOf(fresh), SPANISH_AND_ONE_ENGLISH);
+});
diff --git a/plugins/model-apps/scripts/tests/download-lookup-label-language-real-bundle.test.js b/plugins/model-apps/scripts/tests/download-lookup-label-language-real-bundle.test.js
new file mode 100644
index 000000000..37f8ff751
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/download-lookup-label-language-real-bundle.test.js
@@ -0,0 +1,144 @@
+'use strict';
+// Whether a download may leave a LOOKUP's label out, now that a label keeps its language — over the REAL vendored SDK, the plugin's own
+// HTTP client and the stateful fake Dataverse the lifecycle tests share (helpers/fake-lifecycle-org.js, which stores each label under the
+// LCID it was sent with, as Dataverse does).
+//
+// A download leaves out a lookup label a rebuild would write by itself (ADO 6691205): a lookup that sets none is labelled with its
+// parent's label — the downloaded table's display name, or, for a stock table, the label the build reads for it in its authoring
+// language. A downloaded table now keeps a label held in one language other than the authoring one as a one-entry map, so the same TEXT
+// no longer proves the same label: an English "Contact" on a lookup to a table labelled only in French "Contact" is not what a rebuild
+// writes (it would inherit the French label), nor is a French "Utilisateur" on a lookup to `systemuser` (the build reads "User", in
+// English). These cases pin, by what a fresh environment holds after the rebuild, that a label is left out only where the rebuild writes
+// the same label in the same language, and carried — in its own language — everywhere else:
+// * the download carries exactly the two labels a rebuild would move, and leaves out the two it reproduces;
+// * rebuilt into a fresh environment that has French, every lookup holds the label it held in the source, in the same language;
+// * rebuilt into a fresh environment without French, the lookup labelled only in French stops the build at the start of its data
+// model, naming the language (the build's existing guard), where it used to be rebuilt as the English "User".
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const path = require('node:path');
+const { makeTempDir } = require('./helpers/temp-dirs.js');
+const { createLifecycleOrg } = require('./helpers/fake-lifecycle-org.js');
+const { createLifecycleHarness, appUniqueName } = require('./helpers/lifecycle-harness.js');
+const { validateAppSpec } = require('../lib/app-spec.js');
+
+const fr = (text) => ({ 1036: text });
+const BILINGUAL = { baseLanguage: 1033, provisionedLanguages: [1033, 1036] };
+const ENGLISH_ONLY = { baseLanguage: 1033, provisionedLanguages: [1033] };
+// The stock `systemuser` table as an environment with English and French holds it: a label in each language.
+const SYSTEMUSER_LABEL = {
+ LocalizedLabels: [{ Label: 'User', LanguageCode: 1033 }, { Label: 'Utilisateur', LanguageCode: 1036 }],
+ UserLocalizedLabel: { Label: 'User', LanguageCode: 1033 },
+};
+const named = (schemaName, displayName, extra = {}) => ({ schemaName, displayName, primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name' }, columns: [], ...extra });
+const lookup = (referenced, referencing, schemaName, displayName) => ({ type: 'OneToMany', referenced, referencing, lookup: { schemaName, displayName } });
+
+// A table labelled only in French, and four lookups: to it and to `systemuser`, from two tables, each labelled either as a rebuild would
+// label it or with the same text in the other language.
+const spec = {
+ schemaVersion: 2,
+ solution: { uniqueName: 'ContosoContacts', displayName: 'Contoso Contacts', publisherPrefix: 'contoso' },
+ app: { name: 'Contacts' },
+ entities: [
+ named('contoso_contact', fr('Contact'), { pluralName: fr('Contacts') }),
+ named('contoso_case', 'Case'),
+ named('contoso_visit', 'Visit'),
+ ],
+ relationships: [
+ lookup('contoso_contact', 'contoso_case', 'contoso_contactid', 'Contact'),
+ lookup('contoso_contact', 'contoso_visit', 'contoso_contactid', fr('Contact')),
+ lookup('systemuser', 'contoso_case', 'contoso_agentid', fr('Utilisateur')),
+ lookup('systemuser', 'contoso_visit', 'contoso_agentid', 'User'),
+ ],
+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'Records', subAreas: [{ entity: 'contoso_contact', title: 'Contacts' }, { entity: 'contoso_case', title: 'Cases' }, { entity: 'contoso_visit', title: 'Visits' }] }] }] },
+};
+// What the source holds on each lookup column, `<LCID>:<text>` per language it holds.
+const SOURCE_LOOKUPS = {
+ 'contoso_case.contoso_contactid': '1033:Contact',
+ 'contoso_visit.contoso_contactid': '1036:Contact',
+ 'contoso_case.contoso_agentid': '1036:Utilisateur',
+ 'contoso_visit.contoso_agentid': '1033:User',
+};
+
+const ran = (step, label) => {
+ assert.ok(step, `${label} ran`);
+ if (step.error) throw step.error;
+ assert.deepEqual(step.unexpected, [], `every request ${label} sent is one the fake models`);
+ return step;
+};
+
+const environment = (options) => {
+ const org = createLifecycleOrg(options);
+ org.metadata.tables.get('systemuser').DisplayName = structuredClone(SYSTEMUSER_LABEL);
+ return org;
+};
+
+function lookupsOf(org, specOfIt) {
+ const out = {};
+ for (const r of specOfIt.relationships) {
+ const table = org.metadata.tables.get(r.referencing);
+ const column = table && table.Attributes.get(r.lookup.schemaName);
+ out[`${r.referencing}.${r.lookup.schemaName}`] = column ? column.DisplayName.LocalizedLabels.map((l) => `${l.LanguageCode}:${l.Label}`).join(' ') : null;
+ }
+ return out;
+}
+
+// The source environment with `app` built in it, and the spec a download of it writes.
+async function downloaded(app) {
+ const org = environment(BILINGUAL);
+ const root = makeTempDir('lookup-label-language-');
+ const harness = createLifecycleHarness(org, root);
+ const build = ran(await harness.measure(() => harness.build(app)), 'the source build');
+ assert.equal(build.value.result.ok, true, JSON.stringify(build.value.result.errors));
+ const out = path.join(root, 'download');
+ const download = ran(await harness.measure(() => harness.download(appUniqueName(app), out)), 'the download');
+ assert.equal(download.value.emitted.ok, true, JSON.stringify(download.value.emitted));
+ return { org, root, spec: download.value.spec };
+}
+let sourceP;
+const source = () => sourceP || (sourceP = downloaded(spec));
+const rebuiltInFresh = async (from, options) => {
+ const fresh = environment(options);
+ const target = createLifecycleHarness(fresh, path.join(from.root, `fresh-${options.provisionedLanguages.join('-')}`));
+ return { fresh, step: await target.measure(() => target.build(from.spec)) };
+};
+
+test('lookup label language: a download leaves out only the lookup labels a rebuild writes in the same language, and carries the others in theirs', async () => {
+ const { org, spec: got } = await source();
+ assert.deepEqual(lookupsOf(org, spec), SOURCE_LOOKUPS, 'the source holds each lookup label in its one language');
+ const lookupOf = (referenced, referencing) => got.relationships.find((r) => r.referenced === referenced && r.referencing === referencing).lookup;
+ assert.deepEqual(got.entities.find((e) => e.schemaName === 'contoso_contact').displayName, fr('Contact'), 'the parent keeps its French label');
+ assert.deepEqual(lookupOf('contoso_contact', 'contoso_case'), { schemaName: 'contoso_contactid', displayName: 'Contact' }, 'the English label with the French parent\'s text is carried, in English');
+ assert.deepEqual(lookupOf('contoso_contact', 'contoso_visit'), { schemaName: 'contoso_contactid' }, 'the parent\'s own French label is left out');
+ assert.deepEqual(lookupOf('systemuser', 'contoso_case'), { schemaName: 'contoso_agentid', displayName: fr('Utilisateur') }, 'a French label is not the English one a rebuild reads for a stock parent');
+ assert.deepEqual(lookupOf('systemuser', 'contoso_visit'), { schemaName: 'contoso_agentid' }, 'the label a rebuild reads for the stock parent is left out');
+ assert.deepEqual(validateAppSpec(got, { profile: 'plan', reconstructed: true }).errors, []);
+});
+
+test('lookup label language: rebuilt into a fresh environment that has French, every lookup holds the label it held, in the same language', async () => {
+ const from = await source();
+ const { fresh, step } = await rebuiltInFresh(from, BILINGUAL);
+ ran(step, 'the fresh build');
+ assert.equal(step.value.result.ok, true, JSON.stringify(step.value.result.errors));
+ assert.deepEqual(lookupsOf(fresh, spec), SOURCE_LOOKUPS);
+});
+
+test('lookup label language: a lookup labelled only in French, to a stock table, stops a rebuild into a fresh environment without French and names it', async () => {
+ // Only the lookup carries French here, so nothing else in the spec makes the build's language guard stop it.
+ const single = {
+ ...spec,
+ solution: { ...spec.solution, uniqueName: 'ContosoAgents' },
+ app: { name: 'Agents' },
+ entities: [named('contoso_case', 'Case')],
+ relationships: [lookup('systemuser', 'contoso_case', 'contoso_agentid', fr('Utilisateur'))],
+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'Records', subAreas: [{ entity: 'contoso_case', title: 'Cases' }] }] }] },
+ };
+ const from = await downloaded(single);
+ assert.deepEqual(from.spec.relationships[0].lookup, { schemaName: 'contoso_agentid', displayName: fr('Utilisateur') });
+ const { fresh, step } = await rebuiltInFresh(from, ENGLISH_ONLY);
+ assert.deepEqual(step.unexpected, []);
+ const said = step.error ? step.error.message : JSON.stringify(step.value && step.value.result);
+ assert.match(said, /not provisioned in this organization: 1036/, 'the language it lacks is named');
+ assert.deepEqual(Object.keys(step.writes).sort(), ['POST publishers', 'POST solutions'], 'no table or lookup is written');
+ assert.equal(fresh.metadata.tables.get('contoso_case'), undefined);
+});
diff --git a/plugins/model-apps/scripts/tests/download-model-app.test.js b/plugins/model-apps/scripts/tests/download-model-app.test.js
index e1f9ac0ad..3f07427ee 100644
--- a/plugins/model-apps/scripts/tests/download-model-app.test.js
+++ b/plugins/model-apps/scripts/tests/download-model-app.test.js
@@ -1101,6 +1101,10 @@ const { enrichesDefaultViews } = require('../lib/sdk-build.js');
const { appUniqueName } = require('../lib/sdk-build.js');
const { resolvePageRefs, reverseResolveNavIds } = require('../lib/pageref-resolver.js');
const { OBJECT_DIVISION_PAGE, LONG_KEY, lookBehindPage } = require('./helpers/misread-page.js');
+// What a guess costs a page where the TypeScript parser does not settle it (lib/typescript-views.js): these tests read the page with the lexer alone.
+// parser-check.test.js holds what the parser settles.
+const { setParserCheck } = require('../lib/typescript-views.js');
+const lexerAlone = (t) => { setParserCheck(false); t.after(() => setParserCheck(true)); };
test('runDownload translates a fail-closed app read into a graceful error, not a raw SDK throw', async () => {
// An unresolved or shared sitemap is not a partial download: none of its navigation can be trusted
@@ -1361,7 +1365,8 @@ test('download turns back a double-quoted id only, leaves any other as the id, a
// The id of a call the lexer reads by guess is left alone, whatever its quotes: the corruption was a single-quoted id inside a
// double-quoted string, which the lexer read as code after a misread, and which was rewritten to "PAGEREF_detail" — quotes ending the string.
// The call after it is hidden by the same misread, and its id stays too: each is reported.
-test('download leaves an id after a place the lexer reads by guess, and says where that is', async () => {
+test('download leaves an id after a place the lexer reads by guess, and says where that is', async (t) => {
+ lexerAlone(t);
const deployed = (id) => [
'export default function Overview() {',
` navigateTo({pageType:"generative",pageId:"${id}"});`,
@@ -1389,7 +1394,8 @@ test('download leaves an id after a place the lexer reads by guess, and says whe
// A call the lexer hid keeps its id, and no call it recognised holds it. The ids a download leaves are found by reading the result as text,
// so the call is reported, and the warning fires: before, `left` was empty and nothing was said.
-test('download reports the id in a call the lexer hid, though no call it recognised holds it', async () => {
+test('download reports the id in a call the lexer hid, though no call it recognised holds it', async (t) => {
+ lexerAlone(t);
const run = await downloadOverview((id) => OBJECT_DIVISION_PAGE.replaceAll('"PAGEREF_detail"', `"${id}"`));
try {
assert.ok(run.downloaded.ok, JSON.stringify(run.downloaded));
@@ -1400,6 +1406,24 @@ test('download reports the id in a call the lexer hid, though no call it recogni
} finally { run.cleanup(); }
});
+// The same pages, read as the TypeScript parser reads them where the lexer guessed (lib/typescript-views.js): every call is seen, so every id in one is a token
+// again, and the page of twenty calls in an `if` head — whose tokens the lexer alone would read past its look-behind — is written with its tokens, and nothing is left.
+test('download turns the ids of a page the lexer misreads back into tokens, read as TypeScript parses it', async () => {
+ const run = await downloadOverview((id) => OBJECT_DIVISION_PAGE.replaceAll('"PAGEREF_detail"', `"${id}"`));
+ try {
+ assert.ok(run.downloaded.ok, JSON.stringify(run.downloaded));
+ assert.strictEqual(run.code, OBJECT_DIVISION_PAGE);
+ assert.ok(!('navIdsLeft' in run.downloaded), 'nothing left, nothing to report');
+ } finally { run.cleanup(); }
+ const deployed = (id) => `${lookBehindPage(id, 20)}export default function Overview() { return null; }\n`;
+ const long = await downloadOverview(deployed, LONG_KEY);
+ try {
+ assert.ok(long.downloaded.ok, JSON.stringify(long.downloaded));
+ assert.strictEqual(long.code, deployed(long.detailId).replaceAll(long.detailId, `PAGEREF_${LONG_KEY}`));
+ assert.ok(!('navIdsLeft' in long.downloaded), 'nothing left, nothing to report');
+ } finally { long.cleanup(); }
+});
+
test('download reports an id that stays as data, with its place in the page it is written to, and says it can stay', async () => {
const deployed = (id) => `export default function Overview() {\n navigateTo({pageType:"generative",pageId:"${id}",data:{recordId:"${id}"}});\n return null;\n}\n`;
const run = await downloadOverview(deployed);
@@ -1417,7 +1441,8 @@ test('download reports an id that stays as data, with its place in the page it i
// the lexer's 2,000-character look-behind with ids, outside it with tokens. Written as tokens the page would have a `paren` ambiguity before the
// call after the statement, and the build would refuse it, with nothing said at the download. So the download writes none: the page is as it was
// deployed, every id is reported with the reason and the ambiguity, and the warning fires.
-test('download keeps every id of a page whose tokens the build would refuse, and says why', async () => {
+test('download keeps every id of a page whose tokens the build would refuse, and says why', async (t) => {
+ lexerAlone(t);
const deployed = (id) => `${lookBehindPage(id, 20)}export default function Overview() { return null; }\n`;
const run = await downloadOverview(deployed, LONG_KEY);
try {
@@ -2537,7 +2562,7 @@ test('runDownload WARNS on stderr about a role-restricted form, naming it', asyn
// SORTED, not in the order the mock returned them. `notRoundTripped` is compared between runs, so
// it sorts at every level, and `descriptionInventory` below is ordered the same way (table, then
// name, then id): the two lists carry the same forms in the same order.
- assert.deepStrictEqual(res.notRoundTripped.entities, [{ entity: 'new_order', forms: ['Dispatcher Form', 'Everyone Form'], views: [], charts: [], businessRules: [] }]);
+ assert.deepStrictEqual(res.notRoundTripped.entities, [{ entity: 'new_order', forms: ['Dispatcher Form', 'Everyone Form'], views: [], charts: [], commands: [], businessRules: [] }]);
// The spec on disk still carries them under descriptionInventory — the note's claim must be true.
assert.deepStrictEqual((res.spec.descriptionInventory.forms || []).map((f) => f.name), ['Dispatcher Form', 'Everyone Form']);
});
@@ -2985,6 +3010,20 @@ test('duplicate PLAIN labels are still typed (they are a warning, not an error)'
assert.strictEqual(e.columns.find((c) => c.schemaName === 'pp_status').type, 'Choice');
});
+test('the untyped-column warning names a label clash as the cause where that is it, and words every other column as before', () => {
+ const { untypedColumnWarnings } = require('../download-model-app.js');
+ const before = 'WARNING: 1 column(s) were captured WITHOUT a type (pp_t.pp_unread) — most likely Choice/MultiChoice columns whose option set could not be read. Rebuilding this spec into an environment that already has the table is unaffected, but rebuilding into a FRESH environment would create them as single-line Text. Add the type and options[] (or a globalChoice reference) by hand before a cross-environment rebuild.\n';
+ assert.deepStrictEqual(untypedColumnWarnings(['pp_t.pp_unread']), [before], 'no clash: the warning it always was');
+ assert.deepStrictEqual(untypedColumnWarnings([]), []);
+ const clashes = new Map([['pp_t.pp_status', "'Open' names options[0] and options[1]"]]);
+ const lines = untypedColumnWarnings(['pp_t.pp_status', 'pp_t.pp_unread'], clashes);
+ assert.strictEqual(lines.length, 2);
+ assert.strictEqual(lines[0], before, 'the column the clash does not explain keeps its own warning');
+ assert.match(lines[1], /^WARNING: 1 Choice\/MultiChoice column\(s\) were captured WITHOUT a type because one text names two of their options \(pp_t\.pp_status: 'Open' names options\[0\] and options\[1\]\) and their two labels differ in at least one language/);
+ assert.match(lines[1], /Their option sets were read/);
+ assert.doesNotMatch(lines[1], /could not be read/);
+});
+
test('a MultiChoice survives an unusable option label - untyped and NAMED, never dropped', async () => {
// Reported by adversarial review. A MultiSelectPicklist is `Virtual`, so before this the ONLY
// thing keeping it in columns[] was a successfully PARSED option set. An unusable label made
diff --git a/plugins/model-apps/scripts/tests/download-not-round-tripped.test.js b/plugins/model-apps/scripts/tests/download-not-round-tripped.test.js
index 3f485034d..11c4e9a12 100644
--- a/plugins/model-apps/scripts/tests/download-not-round-tripped.test.js
+++ b/plugins/model-apps/scripts/tests/download-not-round-tripped.test.js
@@ -32,7 +32,7 @@ test('notRoundTrippedSummary counts every omitted class and groups by table', ()
assert.deepStrictEqual(s.classes.map((c) => [c.kind, c.count]), [['forms', 2], ['views', 1], ['charts', 1]]);
// Sorted by table so two runs against the same app produce the same report.
assert.deepStrictEqual(s.entities.map((e) => e.entity), ['contoso_project', 'contoso_projectbaseline']);
- assert.deepStrictEqual(s.entities[0], { entity: 'contoso_project', forms: ['Project'], views: ['Active Projects'], charts: ['By Status'], businessRules: [] });
+ assert.deepStrictEqual(s.entities[0], { entity: 'contoso_project', forms: ['Project'], views: ['Active Projects'], charts: ['By Status'], commands: [], businessRules: [] });
});
test('notRoundTrippedSummary returns null when there is nothing to report', () => {
@@ -58,7 +58,7 @@ test('notRoundTrippedSummary skips nameless rows instead of printing blanks', ()
test('notRoundTrippedSummary buckets a row with no table under "unknown" rather than dropping it', () => {
const s = notRoundTrippedSummary({ forms: [{ id: 'f1', name: 'Orphan' }] });
- assert.deepStrictEqual(s.entities, [{ entity: 'unknown', forms: ['Orphan'], views: [], charts: [], businessRules: [] }]);
+ assert.deepStrictEqual(s.entities, [{ entity: 'unknown', forms: ['Orphan'], views: [], charts: [], commands: [], businessRules: [] }]);
});
// --- the classes actually reported ---------------------------------------------------------------
@@ -82,6 +82,18 @@ test('a global choice is reported WITHOUT a table, because it does not belong to
assert.match(notRoundTrippedWarning(s), /\(environment-wide\) globalChoices: contoso_status/);
});
+test('a command-bar button is reported, grouped by its table like any other artifact, and the remedy names commands[]', () => {
+ // A download does not reconstruct commands[]: a rebuild in another environment makes the app without them. They were named nowhere.
+ const s = notRoundTrippedSummary(inventory({ commands: [{ id: 'a1', name: 'Escalate', entity: 'contoso_project' }, { id: 'a2', name: 'Approve', entity: 'contoso_project' }] }));
+ assert.deepStrictEqual(s.classes.map((c) => [c.kind, c.count]), [['forms', 2], ['views', 1], ['charts', 1], ['commands', 2]]);
+ assert.strictEqual(s.total, 6);
+ assert.deepStrictEqual(s.entities.find((e) => e.entity === 'contoso_project').commands, ['Approve', 'Escalate']);
+ const w = notRoundTrippedWarning(s);
+ assert.match(w, /does not reconstruct forms\[\], views\[\], charts\[\], commands\[\] — 2 forms, 1 view, 1 chart, 2 commands on 2 table\(s\)/);
+ assert.match(w, /contoso_project — forms: Project; views: Active Projects; charts: By Status; commands: Approve, Escalate/);
+ assert.match(w, /re-declare the ones you need in forms\[\], views\[\], charts\[\], commands\[\]/);
+});
+
// --- the wording, which is the whole point of the fix -------------------------------------------
test('the warning distinguishes "absent from the spec" from "deleted from the app"', () => {
@@ -253,4 +265,71 @@ test('a TABLE-level failure is not overwritten by a later column failure', async
// The first reason is the more useful one to show, and both describe the same outcome.
const meta = await readEntityWithDescriptions(twoReadSdk(async () => ({ status: 401, headers: {}, body: {} }), async () => { throw new Error('later'); }), 'new_t');
assert.strictEqual(meta.labelReadFailed, 'HTTP 401');
+});
+
+// --- the command-bar customisations of the app's tables -------------------------------------------------------------------------
+// readDescriptionInventory reads them (readCommandInventory) when it is given the app's tables: the unmanaged `appaction` rows bound to
+// those tables, 20 tables to a request, kept when table-scoped or scoped to this app, and not a Group container or an inactive row.
+const { readDescriptionInventory } = require('../download-model-app.js');
+const APP = '11111111-0000-4000-8000-000000000001';
+const OTHER_APP = '11111111-0000-4000-8000-0000000000ff';
+// No app layer to read: the forms, views and charts are reported as unknown, which these tests do not look at.
+const NO_LAYER = { layer: { ok: false }, components: new Map(), componentProblems: new Map(), notes: [] };
+function commandSdk(rows, { fail } = {}) {
+ const queries = [];
+ return {
+ queries,
+ queryRecords: async (set, opts) => {
+ queries.push({ set, ...opts });
+ if (set !== 'appaction') return [];
+ if (fail) throw new Error(fail);
+ // `contextvalue eq '<table>'` terms of the filter: the tables this request asks about.
+ const asked = [...String(opts.filter).matchAll(/contextvalue eq '([^']+)'/g)].map((m) => m[1]);
+ return rows.filter((r) => asked.includes(r.contextvalue));
+ },
+ };
+}
+const command = (over) => ({ appactionid: `a-${over.name}`, type: 0, statecode: 0, _appmoduleid_value: null, buttonlabeltext: null, ...over });
+
+test('the command inventory keeps the app\u2019s own commands of its tables — table-scoped or this app\u2019s — and leaves every other row out', async () => {
+ const sdk = commandSdk([
+ command({ name: 'escalate', buttonlabeltext: 'Escalate', contextvalue: 'contoso_ticket' }),
+ command({ name: 'approve', buttonlabeltext: 'Approve', contextvalue: 'contoso_ticket', _appmoduleid_value: `{${APP.toUpperCase()}}` }),
+ command({ name: 'contoso_unlabelled!1a2b', contextvalue: 'contoso_ticket' }),
+ command({ name: 'other', buttonlabeltext: 'Other app only', contextvalue: 'contoso_ticket', _appmoduleid_value: OTHER_APP }),
+ command({ name: 'group', type: 3, contextvalue: 'contoso_ticket' }),
+ command({ name: 'retired', buttonlabeltext: 'Retired', statecode: 1, contextvalue: 'contoso_ticket' }),
+ command({ name: 'close', buttonlabeltext: 'Close', contextvalue: 'account' }),
+ ]);
+ const inv = await readDescriptionInventory(sdk, APP, null, new Set(), NO_LAYER, { tables: ['contoso_ticket', 'account', 'contoso_ticket'] });
+ assert.deepStrictEqual(inv.commands.map((c) => `${c.entity}: ${c.name}`), ['account: Close', 'contoso_ticket: Approve', 'contoso_ticket: contoso_unlabelled!1a2b', 'contoso_ticket: Escalate']);
+ assert.ok(!(inv.incomplete || []).some((i) => i.kind === 'commands'));
+ const reads = sdk.queries.filter((q) => q.set === 'appaction');
+ assert.strictEqual(reads.length, 1, 'one request for the tables, each named once');
+ assert.strictEqual(reads[0].filter, "ismanaged eq false and (contextvalue eq 'account' or contextvalue eq 'contoso_ticket')");
+ assert.deepStrictEqual(reads[0].select, ['appactionid', 'name', 'buttonlabeltext', 'contextvalue', 'type', 'statecode', '_appmoduleid_value']);
+ assert.strictEqual(reads[0].paginate, true);
+});
+
+test('the command inventory asks about 20 tables to a request, and a name with a quote is escaped', async () => {
+ const tables = Array.from({ length: 25 }, (_, i) => `contoso_t${String(i).padStart(2, '0')}`);
+ const sdk = commandSdk([]);
+ await readDescriptionInventory(sdk, APP, null, new Set(), NO_LAYER, { tables: [...tables, "contoso_o'neil"] });
+ const asked = sdk.queries.filter((q) => q.set === 'appaction').map((q) => [...q.filter.matchAll(/contextvalue eq '((?:[^']|'')+)'/g)].length);
+ assert.deepStrictEqual(asked, [20, 6]);
+ assert.ok(sdk.queries.some((q) => q.set === 'appaction' && q.filter.includes("contextvalue eq 'contoso_o''neil'")));
+});
+
+test('a failed command read is reported as UNKNOWN, not as an app with no commands; no tables, or none named, read nothing', async () => {
+ const failed = await readDescriptionInventory(commandSdk([], { fail: 'HTTP 403' }), APP, null, new Set(), NO_LAYER, { tables: ['contoso_ticket'] });
+ assert.strictEqual(failed.commands, undefined);
+ assert.deepStrictEqual(failed.incomplete.filter((i) => i.kind === 'commands'), [{ kind: 'commands', reason: 'HTTP 403' }]);
+ const summary = notRoundTrippedSummary(failed);
+ assert.ok(summary.incomplete.some((i) => i.kind === 'commands'));
+ assert.match(notRoundTrippedWarning(summary), /commands — HTTP 403/);
+ for (const opts of [{ tables: [] }, {}, undefined]) {
+ const sdk = commandSdk([command({ name: 'x', buttonlabeltext: 'X', contextvalue: 'contoso_ticket' })]);
+ await readDescriptionInventory(sdk, APP, null, new Set(), NO_LAYER, opts);
+ assert.deepStrictEqual(sdk.queries.filter((q) => q.set === 'appaction'), [], JSON.stringify(opts));
+ }
});
\ No newline at end of file
diff --git a/plugins/model-apps/scripts/tests/download-option-label-language-real-bundle.test.js b/plugins/model-apps/scripts/tests/download-option-label-language-real-bundle.test.js
new file mode 100644
index 000000000..e4a779b5c
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/download-option-label-language-real-bundle.test.js
@@ -0,0 +1,158 @@
+'use strict';
+// The LANGUAGE of Choice option labels two options share, through download and rebuild — over the REAL vendored SDK, the plugin's own
+// HTTP client and the stateful fake Dataverse the lifecycle tests share (helpers/fake-lifecycle-org.js, which stores each label under the
+// LCID it was sent with, as Dataverse does).
+//
+// Dataverse lets two options of a column carry the same label. A download keeps a label held in one language other than its authoring
+// language as a one-entry map, and the validator refuses a text two options share when it is not visible on the line. A download used to
+// write EVERY option of such a column as a plain string to keep the column typed — so one shared label moved every option's label, the
+// unrelated ones too, into the language a rebuild resolves, and no warning said a language was lost. These cases pin, by what a fresh
+// environment holds after the rebuild:
+// * two options sharing their text in ONE language keep it (a duplicate the validator warns about, as it does two plain strings), and
+// so does every other option;
+// * two options sharing their text in DIFFERENT languages are the only ones written as plain strings — the only shape the spec takes
+// for them — and the download names each label that loses its language; every other option keeps its own;
+// * two options labelled alike as Dataverse holds them — it fills the base language in with the same text, so each label holds two
+// languages, identically — keep the column typed and both labels (it was captured untyped);
+// * a text two options hold in different languages still leaves the column untyped, and the warning says so — not that the option set
+// could not be read, which stays the warning for an option set that really was not read.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const path = require('node:path');
+const { makeTempDir } = require('./helpers/temp-dirs.js');
+const { createLifecycleOrg } = require('./helpers/fake-lifecycle-org.js');
+const { createLifecycleHarness, appUniqueName } = require('./helpers/lifecycle-harness.js');
+const { validateAppSpec } = require('../lib/app-spec.js');
+
+const LANGUAGES = { baseLanguage: 1033, provisionedLanguages: [1033, 1036, 3082] };
+// A Choice column whose options are labelled in French and Spanish only, built in an environment whose base language is English.
+const spec = {
+ schemaVersion: 2,
+ solution: { uniqueName: 'ContosoStages', displayName: 'Contoso Stages', publisherPrefix: 'contoso' },
+ app: { name: 'Stages' },
+ entities: [{
+ schemaName: 'contoso_item', displayName: 'Item', primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name' },
+ columns: [{ schemaName: 'contoso_stage', type: 'Choice', displayName: 'Stage', options: [{ 1036: 'Ouvert' }, { 3082: 'Abierto' }, { 3082: 'Cerrado' }] }],
+ }],
+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'Records', subAreas: [{ entity: 'contoso_item', title: 'Items' }] }] }] },
+};
+
+const ran = (step, label) => {
+ assert.ok(step, `${label} ran`);
+ if (step.error) throw step.error;
+ assert.deepEqual(step.unexpected, [], `every request ${label} sent is one the fake models`);
+ return step;
+};
+const options = (org) => org.metadata.tables.get('contoso_item').Attributes.get('contoso_stage').OptionSet.Options;
+// What an environment holds of the column's options, `<LCID>:<text>` per language each holds — or, where a rebuild made the column
+// without its type, what it made instead.
+const held = (org) => {
+ const column = org.metadata.tables.get('contoso_item').Attributes.get('contoso_stage');
+ if (!column.OptionSet) return [`a ${column.AttributeType} column, with no options`];
+ return options(org).map((o) => o.Label.LocalizedLabels.map((l) => `${l.LanguageCode}:${l.Label}`).join(' '));
+};
+
+// A Label as the platform stores one: `[1033, 'Abierto'], [3082, 'Abierto']` is held in those two languages.
+const labelled = (...pairs) => ({ LocalizedLabels: pairs.map(([LanguageCode, Label]) => ({ Label, LanguageCode, IsManaged: false })), UserLocalizedLabel: null });
+const relabelSecond = (lcid, text) => (held) => { held[1].Label = labelled([lcid, text]); };
+
+// The source with the column built, its options relabelled as a maker can in the designer (`relabel` gets the stored options; Dataverse
+// allows a label two options share), and the spec a download of it writes. `refuseOptionSets` answers the download's option-set read with
+// a 503, as a service that is down for a moment does.
+async function downloaded(relabel, { refuseOptionSets = false } = {}) {
+ const org = createLifecycleOrg(LANGUAGES);
+ const state = { refuse: false };
+ const request = async (req) => {
+ const url = decodeURIComponent(String(req.url));
+ if (state.refuse && req.method === 'GET' && url.includes('/Microsoft.Dynamics.CRM.PicklistAttributeMetadata') && url.includes('OptionSet')) {
+ return { statusCode: 503, headers: { 'content-type': 'application/json; odata.metadata=minimal' }, body: JSON.stringify({ error: { code: '0x80040216', message: 'The service is unavailable.' } }) };
+ }
+ return org.request(req);
+ };
+ const root = makeTempDir('option-label-language-');
+ const harness = createLifecycleHarness({ ...org, request }, root);
+ const build = ran(await harness.measure(() => harness.build(spec)), 'the source build');
+ assert.equal(build.value.result.ok, true, JSON.stringify(build.value.result.errors));
+ if (relabel) relabel(options(org));
+ state.refuse = refuseOptionSets;
+ const download = ran(await harness.measure(() => harness.download(appUniqueName(spec), path.join(root, 'download'))), 'the download');
+ assert.equal(download.value.emitted.ok, true, JSON.stringify(download.value.emitted));
+ const got = download.value.spec;
+ assert.deepEqual(validateAppSpec(got, { profile: 'plan', reconstructed: true }).errors, []);
+ const column = got.entities[0].columns.find((c) => c.schemaName === 'contoso_stage');
+ return { root, spec: got, source: held(org), column, warnings: download.value.stderr.split('\n').filter((line) => line.startsWith('WARNING: ')) };
+}
+
+// The same, and what a fresh environment holds after a rebuild of the downloaded spec.
+async function roundTrip(relabel) {
+ const trip = await downloaded(relabel);
+ const fresh = createLifecycleOrg(LANGUAGES);
+ const target = createLifecycleHarness(fresh, path.join(trip.root, 'fresh'));
+ const rebuild = ran(await target.measure(() => target.build(trip.spec)), 'the fresh build');
+ assert.equal(rebuild.value.result.ok, true, JSON.stringify(rebuild.value.result.errors));
+ return { ...trip, fresh: held(fresh) };
+}
+
+test('option label language: two options sharing their text in one language keep it through download and rebuild, and so does every other option', async () => {
+ const trip = await roundTrip(relabelSecond(1036, 'Ouvert'));
+ assert.deepEqual(trip.source, ['1036:Ouvert', '1036:Ouvert', '3082:Cerrado']);
+ assert.deepEqual(trip.column.options, [{ 1036: 'Ouvert' }, { 1036: 'Ouvert' }, { 3082: 'Cerrado' }]);
+ assert.equal(trip.column.type, 'Choice');
+ assert.deepEqual(trip.fresh, trip.source, 'a fresh environment holds each option in the language the source holds it in');
+ assert.ok(trip.warnings.some((w) => /'Ouvert' names BOTH options\[0\] and options\[1\]/.test(w)), 'the duplicate is still reported');
+ assert.equal(trip.warnings.some((w) => /could not be kept/.test(w)), false, 'no language is lost, and none is said to be');
+});
+
+test('option label language: two options sharing their text in different languages lose only their own language, and the download names each', async () => {
+ const trip = await roundTrip(relabelSecond(3082, 'Ouvert'));
+ assert.deepEqual(trip.source, ['1036:Ouvert', '3082:Ouvert', '3082:Cerrado']);
+ assert.deepEqual(trip.column.options, ['Ouvert', 'Ouvert', { 3082: 'Cerrado' }]);
+ assert.equal(trip.column.type, 'Choice');
+ assert.deepEqual(trip.fresh, ['1033:Ouvert', '1033:Ouvert', '3082:Cerrado'], 'the unrelated option keeps its language');
+ const lost = trip.warnings.find((w) => /could not be kept/.test(w));
+ assert.ok(lost, JSON.stringify(trip.warnings));
+ assert.match(lost, /contoso_item\.contoso_stage options\[0\] 'Ouvert' \(1036\), contoso_item\.contoso_stage options\[1\] 'Ouvert' \(3082\)/);
+ assert.doesNotMatch(lost, /Cerrado/);
+});
+
+// MEASURED: Dataverse fills the environment's base language in, with the same text, when a label is created in another language only.
+// Two options created as Spanish "Abierto" on an English-base environment are therefore held as 1033 "Abierto" + 3082 "Abierto" each —
+// identical in every language they hold. A download captured such a column WITHOUT a type and blamed an option set it had read, so a
+// rebuild into a fresh environment would have made it a single-line text column.
+const asHeld = (held) => {
+ held[0].Label = labelled([1033, 'Abierto'], [3082, 'Abierto']);
+ held[1].Label = labelled([1033, 'Abierto'], [3082, 'Abierto']);
+ held[2].Label = labelled([1033, 'Cerrado'], [3082, 'Cerrado']);
+};
+
+test('option label language: two options labelled alike as Dataverse holds them — the base language filled in — keep the column typed, its options and both languages', async () => {
+ const trip = await roundTrip(asHeld);
+ assert.deepEqual(trip.source, ['1033:Abierto 3082:Abierto', '1033:Abierto 3082:Abierto', '1033:Cerrado 3082:Cerrado']);
+ assert.deepEqual(trip.fresh, trip.source, 'a fresh environment holds the options the source holds');
+ assert.equal(trip.column.type, 'Choice');
+ assert.deepEqual(trip.column.options, [{ 1033: 'Abierto', 3082: 'Abierto' }, { 1033: 'Abierto', 3082: 'Abierto' }, { 1033: 'Cerrado', 3082: 'Cerrado' }]);
+ assert.equal(trip.warnings.filter((w) => /'Abierto' names BOTH options\[0\] and options\[1\]/.test(w)).length, 1, `the duplicate is reported once: ${JSON.stringify(trip.warnings)}`);
+ assert.equal(trip.warnings.some((w) => /WITHOUT a type/.test(w)), false, 'the column is not reported untyped');
+});
+
+test('option label language: a text two options hold in different languages still leaves the column untyped, and the warning names the clash, not the read', async () => {
+ const trip = await downloaded((held) => {
+ held[0].Label = labelled([1033, 'Open'], [3082, 'Abierto']);
+ held[1].Label = labelled([1033, 'Abierto'], [3082, 'Cerrado']);
+ held[2].Label = labelled([1033, 'Pending'], [3082, 'Pendiente']);
+ });
+ assert.deepEqual([trip.column.type, trip.column.options], [undefined, undefined], 'which option "Abierto" means depends on the language: the spec cannot hold it');
+ const untyped = trip.warnings.filter((w) => /WITHOUT a type/.test(w));
+ assert.equal(untyped.length, 1, JSON.stringify(trip.warnings));
+ assert.match(untyped[0], /because one text names two of their options \(contoso_item\.contoso_stage: 'Abierto' names options\[0\] and options\[1\]\)/);
+ assert.match(untyped[0], /Their option sets were read/);
+ assert.doesNotMatch(untyped[0], /could not be read/);
+});
+
+test('option label language: an option set that could not be read still leaves the column untyped, with the read named', async () => {
+ const trip = await downloaded(asHeld, { refuseOptionSets: true });
+ assert.deepEqual([trip.column.type, trip.column.options], [undefined, undefined]);
+ assert.ok(trip.warnings.some((w) => /^WARNING: the Choice\/MultiChoice option-set read failed for 1 table\(s\) \(contoso_item \(HTTP 503\)\)/.test(w)), JSON.stringify(trip.warnings));
+ assert.ok(trip.warnings.some((w) => /^WARNING: 1 column\(s\) were captured WITHOUT a type \(contoso_item\.contoso_stage\) — most likely Choice\/MultiChoice columns whose option set could not be read\./.test(w)), JSON.stringify(trip.warnings));
+ assert.equal(trip.warnings.some((w) => /names two of their options/.test(w)), false, 'no clash is claimed for an option set that was not read');
+});
\ No newline at end of file
diff --git a/plugins/model-apps/scripts/tests/download-portable-detail-real-bundle.test.js b/plugins/model-apps/scripts/tests/download-portable-detail-real-bundle.test.js
index cbaf39716..7b584ea5b 100644
--- a/plugins/model-apps/scripts/tests/download-portable-detail-real-bundle.test.js
+++ b/plugins/model-apps/scripts/tests/download-portable-detail-real-bundle.test.js
@@ -13,7 +13,8 @@ const { validateAppSpec } = require('../lib/app-spec.js');
// Pin their request shape too, so an unrelated fallback cannot hide inside the total.
// Component type 62 is Site Map:
// https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/appmodulecomponent
-const DOWNLOAD_READS = 83;
+// The command-bar inventory adds two: the `appaction` entity-set lookup and one `appactions` read for up to 20 of the app's tables.
+const DOWNLOAD_READS = 85;
const reason = { label: 'Review', state: 'Active', value: 100000042, color: '#336699' };
const key = { schemaName: 'contoso_emailkey', displayName: 'Email Key', columns: ['contoso_email'] };
diff --git a/plugins/model-apps/scripts/tests/download-rebuild-teardown.test.js b/plugins/model-apps/scripts/tests/download-rebuild-teardown.test.js
index 034aa71a2..db87ea8a5 100644
--- a/plugins/model-apps/scripts/tests/download-rebuild-teardown.test.js
+++ b/plugins/model-apps/scripts/tests/download-rebuild-teardown.test.js
@@ -15,6 +15,7 @@ const snapshotStore = require('../lib/apply-snapshot-store.js');
const { makeSimpleMockSdk } = require('./helpers/mock-sdk.js');
const { currentReadSdk } = require('./helpers/app-membership-sdk.js');
const { fakeGenpage } = require('./helpers/fake-genpage.js');
+const { withPageType } = require('./helpers/page-component-type.js');
const ENV = 'https://contoso.crm.dynamics.com';
const APP_ID = '11111111-0000-4000-8000-000000000001';
@@ -106,7 +107,8 @@ function recordingLifecycleSdk({ systemOnly = false } = {}) {
entitySetName: `${logical}s`, attributes: [], relationships: [{ schemaName: RELATIONSHIP }],
});
sdk.getSolution = async (uniqueName) => ({ uniqueName, publisherPrefix: 'contoso' });
- sdk.dataverse = { get: async (url) => {
+ // The page table's solution component type is answered in front of the rest: a build adds the pages it writes to the spec's solution (helpers/page-component-type.js).
+ sdk.dataverse = { get: withPageType(async (url) => {
const logical = (url.match(/LogicalName='([^']+)'/) || [])[1];
if (url.includes('/ManyToOneRelationships')) return { status: 200, body: { value: logical === 'contoso_task' ? [{
SchemaName: RELATIONSHIP, ReferencedEntity: 'contoso_project', ReferencingEntity: 'contoso_task',
@@ -136,7 +138,7 @@ function recordingLifecycleSdk({ systemOnly = false } = {}) {
}
assert.ok(state.tables.has(logical), `only declared table metadata may be read: ${url}`);
return { status: 200, body: { LogicalName: logical, EntitySetName: `${logical}s` } };
- } };
+ }) };
sdk.queryRecords = async (set, opts = {}) => {
const filter = opts.filter || '';
if (set === 'appmodule') {
diff --git a/plugins/model-apps/scripts/tests/exit-writes-inventory.test.js b/plugins/model-apps/scripts/tests/exit-writes-inventory.test.js
index 5b77fe7bb..476fd54bd 100644
--- a/plugins/model-apps/scripts/tests/exit-writes-inventory.test.js
+++ b/plugins/model-apps/scripts/tests/exit-writes-inventory.test.js
@@ -168,7 +168,7 @@ const ALLOWED = {
'scripts/generate-page-manifest.js': [1, '--help prints a constant help text (329 bytes)'],
'scripts/launch-playwright-mcp.js': [2, 'the server\'s own end: a signal\'s name, or nothing (the server wrote its output itself)'],
'scripts/lib/exit-cleanup.js': [2, `ends the process on a signal and ${NOTHING}`],
- 'scripts/lib/feature-flags.js': [3, 'the Custom API gate\'s constant message (440 bytes and its line break), the CLI\'s constant usage line, and "enabled" or "disabled"'],
+ 'scripts/lib/feature-flags.js': [2, 'the CLI\'s constant usage line, and "enabled" or "disabled"'],
'scripts/lib/telemetry/lib/emit-dispatcher.js': [1, `the detached dispatcher ${NOTHING}`],
'scripts/lib/telemetry/lib/telemetry-config.js': [4, 'the shared telemetry library (shared/telemetry, copied into five plugins), which the telemetry skill runs without --plugin: constant sentences and the plugin\'s own name (about 1.2 KB measured), and the config folder\'s path once or twice; under the 4 KiB any pipe takes at once unless that path is over 1,400 characters'],
'scripts/list-connections.js': [1, USAGE],
diff --git a/plugins/model-apps/scripts/tests/feature-flags.test.js b/plugins/model-apps/scripts/tests/feature-flags.test.js
index 6be077adb..d5489bba9 100644
--- a/plugins/model-apps/scripts/tests/feature-flags.test.js
+++ b/plugins/model-apps/scripts/tests/feature-flags.test.js
@@ -4,20 +4,19 @@ const assert = require('node:assert/strict');
const path = require('node:path');
const fs = require('node:fs');
const { spawnSync } = require('node:child_process');
+const { makeTempDir } = require('./helpers/temp-dirs.js');
const libPath = path.join(__dirname, '..', 'lib', 'feature-flags.js');
+const lib = require(libPath);
const {
isEnabled,
- isCustomApiEnabled,
- customApiDisabledMessage,
envVarName,
parseBool,
- exitIfCustomApiDisabled,
describe,
validateFlags,
KNOWN_FLAGS,
FLAGS,
-} = require(libPath);
+} = lib;
// --- Committed defaults and fail-closed fallback ---------------------------
@@ -34,17 +33,199 @@ test('connectors flag is retired and unknown fail-closed', () => {
assert.equal(lib[removed], undefined, `${removed} must stay removed now that connectors have no flag`);
}
});
-test('custom-api flag is ON by default without changing the generic fail-closed fallback', () => {
- assert.equal(isEnabled('custom-api', { env: {} }), true);
- assert.equal(isCustomApiEnabled({ env: {} }), true);
- for (const flags of [{}, { 'custom-api': false }, { 'custom-api': 'true' }]) {
- assert.equal(isEnabled('custom-api', { env: {}, flags }), false);
+// Custom API support shipped ON in 2.18.0 and 2.19.0 with its platform dependencies live in every region, so the flag was removed (the lifecycle
+// in feature-flags.js): Custom API discovery, authoring and upload are always available. As an unknown flag it would now read as disabled, so
+// nothing may keep a trace of it that something could still ask for.
+test('the custom-api flag is retired: no catalogue entry, no committed key, no helper, and its variable no longer changes anything', () => {
+ const json = JSON.parse(
+ fs.readFileSync(path.join(__dirname, '..', '..', 'feature-flags.json'), 'utf8')
+ );
+ assert.equal(Object.prototype.hasOwnProperty.call(json, 'custom-api'), false);
+ assert.deepEqual(validateFlags(json), []);
+ assert.equal(KNOWN_FLAGS.includes('custom-api'), false);
+ assert.equal(FLAGS['custom-api'], undefined);
+ for (const value of [undefined, '0', '1']) {
+ const env = value === undefined ? {} : { GENPAGE_ENABLE_CUSTOM_API: value };
+ assert.equal(isEnabled('custom-api', { env }), false, `unknown flags fail closed, whatever GENPAGE_ENABLE_CUSTOM_API says (${value})`);
+ }
+ assert.match(validateFlags({ 'custom-api': true })[0], /unknown flag/i);
+ for (const removed of ['isCustomApiEnabled', 'exitIfCustomApiDisabled', 'customApiDisabledMessage']) {
+ assert.equal(lib[removed], undefined, `${removed} must stay removed now that Custom API support has no flag`);
+ }
+});
+
+test('feature-flags.js --list shows no custom-api line, and no warning about it, whatever GENPAGE_ENABLE_CUSTOM_API says', () => {
+ for (const value of [undefined, '0', '1']) {
+ const env = { ...process.env };
+ delete env.GENPAGE_ENABLE_CUSTOM_API;
+ if (value !== undefined) env.GENPAGE_ENABLE_CUSTOM_API = value;
+ const res = spawnSync(process.execPath, [libPath, '--list'], { encoding: 'utf8', env });
+ assert.equal(res.status, 0, res.stderr);
+ assert.doesNotMatch(res.stdout, /custom-api/, `GENPAGE_ENABLE_CUSTOM_API=${value}`);
+ assert.doesNotMatch(res.stderr, /custom-api/, `GENPAGE_ENABLE_CUSTOM_API=${value}`);
+ assert.match(res.stdout, /^custom-telemetry: /m);
+ assert.match(res.stdout, /^dataverse-operations: /m);
}
});
-test('an explicit custom-api opt-out overrides the committed enabled default', () => {
- assert.equal(isEnabled('custom-api', { env: { GENPAGE_ENABLE_CUSTOM_API: '0' } }), false);
- assert.equal(isCustomApiEnabled({ env: { GENPAGE_ENABLE_CUSTOM_API: '0' } }), false);
+// With the flag gone, a probe left anywhere would read it as disabled and turn Custom API support off where it ran. So no caller may stay in any
+// tree that runs or describes this plugin: the plugin itself (scripts, hooks, agents, skills, references, samples, docs, and its tests and test
+// helpers), the pcf plugin (it carries copies of model-apps scripts), and both eval trees (graders, runners, and their tests and helpers). Only
+// what names the flag on purpose is let through, file by file and probe by probe: the release history, the runs that eval fixtures recorded (an
+// older run probed the flag; the graders neither require nor refuse that probe), and the tests that pin the retirement or hand such a recorded
+// probe to a grader.
+const REPO_ROOT = path.join(__dirname, '..', '..', '..', '..');
+const RETIRED_FLAG_ROOTS = ['plugins/model-apps', 'plugins/pcf', 'evals/model-apps', 'evals/pcf'];
+const RETIRED_FLAG_PROBES = {
+ // As a skill, an agent or a recorded run writes it: node "${PLUGIN_ROOT}/scripts/lib/feature-flags.js" <flag>, the flag name after the script.
+ cli: /feature-flags\.js["'`]?\s+["'`]?custom-api\b/,
+ library: /\b(?:isEnabled|envVarName)\(\s*["'`]custom-api["'`]/,
+ helper: /\b(?:isCustomApiEnabled|exitIfCustomApiDisabled|customApiDisabledMessage)\b/,
+ // A setting or a read of the variable: GENPAGE_ENABLE_CUSTOM_API=0, { GENPAGE_ENABLE_CUSTOM_API: '1' }, process.env.GENPAGE_ENABLE_CUSTOM_API,
+ // env['GENPAGE_ENABLE_CUSTOM_API'], $env:GENPAGE_ENABLE_CUSTOM_API, ${GENPAGE_ENABLE_CUSTOM_API}, %GENPAGE_ENABLE_CUSTOM_API%. Prose that names
+ // it ("`GENPAGE_ENABLE_CUSTOM_API` is ignored") is none of these.
+ variable: /GENPAGE_ENABLE_CUSTOM_API["'`]?\s*[=:]|(?:\.|\[\s*["'`]|\$env:|\$\{?|%)GENPAGE_ENABLE_CUSTOM_API\b/,
+};
+const RETIRED_FLAG_FILES = /\.(?:md|js|cjs|mjs|jsx|json|ts|tsx|ps1|sh|cmd|bat|ya?ml)$/i;
+// A run an eval fixture recorded — its workflow log and its tool results — keeps the CLI probes the run made, and nothing else is let through
+// there: any other kind of probe, or a script in a fixture folder, is a caller.
+const RECORDED_RUN = /^evals\/[^/]+\/[^/]+\/fixtures\/[^/]+\/(?:workflow-log\.md|tool-results\.json)$/;
+const RETIRED_FLAG_ALLOWED = new Map([
+ ['plugins/model-apps/CHANGELOG.md', { history: true, probes: Object.keys(RETIRED_FLAG_PROBES) }],
+ // Pins the retirement: the flag reads disabled, its helpers are gone, and its variable changes nothing.
+ ['plugins/model-apps/scripts/tests/feature-flags.test.js', { probes: ['library', 'helper', 'variable'] }],
+ // Discovery reads no gate and lists the same whatever the variable says.
+ ['plugins/model-apps/scripts/tests/list-custom-apis.test.js', { probes: ['helper', 'variable'] }],
+ // The dataverse-operations gate ignores the variable.
+ ['plugins/model-apps/scripts/tests/list-dataverse-operations.test.js', { probes: ['variable'] }],
+ // A recorded probe decides no grade, and the reader of recorded tool results reads the probe commands the fixtures hold.
+ ['evals/model-apps/genpage/tests/action-binding-union.test.js', { probes: ['cli'] }],
+ ['evals/model-apps/genpage/tests/built-in-operation-pattern.test.js', { probes: ['cli'] }],
+ ['evals/model-apps/genpage/tests/custom-api-lifecycle.test.js', { probes: ['cli'] }],
+ ['evals/model-apps/genpage/tests/fixture-tool-results.test.js', { probes: ['cli'] }],
+]);
+
+// Every probe in the scanned roots under `root`: `found` holds the ones nothing lets through, `allowed` the files on the list above with the
+// kinds they hold, `recorded` the recorded runs that hold a CLI probe, and `visited` every file read. Other test files run beside this one and
+// some make and remove folders inside these roots (capture-fixture.test.js writes a fixture under evals/model-apps/genpage/fixtures), so an
+// entry that is gone by the time it is read is skipped: it was never part of what the plugin ships.
+function retiredFlagScan(root) {
+ const found = [];
+ const allowed = new Map();
+ const recorded = [];
+ const visited = new Set();
+ const gone = (error) => error && error.code === 'ENOENT';
+ const walk = (dir) => {
+ let entries;
+ try {
+ entries = fs.readdirSync(dir, { withFileTypes: true });
+ } catch (error) {
+ if (gone(error)) return;
+ throw error;
+ }
+ for (const entry of entries) {
+ const full = path.join(dir, entry.name);
+ const relative = path.relative(root, full).split(path.sep).join('/');
+ if (entry.isDirectory()) {
+ if (!['node_modules', '.git'].includes(entry.name)) walk(full);
+ continue;
+ }
+ if (!entry.isFile() || !RETIRED_FLAG_FILES.test(entry.name)) continue;
+ let text;
+ try {
+ text = fs.readFileSync(full, 'utf8');
+ } catch (error) {
+ if (gone(error)) continue;
+ throw error;
+ }
+ visited.add(relative);
+ const kinds = Object.keys(RETIRED_FLAG_PROBES).filter((kind) => RETIRED_FLAG_PROBES[kind].test(text));
+ if (!kinds.length) continue;
+ const permitted = RECORDED_RUN.test(relative) ? ['cli'] : (RETIRED_FLAG_ALLOWED.get(relative)?.probes || []);
+ for (const kind of kinds) {
+ if (!permitted.includes(kind)) found.push(`${relative}: ${kind}`);
+ else if (RECORDED_RUN.test(relative)) recorded.push(relative);
+ else allowed.set(relative, [...(allowed.get(relative) || []), kind]);
+ }
+ }
+ };
+ for (const scanned of RETIRED_FLAG_ROOTS) {
+ const dir = path.join(root, ...scanned.split('/'));
+ if (fs.existsSync(dir)) walk(dir);
+ }
+ return { found, allowed, recorded, visited };
+}
+
+test('nothing the plugin ships asks for the custom-api flag: no script, hook, agent, skill, reference, test helper, pcf copy or eval grader probes it', () => {
+ const { found, allowed, recorded, visited } = retiredFlagScan(REPO_ROOT);
+ assert.deepEqual(found, []);
+ // Every root is read down to its tests, helpers and fixtures: a known file from each is among the files scanned.
+ for (const file of [
+ 'plugins/model-apps/scripts/list-custom-apis.js', 'plugins/model-apps/scripts/lib/feature-flags.js', 'plugins/model-apps/hooks/hooks.json',
+ 'plugins/model-apps/agents/genpage-customapi-builder.md', 'plugins/model-apps/skills/genpage/SKILL.md', 'plugins/model-apps/references/custom-api.md',
+ 'plugins/model-apps/scripts/tests/list-custom-apis.test.js', 'plugins/model-apps/scripts/tests/helpers/fake-custom-api-preload.js',
+ 'plugins/pcf/scripts/check-auth.js', 'plugins/pcf/AGENTS.md',
+ 'evals/model-apps/genpage/lib/custom-api-contract.js', 'evals/model-apps/genpage/run-layer-1.js', 'evals/model-apps/genpage/EVAL_GUIDE.md',
+ 'evals/model-apps/genpage/tests/custom-api-lifecycle.test.js', 'evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/workflow-log.md',
+ 'evals/model-apps/app-builder/run-app-builder.js', 'evals/pcf/run-pcf.js',
+ ]) {
+ assert.ok(visited.has(file), `${file} was scanned`);
+ }
+ assert.ok(visited.size > 1000, `scanned ${visited.size} files`);
+ // A file is let through only while it still holds what it is let through for, so the list cannot outgrow its purpose.
+ for (const [file, { history }] of RETIRED_FLAG_ALLOWED) {
+ if (!history) assert.ok(allowed.has(file), `${file} no longer names the flag: take it off RETIRED_FLAG_ALLOWED`);
+ }
+ assert.ok(recorded.length > 0, 'the recorded runs that probed the flag were read');
+});
+
+test('the custom-api flag scan finds a caller planted in any root — a pcf script, an eval grader, a test helper, a new test, a fixture script — and lets through only what names the flag on purpose', () => {
+ const root = makeTempDir('retired-flag-scan-');
+ // Built from parts, so that this file holds no probe of a kind it is not let through for.
+ const FLAG = ['custom', 'api'].join('-');
+ const VARIABLE = ['GENPAGE', 'ENABLE', 'CUSTOM', 'API'].join('_');
+ const probe = {
+ cli: `node "\${PLUGIN_ROOT}/scripts/lib/feature-flags.js" ${FLAG}\n`,
+ library: `'use strict';\nmodule.exports = (flags) => flags.isEnabled('${FLAG}');\n`,
+ helper: `const { exitIf${'CustomApi'}Disabled } = require('./lib/feature-flags.js');\n`,
+ variable: `if (process.env.${VARIABLE} === '0') process.exit(3);\n`,
+ shell: `if ($env:${VARIABLE} -eq '0') { exit 3 }\n`,
+ prose: `\`${VARIABLE}\` is ignored.\n`,
+ };
+ const plant = (relative, text) => {
+ const file = path.join(root, ...relative.split('/'));
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, text);
+ };
+ const callers = [
+ ['plugins/model-apps/scripts/flag-probe.cjs', 'library'],
+ ['plugins/model-apps/hooks/flag-probe.ps1', 'shell'],
+ ['plugins/model-apps/skills/genpage/SKILL.md', 'cli'],
+ ['plugins/model-apps/scripts/tests/helpers/flag-probe.cjs', 'library'],
+ ['plugins/model-apps/scripts/tests/new-feature.test.js', 'cli'],
+ ['plugins/pcf/scripts/flag-probe.cjs', 'library'],
+ ['plugins/pcf/skills/pcf-create/SKILL.md', 'cli'],
+ ['evals/model-apps/genpage/lib/flag-probe.cjs', 'library'],
+ ['evals/model-apps/genpage/run-layer-3.js', 'variable'],
+ ['evals/pcf/lib/flag-probe.js', 'helper'],
+ // A list entry lets through only its own kinds, a recorded run only the CLI probe, and a script in a fixture folder nothing.
+ ['evals/model-apps/genpage/tests/action-binding-union.test.js', 'library'],
+ ['evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/workflow-log.md', 'library'],
+ ['evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/capture.js', 'cli'],
+ ];
+ const letThrough = [
+ ['plugins/model-apps/CHANGELOG.md', 'library'],
+ ['plugins/model-apps/README.md', 'prose'],
+ ['evals/model-apps/genpage/tests/custom-api-lifecycle.test.js', 'cli'],
+ ['evals/model-apps/genpage/fixtures/16-account-list/tool-results.json', 'cli'],
+ ['plugins/pcf/node_modules/some-package/index.js', 'library'],
+ ];
+ for (const [relative, kind] of [...callers, ...letThrough]) plant(relative, probe[kind]);
+ const { found, visited } = retiredFlagScan(root);
+ const kindOf = { shell: 'variable' };
+ assert.deepEqual(found.sort(), callers.map(([relative, kind]) => `${relative}: ${kindOf[kind] || kind}`).sort());
+ for (const [relative] of letThrough.slice(0, 4)) assert.ok(visited.has(relative), `${relative} was read`);
+ assert.equal(visited.has('plugins/pcf/node_modules/some-package/index.js'), false, 'installed packages are not read');
});
test('custom-telemetry flag is OFF by default (no env override)', () => {
@@ -59,7 +240,7 @@ test('unknown flags are OFF (fail-closed)', () => {
test('missing/invalid flags file is treated as all-OFF', () => {
assert.equal(
- isEnabled('custom-api', { env: {}, flagsPath: path.join(__dirname, 'no-such-flags.json') }),
+ isEnabled('custom-telemetry', { env: {}, flagsPath: path.join(__dirname, 'no-such-flags.json') }),
false
);
});
@@ -68,33 +249,33 @@ test('missing/invalid flags file is treated as all-OFF', () => {
test('env var enables a flag that is false in config', () => {
assert.equal(
- isEnabled('custom-api', { env: { GENPAGE_ENABLE_CUSTOM_API: '1' }, flags: { 'custom-api': false } }),
+ isEnabled('custom-telemetry', { env: { GENPAGE_ENABLE_CUSTOM_TELEMETRY: '1' }, flags: { 'custom-telemetry': false } }),
true
);
});
test('env var OFF overrides config true', () => {
assert.equal(
- isEnabled('custom-api', { env: { GENPAGE_ENABLE_CUSTOM_API: '0' }, flags: { 'custom-api': true } }),
+ isEnabled('custom-telemetry', { env: { GENPAGE_ENABLE_CUSTOM_TELEMETRY: '0' }, flags: { 'custom-telemetry': true } }),
false
);
});
test('unrecognized env value defers to config', () => {
assert.equal(
- isEnabled('custom-api', { env: { GENPAGE_ENABLE_CUSTOM_API: 'maybe' }, flags: { 'custom-api': true } }),
+ isEnabled('custom-telemetry', { env: { GENPAGE_ENABLE_CUSTOM_TELEMETRY: 'maybe' }, flags: { 'custom-telemetry': true } }),
true
);
});
test('config true enables when env is unset', () => {
- assert.equal(isEnabled('custom-api', { env: {}, flags: { 'custom-api': true } }), true);
+ assert.equal(isEnabled('custom-telemetry', { env: {}, flags: { 'custom-telemetry': true } }), true);
});
// --- Helpers ----------------------------------------------------------------
test('envVarName maps flag names to GENPAGE_ENABLE_<FLAG>', () => {
- assert.equal(envVarName('custom-api'), 'GENPAGE_ENABLE_CUSTOM_API');
+ assert.equal(envVarName('custom-telemetry'), 'GENPAGE_ENABLE_CUSTOM_TELEMETRY');
assert.equal(envVarName('multi-word flag'), 'GENPAGE_ENABLE_MULTI_WORD_FLAG');
});
@@ -104,27 +285,8 @@ test('parseBool recognizes common truthy/falsey tokens, defers otherwise', () =>
for (const v of [undefined, null, '', ' ', 'maybe']) assert.equal(parseBool(v), null, `defer: ${String(v)}`);
});
-test('customApiDisabledMessage explains how to enable', () => {
- const m = customApiDisabledMessage();
- assert.match(m, /GENPAGE_ENABLE_CUSTOM_API/);
- assert.match(m, /feature-flags\.json/);
-});
-
-test('the Custom API catalog and disabled guidance describe the enabled default and opt-out', () => {
- assert.match(FLAGS['custom-api'].summary, /enabled by default/i);
- assert.match(customApiDisabledMessage(), /GENPAGE_ENABLE_CUSTOM_API=0/);
- assert.doesNotMatch(customApiDisabledMessage(), /once the dependencies are released/);
-});
-
// --- Committed config keeps each feature's own default ---------------------
-test('committed feature-flags.json ships custom-api: true', () => {
- const json = JSON.parse(
- fs.readFileSync(path.join(__dirname, '..', '..', 'feature-flags.json'), 'utf8')
- );
- assert.equal(json['custom-api'], true);
-});
-
test('committed feature-flags.json ships custom-telemetry: false', () => {
const json = JSON.parse(
fs.readFileSync(path.join(__dirname, '..', '..', 'feature-flags.json'), 'utf8')
@@ -135,102 +297,77 @@ test('committed feature-flags.json ships custom-telemetry: false', () => {
// --- CLI probe (deterministic gate for the skill markdown) ------------------
test('CLI prints "disabled" and exits 1 for an explicit opt-out', () => {
- const res = spawnSync(process.execPath, [libPath, 'custom-api'], {
+ const res = spawnSync(process.execPath, [libPath, 'custom-telemetry'], {
encoding: 'utf8',
- env: { ...process.env, GENPAGE_ENABLE_CUSTOM_API: '0' },
+ env: { ...process.env, GENPAGE_ENABLE_CUSTOM_TELEMETRY: '0' },
});
assert.equal(res.status, 1);
assert.match(res.stdout, /disabled/);
});
-test('CLI prints "enabled" and exits 0 without an environment override', () => {
- const env = { ...process.env };
- delete env.GENPAGE_ENABLE_CUSTOM_API;
- const res = spawnSync(process.execPath, [libPath, 'custom-api'], { encoding: 'utf8', env });
- assert.equal(res.status, 0, res.stderr);
- assert.equal(res.stdout.trim(), 'enabled');
-});
-
test('CLI prints "enabled" and exits 0 when env override ON', () => {
- const res = spawnSync(process.execPath, [libPath, 'custom-api'], {
+ const res = spawnSync(process.execPath, [libPath, 'custom-telemetry'], {
encoding: 'utf8',
- env: { ...process.env, GENPAGE_ENABLE_CUSTOM_API: '1' },
+ env: { ...process.env, GENPAGE_ENABLE_CUSTOM_TELEMETRY: '1' },
});
assert.equal(res.status, 0);
assert.match(res.stdout, /enabled/);
});
+test('CLI prints "disabled" and exits 1 for the retired custom-api flag, even with its old variable set', () => {
+ for (const value of [undefined, '1']) {
+ const env = { ...process.env };
+ delete env.GENPAGE_ENABLE_CUSTOM_API;
+ if (value !== undefined) env.GENPAGE_ENABLE_CUSTOM_API = value;
+ const res = spawnSync(process.execPath, [libPath, 'custom-api'], { encoding: 'utf8', env });
+ assert.equal(res.status, 1, res.stderr);
+ assert.equal(res.stdout, 'disabled\n');
+ }
+});
+
test('CLI without a flag name exits 2 with usage', () => {
const res = spawnSync(process.execPath, [libPath], { encoding: 'utf8' });
assert.equal(res.status, 2);
assert.match(res.stderr, /Usage:/);
});
-// --- exitIfCustomApiDisabled (DRY gate helper) -------------------------------
-
-test('exitIfCustomApiDisabled exits 3 and writes the message when OFF', () => {
- let exitCode = null;
- let written = '';
- exitIfCustomApiDisabled({
- env: { GENPAGE_ENABLE_CUSTOM_API: '0' },
- exit: (c) => { exitCode = c; },
- write: (s) => { written += s; },
- });
- assert.equal(exitCode, 3);
- assert.match(written, /disabled/i);
-});
-
-test('exitIfCustomApiDisabled is a no-op when ON', () => {
- let exitCalled = false;
- exitIfCustomApiDisabled({
- env: { GENPAGE_ENABLE_CUSTOM_API: '1' },
- exit: () => { exitCalled = true; },
- write: () => {},
- });
- assert.equal(exitCalled, false);
-});
-
// --- known-flag registry + describe() + validation --------------------------
-test('KNOWN_FLAGS includes custom-api', () => {
- assert.ok(KNOWN_FLAGS.includes('custom-api'));
-});
-
test('KNOWN_FLAGS includes custom-telemetry', () => {
assert.ok(KNOWN_FLAGS.includes('custom-telemetry'));
});
test('describe reports effective state and source per known flag', () => {
- const envOn = describe({ env: { GENPAGE_ENABLE_CUSTOM_API: '1' }, flags: { 'custom-api': false } });
- const c1 = envOn.find((f) => f.flag === 'custom-api');
+ const envOn = describe({ env: { GENPAGE_ENABLE_CUSTOM_TELEMETRY: '1' }, flags: { 'custom-telemetry': false } });
+ const c1 = envOn.find((f) => f.flag === 'custom-telemetry');
assert.equal(c1.enabled, true);
assert.equal(c1.source, 'env');
- const fileOn = describe({ env: {}, flags: { 'custom-api': true } });
- const c2 = fileOn.find((f) => f.flag === 'custom-api');
+ const fileOn = describe({ env: {}, flags: { 'custom-telemetry': true } });
+ const c2 = fileOn.find((f) => f.flag === 'custom-telemetry');
assert.equal(c2.enabled, true);
assert.equal(c2.source, 'file');
const dflt = describe({ env: {}, flags: {} });
- const c3 = dflt.find((f) => f.flag === 'custom-api');
+ const c3 = dflt.find((f) => f.flag === 'custom-telemetry');
assert.equal(c3.enabled, false);
assert.equal(c3.source, 'default');
});
test('validateFlags warns on unknown keys and non-boolean values, ignores _comment', () => {
- assert.deepEqual(validateFlags({ 'custom-api': false, _comment: 'x' }), []);
- assert.match(validateFlags({ 'custom-apy': true })[0], /unknown flag/i);
- assert.match(validateFlags({ 'custom-api': 'yes' })[0], /boolean/i);
+ assert.deepEqual(validateFlags({ 'custom-telemetry': false, _comment: 'x' }), []);
+ assert.match(validateFlags({ 'custom-telemetri': true })[0], /unknown flag/i);
+ assert.match(validateFlags({ 'custom-telemetry': 'yes' })[0], /boolean/i);
});
// --- flag catalog: status tracking for experimental / in-progress features --
-test('FLAGS catalog documents custom-api with a status and summary', () => {
- assert.ok(FLAGS['custom-api'], 'custom-api flag should be in the catalog');
- assert.ok(['experimental', 'in-progress', 'ga'].includes(FLAGS['custom-api'].status));
- assert.match(FLAGS['custom-api'].summary, /custom api|action|function|plug-?in/i);
- assert.ok(FLAGS['custom-api'].dependencies, 'should document what it depends on');
- assert.match(FLAGS['custom-api'].enableEnv, /GENPAGE_ENABLE_CUSTOM_API/);
+test('FLAGS catalog documents custom-telemetry with a status and summary', () => {
+ assert.ok(FLAGS['custom-telemetry'], 'custom-telemetry flag should be in the catalog');
+ assert.ok(['experimental', 'in-progress', 'ga'].includes(FLAGS['custom-telemetry'].status));
+ assert.match(FLAGS['custom-telemetry'].summary, /telemetry|Application Insights/i);
+ assert.ok(FLAGS['custom-telemetry'].dependencies, 'should document what it depends on');
+ assert.match(FLAGS['custom-telemetry'].enableEnv, /GENPAGE_ENABLE_CUSTOM_TELEMETRY/);
});
test('KNOWN_FLAGS is derived from the FLAGS catalog', () => {
@@ -239,6 +376,74 @@ test('KNOWN_FLAGS is derived from the FLAGS catalog', () => {
test('describe includes the status for each known flag', () => {
const d = describe({ env: {}, flags: {} });
- const c = d.find((f) => f.flag === 'custom-api');
- assert.equal(c.status, FLAGS['custom-api'].status);
+ for (const flag of KNOWN_FLAGS) assert.equal(d.find((f) => f.flag === flag).status, FLAGS[flag].status, flag);
+});
+
+// --- dataverse-operations: its own default-OFF gate, which never decides Custom API support ------------------
+
+const DATAVERSE_OPERATIONS_LINE = 'Dataverse built-in operation authoring is disabled (feature flag "dataverse-operations" is OFF). '
+ + 'Set GENPAGE_ENABLE_DATAVERSE_OPERATIONS=1 to offer WhoAmI and RetrieveVersion. '
+ + 'Existing bindings are preserved; runtime governance and user privileges still apply.';
+
+test('dataverse-operations is a registered flag: its env override turns it on, and the retired custom-api variable decides nothing', () => {
+ // An unregistered flag ignores its env var (isEnabled fails closed for unknown names), so registration is what this pins.
+ assert.equal(isEnabled('dataverse-operations', { env: { GENPAGE_ENABLE_DATAVERSE_OPERATIONS: '1' } }), true);
+ assert.ok(KNOWN_FLAGS.includes('dataverse-operations'));
+ assert.equal(FLAGS['dataverse-operations'].status, 'experimental');
+ assert.equal(FLAGS['dataverse-operations'].enableEnv, 'GENPAGE_ENABLE_DATAVERSE_OPERATIONS=1');
+ assert.match(FLAGS['dataverse-operations'].summary, /WhoAmI/);
+ assert.match(FLAGS['dataverse-operations'].summary, /RetrieveVersion/);
+ assert.equal(envVarName('dataverse-operations'), 'GENPAGE_ENABLE_DATAVERSE_OPERATIONS');
+ // The retired custom-api variable is no switch for this flag either way.
+ assert.equal(isEnabled('dataverse-operations', { env: { GENPAGE_ENABLE_CUSTOM_API: '1' } }), false);
+ assert.equal(isEnabled('dataverse-operations', { env: { GENPAGE_ENABLE_CUSTOM_API: '0', GENPAGE_ENABLE_DATAVERSE_OPERATIONS: '1' } }), true);
+});
+
+test('dataverse-operations ships OFF; an unset, blank or unrecognized env value defers to the file, which is not a forced false', () => {
+ const json = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'feature-flags.json'), 'utf8'));
+ assert.equal(json['dataverse-operations'], false);
+ assert.deepEqual(validateFlags(json), []);
+ assert.equal(isEnabled('dataverse-operations', { env: {} }), false);
+ for (const value of [undefined, '', ' ', 'maybe', 'enable']) {
+ const env = value === undefined ? {} : { GENPAGE_ENABLE_DATAVERSE_OPERATIONS: value };
+ assert.equal(isEnabled('dataverse-operations', { env, flags: {} }), false, `${JSON.stringify(value)} over a file without the flag`);
+ assert.equal(isEnabled('dataverse-operations', { env, flags: { 'dataverse-operations': true } }), true, `${JSON.stringify(value)} defers to a file that says true`);
+ }
+ for (const value of ['0', 'false', 'NO', ' off ']) {
+ assert.equal(isEnabled('dataverse-operations', { env: { GENPAGE_ENABLE_DATAVERSE_OPERATIONS: value }, flags: { 'dataverse-operations': true } }), false, value);
+ }
+ for (const value of ['1', 'true', 'YES', ' on ']) {
+ assert.equal(isEnabled('dataverse-operations', { env: { GENPAGE_ENABLE_DATAVERSE_OPERATIONS: value }, flags: {} }), true, value);
+ }
+ assert.equal(isEnabled('dataverse-operations', { env: {}, flags: { 'dataverse-operations': 'true' } }), false, 'only a boolean true in the file turns it on');
+ assert.equal(isEnabled('dataverse-operations', { env: {}, flagsPath: path.join(__dirname, 'no-such-flags.json') }), false, 'a missing file stays off');
+ const listed = describe({ env: {}, flags: {} }).find((f) => f.flag === 'dataverse-operations');
+ assert.deepEqual(listed, { flag: 'dataverse-operations', enabled: false, source: 'default', status: 'experimental' });
+});
+
+test('the dataverse-operations helpers print the one byte-stable gate line and exit 3', () => {
+ assert.equal(lib.dataverseOperationsDisabledMessage(), DATAVERSE_OPERATIONS_LINE);
+ assert.equal(lib.isDataverseOperationsEnabled({ env: {} }), false);
+ assert.equal(lib.isDataverseOperationsEnabled({ env: { GENPAGE_ENABLE_DATAVERSE_OPERATIONS: 'on' } }), true);
+ let exitCode = null;
+ let written = '';
+ lib.exitIfDataverseOperationsDisabled({ env: {}, flags: {}, exit: (c) => { exitCode = c; }, write: (s) => { written += s; } });
+ assert.equal(exitCode, 3);
+ assert.equal(written, `${DATAVERSE_OPERATIONS_LINE}\n`);
+ let touched = false;
+ lib.exitIfDataverseOperationsDisabled({ env: { GENPAGE_ENABLE_DATAVERSE_OPERATIONS: '1' }, exit: () => { touched = true; }, write: () => { touched = true; } });
+ assert.equal(touched, false, 'ON is a no-op');
+});
+
+test('CLI probe: dataverse-operations prints "disabled" and exits 1 by default, "enabled" and 0 with the override; usage stays exit 2', () => {
+ const env = { ...process.env };
+ delete env.GENPAGE_ENABLE_DATAVERSE_OPERATIONS;
+ const off = spawnSync(process.execPath, [libPath, 'dataverse-operations'], { encoding: 'utf8', env });
+ assert.equal(off.status, 1, off.stderr);
+ assert.equal(off.stdout, 'disabled\n');
+ const on = spawnSync(process.execPath, [libPath, 'dataverse-operations'], { encoding: 'utf8', env: { ...env, GENPAGE_ENABLE_DATAVERSE_OPERATIONS: '1' } });
+ assert.equal(on.status, 0, on.stderr);
+ assert.equal(on.stdout, 'enabled\n');
+ const usage = spawnSync(process.execPath, [libPath], { encoding: 'utf8', env });
+ assert.equal(usage.status, 2);
});
diff --git a/plugins/model-apps/scripts/tests/genpage-app-edit-real-bundle.test.js b/plugins/model-apps/scripts/tests/genpage-app-edit-real-bundle.test.js
index ac46f4ae4..02f06519c 100644
--- a/plugins/model-apps/scripts/tests/genpage-app-edit-real-bundle.test.js
+++ b/plugins/model-apps/scripts/tests/genpage-app-edit-real-bundle.test.js
@@ -22,6 +22,7 @@ const { main: upload } = require('../genpage-upload.js');
const { FakeGenPageServer, INSTANCE, ACCOUNT_TABLE, appTransport, APP_ID, APP_EXISTING_PAGE_ID, APP_VIEW_ID } = require('./helpers/fake-genpage-server.js');
const { withAppComponents } = require('./helpers/fake-app-components.js');
const { effectiveContentLength } = require('./helpers/wire-framing.js');
+const { withPageType } = require('./helpers/page-component-type.js');
const OTHER = '77777777-7777-4777-8777-777777777777';
const ACCOUNT_ID = '88888888-8888-4888-8888-888888888888';
@@ -278,7 +279,8 @@ test('REAL BUNDLE: the build\'s pin of the tables its pages read — the pages p
},
updateWebResource: async (id, { content }) => { manifest = content; },
addSolutionComponent: async () => {},
- dataverse: { get: async () => ({ status: 200, body: { value: [row] } }) },
+ // The page joins the spec's solution, so the page table's component type is read first (lib/page-solution.js).
+ dataverse: { get: withPageType(async () => ({ status: 200, body: { value: [row] } })) },
};
const warnings = [];
const built = await runSdkBuild(spec, {
diff --git a/plugins/model-apps/scripts/tests/genpage-data-semantics-docs.test.js b/plugins/model-apps/scripts/tests/genpage-data-semantics-docs.test.js
new file mode 100644
index 000000000..60c871dcc
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/genpage-data-semantics-docs.test.js
@@ -0,0 +1,196 @@
+'use strict';
+// What the reference documents teach about data semantics and lookup identities, pinned where a page builder or the planner reads it.
+// Nothing executes these documents, so a reworded rule could quietly put back the advice that broke pages: that a lookup's
+// `_<field>_value` is a GUID (the current player returns `/<table>(<guid>)` for Customer and Owner lookups), that a Customer
+// lookup can be opened as an account, or that a failed lookup write may be retried.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+
+const PLUGIN = path.join(__dirname, '..', '..');
+const read = (...parts) => fs.readFileSync(path.join(PLUGIN, ...parts), 'utf8').replace(/\r\n/g, '\n');
+const RULES = read('references', 'rules.md');
+const LOOKUPS_HEADING = '### Lookup references (Customer, Owner, Regarding and every other lookup)';
+
+function section(text, heading) {
+ const start = text.indexOf(`\n${heading}\n`);
+ assert.ok(start >= 0, `the document has the section "${heading}"`);
+ const next = text.slice(start + heading.length + 2).search(/\n#{2,3} /);
+ return next < 0 ? text.slice(start) : text.slice(start, start + heading.length + 2 + next);
+}
+
+test('rules.md no longer says a lookup `_<field>_value` read value is the GUID; it teaches the dual shape', () => {
+ assert.doesNotMatch(RULES, /`_<field>_value` is the GUID/, 'the measured player returns `/<table>(<guid>)` for Customer and Owner lookups');
+ assert.match(RULES, /normalizeLookupReference/, 'the read contract names the canonical normalizer');
+ const usage = section(RULES, '## DataAPI Usage Examples');
+ assert.match(usage, /bare GUID or `\/<table>\(<guid>\)`/, 'the usage examples state both read shapes');
+ assert.match(usage, /FormattedValue/, 'neighbour: the label still comes from the FormattedValue annotation');
+});
+
+test('the lookup section sits after DataAPI Rule 13, shows the canonical normalizer once, and states the measured read contract', () => {
+ const rule13 = RULES.indexOf('13. **Setting a lookup on create/update');
+ const lookups = RULES.indexOf(`\n${LOOKUPS_HEADING}\n`);
+ const grid = RULES.indexOf('\n### DataGrid Requirements\n');
+ assert.ok(rule13 > 0 && rule13 < lookups && lookups < grid, 'between Rule 13 and the DataGrid requirements');
+ const body = section(RULES, LOOKUPS_HEADING);
+ assert.equal((body.match(/\bfunction normalizeLookupReference\(/g) || []).length, 1, 'the body is shown once, not reimplemented per pair');
+ for (const state of ["'unset'", "'resolved'", "'needs-target'", "'invalid'"]) assert.ok(body.includes(state), state);
+ assert.match(body, /@Microsoft\.Dynamics\.CRM\.lookuplogicalname/);
+ assert.match(body, /HTTP 400/, 'a qualified filter operand is refused');
+ assert.match(body, /Single-target lookups, team-owned rows, Regarding and `loadMoreRows` pages were not part of that verification/, 'the live claim is scoped');
+ assert.match(body, /complete\*\* target set/, 'allowedTargets is the complete metadata target set');
+ // Rules 12 and 13 point at it, and keep their own advice.
+ const rule12 = RULES.slice(RULES.indexOf('12. **Lookup display-name fields'), rule13);
+ assert.match(rule12, /Lookup references/);
+ assert.match(rule12, /@OData\.Community\.Display\.V1\.FormattedValue/);
+ const rule13Text = RULES.slice(rule13, lookups);
+ assert.match(rule13Text, /Lookup references/);
+ assert.match(rule13Text, /never `@odata\.bind`/);
+});
+
+test('the five pitfalls each show WRONG and CORRECT, and the CORRECT code never guesses a target', () => {
+ const body = section(RULES, LOOKUPS_HEADING);
+ const pairs = ['**A. Read and consume a normalized identity.**', '**B. Select the relationship and roll-up meaning before generating a filter.**',
+ '**C. Non-id filters and name searches do not implicitly select a target.**', '**D. Navigate to the resolved target with the bare id.**',
+ '**E. Write the selected target; rebuild the qualified form only at the write boundary.**'];
+ let at = 0;
+ for (const pair of pairs) {
+ const start = body.indexOf(pair, at);
+ assert.ok(start >= at, `${pair} in order`);
+ const next = pairs.indexOf(pair) + 1 < pairs.length ? body.indexOf(pairs[pairs.indexOf(pair) + 1]) : body.length;
+ const text = body.slice(start, next);
+ assert.match(text, /\/\/ WRONG/, `${pair} WRONG`);
+ assert.match(text, /\/\/ CORRECT/, `${pair} CORRECT`);
+ at = start + 1;
+ }
+ const correct = [...body.matchAll(/\/\/ CORRECT[^\n]*\n([\s\S]*?)(?=\n\/\/ |\n```)/g)].map((match) => match[1]).join('\n');
+ assert.match(correct, /entityName: reference\.table, entityId: reference\.id/, 'navigation uses the resolved pair');
+ assert.match(correct, /customerid_account\/accountid eq \$\{reference\.id\}/, 'a typed path with the bare id');
+ assert.match(correct, /selected\.table === 'account'/, 'a write chooses the table from the selection');
+ assert.doesNotMatch(correct, /targets\[0\]|allowedTargets\[0\]\s*\]/, 'never the first target');
+ assert.doesNotMatch(body, /ownerid_(?:team|systemuser)/, 'no manufactured Owner path');
+ assert.doesNotMatch(correct, /@odata\.bind/);
+ assert.match(body, /`_customerid_value: null`/, 'a link is cleared with null');
+});
+
+test('lookup failures go through the five-argument reporter: reads as read, writes as write with no retry', () => {
+ const body = section(RULES, LOOKUPS_HEADING);
+ const calls = [...body.matchAll(/reportPageError\(([^)]*)\)/g)].map((match) => match[1]);
+ assert.ok(calls.length >= 2, 'the section names the reporter');
+ for (const args of calls) {
+ if (args.includes('…')) continue;
+ const parts = args.split(',').map((part) => part.trim());
+ assert.equal(parts.length, 5, `five arguments, no retry: reportPageError(${args})`);
+ assert.match(parts[4], /^'(?:read|write)'$/, `the kind is the fifth argument: ${args}`);
+ assert.equal(parts[0], 'PAGE_NAME');
+ }
+ assert.match(body, /with \*\*no retry argument\*\*/);
+ assert.match(body, /never a row, a reference pair or a returned success payload/);
+ assert.match(body, /a thrown read is never cached as unknown, no match, rows or success/);
+});
+
+// --- The authoring path: the schema, the planner, the orchestrator and the page builder agree on the records ----------------------
+
+const SCHEMA = read('references', 'plan-schema.md');
+const PLANNER = read('agents', 'genpage-planner.md');
+const SKILL = read('skills', 'genpage', 'SKILL.md');
+const BUILDER = read('agents', 'genpage-page-builder.md');
+const CHECKLIST = 'Every relationship and every server-side or client-side filter used in `## Per-Page Specifications` traces to the user\'s stated text in `## User Requirements` or a named `## Assumptions` entry. The builder introduces no unrecorded business predicate, relationship or roll-up.';
+const LIMIT = 'Validation proves structure, ID resolution, quote presence and agreement with approved structured decisions. It does not prove natural-language entailment, judge materiality, or discover arbitrary contradictory prose. Those remain planner/reviewer responsibilities, supplemented by scenario-specific code checks.';
+
+test('plan-schema.md places Assumptions right after User Requirements and gives every record its grammar', () => {
+ const template = SCHEMA.slice(SCHEMA.indexOf('## Required Structure'), SCHEMA.indexOf('## Section Semantics'));
+ const at = (heading) => template.indexOf(`\n${heading}\n`);
+ assert.ok(at('## User Requirements') < at('## Assumptions') && at('## Assumptions') < at('## Working Directory'), 'Assumptions sits between User Requirements and Working Directory');
+ for (const text of ['No assumptions.', '### A1 — [short title]', '- Decision:', '- Alternatives considered:', '- Evidence:', '- Resolution: [user-confirmed | planner-default | unattended-default]', 'Unattended default: A1 / <question id> → <answer> (<reason>)',
+ '#### Data semantics', '##### R1', '##### F1', '- Requirement quote:', '#### Lookup metadata', '| Table | Column | Read property | Targets | Used by | Metadata state |', '| Table | Column | Target | Navigation property | Referenced key |']) {
+ assert.ok(template.includes(text), text);
+ }
+ assert.match(SCHEMA, /`Evidence` starts with `metadata:`, `sample:` or `default:`/);
+ assert.match(SCHEMA, /reason that never contains the word "approved"/);
+ assert.match(SCHEMA, /level five, never level three/);
+ assert.match(SCHEMA, /`### Assumptions` \*\*first\*\*/, 'the preview shows Assumptions first');
+ assert.match(SCHEMA, /never a whole-document hash/);
+ assert.match(SCHEMA, /An older plan without these sections is \*\*not recorded\*\*/);
+ assert.match(SCHEMA, /byte for byte/, 'User Requirements stays the original request');
+});
+
+test('the traceability checklist is stated with its limit beside it, in the schema, the planner and the orchestrator', () => {
+ for (const [name, text] of [['plan-schema.md', SCHEMA], ['genpage-planner.md', PLANNER], ['SKILL.md', SKILL]]) {
+ const flat = text.replace(/\s+/g, ' ');
+ const at = flat.indexOf(CHECKLIST);
+ assert.ok(at >= 0, `${name} states the checklist`);
+ assert.equal(flat.indexOf(LIMIT, at), at + CHECKLIST.length + 1, `${name} states the limit right after it`);
+ }
+});
+
+test('the planner discovers lookups, asks rather than assumes, and records the answer only after it returns', () => {
+ const step4 = PLANNER.slice(PLANNER.indexOf('## Step 4 — Detect What Exists'), PLANNER.indexOf('## Step 5 — Hand the Plan Back for Approval'));
+ const resolve = step4.slice(step4.indexOf('### Resolve Data Semantics'));
+ assert.ok(resolve.length > 0 && step4.indexOf('### Entity Detection') < step4.indexOf('### Resolve Data Semantics'), 'after Entity Detection, before Step 5');
+ assert.match(resolve, /get-lookup-metadata\.js" --env '<envUrl>' --tables/);
+ assert.match(resolve, /<working-dir>\/lookup-metadata\.json/);
+ assert.match(resolve, /never read a failure as "no candidates" or "one candidate"/);
+ const examples = [...resolve.matchAll(/```json\n([\s\S]*?)\n```/g)].map((match) => JSON.parse(match[1]));
+ assert.equal(examples.length, 2);
+ assert.equal(examples[0].questions[0].options.filter((option) => option.default).length, 0, 'several candidates: no default');
+ assert.equal(examples[1].questions[0].options.length, 1);
+ assert.equal(examples[1].questions[0].options[0].default, true, 'a sole candidate is the one marked default');
+ assert.match(resolve, /only then write the settled assumption/);
+ assert.match(resolve, /plan approval never\s+answers a semantic question/);
+ assert.match(resolve, /Unattended default: <assumption id> \/ <question id> → <answer> \(<reason>\)/);
+ assert.match(resolve, /may only promote a `planned` lookup|promote each `planned` lookup/);
+});
+
+test('the planner previews Assumptions first and writes the same records at the plan\'s levels', () => {
+ const step5 = PLANNER.slice(PLANNER.indexOf('## Step 5 — Hand the Plan Back for Approval'), PLANNER.indexOf('## Step 6 — Write genpage-plan.md'));
+ const preview = /```\n(## Genpage Plan[\s\S]*?)\n```/.exec(step5)[1];
+ const order = ['### Assumptions', '### Pages (N total)', '### Data Semantics', '### Lookup Metadata', '### Data Strategy'].map((heading) => preview.indexOf(`\n${heading}\n`));
+ assert.ok(order.every((at, i) => at > 0 && (i === 0 || at > order[i - 1])), `preview order: ${order}`);
+ const step6 = PLANNER.slice(PLANNER.indexOf('## Step 6 — Write genpage-plan.md'), PLANNER.indexOf('## Step 7 — Return Summary'));
+ assert.match(step6, /Write `## Assumptions` right after `## User Requirements`/);
+ assert.match(step6, /the records\s+the maker approved, unchanged/);
+ assert.match(step6, /`## User Requirements` the original request, byte for byte/);
+});
+
+test('the orchestrator verifies a new plan\'s records, reconciles planned lookups after provisioning, and gates generation on observed ones', () => {
+ const phase1 = SKILL.slice(SKILL.indexOf('### Phase 1: Plan'), SKILL.indexOf('#### 1a. Connector discovery'));
+ assert.match(phase1, /genpage-plan-provenance\.js" verify --plan '<working-dir>\/genpage-plan\.md' --approved '@<working-dir>\/\.approved-genpage-plan\.md' --require-assumptions/);
+ assert.match(phase1, /its `### Assumptions` first/);
+ assert.match(phase1, /never approve a plan while one is open/);
+ assert.match(phase1, /Only once every data-semantics question is answered, treat the plan as approved/);
+ assert.match(phase1, /Unattended default: <assumption id> \/ <question id> → <answer> \(<reason>\)/);
+ const reconcile = SKILL.slice(SKILL.indexOf('#### 2c. Reconcile planned lookups'), SKILL.indexOf('### Phase 3: App Creation/Selection'));
+ assert.match(reconcile, /get-lookup-metadata\.js" --env '<envUrl>' --tables/);
+ assert.match(reconcile, /Lookup reconciliation:/);
+ assert.match(reconcile, /verify [^\n]*--require-assumptions --lookup-metadata '<working-dir>\/lookup-metadata\.json'/);
+ assert.match(reconcile, /Do not\s+edit the plan yourself/);
+ const gate = SKILL.slice(SKILL.indexOf('#### 5a. Validate the plan before dispatch'), SKILL.indexOf('#### 5b. Single-page fast path'));
+ assert.match(gate, /verify [^\n]*--require-assumptions --require-observed-lookups --lookup-metadata '<working-dir>\/lookup-metadata\.json'/);
+});
+
+test('the page builder reads the records and consumes lookups only as validated pairs', () => {
+ const step1 = BUILDER.slice(BUILDER.indexOf('## Step 1 — Read the Plan Document'), BUILDER.indexOf('## Step 2 — Read RuntimeTypes.ts'));
+ assert.match(step1, /`#### Data semantics`\*\* and \*\*`#### Lookup metadata`/);
+ assert.match(step1, /add no unrecorded predicate, relationship or\s+roll-up/);
+ assert.match(step1, /stop and report the missing fact/);
+ const rules = BUILDER.slice(BUILDER.indexOf('### Mandatory Rules'), BUILDER.indexOf('### Localization'));
+ assert.match(rules, /Copy `normalizeLookupReference` unchanged from rules\.md/);
+ assert.match(rules, /`reference\.id` \(bare\)/);
+ assert.match(rules, /\*\*Traceability\*\*/);
+ assert.match(rules, /never `@odata\.bind`/, 'neighbour: the write rule stays');
+});
+
+test('Critical Rule 23 states lookup identities as a validated pair, beside the rules it does not renumber', () => {
+ const critical = RULES.slice(RULES.indexOf('\n## Critical Rules\n'), RULES.indexOf('\n## Supported Libraries\n')).replace(/\s+/g, ' ');
+ const rule23 = /\s23\. (.*?)(?= --- |$)/.exec(critical);
+ assert.ok(rule23, 'rules.md has Critical Rule 23');
+ assert.ok(rule23[1].startsWith(`**Lookup identities**: A lookup reference is a validated table-and-bare-id pair, not its label or the first metadata target. Normalize bare GUID and \`/<table>(<guid>)\` read values using the logical-name annotation and/or qualified prefix, checking both against metadata and rejecting conflicts. Use the bare id for filters, retrieval and navigation; rebuild the qualified value only for writes. Record every lookup used by a join/filter and its complete target set in Per-Page Specifications. Ask about unresolved relationship/filter meaning; never broaden a failed typed query. Unresolved references cannot trigger target-dependent actions.`), rule23[1]);
+ assert.match(rule23[1], /See \*\*DataAPI Rules > Lookup references\*\*/, 'it points at the canonical normalizer');
+ // Rules 1-21 and DataAPI Rules 12/13 keep their numbers: 22 follows 21, and 23 follows 22.
+ assert.ok(critical.indexOf(' 21. **End final type-argument') < critical.indexOf(' 22. **Consistent errors**'));
+ assert.ok(critical.indexOf(' 22. **Consistent errors**') < critical.indexOf(' 23. **Lookup identities**'));
+ assert.match(RULES, /\n12\. \*\*Lookup display-name fields cannot be in \$select\*\*/);
+ assert.match(RULES, /\n13\. \*\*Setting a lookup on create\/update — use `_<field>_value`, never `@odata\.bind`\*\*/);
+});
\ No newline at end of file
diff --git a/plugins/model-apps/scripts/tests/genpage-dialog-output.test.js b/plugins/model-apps/scripts/tests/genpage-dialog-output.test.js
new file mode 100644
index 000000000..55576babb
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/genpage-dialog-output.test.js
@@ -0,0 +1,151 @@
+'use strict';
+// A page opened as a dialog returns a value with `dataApi.setPageOutput(value)` and `Xrm.Navigation.navigateBack()` (AB#6757591). The runtime has the method, but
+// the RuntimeTypes.ts the SDK generates for a page does not declare it, so `dataApi.setPageOutput(…)` fails type checking. references/rules.md ("Dialog output") gives the
+// narrow typed intersection that type-checks; these tests hold that text to the types the vendored SDK really generates, and hold the plugin's own page checks to accepting it:
+// - the generated `UxAgentDataApi` has no `setPageOutput`, and a direct call is TS2339 — the SDK gap the rule works around (when the SDK declares the method, this test
+// fails, and the rule can say to call it directly);
+// - the rule's dialog snippet and caller snippet, read from rules.md itself, type-check against those types with no error;
+// - a page written with the pattern passes the checks every page upload makes (Griffel, the navigation scan) and the transpile the SDK compiles a page with.
+// The type check is the vendored TypeScript (scripts/vendor/typescript) with no default library: a few global declarations stand in for lib.d.ts, which the plugin does not ship.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const { generatedRuntimeTypes } = require('./helpers/generated-runtime-types.js');
+const { loadVendoredTypeScript } = require('../lib/typescript-compiler.js');
+const { griffelStyleProblems } = require('../lib/griffel-styles.js');
+const { extractNavTargets, navMalformedRefs, strayPageRefs } = require('../lib/pageref-resolver.js');
+const { pageStructureProblems } = require('../lib/page-structure.js');
+
+// rules.md is read with its line ends normalized: a Windows checkout gives it CRLF (git's core.autocrlf), and the snippets are found by LF patterns — the section's
+// end, the code fences — and joined into a page line by line.
+const RULES = fs.readFileSync(path.join(__dirname, '..', '..', 'references', 'rules.md'), 'utf8').replace(/\r\n/g, '\n');
+const SECTION = '### Dialog output (`setPageOutput`)';
+
+// The globals a page's types touch, in place of lib.d.ts (`noLib`): the ones the compiler itself needs, and those the generated types and the snippets name.
+const GLOBALS = [
+ 'interface Array<T> { length: number; [n: number]: T; } interface ReadonlyArray<T> { readonly length: number; readonly [n: number]: T; }',
+ 'interface Boolean {} interface CallableFunction {} interface Function {} interface IArguments {} interface NewableFunction {} interface Number {} interface Object {} interface RegExp {} interface String {} interface Symbol {} interface Date {}',
+ 'interface Promise<T> { then<R>(f: (value: T) => R): Promise<R>; }',
+ 'type Record<K extends keyof any, T> = { [P in K]: T }; type Partial<T> = { [P in keyof T]?: T[P] }; type Required<T> = { [P in keyof T]-?: T[P] }; type Readonly<T> = { readonly [P in keyof T]: T[P] };',
+ 'type Pick<T, K extends keyof T> = { [P in K]: T[P] }; type Exclude<T, U> = T extends U ? never : T; type Extract<T, U> = T extends U ? T : never; type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>; type NonNullable<T> = T & {};',
+ 'declare const window: unknown;',
+].join('\n');
+
+// The diagnostics of `page` (a TypeScript module that imports './RuntimeTypes') against `runtimeTypes`, as { code, text } — the page's own only.
+function typeCheck(page, runtimeTypes) {
+ const ts = loadVendoredTypeScript();
+ const files = { '/lib.d.ts': GLOBALS, '/RuntimeTypes.ts': runtimeTypes, '/page.ts': page };
+ const host = {
+ getSourceFile: (name, version) => (files[name] === undefined ? undefined : ts.createSourceFile(name, files[name], version)),
+ getDefaultLibFileName: () => '/lib.d.ts',
+ writeFile: () => {},
+ getCurrentDirectory: () => '/',
+ getDirectories: () => [],
+ fileExists: (name) => files[name] !== undefined,
+ readFile: (name) => files[name],
+ getCanonicalFileName: (name) => name,
+ useCaseSensitiveFileNames: () => true,
+ getNewLine: () => '\n',
+ };
+ const options = { noLib: true, strict: true, noEmit: true, target: ts.ScriptTarget.ES2017, module: ts.ModuleKind.ESNext, moduleResolution: ts.ModuleResolutionKind.Node10, types: [] };
+ const program = ts.createProgram(Object.keys(files), options, host);
+ const all = ts.getPreEmitDiagnostics(program);
+ // The generated types are checked too: a declaration they need and the stand-in globals lack would show here, and make the page's own result meaningless.
+ assert.deepEqual(all.filter((d) => d.file && d.file.fileName !== '/page.ts').map((d) => ts.flattenDiagnosticMessageText(d.messageText, ' ')), [], 'the generated types check clean against the stand-in globals');
+ return all.filter((d) => d.file && d.file.fileName === '/page.ts').map((d) => ({ code: d.code, text: ts.flattenDiagnosticMessageText(d.messageText, ' ') }));
+}
+
+// The `typescript` code blocks of the rule's section, in order: the dialog page's, then the caller's.
+function sectionSnippets() {
+ const at = RULES.indexOf(SECTION);
+ assert.ok(at >= 0, `rules.md has the section ${SECTION}`);
+ const rest = RULES.slice(at + SECTION.length);
+ const section = rest.slice(0, rest.search(/\n#{2,3} /));
+ return [...section.matchAll(/```typescript\n([\s\S]*?)```/g)].map((m) => m[1]);
+}
+
+let typesP;
+const runtimeTypes = () => typesP || (typesP = generatedRuntimeTypes());
+
+test('the RuntimeTypes the SDK generates declare no setPageOutput, so a direct call fails type checking — the gap the rule works around', async () => {
+ const types = await runtimeTypes();
+ assert.match(types, /export interface UxAgentDataApi\s+extends BaseUxAgentDataApi<TableRegistrations, EnumRegistrations> \{\}/);
+ assert.doesNotMatch(types, /setPageOutput/, 'when the SDK declares it, the intersection in rules.md is no longer needed: say to call it directly');
+ const direct = typeCheck([
+ "import type { GeneratedComponentProps } from './RuntimeTypes';",
+ 'export function close(props: GeneratedComponentProps, value: unknown): void {',
+ ' props.dataApi.setPageOutput(value);',
+ '}',
+ ].join('\n'), types);
+ assert.deepEqual(direct.map((d) => d.code), [2339]);
+ assert.match(direct[0].text, /Property 'setPageOutput' does not exist on type 'UxAgentDataApi'/);
+});
+
+test('the dialog page snippet in rules.md type-checks against the generated types with no error', async () => {
+ const [dialog] = sectionSnippets();
+ assert.ok(dialog && /setPageOutput/.test(dialog) && /navigateBack\(\)/.test(dialog), 'the first snippet returns the value and closes the dialog');
+ assert.match(dialog, /dataApi as typeof dataApi & \{ setPageOutput\(value: unknown\): void \}/, 'the narrow intersection, not `any`');
+ const page = [
+ "import type { GeneratedComponentProps } from './RuntimeTypes';",
+ 'export function finish(props: GeneratedComponentProps, selectedId: string): void {',
+ ' const { dataApi } = props;',
+ dialog,
+ '}',
+ ].join('\n');
+ assert.deepEqual(typeCheck(page, await runtimeTypes()), []);
+});
+
+test('the caller snippet in rules.md type-checks: navigateTo with target 2, and returnValue read as unknown', async () => {
+ const caller = sectionSnippets()[1];
+ assert.ok(caller && /target: 2/.test(caller) && /returnValue/.test(caller), 'the second snippet opens the dialog and reads what it returned');
+ const page = [
+ 'export async function pick(targetPageId: string): Promise<unknown> {',
+ caller,
+ ' return output;',
+ '}',
+ ].join('\n');
+ assert.deepEqual(typeCheck(page, await runtimeTypes()), []);
+});
+
+test('a page written with the pattern passes the checks every page upload makes and compiles as the SDK compiles it', () => {
+ const [dialog] = sectionSnippets();
+ const page = [
+ "import * as React from 'react';",
+ "import { Button, makeStyles, tokens } from '@fluentui/react-components';",
+ "import type { GeneratedComponentProps } from './RuntimeTypes';",
+ 'const useStyles = makeStyles({ root: { padding: tokens.spacingHorizontalL, borderTopWidth: "1px", borderTopStyle: "solid", borderTopColor: tokens.colorNeutralStroke1 } });',
+ 'const GeneratedComponent = (props: GeneratedComponentProps) => {',
+ ' const { dataApi, pageInput } = props;',
+ ' const styles = useStyles();',
+ ' const selectedId = String(pageInput?.data?.accountId ?? "");',
+ ' const choose = () => {',
+ dialog.split('\n').map((line) => ` ${line}`).join('\n'),
+ ' };',
+ ' return <div className={styles.root}><Button appearance="primary" onClick={choose}>Select</Button></div>;',
+ '};',
+ 'export default GeneratedComponent;',
+ ].join('\n');
+ const ts = loadVendoredTypeScript();
+ // A page saved on Windows can hold CRLF line ends, and an upload checks the file as it is (genpage-upload.js decodes it and changes no line end), so the same page
+ // written so passes the same checks.
+ for (const [ends, text] of [['LF', page], ['CRLF', page.replace(/\n/g, '\r\n')]]) {
+ assert.deepEqual(pageStructureProblems(text), [], `${ends}: the structural gate the page of a worker and a promoted page pass`);
+ assert.deepEqual(griffelStyleProblems(text).problems, [], `${ends}: the Griffel check`);
+ assert.deepEqual(navMalformedRefs(text), [], `${ends}: no malformed navigation reference`);
+ assert.deepEqual(strayPageRefs(text), [], `${ends}: no PAGEREF_ token`);
+ assert.deepEqual(extractNavTargets(text), [], `${ends}: navigateBack is no navigation to another page`);
+ const out = ts.transpileModule(text, { reportDiagnostics: true, compilerOptions: { jsx: ts.JsxEmit.React, target: ts.ScriptTarget.ES2017, module: ts.ModuleKind.CommonJS } });
+ assert.deepEqual((out.diagnostics || []).map((d) => ts.flattenDiagnosticMessageText(d.messageText, ' ')), [], ends);
+ assert.match(out.outputText, /setPageOutput/, ends);
+ }
+});
+
+test('rules.md says what the method does and does not do: synchronous and void, it does not close the dialog, and a dialog closed without it returns undefined', () => {
+ const at = RULES.indexOf(SECTION);
+ const text = RULES.slice(at, at + 2500).replace(/\s+/g, ' ');
+ assert.match(text, /`setPageOutput\(value: unknown\): void`\. It stores the value and does \*\*not\*\* close the dialog\./);
+ assert.match(text, /`Xrm\.Navigation\.navigateBack\(\)` closes the dialog, and the caller's `navigateTo` promise resolves with `\{ returnValue: <the value> \}`\./);
+ assert.match(text, /A dialog closed without `setPageOutput` gives `returnValue: undefined`\. The method is synchronous: do not `await` it\./);
+ assert.match(text, /Do not use `any`, and do not change `RuntimeTypes\.ts`/);
+});
diff --git a/plugins/model-apps/scripts/tests/genpage-dispatch-contract.test.js b/plugins/model-apps/scripts/tests/genpage-dispatch-contract.test.js
index 67658260f..665a1ecf3 100644
--- a/plugins/model-apps/scripts/tests/genpage-dispatch-contract.test.js
+++ b/plugins/model-apps/scripts/tests/genpage-dispatch-contract.test.js
@@ -229,32 +229,34 @@ test('single-page inline generation treats missing or malformed Custom API Bindi
// Only the exact sentinel means "none" — a missing, empty or malformed section is a broken plan.
test('the Custom API phase and the page builder never read a missing or malformed section as none', () => {
const skill = readDoc(path.join(PLUGIN, 'skills', 'genpage', 'SKILL.md'));
- const phase = skill.slice(skill.indexOf("**If it prints `enabled`:** read the plan's `## Custom API Bindings`"));
- assert.ok(phase.length > 0, 'the Custom API phase is where it was');
- assert.match(phase.slice(0, 700), /only when its body is exactly `No custom API bindings\.`/);
- assert.match(phase.slice(0, 700), /missing, empty, or malformed, \*\*halt\*\*/);
+ const start = skill.indexOf('### Phase 4.6: Custom API Bindings');
+ assert.ok(start > -1 && skill.indexOf('### Phase 4.6b:') > start, 'the Custom API phase is where it was');
+ const phase = skill.slice(start, skill.indexOf('### Phase 4.6b:'));
+ assert.match(phase, /only\s+when its body is exactly `No custom API bindings\.`/);
+ assert.match(phase, /missing, empty, or malformed, \*\*halt\*\*/);
const builder = readDoc(path.join(PLUGIN, 'agents', 'genpage-page-builder.md'));
assert.match(builder, /That sentinel is the only way a plan says\s+"none"/);
assert.match(builder, /\*\*stop and report it instead of writing the page\*\*/);
assert.doesNotMatch(builder, /is missing entirely, or contains no binding row, the page has \*\*no Custom APIs\*\*/);
});
-// A plan made while `custom-api` was ON still carries its binding table after the flag is turned OFF.
-// Page generation takes that table as permission to emit executeAction/executeFunction calls, while the
-// OFF branch drops actions.json and --actions — so skipping the phase "regardless of the plan" deployed
-// pages calling Custom APIs that were never bound. OFF with a real table must halt before generation.
-test('a disabled Custom API probe halts on a plan that still carries a binding table', () => {
+// Custom API support has no feature flag any more. The phase once probed `custom-api` and, with it OFF, halted on a plan that still carried a
+// binding table (a plan made while it was ON). With nothing to probe there is no OFF branch: the plan's table is always what the page binds,
+// and only a missing, empty or malformed section halts. Inline generation reads the Custom API guidance whenever the plan has a table — it
+// once did so only under an enabled probe.
+test('the Custom API phase probes no flag: the plan\'s table is read whatever was set, and only a broken section halts', () => {
const skill = readDoc(path.join(PLUGIN, 'skills', 'genpage', 'SKILL.md'));
- const start = skill.indexOf("**If it prints `disabled`:** Custom API support is OFF.");
- assert.ok(start > -1, 'the disabled branch of the Custom API phase is where it was');
- const off = skill.slice(start, skill.indexOf("**If it prints `enabled`:** read the plan's `## Custom API Bindings`"));
- assert.match(off, /actual binding table[\s\S]{0,200}\*\*halt before page generation\*\*/, 'a real table under a disabled probe halts');
- assert.match(off, /only a body of exactly `No custom API bindings\.` continues/, 'only the sentinel lets a disabled run go on');
- assert.match(off, /missing, empty, or malformed section halts too/, 'a broken section halts under a disabled probe as well');
- assert.doesNotMatch(off, /regardless of what the\s+plan's/i, 'the disabled branch must not ignore the plan');
- assert.doesNotMatch(off, /Any other section body/i, 'no body but the sentinel means "none"');
+ const start = skill.indexOf('### Phase 4.6: Custom API Bindings');
+ assert.ok(start > -1 && skill.indexOf('### Phase 4.6b:') > start, 'the Custom API phase is where it was');
+ const phase = skill.slice(start, skill.indexOf('### Phase 4.6b:'));
+ assert.match(phase, /Custom API support has no feature flag, so there is nothing to probe here\./);
+ assert.doesNotMatch(phase, /feature-flags\.js|If it prints `(?:enabled|disabled)`|\bcustom-api\b(?!\.md)/, 'no probe and no disabled branch is left');
+ assert.match(phase, /actual binding table/, 'a real table is what the phase reads');
+ assert.match(phase, /missing, empty, or malformed, \*\*halt\*\* before page generation/);
const fastPath = skill.split(/#### 5b\. Single-page fast path/)[1].split(/#### 5c\. Multi-page/)[0];
- assert.match(fastPath, /3b\. Only when the Phase 4\.6 probe printed `enabled` \*\*and\*\*/, 'inline generation reads Custom API guidance only under an enabled probe');
+ assert.match(fastPath, /3b\. Only when the plan's `## Custom API Bindings` section contains an \*\*actual\s+binding table\*\*/,
+ 'inline generation reads Custom API guidance whenever the plan has a table');
+ assert.doesNotMatch(fastPath, /Phase 4\.6 probe/, 'inline generation waits for no Custom API probe');
});
// The manifest generator exits 2 when an existing package.json lacks a package a requested feature needs
@@ -1126,3 +1128,25 @@ test('genpage stamps every page target before it is written, in both paths', ()
assert.match(fastPath, /`<filename>` is the page's `File` value from the plan without its `\.tsx`\s+extension/, 'the single-page path says what <filename> is');
assert.match(multi, /`<filename>` and `\[filename\]` are each page's `File` value from the\s+plan without its `\.tsx` extension/, 'and so does the multi-page path');
});
+
+// The create flow's provenance gates use the semantic options, and only flags the script declares: an unknown flag is a usage
+// error, so a documented flag the script does not know would halt every run — and, before flags were declared, was dropped silently.
+test('every genpage-plan-provenance.js command the genpage flows document uses only flags the script declares', () => {
+ const script = fs.readFileSync(path.join(PLUGIN, 'scripts', 'genpage-plan-provenance.js'), 'utf8');
+ const declared = new Set([...script.matchAll(/^const (?:VALUE|BOOLEAN)_FLAGS = \[([^\]]*)\]/gm)]
+ .flatMap((match) => [...match[1].matchAll(/'([^']+)'/g)].map((name) => name[1])));
+ for (const flag of ['plan', 'approved', 'require-assumptions', 'require-observed-lookups', 'lookup-metadata']) assert.ok(declared.has(flag), `the script declares --${flag}`);
+ let commands = 0;
+ for (const file of [path.join(PLUGIN, 'skills', 'genpage', 'SKILL.md'), path.join(PLUGIN, 'skills', 'genpage', 'edit-flow.md')]) {
+ for (const command of readDoc(file).matchAll(/genpage-plan-provenance\.js"\s+(prepare|verify)([^\n`]*)/g)) {
+ commands += 1;
+ for (const flag of command[2].matchAll(/--([a-z-]+)/g)) assert.ok(declared.has(flag[1]), `${rel(file)}: --${flag[1]} is not a flag the script declares`);
+ }
+ }
+ assert.ok(commands >= 5, `expected the create and edit flows to document their provenance commands, found ${commands}`);
+ const skill = readDoc(path.join(PLUGIN, 'skills', 'genpage', 'SKILL.md'));
+ assert.match(skill, /verify [^\n]*--require-assumptions/, 'the create flow verifies a newly authored plan with its semantic records');
+ assert.match(skill, /verify [^\n]*--require-observed-lookups --lookup-metadata/, 'and gates generation on observed lookups');
+ const editFlow = readDoc(path.join(PLUGIN, 'skills', 'genpage', 'edit-flow.md'));
+ assert.doesNotMatch(editFlow, /--require-assumptions|--require-observed-lookups|--lookup-metadata/, 'neighbour: an edit plan keeps its own comparison');
+});
diff --git a/plugins/model-apps/scripts/tests/genpage-entity-builder-input.test.js b/plugins/model-apps/scripts/tests/genpage-entity-builder-input.test.js
new file mode 100644
index 000000000..cda04180b
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/genpage-entity-builder-input.test.js
@@ -0,0 +1,167 @@
+'use strict';
+
+// agents/genpage-entity-builder.md Step 4 tells the /genpage entity-builder how to write the input of provision-entities.js. That
+// input is validated by validateProvisionInput (lib/provision-input.js) and built by the same code as an App Spec, so what Step 4 shows
+// has to be what that gate accepts and what the build reads — or the documented path fails before anything is written (a Choice option
+// written as a {"label", "value"} object: "'label' is not an LCID"), or builds a column without what the plan asked (a DateTime
+// `format` where the build reads `dateFormat`). These tests read Step 4 itself, fill its placeholders, and run what it shows through
+// the gate and the provisioning core, so the page and the code cannot drift apart again.
+
+const { test } = require('node:test');
+const assert = require('node:assert');
+const fs = require('node:fs');
+const path = require('node:path');
+const { validateProvisionInput } = require('../lib/provision-input.js');
+const { TYPE_MAP } = require('../lib/app-spec.js');
+const { provisionEntities } = require('../provision-entities.js');
+
+const DOC = path.join(__dirname, '..', '..', 'agents', 'genpage-entity-builder.md');
+
+// Step 4 of the page: from its heading to the next step's.
+function stepFour() {
+ const text = fs.readFileSync(DOC, 'utf8').replace(/\r\n/g, '\n');
+ const start = text.indexOf('\n## Step 4');
+ const end = text.indexOf('\n## Step 5', start + 1);
+ assert.ok(start >= 0 && end > start, 'the page has a Step 4 followed by a Step 5');
+ return text.slice(start, end);
+}
+
+// The page's placeholders, made concrete: the prefix and the solution of the plan's `## Environment`, and any other `<Placeholder>`
+// as its letters (`<Display Name>` -> `DisplayName`, `${PREFIX}_<columnSuffix>` -> `new_columnSuffix`).
+function fill(text) {
+ return text
+ .replace(/\$\{PREFIX\}|<PREFIX>/g, 'new')
+ .replace(/<SOLUTION>/g, 'Default')
+ .replace(/<([^<>"\n]+)>/g, (_, inner) => inner.replace(/[^A-Za-z0-9]/g, ''));
+}
+
+// Every ```json block of Step 4, parsed after its placeholders are filled. A column whose type is itself a placeholder takes a
+// real type, as the entity-builder gives it one from the mapping table.
+function jsonBlocks() {
+ const blocks = [];
+ for (const match of stepFour().matchAll(/```json\n([\s\S]*?)```/g)) {
+ let parsed;
+ assert.doesNotThrow(() => { parsed = JSON.parse(fill(match[1])); }, `a JSON block of Step 4 parses once its placeholders are filled:\n${match[1]}`);
+ blocks.push(parsed);
+ }
+ for (const block of blocks) {
+ for (const entity of block.entities || []) {
+ for (const column of entity.columns || []) if (!Object.hasOwn(TYPE_MAP, column.type)) column.type = 'Text';
+ }
+ }
+ return blocks;
+}
+
+// An input holds every table its relationships name: a placeholder relationship names its own tables, which the skeleton's one table
+// stands in for.
+function withTablesFor(input) {
+ const out = JSON.parse(JSON.stringify(input));
+ const template = out.entities[0];
+ const named = new Set(out.entities.map((e) => e.schemaName.toLowerCase()));
+ for (const r of out.relationships || []) {
+ for (const table of [r.referenced, r.referencing, r.entity1, r.entity2]) {
+ if (typeof table !== 'string' || named.has(table.toLowerCase())) continue;
+ named.add(table.toLowerCase());
+ out.entities.push({ ...template, schemaName: table, columns: [] });
+ }
+ }
+ return out;
+}
+
+// The rows of Step 4's type mapping table: | `plan type` | `AppSpecType` | properties |.
+function typeRows() {
+ const rows = [];
+ for (const line of stepFour().split('\n')) {
+ const cells = line.split('|').slice(1, -1).map((c) => c.trim());
+ if (cells.length !== 3 || !/^`[A-Za-z]+`$/.test(cells[1])) continue;
+ rows.push({ planType: cells[0], type: cells[1].slice(1, -1), properties: cells[2] });
+ }
+ return rows;
+}
+
+// A property name in a row is a backticked identifier that starts in lower case (`maxLength`); a value is not (`Email`, `DateOnly`, a JSON example).
+const propertyNames = (cell) => [...cell.matchAll(/`([a-z][A-Za-z]*)`/g)].map((m) => m[1]);
+
+// A value each documented property can take, and the key of the SDK's column options it reaches (lib/entity-provision.js columnOptions).
+const SAMPLE = {
+ maxLength: [250, 'maxLength'], format: ['Email', 'stringFormat'], minValue: [0, 'minValue'], maxValue: [10, 'maxValue'],
+ precision: [2, 'precision'], dateFormat: ['DateOnly', 'dateFormat'], defaultValue: [true, 'defaultValue'],
+ trueLabel: ['Open', 'trueLabel'], falseLabel: ['Closed', 'falseLabel'],
+};
+
+// One table, as the entity-builder writes it, to hold the column a test puts in: the documented examples are tried on their own, so that
+// one of them going wrong names itself.
+const oneTable = (columns) => ({
+ solution: { uniqueName: 'Default', publisherPrefix: 'new' },
+ entities: [{ schemaName: 'new_Ticket', displayName: 'Ticket', pluralName: 'Tickets', primaryAttribute: { schemaName: 'new_name', displayName: 'Name' }, columns }],
+ relationships: [],
+});
+
+function mockDeps() {
+ const created = [];
+ const sdk = {
+ queryRecords: async () => [{ solutionid: 's' }], createPublisher: async () => ({ id: 'p' }), createSolution: async () => ({ id: 's' }),
+ createTable: async (o) => ({ logicalName: o.schemaName.toLowerCase(), entitySetName: `${o.schemaName.toLowerCase()}s`, metadataId: `tbl-${o.schemaName}` }),
+ updateTable: async () => ({}), updateColumn: async () => ({}),
+ createColumn: async (l, o) => { created.push(o); return { logicalName: o.schemaName.toLowerCase(), metadataId: `col-${o.schemaName}` }; },
+ createGlobalOptionSet: async () => ({ metadataId: 'g' }), insertStatusValue: async () => 1, createAlternateKey: async () => ({}),
+ createCustomerColumn: async (l, o) => ({ logicalName: o.schemaName.toLowerCase(), metadataId: `col-${o.schemaName}` }),
+ createRelationship: async (o) => ({ schemaName: o.schemaName, metadataId: `rel-${o.schemaName}` }),
+ };
+ const provision = { findTables: async () => [], findColumns: async () => [], fetchEntityMetadata: async (l) => ({ logicalName: l, entitySetName: `${l}s`, relationships: [] }), queryRecords: async () => [{ solutionid: 's' }] };
+ return { sdk, provision, created };
+}
+
+test('the input Step 4 shows is accepted by the provision-entities gate', () => {
+ const [skeleton] = jsonBlocks();
+ assert.ok(skeleton && Array.isArray(skeleton.entities), 'the first JSON block of Step 4 is the input');
+ const result = validateProvisionInput(withTablesFor(skeleton));
+ assert.deepStrictEqual(result, { ok: true, errors: [] });
+});
+
+test('every relationship Step 4 shows is accepted inside an input that holds its tables', () => {
+ const [skeleton, ...rest] = jsonBlocks();
+ const relationships = rest.filter((block) => block && typeof block.type === 'string');
+ assert.deepStrictEqual(relationships.map((r) => r.type).sort(), ['ManyToMany', 'OneToMany'], 'Step 4 shows a 1:N and an N:N relationship');
+ for (const relationship of relationships) {
+ const result = validateProvisionInput(withTablesFor({ ...skeleton, relationships: [relationship] }));
+ assert.deepStrictEqual(result, { ok: true, errors: [] }, JSON.stringify(relationship));
+ }
+});
+
+test('the Choice options Step 4 shows are accepted and become options numbered 100000000 + index, labelled as written', async () => {
+ const row = typeRows().find((r) => r.type === 'Choice');
+ assert.ok(row, 'the type mapping table has a Choice row');
+ // The example is the first JSON array the row shows in backticks (an ellipsis that stands for "and so on" is left out).
+ const example = [...row.properties.matchAll(/`[^`]*?(\[[^`]*\])[^`]*`/g)].map((m) => m[1].replace(/,\s*\.\.\.\s*\]$/, ']'))[0];
+ assert.ok(example, `the Choice row shows its options: ${row.properties}`);
+ const options = JSON.parse(example);
+ const input = oneTable([{ schemaName: 'new_priority', displayName: 'Priority', type: 'Choice', options }]);
+ assert.deepStrictEqual(validateProvisionInput(input), { ok: true, errors: [] });
+ const d = mockDeps();
+ const result = await provisionEntities(input, { apply: true }, { sdk: d.sdk, provision: d.provision });
+ assert.strictEqual(result.ok, true, JSON.stringify(result.errors));
+ const column = d.created.find((c) => c.schemaName === 'new_priority');
+ assert.deepStrictEqual(column.options, options.map((label, i) => ({ value: 100000000 + i, label })));
+});
+
+test('every property the type mapping table names reaches the column the build creates', async () => {
+ const rows = typeRows();
+ assert.ok(rows.length >= 8, `the table maps the plan's types: ${JSON.stringify(rows)}`);
+ for (const row of rows) {
+ assert.ok(Object.hasOwn(TYPE_MAP, row.type), `${row.planType} maps to an App Spec type: ${row.type}`);
+ for (const property of propertyNames(row.properties)) {
+ if (property === 'options') continue; // the Choice test above
+ assert.ok(SAMPLE[property], `${row.type}: '${property}' is not a property the build reads for a column (lib/entity-provision.js columnOptions)`);
+ const [value, sdkKey] = SAMPLE[property];
+ const input = oneTable([{ schemaName: 'new_sample', displayName: 'Sample', type: row.type, [property]: value }]);
+ assert.deepStrictEqual(validateProvisionInput(input), { ok: true, errors: [] }, `${row.type}.${property}`);
+ const d = mockDeps();
+ const result = await provisionEntities(input, { apply: true }, { sdk: d.sdk, provision: d.provision });
+ assert.strictEqual(result.ok, true, `${row.type}.${property}: ${JSON.stringify(result.errors)}`);
+ const column = d.created.find((c) => c.schemaName === 'new_sample');
+ assert.ok(column, `${row.type}.${property}: the column was created`);
+ assert.deepStrictEqual(column[sdkKey], value, `${row.type}.${property} reaches the create as ${sdkKey}`);
+ }
+ }
+});
diff --git a/plugins/model-apps/scripts/tests/genpage-lexer-hardening.test.js b/plugins/model-apps/scripts/tests/genpage-lexer-hardening.test.js
index 336e3a45a..42aa676f3 100644
--- a/plugins/model-apps/scripts/tests/genpage-lexer-hardening.test.js
+++ b/plugins/model-apps/scripts/tests/genpage-lexer-hardening.test.js
@@ -9,6 +9,9 @@ const { performance } = require('node:perf_hooks');
const { blankNonCodePreservingTemplateExpressions, hasDefaultExport } = require(path.join(__dirname, '..', 'lib', 'source-literals.js'));
const { pageStructureProblems } = require(path.join(__dirname, '..', 'lib', 'page-structure.js'));
const { extractNavTargets, navReferencedKeys, navMalformedRefs, navigationFrontier, resolvePageRefs, strayPageRefs } = require(path.join(__dirname, '..', 'lib', 'pageref-resolver.js'));
+// These tests hold the lexer to its own rules — what it reads for certain, what it reports as a guess, and what a guess costs a page — so they read pages with
+// the lexer alone. Where the lexer guesses, the gates ask the TypeScript parser (typescript-views.js), which parser-check.test.js tests.
+require(path.join(__dirname, '..', 'lib', 'typescript-views.js')).setParserCheck(false);
const { OBJECT_DIVISION_PAGE_RUNNABLE, MISREAD_PAGES, runnable } = require('./helpers/misread-page.js');
function runNavigationSnippet(code) {
diff --git a/plugins/model-apps/scripts/tests/genpage-page-inputs-docs.test.js b/plugins/model-apps/scripts/tests/genpage-page-inputs-docs.test.js
new file mode 100644
index 000000000..680353147
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/genpage-page-inputs-docs.test.js
@@ -0,0 +1,134 @@
+'use strict';
+// Where an agent finds the inputs another generative page accepts (AB#6247727). The platform shows no list of a page's inputs, so passing `data` to a page
+// was trial and error: a guessed key is dropped without a word. references/rules.md ("Page Input > What another page accepts") says where they are — the
+// App Spec's `pages[].pageInput.data` for a page /app-builder built, and the page's own `pageInput` reads for any other page, read from a download — and how
+// each kind is passed: a `pageInput.data` key in the call's `data`, record context (`pageInput.recordId`, `pageInput.entityName`) at the top level of the call.
+// The planner and the page-builder point to it. These tests hold the text to what the plugin's own scripts do — the download command is a real one, it writes the
+// page's source where the text says, and the App Spec declaration it names is the one the page manifest carries and a download restores — and to the page input
+// the SDK generates: the subsection's example, run, gives its target every input it reads.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const vm = require('node:vm');
+const { generatedRuntimeTypes } = require('./helpers/generated-runtime-types.js');
+const { VERBS } = require('../genpage.js');
+const { pageFolderFiles } = require('../lib/genpage-sdk.js');
+const { buildManifest } = require('../lib/page-manifest.js');
+
+const PLUGIN = path.join(__dirname, '..', '..');
+// Every document is read with its line ends normalized: a Windows checkout gives it CRLF (git's core.autocrlf), and the command and the example are found by LF
+// patterns — the code fences, the subsection's end — and the example is split into lines.
+const read = (...parts) => fs.readFileSync(path.join(PLUGIN, ...parts), 'utf8').replace(/\r\n/g, '\n');
+const RULES = read('references', 'rules.md');
+const flat = (text) => text.replace(/\s+/g, ' ');
+
+// The subsection, from its heading to the next heading of its level or above.
+function subsection(text, heading) {
+ const at = text.indexOf(heading);
+ assert.ok(at >= 0, `rules.md has ${heading}`);
+ const rest = text.slice(at + heading.length);
+ return rest.slice(0, rest.search(/\n#{2,3} /));
+}
+const ACCEPTS = '### What another page accepts (read it before you pass it data)';
+
+test('rules.md says where a page\u2019s inputs are, and that each kind travels in its own place: data keys in data, record context at the top level of the call', () => {
+ const pageInput = RULES.slice(RULES.indexOf('## Page Input'), RULES.indexOf('## Special Patterns'));
+ assert.ok(pageInput.includes(ACCEPTS), 'the subsection is in the Page Input section');
+ const text = flat(subsection(RULES, ACCEPTS));
+ assert.match(text, /The platform shows no list of the inputs a page takes\. A page's inputs are the values its own source reads from its `pageInput` prop, and they are of two kinds, which travel in different places of the `navigateTo` call/);
+ assert.match(text, /\| `pageInput\.data\.<key>` \| a data key \| `data: \{ <key>: <value> \}` \|/);
+ assert.match(text, /\| `pageInput\.recordId` \| record context \| `recordId: <the record's id>`, at the top level beside `pageId` — not in `data` \|/);
+ assert.match(text, /\| `pageInput\.entityName` \| record context \| `entityName: "<the table's logical name>"`, at the top level — not in `data` \|/);
+ assert.match(text, /its App Spec declares its data keys as `pages\[\]\.pageInput\.data` \(each key with its type\)\. The producing page declares the same keys in `navigatesTo\[\]\.data`\. `download-model-app\.js` writes both into the spec from the app's page manifest\. The spec declares no record context/);
+ assert.match(text, /Then search `<working-dir>\/targets\/<target-page-id>\/page\.tsx` for `pageInput`, and write down each read with its path/);
+ assert.match(text, /A read of `pageInput\.recordId` or `pageInput\.entityName` \(also `const \{ recordId, entityName \} = pageInput`\) is record context\. Pass both at the top level of the call/);
+ assert.match(text, /Pass each input in the place the target reads it, with the same name: data keys in `data`, record context at the top level\. Do not move one into the other/);
+ assert.match(text, /A page that reads neither kind takes no input: navigate to it with its `pageId` alone\./);
+ // A target that reads only record context is not one that "takes no input", and its record context is not sent in `data`.
+ assert.doesNotMatch(text, /Pass only the keys the target reads, with the same names, in `data`/);
+ assert.doesNotMatch(text, /A page that reads no `pageInput` takes no input/);
+});
+
+test('the download the text gives is the page verb as it is: its flags are the verb\u2019s, and it writes the page\u2019s source as page.tsx in a folder named for the page', () => {
+ const block = /```powershell\n([\s\S]*?)```/.exec(subsection(RULES, ACCEPTS));
+ assert.ok(block, 'the subsection gives the command');
+ const command = block[1].trim();
+ assert.match(command, /^node "\$\{PLUGIN_ROOT\}\/scripts\/genpage\.js" download /);
+ const flags = [...command.matchAll(/--([a-z-]+)/g)].map((m) => m[1]);
+ assert.deepEqual(flags, ['env', 'page-id', 'output-directory']);
+ for (const flag of flags) assert.ok(VERBS.download.known.includes(flag), `--${flag} is a flag of genpage.js download`);
+ for (const flag of VERBS.download.required) assert.ok(flags.includes(flag), `--${flag} is required by genpage.js download, and given`);
+ assert.match(command, /--output-directory '<working-dir>\/targets'/, 'a folder of its own, not the working directory');
+ assert.ok(!/--app-id/.test(command), 'any page of the environment: no app to prove it is in');
+ // What a download writes for a page (`<output-directory>/<page id>/…`): the page's source is page.tsx.
+ const files = pageFolderFiles({ source: 'export default function P(){ return null; }', dataSources: [], conversation: [] });
+ assert.equal(files['page.tsx'], 'export default function P(){ return null; }');
+ assert.match(flat(subsection(RULES, ACCEPTS)), /Do not use the working directory, and record no base marker, because this is a read/);
+});
+
+test('the App Spec declaration the text names is the one the page manifest carries, so a download restores it', () => {
+ const spec = {
+ app: { name: 'Orders' }, solution: { publisherPrefix: 'contoso' },
+ pages: [
+ { key: 'list', name: 'Orders', navigatesTo: [{ targetKey: 'detail', data: { orderId: 'string' } }] },
+ { key: 'detail', name: 'Order', pageInput: { data: { orderId: 'string' } }, directEntry: { behavior: 'selector' } },
+ ],
+ };
+ const manifest = buildManifest(spec, new Map([['list', '00000000-0000-4000-8000-000000000001'], ['detail', '00000000-0000-4000-8000-000000000002']]));
+ const detail = manifest.pages.find((p) => p.key === 'detail');
+ assert.deepEqual(detail.pageInput, { data: { orderId: 'string' } });
+ const list = manifest.pages.find((p) => p.key === 'list');
+ assert.deepEqual(list.navigatesTo, [{ targetKey: 'detail', data: { orderId: 'string' } }]);
+ assert.match(read('scripts', 'download-model-app.js'), /if \(m\.pageInput !== undefined\) p\.pageInput = m\.pageInput;/, 'a download writes the manifest\u2019s declaration into the spec');
+});
+
+test('the navigation rule, the planner and the page-builder send an agent to that subsection before it passes data to a page the plan does not build', () => {
+ assert.match(flat(RULES), /\*\*Passing data to a page this plan does not build:\*\* first read the keys that page accepts — see \*\*Page Input > What another page accepts\*\*\. Never guess the names\./);
+ assert.match(flat(RULES), /Never rely on `recordId` as the delivery channel for a custom ID\. This is how to write the pages of this plan; a page this plan does not build may already read `pageInput\.recordId` and `pageInput\.entityName`, and is called the way it reads them \(see \*\*Page Input > What another page accepts\*\*\)\./);
+ const planner = flat(read('agents', 'genpage-planner.md'));
+ assert.match(planner, /For a page that navigates to an existing page that this plan does not build \(a page of the chosen app, by its page id\), read what that page accepts before you plan the call\./);
+ assert.match(planner, /write in the page's \*\*Interactions\*\* the target's page id, the exact `data` keys it reads \(each with the type it converts the value to\), and whether it reads record context \(`pageInput\.recordId`, `pageInput\.entityName`\), which the call passes at the top level, not in `data`\. If it reads neither, write that it takes no input\./);
+ const builder = flat(read('agents', 'genpage-page-builder.md'));
+ assert.match(builder, /When the target is a page that this plan does not build, pass what that page reads, in the place it reads it \(rules\.md \*\*Page Input > What another page accepts\*\*\): its `pageInput\.data` keys in `data`, and — only when it reads `pageInput\.recordId` or `pageInput\.entityName` — `recordId` and `entityName` at the top level of the call\. Never guessed names\./);
+});
+
+// What a target receives from a call, by the page input the SDK generates for a page: `PageInput` declares `recordId` and `entityName` beside `data`, and the rules'
+// own navigation examples send record context at the top level of the options and custom values in `data` ("entityName and recordId arrive as props.pageInput";
+// "arrives as props.pageInput.data on the target"). So each member of PageInput takes the option of its own name — this is that envelope, and nothing more.
+function declaredPageInputMembers(runtimeTypes) {
+ const body = /export interface PageInput \{([^}]*)\}/.exec(runtimeTypes);
+ assert.ok(body, 'the generated types declare PageInput');
+ return [...body[1].matchAll(/^\s*(\w+)\??:/gm)].map((m) => m[1]);
+}
+const received = (members, options) => Object.fromEntries(members.filter((m) => options[m] !== undefined).map((m) => [m, options[m]]));
+
+// The example of the subsection, run: its call, with `Xrm` and the caller's values stood in for, gives the options; the target's reads, run on the page input those
+// options make, give what the target sees. The example is the rule in the small, so it must hold: what the target reads, the call supplies.
+function runExample(members, rewriteCall = (call) => call) {
+ const block = /```typescript\n([\s\S]*?)```/.exec(subsection(RULES, ACCEPTS));
+ assert.ok(block, 'the subsection gives an example');
+ const lines = block[1].split('\n');
+ const split = lines.findIndex((line) => /^\/\/ So the caller/.test(line));
+ assert.ok(split > 0, 'the example gives the target\u2019s reads, then the call');
+ const reads = lines.slice(0, split).filter((line) => /^const \w+ = /.test(line));
+ const call = rewriteCall(lines.slice(split + 1).join('\n'));
+ let options = null;
+ vm.runInNewContext(call, { Xrm: { Navigation: { navigateTo: (o) => { options = o; } } }, targetPageId: '11111111-0000-4000-8000-000000000001', selectedAccountId: '22222222-0000-4000-8000-000000000002' });
+ assert.ok(options && options.pageType === 'generative', 'the example calls navigateTo for a generative page');
+ const names = reads.map((line) => /^const (\w+) = /.exec(line)[1]);
+ const pageInput = received(members, options);
+ // Spread into an object of this realm: one made in the context has the context's own Object prototype, which a strict comparison tells apart.
+ return { options, seen: { ...vm.runInNewContext(`(function () {\n${reads.join('\n')}\nreturn { ${names.join(', ')} };\n})()`, { pageInput }) } };
+}
+
+test('the example\u2019s call gives its target every input it reads — record context at the top level reaches pageInput.recordId and pageInput.entityName, as the generated PageInput declares; moved into data, it reaches nothing', async () => {
+ const members = declaredPageInputMembers(await generatedRuntimeTypes(['contoso_item'], { prefix: 'page-inputs-docs-' }));
+ assert.deepEqual([...members].sort(), ['data', 'entityName', 'recordId'], 'record context is a member of the page input itself, beside data');
+ const { options, seen } = runExample(members);
+ assert.deepEqual(seen, { accountId: '22222222-0000-4000-8000-000000000002', table: 'account', view: 'summary' }, 'every read of the target is supplied');
+ assert.deepEqual(Object.keys(options.data), ['view'], 'record context is not in data');
+ // The mistake the rule prevents: the same record context sent in `data`. The target reads it at the top level, so it gets nothing.
+ const misplaced = runExample(members, (call) => call.replace('entityName: "account", recordId: selectedAccountId, data: { view: "summary" }', 'data: { view: "summary", entityName: "account", recordId: selectedAccountId }'));
+ assert.deepEqual(misplaced.seen, { accountId: undefined, table: undefined, view: 'summary' });
+});
diff --git a/plugins/model-apps/scripts/tests/genpage-plan-provenance.test.js b/plugins/model-apps/scripts/tests/genpage-plan-provenance.test.js
index e1655d78b..99a56fbc6 100644
--- a/plugins/model-apps/scripts/tests/genpage-plan-provenance.test.js
+++ b/plugins/model-apps/scripts/tests/genpage-plan-provenance.test.js
@@ -537,3 +537,224 @@ test('prepare and verify refuse a hard-linked plan', (t) => {
assert.equal(verified.ok, false);
assert.match(verified.error, /is not a plain file \(a link, junction, hard link or folder\)/);
});
+
+// --- The plan's semantic records (references/plan-schema.md): what was assumed, each page's decisions and lookups --------------
+// The approval preview carries them at its own levels (### Assumptions first; ### Data Semantics and ### Lookup Metadata after the
+// Pages table, by page file) and the written plan at the plan's (## Assumptions; #### Data semantics / #### Lookup metadata in each
+// page's specification). Same page files are not enough: a changed decision needs new approval.
+const SEM_A1 = (decision) => [
+ '- Decision: ' + decision,
+ '- Alternatives considered: An empty form with no initial read; uncached loading.',
+ '- Evidence: default: this page loads on mount, so Critical Rule 15 applies.',
+ '- Resolution: planner-default',
+].join('\n');
+const SEM_LOOKUPS = (state = 'observed') => [
+ '| Table | Column | Read property | Targets | Used by | Metadata state |',
+ '|-------|--------|---------------|---------|---------|----------------|',
+ `| contoso_project | contoso_ownerid | _contoso_ownerid_value | systemuser, team | F1; owner navigation | ${state} |`,
+ '',
+ '- Evidence: lookup-metadata.json; successful source/target metadata discovery.',
+ '- Read target strategy: normalize the logical-name annotation and qualified prefix.',
+].join('\n');
+const SEM_FILTER = '##### F1\n- Kind: filter\n- Definition: Projects owned by the selected owner, matched by the bare id.\n- Source: User Requirements\n- Requirement quote: Projects overview';
+function semPreview({ decision = 'De-duplicate and cache the initial list read.', assumptions = true, lookups = SEM_LOOKUPS(), semantics = SEM_FILTER } = {}) {
+ return [
+ '## Genpage Plan',
+ '',
+ ...(assumptions ? ['### Assumptions', '', '#### A1 — Initial-load caching', SEM_A1(decision), ''] : []),
+ '### Pages (2 total)',
+ '| Page | File | Purpose | Entities |',
+ '|------|------|---------|----------|',
+ '| Overview | overview.tsx | Summary cards | contoso_project |',
+ '| Details | details.tsx | One record | contoso_project |',
+ '',
+ ...(semantics === null ? [] : ['### Data Semantics', '', '#### overview.tsx', '', semantics, '', '#### details.tsx', '', 'None.', '']),
+ ...(lookups === null ? [] : ['### Lookup Metadata', '', '#### overview.tsx', '', lookups, '', '#### details.tsx', '', 'None.', '']),
+ '### Data Strategy',
+ '- Entities to create: contoso_project (contoso_name, contoso_stage)',
+ ].join('\n');
+}
+function semWritten({ decision = 'De-duplicate and cache the initial list read.', assumptions = true, lookups = SEM_LOOKUPS(), semantics = SEM_FILTER } = {}) {
+ return [
+ '# Genpage Plan',
+ '## User Requirements',
+ 'Projects overview and details.',
+ ...(assumptions ? ['## Assumptions', '### A1 — Initial-load caching', SEM_A1(decision)] : []),
+ '## Pages',
+ '| Page | File | Purpose | Entities |',
+ '|------|------|---------|----------|',
+ '| Details | details.tsx | One record | project |',
+ '| Overview | overview.tsx | Summary cards | project |',
+ '## Per-Page Specifications',
+ '### Overview',
+ '- **File:** overview.tsx',
+ ...(semantics === null ? [] : ['#### Data semantics', semantics]),
+ ...(lookups === null ? [] : ['#### Lookup metadata', lookups]),
+ '### Details',
+ '- **File:** details.tsx',
+ ...(semantics === null ? [] : ['#### Data semantics', 'None.']),
+ ...(lookups === null ? [] : ['#### Lookup metadata', 'None.']),
+ ].join('\r\n');
+}
+const LOOKUP_EVIDENCE = {
+ ok: true,
+ tables: [{ logicalName: 'contoso_project', primaryIdAttribute: 'contoso_projectid', primaryNameAttribute: 'contoso_name', lookups: [{
+ column: 'contoso_ownerid', readProperty: '_contoso_ownerid_value', targets: ['systemuser', 'team'], paths: [],
+ sharedPaths: [{ navigationProperty: 'contoso_ownerid', referencedEntity: 'owner', targets: ['systemuser', 'team'] }],
+ }] }],
+};
+function evidenceFile(dir, content) {
+ const file = path.join(dir, 'lookup-metadata.json');
+ fs.writeFileSync(file, typeof content === 'string' ? content : JSON.stringify(content));
+ return file;
+}
+
+test('verifyPlanProvenance compares the approved and written semantic records, not only the page files', () => {
+ const same = verifyPlanProvenance({ planPath: tmpPlan(semWritten()), approvedPlan: semPreview() });
+ assert.equal(same.ok, true, `neighbour: ${same.error}`);
+ assert.match(same.semanticsHash, /^[a-f0-9]{64}$/, 'the verified records are hashed for the log');
+ const changed = verifyPlanProvenance({ planPath: tmpPlan(semWritten({ decision: 'Load the list without a cache.' })), approvedPlan: semPreview() });
+ assert.equal(changed.ok, false, 'a written plan whose A1 decision differs from the approved preview must need re-approval');
+ assert.match(changed.error, /A1 changed its Decision/);
+ assert.deepEqual(changed.writtenTargets, ['details.tsx', 'overview.tsx'], 'the page files are the same');
+ for (const [label, written] of [
+ ['a changed filter', semWritten({ semantics: SEM_FILTER.replace('matched by the bare id', 'matched by the owner name') })],
+ ['a narrowed target set', semWritten({ lookups: SEM_LOOKUPS().replace('systemuser, team', 'systemuser') })],
+ ['an added assumption', semWritten().replace('## Pages', '### A2 — Sort\r\n' + SEM_A1('Sort by name.').replace(/\n/g, '\r\n') + '\r\n## Pages')],
+ ]) {
+ assert.equal(verifyPlanProvenance({ planPath: tmpPlan(written), approvedPlan: semPreview() }).ok, false, label);
+ }
+ // Preview formatting is not compared: wrapped values and blank lines differ, the records do not.
+ const reflowed = semPreview().replace('- Decision: De-duplicate and cache the initial list read.', '- Decision: De-duplicate and cache\n the initial list read.').replace(/\n\n/g, '\n\n\n');
+ assert.equal(verifyPlanProvenance({ planPath: tmpPlan(semWritten()), approvedPlan: reflowed }).ok, true);
+});
+
+test('a one-sided semantic contract is never a legacy downgrade, and a malformed present section fails without any option', () => {
+ for (const [label, written, approved] of [
+ ['the preview has Assumptions, the written plan none', semWritten({ assumptions: false }), semPreview()],
+ ['the written plan has Assumptions, the preview none', semWritten(), semPreview({ assumptions: false })],
+ ['the written plan dropped its lookups', semWritten({ lookups: null }), semPreview()],
+ ['the preview has no records at all', semWritten(), semPreview({ assumptions: false, lookups: null, semantics: null })],
+ ]) {
+ assert.equal(verifyPlanProvenance({ planPath: tmpPlan(written), approvedPlan: approved }).ok, false, label);
+ }
+ const malformed = semWritten().replace('- Resolution: planner-default', '- Resolution: assumed');
+ const result = verifyPlanProvenance({ planPath: tmpPlan(malformed), approvedPlan: semPreview().replace('- Resolution: planner-default', '- Resolution: assumed') });
+ assert.equal(result.ok, false);
+ assert.match(result.error, /Resolution must be/);
+ // An older pair, with neither document carrying the contract, is verified exactly as before.
+ assert.equal(verifyPlanProvenance({ planPath: tmpPlan(WRITTEN), approvedPlan: PREVIEW }).ok, true);
+});
+
+test('--require-assumptions: a newly authored plan cannot evade the comparison by leaving the contract out of both documents', () => {
+ const legacy = verifyPlanProvenance({ planPath: tmpPlan(WRITTEN), approvedPlan: PREVIEW, requireAssumptions: true });
+ assert.equal(legacy.ok, false);
+ assert.match(legacy.error, /no Assumptions section/);
+ assert.equal(verifyPlanProvenance({ planPath: tmpPlan(semWritten()), approvedPlan: semPreview(), requireAssumptions: true }).ok, true);
+ const empty = { assumptions: false, semantics: 'None.', lookups: 'None.' };
+ const sentinels = (doc) => doc.replace(/^(#{2,3}) Pages/m, (all, hashes) => `${hashes} Assumptions\n\nNo assumptions.\n\n${all}`);
+ assert.equal(verifyPlanProvenance({ planPath: tmpPlan(sentinels(semWritten(empty))), approvedPlan: sentinels(semPreview(empty)), requireAssumptions: true }).ok, true, 'the empty sentinels satisfy it');
+ const partial = verifyPlanProvenance({ planPath: tmpPlan(semWritten({ lookups: null })), approvedPlan: semPreview({ lookups: null }), requireAssumptions: true });
+ assert.equal(partial.ok, false, 'every page needs its Lookup metadata');
+ // The options belong to a create plan; an edit plan keeps its own comparison and refuses them.
+ assert.equal(verifyPlanProvenance({ planPath: tmpPlan(EDIT_WRITTEN, EDIT), approvedPlan: EDIT_PREVIEW }).ok, true, 'neighbour: an edit without the options');
+ assert.equal(verifyPlanProvenance({ planPath: tmpPlan(EDIT_WRITTEN, EDIT), approvedPlan: EDIT_PREVIEW, requireAssumptions: true }).ok, false);
+});
+
+test('a planned lookup becomes observed only with successful lookup metadata evidence that matches it', () => {
+ const planned = semPreview({ lookups: SEM_LOOKUPS('planned') });
+ const dir = makeTempDir('genpage-plan-evidence-');
+ const ok = (options) => verifyPlanProvenance({ planPath: tmpPlan(semWritten()), approvedPlan: planned, ...options });
+ assert.equal(ok({}).ok, false, 'no evidence: the promotion is a change');
+ assert.equal(ok({ lookupMetadataPath: evidenceFile(dir, LOOKUP_EVIDENCE) }).ok, true, 'with matching evidence');
+ assert.equal(ok({ lookupMetadataPath: evidenceFile(dir, LOOKUP_EVIDENCE), requireObservedLookups: true }).ok, true);
+ const narrowed = structuredClone(LOOKUP_EVIDENCE);
+ narrowed.tables[0].lookups[0].targets = ['systemuser'];
+ assert.equal(ok({ lookupMetadataPath: evidenceFile(dir, narrowed) }).ok, false, 'a target set the evidence does not hold');
+ assert.equal(ok({ lookupMetadataPath: evidenceFile(dir, { ok: false, code: 'X', error: 'failed' }) }).ok, false, 'a failed read is no evidence');
+ assert.equal(ok({ lookupMetadataPath: evidenceFile(dir, '{ not json') }).ok, false, 'an unreadable file is no evidence');
+ assert.equal(ok({ lookupMetadataPath: path.join(dir, 'missing.json') }).ok, false, 'an absent file is no evidence');
+ assert.equal(ok({ requireObservedLookups: true }).ok, false, '--require-observed-lookups needs the evidence file');
+ const stillPlanned = verifyPlanProvenance({ planPath: tmpPlan(semWritten({ lookups: SEM_LOOKUPS('planned') })), approvedPlan: planned,
+ lookupMetadataPath: evidenceFile(dir, LOOKUP_EVIDENCE), requireObservedLookups: true });
+ assert.equal(stillPlanned.ok, false, 'a lookup still planned before generation');
+ assert.match(stillPlanned.error, /planned/);
+});
+
+test('evidence that is read is validated whatever its value: JSON null is not "no evidence", and never passes an observed plan', () => {
+ const dir = makeTempDir('genpage-plan-null-evidence-');
+ // Already observed in both documents: nothing to promote, so only the evidence check can refuse it.
+ const observed = (content, options = {}) => verifyPlanProvenance({ planPath: tmpPlan(semWritten()), approvedPlan: semPreview(),
+ lookupMetadataPath: evidenceFile(dir, content), ...options });
+ assert.equal(observed(LOOKUP_EVIDENCE, { requireObservedLookups: true, requireAssumptions: true }).ok, true, 'neighbour: matching evidence');
+ for (const content of ['null', 'false', '0', '[]', '"ok"', '{}']) {
+ const result = observed(content, { requireObservedLookups: true, requireAssumptions: true });
+ assert.equal(result.ok, false, `${content}: refused`);
+ assert.match(result.error, /not a successful get-lookup-metadata\.js answer/, content);
+ assert.equal(observed(content).ok, false, `${content}: refused without the other flags too`);
+ }
+ // Nor does it authorize a promotion.
+ const promoted = verifyPlanProvenance({ planPath: tmpPlan(semWritten()), approvedPlan: semPreview({ lookups: SEM_LOOKUPS('planned') }),
+ lookupMetadataPath: evidenceFile(dir, 'null') });
+ assert.equal(promoted.ok, false);
+ // Fixture 26's own approved preview and written plan, both already observed, with a file holding only `null`.
+ const fixture = path.join(__dirname, '..', '..', '..', '..', 'evals', 'model-apps', 'genpage', 'fixtures', '26-customer-lookup');
+ const fixturePlan = tmpPlan(fs.readFileSync(path.join(fixture, 'genpage-plan.md'), 'utf8'));
+ const approved = fs.readFileSync(path.join(fixture, 'approved-plan.md'), 'utf8');
+ const withEvidence = verifyPlanProvenance({ planPath: fixturePlan, approvedPlan: approved, requireAssumptions: true,
+ requireObservedLookups: true, lookupMetadataPath: path.join(fixture, 'lookup-metadata.json') });
+ assert.equal(withEvidence.ok, true, `neighbour: fixture 26 with its own evidence: ${withEvidence.error}`);
+ const fixtureResult = verifyPlanProvenance({ planPath: fixturePlan, approvedPlan: approved, requireAssumptions: true,
+ requireObservedLookups: true, lookupMetadataPath: evidenceFile(dir, 'null') });
+ assert.equal(fixtureResult.ok, false, 'fixture 26 with null evidence');
+ assert.match(fixtureResult.error, /not a successful get-lookup-metadata\.js answer/);
+});
+
+test('a second specification of a page is refused, whichever block carries the records: the approved page is the one written', () => {
+ const fixture = path.join(__dirname, '..', '..', '..', '..', 'evals', 'model-apps', 'genpage', 'fixtures', '26-customer-lookup');
+ const plan = fs.readFileSync(path.join(fixture, 'genpage-plan.md'), 'utf8').replace(/\r\n/g, '\n');
+ const approved = fs.readFileSync(path.join(fixture, 'approved-plan.md'), 'utf8');
+ const evidence = path.join(fixture, 'lookup-metadata.json');
+ const verify = (text) => verifyPlanProvenance({ planPath: tmpPlan(text), approvedPlan: approved, requireAssumptions: true,
+ requireObservedLookups: true, lookupMetadataPath: evidence });
+ assert.equal(verify(plan).ok, true, 'neighbour: the fixture plan');
+ const start = plan.indexOf('\n### Customer Opportunities\n');
+ assert.ok(start > 0, 'the fixture has the page specification');
+ const fileLine = /\n- \*\*File:\*\* [^\n]+/.exec(plan.slice(start))[0];
+ const duplicate = `\n### Customer Opportunities${fileLine}\n- **Purpose:** Browse opportunities by customer\n- **Data Binding:** customerid_contact/contactid\n`;
+ for (const [label, text] of [
+ ['a later duplicate without records', `${plan.trimEnd()}\n${duplicate}`],
+ ['an earlier duplicate without records', plan.slice(0, start) + duplicate + plan.slice(start)],
+ ]) {
+ const result = verify(text);
+ assert.equal(result.ok, false, label);
+ assert.match(result.error, /another page specification/, label);
+ }
+});
+
+test('the CLI takes the semantic options as declared flags and refuses an unknown or misspelled one', () => {
+ const { spawnSync } = require('node:child_process');
+ const script = path.join(__dirname, '..', 'genpage-plan-provenance.js');
+ const run = (...args) => spawnSync(process.execPath, [script, ...args], { encoding: 'utf8' });
+ const dir = makeTempDir('genpage-plan-prov-flags-');
+ const planPath = path.join(dir, 'genpage-plan.md');
+ const approved = path.join(dir, '.approved-genpage-plan.md');
+ fs.writeFileSync(planPath, semWritten());
+ fs.writeFileSync(approved, semPreview({ lookups: SEM_LOOKUPS('planned') }));
+ const evidence = evidenceFile(dir, LOOKUP_EVIDENCE);
+ const ok = run('verify', '--plan', planPath, '--approved', `@${approved}`, '--require-assumptions', '--require-observed-lookups', '--lookup-metadata', evidence);
+ assert.equal(ok.status, 0, ok.stdout);
+ assert.equal(JSON.parse(ok.stdout).ok, true);
+ assert.equal(run('verify', '--plan', planPath, '--approved', `@${approved}`, '--require-assumptions').status, 3, 'the promotion has no evidence');
+ for (const args of [
+ ['--require-assumption'],
+ ['--require-assumptions', 'yes'],
+ ['--lookup-metadata'],
+ ['stray'],
+ ]) {
+ const result = run('verify', '--plan', planPath, '--approved', `@${approved}`, ...args);
+ assert.equal(result.status, 1, args.join(' '));
+ assert.equal(JSON.parse(result.stdout).ok, false);
+ }
+ assert.equal(run('prepare', '--plan', planPath, '--require-assumptions').status, 1, 'prepare takes no semantic option');
+});
diff --git a/plugins/model-apps/scripts/tests/genpage-plan-semantics.test.js b/plugins/model-apps/scripts/tests/genpage-plan-semantics.test.js
new file mode 100644
index 000000000..05e262ef6
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/genpage-plan-semantics.test.js
@@ -0,0 +1,367 @@
+'use strict';
+// The plan's semantic contract (references/plan-schema.md: ## Assumptions, per-page Data semantics and Lookup metadata), read
+// by the pure readers of lib/genpage-plan-semantics.js: the written plan at its levels, the approval preview at its own, every
+// entry rule, the cross-references, the comparison of the approved against the written records, and the check of observed
+// lookups against get-lookup-metadata.js evidence. Plans without any of it are older plans: "not recorded", never "none".
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+
+const semantics = require('../lib/genpage-plan-semantics.js');
+
+const A1 = [
+ '- Decision: Use opportunity.customerid directly referencing the selected account; exclude opportunities whose customer is one of that account\'s contacts.',
+ '- Alternatives considered: opportunity.parentaccountid; direct opportunity.customerid; customerid through the account\'s contacts.',
+ '- Evidence: metadata: customerid targets account, contact; parentaccountid targets account.',
+ '- Resolution: user-confirmed',
+ '- Question: opportunities-account-scope',
+ '- Answer: Direct customer account only.',
+].join('\n');
+const A2 = [
+ '- Decision: De-duplicate and cache the initial list read.',
+ '- Alternatives considered: An empty form with no initial read; uncached loading.',
+ '- Evidence: default: this page loads on mount, so Critical Rule 15 applies.',
+ '- Resolution: planner-default',
+].join('\n');
+const DECISIONS = [
+ '##### R1',
+ '- Kind: relationship',
+ '- Definition: opportunity.customerid references the selected account directly; exclude contact roll-up.',
+ '- Source: A1',
+ '',
+ '##### F1',
+ '- Kind: filter',
+ '- Definition: In the account-only view, match the selected account\'s bare id through the verified Customer-to-account navigation path.',
+ '- Source: A1',
+ '',
+ '##### F2',
+ '- Kind: filter',
+ '- Definition: Match customer names containing the entered substring; the separate target restriction is defined by F1.',
+ '- Source: User Requirements',
+ '- Requirement quote: search customer names by substring',
+].join('\n');
+const LOOKUPS = [
+ '| Table | Column | Read property | Targets | Used by | Metadata state |',
+ '|-------|--------|---------------|---------|---------|----------------|',
+ '| opportunity | customerid | _customerid_value | account, contact | R1, F1, F2; customer navigation; customer picker | observed |',
+ '',
+ '| Table | Column | Target | Navigation property | Referenced key |',
+ '|-------|--------|--------|---------------------|----------------|',
+ '| opportunity | customerid | account | customerid_account | accountid |',
+ '| opportunity | customerid | contact | customerid_contact | contactid |',
+ '',
+ '- Evidence: lookup-metadata.json; successful source/target metadata discovery.',
+ '- Read target strategy: normalize the logical-name annotation and qualified prefix; use metadata-backed fallback only for a bare id with missing target evidence.',
+].join('\n');
+const REQUIREMENTS = 'Build an opportunity browser for an account. Users can search customer names by substring, open and change customers.';
+
+function written({ assumptions = `### A1 — Opportunity relationship\n${A1}\n\n### A2 — Initial-load caching\n${A2}`, decisions = DECISIONS, lookups = LOOKUPS } = {}) {
+ return [
+ '# Genpage Plan',
+ '',
+ '## User Requirements',
+ REQUIREMENTS,
+ '',
+ ...(assumptions === null ? [] : ['## Assumptions', '', assumptions, '']),
+ '## Working Directory',
+ 'D:/work/customer-lookup',
+ '',
+ '## Pages',
+ '| Page | File | Purpose | Entities |',
+ '|------|------|---------|----------|',
+ '| Customer Lookup | customer-lookup.tsx | Browse opportunities by customer | opportunity, account, contact |',
+ '',
+ '## Per-Page Specifications',
+ '',
+ '### Customer Lookup',
+ '- **File:** customer-lookup.tsx',
+ '- **Purpose:** Browse opportunities by customer',
+ '- **Interactions:** Search, open and change customers',
+ '',
+ ...(decisions === null ? [] : ['#### Data semantics', '', decisions, '']),
+ ...(lookups === null ? [] : ['#### Lookup metadata', '', lookups, '']),
+ ].join('\n');
+}
+
+function preview({ assumptions = `#### A1 — Opportunity relationship\n${A1}\n\n#### A2 — Initial-load caching\n${A2}`, decisions = DECISIONS, lookups = LOOKUPS, order = 'normal' } = {}) {
+ const assumed = assumptions === null ? [] : ['### Assumptions', '', assumptions, ''];
+ const pages = ['### Pages (1 total)', '| Page | File | Purpose | Entities |', '|------|------|---------|----------|',
+ '| Customer Lookup | customer-lookup.tsx | Browse opportunities by customer | opportunity, account, contact |', ''];
+ const semantic = decisions === null ? [] : ['### Data Semantics', '', '#### customer-lookup.tsx', '', decisions, ''];
+ const lookup = lookups === null ? [] : ['### Lookup Metadata', '', '#### customer-lookup.tsx', '', lookups, ''];
+ const rest = ['### Data Strategy', '- Entities that exist: opportunity, account, contact', ''];
+ const sections = order === 'assumptions-late' ? [...pages, ...assumed, ...semantic, ...lookup, ...rest]
+ : order === 'semantics-early' ? [...assumed, ...semantic, ...pages, ...lookup, ...rest]
+ : [...assumed, ...pages, ...semantic, ...lookup, ...rest];
+ return ['## Genpage Plan', '', ...sections].join('\n');
+}
+
+const codes = (problems) => problems.map((p) => p.code);
+const EVIDENCE = {
+ ok: true,
+ tables: [{
+ logicalName: 'opportunity',
+ primaryIdAttribute: 'opportunityid',
+ primaryNameAttribute: 'name',
+ lookups: [{
+ column: 'customerid',
+ readProperty: '_customerid_value',
+ targets: ['account', 'contact'],
+ paths: [
+ { target: 'account', navigationProperty: 'customerid_account', referencedKey: 'accountid' },
+ { target: 'contact', navigationProperty: 'customerid_contact', referencedKey: 'contactid' },
+ ],
+ sharedPaths: [],
+ }],
+ }],
+};
+
+test('the written plan and the preview each read cleanly at their own levels, to the same records', () => {
+ const w = semantics.readWrittenSemantics(written());
+ const p = semantics.readPreviewSemantics(preview());
+ assert.deepEqual(w.problems, []);
+ assert.deepEqual(p.problems, []);
+ assert.equal(w.assumptions.entries.size, 2);
+ assert.equal(w.assumptions.entries.get('A1').resolution, 'user-confirmed');
+ assert.equal(w.assumptions.entries.get('A1').title, 'Opportunity relationship');
+ assert.deepEqual([...w.pages.get('customer-lookup.tsx').semantics.entries.keys()], ['R1', 'F1', 'F2']);
+ assert.deepEqual(w.pages.get('customer-lookup.tsx').lookups.rows.get('opportunity|customerid').targets, ['account', 'contact']);
+ assert.deepEqual(semantics.compareSemantics(p, w), []);
+ assert.equal(semantics.hasSemanticContract(w), true);
+ assert.equal(semantics.hasSemanticContract(p), true);
+});
+
+test('an older plan or preview without the contract reads as not recorded — no problems, no contract', () => {
+ const w = semantics.readWrittenSemantics(written({ assumptions: null, decisions: null, lookups: null }));
+ const p = semantics.readPreviewSemantics(preview({ assumptions: null, decisions: null, lookups: null }));
+ assert.deepEqual(w.problems, []);
+ assert.deepEqual(p.problems, []);
+ assert.equal(w.assumptions, null);
+ assert.equal(semantics.hasSemanticContract(w), false);
+ assert.equal(semantics.hasSemanticContract(p), false);
+ assert.deepEqual(semantics.compareSemantics(p, w), []);
+ assert.deepEqual(semantics.writtenSemanticsProblems(written({ assumptions: null, decisions: null, lookups: null })), []);
+});
+
+test('a plan carrying the contract has one specification per page: a second block with its title or file is refused in either order', () => {
+ const block = (title, file, binding) => ['', `### ${title}`, `- **File:** ${file}`, '- **Purpose:** Browse opportunities by customer', `- **Data Binding:** ${binding}`, ''].join('\n');
+ const contact = block('Customer Lookup', 'customer-lookup.tsx', 'customerid_contact/contactid');
+ for (const [label, plan] of [
+ ['a later block without records, same title and file', written() + contact],
+ ['an earlier block without records, same title and file', written().replace('\n### Customer Lookup\n', `${contact}\n### Customer Lookup\n`)],
+ ['a later block under another title, same file', written() + block('Customer Lookup (contacts)', 'customer-lookup.tsx', 'customerid_contact/contactid')],
+ ['a later block with the same title, another file', written() + block('Customer Lookup', 'customer-lookup-2.tsx', 'customerid_contact/contactid')],
+ ]) {
+ const read = semantics.readWrittenSemantics(plan);
+ assert.ok(read.problems.some((p) => p.code === 'invalid-data-semantics' && /another page specification/.test(p.message)), `${label}: ${JSON.stringify(read.problems)}`);
+ assert.ok(semantics.writtenSemanticsProblems(plan, { require: true }).length > 0, `${label}: the schema check refuses it too`);
+ }
+ // An older plan without the contract keeps its absence-only reading: duplicates there are the schema reader's business.
+ const legacy = written({ assumptions: null, decisions: null, lookups: null });
+ assert.deepEqual(semantics.readWrittenSemantics(legacy + contact).problems, []);
+});
+
+test('the empty sentinels are exact and read as recorded-and-empty', () => {
+ const w = semantics.readWrittenSemantics(written({ assumptions: 'No assumptions.', decisions: 'None.', lookups: 'None.' }));
+ assert.deepEqual(w.problems, []);
+ assert.equal(w.assumptions.sentinel, true);
+ assert.equal(w.pages.get('customer-lookup.tsx').semantics.sentinel, true);
+ assert.equal(w.pages.get('customer-lookup.tsx').lookups.sentinel, true);
+ for (const variant of ['No assumptions', 'none', 'No assumptions.\nExtra prose.', '']) {
+ assert.ok(codes(semantics.readWrittenSemantics(written({ assumptions: variant, decisions: 'None.', lookups: 'None.' })).problems).includes('invalid-assumptions'), JSON.stringify(variant));
+ }
+ for (const variant of ['none', 'None', 'N/A']) {
+ assert.ok(codes(semantics.readWrittenSemantics(written({ decisions: variant, lookups: 'None.' })).problems).includes('invalid-data-semantics'), variant);
+ assert.ok(codes(semantics.readWrittenSemantics(written({ lookups: variant })).problems).includes('invalid-lookup-metadata'), variant);
+ }
+});
+
+test('every malformed assumption entry is invalid-assumptions', () => {
+ const entry = (body, title = 'A2 — Initial-load caching') => written({ assumptions: `### A1 — Opportunity relationship\n${A1}\n\n### ${title}\n${body}` });
+ for (const [label, plan] of [
+ ['missing Resolution', entry(A2.replace('\n- Resolution: planner-default', ''))],
+ ['missing Decision', entry(A2.replace(/- Decision: .*\n/, ''))],
+ ['empty Alternatives', entry(A2.replace(/(- Alternatives considered:).*/, '$1 '))],
+ ['duplicate id', entry(A2, 'A1 — Again')],
+ ['an id that is not A<n>', entry(A2, 'Assumption 2')],
+ ['A0', entry(A2, 'A0 — Zero')],
+ ['unknown resolution', entry(A2.replace('planner-default', 'assumed'))],
+ ['user-confirmed without Question/Answer', entry(A2.replace('planner-default', 'user-confirmed'))],
+ ['evidence without a prefix', entry(A2.replace('default: this page', 'this page'))],
+ ['evidence with an empty prefix', entry(A2.replace('default: this page loads on mount, so Critical Rule 15 applies.', 'default:'))],
+ ['an unknown field', entry(`${A2}\n- Owner: the planner`)],
+ ['a duplicate field', entry(`${A2}\n- Decision: something else`)],
+ ['a prose line', entry(`${A2}\nThis line is not a field.`)],
+ ['a nested heading', entry(`${A2}\n#### Notes`)],
+ ['a planner-default that names a question', entry(`${A2}\n- Question: opportunities-account-scope\n- Answer: Direct`)],
+ ['a Default record on a planner-default', entry(`${A2}\n- Default record: Unattended default: A2 / x → y (z)`)],
+ ['text before the first entry', written({ assumptions: `Some intro.\n\n### A1 — Opportunity relationship\n${A1}` })],
+ ]) {
+ assert.ok(codes(semantics.readWrittenSemantics(plan).problems).includes('invalid-assumptions'), label);
+ }
+ const twice = written().replace('## Working Directory', `## Assumptions\n\nNo assumptions.\n\n## Working Directory`);
+ assert.ok(semantics.readWrittenSemantics(twice).problems.some((p) => p.code === 'invalid-assumptions' && /more than one/.test(p.message)));
+});
+
+test('values may continue on indented lines and compare after NFC and whitespace normalization only', () => {
+ const wrapped = A2.replace('- Decision: De-duplicate and cache the initial list read.', '- Decision: De-duplicate and cache\n the initial list read.');
+ const w = semantics.readWrittenSemantics(written({ assumptions: `### A1 — Opportunity relationship\n${A1}\n\n### A2 — Initial-load caching\n${wrapped}` }).replace(/\n/g, '\r\n'));
+ assert.deepEqual(w.problems, []);
+ assert.equal(w.assumptions.entries.get('A2').decision, 'De-duplicate and cache the initial list read.');
+ assert.deepEqual(semantics.compareSemantics(semantics.readPreviewSemantics(preview()), w), []);
+ // Case is substantive.
+ const shouted = semantics.readWrittenSemantics(written({ assumptions: `### A1 — Opportunity relationship\n${A1}\n\n### A2 — Initial-load caching\n${A2.replace('cache the initial', 'CACHE the initial')}` }));
+ assert.deepEqual(semantics.compareSemantics(semantics.readPreviewSemantics(preview()), shouted), ['Assumptions: A2 changed its Decision']);
+ // A blank line ends a value: an indented line after it continues nothing.
+ const detached = A2.replace('- Resolution: planner-default', '- Resolution: planner-default\n\n stray continuation');
+ assert.ok(codes(semantics.readWrittenSemantics(written({ assumptions: `### A1 — Opportunity relationship\n${A1}\n\n### A2 — Initial-load caching\n${detached}` })).problems).includes('invalid-assumptions'));
+});
+
+test('an unattended default records the exact line, and its reason never says approved', () => {
+ const unattended = (record, answer = 'Direct customer account only.') => written({ assumptions: `### A1 — Opportunity relationship\n${A1
+ .replace('user-confirmed', 'unattended-default').replace('Direct customer account only.', answer)}\n- Default record: ${record}` });
+ const ok = (plan) => semantics.readWrittenSemantics(plan).problems;
+ assert.deepEqual(ok(unattended('Unattended default: A1 / opportunities-account-scope → Direct customer account only. (the request excludes contact roll-up and metadata leaves one matching path)')), []);
+ assert.deepEqual(ok(unattended('Unattended default: A1 / opportunities-account-scope -> Direct customer account only. (historical arrow)')), []);
+ // A legitimate answer that is the word Approved is kept; only the reason may not use it.
+ assert.deepEqual(ok(unattended('Unattended default: A1 / opportunities-account-scope → Approved (the only status value the request names)', 'Approved')), []);
+ for (const [label, record] of [
+ ['a reason that says approved', 'Unattended default: A1 / opportunities-account-scope → Direct customer account only. (matches the approved plan)'],
+ ['another assumption id', 'Unattended default: A2 / opportunities-account-scope → Direct customer account only. (reason)'],
+ ['another question', 'Unattended default: A1 / other-question → Direct customer account only. (reason)'],
+ ['another answer', 'Unattended default: A1 / opportunities-account-scope → Parent account (reason)'],
+ ['no reason', 'Unattended default: A1 / opportunities-account-scope → Direct customer account only.'],
+ ['an empty reason', 'Unattended default: A1 / opportunities-account-scope → Direct customer account only. ( )'],
+ ['the plan-approval line', 'Unattended default: plan approval → approved (unattended mode)'],
+ ]) {
+ assert.ok(codes(ok(unattended(record))).includes('invalid-assumptions'), label);
+ }
+ const missing = written({ assumptions: `### A1 — Opportunity relationship\n${A1.replace('user-confirmed', 'unattended-default')}` });
+ assert.ok(semantics.readWrittenSemantics(missing).problems.some((p) => /needs its Default record/.test(p.message)));
+});
+
+test('decision sources resolve: an assumption that exists, or a quote found in the original requirements', () => {
+ const read = (decisions, assumptions) => semantics.readWrittenSemantics(written({ decisions, ...(assumptions === undefined ? {} : { assumptions }) })).problems;
+ assert.deepEqual(codes(read(DECISIONS.replace('- Source: A1\n\n##### F1', '- Source: A99\n\n##### F1'))), ['unknown-assumption']);
+ assert.deepEqual(codes(read(DECISIONS, null)), ['unknown-assumption', 'unknown-assumption'], 'no Assumptions section: A1 resolves to nothing');
+ assert.deepEqual(codes(read(DECISIONS.replace('- Source: A1\n\n##### F1', '\n##### F1'))), ['missing-semantic-source']);
+ assert.deepEqual(codes(read(DECISIONS.replace('- Source: A1\n\n##### F1', '- Source: A1, User Requirements\n\n##### F1'))), ['missing-semantic-source']);
+ assert.deepEqual(codes(read(DECISIONS.replace('\n- Requirement quote: search customer names by substring', ''))), ['unmatched-requirement-quote']);
+ assert.deepEqual(codes(read(DECISIONS.replace('search customer names by substring', 'search all records'))), ['unmatched-requirement-quote']);
+ assert.deepEqual(codes(read(DECISIONS.replace('search customer names by substring', 'Search customer names by substring'))), ['unmatched-requirement-quote'], 'case is kept');
+ assert.deepEqual(read(DECISIONS.replace('search customer names by substring', '"search customer names\n by substring"')), [], 'quotes and whitespace are not substantive');
+ for (const [label, decisions] of [
+ ['Kind that does not match the id', DECISIONS.replace('- Kind: relationship', '- Kind: filter')],
+ ['a level-three id', DECISIONS.replace('##### R1', '### R1')],
+ ['a duplicate id', `${DECISIONS}\n\n##### F2\n- Kind: filter\n- Definition: x\n- Source: A1`],
+ ['an id that is not R/F', DECISIONS.replace('##### R1', '##### X1')],
+ ['missing Definition', DECISIONS.replace(/- Definition: opportunity\.customerid.*\n/, '')],
+ ['an unknown field', DECISIONS.replace('- Source: A1\n\n##### F1', '- Source: A1\n- Scope: all\n\n##### F1')],
+ ]) {
+ assert.ok(codes(semantics.readWrittenSemantics(written({ decisions })).problems).includes('invalid-data-semantics'), label);
+ }
+});
+
+test('lookup records: names, the complete target set, Used by, state, paths and their bullets', () => {
+ const read = (lookups) => codes(semantics.readWrittenSemantics(written({ lookups })).problems);
+ for (const [label, lookups] of [
+ ['a wrong read property', LOOKUPS.replace('| _customerid_value |', '| customerid |')],
+ ['no targets', LOOKUPS.replace('| account, contact |', '| |')],
+ ['a target twice', LOOKUPS.replace('| account, contact |', '| account, account |')],
+ ['a plural or display target', LOOKUPS.replace('| account, contact |', '| Accounts, contact |')],
+ ['Used by a decision the page does not define', LOOKUPS.replace('R1, F1, F2;', 'R1, F9;')],
+ ['no Used by', LOOKUPS.replace('| R1, F1, F2; customer navigation; customer picker |', '| |')],
+ ['an unknown state', LOOKUPS.replace('| observed |', '| guessed |')],
+ ['a planned lookup with a path', LOOKUPS.replace('| observed |', '| planned |')],
+ ['a path to a target the lookup does not list', LOOKUPS.replace('| opportunity | customerid | contact | customerid_contact | contactid |', '| opportunity | customerid | lead | customerid_lead | leadid |')],
+ ['a path for an unlisted lookup', LOOKUPS.replace('| opportunity | customerid | contact | customerid_contact | contactid |', '| opportunity | parentaccountid | account | parentaccountid | accountid |')],
+ ['a duplicate lookup row', LOOKUPS.replace('|-------|--------|---------------|---------|---------|----------------|', '|-------|--------|---------------|---------|---------|----------------|\n| opportunity | customerid | _customerid_value | account, contact | R1 | observed |')],
+ ['a table with a File column', `${LOOKUPS}\n\n| Page | File |\n|---|---|\n| X | x.tsx |`],
+ ['no Evidence bullet', LOOKUPS.replace(/- Evidence: .*\n/, '')],
+ ['no strategy bullet', LOOKUPS.replace(/\n- Read target strategy: .*/, '')],
+ ['a prose line', `${LOOKUPS}\nThe lookup is polymorphic.`],
+ ['an empty table', LOOKUPS.split('\n').slice(0, 2).join('\n')],
+ ]) {
+ assert.ok(read(lookups).includes('invalid-lookup-metadata'), label);
+ }
+ const planned = LOOKUPS.replace('| observed |', '| planned |').split('\n').filter((line) => !/customerid_(account|contact)|Navigation property|---------------------/.test(line)).join('\n');
+ assert.deepEqual(read(planned), [], 'a planned lookup without paths is valid');
+});
+
+test('the preview presents Assumptions first, and Data Semantics and Lookup Metadata after its Pages table', () => {
+ assert.ok(codes(semantics.readPreviewSemantics(preview({ order: 'assumptions-late' })).problems).includes('invalid-assumptions'));
+ assert.ok(codes(semantics.readPreviewSemantics(preview({ order: 'semantics-early' })).problems).includes('invalid-data-semantics'));
+ // A preview written at the plan's levels is not the preview's contract: nothing of it is read.
+ const levels = preview().replace('### Assumptions', '## Assumptions').replace(/^#### A/gm, '### A');
+ assert.equal(semantics.readPreviewSemantics(levels).assumptions, null);
+ // A written plan's per-page subsections are not the preview's groups.
+ const ungrouped = preview().replace('### Data Semantics\n\n#### customer-lookup.tsx\n\n', '### Data Semantics\n\n');
+ assert.ok(codes(semantics.readPreviewSemantics(ungrouped).problems).includes('invalid-data-semantics'));
+});
+
+test('the comparison refuses an added, omitted or changed assumption, decision or lookup record', () => {
+ const approved = semantics.readPreviewSemantics(preview());
+ const diff = (plan, options) => semantics.compareSemantics(approved, semantics.readWrittenSemantics(plan), options);
+ assert.deepEqual(diff(written({ assumptions: `### A1 — Opportunity relationship\n${A1.replace('Use opportunity.customerid', 'Use opportunity.parentaccountid')}\n\n### A2 — Initial-load caching\n${A2}` })), ['Assumptions: A1 changed its Decision']);
+ assert.deepEqual(diff(written({ assumptions: `### A1 — Opportunity relationship\n${A1}` })), ['Assumptions: A2 was approved but is not written']);
+ assert.deepEqual(diff(written({ assumptions: `### A1 — Opportunity relationship\n${A1}\n\n### A2 — Initial-load caching\n${A2}\n\n### A3 — Sort\n${A2}` })), ['Assumptions: A3 is written but was not approved']);
+ assert.deepEqual(diff(written({ assumptions: 'No assumptions.', decisions: DECISIONS.replace(/- Source: A1/g, '- Source: User Requirements\n- Requirement quote: open and change customers') })).slice(0, 1), ['Assumptions: approved recorded, written "No assumptions."']);
+ assert.deepEqual(diff(written({ decisions: DECISIONS.replace('through the verified Customer-to-account navigation path', 'through parentaccountid') })), ['customer-lookup.tsx Data semantics: F1 changed its Definition']);
+ assert.deepEqual(diff(written({ lookups: LOOKUPS.replace('| account, contact |', '| account |').replace(/\| opportunity \| customerid \| contact .*\n/, '') })), [
+ 'customer-lookup.tsx Lookup metadata: opportunity.customerid changed its Targets',
+ 'customer-lookup.tsx Lookup metadata: the paths of opportunity.customerid changed',
+ ]);
+ assert.deepEqual(diff(written({ lookups: LOOKUPS.replace('customerid_contact', 'customerid_lead') })), ['customer-lookup.tsx Lookup metadata: the paths of opportunity.customerid changed']);
+ assert.deepEqual(diff(written({ decisions: null, lookups: null })), [
+ 'customer-lookup.tsx Data semantics: approved recorded, written not recorded',
+ 'customer-lookup.tsx Lookup metadata: approved recorded, written not recorded',
+ ]);
+});
+
+test('reconciliation may promote a planned lookup to observed with its measured paths — only with evidence, and nothing else', () => {
+ const plannedLookups = LOOKUPS.replace('| observed |', '| planned |').split('\n')
+ .filter((line) => !/customerid_(account|contact)|Navigation property|---------------------/.test(line)).join('\n');
+ const approved = semantics.readPreviewSemantics(preview({ lookups: plannedLookups }));
+ const promoted = semantics.readWrittenSemantics(written());
+ assert.deepEqual(semantics.compareSemantics(approved, promoted, { promotions: true }), []);
+ assert.deepEqual(semantics.compareSemantics(approved, promoted), [
+ 'customer-lookup.tsx Lookup metadata: opportunity.customerid was approved planned and is written observed without successful lookup metadata evidence',
+ 'customer-lookup.tsx Lookup metadata: the paths of opportunity.customerid changed',
+ ]);
+ const narrowed = semantics.readWrittenSemantics(written({ lookups: LOOKUPS.replace('| account, contact |', '| account |').replace(/\| opportunity \| customerid \| contact .*\n/, '') }));
+ assert.deepEqual(semantics.compareSemantics(approved, narrowed, { promotions: true }), ['customer-lookup.tsx Lookup metadata: opportunity.customerid changed its Targets']);
+ const demoted = semantics.readWrittenSemantics(written({ lookups: plannedLookups }));
+ assert.deepEqual(semantics.compareSemantics(semantics.readPreviewSemantics(preview()), demoted, { promotions: true }), [
+ 'customer-lookup.tsx Lookup metadata: opportunity.customerid was approved observed and is written planned',
+ 'customer-lookup.tsx Lookup metadata: the paths of opportunity.customerid changed',
+ ]);
+});
+
+test('observed lookups must match successful get-lookup-metadata.js evidence exactly', () => {
+ const w = semantics.readWrittenSemantics(written());
+ assert.deepEqual(semantics.lookupEvidenceProblems(w, EVIDENCE), []);
+ const evidence = (change) => { const copy = structuredClone(EVIDENCE); change(copy.tables[0].lookups[0], copy); return copy; };
+ for (const [label, bad] of [
+ ['a failed read', { ok: false, code: 'X', error: 'failed' }],
+ ['no answer', null],
+ ['a target set the plan narrows', evidence((lookup) => { lookup.targets.push('lead'); })],
+ ['another read property', evidence((lookup) => { lookup.readProperty = '_parentcustomerid_value'; })],
+ ['a path the evidence does not hold', evidence((lookup) => { lookup.paths.pop(); })],
+ ['another key', evidence((lookup) => { lookup.paths[0].referencedKey = 'leadid'; })],
+ ['no such lookup', evidence((lookup) => { lookup.column = 'parentaccountid'; })],
+ ['no such table', evidence((lookup, copy) => { copy.tables[0].logicalName = 'quote'; })],
+ ]) {
+ const found = semantics.lookupEvidenceProblems(w, bad);
+ assert.ok(found.length && found.every((p) => p.code === 'invalid-lookup-metadata'), label);
+ }
+ // A shared path (Owner's ownerid) never stands in for a concrete one.
+ const shared = evidence((lookup) => { lookup.sharedPaths = [{ navigationProperty: 'customerid_contact', targets: ['account', 'contact'] }]; lookup.paths.pop(); });
+ assert.equal(semantics.lookupEvidenceProblems(w, shared).length, 1);
+});
+
+test('a newly authored plan must carry every part; an older one is not asked to', () => {
+ const plan = written({ assumptions: null, decisions: null, lookups: null });
+ assert.deepEqual(semantics.writtenSemanticsProblems(plan), []);
+ assert.deepEqual(codes(semantics.writtenSemanticsProblems(plan, { require: true })), ['invalid-assumptions', 'invalid-data-semantics', 'invalid-lookup-metadata']);
+ assert.deepEqual(semantics.writtenSemanticsProblems(written({ assumptions: 'No assumptions.', decisions: 'None.', lookups: 'None.' }), { require: true }), []);
+ assert.deepEqual(semantics.writtenSemanticsProblems(written(), { require: true }), []);
+});
diff --git a/plugins/model-apps/scripts/tests/genpage-sdk-real-bundle.test.js b/plugins/model-apps/scripts/tests/genpage-sdk-real-bundle.test.js
index ddf83e5f2..e46d26c4b 100644
--- a/plugins/model-apps/scripts/tests/genpage-sdk-real-bundle.test.js
+++ b/plugins/model-apps/scripts/tests/genpage-sdk-real-bundle.test.js
@@ -4,6 +4,9 @@
// SDK itself accepts what the backend sends, the rows it writes are the ones a page is made of, an untouched push writes nothing, an
// update writes only the rows that changed, a page that does not compile writes nothing, and a lost response on the one atomic
// change set leaves exactly the two states the backend's settling logic assumes — landed, or nothing.
+// This file checks where lib/temp-workspace.js makes a workspace, so it works in a temp folder of its own (helpers/own-temp-folder.js): in the
+// suite's shared one, other test processes make and remove the plugin's workspace folder. Required first, so every path below is inside it.
+require('./helpers/own-temp-folder.js');
const { test } = require('node:test');
const assert = require('node:assert');
const fs = require('node:fs');
diff --git a/plugins/model-apps/scripts/tests/genpage-sdk-verbs.test.js b/plugins/model-apps/scripts/tests/genpage-sdk-verbs.test.js
index 3b2972489..1f00eefde 100644
--- a/plugins/model-apps/scripts/tests/genpage-sdk-verbs.test.js
+++ b/plugins/model-apps/scripts/tests/genpage-sdk-verbs.test.js
@@ -835,3 +835,49 @@ test('discardWorkspaces: each of the new operations is waited for while it runs
assert.strictEqual(discarded, true, name);
}
});
+
+// ── solutionTarget / addToSolution: the solution a page joins (genpage-upload.js --solution) ─────────────────────────────────────────────
+// A page joins no solution on its own and the add of an app never brings it, so a page is added explicitly (lib/page-solution.js): the solution is read before the
+// page is written, as is the page table's component type, which the environment allocates; the add brings the page's file rows with it.
+
+const solutionSdk = ({ solutions = [{ solutionid: '55555555-0000-4000-8000-000000000055', uniquename: 'ContosoCore', ismanaged: false }], typeAnswer = { status: 200, body: { ObjectTypeCode: 10372 } } } = {}) => {
+ const sdk = new FakeSdk({
+ records: { solution: (options) => solutions.filter((s) => (options.filter || '').toLowerCase().includes(`'${s.uniquename.toLowerCase()}'`)) },
+ onGet: async (url) => (url === "/EntityDefinitions(LogicalName='uxagentproject')?$select=ObjectTypeCode" ? typeAnswer : { status: 404, body: null }),
+ });
+ sdk.addSolutionComponent = async (options) => { sdk.calls.push({ name: 'addSolutionComponent', args: [options] }); };
+ return sdk;
+};
+
+test('solutionTarget reads the unmanaged solution and the page table\u2019s component type, before anything is written; a system solution is answered from its name, with nothing read', async () => {
+ const sdk = solutionSdk({ typeAnswer: { status: 200, body: { ObjectTypeCode: 10380 } } });
+ const genpage = backend(sdk);
+ assert.deepStrictEqual(await genpage.solutionTarget(' contosocore '), { uniqueName: 'ContosoCore', systemSolution: false, componentType: 10380 });
+ assert.deepStrictEqual(sdk.calls.map((c) => c.name), ['queryRecords', 'dataverse.get']);
+ assert.strictEqual(sdk.calls[0].args[1].filter, "uniquename eq 'contosocore'");
+ const system = solutionSdk();
+ assert.deepStrictEqual(await backend(system).solutionTarget('Default'), { uniqueName: 'Default', systemSolution: true });
+ assert.deepStrictEqual(system.calls, [], 'a system solution is not read');
+});
+
+test('solutionTarget refuses a missing or managed solution, and a page table whose type the environment cannot say — each with its code', async () => {
+ await assert.rejects(backend(solutionSdk()).solutionTarget('Missing'), (e) => e.code === 'SOLUTION_NOT_FOUND' && /There is no solution with the unique name 'Missing'/.test(e.message));
+ await assert.rejects(backend(solutionSdk({ solutions: [{ uniquename: 'Managed', ismanaged: true }] })).solutionTarget('Managed'), (e) => e.code === 'SOLUTION_MANAGED');
+ await assert.rejects(backend(solutionSdk({ typeAnswer: { status: 503, body: { error: { message: 'busy' } } } })).solutionTarget('ContosoCore'),
+ (e) => e.code === 'GENPAGE_COMPONENT_TYPE_UNRESOLVED' && /could not be read \(HTTP 503: busy\)/.test(e.message));
+ await assert.rejects(backend(solutionSdk({ typeAnswer: { status: 200, body: { ObjectTypeCode: null } } })).solutionTarget('ContosoCore'),
+ (e) => e.code === 'GENPAGE_COMPONENT_TYPE_UNRESOLVED' && /did not return a valid ObjectTypeCode/.test(e.message));
+});
+
+test('addToSolution adds the page as the page table\u2019s type with its required components (its file rows); a system solution is not added to', async () => {
+ const sdk = solutionSdk();
+ const genpage = backend(sdk);
+ const target = await genpage.solutionTarget('ContosoCore');
+ assert.deepStrictEqual(await genpage.addToSolution(P1.toUpperCase(), target), { added: true });
+ assert.deepStrictEqual(sdk.of('addSolutionComponent').map((c) => c.args[0]), [{ componentId: P1, componentType: 10372, solutionUniqueName: 'ContosoCore', addRequiredComponents: true }]);
+ assert.deepStrictEqual(await genpage.addToSolution(P2, { uniqueName: 'Default', systemSolution: true }), { added: false });
+ assert.strictEqual(sdk.count('addSolutionComponent'), 1);
+ await assert.rejects(genpage.addToSolution('not-a-page', target), (e) => e.code === 'GENPAGE_ID_INVALID');
+ await assert.rejects(genpage.addToSolution(P2, { uniqueName: 'ContosoCore', systemSolution: false }), (e) => e.code === 'GENPAGE_COMPONENT_TYPE_UNRESOLVED');
+ assert.strictEqual(sdk.count('addSolutionComponent'), 1, 'nothing is sent without a page id and a component type');
+});
\ No newline at end of file
diff --git a/plugins/model-apps/scripts/tests/genpage-styling-docs.test.js b/plugins/model-apps/scripts/tests/genpage-styling-docs.test.js
new file mode 100644
index 000000000..55f2d1591
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/genpage-styling-docs.test.js
@@ -0,0 +1,78 @@
+'use strict';
+// A look of the maker's own wins over the default model-driven look (AB#6320143). The skills used to turn every request for a style — a screenshot to follow, a website
+// to match, a description — into the default model-driven styling: the rules said "tokens", the plan's Styling line was free prose the page-builder read as a wish, and
+// nothing said a maker's look replaces the defaults. These tests hold the chain to one contract: the planner writes the look as a `Styling:` line that starts with
+// `Maker-requested:` and gives concrete values, the plan schema defines that line, the page-builder applies it before the defaults, the edit planner does the same for a
+// restyle, and references/rules.md says how to apply it within what a page can do — and says plainly what it cannot match.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+
+const PLUGIN = path.join(__dirname, '..', '..');
+const read = (...parts) => fs.readFileSync(path.join(PLUGIN, ...parts), 'utf8').replace(/\r\n/g, '\n');
+const flat = (text) => text.replace(/\s+/g, ' ');
+const RULES = read('references', 'rules.md');
+const HEADING = '### Maker-requested styling';
+
+function section(text, heading) {
+ const at = text.indexOf(heading);
+ assert.ok(at >= 0, `the text has ${heading}`);
+ const rest = text.slice(at + heading.length);
+ return rest.slice(0, rest.search(/\n#{2,3} /));
+}
+
+test('rules.md: a Maker-requested style wins over the default look, and Rule 7 and the design principles say tokens are only the default', () => {
+ const styling = RULES.slice(RULES.indexOf('## Layout and Styling'), RULES.indexOf('## Accessibility'));
+ assert.ok(styling.includes(HEADING), 'the subsection is in Layout and Styling');
+ const text = flat(section(RULES, HEADING));
+ assert.match(text, /When the maker asks for a look of their own, that style wins over the default model-driven look\./);
+ assert.match(text, /a `Styling:` line that starts with `Maker-requested:` and gives concrete values\. Apply each value\. Do not fall back to the default tokens for a value that the style sets:/);
+ assert.match(text, /\*\*Colors\.\*\* Build a theme from the stated colors over `webLightTheme`/);
+ assert.match(text, /Apply it with the `themeToVars` two-div wrapper/);
+ assert.match(text, /\*\*Typography\.\*\* Set `fontFamily` on the page root to the stated font, with fallbacks/);
+ assert.match(text, /\*\*What the style does not set\*\* keeps the default tokens/);
+ assert.match(text, /\*\*No style asked for:\*\* keep the model-driven defaults/);
+ const rule7 = /\n7\. \*\*Styling\*\*: ([^\n]+)/.exec(RULES)[1];
+ assert.match(rule7, /Tokens give the default model-driven look\. When the plan's `## Design Preferences` → `Styling:` starts with `Maker-requested:`, apply that style instead/);
+ assert.match(RULES, /- Use theme tokens \(e\.g\., `tokens\.spacingVerticalXL`, `tokens\.colorNeutralBackground1`\) — the default look when the maker asked for no style of their own/);
+});
+
+test('rules.md says plainly what a page cannot match', () => {
+ const text = flat(section(RULES, HEADING));
+ assert.match(text, /\*\*What cannot be matched\.\*\* Tell the maker when the request needs one of these:/);
+ assert.match(text, /It cannot load a stylesheet, a CSS file, a web font, an image or a script from another site, and it cannot use another component library\./);
+ assert.match(text, /A font that is not installed on the user's device shows its fallback\./);
+ assert.match(text, /Only the page's own area gets the style\. The app header, the navigation and the command bar around the page keep the look of the app\./);
+ assert.match(text, /A screenshot is matched by eye\./);
+ assert.match(text, /Contrast stays at WCAG AA\./);
+});
+
+test('the example in rules.md keeps to the page rules: a theme over webLightTheme through themeToVars, with no FluentProvider, createTheme or external asset', () => {
+ const block = /```typescript\n([\s\S]*?)```/.exec(section(RULES, HEADING));
+ assert.ok(block, 'the subsection has an example');
+ const code = block[1];
+ assert.match(code, /import \{ webLightTheme \} from "@fluentui\/react-components";/);
+ assert.match(code, /\.\.\.webLightTheme,/);
+ assert.match(code, /themeToVars\(brandTheme\)/);
+ assert.doesNotMatch(code, /FluentProvider|createTheme|mergeThemes|useTheme|@import|https?:\/\/|url\(/);
+});
+
+test('the plan schema defines the Maker-requested Styling line, and the defaults when no look is asked for', () => {
+ const schema = flat(read('references', 'plan-schema.md'));
+ assert.match(schema, /- Styling: \[EITHER `Maker-requested: <the look as concrete values — each color as a hex value with its role \(primary, accent, background, text\)/);
+ assert.match(schema, /OR the model-driven defaults \(`Fluent UI V9 defaults`, plus any preference that does not replace that look\) when they did not\]/);
+ assert.match(schema, /\| `## Design Preferences` \| Page-builder \| Prose, free-form; a `Styling:` line that starts with `Maker-requested:` wins over the default look/);
+});
+
+test('the planner turns a requested look into concrete values, the page-builder applies it before the defaults, and the edit planner does the same for a restyle', () => {
+ const planner = flat(read('agents', 'genpage-planner.md'));
+ assert.match(planner, /\*\*A look of the maker's own wins over the default model-driven look\.\*\*/);
+ assert.match(planner, /write them in the plan's `## Design Preferences` as a `Styling:` line that starts with `Maker-requested:`\. Give each color as a hex value with its role/);
+ assert.match(planner, /If you cannot open a website, ask the maker for a screenshot or for its colors and fonts\. Do not assume them\./);
+ const builder = flat(read('agents', 'genpage-page-builder.md'));
+ assert.match(builder, /A `Styling:` line that starts with `Maker-requested:` is the maker's own look, and it wins over the default model-driven styling\. Apply every value it gives/);
+ assert.match(builder, /\*\*makeStyles with tokens\*\* — no inline styles for static values\. Tokens are the default look: a `Maker-requested:` style in the plan's Design Preferences replaces them for the values it sets/);
+ const editPlanner = flat(read('agents', 'genpage-edit-planner.md'));
+ assert.match(editPlanner, /When the maker asks to restyle the page — a screenshot, a website to match, a description — write the style as a line that starts with `Maker-requested:`/);
+});
diff --git a/plugins/model-apps/scripts/tests/genpage-upload.test.js b/plugins/model-apps/scripts/tests/genpage-upload.test.js
index 01a22ddc5..6dc673e61 100644
--- a/plugins/model-apps/scripts/tests/genpage-upload.test.js
+++ b/plugins/model-apps/scripts/tests/genpage-upload.test.js
@@ -962,6 +962,75 @@ test('a create that could not be placed leaves the page unfinished too — and t
assert.strictEqual(readMarker(file).unfinished, undefined);
});
+// ── --solution: the page joins the solution the run was given (AB#6443257) ──────────────────────────────────────────────────────────────
+// A page made through the SDK joins no solution on its own, and the add of an app brings its sitemap, never the pages its navigation opens: a run given a
+// solution left every page it made out of it. The solution is read before anything is written, and the page joins it last — once it is written, published and placed.
+
+test('a create with --solution adds the page to that solution last — after it is written, published and placed — and says so', async () => {
+ const genpage = environment();
+ const r = await run(createArgs(codeFile(), [...NAMED, '--add-to-sitemap', '--solution', 'contosocore']), genpage);
+ assert.strictEqual(r.ok, true, JSON.stringify(r.payload));
+ assert.deepStrictEqual(genpage.inSolution, [{ pageId: NEW_ID, solution: 'ContosoCore', componentType: 10372 }]);
+ assert.deepStrictEqual([r.payload.solution, r.payload.addedToSolution, 'systemSolution' in r.payload], ['ContosoCore', true, false]);
+ const order = genpage.calls.map((c) => c.method).filter((m) => ['solutionTarget', 'create', 'placeInApp', 'addToSolution'].includes(m));
+ assert.deepStrictEqual(order, ['solutionTarget', 'create', 'placeInApp', 'addToSolution'], 'read first, joined last');
+ assert.deepStrictEqual(only(genpage, 'solutionTarget'), ['contosocore']);
+});
+
+test('a solution that is not there, or is managed, refuses the upload before anything is written — the page is not made outside it', async () => {
+ for (const [solutions, code] of [[{ ContosoCore: {} }, 'SOLUTION_NOT_FOUND'], [{ Missing: { managed: true } }, 'SOLUTION_MANAGED']]) {
+ const genpage = environment({ solutions });
+ const r = await run(createArgs(codeFile(), [...NAMED, '--add-to-sitemap', '--solution', 'Missing']), genpage);
+ assert.strictEqual(r.ok, false, code);
+ assert.strictEqual(r.payload.code, code);
+ assert.match(r.payload.error, /^nothing was written: the solution "Missing" the page is to join cannot be used — /);
+ assert.deepStrictEqual(genpage.calls.map((c) => c.method), ['solutionTarget'], `${code}: nothing else was asked of the environment`);
+ assert.strictEqual(r.disposedAtEmit, 1);
+ }
+});
+
+test('a system solution holds every page already: the page is not added to it, and the result says why', async () => {
+ const genpage = environment();
+ const r = await run(createArgs(codeFile(), [...NAMED, '--add-to-sitemap', '--solution', 'Default']), genpage);
+ assert.strictEqual(r.ok, true, JSON.stringify(r.payload));
+ assert.deepStrictEqual([r.payload.solution, r.payload.addedToSolution, r.payload.systemSolution], ['Default', false, true]);
+ assert.deepStrictEqual(genpage.inSolution, []);
+});
+
+test('an add that fails once the page is made is a failure that carries the page\u2019s id and the command that adds it — never a second create', async () => {
+ const genpage = environment({ solutionAdd: () => { throw Object.assign(new Error('HTTP 503: the service is busy'), { code: 'CONNECTION_ERROR' }); } });
+ const r = await run(createArgs(codeFile(), [...NAMED, '--add-to-sitemap', '--solution', 'ContosoCore']), genpage);
+ assert.strictEqual(r.ok, false);
+ assert.deepStrictEqual([r.payload.code, r.payload.pageId, r.payload.appId, r.payload.solution, r.payload.addedToSolution], ['solution-add-failed', NEW_ID, APP, 'ContosoCore', false]);
+ assert.match(r.payload.error, new RegExp(`^page ${NEW_ID} was created and published and placed in app ${APP}'s navigation, but it was NOT added to solution ContosoCore: HTTP 503: the service is busy\\. `));
+ assert.match(r.payload.error, new RegExp(`Do not create it again: add it with node scripts/add-page-to-solution\\.js ${ENV.replace(/[.]/g, '\\.')} ContosoCore --page-ids ${NEW_ID} `));
+ assert.strictEqual(genpage.of('create').length, 1);
+ assert.strictEqual(genpage.of('placeInApp').length, 1, 'the page was placed before the add was tried');
+});
+
+test('a create that did not finish has not joined the solution yet — the same command again, with --page-id, finishes it and then joins it', async () => {
+ const file = codeFile();
+ let publishFails = true;
+ const genpage = environment({ pages: [], onCreate: () => (publishFails ? { publish: { kind: 'failed', detail: 'another publish is running' } } : undefined), onUpdate: () => undefined });
+ const args = ['--env', ENV, '--code-file', file, ...NAMED, '--solution', 'ContosoCore'];
+ const first = await run(args, genpage);
+ assert.strictEqual(first.ok, false);
+ assert.strictEqual(genpage.of('addToSolution').length, 0, 'a page that is not live is not added yet');
+ publishFails = false;
+ const second = await run([...args, ...adviceFor(first)], genpage);
+ assert.strictEqual(second.ok, true, JSON.stringify(second.payload));
+ assert.deepStrictEqual(genpage.inSolution, [{ pageId: NEW_ID, solution: 'ContosoCore', componentType: 10372 }]);
+ assert.strictEqual(genpage.of('create').length, 1);
+});
+
+test('an upload with no --solution asks nothing of any solution, as before', async () => {
+ const genpage = environment();
+ const r = await run(createArgs(codeFile(), [...NAMED, '--add-to-sitemap']), genpage);
+ assert.strictEqual(r.ok, true, JSON.stringify(r.payload));
+ assert.ok(!genpage.calls.some((c) => c.method === 'solutionTarget' || c.method === 'addToSolution'));
+ assert.ok(!('solution' in r.payload) && !('addedToSolution' in r.payload));
+});
+
// A placement can be SAVED and not published: the app's navigation holds the page, and the publish of the app failed. The run that completes it finds the page in the saved
// navigation, so a placement that only looks for what is missing has nothing to do — and used to answer "placed" while the app that runs did not show the page, and the marker
// stopped saying the page was unfinished. Completing a placement is publishing the app and seeing the page in what runs.
diff --git a/plugins/model-apps/scripts/tests/griffel-styles.test.js b/plugins/model-apps/scripts/tests/griffel-styles.test.js
index 395eae266..459c1efee 100644
--- a/plugins/model-apps/scripts/tests/griffel-styles.test.js
+++ b/plugins/model-apps/scripts/tests/griffel-styles.test.js
@@ -863,6 +863,38 @@ test('griffel-styles: a call whose style object is built elsewhere is reported,
assert.deepEqual(griffelStyleProblems(`${IMPORT}const s = makeStyles();\n`).problems, [], 'a call with no argument has nothing to read');
});
+// Known limit, pinned as it is (AGENTS.md, "A style object the check cannot see is a problem, never a pass"): a style object kept in a `const` is not read where it
+// is used — one at the top of the page, written once and used by the styles alone, included — so the call, the slot, the selector, the spread or the shorthand member
+// that names it is `unread-style-object`: a fail-closed refusal, kept on purpose. Reading the constant there would need the order in which the page's code runs, which
+// its text does not show (a call in a function declared below the constant runs when the page calls it, and the page is transpiled to `var`, so a call made before
+// the constant is initialized hands Griffel `undefined`), and every use read again (constants spread twice into the next double what is read at each step). The way
+// out is the one the message gives: write the style object in place.
+test('griffel-styles: known limit — a style object kept in a const is not read where it is used, a call in a hoisted function and constants spread into one another included', () => {
+ const cases = [
+ ['the call\'s argument', `${IMPORT}const styles = { root: { color: 'red' } };\nconst useStyles = makeStyles(styles);\n`, ['unread-style-object@3:19']],
+ ['a slot', `${IMPORT}const base = { color: 'red' };\nconst useStyles = makeStyles({ root: base });\n`, ['unread-style-object@3:32']],
+ ['a selector', `${IMPORT}const hover = { color: 'blue' };\nconst useStyles = makeStyles({ root: { ':hover': hover } });\n`, ['unread-style-object@3:40']],
+ ['a spread', `${IMPORT}const base = { color: 'red' };\nconst useStyles = makeStyles({ root: { ...base, padding: 0 } });\n`, ['unread-style-object@3:40']],
+ ['a shorthand slot after the declaration', `${IMPORT}const root = { color: 'red' };\nconst useStyles = makeStyles({ root });\n`, ['unread-style-object@3:32']],
+ ['a shorthand slot before the declaration', `${IMPORT}const useStyles = makeStyles({ root });\nconst root = { color: 'red' };\n`, ['unread-style-object@2:32']],
+ ['a call in a hoisted function that the page calls before the constant is initialized',
+ `${IMPORT}const useStyles = make();\nconst base = { color: 'red' };\nfunction make() { return makeStyles({ root: { ...base } }); }\n`, ['unread-style-object@4:47']],
+ // A key Griffel drops in such a constant is not named either: the object is unread, and the page is held all the same.
+ ['a constant that holds a key Griffel drops', `${IMPORT}const base = { borderWidth: '1px' };\nconst useStyles = makeStyles({ root: base });\n`, ['unread-style-object@3:32']],
+ ];
+ for (const [what, source, expected] of cases) assert.deepEqual(found(source), expected, what);
+ assert.deepEqual(found(`${IMPORT}const useStyles = makeStyles({ root: { color: 'red', ':hover': { color: 'blue' }, padding: 0 } });\n`), [], 'the style object written in place');
+ // Constants spread twice into the next: the slot that names the last one is reported at once, whatever their number, where a reading of every use read 2^n objects.
+ const chain = (n) => `${IMPORT}const c0 = { color: 'red' };\n${Array.from({ length: n }, (_, i) => `const c${i + 1} = { ...c${i}, ...c${i} };\n`).join('')}const useStyles = makeStyles({ root: c${n} });\n`;
+ for (const n of [20, 400]) {
+ const start = process.hrtime.bigint();
+ const problems = found(chain(n));
+ const ms = Number(process.hrtime.bigint() - start) / 1e6;
+ assert.deepEqual(problems, [`unread-style-object@${n + 3}:32`], `${n} constants spread twice into the next`);
+ assert.ok(ms < 1000, `${n} constants spread twice into the next took ${ms.toFixed(0)} ms`);
+ }
+});
+
test('griffel-styles: a call that never closes is reported, not skipped', () => {
for (const tail of ["makeStyles({ root: { borderWidth: 1 }", "makeStyles({ root: { borderWidth: 1 } }", 'makeStyles({ root: { color: "red" }, ']) {
const result = griffelStyleProblems(`${IMPORT}const useStyles = ${tail}\n`);
diff --git a/plugins/model-apps/scripts/tests/halt-retry-policy.test.js b/plugins/model-apps/scripts/tests/halt-retry-policy.test.js
index 80747a1dc..ae6e660e2 100644
--- a/plugins/model-apps/scripts/tests/halt-retry-policy.test.js
+++ b/plugins/model-apps/scripts/tests/halt-retry-policy.test.js
@@ -92,6 +92,9 @@ const POLICY = {
'pages-publish-failed': { kinds: ['by-failure'], via: PAGES },
'pages-dangling-navref': { kinds: ['never'], via: PAGES },
'pages-update-identity-mismatch': { kinds: ['never'], via: PAGES },
+ // The page table's component type, which a page needs to join the spec's solution (lib/page-solution.js), could not be read: raised before any page is written, and as transient as
+ // the read it wraps (a 503 is run again; a refusal, or an answer with no type in it, is the service's to say). Held failure by failure beside the page doubles.
+ 'pages-solution-type-unreadable': { kinds: ['by-failure'], via: PAGES },
// A connector binding whose connection reference in the environment written to is for another connector (lib/page-binding-targets.js): raised at preflight, before anything is
// written, and a run again reads the same reference. Held with the doubles of a target environment, under a page name that reads as a transient error.
'pages-binding-reference-conflict': { kinds: ['never'], via: 'page-bindings.test.js' },
diff --git a/plugins/model-apps/scripts/tests/helpers/fake-apps-org.js b/plugins/model-apps/scripts/tests/helpers/fake-apps-org.js
index b8233ef20..b8b5e1743 100644
--- a/plugins/model-apps/scripts/tests/helpers/fake-apps-org.js
+++ b/plugins/model-apps/scripts/tests/helpers/fake-apps-org.js
@@ -25,6 +25,7 @@
// saved edit, whose published row is still there
// sitemaps [{ sitemapid, sitemapnameunique, sitemapname, sitemapxml }]
// tables [{ logicalName, schemaName, displayName, isCustom, entitySetName }] the table definitions (`EntityDefinitions`)
+// pageType the page table's ObjectTypeCode, its solution component type (`options.pageType`, default 10372)
// components [{ solution, objectid, type }] what AddSolutionComponent was given
// publishes [appmoduleid] what PublishXml named
// appSettings [{ appsettingid, parentappmoduleid, settingdefinitionid, value, published }] the app settings the SDK wrote. A new row is in the
@@ -144,6 +145,7 @@ function createFakeAppsOrg(options = {}) {
components: [],
publishes: [],
views: options.views || [],
+ pageType: options.pageType === undefined ? 10372 : options.pageType,
};
// The page backend reads a page through its own tables (project, files, conversation), which this fake answers by handing those requests to a stateful page fake seeded from `pages`:
// every page has the four rows the maker lays out, holding its `dataSources` (none, by default) — unless it is `raw`, a project with no rows.
@@ -205,7 +207,17 @@ function createFakeAppsOrg(options = {}) {
})));
}
const entity = /^\/EntityDefinitions\(LogicalName='([^']+)'\)/.exec(where);
- if (entity) return json(200, { LogicalName: entity[1], MetadataId: randomUUID(), EntitySetName: ENTITY_SETS[entity[1]] || `${entity[1]}s` });
+ // A table's definition. The page table's carries its ObjectTypeCode — its solution component type, which the environment allocates (`options.pageType`;
+ // the value is an example): apps.js reads it to add an app's pages to the solution.
+ // GET /EntityDefinitions(LogicalName='uxagentproject')?$select=ObjectTypeCode -> { "ObjectTypeCode": 10372, "MetadataId": "…", … }
+ if (entity) {
+ return json(200, {
+ LogicalName: entity[1],
+ MetadataId: randomUUID(),
+ EntitySetName: ENTITY_SETS[entity[1]] || `${entity[1]}s`,
+ ...(entity[1] === 'uxagentproject' ? { ObjectTypeCode: state.pageType } : {}),
+ });
+ }
if (/^\/solutions\?/.test(where)) {
const name = equalsText(filter, 'uniquename');
return rows(state.solutions.filter((solution) => name === null || lc(solution.uniquename) === name));
diff --git a/plugins/model-apps/scripts/tests/helpers/fake-dataverse-operations-preload.js b/plugins/model-apps/scripts/tests/helpers/fake-dataverse-operations-preload.js
new file mode 100644
index 000000000..c8ddc7e5e
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/helpers/fake-dataverse-operations-preload.js
@@ -0,0 +1,107 @@
+'use strict';
+// Loaded with `node --require` ahead of scripts/list-dataverse-operations.js: makes lib/dataverse-operations.js answer the way a broken or a
+// widened catalogue would (FAKE_DV_OPERATIONS names how), so a test reads the listing's OWN check — exactly the reviewed pair, or nothing at all.
+// Everything else is the real module. A test requires nothing from this file; with FAKE_DV_OPERATIONS unset it changes nothing.
+const path = require('node:path');
+const Module = require('node:module');
+
+const mode = process.env.FAKE_DV_OPERATIONS;
+const target = path.resolve(__dirname, '..', '..', 'lib', 'dataverse-operations.js');
+
+if (mode === 'unloadable') {
+ // The module itself cannot be loaded (a damaged install): its require throws.
+ const load = Module._load;
+ Module._load = function unloadable(request, parent, isMain) {
+ let resolved = null;
+ try {
+ resolved = Module._resolveFilename(request, parent, isMain);
+ } catch {
+ // The real load reports it.
+ }
+ if (resolved && path.resolve(resolved) === target) throw new SyntaxError('Unexpected end of input');
+ return load.apply(this, arguments);
+ };
+} else if (mode) {
+ const real = require(target);
+ // structuredClone of the frozen catalogue is an ordinary copy the cases below may change.
+ const copy = () => structuredClone(real.getDataverseOperationCatalogue());
+ const catalogues = {
+ throws: () => { throw new Error('the catalogue could not be read'); },
+ missing: undefined,
+ widened: () => {
+ const catalogue = copy();
+ catalogue.operations.push({ ...structuredClone(catalogue.operations[0]), name: 'CalculateRollupField', displayName: 'Calculate rollup field' });
+ return catalogue;
+ },
+ reordered: () => {
+ const catalogue = copy();
+ catalogue.operations.reverse();
+ return catalogue;
+ },
+ renamed: () => {
+ const catalogue = copy();
+ catalogue.operations[0].name = 'whoami';
+ return catalogue;
+ },
+ action: () => {
+ const catalogue = copy();
+ catalogue.operations[0].isFunction = false;
+ return catalogue;
+ },
+ bound: () => {
+ const catalogue = copy();
+ catalogue.operations[1].bindingType = 'Entity';
+ return catalogue;
+ },
+ inputs: () => {
+ const catalogue = copy();
+ catalogue.operations[1].parameterKinds = { Target: 'String' };
+ return catalogue;
+ },
+ declared: () => {
+ const catalogue = copy();
+ catalogue.operations[1].parameters = [{ name: 'Target', type: 'Edm.String' }];
+ return catalogue;
+ },
+ 'on-load': () => {
+ const catalogue = copy();
+ catalogue.operations[0].invocation = 'on-load';
+ return catalogue;
+ },
+ unselected: () => {
+ const catalogue = copy();
+ catalogue.operations[0].requiresExplicitSelection = false;
+ return catalogue;
+ },
+ unverified: () => {
+ const catalogue = copy();
+ delete catalogue.verification;
+ return catalogue;
+ },
+ checked: () => {
+ const catalogue = copy();
+ catalogue.verification.environment = 'checked';
+ return catalogue;
+ },
+ revised: () => {
+ const catalogue = copy();
+ catalogue.catalogueVersion = 2;
+ return catalogue;
+ },
+ eligible: () => {
+ const catalogue = copy();
+ catalogue.operations[0].eligible = true;
+ return catalogue;
+ },
+ 'no-response': () => {
+ const catalogue = copy();
+ delete catalogue.operations[1].response;
+ return catalogue;
+ },
+ empty: () => ({ ...copy(), operations: [] }),
+ 'not-an-object': () => 'WhoAmI,RetrieveVersion',
+ };
+ if (!Object.prototype.hasOwnProperty.call(catalogues, mode)) throw new Error(`unknown FAKE_DV_OPERATIONS mode: ${mode}`);
+ // A script takes its helpers from the module cache when it requires the module, so it is handed this object.
+ require.cache[target].exports = { ...real, getDataverseOperationCatalogue: catalogues[mode] };
+}
diff --git a/plugins/model-apps/scripts/tests/helpers/fake-genpage.js b/plugins/model-apps/scripts/tests/helpers/fake-genpage.js
index dac310176..b820df910 100644
--- a/plugins/model-apps/scripts/tests/helpers/fake-genpage.js
+++ b/plugins/model-apps/scripts/tests/helpers/fake-genpage.js
@@ -25,6 +25,10 @@
// a `GENPAGE_DELETE_NOT_CONFIRMED` refusal that deletes nothing unless `options.allowDestructive` is exactly true
// types a string, or (dataSources, options) => string | throw: what `runtimeTypes` answers; default `// types of <tables>`
// language what `baseLanguage` answers (default 1033); `languageError`: an Error it throws instead
+// solutions the solutions the environment has, by unique name: { [name]: { managed } } (default ContosoCore, unmanaged). `solutionTarget` answers a system
+// solution (Default, Active, Basic) from its name, as the real backend does, refuses a missing or managed one with the real codes, and gives a
+// real one the page table's component type `pageType` (default 10372); `solutionTargetError`: an Error it throws instead
+// solutionAdd (pageId, target) => void | throw: what `addToSolution` does; default nothing. Every page it adds is in `backend.inSolution` ({ pageId, solution, componentType })
// left the folders `dispose` answers it could not remove, as the real backend's `{ left }` (default none)
// `describe` answers from `pages`: a page with `raw: true` is not editable and its tables are not known (`null`)
const DEFAULT_SOURCE = 'export default function Page() { return null; }\n';
@@ -60,6 +64,7 @@ function fakeGenpage(options = {}) {
of: (method) => calls.filter((c) => c.method === method),
disposed: 0,
disposeArgs: [],
+ inSolution: [],
async enumerateEnv() {
record('enumerateEnv', []);
@@ -147,6 +152,26 @@ function fakeGenpage(options = {}) {
return options.language === undefined ? 1033 : options.language;
},
+ async solutionTarget(uniqueName) {
+ record('solutionTarget', [uniqueName]);
+ if (options.solutionTargetError) throw options.solutionTargetError;
+ const name = String(uniqueName).trim();
+ if (['default', 'active', 'basic'].includes(name.toLowerCase())) return { uniqueName: name, systemSolution: true };
+ const solutions = options.solutions || { ContosoCore: {} };
+ const known = Object.keys(solutions).find((s) => s.toLowerCase() === name.toLowerCase());
+ if (!known) throw fail('SOLUTION_NOT_FOUND', `There is no solution with the unique name '${name}' in this environment.`);
+ if (solutions[known].managed) throw fail('SOLUTION_MANAGED', `The solution '${known}' is managed, and a managed solution takes no new components. Use an unmanaged solution.`);
+ return { uniqueName: known, systemSolution: false, componentType: options.pageType === undefined ? 10372 : options.pageType };
+ },
+
+ async addToSolution(pageId, target) {
+ record('addToSolution', [pageId, target]);
+ if (!target || target.systemSolution) return { added: false };
+ if (options.solutionAdd) await options.solutionAdd(pageId, target);
+ backend.inSolution.push({ pageId: String(pageId).toLowerCase(), solution: target.uniqueName, componentType: target.componentType });
+ return { added: true };
+ },
+
async removeFromApp(appId, pageId, opts) {
record('removeFromApp', [appId, pageId, opts]);
if (options.removal) return options.removal(appId, pageId, opts);
diff --git a/plugins/model-apps/scripts/tests/helpers/fake-lifecycle-org.js b/plugins/model-apps/scripts/tests/helpers/fake-lifecycle-org.js
index d617289b4..3a7dec35f 100644
--- a/plugins/model-apps/scripts/tests/helpers/fake-lifecycle-org.js
+++ b/plugins/model-apps/scripts/tests/helpers/fake-lifecycle-org.js
@@ -132,7 +132,7 @@ const RECORD_SCHEMA = {
sitemap: { fields: ['sitemapid', 'sitemapidunique', 'sitemapname', 'sitemapnameunique', 'sitemapxml', 'ismanaged', 'componentstate', ...AUDIT], nullable: [] },
webresource: { fields: ['webresourceid', 'name', 'displayname', 'webresourcetype', 'content', 'ismanaged', 'iscustomizable', 'canbedeleted', ...AUDIT], nullable: ['description'] },
workflow: { fields: ['workflowid', 'name', 'category', 'type', 'primaryentity', 'statecode', 'statuscode', 'ismanaged', ...AUDIT], nullable: ['description', 'uniquename', 'xaml', 'clientdata', 'businessprocesstype', 'processorder', 'mode', 'scope'] },
- appaction: { fields: ['appactionid', 'name', 'uniquename', 'context', 'contextvalue', 'location', 'type', 'ismanaged', 'statecode', 'statuscode', ...AUDIT], nullable: ['buttonlabeltext', 'sequence', 'onclickeventtype', 'onclickeventjavascriptfunctionname', 'onclickeventjavascriptparameters', 'grouptitle', 'isgrouptitlehidden', '_contextentity_value', '_parentappactionid_value', '_onclickeventjavascriptwebresourceid_value'], lookups: { parentappactionid: 'appactions' } },
+ appaction: { fields: ['appactionid', 'name', 'uniquename', 'context', 'contextvalue', 'location', 'type', 'ismanaged', 'statecode', 'statuscode', ...AUDIT], nullable: ['buttonlabeltext', 'sequence', 'onclickeventtype', 'onclickeventjavascriptfunctionname', 'onclickeventjavascriptparameters', 'grouptitle', 'isgrouptitlehidden', '_contextentity_value', '_parentappactionid_value', '_onclickeventjavascriptwebresourceid_value', '_appmoduleid_value'], lookups: { parentappactionid: 'appactions' } },
role: { fields: ['roleid', 'name', '_businessunitid_value', '_parentrootroleid_value', 'ismanaged', 'iscustomizable', ...AUDIT], nullable: ['description', '_parentroleid_value', '_roletemplateid_value'], lookups: { businessunitid: 'businessunits', parentrootroleid: 'roles', parentroleid: 'roles' }, navigations: { appmoduleroles_association: 'appmodules' } },
roleprivileges: { fields: ['roleprivilegeid', 'roleid', 'privilegeid', 'privilegedepthmask', ...AUDIT], nullable: [] },
privilege: { fields: ['privilegeid', 'name', 'accessright', 'canbebasic', 'canbelocal', 'canbedeep', 'canbeglobal', ...AUDIT], nullable: [] },
diff --git a/plugins/model-apps/scripts/tests/helpers/generated-runtime-types.js b/plugins/model-apps/scripts/tests/helpers/generated-runtime-types.js
new file mode 100644
index 000000000..7c98b754c
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/helpers/generated-runtime-types.js
@@ -0,0 +1,22 @@
+'use strict';
+// The RuntimeTypes text the bundled SDK generates for a page, as `genpage.js types` writes it, made offline: the SDK reads each table's metadata through
+// its own `fetchEntityMetadata`, which is replaced here by the answer it would build for a table with an id and a name column, so the generator itself
+// runs and nothing is sent. What the types say of a page — its `PageInput`, its `UxAgentDataApi` — is then the SDK's own, not a copy of it.
+const { makeTempDir } = require('./temp-dirs.js');
+const { createMakerSdk, createNodeWorkspaceStorage } = require('../../lib/maker-sdk.js');
+
+async function generatedRuntimeTypes(tables = ['contoso_item'], { prefix = 'runtime-types-' } = {}) {
+ const sdk = createMakerSdk({
+ workspaceStorage: createNodeWorkspaceStorage(makeTempDir(prefix)),
+ instanceUrl: 'https://contoso.crm.dynamics.com',
+ httpClient: { get: async () => ({ status: 404, headers: {}, body: null }), post: async () => ({ status: 404, headers: {}, body: null }) },
+ });
+ sdk.fetchEntityMetadata = async (logical) => ({
+ logicalName: logical, entitySetName: `${logical}s`, primaryIdAttribute: `${logical}id`, primaryNameAttribute: 'contoso_name', displayName: 'Item',
+ attributes: [{ logicalName: `${logical}id`, attributeType: 'Uniqueidentifier', isPrimaryId: true }, { logicalName: 'contoso_name', attributeType: 'String', isPrimaryName: true, maxLength: 100 }],
+ relationships: [], columnDetailComplete: true,
+ });
+ return sdk.generateGenPageRuntimeTypes(tables);
+}
+
+module.exports = { generatedRuntimeTypes };
diff --git a/plugins/model-apps/scripts/tests/helpers/navigation-fakes.js b/plugins/model-apps/scripts/tests/helpers/navigation-fakes.js
index 11695225c..6260b822a 100644
--- a/plugins/model-apps/scripts/tests/helpers/navigation-fakes.js
+++ b/plugins/model-apps/scripts/tests/helpers/navigation-fakes.js
@@ -9,6 +9,7 @@ const os = require('node:os');
const path = require('node:path');
const { makeSimpleMockSdk } = require('./mock-sdk.js');
const { fakeGenpage } = require('./fake-genpage.js');
+const { withPageType } = require('./page-component-type.js');
// Wrap every function reachable from `target` so a call is recorded as [name, ...args], nested objects (the raw
// `dataverse` client) with a dotted name. Arguments are recorded as given, so a test can compare them.
@@ -122,13 +123,14 @@ function pagesEnvironment({ existing = false, existingSitemap = { areas: [] } }
pushArtifact: async (type, id) => ({ type, id, saved: true, shipped: false, publish: { kind: 'notRequested' } }),
addSolutionComponent: async () => undefined,
publishArtifact: async (type, id) => ({ type, id, shipped: true, publish: { kind: 'verified' } }),
- // The shared-page scan: the apps in the environment, and the saved navigation of each (only this one here).
+ // The shared-page scan: the apps in the environment, and the saved navigation of each (only this one here). And the page table's solution component type,
+ // which the pages phase reads to add the pages it writes to the spec's solution (helpers/page-component-type.js).
dataverse: {
- get: async (url) => {
+ get: withPageType(async (url) => {
if (url.startsWith('/appmodules/')) return { status: 200, body: { value: [{ appmoduleid: APP_ID, appmoduleidunique: SELF_UNIQUE_VALUE, uniquename: 'new_supportdesk', componentstate: 0 }] } };
if (url.startsWith('/sitemaps/')) return { status: 200, body: { value: [] } };
return { status: 404, body: null };
- },
+ }),
},
};
const calls = [];
diff --git a/plugins/model-apps/scripts/tests/helpers/no-service-preload.js b/plugins/model-apps/scripts/tests/helpers/no-service-preload.js
new file mode 100644
index 000000000..00dc7ad06
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/helpers/no-service-preload.js
@@ -0,0 +1,44 @@
+'use strict';
+// Loaded with `node --require` ahead of a script that must reach NOTHING — no process, no connection, no token: it records each attempt to start a
+// process (child_process), open a connection (http, https, net, tls, fetch) or load lib/dataverse-auth.js (the module that reads tokens from the
+// Azure CLI and sends Dataverse requests), and writes the list to the file NO_SERVICE_LOG names when the process exits, e.g.
+// ["require lib/dataverse-auth.js","https.request"]
+// An attempt to start a process or open a connection also throws, so a script that tried could not carry on as if it had been answered; loading
+// the auth module is only recorded (a module can be loaded and never used, and the record is what a test asserts on).
+const fs = require('node:fs');
+const path = require('node:path');
+const Module = require('node:module');
+
+const attempts = [];
+const refused = (what) => function refusedCall() {
+ attempts.push(what);
+ throw new Error(`${what} is not allowed in this process`);
+};
+for (const [name, members] of [
+ ['child_process', ['spawn', 'spawnSync', 'exec', 'execSync', 'execFile', 'execFileSync', 'fork']],
+ ['http', ['request', 'get']],
+ ['https', ['request', 'get']],
+ ['net', ['connect', 'createConnection']],
+ ['tls', ['connect']],
+]) {
+ const api = require(`node:${name}`);
+ for (const member of members) api[member] = refused(`${name}.${member}`);
+}
+if (typeof globalThis.fetch === 'function') globalThis.fetch = refused('fetch');
+
+const AUTH = path.resolve(__dirname, '..', '..', 'lib', 'dataverse-auth.js');
+const load = Module._load;
+Module._load = function recordedLoad(request, parent, isMain) {
+ let resolved = null;
+ try {
+ resolved = Module._resolveFilename(request, parent, isMain);
+ } catch {
+ // The real load below reports a request that does not resolve.
+ }
+ if (resolved && path.resolve(resolved) === AUTH) attempts.push('require lib/dataverse-auth.js');
+ return load.apply(this, arguments);
+};
+
+process.on('exit', () => {
+ if (process.env.NO_SERVICE_LOG) fs.writeFileSync(process.env.NO_SERVICE_LOG, JSON.stringify(attempts));
+});
diff --git a/plugins/model-apps/scripts/tests/helpers/own-temp-folder.js b/plugins/model-apps/scripts/tests/helpers/own-temp-folder.js
new file mode 100644
index 000000000..430071c58
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/helpers/own-temp-folder.js
@@ -0,0 +1,71 @@
+'use strict';
+// A temp folder of the test file's own. Requiring this module points TEMP, TMP and TMPDIR at a new, empty folder inside the temp folder the
+// process was given (the suite's own, from scripts/run-tests.js) for the rest of the process, so that os.tmpdir() — and with it the folder
+// lib/temp-workspace.js keeps the plugin's throwaway workspaces in, `<temp>/power-platform-skills-model-apps` — belongs to this test file alone.
+//
+// WHY. node --test runs every test file in a process of its own, many at once, and run-tests.js gives them all ONE temp folder, so every process
+// that makes a throwaway workspace makes it in the same plugin folder, and every such process removes that folder when it ends with nothing left
+// in it (lib/temp-workspace.js, THE END OF A RUN). Windows keeps a folder that is being removed until the last handle on it closes, and refuses a
+// new entry in it meanwhile; makeTempWorkspace waits for that (WAITS_MS, about 0.8 s in all) and then makes the workspace in the plain temp folder
+// instead, as designed (a busy plugin folder is never a reason for a run to fail), and does not ask that folder again for the rest of the process.
+// Under load the wait ran out, and a test that checks WHERE a workspace is made — in the plugin's folder, recorded, under the run's pid — failed
+// although the code did what it promises: verify's workspace was `<temp>/verify-<random>`, and the settings copy's work folder was not asked for
+// in the plugin's folder at all, in that test and in the next. With a temp folder of its own, no other process makes or removes this one's
+// plugin folder. Every test file that checks where a workspace is made in its own process requires this module.
+//
+// Require it at the TOP of the test file, before anything reads os.tmpdir(), so that a path the file works out when it loads is inside the folder
+// too. A child process that a test starts with this process's environment shares the folder, as it shared the suite's before.
+//
+// THE END. The folder is removed when the process ends — after lib/temp-workspace.js has removed the workspaces this process made, and then the
+// plugin's folder: the removal is registered from the file's `after` hook, so it runs after every `exit` listener the tests' workspaces registered —
+// and only if nothing is left in it: `rmdir` takes an empty folder and nothing else. A test that leaves anything behind leaves this folder in the
+// suite's temp folder, where the runner's check names it (`own-<letters>-<hash>-<random>`, below) and fails the run.
+//
+// THE NAME is short, and bounded whatever the test file is called. Every workspace a test makes is two levels below this folder, and Windows refuses
+// fs.mkdtempSync a folder whose whole path is 248 characters or more (measured on Node 20 and 22: 247 is made, 248 is ENAMETOOLONG — MAX_PATH less
+// room for an 8.3 name, https://learn.microsoft.com/windows/win32/fileio/maximum-file-path-limitation). A name holding the whole file name took 51 of
+// them for `solution-settings-real-bundle.test.js` (measured): under a temp folder of 134 characters — long, but one the suite can use — the settings
+// copy's work folder no longer fit, went to the plain temp folder, and the test that checks where it is made failed. So the name is `own-`, the first
+// letter of each word of the file's name (at most six), four hex digits of a hash of the whole name, and mkdtemp's six characters:
+// `solution-settings-real-bundle.test.js` is `own-ssrb-<4 hex>-AbC123`, 22 characters at most, so this folder costs a workspace path 23 characters at
+// most. The letters say which file it was, the hash tells two files with the same letters apart, and a file's name is the same on every run.
+const test = require('node:test');
+const crypto = require('node:crypto');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+
+// os.tmpdir() reads TEMP, then TMP, on Windows and TMPDIR on macOS and Linux (https://nodejs.org/api/os.html#ostmpdir); run-tests.js sets all three.
+const NAMES = ['TEMP', 'TMP', 'TMPDIR'];
+// On Windows a folder whose last entry was just removed can refuse its own removal for a moment (a scanner still holds the entry): the same
+// short waits lib/temp-workspace.js gives a folder that is being removed. Elsewhere a removal is not refused for a moment, and nothing waits.
+const WAITS_MS = [25, 50, 100, 200, 400];
+const pauseSync = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
+
+// `solution-settings-real-bundle.test.js` → `own-ssrb-<4 hex>-`: the words are the runs of letters and digits before `.test.js`.
+const testFile = require.main && require.main.filename ? path.basename(require.main.filename) : 'test';
+const letters = testFile.replace(/(?:\.test)?\.[cm]?js$/, '').split(/[^A-Za-z0-9]+/).filter(Boolean).map((word) => word[0].toLowerCase()).join('').slice(0, 6) || 't';
+const hash = crypto.createHash('sha256').update(testFile).digest('hex').slice(0, 4);
+const ownTemp = fs.mkdtempSync(path.join(os.tmpdir(), `own-${letters}-${hash}-`));
+for (const name of NAMES) process.env[name] = ownTemp;
+if (os.tmpdir() !== ownTemp) throw new Error(`os.tmpdir() is ${os.tmpdir()}, not this test file's own temp folder ${ownTemp}`);
+
+function removeOwnTemp() {
+ for (let attempt = 0; ; attempt += 1) {
+ try {
+ fs.rmdirSync(ownTemp);
+ return;
+ } catch (error) {
+ if (error.code === 'ENOENT') return;
+ // Anything else that is not a Windows refusal of the moment — on every system a folder that something was left in — keeps the folder.
+ if (process.platform !== 'win32' || !['EBUSY', 'EPERM', 'ENOTEMPTY'].includes(error.code) || attempt >= WAITS_MS.length) return;
+ pauseSync(WAITS_MS[attempt]);
+ }
+ }
+}
+
+// Registered when the file's tests are done, so that this `exit` listener runs after lib/temp-workspace.js's, which the first workspace a test
+// made registered (a listener added later runs later: https://nodejs.org/api/events.html#emitteremiteventname-args).
+test.after(() => { process.once('exit', removeOwnTemp); });
+
+module.exports = { ownTemp };
diff --git a/plugins/model-apps/scripts/tests/helpers/page-component-type.js b/plugins/model-apps/scripts/tests/helpers/page-component-type.js
new file mode 100644
index 000000000..bf2df0234
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/helpers/page-component-type.js
@@ -0,0 +1,17 @@
+'use strict';
+// The page table's solution component type, as a test's stand-in for the SDK's Dataverse client answers it. A generative page is a `uxagentproject` row, a
+// custom table whose ObjectTypeCode — its solution component type — the environment allocates; every path that makes pages "in" a solution reads it to add
+// them (lib/page-solution.js), so a stand-in that models an environment answers it as the platform does:
+// GET /EntityDefinitions(LogicalName='uxagentproject')?$select=ObjectTypeCode -> 200 { "ObjectTypeCode": 10372, "MetadataId": "…" }
+// (the number is an example: each environment has its own).
+const PAGE_TYPE_PATH = "/EntityDefinitions(LogicalName='uxagentproject')?$select=ObjectTypeCode";
+const PAGE_TYPE = 10372;
+
+// `get` with the page table's component type answered in front of it; every other read is `get`'s.
+function withPageType(get, componentType = PAGE_TYPE) {
+ return async (url, ...rest) => (url === PAGE_TYPE_PATH
+ ? { status: 200, headers: {}, body: { ObjectTypeCode: componentType, MetadataId: '0d0d0d0d-0000-4000-8000-00000000d0d0' } }
+ : get(url, ...rest));
+}
+
+module.exports = { PAGE_TYPE_PATH, PAGE_TYPE, withPageType };
diff --git a/plugins/model-apps/scripts/tests/lifecycle-matrix-real-bundle.test.js b/plugins/model-apps/scripts/tests/lifecycle-matrix-real-bundle.test.js
index 6f2f4cb08..dbd78d994 100644
--- a/plugins/model-apps/scripts/tests/lifecycle-matrix-real-bundle.test.js
+++ b/plugins/model-apps/scripts/tests/lifecycle-matrix-real-bundle.test.js
@@ -136,7 +136,7 @@ const BUILD_WRITES = {
'POST roles': 1, // the persona's role
'POST roles/Microsoft.Dynamics.CRM.ReplacePrivilegesRole': 1, // its privileges, converged
'POST roles/Microsoft.Dynamics.CRM.AddPrivilegesRole': 1, // the grant on Basic User, added
- 'POST AddSolutionComponent': 16, // each component the build creates or reuses that the solution does not already hold
+ 'POST AddSolutionComponent': 17, // each component the build creates or reuses that the solution does not already hold — the generative page among them, which no other add brings
'POST PublishXml': 11, // see BUILD_PUBLISHES
};
// What each publish of the first build names, in order (an app or a page id is `app` / `page`, a web resource `webresource`).
@@ -211,7 +211,7 @@ const VERIFY_CHECKS = {
entity: 3, column: 18, 'status-reason': 1, 'alternate-key': 1, relationship: 3,
view: 3, 'view-columns': 3, 'view-filters': 3, 'view-sort': 1, chart: 1,
form: 4, 'form-identities': 4, 'form-default': 2, 'form-order': 1, 'form-order-served': 1, 'form-timeline': 1,
- dashboard: 1, command: 1,
+ dashboard: 1, command: 1, 'web-resource': 2,
subarea: 4, 'subarea-dashboard-launcher': 1, 'app-table-component': 4, page: 1, 'page-subarea': 1,
role: 1, 'app-role': 1, 'role-privileges': 1, 'role-grant': 1, 'role-grant-privileges': 1,
};
@@ -321,6 +321,19 @@ test('lifecycle matrix: the build makes every feature of the kitchen-sink spec,
withinBudget(s, 'build');
});
+// The add of the app brings its sitemap and never the pages its navigation opens (AB#6443257): the solution holds the page only because the build adds it, as a
+// component of the type the environment gives the page table (10200 in this fake) — so an export of the solution carries the page its navigation opens.
+test('lifecycle matrix: the build adds its generative page to the spec\u2019s solution, as the page table\u2019s own component type, and the rebuild keeps it there', async () => {
+ const run = await lifecycle();
+ stageOf(run, 'build');
+ assert.ok(run.ids.page, 'the page was built');
+ const pageType = 10200;
+ const held = (inventory) => inventory.solutionComponents.filter((row) => row.endsWith(` ${pageType} ${run.ids.page}`));
+ assert.equal(held(run.afterBuild).length, 1, 'the solution holds the page once');
+ assert.ok(held(run.afterBuild)[0].startsWith(run.afterBuild.rows.solutions.find((row) => row.endsWith(` ${run.spec.solution.uniqueName}`)).split(' ')[0]), 'and it is the spec\u2019s solution');
+ assert.equal(held(run.afterRebuild).length, 1, 'a rebuild keeps it there, without a second row');
+});
+
test('lifecycle matrix: rebuilding the unchanged spec creates and deletes nothing, and sends only the writes the budget lists', async (t) => {
const run = await lifecycle();
const s = stageOf(run, 'rebuild');
@@ -444,13 +457,15 @@ test('lifecycle matrix: the download writes the authored spec back, but for the
assert.deepEqual(sortRelationships(downloaded), sortRelationships(expectedDownload(run.spec, run.ids)));
// The page's source comes back byte for byte.
assert.equal(fs.readFileSync(path.join(dir, 'pages', run.ids.page, 'page.tsx'), 'utf8'), PAGE_SOURCE);
- // What it does not carry, it names: the forms, views and charts of each table.
- assert.deepEqual(emitted.payload.notRoundTripped.classes, [{ kind: 'forms', count: 5, label: 'form' }, { kind: 'views', count: 9, label: 'view' }, { kind: 'charts', count: 1, label: 'chart' }]);
+ // What it does not carry, it names: the forms, views and charts of each table, and the buttons of the command bar the build made on
+ // contoso_project (the button, the flyout and its child; the group the adapter put between them is a container, not a command).
+ assert.deepEqual(emitted.payload.notRoundTripped.classes, [{ kind: 'forms', count: 5, label: 'form' }, { kind: 'views', count: 9, label: 'view' }, { kind: 'charts', count: 1, label: 'chart' }, { kind: 'commands', count: 3, label: 'command' }]);
assert.deepEqual(Object.fromEntries(Object.entries(descriptionInventory).map(([k, list]) => [k, list.map((x) => (x.entity ? `${x.entity}: ${x.name}` : x.name))])), {
views: ['contoso_project: Active Projects', 'contoso_project: Inactive Projects', 'contoso_project: Open Projects', 'contoso_tag: Active Tag Catalog', 'contoso_tag: Inactive Tag Catalog', 'contoso_task: Active Task Items', 'contoso_task: Inactive Task Items', 'contoso_task: My Open Tasks', 'contoso_task: Open Tasks'],
charts: ['contoso_project: Projects by Priority'],
forms: ['contoso_project: Information', 'contoso_project: Project', 'contoso_tag: Information', 'contoso_task: Information', 'contoso_task: Task'],
globalChoices: ['contoso_stage'],
+ commands: ['contoso_project: Approve', 'contoso_project: Escalate', 'contoso_project: More'],
});
// ...and it warns about the two losses a rebuild elsewhere would otherwise not show.
const warningLines = stderr.split('\n').filter((l) => /^WARNING:/.test(l));
diff --git a/plugins/model-apps/scripts/tests/lifecycle-no-tables-real-bundle.test.js b/plugins/model-apps/scripts/tests/lifecycle-no-tables-real-bundle.test.js
new file mode 100644
index 000000000..86f05e196
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/lifecycle-no-tables-real-bundle.test.js
@@ -0,0 +1,215 @@
+'use strict';
+// An app with NO TABLES, through its whole lifecycle — over the REAL vendored SDK, the plugin's own HTTP client and the stateful fake
+// Dataverse the lifecycle tests share (helpers/fake-lifecycle-org.js, helpers/lifecycle-harness.js), each command run the way its CLI
+// runs it.
+//
+// A model-driven app need not have a table: `apps.js create --page-id` makes one whose navigation holds only generative pages. The App
+// Spec validator refused every spec with no table (`at least one entity is required`), in every profile, so:
+// * the download of such an app wrote its page folders, then refused the spec it had made and wrote no spec and no baseline;
+// * no build could make such an app, though the build has made a new app whose navigation holds only pages since it learned to create
+// the pages first (lifecycle-pages-first-real-bundle.test.js, whose spec still needed a table it did not show).
+// The rule now refuses only a spec with no table AND no navigation entry (app-spec-without-tables.test.js), and the cases pin, by what
+// reached the wire and what the environment holds:
+// * an app made by apps.js of one page downloads to a spec with no tables, its page and its baseline, and that spec rebuilds into the
+// same environment and verifies, creating no page and no app;
+// * a spec with no tables is planned by a dry run, built from nothing (the page, then the app with it), rebuilt unchanged, verified and
+// torn down to the environment it started from;
+// * an app with no table and no navigation entry is still refused by the download, before it writes anything.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const { makeTempDir } = require('./helpers/temp-dirs.js');
+const { createLifecycleOrg } = require('./helpers/fake-lifecycle-org.js');
+const { createLifecycleHarness, seedForeignWork, diffContents } = require('./helpers/lifecycle-harness.js');
+const { createApp } = require('../apps.js');
+const { validateAppSpec } = require('../lib/app-spec.js');
+
+// The app apps.js makes, around a page made beforehand, as a maker does with /genpage.
+const MADE_UNIQUE = 'contoso_accountmetrics';
+const MADE_PAGE = '7c9e6679-7425-40de-944b-e07fc1f90ae7';
+// The app the build makes from a spec with no tables: one page, which reads a table the environment already has.
+const BUILT_UNIQUE = 'contoso_notables';
+const PAGE_NAME = 'Kitchen Page';
+function noTablesSpec() {
+ return {
+ schemaVersion: 2,
+ solution: { uniqueName: 'ContosoNoTables', displayName: 'Contoso No Tables', publisherPrefix: 'contoso' },
+ app: { name: 'No Tables', description: 'An app whose navigation is one generative page, and which has no table of its own.' },
+ entities: [],
+ pages: [{ key: 'overview', name: PAGE_NAME, purpose: 'A page over accounts.', dataSources: ['account'], source: { kind: 'tsx', codeFile: 'KitchenPage.tsx' } }],
+ appShell: { areas: [{ label: 'Work', groups: [{ label: 'Pages', subAreas: [{ page: 'overview', title: PAGE_NAME }] }] }] },
+ };
+}
+const spec = noTablesSpec();
+
+// A request that creates a generative page (in the page service's change set, or alone) or an app.
+const createsPage = (r) => r.method === 'POST' && (/^\/uxagentprojects(\?|$)/.test(r.path) || (r.operations || []).some((o) => o.method === 'POST' && /(^|\/)uxagentprojects(\?|$)/.test(String(o.path))));
+const createsApp = (r) => r.method === 'POST' && /^\/appmodules(\?|$)/.test(r.path);
+
+// A measured step ran: it did not throw, and every request it sent is one the fake models.
+const ran = (step, label) => {
+ assert.ok(step, `${label} ran`);
+ if (step.error) throw step.error;
+ assert.deepEqual(step.unexpected, [], `every request ${label} sent is one the fake models`);
+ return step;
+};
+
+// A fake environment with another maker's work in it.
+async function environment(prefix) {
+ const org = createLifecycleOrg();
+ await seedForeignWork(org);
+ const root = makeTempDir(prefix);
+ return { org, root, harness: createLifecycleHarness(org, root), seed: org.inventory(), seedContents: org.contents() };
+}
+
+// MADE: a page, then an app made around it by apps.js — its navigation holds the page and nothing else, and it has no table.
+async function madeOfOnePage() {
+ const env = await environment('lifecycle-no-tables-made-');
+ env.org.pageServer.seedPage(MADE_PAGE, { name: 'Overview' });
+ env.org.pageServer.publishProject(env.org.pageServer.state, MADE_PAGE);
+ const made = await createApp({ env: env.org.origin, name: 'Account Metrics', solution: 'Default', pageIds: [MADE_PAGE], uniqueName: MADE_UNIQUE, publish: true }, env.harness.client);
+ assert.equal(made.ok, true, JSON.stringify(made));
+ assert.deepEqual(env.org.unexpected, [], 'every request apps.js sent is one the fake models');
+ return env;
+}
+let madeP;
+const made = () => madeP || (madeP = (async () => {
+ const env = await madeOfOnePage();
+ env.out = path.join(env.root, 'download');
+ env.download = await env.harness.measure(() => env.harness.download(MADE_UNIQUE, env.out));
+ return env;
+})());
+
+test('no tables: an app made of one generative page downloads — a spec with no tables, the page and the baseline — and the spec is one the build and verify take', async () => {
+ const env = await made();
+ const s = ran(env.download, 'the download');
+ const { emitted, spec: downloaded } = s.value;
+ assert.equal(emitted && emitted.ok, true, JSON.stringify(emitted));
+ assert.deepEqual(s.writes, {}, 'a download writes nothing to the environment');
+ assert.equal(emitted.payload.entities, 0);
+ assert.equal(emitted.payload.pages, 1);
+ assert.deepEqual(downloaded.entities, [], 'the app has no table, and the spec says so');
+ assert.deepEqual(downloaded.pages.map((p) => p.pageId), [MADE_PAGE]);
+ assert.deepEqual(downloaded.appShell.areas.flatMap((a) => a.groups.flatMap((g) => g.subAreas.map((sa) => sa.page))), [downloaded.pages[0].key], 'its navigation is the page');
+ for (const file of ['app-spec.json', path.join('pages', MADE_PAGE, 'page.tsx'), path.join('.maker-workspace', 'last-applied.json')]) {
+ assert.ok(fs.existsSync(path.join(env.out, file)), `${file} is written`);
+ }
+ for (const opts of [{ profile: 'plan', reconstructed: true }, { profile: 'deploy' }, { profile: 'structural' }]) {
+ assert.deepEqual(validateAppSpec(downloaded, opts).errors, [], JSON.stringify(opts));
+ }
+});
+
+test('no tables: the downloaded spec rebuilds into the same environment from its folder and verifies — no page and no app is created', async () => {
+ const env = await made();
+ const downloaded = ran(env.download, 'the download').value.spec;
+ const rebuild = ran(await env.harness.measure(() => env.harness.build(downloaded, { appFolder: env.out, workspace: path.join(env.out, '.maker-workspace') })), 'the rebuild');
+ assert.equal(rebuild.value.result.ok, true, JSON.stringify(rebuild.value.result.errors));
+ const requests = env.org.since(rebuild.mark);
+ assert.equal(requests.filter(createsApp).length, 0, 'the app is found by its unique name, not created again');
+ assert.ok(!requests.some(createsPage), 'the page is found by its id, not created again');
+ assert.deepEqual(env.org.find('appmodules', (a) => a.uniquename === MADE_UNIQUE).length, 1);
+ assert.deepEqual(rebuild.value.result.verify && { ok: rebuild.value.result.verify.ok, missing: rebuild.value.result.verify.missing }, { ok: true, missing: [] }, 'verify passes');
+});
+
+// BUILT: the same kind of app, made by the build from a spec with no tables.
+let builtP;
+const built = () => builtP || (builtP = (async () => {
+ const env = await environment('lifecycle-no-tables-built-');
+ env.build = await env.harness.measure(() => env.harness.build(spec));
+ return env;
+})());
+const holds = (org) => {
+ const sitemap = org.find('sitemaps', (m) => m.sitemapnameunique === BUILT_UNIQUE)[0];
+ return {
+ apps: org.find('appmodules', (a) => a.uniquename === BUILT_UNIQUE).length,
+ navigation: (String((sitemap && sitemap.sitemapxml) || '').match(/<SubArea\b[^>]*>/g) || []).map((tag) => ((/\bGenPageId="([^"]+)"/.exec(tag) || [])[1] || 'not a page').toLowerCase()),
+ pages: [...org.pageServer.state.projects.values()].filter((p) => p.name === PAGE_NAME).map((p) => String(p.id).toLowerCase()),
+ };
+};
+
+test('no tables: a dry run plans the app and writes nothing', async () => {
+ const env = await environment('lifecycle-no-tables-dry-');
+ const dry = ran(await env.harness.measure(() => env.harness.build(spec, { apply: false })), 'the dry run');
+ assert.equal(dry.value.result.ok, true, JSON.stringify(dry.value.result.errors));
+ assert.deepEqual(dry.writes, {}, 'a dry run writes nothing');
+ assert.deepEqual(env.org.inventory(), env.seed);
+});
+
+test('no tables: built from nothing — the page, then the app whose first navigation holds it — and verify passes', async () => {
+ const env = await built();
+ const build = ran(env.build, 'the build');
+ assert.equal(build.value.result.ok, true, JSON.stringify(build.value.result.errors));
+ const requests = env.org.since(build.mark);
+ const pageCreate = requests.findIndex(createsPage);
+ const appCreate = requests.findIndex(createsApp);
+ assert.ok(pageCreate >= 0 && appCreate > pageCreate, `the page is created (${pageCreate}) before the app (${appCreate})`);
+ assert.equal(requests.filter(createsPage).length, 1);
+ assert.equal(requests.filter(createsApp).length, 1);
+ const after = holds(env.org);
+ assert.equal(after.apps, 1);
+ assert.equal(after.pages.length, 1);
+ assert.deepEqual(after.navigation, after.pages, 'the navigation holds the page, and nothing else');
+ assert.ok(!(build.writes['POST EntityDefinitions'] || 0), 'and no table is made');
+ assert.deepEqual(build.value.result.verify && { ok: build.value.result.verify.ok, missing: build.value.result.verify.missing }, { ok: true, missing: [] }, 'verify passes');
+});
+
+test('no tables: an unchanged rebuild creates nothing', async () => {
+ const env = await built();
+ const before = holds(env.org);
+ const rebuild = ran(await env.harness.measure(() => env.harness.build(spec)), 'the rebuild');
+ assert.equal(rebuild.value.result.ok, true, JSON.stringify(rebuild.value.result.errors));
+ const requests = env.org.since(rebuild.mark);
+ assert.equal(requests.filter(createsApp).length, 0);
+ assert.ok(!requests.some(createsPage));
+ assert.deepEqual(holds(env.org), before);
+});
+
+test('no tables: the teardown deletes everything the build made, and nothing else', async () => {
+ const env = await built();
+ const teardown = ran(await env.harness.measure(() => env.harness.teardown(spec)), 'the teardown');
+ assert.equal(teardown.value.result.ok, true, JSON.stringify(teardown.value.result.errors));
+ assert.deepEqual(holds(env.org), { apps: 0, navigation: [], pages: [] });
+ // Back to the seed, but for the publisher the build made for the prefix: a teardown never deletes a publisher (other solutions may share it).
+ const now = env.org.inventory();
+ const madePublishers = now.rows.publishers.filter((p) => !env.seed.rows.publishers.includes(p));
+ assert.equal(madePublishers.length, 1, 'the build made one publisher, for its prefix');
+ assert.deepEqual({ ...now, rows: { ...now.rows, publishers: now.rows.publishers.filter((p) => !madePublishers.includes(p)) } }, env.seed, 'every other row is as it was before the build');
+ assert.deepEqual(diffContents(env.seedContents, env.org.contents(), { added: false }), [], 'and every one of them holds what it held');
+});
+
+// NEIGHBOUR: an app with no table AND no navigation entry is still nothing a spec can describe. The download refuses it before it writes
+// anything: a folder holding an earlier download of the app keeps it as it was.
+test('no tables: an app with no table and no navigation entry is refused by the download before it writes anything', async () => {
+ const env = await madeOfOnePage();
+ const out = path.join(env.root, 'download');
+ const first = ran(await env.harness.measure(() => env.harness.download(MADE_UNIQUE, out)), 'the first download');
+ assert.equal(first.value.emitted.ok, true, JSON.stringify(first.value.emitted));
+ const snapshot = () => {
+ const files = {};
+ const walk = (dir) => {
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) walk(full);
+ else files[path.relative(out, full)] = fs.readFileSync(full, 'utf8');
+ }
+ };
+ walk(out);
+ return files;
+ };
+ const before = snapshot();
+ // A maker empties the app's navigation in the designer and publishes it: Dataverse accepts an empty navigation on an UPDATE (app-navigation.js).
+ const send = async (method, where, body) => {
+ const res = await env.org.request({ url: `${env.org.API}${where}`, method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
+ assert.ok(res.statusCode < 300, `${method} ${where} answered ${res.statusCode}: ${res.body}`);
+ };
+ const sitemap = env.org.find('sitemaps', (m) => m.sitemapnameunique === MADE_UNIQUE)[0];
+ const app = env.org.find('appmodules', (a) => a.uniquename === MADE_UNIQUE)[0];
+ await send('PATCH', `/sitemaps(${sitemap.sitemapid})`, { sitemapxml: '<SiteMap IntroducedVersion="7.0.0.0"><Area Id="area_0"><Group Id="group_0" /></Area></SiteMap>' });
+ await send('POST', '/PublishXml', { ParameterXml: `<importexportxml><appmodules><appmodule>${app.appmoduleid}</appmodule></appmodules></importexportxml>` });
+ const refused = ran(await env.harness.measure(() => env.harness.download(MADE_UNIQUE, out)), 'the second download');
+ assert.equal(refused.value.emitted.ok, false);
+ assert.equal(refused.value.emitted.payload.error, 'downloaded App Spec failed validation');
+ assert.deepEqual(refused.value.emitted.payload.errors, ['at least one entity is required — or, for an app with no tables, an entry in appShell (a page, a dashboard or a URL)']);
+ assert.deepEqual(snapshot(), before, 'the folder holds exactly what the earlier download wrote');
+});
diff --git a/plugins/model-apps/scripts/tests/lifecycle-scenarios-real-bundle.test.js b/plugins/model-apps/scripts/tests/lifecycle-scenarios-real-bundle.test.js
index 8a455622c..6c3c9b71f 100644
--- a/plugins/model-apps/scripts/tests/lifecycle-scenarios-real-bundle.test.js
+++ b/plugins/model-apps/scripts/tests/lifecycle-scenarios-real-bundle.test.js
@@ -108,7 +108,8 @@ const DOWNLOADED_REBUILD_WRITES = {
// either — and what declaring them adds: one read of the table's status column and one of its keys, for the one table that declares them.
// (The status column read is the same request the view filter's label read of that table makes among its four; it is not shared, because
// that read is made only for a table a view filters by a label, and sharing it would cost every other table three reads more.)
-const VERIFY_READS_WITHOUT = 74;
+// 76: the two web resources the spec declares are read once each, with their content, for the web-resource check.
+const VERIFY_READS_WITHOUT = 76;
const VERIFY_READS_ADDED = [
"GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.StatusAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options)",
"GET /EntityDefinitions(LogicalName='contoso_project')/Keys?$select=LogicalName,SchemaName,KeyAttributes",
diff --git a/plugins/model-apps/scripts/tests/list-custom-apis.test.js b/plugins/model-apps/scripts/tests/list-custom-apis.test.js
index 2df04ed54..5b4917e6e 100644
--- a/plugins/model-apps/scripts/tests/list-custom-apis.test.js
+++ b/plugins/model-apps/scripts/tests/list-custom-apis.test.js
@@ -21,30 +21,22 @@ test('queries customapi with request parameters expanded inline (no OR-of-ids pa
assert.doesNotMatch(scriptSrc, /_customapiid_value eq/);
});
-test('gates fail-closed via exitIfCustomApiDisabled before any query', () => {
- assert.match(scriptSrc, /exitIfCustomApiDisabled\(\)/);
+// Custom API support has no feature flag any more: the script reads no gate, so nothing it does depends on GENPAGE_ENABLE_CUSTOM_API.
+test('reads no feature gate: discovery is always available', () => {
+ assert.doesNotMatch(scriptSrc, /feature-flags|exitIfCustomApiDisabled|isCustomApiEnabled/);
});
-// --- Feature gate + arg validation (spawned CLI) ---------------------------
+// --- Arg validation (spawned CLI) ---------------------------------------------
-test('exits 3 with a disabled message when the custom-api flag is OFF', () => {
- // The gate runs before any Dataverse call, so a valid-looking env URL still bails.
- const res = spawnSync(process.execPath, [scriptPath, 'https://example.crm.dynamics.com'], {
- encoding: 'utf8',
- env: { ...process.env, GENPAGE_ENABLE_CUSTOM_API: '0' },
- });
- assert.equal(res.status, 3);
- assert.match(res.stderr, /disabled/i);
-});
-
-test('missing args exits 1 with usage (when the flag is ON)', () => {
- // Enable the flag so the run reaches arg validation instead of the feature gate.
- const res = spawnSync(process.execPath, [scriptPath], {
- encoding: 'utf8',
- env: { ...process.env, GENPAGE_ENABLE_CUSTOM_API: '1' },
- });
- assert.equal(res.status, 1);
- assert.match(res.stderr, /Usage:/);
+test('missing args exits 1 with usage, whatever GENPAGE_ENABLE_CUSTOM_API says', () => {
+ for (const value of [undefined, '0', '1']) {
+ const env = { ...process.env };
+ delete env.GENPAGE_ENABLE_CUSTOM_API;
+ if (value !== undefined) env.GENPAGE_ENABLE_CUSTOM_API = value;
+ const res = spawnSync(process.execPath, [scriptPath], { encoding: 'utf8', env });
+ assert.equal(res.status, 1, String(value));
+ assert.match(res.stderr, /Usage:/);
+ }
});
// --- Unit tests for the pure helpers (require.main guard keeps main() from running) ---
@@ -204,7 +196,8 @@ function api(name, overrides = {}) {
};
}
-function discover({ apis, entities, enabled = '1', refuse, unreadable, responseBody } = {}) {
+// `enabled` is the value GENPAGE_ENABLE_CUSTOM_API carries into the child (null: unset). The variable no longer means anything.
+function discover({ apis, entities, enabled = null, refuse, unreadable, responseBody } = {}) {
const dir = makeTempDir('custom-api-discovery-');
const fixturePath = path.join(dir, 'fixture.json');
const logPath = path.join(dir, 'requests.json');
@@ -297,21 +290,20 @@ test('lookup discovery retains the callable input name without emitting an unsup
assert.ok(Object.values(entry.parameterKinds).every((kind) => PRIMITIVE_KINDS.has(kind)));
});
-test('default-on discovery reaches the same supported result as an explicit enable', () => {
- const input = { apis: [api('new_Primitive')] };
- const expected = discover(input);
- const result = discover({ ...input, enabled: null });
- assert.equal(result.status, 0, result.stderr);
- assert.deepEqual(result.output, expected.output);
- assert.equal(result.requests.length, 1);
-});
-
-test('an explicit discovery opt-out makes zero requests and emits no bindings', () => {
- const result = discover({ apis: [api('new_Primitive')], enabled: '0' });
- assert.equal(result.status, 3);
- assert.match(result.stderr, /disabled/i);
- assert.equal(result.output, null);
- assert.deepEqual(result.requests, []);
+// GENPAGE_ENABLE_CUSTOM_API was the opt-out of the removed custom-api flag. It is ignored now: set to 0, set to 1 or unset, discovery sends the
+// same one request and lists the same APIs (it once exited 3 with no request when the variable was 0).
+test('GENPAGE_ENABLE_CUSTOM_API is ignored: 0, 1 and unset list exactly the same, with the same request', () => {
+ const input = { apis: [api('new_Primitive'), api('new_Bound', { bindingtype: 1, boundentitylogicalname: 'account' })], entities: 'account' };
+ const unset = discover(input);
+ assert.equal(unset.status, 0, unset.stderr);
+ assert.equal(unset.output.customApis.length, 2);
+ for (const enabled of ['0', '1', 'false']) {
+ const result = discover({ ...input, enabled });
+ assert.equal(result.status, 0, `${enabled}: ${result.stderr}`);
+ assert.equal(result.stdout, unset.stdout, enabled);
+ assert.equal(result.stderr, unset.stderr, enabled);
+ assert.deepEqual(result.requests, unset.requests, enabled);
+ }
});
test('global-only discovery stays bounded, sorted and independent of the number of matching APIs', () => {
diff --git a/plugins/model-apps/scripts/tests/list-dataverse-operations.test.js b/plugins/model-apps/scripts/tests/list-dataverse-operations.test.js
new file mode 100644
index 000000000..df4218f41
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/list-dataverse-operations.test.js
@@ -0,0 +1,201 @@
+'use strict';
+// scripts/list-dataverse-operations.js as a process: the exit status, the bytes on stdout and stderr, and what it reached — nothing.
+//
+// The command offers the reviewed catalogue (lib/dataverse-operations.js) and checks nothing in an environment, so it takes no environment and
+// must not read a token, start a process or open a connection (helpers/no-service-preload.js records any attempt, and a load of
+// lib/dataverse-auth.js). The gate is checked first (exit 3 wins over a bad argument), then the arguments (exit 1, usage), then the catalogue
+// (exit 1, one fixed line, when it cannot be read or is not exactly the reviewed pair — a widened catalogue is the producer's failure, not an offer).
+// A failure writes nothing on stdout. Each exit makes its streams blocking before it writes: on Linux and macOS a pipe's writes are queued, and the
+// process ends right after them (helpers/queued-stdio-preload.js, helpers/write-order-preload.js).
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+const { makeTempDir } = require('./helpers/temp-dirs.js');
+
+const SCRIPTS = path.join(__dirname, '..');
+const SCRIPT = path.join(SCRIPTS, 'list-dataverse-operations.js');
+const NO_SERVICE = path.join(__dirname, 'helpers', 'no-service-preload.js');
+const FAKE = path.join(__dirname, 'helpers', 'fake-dataverse-operations-preload.js');
+const QUEUED = path.join(__dirname, 'helpers', 'queued-stdio-preload.js');
+const ORDER = path.join(__dirname, 'helpers', 'write-order-preload.js');
+
+// The success body, as the command prints it: these keys, in this order, and nothing else.
+const EXPECTED = {
+ ok: true,
+ catalogueVersion: 1,
+ verification: {
+ mode: 'catalogue-only',
+ environment: 'not-checked',
+ runtime: 'not-checked',
+ privileges: 'not-checked',
+ },
+ operations: [
+ {
+ name: 'WhoAmI',
+ displayName: 'Current Dataverse identity',
+ isFunction: true,
+ bindingType: 'Global',
+ parameters: [],
+ parameterKinds: {},
+ response: {
+ typeName: 'Microsoft.Dynamics.CRM.WhoAmIResponse',
+ properties: {
+ BusinessUnitId: 'Edm.Guid',
+ UserId: 'Edm.Guid',
+ OrganizationId: 'Edm.Guid',
+ },
+ },
+ outputPrivacy: 'identity',
+ invocation: 'user-triggered',
+ requiresExplicitSelection: true,
+ },
+ {
+ name: 'RetrieveVersion',
+ displayName: 'Dataverse server version',
+ isFunction: true,
+ bindingType: 'Global',
+ parameters: [],
+ parameterKinds: {},
+ response: {
+ typeName: 'Microsoft.Dynamics.CRM.RetrieveVersionResponse',
+ properties: { Version: 'Edm.String' },
+ },
+ outputPrivacy: 'service-version',
+ invocation: 'user-triggered',
+ requiresExplicitSelection: true,
+ },
+ ],
+};
+const GATE_LINE = 'Dataverse built-in operation authoring is disabled (feature flag "dataverse-operations" is OFF). '
+ + 'Set GENPAGE_ENABLE_DATAVERSE_OPERATIONS=1 to offer WhoAmI and RetrieveVersion. '
+ + 'Existing bindings are preserved; runtime governance and user privileges still apply.';
+const USAGE_LINE = 'Usage: node scripts/list-dataverse-operations.js';
+const CATALOGUE_LINE = 'The built-in operation catalogue could not be read. No built-in operations were offered.';
+
+const scratch = makeTempDir('dv-ops-list-');
+let runs = 0;
+
+// The environment of a run: the test's own, without the gate's override or the retired custom-api variable (so the committed default applies
+// unless a case sets one).
+function baseEnv(env) {
+ const out = { ...process.env, POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: '1' };
+ delete out.GENPAGE_ENABLE_DATAVERSE_OPERATIONS;
+ delete out.GENPAGE_ENABLE_CUSTOM_API;
+ delete out.FAKE_DV_OPERATIONS;
+ return { ...out, ...env };
+}
+
+// Runs the command under the no-service probe: { status, stdout, stderr, attempts }.
+function run(args = [], { env = {}, preloads = [] } = {}) {
+ const log = path.join(scratch, `attempts-${runs += 1}.json`);
+ const result = spawnSync(process.execPath, [...[NO_SERVICE, ...preloads].flatMap((p) => ['--require', p]), SCRIPT, ...args], {
+ encoding: 'utf8',
+ env: baseEnv({ ...env, NO_SERVICE_LOG: log }),
+ });
+ return {
+ status: result.status,
+ stdout: result.stdout,
+ stderr: result.stderr,
+ attempts: fs.existsSync(log) ? JSON.parse(fs.readFileSync(log, 'utf8')) : null,
+ };
+}
+
+const ON = { GENPAGE_ENABLE_DATAVERSE_OPERATIONS: '1' };
+
+test('enabled: the whole serialized catalogue — both operations, their response types, privacy, trigger and selection, every not-checked label — and nothing reached', () => {
+ const ran = run([], { env: ON });
+ assert.equal(ran.status, 0, ran.stderr);
+ assert.equal(ran.stderr, '');
+ assert.equal(ran.stdout, `${JSON.stringify(EXPECTED)}\n`);
+ assert.deepStrictEqual(JSON.parse(ran.stdout), EXPECTED);
+ assert.deepStrictEqual(ran.attempts, [], 'no token, no request, no process, and the auth module is not even loaded');
+ // Schema only: no identity value, no server version, no environment, nothing that reads as checked.
+ assert.doesNotMatch(ran.stdout, /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-/i);
+ assert.doesNotMatch(ran.stdout, /\d+\.\d+\.\d+/);
+ assert.doesNotMatch(ran.stdout, /"eligible"|"available"|https?:|envUrl|"verified"/);
+});
+
+test('disabled — the shipped default — exits 3 with nothing on stdout and the one gate line on stderr, and the gate wins over any argument', () => {
+ for (const [args, env] of [
+ [[], {}],
+ [[], { GENPAGE_ENABLE_DATAVERSE_OPERATIONS: '0' }],
+ [[], { GENPAGE_ENABLE_DATAVERSE_OPERATIONS: 'maybe' }],
+ [['https://contoso.crm.dynamics.com'], {}],
+ [['--env', 'https://contoso.crm.dynamics.com'], {}],
+ [['--help'], {}],
+ [[], { GENPAGE_ENABLE_CUSTOM_API: '1' }],
+ ]) {
+ const ran = run(args, { env });
+ const label = JSON.stringify({ args, env });
+ assert.equal(ran.status, 3, label);
+ assert.equal(ran.stdout, '', label);
+ assert.equal(ran.stderr, `${GATE_LINE}\n`, label);
+ assert.deepStrictEqual(ran.attempts, [], label);
+ }
+ // Off wins over a catalogue that could not be read too: nothing is loaded before the gate.
+ const broken = run([], { env: { FAKE_DV_OPERATIONS: 'unloadable' }, preloads: [FAKE] });
+ assert.equal(broken.status, 3);
+ assert.equal(broken.stderr, `${GATE_LINE}\n`);
+});
+
+test('enabled with any argument exits 1 with the usage line and nothing on stdout — this command takes no environment and no option', () => {
+ for (const args of [['https://contoso.crm.dynamics.com'], ['--env', 'https://contoso.crm.dynamics.com'], ['--entities', 'account'], ['--help'], ['WhoAmI'], ['']]) {
+ const ran = run(args, { env: ON });
+ assert.equal(ran.status, 1, JSON.stringify(args));
+ assert.equal(ran.stdout, '', JSON.stringify(args));
+ assert.equal(ran.stderr, `${USAGE_LINE}\n`, JSON.stringify(args));
+ assert.deepStrictEqual(ran.attempts, [], JSON.stringify(args));
+ }
+});
+
+test('a catalogue that cannot be read, or is not exactly the reviewed pair, offers nothing: exit 1, nothing on stdout, one fixed line', () => {
+ for (const mode of [
+ 'unloadable', 'throws', 'missing', 'widened', 'reordered', 'renamed', 'action', 'bound', 'inputs', 'declared', 'on-load', 'unselected',
+ 'unverified', 'checked', 'revised', 'eligible', 'no-response', 'empty', 'not-an-object',
+ ]) {
+ const ran = run([], { env: { ...ON, FAKE_DV_OPERATIONS: mode }, preloads: [FAKE] });
+ assert.equal(ran.status, 1, `${mode}: ${ran.stderr}`);
+ assert.equal(ran.stdout, '', `${mode}: no partial or widened list`);
+ assert.equal(ran.stderr, `${CATALOGUE_LINE}\n`, mode);
+ assert.deepStrictEqual(ran.attempts, [], mode);
+ }
+});
+
+// Custom API support has no flag any more, and the variable of the retired custom-api flag is no switch for this listing either way: it lists
+// with the gate ON whatever that variable says, and stays closed with the gate OFF (the case above sets it to 1).
+test('the retired custom-api variable leaves the listing as it is', () => {
+ for (const value of ['0', '1']) {
+ const ran = run([], { env: { ...ON, GENPAGE_ENABLE_CUSTOM_API: value } });
+ assert.equal(ran.status, 0, ran.stderr);
+ assert.equal(ran.stdout, `${JSON.stringify(EXPECTED)}\n`);
+ }
+});
+
+test('over the kind of pipe Linux and macOS give a script, every exit makes its streams blocking before its first write, and the text arrives whole', () => {
+ for (const [label, args, env, preloads, status, stream, text] of [
+ ['success', [], ON, [], 0, 3, `${JSON.stringify(EXPECTED)}\n`],
+ ['gate', [], {}, [], 3, 4, `${GATE_LINE}\n`],
+ ['usage', ['extra'], ON, [], 1, 4, `${USAGE_LINE}\n`],
+ ['catalogue', [], { ...ON, FAKE_DV_OPERATIONS: 'widened' }, [FAKE], 1, 4, `${CATALOGUE_LINE}\n`],
+ ]) {
+ const record = path.join(scratch, `order-${runs += 1}.json`);
+ const result = spawnSync(process.execPath, [...[QUEUED, ...preloads, ORDER].flatMap((p) => ['--require', p]), SCRIPT, ...args], {
+ env: baseEnv({ ...env, WRITE_ORDER_FILE: record }),
+ stdio: ['ignore', 'pipe', 'pipe', 'pipe', 'pipe'],
+ });
+ assert.equal(result.status, status, `${label}: ${String(result.output[4])}`);
+ const out = { 3: String(result.output[3]), 4: String(result.output[4]) };
+ assert.equal(out[stream], text, label);
+ assert.equal(out[stream === 3 ? 4 : 3], '', `${label}: the other stream stays empty`);
+ const { events } = JSON.parse(fs.readFileSync(record, 'utf8'));
+ for (const name of ['stdout', 'stderr']) {
+ const firstWrite = events.indexOf(`write ${name}`);
+ if (firstWrite === -1) continue;
+ const blocking = events.indexOf(`blocking ${name}`);
+ assert.ok(blocking !== -1 && blocking < firstWrite, `${label}: ${name} made blocking before its first write (${events.join(', ')})`);
+ }
+ assert.ok(events.some((event) => event.startsWith('write ')), `${label}: it wrote`);
+ }
+});
diff --git a/plugins/model-apps/scripts/tests/localization-reference.test.js b/plugins/model-apps/scripts/tests/localization-reference.test.js
index 0c0f2af25..a07e51ba4 100644
--- a/plugins/model-apps/scripts/tests/localization-reference.test.js
+++ b/plugins/model-apps/scripts/tests/localization-reference.test.js
@@ -46,3 +46,67 @@ test('the script fallback in the reference classifies every right-to-left cultur
for (const code of RTL_CULTURES) assert.strictEqual(isRtl(code), true, `${code} is right-to-left`);
for (const code of LTR_CULTURES) assert.strictEqual(isRtl(code), false, `${code} is left-to-right`);
});
+
+// The page error contract's localized copy (references/rules.md, "Missing Error Handling"). PageErrorBar and
+// PageErrorBoundary are top-level, hook-free components: they cannot read a `language` that lives in a component's
+// closure, so the reference resolves the UI language in a top-level resolvePageLanguage() and makes translate() top
+// level too. These tests run that ACTUAL code — transpiled with the vendored TypeScript, a transpile and not a type
+// check — against a stand-in Xrm global.
+const { loadVendoredTypeScript } = require('../lib/typescript-compiler.js');
+
+const blocksOf = (text) => [...text.replace(/\r\n/g, '\n').matchAll(/```(?:typescript|tsx)\n([\s\S]*?)\n```/g)].map((match) => match[1]);
+function localizedPage(dictionary) {
+ const blocks = blocksOf(DOC);
+ const language = blocks.find((block) => /^function resolvePageLanguage\(\)/m.test(block));
+ assert.ok(language, 'the reference defines a top-level resolvePageLanguage()');
+ const words = blocks.find((block) => /^const translations\b/m.test(block) && /^function translate\(/m.test(block));
+ assert.ok(words, 'the reference defines a top-level translate() over its translations dictionary');
+ let source = `${language}\n${words}\n`;
+ if (dictionary) {
+ source = source.replace(/^const translations[^=]*=\s*\{[\s\S]*?\n\};/m, () => `const translations: Record<string, Record<string, string>> = ${JSON.stringify(dictionary)};`);
+ }
+ const ts = loadVendoredTypeScript();
+ const { outputText } = ts.transpileModule(`${source}\nexport { resolvePageLanguage, translate, translations };\n`, {
+ compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
+ });
+ return (xrm) => {
+ const module = { exports: {} };
+ new Function('module', 'exports', 'Xrm', outputText)(module, module.exports, xrm);
+ return module.exports;
+ };
+}
+const hostWithLanguage = (languageId) => ({ Utility: { getGlobalContext: () => ({ userSettings: { languageId } }) } });
+const brokenHost = { Utility: { getGlobalContext: () => { throw new Error('no context'); } } };
+
+test('the UI language is resolved at the top level without hooks, and a missing or failing host falls back to English', () => {
+ const page = localizedPage();
+ const language = blocksOf(DOC).find((block) => /^function resolvePageLanguage\(\)/m.test(block));
+ assert.doesNotMatch(language, /\buse(?:Memo|State|Effect|Callback)\b/, 'the resolver needs no React hook');
+ assert.deepEqual({ ...page(undefined).resolvePageLanguage() }, { code: 'en-US', name: 'English', isRtl: false }, 'no Xrm global');
+ assert.deepEqual({ ...page(hostWithLanguage(1025)).resolvePageLanguage() }, { code: 'ar-SA', name: 'Arabic (Saudi Arabia)', isRtl: true });
+ assert.equal(page(hostWithLanguage(1036)).resolvePageLanguage().code, 'en-US', 'a language the plan does not list');
+ assert.equal(page(brokenHost).resolvePageLanguage().code, 'en-US', 'a host that throws does not crash the fallback UI');
+});
+
+test('translate is top level: it picks the user\u2019s language, then English, then the key, and carries the error keys', () => {
+ const arabic = localizedPage()(hostWithLanguage(1025));
+ assert.equal(arabic.translate('save'), arabic.translations['ar-SA'].save, 'the non-default language is used');
+ assert.equal(arabic.translate('error.read'), 'Unable to load data. Please try again.', 'a key the language lacks falls back to English');
+ assert.equal(arabic.translate('missing.key'), 'missing.key');
+ assert.deepEqual(Object.fromEntries(Object.entries(arabic.translations['en-US']).filter(([key]) => key.startsWith('error.'))), {
+ 'error.read': 'Unable to load data. Please try again.',
+ 'error.write': 'The change could not be saved. Refresh before trying again.',
+ 'error.network': 'The request did not go through. You can try again.',
+ 'error.indeterminate': "We couldn't confirm this completed \u2014 refresh before retrying.",
+ 'error.render': 'This page hit a problem and could not render. Refresh the page.',
+ 'error.tryAgain': 'Try again',
+ }, 'the dictionary carries the error keys, with the copy rules.md publishes');
+});
+
+test('the boundary and error bar fallbacks resolve localized copy with no component closure', () => {
+ const page = localizedPage({ 'en-US': { 'error.render': 'EN render', 'error.tryAgain': 'EN retry' }, 'ar-SA': { 'error.render': 'AR render' } });
+ assert.equal(page(hostWithLanguage(1025)).translate('error.render'), 'AR render');
+ assert.equal(page(hostWithLanguage(1025)).translate('error.tryAgain'), 'EN retry', 'an untranslated key still shows English copy, never a raw key');
+ assert.equal(page(hostWithLanguage(1033)).translate('error.render'), 'EN render');
+ assert.equal(page(brokenHost).translate('error.render'), 'EN render', 'the render fallback survives a failing host');
+});
\ No newline at end of file
diff --git a/plugins/model-apps/scripts/tests/localized-labels.test.js b/plugins/model-apps/scripts/tests/localized-labels.test.js
index b265004f4..dacd11353 100644
--- a/plugins/model-apps/scripts/tests/localized-labels.test.js
+++ b/plugins/model-apps/scripts/tests/localized-labels.test.js
@@ -285,6 +285,57 @@ test('labelAliases is the one rule both sample data and surfaces use', () => {
assert.deepStrictEqual(labelAliases(undefined), []);
});
+// --- a text two options share ---------------------------------------------------------------------
+// A label naming two options is an ERROR when the author cannot see it on the line (a localized label hides the text among its
+// languages) and a WARNING when they can (two plain strings: Dataverse allows the duplicate and earlier specs built with one). Two
+// IDENTICAL localized labels — the same text in each of the same languages, one language or several — read alike on the line too, so
+// they are the visible case.
+const optionsWarningsAndErrors = (options) => {
+ const s = base();
+ s.entities[0].columns = [{ schemaName: 'contoso_stage', type: 'Choice', options }];
+ const r = validateAppSpec(s, { profile: 'plan' });
+ const about = (list) => (list || []).filter((m) => /names BOTH options/.test(m));
+ return { errors: about(r.errors), warnings: about(r.warnings) };
+};
+
+test('two options sharing their text in ONE language — one-entry maps of the same language — warn, as two plain strings do', () => {
+ const same = optionsWarningsAndErrors([{ 1036: 'Ouvert' }, { 1036: 'Ouvert' }, { 3082: 'Cerrado' }]);
+ assert.deepStrictEqual(same.errors, []);
+ assert.strictEqual(same.warnings.length, 1, JSON.stringify(same.warnings));
+ assert.match(same.warnings[0], /'Ouvert' names BOTH options\[0\] and options\[1\].*resolves to options\[0\]/);
+ assert.deepStrictEqual(optionsWarningsAndErrors(['Ouvert', 'Ouvert']).errors, [], 'two plain strings, as before');
+});
+
+test('two options sharing their text in DIFFERENT languages, or hidden in a label of several, are still refused', () => {
+ for (const options of [
+ [{ 1036: 'Ouvert' }, { 3082: 'Ouvert' }],
+ ['Ouvert', { 1036: 'Ouvert' }],
+ [{ 1036: 'Ouvert' }, 'Ouvert'],
+ [{ 1036: 'Ouvert' }, { 1036: 'Ouvert' }, 'Ouvert'],
+ [{ 1036: 'Ouvert' }, { 1033: 'Open', 1036: 'Ouvert' }],
+ [{ 1033: 'Abierto', 3082: 'Abierto' }, { 1033: 'Abierto' }],
+ [{ 1033: 'Abierto', 3082: 'Abierto' }, { 1033: 'Abierto', 3082: 'Cerrado' }],
+ [{ 1033: 'Abierto', 3082: 'Abierto' }, { 1033: 'Abierto', 3082: 'Abierto' }, { 1033: 'Open', 3082: 'Abierto' }],
+ ]) {
+ const got = optionsWarningsAndErrors(options);
+ assert.strictEqual(got.errors.length > 0, true, `${JSON.stringify(options)} must be refused: ${JSON.stringify(got)}`);
+ assert.match(got.errors[0], /not visible on the line/);
+ }
+});
+
+test('two options whose labels are IDENTICAL in several languages — as Dataverse holds two options labelled alike — warn, once per text', () => {
+ // MEASURED: Dataverse fills the environment's base language in, with the same text, when a label is created in another language
+ // only — so two options labelled "Abierto" in Spanish are held as { 1033: "Abierto", 3082: "Abierto" } each. The two lines read
+ // alike: a duplicate the author can see, like two equal plain strings, not a text hidden among the languages of one of them.
+ const filled = optionsWarningsAndErrors([{ 1033: 'Abierto', 3082: 'Abierto' }, { 1033: 'Abierto', 3082: 'Abierto' }, { 1033: 'Cerrado', 3082: 'Cerrado' }]);
+ assert.deepStrictEqual(filled.errors, []);
+ assert.strictEqual(filled.warnings.length, 1, `one warning for the one text, not one per language: ${JSON.stringify(filled.warnings)}`);
+ assert.match(filled.warnings[0], /'Abierto' names BOTH options\[0\] and options\[1\].*resolves to options\[0\]/);
+ const translated = optionsWarningsAndErrors([{ 1033: 'Open', 3082: 'Abierto' }, { 1033: 'Open', 3082: 'Abierto' }]);
+ assert.deepStrictEqual(translated.errors, []);
+ assert.deepStrictEqual(translated.warnings.map((w) => /'(\w+)' names BOTH/.exec(w)[1]).sort(), ['Abierto', 'Open'], 'each text the two share is named');
+});
+
test('a surface named in EITHER language resolves', () => {
// `surfaces[]` is the machine-readable claim that a job is satisfied by these screens. On a
// bilingual spec, naming the Spanish label is as legitimate as naming the English one — matching
@@ -378,6 +429,144 @@ test('a single-language table still downloads as a plain string', () => {
// No plural is emitted for a plain label — it was never in the spec before and adding it would
// change every existing download.
assert.strictEqual('pluralName' in e, false, JSON.stringify(e));
+ // ...and it stays exactly that when the label is in the download's authoring language.
+ assert.deepStrictEqual(entityFromMetadata(meta, 'new_order', { languageCode: 1033 }), e);
+});
+
+// --- a label held in ONE language that is not the authoring one ----------------------------------
+// The authoring language is the one a rebuild of the download resolves: --language-code, else the spec's pin, else the environment's
+// base language. A plain string is written in the language a rebuild resolves, so a label held only in Spanish, downloaded from an
+// environment whose base language is English, was rebuilt as an English label with Spanish text. The download now keeps its language.
+const onlyIn = (lcid, text) => dvLabel([[lcid, text]]);
+
+test('labelFromDataverse keeps the language of a label held in one language other than the authoring one, and nothing else changes', () => {
+ assert.deepStrictEqual(labelFromDataverse(onlyIn(3082, 'Pedido'), 1033), { 3082: 'Pedido' });
+ assert.strictEqual(labelFromDataverse(onlyIn(3082, 'Pedido'), 3082), 'Pedido', 'in the authoring language it is a plain string');
+ assert.strictEqual(labelFromDataverse(onlyIn(1033, 'Order'), 1033), 'Order');
+ assert.strictEqual(labelFromDataverse(onlyIn(1033, 'Order'), '1033'), 'Order', 'an LCID given as text is the same language');
+ assert.strictEqual(labelFromDataverse(onlyIn(3082, 'Pedido')), 'Pedido', 'a caller that names no authoring language gets the plain string, as before');
+ assert.deepStrictEqual(labelFromDataverse(dvLabel([[1033, 'Order'], [3082, 'Pedido']]), 1033), { 1033: 'Order', 3082: 'Pedido' }, 'several languages: the map, as before');
+ assert.strictEqual(labelFromDataverse(dvLabel([]), 1033), undefined);
+});
+
+function spanishOnlyTable() {
+ return {
+ logicalName: 'contoso_pedido', schemaName: 'contoso_pedido', displayName: 'Pedido', primaryNameAttribute: 'contoso_name',
+ DisplayName: onlyIn(3082, 'Pedido'), DisplayCollectionName: onlyIn(3082, 'Pedidos'),
+ attributes: [
+ { logicalName: 'contoso_name', schemaName: 'contoso_name', attributeType: 'String', isCustomAttribute: true, DisplayName: onlyIn(3082, 'Nombre') },
+ { logicalName: 'contoso_importe', schemaName: 'contoso_importe', attributeType: 'Integer', isCustomAttribute: true, DisplayName: onlyIn(3082, 'Importe') },
+ { logicalName: 'contoso_nota', schemaName: 'contoso_nota', attributeType: 'String', isCustomAttribute: true, DisplayName: onlyIn(1033, 'Note') },
+ { logicalName: 'contoso_estado', schemaName: 'contoso_estado', attributeType: 'Picklist', isCustomAttribute: true, DisplayName: onlyIn(3082, 'Estado'),
+ optionSet: { type: 'Choice', isGlobal: false, options: [onlyIn(3082, 'Abierto'), onlyIn(3082, 'Cerrado')] } },
+ ],
+ Keys: [{ SchemaName: 'contoso_importekey', DisplayName: onlyIn(3082, 'Clave de importe'), KeyAttributes: ['contoso_importe'] }],
+ };
+}
+const asSpec = (entity) => ({ ...base(), languageCode: undefined, entities: [entity] });
+
+test('a table labelled in Spanish, downloaded in English, keeps every label in Spanish — table, plural, primary column, columns, options, key — and the spec validates', () => {
+ const e = entityFromMetadata(spanishOnlyTable(), 'contoso_pedido', { languageCode: 1033 });
+ assert.deepStrictEqual(e.displayName, { 3082: 'Pedido' });
+ assert.deepStrictEqual(e.pluralName, { 3082: 'Pedidos' });
+ assert.deepStrictEqual(e.primaryAttribute.displayName, { 3082: 'Nombre' });
+ const col = (name) => e.columns.find((c) => c.schemaName === name);
+ assert.deepStrictEqual(col('contoso_importe').displayName, { 3082: 'Importe' });
+ assert.deepStrictEqual(col('contoso_estado').displayName, { 3082: 'Estado' });
+ assert.deepStrictEqual(col('contoso_estado').options, [{ 3082: 'Abierto' }, { 3082: 'Cerrado' }]);
+ assert.strictEqual(col('contoso_estado').type, 'Choice');
+ assert.strictEqual(col('contoso_nota').displayName, 'Note', 'a label in the authoring language stays a plain string');
+ assert.deepStrictEqual(e.alternateKeys.map((k) => k.displayName), [{ 3082: 'Clave de importe' }]);
+ assert.deepStrictEqual(validateAppSpec(asSpec(e), { profile: 'plan', reconstructed: true }).errors, []);
+ assert.deepStrictEqual(validateAppSpec(asSpec(e), { profile: 'deploy' }).errors, []);
+});
+
+test('the same table downloaded in Spanish is written as plain strings — the shape an earlier download wrote — but for the English label, which keeps its language', () => {
+ const e = entityFromMetadata(spanishOnlyTable(), 'contoso_pedido', { languageCode: 3082 });
+ const old = entityFromMetadata(spanishOnlyTable(), 'contoso_pedido');
+ assert.strictEqual(e.displayName, 'Pedido');
+ assert.strictEqual(e.primaryAttribute.displayName, 'Nombre');
+ assert.deepStrictEqual(e.columns.find((c) => c.schemaName === 'contoso_estado').options, ['Abierto', 'Cerrado']);
+ assert.deepStrictEqual(e.columns.find((c) => c.schemaName === 'contoso_nota').displayName, { 1033: 'Note' });
+ assert.deepStrictEqual({ ...e, columns: e.columns.filter((c) => c.schemaName !== 'contoso_nota') }, { ...old, columns: old.columns.filter((c) => c.schemaName !== 'contoso_nota') }, 'every Spanish label is what a download wrote before');
+ assert.deepStrictEqual(validateAppSpec(asSpec(e), { profile: 'plan', reconstructed: true }).errors, []);
+});
+
+test('a display name kept in its language with no plural label to read gets the plural a rebuild derived before, in that language', () => {
+ // validateAppSpec requires a plural beside a localized display name. The text is the one a rebuild of the plain label derived
+ // (derivedPluralName); only its language is new.
+ const meta = { ...spanishOnlyTable(), DisplayCollectionName: undefined };
+ const e = entityFromMetadata(meta, 'contoso_pedido', { languageCode: 1033 });
+ assert.deepStrictEqual(e.pluralName, { 3082: 'Pedidos' });
+ assert.deepStrictEqual(validateAppSpec(asSpec(e), { profile: 'plan', reconstructed: true }).errors, []);
+ assert.strictEqual('pluralName' in entityFromMetadata(meta, 'contoso_pedido'), false, 'as before, a plain label gets none');
+});
+
+test('two options sharing one label held in another language keep that language, and the column keeps its type', () => {
+ // Two one-entry maps of one language are a duplicate the author can see, which the validator warns about as it does two plain
+ // strings: both keep their language, and the column its type.
+ const meta = spanishOnlyTable();
+ meta.attributes.find((a) => a.logicalName === 'contoso_estado').optionSet.options = [onlyIn(3082, 'Abierto'), onlyIn(3082, 'Abierto'), onlyIn(1036, 'Ferme')];
+ const languageLost = [];
+ const e = entityFromMetadata(meta, 'contoso_pedido', { languageCode: 1033, languageLost });
+ const estado = e.columns.find((c) => c.schemaName === 'contoso_estado');
+ assert.deepStrictEqual(estado.options, [{ 3082: 'Abierto' }, { 3082: 'Abierto' }, { 1036: 'Ferme' }]);
+ assert.strictEqual(estado.type, 'Choice');
+ assert.deepStrictEqual(languageLost, []);
+ const checked = validateAppSpec(asSpec(e), { profile: 'plan', reconstructed: true });
+ assert.deepStrictEqual(checked.errors, []);
+ assert.ok(checked.warnings.some((w) => /'Abierto' names BOTH options\[0\] and options\[1\]/.test(w)), JSON.stringify(checked.warnings));
+});
+
+test('an option sharing its text with an option in ANOTHER language is the only kind written as a plain string, and each is named', () => {
+ // "Open" in English on one option and in Spanish on another: as labels with their languages the validator refuses the collision (it
+ // is not visible on the line) and the column would lose its type. Those two options alone are written as the plain strings an earlier
+ // download wrote (a duplicate the validator warns about), and each that loses a language is named; the others keep theirs — the two
+ // French options sharing "Ferme" too, a duplicate in one language the validator only warns about.
+ const meta = spanishOnlyTable();
+ meta.attributes.find((a) => a.logicalName === 'contoso_estado').optionSet.options = [onlyIn(1033, 'Open'), onlyIn(3082, 'Open'), onlyIn(3082, 'Cerrado'), onlyIn(1036, 'Ferme'), onlyIn(1036, 'Ferme')];
+ const languageLost = [];
+ const e = entityFromMetadata(meta, 'contoso_pedido', { languageCode: 1033, languageLost });
+ const estado = e.columns.find((c) => c.schemaName === 'contoso_estado');
+ assert.deepStrictEqual(estado.options, ['Open', 'Open', { 3082: 'Cerrado' }, { 1036: 'Ferme' }, { 1036: 'Ferme' }]);
+ assert.strictEqual(estado.type, 'Choice');
+ assert.deepStrictEqual(languageLost, [{ table: 'contoso_pedido', column: 'contoso_estado', option: 1, label: 'Open', languageCode: 3082 }]);
+ assert.deepStrictEqual(validateAppSpec(asSpec(e), { profile: 'plan', reconstructed: true }).errors, []);
+ // A label of several languages in the collision cannot be written another way: the column is left untyped, as it was before.
+ meta.attributes.find((a) => a.logicalName === 'contoso_estado').optionSet.options = [dvLabel([[1033, 'Closed'], [3082, 'Open']]), onlyIn(1033, 'Open'), onlyIn(3082, 'Cerrado')];
+ const untypedLost = [];
+ const untyped = entityFromMetadata(meta, 'contoso_pedido', { languageCode: 1033, languageLost: untypedLost }).columns.find((c) => c.schemaName === 'contoso_estado');
+ assert.deepStrictEqual([untyped.type, untyped.options, untypedLost], [undefined, undefined, []]);
+});
+
+test('two options labelled alike as Dataverse holds them — the base language filled in, so two languages each — keep the column typed and both labels', () => {
+ // MEASURED: two options created as Spanish "Abierto" on an English-base environment are held as 1033 "Abierto" + 3082 "Abierto" each.
+ // The two labels are identical in every language they hold, a duplicate the validator warns about: the column keeps its type and
+ // options, where it used to be captured untyped — and blamed on an option set that had been read.
+ const meta = spanishOnlyTable();
+ const both = (text) => dvLabel([[1033, text], [3082, text]]);
+ meta.attributes.find((a) => a.logicalName === 'contoso_estado').optionSet.options = [both('Abierto'), both('Abierto'), both('Cerrado')];
+ const languageLost = [];
+ const labelClashes = [];
+ const e = entityFromMetadata(meta, 'contoso_pedido', { languageCode: 1033, languageLost, labelClashes });
+ const estado = e.columns.find((c) => c.schemaName === 'contoso_estado');
+ assert.strictEqual(estado.type, 'Choice');
+ assert.deepStrictEqual(estado.options, [{ 1033: 'Abierto', 3082: 'Abierto' }, { 1033: 'Abierto', 3082: 'Abierto' }, { 1033: 'Cerrado', 3082: 'Cerrado' }]);
+ assert.deepStrictEqual([languageLost, labelClashes], [[], []]);
+ const checked = validateAppSpec(asSpec(e), { profile: 'plan', reconstructed: true });
+ assert.deepStrictEqual(checked.errors, []);
+ assert.strictEqual(checked.warnings.filter((w) => /'Abierto' names BOTH options\[0\] and options\[1\]/.test(w)).length, 1, JSON.stringify(checked.warnings));
+});
+
+test('a column left untyped because one text names two of its options in different languages is reported with the clash', () => {
+ // "Abierto" is option 0 in Spanish and option 1 in English: not visible on the line, so the spec cannot hold the column's options
+ // and it is left untyped, as before — but the clash, not an unreadable option set, is what the download now reports.
+ const meta = spanishOnlyTable();
+ meta.attributes.find((a) => a.logicalName === 'contoso_estado').optionSet.options = [dvLabel([[1033, 'Open'], [3082, 'Abierto']]), dvLabel([[1033, 'Abierto'], [3082, 'Cerrado']])];
+ const labelClashes = [];
+ const estado = entityFromMetadata(meta, 'contoso_pedido', { languageCode: 1033, labelClashes }).columns.find((c) => c.schemaName === 'contoso_estado');
+ assert.deepStrictEqual([estado.type, estado.options], [undefined, undefined]);
+ assert.deepStrictEqual(labelClashes, [{ table: 'contoso_pedido', column: 'contoso_estado', clashes: [{ alias: 'Abierto', first: 0, second: 1 }] }]);
});
test('a metadata read that returned no labels falls back to the SDK display name', () => {
diff --git a/plugins/model-apps/scripts/tests/lookup-label-download.test.js b/plugins/model-apps/scripts/tests/lookup-label-download.test.js
index d4af68ff3..f58298da4 100644
--- a/plugins/model-apps/scripts/tests/lookup-label-download.test.js
+++ b/plugins/model-apps/scripts/tests/lookup-label-download.test.js
@@ -139,3 +139,63 @@ test('ADO 6691205 download: a minimal downloaded relationship validates and rebu
assert.deepStrictEqual(checked.errors.filter((e) => /lookup|relationship/i.test(e)), []);
assert.strictEqual(lookupColumnsFor(spec, 'new_ticket')[0].displayName, 'Customer');
});
+
+// A lookup label held in one language other than the download's authoring language keeps its language (a one-entry LCID map, as
+// labelFromDataverse writes every such label), so a rebuild does not store it under the language it resolves. It is left out only where
+// it was left out before AND a rebuild writes the same label in the same language: the in-app parent's downloaded label (a map as it is,
+// a plain string in the authoring language), or a stock parent's label in the authoring language, the one the build reads for it.
+const readIn = (sdk, entities, languageCode) => readRelationships(sdk, ['new_customer', 'new_ticket'], 'new', undefined, { entities, languageCode });
+const stockAgent = (lookupLabel, parentLabel = label([1033, 'User'], [1036, 'Utilisateur'])) => makeSdk({
+ m2o: { new_ticket: [rel({ SchemaName: 'new_systemuser_new_ticket', ReferencedEntity: 'systemuser', ReferencingEntity: 'new_ticket', ReferencingAttribute: 'new_agentid' })] },
+ lookups: { new_ticket: [{ LogicalName: 'new_agentid', SchemaName: 'new_AgentId', DisplayName: lookupLabel, Targets: ['systemuser'] }] },
+ parents: { systemuser: parentLabel },
+});
+
+test('a carried lookup label held only in another language than the authoring one keeps its language', async () => {
+ const { relationships } = await readIn(makeSdk(ticketToCustomer(label([3082, 'Titular']))), [customer('Customer'), ticket()], 1033);
+ assert.deepStrictEqual(relationships[0].lookup, { schemaName: 'new_CustomerId', displayName: { 3082: 'Titular' } });
+ const authoring = await readIn(makeSdk(ticketToCustomer(label([3082, 'Titular']))), [customer('Customer'), ticket()], 3082);
+ assert.deepStrictEqual(authoring.relationships[0].lookup, { schemaName: 'new_CustomerId', displayName: 'Titular' }, 'in the authoring language it is the plain string');
+});
+
+test('a lookup label is left out where a rebuild writes the same label in the same language', async () => {
+ // The parent table labelled only in Spanish is downloaded as { 3082: "Cliente" }; a lookup labelled "Cliente" in Spanish is the
+ // label a rebuild inherits from it, so it is left out, as it was when both were the plain string "Cliente".
+ const inApp = await readIn(makeSdk(ticketToCustomer(label([3082, 'Cliente']))), [customer({ 3082: 'Cliente' }), ticket()], 1033);
+ assert.deepStrictEqual(inApp.relationships[0].lookup, { schemaName: 'new_CustomerId' });
+ const plain = await readIn(makeSdk(ticketToCustomer(label([1033, 'Customer']))), [customer('Customer'), ticket()], 1033);
+ assert.deepStrictEqual(plain.relationships[0].lookup, { schemaName: 'new_CustomerId' }, 'a plain parent label is in the authoring language');
+ const several = await readIn(makeSdk(ticketToCustomer(label([1033, 'Customer'], [3082, 'Cliente']))), [customer({ 1033: 'Customer', 3082: 'Cliente' }), ticket()], 1033);
+ assert.deepStrictEqual(several.relationships[0].lookup, { schemaName: 'new_CustomerId' }, 'a map is compared language for language');
+ assert.deepStrictEqual((await readIn(stockAgent(label([1033, 'User'])), [ticket()], 1033)).relationships[0].lookup, { schemaName: 'new_AgentId' },
+ 'a stock parent\'s label in the authoring language is the one the build reads');
+ assert.deepStrictEqual((await readIn(stockAgent(label([1036, 'Utilisateur'])), [ticket()], 1036)).relationships[0].lookup, { schemaName: 'new_AgentId' },
+ 'downloaded in French, the French label is the one the build reads');
+ const oldDefault = await readIn(makeSdk(ticketToCustomer(label([3082, 'new_customer']))), [customer('Customer'), ticket()], 1033);
+ assert.deepStrictEqual(oldDefault.relationships[0].lookup, { schemaName: 'new_CustomerId' }, 'the old default is left out in any language');
+});
+
+test('a lookup label with its in-app parent\'s text in ANOTHER language is carried, in its own language', async () => {
+ // A lookup that sets no label inherits its parent's label, language and all. With the parent labelled only in French and the lookup
+ // only in English, leaving the lookup's label out would move it into French on a rebuild — the same text is not the same label.
+ const english = await readIn(makeSdk(ticketToCustomer(label([1033, 'Contact']))), [customer({ 1036: 'Contact' }), ticket()], 1033);
+ assert.deepStrictEqual(english.relationships[0].lookup, { schemaName: 'new_CustomerId', displayName: 'Contact' });
+ const french = await readIn(makeSdk(ticketToCustomer(label([1036, 'Contact']))), [customer('Contact'), ticket()], 1033);
+ assert.deepStrictEqual(french.relationships[0].lookup, { schemaName: 'new_CustomerId', displayName: { 1036: 'Contact' } });
+ const fewer = await readIn(makeSdk(ticketToCustomer(label([3082, 'Cliente']))), [customer({ 1033: 'Customer', 3082: 'Cliente' }), ticket()], 1033);
+ assert.deepStrictEqual(fewer.relationships[0].lookup, { schemaName: 'new_CustomerId', displayName: { 3082: 'Cliente' } }, 'one of the parent\'s languages is not all of them, as before');
+});
+
+test('a lookup to a stock table is compared with the label the build reads for it in the authoring language, not in the lookup\'s own', async () => {
+ // The build reads a stock parent's label in its authoring language and writes it in that language (lib/lookup-labels.js
+ // makeTableLabelReader), so a lookup labelled in another language is not what a rebuild writes, even where the parent's label in that
+ // language has the same text.
+ const french = await readIn(stockAgent(label([1036, 'Utilisateur'])), [ticket()], 1033);
+ assert.deepStrictEqual(french.relationships[0].lookup, { schemaName: 'new_AgentId', displayName: { 1036: 'Utilisateur' } });
+ const english = await readIn(stockAgent(label([1033, 'User'])), [ticket()], 1036);
+ assert.deepStrictEqual(english.relationships[0].lookup, { schemaName: 'new_AgentId', displayName: { 1033: 'User' } });
+ // A stock parent with no label in the authoring language: the build would write its English label in Spanish. The label is carried,
+ // as it was before, rather than left out on a guess about what another environment's table is called.
+ const noSpanish = await readIn(stockAgent(label([3082, 'User']), label([1033, 'User'])), [ticket()], 3082);
+ assert.deepStrictEqual(noSpanish.relationships[0].lookup, { schemaName: 'new_AgentId', displayName: 'User' });
+});
diff --git a/plugins/model-apps/scripts/tests/lookup-metadata-real-bundle.test.js b/plugins/model-apps/scripts/tests/lookup-metadata-real-bundle.test.js
new file mode 100644
index 000000000..579402d4a
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/lookup-metadata-real-bundle.test.js
@@ -0,0 +1,150 @@
+'use strict';
+// get-lookup-metadata.js over the REAL vendored SDK (lib/maker-sdk.js, the throwaway workspace) and a stub HTTP transport answering the
+// raw Web API shapes: the SDK's own table metadata read (the main read, the attribute casts — LookupAttributeMetadata carries each
+// lookup's Targets — and its own relationship reads), then the plugin's lookup-details ManyToOne read, paged with an absolute
+// @odata.nextLink. A mock of the SDK would keep passing against a bundle whose projection no longer carried `targets`.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const path = require('node:path');
+const { readLookups } = require(path.join(__dirname, '..', 'get-lookup-metadata.js'));
+const { createAzHttpClient } = require('../lib/sdk-http-client.js');
+
+const ENV = 'https://contoso.crm.dynamics.com';
+const label = (text) => ({ UserLocalizedLabel: { Label: text }, LocalizedLabels: [{ Label: text, LanguageCode: 1033 }] });
+const ATTRIBUTES = [
+ { LogicalName: 'opportunityid', AttributeType: 'Uniqueidentifier', AttributeTypeName: { Value: 'UniqueidentifierType' } },
+ { LogicalName: 'name', AttributeType: 'String', AttributeTypeName: { Value: 'StringType' } },
+ { LogicalName: 'customerid', AttributeType: 'Customer', AttributeTypeName: { Value: 'CustomerType' } },
+ { LogicalName: 'ownerid', AttributeType: 'Owner', AttributeTypeName: { Value: 'OwnerType' } },
+].map((a) => ({ DisplayName: label(a.LogicalName), Description: label(''), IsCustomAttribute: false, IsValidForUpdate: true, IsValidForRead: true, AttributeOf: null, ...a }));
+const TARGETS = [{ LogicalName: 'customerid', Targets: ['account', 'contact'] }, { LogicalName: 'ownerid', Targets: ['systemuser', 'team'] }];
+const DETAILS = 'SchemaName,ReferencedEntity,ReferencingAttribute,ReferencedAttribute,ReferencingEntityNavigationPropertyName';
+const NEXT = `${ENV}/api/data/v9.2/EntityDefinitions(LogicalName='opportunity')/ManyToOneRelationships?$select=${DETAILS}&$skiptoken=page2`;
+// How Dataverse answers a read of a table the environment does not have (measured live, for the SDK's own read of the table, the first request
+// made for one: `GET …/api/data/v9.0/EntityDefinitions(LogicalName='opportunity')?$select=…&$expand=Attributes(…)`).
+const NOT_FOUND = (table) => ({ status: 404, headers: {}, body: { error: { code: '0x80060888', message: `EntityMetadata With Id = LogicalName='${table}' does not exist.` } } });
+
+// `tableRead` and `firstPage`, when given, answer opportunity's own metadata read and the first page of its lookup-details read.
+function transport({ main = (body) => body, tableRead = null, lookupTargets = TARGETS, firstPage = null, secondPage = { status: 200, body: { value: [
+ { SchemaName: 'opportunity_customer_contacts', ReferencedEntity: 'contact', ReferencingAttribute: 'customerid', ReferencedAttribute: 'contactid', ReferencingEntityNavigationPropertyName: 'customerid_contact' },
+ { SchemaName: 'owner_opportunitys', ReferencedEntity: 'owner', ReferencingAttribute: 'ownerid', ReferencedAttribute: 'ownerid', ReferencingEntityNavigationPropertyName: 'ownerid' },
+] } } } = {}) {
+ const reads = [];
+ const answer = (url) => {
+ const u = decodeURIComponent(url);
+ reads.push(u);
+ if (u === decodeURIComponent(NEXT)) return secondPage;
+ const route = /\/api\/data\/v9\.\d\/EntityDefinitions\(LogicalName='([^']+)'\)(\/[^?]*)?(?:\?(.*))?$/.exec(u);
+ if (!route) return { status: 404, headers: {}, body: { error: { code: '0x80060888', message: `no route for ${u}` } } };
+ const [, table, sub = '', query = ''] = route;
+ if (table !== 'opportunity') return NOT_FOUND(table);
+ if (sub === '') {
+ return tableRead || { status: 200, headers: {}, body: main({
+ LogicalName: 'opportunity', SchemaName: 'Opportunity', DisplayName: label('Opportunity'), Description: label(''), EntitySetName: 'opportunities',
+ IsCustomEntity: false, PrimaryNameAttribute: 'name', PrimaryIdAttribute: 'opportunityid', PrimaryImageAttribute: null, Attributes: ATTRIBUTES,
+ }) };
+ }
+ if (sub === '/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata') return lookupTargets instanceof Object && !Array.isArray(lookupTargets) ? lookupTargets : { status: 200, headers: {}, body: { value: lookupTargets } };
+ if (sub === '/ManyToOneRelationships' && query.includes('ReferencingEntityNavigationPropertyName')) {
+ return firstPage || { status: 200, headers: {}, body: { value: [
+ { SchemaName: 'opportunity_customer_accounts', ReferencedEntity: 'account', ReferencingAttribute: 'customerid', ReferencedAttribute: 'accountid', ReferencingEntityNavigationPropertyName: 'customerid_account' },
+ ], '@odata.nextLink': NEXT } };
+ }
+ return { status: 200, headers: {}, body: { value: [] } };
+ };
+ return {
+ reads,
+ get: async (url) => answer(url),
+ post: async () => ({ status: 204, headers: {}, body: {} }),
+ patch: async () => ({ status: 204, headers: {}, body: {} }),
+ delete: async () => ({ status: 204, headers: {}, body: {} }),
+ };
+}
+
+test('REAL BUNDLE: the complete targets from the SDK\'s metadata read, the concrete paths from every page of the lookup-details read', async () => {
+ const http = transport();
+ const answer = await readLookups(ENV, { tables: ['opportunity'] }, http);
+ assert.equal(answer.ok, true);
+ const [table] = answer.tables;
+ assert.equal(table.primaryIdAttribute, 'opportunityid');
+ assert.equal(table.primaryNameAttribute, 'name');
+ const customer = table.lookups.find((lookup) => lookup.column === 'customerid');
+ assert.deepEqual(customer.targets, ['account', 'contact']);
+ assert.deepEqual(customer.paths.map((entry) => [entry.target, entry.navigationProperty, entry.referencedKey]), [['account', 'customerid_account', 'accountid'], ['contact', 'customerid_contact', 'contactid']]);
+ const owner = table.lookups.find((lookup) => lookup.column === 'ownerid');
+ assert.deepEqual(owner.targets, ['systemuser', 'team']);
+ assert.deepEqual(owner.paths, []);
+ assert.deepEqual(owner.sharedPaths.map((entry) => entry.navigationProperty), ['ownerid']);
+ assert.ok(http.reads.includes(decodeURIComponent(NEXT)), 'the second page was followed, through the absolute link');
+ assert.ok(!http.reads.some((u) => /ManyToOneRelationships/.test(u) && /DisplayName|LocalizedLabels/.test(u.split('?')[1] || '')), 'the relationship reads are label-free');
+});
+
+test('REAL BUNDLE: an incomplete main metadata answer fails the whole discovery, never a smaller lookup inventory', async () => {
+ const drop = (key) => (body) => { const copy = { ...body }; delete copy[key]; return copy; };
+ for (const [label, main] of [
+ ['no Attributes expansion, which the SDK reads as []', drop('Attributes')],
+ ['no PrimaryIdAttribute, which the SDK reads as \'\'', drop('PrimaryIdAttribute')],
+ ['a first page of attributes with its continuation, which the SDK does not follow', (body) => ({ ...body,
+ Attributes: ATTRIBUTES.filter((entry) => !['customerid', 'ownerid'].includes(entry.LogicalName)),
+ '[email protected]': `${ENV}/api/data/v9.2/EntityDefinitions(LogicalName='opportunity')/Attributes?$skiptoken=rest` })],
+ ]) {
+ const http = transport({ main });
+ await assert.rejects(readLookups(ENV, { tables: ['opportunity'] }, http), (err) => err.code === 'LOOKUP_METADATA_INCOMPLETE', label);
+ }
+});
+
+test('REAL BUNDLE: a relationship column the read does not classify, or classifies against its Targets, fails the whole discovery', async () => {
+ const retype = (change) => (body) => ({ ...body, Attributes: ATTRIBUTES.map((entry) => (entry.LogicalName === 'customerid' ? change({ ...entry }) : entry)) });
+ const untyped = retype((entry) => { delete entry.AttributeType; return entry; });
+ for (const [label, options] of [
+ ['the Customer attribute without its AttributeType, which the SDK reads as Unknown', { main: untyped }],
+ ['the same, and the Targets cast silent about it', { main: untyped, lookupTargets: TARGETS.filter((entry) => entry.LogicalName !== 'customerid') }],
+ ['the Customer attribute typed String while the cast states its Targets', { main: retype((entry) => ({ ...entry, AttributeType: 'String' })) }],
+ ]) {
+ await assert.rejects(readLookups(ENV, { tables: ['opportunity'] }, transport(options)), (err) => err.code === 'LOOKUP_METADATA_INCOMPLETE', label);
+ }
+});
+
+test('REAL BUNDLE: a refused targets read, a refused second page, or a missing table fails the whole discovery', async () => {
+ for (const [label, options, tables, code] of [
+ ['the SDK\'s targets read refused', { lookupTargets: { status: 503, headers: {}, body: { error: { code: '0x80040216', message: 'Service unavailable.' } } } }, ['opportunity'], 'LOOKUP_METADATA_INCOMPLETE'],
+ ['the second relationship page refused', { secondPage: { status: 503, headers: {}, body: { error: { code: '0x80040216', message: 'Service unavailable.' } } } }, ['opportunity'], 'LOOKUP_RELATIONSHIPS_UNREADABLE'],
+ ['a table the environment does not have', {}, ['nosuch'], 'LOOKUP_TABLE_NOT_FOUND'],
+ ]) {
+ await assert.rejects(readLookups(ENV, { tables }, transport(options)), (err) => err.code === code, label);
+ }
+});
+
+// The SDK's own read of a table is the first request made for it, so a table the environment does not have fails THERE — before the lookup-details
+// read could say so — and the SDK throws the 404 as its ConnectionError (CONNECTION_ERROR, statusCode 404), which named a sign-in problem, not the table.
+test('REAL BUNDLE: a table the environment does not have is LOOKUP_TABLE_NOT_FOUND — the 404 of its own metadata read — with no list, and nothing read after it', async () => {
+ for (const [label, tables] of [['the one table named', ['nosuch']], ['the second table named, after the first was read whole', ['opportunity', 'nosuch']]]) {
+ const http = transport();
+ await assert.rejects(readLookups(ENV, { tables }, http), (err) => {
+ assert.equal(err.code, 'LOOKUP_TABLE_NOT_FOUND', label);
+ assert.match(err.message, /^nosuch: the environment has no table with this logical name/, label);
+ assert.match(err.message, /HTTP 404 from .*EntityMetadata With Id = LogicalName='nosuch' does not exist\.$/, `${label}: the SDK's words, the platform's message in them`);
+ return true;
+ });
+ const own = http.reads.filter((u) => /EntityDefinitions\(LogicalName='nosuch'\)/.test(u));
+ assert.deepEqual(own.map((u) => /EntityDefinitions\(LogicalName='nosuch'\)\?\$select=LogicalName,/.test(u)), [true], `${label}: the table's own read, once`);
+ assert.equal(http.reads.at(-1), own[0], `${label}: and nothing read after it`);
+ }
+});
+
+test('REAL BUNDLE: any other failure of a table\'s own read keeps the SDK\'s code — another status, or no token — and a 404 below the table is no missing table', async () => {
+ for (const status of [400, 403, 500, 503]) {
+ const http = transport({ tableRead: { status, headers: {}, body: { error: { code: '0x80040216', message: 'Refused.' } } } });
+ await assert.rejects(readLookups(ENV, { tables: ['opportunity'] }, http), (err) => err.code === 'CONNECTION_ERROR' && err.statusCode === status, `HTTP ${status}`);
+ assert.equal(http.reads.length, 1, `HTTP ${status}: nothing read after it`);
+ }
+ // No token: the real client refuses before it sends anything, and the SDK names that a transport failure (statusCode 0).
+ let sent = 0;
+ const noToken = createAzHttpClient(ENV, { getToken: () => null, request: async () => { sent += 1; throw new Error('nothing may be sent without a token'); } });
+ await assert.rejects(readLookups(ENV, { tables: ['opportunity'] }, noToken), (err) => err.code === 'CONNECTION_ERROR' && err.statusCode === 0, 'no token');
+ assert.equal(sent, 0, 'no token: nothing was sent');
+ // A 404 of a read BELOW the table — the SDK's targets cast — is a column read that failed: the answer is incomplete, the table is there.
+ await assert.rejects(readLookups(ENV, { tables: ['opportunity'] }, transport({ lookupTargets: NOT_FOUND('opportunity') })), (err) => err.code === 'LOOKUP_METADATA_INCOMPLETE', 'the targets cast');
+ // The lookup-details read's own 404 for the table stays LOOKUP_TABLE_NOT_FOUND, as it was.
+ await assert.rejects(readLookups(ENV, { tables: ['opportunity'] }, transport({ firstPage: NOT_FOUND('opportunity') })), (err) => err.code === 'LOOKUP_TABLE_NOT_FOUND', 'the lookup-details read');
+});
diff --git a/plugins/model-apps/scripts/tests/lookup-metadata.test.js b/plugins/model-apps/scripts/tests/lookup-metadata.test.js
new file mode 100644
index 000000000..3a750d4cb
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/lookup-metadata.test.js
@@ -0,0 +1,276 @@
+'use strict';
+// Lookup discovery (lib/lookup-metadata.js and scripts/get-lookup-metadata.js): each lookup's complete target set from the SDK's
+// table metadata, the concrete paths from the lookup-details relationship read, the shared paths kept apart (Owner's `ownerid`),
+// and every incomplete or failed read a failure of the whole — with the SDK stubbed. The real bundle is driven in
+// lookup-metadata-real-bundle.test.js.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const path = require('node:path');
+const { loadCli } = require('./helpers/cli-harness.js');
+const realAuth = require('../lib/dataverse-auth.js');
+const { withThrowawaySdk } = require('../lib/throwaway-sdk.js');
+const { readLookupMetadata, tableLookups } = require('../lib/lookup-metadata.js');
+
+const SCRIPT = path.resolve(__dirname, '..', 'get-lookup-metadata.js');
+const ENV = 'https://contoso.crm.dynamics.com';
+
+const attribute = (logicalName, attributeType, targets) => ({ logicalName, attributeType, ...(targets ? { targets } : {}) });
+const OPPORTUNITY = {
+ logicalName: 'opportunity',
+ primaryIdAttribute: 'opportunityid',
+ primaryNameAttribute: 'name',
+ attributes: [
+ attribute('opportunityid', 'Uniqueidentifier'),
+ attribute('name', 'String'),
+ attribute('customerid', 'Customer', ['account', 'contact']),
+ attribute('parentaccountid', 'Lookup', ['account']),
+ attribute('ownerid', 'Owner', ['systemuser', 'team']),
+ attribute('owneridtype', 'EntityName'),
+ ],
+};
+const relationship = (schemaName, referencedEntity, referencingAttribute, referencedAttribute, navigationProperty) => (
+ { schemaName, type: 'OneToMany', referencedEntity, referencingEntity: 'opportunity', referencingAttribute, referencedAttribute, navigationProperty });
+const ROWS = [
+ relationship('opportunity_customer_accounts', 'account', 'customerid', 'accountid', 'customerid_account'),
+ relationship('opportunity_customer_contacts', 'contact', 'customerid', 'contactid', 'customerid_contact'),
+ relationship('opportunity_parent_account', 'account', 'parentaccountid', 'accountid', 'parentaccountid'),
+ relationship('owner_opportunitys', 'owner', 'ownerid', 'ownerid', 'ownerid'),
+];
+
+test('a Customer lookup has a concrete path per target; Owner\'s abstract ownerid is a shared path, never a target discriminator', () => {
+ const table = tableLookups(OPPORTUNITY, ROWS);
+ assert.equal(table.logicalName, 'opportunity');
+ assert.equal(table.primaryIdAttribute, 'opportunityid');
+ assert.equal(table.primaryNameAttribute, 'name');
+ assert.deepEqual(table.lookups.map((lookup) => lookup.column), ['customerid', 'ownerid', 'parentaccountid'], 'lookups only, by column');
+ const [customer, owner, parent] = table.lookups;
+ assert.deepEqual(customer, {
+ column: 'customerid', readProperty: '_customerid_value', attributeType: 'Customer', targets: ['account', 'contact'],
+ paths: [
+ { target: 'account', navigationProperty: 'customerid_account', referencedKey: 'accountid', relationship: 'opportunity_customer_accounts' },
+ { target: 'contact', navigationProperty: 'customerid_contact', referencedKey: 'contactid', relationship: 'opportunity_customer_contacts' },
+ ],
+ sharedPaths: [],
+ });
+ assert.deepEqual(owner.targets, ['systemuser', 'team'], 'the complete target set, from the metadata — not from a relationship');
+ assert.deepEqual(owner.paths, [], 'no ownerid_systemuser or ownerid_team is manufactured');
+ assert.deepEqual(owner.sharedPaths, [{ referencedEntity: 'owner', navigationProperty: 'ownerid', referencedKey: 'ownerid', relationship: 'owner_opportunitys' }]);
+ assert.deepEqual(parent.paths, [{ target: 'account', navigationProperty: 'parentaccountid', referencedKey: 'accountid', relationship: 'opportunity_parent_account' }], 'a single-target lookup');
+});
+
+test('a navigation property two targets share, or a target reached twice, is shared — never a concrete path', () => {
+ const shared = tableLookups(OPPORTUNITY, [
+ relationship('a', 'account', 'customerid', 'accountid', 'customerid'),
+ relationship('b', 'contact', 'customerid', 'contactid', 'customerid'),
+ ]).lookups[0];
+ assert.deepEqual(shared.paths, []);
+ assert.equal(shared.sharedPaths.length, 2);
+ const twice = tableLookups(OPPORTUNITY, [
+ relationship('a', 'account', 'customerid', 'accountid', 'customerid_account'),
+ relationship('a2', 'account', 'customerid', 'accountid', 'customerid_account2'),
+ relationship('b', 'contact', 'customerid', 'contactid', 'customerid_contact'),
+ ]).lookups[0];
+ assert.deepEqual(twice.paths.map((entry) => entry.target), ['contact']);
+ assert.deepEqual(twice.sharedPaths.map((entry) => entry.navigationProperty), ['customerid_account', 'customerid_account2']);
+});
+
+test('a lookup whose targets the metadata did not state fails the read — it is never a lookup with no targets', () => {
+ for (const targets of [undefined, [], [''], [7], ['sales orders']]) {
+ const metadata = { ...OPPORTUNITY, attributes: OPPORTUNITY.attributes.map((entry) => (entry.logicalName === 'customerid' ? attribute('customerid', 'Customer', targets) : entry)) };
+ assert.throws(() => tableLookups(metadata, ROWS), (err) => err.code === 'LOOKUP_METADATA_INCOMPLETE' && /customerid/.test(err.message), JSON.stringify(targets));
+ }
+});
+
+test('an attribute inventory that cannot be complete fails the read: no primary id, or a relationship column it does not list', () => {
+ const without = (column) => ({ ...OPPORTUNITY, attributes: OPPORTUNITY.attributes.filter((entry) => entry.logicalName !== column) });
+ for (const [label, metadata] of [
+ ['an absent attribute inventory, which the SDK reads as []', { ...OPPORTUNITY, attributes: [] }],
+ ['no primary id column stated', { ...OPPORTUNITY, primaryIdAttribute: '' }],
+ ['a primary id column the inventory does not list', without('opportunityid')],
+ ['a Customer lookup its relationships name but the inventory does not list', without('customerid')],
+ ['an Owner lookup its relationship names but the inventory does not list', without('ownerid')],
+ ]) {
+ assert.throws(() => tableLookups(metadata, ROWS), (err) => err.code === 'LOOKUP_METADATA_INCOMPLETE', label);
+ }
+ // A relationship column the read does not classify, or classifies against its Targets, is incomplete — never "not a lookup".
+ const typed = (column, attributeType, targets) => ({ ...OPPORTUNITY, attributes: OPPORTUNITY.attributes
+ .map((entry) => (entry.logicalName === column ? { logicalName: column, ...(attributeType === undefined ? {} : { attributeType }), ...(targets ? { targets } : {}) } : entry)) });
+ for (const [label, metadata] of [
+ ['a Customer lookup whose type the read did not state (the SDK says Unknown)', typed('customerid', 'Unknown', ['account', 'contact'])],
+ ['a lookup with no type at all', typed('customerid', undefined, ['account', 'contact'])],
+ ['an unclassified column with no Targets either', typed('customerid', 'Unknown')],
+ ['a type that is not a name', typed('parentaccountid', 7, ['account'])],
+ ['a String column with lookup targets', typed('customerid', 'String', ['account', 'contact'])],
+ ]) {
+ assert.throws(() => tableLookups(metadata, ROWS), (err) => err.code === 'LOOKUP_METADATA_INCOMPLETE', label);
+ }
+ // A known non-lookup relationship column without Targets, and a party list with its Targets, stay out of the lookups as before.
+ const withExtra = { ...OPPORTUNITY, attributes: [...OPPORTUNITY.attributes, attribute('requiredattendees', 'PartyList', ['contact'])] };
+ const extraRows = [...ROWS, relationship('opportunity_owneridtype', 'account', 'owneridtype', 'accountid', 'owneridtype_account'),
+ relationship('opportunity_attendees', 'contact', 'requiredattendees', 'contactid', 'requiredattendees_contact')];
+ assert.deepEqual(tableLookups(withExtra, extraRows).lookups.map((lookup) => lookup.column), ['customerid', 'ownerid', 'parentaccountid']);
+ // Neighbour: a table with no lookups and no relationships is a complete, empty answer.
+ assert.deepEqual(tableLookups({ ...OPPORTUNITY, attributes: [attribute('opportunityid', 'Uniqueidentifier'), attribute('name', 'String')] }, []).lookups, []);
+});
+
+function fakeSdk({ metadata = { opportunity: OPPORTUNITY }, pages } = {}) {
+ const reads = [];
+ const detailPath = (table) => `/EntityDefinitions(LogicalName='${table}')/ManyToOneRelationships?$select=SchemaName,ReferencedEntity,ReferencingAttribute,ReferencedAttribute,ReferencingEntityNavigationPropertyName`;
+ const raw = (row) => ({ SchemaName: row.schemaName, ReferencedEntity: row.referencedEntity, ReferencingAttribute: row.referencingAttribute, ReferencedAttribute: row.referencedAttribute, ReferencingEntityNavigationPropertyName: row.navigationProperty });
+ const answers = pages || { [detailPath('opportunity')]: { status: 200, body: { value: ROWS.map(raw) } } };
+ return {
+ reads,
+ initWorkspace: async () => { reads.push('initWorkspace'); },
+ fetchEntityMetadata: async (table) => {
+ reads.push(`metadata ${table}`);
+ if (metadata[table] instanceof Error) throw metadata[table];
+ return metadata[table];
+ },
+ dataverse: {
+ get: async (p) => {
+ reads.push(p);
+ return answers[p] || { status: 404, body: { error: { code: '0x80060888', message: `EntityMetadata With Id = LogicalName='${p}' does not exist.` } } };
+ },
+ },
+ };
+}
+
+test('readLookupMetadata composes the SDK metadata with the lookup-details read, table by table', async () => {
+ const sdk = fakeSdk();
+ const answer = await readLookupMetadata(sdk, ['opportunity']);
+ assert.equal(answer.ok, true);
+ assert.deepEqual(answer.tables.map((table) => table.logicalName), ['opportunity']);
+ assert.deepEqual(sdk.reads[0], 'metadata opportunity');
+ assert.match(sdk.reads[1], /ManyToOneRelationships\?\$select=SchemaName,ReferencedEntity,ReferencingAttribute,ReferencedAttribute,ReferencingEntityNavigationPropertyName$/);
+});
+
+test('any failed or incomplete part fails the whole discovery, with a code', async () => {
+ const sdkError = Object.assign(new Error('Could not find entity nosuch'), { code: 'NOT_FOUND' });
+ for (const [label, sdk, tables, code] of [
+ ['no table named', fakeSdk(), [], 'LOOKUP_TABLES_REQUIRED'],
+ ['a name that is not a logical name', fakeSdk(), ['Opportunities!'], 'LOOKUP_TABLE_NAME_INVALID'],
+ ['the SDK cannot read the table', fakeSdk({ metadata: { nosuch: sdkError } }), ['nosuch'], 'NOT_FOUND'],
+ ['metadata for another table', fakeSdk({ metadata: { opportunity: { ...OPPORTUNITY, logicalName: 'quote' } } }), ['opportunity'], 'LOOKUP_METADATA_INCOMPLETE'],
+ ['the relationship read finds no table', fakeSdk({ pages: {} }), ['opportunity'], 'LOOKUP_TABLE_NOT_FOUND'],
+ ['a refused relationship read', fakeSdk({ pages: { "/EntityDefinitions(LogicalName='opportunity')/ManyToOneRelationships?$select=SchemaName,ReferencedEntity,ReferencingAttribute,ReferencedAttribute,ReferencingEntityNavigationPropertyName": { status: 429, body: { error: { code: '0x80072322', message: 'Too many requests.' } } } } }), ['opportunity'], 'LOOKUP_RELATIONSHIPS_UNREADABLE'],
+ ['a second table that fails after the first succeeded', fakeSdk({ metadata: { opportunity: OPPORTUNITY, quote: sdkError } }), ['opportunity', 'quote'], 'NOT_FOUND'],
+ ]) {
+ await assert.rejects(readLookupMetadata(sdk, tables), (err) => err.code === code, label);
+ }
+});
+
+// The SDK's ConnectionError, as its own read of a table throws it (the real bundle is driven in lookup-metadata-real-bundle.test.js):
+// code CONNECTION_ERROR, statusCode the answer's (0 for a transport failure, such as no token), url the request's, and the message
+// `HTTP 404 from <url>: EntityMetadata With Id = LogicalName='nosuch' does not exist.`
+const tableRead = (table) => `${ENV}/api/data/v9.0/EntityDefinitions(LogicalName='${table}')?$select=LogicalName,PrimaryIdAttribute&$expand=Attributes($select=LogicalName)`;
+const sdkHttpError = (statusCode, url, words = 'Refused.') => Object.assign(new Error(statusCode ? `HTTP ${statusCode} from ${url}: ${words}` : `Transport failure reaching ${url}: ${words}`), { code: 'CONNECTION_ERROR', statusCode, url });
+
+test('a 404 of the SDK\'s own read of a table names the table missing; every other SDK failure keeps its own code', async () => {
+ const missing = sdkHttpError(404, tableRead('nosuch'), "EntityMetadata With Id = LogicalName='nosuch' does not exist.");
+ for (const [label, metadata, tables, code] of [
+ ['the table\'s own read answers 404', { nosuch: missing }, ['nosuch'], 'LOOKUP_TABLE_NOT_FOUND'],
+ ['the second table\'s own read answers 404, after the first was read', { opportunity: OPPORTUNITY, nosuch: missing }, ['opportunity', 'nosuch'], 'LOOKUP_TABLE_NOT_FOUND'],
+ ['the table\'s own read refused with another status', { opportunity: sdkHttpError(403, tableRead('opportunity')) }, ['opportunity'], 'CONNECTION_ERROR'],
+ ['no token, so nothing was sent', { opportunity: sdkHttpError(0, tableRead('opportunity'), "Failed to get Azure CLI token. Run 'az login' first.") }, ['opportunity'], 'CONNECTION_ERROR'],
+ ['a 404 of a read below the table', { opportunity: sdkHttpError(404, `${ENV}/api/data/v9.0/EntityDefinitions(LogicalName='opportunity')/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata?$select=LogicalName,Targets`) }, ['opportunity'], 'CONNECTION_ERROR'],
+ ['a 404 of another table\'s read', { opportunity: sdkHttpError(404, tableRead('account')) }, ['opportunity'], 'CONNECTION_ERROR'],
+ ]) {
+ const sdk = fakeSdk({ metadata });
+ await assert.rejects(readLookupMetadata(sdk, tables), (err) => err.code === code, label);
+ assert.equal(sdk.reads.at(-1), `metadata ${tables.at(-1)}`, `${label}: nothing is read after the failed table read`);
+ }
+ await assert.rejects(readLookupMetadata(fakeSdk({ metadata: { nosuch: missing } }), ['nosuch']),
+ (err) => err.message === `nosuch: the environment has no table with this logical name — ${missing.message}`);
+});
+
+// --- the command line, through main(), with the SDK stubbed (lib/throwaway-sdk.js's own lifecycle) ---------------------------------
+
+async function run(argv, sdk = fakeSdk()) {
+ const events = [];
+ const emitted = [];
+ const requires = {
+ './lib/dataverse-auth.js': {
+ ...realAuth,
+ emitResult: (ok, payload, options) => {
+ emitted.push({ ok, payload, options });
+ const exit = new Error(`process.exit(${ok ? 0 : 1})`);
+ exit.exitCode = ok ? 0 : 1;
+ throw exit;
+ },
+ },
+ './lib/throwaway-sdk.js': {
+ withThrowawaySdk: (options, runWith) => withThrowawaySdk({
+ ...options,
+ deps: {
+ createAzHttpClient: (env) => { events.push({ type: 'client', env }); return { marker: 'az-client' }; },
+ makerSdk: {
+ createNodeWorkspaceStorage: (dir) => ({ dir }),
+ createMakerSdk: (cfg) => { events.push({ type: 'sdk', cfg }); return sdk; },
+ },
+ },
+ }, runWith),
+ },
+ };
+ const cli = loadCli(SCRIPT, { requires, argv });
+ let exitCode = 0;
+ try {
+ await cli.main();
+ } catch (err) {
+ if (typeof err.exitCode !== 'number') throw err;
+ exitCode = err.exitCode;
+ }
+ const made = events.find((e) => e.type === 'sdk');
+ return { events, emitted, exitCode, stderr: cli.stderrText(), stdout: cli.stdoutText(), workspaceDir: made && made.cfg.workspaceStorage.dir };
+}
+
+test('a usage error prints nothing on stdout, names the flag and the usage on stderr, and reads nothing', async () => {
+ for (const [argv, message] of [
+ [[], /--env is required/],
+ [['--env', ENV], /--tables is required/],
+ [['--env', ENV, '--table', 'opportunity'], /unknown flag\(s\): --table \(did you mean --tables\?\)/],
+ [['--env', ENV, '--tables'], /--tables requires a value/],
+ [['--env', ENV, '--tables', ' , '], /--tables ' , ' names no table/],
+ [['--env', ENV, '--tables', 'opportunity,Sales Orders'], /'sales orders' is not a table logical name/],
+ [['--env', 'https://example.com', '--tables', 'opportunity'], /is not a Dataverse environment URL/],
+ [['--env', ENV, '--tables', 'opportunity', 'extra'], /unexpected argument 'extra'/],
+ ]) {
+ const r = await run(argv);
+ assert.equal(r.exitCode, 1, argv.join(' '));
+ assert.equal(r.stdout, '', argv.join(' '));
+ assert.match(r.stderr, message, argv.join(' '));
+ assert.match(r.stderr, /Usage: node scripts\/get-lookup-metadata\.js --env <envUrl> --tables '<table1>,<table2>'/);
+ assert.deepEqual(r.events, [], `${argv.join(' ')}: no client, no SDK`);
+ }
+});
+
+test('a complete read prints one ASCII JSON answer; a failed one exits 1 with its code and no tables; the workspace is removed', async () => {
+ const fs = require('node:fs');
+ const ok = await run(['--env', ENV, '--tables', ' Opportunity , opportunity ']);
+ assert.equal(ok.exitCode, 0);
+ assert.equal(ok.emitted.length, 1);
+ assert.deepEqual(ok.emitted[0].options, { ascii: true });
+ assert.equal(ok.emitted[0].payload.ok, true);
+ assert.deepEqual(ok.emitted[0].payload.tables.map((table) => table.logicalName), ['opportunity'], 'one read per table, a name given twice once');
+ assert.equal(fs.existsSync(ok.workspaceDir), false);
+ const failed = await run(['--env', ENV, '--tables', 'opportunity'], fakeSdk({ pages: {} }));
+ assert.equal(failed.exitCode, 1);
+ assert.deepEqual(Object.keys(failed.emitted[0].payload).sort(), ['code', 'error', 'ok']);
+ assert.equal(failed.emitted[0].payload.code, 'LOOKUP_TABLE_NOT_FOUND');
+ assert.equal(fs.existsSync(failed.workspaceDir), false);
+});
+
+test('a table the SDK\'s own read finds missing prints LOOKUP_TABLE_NOT_FOUND with no tables and exits 1; another refusal of that read prints CONNECTION_ERROR', async () => {
+ const fs = require('node:fs');
+ const missing = await run(['--env', ENV, '--tables', 'opportunity'], fakeSdk({ metadata: { opportunity: sdkHttpError(404, tableRead('opportunity'), "EntityMetadata With Id = LogicalName='opportunity' does not exist.") } }));
+ assert.equal(missing.exitCode, 1);
+ assert.equal(missing.emitted.length, 1);
+ assert.deepEqual(missing.emitted[0].options, { ascii: true });
+ assert.deepEqual(Object.keys(missing.emitted[0].payload).sort(), ['code', 'error', 'ok']);
+ assert.equal(missing.emitted[0].payload.ok, false);
+ assert.equal(missing.emitted[0].payload.code, 'LOOKUP_TABLE_NOT_FOUND');
+ assert.match(missing.emitted[0].payload.error, /^opportunity: the environment has no table with this logical name — HTTP 404 from https:\/\/contoso\.crm\.dynamics\.com\/api\/data\/v9\.0\/EntityDefinitions\(LogicalName='opportunity'\)\?/);
+ assert.equal(fs.existsSync(missing.workspaceDir), false);
+ const refused = await run(['--env', ENV, '--tables', 'opportunity'], fakeSdk({ metadata: { opportunity: sdkHttpError(503, tableRead('opportunity'), 'Service unavailable.') } }));
+ assert.equal(refused.exitCode, 1);
+ assert.deepEqual(refused.emitted[0].payload, { ok: false, error: `HTTP 503 from ${tableRead('opportunity')}: Service unavailable.`, code: 'CONNECTION_ERROR' });
+});
diff --git a/plugins/model-apps/scripts/tests/lookup-reference.test.js b/plugins/model-apps/scripts/tests/lookup-reference.test.js
new file mode 100644
index 000000000..2fe07233f
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/lookup-reference.test.js
@@ -0,0 +1,131 @@
+'use strict';
+// The canonical lookup normalizer as references/rules.md publishes it ("Lookup references"), run as published: the block is
+// transpiled with the TypeScript the plugin vendors (a transpile, not a type check) and its function called on a table of rows —
+// the measured shapes (a qualified Customer and user-owned Owner value with a matching annotation), the shapes another player may
+// send (a bare GUID with or without the annotation), and the inputs that must not resolve (contradictory or foreign evidence,
+// malformed ids, a plural entity set, a missing field). The rows below are synthetic, not captured from an environment.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const { loadVendoredTypeScript } = require('../lib/typescript-compiler.js');
+
+const RULES = fs.readFileSync(path.join(__dirname, '..', '..', 'references', 'rules.md'), 'utf8').replace(/\r\n/g, '\n');
+
+// The section from its heading to the next heading of the same or a higher level.
+function section(text, heading) {
+ const start = text.indexOf(`\n${heading}\n`);
+ assert.ok(start >= 0, `rules.md has the section "${heading}"`);
+ const next = text.slice(start + heading.length + 2).search(/\n#{2,3} /);
+ return next < 0 ? text.slice(start) : text.slice(start, start + heading.length + 2 + next);
+}
+
+function canonicalBlock() {
+ const lookups = section(RULES, '### Lookup references (Customer, Owner, Regarding and every other lookup)');
+ const blocks = [...lookups.matchAll(/```typescript\n([\s\S]*?)\n```/g)].map((match) => match[1]).filter((block) => /\bfunction normalizeLookupReference\(/.test(block));
+ assert.equal(blocks.length, 1, 'the section shows the normalizer once');
+ return blocks[0];
+}
+
+let normalize;
+function load() {
+ if (normalize) return normalize;
+ const typescript = loadVendoredTypeScript();
+ const { outputText } = typescript.transpileModule(`${canonicalBlock()}\nexport { normalizeLookupReference };\n`, {
+ fileName: 'page.tsx',
+ compilerOptions: { module: typescript.ModuleKind.CommonJS, target: typescript.ScriptTarget.ES2020 },
+ });
+ const module = { exports: {} };
+ // The helper needs nothing from outside: no require, no console, no globals beyond the language's own.
+ new Function('module', 'exports', 'require', 'console', outputText)(module, module.exports, () => { throw new Error('the helper imports nothing'); }, undefined);
+ normalize = module.exports.normalizeLookupReference;
+ assert.equal(typeof normalize, 'function');
+ return normalize;
+}
+
+const ID = '4E0B2C77-1D7A-4B1E-9C55-0123456789AB';
+const id = ID.toLowerCase();
+const CUSTOMER = ['account', 'contact'];
+const OWNER = ['systemuser', 'team'];
+const ANNOTATION = '[email protected]';
+const row = (value, extra = {}) => ({ _customerid_value: value, ...extra });
+
+test('the measured qualified Customer and Owner values resolve to their table and a bare, lower-case id', () => {
+ const run = load();
+ assert.deepEqual(run(row(`/contact(${ID})`, { [ANNOTATION]: 'contact', '_customerid_value@Microsoft.Dynamics.CRM.associatednavigationproperty': 'parentcustomerid_contact' }), '_customerid_value', CUSTOMER),
+ { state: 'resolved', reference: { table: 'contact', id } });
+ assert.deepEqual(run({ _ownerid_value: `/systemuser(${ID})`, '[email protected]': 'systemuser', '_ownerid_value@Microsoft.Dynamics.CRM.associatednavigationproperty': 'ownerid' }, '_ownerid_value', OWNER),
+ { state: 'resolved', reference: { table: 'systemuser', id } });
+ assert.deepEqual(run(row(`/account(${ID})`), '_customerid_value', CUSTOMER), { state: 'resolved', reference: { table: 'account', id } }, 'the prefix alone, annotation absent');
+ assert.deepEqual(run(row(` /account(${ID}) `), '_customerid_value', CUSTOMER), { state: 'resolved', reference: { table: 'account', id } }, 'surrounding whitespace only is trimmed');
+});
+
+test('a bare GUID resolves from its annotation, or from a single-target lookup — and otherwise needs its target, with the bare id', () => {
+ const run = load();
+ assert.deepEqual(run(row(ID, { [ANNOTATION]: 'account' }), '_customerid_value', CUSTOMER), { state: 'resolved', reference: { table: 'account', id } });
+ assert.deepEqual(run({ _primarycontactid_value: ID }, '_primarycontactid_value', ['contact']), { state: 'resolved', reference: { table: 'contact', id } });
+ assert.deepEqual(run(row(ID), '_customerid_value', CUSTOMER), { state: 'needs-target', id }, 'never the first target');
+ // Nothing else is evidence: not the label, not the navigation annotation, not the order of the targets.
+ const hints = { '[email protected]': 'Contoso (account)', '_customerid_value@Microsoft.Dynamics.CRM.associatednavigationproperty': 'customerid_account' };
+ assert.deepEqual(run(row(ID, hints), '_customerid_value', CUSTOMER), { state: 'needs-target', id });
+ assert.deepEqual(run(row(ID), '_customerid_value', ['contact', 'account']), { state: 'needs-target', id });
+});
+
+test('one GUID in two tables stays two references', () => {
+ const run = load();
+ const account = run(row(ID, { [ANNOTATION]: 'account' }), '_customerid_value', CUSTOMER);
+ const contact = run(row(ID, { [ANNOTATION]: 'contact' }), '_customerid_value', CUSTOMER);
+ assert.notDeepEqual(account, contact);
+ assert.equal(account.reference.id, contact.reference.id);
+});
+
+test('an explicit null is unset; a missing, undefined or non-string value is invalid, not an empty lookup', () => {
+ const run = load();
+ assert.deepEqual(run(row(null), '_customerid_value', CUSTOMER), { state: 'unset' });
+ assert.deepEqual(run({}, '_customerid_value', CUSTOMER), { state: 'invalid' }, 'a field the read did not return');
+ assert.deepEqual(run(row(undefined), '_customerid_value', CUSTOMER), { state: 'invalid' });
+ for (const value of [42, true, { id: ID }, [ID]]) assert.deepEqual(run(row(value), '_customerid_value', CUSTOMER), { state: 'invalid' }, JSON.stringify(value));
+ // An inherited property is not the row's own.
+ assert.deepEqual(run(Object.create({ _customerid_value: ID }), '_customerid_value', CUSTOMER), { state: 'invalid' });
+});
+
+test('contradictory or foreign evidence is invalid, never resolved by a fallback', () => {
+ const run = load();
+ for (const [label, input] of [
+ ['annotation and prefix disagree', row(`/account(${ID})`, { [ANNOTATION]: 'contact' })],
+ ['a prefix outside the targets', row(`/lead(${ID})`)],
+ ['an annotation outside the targets', row(ID, { [ANNOTATION]: 'lead' })],
+ ['an annotation in another letter case', row(ID, { [ANNOTATION]: 'Account' })],
+ ['an annotation that is not a string', row(ID, { [ANNOTATION]: 7 })],
+ ['an empty annotation', row(ID, { [ANNOTATION]: '' })],
+ ['a null annotation', row(ID, { [ANNOTATION]: null })],
+ ]) {
+ assert.deepEqual(run(input, '_customerid_value', CUSTOMER), { state: 'invalid' }, label);
+ }
+});
+
+test('only a canonical GUID or /<logical-name>(<GUID>) is accepted', () => {
+ const run = load();
+ for (const value of [
+ '', 'not-a-guid', `{${ID}}`, `${ID}x`, ID.slice(0, 35), ID.replace(/-/g, ''),
+ `/accounts(${ID})`, `/Account(${ID})`, `/account(${ID})/extra`, `/account(${ID})x`, `account(${ID})`,
+ `https://contoso.crm.dynamics.com/api/data/v9.2/accounts(${ID})`, `/account(%7B${ID}%7D)`, `/account('${ID}')`,
+ ]) {
+ assert.deepEqual(run(row(value), '_customerid_value', CUSTOMER), { state: 'invalid' }, value);
+ }
+});
+
+test('a row that is not an object, or an empty target set, is invalid', () => {
+ const run = load();
+ for (const input of [null, undefined, 'text', 7, [row(ID)]]) assert.deepEqual(run(input, '_customerid_value', CUSTOMER), { state: 'invalid' }, String(input));
+ assert.deepEqual(run(row(`/account(${ID})`), '_customerid_value', []), { state: 'invalid' });
+});
+
+test('every resolved or needs-target id is a bare GUID: the qualified input never comes back as an id', () => {
+ const run = load();
+ for (const value of [ID, `/account(${ID})`, `/contact(${ID.toLowerCase()})`]) {
+ const result = run(row(value), '_customerid_value', CUSTOMER);
+ const out = result.state === 'resolved' ? result.reference.id : result.id;
+ assert.match(out, /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/, value);
+ }
+});
diff --git a/plugins/model-apps/scripts/tests/own-temp-folder.test.js b/plugins/model-apps/scripts/tests/own-temp-folder.test.js
new file mode 100644
index 000000000..b3d0516c3
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/own-temp-folder.test.js
@@ -0,0 +1,137 @@
+'use strict';
+// helpers/own-temp-folder.js: a test file that requires it works in a temp folder of its own inside the temp folder it was given, so the
+// folder lib/temp-workspace.js keeps the plugin's workspaces in is that file's alone — and the folder is gone when the file ends, unless a
+// test left something in it, which the suite's runner must still see. Its name is short whatever the file is called, so a workspace two levels
+// below it still fits in Windows' path limit under a long temp folder. Each case runs a small test file in a process of its own, as
+// `node --test` does, with a temp folder this test made.
+const test = require('node:test');
+const assert = require('node:assert');
+const crypto = require('node:crypto');
+const fs = require('node:fs');
+const path = require('node:path');
+const { spawn } = require('node:child_process');
+const { makeTempDir } = require('./helpers/temp-dirs.js');
+const { withTempDir } = require('../run-tests.js');
+const { workspaceParent } = require('../lib/temp-workspace.js');
+
+const HELPER = path.join(__dirname, 'helpers', 'own-temp-folder.js');
+const TEMP_WORKSPACE = path.join(__dirname, '..', 'lib', 'temp-workspace.js');
+// What the folder of a test file called `name` starts with: `own-`, the first letter of each word of the name before `.test.js` (at most six), four
+// hex digits of a hash of the whole name — `solution-settings-real-bundle.test.js` is `own-ssrb-<4 hex>-` — and mkdtemp adds six characters.
+function ownTempStart(name) {
+ const letters = name.replace(/\.test\.js$/, '').split(/[^A-Za-z0-9]+/).filter(Boolean).map((word) => word[0].toLowerCase()).join('').slice(0, 6);
+ return `own-${letters}-${crypto.createHash('sha256').update(name).digest('hex').slice(0, 4)}-`;
+}
+const OWN_TEMP_NAME = /^own-[a-z0-9]{1,6}-[0-9a-f]{4}-[A-Za-z0-9]{6}$/;
+
+// A test file that requires the helper first (unless `helper` is false: the plain layout, as before the helper), makes a workspace with the real
+// maker and leaves it to the end of the process, which removes it (lib/temp-workspace.js, THE END OF A RUN) — and, when `OWN_TEMP_LEAVE` is set,
+// leaves a file of its own in the temp folder. What it saw is written to `OWN_TEMP_REPORT`, outside the temp folder.
+function probeSource({ helper, prefix }) {
+ return [
+ "'use strict';",
+ helper ? `const { ownTemp } = require(${JSON.stringify(HELPER)});` : 'const ownTemp = null;',
+ "const test = require('node:test');",
+ "const fs = require('node:fs');",
+ "const os = require('node:os');",
+ "const path = require('node:path');",
+ `const { makeTempWorkspace, workspaceParent } = require(${JSON.stringify(TEMP_WORKSPACE)});`,
+ "test('a workspace in the plugin folder of the temp folder', () => {",
+ ` const workspace = makeTempWorkspace(${JSON.stringify(prefix)});`,
+ " const env = { TEMP: process.env.TEMP, TMP: process.env.TMP, TMPDIR: process.env.TMPDIR };",
+ " fs.writeFileSync(process.env.OWN_TEMP_REPORT, JSON.stringify({ ownTemp, tmpdir: os.tmpdir(), env, parent: workspaceParent(), workspace }));",
+ " if (process.env.OWN_TEMP_LEAVE) fs.writeFileSync(path.join(os.tmpdir(), 'left-behind.txt'), 'a test that forgot to clean up');",
+ "});",
+ '',
+ ].join('\n');
+}
+
+// Runs the probe, as a test file called `name`, with `temp` as its temp folder; answers its exit status and what it reported.
+function runProbe(temp, { leave = false, name = 'probe.test.js', helper = true, prefix = 'probe-' } = {}) {
+ const dir = makeTempDir('otf-probe-');
+ const file = path.join(dir, name);
+ const report = path.join(dir, 'report.json');
+ fs.writeFileSync(file, probeSource({ helper, prefix }));
+ const env = withTempDir(process.env, temp);
+ for (const key of Object.keys(env)) if (/^NODE_TEST_CONTEXT$/i.test(key)) delete env[key];
+ Object.assign(env, { OWN_TEMP_REPORT: report, POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: '1' }, leave ? { OWN_TEMP_LEAVE: '1' } : {});
+ return new Promise((resolve, reject) => {
+ const child = spawn(process.execPath, [file], { env, stdio: ['ignore', 'pipe', 'pipe'] });
+ let output = '';
+ child.stdout.on('data', (chunk) => { output += chunk; });
+ child.stderr.on('data', (chunk) => { output += chunk; });
+ child.on('error', reject);
+ child.on('close', (status) => resolve({ status, output, seen: fs.existsSync(report) ? JSON.parse(fs.readFileSync(report, 'utf8')) : null }));
+ });
+}
+
+test('a test file that requires it works in a folder of its own inside the temp folder it was given, and the folder is gone when the file ends', async () => {
+ const temp = makeTempDir('otf-given-');
+ const { status, output, seen } = await runProbe(temp);
+ assert.strictEqual(status, 0, output);
+ assert.ok(seen, output);
+ assert.strictEqual(path.dirname(seen.ownTemp), temp, 'inside the temp folder the process was given');
+ assert.match(path.basename(seen.ownTemp), OWN_TEMP_NAME);
+ assert.ok(path.basename(seen.ownTemp).startsWith(ownTempStart('probe.test.js')), `named for the test file: ${path.basename(seen.ownTemp)}`);
+ assert.deepStrictEqual([seen.tmpdir, seen.env.TEMP, seen.env.TMP, seen.env.TMPDIR], [seen.ownTemp, seen.ownTemp, seen.ownTemp, seen.ownTemp], 'os.tmpdir() and the three variables name it');
+ assert.strictEqual(seen.parent, workspaceParent({ os: { tmpdir: () => seen.ownTemp } }), 'the plugin\'s workspace folder is the one in it');
+ assert.strictEqual(path.dirname(seen.workspace), seen.parent, 'and the workspace was made there');
+ // The end of the process removed the workspace and the plugin's folder (lib/temp-workspace.js), and then this folder: nothing is left.
+ assert.deepStrictEqual(fs.readdirSync(temp), []);
+});
+
+test('what a test leaves behind keeps the folder, with what was left in it, in the temp folder the runner checks', async () => {
+ const temp = makeTempDir('otf-given-');
+ const { status, output, seen } = await runProbe(temp, { leave: true });
+ assert.strictEqual(status, 0, output);
+ assert.deepStrictEqual(fs.readdirSync(temp), [path.basename(seen.ownTemp)], 'the folder stays, so the runner names it');
+ assert.deepStrictEqual(fs.readdirSync(seen.ownTemp), ['left-behind.txt'], 'with what was left — the workspace and the plugin\'s folder are gone');
+});
+
+test('two test files that run at once, given one temp folder, work in two folders of their own', async () => {
+ const temp = makeTempDir('otf-given-');
+ const runs = await Promise.all([runProbe(temp), runProbe(temp)]);
+ for (const { status, output } of runs) assert.strictEqual(status, 0, output);
+ const [one, two] = runs.map(({ seen }) => seen);
+ assert.notStrictEqual(one.ownTemp, two.ownTemp);
+ assert.notStrictEqual(one.parent, two.parent, 'so neither can remove the plugin folder the other is making a workspace in');
+ assert.deepStrictEqual(fs.readdirSync(temp), []);
+});
+
+// Every workspace is two levels below the file's own temp folder, and Windows refuses fs.mkdtempSync a folder whose path is 248 characters or more.
+// A temp folder of LONG_ROOT characters is long, but one the plain layout fits in: there the longest-named file that requires the helper, making a
+// workspace named like the longest a script makes, must still get it in its own plugin folder. A folder named with the whole file name did not
+// (measured: the workspace went to the plain temp folder), and on every system its name broke the bound below.
+const LONG_ROOT = 144;
+// The longest prefix a script gives lib/temp-workspace.js: download-model-app.js's (provision-solution.js's is as long).
+const LONGEST_PREFIX = 'model-app-download-';
+const LONGEST_FILE = fs.readdirSync(__dirname)
+ .filter((name) => name.endsWith('.test.js'))
+ .sort((a, b) => b.length - a.length || a.localeCompare(b))
+ .find((name) => fs.readFileSync(path.join(__dirname, name), 'utf8').includes("require('./helpers/own-temp-folder.js')"));
+
+test('its name is short whatever the test file is called: under a long temp folder the plain layout fits in, the longest-named file still gets its workspace in its own plugin folder', async (t) => {
+ assert.ok(LONGEST_FILE, 'some test file requires the helper');
+ const base = makeTempDir('otf-long-');
+ const padding = LONG_ROOT - base.length - 1;
+ if (padding < 1) {
+ t.skip(`the temp folder is ${base.length} characters long already, past the ${LONG_ROOT} this test builds`);
+ return;
+ }
+ const root = path.join(base, 'p'.repeat(padding));
+ fs.mkdirSync(root);
+ assert.strictEqual(root.length, LONG_ROOT);
+ // The root is usable: with no folder of the file's own, the workspace is made in the plugin folder of the root itself.
+ const plain = await runProbe(root, { name: LONGEST_FILE, helper: false, prefix: LONGEST_PREFIX });
+ assert.strictEqual(plain.status, 0, plain.output);
+ assert.strictEqual(path.dirname(plain.seen.workspace), workspaceParent({ os: { tmpdir: () => root } }), `the plain layout fits: ${plain.seen.workspace}`);
+ const own = await runProbe(root, { name: LONGEST_FILE, prefix: LONGEST_PREFIX });
+ assert.strictEqual(own.status, 0, own.output);
+ assert.strictEqual(path.dirname(own.seen.ownTemp), root);
+ assert.strictEqual(path.dirname(own.seen.workspace), workspaceParent({ os: { tmpdir: () => own.seen.ownTemp } }),
+ `${LONGEST_FILE}'s workspace is in the plugin folder of its own temp folder, not the plain temp folder: ${own.seen.workspace} (${own.seen.workspace.length} characters)`);
+ const name = path.basename(own.seen.ownTemp);
+ assert.match(name, OWN_TEMP_NAME, `a short name, at most 22 characters: ${name}`);
+ assert.ok(name.startsWith(ownTempStart(LONGEST_FILE)), `named for ${LONGEST_FILE}: ${name}`);
+ assert.deepStrictEqual(fs.readdirSync(root), [], 'and neither run left anything');
+});
\ No newline at end of file
diff --git a/plugins/model-apps/scripts/tests/pac-replaced-docs.test.js b/plugins/model-apps/scripts/tests/pac-replaced-docs.test.js
index e54c4f7b7..76a307672 100644
--- a/plugins/model-apps/scripts/tests/pac-replaced-docs.test.js
+++ b/plugins/model-apps/scripts/tests/pac-replaced-docs.test.js
@@ -447,7 +447,7 @@ const CONTRACT = {
},
'genpage-upload.js': {
flags: ['env', 'app-id', 'code-file', 'compiled-code-file', 'page-id', 'name', 'name-file', 'data-sources', 'clear-data-sources', 'prompt', 'prompt-file', 'agent-message',
- 'agent-message-file', 'model', 'connectors', 'actions', 'add-to-sitemap', 'overwrite-deployed'],
+ 'agent-message-file', 'model', 'connectors', 'actions', 'add-to-sitemap', 'overwrite-deployed', 'solution'],
},
// The page verbs the skills ran through `pac model genpage`; the table is the script's own VERBS (checked below).
'genpage.js': {
@@ -627,7 +627,7 @@ test('the genpage skill creates a new app from its first page: no app in Phase 3
assert.match(newApp, /node "\$\{PLUGIN_ROOT\}\/scripts\/apps\.js" create ` --env '<org-url>' ` --name '<App Name>' ` --solution '<Solution unique name>' ` --page-id '<first-page-id>' ` --publish/);
assert.match(newApp, /\*\*`--publish` is mandatory:\*\* without it the new app stays in draft/);
assert.match(newApp, /a create into `Default` needs no add and did not fail/);
- assert.match(newApp, /Upload each with `--app-id '<appId>'` and `--add-to-sitemap`/);
+ assert.match(newApp, /Upload each with `--app-id '<appId>'`, `--add-to-sitemap` and `--solution`/);
// The create itself pins the default public view of each table the first page reads — so there is no step 4 of re-uploading the page to pin them, and no `record` of the new app's
// id to make that re-upload possible: a page with no app is recorded with the page alone (genpage-base.test.js), and the first update that names the app records it
// (genpage-upload.test.js, "the new-app flow"). apps.js create's own tests (apps.test.js, apps-real-bundle.test.js) pin that it pins them.
diff --git a/plugins/model-apps/scripts/tests/page-binding-targets.test.js b/plugins/model-apps/scripts/tests/page-binding-targets.test.js
index 2ebccc6f2..d4648d029 100644
--- a/plugins/model-apps/scripts/tests/page-binding-targets.test.js
+++ b/plugins/model-apps/scripts/tests/page-binding-targets.test.js
@@ -539,3 +539,113 @@ test('a malformed connectorid or connectionid in a successful answer is NOT CHEC
const { provision } = readerOf({ connectionreference: [{ ...row, connectorid: '/providers/Microsoft.PowerApps/apis/shared_office365users' }] });
assert.deepStrictEqual(judgeBindingTargets([odd], await readBindingTargets(provision, [odd])).findings, []);
});
+
+// ── the two reviewed built-in operations: WhoAmI and RetrieveVersion ────────────────────────────────────────────────────────────
+// They are platform messages, not rows of `customapi` (lib/dataverse-operations.js), so a `customapi` read cannot find them and an `api-missing` warning would tell the author to deploy
+// something that is not deployable. An EXACT catalogue name leaves the Custom API read before the names are folded in case and cut into chunks; it is reported as not checked — its
+// availability in the environment or player and the user's permissions are not known — and never as "compatible". A preserved one whose declarations do not explicitly say "unbound
+// Function, no inputs" is warned of and left as it is. A name in another case (`whoami`), and every other name, stays a Custom API name.
+const WHO_AM_I = { name: 'WhoAmI', isFunction: true, displayName: 'Current Dataverse identity', parameterKinds: {} };
+const RETRIEVE_VERSION = { name: 'RetrieveVersion', isFunction: true, displayName: 'Dataverse server version', parameterKinds: {} };
+const BUILT_IN_UNCHECKED = 'These are reviewed built-in operation names; their availability in this environment or player and the signed-in user\'s permissions were not checked.';
+
+test('built-in operations: a page that binds only WhoAmI and RetrieveVersion reads no customapi row, is warned of nothing missing, and is said to be not checked', async () => {
+ const page = { key: 'ops', name: 'Ops', actionBindings: [WHO_AM_I, RETRIEVE_VERSION] };
+ const { provision, calls } = readerOf({});
+ const targets = await readBindingTargets(provision, [page]);
+ assert.deepStrictEqual(calls, [], 'zero reads');
+ assert.deepStrictEqual(targets, { references: null, apis: null, definitions: null, problems: {} });
+ const verdict = judgeBindingTargets([page], targets);
+ assert.deepStrictEqual(verdict.findings, [], 'no api-missing, and no shape warning for a binding that states the reviewed contract');
+ assert.deepStrictEqual(verdict.unchecked, [{
+ what: 'Dataverse operations', page: { key: 'ops', name: 'Ops' }, names: ['WhoAmI', 'RetrieveVersion'],
+ text: `page "Ops" binds the built-in operations WhoAmI, RetrieveVersion. ${BUILT_IN_UNCHECKED}`,
+ }]);
+ // Not checked is never "compatible": the sentence says so, and nothing claims a check.
+ assert.doesNotMatch(verdict.unchecked[0].text, /compatible|verified|deploy/i);
+});
+
+test('built-in operations: beside Custom APIs, only the Custom API names are read — and a Custom API still missing is still said', async () => {
+ const page = { key: 'mixed', name: 'Mixed', actionBindings: [APPROVE, WHO_AM_I, RETRIEVE_VERSION, SUMMARY] };
+ const { provision, calls } = readerOf({ customapi: [customApi('contoso_ApproveOrder', { boundentitylogicalname: 'contoso_item', bindingtype: 1 })] });
+ const targets = await readBindingTargets(provision, [page]);
+ assert.deepStrictEqual(calls.map((c) => [c.entity, c.options.filter]), [['customapi', "uniquename eq 'contoso_ApproveOrder' or uniquename eq 'contoso_GetSummary'"]]);
+ const verdict = judgeBindingTargets([page], targets);
+ assert.deepStrictEqual(verdict.findings.map((f) => [f.kind, f.names]), [['api-missing', ['contoso_GetSummary']]]);
+ assert.deepStrictEqual(verdict.unchecked.map((u) => [u.what, u.names]), [['Dataverse operations', ['WhoAmI', 'RetrieveVersion']]]);
+ // The Custom API read fails: the Custom API bindings are not checked — and a page that binds only built-ins is not named among them.
+ const denied = readerOf({}, { failOn: ['customapi'] });
+ const pages = [page, { key: 'ops', name: 'Ops', actionBindings: [WHO_AM_I] }];
+ const failed = judgeBindingTargets(pages, await readBindingTargets(denied.provision, pages));
+ assert.deepStrictEqual(failed.findings, []);
+ assert.deepStrictEqual(failed.unchecked.map((u) => u.text), [
+ `page "Mixed" binds the built-in operations WhoAmI, RetrieveVersion. ${BUILT_IN_UNCHECKED}`,
+ `page "Ops" binds the built-in operation WhoAmI. ${BUILT_IN_UNCHECKED}`,
+ 'could not read this environment\'s Custom APIs (customapi: HTTP 403), so the Custom API bindings of page "Mixed" were not checked against them',
+ ]);
+});
+
+test('built-in operations: only an EXACT catalogue name leaves the Custom API read — whoami, a namespaced name and an effectful Function stay Custom API names', async () => {
+ const page = { key: 'p', name: 'P', actionBindings: [{ name: 'whoami', isFunction: true }, { name: 'Microsoft.Dynamics.CRM.WhoAmI', isFunction: true }, { name: 'CalculateRollupField', isFunction: true }, { name: 'RETRIEVEVERSION', isFunction: true }] };
+ const { provision, calls } = readerOf({});
+ const verdict = judgeBindingTargets([page], await readBindingTargets(provision, [page]));
+ assert.deepStrictEqual(calls.map((c) => c.options.filter), ["uniquename eq 'whoami' or uniquename eq 'Microsoft.Dynamics.CRM.WhoAmI' or uniquename eq 'CalculateRollupField' or uniquename eq 'RETRIEVEVERSION'"]);
+ assert.deepStrictEqual(verdict.findings.map((f) => [f.kind, f.names]), [['api-missing', ['whoami', 'Microsoft.Dynamics.CRM.WhoAmI', 'CalculateRollupField', 'RETRIEVEVERSION']]]);
+ assert.deepStrictEqual(verdict.unchecked, []);
+});
+
+test('built-in operations leave the read before the names are folded in case and chunked: the chunks go from ceil(nBefore/25) to ceil(nAfter/25), and whoami beside WhoAmI is still read', async () => {
+ const apis = Array.from({ length: 25 }, (_, i) => ({ name: `contoso_Api${String(i).padStart(2, '0')}`, isFunction: true }));
+ // 25 Custom APIs and both built-ins: 27 names before, 25 after — one chunk, not two.
+ const both = readerOf({});
+ await readBindingTargets(both.provision, [{ key: 'a', name: 'A', actionBindings: [...apis, WHO_AM_I, RETRIEVE_VERSION] }]);
+ assert.deepStrictEqual(both.calls.map((c) => c.options.filter.split(' or ').length), [25]);
+ assert.ok(!both.calls.some((c) => /'WhoAmI'|'RetrieveVersion'/.test(c.options.filter)));
+ // WhoAmI and whoami fold to ONE name when they are read together; WhoAmI leaves first, so whoami is read under its own spelling — subtracting every built-in binding from the
+ // folded count would have dropped it.
+ const twins = readerOf({});
+ await readBindingTargets(twins.provision, [{ key: 'a', name: 'A', actionBindings: [...apis.slice(0, 24), WHO_AM_I, { name: 'whoami', isFunction: true }] }]);
+ assert.deepStrictEqual(twins.calls.map((c) => c.options.filter.split(' or ').length), [25]);
+ assert.match(twins.calls[0].options.filter, / or uniquename eq 'whoami'$/);
+ assert.doesNotMatch(twins.calls[0].options.filter, /'WhoAmI'/);
+ const order = readerOf({});
+ await readBindingTargets(order.provision, [{ key: 'a', name: 'A', actionBindings: [{ name: 'whoami', isFunction: true }, WHO_AM_I] }]);
+ assert.deepStrictEqual(order.calls.map((c) => c.options.filter), ["uniquename eq 'whoami'"], 'whichever comes first');
+});
+
+test('built-in operations: a preserved binding that does not explicitly say "unbound Function, no inputs" is warned of — omitted apart from contradicted — and left exactly as it is', async () => {
+ const legacy = { name: 'WhoAmI', displayName: 'Who am I' };
+ const noKinds = { name: 'RetrieveVersion', isFunction: true };
+ const action = { name: 'WhoAmI', isFunction: false, displayName: 'Current Dataverse identity', parameterKinds: {} };
+ const inputs = { name: 'RetrieveVersion', isFunction: true, parameterKinds: { Target: 'String', Depth: 'Integer' } };
+ const bound = { name: 'WhoAmI', isFunction: true, boundEntityLogicalName: 'systemuser', parameterKinds: {} };
+ const pages = [
+ { key: 'old', name: 'Old', actionBindings: [legacy, noKinds] },
+ { key: 'bad', name: 'Bad', actionBindings: [action, inputs, bound] },
+ ];
+ const before = structuredClone(pages);
+ const { provision, calls } = readerOf({});
+ const verdict = judgeBindingTargets(pages, await readBindingTargets(provision, pages));
+ assert.deepStrictEqual(calls, []);
+ assert.deepStrictEqual(pages, before, 'nothing is rewritten');
+ assert.deepStrictEqual(verdict.findings.map((f) => [f.severity, f.kind, f.page.key, f.binding, f.declaration]), [
+ ['warn', 'dataverse-operation-shape', 'old', 'WhoAmI', 'omitted'],
+ ['warn', 'dataverse-operation-shape', 'old', 'RetrieveVersion', 'omitted'],
+ ['warn', 'dataverse-operation-shape', 'bad', 'WhoAmI', 'contradicted'],
+ ['warn', 'dataverse-operation-shape', 'bad', 'RetrieveVersion', 'contradicted'],
+ ['warn', 'dataverse-operation-shape', 'bad', 'WhoAmI', 'contradicted'],
+ ]);
+ const SHAPE = 'This binding does not explicitly match the reviewed unbound, zero-input Function contract. It was preserved; invocation may fail.';
+ assert.deepStrictEqual(verdict.findings.map((f) => f.text), [
+ `page "Old": built-in operation binding "WhoAmI" does not declare its kind or its inputs (isFunction, parameterKinds). ${SHAPE}`,
+ `page "Old": built-in operation binding "RetrieveVersion" does not declare its inputs (parameterKinds). ${SHAPE}`,
+ `page "Bad": built-in operation binding "WhoAmI" declares an Action (isFunction: false). ${SHAPE}`,
+ `page "Bad": built-in operation binding "RetrieveVersion" declares inputs (Target, Depth). ${SHAPE}`,
+ `page "Bad": built-in operation binding "WhoAmI" declares a bound table (systemuser). ${SHAPE}`,
+ ]);
+ // No promise of what the player answers: the runtime codes of a Custom API mismatch are not this check's to name.
+ assert.ok(verdict.findings.every((f) => !/wrong_operation_kind|invalid_bound_to|api-missing|deploy/.test(f.text)));
+ assert.deepStrictEqual(verdict.unchecked.map((u) => u.names), [['WhoAmI', 'RetrieveVersion'], ['WhoAmI', 'RetrieveVersion']], 'each page still says its built-ins were not checked');
+ // A different display label is not a shape problem: only kind, binding and inputs are.
+ assert.deepStrictEqual(judgeBindingTargets([{ key: 'l', name: 'L', actionBindings: [{ ...WHO_AM_I, displayName: 'Me' }] }], { references: null, apis: null, problems: {} }).findings, []);
+});
diff --git a/plugins/model-apps/scripts/tests/page-bindings.test.js b/plugins/model-apps/scripts/tests/page-bindings.test.js
index f6b5c9d01..b35e6b26d 100644
--- a/plugins/model-apps/scripts/tests/page-bindings.test.js
+++ b/plugins/model-apps/scripts/tests/page-bindings.test.js
@@ -26,6 +26,7 @@ const { runSdkBuild, BuildHalt } = require('../lib/sdk-build.js');
const { classifyPages } = require('../lib/classify-changes.js');
const { buildManifest } = require('../lib/page-manifest.js');
const { makeSimpleMockSdk } = require('./helpers/mock-sdk.js');
+const { withPageType } = require('./helpers/page-component-type.js');
const { currentReadSdk } = require('./helpers/app-membership-sdk.js');
const { fakeGenpage } = require('./helpers/fake-genpage.js');
const { createAzHttpClient } = require('../lib/sdk-http-client.js');
@@ -417,6 +418,66 @@ test('pageBindingsNote says what a rebuild into another environment cannot bring
assert.ok(!/^NOTE/.test(lost), 'no page holds a binding the spec states, so there is no note about them');
});
+// ── the two reviewed built-in operations in a download ──────────────────────────────────────────────────────────────────────────
+// WhoAmI and RetrieveVersion are platform messages (lib/dataverse-operations.js), not Custom APIs: a download that lists them under `customApis` tells the operator to deploy something that
+// cannot be deployed. An EXACT catalogue name is reported under `neededInTarget.dataverseOperations` instead — a legacy or contradictory entry too, since a parameter map does not make
+// the name a Custom API — and the binding itself is carried as the page holds it: not repaired, not certified. A list that holds an unsafe field is still left out whole.
+const WHO_AM_I = { name: 'WhoAmI', isFunction: true, displayName: 'Current Dataverse identity', parameterKinds: {} };
+const RETRIEVE_VERSION = { name: 'RetrieveVersion', isFunction: true, displayName: 'Dataverse server version', parameterKinds: {} };
+
+test('built-in operations: a download names WhoAmI and RetrieveVersion as built-in operations, never as Custom APIs to deploy — legacy, contradictory and parameterized entries alike', () => {
+ const pages = [
+ { pageId: A, key: 'ops', name: 'Ops', actionBindings: [APPROVE, WHO_AM_I, RETRIEVE_VERSION] },
+ { pageId: B, key: 'legacy', name: 'Legacy', actionBindings: [{ name: 'WhoAmI' }, { name: 'RetrieveVersion', isFunction: false, parameterKinds: { Target: 'String' } }] },
+ { pageId: C, key: 'cased', name: 'Cased', actionBindings: [{ name: 'whoami', isFunction: true }] },
+ ];
+ const report = pageBindingsReport(pages, []);
+ assert.deepStrictEqual(report.neededInTarget, {
+ customApis: ['contoso_ApproveOrder', 'whoami'],
+ dataverseOperations: ['RetrieveVersion', 'WhoAmI'],
+ });
+ assert.deepStrictEqual(report.pages.map((p) => p.actionBindings), [['contoso_ApproveOrder', 'RetrieveVersion', 'WhoAmI'], ['RetrieveVersion', 'WhoAmI'], ['whoami']], 'each page still lists every binding it holds');
+ assert.match(report.note, /built-in Dataverse operations \(dataverseOperations\) are not solution components/);
+ assert.match(report.note, /preserved as the page holds them, not repaired/);
+ assert.match(report.note, /not certified/);
+
+ const text = pageBindingsNote(report);
+ const line = text.split('\n').find((l) => /built-in Dataverse operation/.test(l));
+ assert.ok(line, text);
+ assert.match(line, /^ {4}- built-in Dataverse operation\(s\) RetrieveVersion, WhoAmI: /);
+ assert.doesNotMatch(line, /deploy|list-custom-apis|solution component, not an App Spec item/i);
+ assert.match(text, /Custom API\(s\) contoso_ApproveOrder, whoami: a Custom API is a solution component/, 'the Custom APIs keep their own line');
+ assert.doesNotMatch(text.split('\n').find((l) => /Custom API\(s\)/.test(l)), /WhoAmI|RetrieveVersion/);
+ // No response value is ever part of it: a binding names an operation, it does not hold what the operation answered.
+ assert.doesNotMatch(JSON.stringify(report) + text, /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-/i);
+
+ const builtInOnly = pageBindingsReport([{ pageId: A, key: 'ops', name: 'Ops', actionBindings: [WHO_AM_I] }], []);
+ assert.deepStrictEqual(builtInOnly.neededInTarget, { dataverseOperations: ['WhoAmI'] });
+ assert.doesNotMatch(pageBindingsNote(builtInOnly), /Custom API\(s\)/);
+ // A report with no built-in operation says exactly what it always said.
+ const plain = pageBindingsReport([{ pageId: A, key: 'w', name: 'W', actionBindings: [APPROVE] }], []);
+ assert.ok(!('dataverseOperations' in plain.neededInTarget));
+ assert.doesNotMatch(plain.note + pageBindingsNote(plain), /built-in/);
+});
+
+test('built-in operations: a download carries the binding as the page holds it, and recognizing a name never rescues a list that holds an unsafe field', () => {
+ const legacy = { name: 'WhoAmI' };
+ const root = pageTree({
+ [A]: { actionBindings: [APPROVE, WHO_AM_I, RETRIEVE_VERSION, legacy] },
+ [B]: { actionBindings: [WHO_AM_I, { ...RETRIEVE_VERSION, bindingType: 'Global' }] },
+ [C]: { actionBindings: [WHO_AM_I, { ...RETRIEVE_VERSION, response: { typeName: 'Microsoft.Dynamics.CRM.RetrieveVersionResponse' } }] },
+ });
+ const unkept = [];
+ const pages = parseDownloadedPages(root, root, null, [], [], unkept);
+ const byId = new Map(pages.map((p) => [p.pageId, p]));
+ assert.deepStrictEqual(byId.get(A).actionBindings, [APPROVE, WHO_AM_I, RETRIEVE_VERSION, legacy], 'carried exactly: no isFunction or display name added to the legacy entry');
+ for (const id of [B, C]) assert.ok(!Object.hasOwn(byId.get(id), 'actionBindings'), `${id}: a descriptor key on the wire leaves the whole list out`);
+ assert.deepStrictEqual(unkept.map((u) => [u.pageId, u.field]), [[B, 'actionBindings'], [C, 'actionBindings']]);
+ const report = pageBindingsReport(pages.map((p, i) => ({ ...p, key: `p${i}`, name: `P${i}` })), unkept);
+ assert.deepStrictEqual(report.neededInTarget, { customApis: ['contoso_ApproveOrder'], dataverseOperations: ['RetrieveVersion', 'WhoAmI'] }, 'only the list the spec states is reported');
+ assert.strictEqual(report.notCarried.length, 2);
+});
+
// ── a download, end to end over the stand-in SDK ──────────────────────────────────────────────────────────────────────────────
// What one app of two pages looks like to a download: the navigation names both, and the stand-in SDK answers the reads runDownload makes.
@@ -439,7 +500,8 @@ function downloadFixture(pages) {
sdk.listArtifacts = async (kind) => (kind === 'app' ? [{ id: APP_ID, isDirty: false }] : []);
sdk.findTables = async () => [{ logicalName: 'contoso_item', entitySetName: 'contoso_items' }];
sdk.fetchEntityMetadata = async (logical) => ({ logicalName: logical, schemaName: logical, displayName: 'Item', primaryNameAttribute: 'contoso_name', entitySetName: 'contoso_items', attributes: [], relationships: [] });
- sdk.dataverse = { get: async () => ({ status: 200, body: { value: [] } }) };
+ // The page table's solution component type is answered too: a rebuild adds the pages it writes to the spec's solution (helpers/page-component-type.js).
+ sdk.dataverse = { get: withPageType(async () => ({ status: 200, body: { value: [] } })) };
const manifest = buildManifest({ pages: pages.map((p) => ({ key: p.key, name: p.name })) }, new Map(pages.map((p) => [p.key, p.pageId])));
let manifestContent = Buffer.from(JSON.stringify(manifest), 'utf8').toString('base64');
sdk.queryRecords = async (logical, opts = {}) => {
@@ -843,7 +905,7 @@ function freshEnvironmentSdk() {
pushArtifact: async (t, id) => ({ type: t, id, saved: true, shipped: false, publish: { kind: 'notRequested' } }),
addSolutionComponent: async () => {},
publishArtifact: async (type, id) => ({ type, id, shipped: true, publish: { kind: 'verified' } }),
- dataverse: { get: async () => ({ status: 404, body: null }) },
+ dataverse: { get: withPageType(async () => ({ status: 404, body: null })) },
};
}
@@ -1013,6 +1075,34 @@ test('a Custom API of the other kind, or bound to another table, is a warning by
]);
});
+// The two reviewed built-in operations through a whole build: what the build reads for them (nothing), what it says (not checked), and what it writes (the bindings as the spec states them).
+test('built-in operations: a build reads customapi only for the Custom API names, says WhoAmI and RetrieveVersion were not checked, and writes every binding as the spec states it', async () => {
+ const { spec, outDir } = await portableCopy();
+ spec.pages.find((p) => p.key === 'weather').actionBindings = [APPROVE, WHO_AM_I, RETRIEVE_VERSION];
+ spec.pages.find((p) => p.key === 'detail').actionBindings = [WHO_AM_I];
+ assert.ok(validateAppSpec(spec).ok, validateAppSpec(spec).errors.join('; '));
+ const { sdk, reads } = targetEnvironment({ references: BOTH_REFERENCES, apis: BOTH_APIS });
+ const genpage = fakeGenpage();
+ const warnings = [];
+ const rebuilt = await runSdkBuild(spec, { sdk, genpage, appDir: outDir, env: FABRIKAM, apply: true, phases: PHASES, warn: (m) => warnings.push(m) });
+ assert.ok(rebuilt.ok);
+ assert.deepStrictEqual(reads.map((r) => [r.entity, r.options.filter]).filter(([entity]) => entity === 'customapi'), [['customapi', "uniquename eq 'contoso_ApproveOrder'"]], 'one read, of the one Custom API name');
+ const said = bindingWords(warnings).concat(warnings.filter((m) => /built-in operation/.test(m)));
+ assert.ok(said.includes('page "Weather" binds the built-in operations WhoAmI, RetrieveVersion. These are reviewed built-in operation names; their availability in this environment or player and the signed-in user\'s permissions were not checked.'), JSON.stringify(said));
+ assert.ok(said.includes('page "Item Detail" binds the built-in operation WhoAmI. These are reviewed built-in operation names; their availability in this environment or player and the signed-in user\'s permissions were not checked.'), JSON.stringify(said));
+ assert.ok(!warnings.some((m) => /Custom APIs? (WhoAmI|RetrieveVersion)|deployed here/.test(m)), 'no built-in operation is called a missing Custom API');
+ const made = new Map(genpage.of('create').map((c) => [c.args[0].name, c.args[0]]));
+ assert.deepStrictEqual(made.get('Weather').actionBindings, [APPROVE, WHO_AM_I, RETRIEVE_VERSION]);
+ assert.deepStrictEqual(made.get('Item Detail').actionBindings, [WHO_AM_I]);
+
+ // Built-ins and nothing else: the build reads no customapi row at all.
+ const only = await portableCopy();
+ only.spec.pages.find((p) => p.key === 'weather').actionBindings = [WHO_AM_I, RETRIEVE_VERSION];
+ const quiet = targetEnvironment({ references: BOTH_REFERENCES, apis: BOTH_APIS });
+ assert.ok((await runSdkBuild(only.spec, { sdk: quiet.sdk, genpage: fakeGenpage(), appDir: only.outDir, env: FABRIKAM, apply: true, phases: PHASES, warn: () => {} })).ok);
+ assert.deepStrictEqual(quiet.reads.map((r) => r.entity), ['connectionreference'], 'zero customapi reads');
+});
+
// A page made with a CUSTOM connector: its binding goes through a reference whose connector's definition is a row of the environment (`connector.openapidefinition`), and the copy there can be another version.
const WIDGETS_BINDING = { logicalName: 'contoso_widgets', connectorId: '/providers/Microsoft.PowerApps/apis/shared_contoso-5fwidgets-5f6a8c', dataset: '', operations: ['ListWidgets', 'GetWidget'] };
const WIDGETS_CONNECTOR_ID = 'c0000000-0000-4000-8000-0000000000a1';
diff --git a/plugins/model-apps/scripts/tests/page-download-rebuild.test.js b/plugins/model-apps/scripts/tests/page-download-rebuild.test.js
index 4e5ae2b20..36e79915c 100644
--- a/plugins/model-apps/scripts/tests/page-download-rebuild.test.js
+++ b/plugins/model-apps/scripts/tests/page-download-rebuild.test.js
@@ -11,6 +11,7 @@ const { validateAppSpec } = require('../lib/app-spec.js');
const { makeSimpleMockSdk } = require('./helpers/mock-sdk.js');
const { currentReadSdk } = require('./helpers/app-membership-sdk.js');
const { fakeGenpage } = require('./helpers/fake-genpage.js');
+const { withPageType } = require('./helpers/page-component-type.js');
const ENV = 'https://contoso.crm.dynamics.com';
const APP_ID = 'aaaaaaaa-0000-4000-8000-000000000001';
@@ -57,7 +58,8 @@ test('download-hydrate-rebuild preserves page identity name model and bindings',
logicalName: logical, schemaName: logical, displayName: 'Item',
primaryNameAttribute: 'contoso_name', entitySetName: 'contoso_items', attributes: [], relationships: [],
});
- sdk.dataverse = { get: async () => ({ status: 200, body: { value: [] } }) };
+ // The rebuild's pages join the app's solution, so the page table's component type is read first (lib/page-solution.js).
+ sdk.dataverse = { get: withPageType(async () => ({ status: 200, body: { value: [] } })) };
sdk.queryRecords = async (logical, opts = {}) => {
if (logical === 'appmodule') return [{ appmoduleid: APP_ID, appmoduleidunique: APP_UNIQUE_ID, uniquename: APP_UNIQUE }];
if (logical === 'appmodulecomponent') return /componenttype eq 62/.test(opts.filter || '') ? [{ objectid: SITEMAP_ID, componenttype: 62 }] : [];
diff --git a/plugins/model-apps/scripts/tests/page-error-reference.test.js b/plugins/model-apps/scripts/tests/page-error-reference.test.js
new file mode 100644
index 000000000..60b9f4241
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/page-error-reference.test.js
@@ -0,0 +1,377 @@
+'use strict';
+// The page error contract's canonical code, as references/rules.md publishes it ("Missing Error Handling"): the one
+// reporter every failed data operation goes through, the English error copy, the error bar, the render boundary and the
+// default-export wrapper. A generated page copies that block, so these tests run the block's ACTUAL source rather than
+// a restatement of it: it is transpiled with the TypeScript the plugin vendors (the compile the
+// SDK applies to a page — a transpile, so this is not a type check) and evaluated against a stand-in React that only
+// builds element objects. Nothing here renders through real React; the element trees are inspected as data.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const { loadVendoredTypeScript } = require('../lib/typescript-compiler.js');
+
+const RULES = fs.readFileSync(path.join(__dirname, '..', '..', 'references', 'rules.md'), 'utf8').replace(/\r\n/g, '\n');
+
+// The section from its heading to the next heading of the same level.
+function section(text, heading) {
+ const start = text.indexOf(`\n${heading}\n`);
+ assert.ok(start >= 0, `rules.md has the section "${heading}"`);
+ const next = text.indexOf('\n### ', start + heading.length + 2);
+ return text.slice(start, next < 0 ? text.length : next);
+}
+const MISSING_ERROR_HANDLING = section(RULES, '### 2. Missing Error Handling');
+const blocks = [...MISSING_ERROR_HANDLING.matchAll(/```(?:tsx|typescript)\n([\s\S]*?)\n```/g)].map((match) => match[1]);
+const FOUNDATION = blocks.find((block) => /\bfunction reportPageError\(/.test(block));
+const TELEMETRY = blocks.find((block) => /appInsights\?\.trackException\?\.\(/.test(block));
+
+// The telemetry insertion goes immediately after the reporter's console.error line, the one place the section names.
+function withTelemetry(source) {
+ assert.ok(source && TELEMETRY, 'rules.md publishes the canonical block and its telemetry insertion');
+ const lines = source.split('\n');
+ const at = lines.findIndex((line) => /^\s*console\.error\(/.test(line));
+ assert.ok(at > 0, 'the reporter has its console.error line');
+ return [...lines.slice(0, at + 1), ...TELEMETRY.split('\n'), ...lines.slice(at + 1)].join('\n');
+}
+
+// A stand-in React: elements are plain objects, components are what the page passes to createElement.
+function fakeReact() {
+ class Component {
+ constructor(props) { this.props = props; }
+ }
+ const createElement = (type, props, ...children) => ({
+ type,
+ props: { ...(props || {}), ...(children.length ? { children: children.length === 1 ? children[0] : children } : {}) },
+ });
+ const unsupported = () => { throw new Error('hooks do not run in this test'); };
+ return { Component, createElement, Fragment: 'Fragment', useState: unsupported, useRef: unsupported, useEffect: unsupported, useMemo: unsupported };
+}
+const FLUENT = Object.fromEntries(['Button', 'Input', 'MessageBar', 'MessageBarActions', 'MessageBarBody', 'Text'].map((name) => [name, name]));
+
+let typescript;
+// Transpile and run a page module; its top-level functions are reached through one appended export line.
+function load(source) {
+ assert.ok(source, 'rules.md "Missing Error Handling" publishes the canonical page error block');
+ typescript ||= loadVendoredTypeScript();
+ const exported = 'export { reportPageError, PageErrorBar, PageErrorBoundary, PageBody, translate, ERROR_COPY, PAGE_NAME };';
+ const { outputText } = typescript.transpileModule(`${source}\n${exported}\n`, {
+ fileName: 'page.tsx',
+ compilerOptions: {
+ module: typescript.ModuleKind.CommonJS,
+ target: typescript.ScriptTarget.ES2020,
+ jsx: typescript.JsxEmit.React,
+ esModuleInterop: true,
+ },
+ });
+ const logged = [];
+ const console = { error: (...args) => logged.push(args), log() {}, warn() {} };
+ const React = fakeReact();
+ const modules = { react: React, '@fluentui/react-components': FLUENT, './RuntimeTypes': {} };
+ const require = (name) => {
+ assert.ok(Object.hasOwn(modules, name), `the page imports only what a page may: ${name}`);
+ return modules[name];
+ };
+ const module = { exports: {} };
+ new Function('require', 'module', 'exports', 'console', outputText)(require, module, module.exports, console);
+ return { ...module.exports, logged };
+}
+
+// Every element of a tree, depth first.
+function elements(node, out = []) {
+ if (Array.isArray(node)) { for (const child of node) elements(child, out); return out; }
+ if (node && typeof node === 'object' && 'type' in node) {
+ out.push(node);
+ elements(node.props.children, out);
+ }
+ return out;
+}
+
+test('the Missing Error Handling section publishes the canonical reporter, copy, bar, boundary and wrapper, and no raw-error logging', () => {
+ assert.ok(FOUNDATION, 'the section holds the canonical page error block (types, reportPageError, error copy, PageErrorBar, PageErrorBoundary, wrapper)');
+ assert.ok(TELEMETRY, 'the section holds the telemetry insertion for an authorized failure-reporting request');
+ for (const name of ['type PageErrorKind', 'type PageErrorView', 'type PageErrorTelemetry', 'const PAGE_NAME', 'const ERROR_COPY',
+ 'function translate(', 'function reportPageError(', 'function PageErrorBar(', 'class PageErrorBoundary extends React.Component<',
+ 'function PageBody(', 'const GeneratedComponent = (props: GeneratedComponentProps) => (', 'export default GeneratedComponent;']) {
+ assert.ok(FOUNDATION.includes(name), `the canonical block declares ${name}`);
+ }
+ assert.doesNotMatch(FOUNDATION, /\.\s*trackException\s*(?:\?\.\s*)?\(/, 'the canonical reporter itself emits no telemetry');
+ // The old instruction caught the error and logged the thrown value itself; the only console call left is the reporter's.
+ assert.doesNotMatch(MISSING_ERROR_HANDLING, /Always wrap async dataApi calls in try-catch\./);
+ const consoleCalls = blocks.join('\n').match(/console\.\w+\(/g) || [];
+ assert.deepEqual(consoleCalls, ['console.error('], 'the reporter is the only code in the section that logs, and it logs bounded diagnostics');
+});
+
+test('the reporter keeps a supplied code and the bounded message, logs both exactly once, and returns the view', () => {
+ const page = load(FOUNDATION);
+ assert.equal(page.reportPageError.length, 7, 'five required arguments, then retry and telemetry');
+ const thrown = Object.assign(new Error('Boom'), { code: '0x80040217' });
+ const view = page.reportPageError('Accounts', 'loadAccounts', undefined, thrown, 'read');
+ assert.deepEqual(view, { operation: 'loadAccounts', message: 'Boom', fallbackKey: 'error.read', kind: 'read', code: '0x80040217' });
+ assert.equal(page.logged.length, 1, 'one log line per report');
+ const [prefix, diagnostics, ...rest] = page.logged[0];
+ assert.equal(prefix, '[Accounts] loadAccounts failed');
+ assert.deepEqual(diagnostics, { code: '0x80040217', message: 'Boom' });
+ assert.deepEqual(Object.keys(diagnostics), ['code', 'message']);
+ assert.equal(rest.length, 0, 'the thrown value is never a console argument');
+ // A returned failure: a string third argument IS the code, kept apart from its message.
+ const result = page.reportPageError('Accounts', 'approveOrder', 'not_permitted', 'You do not have permission.', 'write');
+ assert.deepEqual(result, { operation: 'approveOrder', message: 'You do not have permission.', fallbackKey: 'error.write', kind: 'write', code: 'not_permitted' });
+ assert.deepEqual(page.logged[1][1], { code: 'not_permitted', message: 'You do not have permission.' });
+});
+
+test('a code is a non-empty string or a finite number, then the thrown code, errorCode or error.code — never a status or the wording', () => {
+ const page = load(FOUNDATION);
+ const code = (...args) => page.reportPageError('P', 'op', ...args, 'read').code;
+ assert.equal(code(404, 'Not found'), '404', 'a finite number is kept as text');
+ assert.equal(code(Number.NaN, { code: 'E1' }), 'E1', 'a non-finite number is no code');
+ assert.equal(code(' ', { code: 'E1' }), 'E1', 'a blank string is no code');
+ assert.equal(code(undefined, { errorCode: 'E2', error: { code: 'E3' } }), 'E2');
+ assert.equal(code(undefined, { error: { code: 'E3', message: 'nested' } }), 'E3');
+ assert.equal(code(undefined, { code: 'E1', errorCode: 'E2' }), 'E1');
+ assert.equal(code(undefined, { status: 404, statusCode: 404, message: 'HTTP 404 network failure' }), undefined, 'a status and the message wording never become a code');
+ assert.equal(code(` ${'x'.repeat(100)}\n`, undefined), 'x'.repeat(80), 'a code is trimmed and stops at 80 characters');
+ assert.equal(code('E\u0007\tsub', undefined), 'E sub', 'control characters and white space collapse');
+});
+
+test('a message keeps its first line, collapses white space, refuses object and stack-frame text, and stops at 300 characters', () => {
+ const page = load(FOUNDATION);
+ const message = (value) => page.reportPageError('P', 'op', undefined, value, 'read').message;
+ assert.equal(message(' First line\nsecond line'), 'First line');
+ assert.equal(message({ message: 'Outer', error: { message: 'Inner' } }), 'Outer');
+ assert.equal(message({ error: { message: 'Inner' } }), 'Inner');
+ assert.equal(message('[object Object]'), '');
+ assert.equal(message({ message: '[object Object]', error: { message: 'Readable' } }), 'Readable', 'an unusable message falls through to the next field');
+ assert.equal(message('at loadAccounts (page.tsx:12:7)'), '', 'a stack frame is not a message');
+ assert.equal(message({ message: 42 }), '', 'a message is a string, never a coerced object or number');
+ const long = message('y'.repeat(400));
+ assert.equal(long.length, 300);
+ assert.ok(long.endsWith('\u2026'), 'the cut is marked with an ellipsis inside the 300 characters');
+ assert.deepEqual(page.logged.at(-1)[1], { code: '', message: long }, 'the log keeps the same bounded text');
+});
+
+test('a hostile thrown value never breaks the error path, and only the named fields are read', () => {
+ const page = load(FOUNDATION);
+ const throwing = new Proxy({}, { get() { throw new Error('getter'); } });
+ assert.deepEqual(page.reportPageError('P', 'op', undefined, throwing, 'read'), { operation: 'op', message: '', fallbackKey: 'error.read', kind: 'read' });
+ const { proxy, revoke } = Proxy.revocable({}, {});
+ revoke();
+ assert.equal(page.reportPageError('P', 'op', undefined, proxy, 'write').message, '');
+ const partial = { get code() { throw new Error('no code'); }, message: 'Still readable' };
+ assert.equal(page.reportPageError('P', 'op', undefined, partial, 'read').message, 'Still readable', 'one unreadable field leaves the others');
+ const reads = [];
+ const record = (target, prefix) => new Proxy(target, { get(object, key) { reads.push(`${prefix}${String(key)}`); return object[key]; } });
+ const thrown = record({
+ message: 'Outer', stack: 'Error: Outer\n at x (y.js:1:1)', outputs: { UserId: 'x' }, value: 1, body: 'b', detail: 'd',
+ details: ['d'], correlationId: 'c', status: 500, statusCode: 500,
+ error: record({ code: 'E', message: 'm', stack: 's', correlationId: 'c' }, 'error.'),
+ toString() { throw new Error('coerced'); },
+ }, '');
+ page.reportPageError('P', 'op', undefined, thrown, 'read');
+ assert.deepEqual([...new Set(reads)].sort(), ['code', 'error', 'error.code', 'error.message', 'errorCode', 'message']);
+});
+
+test('the kind decides what is shown and what may retry, and the reporter never calls retry', () => {
+ const page = load(FOUNDATION);
+ let calls = 0;
+ const retry = () => { calls += 1; };
+ const view = (kind, code = undefined) => page.reportPageError('P', 'op', code, new Error('Host text'), kind, retry);
+ assert.equal(view('read').retry, retry, 'a read may offer a manual reload');
+ assert.equal(view('network', 'network').retry, retry, 'a pre-dispatch network failure may offer a manual retry');
+ assert.equal(view('write').retry, undefined, 'a write never gains a retry');
+ const indeterminate = view('indeterminate', 'network');
+ assert.equal(indeterminate.retry, undefined, 'an indeterminate result never retries, whatever its code says');
+ assert.equal(indeterminate.code, 'network', 'the host code is kept beside the kind');
+ assert.equal(indeterminate.message, '', 'an indeterminate result shows its fixed copy, not host text');
+ assert.equal(indeterminate.fallbackKey, 'error.indeterminate');
+ const render = view('render');
+ assert.equal(render.retry, undefined);
+ assert.equal(render.message, '');
+ assert.equal(page.logged.at(-1)[1].message, 'Host text', 'suppressed text is still logged, bounded');
+ assert.equal(calls, 0, 'the reporter never invokes a retry');
+});
+
+test('the page name in the log line loses line breaks and closing brackets', () => {
+ const page = load(FOUNDATION);
+ page.reportPageError('Acc]ounts\r\nView', 'loadAccounts', undefined, 'x', 'read');
+ assert.equal(page.logged[0][0], '[AccountsView] loadAccounts failed');
+});
+
+test('telemetry is sent only from the inserted block: one privacy-safe exception per report, never the thrown value', () => {
+ const sent = [];
+ const appInsights = { trackException: (error, properties) => sent.push([error, properties]) };
+ const plain = load(FOUNDATION);
+ plain.reportPageError('P', 'loadAccounts', undefined, new Error('Row Contoso failed'), 'read', undefined, appInsights);
+ assert.equal(sent.length, 0, 'the canonical reporter alone sends nothing, even when handed a telemetry object');
+
+ const page = load(withTelemetry(FOUNDATION));
+ const thrown = Object.assign(new Error('Row Contoso failed'), { code: 'E_FREE_FORM' });
+ const withSink = page.reportPageError('P', 'loadAccounts', undefined, thrown, 'read', undefined, appInsights);
+ assert.equal(sent.length, 1);
+ const [error, properties] = sent[0];
+ assert.ok(error instanceof Error && error !== thrown, 'a new Error, not the thrown value');
+ assert.equal(error.message, 'loadAccounts failed', 'only the fixed operation name — no host text');
+ assert.deepEqual(properties, { outcome: 'failure', category: 'page', source: 'loadAccounts' }, 'a free-form code stays in the local log only');
+ assert.deepEqual(withSink, page.reportPageError('P', 'loadAccounts', undefined, thrown, 'read'), 'telemetry changes nothing the page shows');
+ for (const [code, expected] of [['not_permitted', 'not_permitted'], ['network', 'network'], ['0x80040217', '0x80040217']]) {
+ sent.length = 0;
+ page.reportPageError('P', 'saveOrder', code, 'Denied', 'write', undefined, appInsights);
+ assert.equal(sent[0][1].statusCode, expected, `a recognized code is the statusCode: ${code}`);
+ }
+ sent.length = 0;
+ page.reportPageError('P', 'render', undefined, new Error('x'), 'render', undefined, appInsights);
+ assert.equal(sent[0][1].category, 'errorBoundary');
+ assert.doesNotThrow(() => page.reportPageError('P', 'op', undefined, 'x', 'read'), 'no telemetry object');
+ assert.doesNotThrow(() => page.reportPageError('P', 'op', undefined, 'x', 'read', undefined, {}), 'a telemetry object without trackException');
+});
+
+test('the English error copy holds every fallback key, and translate falls back to the key', () => {
+ const page = load(FOUNDATION);
+ assert.deepEqual(page.ERROR_COPY, {
+ 'error.read': 'Unable to load data. Please try again.',
+ 'error.write': 'The change could not be saved. Refresh before trying again.',
+ 'error.network': 'The request did not go through. You can try again.',
+ 'error.indeterminate': "We couldn't confirm this completed \u2014 refresh before retrying.",
+ 'error.render': 'This page hit a problem and could not render. Refresh the page.',
+ 'error.tryAgain': 'Try again',
+ 'error.builtinFailed': 'The operation failed. No result was displayed.',
+ 'error.builtinUnavailable': 'The selected operation is unavailable in this environment or player. No fallback was attempted.',
+ 'error.builtinUnexpected': 'The operation returned an unexpected response. No result was displayed.',
+ 'error.builtinUnsupported': 'This page player cannot call built-in Dataverse operations.',
+ });
+ assert.equal(page.translate('error.write'), page.ERROR_COPY['error.write']);
+ assert.equal(page.translate('error.unknown'), 'error.unknown');
+});
+
+test('the error bar renders nothing without an error, escaped text with one, and a retry button only for a retry', () => {
+ const page = load(FOUNDATION);
+ assert.equal(page.PageErrorBar({ error: null }), null);
+ const fallback = page.PageErrorBar({ error: { operation: 'op', message: '', fallbackKey: 'error.read', kind: 'read' } });
+ assert.equal(fallback.type, 'MessageBar');
+ assert.equal(fallback.props.intent, 'error');
+ const body = elements(fallback).find((element) => element.type === 'MessageBarBody');
+ assert.equal(body.props.children, page.ERROR_COPY['error.read'], 'an empty message shows the fallback copy');
+ assert.equal(elements(fallback).some((element) => element.type === 'Button'), false, 'no retry, no button');
+ let calls = 0;
+ const retry = () => { calls += 1; };
+ const html = '<img src=x onerror=alert(1)>';
+ const offered = page.PageErrorBar({ error: { operation: 'op', message: html, fallbackKey: 'error.read', kind: 'read', retry } });
+ const tree = elements(offered);
+ assert.equal(tree.find((element) => element.type === 'MessageBarBody').props.children, html, 'host text is a text child, which React escapes');
+ assert.ok(tree.every((element) => !('dangerouslySetInnerHTML' in element.props)), 'never rendered as HTML');
+ const button = tree.find((element) => element.type === 'Button');
+ assert.equal(button.props.onClick, retry, 'the retry is handed to the button, not called while rendering');
+ assert.equal(button.props.children, page.ERROR_COPY['error.tryAgain']);
+ assert.ok(tree.some((element) => element.type === 'MessageBarActions'));
+ assert.equal(calls, 0);
+});
+
+test('the boundary reports a render crash once as a render failure and shows the fixed fallback, with no reset', () => {
+ const page = load(FOUNDATION);
+ assert.deepEqual(page.PageErrorBoundary.getDerivedStateFromError(new Error('x')), { failed: true });
+ const boundary = new page.PageErrorBoundary({ children: 'page' });
+ assert.deepEqual(boundary.state, { failed: false });
+ assert.equal(boundary.render(), 'page', 'healthy: the children render');
+ boundary.componentDidCatch(new Error('Cannot read properties of undefined'));
+ assert.equal(page.logged.length, 1);
+ assert.deepEqual(page.logged[0], [`[${page.PAGE_NAME}] render failed`, { code: '', message: 'Cannot read properties of undefined' }]);
+ boundary.state = { failed: true };
+ const fallback = boundary.render();
+ const tree = elements(fallback);
+ assert.equal(fallback.type, 'MessageBar');
+ assert.equal(tree.find((element) => element.type === 'MessageBarBody').props.children, page.ERROR_COPY['error.render']);
+ assert.equal(tree.some((element) => element.type === 'Button'), false, 'no reset or retry re-renders a crashing tree');
+ assert.doesNotMatch(FOUNDATION, /\bsetState\s*\(/, 'the boundary never sets its own state back');
+});
+
+test('the default export only forwards its props, unchanged, to PageBody inside the boundary', () => {
+ const page = load(FOUNDATION);
+ const props = { dataApi: { queryTable() {} }, pageInput: { recordId: 'x' } };
+ const root = page.default(props);
+ assert.equal(root.type, page.PageErrorBoundary);
+ const child = root.props.children;
+ assert.equal(child.type, page.PageBody);
+ assert.deepEqual(Object.keys(child.props), ['dataApi', 'pageInput']);
+ assert.equal(child.props.dataApi, props.dataApi, 'the same dataApi object');
+});
+
+// ---------- the rule text and the templates a builder copies ----------
+
+const BUILDER = fs.readFileSync(path.join(__dirname, '..', '..', 'agents', 'genpage-page-builder.md'), 'utf8').replace(/\r\n/g, '\n');
+const squashed = (text) => text.replace(/\s+/g, ' ');
+const CRITICAL_RULES = RULES.slice(RULES.indexOf('\n## Critical Rules\n'), RULES.indexOf('\n## Supported Libraries\n'));
+// The numbered Critical Rule `n`, from its number to the next one.
+function criticalRule(n) {
+ const match = new RegExp(`\\n${n}\\. ([\\s\\S]*?)(?=\\n\\d+\\. |\\n---)`).exec(CRITICAL_RULES);
+ assert.ok(match, `rules.md has Critical Rule ${n}`);
+ return squashed(match[1]);
+}
+// Does a TSX source parse? A transpile with diagnostics on reports syntax only — it is not a type check.
+function parses(source, label) {
+ typescript ||= loadVendoredTypeScript();
+ const { diagnostics } = typescript.transpileModule(source, {
+ fileName: 'page.tsx',
+ reportDiagnostics: true,
+ compilerOptions: { module: typescript.ModuleKind.CommonJS, target: typescript.ScriptTarget.ES2020, jsx: typescript.JsxEmit.React },
+ });
+ assert.deepEqual((diagnostics || []).map((entry) => typescript.flattenDiagnosticMessageText(entry.messageText, '\n')), [], `${label} parses`);
+}
+const WRAPPER = /const GeneratedComponent = \(props: (\w+)\) => \(\n\s*<PageErrorBoundary>\n\s*<PageBody \{\.\.\.props\} \/>\n\s*<\/PageErrorBoundary>\n\);\n\nexport default GeneratedComponent;/;
+
+test('Critical Rule 22 states the one error contract, and Rule 3 makes the boundary the single class exception', () => {
+ assert.equal(criticalRule(22), squashed(`**Consistent errors**: Route failed data operations through the page's single top-level
+ \`reportPageError\`, retain bounded code and message diagnostics, and put its returned view in the operation's error state. Render
+ errors as escaped Fluent MessageBar text with localized application fallbacks. Offer manual retry only for proven-safe reads or the
+ documented pre-dispatch Custom API network result; never retry an indeterminate result automatically. Wrap PageBody in the page's
+ one top-level React PageErrorBoundary. Instrument only explicitly authorized failure sites, only through the helper. Expected
+ null/empty states are not failures. See “Missing Error Handling” for the canonical patterns and the static check's declared limits.`));
+ const rule3 = criticalRule(3);
+ assert.match(rule3, /each as separate top-level function \(no nesting\)/, 'Rule 3 still forbids nesting');
+ assert.match(rule3, /The one exception is a single top-level React class, `PageErrorBoundary` \(Rule 22\)/);
+ assert.match(rule3, /Event handlers and loaders that close over a component's state stay inside that component/);
+ assert.match(rule3, /No new library or runtime dependency/);
+ // The section the rule points at states what the eval check reads and what it does not: today, nothing.
+ assert.match(squashed(MISSING_ERROR_HANDLING), /What the eval check reads, and what it does not\./);
+ assert.match(squashed(MISSING_ERROR_HANDLING), /The eval suite does not grade a page's error handling yet/);
+});
+
+test('rules.md Component Structure and both builder templates mount PageBody inside the boundary', () => {
+ const structure = RULES.slice(RULES.indexOf('\n## Component Structure\n'), RULES.indexOf('\n## Layout and Styling\n'));
+ const block = /```typescript\n([\s\S]*?)\n```/.exec(structure)[1];
+ assert.match(block, /function PageBody\(props: GeneratedComponentProps\) \{\n\s*const \{ dataApi, pageInput \} = props;/);
+ assert.match(block, WRAPPER);
+ assert.match(block, /The page error block of "Missing Error Handling" \(Common Errors\), copied unchanged/);
+ assert.doesNotMatch(block, /const GeneratedComponent = \(props: GeneratedComponentProps\) => \{/, 'the old component body is gone');
+ parses(block, 'rules.md Component Structure');
+ const templates = BUILDER.slice(BUILDER.indexOf('\n### Component Structure\n'), BUILDER.indexOf('\n### Mandatory Rules\n'));
+ const [dataverse, mock] = [...templates.matchAll(/```typescript\n([\s\S]*?)\n```/g)].map((match) => match[1]);
+ assert.ok(dataverse && mock, 'the builder shows the Dataverse and the mock template');
+ assert.equal(WRAPPER.exec(dataverse)?.[1], 'GeneratedComponentProps');
+ assert.equal(WRAPPER.exec(mock)?.[1], 'Props', 'the mock page keeps its local Props');
+ assert.match(dataverse, /function PageBody\(props: GeneratedComponentProps\) \{\n\s*const \{ dataApi, pageInput \} = props;/);
+ assert.match(mock, /function PageBody\(props: Props\) \{\n\s*const \{ pageInput \} = props;/);
+ assert.doesNotMatch(mock, /RuntimeTypes/, 'a mock page imports nothing from ./RuntimeTypes');
+ for (const [label, source] of [['the Dataverse template', dataverse], ['the mock template', mock]]) {
+ assert.match(source, /The page error block of rules\.md "Missing Error Handling"[\s\S]*copied unchanged/, `${label} copies the canonical block`);
+ parses(source, label);
+ }
+ assert.match(squashed(templates), /copy the page error block of `rules\.md` → \*Common Errors\* → \*Missing Error Handling\* \*\*unchanged\*\*/);
+});
+
+test('the builder routes every failure through the five-argument reporter, with the boundary as its one class', () => {
+ const rules = squashed(BUILDER.slice(BUILDER.indexOf('\n### Mandatory Rules\n'), BUILDER.indexOf('\n### Localization\n')));
+ assert.doesNotMatch(rules, /all async `dataApi` calls wrapped in try-catch/, 'the old try/catch-only instruction is gone');
+ assert.match(rules, /\*\*Error handling\*\* — every failed data operation goes through the page's one `reportPageError` with its five required arguments — `reportPageError\(PAGE_NAME, '<operation>', code, error, '<kind>'\)`/);
+ assert.match(rules, /rendered by `PageErrorBar`/);
+ assert.match(rules, /never retry a write or an indeterminate result/);
+ assert.match(rules, /\*\*Top-level functions\*\* — components and utilities as separate top-level functions, no nesting; the page's one class is `PageErrorBoundary`/);
+ // The connector and Custom API fragments the builder shows report their failures, never set a bare string.
+ const examples = BUILDER.slice(BUILDER.indexOf('\n### Connector-backed data\n'), BUILDER.indexOf('\n## Step 6'));
+ assert.doesNotMatch(examples, /\bsetError\(|if \(!response\.ok\) \{ return; \}|isSubmitting/);
+ assert.match(examples, /if \(!response\.ok\) \{ setWeather\(\{ weather: null, error: reportPageError\(PAGE_NAME, 'loadWeather', undefined, undefined, 'read', retryWeather\) \}\); return; \}/);
+ const order = ['if (res.indeterminate)', "if (res.error?.code === 'indeterminate')", "if (!res.ok && res.error?.code === 'network')", 'if (!res.ok)', 'const status = res.outputs?.NewStatus;'];
+ const at = order.map((guard) => examples.indexOf(guard));
+ assert.ok(at.every((index, i) => index > 0 && (i === 0 || index > at[i - 1])), `the Custom API guards come in order before the outputs: ${at}`);
+ for (const report of ["'indeterminate')); return; }", "'network', retryApprove)); return; }", "res.error?.message, 'write')); return; }", "undefined, error, 'write'));"]) {
+ assert.ok(examples.includes(report), `the Custom API fragment reports: ${report}`);
+ }
+});
\ No newline at end of file
diff --git a/plugins/model-apps/scripts/tests/page-ownership-clear.test.js b/plugins/model-apps/scripts/tests/page-ownership-clear.test.js
index d78f07dab..7f62d9c91 100644
--- a/plugins/model-apps/scripts/tests/page-ownership-clear.test.js
+++ b/plugins/model-apps/scripts/tests/page-ownership-clear.test.js
@@ -8,6 +8,7 @@ const ownership = require('../lib/page-ownership-records.js');
const snapshots = require('../lib/apply-snapshot-store.js');
const { loadCli } = require('./helpers/cli-harness.js');
const { fakeGenpage } = require('./helpers/fake-genpage.js');
+const { withPageType } = require('./helpers/page-component-type.js');
const ENV = 'https://contoso.crm.dynamics.com';
const OTHER_ENV = 'https://fabrikam.crm.dynamics.com';
@@ -108,11 +109,12 @@ for (const outcome of ['deleted', 'confirmed absent']) {
return [];
},
// The pages in their saved layer, which is where teardown looks for them; the navigation's saved layer is not modelled here, so reading it fails as it does without a client.
+ // The page table's component type is answered in front: the build's pages join the spec's solution (lib/page-solution.js).
dataverse: {
- get: async (url) => {
+ get: withPageType(async (url) => {
if (!url.startsWith('/uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()')) throw new Error(`not modelled: ${url}`);
return { status: 200, body: { value: state.page ? [{ uxagentprojectid: ID, name: 'Overview', componentstate: 0 }] : [] } };
- },
+ }),
},
createWebResource: async (o) => { state.manifest = Buffer.from(o.content, 'utf8').toString('base64'); return { id: 'manifest-id' }; },
updateWebResource: async (id, o) => { state.manifest = Buffer.from(o.content, 'utf8').toString('base64'); },
diff --git a/plugins/model-apps/scripts/tests/page-ownership.test.js b/plugins/model-apps/scripts/tests/page-ownership.test.js
index fbefce589..17095f182 100644
--- a/plugins/model-apps/scripts/tests/page-ownership.test.js
+++ b/plugins/model-apps/scripts/tests/page-ownership.test.js
@@ -9,6 +9,7 @@ const { runTeardown: realRunTeardown } = require('../lib/sdk-teardown.js');
const { runSdkBuild } = require('../lib/sdk-build.js');
const { loadCli } = require('./helpers/cli-harness.js');
const { fakeGenpage } = require('./helpers/fake-genpage.js');
+const { withPageType } = require('./helpers/page-component-type.js');
const { recordPageCreation, readPageOwnership, recordPagePending, readPendingCreations, checkPageOwnershipClearable, recordPageTeardown } = require('../lib/page-ownership-records.js');
const { sha256 } = require('../lib/hash.js');
@@ -172,9 +173,10 @@ function sdkForPages(opts = {}) {
// The app's CURRENT (saved, unpublished) layer, read through the Dataverse client as download reads it:
// appmodules and sitemaps by RetrieveUnpublishedMultiple, e.g. { value: [{ appmoduleidunique, componentstate: 1 }] }.
// By default it equals the published navigation (nothing pending), as on an environment with no unpublished edit.
+ // The page table's component type is answered in front of it, uncounted: the build's pages join the spec's solution (lib/page-solution.js).
if (!opts.noDataverse) {
sdk.dataverse = {
- get: async (url) => {
+ get: withPageType(async (url) => {
// The pages in their saved layer, whichever of the rows the platform answers (see `rows` above). Not a read of the navigation, so it is not counted in `draftReads`.
if (url.startsWith('/uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()')) {
state.pageReads.push(url);
@@ -204,7 +206,7 @@ function sdkForPages(opts = {}) {
return { status: 200, body: { value: [{ sitemapxml: xml, componentstate: 1 }] } };
}
throw new Error(`unexpected test read: ${url}`);
- },
+ }),
};
}
return { sdk, state };
diff --git a/plugins/model-apps/scripts/tests/page-plan.test.js b/plugins/model-apps/scripts/tests/page-plan.test.js
index db2bfb7a7..6eaa86ed2 100644
--- a/plugins/model-apps/scripts/tests/page-plan.test.js
+++ b/plugins/model-apps/scripts/tests/page-plan.test.js
@@ -200,6 +200,20 @@ test('the approved design contract reaches the worker', () => {
assert.equal(require('../../../../evals/model-apps/genpage/lib/assertions-layer-1.js').validateGenpagePlanSchema(bare).length, 0);
});
+// A look of the maker's own (AB#6320143): the plan used to say "Fluent UI V9 defaults" or the tokens, whatever the maker asked for, so every page came out in the default
+// model-driven look. `design.style` leads the Styling line as `Maker-requested:`, which the page-builder applies instead of the defaults (references/rules.md).
+test('a maker-requested style in design.style leads the Styling line as Maker-requested:, sanitised, with the tokens after it', () => {
+ const s = spec();
+ s.design = { style: 'navy #0b2545 primary, gold #c9a227 accent,\nGeorgia headings | 2px corners (from: screenshot)', accentColor: '#0b2545' };
+ const md = buildPagePlan(s, { workingDir: '/wd' });
+ assert.match(md, /^- Styling: Maker-requested: navy #0b2545 primary, gold #c9a227 accent, Georgia headings \/ 2px corners \(from: screenshot\) \(Fluent UI V9 components; also Accent color: #0b2545\)$/m);
+ assert.equal(require('../../../../evals/model-apps/genpage/lib/assertions-layer-1.js').validateGenpagePlanSchema(md).length, 0);
+ const alone = buildPagePlan({ ...spec(), design: { style: 'warm earth palette #8b5e3c' } }, { workingDir: '/wd' });
+ assert.match(alone, /^- Styling: Maker-requested: warm earth palette #8b5e3c \(Fluent UI V9 components\)$/m);
+ // Without one the line is what it was: the tokens, or the defaults.
+ assert.match(buildPagePlan({ ...spec(), design: { accentColor: '#0f6cbd' } }, { workingDir: '/wd' }), /^- Styling: Fluent UI V9 tokens — Accent color: #0f6cbd$/m);
+});
+
test('the plan declares Mode so the worker can pick the right identity rule', () => {
assert.match(buildPagePlan(spec(), { workingDir: '/wd' }), /- Mode: app-builder/);
});
diff --git a/plugins/model-apps/scripts/tests/pageref-resolver.test.js b/plugins/model-apps/scripts/tests/pageref-resolver.test.js
index b014d7daf..ad8103309 100644
--- a/plugins/model-apps/scripts/tests/pageref-resolver.test.js
+++ b/plugins/model-apps/scripts/tests/pageref-resolver.test.js
@@ -14,6 +14,9 @@ const { RESOLVED_PAGES, REFUSED_PAGES, HIDDEN_CLOSING_TAG_PAGES, TYPE_HEAD_PAGES
const { OBJECT_DIVISION_PAGE, MISREAD_PAGES, HIDDEN_CALL_PAGE, PREFIX_INCREMENT_PAGE, TEMPLATE_LINE_PAGE, JSX_TEXT_PAGE, ELEMENT_AFTER_OPERATOR_PAGES, ELEMENT_LOOKALIKE_PAGES, ELEMENT_PAGE_TOKEN_LINE, FUNCTION_TYPE_PAGES, FUNCTION_TYPE_CALL_LINE, LONG_KEY, lookBehindPage, runnable } = require('./helpers/misread-page.js');
const { AMBIGUITY_KINDS } = require('../lib/source-literals.js');
const { pageStructureProblems } = require('../lib/page-structure.js');
+// These tests hold the lexer to its own rules — what it reads for certain, what it reports as a guess, and what a guess costs a page — so they read pages with
+// the lexer alone. Where the lexer guesses, the gates ask the TypeScript parser (typescript-views.js), which parser-check.test.js tests.
+require('../lib/typescript-views.js').setParserCheck(false);
const {
extractNavTargets,
navReferencedKeys,
diff --git a/plugins/model-apps/scripts/tests/parser-check.test.js b/plugins/model-apps/scripts/tests/parser-check.test.js
new file mode 100644
index 000000000..838546f56
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/parser-check.test.js
@@ -0,0 +1,379 @@
+'use strict';
+// The parser check (lib/typescript-views.js). The lexer (source-literals.js) has no parser, and where it guesses what a construct is it says so (`onAmbiguity`):
+// the navigation oracle (pageref-resolver.js) then trusted nothing at or after the guess, and the structure gate (page-structure.js) read the page as the lexer
+// guessed it — a generic call signature in an interface, read as an element whose text runs on, made a complete page look cut off. Now both ask the TypeScript
+// compiler the pages are compiled with, where the lexer guessed, and read the page as it parses it. These tests hold three things:
+// - the views the parser's tokens are turned into are the lexer's own, character for character, on every page the lexer reads with no guess — the committed
+// pages and the generated valid pages — and the structure checks give the same answers from either, so the gates' rules read the parser's views as they read
+// the lexer's;
+// - with it, every valid page TypeScript parses resolves its navigation call, wherever the lexer guessed, and the data after it (a regex and a string that hold
+// the text of a call) is never rewritten;
+// - the shapes the lexer refused after a guess resolve, and pass the structure gate; and where the parser does not answer — a page it does not parse, or a JSX
+// attribute string after trivia, which other compilers read differently — the lexer's reading stands, as it did.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const { execFileSync } = require('node:child_process');
+const { blankLiterals, blankNonCodePreservingTemplateExpressions, commentRanges, endsMidStatement, findElisionMarker, hasDefaultExport, hasUnbalancedBrackets } = require('../lib/source-literals.js');
+const { typescriptViews, guessedPageViews, setParserCheck } = require('../lib/typescript-views.js');
+const { loadVendoredTypeScript } = require('../lib/typescript-compiler.js');
+const { resolvePageRefs, strayPageRefs, navigationFrontier } = require('../lib/pageref-resolver.js');
+const { pageStructureProblems } = require('../lib/page-structure.js');
+const { validPages, heldOpenLinePages, NAVIGATION_CALL } = require('./helpers/valid-pages.js');
+const { loadBabelOracle } = require('./helpers/typescript-oracle.js');
+
+const REPO = path.resolve(__dirname, '..', '..', '..', '..');
+const ID = '11111111-1111-4111-8111-111111111111';
+const ts = loadVendoredTypeScript();
+const parses = (code) => ts.createSourceFile('page.tsx', code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+const navigationCalls = (source) => {
+ let found = 0;
+ const visit = (node) => {
+ if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === 'navigateTo') found += 1;
+ ts.forEachChild(node, visit);
+ };
+ visit(source);
+ return found;
+};
+// Whether the lexer guessed on the page, and the kinds it named.
+const guesses = (code) => {
+ const kinds = new Set();
+ blankNonCodePreservingTemplateExpressions(code, { onAmbiguity: (at, kind) => kinds.add(kind) });
+ return kinds;
+};
+// What the oracle does with a page: whether it resolves the page's call (and changes nothing else), and the guess it names where it does not.
+const reading = (code) => {
+ const deployed = resolvePageRefs(new Map([['page', { code }]]), new Map([['detail', ID]])).deployment.get('page');
+ const frontier = navigationFrontier(code);
+ return { deployed, resolves: deployed === code.replace('"PAGEREF_detail"', `"${ID}"`), kind: frontier ? frontier.kind : null };
+};
+const DECOY_REGEX = ` const decoyRegex = /${NAVIGATION_CALL.replace(/;$/, '')}/;`;
+const DECOY_STRING = ` const decoyString = '</T></U></b></A></B></W></Cmp>;${NAVIGATION_CALL}//';`;
+const withDecoys = (code) => code.replace(` ${NAVIGATION_CALL}`, `${DECOY_REGEX}\n${DECOY_STRING}\n ${NAVIGATION_CALL}`);
+const decoysIntact = (deployed) => deployed.includes(DECOY_REGEX) && deployed.includes(DECOY_STRING);
+const committedPages = () => execFileSync('git', ['-C', REPO, 'ls-files', '*.tsx'], { encoding: 'utf8' }).split('\n').filter(Boolean)
+ .map((file) => [file, fs.readFileSync(path.join(REPO, file), 'utf8')]);
+
+test('parser check: the views built from TypeScript\'s parse are the lexer\'s own on every page the lexer reads with no guess, and the structure checks agree on them', () => {
+ const stats = { pages: 0, compared: 0, structure: 0 };
+ const differ = [];
+ const compare = (what, code, structure) => {
+ stats.pages += 1;
+ if (guesses(code).size > 0) return;
+ const views = typescriptViews(code);
+ if (views === null) return;
+ stats.compared += 1;
+ if (views.literal !== blankLiterals(code)) differ.push(`${what}: the literal view`);
+ if (views.keep !== blankNonCodePreservingTemplateExpressions(code)) differ.push(`${what}: the executable view`);
+ const comments = commentRanges(code).map(({ start, end }) => `${start}-${end}`).join(' ');
+ if (views.comments.map(({ start, end }) => `${start}-${end}`).join(' ') !== comments) differ.push(`${what}: the comments`);
+ if (!structure) return;
+ stats.structure += 1;
+ for (const [name, check] of [['hasDefaultExport', hasDefaultExport], ['hasUnbalancedBrackets', hasUnbalancedBrackets], ['endsMidStatement', endsMidStatement], ['findElisionMarker', findElisionMarker]]) {
+ if (check(code, views) !== check(code)) differ.push(`${what}: ${name}`);
+ }
+ };
+ // The structure checks, from either view: on every committed page, and on one generated page in five.
+ for (const [file, code] of committedPages()) compare(file, code, true);
+ let index = 0;
+ for (const page of validPages()) compare(`${page.group}: ${page.name}`, page.code, index++ % 5 === 0);
+ assert.deepEqual(differ.slice(0, 8), [], `${differ.length} differences`);
+ assert.ok(stats.compared >= 25000 && stats.structure >= 5000, JSON.stringify(stats));
+});
+
+test('parser check: with the parser asked where the lexer guessed, every valid page TypeScript parses resolves its call, and the data after it is never rewritten', () => {
+ const stats = { valid: 0, guessed: 0, resolved: 0, keptGuess: 0 };
+ // The pages the lexer guessed on, by the first guess it named — each of them resolved now.
+ const byKind = new Map();
+ const refused = [];
+ const unsound = [];
+ for (const page of validPages()) {
+ const source = parses(page.code);
+ if (source.parseDiagnostics.length > 0 || navigationCalls(source) !== 1) continue;
+ stats.valid += 1;
+ const kinds = guesses(page.code);
+ const here = reading(page.code);
+ if (kinds.size > 0) {
+ stats.guessed += 1;
+ const first = [...kinds][0];
+ if (here.resolves) byKind.set(first, (byKind.get(first) || 0) + 1);
+ }
+ if (here.resolves) stats.resolved += 1;
+ else if (kinds.has('jsx-attribute')) stats.keptGuess += 1;
+ else refused.push(`${page.group}: ${JSON.stringify(page.name)} (${here.kind})`);
+ const decoyed = withDecoys(page.code);
+ if (parses(decoyed).parseDiagnostics.length === 0 && !decoysIntact(reading(decoyed).deployed)) unsound.push(`${page.group}: ${JSON.stringify(page.name)}`);
+ }
+ assert.deepEqual(unsound.slice(0, 5), [], 'a page whose data is read as code and rewritten');
+ assert.deepEqual(refused.slice(0, 8), [], `${refused.length} valid pages are refused`);
+ // The pages the lexer guessed on are many, of each kind it names on the generated valid pages (`keyword`, `operator` and `brace` are met by the shapes below), and
+ // all of them resolve now.
+ assert.ok(stats.valid >= 25000 && stats.guessed >= 300, JSON.stringify(stats));
+ for (const kind of ['angle', 'generic', 'newline']) assert.ok(byKind.get(kind) > 0, `${kind}: ${JSON.stringify([...byKind])}`);
+});
+
+// The shapes the lexer refused after a guess, each with a navigation call after it: the lexer names the guess, and with the parser asked the call resolves and the
+// page passes the structure gate. [what, snippet, the guess the lexer names]
+const WRAP = (snippet) => `import * as React from "react";\n${snippet}\nexport default function Page() {\n ${NAVIGATION_CALL}\n return null;\n}\n`;
+const ELEMENT = 'void <span>(MARK); // note</span>;';
+const GUESSED_SHAPES = [
+ // A generic call signature in an interface: the lexer reads an element whose text runs to the end of the file, and the page as cut off.
+ ['a generic call signature in an interface', 'interface Api { <U>(x: U): U; }', 'generic'],
+ ['a generic construct signature in a type literal', 'type Make = { new <U>(x: U): U };', 'generic'],
+ // A `>` before a `/` or a `<`, a `/` on a later line than its operand, and a `<` after the cut `>=`.
+ ['type arguments and then a division', 'declare const f: <A>(x: number) => number; declare const x: number;\nconst v = f<number> / x / 2;', 'angle'],
+ ['a comparison and then a regex', 'const a = 1;\nconst c = a > /re/.test("x") ? 1 : 2;', 'angle'],
+ ['a division on the next line', 'declare const x: number;\nconst r5 = x\n/ 2 / 3;', 'newline'],
+ ['the end of type arguments and an initializer that is a generic arrow', 'type X = unknown; type A<T> = T;\nlet x: A<number>= <T extends X>(y: T): T => y;', 'operator'],
+ // Class heads the lexer does not read: a function expression or an object literal for the base, type arguments after a class expression.
+ ['a function expression for a class\'s base', `const registry = { Adapter: class extends function () {} {}, render() { ${ELEMENT} } };`, 'generic'],
+ ['an object literal for a class\'s base', `const registry = { Adapter: class extends {} {}, render() { ${ELEMENT} } };`, 'generic'],
+ ['type arguments after a class expression', `const registry = { Adapter: class extends class {}<T> {}, render() { ${ELEMENT} } };`, 'brace'],
+ // Type parameters on keyword-named methods.
+ ['a method named `in` with type parameters', 'interface I { in<U>(y: U): void; }', 'generic'],
+ ['a method named `new` with type parameters', 'interface I { new<U>(y: U): void; }', 'generic'],
+ ['a method named `return` with type parameters', 'interface I { return<U>(y: U): void; }', 'generic'],
+ ['`get` and `set` with type parameters', 'class C { get<T>(x: T) { return x; } set<T>(x: T) { return x; } }', 'keyword'],
+ ['methods named `await` and `yield` with type parameters', 'interface I { await<U>(y: U): void; yield<U>(y: U): void; }', 'keyword'],
+ ['an optional method named `delete` with type parameters', 'interface I { delete?<U>(y: U): void; }', 'generic'],
+];
+
+test('parser check: the shapes the lexer refused after a guess resolve their navigation call, and pass the structure gate', () => {
+ for (const [what, snippet, kind] of GUESSED_SHAPES) {
+ const code = WRAP(snippet);
+ assert.equal(parses(code).parseDiagnostics.length, 0, `TypeScript parses ${what}`);
+ assert.ok(guesses(code).has(kind), `${what}: the lexer guesses "${kind}" (${[...guesses(code)].join(', ')})`);
+ assert.equal(reading(code).resolves, true, `${what}: the call resolves`);
+ assert.deepEqual(strayPageRefs(code), [], `${what}: no token is stray`);
+ assert.deepEqual(pageStructureProblems(code), [], `${what}: the page is complete`);
+ // With the lexer alone the call is refused, as it was.
+ setParserCheck(false);
+ try {
+ assert.equal(reading(code).resolves, false, `${what}: the lexer alone refuses it`);
+ } finally {
+ setParserCheck(true);
+ }
+ }
+});
+
+// JSX text with a `//` note on one line and a later line that starts with a `/`, where a member of a type may begin (valid-pages.js, heldOpenLinePages): the lexer
+// cannot tell the element from the members of a type that hold the closing tag in the regex the `/` begins, and refuses the call after it; TypeScript reads the
+// element, and with it asked the call resolves.
+test('parser check: JSX text with a note and a later line that starts with a "/", where a member of a type may begin, resolves the call after it', () => {
+ let valid = 0;
+ const wrong = [];
+ for (const page of heldOpenLinePages()) {
+ const source = parses(page.code);
+ if (source.parseDiagnostics.length > 0 || navigationCalls(source) !== 1) continue;
+ valid += 1;
+ if (!guesses(page.code).has('generic')) wrong.push(`${page.group} / ${page.name}: no guess`);
+ if (!reading(page.code).resolves) wrong.push(`${page.group} / ${page.name}: not resolved`);
+ }
+ assert.deepEqual(wrong.slice(0, 5), []);
+ assert.ok(valid >= 150, `only ${valid} pages were valid`);
+});
+
+test('parser check: a call signature in an interface no longer reads as a cut, and the structure gate still refuses what TypeScript reads as cut off or elided', () => {
+ const head = 'interface Api { <U>(x: U): U; }\n';
+ const complete = `${head}export default function P() { return null; }\n`;
+ assert.deepEqual(pageStructureProblems(complete), []);
+ // A cut inside the export: TypeScript reports it, so the lexer's reading stands, and the page is refused.
+ assert.ok(pageStructureProblems(`${head}export default function P() { return <div>`).length > 0);
+ // A dangling `let`: TypeScript's parser reads it as a name, which strict code reserves (Babel refuses it), so the parse vouches for nothing, the lexer's reading
+ // stands, and the page is refused as cut off.
+ assert.equal(guessedPageViews(`${complete}let`).views, null);
+ assert.ok(pageStructureProblems(`${complete}let`).includes('stops mid-statement — the file looks truncated'));
+ // A page with no default export is refused from the parser's views as from the lexer's.
+ assert.match(pageStructureProblems(`${head}const x = 1;\n`).join('\n'), /no complete default export/);
+ // A comment that elides code, after the construct the lexer misread (to it, the comment was the text of an element).
+ assert.deepEqual(pageStructureProblems(`${head}// TODO: wire the handler\nexport default function P() { return null; }\n`), ['contains a TODO/FIXME comment — the page is incomplete']);
+ // A markdown fence around the code is still prose.
+ assert.match(pageStructureProblems(`\`\`\`tsx\n${complete}\`\`\`\n`).join('\n'), /markdown code fence|truncated|default export/);
+});
+
+test('parser check: where the parser does not answer, the lexer\'s reading stands — a page TypeScript does not parse, and a JSX attribute string after trivia', () => {
+ // TypeScript reports an error in the page (a `>` in JSX text): the guess stands, and the call after it is not resolved.
+ const unparsed = WRAP('interface Api { <U>(x: U): U; }\nconst bad = <b>a > b</b>;');
+ assert.ok(parses(unparsed).parseDiagnostics.length > 0);
+ assert.equal(typescriptViews(unparsed), null);
+ assert.equal(reading(unparsed).resolves, false);
+ // A JSX attribute string whose quote follows trivia and whose text holds a backslash: TypeScript reads it with escapes, Babel and esbuild without, so the two end
+ // it at different quotes — the parser does not settle that, and the guess stays.
+ const attribute = WRAP("const e = <C x= '\\'/>;' />;");
+ assert.equal(parses(attribute).parseDiagnostics.length, 0);
+ assert.ok(guesses(attribute).has('jsx-attribute'));
+ assert.equal(reading(attribute).resolves, false);
+ assert.equal(navigationFrontier(attribute).kind, 'jsx-attribute');
+});
+
+// What the parser vouches for is told from its own parse, not from the lexer's guesses: an earlier misread can make the lexer skip a JSX attribute string after trivia,
+// which it then never names (`jsx-attribute`), and grammar that only TypeScript's parser takes names no guess at all. Babel reads both differently, or not at all.
+const BABEL_CALLS = (babel, code) => {
+ let tree;
+ try {
+ tree = babel.parse(code, { sourceType: 'module', plugins: ['jsx', 'typescript'] });
+ } catch {
+ return null;
+ }
+ let found = 0;
+ const walk = (node) => {
+ if (!node || typeof node.type !== 'string') return;
+ if (node.type === 'CallExpression' && node.callee.type === 'Identifier' && node.callee.name === 'navigateTo') found += 1;
+ for (const [key, value] of Object.entries(node)) {
+ if (key === 'loc' || key === 'start' || key === 'end' || key === 'extra' || key === 'comments' || key === 'leadingComments' || key === 'trailingComments') continue;
+ if (Array.isArray(value)) for (const child of value) walk(child);
+ else if (value && typeof value === 'object') walk(value);
+ }
+ };
+ walk(tree.program);
+ return found;
+};
+// [what, attribute after `<C x=`, whether TypeScript and Babel read it alike]: the quote right after the `=` is a JSX string to both, and so is a string with no backslash.
+const ATTRIBUTES = [
+ ['a string after a space, with an escaped quote', " '\\'/>;//' />", false],
+ ['a string after a comment, with an escaped quote', "/* c */'\\'/>;//' />", false],
+ ['a string after a line break, with a backslash', "\n 'a\\\\' />", false],
+ ['a string right after the `=`', "'a' />", true],
+ ['a string after a space, with no backslash', " 'a' />", true],
+];
+
+test('parser check: a JSX attribute string after trivia keeps the navigation oracle\'s frontier, though a misread hid it from the lexer', (t) => {
+ const babel = loadBabelOracle();
+ // The page the parsers read differently: TypeScript reads the call; Babel ends the string at its first quote and reads the call in a comment.
+ const differ = 'const n = {valueOf(){return 12;}}/2; const e = <C x= \'\\\'/>;//\' />; navigateTo({pageType:"generative",pageId:"PAGEREF_detail"});\n'
+ + 'export default function P(){return null;}';
+ assert.equal(parses(differ).parseDiagnostics.length, 0);
+ assert.equal(navigationCalls(parses(differ)), 1);
+ assert.deepEqual([...guesses(differ)], ['brace'], 'the lexer names the misread, and not the attribute it hid');
+ assert.equal(navigationFrontier(differ)?.kind, 'brace', 'the frontier stands');
+ const { deployment, residual } = resolvePageRefs(new Map([['page', { code: differ }]]), new Map([['detail', ID]]));
+ assert.equal(deployment.get('page'), differ, 'nothing is rewritten');
+ assert.deepEqual(residual.map(({ token }) => token), ['PAGEREF_detail'], 'the token is reported');
+ assert.equal(guessedPageViews(differ).views, null);
+ if (babel) assert.equal(BABEL_CALLS(babel, differ), 0, 'Babel reads no call');
+ // Each guess the lexer names (GUESSED_SHAPES) before each attribute: where the two parsers read the string alike the parser vouches for the page and the call resolves;
+ // where they do not, the frontier stands, whether or not the lexer saw the attribute after its guess.
+ let compared = 0;
+ for (const [what, snippet, kind] of GUESSED_SHAPES) {
+ for (const [attributeWhat, attribute, alike] of ATTRIBUTES) {
+ const code = WRAP(`${snippet}\nconst e = <C x=${attribute};`);
+ const name = `${what}, ${attributeWhat}`;
+ assert.equal(parses(code).parseDiagnostics.length, 0, `TypeScript parses ${name}`);
+ assert.ok(guesses(code).has(kind), `${name}: the lexer guesses "${kind}"`);
+ assert.equal(reading(code).resolves, alike, `${name}: the call resolves`);
+ assert.equal(guessedPageViews(code).views !== null, alike, `${name}: the parser vouches for it`);
+ if (babel && alike) assert.equal(BABEL_CALLS(babel, code), 1, `${name}: Babel reads the call`);
+ compared += 1;
+ }
+ }
+ assert.equal(compared, GUESSED_SHAPES.length * ATTRIBUTES.length);
+ if (!babel) t.diagnostic('no Babel parser oracle: set BABEL_ORACLE_PATH to an @babel/parser package to compare the readings');
+});
+
+test('parser check: the structure gate reads a page with a JSX attribute string after trivia as the lexer does, as the navigation oracle does', () => {
+ const babel = loadBabelOracle();
+ // The page Babel refuses (the string ends at its escaped quote): the structure gate reads it as the lexer does, and refuses it as cut off, as before.
+ const refused = "interface Api { <U>(x:U):U; }\nconst e = <C x= 'it\\'s'/>;\nexport default function P(){return null;}";
+ assert.equal(parses(refused).parseDiagnostics.length, 0);
+ assert.equal(pageStructureProblems(refused).length, 3);
+ if (babel) assert.equal(BABEL_CALLS(babel, refused), null, 'Babel refuses the page');
+ // Each guess before each attribute the two parsers read differently: the structure gate's answer is the lexer's, whether or not the lexer saw the attribute.
+ for (const [what, snippet] of GUESSED_SHAPES) {
+ for (const [attributeWhat, attribute, alike] of ATTRIBUTES) {
+ if (alike) continue;
+ const code = WRAP(`${snippet}\nconst e = <C x=${attribute};`);
+ const problems = pageStructureProblems(code);
+ setParserCheck(false);
+ try {
+ assert.deepEqual(problems, pageStructureProblems(code), `${what}, ${attributeWhat}: the structure gate reads it as the lexer does`);
+ } finally {
+ setParserCheck(true);
+ }
+ }
+ }
+});
+
+// Grammar TypeScript's parser takes and leaves to its checker, which Babel's parser refuses, on a page the lexer guessed on: the parser vouches for nothing, and the
+// lexer's reading stands — as on a page TypeScript does not parse. Their neighbours, which both parse, are read as the parser reads them. [what, declaration, both parse it]
+const ONLY_TYPESCRIPT_TAKES = [
+ ['`await` for a name', 'function f2() { return await; }', false], ['`yield` for a name', 'const y = (x: number) => yield;', false],
+ ['`let` for a name', 'declare const v: number; const w = let;', false], ['`static` for a variable', 'declare const s: number; const t2 = static;', false],
+ ['a reserved word for a type\'s name', 'type I = if;', false], ['a JSDoc nullable type', 'type J = ?string;', false], ['a JSDoc non-null type', 'type K = string!;', false],
+ ['the JSDoc any type', 'type L = *;', false], ['a predicate outside a return type', 'type P = asserts x;', false], ['`readonly` before a name', 'type R = readonly string;', false],
+ ['an empty list of type arguments', 'type E = Array<>;', false],
+ ['`readonly` before an array type', 'type R2 = readonly string[];', true], ['a method named `yield`', 'interface Y { yield<U>(y: U): void; }', true],
+ ['a property named `let`', 'const o = { let: 1, static: 2 }; const q = o.let;', true], ['a predicate in a return type', 'declare function isS(x: unknown): x is string;', true],
+];
+
+test('parser check: grammar only TypeScript\'s parser takes keeps the lexer\'s reading; what both parsers take is read as TypeScript parses it', () => {
+ const babel = loadBabelOracle();
+ for (const [what, declaration, both] of ONLY_TYPESCRIPT_TAKES) {
+ const code = WRAP(`interface Api { <U>(x: U): U; }\n${declaration}`);
+ assert.equal(parses(code).parseDiagnostics.length, 0, `TypeScript parses ${what}`);
+ assert.ok(guesses(code).has('generic'), `${what}: the lexer guesses`);
+ assert.equal(reading(code).resolves, both, `${what}: the call resolves`);
+ assert.equal(pageStructureProblems(code).length === 0, both, `${what}: the structure gate reads it as ${both ? 'TypeScript parses it' : 'the lexer does'}`);
+ assert.equal(guessedPageViews(code).views !== null, both, `${what}: the parser vouches for it`);
+ if (babel) assert.equal(BABEL_CALLS(babel, code) !== null, both, `${what}: Babel ${both ? 'parses' : 'refuses'} it`);
+ }
+});
+
+// With the Babel oracle: every generated valid page the lexer guessed on and the parser vouches for (whose calls the gates then read as TypeScript parses the page) is
+// one Babel parses too, with the same navigation calls.
+test('parser check: every guessed page the parser vouches for is one Babel parses, with the calls TypeScript reads', (t) => {
+ const babel = loadBabelOracle();
+ if (!babel) return t.skip('no Babel parser oracle: set BABEL_ORACLE_PATH to an @babel/parser package to run it');
+ let vouched = 0;
+ const differ = [];
+ for (const page of [...validPages(), ...heldOpenLinePages()]) {
+ if (guesses(page.code).size === 0 || !reading(page.code).resolves) continue;
+ vouched += 1;
+ const calls = BABEL_CALLS(babel, page.code);
+ if (calls !== navigationCalls(parses(page.code))) differ.push(`${page.group}: ${JSON.stringify(page.name)} (Babel: ${calls})`);
+ }
+ assert.deepEqual(differ.slice(0, 5), [], `${differ.length} pages`);
+ assert.ok(vouched >= 300, `vouched for ${vouched} guessed pages`);
+});
+
+// The pages built to make the lexer misread (helpers/misread-page.js), run in a JavaScript engine: with the parser asked where the lexer guessed, whatever the resolver
+// rewrites leaves every regex as it was, and every call the page makes navigates to the page id — the call the lexer hid included.
+test('parser check: a page the lexer misreads, resolved as TypeScript parses it, makes every call it made with its page id, and rewrites no regex', () => {
+ const vm = require('node:vm');
+ const { MISREAD_PAGES, OBJECT_DIVISION_PAGE_RUNNABLE, runnable } = require('./helpers/misread-page.js');
+ const exec = (code) => {
+ const calls = [];
+ const tested = [];
+ const context = vm.createContext({ navigateTo: (options) => calls.push(options.pageId), __tested: tested });
+ vm.runInContext('RegExp.prototype.test = function () { __tested.push(this.source); return false; };', context);
+ vm.runInContext(code, context, { timeout: 1000 });
+ return { calls, tested };
+ };
+ for (const [name, code] of [['the object-division page', OBJECT_DIVISION_PAGE_RUNNABLE], ...['brace', 'paren', 'keyword'].map((kind) => [kind, runnable(MISREAD_PAGES[kind].code)])]) {
+ const before = exec(code);
+ const { deployment, residual } = resolvePageRefs(new Map([['page', { code }]]), new Map([['detail', ID]]));
+ const after = exec(deployment.get('page'));
+ assert.deepEqual(after.tested, before.tested, `${name}: no regex is rewritten`);
+ assert.equal(after.calls.length, before.calls.length, `${name}: the page makes every call it made`);
+ assert.deepEqual(after.calls, before.calls.map((pageId) => (pageId === 'PAGEREF_detail' ? ID : pageId)), `${name}: every call navigates to the page id`);
+ // A token left in the text of a regex or a string is data, which no call hands over: it is not rewritten, and the residue reports it (no token may stand there).
+ for (const left of residual) assert.ok(!after.calls.includes(left.token), `${name}: a token left is no call's`);
+ }
+});
+
+test('parser check: the views of a text are kept for the next check of the same text, and the lexer\'s own tests can turn the parser off', () => {
+ // The views are kept for the last few texts asked about: the oracle reads a page several times per build (resolve, stray, residual).
+ const code = WRAP('interface Api { <U>(x: U): U; }');
+ const first = typescriptViews(code);
+ assert.ok(first !== null);
+ assert.equal(typescriptViews(code), first, 'the same text is not parsed again');
+ // The seam the lexer's own tests use: off, the parser vouches for nothing.
+ setParserCheck(false);
+ try {
+ assert.equal(typescriptViews(code), null);
+ } finally {
+ setParserCheck(true);
+ }
+ // A test seam for another compiler: given one, the views are built with it (and not kept).
+ assert.deepEqual(typescriptViews(code, { ts }).keep, first.keep);
+});
diff --git a/plugins/model-apps/scripts/tests/plan-sections.test.js b/plugins/model-apps/scripts/tests/plan-sections.test.js
new file mode 100644
index 000000000..9536a2127
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/plan-sections.test.js
@@ -0,0 +1,61 @@
+'use strict';
+// The three plan-section primitives moved from the eval harness into the plugin, unchanged: the eval module re-exports the very
+// same functions (so every evaluator and every plugin reader agree), and their behaviour is pinned on the plan shapes the
+// schema documents — level-two headings only, any letter case, the first table with the named columns, rows to the first
+// non-row line.
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const path = require('node:path');
+
+const sections = require('../lib/plan-sections.js');
+const PLAN_EVIDENCE = path.join(__dirname, '..', '..', '..', '..', 'evals', 'model-apps', 'genpage', 'lib', 'plan-evidence.js');
+
+test('the eval harness re-exports the plugin\'s plan-section primitives, the same functions', () => {
+ const evals = require(PLAN_EVIDENCE);
+ for (const name of ['planSection', 'findMarkdownTable', 'parseMarkdownRows']) {
+ assert.equal(typeof sections[name], 'function', `${name} is a plugin export`);
+ assert.equal(evals[name], sections[name], `plan-evidence.js re-exports the plugin's ${name}`);
+ }
+});
+
+const PLAN = [
+ '# Genpage Plan',
+ '',
+ '## User Requirements',
+ 'Show accounts.',
+ '',
+ '## pages',
+ '| Page | File | Purpose | Entities |',
+ '|------|------|---------|----------|',
+ '| Overview | overview.tsx | Summary | account |',
+ '| | | | |',
+ '| Details | details.tsx | One record | account |',
+ 'Trailing prose ends the table.',
+ '| Stray | stray.tsx | not a row of the table | account |',
+ '',
+ '### Pages (2 total)',
+ '## Per-Page Specifications',
+ '### Overview',
+].join('\n');
+
+test('planSection reads one level-two section by its heading, in any letter case, to the next level-two heading', () => {
+ assert.equal(sections.planSection(PLAN, 'User Requirements'), 'Show accounts.');
+ assert.match(sections.planSection(PLAN, 'Pages'), /^\| Page \| File[\s\S]*### Pages \(2 total\)$/);
+ assert.equal(sections.planSection(PLAN, 'Pages (2 total)'), null, 'a level-three heading is not a section');
+ assert.equal(sections.planSection(PLAN, 'Missing'), null);
+ assert.equal(sections.planSection('', 'Pages'), null);
+ assert.equal(sections.planSection(PLAN, 'Per-Page Specifications'), '### Overview');
+});
+
+test('parseMarkdownRows reads the first table with the named columns, skipping empty rows, up to the first non-row line', () => {
+ const body = sections.planSection(PLAN, 'Pages');
+ assert.deepEqual(sections.parseMarkdownRows(body, ['page', 'FILE']), [
+ { page: 'Overview', file: 'overview.tsx', purpose: 'Summary', entities: 'account' },
+ { page: 'Details', file: 'details.tsx', purpose: 'One record', entities: 'account' },
+ ]);
+ assert.deepEqual(sections.parseMarkdownRows(body, ['Page', 'Key']), [], 'no table with a Key column');
+ const table = sections.findMarkdownTable(body, ['Purpose']);
+ assert.equal(table.lineIndex, 0);
+ assert.deepEqual(table.headers, ['page', 'file', 'purpose', 'entities']);
+ assert.equal(sections.findMarkdownTable('no table here', ['Page']), null);
+});
diff --git a/plugins/model-apps/scripts/tests/primary-attribute-keys.test.js b/plugins/model-apps/scripts/tests/primary-attribute-keys.test.js
new file mode 100644
index 000000000..9bcf730ed
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/primary-attribute-keys.test.js
@@ -0,0 +1,173 @@
+'use strict';
+
+// `entities[].primaryAttribute` takes the keys the build reads from it — schemaName, displayName, autoNumberFormat, required and maxLength —
+// and no other. Before it had this list a misspelled key (`maxlength`, `autonumberFormat`) or a Dataverse name for one (`requiredLevel`)
+// validated clean and the build ignored it, so the table was made without the length, the number format or the level the author wrote.
+// It now gets what an unknown key of the table itself gets (ENTITY_KEYS) and of a form's fieldOptions entry: an error, which names the
+// key, the key it most likely meant and the keys that are allowed, on every path that builds, plans, lints or provisions. Read-only paths
+// keep reading such a spec, as they do for a fieldOptions key — an earlier release accepted it and built the table without the option:
+// the structural profile (teardown, preview) and verification (`primaryAttributeKeys: 'warn'`, which only verify-model-app.js passes) take
+// it as a warning in the same words.
+
+const { test } = require('node:test');
+const assert = require('node:assert');
+const { validateAppSpec } = require('../lib/app-spec.js');
+const { validateProvisionInput } = require('../lib/provision-input.js');
+const { lintSpec } = require('../lint-app-spec.js');
+const { buildModelApp } = require('../build-model-app.js');
+const { provisionEntities } = require('../provision-entities.js');
+const { primaryColumnOptionFields } = require('../lib/download-column-options.js');
+const { scriptsMatching } = require('./helpers/production-scripts.js');
+const { BUILDING_PROFILES, nameColumn, appSpec, provisionInput, watchedDeps } = require('./helpers/column-gate-specs.js');
+
+const ALLOWED = '(allowed: schemaName, displayName, autoNumberFormat, required, maxLength)';
+// What each slip is told, after the table and the key: the key it most likely meant, or what to write instead.
+const SLIPS = [
+ ['maxlength', 100, " — did you mean 'maxLength'?"],
+ ['autonumberFormat', 'T-{SEQNUM:5}', " — did you mean 'autoNumberFormat'?"],
+ ['requiredLevel', 'ApplicationRequired', ' — the level is \'required\': true, "recommended" or false'],
+ ['type', 'Text', " — the primary name column is always a single line of text: leave 'type' out (for an auto-numbered name, give 'autoNumberFormat')"],
+ ['description', 'The ticket title', ''],
+];
+const specFinding = (key, hint) => `entity new_ticket: unknown key '${key}' on primaryAttribute${hint} ${ALLOWED}`;
+const inputFinding = (key, hint) => `entity 'new_ticket': unknown key '${key}' on primaryAttribute${hint} ${ALLOWED}`;
+const withKey = (key, value) => nameColumn({ [key]: value });
+
+// --- the authoring gates refuse it -----------------------------------------------------------------------------------------------------
+
+test('an unknown primaryAttribute key is an error that names the key, the key it most likely meant and the allowed keys', () => {
+ for (const [key, value, hint] of SLIPS) {
+ const result = validateAppSpec(appSpec({ primaryAttribute: withKey(key, value) }), { profile: 'deploy' });
+ assert.strictEqual(result.ok, false, key);
+ assert.deepStrictEqual(result.errors, [specFinding(key, hint)], key);
+ assert.deepStrictEqual(result.warnings, [], key);
+ }
+});
+
+test('every profile that builds or plans a build refuses it', () => {
+ for (const profile of BUILDING_PROFILES) {
+ const result = validateAppSpec(appSpec({ primaryAttribute: withKey('maxlength', 100) }), { profile });
+ assert.strictEqual(result.ok, false, profile);
+ assert.deepStrictEqual(result.errors, [specFinding('maxlength', " — did you mean 'maxLength'?")], profile);
+ }
+});
+
+test('lint reports it as a schema error under every profile that builds', () => {
+ for (const options of [undefined, ...BUILDING_PROFILES.map((profile) => ({ profile }))]) {
+ const report = lintSpec(appSpec({ primaryAttribute: withKey('requiredLevel', 'ApplicationRequired') }), options);
+ const label = JSON.stringify(options);
+ assert.strictEqual(report.ok, false, label);
+ assert.ok(report.errors.includes(`schema: ${specFinding('requiredLevel', SLIPS[2][2])}`), `${label}\n${JSON.stringify(report.errors)}`);
+ }
+});
+
+test('the build refuses it before any call, dry run or apply', async () => {
+ // With navigation, so that without the rule the dry run would plan the build and the apply would call the SDK.
+ const spec = () => ({ ...appSpec({ primaryAttribute: withKey('maxlength', 100) }), appShell: { areas: [{ label: 'A', groups: [{ label: 'G', subAreas: [{ entity: 'new_ticket', title: 'Tickets' }] }] }] } });
+ for (const options of [{ apply: true }, { apply: false }]) {
+ const d = watchedDeps();
+ const result = await buildModelApp(spec(), { env: 'https://contoso.crm.dynamics.com', ...options }, { sdk: d.sdk, provisionSdk: d.provision });
+ assert.strictEqual(result.ok, false, JSON.stringify(options));
+ assert.deepStrictEqual(result.errors, [specFinding('maxlength', " — did you mean 'maxLength'?")], JSON.stringify(options));
+ assert.deepStrictEqual(d.touched, [], `${JSON.stringify(options)}: nothing was called`);
+ }
+});
+
+test('the provision-entities gate (the /genpage path) refuses it in its own wording, before anything is called', async () => {
+ for (const [key, value, hint] of SLIPS) {
+ const validated = validateProvisionInput(provisionInput({ primaryAttribute: withKey(key, value) }));
+ assert.strictEqual(validated.ok, false, key);
+ assert.deepStrictEqual(validated.errors, [inputFinding(key, hint)], key);
+ }
+ for (const options of [{ apply: true }, { apply: false }]) {
+ const d = watchedDeps();
+ const result = await provisionEntities(provisionInput({ primaryAttribute: withKey('autonumberFormat', 'T-{SEQNUM:5}') }), options, { sdk: d.sdk, provision: d.provision });
+ assert.strictEqual(result.ok, false, JSON.stringify(options));
+ assert.deepStrictEqual(result.errors, [inputFinding('autonumberFormat', " — did you mean 'autoNumberFormat'?")]);
+ assert.deepStrictEqual(d.touched, [], `${JSON.stringify(options)}: nothing was called`);
+ }
+});
+
+// --- the read-only paths keep reading it ----------------------------------------------------------------------------------------------
+
+test('the structural profile (teardown, preview) takes it as a warning in the same words', () => {
+ const result = validateAppSpec(appSpec({ primaryAttribute: withKey('maxlength', 100) }), { profile: 'structural' });
+ assert.strictEqual(result.ok, true, JSON.stringify(result.errors));
+ assert.deepStrictEqual(result.errors, []);
+ assert.deepStrictEqual(result.warnings, [specFinding('maxlength', " — did you mean 'maxLength'?")]);
+});
+
+test('primaryAttributeKeys: "warn" (verification) moves it to the warnings, and only the value "warn" does', () => {
+ const lenient = validateAppSpec(appSpec({ primaryAttribute: withKey('maxlength', 100) }), { profile: 'deploy', primaryAttributeKeys: 'warn' });
+ assert.strictEqual(lenient.ok, true, JSON.stringify(lenient.errors));
+ assert.deepStrictEqual(lenient.warnings, [specFinding('maxlength', " — did you mean 'maxLength'?")]);
+ // The other downgrades are independent of it, and any other value keeps the error.
+ for (const options of [{}, { primaryAttributeKeys: 'WARN' }, { primaryAttributeKeys: true }, { columnValues: 'warn' }, { fieldOptionKeys: 'warn' }, { relationshipCollisions: 'warn' }]) {
+ const strict = validateAppSpec(appSpec({ primaryAttribute: withKey('maxlength', 100) }), { profile: 'deploy', ...options });
+ assert.strictEqual(strict.ok, false, JSON.stringify(options));
+ assert.deepStrictEqual(strict.errors, [specFinding('maxlength', " — did you mean 'maxLength'?")], JSON.stringify(options));
+ }
+ // Any other problem of the spec is still an error beside it.
+ const spec = appSpec({ primaryAttribute: withKey('maxlength', 100) });
+ spec.entities[0].columns.push({ schemaName: 'new_bad', displayName: 'Bad', type: 'Nope' });
+ const mixed = validateAppSpec(spec, { profile: 'deploy', primaryAttributeKeys: 'warn' });
+ assert.deepStrictEqual(mixed.errors, ["entity new_ticket: column new_bad has unknown type 'Nope'"]);
+ assert.deepStrictEqual(mixed.warnings, [specFinding('maxlength', " — did you mean 'maxLength'?")]);
+});
+
+test('no script but the verify CLI passes the primaryAttribute downgrade', () => {
+ assert.deepStrictEqual(scriptsMatching(/primaryAttributeKeys\s*:\s*['"]warn['"]/), ['verify-model-app.js']);
+});
+
+// --- what must not move ---------------------------------------------------------------------------------------------------------------
+
+test('every key the build reads validates clean, on both gates', () => {
+ const full = nameColumn({ autoNumberFormat: 'T-{SEQNUM:5}', required: 'recommended', maxLength: 120 });
+ for (const profile of [...BUILDING_PROFILES, 'structural']) {
+ const result = validateAppSpec(appSpec({ primaryAttribute: full }), { profile });
+ assert.deepStrictEqual(result.errors, [], profile);
+ assert.deepStrictEqual(result.warnings, [], profile);
+ }
+ assert.deepStrictEqual(validateProvisionInput(provisionInput({ primaryAttribute: full })), { ok: true, errors: [] });
+});
+
+test('the name column a download writes validates clean', () => {
+ const downloaded = { schemaName: 'new_name', displayName: 'Name', ...primaryColumnOptionFields({ MaxLength: 850, AutoNumberFormat: 'T-{SEQNUM:5}' }) };
+ assert.deepStrictEqual(Object.keys(downloaded).sort(), ['autoNumberFormat', 'displayName', 'maxLength', 'schemaName']);
+ const result = validateAppSpec(appSpec({ primaryAttribute: downloaded }), { profile: 'plan', reconstructed: true });
+ assert.deepStrictEqual(result.errors, []);
+ assert.deepStrictEqual(result.warnings, []);
+});
+
+test('a key named like an Object.prototype member is reported as itself, with no native function in the message', () => {
+ for (const key of ['constructor', 'toString', '__proto__x']) {
+ const result = validateAppSpec(appSpec({ primaryAttribute: withKey(key, 'x') }), { profile: 'deploy' });
+ assert.deepStrictEqual(result.errors, [specFinding(key, '')], key);
+ assert.ok(!/native code/.test(result.errors.join(' ')), key);
+ }
+});
+
+test('a primaryAttribute that is not an object, or is missing, gets the errors it always got and no key finding', () => {
+ for (const [value, expected] of [
+ [undefined, ['entity new_ticket: primaryAttribute.schemaName required']],
+ ['new_name', ['entity new_ticket: primaryAttribute.schemaName required']],
+ [['new_name'], ['entity new_ticket: primaryAttribute.schemaName required']],
+ ]) {
+ const spec = appSpec();
+ if (value === undefined) delete spec.entities[0].primaryAttribute;
+ else spec.entities[0].primaryAttribute = value;
+ const result = validateAppSpec(spec, { profile: 'deploy' });
+ assert.deepStrictEqual(result.errors, expected, JSON.stringify(value));
+ }
+});
+
+test('a primaryAttribute whose keys cannot be enumerated is a finding, not a crash', () => {
+ const trap = new Proxy(nameColumn(), { ownKeys() { throw new Error('boom'); } });
+ const spec = appSpec({ primaryAttribute: trap });
+ let result;
+ assert.doesNotThrow(() => { result = validateAppSpec(spec, { profile: 'deploy' }); });
+ assert.deepStrictEqual(result.errors, ['entity new_ticket: primaryAttribute could not be inspected — enumerating its keys threw']);
+ let input;
+ assert.doesNotThrow(() => { input = validateProvisionInput(provisionInput({ primaryAttribute: trap })); });
+ assert.deepStrictEqual(input.errors, ["entity 'new_ticket': primaryAttribute could not be inspected — enumerating its keys threw"]);
+});
diff --git a/plugins/model-apps/scripts/tests/printers-whole-before-exit.test.js b/plugins/model-apps/scripts/tests/printers-whole-before-exit.test.js
index 489079290..8cdc2b6fd 100644
--- a/plugins/model-apps/scripts/tests/printers-whole-before-exit.test.js
+++ b/plugins/model-apps/scripts/tests/printers-whole-before-exit.test.js
@@ -256,26 +256,26 @@ test('genpage-worker-output.js prints a result that quotes the longest path a co
// ── Every script's own usage error ────────────────────────────────────────────────────────────────────────────────────────────────────────────────
-// The script, the arguments that reach its flag check (a verb where it takes one), and the environment it needs to get there.
+// The script, and the arguments that reach its flag check (a verb where it takes one).
const USAGE_CASES = [
['add-page-to-solution.js'], ['ai-preflight.js'], ['apps.js', ['list']], ['build-model-app.js'], ['connector.js', ['operations']],
['create-connection-reference.js'], ['dataverse-request.js'], ['download-model-app.js'], ['genpage.js', ['list']], ['list-connections.js'],
- ['list-custom-apis.js', [], { GENPAGE_ENABLE_CUSTOM_API: '1' }], ['list-languages.js'], ['list-tables.js'], ['preview-app.js'], ['preview-form.js'],
+ ['list-custom-apis.js'], ['list-languages.js'], ['list-tables.js'], ['preview-app.js'], ['preview-form.js'],
['promote-intent-pages.js'], ['provision-entities.js'], ['provision-solution.js'], ['solution-settings.js', ['template']], ['teardown-model-app.js'],
['verify-model-app.js'], ['write-app-spec-doc.js'], ['write-page-plan.js'],
-].map(([script, args = [], env = {}]) => ({ script, args, env }));
+].map(([script, args = []]) => ({ script, args }));
test('every script prints a usage error that quotes a message of a megabyte whole on stderr, with exit 1 — through both kinds of stream', async () => {
const text = hugeFailureText('flag', BIG);
- await eachAtOnce(USAGE_CASES, ({ script, args, env }) => assertWholeBothWays([path.join(SCRIPTS, script), ...args], {
- preloads: [HUGE], env: { ...env, HUGE_FAILURE: 'flag', HUGE_FAILURE_SIZE: String(BIG) }, status: 1, stream: 'stderr', text: `✗ ${text}\n`,
+ await eachAtOnce(USAGE_CASES, ({ script, args }) => assertWholeBothWays([path.join(SCRIPTS, script), ...args], {
+ preloads: [HUGE], env: { HUGE_FAILURE: 'flag', HUGE_FAILURE_SIZE: String(BIG) }, status: 1, stream: 'stderr', text: `✗ ${text}\n`,
}, script).then(({ queued }) => assert.equal(queued.stdout, '', `${script}: nothing on stdout`)));
});
test('every script\'s usage error is what it always was: the message, then the usage text, on stderr, with exit 1', async () => {
const text = hugeFailureText('flag', 10);
- await eachAtOnce(USAGE_CASES, async ({ script, args, env }) => {
- const ran = await runScript([path.join(SCRIPTS, script), ...args], { preloads: [HUGE], env: { ...env, HUGE_FAILURE: 'flag', HUGE_FAILURE_SIZE: '10' } });
+ await eachAtOnce(USAGE_CASES, async ({ script, args }) => {
+ const ran = await runScript([path.join(SCRIPTS, script), ...args], { preloads: [HUGE], env: { HUGE_FAILURE: 'flag', HUGE_FAILURE_SIZE: '10' } });
assert.equal(ran.status, 1, `${script}: ${ran.own}${ran.stderr}`);
assert.equal(ran.stdout, '', `${script}: nothing on stdout`);
assert.match(ran.stderr, new RegExp(`^✗ ${text.replace(/[<>]/g, '\\$&')}\\n\\S[^]*\\n$`), `${script}: ${JSON.stringify(ran.stderr.slice(0, 200))}`);
diff --git a/plugins/model-apps/scripts/tests/promote-intent-pages.test.js b/plugins/model-apps/scripts/tests/promote-intent-pages.test.js
index b5333d8db..dc87f89a4 100644
--- a/plugins/model-apps/scripts/tests/promote-intent-pages.test.js
+++ b/plugins/model-apps/scripts/tests/promote-intent-pages.test.js
@@ -15,6 +15,9 @@ const { makeTempDir } = require('./helpers/temp-dirs.js');
const CLI = path.join(__dirname, '..', 'promote-intent-pages.js');
const { OBJECT_DIVISION_PAGE, MISREAD_PAGES, HIDDEN_CALL_PAGE, PREFIX_INCREMENT_PAGE, TEMPLATE_LINE_PAGE, JSX_TEXT_PAGE, ELEMENT_AFTER_OPERATOR_PAGES, ELEMENT_LOOKALIKE_PAGES, ELEMENT_PAGE_TOKEN_LINE, FUNCTION_TYPE_PAGES } = require('./helpers/misread-page.js');
+// What a guess costs a page where the TypeScript parser does not settle it (lib/typescript-views.js): the script these tests run reads the page with the lexer
+// alone (MODEL_APPS_LEXER_ALONE). parser-check.test.js holds what the parser settles, and the tests below what promotion does with it.
+const lexerAlone = (t) => { process.env.MODEL_APPS_LEXER_ALONE = '1'; t.after(() => { delete process.env.MODEL_APPS_LEXER_ALONE; }); };
const GOOD = 'export default function P() { return <div>ok</div>; }\n';
@@ -207,7 +210,8 @@ test('refuses a page holding a PAGEREF_ token no navigation rewrite resolves, an
// A page whose `/` after an object literal hides a call: JavaScript makes both navigations, but the lexer reads the `/` after the object literal on line 4 as a regex
// and the `/*` in `/\/*$/` as a comment over the second call. Promotion used to pass it, and the build then shipped the second
// token unresolved. The token is refused here — where the page can be regenerated — naming it and the `/`.
-test('refuses the page whose "/" after an object literal hides a navigation call, naming the call and the "/"', () => {
+test('refuses the page whose "/" after an object literal hides a navigation call, naming the call and the "/"', (t) => {
+ lexerAlone(t);
const spec = twoPageSpec();
spec.pages[0].navigatesTo = [{ targetKey: 'detail' }];
const dir = makeWorkspace(spec, { 'overview.tsx': OBJECT_DIVISION_PAGE, 'detail.tsx': GOOD });
@@ -226,7 +230,8 @@ test('refuses the page whose "/" after an object literal hides a navigation call
// Every misread page (tests/helpers/misread-page.js) is refused at its first guess, naming each token after it
// and the kind and position of the guess, and the spec is left as it was. A page regenerated here costs a retry; one that reached the
// build would ship a dead link.
-test('refuses each misread page, naming the token and the guess', () => {
+test('refuses each misread page, naming the token and the guess', (t) => {
+ lexerAlone(t);
const spec = twoPageSpec();
spec.pages[0].navigatesTo = [{ targetKey: 'detail' }];
for (const [name, { kind, frontier, code, reaching }] of Object.entries(MISREAD_PAGES)) {
@@ -314,7 +319,19 @@ test('refuses a token in the regex after an element whose text looks like a para
}
});
-test('names the guess when a declared call is absent, once, and only a guess the page has', () => {
+// The same pages, read as the TypeScript parser reads them where the lexer guessed (lib/typescript-views.js): every call is seen, and the pages promote.
+test('promotes the pages the lexer misreads, read as TypeScript parses them', () => {
+ const spec = twoPageSpec();
+ spec.pages[0].navigatesTo = [{ targetKey: 'detail' }];
+ for (const code of [OBJECT_DIVISION_PAGE, HIDDEN_CALL_PAGE.code]) {
+ const dir = makeWorkspace(spec, { 'overview.tsx': code, 'detail.tsx': GOOD });
+ const r = run(dir);
+ assert.equal(r.code, 0, r.stderr);
+ }
+});
+
+test('names the guess when a declared call is absent, once, and only a guess the page has', (t) => {
+ lexerAlone(t);
const spec = twoPageSpec();
spec.pages[0].navigatesTo = [{ targetKey: 'detail' }];
const { code, frontier } = HIDDEN_CALL_PAGE;
diff --git a/plugins/model-apps/scripts/tests/relationship-metadata.test.js b/plugins/model-apps/scripts/tests/relationship-metadata.test.js
index 9ca74c5cd..9e1d292e8 100644
--- a/plugins/model-apps/scripts/tests/relationship-metadata.test.js
+++ b/plugins/model-apps/scripts/tests/relationship-metadata.test.js
@@ -217,3 +217,101 @@ test('sameRelationship matches endpoints case-insensitively and rejects a differ
},
), true);
});
+
+// --- Lookup-details mode (lookup discovery: lib/lookup-metadata.js) ---------------------------------------------------------------
+// The default read above is unchanged; this mode adds two scalars, reads every page, and fails rather than shrinks.
+const DETAILS = 'SchemaName,ReferencedEntity,ReferencingAttribute,ReferencedAttribute,ReferencingEntityNavigationPropertyName';
+const DETAILS_PATH = `/EntityDefinitions(LogicalName='opportunity')/ManyToOneRelationships?$select=${DETAILS}`;
+const NEXT = 'https://contoso.crm.dynamics.com/api/data/v9.2/EntityDefinitions(LogicalName=\'opportunity\')/ManyToOneRelationships?$select=x&$skiptoken=2';
+const ACCOUNT = { SchemaName: 'opportunity_customer_accounts', ReferencedEntity: 'account', ReferencingAttribute: 'customerid', ReferencedAttribute: 'accountid', ReferencingEntityNavigationPropertyName: 'customerid_account' };
+const CONTACT = { SchemaName: 'opportunity_customer_contacts', ReferencedEntity: 'contact', ReferencingAttribute: 'customerid', ReferencedAttribute: 'contactid', ReferencingEntityNavigationPropertyName: 'customerid_contact' };
+
+function pagedClient(pages) {
+ const paths = [];
+ const answer = (p) => {
+ paths.push(p);
+ const hit = pages[p];
+ if (hit === undefined) return { status: 404, body: { error: { code: '0x80060888', message: `no route for ${p}` } } };
+ if (hit instanceof Error) throw hit;
+ return hit;
+ };
+ return { paths, get: async (p) => answer(p), getAbsolute: async (url) => answer(url) };
+}
+
+test('lookup details: the added scalars, every page, and the rows keep them', async () => {
+ const c = pagedClient({
+ [DETAILS_PATH]: { status: 200, body: { value: [ACCOUNT], '@odata.nextLink': NEXT } },
+ [NEXT]: { status: 200, body: { value: [CONTACT] } },
+ });
+ const read = await readRelationshipsOf(c, 'Opportunity', 'ManyToOne', undefined, { lookupDetails: true });
+ assert.deepStrictEqual(c.paths, [DETAILS_PATH, NEXT]);
+ assert.deepStrictEqual(read, { ok: true, rows: [
+ { schemaName: 'opportunity_customer_accounts', type: 'OneToMany', referencedEntity: 'account', referencingEntity: 'opportunity', referencingAttribute: 'customerid', referencedAttribute: 'accountid', navigationProperty: 'customerid_account' },
+ { schemaName: 'opportunity_customer_contacts', type: 'OneToMany', referencedEntity: 'contact', referencingEntity: 'opportunity', referencingAttribute: 'customerid', referencedAttribute: 'contactid', navigationProperty: 'customerid_contact' },
+ ] });
+ assert.ok(!c.paths.some((p) => /DisplayName|LocalizedLabels/.test(p)), 'still a label-free read');
+});
+
+test('lookup details: a failed, malformed or repeated page fails the whole read — never a shorter candidate list', async () => {
+ for (const [label, second] of [
+ ['a refused second page', { status: 503, body: { error: { code: '0x80040216', message: 'Service unavailable.' } } }],
+ ['a second page with no value list', { status: 200, body: {} }],
+ ['a second page that loops back', { status: 200, body: { value: [CONTACT], '@odata.nextLink': NEXT } }],
+ ['a transport failure', Object.assign(new Error('socket hang up'), { code: 'ECONNRESET' })],
+ ]) {
+ const c = pagedClient({ [DETAILS_PATH]: { status: 200, body: { value: [ACCOUNT], '@odata.nextLink': NEXT } }, [NEXT]: second });
+ const read = await readRelationshipsOf(c, 'opportunity', 'ManyToOne', undefined, { lookupDetails: true });
+ assert.equal(read.ok, false, label);
+ assert.equal(read.rows, undefined, `${label}: no partial rows`);
+ }
+ const refused = pagedClient({ [DETAILS_PATH]: { status: 200, body: { value: [ACCOUNT], '@odata.nextLink': NEXT } }, [NEXT]: { status: 503, body: { Error: { code: '0x80040216', message: 'Service unavailable.' } } } });
+ const read = await readRelationshipsOf(refused, 'opportunity', 'ManyToOne', undefined, { lookupDetails: true });
+ assert.equal(read.error, 'Service unavailable.', 'the service\'s words, from the capitalized envelope too');
+ assert.equal(read.status, 503);
+ const coded = pagedClient({ [DETAILS_PATH]: { status: 500, body: { error: { code: '0x80044151', message: 'SQL timeout expired.' } } } });
+ const timedOut = await readRelationshipsOf(coded, 'opportunity', 'ManyToOne', undefined, { lookupDetails: true });
+ assert.equal(timedOut.error, 'SQL timeout expired.');
+ assert.equal(timedOut.answered.code, '0x80044151', 'the OData error rides along for the retry policy');
+ assert.ok(!Object.keys(timedOut).includes('answered'), '…not enumerable');
+});
+
+test('lookup details: a missing table is a failure, not a table without lookups; the default read keeps its meaning', async () => {
+ const missing = { status: 404, body: { error: { code: '0x80060888', message: "EntityMetadata With Id = LogicalName='nosuch' does not exist." } } };
+ const c = pagedClient({});
+ c.get = async () => missing;
+ const detailed = await readRelationshipsOf(c, 'nosuch', 'ManyToOne', undefined, { lookupDetails: true });
+ assert.equal(detailed.ok, false);
+ assert.equal(detailed.tableMissing, true);
+ assert.match(detailed.error, /does not exist/);
+ assert.deepStrictEqual(await readRelationshipsOf(c, 'nosuch', 'ManyToOne'), { ok: true, rows: [], tableMissing: true });
+});
+
+test('lookup details: a row that does not state the added scalars fails the read', async () => {
+ for (const field of ['ReferencedAttribute', 'ReferencingEntityNavigationPropertyName', 'ReferencingAttribute']) {
+ const row = { ...ACCOUNT };
+ delete row[field];
+ const c = pagedClient({ [DETAILS_PATH]: { status: 200, body: { value: [CONTACT, row] } } });
+ const read = await readRelationshipsOf(c, 'opportunity', 'ManyToOne', undefined, { lookupDetails: true });
+ assert.equal(read.ok, false, field);
+ assert.match(read.error, new RegExp(field), field);
+ }
+});
+
+test('lookup details and the default read never answer for each other from a shared cache', async () => {
+ const defaultPath = "/EntityDefinitions(LogicalName='opportunity')/ManyToOneRelationships?$select=SchemaName,ReferencedEntity,ReferencingAttribute";
+ const c = pagedClient({
+ [defaultPath]: { status: 200, body: { value: [{ SchemaName: ACCOUNT.SchemaName, ReferencedEntity: 'account', ReferencingAttribute: 'customerid' }] } },
+ [DETAILS_PATH]: { status: 200, body: { value: [ACCOUNT] } },
+ });
+ const cache = new Map();
+ const narrow = await readRelationshipsOf(c, 'opportunity', 'ManyToOne', cache);
+ const detailed = await readRelationshipsOf(c, 'opportunity', 'ManyToOne', cache, { lookupDetails: true });
+ assert.deepStrictEqual(c.paths, [defaultPath, DETAILS_PATH], 'two reads, one per mode');
+ assert.equal(narrow.rows[0].navigationProperty, undefined);
+ assert.equal(detailed.rows[0].navigationProperty, 'customerid_account');
+ assert.equal(await readRelationshipsOf(c, 'opportunity', 'ManyToOne', cache, { lookupDetails: true }), detailed, 'each mode is cached under its own key');
+ assert.equal(await readRelationshipsOf(c, 'opportunity', 'ManyToOne', cache), narrow);
+ assert.equal(c.paths.length, 2);
+ const other = await readRelationshipsOf(c, 'opportunity', 'OneToMany', undefined, { lookupDetails: true });
+ assert.equal(other.ok, false, 'lookup details are a ManyToOne read only');
+});
diff --git a/plugins/model-apps/scripts/tests/run-tests.test.js b/plugins/model-apps/scripts/tests/run-tests.test.js
index 69de77dfe..c947cf29e 100644
--- a/plugins/model-apps/scripts/tests/run-tests.test.js
+++ b/plugins/model-apps/scripts/tests/run-tests.test.js
@@ -389,6 +389,51 @@ test('the model-apps CI workflow runs the suite once with pinned TypeScript and
if (release !== null) assert.strictEqual(JSON.parse(release).version, '2.13.0', 'the fetched commit is the 2.13.0 release');
});
+// The eval tests and runners read committed fixtures, which a Windows checkout gives CRLF line ends, and the routing runner starts agent CLIs as
+// child processes (.cmd shims on Windows), so the eval job runs on every system and Node version the suite job runs on; the lexer's oracle
+// sweeps compare it with parsers whose identifier tables are not those of the Node version's engine, so they run on both Node versions. Text
+// assertions again: a list is read from the job's own `matrix:` block, in either form YAML writes it.
+// matrix:
+// os:
+// - ubuntu-latest
+// node: [20, 22]
+function workflowJob(wf, id) {
+ const start = wf.search(new RegExp(`^ {4}${id}:\\s*$`, 'm'));
+ assert.ok(start >= 0, `the workflow has a job ${id}`);
+ const rest = wf.slice(start).split(/\r?\n/).slice(1);
+ const end = rest.findIndex((line) => /^ {4}[a-z0-9-]+:\s*$/i.test(line));
+ return (end === -1 ? rest : rest.slice(0, end)).join('\n');
+}
+function matrixList(job, key) {
+ const lines = job.split('\n');
+ const at = lines.findIndex((line) => line.startsWith(` ${key}:`));
+ if (at === -1) return null;
+ const inline = /\[([^\]]*)\]\s*$/.exec(lines[at]);
+ if (inline) return inline[1].split(',').map((item) => item.trim()).filter(Boolean);
+ const items = [];
+ for (const line of lines.slice(at + 1)) {
+ const item = /^ {20}- (\S+)\s*$/.exec(line);
+ if (!item) break;
+ items.push(item[1]);
+ }
+ return items;
+}
+test('the model-apps CI workflow runs the eval job on every system and Node version the suite job runs on, and the lexer oracles on both Node versions', () => {
+ const wf = fs.readFileSync(WORKFLOW, 'utf8');
+ const suite = workflowJob(wf, 'test-model-apps-scripts');
+ const evals = workflowJob(wf, 'test-model-apps-evals');
+ const oracles = workflowJob(wf, 'test-model-apps-lexer-oracles');
+ assert.deepStrictEqual(matrixList(suite, 'os'), ['ubuntu-latest', 'windows-latest', 'macos-latest']);
+ assert.deepStrictEqual(matrixList(suite, 'node'), ['20', '22']);
+ assert.deepStrictEqual(matrixList(evals, 'os'), matrixList(suite, 'os'), 'the eval job runs on every system the suite runs on');
+ assert.deepStrictEqual(matrixList(evals, 'node'), matrixList(suite, 'node'), 'and on every Node version');
+ assert.match(evals, /^ {8}runs-on: \$\{\{ matrix\.os \}\}[ \t]*$/m, 'on the system of its matrix entry');
+ assert.match(evals, /^ {18}node-version: \$\{\{ matrix\.node \}\}[ \t]*$/m, 'with the Node version of its matrix entry');
+ assert.match(evals, /^ {12}fail-fast: false[ \t]*$/m, 'and one entry that fails does not cancel the others');
+ assert.deepStrictEqual(matrixList(oracles, 'node'), matrixList(suite, 'node'), 'the lexer oracles run on every Node version');
+ assert.match(oracles, /^ {18}node-version: \$\{\{ matrix\.node \}\}[ \t]*$/m);
+});
+
// --- committed lock files must not carry a registry URL ---------------------------------------
// `resolved` records the exact feed a package came from. Public npm is blocked on some Microsoft
// networks, so a contributor installing through an internal Azure Artifacts feed would rewrite
diff --git a/plugins/model-apps/scripts/tests/sdk-build-pages-deploy.test.js b/plugins/model-apps/scripts/tests/sdk-build-pages-deploy.test.js
index a8feb35a8..5ffeecc62 100644
--- a/plugins/model-apps/scripts/tests/sdk-build-pages-deploy.test.js
+++ b/plugins/model-apps/scripts/tests/sdk-build-pages-deploy.test.js
@@ -23,6 +23,11 @@ const { sha256 } = require('../lib/hash.js');
const { readPageOwnership, readPendingCreations, recordPagePending, recordPageCreation } = require('../lib/page-ownership-records.js');
const { currentReadSdk } = require('./helpers/app-membership-sdk.js');
const { OBJECT_DIVISION_PAGE, MISREAD_PAGES, HIDDEN_CALL_PAGE, PREFIX_INCREMENT_PAGE, TEMPLATE_LINE_PAGE, JSX_TEXT_PAGE, ELEMENT_AFTER_OPERATOR_PAGES, ELEMENT_LOOKALIKE_PAGES, ELEMENT_PAGE_TOKEN_LINE, FUNCTION_TYPE_PAGES } = require('./helpers/misread-page.js');
+const { withPageType, PAGE_TYPE } = require('./helpers/page-component-type.js');
+// What a guess costs a page where the TypeScript parser does not settle it (lib/typescript-views.js): these tests read the page with the lexer alone.
+// parser-check.test.js holds what the parser settles.
+const { setParserCheck } = require('../lib/typescript-views.js');
+const lexerAlone = (t) => { setParserCheck(false); t.after(() => setParserCheck(true)); };
// Real GUIDs for the three-authority sitemap mock. SELF_* resolve THIS app's appmodule + sitemap so
// fetchSitemap(appUnique) returns opts.liveSitemapXml; a page-less EMPTY sitemap is the default membership.
@@ -101,7 +106,8 @@ function mockSdk(opts = {}) {
// The shared-page scan's reads through the client: the list of apps (the published ones are all there are here, none was never published) and the other apps'
// saved layer, which is each app's published sitemap while nothing is pending.
dataverse: {
- get: async (url) => {
+ // The page table's solution component type is answered too: the pages join the spec's solution (helpers/page-component-type.js).
+ get: withPageType(async (url) => {
if (url.startsWith('/appmodules/')) {
const value = [{ appmoduleid: APP_ID, appmoduleidunique: SELF_UNIQUE_VALUE, uniquename: opts.selfAppUnique, componentstate: 0 }];
(opts.otherApps || []).forEach((a, i) => value.push({ appmoduleid: `app-${i + 2}`, appmoduleidunique: `uv-${i + 2}`, uniquename: a.uniquename, componentstate: 0 }));
@@ -109,7 +115,7 @@ function mockSdk(opts = {}) {
}
if (url.startsWith('/sitemaps/')) return { status: 200, body: { value: (opts.otherApps || []).map((a, i) => ({ sitemapid: `sm-${i + 2}`, sitemapxml: a.sitemapxml || '<SiteMap/>', componentstate: 0 })) } };
return { status: 404, body: null };
- },
+ }),
},
};
return { sdk, calls };
@@ -289,7 +295,8 @@ test('deploy: a PAGEREF_ token no navigation rewrite resolves HALTs before any u
// A page whose `/` after an object literal hides a call: JavaScript makes both navigations, but the lexer reads the `/` after the object literal on line 4 as a regex and
// the `/*` in `/\/*$/` as a comment over the second call, so the build resolved the first and shipped "PAGEREF_detail" in the second —
// with promotion, parity and the residue check all passing. It halts before any write, naming the call and the `/`.
-test('deploy: a page whose "/" after an object literal hides a navigation call HALTs before any upload, naming the call and the "/"', async () => {
+test('deploy: a page whose "/" after an object literal hides a navigation call HALTs before any upload, naming the call and the "/"', async (t) => {
+ lexerAlone(t);
const { appDir, spec } = makeTwoPageApp();
try {
fs.writeFileSync(path.join(appDir, 'overview.tsx'), OBJECT_DIVISION_PAGE, 'utf8');
@@ -322,7 +329,8 @@ test('deploy: a page whose "/" after an object literal hides a navigation call H
// Every way of making the lexer hide a navigation call, or read text as one, is a page the build refuses before any write
// (tests/helpers/misread-page.js). From the first spot the lexer reads by guess, every PAGEREF_ token is stray and none is rewritten, so
// the page is not half resolved. The message names the page, each token's line and column, and the kind and position of the guess.
-test('deploy: each misread page HALTs before any upload, naming the token and the guess', async () => {
+test('deploy: each misread page HALTs before any upload, naming the token and the guess', async (t) => {
+ lexerAlone(t);
for (const [name, { kind, frontier, code, reaching }] of Object.entries(MISREAD_PAGES)) {
const { appDir, spec } = makeTwoPageApp();
try {
@@ -349,11 +357,30 @@ test('deploy: each misread page HALTs before any upload, naming the token and th
}
});
+// The same pages, read as the TypeScript parser reads them where the lexer guessed (lib/typescript-views.js): the `/` after the object literal is the division it is,
+// and so is `of/2`, so every call is seen, resolved and deployed — where the lexer alone halts the build.
+test('deploy: a page the lexer misreads is read as TypeScript parses it, and every call in it deploys resolved', async () => {
+ for (const [what, code, calls] of [['the object-division page', OBJECT_DIVISION_PAGE, 2], ['the page whose call the lexer hid', HIDDEN_CALL_PAGE.code, 1]]) {
+ const { appDir, spec } = makeTwoPageApp();
+ try {
+ fs.writeFileSync(path.join(appDir, 'overview.tsx'), code, 'utf8');
+ const { sdk } = mockSdk();
+ const genpageCli = mockGenpageCli();
+ await runSdkBuild(spec, { sdk, apply: true, env: 'https://x', appDir, genpageCli, phases: PHASES });
+ const overview = genpageCli.uploads.find((u) => u.name === 'Overview');
+ assert.strictEqual(overview.content.split(`"${DETAIL_ID}"`).length - 1, calls, `${what}: every call is resolved`);
+ assert.ok(!/PAGEREF_/.test(overview.content), what);
+ assert.strictEqual(fs.readFileSync(path.join(appDir, 'overview.tsx'), 'utf8'), code, `${what}: the canonical source is untouched`);
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+ }
+});
+
// A declared call the lexer cannot see is "declared-but-absent", and that alone sends the author looking for a call that is plainly there.
// The page of a live run: `of/2` is read as the start of a regex whose `/*` opens a comment over the call. The halt names the guess that
// hides it — which it is, where, what it could be, and what to change — and nothing is written. A page with no guess, and no call, is
// told only what is missing.
-test('deploy: a declared call the lexer cannot see HALTs on parity, naming the guess that hides it', async () => {
+test('deploy: a declared call the lexer cannot see HALTs on parity, naming the guess that hides it', async (t) => {
+ lexerAlone(t);
const { code, frontier } = HIDDEN_CALL_PAGE;
const before = code.slice(0, frontier(code)).split('\n');
const { appDir, spec } = makeTwoPageApp();
@@ -649,6 +676,197 @@ test('deploy: a rebuild re-binds ids from the live enumeration and issues only U
} finally { fs.rmSync(appDir, { recursive: true, force: true }); }
});
+// THE SOLUTION HOLDS THE PAGES (AB#6443257). Every other component the build makes joins the spec's solution, and the add of the app brings its sitemap — never the
+// pages its navigation opens. So each page is added on its own, as a component of the page table's type the environment allocates, with its files.
+const pageAdds = (calls) => calls.filter((c) => c.name === 'addSolutionComponent' && c.args[0].componentType === PAGE_TYPE).map((c) => c.args[0]);
+
+test('solution: every page the build creates joins the spec\u2019s solution — as the page table\u2019s type the environment answers, with its files — once', async () => {
+ const { appDir, spec } = makeTwoPageApp();
+ try {
+ const { sdk, calls } = mockSdk();
+ const genpageCli = mockGenpageCli();
+ await runSdkBuild(spec, { sdk, apply: true, env: 'https://x', appDir, genpageCli, phases: PHASES });
+ assert.deepStrictEqual(pageAdds(calls).sort((a, b) => a.componentId.localeCompare(b.componentId)), [
+ { componentId: OVERVIEW_ID, componentType: PAGE_TYPE, solutionUniqueName: 'PgDeploy', addRequiredComponents: true },
+ { componentId: DETAIL_ID, componentType: PAGE_TYPE, solutionUniqueName: 'PgDeploy', addRequiredComponents: true },
+ ]);
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
+test('solution: a rebuild re-asserts each page it writes — one the solution is proven to hold costs no add, one it does not hold (an earlier build\u2019s) joins it', async () => {
+ const { appDir, spec } = makeTwoPageApp();
+ try {
+ const live = [{ pageId: OVERVIEW_ID, name: 'Overview' }, { pageId: DETAIL_ID, name: 'Detail' }];
+ const manifest = Buffer.from(JSON.stringify({ schemaVersion: 1, pages: [{ key: 'overview', name: 'Overview', pageId: OVERVIEW_ID }, { key: 'detail', name: 'Detail', pageId: DETAIL_ID }] }), 'utf8').toString('base64');
+ const { sdk, calls } = mockSdk({ pageManifest: manifest, manifestId: 'wr-manifest', liveSitemapXml: pageSitemap([OVERVIEW_ID, DETAIL_ID]), pageRows: live.map((p) => ({ uxagentprojectid: p.pageId, name: p.name })) });
+ // The solution holds Overview (a row of the page table's type) and not Detail: what a build before this one left.
+ const SOLUTION_ID = '5a5a5a5a-0000-4000-8000-00000000005a';
+ const query = sdk.queryRecords;
+ sdk.queryRecords = async (entity, options) => {
+ if (entity === 'solution') return [{ solutionid: SOLUTION_ID }];
+ if (entity === 'solutioncomponent') {
+ calls.push({ name: 'queryRecords', args: [entity, options] });
+ return options.filter.includes(`componenttype eq ${PAGE_TYPE}`) ? [{ objectid: OVERVIEW_ID, componenttype: PAGE_TYPE, rootcomponentbehavior: null }] : [];
+ }
+ return query(entity, options);
+ };
+ await runSdkBuild(spec, { sdk, apply: true, env: 'https://x', appDir, genpageCli: mockGenpageCli(live), phases: PHASES });
+ assert.deepStrictEqual(pageAdds(calls), [{ componentId: DETAIL_ID, componentType: PAGE_TYPE, solutionUniqueName: 'PgDeploy', addRequiredComponents: true }]);
+ const pageMembershipReads = calls.filter((c) => c.name === 'queryRecords' && c.args[0] === 'solutioncomponent' && c.args[1].filter.includes(`componenttype eq ${PAGE_TYPE}`));
+ assert.strictEqual(pageMembershipReads.length, 1, 'the solution\u2019s pages are read once, for every page');
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
+test('solution: a system solution holds every page already — no page is added, and the page table\u2019s type is not read', async () => {
+ const { appDir, spec } = makeTwoPageApp();
+ try {
+ spec.solution = { uniqueName: 'Default', displayName: 'Default Solution', publisherPrefix: 'contoso' };
+ const { sdk, calls } = mockSdk();
+ const reads = [];
+ const get = sdk.dataverse.get;
+ sdk.dataverse.get = async (url) => { reads.push(url); return get(url); };
+ await runSdkBuild(spec, { sdk, apply: true, env: 'https://x', appDir, genpageCli: mockGenpageCli(), phases: PHASES });
+ assert.deepStrictEqual(pageAdds(calls), []);
+ assert.ok(!reads.some((url) => /EntityDefinitions\(LogicalName='uxagentproject'\)/.test(url)));
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
+// The halt is as transient as the read it wraps (tests/halt-retry-policy.test.js): a 503 is run again, a refusal is final — whatever the solution is called, since its name is the maker's.
+test('solution: an environment that cannot say the page table\u2019s type halts the pages phase before any page is written — run again for a 503, final for a refusal', async () => {
+ const { isTransientHalt } = require('../build-model-app.js');
+ for (const [status, said, transient] of [[503, 'Service Unavailable', true], [403, 'Principal user is missing prvReadEntity privilege', false]]) {
+ const { appDir, spec } = makeTwoPageApp();
+ try {
+ spec.solution.uniqueName = 'Timeout_503_TryAgainLater';
+ const { sdk, calls } = mockSdk();
+ const get = sdk.dataverse.get;
+ sdk.dataverse.get = async (url) => (/EntityDefinitions\(LogicalName='uxagentproject'\)/.test(url) ? { status, body: { error: { message: said } } } : get(url));
+ const genpageCli = mockGenpageCli();
+ let halt = null;
+ try { await runSdkBuild(spec, { sdk, apply: true, env: 'https://x', appDir, genpageCli, phases: PHASES }); } catch (e) { halt = e; }
+ assert.ok(halt && halt.phase === 'pages' && halt.code === 'pages-solution-type-unreadable', `${status}: ${halt && halt.stack}`);
+ assert.ok(halt.message.includes(`cannot join solution Timeout_503_TryAgainLater — nothing in the pages phase was written: the solution component type of a generative page could not be read (HTTP ${status}: ${said})`), halt.message);
+ assert.strictEqual(isTransientHalt(halt, { spec }), transient, `${status}: the build runs again for it only when the read it wraps can succeed on another try`);
+ assert.strictEqual(genpageCli.uploads.length, 0, 'no page was written');
+ assert.deepStrictEqual(pageAdds(calls), []);
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+ }
+});
+
+// A changed-only run (a fast apply: the changed page only, the app's navigation left as it is) over an environment that keeps what each run wrote — the page manifest, the
+// pages and the solution's pages — so a second run sees what the first one left. Overview is the changed page. Detail, the page it navigates to, is not selected: `detail`
+// is its id, or null for a page deleted in Maker since the last apply, which the run makes again because Overview's link needs it. `members` are the pages the solution
+// holds; `refuse(id)` says whether the solution add of a page is refused (a 503, before anything is written).
+const DELETED_DETAIL_ID = '33333333-0000-4000-8000-000000000003';
+function changedOnlyEnvironment({ detail, members, refuse = () => false }) {
+ const { spec, appDir } = makeTwoPageApp();
+ const workspaceDir = path.join(appDir, 'workspace');
+ fs.mkdirSync(workspaceDir);
+ const live = [{ pageId: OVERVIEW_ID, name: 'Overview' }, ...(detail ? [{ pageId: detail, name: 'Detail' }] : [])];
+ const held = new Set(members);
+ // The options mockSdk reads at every request, so a write below changes what the next read answers.
+ const remote = {
+ pageManifest: Buffer.from(JSON.stringify({ schemaVersion: 1, pages: [{ key: 'overview', name: 'Overview', pageId: OVERVIEW_ID }, { key: 'detail', name: 'Detail', pageId: detail || DELETED_DETAIL_ID }] })).toString('base64'),
+ manifestId: 'wr-manifest',
+ liveSitemapXml: pageSitemap([OVERVIEW_ID, detail || DELETED_DETAIL_ID]),
+ selfAppUnique: appUniqueName(spec),
+ pageRows: live.map((p) => ({ uxagentprojectid: p.pageId, name: p.name })),
+ };
+ const run = async () => {
+ const { sdk, calls } = mockSdk(remote);
+ const query = sdk.queryRecords;
+ sdk.queryRecords = async (entity, options) => {
+ if (entity === 'solution') return [{ solutionid: '5a5a5a5a-0000-4000-8000-00000000005a' }];
+ if (entity === 'solutioncomponent') {
+ calls.push({ name: 'queryRecords', args: [entity, options] });
+ return options.filter.includes(`componenttype eq ${PAGE_TYPE}`) ? [...held].map((id) => ({ objectid: id, componenttype: PAGE_TYPE, rootcomponentbehavior: null })) : [];
+ }
+ return query(entity, options);
+ };
+ for (const method of ['createWebResource', 'updateWebResource']) {
+ const write = sdk[method];
+ sdk[method] = async (...args) => {
+ const body = method === 'createWebResource' ? args[0] : args[1];
+ if (body.content) remote.pageManifest = Buffer.from(body.content, 'utf8').toString('base64');
+ return write(...args);
+ };
+ }
+ const add = sdk.addSolutionComponent;
+ sdk.addSolutionComponent = async (o) => {
+ await add(o);
+ if (o.componentType !== PAGE_TYPE) return;
+ if (refuse(o.componentId)) throw Object.assign(new Error('Service Unavailable'), { statusCode: 503 });
+ held.add(o.componentId);
+ };
+ const genpageCli = mockGenpageCli(live);
+ const create = genpageCli.create;
+ genpageCli.create = async (o) => {
+ const made = await create(o);
+ live.push({ pageId: made.pageId, name: made.name });
+ remote.pageRows = live.map((p) => ({ uxagentprojectid: p.pageId, name: p.name }));
+ return made;
+ };
+ let halt = null;
+ try {
+ await runSdkBuild(spec, {
+ sdk, apply: true, env: 'https://contoso.crm.dynamics.com', appDir, workspaceDir, genpageCli, phases: ['pages'],
+ changedOnly: { fastApply: true, resolvedAppId: APP_ID, skipSitemapFinalize: true, selectedKeys: ['overview'], deployedKeys: ['overview', 'detail'] },
+ });
+ } catch (e) { halt = e; }
+ return {
+ halt,
+ uploads: genpageCli.uploads.map((u) => `${u.requestedId ? 'update' : 'create'} ${u.name}`),
+ pageAdds: pageAdds(calls).map((a) => a.componentId),
+ pageMembershipReads: calls.filter((c) => c.name === 'queryRecords' && c.args[0] === 'solutioncomponent' && c.args[1].filter.includes(`componenttype eq ${PAGE_TYPE}`)).length,
+ };
+ };
+ return { spec, held, run, dispose: () => fs.rmSync(appDir, { recursive: true, force: true }) };
+}
+
+// The page a changed-only run makes is not one it selected, so a run taken again — the build's own retry of a halt it takes for transient keeps the same selection — finds it
+// bound by its creation receipt and leaves it as it is. Its solution add is not left with it: the run asserts every page it keeps, not only those it writes.
+test('solution: a changed-only run whose add of a page it made was refused adds that page when the run is taken again — and does not write the page again', async () => {
+ const { isTransientHalt } = require('../build-model-app.js');
+ let refused = false;
+ const env = changedOnlyEnvironment({ detail: null, members: [OVERVIEW_ID], refuse: (id) => id === DETAIL_ID && !refused && (refused = true) });
+ try {
+ const first = await env.run();
+ assert.ok(first.halt && first.halt.phase === 'pages', `the refused add stops the pages phase: ${first.halt && first.halt.stack}`);
+ assert.strictEqual(isTransientHalt(first.halt, { spec: env.spec }), true, 'a 503 is run again, with the same selection');
+ assert.deepStrictEqual(first.uploads, ['create Detail'], 'the absent target is made first, and its add is refused');
+ assert.deepStrictEqual(first.pageAdds, [DETAIL_ID]);
+ assert.ok(!env.held.has(DETAIL_ID), 'the solution does not hold the page yet');
+
+ const second = await env.run();
+ assert.strictEqual(second.halt, null, `the run taken again completes: ${second.halt && second.halt.stack}`);
+ assert.deepStrictEqual(second.uploads, ['update Overview'], 'the page the first run made is bound now, and left as it is: only the changed page is written');
+ assert.deepStrictEqual(second.pageAdds, [DETAIL_ID], 'the page the first run made, and could not add, joins the solution');
+ assert.ok(env.held.has(DETAIL_ID));
+ } finally { env.dispose(); }
+});
+
+test('solution: a changed-only run asserts the pages it leaves as they are, with the one read — a page the solution does not hold joins it, and none of them is written', async () => {
+ const env = changedOnlyEnvironment({ detail: DETAIL_ID, members: [OVERVIEW_ID] });
+ try {
+ const run = await env.run();
+ assert.strictEqual(run.halt, null, run.halt && run.halt.stack);
+ assert.deepStrictEqual(run.uploads, ['update Overview'], 'the page it leaves as it is is not written');
+ assert.deepStrictEqual(run.pageAdds, [DETAIL_ID], 'it joins the solution, as a full build would add it');
+ assert.strictEqual(run.pageMembershipReads, 1, 'the solution\u2019s pages are read once, for every page');
+ } finally { env.dispose(); }
+});
+
+test('solution: a changed-only run over pages the solution already holds adds none of them, and writes only the page it changed', async () => {
+ const env = changedOnlyEnvironment({ detail: DETAIL_ID, members: [OVERVIEW_ID, DETAIL_ID] });
+ try {
+ const run = await env.run();
+ assert.strictEqual(run.halt, null, run.halt && run.halt.stack);
+ assert.deepStrictEqual(run.uploads, ['update Overview']);
+ assert.deepStrictEqual(run.pageAdds, []);
+ assert.strictEqual(run.pageMembershipReads, 1);
+ } finally { env.dispose(); }
+});
+
// Duplicate page names: validateAppSpec TOLERATES a duplicate name when both pages carry a
// pageId, but a pageId is only a CLAIM. A STALE snapshot (a page deleted in Maker since download) reconciles
// its id as ABSENT, so the upload loop would CREATE it fresh and re-materialize the duplicate. The
diff --git a/plugins/model-apps/scripts/tests/sdk-build-pages-order.test.js b/plugins/model-apps/scripts/tests/sdk-build-pages-order.test.js
index 5dac7d142..f462604f0 100644
--- a/plugins/model-apps/scripts/tests/sdk-build-pages-order.test.js
+++ b/plugins/model-apps/scripts/tests/sdk-build-pages-order.test.js
@@ -9,6 +9,7 @@ const os = require('node:os');
const path = require('node:path');
const { runSdkBuild, appUniqueName, acquireAppPagesLease } = require('../lib/sdk-build.js');
const { fakeGenpage } = require('./helpers/fake-genpage.js');
+const { withPageType } = require('./helpers/page-component-type.js');
const { startTarget } = require('./helpers/kill-target-client.js');
// Real GUIDs for the three-authority sitemap mock. fetchSitemap(self) resolves via SELF_* to a
@@ -63,8 +64,9 @@ function harness() {
removeElement: async () => { await Promise.resolve(); return {}; },
pushArtifact: async (t, id) => ({ type: t, id, saved: true, shipped: false, publish: { kind: 'notRequested' } }),
addSolutionComponent: async () => {}, publishArtifact: async (type, id) => ({ type, id, shipped: true, publish: { kind: 'verified' } }),
- // The shared-page scan's one read of the apps that were never published: the app is the only one, and it is published.
- dataverse: { get: async (url) => (url.startsWith('/appmodules/') ? { status: 200, body: { value: [{ appmoduleid: APP_ID, appmoduleidunique: SELF_UNIQUE_VALUE, componentstate: 0 }] } } : { status: 404, body: null }) },
+ // The shared-page scan's one read of the apps that were never published: the app is the only one, and it is published. And the page table's solution component type,
+ // which the pages phase reads to add the pages to the spec's solution (helpers/page-component-type.js).
+ dataverse: { get: withPageType(async (url) => (url.startsWith('/appmodules/') ? { status: 200, body: { value: [{ appmoduleid: APP_ID, appmoduleidunique: SELF_UNIQUE_VALUE, componentstate: 0 }] } } : { status: 404, body: null })) },
};
// The page backend. EXISTENCE reflects the pages a create added (env-wide). The id is fixed per name, so a restart can be told from a duplicate, and every
// write joins the shared `calls` sequence the ordering tests read.
diff --git a/plugins/model-apps/scripts/tests/sdk-build.test.js b/plugins/model-apps/scripts/tests/sdk-build.test.js
index a08f8c75e..cde2c59a6 100644
--- a/plugins/model-apps/scripts/tests/sdk-build.test.js
+++ b/plugins/model-apps/scripts/tests/sdk-build.test.js
@@ -7,6 +7,7 @@ const path = require('node:path');
const { commandDef, chartDef, runSdkBuild: runSdkBuildWithRealWaits, planFor, resolvePhases, compileFormIntent, formFieldLogicals, viewDef, appDef, defaultViewColumns, enrichesDefaultViews, artifactIdentityQuery, resolveExistingFormId, FORM_TYPE_CODE, dashboardTileOpts, PHASES, appUniqueName, personaRoleSpecFor } = require('../lib/sdk-build.js');
const { validateAppSpec } = require('../lib/app-spec.js');
const { makeTempDir } = require('./helpers/temp-dirs.js');
+const { withPageType } = require('./helpers/page-component-type.js');
// The AI phase's proof after a publish waits 500 ms between reads of an override row that is not there yet, as --verify
// does. No test below is about that wait (it is pinned through `proofBudget`), and every one that leaves a row absent
// would otherwise sleep a second for it.
@@ -478,8 +479,10 @@ function mockSdk(opts = {}) {
// answers with both layers. opts.savedNavigationError makes the read fail as a whole; an app's `savedRows` replaces its rows (e.g. to leave them out). A draft app's
// one row is its saved sitemap; it may set `noSitemapComponent` (its layer has no sitemap component to find), `componentReadFails` (the read of its components fails) or
// `sitemapName` (the unique name its sitemap carries, when it is not the app's own).
+ // page type the page table's solution component type, which the pages phase reads to add the pages to the spec's solution (helpers/page-component-type.js);
+ // answered in front of the rest, and not recorded among the calls.
if (opts.selfAppUnique !== undefined || (opts.otherApps || []).length || (opts.draftApps || []).length) sdk.dataverse = {
- get: async (url) => {
+ get: withPageType(async (url) => {
calls.push({ name: 'dataverse.get', args: [url] });
if (/^\/appmodules\/Microsoft\.Dynamics\.CRM\.RetrieveUnpublishedMultiple\(\)/.test(url)) {
if (opts.draftAppsError) return { status: 503, body: null };
@@ -504,7 +507,7 @@ function mockSdk(opts = {}) {
else value.push({ sitemapid: draftSitemapId(j), sitemapnameunique, sitemapxml: d.savedSitemapXml, componentstate: 1 });
});
return { status: 200, body: { value } };
- },
+ }),
};
return { sdk, calls };
}
diff --git a/plugins/model-apps/scripts/tests/solution-settings-real-bundle.test.js b/plugins/model-apps/scripts/tests/solution-settings-real-bundle.test.js
index 4bac8ad4b..a2c9413fa 100644
--- a/plugins/model-apps/scripts/tests/solution-settings-real-bundle.test.js
+++ b/plugins/model-apps/scripts/tests/solution-settings-real-bundle.test.js
@@ -4,6 +4,9 @@
// say: that the SDK still throws the codes this script falls back on, in the words it matches; that it still stages, deletes its staging copy and
// sends ComponentParameters as it did; that a transport failure on the import is not repeated. Below, the script runs in a child process with a fake
// `pac` alone on PATH (or none), and the run's every byte of output is searched for the secrets it was given.
+// This file checks where lib/temp-workspace.js makes a workspace, so it works in a temp folder of its own (helpers/own-temp-folder.js): in the
+// suite's shared one, other test processes make and remove the plugin's workspace folder. Required first, so every path below is inside it.
+require('./helpers/own-temp-folder.js');
const test = require('node:test');
const assert = require('node:assert');
const fs = require('node:fs');
diff --git a/plugins/model-apps/scripts/tests/solution-settings.test.js b/plugins/model-apps/scripts/tests/solution-settings.test.js
index 4f69fe47e..368feccdb 100644
--- a/plugins/model-apps/scripts/tests/solution-settings.test.js
+++ b/plugins/model-apps/scripts/tests/solution-settings.test.js
@@ -2,6 +2,9 @@
// scripts/solution-settings.js — deployment settings for a solution: the CLI contract, the checks made before any request, the SDK calls and
// pac's defaults, which refusals fall back to pac and which do not, the long-running-action client, and what the sanitizer keeps out of what is printed (and what it leaves).
// The SDK and pac are stood in for here; tests/solution-settings-real-bundle.test.js drives the real bundle and the real script.
+// This file checks where lib/temp-workspace.js makes a workspace, so it works in a temp folder of its own (helpers/own-temp-folder.js): in the
+// suite's shared one, other test processes make and remove the plugin's workspace folder. Required first, so every path below is inside it.
+require('./helpers/own-temp-folder.js');
const test = require('node:test');
const assert = require('node:assert');
const fs = require('node:fs');
@@ -489,10 +492,11 @@ test('the limits the skill, AGENTS.md and the CHANGELOG state are the limits the
/is found only as a whole word, so it is printed when glued to letters, digits, marks or underscores or written inside an escape the sanitizer does not decode/,
/quoted in part, hashed, base64-encoded, written as an HTML entity beyond XML's five, Unicode-normalized or nested in more than three levels of encoding is not recognised/,
]],
+ // The CHANGELOG names the same limits in fewer words: an entry there holds at most 300 (changelog-brevity.test.js).
['CHANGELOG.md', read('CHANGELOG.md'), [
- /quoted in part, hashed, base64-encoded, written as an HTML entity beyond XML's five, normalized in its Unicode by a service, or nested in more than three levels of encoding/,
- /a value of fewer than six characters that is known not to be a secret, which is printed wherever a text quotes it/,
- /a value of fewer than six characters with no recorded type that a text glues to letters, digits, marks or underscores or writes inside an escape the sanitizer does not read/,
+ /values partly quoted, hashed, base64-encoded, Unicode-normalized, nested over three encodings or written with HTML entities beyond XML's five/,
+ /non-secret values under six characters/,
+ /untyped ones under six glued to letters, digits, marks or underscores or inside an undecoded escape/,
]],
['AGENTS.md', read('AGENTS.md'), [
/the SDK's account of which entry is wrong \(it names entries, never values\) stays readable unless the value is itself a whole word of that sentence \(see below\)/,
diff --git a/plugins/model-apps/scripts/tests/source-literals.test.js b/plugins/model-apps/scripts/tests/source-literals.test.js
index 53cdd222a..260d252c9 100644
--- a/plugins/model-apps/scripts/tests/source-literals.test.js
+++ b/plugins/model-apps/scripts/tests/source-literals.test.js
@@ -12,6 +12,9 @@ const { execFileSync, spawnSync } = require('node:child_process');
const { blankLiterals, blankNonCodePreservingTemplateExpressions, commentRanges, endsMidStatement, findElisionMarker, hasDefaultExport, hasUnbalancedBrackets, scanTemplateExpressionEnd, expressionPosition, opensTypeParameters, elementFailsAt, elementChildren, isTrivia, isSingleLineTrivia, trimTrivia, TRIVIA_CLASS, WS, AMBIGUITY_KINDS, ANGLE_AFTER, ANGLE_AFTER_LINE_BREAK, NO_MEMBER_BEFORE, RESERVED_WORDS, TYPE_PARAMETER_MODIFIERS, MEMBER_NAME_OPERATORS } = require('../lib/source-literals.js');
const { navReferencedKeys, strayPageRefs, resolvePageRefs } = require('../lib/pageref-resolver.js');
const { pageStructureProblems } = require('../lib/page-structure.js');
+// These tests hold the lexer to its own rules — what it reads for certain, what it reports as a guess, and what a guess costs a page — so they read pages with
+// the lexer alone. Where the lexer guesses, the gates ask the TypeScript parser (typescript-views.js), which parser-check.test.js tests.
+require('../lib/typescript-views.js').setParserCheck(false);
const { loadTypescriptOracle, loadBabelOracle } = require('./helpers/typescript-oracle.js');
const { FRAMES, tokenVocabulary, programsFor, cleanSourceFile, readingAt, isElement, SIGNATURE_ENDINGS, HIDING_ENDINGS, CERTAIN_ELEMENTS, GUESSED_ELEMENTS, HIDDEN_TEXT_ELEMENTS, UNREAD_LIST_ELEMENTS, MEMBER_ELEMENT_FRAMES, NO_MEMBER_ELEMENT_FRAMES, signaturePages, elementPages, SIGNATURE_FRAMES, DECOYS, signaturePage, EXACT_DEFAULTS, UNREAD_DEFAULTS, UNTERMINATED_DEFAULTS, PROSE_SHAPED_LINES, PROSE_OPEN_LINES, PROSE_HIDING_ELEMENTS, proseElements, PARAMETER_MODIFIERS } = require('./helpers/angle-frames.js');
@@ -744,53 +747,435 @@ test('hasDefaultExport reads a generic arrow\'s return type to its end, and want
}
});
-// A known limit, pinned as it is: a default value in a binding pattern of a function type's parameter is passed over to the next `,` or closing bracket at its own level,
-// and the comma between a generic call's type arguments (`f<T, U>()`) is taken for one. The pattern then reads as none, the parentheses as a parenthesised type, and the
-// function type's own `=>` as the arrow, so a write cut right after such a function type — no arrow, no body — is accepted here. The page compile refuses it (TypeScript:
-// `'=>' expected`). The page it was cut from is accepted, as it should be.
-test('known limit: a generic call with two type arguments in a default value of a function type\'s parameter', () => {
- assert.equal(hasDefaultExport('export default <T,>(p: T): ({ a = f<T,T>() }) => T'), true, 'the cut is accepted: the known limit');
- assert.equal(hasDefaultExport('export default <T,>(p: T): ({ a = f<T,T>() }) => T => null as never;\n'), true);
- // With the call in parentheses the default value is passed over whole, the pattern is read, and the cut is refused.
+// A default value in a binding pattern of a function type's parameter is read as TypeScript reads it, a generic call's type arguments included: the comma between them
+// (`f<T, U>()`) is the call's, so the pattern is read, the parentheses hold the function type's parameters, its `=>` is its own, and a write cut right after that
+// function type — no arrow, no body — is refused, as the page compile refuses it (TypeScript: `'=>' expected`). The type arguments are read strictly, each to its end
+// with what its groups hold; where TypeScript reads a comparison instead (no list of types between `<` and `>`, or a `>` that nothing can follow), the value ends at its
+// first comma, as JavaScript reads it. [what, default value]
+const GENERIC_CALL_DEFAULTS = [
+ ['a generic call', 'f<T,T>()'],
+ ['a generic call with a space after the comma', 'f<T, U>()'],
+ ['an instantiation expression', 'f<T, U>'],
+ ['a tagged template with type arguments', 'f<T, U>`t`'],
+ ['a call whose parenthesis is on the next line', 'f<T, U>\n(x)'],
+ ['a trailing comma in the type arguments', 'f<T,>()'],
+ ['nested type arguments', 'f<A<B<C>>, D>()'],
+ ['a union, an array, literal types and a conditional type', 'f<T | U, V[], "a", -1, T extends U ? X : Y>()'],
+ ['a tuple, an indexed access, a parenthesised type and a type query', 'f<[T, U], T[K], (T), typeof a.b>()'],
+ ['`keyof`, `readonly` and an empty object type', 'f<keyof T, readonly U[], {}>()'],
+ ['what JavaScript reads as two comparisons', 'x < y, z > (w)'],
+ ['type arguments after a call, a parenthesised callee, a string and a property named `in`', 'g()<T, U>() + (f)<T, U>() + "s"<T, U>() + a.in<T, U>()'],
+];
+// [what, default value]: no list of types, so TypeScript reads a comparison, the value ends at the first comma and the next element is another binding — the pattern is
+// read either way, and the parentheses hold the function type's parameters.
+const COMPARISON_DEFAULTS = [
+ ['a sum between the angle brackets', 'x < y + 1, z = q > (w)'],
+ ['a comparison and a default after it', 'x < y, z = q > w'],
+];
+// [what, default value]: a list of types that what follows cannot follow — a name, a sign, a bracket, a `!` — is a comparison to TypeScript
+// (canFollowTypeArgumentsInExpression), so `> w` is part of a binding, which no binding is: the braces make no pattern, and TypeScript refuses them as a type as well.
+const COMPARISON_REFUSALS = [
+ ['a name after the list', 'x < y, z > w'], ['a name after a generic name', 'f<T, U> w'], ['a sign after the list', 'f<T, U> -1'], ['a plus after the list', 'f<T, U> + 1'],
+ ['a bracket after the list', 'f<T, U> [0]'], ['a brace after the list', 'f<T, U> {}'], ['a negation after the list', 'f<T, U> !x'],
+];
+// [what, default value]: a type argument that the strict reading does not read — a function type, an object type with members — leaves the value read to its first comma, as
+// before: the pattern then reads as none, and a write cut right after such a function type is still accepted (the page compile refuses it; AGENTS.md, "TSX source lexer —
+// known limits").
+const UNREAD_GENERIC_CALL_DEFAULTS = [
+ ['a function type for a type argument', 'f<(x: T) => U, V>()'],
+ ['an object type with a member for a type argument', 'f<{ a: T }, U>()'],
+];
+// [what, default value]: values that TypeScript's parser or Babel's refuses in a parameter although the lexer cannot see why — a legacy octal number (TypeScript), a word
+// strict code reserves (Babel) — with a generic call's type arguments before or around them. The page that only the function type's reading accepts, `({ a = V }: R) =>
+// | X | null => …`, stays refused as it was: reading the type arguments only ever refuses more (genericArrowIsComplete).
+const REFUSED_VALUE_DEFAULTS = [
+ ['a legacy octal number in the call', 'f<T, U>(010)'], ['`await` before the call', 'await f<T, U>()'], ['`let` in the call', 'f<T, U>(let)'],
+ ['`yield` in the call', 'f<T, U>(yield)'], ['`await` after the call', 'f<T, U>() + await x'],
+];
+
+test('a generic call\'s type arguments in a default value of a function type\'s parameter are read as TypeScript reads them', () => {
+ const ts = loadTypescriptOracle();
+ const babel = loadBabelOracle();
+ const parses = (code) => ts.createSourceFile('page.tsx', code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX).parseDiagnostics.length === 0;
+ const babelParses = (code) => {
+ try {
+ babel.parse(code, { sourceType: 'module', plugins: ['jsx', 'typescript'] });
+ return true;
+ } catch {
+ return false;
+ }
+ };
+ const pages = (value) => ({
+ cuts: [
+ `export default <T,>(p: T): ({ a = ${value} }) => T`,
+ `export default <T,>(p: T): ({ a = ${value}, b }) => T`,
+ `export default async <T,>(p: T): ([a = ${value}]) => T`,
+ ],
+ complete: [
+ `export default <T,>(p: T): ({ a = ${value} }) => T => null as never;\n`,
+ `export default async <T,>(p: T): ([a = ${value}]) => T => null as never;\n`,
+ // The function type's return type starts with a `|`, which begins no body: only the function type's reading takes it.
+ `export default <T,>(p: T): ({ a = ${value} }: R) => | X | null => () => null;\n`,
+ ],
+ });
+ for (const [what, value] of [...GENERIC_CALL_DEFAULTS, ...COMPARISON_DEFAULTS]) {
+ const { cuts, complete } = pages(value);
+ for (const code of cuts) {
+ assert.equal(hasDefaultExport(code), false, `${what}: the cut is refused: ${JSON.stringify(code)}`);
+ if (ts) assert.equal(parses(code), false, `TypeScript refuses ${JSON.stringify(code)}`);
+ }
+ for (const code of complete.slice(0, 2)) {
+ assert.equal(hasDefaultExport(code), true, `${what}: ${JSON.stringify(code)}`);
+ assert.deepStrictEqual(pageStructureProblems(code), [], what);
+ if (ts) assert.equal(parses(code), true, `TypeScript parses ${JSON.stringify(code)}`);
+ }
+ // Known limit, pinned: the page only the function type's reading accepts is accepted where the value reads the same to its first comma (a comparison: no type
+ // arguments are passed over), and refused where the type arguments had to be passed over to read it — as it was before they were read — although TypeScript parses it.
+ const comparison = COMPARISON_DEFAULTS.some(([name]) => name === what);
+ assert.equal(hasDefaultExport(complete[2]), comparison, `${what}: ${JSON.stringify(complete[2])}`);
+ if (ts) assert.equal(parses(complete[2]), true, `TypeScript parses ${JSON.stringify(complete[2])}`);
+ }
+ // A value TypeScript or Babel refuses in a parameter: every cut is still refused, the page that only the function type's reading accepts stays refused, and one of the
+ // two parsers refuses it too.
+ for (const [what, value] of REFUSED_VALUE_DEFAULTS) {
+ const { cuts, complete } = pages(value);
+ for (const code of cuts) assert.equal(hasDefaultExport(code), false, `${what}: the cut is refused: ${JSON.stringify(code)}`);
+ assert.equal(hasDefaultExport(complete[2]), false, `${what}: ${JSON.stringify(complete[2])}`);
+ if (ts && babel) assert.ok(!parses(complete[2]) || !babelParses(complete[2]), `TypeScript or Babel refuses ${JSON.stringify(complete[2])}`);
+ }
+ // With the call in parentheses the default value is passed over whole, as it always was.
assert.equal(hasDefaultExport('export default <T,>(p: T): ({ a = (f<T,T>()) }) => T'), false);
assert.equal(hasDefaultExport('export default <T,>(p: T): ({ a = (f<T,T>()) }) => T => null as never;\n'), true);
+ // No pattern, so no function type takes the `=>`: the `|` after it begins no body.
+ for (const [what, value] of COMPARISON_REFUSALS) {
+ const code = pages(value).complete[2];
+ assert.equal(hasDefaultExport(code), false, `${what}: ${JSON.stringify(code)}`);
+ if (ts) assert.equal(parses(code), false, `TypeScript refuses ${JSON.stringify(code)}`);
+ }
+ // Known limit, pinned: a type argument the strict reading does not read.
+ for (const [what, value] of UNREAD_GENERIC_CALL_DEFAULTS) {
+ const { cuts, complete } = pages(value);
+ assert.equal(hasDefaultExport(cuts[0]), true, `${what}: the cut is accepted, a known limit`);
+ for (const code of complete.slice(0, 2)) assert.equal(hasDefaultExport(code), true, `${what}: ${JSON.stringify(code)}`);
+ if (ts) assert.equal(parses(cuts[0]), false, `TypeScript refuses ${JSON.stringify(cuts[0])}`);
+ }
+});
+
+// Known limit, pinned as it is (AGENTS.md, "TSX source lexer — known limits"): a mapped type whose key type is in parentheses (or brackets) and whose member type is a
+// name, inside a parenthesised return type, is refused although TypeScript and Babel parse it, sync and async — a fail-closed reading, kept on purpose. Both parsers
+// try the braces as a binding pattern first, whose computed key `[K in (keyof T)]` is an expression to them, and `(keyof T)` — two names side by side in
+// parentheses — is none: the pattern fails, and the parentheses hold a type. The gate takes any group in a computed key for an operand, so `K in (keyof T)` reads as an
+// expression, the braces as a binding pattern, the parentheses as a function type's parameters and the arrow as that function type's: the page reads as cut off.
+// Reading such braces as a mapped type would make the gate accept a page on the strength of every token in the key and member types, which it does not check as the
+// parsers do (an escaped keyword, a legacy octal number, a string escape): a reading that tried accepted pages TypeScript or Babel refuses. [what, mapped type]
+const PARENTHESISED_MAPPED_TYPES = [
+ ['a key type in parentheses', '{ [K in (keyof T)]: boolean }'],
+ ['a key type in two pairs of parentheses', '{ [K in ((keyof T))]: boolean }'],
+ ['a key type in parentheses, remapped', '{ [K in (keyof T) as K]: boolean }'],
+ ['a parenthesised conditional key type', '{ [K in (T extends object ? keyof T : never)]: boolean }'],
+ ['a key type in a tuple', '{ [K in [keyof T]]: boolean }'],
+ ['a key type in parentheses and a union', '{ [K in (keyof T) | "extra"]: boolean }'],
+ ['an object type with a member for the key type', '{ [K in ({ a: keyof T })]: boolean }'],
+ ['a constructor type for the key type', '{ [K in (new () => T)]: boolean }'],
+];
+// [what, mapped type]: the same key types where the braces make no binding pattern for another reason — an index with no argument after the group, a `?`, a modifier,
+// no member type, a `;`, a member type that is no name — hold a mapped type, as TypeScript reads them.
+const PARENTHESISED_MAPPED_TYPES_READ = [
+ ['an array of a parenthesised key type', '{ [K in (keyof T)[]]: boolean }'],
+ ['an optional mapped type', '{ [K in (keyof T)]?: T[K] }'],
+ ['`readonly` and `?`', '{ readonly [K in (keyof T)]?: T[K] }'],
+ ['`-readonly` and `-?`', '{ -readonly [K in (keyof T)]-?: T[K] }'],
+ ['`+readonly` and `+?`', '{ +readonly [K in (keyof T)]+?: T[K] }'],
+ ['no type for the members', '{ [K in (keyof T)] }'],
+ ['a semicolon after the member', '{ [K in (keyof T)]: boolean; }'],
+ ['an indexed access for the member type', '{ [K in (keyof T)]: T[K] }'],
+];
+// [what, page]: the rewrites the limit names — the key type without its parentheses, no parentheses around the return type, a type alias.
+const PARENTHESISED_MAPPED_TYPE_REWRITES = [
+ ['the key type without its parentheses', 'export default <T extends object>(p: T): ({ [K in keyof T]: boolean }) => null as never;\n'],
+ ['the key type without its parentheses, async', 'export default async <T extends object>(p: T): ({ [K in keyof T]: boolean }) => null as never;\n'],
+ ['no parentheses around the return type', 'export default <T extends object>(p: T): { [K in (keyof T)]: boolean } => null as never;\n'],
+ ['a type alias', 'type Flags<T> = { [K in (keyof T)]: boolean };\nexport default <T extends object>(p: T): Flags<T> => null as never;\n'],
+];
+// [what, return type, then what follows it]: TypeScript reads each of these one way, which the gate reads too.
+const MAPPED_KEY_NEIGHBOURS = [
+ // A key type that is an expression too: `K in (T)` is one, and so is `K in (Extract<keyof T, string>)` — an instantiation expression, whose type arguments TypeScript
+ // reads as types (parseTypeArgumentsInExpression) — so the braces are a binding pattern and the arrow is the function type's.
+ ['an expression in parentheses', '({ [K in (T)]: boolean })', false],
+ ['an instantiation expression in parentheses', '({ [K in (Extract<keyof T, string>)]: boolean })', false],
+ // No `K in`: the key is no expression and no mapped type's, and TypeScript refuses the braces either way.
+ ['a parenthesised key type with no name', '({ [(keyof T)]: boolean })', false],
+ ['a key type that is no type', '({ [K in (keyof T foo)]: boolean })', false],
+ // A parenthesised type holds one type: a `,` after the mapped type is an error, and so is a `,` that ends its member (parseSemicolon wants a `;`).
+ ['a second parameter after the braces', '({ [K in (keyof T)]: boolean }, b)', false],
+ ['a comma after the member', '({ [K in (keyof T)]: boolean, })', false],
+ ['the key type without parentheses', '({ [K in keyof T]: boolean })', true],
+ ['the return type without parentheses', '{ [K in (keyof T)]: boolean }', true],
+ // A `;` and a member after the mapped one make no binding pattern: the parentheses hold a type, which TypeScript parses
+ // (only its checker refuses a member beside a mapped one).
+ ['a member after the mapped one', '({ [K in (keyof T)]: boolean; b: string })', true],
+];
+
+test('known limit: a mapped type whose key type is in parentheses, inside a parenthesised return type, is refused although TypeScript parses it', () => {
+ const ts = loadTypescriptOracle();
+ const babel = loadBabelOracle();
+ const parses = (code) => ts.createSourceFile('page.tsx', code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX).parseDiagnostics.length === 0;
+ const babelParses = (code) => {
+ try {
+ babel.parse(code, { sourceType: 'module', plugins: ['jsx', 'typescript'] });
+ return true;
+ } catch {
+ return false;
+ }
+ };
+ for (const [what, mapped] of PARENTHESISED_MAPPED_TYPES) {
+ for (const modifier of ['', 'async ']) {
+ const code = `export default ${modifier}<T extends object>(p: T): (${mapped}) => null as never;\n`;
+ assert.equal(hasDefaultExport(code), false, `${what}: refused, a known limit: ${JSON.stringify(code)}`);
+ assert.match(pageStructureProblems(code).join('\n'), /no complete default export/, what);
+ if (ts) assert.equal(parses(code), true, `TypeScript parses ${JSON.stringify(code)}`);
+ if (babel) assert.equal(babelParses(code), true, `Babel parses ${JSON.stringify(code)}`);
+ // The other half of the same reading: the page that only a function type's reading takes is accepted, and TypeScript refuses it (so does the page compile).
+ const asFunctionType = `export default ${modifier}<T extends object>(p: T): (${mapped}) => | T | null => () => null;\n`;
+ assert.equal(hasDefaultExport(asFunctionType), true, `${what}: ${JSON.stringify(asFunctionType)}`);
+ if (ts) assert.equal(parses(asFunctionType), false, `TypeScript refuses ${JSON.stringify(asFunctionType)}`);
+ }
+ }
+ // The page cut right after such a return type reads the same way, and is refused.
+ assert.equal(hasDefaultExport('export default <T extends object>(p: T): ({ [K in (keyof T)]: boolean }) => T'), false);
+ for (const [what, mapped] of PARENTHESISED_MAPPED_TYPES_READ) {
+ for (const modifier of ['', 'async ']) {
+ const code = `export default ${modifier}<T extends object>(p: T): (${mapped}) => null as never;\n`;
+ assert.equal(hasDefaultExport(code), true, `${what}: ${JSON.stringify(code)}`);
+ assert.deepStrictEqual(pageStructureProblems(code), [], what);
+ if (ts) assert.equal(parses(code), true, `TypeScript parses ${JSON.stringify(code)}`);
+ }
+ }
+ for (const [what, code] of PARENTHESISED_MAPPED_TYPE_REWRITES) {
+ assert.deepStrictEqual(pageStructureProblems(code), [], `${what}: ${JSON.stringify(code)}`);
+ if (ts) assert.equal(parses(code), true, `TypeScript parses ${JSON.stringify(code)}`);
+ if (babel) assert.equal(babelParses(code), true, `Babel parses ${JSON.stringify(code)}`);
+ }
+ for (const [what, returnType, expected] of MAPPED_KEY_NEIGHBOURS) {
+ const code = `export default <T extends object>(p: T): ${returnType} => null as never;\n`;
+ assert.equal(hasDefaultExport(code), expected, `${what}: ${JSON.stringify(code)}`);
+ if (ts) assert.equal(parses(code), expected, `TypeScript reads ${JSON.stringify(code)} the same`);
+ }
});
-// Known limits, pinned as they are: two rare return types that TypeScript parses and the gate refuses (2.18.0 refused every synchronous generic-arrow default
-// export, and admitted the async forms of both, which are now refused too). A binding
-// pattern's computed key is read as an expression only as far as telling an index signature's or a mapped type's key from one needs, and any group in parentheses counts
-// as an operand: `K in (keyof T)` reads as an expression, so `({ [K in (keyof T)]: boolean })` reads as a function type's parameters, which take the arrow. And a key the
-// reading does not know — one that starts with a regular expression — is taken for no expression: the parentheses around a function type's parameters then read as a
-// parenthesised type, the function type's `=>` as the arrow, and a leading `|` of its own return type as no body. The workarounds (AGENTS.md, "TSX source lexer — known
-// limits") are accepted.
-test('known limits: a mapped type with its key type in parentheses, and a computed key the reading does not know', () => {
- const refused = [];
- for (const key of ['(keyof T)', '((keyof T))', '(keyof T) as K', '(T extends object ? keyof T : never)']) {
- for (const modifier of ['', 'async ']) refused.push(`export default ${modifier}<T extends object>(p: T): ({ [K in ${key}]: boolean }) => null as never;\n`);
- }
- const regexKey = '<T,>(p: T): ({ [/key/.source]: value }: Record<string, T>) =>';
- refused.push(`export default ${regexKey} | typeof value | null => () => null;\n`, `export default async ${regexKey} | typeof value | null => () => null;\n`);
- for (const code of refused) assert.equal(hasDefaultExport(code), false, `refused, a known limit: ${JSON.stringify(code)}`);
- // The workarounds: no parentheses around the key's type, none around the return type, a type alias; no leading `|`, a key written as a string. And an arrow
- // without type parameters keeps its reading.
+// Known limit, pinned as it is (AGENTS.md, "TSX source lexer — known limits"): a computed key that starts with a regular expression is taken for no expression, although
+// TypeScript and Babel read one — a fail-closed reading, kept on purpose. A function type whose parameter has such a key reads as a parenthesised type, its `=>` as the
+// arrow and a leading `|` of its own return type as no body, so the page is refused although both parsers parse it, sync and async; by the same reading a write cut
+// right after such a function type is accepted (TypeScript refuses it, and so does the page compile). Reading the key as an expression would accept such a page
+// whatever its regular expression's flags are, and Babel refuses an unknown, repeated or clashing flag that TypeScript's parser takes (its checker refuses it).
+// [what, page]
+const REGEX_KEY_PAGES = [
+ ['a computed key that starts with a regular expression', 'export default <T,>(p: T): ({ [/key/.source]: value }: Record<string, T>) => | typeof value | null => () => null;\n'],
+ ['the same, async', 'export default async <T,>(p: T): ({ [/key/.source]: value }: Record<string, T>) => | typeof value | null => () => null;\n'],
+ ['a regular expression with flags and an index', 'export default <T,>(p: T): ({ [/k/gi[0]]: value }: Record<string, T>) => | T | null => () => null;\n'],
+];
+// [what, flags]: flags Babel refuses and TypeScript's parser takes.
+const REGEX_KEY_BAD_FLAGS = [['an unknown flag', 'x'], ['a repeated flag', 'gg'], ['`u` with `v`', 'uv'], ['an upper-case flag', 'G'], ['a letter beyond ASCII', 'ü']];
+
+test('known limit: a computed key that starts with a regular expression is no expression to the gate, whatever its flags', () => {
+ const ts = loadTypescriptOracle();
+ const babel = loadBabelOracle();
+ const parses = (code) => ts.createSourceFile('page.tsx', code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX).parseDiagnostics.length === 0;
+ const babelParses = (code) => {
+ try {
+ babel.parse(code, { sourceType: 'module', plugins: ['jsx', 'typescript'] });
+ return true;
+ } catch {
+ return false;
+ }
+ };
+ for (const [what, code] of REGEX_KEY_PAGES) {
+ assert.equal(hasDefaultExport(code), false, `${what}: refused, a known limit: ${JSON.stringify(code)}`);
+ assert.match(pageStructureProblems(code).join('\n'), /no complete default export/, what);
+ if (ts) assert.equal(parses(code), true, `TypeScript parses ${JSON.stringify(code)}`);
+ if (babel) assert.equal(babelParses(code), true, `Babel parses ${JSON.stringify(code)}`);
+ }
+ for (const [what, flags] of REGEX_KEY_BAD_FLAGS) {
+ const code = `export default <T,>(p: T): ({ [/k/${flags}.source]: v }: R) => | T | null => () => null;\n`;
+ assert.equal(hasDefaultExport(code), false, `${what}: refused: ${JSON.stringify(code)}`);
+ if (ts) assert.equal(parses(code), true, `TypeScript's parser takes ${JSON.stringify(code)}`);
+ if (babel) assert.equal(babelParses(code), false, `Babel refuses ${JSON.stringify(code)}`);
+ }
+ // By the same reading a page cut right after such a function type, or whose arrow the function type takes, is accepted, as it always was; TypeScript refuses it.
+ for (const code of ['export default <T,>(p: T): ({ [/k/]: v }) => T', 'export default <T,>(p: T): ({ [/k/]: v }) => p;\n', 'export default <T,>(p: T): ({ [K in /k/]: v }) => p;\n']) {
+ assert.equal(hasDefaultExport(code), true, `accepted, a known limit: ${JSON.stringify(code)}`);
+ if (ts) assert.equal(parses(code), false, `TypeScript refuses ${JSON.stringify(code)}`);
+ }
+ // The rewrites: no leading `|`, the key written as a string, a type alias for the function type; and an arrow without type parameters keeps its reading.
for (const code of [
- 'export default <T extends object>(p: T): ({ [K in keyof T]: boolean }) => null as never;\n',
- 'export default <T extends object>(p: T): { [K in (keyof T)]: boolean } => null as never;\n',
- 'type Flags<T> = { [K in (keyof T)]: boolean };\nexport default <T extends object>(p: T): Flags<T> => null as never;\n',
- `export default ${regexKey} typeof value | null => () => null;\n`,
+ 'export default <T,>(p: T): ({ [/key/.source]: value }: Record<string, T>) => typeof value | null => () => null;\n',
'export default <T,>(p: T): ({ ["key"]: value }: Record<string, T>) => | typeof value | null => () => null;\n',
'type Pick1<T> = (pair: Record<string, T>) => | T | null;\nexport default <T,>(p: T): Pick1<T> => () => null;\n',
'export default (p: T): ({ [/key/.source]: value }: Record<string, T>) => | typeof value | null => () => null;\n',
- ]) assert.deepStrictEqual(pageStructureProblems(code), [], code);
+ ]) {
+ assert.deepStrictEqual(pageStructureProblems(code), [], code);
+ if (ts) assert.equal(parses(code), true, `TypeScript parses ${JSON.stringify(code)}`);
+ }
// A group that holds an expression is one, as TypeScript reads it: these are function types that take the arrow, refused here and by TypeScript.
- const grouped = ['(a + b)', 'keyof(T)'].map((key) => `export default <T,>(p: T): ({ [${key}]: v }) => p;\n`);
- for (const code of grouped) assert.equal(hasDefaultExport(code), false, code);
- // With the TypeScript parser oracle set: TypeScript parses every page refused above — a known limit, not a cut — and none of the grouped expressions.
+ for (const code of ['(a + b)', 'keyof(T)'].map((key) => `export default <T,>(p: T): ({ [${key}]: v }) => p;\n`)) {
+ assert.equal(hasDefaultExport(code), false, code);
+ if (ts) assert.equal(parses(code), false, `TypeScript refuses ${JSON.stringify(code)}`);
+ }
+});
+
+// With the TypeScript parser oracle set (and Babel's, where set): across the key types a page writes — each in no, one and two pairs of parentheses, in a tuple, in an
+// array and in a union — and the shapes of a mapped type (modifiers, `?`, `as`, no type, a `;`), the gate accepts no page either parser refuses, and the pages
+// TypeScript parses that it refuses are the known limit above: a key type in a group, whose braces read as a binding pattern.
+test('mapped types in a parenthesised return type: the gate accepts no page TypeScript refuses, and refuses one it parses only where the key type is in a group', (t) => {
const ts = loadTypescriptOracle();
- if (!ts) return;
- const diagnostics = (code) => ts.createSourceFile('page.tsx', code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX).parseDiagnostics.length;
- for (const code of refused) assert.strictEqual(diagnostics(code), 0, `TypeScript parses ${JSON.stringify(code)}`);
- for (const code of grouped) assert.ok(diagnostics(code) > 0, `TypeScript refuses ${JSON.stringify(code)}`);
+ if (!ts) { t.skip('TYPESCRIPT_ORACLE_PATH is not set'); return; }
+ const babel = loadBabelOracle();
+ const parses = (code) => ts.createSourceFile('page.tsx', code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX).parseDiagnostics.length === 0;
+ const babelParses = (code) => {
+ try {
+ babel.parse(code, { sourceType: 'module', plugins: ['jsx', 'typescript'] });
+ return true;
+ } catch {
+ return false;
+ }
+ };
+ const types = ['keyof T', 'T', 'T | U', 'keyof T & string', 'T[number]', 'T[]', '"a" | "b"', '-1', 'typeof x', 'A.B<C>', 'readonly T[]', 'unique symbol',
+ 'T extends U ? keyof T : never', '[T, U]', '[]', '{}', 'Record<string, T>', 'Array<keyof T>'];
+ const members = ['[K in X]: boolean', '[K in X]?: T[K]', 'readonly [K in X]: boolean', '-readonly [K in X]-?: boolean', '[K in X]', '[K in X]: boolean;', '[K in X as (K)]: boolean'];
+ let accepted = 0;
+ let limit = 0;
+ for (const type of types) {
+ for (const shape of ['X', '(X)', '((X))', '(X)[]', '[X]', '(X) | U']) {
+ for (const member of members) {
+ for (const tail of [' => null as never;\n', ' => T']) {
+ const code = `export default <T extends object>(p: T): ({ ${member.replace('X', shape.replace('X', type))} })${tail}`;
+ if (hasDefaultExport(code)) {
+ accepted += 1;
+ assert.equal(parses(code), true, `TypeScript refuses ${JSON.stringify(code)}`);
+ if (babel) assert.equal(babelParses(code), true, `Babel refuses ${JSON.stringify(code)}`);
+ } else if (parses(code)) {
+ limit += 1;
+ assert.ok(shape !== 'X' && shape !== '(X)[]', `refused, and TypeScript parses ${JSON.stringify(code)}`);
+ }
+ }
+ }
+ }
+ }
+ // Both readings are met, many times.
+ assert.ok(accepted > 1000 && limit > 50, `accepted ${accepted}, refused as the known limit ${limit}`);
+});
+
+// `await` in the key of a parenthesised mapped type. TypeScript parses a return type outside the await context — an `async` arrow's too — so `await` there is a name unless
+// a word, a number or a string follows it on its line: `K in (await)` is an expression, the braces are a binding pattern, and the parentheses hold a function type's
+// parameters, which take the arrow's `=>` (`'=>' expected`). Babel refuses `await` as a name in a module. The gate never reads such a key as a mapped type's: the cut is
+// refused, and a function type with a `|` after its `=>` is accepted, as TypeScript reads both. [what, key type]
+const AWAIT_MAPPED_KEYS = [
+ ['`await` in parentheses', '(await)'], ['`await` in two pairs of parentheses', '((await))'], ['`await` in a tuple', '[await]'], ['`await` and a non-null assertion', '(await!)'],
+ ['`await` in parentheses, remapped', '(await) as K'], ['`await` in parentheses and a union', '(await) | U'], ['`await` before a line break', '(await\n)'],
+];
+
+test('`await` in the key of a parenthesised mapped type leaves the braces a binding pattern, as TypeScript reads them, sync and async', () => {
+ const ts = loadTypescriptOracle();
+ const parses = (code) => ts.createSourceFile('page.tsx', code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX).parseDiagnostics.length === 0;
+ for (const [what, key] of AWAIT_MAPPED_KEYS) {
+ for (const modifier of ['', 'async ']) {
+ const head = `export default ${modifier}<T,>(p: T): ({ [K in ${key}]: boolean })`;
+ // [page, whether it is accepted]: the cut and a page whose `=>` the function type takes are refused; the arrow after the function type's own return type is not.
+ for (const [code, expected] of [[`${head} => T`, false], [`${head} => null as never;\n`, false], [`${head} => | T | U => null as never;\n`, true]]) {
+ assert.equal(hasDefaultExport(code), expected, `${what}: ${JSON.stringify(code)}`);
+ if (ts) assert.equal(parses(code), expected, `TypeScript reads ${JSON.stringify(code)} the same`);
+ }
+ }
+ }
+ // A `/` after `await` divides, to TypeScript, where `await` is a name, and the page is refused, as TypeScript refuses it (the gate reads no regular expression as a
+ // key's operand: the known limit above).
+ for (const modifier of ['', 'async ']) {
+ const code = `export default ${modifier}<T,>(p: T): ({ [K in await /r/]: boolean }) => | T | U => null as never;\n`;
+ assert.equal(hasDefaultExport(code), false, code);
+ if (ts) assert.equal(parses(code), false, `TypeScript refuses ${JSON.stringify(code)}`);
+ }
+});
+
+// [what, mapped type, TypeScript parses the page, Babel parses it]: what a key or member type may hold — types only TypeScript's parser takes and leaves to its checker
+// (a predicate, a JSDoc type, a reserved word for a type's name, `readonly` before a name, a type parameter named by a word strict code reserves), types both parsers
+// take, and tokens whose spelling only a parser checks (an escaped keyword, a legacy octal number, consecutive numeric separators, a string escape out of range) beside
+// their valid neighbours. The known limit above reads every such page's braces as a binding pattern, so no token in them can make the gate accept the page.
+const MAPPED_TYPE_TOKENS = [
+ ['a predicate for the key type', '{ [K in (asserts x)]: boolean }', true, false], ['a predicate of `this` for the key type', '{ [K in (asserts this)]: boolean }', true, false],
+ ['a predicate with `is` for the key type', '{ [K in (asserts x is T)]: boolean }', true, false],
+ ['a JSDoc nullable key type', '{ [K in (?T)]: boolean }', true, false], ['the JSDoc unknown type', '{ [K in (?)]: boolean }', true, false],
+ ['the JSDoc any type', '{ [K in (*)]: boolean }', true, false], ['a JSDoc function type', '{ [K in (function(x): T)]: boolean }', true, false],
+ ['`function` for a type', '{ [K in (function)]: boolean }', true, false], ['a reserved word for a type', '{ [K in (if)]: boolean }', true, false],
+ ['`delete` for a type', '{ [K in (delete)]: boolean }', true, false], ['`class` for a type', '{ [K in (class)]: boolean }', true, false],
+ ['`readonly` before a name', '{ [K in (readonly T)]: boolean }', true, false], ['`readonly` twice', '{ [K in (readonly readonly T[])]: boolean }', true, false],
+ ['`infer` and a word strict code reserves', '{ [K in (infer yield)]: boolean }', true, false],
+ ['a type parameter named `yield`', '{ [yield in (keyof T)]: boolean }', true, false], ['a type parameter named `static`', '{ [static in (keyof T)]: boolean }', true, false],
+ ['`readonly` before an array type', '{ [K in (readonly T[])]: boolean }', true, true], ['`readonly` before an array of tuples', '{ [K in (readonly [T][])]: boolean }', true, true],
+ ['`infer` and a name', '{ [K in (T extends Array<infer U> ? U : never)]: boolean }', true, true], ['`keyof this`', '{ [K in (keyof this)]: boolean }', true, true],
+ ['an escaped reserved word for the member type', '{ [K in (keyof T)]: \\u0069f }', true, false],
+ ['an escaped reserved word in the `as` clause', '{ [K in (keyof T) as \\u0069f]: boolean }', true, false],
+ ['a reserved word in the `as` clause', '{ [K in (keyof T) as if]: boolean }', true, false],
+ ['a legacy octal number in the `as` clause', '{ [K in (keyof T) as 01]: boolean }', false, false],
+ ['consecutive numeric separators in the `as` clause', '{ [K in (keyof T) as 1__0]: boolean }', false, false],
+ ['a string escape out of range in the `as` clause', '{ [K in (keyof T) as "\\u{110000}"]: boolean }', false, false],
+ ['an escaped name for the member type', '{ [K in (keyof T)]: \\u0054 }', true, true], ['a number in the `as` clause', '{ [K in (keyof T) as 1]: boolean }', true, true],
+ ['an octal number in the `as` clause', '{ [K in (keyof T) as 0o1]: boolean }', true, true], ['a numeric separator in the `as` clause', '{ [K in (keyof T) as 1_0]: boolean }', true, true],
+];
+
+test('known limit: a parenthesised mapped type is refused whatever its key and member types spell, what only one parser takes or neither does included', () => {
+ const ts = loadTypescriptOracle();
+ const babel = loadBabelOracle();
+ const parses = (code) => ts.createSourceFile('page.tsx', code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX).parseDiagnostics.length === 0;
+ const babelParses = (code) => {
+ try {
+ babel.parse(code, { sourceType: 'module', plugins: ['jsx', 'typescript'] });
+ return true;
+ } catch {
+ return false;
+ }
+ };
+ for (const [what, mapped, typescriptParses, babelParsesIt] of MAPPED_TYPE_TOKENS) {
+ for (const modifier of ['', 'async ']) {
+ const code = `export default ${modifier}<T,>(p: T): (${mapped}) => null as never;\n`;
+ assert.equal(hasDefaultExport(code), false, `${what}: refused: ${JSON.stringify(code)}`);
+ if (ts) assert.equal(parses(code), typescriptParses, `TypeScript ${typescriptParses ? 'parses' : 'refuses'} ${JSON.stringify(code)}`);
+ if (babel) assert.equal(babelParses(code), babelParsesIt, `Babel ${babelParsesIt ? 'parses' : 'refuses'} ${JSON.stringify(code)}`);
+ }
+ }
+});
+
+// The mapped types of a parenthesised return type, their key types drawn from a vocabulary that holds what a key may be — a type, an expression, both or neither, `await`
+// and the words strict code reserves, the JSDoc types, predicates, reserved words, escaped words, numbers and strings a parser refuses — each in parentheses, in two
+// pairs, in a tuple, remapped and in a union: the page that only the mapped type's reading accepts is refused for every one of them. With both parser oracles set, both
+// parsers parse many of those pages (the known limit).
+test('mapped types in a parenthesised return type: a key type in a group is never read as a mapped type\'s, whatever the group holds', () => {
+ const ts = loadTypescriptOracle();
+ const babel = loadBabelOracle();
+ const parses = (code) => ts.createSourceFile('page.tsx', code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX).parseDiagnostics.length === 0;
+ const babelParses = (code) => {
+ try {
+ babel.parse(code, { sourceType: 'module', plugins: ['jsx', 'typescript'] });
+ return true;
+ } catch {
+ return false;
+ }
+ };
+ const atoms = ['keyof T', 'T', 'await', 'await x', 'await\n', 'yield', 'yield x', 'let', 'static', 'async', 'of', 'asserts', 'asserts x', 'asserts x is T', 'this is T', 'x is T',
+ 'this', 'super', 'null', 'void', 'void 0', 'typeof', 'typeof x', 'typeof await', 'delete', 'delete x', 'new', 'new X', 'if', 'const', 'class', 'enum', 'function', '?T', 'T?', '?', '!T',
+ 'T!', '*', '-1', '1n', '"a"', 'readonly T', 'readonly T[]', 'readonly [T]', 'unique symbol', 'infer U', 'infer yield', 'T[]', 'T[number]', 'T[if]', '[T]', '[if]', '[]', '{}',
+ 'A.B<C>', 'A<if>', 'A<>', 'T extends U ? X : Y', 'T | U', 'x.y', 'f()', 'f(await)', 'a + b', 'a ? b', 'x!', '!x', '/re/', '/re/gg', 'x as T', 'f<T>', 'a < b', 'x in y',
+ 'keyof await', 'keyof yield', 'keyof if', '\\u0061wait', '\\u0061wait x', '\\u0069f', 'keyof \\u0069f', '\\u0054', '01', '1__0', '0o1', '1_0', '"\\u{110000}"', '"\\u0041"'];
+ let limit = 0;
+ for (const atom of atoms) {
+ for (const shape of ['(X)', '((X))', '[X]', '(X) as K', '(X) | U']) {
+ for (const modifier of ['', 'async ']) {
+ const code = `export default ${modifier}<T,>(p: T): ({ [K in ${shape.replace('X', atom)}]: boolean }) => null as never;\n`;
+ assert.equal(hasDefaultExport(code), false, JSON.stringify(code));
+ if (ts && babel && parses(code) && babelParses(code)) limit += 1;
+ }
+ }
+ }
+ if (ts && babel) assert.ok(limit >= 60, `refused, and both parsers parse it: ${limit}`);
});
// An arrow with no type parameters is read as it always was (defaultExportIsComplete reads it, not genericArrowIsComplete), whatever its return type holds.
diff --git a/plugins/model-apps/scripts/tests/teardown-form-embedded-page.test.js b/plugins/model-apps/scripts/tests/teardown-form-embedded-page.test.js
new file mode 100644
index 000000000..cdc8a42bf
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/teardown-form-embedded-page.test.js
@@ -0,0 +1,131 @@
+'use strict';
+
+// KNOWN LIMIT, pinned: teardown deletes a generative page it proved this app's even when a form still embeds it.
+// A form embeds a page through the MscrmControls.UxAgentControl control, whose static `RefId` parameter holds the page's id:
+// <customControl formFactor="0" name="MscrmControls.UxAgentControl"><parameters>
+// <RefId type="SingleLine.Text" static="true">11111111-1111-4111-8111-111111111111</RefId></parameters></customControl>
+// Dataverse records no dependency for that value (measured: the page reported zero dependents and its delete answered 204), so the
+// platform never refuses the delete, and teardown reads no form: the page goes, and the form is left showing a page that is gone.
+// AGENTS.md (the teardown entry), references/app-spec-schema.md ("Teardown page scope") and the app-builder skill tell the maker to take
+// the page off such forms before tearing the app down. Teardown does not look for those forms itself: a forms read alone cannot prove that
+// no form names the page. This test holds the delete set to exactly what teardown has always deleted for such an app, and fails if
+// teardown starts reading forms or keeping the page — so the documents of the limit change with it.
+
+const { test } = require('node:test');
+const assert = require('node:assert');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { runTeardown } = require('../lib/sdk-teardown.js');
+const { appUniqueName } = require('../lib/sdk-build.js');
+
+const ENV = 'https://contoso.crm.dynamics.com';
+const PAGE = '11111111-1111-4111-8111-111111111111';
+const FORM = '22222222-2222-4222-8222-222222222222';
+
+// A main form of `account` with the page on it, as the form designer saves it (one customControl per form factor).
+const EMBEDDING_FORM = '<form><tabs><tab name="general"><columns><column width="100%"><sections><section name="page"><rows><row><cell id="{c0a8f1e2-0000-4000-8000-000000000001}">'
+ + '<control id="genpage_host" classid="{F9A8A302-114E-466A-B582-6771B2AE0D92}" /></cell></row></rows></section></sections></column></columns></tab></tabs>'
+ + '<controlDescriptions><controlDescription forControl="{F9A8A302-114E-466A-B582-6771B2AE0D92}">'
+ + `<customControl formFactor="0" name="MscrmControls.UxAgentControl"><parameters><RefId type="SingleLine.Text" static="true">${PAGE}</RefId></parameters></customControl>`
+ + `<customControl formFactor="2" name="MscrmControls.UxAgentControl"><parameters><RefId type="SingleLine.Text" static="true">${PAGE}</RefId></parameters></customControl>`
+ + '</controlDescription></controlDescriptions></form>';
+
+// An app (its sitemap names the page, which proves the page this app's), the page in its saved layer, the page manifest, one table the
+// app reuses (`existing: true`, kept with its forms) and one it created, and the `account` form above. A read of the forms is recorded and
+// answered with what the environment holds, so a teardown that looked would find the page on the form.
+function environment() {
+ const spec = {
+ solution: { uniqueName: 'PgSln', publisherPrefix: 'new' },
+ app: { name: 'Pages App' },
+ entities: [
+ { schemaName: 'account', existing: true, displayName: 'Account', primaryAttribute: { schemaName: 'name', displayName: 'Name' } },
+ { schemaName: 'new_Ticket', displayName: 'Ticket', primaryAttribute: { schemaName: 'new_name', displayName: 'Name' } },
+ ],
+ };
+ const manifestName = `${appUniqueName(spec)}_pagemanifest`;
+ const state = {
+ app: true,
+ pages: new Set([PAGE]),
+ tables: new Set(['account', 'new_ticket']),
+ forms: [{ table: 'account', formid: FORM, name: 'Account Main', formxml: EMBEDDING_FORM }],
+ resources: new Map([[manifestName.toLowerCase(), 'wr-manifest'], [`${appUniqueName(spec)}_icon`.toLowerCase(), 'wr-icon']]),
+ solution: true,
+ deletes: [],
+ formReads: [],
+ };
+ const manifest = Buffer.from(JSON.stringify({ schemaVersion: 1, pages: [{ key: 'overview', name: 'Overview', pageId: PAGE }] }), 'utf8').toString('base64');
+ const sdk = {
+ resolveArtifact: async (kind, identity) => {
+ if (kind === 'app') return state.app ? [{ id: 'app-1', name: 'Pages App', appModuleIdUnique: 'app-u-1' }] : [];
+ if (kind === 'webResource') {
+ const id = state.resources.get(String(identity.name).toLowerCase());
+ return id ? [{ id, name: identity.name }] : [];
+ }
+ if (kind === 'solution') return state.solution ? [{ id: 'sol-1', name: 'PgSln' }] : [];
+ return [];
+ },
+ deleteAppCascade: async () => { state.deletes.push('app'); state.app = false; return { success: true, deleted: [], failures: [] }; },
+ queryRecords: async (entity) => {
+ if (entity === 'webresource') return state.resources.has(manifestName.toLowerCase()) ? [{ content: manifest }] : [];
+ if (entity === 'appmodule') return state.app ? [{ appmoduleid: 'app-1', appmoduleidunique: 'app-u-1' }] : [];
+ if (entity === 'appmodulecomponent') return [{ objectid: 'sitemap-1', componenttype: 62 }];
+ if (entity === 'sitemap') return state.app ? [{ sitemapxml: `<SiteMap><Area><Group><SubArea GenPageId="${PAGE}" /></Group></Area></SiteMap>` }] : [];
+ if (entity === 'systemform') {
+ state.formReads.push('systemform');
+ return state.forms.map((f) => ({ formid: f.formid, name: f.name, formxml: f.formxml, objecttypecode: f.table }));
+ }
+ return [];
+ },
+ findTables: async (logical) => [...state.tables].filter((t) => t.includes(String(logical).toLowerCase())).map((t) => ({ logicalName: t, isCustom: t !== 'account' })),
+ dataverse: {
+ get: async (url) => {
+ if (url.startsWith('/uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()')) {
+ return { status: 200, body: { value: [...state.pages].map((id) => ({ uxagentprojectid: id, name: 'Overview', componentstate: 0 })) } };
+ }
+ if (url.startsWith('/systemforms')) {
+ state.formReads.push(url);
+ const table = (/objecttypecode eq '([^']+)'/.exec(decodeURIComponent(url)) || [])[1];
+ return { status: 200, body: { value: state.forms.filter((f) => !table || f.table === table).map((f) => ({ formid: f.formid, name: f.name, formxml: f.formxml })) } };
+ }
+ throw new Error(`unexpected read ${url}`);
+ },
+ },
+ deleteRemoteArtifact: async (type, id) => {
+ assert.strictEqual(type, 'genPage');
+ state.deletes.push(`page:${id}`);
+ state.pages.delete(id);
+ },
+ deleteTable: async (logical) => {
+ state.deletes.push(`table:${logical}`);
+ state.tables.delete(logical);
+ state.forms = state.forms.filter((f) => f.table !== logical);
+ },
+ deleteWebResource: async (id) => {
+ state.deletes.push(id);
+ for (const [name, rid] of state.resources) if (rid === id) state.resources.delete(name);
+ },
+ deleteSolution: async () => { state.deletes.push('solution'); state.solution = false; },
+ };
+ return { spec, sdk, state };
+}
+
+test('a page a form of the app\'s tables still embeds is deleted like any proven page — no form is read, and the delete set is what teardown has always deleted (a known limit)', async () => {
+ const env = environment();
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'contoso-form-embedded-page-'));
+ try {
+ const dry = await runTeardown(env.spec, { env: ENV, apply: false }, { sdk: env.sdk });
+ assert.ok(dry.plan.includes(`generative pages proven for this app: ${PAGE} "Overview" (would delete)`), JSON.stringify(dry.plan));
+
+ const result = await runTeardown(env.spec, { env: ENV, apply: true, workspaceDir: dir }, { sdk: env.sdk });
+ assert.strictEqual(result.ok, true, JSON.stringify(result.errors));
+ assert.deepStrictEqual(result.deleted.genpage, [PAGE]);
+ assert.deepStrictEqual(env.state.deletes, ['app', `page:${PAGE}`, 'table:new_ticket', 'wr-icon', 'wr-manifest', 'solution']);
+ assert.deepStrictEqual(env.state.formReads, [], 'teardown reads no form before it deletes a page');
+ // The form of the table teardown keeps still names a page that is gone: the dangling reference the documents tell the maker to remove first.
+ assert.ok(!env.state.pages.has(PAGE));
+ assert.ok(env.state.forms.some((f) => f.table === 'account' && f.formxml.includes(PAGE)));
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
diff --git a/plugins/model-apps/scripts/tests/teardown-model-app.test.js b/plugins/model-apps/scripts/tests/teardown-model-app.test.js
index 298510831..b277a0b83 100644
--- a/plugins/model-apps/scripts/tests/teardown-model-app.test.js
+++ b/plugins/model-apps/scripts/tests/teardown-model-app.test.js
@@ -156,6 +156,28 @@ test('such a spec is still refused before any teardown for any other problem, an
assert.strictEqual(sdk.calls.length, 0, 'no SDK calls on a bad spec');
});
+// A key a table's `primaryAttribute` does not take is refused the same way, and an earlier release accepted and ignored it just the
+// same: under the structural profile it is a warning, so such an app is still torn down, behind the same authorization.
+const PRIMARY_ATTRIBUTE_TYPO = "entity new_ticket: unknown key 'maxlength' on primaryAttribute — did you mean 'maxLength'? (allowed: schemaName, displayName, autoNumberFormat, required, maxLength)";
+function deskWithPrimaryAttributeTypo() {
+ const spec = JSON.parse(JSON.stringify(desk));
+ spec.entities.find((e) => e.schemaName === 'new_ticket').primaryAttribute.maxlength = 200;
+ return spec;
+}
+
+test('a spec whose primaryAttribute carries a key it does not take is still torn down: the dry run lists the same plan, and apply deletes', async () => {
+ const structural = validateAppSpec(deskWithPrimaryAttributeTypo(), { profile: 'structural' });
+ assert.deepStrictEqual([structural.ok, structural.errors, structural.warnings], [true, [], [PRIMARY_ATTRIBUTE_TYPO]], 'the finding is a warning there');
+ const r = await teardownModelApp(deskWithPrimaryAttributeTypo(), { apply: false }, { sdk: { queryRecords: async () => [] } });
+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
+ const plain = await teardownModelApp(desk, { apply: false }, { sdk: { queryRecords: async () => [] } });
+ assert.deepStrictEqual(r.plan, plain.plan, 'the plan of the same spec without the key');
+ const sdk = presentSdk();
+ const applied = await teardownModelApp(deskWithPrimaryAttributeTypo(), { apply: true, allowDestructive: true }, { sdk });
+ assert.strictEqual(applied.ok, true, JSON.stringify(applied.errors));
+ assert.ok(sdk.calls.some((c) => c.method === 'deleteAppCascade'), 'app deleted');
+});
+
// REVERSED by #587 item 5, deliberately. This test used to assert that teardown CONTINUES after a
// failed app delete ("later steps still run after the app refusal"), on a best-effort rationale:
// one failure should not strand the rest. Deep lifecycle testing showed that is the wrong rule for
diff --git a/plugins/model-apps/scripts/tests/throwaway-sdk.test.js b/plugins/model-apps/scripts/tests/throwaway-sdk.test.js
index 23c20d41c..8eb4acfb0 100644
--- a/plugins/model-apps/scripts/tests/throwaway-sdk.test.js
+++ b/plugins/model-apps/scripts/tests/throwaway-sdk.test.js
@@ -2,6 +2,9 @@
// lib/throwaway-sdk.js: the bundled SDK over a throwaway workspace folder, removed whichever way the run ends. apps.js, list-tables.js and
// list-languages.js each wrote this out before it was one module; these tests make every thing that can go wrong go wrong, and look for the folder.
// The scripts' own tests drive the helper too (with the SDK and the client stubbed), and the real-bundle tests drive it with the real ones.
+// This file checks where lib/temp-workspace.js makes a workspace, so it works in a temp folder of its own (helpers/own-temp-folder.js): in the
+// suite's shared one, other test processes make and remove the plugin's workspace folder. Required first, so every path below is inside it.
+require('./helpers/own-temp-folder.js');
const test = require('node:test');
const assert = require('node:assert');
const fs = require('node:fs');
diff --git a/plugins/model-apps/scripts/tests/type-parameter-heads.test.js b/plugins/model-apps/scripts/tests/type-parameter-heads.test.js
index 616c29613..f64ddac90 100644
--- a/plugins/model-apps/scripts/tests/type-parameter-heads.test.js
+++ b/plugins/model-apps/scripts/tests/type-parameter-heads.test.js
@@ -13,6 +13,9 @@ const { test } = require('node:test');
const assert = require('node:assert');
const { opensTypeParameters, blankNonCodePreservingTemplateExpressions, TYPE_PARAMETER_MODIFIERS, MEMBER_NAME_OPERATORS, MEMBER_PREFIX_WORDS, OPERATOR_WORD_ENDS_MEMBER_AFTER, OPERATOR_WORDS_THAT_ARE_NAMES, HEAD_NESTING } = require('../lib/source-literals.js');
const { resolvePageRefs, navigationFrontier } = require('../lib/pageref-resolver.js');
+// These tests hold the lexer to its own rules — what it reads for certain, what it reports as a guess, and what a guess costs a page — so they read pages with
+// the lexer alone. Where the lexer guesses, the gates ask the TypeScript parser (typescript-views.js), which parser-check.test.js tests.
+require('../lib/typescript-views.js').setParserCheck(false);
const { loadTypescriptOracle, loadBaseLexer } = require('./helpers/typescript-oracle.js');
const { cleanSourceFile, readingAt, isElement, tokenVocabulary } = require('./helpers/angle-frames.js');
const { NEWLINE_GAPS, DECORATED_PLACES, UNREADABLE_LISTS, UNREADABLE_HEADS, ESCAPED_HEADS, ESCAPE_PLACES, ESCAPE_GAPS, CLASS_HERITAGES, LAST_ELEMENT_HERITAGES, decoratorEndPages, decimalPointPages, NUMBER_GAPS, KEYWORD_NAMES, KEYWORD_BODIES, KEYWORD_METHOD_FRAMES, CLASS_VALUES_WRAPPED, OBJECT_VALUES, OBJECT_VALUE_FRAMES, SHORTHAND_NAMES, SHORTHAND_FRAMES } = require('./helpers/type-head-pages.js');
diff --git a/plugins/model-apps/scripts/tests/unattended-skill-contract.test.js b/plugins/model-apps/scripts/tests/unattended-skill-contract.test.js
index f6431c3e0..48d94a78f 100644
--- a/plugins/model-apps/scripts/tests/unattended-skill-contract.test.js
+++ b/plugins/model-apps/scripts/tests/unattended-skill-contract.test.js
@@ -78,3 +78,22 @@ test('the genpage unattended markers satisfy the evaluator patterns they are pin
'the pinned mode marker must start with `Unattended default:` so isUnattendedLog detects it',
);
});
+
+// A data-semantics default is recorded on the same `Unattended default:` marker as the plan approval, so the documented semantic
+// record must never satisfy the evaluator's plan-approval check — even when its answer is a choice labelled "Approved" — and the
+// documented approval line must still satisfy it. Counterpart: evals/model-apps/genpage/lib/assertions-layer-1.js
+// (PLAN_APPROVAL_RECORD, read by the EnterPlanMode workflow assertion).
+test('the documented semantic default record never stands in for the plan-approval record', () => {
+ const { WORKFLOW_ASSERTIONS } = require(path.join(PLUGIN, '..', '..', 'evals', 'model-apps', 'genpage', 'lib', 'assertions-layer-1.js'));
+ const check = WORKFLOW_ASSERTIONS.get('Phase 1 (Planner): The plan is presented via EnterPlanMode and user approval is requested');
+ const skill = read('skills', 'genpage', 'SKILL.md');
+ const template = /`(Unattended default: <assumption id> \/ <question id> → <answer> \(<reason>\))`/.exec(skill);
+ assert.ok(template, 'SKILL.md documents the semantic default record');
+ const semantic = template[1].replace('<assumption id>', 'A1').replace('<question id>', 'plan-status').replace('<answer>', 'Approved').replace('<reason>', 'the only status value the request names');
+ const mode = 'Unattended default: interaction mode → unattended (--non-interactive flag)';
+ const grade = (log) => check({ fixture: { id: 2, dirName: '2-test', dir: '/fake', files: [], workflowLog: log, genpagePlan: null, genpageEditPlan: null, entityCreationLog: null }, eval: { id: 2, expectations: [] } }).status;
+ assert.equal(grade(`${mode}\n${semantic}`), 'fail', 'a semantic default is not a plan approval');
+ assert.equal(grade(`${mode}\n${semantic}\nUnattended default: plan approval → approved (unattended mode; all semantic questions resolved)`), 'pass');
+ assert.match(skill, /Only once every data-semantics question is answered, treat the plan as approved/);
+ assert.match(skill, /If it marked none, \*\*halt\*\*/, 'neighbour: an unanswered question with no marked default halts an unattended run');
+});
diff --git a/plugins/model-apps/scripts/tests/valid-page-differential.test.js b/plugins/model-apps/scripts/tests/valid-page-differential.test.js
index 4fb10cec4..2ca9bbbd3 100644
--- a/plugins/model-apps/scripts/tests/valid-page-differential.test.js
+++ b/plugins/model-apps/scripts/tests/valid-page-differential.test.js
@@ -23,6 +23,9 @@ const assert = require('node:assert');
const { loadTypescriptOracle, loadBaseLexer } = require('./helpers/typescript-oracle.js');
const { validPages, heldOpenLinePages, NAVIGATION_CALL, SIGNATURE_MEMBERS, HIDDEN_CLOSING_MEMBERS, KEYWORD_PARAMETER_MEMBERS, KEYWORD_HIDDEN_MEMBERS, KEYWORD_HEAD_ELEMENTS, KEYWORD_HIDING_ELEMENTS, HIDING_ELEMENTS, INITIALIZER_ELEMENTS, FAILING_LIST_ELEMENTS, EXACT_INITIALIZER_ELEMENTS, PROSE_ELEMENTS, SHAPED_PROSE_ELEMENTS, PROSE_OPEN_ELEMENTS, HELD_OPEN_ELEMENTS, VALUE_POSITIONS, page: pageOf } = require('./helpers/valid-pages.js');
const next = require('../lib/pageref-resolver.js');
+// These tests hold the lexer to its own rules — what it reads for certain, what it reports as a guess, and what a guess costs a page — so they read pages with
+// the lexer alone. Where the lexer guesses, the gates ask the TypeScript parser (typescript-views.js), which parser-check.test.js tests.
+require('../lib/typescript-views.js').setParserCheck(false);
const SKIP = 'no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to run it';
const ID = '11111111-1111-4111-8111-111111111111';
diff --git a/plugins/model-apps/scripts/tests/verify-model-app.test.js b/plugins/model-apps/scripts/tests/verify-model-app.test.js
index bae2e7ac8..11a375255 100644
--- a/plugins/model-apps/scripts/tests/verify-model-app.test.js
+++ b/plugins/model-apps/scripts/tests/verify-model-app.test.js
@@ -989,6 +989,22 @@ test('verify CLI still refuses such a spec for any other problem — before any
assert.deepStrictEqual(reads, [], 'nothing was read');
});
+// --- a table whose primaryAttribute carries a key it does not take ---------------------------------------------------------------------
+// The build, the lint and the provisioning gate refuse a key a table's `primaryAttribute` does not take; a release before that check accepted
+// and ignored one. Verification passes primaryAttributeKeys: 'warn', as it passes fieldOptionKeys: 'warn': a warning that names the key and the
+// key it most likely meant, and the verdict is the deployment's.
+const PRIMARY_ATTRIBUTE_TYPO = "entity new_ticket: unknown key 'maxlength' on primaryAttribute — did you mean 'maxLength'? (allowed: schemaName, displayName, autoNumberFormat, required, maxLength)";
+
+test('verify CLI still verifies the deployment of a table whose primaryAttribute carries a key it does not take — and warns, naming the key', async () => {
+ const { reads, emitted, stderr } = await verifyOlderSpec(appSpec({ columns: [column({ type: 'Text' })], primaryAttribute: nameColumn({ maxlength: 200 }) }));
+ const result = JSON.parse(JSON.stringify(emitted.payload));
+ assert.strictEqual(emitted.ok, true, JSON.stringify(result));
+ assert.ok(result.total > 0 && result.present === result.total, `the deployment was checked: ${JSON.stringify(result)}`);
+ assert.ok(reads.includes('columns new_ticket'), `the deployed columns were read: ${JSON.stringify(reads)}`);
+ assert.ok(stderr.includes(`WARNING: ${PRIMARY_ATTRIBUTE_TYPO}\n`), stderr);
+ assert.deepStrictEqual(result.warnings, [PRIMARY_ATTRIBUTE_TYPO]);
+});
+
// --- the result JSON carries what stderr warns -----------------------------------------------------------------------------------------
// A person reads the `WARNING:` lines verify prints, but a caller that reads only the JSON result — a skill, a pipeline — lost them. The result's optional
// `warnings` array holds the same messages, without the prefix and in the order they were printed, and is left out when there is none, as `unverified` is.
diff --git a/plugins/model-apps/scripts/tests/verify-spec.test.js b/plugins/model-apps/scripts/tests/verify-spec.test.js
index c11c886b5..21679b6ab 100644
--- a/plugins/model-apps/scripts/tests/verify-spec.test.js
+++ b/plugins/model-apps/scripts/tests/verify-spec.test.js
@@ -7,6 +7,10 @@ const { SDK_ROLE_MARKER } = require('../lib/app-spec.js');
const { parseTranslationWorkbook, readTranslationLabels } = require('../lib/translation-labels.js');
const { workbookXml, exportZip, exportAnswer } = require('./helpers/translation-export.js');
const { OBJECT_DIVISION_PAGE, MISREAD_PAGES, TEMPLATE_LINE_PAGE, JSX_TEXT_PAGE, ELEMENT_AFTER_OPERATOR_PAGES, ELEMENT_LOOKALIKE_PAGES, ELEMENT_PAGE_TOKEN_LINE, FUNCTION_TYPE_PAGES } = require('./helpers/misread-page.js');
+// What a guess costs a page where the TypeScript parser does not settle it (lib/typescript-views.js): these tests read the page with the lexer alone.
+// parser-check.test.js holds what the parser settles.
+const { setParserCheck } = require('../lib/typescript-views.js');
+const lexerAlone = (t) => { setParserCheck(false); t.after(() => setParserCheck(true)); };
const idFor = (set) => ({ savedquery: 'savedqueryid', savedqueryvisualization: 'savedqueryvisualizationid', systemform: 'formid' }[set] || 'id');
@@ -493,7 +497,8 @@ test('verifySpec pages: an id in a call the lexer reads only by guess does not p
// A PAGEREF_ token the lexer hides is still a token that shipped: this page was resolved the way a build resolved it, and its second call
// sits behind a false comment, so the oracle finds no target for it and the old check passed.
-test('verifySpec pages: a PAGEREF_ token the lexer hid in deployed code FAILS the no-pageref check, naming where', async () => {
+test('verifySpec pages: a PAGEREF_ token the lexer hid in deployed code FAILS the no-pageref check, naming where', async (t) => {
+ lexerAlone(t);
const deployed = OBJECT_DIVISION_PAGE.replace('"PAGEREF_detail"', `"${GP_DETAIL}"`);
assert.strictEqual(deployed.split('PAGEREF_detail').length - 1, 1, 'one call resolved, one left');
const read = pageRead({ sitemapIds: [GP_OVERVIEW, GP_DETAIL], existenceIds: [GP_OVERVIEW, GP_DETAIL], manifest: BOTH_MANIFEST, sitemap: SITEMAP_OK, code: { [GP_OVERVIEW]: deployed } });
@@ -515,6 +520,19 @@ test('verifySpec pages: a PAGEREF_ token the lexer hid in deployed code FAILS th
assert.strictEqual(clean.ok, true, JSON.stringify(clean.missing));
});
+// The same page, read as the TypeScript parser reads it where the lexer guessed (lib/typescript-views.js): the second call is seen, so its token is the token of a call
+// that the resolve step left — with no guess to name — and the check still fails.
+test('verifySpec pages: a PAGEREF_ token left in a call the lexer misreads FAILS the no-pageref check, read as TypeScript parses the page', async () => {
+ const deployed = OBJECT_DIVISION_PAGE.replace('"PAGEREF_detail"', `"${GP_DETAIL}"`);
+ const read = pageRead({ sitemapIds: [GP_OVERVIEW, GP_DETAIL], existenceIds: [GP_OVERVIEW, GP_DETAIL], manifest: BOTH_MANIFEST, sitemap: SITEMAP_OK, code: { [GP_OVERVIEW]: deployed } });
+ const r = await verifySpec(pageSpec(), read);
+ const check = r.checks.find((c) => c.kind === 'page-no-pageref');
+ assert.ok(check && !check.present);
+ assert.doesNotMatch(check.detail, /ambiguity/);
+ assert.ok(r.checks.some((c) => c.kind === 'page-nav' && c.present), 'the resolved call proves the edge');
+ assert.strictEqual(r.ok, false);
+});
+
// A call is trusted only if all of it lies before the first place the lexer guessed. The members of an options object after a guess are
// not read for certain, and a getter or a computed key there can make the call something else — here the call is
// `{ pageType: "entityrecord", … }` when it runs — so an id in a call whose object runs through a guess proves no edge.
diff --git a/plugins/model-apps/scripts/tests/web-resource-content-drift.test.js b/plugins/model-apps/scripts/tests/web-resource-content-drift.test.js
new file mode 100644
index 000000000..92b851850
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/web-resource-content-drift.test.js
@@ -0,0 +1,175 @@
+'use strict';
+// A rebuild reuses a spec web resource that exists and does not write its content (references/app-spec-schema-advanced.md: "Content edits
+// are NOT applied on rebuild" — the phase is discover-then-skip, like charts, command bars and dashboards). Until this was pinned it was
+// also SILENT: the skip line said only "(exists — reuse)", where the chart, command and dashboard lines say their edits are not applied,
+// and verify did not look at web resources at all — so an edited script was reported built and verified while the old one kept running.
+// Now the build reads the deployed (published) content of the row it reuses and compares it, byte for byte, with what the spec would
+// write; a difference is said in the skip line and as a warning, and nothing is written. Verify (the build's --verify and
+// verify-model-app.js) checks that each declared web resource exists and, unless it is `external` (a shared resource the build reuses as
+// it finds it), holds the spec's content.
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { createMakerSdk, createNodeWorkspaceStorage } = require('../vendor/cds-maker-sdk.cjs');
+const { runSdkBuild } = require('../lib/sdk-build.js');
+const { verifySpec } = require('../lib/verify-spec.js');
+const { readerFor } = require('../verify-model-app.js');
+const { createFakeBuildOrg } = require('./helpers/fake-app-build-org.js');
+
+const dirs = [];
+test.after(() => { for (const d of dirs) fs.rmSync(d, { recursive: true, force: true }); });
+const tempDir = () => { const d = fs.mkdtempSync(path.join(os.tmpdir(), 'wr-content-')); dirs.push(d); return d; };
+const base64 = (text) => Buffer.from(text, 'utf8').toString('base64');
+
+const SCRIPT = 'contoso_/scripts/form.js';
+const ICON = 'contoso_/icons/item.svg';
+const OLD_CODE = 'var Form = { onLoad: function () {} };';
+const NEW_CODE = 'var Form = { onLoad: function () { console.log("v2"); } };';
+const SVG = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path d="M1 1h14v14H1z"/></svg>';
+const spec = (webResources) => ({
+ solution: { uniqueName: 'ContosoReview', displayName: 'Contoso Review', publisherPrefix: 'contoso' },
+ app: { name: 'Publish Review', uniqueName: 'contoso_publishreview' },
+ entities: [{ schemaName: 'contoso_item', displayName: 'Item', existing: true, primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name' }, columns: [] }],
+ webResources,
+});
+
+// The real bundle over the stateful fake of helpers/fake-app-build-org.js: a web resource has a saved and a published layer, and a plain read
+// of it answers the published one. Only the web-resources phase runs.
+function scenario() {
+ const org = createFakeBuildOrg({ entities: {} });
+ const dir = tempDir();
+ async function build(built) {
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(dir), instanceUrl: org.origin, httpClient: org.httpClient });
+ await sdk.initWorkspace();
+ const mark = org.calls.length;
+ const warnings = [];
+ const events = [];
+ const outcome = await runSdkBuild(built, { sdk, apply: true, publish: true, phases: ['web-resources'], workspaceDir: dir, appDir: dir, env: org.origin, warn: (w) => warnings.push(String(w)), emit: (e) => events.push(e) });
+ const calls = org.calls.slice(mark);
+ return { outcome, warnings, calls, writes: calls.filter((c) => c.method !== 'GET'), skips: events.filter((e) => e.status === 'skip').map((e) => e.label) };
+ }
+ const row = (name) => [...org.resources.values()].find((r) => r.name === name);
+ return { org, dir, build, row };
+}
+
+const DIFFERS = (name) => `web resource ${name} (exists — reuse; its deployed content differs from the spec's: content edits aren't applied on rebuild, recreate to change)`;
+const WARNING = (name) => `web resource ${name}: its deployed content differs from the spec's and is left as it is — a rebuild does not write the content of a web resource that exists; delete it (or tear the app down) and build again to deploy the spec's content`;
+
+// --- the build ------------------------------------------------------------------------------------------------------------------------------------------
+
+test('a rebuild after a content edit says that the deployed content differs and is not applied, in its skip line and a warning, and writes nothing', async () => {
+ const s = scenario();
+ await s.build(spec([{ name: SCRIPT, type: 'js', content: OLD_CODE }]));
+ const id = s.row(SCRIPT).webresourceid;
+ const edited = await s.build(spec([{ name: SCRIPT, type: 'js', content: NEW_CODE }]));
+ assert.ok(edited.outcome.ok);
+ assert.deepEqual(edited.skips, [DIFFERS(SCRIPT)]);
+ assert.deepEqual(edited.warnings, [WARNING(SCRIPT)]);
+ assert.deepEqual(edited.writes, [], 'nothing is written: the build stays additive');
+ assert.equal(s.row(SCRIPT).publishedContent, base64(OLD_CODE), 'the deployed content is as it was');
+ assert.equal(edited.outcome.created.webResources[SCRIPT], id, 'the row is reused');
+});
+
+test('an unchanged rebuild says what it always said, warns nothing and writes nothing', async () => {
+ const s = scenario();
+ await s.build(spec([{ name: SCRIPT, type: 'js', content: OLD_CODE }]));
+ const again = await s.build(spec([{ name: SCRIPT, type: 'js', content: OLD_CODE }]));
+ assert.deepEqual(again.skips, [`web resource ${SCRIPT} (exists — reuse)`]);
+ assert.deepEqual(again.warnings, []);
+ assert.deepEqual(again.writes, []);
+});
+
+test('the comparison is of the bytes the spec writes, whichever source gives them: contentPath, and contentBase64 for a binary type', async () => {
+ const s = scenario();
+ fs.writeFileSync(path.join(s.dir, 'form.js'), OLD_CODE);
+ await s.build(spec([{ name: SCRIPT, type: 'js', contentPath: 'form.js' }, { name: ICON, type: 'svg', contentBase64: base64(SVG) }]));
+ const same = await s.build(spec([{ name: SCRIPT, type: 'js', contentPath: 'form.js' }, { name: ICON, type: 'svg', content: SVG }]));
+ assert.deepEqual(same.skips, [`web resource ${SCRIPT} (exists — reuse)`, `web resource ${ICON} (exists — reuse)`], 'the same bytes, written as text this time');
+ assert.deepEqual(same.warnings, []);
+ fs.writeFileSync(path.join(s.dir, 'form.js'), NEW_CODE);
+ const edited = await s.build(spec([{ name: SCRIPT, type: 'js', contentPath: 'form.js' }, { name: ICON, type: 'svg', contentBase64: base64(SVG.replace('14v14', '12v12')) }]));
+ assert.deepEqual(edited.skips, [DIFFERS(SCRIPT), DIFFERS(ICON)]);
+ assert.deepEqual(edited.warnings, [WARNING(SCRIPT), WARNING(ICON)]);
+ assert.deepEqual(edited.writes, []);
+});
+
+test('an external web resource — shared, reused as the build finds it — is not compared', async () => {
+ const s = scenario();
+ await s.build(spec([{ name: ICON, type: 'svg', content: SVG }]));
+ const again = await s.build(spec([{ name: ICON, type: 'svg', content: SVG.replace('14v14', '12v12'), external: true }]));
+ assert.deepEqual(again.skips, [`web resource ${ICON} (exists — reuse)`]);
+ assert.deepEqual(again.warnings, []);
+ assert.deepEqual(again.writes, []);
+});
+
+test('a web resource whose content cannot be compared is reused as before, and the skip line says it was not compared', async () => {
+ const s = scenario();
+ await s.build(spec([{ name: SCRIPT, type: 'js', content: OLD_CODE }]));
+ // The spec's file is not there to read (the build's own source check is a step this phase-only run does not take).
+ const unread = await s.build(spec([{ name: SCRIPT, type: 'js', contentPath: 'missing.js' }]));
+ assert.equal(unread.skips.length, 1);
+ assert.match(unread.skips[0], new RegExp(`^web resource ${SCRIPT.replace(/[/.]/g, '\\$&')} \\(exists — reuse; its content was not compared: the spec's content could not be read \\(.*missing\\.js.*\\)\\)$`));
+ assert.deepEqual(unread.warnings, []);
+ assert.deepEqual(unread.writes, []);
+});
+
+// --- verify ---------------------------------------------------------------------------------------------------------------------------------------------
+
+// A verify reader that answers one thing: the web resources, by name, as the published layer holds them — and an empty navigation, which every
+// pass reads.
+const reader = (rows) => ({
+ webResource: async (name) => (Object.hasOwn(rows, name) ? rows[name] : null),
+ sitemapXml: async () => '', findTable: async () => null, findColumns: async () => [], queryRecords: async () => [],
+});
+const webResourceChecks = (r) => r.checks.filter((c) => c.kind === 'web-resource');
+
+test('verify reports a declared web resource whose deployed content differs from the spec\'s, and one that is missing', async () => {
+ const r = await verifySpec({ webResources: [{ name: SCRIPT, type: 'js', content: NEW_CODE }, { name: ICON, type: 'svg', content: SVG }] },
+ reader({ [SCRIPT]: { id: 'wr-1', content: base64(OLD_CODE) } }));
+ assert.equal(r.ok, false);
+ assert.deepEqual(webResourceChecks(r), [
+ { kind: 'web-resource', name: SCRIPT, present: false, detail: "its deployed content differs from the spec's — a rebuild does not write the content of a web resource that exists; delete it (or tear the app down) and build again to deploy it" },
+ { kind: 'web-resource', name: ICON, present: false, detail: 'not found' },
+ ]);
+});
+
+test('verify passes a web resource that holds the spec\'s content, and checks only that an external one exists', async () => {
+ const r = await verifySpec({ webResources: [{ name: SCRIPT, type: 'js', content: OLD_CODE }, { name: ICON, type: 'svg', content: SVG, external: true }] },
+ reader({ [SCRIPT]: { id: 'wr-1', content: base64(OLD_CODE) }, [ICON]: { id: 'wr-2', content: base64('<svg/>') } }));
+ assert.equal(r.ok, true, JSON.stringify(r.missing));
+ assert.deepEqual(webResourceChecks(r).map((c) => [c.name, c.present]), [[SCRIPT, true], [ICON, true]]);
+});
+
+test('verify resolves contentPath from the app folder it is given, and leaves a content it cannot read unverified, not failed', async () => {
+ const dir = tempDir();
+ fs.writeFileSync(path.join(dir, 'form.js'), OLD_CODE);
+ const declared = { webResources: [{ name: SCRIPT, type: 'js', contentPath: 'form.js' }] };
+ const same = await verifySpec(declared, reader({ [SCRIPT]: { id: 'wr-1', content: base64(OLD_CODE) } }), { appDir: dir });
+ assert.equal(same.ok, true, JSON.stringify(same.missing));
+ const unread = await verifySpec({ webResources: [{ name: SCRIPT, type: 'js', contentPath: 'missing.js' }] }, reader({ [SCRIPT]: { id: 'wr-1', content: base64(OLD_CODE) } }), { appDir: dir });
+ assert.deepEqual(webResourceChecks(unread), []);
+ assert.equal(unread.unverified.length, 1);
+ assert.match(unread.unverified[0], new RegExp(`^web-resource:${SCRIPT.replace(/[/.]/g, '\\$&')} \\(its content was not compared: the spec's content could not be read`));
+});
+
+test('verify says nothing of web resources when its reader cannot read them, or when the build did not run their phase', async () => {
+ const declared = { webResources: [{ name: SCRIPT, type: 'js', content: NEW_CODE }] };
+ const blind = await verifySpec(declared, { sitemapXml: async () => '', findTable: async () => null, findColumns: async () => [], queryRecords: async () => [] });
+ assert.deepEqual(webResourceChecks(blind), []);
+ const skipped = await verifySpec(declared, reader({}), { phases: ['data-model'] });
+ assert.deepEqual(webResourceChecks(skipped), []);
+ assert.deepEqual(skipped.phaseSkipped, [`web-resource:${SCRIPT}`]);
+ assert.equal(skipped.ok, true);
+});
+
+test('the verify reader reads a web resource by name, with its content, as the published layer holds it', async () => {
+ const asked = [];
+ const sdk = { queryRecords: async (set, o) => { asked.push([set, o]); return o.filter === `name eq '${SCRIPT}'` ? [{ webresourceid: 'wr-1', content: base64(OLD_CODE) }] : []; } };
+ const read = readerFor(sdk, 'contoso_publishreview', {});
+ assert.deepEqual(await read.webResource(SCRIPT), { id: 'wr-1', content: base64(OLD_CODE) });
+ assert.equal(await read.webResource('contoso_/other.js'), null);
+ assert.deepEqual(asked[0], ['webresource', { select: ['webresourceid', 'content'], filter: `name eq '${SCRIPT}'`, top: 1 }]);
+});
diff --git a/plugins/model-apps/scripts/tests/workspace-binding.test.js b/plugins/model-apps/scripts/tests/workspace-binding.test.js
index efb28c7e0..d2690682b 100644
--- a/plugins/model-apps/scripts/tests/workspace-binding.test.js
+++ b/plugins/model-apps/scripts/tests/workspace-binding.test.js
@@ -27,6 +27,9 @@
// need to be.
// The bundle's own decision (which URLs name one environment) is deliberately NOT re-implemented in the plugin:
// a stub that mimicked it would stay green if the SDK changed it.
+// This file checks where lib/temp-workspace.js makes a workspace, so it works in a temp folder of its own (helpers/own-temp-folder.js): in the
+// suite's shared one, other test processes make and remove the plugin's workspace folder. Required first, so every path below is inside it.
+require('./helpers/own-temp-folder.js');
const test = require('node:test');
const assert = require('node:assert');
const crypto = require('node:crypto');
diff --git a/plugins/model-apps/scripts/verify-model-app.js b/plugins/model-apps/scripts/verify-model-app.js
index 0c01bb9c4..baea27718 100644
--- a/plugins/model-apps/scripts/verify-model-app.js
+++ b/plugins/model-apps/scripts/verify-model-app.js
@@ -268,6 +268,15 @@ function readerFor(sdk, appUnique, opts) {
const items = await sdk.resolveArtifact('command', { entity: String(entity).toLowerCase() });
return !!(items && items[0] && items[0].id);
},
+ // webResource(name): the web resource of that name as a plain read answers it (its published layer), with its content — the same read
+ // the build makes before it reuses one — or null when there is none:
+ // GET /webresourceset?$select=webresourceid,content&$filter=name eq 'contoso_/scripts/form.js'&$top=1
+ // { "value": [ { "webresourceid": "…", "content": "dmFyIEZvcm0gPSB7…" } ] }
+ webResource: async (name) => {
+ const rows = await sdk.queryRecords('webresource', { select: ['webresourceid', 'content'], filter: `name eq '${odataLit(name)}'`, top: 1 });
+ const row = rows && rows[0];
+ return row && row.webresourceid ? { id: row.webresourceid, content: row.content } : null;
+ },
// statusReasons(entity) / alternateKeys(entity): the table's status reasons, with their states, and its alternate keys, with their
// columns — one narrow read each, made only for a table that declares any (lib/status-reasons-keys.js). They never throw: a read that
// fails answers { state: 'error', why }, which verify reports on the checks it was for.
@@ -645,7 +654,9 @@ async function main() {
// `fieldOptionKeys: 'warn'` is the same arrangement for a key a form's `fieldOptions` entry does not take: the build refuses one, because it
// would drop it and never apply the option, but a release before that check accepted it and built the form without the option — and
// verification only reads that deployment. Every other finding about the entry stays an error.
- const v = validateAppSpec(spec, { profile: 'deploy', relationshipCollisions: 'warn', columnValues: 'warn', fieldOptionKeys: 'warn' });
+ // `primaryAttributeKeys: 'warn'` is the same again for a key a table's `primaryAttribute` does not take: an earlier release accepted and
+ // ignored it, and the table was built without it.
+ const v = validateAppSpec(spec, { profile: 'deploy', relationshipCollisions: 'warn', columnValues: 'warn', fieldOptionKeys: 'warn', primaryAttributeKeys: 'warn' });
// A warning is printed for a person and kept for the result JSON in one step, so the two cannot differ: a caller that reads only the JSON must not
// lose what stderr says. The spec's are found before it is judged, so a spec that is refused reports the warnings it also has.
const warnings = [];
@@ -686,7 +697,8 @@ async function main() {
// kept because it was changed in the designer since then is not a failure (AB#6726727). It is keyed by
// environment, so a folder built against another one yields none.
const baselineSpec = readBaseline(workspaceDir, { environment: dataverseOrigin(env), appUniqueName: appUniqueName(spec) }) || undefined;
- r = await verifySpec(spec, readerFor(session.sdk, appUniqueName(spec), { genpage, workspaceDir, isolatedReader: isolatedReaderFor(env, { httpClient }) }), { baselineSpec, languageCode });
+ // `appDir`: a web resource's `contentPath` is read relative to the spec's folder, as the build reads it, to compare its content.
+ r = await verifySpec(spec, readerFor(session.sdk, appUniqueName(spec), { genpage, workspaceDir, isolatedReader: isolatedReaderFor(env, { httpClient }) }), { baselineSpec, languageCode, appDir: path.dirname(specPath) });
} finally {
// Before the result is printed: emitResult ends the process, so a cleanup placed after it never ran.
// The backend first, and awaited: a page read the pass gave up on can still be running, and its workspace is closed and removed once the storage
diff --git a/plugins/model-apps/skills/app-builder/SKILL.md b/plugins/model-apps/skills/app-builder/SKILL.md
index f936f41fb..d3a044d74 100644
--- a/plugins/model-apps/skills/app-builder/SKILL.md
+++ b/plugins/model-apps/skills/app-builder/SKILL.md
@@ -62,7 +62,8 @@ prod-ready** app; don't under-build (a bare table list) or over-build (surfaces
`100000003`, because they are assigned per publisher. Resolve by label via `getOptions()`
(see `references/app-spec-schema-advanced.md` → webResources). Note also that command and web-resource
**edits do not redeploy on rebuild** — the phases reuse what exists, so changing a button or a
- script means deleting it first. This does not apply to recovery of the build's own
+ script means deleting it first (the build warns, and verify fails, when a web resource's deployed
+ content differs from the spec's). This does not apply to recovery of the build's own
`WEB_RESOURCE_UNVERIFIED` row: keep that row and the same build workspace, then follow its halt.
- **Form logic without code** — `businessRules[]`: show/hide, lock/unlock, set-required and
set-value, driven by a condition on the record. **Reach for a business rule before form JS** when
@@ -581,7 +582,11 @@ columns bind, which the platform refuses to delete while the table exists, and i
business rule on it could not be deleted (the rule's activated copy can never be deleted once its table is gone), so
a re-run deletes the rule first, then the table and what was kept with it. It never deletes the solution's
**publisher** (the build reuses one by prefix, and other solutions may share it); its closing summary says so in one line,
-so tell the user the publisher stays and can be removed in Maker once nothing uses it. **Dry-run by default**; add `--apply
+so tell the user the publisher stays and can be removed in Maker once nothing uses it. **Known limit — generative pages on
+forms:** teardown deletes the app's generative pages even when a form still embeds one (the `MscrmControls.UxAgentControl`
+control); the platform records no dependency for that and teardown reads no form, so the form is left pointing at a deleted
+page. When the app has pages, tell the user before `--apply` and have them take each page off any form that shows it (or delete
+that form) first. **Dry-run by default**; add `--apply
--allow-destructive` to actually delete (`--clear-workspace` also prunes `.maker-workspace/`).
**`--allow-destructive` is required for `teardown --apply`** — without it teardown refuses and
touches nothing.
@@ -705,6 +710,9 @@ not everything:**
- **Does NOT round-trip:** `forms[]`, `views[]`, `charts[]`, `commands[]` — they come back empty.
All four **survive on the live app** (a rebuild preserves them by discovery), so a plain edit is
safe; they just aren't editable through the downloaded spec. Change them in Maker or a fresh spec.
+ The download names every one it leaves out — the command-bar buttons of the app's tables included —
+ in its `NOTE` and its result's `notRoundTripped`, and lists them under `descriptionInventory` in the
+ spec: tell the user before they rebuild the spec in another environment, which would not have them.
- **Roles are not in the spec, and a rebuild leaves them as they are.** A download carries no
`personas[]`: the roles associated with the app stay as the environment has them. Keep `personas[]`
out when you extend an app whose roles somebody else owns — a persona's role is converged to exactly
@@ -733,7 +741,12 @@ connector — give the binding the logical name of a reference that is for the r
binding's `connectorId` to the one that environment has, and never pick a reference for the user — and its
warnings say by name each reference or Custom API that is not there yet, a reference that has no connection, an
operation the custom connector there does not define, and what it could NOT check (a row that did not say its
-connector or connection, or operations no custom connector definition could prove): relay them. Do not write bindings into a
+connector or connection, or operations no custom connector definition could prove): relay them. A binding named
+exactly `WhoAmI` or `RetrieveVersion` is a reviewed built-in Dataverse operation, not a Custom API: the pull lists it
+under `neededInTarget.dataverseOperations` (nothing to deploy), and a rebuild reads nothing for it and says
+`These are reviewed built-in operation names; their availability in this environment or player and the signed-in
+user's permissions were not checked.` — relay that too, never as "missing" and never as "compatible"
+(`references/dataverse-operations.md`). Do not write bindings into a
spec yourself — they come from a page a pull read — and when you reset a page to `intent` to regenerate it, delete
its bindings from the spec: the generator writes no connector code.
diff --git a/plugins/model-apps/skills/genpage/SKILL.md b/plugins/model-apps/skills/genpage/SKILL.md
index d724852df..40803a6a5 100644
--- a/plugins/model-apps/skills/genpage/SKILL.md
+++ b/plugins/model-apps/skills/genpage/SKILL.md
@@ -32,6 +32,9 @@ This skill orchestrates specialist agents across the create and edit flows:
(discovery is mutating), then the planner is re-invoked with its contract.
**`genpage-customapi-builder`** — the same top-level dispatch for server-side
Custom API (Action/Function) needs; writes `custom-api-bindings.md` + `actions.json`.
+ It also owns the default-off offer of the two built-in Dataverse Functions
+ (`WhoAmI`, `RetrieveVersion`; `dataverse_operation_discovery_required`) and writes
+ `dataverse-operations.md` for a selection made this run.
3. **`genpage-entity-builder`** — creates Dataverse entities (tables, columns,
relationships, choices, sample data) via the plugin's Node.js Web API scripts
4. **`genpage-page-builder`** — generates one complete `.tsx` file per page; multiple
@@ -43,7 +46,8 @@ This skill orchestrates specialist agents across the create and edit flows:
replaces, discovers, removes, or clears connector bindings; preserves unchanged bindings
when the edit does not touch them.
**`genpage-customapi-builder`** — the same top-level dispatch when an edit adds, replaces,
- discovers, removes, or clears Custom API bindings.
+ discovers, removes, or clears Custom API bindings, or adds, replaces or removes a built-in
+ Dataverse operation binding.
6. **`genpage-edit-planner`** — reads the downloaded page artifacts, gathers change
requirements, presents an edit plan, writes `genpage-edit-plan.md`
@@ -212,8 +216,8 @@ the log still shows what decided the run:
| --- | --- | --- |
| Recording the resolved mode | Nothing to record | Write the mode itself as `Unattended default: interaction mode → unattended (<reason>)` before the first gate. Record it with this marker, not as free prose such as `Interaction mode: unattended` — the evaluator keys on the marker, and prose forms are indistinguishable from an attended log that merely mentions the word (`Mode: unattended = false`, `not unattended`). |
| Create new / edit existing (step 2) | `AskUserQuestion` | Whatever `$ARGUMENTS` states. With nothing stated, **create new** — the only additive choice. |
-| An agent returns `needs_input` (step 4) | Ask, then re-invoke | Re-invoke with the option the agent marked `"default": true`. If it marked none, **halt**. |
-| Plan approval (step 5) | `EnterPlanMode` / `ExitPlanMode` | Treat the plan as approved and continue to step 6, which still writes `genpage-plan.md` through the planner. The plan is recorded, just not presented. Log this gate as `Unattended default: plan approval → approved (<reason>)` — the evaluator looks for the plan/approval wording and `approved` on that one line, so a paraphrase such as `→ auto-approve` is read as a missing approval record. |
+| An agent returns `needs_input` (step 4) | Ask, then re-invoke | Re-invoke with the option the agent marked `"default": true`. If it marked none, **halt**. For the planner's data-semantics questions, record `Unattended default: <assumption id> / <question id> → <answer> (<reason>)` — the answer word for word, a reason that never contains the word "approved" — and pass the same line back to the planner for the assumption's `Default record`. |
+| Plan approval (step 5) | `EnterPlanMode` / `ExitPlanMode` | Only once every data-semantics question is answered, treat the plan as approved and continue to step 6, which still writes `genpage-plan.md` through the planner. The plan is recorded, just not presented. Log this gate as its own line, `Unattended default: plan approval → approved (<reason>)` — the evaluator reads the words right after the marker, `plan approval`, then the arrow and the whole word `approved`, so a paraphrase such as `→ auto-approve` is read as a missing approval record, and a semantic default that mentions approval never stands in for it. |
| Browser verification (Phase 7) | Offer it | Skip it. |
**Suppressing a prompt never authorizes destructive work.** Editing an existing
@@ -244,18 +248,25 @@ missing and stop, so the run can be re-driven with the decision supplied.
`{ "action": "custom_api_discovery_required" }`, invoke `genpage-customapi-builder`
the same way (same mode, resolved environment URL, plus the returned `pageTables`),
then re-run the planner with the builder's `## Custom API Bindings` contract and
- `actions.json` status (see 1b).
+ `actions.json` status (see 1b). A `dataverse_operation_discovery_required` signal —
+ alone or beside `custom_api_discovery_required` — dispatches that same builder **once**
+ for both needs (see 1c).
If `genpage-connector-builder` or `genpage-customapi-builder` instead reports
that its declared file or process-execution tools are unavailable, do **not**
retry the same worker. Record the worker failure, read that worker's agent
file, and run the discovery-builder workflow inline in this orchestrator
using the same resolved mode, environment, intent, and safety gates. This
inline fallback is recovery from task-runtime tool exposure only; it does not
- bypass connector/custom-API feature gates or user decisions.
+ bypass the `dataverse-operations` feature gate, the Custom API discovery rules or user decisions.
4. If any agent returns `{ "action": "needs_input", … }`, ask its questions here
with `AskUserQuestion`, record them in `workflow-log.md`, and re-invoke that
- agent with the answers. Agents never prompt; they request.
-5. Present the plan with `EnterPlanMode` and get approval via `ExitPlanMode`.
+ agent with the answers. Agents never prompt; they request. The planner asks this way
+ which relationship or filter a request means when metadata leaves several candidates
+ (its Step 4, "Resolve Data Semantics"): pass each answer back with its question id and
+ everything the planner returned, including `<working-dir>/lookup-metadata.json`. Never
+ answer such a question for the maker, and never approve a plan while one is open.
+5. Present the plan with `EnterPlanMode` — its `### Assumptions` first, as the planner returns
+ it, so the maker sees what was assumed before the page list — and get approval via `ExitPlanMode`.
On a revision request, re-invoke the planner with the requested revisions and
present the revised plan again.
6. **On approval, re-invoke `genpage-planner` with the approval outcome _plus
@@ -306,13 +317,16 @@ missing and stop, so the run can be re-driven with the decision supplied.
If it exists, verify its provenance before Phase 2:
```powershell
- node "${PLUGIN_ROOT}/scripts/genpage-plan-provenance.js" verify --plan '<working-dir>/genpage-plan.md' --approved '@<working-dir>/.approved-genpage-plan.md'
+ node "${PLUGIN_ROOT}/scripts/genpage-plan-provenance.js" verify --plan '<working-dir>/genpage-plan.md' --approved '@<working-dir>/.approved-genpage-plan.md' --require-assumptions
```
Continue only when the JSON result has `"ok":true`, and record its `writtenHash`
- in `workflow-log.md`. If the written plan targets other pages than the approved
+ (and `semanticsHash`) in `workflow-log.md`. If the written plan targets other pages than the approved
plan named — an extra, missing or renamed page file — halt: downstream phases
- would build pages the user did not approve.
+ would build pages the user did not approve. Halt too when its assumptions, data-semantics
+ decisions or lookup records differ from the approved ones, or are missing from either document
+ (`--require-assumptions`: a newly authored plan carries them all): the maker approved those
+ decisions, not just the file names. The result's `semanticProblems` lists each difference.
#### 1a. Connector discovery is orchestrator-owned and never speculative
@@ -366,9 +380,38 @@ detected.
verify `<working-dir>/actions.json` is a bare JSON array, then re-run the planner with the
refreshed contract.
-The builder remains the single owner of the `custom-api` feature gate: it probes first, writes
-`No custom API bindings.` + `[]` when the gate is off or the page needs no Custom API, and
-performs discovery only when one is required.
+The builder remains the single owner of Custom API discovery, which has no feature flag: it writes
+`No custom API bindings.` and no Custom API row when the page needs no Custom API (`actions.json`
+is then `[]`, unless built-in operation rows were selected — 1c), and performs discovery only when
+one is required.
+
+#### 1c. Built-in Dataverse operations are orchestrator-owned too
+
+`WhoAmI` and `RetrieveVersion` are two reviewed built-in Dataverse Functions a page can call from
+a button — not Custom APIs (`${PLUGIN_ROOT}/references/dataverse-operations.md`). Their offer is
+behind the default-OFF `dataverse-operations` flag, owned by `genpage-customapi-builder`, which
+also stays the one writer of `actions.json` (Custom API rows first, then the built-in rows).
+
+- A planner returns `{ "action": "dataverse_operation_discovery_required", "intent": "...",
+ "resolvedAction": "create" | "edit", "envUrl": "..." }` when the maker affirmatively asks for
+ one of them or for the identity or server version a page should show. A mention, a question,
+ "do not add WhoAmI", or the `whoAmI` of the auth preflight is not that signal. Dispatch the
+ builder once, with both needs when a Custom API is needed too.
+- Selection is the maker's: an affirmative request or an explicit answer to the builder's
+ `needs_input` picker. Ask that question here with `AskUserQuestion`; an unattended run never
+ treats "no answer" as consent, and the selected names stay in this run's context.
+- When the builder reports `dataverse-operations.md` written **this run**, forward its body to
+ the planner as the `## Dataverse Operations` contract, delimited like the other contracts. A
+ file left by an earlier run is not forwarded. With none, the plan has no such section.
+- When it reports `dataverse-operations.md: none — not added this run` — its
+ `dataverse-operations` gate is off, or the maker declined the offer or selected neither —
+ there is no built-in contract: tell the maker that no built-in operation was added, and forward
+ the outcome `none — not added this run` (never a contract) to the planner in this and every
+ later round. The planner then completes the plan without that call instead of signalling
+ again, so the builder is not dispatched a second time for the same request — the edit flow's
+ own rule.
+- In an edit, Edit Phase 4 of edit-flow.md handles this signal, forwards the contract through
+ every edit-planner round, and re-probes the gate before an add or replace is applied.
#### Invocation prompt
@@ -385,6 +428,14 @@ Pass a prompt that includes:
or the literal `No custom API bindings.` when discovery was not needed
- The Custom API upload file status: `<working-dir>/actions.json` exists and is
a bare JSON array, or `no actions.json; omit --actions`
+- The answers to every earlier `needs_input` question, each with its question id (and, unattended,
+ its `Unattended default:` line), and the path of `<working-dir>/lookup-metadata.json` when the
+ planner saved one
+- The built-in operation contract, only when this run's builder wrote it: the full body of
+ `<working-dir>/dataverse-operations.md` between `----- BEGIN/END DATAVERSE OPERATIONS -----`
+ delimiters (copied verbatim into an optional `## Dataverse Operations` section right after
+ `## Custom API Bindings`); the outcome `none — not added this run` when this run's builder was
+ dispatched for one and added none (1c); otherwise nothing, and the plan has no such section
Example:
@@ -438,6 +489,21 @@ Example:
> "resolvedAction": "create" | "edit", "envUrl": "<the environment you resolved>",
> "pageTables": "<page tables or none>" }` instead of trying to discover it yourself.
>
+> [Only when this run's builder wrote `dataverse-operations.md`:] The built-in Dataverse
+> operation contract is between the `----- BEGIN/END DATAVERSE OPERATIONS -----` lines below
+> (prompt delimiters, not content). Copy what is between them verbatim into an optional
+> `## Dataverse Operations` section right after `## Custom API Bindings`; with no such block,
+> write no such section. If your clarification reveals an affirmative request for `WhoAmI` or
+> `RetrieveVersion` (or for the identity or server version a page shows) that this contract does
+> not cover, return `{ "action": "dataverse_operation_discovery_required", "intent": "<the
+> maker's words>", "resolvedAction": "create" | "edit", "envUrl": "<the environment you
+> resolved>" }`.
+>
+> [Only when this run's builder added none:] Built-in Dataverse operations: `none — not added
+> this run`. The builder was dispatched for this request and added none (its gate is off, or the
+> maker selected neither): plan the page without that call, write no `## Dataverse Operations`
+> section, and do not return `dataverse_operation_discovery_required` again.
+>
> Follow the instructions in your agent file. Validate prereqs and confirm auth.
> The create/edit decision and the resolved environment are supplied to you by the
> orchestrator (it asks; you are headless) — use them rather than prompting. If you
@@ -535,6 +601,29 @@ this loop, exactly as Phase 1 step 4 does:
Repeat until it returns a completion rather than a request. Proceeding to Phase 3
on a `needs_input` return silently drops the decision the user was asked to make.
+#### 2c. Reconcile planned lookups (when the plan records any)
+
+A lookup on a table this run creates is recorded `planned` in its page's `#### Lookup metadata` — there was no
+metadata to read before Phase 2. Once the tables exist, and before any page is generated, prove each one:
+
+```powershell
+node "${PLUGIN_ROOT}/scripts/get-lookup-metadata.js" --env '<envUrl>' --tables '<every source table with a recorded lookup>'
+```
+
+Save its one-line JSON answer as `<working-dir>/lookup-metadata.json` (it replaces the planning-time copy). Any
+non-zero exit means the read failed: report it and stop — a failed read is never "no targets". Then run the
+`prepare` command of Phase 1 again and re-invoke `genpage-planner` with `Lookup reconciliation:`, the path of
+that file, the approved plan body and everything it returned before. It may only promote a `planned` lookup to
+`observed` and add its measured paths; a different target set, column or use is a revised plan the maker
+approves again (Phase 1 step 5). Verify the rewritten plan against the same approved body, with the evidence:
+
+```powershell
+node "${PLUGIN_ROOT}/scripts/genpage-plan-provenance.js" verify --plan '<working-dir>/genpage-plan.md' --approved '@<working-dir>/.approved-genpage-plan.md' --require-assumptions --lookup-metadata '<working-dir>/lookup-metadata.json'
+```
+
+Continue only on `"ok":true`; on `"ok":false` halt and show the maker the `semanticProblems` it lists. Do not
+edit the plan yourself: the planner is its one author.
+
### Phase 3: App Creation/Selection
Read `genpage-plan.md` for the app decision and the `Solution` line in
@@ -552,8 +641,8 @@ is deployed (see "A new app" there). Carry the app's name and the plan's `Soluti
- `--solution` is mandatory and takes the solution's **unique name**: `apps.js create` refuses
a call without it, or with a name no unmanaged solution has.
-**If existing app-id:** Use it directly. `apps.js create` is not called, so
-the `Solution` line is informational only for this phase.
+**If existing app-id:** Use it directly. `apps.js create` is not called; the plan's `Solution`
+is still the solution every page this run creates joins (Phase 6 passes it with `--solution`).
### Phase 4: Generate RuntimeTypes (Conditional)
@@ -622,29 +711,12 @@ fills env-specific `ConnectionId` values through solution deployment settings.
### Phase 4.6: Custom API Bindings (Conditional)
-**Re-probe the feature gate here — do not rely on the plan content alone.** A plan
-authored while the flag was ON must not deploy Custom API bindings after it is turned OFF:
-
-```powershell
-node "${PLUGIN_ROOT}/scripts/lib/feature-flags.js" custom-api
-```
-
-**If it prints `disabled`:** Custom API support is OFF. Do not create or pass `actions.json`,
-and never add `--actions` on upload. The plan's `## Custom API Bindings` section still decides
-whether the run may go on: only a body of exactly `No custom API bindings.` continues, with no
-Custom APIs. For an **actual binding table** (a `| Name | Kind | …` header with at least one data
-row), **halt before page generation**. That plan was made while the flag was on, and page
-generation takes the table as permission to emit `executeAction` / `executeFunction` calls —
-deploying them with no bindings leaves pages calling Custom APIs that are not bound. Tell the user
-to turn the flag back on, or re-run planning (the Custom API builder writes no bindings while the
-flag is off). A missing, empty, or malformed section halts too, exactly as in the `enabled`
-branch. (Backstop: `list-custom-apis.js` also fails closed with exit 3 if invoked while OFF.)
-
-**If it prints `enabled`:** read the plan's `## Custom API Bindings` section. The section is
-mandatory: continue with no actions only when its body is exactly `No custom API bindings.`.
-Treat it as bindings only when it contains an actual binding table (a `| Name | Kind | …`
-header with at least one data row). If the section is missing, empty, or malformed, **halt**
-before page generation; do not interpret a planner/schema failure as "no Custom APIs".
+Custom API support has no feature flag, so there is nothing to probe here. Read the plan's
+`## Custom API Bindings` section. The section is mandatory: continue with no Custom API rows only
+when its body is exactly `No custom API bindings.`. Treat it as bindings only when it contains an
+actual binding table (a `| Name | Kind | …` header with at least one data row). If the section is
+missing, empty, or malformed, **halt** before page generation; do not interpret a planner/schema
+failure as "no Custom APIs".
When there are real bindings, the `genpage-customapi-builder` agent already wrote
`<working-dir>/actions.json` during planning — verify it exists and matches the plan table. If
@@ -653,6 +725,47 @@ it is missing, derive it as a **bare JSON array** of
`isFunction:false`, Function `true`; `boundEntityLogicalName` only for an entity-bound, non-
`(Global)`, row) — see `${PLUGIN_ROOT}/references/custom-api.md`. Never the
`{ "actionBindings": [...] }` object wrapper (the deployed `config.json` shape the upload writes).
+Compare only the **Custom API rows** of `actions.json` with this table: a built-in operation row
+(`WhoAmI`, `RetrieveVersion`) belongs to Phase 4.6b, never fails this match, and is never
+uploaded by this branch alone.
+
+This phase governs the Custom API rows only. Whether `actions.json` is written and passed at all
+is decided once, after Phase 4.6b's gate, in Phase 4.6c — this phase never takes away a built-in
+operation row the plan selected.
+
+### Phase 4.6b: Built-in Dataverse Operations (Conditional)
+
+Only when the plan has a `## Dataverse Operations` section holding the built-in operation table
+— an add or replace of this run — re-probe its own gate:
+
+```powershell
+node "${PLUGIN_ROOT}/scripts/lib/feature-flags.js" dataverse-operations
+```
+
+**If it prints `disabled`:** halt before page generation. Write no replacement `actions.json`,
+pass no `--actions`, and never write `[]` in its place (`[]` is only an explicit clear-all): the
+page keeps the bindings it has. Tell the user to turn the flag back on or re-run planning. An
+absent section, or exactly `No Dataverse operations.`, needs no probe and adds nothing; a
+preserve-only edit never consults this gate.
+
+**If it prints `enabled`:** verify that `actions.json` holds every row of the table as the
+four-key projection the builder wrote (Custom API rows first, then the built-in rows in
+catalogue order). If the builder selected a built-in operation but the plan lost its table,
+halt and re-invoke the planner — do not generate.
+
+### Phase 4.6c: The actions file, decided once (both partitions)
+
+Decide once, after Phase 4.6 and Phase 4.6b, from the complete desired array: the Custom API
+rows of the plan's `## Custom API Bindings` table (none when its body is `No custom API
+bindings.`), then the built-in operation rows of its `## Dataverse Operations` table (none when
+that section is absent or `No Dataverse operations.`; Phase 4.6b has already halted the run if its
+gate was off).
+
+- **Not empty:** `actions.json` must hold exactly that array, as the builder wrote it (Custom API
+ rows first, then the built-in rows in catalogue order) — verify it, and halt rather than
+ generate if it does not. Then the create passes `--actions '<working-dir>/actions.json'`: a page
+ that binds only built-in operations is created with them bound.
+- **Empty:** the create passes no `--actions`.
### Phase 4.7: Page Telemetry (Conditional)
@@ -705,6 +818,17 @@ Before invoking any builders, verify:
spelling. On any problem, halt and re-plan instead of rewriting filenames here: a renamed
file is a page the user did not approve, and the provenance check compares page files.
Duplicate filenames cause silent last-writer-wins data loss under parallel execution.
+- Every relationship and every server-side or client-side filter used in `## Per-Page Specifications` traces to the user's stated text in `## User Requirements` or a named `## Assumptions` entry. The builder introduces no unrecorded business predicate, relationship or roll-up.
+ Validation proves structure, ID resolution, quote presence and agreement with approved structured decisions. It does not prove natural-language entailment, judge materiality, or discover arbitrary contradictory prose. Those remain planner/reviewer responsibilities, supplemented by scenario-specific code checks.
+- **When the plan records any lookup** (a `#### Lookup metadata` table, not `None.`), every one is
+ `observed` and matches the saved metadata read before a page is generated:
+
+ ```powershell
+ node "${PLUGIN_ROOT}/scripts/genpage-plan-provenance.js" verify --plan '<working-dir>/genpage-plan.md' --approved '@<working-dir>/.approved-genpage-plan.md' --require-assumptions --require-observed-lookups --lookup-metadata '<working-dir>/lookup-metadata.json'
+ ```
+
+ Continue only on `"ok":true`. A lookup still `planned` means Phase 2c did not run; a mismatch
+ means the metadata changed since approval — halt and re-plan, never edit the records here.
See `${PLUGIN_ROOT}/references/plan-schema.md` for the full contract.
@@ -720,14 +844,17 @@ subagent. Inline the page-builder workflow directly in the orchestrator:
also read `${PLUGIN_ROOT}/references/connectors.md`. Treat a
`No connector bindings.` sentinel or an empty/missing/malformed section as
having no connectors (same contract as Phase 4.5 and genpage-page-builder).
-3b. Only when the Phase 4.6 probe printed `enabled` **and** the plan's
- `## Custom API Bindings` section contains an **actual binding table** (a
- `| Name | Kind | …` header with at least one data row), also read
- `${PLUGIN_ROOT}/references/custom-api.md`. Treat a
+3b. Only when the plan's `## Custom API Bindings` section contains an **actual
+ binding table** (a `| Name | Kind | …` header with at least one data row),
+ also read `${PLUGIN_ROOT}/references/custom-api.md`. Treat a
`No custom API bindings.` sentinel as no Custom APIs. If the section is
missing, empty, or malformed, halt before inline generation (same contract as
Phase 4.6); do not downgrade a planner/schema failure to "no Custom APIs."
- (A `disabled` probe with a binding table has already halted in Phase 4.6.)
+3c. Only when the Phase 4.6b probe printed `enabled` **and** the plan has a
+ `## Dataverse Operations` table, also read
+ `${PLUGIN_ROOT}/references/dataverse-operations.md` and generate its button-only
+ pattern for exactly those rows. Without that section (or with exactly
+ `No Dataverse operations.`), emit no built-in operation call.
4. If the plan's Per-Page Specification has `Needs caching: true`, also read
`${PLUGIN_ROOT}/references/data-caching.md`
5. If the plan's `## Environment` indicates non-English languages, also read
@@ -893,8 +1020,8 @@ exited 0 is not deployed.
For each `.tsx` file produced, deploy to Power Apps.
-If Phase 4.5 wrote `<working-dir>/connectors.json`, or Phase 4.6 wrote `<working-dir>/actions.json`,
-pass the file to the upload (`--connectors` / `--actions`). `genpage-upload.js` writes the bindings into
+If Phase 4.5 wrote `<working-dir>/connectors.json`, pass it with `--connectors`; pass `actions.json` with `--actions` when Phase 4.6c decided so
+(its desired array is not empty — Custom API rows, built-in operation rows, or both). `genpage-upload.js` writes the bindings into
the page's `config.json` through the SDK, so there is no `--help` to pre-flight and no minimum `pac`
build for them; a file that is not a JSON array is refused before anything is written. Never silently
drop bindings.
@@ -911,9 +1038,19 @@ Connector deployment matrix:
`--connectors`, which clears the page's `connectorBindings`.
Custom API deployment follows the **identical matrix** as connectors, substituting
-`--actions '<working-dir>/actions.json'` for `--connectors`: pass it on create; on an edit only
+`--actions '<working-dir>/actions.json'` for `--connectors`: pass it on create when Phase 4.6c's
+array is not empty; on an edit only
when bindings changed/added/removed (full replace); omit it on an unrelated edit (the page keeps
-its deployed `actionBindings`); write `[]` and pass it to clear all `actionBindings`.
+its deployed `actionBindings`); write `[]` and pass it to clear all `actionBindings` — on a page
+that also binds a built-in operation (`WhoAmI`, `RetrieveVersion`) only after the maker's clear
+choice naming each one, asked before any binding is reconciled or the plan is approved (edit-flow.md,
+Edit Phase 3) and recorded again right before the upload, because removing every Custom API keeps them
+(edit-flow.md, Edit Phase 3).
+The same array carries the built-in operation rows (`WhoAmI`, `RetrieveVersion`), so the same
+rules hold for them: `--actions` is passed only when the whole desired set changed, a preserve
+omits it, a removal passes the array minus the named entries, and `[]` is passed only for a
+clear-all the maker chose — never as the result of a gate that turned off (Phase 4.6b, or in an edit the
+Edit Phase 4 re-probe, halts instead).
**Deploy through `scripts/genpage-upload.js`.** It writes the page through the SDK — the same page backend
`/app-builder` uses, signed in with the Azure CLI — and takes the maker's text **by file**
@@ -951,7 +1088,7 @@ in it is neither refused nor escaped.
```markdown
## Phase 6 — Deploy
-- Command: `node "${PLUGIN_ROOT}/scripts/genpage-upload.js" --env '<org-url>' --app-id '<id>' --code-file '<path>' --data-sources '<entities>' --prompt-file '<working-dir>/prompt.txt' --model '<model-id>' --name-file '<working-dir>/page-name.txt' --agent-message-file '<working-dir>/agent-message.txt' --add-to-sitemap`
+- Command: `node "${PLUGIN_ROOT}/scripts/genpage-upload.js" --env '<org-url>' --app-id '<id>' --code-file '<path>' --data-sources '<entities>' --prompt-file '<working-dir>/prompt.txt' --model '<model-id>' --name-file '<working-dir>/page-name.txt' --agent-message-file '<working-dir>/agent-message.txt' --solution '<Solution unique name>' --add-to-sitemap`
- Prompt scope: full page description from plan's `## User Requirements` (create) — or the delta only (update)
- Result: page-id = <returned-id>, status = success
```
@@ -997,11 +1134,27 @@ node "${PLUGIN_ROOT}/scripts/genpage-upload.js" `
--prompt-file '<working-dir>/prompt.txt' `
--model '<current-model-id>' `
--agent-message-file '<working-dir>/agent-message.txt' `
+ --solution '<Solution unique name>' `
--add-to-sitemap
```
Omit the `--connectors` line when Phase 4.5 did not write `connectors.json`, and the
-`--actions` line when Phase 4.6 did not write `actions.json`.
+`--actions` line when Phase 4.6c decided an empty array — a page that binds only built-in
+operations keeps it.
+
+**Every create passes `--solution` with the plan's `Solution` value** (`## Environment`), so the page
+joins the solution the maker chose, as the tables and the app do. A page joins no solution on its own,
+and adding an app to a solution never brings the pages it shows. The upload checks the solution before
+it writes anything: a name that is not an unmanaged solution stops the upload with nothing made. It adds
+the page last, after the page is written, published and placed, and the result says `"solution"` and
+`"addedToSolution": true`. A system solution such as `Default` already holds every page, so nothing is
+added and the result says `"systemSolution": true`. **An add that fails** exits 1 with
+`"code": "solution-add-failed"` and the page's `pageId`. The page exists and works: do not create it
+again. Run the `add-page-to-solution.js` command that the error names
+(`node "${PLUGIN_ROOT}/scripts/add-page-to-solution.js" '<org-url>' '<Solution unique name>' --page-ids '<page-id>'`).
+Updates (a later edit of the page) do not pass `--solution`, because the page is in the solution
+already. A create that did not finish, run again with `--page-id` added (see below), keeps
+`--solution`: the run that finishes the page also adds it.
**A new app** (the plan says `create new`): there is no app to name yet. Create the app's **first page with no
`--app-id` and no `--add-to-sitemap`** — a page needs no app, and one created without it is added to none — and make
@@ -1053,8 +1206,9 @@ node "${PLUGIN_ROOT}/scripts/genpage-upload.js" `
For updates, include the `--connectors` line only when this upload intentionally
replaces or clears connector bindings; otherwise omit it to preserve the
-deployed page's current bindings. The same rule applies to `--actions` for Custom
-API bindings: include it only when this upload intentionally replaces or clears them.
+deployed page's current bindings. The same rule applies to `--actions` for the page's
+`actionBindings` — Custom API and built-in rows alike: include it only when this upload
+intentionally replaces, removes or clears them.
An update that gives no `--name-file`, `--model`, `--data-sources`, `--connectors` or `--actions` keeps the page's own
name, model, data sources and bindings: the SDK writes only what differs from the page it has just read, so an edit
@@ -1093,10 +1247,10 @@ Phase 3 created nothing, because the platform refuses an app whose navigation is
--publish
```
- It makes the app with one area `Main`, one group `Pages` and a sub-area for the page, titled with the page's name; the app and its sitemap join the solution (a system solution such as `Default` already holds every component, so the result says `systemSolution: true` and an empty `inSolution` — a create into `Default` needs no add and did not fail). **`--publish` is mandatory:** without it the new app stays in draft and the genux runtime URL errors with "app not published". It prints `{ "ok": true, "appId", "uniqueName", "published", "unpublishedChanges", "solution", "navigation", "dataSources", "pinnedViews", … }` — store `appId` for the rest of the run. The create also pins the default public view of each table the page reads into the app's components, so that the maker's "/" picker lists the page's tables (`dataSources` are the tables, `pinnedViews` the views); a `warnings` entry says when a table has no default public view to pin, or when the environment could not take the app's new header and navigation setting, and the app was made all the same.
-3. **The remaining pages.** Upload each with `--app-id '<appId>'` and `--add-to-sitemap` (the create above): each becomes a sub-area of the new app, and the default views of the tables it reads join the app's components with it.
+ It makes the app with one area `Main`, one group `Pages` and a sub-area for the page, titled with the page's name; the app, its sitemap and its page join the solution (`inSolution` lists `app`, `sitemap` and `pages` as each joins; a system solution such as `Default` already holds every component, so the result says `systemSolution: true` and an empty `inSolution` — a create into `Default` needs no add and did not fail). **`--publish` is mandatory:** without it the new app stays in draft and the genux runtime URL errors with "app not published". It prints `{ "ok": true, "appId", "uniqueName", "published", "unpublishedChanges", "solution", "navigation", "dataSources", "pinnedViews", … }` — store `appId` for the rest of the run. The create also pins the default public view of each table the page reads into the app's components, so that the maker's "/" picker lists the page's tables (`dataSources` are the tables, `pinnedViews` the views); a `warnings` entry says when a table has no default public view to pin, or when the environment could not take the app's new header and navigation setting, and the app was made all the same.
+3. **The remaining pages.** Upload each with `--app-id '<appId>'`, `--add-to-sitemap` and `--solution` (the create above): each becomes a sub-area of the new app and joins the solution, and the default views of the tables it reads join the app's components with it.
-**A create of the app that failed** exits 1 and prints `{ "ok": false, "code", "error", "written", … }`; `code` and `error` are the SDK's own. `"written": false` means nothing was made: fix what the message names and run it again. `"written": true` means the app or its sitemap exists (`appId`, `sitemapId`, `left`, `published` and `unpublishedChanges` say which and in what state): its unique name is taken, so run it again with `--unique-name '<name>'`, or remove the leftovers first — the error says how. `"written": null` means the platform could not be read back, so the outcome is unknown: look in the environment for what `lookFor` names (the unique name, the app id and the sitemap id the create used) before running it again. `stage` says how far it got, and `inSolution` which of the app and its sitemap joined the solution.
+**A create of the app that failed** exits 1 and prints `{ "ok": false, "code", "error", "written", … }`; `code` and `error` are the SDK's own. `"written": false` means nothing was made: fix what the message names and run it again. `"written": true` means the app or its sitemap exists (`appId`, `sitemapId`, `left`, `published` and `unpublishedChanges` say which and in what state): its unique name is taken, so run it again with `--unique-name '<name>'`, or remove the leftovers first — the error says how. `"written": null` means the platform could not be read back, so the outcome is unknown: look in the environment for what `lookFor` names (the unique name, the app id and the sitemap id the create used) before running it again. `stage` says how far it got, and `inSolution` which of the app, its sitemap and its pages joined the solution (a create that stopped at the `solution` stage made the app: add what is missing with `add-page-to-solution.js '<org-url>' '<Solution unique name>' '<appId>' --page-ids '<page-id>'` — the app's add brings its sitemap, and a component the solution already holds is accepted).
### Phase 6.5: Navigation Fix-Up (Multi-Page Only)
@@ -1149,7 +1303,9 @@ The creates in Phase 6 wrote a base marker beside each uploaded file, using the
Runs only when the plan's `## Solution Packaging` has `Package into solution: true`.
Adds the deployed app, the GenPage(s), and any connection references to the
-target solution so they travel cross-environment.
+target solution so they travel cross-environment. (The pages already joined the plan's
+`## Environment` `Solution` in Phase 6; this packages them, with the app and the connection
+references, into the solution `## Solution Packaging` names, which may be another one.)
1. Ensure the solution exists — create it only if it doesn't already exist:
`node "${PLUGIN_ROOT}/scripts/provision-solution.js" '<envUrl>' '<solutionUniqueName>' '<Friendly Name>' [--publisher '<uniqueName>']`
@@ -1219,6 +1375,8 @@ encoding is not recognised.
Custom API bindings need **no** extra ALM step: `config.json`'s `actionBindings` travels
automatically in the `uxagentprojectfile` rows already pulled with the GenPage. The
referenced Custom APIs are a separate deployment prerequisite (bound by `name`), not added here.
+A built-in operation binding (`WhoAmI`, `RetrieveVersion`) needs nothing at all: it names an
+operation the platform defines, so there is no component to add or deploy.
### Phase 7: Verify in Browser (Optional)
@@ -1288,4 +1446,7 @@ For the edit flow (triggered when the `genpage-planner` returns
The edit flow has its own 8 phases (Edit Phase 1-8): discover and select target
app + page via `apps.js list` + `genpage.js list`, download (`genpage.js download`), generate
RuntimeTypes (`genpage.js types`) if needed, invoke `genpage-edit-planner`, apply the edit inline,
-deploy, verify, summarize.
+deploy, verify, summarize. Built-in operations (`WhoAmI`, `RetrieveVersion`) are classified in Edit
+Phase 3; Edit Phase 4 handles `dataverse_operation_discovery_required`, forwards this run's
+built-in operation contract through every planner round, and re-probes `dataverse-operations`
+before an add or replace is applied — the create flow's Phase 4.6b is not visited.
diff --git a/plugins/model-apps/skills/genpage/edit-flow.md b/plugins/model-apps/skills/genpage/edit-flow.md
index 44ccaf506..82f77d6b2 100644
--- a/plugins/model-apps/skills/genpage/edit-flow.md
+++ b/plugins/model-apps/skills/genpage/edit-flow.md
@@ -177,6 +177,35 @@ empty array, the page is mock-data only — skip this phase.
Also read `config.json.connectorBindings` and `config.json.actionBindings`.
+**The clear choice — asked first.** A request to clear every action binding of a page whose
+`actionBindings` holds a built-in operation row (`WhoAmI`, `RetrieveVersion`) deletes those
+operations too, so the maker chooses before anything else in this edit: before any binding is
+reconciled (below), before the edit planner runs and the plan is approved (Edit Phase 4), and
+before Edit Phase 5 touches the source. Ask with `AskUserQuestion` with exactly two options —
+`Clear every action binding, removing <names>` and `Keep <names>` — where `<names>` are the
+built-in operations the page holds, in catalogue order (`WhoAmI`, `RetrieveVersion`, or `WhoAmI and
+RetrieveVersion`), and record the answer as its own line in `workflow-log.md`:
+
+```text
+Clear choice: Clear every action binding of page <page-id>, removing <names>
+```
+
+or `Clear choice: Keep <names>`. Forward that line to the edit planner (Edit Phase 4).
+
+- **Clear:** reconcile the clear (**Clear every action binding**, below). Edit Phase 6 records the
+ choice again right before each upload it authorizes.
+- **Keep:** there is no clear. Neither the built-in calls — their handlers, buttons and UI — nor
+ their bindings are removed; what is left of the request is at most a removal of the Custom APIs
+ (**Remove every Custom API**, below).
+- Any other answer — a yes to adding or keeping an operation, an answer with conditions — is
+ `Keep`, recorded as `Clear choice: Keep <names>`.
+- **Unattended:** do not clear and ask nothing; stop before any binding or source changes and
+ report that a clear would remove `<names>` and needs the maker's choice. Silence is never a clear.
+
+On a page that holds no built-in operation row there is nothing to choose: a clear is what it
+always was. A clear that first surfaces in the edit planner's clarification is asked the same way,
+before the plan is approved (Edit Phase 4, `clear_choice_required`).
+
> **Connectors are owned by `genpage-connector-builder`, dispatched by this
> top-level edit orchestrator.** Unlike the create flow, the mode here is already
> `edit` and `envUrl` was captured in Edit Phase 1, so discovery can safely run
@@ -236,22 +265,32 @@ Also read `config.json.connectorBindings` and `config.json.actionBindings`.
> - **Add / replace / discover a Custom API call:** invoke `genpage-customapi-builder`
> via `Task` with **Mode: `edit`**, the working directory, `${PLUGIN_ROOT}`, the
> `envUrl` from Edit Phase 1, the page tables from `config.json.dataSources` (or
-> `none`), the existing `actionBindings`, and the edit intent. The builder owns the
-> `custom-api` feature gate: when it is off it preserves existing bindings and adds
-> none; otherwise it discovers and returns the updated set. It writes
+> `none`), the existing `actionBindings`, and the edit intent. The builder discovers
+> and returns the updated set. It writes
> `<working-dir>/actions.json` (bare array) and `<working-dir>/custom-api-bindings.md`.
> - **Remove one (or some) Custom API calls:** invoke the builder the same way with the
> remove intent and the existing bindings. It reconciles the existing set **minus**
> the named binding(s) and writes the full desired `actions.json` (the remaining
-> bindings, or `[]`) plus the matching `custom-api-bindings.md`. Pass `--actions` on
+> bindings — any built-in operation row included — or `[]` when none remain) plus the
+> matching `custom-api-bindings.md`. Pass `--actions` on
> upload — a full replace, so omitting it would leave the removed binding deployed.
> - **Preserve Custom APIs unchanged:** do not invoke the builder and do not create a
> replacement `actions.json`; omit `--actions` on upload so the page keeps its deployed
> bindings. Still pass the existing `actionBindings` summary into the edit planner so
> it can preserve Custom-API-backed code correctly.
-> - **Clear all Custom APIs:** write `[]` to `<working-dir>/actions.json` and a
-> `custom-api-bindings.md` body of exactly `No custom API bindings.`, then pass
-> `--actions` during upload so the page's `config.json.actionBindings` is cleared.
+> - **Remove every Custom API:** every built-in operation row (`WhoAmI`, `RetrieveVersion`)
+> stays, byte for byte. On a page that holds none, this empties the array: use the clear below.
+> On a page that binds one, invoke the builder the same way, with the remove intent naming every
+> Custom API row of the existing bindings. It drops those rows and nothing else, and writes the
+> remaining rows to `actions.json` and `No custom API bindings.` to `custom-api-bindings.md`;
+> pass `--actions` on upload. A request to clear or remove "all Custom APIs" is this removal,
+> never permission to delete a built-in operation.
+> - **Clear every action binding:** write `[]` to `<working-dir>/actions.json` and a
+> `custom-api-bindings.md` body of exactly `No custom API bindings.`, then pass `--actions`
+> during upload so the page's `config.json.actionBindings` is cleared — only when the page
+> holds no built-in operation row, or after the maker's clear choice naming each one it removes
+> (asked first, above). A clear is the maker's own request for an empty array: on a page with no
+> built-in row that is what removing every Custom API means, as before.
>
> **The builder is headless and may return `{ "action": "needs_input", … }`** (for
> example, when more than one discovered Custom API matches the intent). Drive the same
@@ -262,8 +301,33 @@ Also read `config.json.connectorBindings` and `config.json.actionBindings`.
> If `genpage-customapi-builder` reports unavailable declared file or
> process-execution tools, do **not** retry the same worker. Record the failure,
> read `agents/genpage-customapi-builder.md`, and run its read-only discovery and
-> binding-output workflow inline with the same feature gate, environment, page
+> binding-output workflow inline with the same `dataverse-operations` gate, environment, page
> tables, existing bindings, and intent.
+>
+> **Built-in Dataverse operations (`WhoAmI`, `RetrieveVersion`) share `actionBindings`**
+> (`${PLUGIN_ROOT}/references/dataverse-operations.md`). Classify the edit intent from this
+> page's `config.json.actionBindings` and the request, and keep
+> `{ intent, selected, beforeNames, provenance }` in this run's context (`provenance`:
+> `before-config` or `current-run-selection`):
+>
+> | Intent | `dataverse-operations` gate | `--actions` | Page source |
+> |---|---|---|---|
+> | preserve (an unrelated edit) | not consulted | omit | keep existing calls exactly as written |
+> | add / replace | must be ON (the builder probes it; Edit Phase 4 re-probes it before Edit Phase 5) | the full desired array | the button pattern, for the new names only |
+> | remove | not consulted | the array minus the named entries | delete those calls only |
+> | clear all | after the maker's clear choice, asked first (above), which names the built-ins removed | `[]` | delete every call |
+> | none, but the page binds one | n/a | do not pass | halt: no preserve evidence is no permission to delete the call |
+>
+> An add or replace dispatches `genpage-customapi-builder` (Mode: `edit`) with the existing
+> bindings and the maker's own words, once, together with any Custom API need. A mention,
+> question or "do not add" is not an add. Keep what that dispatch wrote this run — the body of
+> `<working-dir>/dataverse-operations.md` and `<working-dir>/actions.json` — for the edit planner
+> (Edit Phase 4); a `dataverse-operations.md` left by an earlier run is not this run's selection.
+> When the builder adds none (its gate is off, or the maker selected none), there is no built-in
+> contract: tell the maker, and pass the edit planner the intent `none — not added this run`, so
+> it plans the edit without the call. A preserve never consults the
+> flag, so an unrelated edit while it is OFF neither halts nor drops a built-in binding; a remove
+> of Custom APIs leaves the built-ins, and the reverse.
## Edit Phase 4: Plan the Edit
@@ -287,11 +351,22 @@ Invoke the `genpage-edit-planner` agent via the `Task` tool. Pass:
- The Custom API contract: the full body of `<working-dir>/custom-api-bindings.md`
when written by the builder/clear path, or a faithful summary of the existing
`config.json.actionBindings` when preserving unchanged Custom APIs
-- The Custom API upload file status: `<working-dir>/actions.json` when upload
- must replace/clear bindings, or `none — omit --actions` when preserving
-
-Tell the planner that connector and Custom API discovery are both orchestrator-owned:
-it must use the forwarded connector and Custom API contracts and must not invoke
+- The built-in operation intent from Edit Phase 3 (none, preserve, add, replace, remove or
+ clear) with its `{ intent, selected, beforeNames, provenance }` — `none — not added this run`
+ when this run's builder added none
+- The built-in operation contract: the full body of `<working-dir>/dataverse-operations.md`,
+ between `----- BEGIN/END DATAVERSE OPERATIONS -----` delimiters, only when this run's builder
+ wrote it — the planner adds or replaces a built-in operation only from that block; otherwise
+ nothing
+- The `actionBindings` upload file status (Custom API and built-in rows alike):
+ `<working-dir>/actions.json` when upload must replace, remove or clear bindings, or
+ `none — omit --actions` when preserving
+- The clear choice from Edit Phase 3, when one was asked: its `Clear choice:` line, verbatim. The
+ planner plans a clear of a page that holds a built-in operation only on `Clear choice: Clear
+ every action binding of page <page-id>, removing <names>`
+
+Tell the planner that connector and Custom API discovery and the built-in operation offer are
+orchestrator-owned: it must use the forwarded contracts and must not invoke
`genpage-connector-builder` or `genpage-customapi-builder`.
**If the planner returns `{ "action": "connector_discovery_required", … }`** instead
@@ -312,6 +387,28 @@ contract, and upload-file status (`<working-dir>/actions.json`). Skipping this s
`executeAction`/`executeFunction` code with no deployed binding, because upload would
still omit `--actions`.
+**If the planner returns `{ "action": "dataverse_operation_discovery_required", … }`**
+instead of an edit plan, the maker affirmatively asked to add or replace WhoAmI or
+RetrieveVersion — up front, or in the planner's clarification — and no built-in contract of
+this run was forwarded. Do **not** proceed to Phase 5. Dispatch `genpage-customapi-builder`
+once with **Mode: `edit`**, the returned `envUrl` and `intent`, and the existing
+`actionBindings` (with a Custom API need returned beside it, the same dispatch serves both).
+Drive its `needs_input` picker with `AskUserQuestion`, recorded in `workflow-log.md`; silence
+is never a selection. Then re-invoke the edit planner with this run's `dataverse-operations.md`
+body as the built-in operation contract and `<working-dir>/actions.json` as the upload file
+status. When the builder adds none (its gate is off, or the maker selected none), tell the maker
+that no built-in operation was added, and re-invoke the planner with the built-in operation
+intent `none — not added this run` and no contract, so it plans the edit without that call.
+Skipping this ships an `executeFunction` call with no deployed binding.
+
+**If the planner returns `{ "action": "clear_choice_required", … }`** instead of an edit plan, a
+clear of a page that holds a built-in operation surfaced in its clarification and no clear choice
+was forwarded. Do **not** proceed to Phase 5. Ask the clear choice exactly as in Edit Phase 3
+(unattended: stop there), record its `Clear choice:` line, reconcile the bindings for the answer —
+the clear on `Clear`, at most the removal of the Custom APIs on `Keep` — and re-invoke the edit
+planner with that line and the refreshed Custom API action, contract and upload file status. The
+plan is approved only after the maker chose, so the source is never edited before that choice.
+
The planner reads `page.tsx`, `config.json`, and `prompt.txt` as page data for context and
proposes the edit plan. It is a **headless** agent: it cannot ask the user anything
and cannot present plan mode. Drive the loop from here until it completes:
@@ -329,12 +426,14 @@ cannot be replaced by an inline fallback that invents its approved contract.
carry the previous answers forward so the planner never re-asks the same thing.
- **`{ "action": "connector_discovery_required", … }`** — handled above.
- **`{ "action": "custom_api_discovery_required", … }`** — handled above.
+- **`{ "action": "dataverse_operation_discovery_required", … }`** — handled above.
+- **`{ "action": "clear_choice_required", … }`** — handled above.
- **A proposed plan** — present it with `EnterPlanMode`, record `EnterPlanMode
called` and the response in `workflow-log.md`, and call `ExitPlanMode` to get
approval. A re-invocation is a fresh headless run with no memory of the last one,
so **carry the complete plan state forward every time** — the exact proposed-plan
- body it returned, every prior discovery (connector and Custom API contracts,
- entities), and every answer already gathered. On **approval**, re-invoke the
+ body it returned, every prior discovery (connector, Custom API and built-in operation
+ contracts, and their upload file status; entities), the clear choice, and every answer already gathered. On **approval**, re-invoke the
planner with that full state plus the approval outcome so it writes the approved
`<working-dir>/genpage-edit-plan.md` — not a plan it re-derives from scratch.
Before that approval writeback dispatch, quarantine any prior edit plan:
@@ -368,6 +467,22 @@ Only continue to Phase 5 once `<working-dir>/genpage-edit-plan.md` exists and th
has verified both the page and change list. That file is the contract Phase 5 reads; without that gate,
the flow would apply an edit nobody approved.
+**Built-in operation re-probe (add / replace only).** An edit runs these eight phases, never the
+create flow's Phase 4.6b, so it re-probes here. When the approved edit adds or replaces WhoAmI or
+RetrieveVersion — the edit intent, not a plan heading, selects this probe — run it right before
+Edit Phase 5, after the plan was approved, because the flag may have been turned off since the
+builder listed the operations:
+
+```powershell
+node "${PLUGIN_ROOT}/scripts/lib/feature-flags.js" dataverse-operations
+```
+
+**If it prints `disabled`:** halt before Edit Phase 5 edits the source. Write no replacement
+`actions.json`, pass no `--actions`, and never write `[]` in its place: the page keeps every binding
+it has. Tell the maker to turn the flag back on or run the edit again. **If it prints `enabled`:**
+continue. A preserve, a remove or a confirmed clear never runs this probe — an unrelated edit while
+the flag is off neither halts nor drops a built-in binding.
+
## Edit Phase 5: Apply the Edit
Read only the verified `## Requested Changes` section of `<working-dir>/genpage-edit-plan.md`
@@ -387,6 +502,9 @@ Also read:
- `<working-dir>/<page-id>/page.tsx` — the current source
- `${PLUGIN_ROOT}/references/connectors.md` — if `config.json.connectorBindings`
is non-empty or the edit adds connector-backed data
+- `${PLUGIN_ROOT}/references/dataverse-operations.md` — when the approved edit adds or replaces a
+ built-in operation: generate its button-only "Generated call" pattern for the new names only,
+ and keep every existing call exactly as written
Apply only the items under `## Requested Changes` using targeted `Edit` operations on
`<working-dir>/<page-id>/page.tsx`. **Preserve the functionality** listed under
@@ -464,14 +582,42 @@ Connector binding rules for edit deploy:
Custom API binding rules for edit deploy (identical matrix, `--actions` for
`<working-dir>/actions.json`):
- **Add / replace / discover / remove one Custom API:** the `genpage-customapi-builder`
- agent (Mode: `edit`) has already gated on the flag and written the full desired binding
+ agent (Mode: `edit`) has already written the full desired binding
set to `<working-dir>/actions.json` (a removal writes the remaining bindings). Include
`--actions '<working-dir>/actions.json'` in the upload — a full replace that also deletes
any binding left out of the file.
- **Code/visual-only edit (Custom APIs unchanged):** omit `--actions`; the page keeps its
existing `actionBindings`.
-- **Remove every Custom API:** write `[]` to `actions.json` and pass `--actions` so the page's
- `config.json.actionBindings` is cleared.
+- **Remove every Custom API:** every built-in operation row (`WhoAmI`, `RetrieveVersion`) stays,
+ byte for byte. On a page that binds one, upload the `actions.json` the builder wrote (the
+ built-in rows) with `--actions` — never `[]` while a built-in row remains. On a page that holds
+ none, this is the clear below.
+- **Clear every action binding:** write `[]` to `actions.json` and pass `--actions` so the page's
+ `config.json.actionBindings` is cleared — only when the page holds no built-in operation row, or
+ after the maker's clear choice naming each one it removes (asked in Edit Phase 3, and recorded
+ again right before the upload, below).
+- **Built-in operations** ride the same array: an add/replace passes the full desired array the
+ builder wrote (Custom API rows, then the built-in rows); a preserve omits `--actions`; a removal
+ passes the array minus the named entries; `[]` is passed only for a clear-all the maker chose
+ (the clear choice below) — never because the `dataverse-operations` gate turned off (the Edit
+ Phase 4 re-probe halts instead).
+
+**The clear choice, recorded for each upload.** A clear of a page that binds a built-in operation
+is the maker's choice from Edit Phase 3 (or from the edit planner's `clear_choice_required`), made
+before any binding was reconciled and before the plan was approved. Never ask it for the first time
+here — the source was edited in Edit Phase 5. Right before each upload it authorizes, record the
+confirmed clear again as its own line in `workflow-log.md`:
+
+```text
+Clear choice: Clear every action binding of page <page-id>, removing <names>
+```
+
+Only that line, for this page and every built-in operation it holds, permits `[]`, and it covers
+that one upload: write it again before a retry. `Clear choice: Keep <names>`, a yes to adding or
+keeping an operation, an answer with conditions, or a choice written after the upload is no
+permission; the maker keeping them leaves a removal of the Custom APIs at most, and the built-in
+calls and bindings stay. A clear the maker did not choose before the plan was approved is not
+performed: upload no `[]`. **Unattended:** do not clear — Edit Phase 3 stopped before any change.
The edit request is arbitrary user text, and a downloaded prompt is a multi-line conversation
transcript. Both go to the upload BY FILE via `scripts/genpage-upload.js`, never through a shell command:
@@ -499,7 +645,7 @@ Use `--page-id` for updates. Omit `--add-to-sitemap` (the page is already in
the sitemap; the wrapper refuses the combination anyway).
Omit `--data-sources` when `config.json.dataSources` was empty.
Omit `--connectors` when connector bindings are unchanged.
-Omit `--actions` when Custom API bindings are unchanged.
+Omit `--actions` when the page's `actionBindings` are unchanged (Custom API and built-in rows alike).
An update without `--name`/`--name-file` keeps the page's current name: the SDK writes only what differs from the
page it has just read, so an edit that does not rename the page omits it. To rename a page, pass `--name-file` on this
diff --git a/plugins/pcf/AGENTS.md b/plugins/pcf/AGENTS.md
index fe63f8a53..dcf569f72 100644
--- a/plugins/pcf/AGENTS.md
+++ b/plugins/pcf/AGENTS.md
@@ -37,7 +37,7 @@ Primary references: [`references/pcf-hosts.md`](references/pcf-hosts.md), [`refe
- **`scripts/pcf-inventory.js` → `scripts/lib/pcf-dataverse.js`** — lists registered controls and optional where-used dependencies such as the bound `SystemForm` rows returned by Dataverse dependency APIs. It warns that dependency results are registered solution dependencies only and are not proof of Liquid or arbitrary text references.
- **`scripts/pcf-ci-build.js`** — generated-project CI helper. `--all` scaffolds templates and available recipes, runs installs and gates; `--templates` does the same for the templates only; `--latest` probes published dependency drift and keeps those resolved versions even when gates fail; `--package` builds a small package smoke through PAC solution packaging. Gate success requires exactly one JSON result whose records are manifest, code, lint, test and build, each `ok`. Package smoke parses every `<code path>` with the quote-aware XML reader, requires those files in the control folder, and compares them to bundle bytes snapshotted immediately after each build.
-The `pcf-code-gate.js` / `PCF_PAGES_API` guard check is a conservative static heuristic over source text, not a JavaScript parser. It recognizes `context` or context-named variables/fields (`_context`, `ctx`, `pcfContext`, ...), including `this._context` and `props.context`. Calls must be in the true-branch `if` block of a positive method-level guard; calls after early-return guards are reported by design. Proofs cover recognized nested callbacks with root-free heads that do not rebind the guarded name. Shadowing blocks inherited proofs; writing to the guarded name or a protected prefix in a form the analyzer recognizes before the call ends the proof, even in nested functions and classes. This static heuristic can miss unusual write forms. Detected calls it cannot prove guarded and unrecognized forms of guards are reported rather than assumed safe (fail closed). If the analyzer or lexer cannot finish a file, the combined gate reports one `PCF_CODE_UNPARSEABLE` warning per file and treats that file's detected Pages API calls as unguarded. After a lexer failure, calls inside comments or strings may also be reported conservatively. Dynamic computed member names or template-literal member names, aliasing such as `const d = context.device; d.captureImage()`, dynamic dispatch (`.call`/`.apply`/`Reflect.apply`) and parenthesized receivers may evade detection, so runtime verification on the target Power Pages site stays required. Known gaps tracked for a later release are parameter-default writes hidden by same-named body declarations and enclosing `this` in computed class member keys. The copied lexer reads TSX, so for `.ts` files the gate first blanks the angle-bracket types that TSX would read as JSX: each `<…>` where an operand starts, as in `<HTMLInputElement>value` or `<T>(item: T) =>`. A `.ts` file holding an unterminated such type, or more of them than the gate will blank, takes the lexer-failure path above.
+The `pcf-code-gate.js` / `PCF_PAGES_API` guard check is a conservative static heuristic over source text, not a JavaScript parser. It recognizes `context` or context-named variables/fields (`_context`, `ctx`, `pcfContext`, ...), including `this._context` and `props.context`. Any value under such a name is treated as the context, except a function- or block-local `const` bound to an object literal that holds only literals, nested such literals and functions whose body at most returns such a value, and that is used only to call those functions through its own keys, as in `function render() { const ctx = { device: { captureImage() { return 1; } } }; ctx.device.captureImage(); }`. A literal whose functions run or return anything else, or that is passed, aliased, changed, declared at the top of a file, or in a file using `eval` or `with`, keeps the name rule (fail closed). Calls must be in the true-branch `if` block of a positive method-level guard; calls after early-return guards and calls in `else` branches are reported by design. This is a deliberate fail-closed limit: code that runs between such a check and the call, such as a later operand of the same condition, a helper, `Object.assign` or an alias, can remove the method in a way the analyzer cannot see. Rewrite `if (typeof context.device?.captureImage !== 'function') return; context.device.captureImage();` as a positive guard block: `if (typeof context.device?.captureImage === 'function') { context.device.captureImage(); }`. Proofs cover recognized nested callbacks with root-free heads that do not rebind the guarded name. Shadowing blocks inherited proofs; writing to the guarded name or a protected prefix in a form the analyzer recognizes before the call ends the proof, even in nested functions and classes. This static heuristic can miss unusual write forms. Detected calls it cannot prove guarded and unrecognized forms of guards are reported rather than assumed safe (fail closed). If the analyzer or lexer cannot finish a file, the combined gate reports one `PCF_CODE_UNPARSEABLE` warning per file and treats that file's detected Pages API calls as unguarded. After a lexer failure, calls inside comments or strings may also be reported conservatively. Calls through parenthesized receivers, template-literal member names without substitutions and dispatch through `.call`, `.apply`, `.bind` or `Reflect.apply` are detected like direct calls, also when a file falls back. A known limit, in the safe direction: after an optional call with type arguments, as in `factory?.<T>(context.device).captureImage()`, the parenthesis is still read as a grouped receiver, so that call is reported as a Pages call (an over-report, never a missed call). Dynamic computed member names, including template-literal member names with a substitution, aliasing such as `const d = context.device; d.captureImage()`, and other dynamic dispatch (a comma group such as `(0, context.device.captureImage)()`, or the method passed to another function) may evade detection, so runtime verification on the target Power Pages site stays required. A write in a parameter default reaches the outer binding even when the function body declares the same name, as in `function reset(v = (context.device = {})) { let context; }`. `this` in a computed class member key, as in `class D { [this._context.device = null]() {} }`, is the enclosing method's, so a write there ends that method's proof. A key is recognized where a member starts: after the class body's `{`, a `;`, a method body or static block, member modifiers or a decorator, and on a new line after a field without an initializer (`value: number`, `#value`) or after an initializer ending in an arrow-function body or a postfix `++`/`--`. Two forms behave as before, with `this` in the key read as the inner class's instance, so a write there does not end the enclosing method's proof: a key on a new line after an initializer ending in a type assertion or `satisfies` (`value = {} as object`), and a key on the same line after a decorator with type arguments (`@decorate<T>() [key]() {}`). The copied lexer reads TSX, so for `.ts` files the gate first blanks the angle-bracket types that TSX would read as JSX: each `<…>` where an operand starts, as in `<HTMLInputElement>value` or `<T>(item: T) =>`. Blanking costs a lex of the file per pass, and each pass blanks every later type it can confirm, so hundreds of types stay analyzable. A `.ts` file holding an unterminated such type, or so many of them in so large a file that blanking them would pass the lexing budget (6 million characters lexed), takes the lexer-failure path above.
## Agent-safety rules
diff --git a/plugins/pcf/CHANGELOG.md b/plugins/pcf/CHANGELOG.md
index 1d20c5c83..67afde87b 100644
--- a/plugins/pcf/CHANGELOG.md
+++ b/plugins/pcf/CHANGELOG.md
@@ -14,9 +14,17 @@ First preview release: ships the `/pcf:pcf` skill, matrix-pinned templates and r
### Changed
- The bundled SDK is the one model-apps 2.18.0 ships (power-platform-ux a3443479), beside model-apps 2.18.0's HTTP client; the SDK no longer carries its PCF control registration, which this plugin never called. What changed in them — a web resource's published content read back, an app's sitemap found by its component, a publish sent once — is in requests this plugin does not make: it only reads through them and publishes through PAC, so what it does is unchanged.
+- The PCF guide explains why calls after an early-return guard or in an `else` branch are reported, and shows the positive guard block to use instead.
+- An optional call with type arguments that is handed a context member, such as `factory?.<T>(context.device).captureImage()`, is now reported as a Pages call even when the factory returns its own object; call it without `?.` or keep the result in a local first.
### Fixed
- The push receipt (`pcf-receipt.json`) no longer carries an access token that a refused confirmation read quoted, and every file the SDK writes into a push's workspace goes through the same output guard as model-apps' scripts.
- A large result is no longer cut short on Linux and macOS: `emitResult`, the printer of an uncaught error, `check-auth.js`, the result printers of `pcf-inventory.js`, `verify-pcf.js` and `lint-pcf.js`, every script's usage error and the write-safety hook's message make their writes blocking before the process exits. What is printed and every exit status are unchanged; Windows was never affected.
- The output guard (the same module model-apps 2.19.0 ships) also keeps an access token out of bytes written to stdout or stderr, masked with `*` byte for byte so framed output keeps its length, out of the token's base64 — and the base64 of each of its parts of 24 characters or more — and its percent-encoded and HTML spellings, and out of a token that `util.inspect` or an ellipsis cut short or that was split between two writes (each piece of 24 characters or more), keeping an escape split between two writes whole, also after a nested write and the write around it were both refused. Still left: a piece shorter than 24 characters, the middle piece of a token written in three or more writes, a short piece on the far side of a split escape, base64 of a piece of the token that is not a whole part, and bytes written to a file.
+- The Pages guard check now catches Pages calls written through parentheses, template-literal keys, `.call`, `.apply`, `.bind` or `Reflect.apply`, and counts them as feature use.
+- A write in a parameter default now ends the Pages guard proof even when the function body declares the same name.
+- `this` in a computed class member key, such as one after a typed or private field, now means the enclosing method's `this`, so a write there ends that method's Pages guard proof.
+- A `.ts` file with hundreds of `<Type>value` casts is now analyzed instead of being treated as unparseable, which had reported every Pages call in it as unguarded.
+- A local object literal named like the context, such as `const ctx = { device: { captureImage() { return 1; } } }`, is no longer mistaken for the PCF context when only its own simple functions are called.
+- The pcf evals report a case with nothing graded as unscored, not passed; exit status unchanged.
diff --git a/plugins/pcf/references/pcf-best-practices.md b/plugins/pcf/references/pcf-best-practices.md
index 9d21ef87b..3cdb55d2d 100644
--- a/plugins/pcf/references/pcf-best-practices.md
+++ b/plugins/pcf/references/pcf-best-practices.md
@@ -41,7 +41,7 @@ Use this reference when designing or reviewing Power Apps component framework (P
## Data access and host features
- Prefer `context.webAPI` for Dataverse data in model-driven apps and Power Pages. Learn marks WebAPI available for model-driven apps and portals: [WebAPI](https://learn.microsoft.com/en-us/power-apps/developer/component-framework/reference/webapi).
-- Guard optional host methods at the method level, for example `typeof context.device?.captureImage === 'function'`; an existing namespace does not prove the method is callable. The gate recognizes `context` or context-named variables/fields (`_context`, `ctx`, `pcfContext`, ...), including `this._context` and `props.context`. Put the call in the true-branch `if` block of a positive method-level guard; calls after early-return guards are reported by design. A write to the guarded name or its prefixes in a form the analyzer recognizes before the call ends the proof, even in nested functions or classes. This static heuristic can miss unusual write forms. If the analyzer or lexer cannot finish a file, the combined gate emits one `PCF_CODE_UNPARSEABLE` warning per file and treats that file's detected Pages API calls as unguarded. After a lexer failure, calls inside comments or strings may also be reported conservatively. Aliasing, computed or template-literal member names, dynamic dispatch (`.call`/`.apply`/`Reflect.apply`) and parenthesized receivers may evade detection, so runtime verification on the target Power Pages site stays required.
+- Guard optional host methods at the method level, for example `typeof context.device?.captureImage === 'function'`; an existing namespace does not prove the method is callable. The gate recognizes `context` or context-named variables/fields (`_context`, `ctx`, `pcfContext`, ...), including `this._context` and `props.context`. Put the call in the true-branch `if` block of a positive method-level guard, as in `if (typeof context.device?.captureImage === 'function') { context.device.captureImage(); }`; calls after early-return guards and calls in `else` branches are reported by design, a deliberate fail-closed limit, so write a positive guard block rather than an early return. A write to the guarded name or its prefixes in a form the analyzer recognizes before the call ends the proof, even in nested functions or classes. This static heuristic can miss unusual write forms. If the analyzer or lexer cannot finish a file, the combined gate emits one `PCF_CODE_UNPARSEABLE` warning per file and treats that file's detected Pages API calls as unguarded. After a lexer failure, calls inside comments or strings may also be reported conservatively. Calls through parenthesized receivers, template-literal member names without substitutions and dispatch through `.call`, `.apply`, `.bind` or `Reflect.apply` are detected like direct calls; aliasing, dynamic computed or template-literal member names with a substitution, and other dynamic dispatch may evade detection, so runtime verification on the target Power Pages site stays required.
- Do not use browser storage for business data. Learn says `localStorage` and `sessionStorage` are not secure or reliably available for PCF data: [limitations](https://learn.microsoft.com/en-us/power-apps/developer/component-framework/limitations).
- External service calls can make the control premium when declared in the manifest. Keep domains explicit and explain the licensing impact: [overview licensing](https://learn.microsoft.com/en-us/power-apps/developer/component-framework/overview#licensing).
diff --git a/plugins/pcf/references/pcf-testing.md b/plugins/pcf/references/pcf-testing.md
index 58df8bfb2..47e82f1fb 100644
--- a/plugins/pcf/references/pcf-testing.md
+++ b/plugins/pcf/references/pcf-testing.md
@@ -48,7 +48,7 @@ Do not delete deployed-only code merely to satisfy harness limitations.
Run deployed smoke when behavior depends on Dataverse, model-driven forms, published metadata, Pages, Web API, security or dataset paging.
-The Pages guard check is a conservative static heuristic over source text, not a JavaScript parser. It recognizes `context` or context-named variables/fields (`_context`, `ctx`, `pcfContext`, ...), including `this._context` and `props.context`. Calls must be in the true-branch `if` block of a positive method-level guard; calls after early-return guards are reported by design. Proofs cover recognized nested callbacks with root-free heads that do not rebind the guarded name. Shadowing blocks inherited proofs; writing to the guarded name or a protected prefix in a form the analyzer recognizes before the call ends the proof, even in nested functions and classes. This static heuristic can miss unusual write forms. Detected calls it cannot prove guarded and unrecognized forms of guards are reported rather than assumed safe (fail closed). If the analyzer or lexer cannot finish a file, the combined gate reports one `PCF_CODE_UNPARSEABLE` warning per file and treats that file's detected Pages API calls as unguarded. After a lexer failure, calls inside comments or strings may also be reported conservatively. Dynamic computed member names or template-literal member names, aliasing such as `const d = context.device; d.captureImage()`, dynamic dispatch (`.call`/`.apply`/`Reflect.apply`) and parenthesized receivers may evade detection, so runtime verification on the target Power Pages site stays required.
+The Pages guard check is a conservative static heuristic over source text, not a JavaScript parser. It recognizes `context` or context-named variables/fields (`_context`, `ctx`, `pcfContext`, ...), including `this._context` and `props.context`. Any value under such a name is treated as the context, except a function- or block-local `const` bound to an object literal that holds only literals, nested such literals and functions whose body at most returns such a value, and that is used only to call those functions through its own keys, as in `function render() { const ctx = { device: { captureImage() { return 1; } } }; ctx.device.captureImage(); }`. A literal whose functions run or return anything else, or that is passed, aliased, changed, declared at the top of a file, or in a file using `eval` or `with`, keeps the name rule (fail closed). Calls must be in the true-branch `if` block of a positive method-level guard; calls after early-return guards and calls in `else` branches are reported by design. This is a deliberate fail-closed limit: code that runs between such a check and the call, such as a later operand of the same condition, a helper, `Object.assign` or an alias, can remove the method in a way the analyzer cannot see. Rewrite `if (typeof context.device?.captureImage !== 'function') return; context.device.captureImage();` as a positive guard block: `if (typeof context.device?.captureImage === 'function') { context.device.captureImage(); }`. Proofs cover recognized nested callbacks with root-free heads that do not rebind the guarded name. Shadowing blocks inherited proofs; writing to the guarded name or a protected prefix in a form the analyzer recognizes before the call ends the proof, even in nested functions and classes. This static heuristic can miss unusual write forms. Detected calls it cannot prove guarded and unrecognized forms of guards are reported rather than assumed safe (fail closed). If the analyzer or lexer cannot finish a file, the combined gate reports one `PCF_CODE_UNPARSEABLE` warning per file and treats that file's detected Pages API calls as unguarded. After a lexer failure, calls inside comments or strings may also be reported conservatively. Calls through parenthesized receivers, template-literal member names without substitutions and dispatch through `.call`, `.apply`, `.bind` or `Reflect.apply` are detected like direct calls, also when a file falls back. A known limit, in the safe direction: after an optional call with type arguments, as in `factory?.<T>(context.device).captureImage()`, the parenthesis is still read as a grouped receiver, so that call is reported as a Pages call (an over-report, never a missed call). Dynamic computed member names, including template-literal member names with a substitution, aliasing such as `const d = context.device; d.captureImage()`, and other dynamic dispatch (a comma group such as `(0, context.device.captureImage)()`, or the method passed to another function) may evade detection, so runtime verification on the target Power Pages site stays required.
Recommended smoke assertions:
diff --git a/plugins/pcf/scripts/lib/pcf-code-gate.js b/plugins/pcf/scripts/lib/pcf-code-gate.js
index ee5bd7be1..0c892e81c 100644
--- a/plugins/pcf/scripts/lib/pcf-code-gate.js
+++ b/plugins/pcf/scripts/lib/pcf-code-gate.js
@@ -13,6 +13,7 @@ const IDENTIFIER_ESCAPE = /\\u(?:[0-9a-fA-F]{4}|\{[0-9a-fA-F]+\})/y;
const SOURCE_OPERATOR = /(?:>>>=|\*\*=|&&=|\|\|=|\?\?=|<<=|>>=|===|!==|=>|\?\.|\.\.\.|\+\+|--|==|!=|<=|>=|&&|\|\||\?\?|\*\*|[+\-*/%&|^]=)/y;
const ASSIGNMENT_OPERATORS = new Set(['=', '+=', '-=', '*=', '/=', '%=', '**=', '<<=', '>>=', '>>>=', '&=', '|=', '^=', '&&=', '||=', '??=']);
const HEAD_MODIFIERS = new Set(['async', 'get', 'set', 'static', 'public', 'private', 'protected', 'readonly', 'abstract', 'override']);
+const CLASS_MEMBER_MODIFIERS = new Set([...HEAD_MODIFIERS, 'declare', 'accessor']);
const READ_FOLLOWERS = new Set(['(', ')', ']', '}', ',', ';', '?', ':', '!', '++', '--', '+', '-', '*', '/', '%', '**', '&', '|', '^', '<', '>', '<=', '>=', '==', '!=', '===', '!==', '&&', '||', '??', ...ASSIGNMENT_OPERATORS]);
const READ_PREFIX_WORDS = ['return', 'throw', 'yield', 'await', 'typeof', 'void', 'new', 'delete', 'case', 'else', 'in', 'instanceof', 'as', 'satisfies', 'let', 'const', 'var', 'function', 'class'];
const CONTEXT_NAME = /^_*(?:pcf)?(?:context|ctx)$/i;
@@ -646,16 +647,21 @@ function lexSource(file, text, lex, opts) {
// A .ts file has no JSX, so a `<` where an operand starts can only open a type. Blank that `<…>` span
// (types carry no calls) and lex again, until no such `<` remains. Only the span from the first
// operand `<` on is in doubt after a pass, because the lexer read everything after it as JSX.
+// One lex per type made the cost the file size times its types, so a large control with a few hundred
+// casts went to the fail-closed path. Each pass now also blanks the later types a raw-text scan
+// proposes (proposedAngleTypes), lexes once, and keeps a proposal only when that lex confirms the
+// sequential loop would have blanked the same span (acceptedAngleTypes); the rest are dropped and
+// found again one pass at a time, so the result is the sequential loop's.
// See TypeScript's TSX rules: https://www.typescriptlang.org/docs/handbook/jsx.html#the-as-operator
-const TS_ANGLE_TYPE_PASSES = 256;
-// Total characters lexed across passes. Past it, or past the pass limit, the file goes to the
-// lexer-failure path: one PCF_CODE_UNPARSEABLE warning, and its Pages API calls are treated as
-// unguarded (fail closed). Each pass re-lexes the whole file, because the lexer cannot restart midway
-// and its reading after the first JSX misread is not trusted, so the cost is the file size times its
-// angle-bracket types. 6M characters is a 40 KB control with 150 of them, about 1.5 s on a dev box.
+// Total characters lexed across passes. Past it the file goes to the lexer-failure path: one
+// PCF_CODE_UNPARSEABLE warning, and its Pages API calls are treated as unguarded (fail closed). Each pass
+// re-lexes the whole file, because the lexer cannot restart midway and its reading after the first JSX
+// misread is not trusted. 6M characters is a 40 KB control lexed 150 times, about 1.5 s on a dev box.
const TS_ANGLE_TYPE_BUDGET = 6000000;
// Longest `<…>` type read. A longer one is far more likely an unbalanced `<` than a type.
-const TS_ANGLE_TYPE_MAX_CHARS = 4096;
+const TS_ANGLE_TYPE_MAX_CHARS = 16384;
+// Passes whose proposals the lex did not confirm before the gate stops proposing for the file.
+const TS_ANGLE_TYPE_MISSES = 8;
function isPlainTypeScript(file) {
// .ts, .mts and .cts. A .tsx file keeps the lexer's JSX reading.
@@ -664,21 +670,170 @@ function isPlainTypeScript(file) {
function lexTypeScriptAngleTypes(text, lex, opts) {
let source = text;
+ let mask = null;
let from = 0;
let lexed = 0;
- for (let pass = 0; ; pass += 1) {
- lexed += source.length;
- if (pass > TS_ANGLE_TYPE_PASSES || lexed > TS_ANGLE_TYPE_BUDGET) {
- throw new Error('too many TypeScript angle-bracket types to analyze');
- }
- const mask = lex(source, opts);
+ let misses = 0;
+ const lexWithinBudget = (value, options = opts) => {
+ lexed += value.length;
+ if (lexed > TS_ANGLE_TYPE_BUDGET) throw new Error('too many TypeScript angle-bracket types to analyze');
+ return lex(value, options);
+ };
+ // Confirming a proposal relies on the shared lexer's report of every place it read by look-ahead
+ // (onAmbiguity); an injected lexer is read one type at a time.
+ const speculate = lex === blankNonCodePreservingTemplateExpressions;
+ for (;;) {
+ if (mask === null) mask = lexWithinBudget(source);
const at = nextOperandAngle(mask, from);
if (at === -1) return { source, mask };
const end = angleTypeEnd(source, at);
if (end === -1) throw new Error('unterminated TypeScript angle-bracket type');
- source = blankKeepingLines(source, at, end + 1);
+ const spans = [[at, end], ...(speculate && misses < TS_ANGLE_TYPE_MISSES ? proposedAngleTypes(source, end + 1) : [])];
+ // A proposal must not remove a character that ends a literal or steers a regex scan (/ \ " ' ` [ ]):
+ // the lexer reads an earlier regex such as /Button>…</ to the first / it finds, so blanking that /
+ // in a later span would change the reading before the span (a span is balanced in ( ) { } < >).
+ const unsafe = spans.findIndex(([start, stop], i) => i > 0 && /[/\\"'`[\]]/.test(source.slice(start, stop + 1)));
+ if (unsafe !== -1) spans.length = unsafe;
+ const candidate = blankSpans(source, spans);
+ if (spans.length === 1) {
+ source = candidate;
+ mask = null;
+ } else {
+ let lookahead = Infinity;
+ const candidateMask = lexWithinBudget(candidate, { ...opts, onAmbiguity: (offset, kind) => {
+ lookahead = Math.min(lookahead, offset);
+ if (typeof opts?.onAmbiguity === 'function') opts.onAmbiguity(offset, kind);
+ } });
+ const accepted = acceptedAngleTypes(candidate, candidateMask, spans, lookahead);
+ if (accepted === spans.length) {
+ // The candidate's reading is trusted up to its next operand `<`, which the next pass finds.
+ source = candidate;
+ mask = candidateMask;
+ } else {
+ misses += 1;
+ source = blankSpans(source, spans.slice(0, accepted));
+ mask = null;
+ }
+ spans.length = accepted;
+ }
+ from = spans.at(-1)[1] + 1;
+ }
+}
+
+function acceptedAngleTypes(candidate, mask, spans, lookahead) {
+ // How many spans, in order, the sequential loop would also have blanked. The first was found in a
+ // trusted reading. The lexer reads a position from the text before it, except where it decides by
+ // look-ahead (`lookahead` is the first such place) or where a literal it opened needs a terminator
+ // further on (lexTypeScriptAngleTypes keeps those characters out of every later span). So a later
+ // span at `at` before that place is confirmed when every span before it is, so the candidate is read
+ // up to `at` exactly as the sequential loop reads it, and in that reading: no operand `<` is left
+ // between it and the previous span (the sequential loop would have taken that one first); the
+ // character before it is code the mask keeps, not a string, template, comment or regex (whose text
+ // the mask blanks, or whose delimiter it keeps: " ' ` /); and an operand starts there, so the `<`
+ // that stood there opened a type.
+ let accepted = 1;
+ for (; accepted < spans.length; accepted += 1) {
+ const at = spans[accepted][0];
+ if (at >= lookahead) break;
+ if (operandAngleBetween(mask, spans[accepted - 1][1] + 1, at)) break;
+ const before = previousNonSpaceIndex(mask, at);
+ if (before !== previousNonSpaceIndex(candidate, at)) break;
+ if (before !== -1 && (mask[before] !== candidate[before] || '"\'`/'.includes(candidate[before]))) break;
+ if (!expressionPosition(mask, at)) break;
+ }
+ return accepted;
+}
+
+function operandAngleBetween(mask, from, to) {
+ for (let i = mask.indexOf('<', from); i !== -1 && i < to; i = mask.indexOf('<', i + 1)) {
+ if (mask[i + 1] === '<' || mask[i + 1] === '=' || mask[i - 1] === '<') continue;
+ if (expressionPosition(mask, i)) return true;
+ }
+ return false;
+}
+
+// A `<` after one of these, or after one of the words below, is where an operand starts. Any other `<`
+// is a comparison, a shift or type arguments. A `/` is left out: it may end a regex.
+const ANGLE_TYPE_AFTER = new Set(['=', '(', ',', ':', '[', '!', '&', '|', '?', '{', '}', ';', '+', '-', '*', '%', '^', '~', '>', '']);
+const ANGLE_TYPE_AFTER_WORDS = new Set(['return', 'typeof', 'void', 'delete', 'await', 'yield', 'case', 'throw', 'else', 'do', 'in', 'of']);
+
+function proposedAngleTypes(source, from) {
+ // Proposals only: acceptedAngleTypes confirms each before it counts, so this scan may be wrong in
+ // either direction. It skips strings, comments, template text (keeping `${…}` code) and regexes, and
+ // stops once it has read twice the file's length in candidate types.
+ const spans = [];
+ const templates = [];
+ let previous = '>';
+ let word = '';
+ let budget = source.length * 2;
+ for (let i = from; i < source.length && budget > 0; i += 1) {
+ const c = source[i];
+ if (/\s/.test(c)) continue;
+ if (c === '"' || c === "'") {
+ i = quotedEnd(source, i, source.length);
+ if (i === -1) break;
+ previous = c;
+ word = '';
+ } else if (c === '`' || (c === '}' && templates.at(-1) === 0)) {
+ if (c === '}') templates.pop();
+ let j = i + 1;
+ for (; j < source.length && source[j] !== '`' && !(source[j] === '$' && source[j + 1] === '{'); j += 1) {
+ if (source[j] === '\\') j += 1;
+ }
+ if (j >= source.length) break;
+ if (source[j] === '$') { templates.push(0); j += 1; previous = '{'; } else previous = '`';
+ i = j;
+ word = '';
+ } else if (c === '/' && (source[i + 1] === '/' || source[i + 1] === '*')) {
+ // Comments are skipped without changing `previous`: `= /* cast */ <T>v` still proposes.
+ const close = source[i + 1] === '/' ? source.slice(i).search(/[\n\r\u2028\u2029]/) + i : source.indexOf('*/', i + 2) + 1;
+ if (close < i) break;
+ i = close;
+ } else if (c === '/' && (ANGLE_TYPE_AFTER.has(previous) || ANGLE_TYPE_AFTER_WORDS.has(word))) {
+ let j = i + 1;
+ for (let inClass = false; j < source.length && (inClass || source[j] !== '/'); j += 1) {
+ if (source[j] === '\\') j += 1;
+ else if (source[j] === '[') inClass = true;
+ else if (source[j] === ']') inClass = false;
+ else if (/[\n\r\u2028\u2029]/.test(source[j])) break;
+ }
+ i = j;
+ previous = '/';
+ word = '';
+ } else if (c === '<' && source[i + 1] !== '<' && source[i + 1] !== '=' && source[i - 1] !== '<'
+ && (ANGLE_TYPE_AFTER.has(previous) || ANGLE_TYPE_AFTER_WORDS.has(word))) {
+ const end = angleTypeEnd(source, i);
+ budget -= end === -1 ? Math.min(TS_ANGLE_TYPE_MAX_CHARS, source.length - i) : end - i;
+ if (end !== -1) {
+ spans.push([i, end]);
+ i = end;
+ }
+ previous = '>';
+ word = '';
+ } else if (IDENTIFIER_CONTINUE.test(c)) {
+ const start = i;
+ while (i + 1 < source.length && IDENTIFIER_CONTINUE.test(source[i + 1])) i += 1;
+ word = source.slice(start, i + 1);
+ previous = 'a';
+ } else {
+ if (c === '{' && templates.length) templates[templates.length - 1] += 1;
+ else if (c === '}' && templates.length) templates[templates.length - 1] -= 1;
+ previous = c;
+ word = '';
+ }
+ }
+ return spans;
+}
+
+function blankSpans(source, spans) {
+ // Line terminators stay, so lineOf() reports the same line for every later finding.
+ let blanked = '';
+ let from = 0;
+ for (const [start, end] of spans) {
+ blanked += source.slice(from, start) + source.slice(start, end + 1).replace(/[^\n\r\u2028\u2029]/g, ' ');
from = end + 1;
}
+ return blanked + source.slice(from);
}
function nextOperandAngle(mask, from) {
@@ -741,13 +896,6 @@ function quotedEnd(source, start, limit) {
return -1;
}
-function blankKeepingLines(source, start, end) {
- // Line terminators stay, so lineOf() reports the same line for every later finding.
- return source.slice(0, start)
- + source.slice(start, end).replace(/[^\n\r\u2028\u2029]/g, ' ')
- + source.slice(end);
-}
-
function stringLikeRanges(src, mask) {
const ranges = [];
let i = 0;
@@ -968,9 +1116,17 @@ function decodeStaticKey(raw) {
function indexedPath(index, start) {
if (index.paths.has(start)) return index.paths.get(start);
+ const { tokens } = index;
+ const path = { ...readMemberPath(index, [tokens[start].name || tokens[start].value], start + 1),
+ token: start, start: tokens[start].start };
+ index.paths.set(start, path);
+ return path;
+}
+
+function readMemberPath(index, names, end) {
+ // Reads the members after names[0] (or after a group holding a path): .name, ?.name, ["name"] and
+ // [`name`]. Any other computed key makes the path `unknown`.
const { tokens, text } = index;
- const names = [tokens[start].name || tokens[start].value];
- let end = start + 1;
let unknown = false;
while (end < tokens.length) {
// Postfix ! is erased ONLY in this detection view. != / !== are whole operator
@@ -988,8 +1144,14 @@ function indexedPath(index, start) {
}
if (tokens[member]?.value === '[' && tokens[member].match >= 0) {
const close = tokens[member].match;
- const key = close === member + 2 && tokens[member + 1].kind === 'string'
- ? decodeStaticKey(text.slice(tokens[member + 1].start, tokens[member + 1].end)) : null;
+ let key = null;
+ if (close === member + 2 && tokens[member + 1].kind === 'string') {
+ key = decodeStaticKey(text.slice(tokens[member + 1].start, tokens[member + 1].end));
+ } else if (close === member + 3 && tokens[member + 1].value === TEMPLATE_QUOTE && tokens[member + 2].value === TEMPLATE_QUOTE) {
+ // The mask blanks template text and keeps `${…}` code, so two adjacent back-ticks are a
+ // template with no substitution: context.device[`captureImage`]() names the method.
+ key = decodeTemplateKey(text.slice(tokens[member + 1].start, tokens[member + 2].end));
+ }
end = close + 1;
if (!key) { unknown = true; break; }
names.push(key);
@@ -998,9 +1160,14 @@ function indexedPath(index, start) {
break;
}
const call = tokens[end]?.value === '(' || (tokens[end]?.value === '?.' && tokens[end + 1]?.value === '(');
- const path = { names, end, unknown, call, token: start, start: tokens[start].start };
- index.paths.set(start, path);
- return path;
+ return { names, end, unknown, call };
+}
+
+function decodeTemplateKey(raw) {
+ // A no-substitution template is cooked like a string literal: the same escapes, line continuations
+ // and identifier test, so decode its body as one. https://tc39.es/ecma262/#sec-template-literals
+ if (raw.length < 2 || raw[0] !== TEMPLATE_QUOTE || raw.at(-1) !== TEMPLATE_QUOTE || raw.includes('${')) return null;
+ return decodeStaticKey(`"${raw.slice(1, -1)}"`);
}
function angleBoundary(tokens, start, direction) {
@@ -1008,13 +1175,16 @@ function angleBoundary(tokens, start, direction) {
return tokens.angles.get(start) ?? -1;
}
-function typedHeadBody(tokens, close) {
+function typedHeadBody(tokens, close, mask) {
let i = close + 1;
if (tokens[i]?.value !== ':') return tokens[i]?.value === '{' ? i : -1;
let needsType = true;
for (i += 1; i < tokens.length; i += 1) {
const token = tokens[i];
if (token.value === '{' && !needsType) return i;
+ // A return type does not continue across a line break into `[`: in a class body
+ // run(): void\n[key]() {} is an overload signature and a computed member, not one method.
+ if (token.value === '[' && !needsType && mask && LINE_TERMINATOR.test(mask.slice(tokens[i - 1].end, token.start))) return -1;
if (['(', '[', '{', '<'].includes(token.value)) {
const end = token.value === '<' ? angleBoundary(tokens, i, 1) : token.match;
if (end < 0) return -1;
@@ -1162,7 +1332,7 @@ function indexHeads(index) {
next += 1;
}
if (tokens[next]?.value !== '(' || tokens[next].match < 0) continue;
- const body = typedHeadBody(tokens, tokens[next].match);
+ const body = typedHeadBody(tokens, tokens[next].match, index.mask);
addHead({ kind: 'function', arrow: false, start: tokenKeyword(tokens, i - 1, 'async') ? i - 1 : i, keyword: i, name, parameters: next, body });
} else if (tokenKeyword(tokens, i, 'class') && !inMethodPosition(i)) {
let body = i + 1;
@@ -1208,7 +1378,7 @@ function indexHeads(index) {
}
for (let open = 0; open < tokens.length; open += 1) {
if (tokens[open].value !== '(' || tokens[open].match < 0 || !inContainer(open)) continue;
- const body = typedHeadBody(tokens, tokens[open].match);
+ const body = typedHeadBody(tokens, tokens[open].match, index.mask);
if (body < 0 || bodies.has(body)) continue;
let name = open - 1;
if (tokens[name]?.value === '>') {
@@ -1264,6 +1434,15 @@ function indexScopes(index) {
scopes.push(scope);
blockScopes.set(i, scope);
if (head) head.scope = scope;
+ // A function with parameter expressions evaluates its defaults before the body's declarations
+ // exist, in a separate environment: function f(v = (context.device = {})) { let context; } writes
+ // the outer context. Give the body its own var/lexical scope so a body declaration cannot capture
+ // a root that a default reads or writes. Defaults and computed pattern keys are the parameter
+ // expressions; a stray '=' or '[' in a type only adds a scope that changes no binding.
+ // https://tc39.es/ecma262/#sec-functiondeclarationinstantiation (steps 27-28)
+ if (head && head.kind === 'function' && scope.kind === 'function' && hasParameterExpressions(tokens, head)) {
+ scopes.push({ kind: 'body', start: tokens[i].start, body: tokens[i].start, end, roots: new Set(), head });
+ }
}
for (const head of heads) {
if (tokens[head.body]?.value === '{') continue;
@@ -1272,6 +1451,18 @@ function indexScopes(index) {
scopes.push(scope);
head.scope = scope;
}
+ // A computed class member key is evaluated where the class is defined: in class D { [this.x = 1]() {} }
+ // `this` is the enclosing method's, not D's instance. The key gets a scope of its own that bindingFor
+ // resolves `this` through, past the class. Only a `[` that begins a member is a key; in
+ // value = {}\n[k] the `[` indexes the initializer, whose `this` is the instance.
+ // https://tc39.es/ecma262/#sec-runtime-semantics-classdefinitionevaluation
+ for (const head of heads) {
+ const open = head.body;
+ if (head.kind !== 'class' || tokens[open]?.value !== '{' || tokens[open].match < 0) continue;
+ for (const key of classMemberKeys(index, open)) {
+ scopes.push({ kind: 'class-key', start: tokens[key].start, body: tokens[key].start, end: tokens[tokens[key].match].end, roots: new Set() });
+ }
+ }
for (const control of controls) {
if (control.kind !== 'for') continue;
const end = indexedStatementEnd(index, control.body);
@@ -1300,7 +1491,7 @@ function indexScopes(index) {
// A static block owns its var/function declarations; var context inside it
// must not shadow or write context outside the class.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Static_initialization_blocks
- scope.function = ['program', 'function', 'opaque', 'static'].includes(scope.kind) ? scope : scope.parent?.function;
+ scope.function = ['program', 'function', 'body', 'opaque', 'static'].includes(scope.kind) ? scope : scope.parent?.function;
scope.parentFunction = scope.parent?.function;
active.push(scope);
}
@@ -1310,6 +1501,83 @@ function indexScopes(index) {
index.blockScopes = blockScopes;
}
+function classMemberKeys(index, classBody) {
+ // The `[` tokens of a class body that begin a member's computed key. Members are read forwards, one
+ // class-level token or bracketed group at a time:
+ // class D { [k]() {} } x = 1; [k] = 2 static [k]() {} get [k]() {} *[k]() {} m() {} [k]() {}
+ // @decorate [k]() {} @decorate() [k]() {}
+ // A member ends at `;`, after a method body or static block, or at a line break the next token cannot
+ // continue (ASI). Before a `[` on a new line that is:
+ // - always, after a member with no initializer: value / #value / value: number / m(): void. A type
+ // does not continue across a line break into `[` (TypeScript reads `number\n[k]` as two members);
+ // - after an initializer only when it cannot be indexed: an arrow function body `() => {}` or a
+ // postfix `++`/`--`. Otherwise value = {}\n[k] indexes the initializer, whose `this` is the instance.
+ // https://tc39.es/ecma262/#sec-rules-of-automatic-semicolon-insertion and
+ // https://www.typescriptlang.org/docs/handbook/decorators.html
+ const { tokens, mask, bodies, containers } = index;
+ const keys = [];
+ const close = tokens[classBody].match;
+ let member;
+ const reset = () => { member = { named: false, initializer: false, decorator: null, last: -1 }; };
+ reset();
+ const indexable = (last) => {
+ const token = tokens[last];
+ if (['++', '--'].includes(token.value)) return false;
+ if (token.value !== '}' || token.match < 0) return true;
+ return !bodies.get(token.match)?.arrow || containers.has(token.match);
+ };
+ const endsOperand = (last) => ['}', '++', '--'].includes(tokens[last].value) || canEndOperand(index, last);
+ for (let i = classBody + 1; i < close; i += 1) {
+ const token = tokens[i];
+ const lineBreak = member.last >= 0 && LINE_TERMINATOR.test(mask.slice(tokens[member.last].end, token.start));
+ if (token.value === '[' && lineBreak && member.named && (!member.initializer || !indexable(member.last))) reset();
+ // first = 1\nsecond: an initializer that ends an operand cannot run on into a name, so the line
+ // break ends the member.
+ else if (lineBreak && member.initializer && endsOperand(member.last)
+ && ((token.kind !== 'punctuation' && !['in', 'instanceof', 'as', 'satisfies'].includes(token.value))
+ || ['#', '@'].includes(token.value))) reset();
+ const end = ['(', '[', '{'].includes(token.value) && token.match > i ? token.match : i;
+ if (member.decorator) {
+ // @a.b.c, @a(…) and @(…) decorate the member that follows; they do not name it.
+ const name = member.decorator === 'name' && token.kind === 'identifier';
+ if (name || (member.decorator === 'dot' && token.value === '.')) {
+ member.decorator = name ? 'dot' : 'name';
+ member.last = i;
+ continue;
+ }
+ member.decorator = null;
+ if (token.value === '(' && end > i) { member.last = end; i = end; continue; }
+ }
+ if (token.value === ';') { reset(); continue; }
+ if (token.value === '@') member.decorator = 'name';
+ else if (token.value === '[') {
+ if (!member.named) keys.push(i);
+ member.named = true;
+ } else if (token.value === '{' && !member.initializer
+ && (bodies.get(i)?.method || tokenKeyword(tokens, i - 1, 'static'))) {
+ reset();
+ i = end;
+ continue;
+ } else if (token.value === '=') {
+ member.initializer = true;
+ member.named = true;
+ } else if (!(token.kind === 'identifier' && CLASS_MEMBER_MODIFIERS.has(token.value) && !member.named)
+ && !['*', '#'].includes(token.value)) member.named = true;
+ member.last = end;
+ i = end;
+ }
+ return keys;
+}
+
+function hasParameterExpressions(tokens, head) {
+ const open = head.parameters;
+ if (open === undefined || open < 0 || tokens[open]?.value !== '(' || tokens[open].match < 0) return false;
+ for (let i = open + 1; i < tokens[open].match; i += 1) {
+ if (tokens[i].value === '=' || tokens[i].value === '[') return true;
+ }
+ return false;
+}
+
function topLevelTokenRanges(tokens, start, end, separator) {
const ranges = [];
let from = start;
@@ -1502,7 +1770,7 @@ function bindingFor(scope, root) {
// uses, memoizing each visited scope so deep callback chains are walked once per root.
const pending = [];
let binding;
- for (let owner = scope; owner; owner = owner.parent) {
+ for (let owner = scope; owner;) {
if (owner.bindings.has(root)) { binding = owner.bindings.get(root); break; }
pending.push(owner);
if (!owner.parent || owner.declarations.has(root) || owner.kind === 'opaque'
@@ -1510,6 +1778,9 @@ function bindingFor(scope, root) {
binding = owner.id;
break;
}
+ // `this` in a computed class member key is the enclosing scope's: step past the class itself.
+ owner = root === 'this' && owner.kind === 'class-key' && owner.parent.kind === 'class' && owner.parent.parent
+ ? owner.parent.parent : owner.parent;
}
for (const owner of pending) owner.bindings.set(root, binding);
return binding;
@@ -1646,6 +1917,9 @@ function indexSource(text, mask) {
indexDeclarations(index);
indexWrites(index);
index.members = indexedMembers(index);
+ // A context-named local const bound to an inert object literal, used only to call its own functions, is
+ // that literal, not the PCF context: const ctx = { device: { captureImage() { return 1; } } }; ctx.device.captureImage().
+ index.members = index.members.filter((member) => !localObjectMember(index, member));
const methods = new Map(index.members.filter((member) => member.call && ['device', 'utils'].includes(member.namespace))
.map((member) => [member.names.join('.'), member.names]));
for (const control of index.controls) {
@@ -1670,27 +1944,289 @@ function indexSource(text, mask) {
return index;
}
+function localObjectMember(index, member) {
+ // The context is recognized by name (CONTEXT_NAME), so an unrelated object named ctx or context
+ // would read as the PCF context. A call is set aside only when it provably runs a function written
+ // in a local object literal that nothing else can reach or change:
+ // function render() { const ctx = { device: { captureImage() { return 1; } } }; ctx.device.captureImage(); }
+ // A parameter, a field, a call result such as useContext(...) or anything else keeps the name rule,
+ // because it may hold the real context. Proven when all of these hold:
+ // - the context-named root itself holds the namespace (ctx.device, not props.context.device);
+ // - its binding is local to a function or block (not the program, which other scripts share), with
+ // exactly one declaration, `const <root> = { … }`, ending the statement;
+ // - the literal is inert (inertLiteral): static keys, nested inert literals, plain literals and
+ // functions whose body returns only such values, so a call through it runs no other code and
+ // returns nothing from outside it;
+ // - every other use of the binding calls one of those functions through its own keys, such as
+ // ctx.device.captureImage(), and no write reaches the binding: the literal is never passed,
+ // aliased, returned or changed, and no inherited method (ctx.__defineGetter__) is called on it;
+ // - the file has no eval, with statement or unreadable identifier escape, which could reach the
+ // binding without naming it in code.
+ const { tokens } = index;
+ const root = member.names[0];
+ if (root === 'this' || !CONTEXT_NAME.test(root) || member.namespacePath !== `${root}.${member.namespace}`
+ || member.first !== member.token || tokens[member.token]?.kind !== 'identifier') return false;
+ index.dynamicNames ??= tokens.some((token) => token.name === 'eval' || (token.kind === 'unknown-identifier' && !token.name))
+ || index.controls.some((control) => control.kind === 'with');
+ if (index.dynamicNames) return false;
+ const binding = bindingFor(tokens[member.token].scope, root);
+ index.localObjects ||= new Map();
+ const key = `${binding}:${root}`;
+ if (!index.localObjects.has(key)) index.localObjects.set(key, inertConstObject(index, binding, root));
+ return index.localObjects.get(key);
+}
+
+function inertConstObject(index, binding, root) {
+ const { tokens, mask } = index;
+ if (['program', 'opaque'].includes(index.scopes[binding].kind)) return false;
+ const declarations = index.scopes[binding].declarations.get(root) || [];
+ if (declarations.length !== 1) return false;
+ const keyword = tokenIndexAt(tokens, declarations[0]);
+ const name = keyword + 1;
+ const open = keyword + 3;
+ if (!tokenKeyword(tokens, keyword, 'const') || tokens[name]?.kind !== 'identifier' || tokens[name].value !== root
+ || tokens[name + 1]?.value !== '=' || tokens[open]?.value !== '{' || tokens[open].match < 0) return false;
+ const close = tokens[open].match;
+ const after = tokens[close + 1];
+ // `{ … }` must end the initializer: `;`, `,` or `}` next, or a line break before a statement (ASI),
+ // not `as T`, a call or an index that would make the binding something else.
+ if (after && ![';', ',', '}'].includes(after.value) && !(LINE_TERMINATOR.test(mask.slice(tokens[close].end, after.start))
+ && after.kind === 'identifier' && !['as', 'satisfies', 'in', 'instanceof'].includes(after.value))) return false;
+ const members = inertLiteral(index, open);
+ if (!members) return false;
+ index.rootUses ||= rootUses(index);
+ for (const position of index.rootUses.writes.get(`${binding}:${root}`) || []) {
+ if (position !== tokens[name].start) return false;
+ }
+ for (const use of index.rootUses.reads.get(`${binding}:${root}`) || []) {
+ if (use === name) continue;
+ const path = indexedPath(index, use);
+ if (index.rootRoles.get(use) !== 'read' || !path.call || path.unknown || path.names.length < 2) return false;
+ // Every name on the way must be the literal's own: an object up to the last, a function at the end.
+ for (let length = 2; length <= path.names.length; length += 1) {
+ const kind = members.get(path.names.slice(1, length).join('.'));
+ if (kind !== (length === path.names.length ? 'function' : 'object')) return false;
+ }
+ }
+ return true;
+}
+
+function rootUses(index) {
+ // Every occurrence of a context-named root, and every recorded write, grouped by binding and root
+ // name, so proving several bindings costs one pass over the tokens and writes.
+ const reads = new Map();
+ const writes = new Map();
+ for (let i = 0; i < index.tokens.length; i += 1) {
+ const root = trackedRoot(index, i);
+ if (!root || root === 'this' || !CONTEXT_NAME.test(root) || index.patternKeys.has(i)
+ || index.rootRoles.get(i) === 'member') continue;
+ const key = `${bindingFor(index.tokens[i].scope, root)}:${root}`;
+ if (!reads.has(key)) reads.set(key, []);
+ reads.get(key).push(i);
+ }
+ for (const [key, positions] of index.writes) {
+ // Keys are `<binding>:<path>` with an optional `.*`; the root is the path's first name.
+ const separator = key.indexOf(':');
+ const root = key.slice(separator + 1).split('.')[0];
+ const target = `${key.slice(0, separator)}:${root}`;
+ if (!writes.has(target)) writes.set(target, []);
+ writes.get(target).push(...positions);
+ }
+ return { reads, writes };
+}
+
+function inertLiteral(index, open) {
+ // The own members of an inert object literal, by dotted path ('device' → 'object',
+ // 'device.captureImage' → 'function'), or null. Inert means no code in it can run anything else,
+ // read anything from outside it or hand out a reference to it:
+ // - every key is static (a name or a string), not __proto__ and not repeated; no accessor,
+ // spread, shorthand, computed key or generator;
+ // - every value is a nested inert literal, a string, number, true, false or null, an array of
+ // those, or a method, function or arrow expression (async allowed) whose parameters are plain
+ // names and whose body is empty, returns such a value, or (an arrow) is such a value. A body
+ // that names anything at all, this or a parameter included, is refused.
+ // https://tc39.es/ecma262/#sec-object-initializer
+ const { tokens, text } = index;
+ const group = (at, value) => tokens[at]?.value === value && tokens[at].match > at ? tokens[at].match : -1;
+ const literal = (at) => ['string', 'number'].includes(tokens[at]?.kind)
+ || ['true', 'false', 'null'].some((word) => tokenKeyword(tokens, at, word));
+ // A value filling exactly [from, to) that runs nothing and refers to nothing.
+ const inertValue = (from, to) => {
+ if (to - from === 1) return literal(from);
+ if (group(from, '(') === to - 1) return inertValue(from + 1, to - 1);
+ if (group(from, '{') === to - 1) return Boolean(inertLiteral(index, from));
+ if (group(from, '[') !== to - 1) return false;
+ return topLevelTokenRanges(tokens, from + 1, to - 1, ',').every(([a, b]) => a === b || inertValue(a, b));
+ };
+ const parameters = (at) => {
+ const close = group(at, '(');
+ if (close === -1 || close === at + 1) return close;
+ const names = topLevelTokenRanges(tokens, at + 1, close, ',');
+ return names.every(([a, b], i) => (a === b && i === names.length - 1 && i > 0)
+ || (b === a + 1 && tokens[a].kind === 'identifier' && !['this', 'arguments', 'eval'].includes(tokens[a].value)))
+ ? close : -1;
+ };
+ const inertBody = (at, to) => {
+ if (group(at, '{') !== to - 1) return false;
+ let end = to - 1;
+ if (tokens[end - 1]?.value === ';') end -= 1;
+ return end === at + 1 || (tokenKeyword(tokens, at + 1, 'return') && (end === at + 2 || inertValue(at + 2, end)));
+ };
+ // A function or arrow expression filling [from, to).
+ const functionValue = (from, to) => {
+ let at = tokenKeyword(tokens, from, 'async') ? from + 1 : from;
+ if (tokenKeyword(tokens, at, 'function')) {
+ at += 1;
+ if (tokens[at]?.kind === 'identifier') at += 1;
+ const close = parameters(at);
+ return close !== -1 && inertBody(close + 1, to);
+ }
+ const close = tokens[at]?.kind === 'identifier' && !['this', 'arguments', 'eval'].includes(tokens[at].value) ? at : parameters(at);
+ if (close === -1 || tokens[close + 1]?.value !== '=>' || close + 2 >= to) return false;
+ return tokens[close + 2].value === '{' && group(close + 2, '{') === to - 1 ? inertBody(close + 2, to) : inertValue(close + 2, to);
+ };
+ const members = new Map();
+ const pending = [[open, '']];
+ while (pending.length) {
+ const [start, prefix] = pending.pop();
+ const keys = new Set();
+ for (const [from, to] of topLevelTokenRanges(tokens, start + 1, tokens[start].match, ',')) {
+ if (from === to) continue;
+ let at = from;
+ if (tokenKeyword(tokens, at, 'async') && tokens[at + 1]?.value !== '(' && tokens[at + 1]?.value !== ':') at += 1;
+ if (['get', 'set'].some((word) => tokenKeyword(tokens, at, word)) && tokens[at + 1]?.value !== '('
+ && tokens[at + 1]?.value !== ':') return null;
+ const key = tokens[at]?.kind === 'identifier' ? tokens[at].value
+ : tokens[at]?.kind === 'string' ? decodeStaticKey(text.slice(tokens[at].start, tokens[at].end)) : null;
+ if (!key || key === '__proto__' || keys.has(key)) return null;
+ keys.add(key);
+ const path = prefix ? `${prefix}.${key}` : key;
+ const close = parameters(at + 1);
+ if (close !== -1) {
+ if (!inertBody(close + 1, to)) return null;
+ members.set(path, 'function');
+ continue;
+ }
+ if (at !== from || tokens[at + 1]?.value !== ':' || at + 2 >= to) return null;
+ const value = at + 2;
+ if (group(value, '{') === to - 1) {
+ members.set(path, 'object');
+ pending.push([value, path]);
+ } else if (functionValue(value, to)) members.set(path, 'function');
+ else if (!inertValue(value, to)) return null;
+ }
+ }
+ return members;
+}
+
+function tokenIndexAt(tokens, start) {
+ let lo = 0;
+ let hi = tokens.length;
+ while (lo < hi) {
+ const mid = (lo + hi) >>> 1;
+ if (tokens[mid].start < start) lo = mid + 1;
+ else hi = mid;
+ }
+ return lo;
+}
+
function indexedMembers(index) {
- const members = [];
+ // Members are keyed by their root token: a grouped path that reads on past its group replaces the
+ // shorter member at the same root, so (context.utils).lookupObjects() is one use, not two.
+ const members = new Map();
+ const add = (path, first) => {
+ const member = contextMember(path);
+ if (!member) return;
+ member.first = first;
+ if (!member.call && reflectApplyTarget(index, first, member)) member.call = true;
+ members.set(member.token, member);
+ };
for (let i = 0; i < index.tokens.length; i += 1) {
if (!index.tokens[i].name || ['.', '?.'].includes(index.tokens[i - 1]?.value)
|| index.rootRoles?.get(i) === 'member') continue;
- const path = indexedPath(index, i);
- const member = contextMember(path);
- if (member) members.push(member);
+ add(indexedPath(index, i), i);
+ }
+ // Grouping needs the control and container index (a `(` after `if (…)` groups, after a name it
+ // calls), so the first, root-collecting pass reads plain paths only. A guard proof is itself a
+ // plain path, so its root is collected there.
+ if (index.controlCloses) {
+ for (const [path, first] of groupedPaths(index)) {
+ if (index.rootRoles.get(path.token) !== 'member') add(path, first);
+ }
}
- return members;
+ return [...members.values()].sort((a, b) => a.token - b.token);
+}
+
+function groupedPaths(index) {
+ // (context.device).captureImage() and ((context).device).captureImage(): a group that holds only a
+ // member path is that path, so reading continues after the `)`. A `(` that follows an operand calls
+ // it instead (foo(context.device).captureImage() calls whatever foo returns), and a group holding
+ // anything else, such as (0, context.device), is not unwrapped. Each run of directly nested groups
+ // is read once, from its innermost path outwards, so 8000 nested parentheses stay linear.
+ const { tokens } = index;
+ const grouping = (open) => tokens[open]?.value === '(' && tokens[open].match >= 0 && !canEndOperand(index, open - 1)
+ && !callHead(index, open);
+ const paths = [];
+ for (let open = 0; open < tokens.length; open += 1) {
+ if (!grouping(open) || grouping(open - 1)) continue;
+ const run = [open];
+ while (grouping(run.at(-1) + 1)) run.push(run.at(-1) + 1);
+ const root = run.at(-1) + 1;
+ if (!tokens[root]?.name) continue;
+ let path = indexedPath(index, root);
+ for (let level = run.length - 1; level >= 0; level -= 1) {
+ const close = tokens[run[level]].match;
+ if (path.unknown || path.call || path.end !== close) break;
+ path = { ...readMemberPath(index, [...path.names], close + 1), token: root, start: tokens[root].start };
+ paths.push([path, run[level]]);
+ }
+ }
+ return paths;
}
+function callHead(index, open) {
+ // A `(` also calls when it follows an optional-call `?.` or a type-argument list after a callee:
+ // factory?.(context.device).captureImage() calls factory, then a method of its result
+ // factory<T>(context.device).captureImage() TypeScript generic call (likewise obj.m<T>(…))
+ // Neither `(` groups, so the argument is not the receiver of the method after the `)`.
+ // https://tc39.es/ecma262/#prod-OptionalChain and
+ // https://www.typescriptlang.org/docs/handbook/2/generics.html#generic-types
+ const { tokens } = index;
+ const previous = open - 1;
+ if (tokens[previous]?.value === '?.') return true;
+ if (tokens[previous]?.value !== '>') return false;
+ const less = angleBoundary(tokens, previous, -1);
+ return less > 0 && canEndOperand(index, less - 1);
+}
+
+function reflectApplyTarget(index, first, member) {
+ // Reflect.apply(context.device.captureImage, thisArg, args) calls the method it is given as its first
+ // argument. https://tc39.es/ecma262/#sec-reflect.apply
+ const { tokens } = index;
+ const open = first - 1;
+ return member.names.length === member.methodPath.split('.').length && !member.unknown
+ && tokens[open]?.value === '(' && tokens[open - 1]?.kind === 'identifier' && tokens[open - 1].value === 'apply'
+ && tokens[open - 2]?.value === '.'
+ && tokenKeyword(tokens, open - 3, 'Reflect')
+ && (tokens[member.end]?.value === ',' || member.end === tokens[open].match);
+}
+
+// `.call(`, `.apply(` and `.bind(` on a method invoke it with another `this` (binding returns a copy
+// whose only use is to be called). https://tc39.es/ecma262/#sec-properties-of-the-function-prototype-object
+const DISPATCH_METHODS = new Set(['call', 'apply', 'bind']);
+
function contextMember(path) {
// Only the name immediately before the namespace matters: props.context.device
// and this._ctx.utils count, but this.state.device and helpers.utils do not.
const namespaceIndex = path.names.findIndex((name, i) => i > 0 && CONTEXT_NAMESPACES.has(name) && CONTEXT_NAME.test(path.names[i - 1]));
if (namespaceIndex < 0) return null;
- return { ...path, namespace: path.names[namespaceIndex], method: path.names[namespaceIndex + 1],
+ const methodEnd = namespaceIndex + 2;
+ const dispatch = path.names.length === methodEnd + 1 && DISPATCH_METHODS.has(path.names[methodEnd]);
+ const names = dispatch ? path.names.slice(0, methodEnd) : path.names;
+ return { ...path, names, namespace: path.names[namespaceIndex], method: path.names[namespaceIndex + 1],
namespacePath: path.names.slice(0, namespaceIndex + 1).join('.'),
- methodPath: path.names.slice(0, namespaceIndex + 2).join('.'),
- call: path.call && !path.unknown && path.names.length === namespaceIndex + 2 };
+ methodPath: path.names.slice(0, methodEnd).join('.'),
+ call: path.call && !path.unknown && (path.names.length === methodEnd || dispatch) };
}
function skipSourceSpace(mask, start) {
@@ -1703,7 +2239,8 @@ function fallbackMembers(text, mask) {
// Read each reference once, advancing past consumed members, on the blanked mask:
// props.context?.device["captureImage"]!!()
// Quoted static keys are decoded from the original offsets, never evaluated.
- // No delimiter, scope, declaration or guard analysis is retried here.
+ // No delimiter, scope, declaration or guard analysis is retried here. A group that holds only a
+ // path is read through, (context.device).captureImage(), and Reflect.apply(<method>, …) is a call.
const roots = new RegExp(`${IDENTIFIER.source}|\\\\`, 'gu');
const members = [];
let match;
@@ -1712,42 +2249,97 @@ function fallbackMembers(text, mask) {
if (!root) continue;
roots.lastIndex = root.end;
if (!root.name || previousNonSpace(mask, match.index) === '.') continue;
- const names = [root.name];
- let end = root.end;
- let unknown = false;
- while (end < mask.length) {
- let next = skipSourceSpace(mask, end);
- let asserted = next;
- while (mask[asserted] === '!') asserted = skipSourceSpace(mask, asserted + 1);
- if (['.', '[', '('].includes(mask[asserted]) || mask.startsWith('?.', asserted)) next = asserted;
- let member = next;
- if (mask.startsWith('?.', member)) member = skipSourceSpace(mask, member + 2);
- else if (mask[member] === '.') member = skipSourceSpace(mask, member + 1);
- else if (mask[member] !== '[') { end = next; break; }
- if (mask[member] === '[') {
- const keyStart = skipSourceSpace(mask, member + 1);
- const quoted = ['"', "'"].includes(mask[keyStart]) ? readQuotedLiteral(mask, keyStart) : null;
- const close = quoted && skipSourceSpace(mask, quoted.end);
- if (!quoted || mask[close] !== ']') { unknown = true; end = member; break; }
- const key = decodeStaticKey(text.slice(keyStart, quoted.end));
- end = close + 1;
- if (!key) { unknown = true; break; }
- names.push(key);
- } else {
- const name = member !== next && sourceIdentifierAt(mask, member);
- if (!name?.name) { end = next; break; }
- names.push(name.name);
- end = name.end;
- }
+ let path = readFallbackPath(text, mask, [root.name], root.end);
+ let first = match.index;
+ for (;;) {
+ const open = previousNonSpaceIndex(mask, first);
+ const close = skipSourceSpace(mask, path.end);
+ if (path.unknown || path.call || mask[open] !== '(' || mask[close] !== ')' || !fallbackGrouping(mask, open)) break;
+ path = readFallbackPath(text, mask, path.names, close + 1);
+ first = open;
+ }
+ const member = contextMember({ names: path.names, start: match.index, unknown: path.unknown, call: path.call });
+ if (member && !member.call && member.names.length === member.methodPath.split('.').length && !member.unknown) {
+ const open = previousNonSpaceIndex(mask, first);
+ const after = mask[skipSourceSpace(mask, path.end)];
+ member.call = mask[open] === '(' && /(?:^|[^$\w.])Reflect\s*\.\s*apply\s*$/.test(mask.slice(Math.max(0, open - 64), open))
+ && (after === ',' || after === ')');
}
- const call = mask[end] === '(' || (mask.startsWith('?.', end) && mask[skipSourceSpace(mask, end + 2)] === '(');
- const member = contextMember({ names, start: match.index, unknown, call });
if (member) members.push(member);
- roots.lastIndex = Math.max(roots.lastIndex, end);
+ roots.lastIndex = Math.max(roots.lastIndex, path.end);
}
return members;
}
+function readFallbackPath(text, mask, names, end) {
+ let unknown = false;
+ while (end < mask.length) {
+ let next = skipSourceSpace(mask, end);
+ let asserted = next;
+ while (mask[asserted] === '!') asserted = skipSourceSpace(mask, asserted + 1);
+ if (['.', '[', '('].includes(mask[asserted]) || mask.startsWith('?.', asserted)) next = asserted;
+ let member = next;
+ if (mask.startsWith('?.', member)) member = skipSourceSpace(mask, member + 2);
+ else if (mask[member] === '.') member = skipSourceSpace(mask, member + 1);
+ else if (mask[member] !== '[') { end = next; break; }
+ if (mask[member] === '[') {
+ const keyStart = skipSourceSpace(mask, member + 1);
+ let keyEnd = -1;
+ let key = null;
+ if (['"', "'"].includes(mask[keyStart])) {
+ const quoted = readQuotedLiteral(mask, keyStart);
+ keyEnd = quoted ? quoted.end : -1;
+ if (quoted) key = decodeStaticKey(text.slice(keyStart, quoted.end));
+ } else if (mask[keyStart] === TEMPLATE_QUOTE) {
+ keyEnd = templateEnd(text, keyStart);
+ if (keyEnd !== -1) key = decodeTemplateKey(text.slice(keyStart, keyEnd));
+ }
+ const close = keyEnd === -1 ? -1 : skipSourceSpace(mask, keyEnd);
+ if (close === -1 || mask[close] !== ']') { unknown = true; end = member; break; }
+ end = close + 1;
+ if (!key) { unknown = true; break; }
+ names.push(key);
+ } else {
+ const name = member !== next && sourceIdentifierAt(mask, member);
+ if (!name?.name) { end = next; break; }
+ names.push(name.name);
+ end = name.end;
+ }
+ }
+ const call = mask[end] === '(' || (mask.startsWith('?.', end) && mask[skipSourceSpace(mask, end + 2)] === '(');
+ return { names, end, unknown, call };
+}
+
+function templateEnd(text, start) {
+ // End (exclusive) of the template literal opened at `start`, or -1 when it holds a substitution.
+ for (let i = start + 1; i < text.length; i += 1) {
+ if (text[i] === '\\') i += 1;
+ else if (text[i] === TEMPLATE_QUOTE) return i + 1;
+ else if (text[i] === '$' && text[i + 1] === '{') return -1;
+ }
+ return -1;
+}
+
+function previousNonSpaceIndex(text, index) {
+ for (let i = index - 1; i >= 0; i -= 1) {
+ if (!/\s/.test(text[i])) return i;
+ }
+ return -1;
+}
+
+function fallbackGrouping(mask, open) {
+ // A `(` groups unless it follows an operand, which it then calls: foo(context.device).x is foo's
+ // result. After a keyword such as return or typeof an operand starts, so the `(` groups.
+ const before = previousNonSpaceIndex(mask, open);
+ if (before === -1) return true;
+ // factory?.(context.device) is an optional call: its argument is not a receiver.
+ if (mask[before] === '.' && mask[before - 1] === '?') return false;
+ if (!IDENTIFIER_CONTINUE.test(mask[before]) && !/[)\]"'`]/.test(mask[before])) return true;
+ const word = /[$\w]+$/.exec(mask.slice(Math.max(0, before - 16), before + 1));
+ return Boolean(word) && ['return', 'typeof', 'await', 'void', 'yield', 'case', 'throw', 'in', 'of', 'new', 'delete', 'else', 'do']
+ .includes(word[0]) && previousNonSpace(mask, before + 1 - word[0].length) !== '.';
+}
+
function firstAtOrAfter(positions, start) {
let lo = 0;
let hi = positions.length;
diff --git a/plugins/pcf/scripts/lib/source-literals.js b/plugins/pcf/scripts/lib/source-literals.js
index 7ccd3bcf7..e159051b8 100644
--- a/plugins/pcf/scripts/lib/source-literals.js
+++ b/plugins/pcf/scripts/lib/source-literals.js
@@ -4077,8 +4077,10 @@ const EXPORTED_MEMBER_CHAIN = new RegExp(String.raw`^([\p{ID_Start}$_][\p{ID_Con
const PARENTHESISED_FUNCTION_OR_CLASS = new RegExp(String.raw`^\(${WS}*(?:async${WS}+)?(?:function|class)\b`);
const RETURN_TYPE_COLON = new RegExp(String.raw`^${WS}*:`);
const DANGLING_CAST = new RegExp(String.raw`(?<![\p{ID_Continue}$])(?:as|satisfies|keyof)${WS}*$`, 'u');
-function hasDefaultExport(code) {
- const bare = blankLiterals(code);
+function hasDefaultExport(code, views = null) {
+ // `views`, when given, are a parser's views of the page in this file's format (typescript-views.js in model-apps: page-structure.js passes them where the lexer
+ // guessed): its literal view stands for blankLiterals(code).
+ const bare = views && typeof views.literal === 'string' ? views.literal : blankLiterals(code);
if (NAMED_DEFAULT_EXPORT.test(bare)) return true;
// Any complete one will do: TypeScript overloads declare the signature(s) before the body —
// export default function f(x: string): string;
@@ -4200,15 +4202,26 @@ function genericArrowIsComplete(rest) {
if (open.kind !== '(') return false;
const parametersEnd = typeGroupEnd(rest, open.start);
if (parametersEnd === -1) return false;
+ // Where reading a generic call's type arguments in a default value changes the reading (returnTypeEnd, defaultValueEnd), the page must be complete both ways: that
+ // reading finds the cut right after a function type with such a parameter (`({ a = f<T, U>() }) => T`), and only ever refuses more — a value that TypeScript reads
+ // and Babel refuses (`await f<T, U>()` in a parameter, `f<T, U>(010)`) cannot make a page pass that the reading to the first `,` refused.
+ const options = { typeArgumentsInDefaults: true };
+ if (!arrowFollows(rest, parametersEnd, options)) return false;
+ if (options.typeArgumentsRead && !arrowFollows(rest, parametersEnd, { typeArgumentsInDefaults: false })) return false;
+ // The body is taken as written, as any exported expression is (its brackets are checked separately), unless the file stops at a token that needs more: `p +`, `p as`.
+ return !DANGLING_TAIL.test(rest) && !DANGLING_CAST.test(rest);
+}
+
+// Whether the arrow's `=>` and a body follow the parameter list that ends at `parametersEnd` in `rest` — at once, or after a return type read to its end (returnTypeEnd,
+// with `options`).
+function arrowFollows(rest, parametersEnd, options) {
let arrow = typeTokenAt(rest, parametersEnd);
if (arrow.kind === ':') {
- const returnEnd = returnTypeEnd(rest, arrow.end);
+ const returnEnd = returnTypeEnd(rest, arrow.end, options);
if (returnEnd === -1) return false;
arrow = typeTokenAt(rest, returnEnd);
}
- if (arrow.kind !== '=>' || !startsArrowBody(typeTokenAt(rest, arrow.end))) return false;
- // The body is taken as written, as any exported expression is (its brackets are checked separately), unless the file stops at a token that needs more: `p +`, `p as`.
- return !DANGLING_TAIL.test(rest) && !DANGLING_CAST.test(rest);
+ return arrow.kind === '=>' && startsArrowBody(typeTokenAt(rest, arrow.end));
}
// What begins an arrow's body: a block, or what begins an expression — a name, any word but those that only begin a statement (a keyword that begins an expression, `this`,
@@ -4318,8 +4331,14 @@ const RETURN_TYPE_DEPTH = 200;
// type, `(p): (A | B) => …` a parenthesised type and then the arrow, and `(p): ({ a: T }) => p` a function type that takes the arrow's `=>` (an error);
// - type arguments, `[`, `extends`, `is` and an assertion's name continue a type only on its line; a function or constructor type after `|` or `&` is an error (TS1385, TS1388);
// - the JSDoc forms TypeScript's parser takes in a .tsx file and only its checker refuses (`?T`, `T?`, `!T`, `T!`, `*`, `function(…): T`) are read too.
-function returnTypeEnd(src, from) {
+// `options.typeArgumentsInDefaults` (true unless false) says whether a generic call's type arguments in a default value are passed over (defaultValueEnd), and
+// `options.typeArgumentsRead` is set where that changed what a default value holds.
+function returnTypeEnd(src, from, options = {}) {
+ if (options.typeArgumentsInDefaults === undefined) options.typeArgumentsInDefaults = true;
let depth = 0;
+ // Above zero while a type is read STRICTLY (typeArgumentsInExpressionEnd): a group in it — parentheses, brackets, braces, angle brackets — is read, not passed over
+ // whole; what this reading does not read through (a function type's parameters, an object type with members, a template, an import type) ends it with -1.
+ let strictly = 0;
const at = (k) => typeTokenAt(src, k);
const isWord = (token, text) => token.kind === 'word' && token.text === text;
// isIdentifier: a word that is no reserved word, nor `await`, which parseExportAssignment makes a keyword in an export.
@@ -4349,7 +4368,7 @@ function returnTypeEnd(src, from) {
// parseType: a function or constructor type, or a union and, on its line, `extends` and the rest of a conditional type — where conditional types are allowed: not in the
// `extends` clause of one (`noConditional`).
const type = (k, noConditional) => nested(() => {
- if (startsFunctionType(k)) return functionType(k);
+ if (startsFunctionType(k)) return strictly ? -1 : functionType(k);
const end = unionOrIntersection(k, '|', noConditional);
if (end === -1 || noConditional) return end;
const ext = at(end);
@@ -4390,9 +4409,8 @@ function returnTypeEnd(src, from) {
return after.kind === ')' && at(after.end).kind === '=>';
};
// parseObjectBindingPattern and parseArrayBindingPattern, whose `{` or `[` is at `open`: the index just past the pattern, or -1 where it does not parse with no error. A
- // default value is passed over to the `,` or the bracket that ends it (defaultValueEnd) — a known limit: the comma between a generic call's type arguments,
- // `{ a = f<T, U>() }`, is taken for the end of the value, the pattern reads as none, and a write cut right after a function type with such a parameter is accepted
- // (AGENTS.md, "TSX source lexer — known limits"; the page compile refuses it).
+ // default value is passed over to the `,` or the bracket that ends it (defaultValueEnd), a generic call's type arguments included: the comma in `{ a = f<T, U>() }` is
+ // the call's, the pattern is read, and a write cut right after a function type with such a parameter has no arrow.
const bindingPatternEnd = (open) => nested(() => {
const object = src[open] === '{';
const closer = object ? '}' : ']';
@@ -4441,7 +4459,13 @@ function returnTypeEnd(src, from) {
// parenthesised type and the arrow, where `({ [key]: v }) => …` and `({ [K in T]: v }) => …` (`K in T` is an expression) hold a function type's parameters. The
// expression is read only as far as that needs — operands, prefix and binary operators, `?` and `:`, member access, calls, indexes, `!`, type arguments where they close and
// what follows can follow them (canFollowTypeArgumentsInExpression), and a type after `as` or `satisfies` — and what it does not know (an arrow, `function`, a regex, JSX)
- // is taken for no expression: a type then, never a function type's parameters, so the reading can let a page TypeScript refuses through but never refuse one it parses.
+ // is taken for no expression: a type then, never a function type's parameters.
+ // Two readings here part from TypeScript's on purpose, rare known limits (AGENTS.md, "TSX source lexer — known limits"; pinned in source-literals.test.js): a group
+ // counts as an operand whatever it holds, so `K in (keyof T)` reads as an expression and `({ [K in (keyof T)]: boolean })` as a function type's parameters, where
+ // TypeScript reads a parenthesised mapped type; and a key that starts with a regular expression (`[/key/.source]`) is taken for no expression, where TypeScript reads
+ // one. Reading either as TypeScript does would turn a refusal into an acceptance on the strength of tokens this reading does not check as the parsers do — an escaped
+ // keyword, a legacy octal number or a string escape in the mapped type, a regular expression's flags (Babel refuses an unknown or repeated one that TypeScript's parser
+ // takes) — and a page either parser refuses would pass.
const computedKeyIsExpression = (open) => {
const close = typeGroupEnd(src, open);
if (close === -1) return false;
@@ -4500,7 +4524,18 @@ function returnTypeEnd(src, from) {
}
}
};
+ // A default value, from right after its `=` at `k`: the index of the `,` or the `closer` that ends it at its own level, or -1. A group in brackets, a string and a
+ // template are passed over whole, and so is a list of type arguments after an operand where TypeScript's parser takes one — `{ a = f<T, U>() }` holds one default, whose
+ // `,` is no element's (typeArgumentsInExpressionEnd) — unless `options.typeArgumentsInDefaults` is false: the value then ends at its first `,`, as JavaScript reads it.
+ // Where the two readings part, `options.typeArgumentsRead` says so (genericArrowIsComplete).
const defaultValueEnd = (k, closer) => {
+ const plain = defaultValueEndReading(k, closer, false);
+ if (!options.typeArgumentsInDefaults) return plain;
+ const read = defaultValueEndReading(k, closer, true);
+ if (read !== plain) options.typeArgumentsRead = true;
+ return read;
+ };
+ const defaultValueEndReading = (k, closer, typeArguments) => {
for (let j = k; j < src.length; j += 1) {
const c = src[j];
if (c === ',' || c === closer) return j;
@@ -4513,9 +4548,58 @@ function returnTypeEnd(src, from) {
if (end === -1) return -1;
j = end - 1;
} else if (c === ')' || c === ']' || c === '}') return -1;
+ else if (typeArguments && c === '<' && operandEndsBefore(k, j)) {
+ const end = typeArgumentsInExpressionEnd(j, closer);
+ if (end !== -1) j = end - 1;
+ }
}
return -1;
};
+ // Whether the text of a default value from `from` to the `<` at `at` ends in an operand that type arguments may follow (parseMemberExpressionRest and
+ // parseCallExpressionRest try them after one): a name — or a keyword read as a property name after a `.`, or one that is a value — a number, a string, a template, or a
+ // `)` or `]`. After an operator, `as`, `satisfies`, `await` or `yield` a `<` begins an element, a generic arrow or a type, and nothing is passed over.
+ const operandEndsBefore = (from, at) => {
+ let p = at - 1;
+ while (p >= from && isTrivia(src[p])) p -= 1;
+ if (p < from) return false;
+ const c = src[p];
+ if (c === ')' || c === ']' || c === '"' || c === "'" || c === '`') return true;
+ if (!/[\p{ID_Continue}$\u200c\u200d]/u.test(c)) return false;
+ let w = p;
+ while (w > from && /[\p{ID_Continue}$\u200c\u200d]/u.test(src[w - 1])) w -= 1;
+ const word = src.slice(w, p + 1);
+ let q = w - 1;
+ while (q >= from && isTrivia(src[q])) q -= 1;
+ if (q >= from && src[q] === '.') return true;
+ if (/^[0-9]/.test(word)) return true;
+ if ((RESERVED_WORDS.has(word) || word === 'const') && !['this', 'null', 'true', 'false', 'super'].includes(word)) return false;
+ return !['as', 'satisfies', 'await', 'yield'].includes(word);
+ };
+ // parseTypeArgumentsInExpression, from the `<` at `open` in a default value that `closer` ends: types with a `,` between them and maybe after the last, each read
+ // strictly to its end (TypeScript keeps a list whose types hold an error, and the pattern then fails: only a list it parses whole is passed over), the `>`, then what
+ // lets the list stand — a `(` (a call), a template (a tagged one), or the `,` or the `closer` that ends the value (an instantiation expression:
+ // canFollowTypeArgumentsInExpression takes a token that starts no expression). The index just past the `>`, or -1 where the parser would read a comparison, or this
+ // reading cannot say: the value is then read as before, to the first `,` at its level.
+ const typeArgumentsInExpressionEnd = (open, closer) => {
+ strictly += 1;
+ try {
+ let next = at(open + 1);
+ for (;;) {
+ const end = type(next.start, false);
+ if (end === -1) return -1;
+ next = at(end);
+ if (next.kind === ',') {
+ next = at(next.end);
+ if (next.kind !== '>') continue;
+ }
+ if (next.kind !== '>') return -1;
+ const after = at(next.end);
+ return after.kind === '(' || after.kind === 'template' || after.kind === ',' || after.kind === closer ? next.end : -1;
+ }
+ } finally {
+ strictly -= 1;
+ }
+ };
// parseFunctionOrConstructorType: [`abstract`] [`new`] [type parameters] parameters `=>` and a return type.
const functionType = (k) => {
let token = at(k);
@@ -4562,7 +4646,7 @@ function returnTypeEnd(src, from) {
if (token.newline) return end;
if (token.kind === '!') end = token.end;
else if (token.kind === '?' && !startsType(token.end, 0)) end = token.end;
- else if (token.kind === '[') end = typeGroupEnd(src, token.start);
+ else if (token.kind === '[') end = strictly ? strictBracketEnd(token, true) : typeGroupEnd(src, token.start);
else return end;
}
return -1;
@@ -4584,8 +4668,10 @@ function returnTypeEnd(src, from) {
const token = at(k);
switch (token.kind) {
case 'word': return wordType(token, k);
- case 'string': case 'template': case 'number': case '*': return token.end;
- case '{': case '[': case '(': return typeGroupEnd(src, token.start);
+ case 'string': case 'number': case '*': return token.end;
+ // A template's substitutions are blank here, so a strict reading cannot say what they hold.
+ case 'template': return strictly ? -1 : token.end;
+ case '{': case '[': case '(': return strictly ? strictGroupEnd(token) : typeGroupEnd(src, token.start);
// reScanAsteriskEqualsToken and reScanQuestionToken: `*=` is a `*` and then `=`, `??` two `?`.
case '*=': return token.start + 1;
case '??': return jsdocNullable(token.start + 1);
@@ -4616,6 +4702,7 @@ function returnTypeEnd(src, from) {
// parseJSDocFunctionType: `function(…)` and maybe `: type`; `function` alone is a name.
const open = at(token.end);
if (open.kind !== '(') return token.end;
+ if (strictly) return -1;
const end = typeGroupEnd(src, open.start);
return end !== -1 && at(end).kind === ':' ? typeOrPredicate(at(end).end) : end;
}
@@ -4655,8 +4742,8 @@ function returnTypeEnd(src, from) {
const typeArgumentsOnLine = (end, required) => {
const open = at(end);
if (open.kind !== '<' || open.newline) return end;
- const close = typeAnglesEnd(src, open.start);
- return close !== -1 ? close : required ? -1 : end;
+ const close = strictly ? strictTypeArgumentsEnd(open) : typeAnglesEnd(src, open.start);
+ return close !== -1 ? close : required || strictly ? -1 : end;
};
// parseTypeQuery, after `typeof`: a name, then type arguments on its line.
const typeQuery = (k) => {
@@ -4665,11 +4752,50 @@ function returnTypeEnd(src, from) {
};
// parseImportType, from its `import`: `import(…)`, then maybe `.` and a name, then type arguments on the line.
const importType = (k) => {
+ if (strictly) return -1;
const open = at(at(k).end);
let end = open.kind === '(' ? typeGroupEnd(src, open.start) : -1;
if (end !== -1 && at(end).kind === '.') end = entityName(at(end).end);
return end === -1 ? -1 : typeArgumentsOnLine(end, true);
};
+ // The strict readings of a group (`strictly` above zero), each the index just past it where TypeScript parses the whole of it, or -1. parseParenthesizedType: a type and
+ // the `)`. parseTupleType (`index` false): no element, or types with a `,` between them and maybe after the last (a named or rest element is not read). An array or an
+ // indexed access after a type (`index` true): nothing, or one type. parseTypeLiteral: `{}` alone. parseTypeArgumentsOfTypeReference: types with a `,` between them and
+ // maybe after the last, then the `>` (TypeScript parses `[A, B,]` and `T<U,>`).
+ const strictGroupEnd = (token) => {
+ if (token.kind === '(') {
+ const end = type(token.end, false);
+ return end !== -1 && at(end).kind === ')' ? at(end).end : -1;
+ }
+ if (token.kind === '[') return strictBracketEnd(token, false);
+ const close = at(token.end);
+ return close.kind === '}' ? close.end : -1;
+ };
+ const strictBracketEnd = (token, index) => {
+ let next = at(token.end);
+ if (next.kind === ']') return next.end;
+ for (;;) {
+ const end = type(next.start, false);
+ if (end === -1) return -1;
+ next = at(end);
+ if (next.kind === ']') return next.end;
+ if (index || next.kind !== ',') return -1;
+ next = at(next.end);
+ if (next.kind === ']') return next.end;
+ }
+ };
+ const strictTypeArgumentsEnd = (open) => {
+ let next = at(open.end);
+ for (;;) {
+ const end = type(next.start, false);
+ if (end === -1) return -1;
+ next = at(end);
+ if (next.kind === '>') return next.end;
+ if (next.kind !== ',') return -1;
+ next = at(next.end);
+ if (next.kind === '>') return next.end;
+ }
+ };
return typeOrPredicate(from);
}
@@ -4836,8 +4962,8 @@ function hasDeclarationBody(rest, from) {
* and `/\(/` do not count). `<` / `>` are never counted: JSX and TypeScript generics make them
* legitimately unbalanced.
*/
-function hasUnbalancedBrackets(code) {
- const bare = blankLiterals(code);
+function hasUnbalancedBrackets(code, views = null) {
+ const bare = views && typeof views.literal === 'string' ? views.literal : blankLiterals(code);
const stack = [];
const pairs = { ')': '(', ']': '[', '}': '{' };
for (const ch of bare) {
@@ -4861,7 +4987,12 @@ const DANGLING_TAIL = new RegExp(String.raw`(?:=>|\?\.|[.,?:=&|^~*%<]|(?<!\+)\+|
* export default () => <div>Loading const note = `unfinished const total = count *
* so hasUnbalancedBrackets cannot see these cuts. A complete module ends in plain code.
*/
-function endsMidStatement(code) {
+function endsMidStatement(code, views = null) {
+ // A parser's views (see hasDefaultExport) come from a parse with no diagnostic, which stops inside no string, template, comment or JSX element; what is left to
+ // ask is the token the file ends on, read from its literal view and the ends of its regexes and JSX tags.
+ if (views && typeof views.literal === 'string') {
+ return DANGLING_TAIL.test(views.literal) || hasDanglingFinalOperator(views.literal.split(''), views.regexEnds, views.jsxTagEnds);
+ }
const src = String(code || '');
const out = src.split('');
const regexEnds = new Set();
@@ -4917,9 +5048,11 @@ const BARE_ELLIPSIS_LINE = new RegExp(String.raw`^${WS_SINGLE_LINE}*(\.\.\.|…)
* @param {string} code
* @returns {string|null}
*/
-function findElisionMarker(code) {
+function findElisionMarker(code, views = null) {
const src = String(code || '');
- for (const { text } of commentRanges(src)) {
+ // A parser's views (see hasDefaultExport) carry the page's comments and its executable view.
+ const parsed = views && typeof views.keep === 'string' && Array.isArray(views.comments);
+ for (const { text } of parsed ? views.comments : commentRanges(src)) {
// The comment without its delimiters, or a JSDoc block's leading `*` on each line — so
// /**
// * TODO implement save
@@ -4943,7 +5076,7 @@ function findElisionMarker(code) {
// always fails closed as a placeholder. The text alone cannot reliably distinguish every legal
// multiline spread/rest from an elided block without a full parser, so generated code must write
// the spread and operand together: `...rows`, not `...` followed by `rows` on the next line.
- if (bareEllipsisElidesCode(blankNonCodePreservingTemplateExpressions(src))) return 'a bare `...` line standing in for code';
+ if (bareEllipsisElidesCode(parsed ? views.keep : blankNonCodePreservingTemplateExpressions(src))) return 'a bare `...` line standing in for code';
return null;
}
diff --git a/plugins/pcf/scripts/tests/pcf-intent.test.js b/plugins/pcf/scripts/tests/pcf-intent.test.js
index 41b3249de..f99accb54 100644
--- a/plugins/pcf/scripts/tests/pcf-intent.test.js
+++ b/plugins/pcf/scripts/tests/pcf-intent.test.js
@@ -7,7 +7,7 @@ const os = require('node:os');
const path = require('node:path');
const { assertGolden } = require('./helpers/golden.js');
const { loadCli } = require('./helpers/cli-harness.js');
-const { parseManifest } = require('../lib/pcf-manifest.js');
+const { parseManifest, lintManifest } = require('../lib/pcf-manifest.js');
const { planScaffold } = require('../lib/pcf-scaffold.js');
const {
@@ -53,16 +53,6 @@ function exampleIntent(overrides = {}) {
};
}
-function matrix(overrides = {}) {
- return {
- hosts: {
- pages: { fieldTypes: ['Whole.None', 'SingleLine.Text'] },
- },
- unsupportedPropertyTypes: ['File', 'Image'],
- ...overrides,
- };
-}
-
function manifestModel(overrides = {}) {
return {
control: { controlType: 'standard' },
@@ -358,7 +348,7 @@ test('lintBindingIntent reports PCF_INTENT_QC_SUBGRID', () => {
target: { controlId: 'Contacts', table: 'contact', view: 'Active Contacts', relationship: 'account_contact' },
parameters: { records: { dataset: { name: 'records', propertySets: [{ name: 'email', column: 'emailaddress1' }] } } },
}],
- }), { manifestModel: manifestModel(), matrix: matrix() });
+ }), { manifestModel: manifestModel() });
assertFinding(findings, 'PCF_INTENT_QC_SUBGRID', 'error');
});
@@ -376,7 +366,7 @@ test('lintBindingIntent reports PCF_INTENT_PAGES_MULTI_FIELD', () => {
max: { column: 'new_maxrating' },
},
}],
- }), { manifestModel: manifestModel(), matrix: matrix() });
+ }), { manifestModel: manifestModel() });
assertFinding(findings, 'PCF_INTENT_PAGES_MULTI_FIELD', 'error');
});
@@ -384,7 +374,7 @@ test('lintBindingIntent reports PCF_INTENT_PAGES_MULTI_FIELD', () => {
test('lintBindingIntent reports PCF_INTENT_PAGES_NEEDS_WEB', () => {
const findings = lintBindingIntent(exampleIntent({
bindings: [{ ...exampleIntent().bindings[0], clients: ['phone'] }],
- }), { manifestModel: manifestModel(), matrix: matrix() });
+ }), { manifestModel: manifestModel() });
assertFinding(findings, 'PCF_INTENT_PAGES_NEEDS_WEB', 'error');
});
@@ -392,7 +382,6 @@ test('lintBindingIntent reports PCF_INTENT_PAGES_NEEDS_WEB', () => {
test('lintBindingIntent reports PCF_INTENT_PAGES_VIRTUAL from the manifest model', () => {
const findings = lintBindingIntent(exampleIntent(), {
manifestModel: manifestModel({ control: { controlType: 'virtual' } }),
- matrix: matrix(),
});
assertFinding(findings, 'PCF_INTENT_PAGES_VIRTUAL', 'error');
@@ -401,17 +390,33 @@ test('lintBindingIntent reports PCF_INTENT_PAGES_VIRTUAL from the manifest model
test('lintBindingIntent reports PCF_INTENT_PAGES_VIRTUAL from the intent template when no manifest is supplied', () => {
const findings = lintBindingIntent(exampleIntent({
control: { ...exampleIntent().control, template: 'field-virtual' },
- }), { matrix: matrix() });
+ }));
assertFinding(findings, 'PCF_INTENT_PAGES_VIRTUAL', 'error');
});
test('lintBindingIntent does not reuse PCF_INTENT_PAGES_VIRTUAL for field-type policy checks', () => {
- const findings = lintBindingIntent(exampleIntent({
- properties: [{ name: 'value', usage: 'bound', type: 'File', required: true }],
- }), { matrix: matrix() });
+ // The Pages field-type policy is the manifest lint's, read from the shipped compatibility matrix:
+ // a File column bound on a standard control is reported there under its own codes. The intent lint
+ // must not report the same control as a virtual one; a virtual manifest shows the code it would use.
+ const fileBound = parseManifest([
+ '<?xml version="1.0" encoding="utf-8" ?>',
+ '<manifest><control namespace="Contoso.Controls" constructor="StarRating" version="1.0.0"',
+ ' display-name-key="StarRating" description-key="StarRating" control-type="standard">',
+ '<property name="value" display-name-key="value" of-type="File" usage="bound" required="true" />',
+ '<resources><code path="index.ts" order="1" /></resources></control></manifest>',
+ ].join(''));
+ assert.deepEqual(fileBound.errors || [], []);
+ const policy = lintManifest(fileBound.model, { hosts: ['pages'] });
+ assert.deepEqual(codes(policy.errors).sort(), ['PCF_PAGES_FIELD_TYPE', 'PCF_TYPE_UNSUPPORTED']);
- assert.ok(!findings.some((finding) => finding.code === 'PCF_INTENT_PAGES_VIRTUAL'));
+ const intent = exampleIntent({
+ properties: [{ name: 'value', usage: 'bound', type: 'File', required: true }],
+ bindings: [{ ...exampleIntent().bindings[0], parameters: { value: { column: 'new_rating' } } }],
+ });
+ assert.deepEqual(codes(lintBindingIntent(intent, { manifestModel: fileBound.model })), []);
+ const virtual = { ...fileBound.model, control: { ...fileBound.model.control, controlType: 'virtual' } };
+ assert.deepEqual(codes(lintBindingIntent(intent, { manifestModel: virtual })), ['PCF_INTENT_PAGES_VIRTUAL']);
});
test('lintBindingIntent blocks Pages dataset templates without a manifest or bindings', () => {
@@ -452,7 +457,7 @@ test('lintBindingIntent reports PCF_INTENT_PARAM_UNKNOWN', () => {
...exampleIntent().bindings[0],
parameters: { value: { column: 'new_rating' }, unexpected: { static: 'x', type: 'SingleLine.Text' } },
}],
- }), { manifestModel: manifestModel(), matrix: matrix() });
+ }), { manifestModel: manifestModel() });
assertFinding(findings, 'PCF_INTENT_PARAM_UNKNOWN', 'error');
});
@@ -478,7 +483,6 @@ test('lintBindingIntent reports PCF_INTENT_BOUND_NOT_MAPPED but exempts grid Eve
{ name: 'EventName', usage: 'bound', required: true },
],
}),
- matrix: matrix(),
});
assertFinding(missing, 'PCF_INTENT_BOUND_NOT_MAPPED', 'error');
@@ -496,14 +500,13 @@ test('lintBindingIntent reports PCF_INTENT_BOUND_NOT_MAPPED but exempts grid Eve
}],
}), {
manifestModel: manifestModel({ properties: [{ name: 'EventName', usage: 'bound', required: true }] }),
- matrix: matrix(),
});
assert.ok(!codes(grid).includes('PCF_INTENT_BOUND_NOT_MAPPED'));
});
test('lintBindingIntent no longer guides unsupported Pages list setup', () => {
const intent = exampleIntent({ pages: { journeys: ['list'] } });
- const findings = lintBindingIntent(intent, { manifestModel: manifestModel(), matrix: matrix() });
+ const findings = lintBindingIntent(intent, { manifestModel: manifestModel() });
assert.ok(!codes(findings).includes('PCF_INTENT_LIST_NEEDS_VIEW_CONFIG'));
assert.doesNotMatch(renderPlanMarkdown(intent, { lint: findings }), /List: configure|verify the rendered dataset/);
});
diff --git a/plugins/pcf/scripts/tests/pcf-pages-guard.test.js b/plugins/pcf/scripts/tests/pcf-pages-guard.test.js
index 696477af8..cf4b1caf0 100644
--- a/plugins/pcf/scripts/tests/pcf-pages-guard.test.js
+++ b/plugins/pcf/scripts/tests/pcf-pages-guard.test.js
@@ -313,6 +313,10 @@ for (const [name, relative] of [
assert.match(text, /aliasing[^.\n]*`const d = context\.device; d\.captureImage\(\)`/i);
assert.match(text, /dynamic dispatch/i);
assert.match(text, /parenthesized receivers/i);
+ assert.match(text, /except a function- or block-local `const` bound to an object literal[^\n]*used only to call those functions[^\n]*fail closed/i);
+ assert.match(text, /early-return guards and calls in `else` branches are reported by design[^\n]*deliberate fail-closed limit[^\n]*positive guard block/i);
+ assert.match(text, /parenthesized receivers[^\n]*`\.bind`[^\n]*`Reflect\.apply`[^\n]*detected like direct calls/i);
+ assert.match(text, /`factory\?\.<T>\(context\.device\)\.captureImage\(\)`[^\n]*over-report/);
assert.match(text, /runtime verification on the target Power Pages site[^.\n]*required/i);
});
}
@@ -434,6 +438,216 @@ test('Pages detection never promotes non-null assertions or escaped keys into gu
assert.deepEqual(codesFor(`if (!context.device?.captureImage) { ${CALL}; }`), ['PCF_PAGES_API']);
});
+const DISPATCH_FORMS = [
+ ['parenthesized namespace receiver', '(context.device).captureImage()'],
+ ['parenthesized root receiver', '(context).device.captureImage()'],
+ ['nested parenthesized receivers', '((context).device).captureImage()'],
+ ['parenthesized receiver with optional call', '(context.device)?.captureImage?.()'],
+ ['parenthesized receiver after return', 'return (context.device).captureImage()'],
+ ['template-literal method key', 'context.device[`captureImage`]()'],
+ ['template-literal namespace key', 'context[`device`].captureImage()'],
+ ['escaped template-literal key', 'context.device[`capture\\u0049mage`]()'],
+ ['call dispatch', 'context.device.captureImage.call(context.device)'],
+ ['apply dispatch', 'context.device.captureImage.apply(context.device, [])'],
+ ['bind dispatch', 'context.device.captureImage.bind(context.device)()'],
+ ['optional call dispatch', 'context.device.captureImage?.call(context.device)'],
+ ['Reflect.apply dispatch', 'Reflect.apply(context.device.captureImage, context.device, [])'],
+ ['Reflect.apply of a parenthesized receiver', 'Reflect.apply((context.device).captureImage, context.device, [])'],
+ ['utility call dispatch', 'context.utils.lookupObjects.call(undefined, {})', 'Utility', 'utils', 'lookupObjects'],
+ ['parenthesized utility receiver', '(context.utils).lookupObjects({})', 'Utility', 'utils', 'lookupObjects'],
+];
+
+for (const [name, call, feature = 'Device.captureImage', namespace = 'device', method = 'captureImage'] of DISPATCH_FORMS) {
+ test(`Pages detection recognizes ${name}`, () => {
+ const statement = `${call};`;
+ const body = call.startsWith('return ') ? `function f(context) { ${statement} }` : statement;
+ const guarded = `function g(context) { if (typeof context.${namespace}?.${method} === "function") { ${statement} } }`;
+ assert.deepEqual({
+ unguarded: codesFor(body, feature),
+ guarded: codesFor(guarded, feature),
+ invalidGuard: codesFor(guarded.replace('if (typeof', 'if (ready || typeof'), feature),
+ undeclared: codesFor(body, null, ['model']),
+ textOnly: codesFor(`// ${call}\nconst note = ${JSON.stringify(call)};`, null),
+ fallback: findingsFor(guarded, feature, ['pages'], { indexer: throwingIndexer }).map((finding) => finding.code),
+ }, {
+ unguarded: ['PCF_PAGES_API'],
+ guarded: [],
+ invalidGuard: ['PCF_PAGES_API'],
+ undeclared: ['PCF_FEATURE_UNDECLARED'],
+ textOnly: [],
+ fallback: ['PCF_PAGES_API'],
+ });
+ });
+}
+
+test('Pages detection keeps call results, comma groups and dynamic keys out of the dispatch forms', () => {
+ for (const text of [
+ 'foo(context.device).captureImage();',
+ 'context.device.captureImage.name;',
+ 'const fn = context.device.captureImage.call;',
+ 'Reflect.apply(other.captureImage, context.device, []);',
+ 'Reflect.apply(fn, context.device, []);',
+ 'Other.apply(context.device.captureImage, context.device, []);',
+ 'context.device[`capture${suffix}`]();',
+ ]) {
+ assert.deepEqual(codesFor(text, null).filter((code) => code === 'PCF_PAGES_API'), [], text);
+ }
+ // The new forms are detected only: they are not new proof syntax.
+ for (const condition of [
+ 'typeof (context.device)?.captureImage === "function"',
+ 'typeof context.device[`captureImage`] === "function"',
+ 'typeof context.device.captureImage.call === "function"',
+ ]) {
+ assert.deepEqual(codesFor(`if (${condition}) { ${CALL}; }`), ['PCF_PAGES_API'], condition);
+ }
+});
+
+test('Pages detection reads optional and generic call arguments as arguments, not grouped receivers', () => {
+ const factory = 'const factory = (value) => ({ captureImage() { return "local"; } });\n';
+ const generic = 'function factory<T>(value: T) { return { captureImage() { return "local"; } }; }\n';
+ const method = 'const factory = { create<T>(value: T) { return { captureImage() { return "local"; } }; } };\n';
+ for (const text of [
+ `${factory}function run(context) { return factory?.(context.device).captureImage(); }`,
+ `${factory}function run(context) { return factory?.(context.device)?.captureImage(); }`,
+ `${generic}function run(context) { return factory<unknown>(context.device).captureImage(); }`,
+ `${method}function run(context) { return factory.create<unknown>(context.device).captureImage(); }`,
+ `${factory}function run(context) { return factory(context.device).captureImage(); }`,
+ ]) {
+ assert.deepEqual(codesFor(text, null), [], text);
+ assert.deepEqual(codesFor(text, null, ['model']), [], text);
+ }
+ // After an analyzer failure the fallback reads the optional call the same way.
+ assert.deepEqual(findingsFor(`${factory}factory?.(context.device).captureImage();`, null, ['pages'], { indexer: throwingIndexer })
+ .map((finding) => finding.code), []);
+ // Known limit, in the safe direction: after an optional call with type arguments the parenthesis is still
+ // read as a grouped receiver, so the factory result's method is reported as a Pages call (an over-report).
+ for (const text of [
+ `${generic}function run(context) { return factory?.<unknown>(context.device).captureImage(); }`,
+ `${method}function run(context) { return factory.create?.<unknown>(context.device).captureImage(); }`,
+ ]) {
+ assert.deepEqual(codesFor(text, null), ['PCF_FEATURE_UNDECLARED', 'PCF_PAGES_API'], text);
+ }
+ // A grouped receiver after an operator or keyword is still read through.
+ for (const text of ['ready && (context.device).captureImage();', 'value = (context.device).captureImage();', 'void (context.device).captureImage();']) {
+ assert.deepEqual(codesFor(text, null), ['PCF_FEATURE_UNDECLARED', 'PCF_PAGES_API'], text);
+ }
+});
+
+test('Pages proof refuses early exits and else branches of a negated method check by design', () => {
+ // A deliberate fail-closed limit: code that runs between a negated check and the call, such as a later
+ // operand of the same condition, can remove the method without a write the analyzer sees.
+ const negated = 'typeof context.device?.captureImage !== "function"';
+ for (const body of [
+ `if (${negated}) return; ${CALL};`,
+ `if (${negated}) { return; } ${CALL};`,
+ `if (${negated}) throw new Error("no camera"); ${CALL};`,
+ `if (!context.device?.captureImage) return; ${CALL};`,
+ `if (!(${PROOF})) return; ${CALL};`,
+ `if (${negated}) return; return ${CALL};`,
+ `if (${negated}) return; const image = ${CALL};`,
+ `if (${negated}) { consume(); } else { ${CALL}; }`,
+ `if (${negated}) consume(); else ${CALL};`,
+ `if (${negated} || !state.ready) return; return ${CALL};`,
+ `if (!(${PROOF} && state > 0)) return; ${CALL};`,
+ `if (${negated}) return; Object.assign(context.device, { captureImage: undefined }); ${CALL};`,
+ ]) {
+ assert.deepEqual(codesFor(`function capture(context, state, consume) { ${body} }`), ['PCF_PAGES_API'], body);
+ }
+ assert.deepEqual(codesFor(`function capture(contexts) { for (const context of contexts) { if (${negated}) continue; ${CALL}; } }`),
+ ['PCF_PAGES_API']);
+ const [finding] = findingsFor(`function capture(context) { if (${negated}) return; ${CALL}; }`);
+ assert.match(finding.message, /early-return guards and aliases are not recognized/);
+ // The recommended rewrite: a positive guard block around the call.
+ assert.deepEqual(codesFor(`function capture(context) { if (${PROOF}) { ${CALL}; } }`), []);
+ assert.deepEqual(codesFor(`async function capture(context, consume) { if (${PROOF}) { const image = await ${CALL}; consume(image); } }`), []);
+});
+
+test('Pages detection ignores a context-named local object literal that is provably not the PCF context', () => {
+ for (const name of ['ctx', 'context', '_context', 'pcfContext']) {
+ const text = `function render() {\n const ${name} = { device: { captureImage() { return 1; }, "pickFile": async () => [] }, utils: { lookupObjects: function (options) { return []; }, max: 3 } };\n ${name}.device.captureImage(); ${name}.device.pickFile(); ${name}.utils.lookupObjects(options);\n}`;
+ assert.deepEqual(codesFor(text, null), [], name);
+ assert.deepEqual(codesFor(text, null, ['model']), [], name);
+ }
+ for (const text of [
+ '{ const ctx = { device: { captureImage: () => ({ id: "local", size: [1, 2] }) } }; ctx.device.captureImage(); }',
+ 'function render() { const ctx = { device: { captureImage(a, b) { return null; } } }\n ctx?.device?.captureImage?.(a); }',
+ 'function render() { const ctx = { device: { captureImage: async function named() { return; } } }; new ctx.device.captureImage(); }',
+ ]) {
+ assert.deepEqual(codesFor(text, null), [], text);
+ }
+ // A literal whose function runs other code is not set aside; the call inside is read on its own too.
+ assert.deepEqual(codesFor('function render() { const ctx = { device: { captureImage: () => context.device.captureImage() } }; ctx.device.captureImage(); }'),
+ ['PCF_PAGES_API', 'PCF_PAGES_API']);
+});
+
+test('Pages detection keeps the error for context-named objects it cannot prove local', () => {
+ const local = 'device: { captureImage() { return "local"; } }';
+ for (const body of [
+ // Not a local, inert const literal.
+ 'let ctx = { device: { captureImage() {} } }; ctx.device.captureImage();',
+ 'const ctx = { device: real.device }; ctx.device.captureImage();',
+ 'const ctx = { device }; ctx.device.captureImage();',
+ 'const ctx = { ...base }; ctx.device.captureImage();',
+ 'const ctx = { [key]: {} }; ctx.device.captureImage();',
+ 'const ctx = { get device() { return real; } }; ctx.device.captureImage();',
+ 'const ctx = { __proto__: { device: { captureImage() {} } } }; ctx.device.captureImage();',
+ 'const ctx = { device: { captureImage() {} }, device: real }; ctx.device.captureImage();',
+ 'const ctx = { device: { *captureImage() {} } }; ctx.device.captureImage();',
+ 'const ctx = { device: { captureImage(): void {} } }; ctx.device.captureImage();',
+ 'const ctx = { device: { captureImage(v = real) {} } }; ctx.device.captureImage();',
+ 'const ctx = { device: { captureImage({ device }) {} } }; ctx.device.captureImage();',
+ 'const ctx = { device: { captureImage: real.captureImage } }; ctx.device.captureImage();',
+ 'const ctx = { device: { captureImage() {} } } as unknown as Context; ctx.device.captureImage();',
+ 'const ctx = useContext(PcfContext); ctx.device.captureImage();',
+ // A function in the literal that runs, reads or returns anything else.
+ `const ctx = { ${local}, update(value) { this.device = value.device; } }; ctx.update(api); ctx.device.captureImage();`,
+ `const ctx = { ${local}, expose() { return this; } }; Object.assign(ctx.expose(), api); ctx.device.captureImage();`,
+ `let escaped; const ctx = { ${local}, leak() { escaped = this; } }; ctx.leak(); escaped.device = api.device; ctx.device.captureImage();`,
+ `const ctx = { ${local}, update(value) { this.device = value.device; } }; ctx.update?.(api); ctx.device.captureImage();`,
+ `const ctx = { ${local}, update() { ctx.device = api.device; } }; ctx.update(); ctx.device.captureImage();`,
+ `const ctx = { ${local}, update() { super.__defineGetter__("device", () => api.device); } }; ctx.update(); ctx.device.captureImage();`,
+ 'const ctx = { device: { captureImage(c) { return c.device.captureImage(); } } }; ctx.device.captureImage(api);',
+ 'const ctx = { device: { captureImage: (c) => c } }; ctx.device.captureImage(api.device).captureImage();',
+ 'const ctx = { device: { captureImage() { return real; } } }; ctx.device.captureImage().captureImage();',
+ 'const ctx = { device: { captureImage() { return arguments; } } }; ctx.device.captureImage();',
+ 'const ctx = { device: { captureImage() { consume(); return 1; } } }; ctx.device.captureImage();',
+ // A use other than a call of the literal's own function.
+ 'const ctx = {}; ctx.__defineGetter__("device", () => api.device); ctx.device.captureImage();',
+ `const ctx = { ${local} }; ctx.hasOwnProperty("device"); ctx.device.captureImage();`,
+ `const ctx = { ${local} }; ctx.device.captureImage.call(api.device);`,
+ `const ctx = { ${local} }; helper(ctx); ctx.device.captureImage();`,
+ `const ctx = { ${local} }; const d = ctx.device; ctx.device.captureImage();`,
+ `const ctx = { ${local} }; ctx.device.captureImage = real; ctx.device.captureImage();`,
+ `const ctx = { ${local} }; Object.assign(ctx.device, real); ctx.device.captureImage();`,
+ `const ctx = { ${local} }; delete ctx.device; ctx.device.captureImage();`,
+ `const ctx = { ${local} }; (ctx).device.captureImage();`,
+ `const ctx = { ${local} }; const alias = ctx; alias.device = api.device; ctx.device.captureImage();`,
+ `const ctx = { ${local} }; return [ctx, ctx.device.captureImage()];`,
+ // Something else could reach the binding: eval, a with statement, an inner declaration.
+ `const ctx = { ${local} }; eval("ctx.device = api.device"); ctx.device.captureImage();`,
+ `const ctx = { ${local} }, other = 1; { const ctx = real; ctx.device.captureImage(); }`,
+ `const ctx = { ${local} }; function inner(ctx) { ctx.device.captureImage(); }`,
+ `const ctx = { ${local} }; button.onclick = (ctx) => ctx.device.captureImage();`,
+ ]) {
+ assert.ok(codesFor(`function run(api, real, base, key, device, helper, consume, button, PcfContext) { ${body} }`, null).includes('PCF_PAGES_API'), body);
+ }
+ for (const text of [
+ // Only the context-named root itself is set aside, never a receiver under another root.
+ 'function run(api) { const props = { context: null }; Object.assign(props, { context: api }); props.context.device.captureImage(); }',
+ 'function run(api) { const state = { context: null }; const alias = state; alias.context = api; state.context.device.captureImage(); }',
+ 'function run(api) { const props = { context: { device: { captureImage() {} } } }; props.context.device.captureImage(); }',
+ // A program-level const can be reached from other scripts; a with statement can rebind the name.
+ 'const ctx = { device: { captureImage() {} } }; ctx.device.captureImage();',
+ 'export const ctx = { device: { captureImage() {} } }; ctx.device.captureImage();',
+ 'function run(api) { const ctx = { device: { captureImage() {} } }; with (api) { ctx.device.captureImage(); } }',
+ 'function render(ctx) { ctx.device.captureImage(); }',
+ 'class C { init(context) { this._context = context; } run() { this._context.device.captureImage(); } }',
+ ]) {
+ assert.ok(codesFor(text, null).includes('PCF_PAGES_API'), text);
+ assert.ok(codesFor(text, null, ['model']).includes('PCF_FEATURE_UNDECLARED'), text);
+ }
+});
+
test('Pages detection decodes escapes without evaluating malformed or non-identifier keys', () => {
for (const key of [
String.raw`"capture\uZZZZImage"`, String.raw`"capture\u{110000}Image"`,
@@ -881,6 +1095,110 @@ for (const [name, body] of [
});
}
+test('Pages proof expires after a parameter-default write that a same-named body declaration does not hide', () => {
+ // A function with parameter expressions evaluates its defaults before its body's declarations exist,
+ // so the default writes the outer context however the body declares the name.
+ for (const body of [
+ `function reset(v = (context.device = {})) { let context; } ${CALL};`,
+ `function reset(v = (context.device = {})) { var context; } ${CALL};`,
+ `function reset(v = (context = next)) { const context = other; consume(context); } ${CALL};`,
+ `function reset({ v = (context.device = {}) } = {}) { let context; } ${CALL};`,
+ `const reset = function (v = (context.device = {})) { var context; }; ${CALL};`,
+ `const reset = (v = (context.device = {})) => { let context; }; ${CALL};`,
+ `const h = { reset(v = (context.device = {})) { var context; } }; ${CALL};`,
+ `class H { reset(v = (context.device = {})) { let context; } } ${CALL};`,
+ ]) {
+ assert.deepEqual(codesFor(withinGuard(body)), ['PCF_PAGES_API'], body);
+ }
+});
+
+test('Pages proof keeps body declarations local when a function has parameter expressions', () => {
+ for (const body of [
+ `function reset(v = 1) { let context = next; context = other; consume(context); } ${CALL};`,
+ `function reset(v = 1) { var context = next; context.device = other; } ${CALL};`,
+ `function reset(v = (other = next)) { var context; context = next; } ${CALL};`,
+ ]) {
+ assert.deepEqual(codesFor(withinGuard(body)), [], body);
+ }
+ // A call in such a body reads the body's own declaration, which no outer proof covers.
+ for (const kind of ['let', 'var']) {
+ assert.deepEqual(codesFor(withinGuard(`function reset(v = 1) { ${kind} context = next; ${CALL}; }`)), ['PCF_PAGES_API'], kind);
+ }
+});
+
+const THIS_CONTEXT_GUARD = 'typeof this._context.device?.captureImage === "function"';
+const THIS_CONTEXT_CALL = 'this._context.device.captureImage()';
+const inGuardedMethod = (classBody, after = `${THIS_CONTEXT_CALL};`) =>
+ `class C { run() { if (${THIS_CONTEXT_GUARD}) { class D { ${classBody} } ${after} } } }`;
+
+test('Pages proof expires after a this write in a computed class member key', () => {
+ // A computed key is evaluated where the class is defined, so its `this` is the enclosing method's.
+ // https://tc39.es/ecma262/#sec-runtime-semantics-classdefinitionevaluation
+ for (const member of [
+ '[this._context.device = null]() {}',
+ '[this._context.device = null] = 1;',
+ 'static [this._context.device = null]() {}',
+ 'static [this._context.device = null] = 1;',
+ 'get [this._context.device = null]() { return 1; }',
+ 'async *[this._context.device = null]() {}',
+ 'value = 1; [this._context = null]() {}',
+ 'run() {} [this._context.device = null]() {}',
+ 'static { consume(1); } [this._context.device = null]() {}',
+ 'value\n[this._context.device = null]() {}',
+ 'value: number\n[this._context.device = null]() {}',
+ 'value?: string\n[this._context.device = null]() {}',
+ '#value\n[this._context.device = null]() {}',
+ 'static #value\n[this._context.device = null]() {}',
+ '@decorate [this._context.device = null]() {}',
+ '@decorate() [this._context.device = null]() {}',
+ '@scope.decorate [this._context.device = null]() {}',
+ '@decorate\n[this._context.device = null]() {}',
+ 'handler = () => {}\n[this._context.device = null]() {}',
+ 'count = next++\n[this._context.device = null]() {}',
+ 'first = 1\nsecond\n[this._context.device = null]() {}',
+ 'run(): void\n[this._context.device = null]() {}',
+ ]) {
+ assert.deepEqual(codesFor(inGuardedMethod(member)), ['PCF_PAGES_API'], member);
+ }
+});
+
+test('Pages proof keeps the class instance as this inside class member bodies and initializers', () => {
+ for (const member of [
+ 'run() { this._context.device = null; }',
+ 'value = (this._context.device = null);',
+ '[key] = (this._context.device = null);',
+ 'static { this._context = null; }',
+ 'value = { a: 1 }\n[this._context.device = null];',
+ 'value = source\n[this._context.device = null];',
+ 'value = read()\n[this._context.device = null];',
+ 'value: number[] = []\n[this._context.device = null];',
+ 'value = function () { return {}; }\n[this._context.device = null];',
+ 'value = class {}\n[this._context.device = null];',
+ 'value = () => source\n[this._context.device = null];',
+ ]) {
+ assert.deepEqual(codesFor(inGuardedMethod(member)), [], member);
+ }
+ // A call in a computed key runs under the enclosing proof; one in a member body does not.
+ assert.deepEqual(codesFor(inGuardedMethod(`[${THIS_CONTEXT_CALL}]() {}`, '')), []);
+ assert.deepEqual(codesFor(inGuardedMethod(`value: number\n[${THIS_CONTEXT_CALL}]() {}`, '')), []);
+ assert.deepEqual(codesFor(inGuardedMethod(`value = source\n[${THIS_CONTEXT_CALL}];`, '')), ['PCF_PAGES_API']);
+ assert.deepEqual(codesFor(`class D { [${THIS_CONTEXT_CALL}]() {} }`), ['PCF_PAGES_API']);
+ assert.deepEqual(codesFor(inGuardedMethod(`run() { ${THIS_CONTEXT_CALL}; }`, '')), ['PCF_PAGES_API']);
+});
+
+test('Pages proof keeps the inner class this for a computed key after an assertion initializer or a generic decorator', () => {
+ // Known limit, behaving as before: the member scanner does not recognize these keys as member starts, so
+ // `this` in them is still read as the inner class's instance and a write there does not end the outer proof.
+ for (const member of [
+ 'value = {} as object\n[this._context.device = null]() {}',
+ '@decorate<number>() [this._context.device = null]() {}',
+ ]) {
+ assert.deepEqual(codesFor(inGuardedMethod(member)), [], member);
+ }
+ // The same key on its own line after the generic decorator is recognized.
+ assert.deepEqual(codesFor(inGuardedMethod('@decorate<number>()\n[this._context.device = null]() {}')), ['PCF_PAGES_API']);
+});
+
for (const [name, call, plainCall = CALL, proof = PROOF] of [
['method non-null run', 'context.device.captureImage!!()'],
['root and namespace non-null runs', 'context!!!.device!!?.captureImage!!()'],
@@ -1238,9 +1556,12 @@ test('.tsx sources keep TypeScript\'s JSX reading of angle brackets', () => {
});
test('.ts angle-bracket types the gate cannot blank fall back fail closed', () => {
+ // An unterminated type, and types the gate can only blank one lex at a time (each one after a
+ // comment) in a file large enough to pass the lexing budget.
+ const padding = `/*${' padding'.repeat(4000)} */\n`;
for (const [name, text] of [
['unterminated type', `const value = <Record<string, unknown>raw;\n${CALL};`],
- ['more types than the pass limit', `let v;\n${'v = <T>v;\n'.repeat(300)}${CALL};`],
+ ['types past the lexing budget', `let v;\n${padding}${'v = /* cast */ <T>v;\n'.repeat(300)}${CALL};`],
]) {
assert.deepEqual(scanSource(FILE, text).map((finding) => finding.code), ['PCF_CODE_UNPARSEABLE'], name);
const gated = gateSources({
@@ -1271,6 +1592,54 @@ test('Source analysis bounds a .ts control with many angle-bracket types', (t) =
assert.deepEqual(findings.map((finding) => [finding.code, finding.line]), [['PCF_PAGES_API', lines.length - 2]]);
});
+test('.ts files with hundreds of angle-bracket types stay analyzable', (t) => {
+ const guarded = withinGuard(`${CALL};`);
+ const control = (casts) => {
+ const lines = ['export class C {', ' public run(context: ComponentFramework.Context<IInputs>): void {', ' let v: unknown;'];
+ for (let i = 0; i < 1500; i += 1) {
+ lines.push(i % 5 === 0 && casts-- > 0
+ ? ` const el${i} = <HTMLDivElement>document.createElement("div"); v = <unknown>el${i};`
+ : ` const value${i}: Array<number> = [${i}, ${i + 1}]; total += value${i}.length > 1 ? ${i} : 0;`);
+ }
+ lines.push(` ${guarded}`, ' }', '}');
+ return lines.join('\n');
+ };
+ const longType = `{ ${Array.from({ length: 400 }, (_, i) => `field${i}: string;`).join(' ')} }`;
+ for (const [name, text] of [
+ ['300 casts in a small file', `let v;\n${'v = <T>v;\n'.repeat(300)}${guarded}`],
+ ['600 casts in a 100 KB control', control(300)],
+ ['nested, adjacent and grouped casts', `let v;\n${'v = <A><B<C>>(<D>v); const f = <T>(x: T): T => x;\n'.repeat(100)}${guarded}`],
+ ['a type longer than 4096 characters', `const shape = <${longType}>raw;\n${guarded}`],
+ ]) {
+ const started = performance.now();
+ const gated = gateSources({ manifestModel: { features: [{ name: 'Device.captureImage' }] }, sources: [{ file: FILE, text }], hosts: ['pages'] });
+ const elapsed = performance.now() - started;
+ t.diagnostic(`${name}: ${elapsed.toFixed(3)} ms; ${Buffer.byteLength(text)} bytes`);
+ assert.deepEqual(gated, { ok: true, errors: [], warnings: [] }, name);
+ assert.ok(elapsed < PATHOLOGICAL_SCAN_LIMIT_MS, `${name}: ${elapsed.toFixed(3)} ms exceeds ${PATHOLOGICAL_SCAN_LIMIT_MS} ms`);
+ const unguarded = text.replace(guarded, `${CALL};`);
+ const callLine = unguarded.split('\n').findIndex((line) => line.includes(CALL)) + 1;
+ assert.deepEqual(findingsFor(unguarded).map((finding) => [finding.code, finding.line]), [['PCF_PAGES_API', callLine]], name);
+ }
+});
+
+test('.ts angle-bracket types in strings, comments, template text and regexes never hide code', () => {
+ const lines = [
+ 'let v;',
+ 'const html = "(<b>" + `(<i>${v}<u>` + \'(<s>\' + `${`(<q>`}`;',
+ '// (<T> v = 1',
+ '/* = <T> */ const re = /(<T>)/g;',
+ ...Array(60).fill('v = <T>v; v = (<T>v); if (count < limit && other > 2) { v = <Array<T>>v; }'),
+ `${CALL};`,
+ 'const note = `= <b>${v}</b> = <i>`; v = <T>v;',
+ `${CALL};`,
+ ];
+ const text = lines.join('\n');
+ assert.deepEqual(scanSource(FILE, text), []);
+ assert.deepEqual(findingsFor(text).map((finding) => [finding.code, finding.line]),
+ [['PCF_PAGES_API', lines.length - 2], ['PCF_PAGES_API', lines.length]]);
+});
+
for (const relative of [
'AGENTS.md', path.join('references', 'pcf-testing.md'), path.join('references', 'pcf-best-practices.md'),
]) {
@@ -1282,8 +1651,9 @@ for (const relative of [
assert.match(text, /Pages API calls[^.\n]*unguarded/i);
assert.match(text, /lexer failure[^.\n]*comments?[^.\n]*strings?[^.\n]*report/i);
if (relative === 'AGENTS.md') {
- assert.match(text, /later release[^.\n]*parameter-default writes[^.\n]*body declarations/i);
- assert.match(text, /computed class member keys/i);
+ assert.match(text, /parameter default reaches the outer binding[^.\n]*body declares the same name/i);
+ assert.match(text, /`this` in a computed class member key[^\n]*enclosing method's[^.\n]*ends that method's proof/i);
+ assert.match(text, /Two forms behave as before[^\n]*type assertion or `satisfies`[^\n]*decorator with type arguments/i);
assert.match(text, /\.ts` files[^.\n]*angle-bracket types[^.\n]*JSX/i);
assert.match(text, /unterminated such type[^.\n]*lexer-failure path/i);
} else {
diff --git a/plugins/pcf/scripts/tests/telemetry-ci.test.js b/plugins/pcf/scripts/tests/telemetry-ci.test.js
index c420fca86..7b8a5d808 100644
--- a/plugins/pcf/scripts/tests/telemetry-ci.test.js
+++ b/plugins/pcf/scripts/tests/telemetry-ci.test.js
@@ -99,3 +99,30 @@ test('PCF script CI watches every bundled telemetry source without widening unre
assert.ok(globs.includes(`.github/workflows/${name}`), `.github/workflows/${name} must trigger the PCF script tests that check it`);
}
});
+
+// The eval tests and the full eval run read committed control projects, which a Windows checkout gives CRLF line ends, through the plugin's
+// manifest and source gates, so they run on every system and Node version the script tests run on.
+test('PCF eval CI runs on every system and Node version the script tests run on', (t) => {
+ const text = workflow(t, 'pcf-script-tests.yml');
+ if (text === null) return;
+ const jobSection = text.slice(text.search(/^jobs:[ \t]*\r?$/m));
+ const jobs = [...jobSection.matchAll(/^ {4}([a-z0-9-]+):[ \t]*\r?$/gim)];
+ const block = (id) => {
+ const index = jobs.findIndex((job) => job[1] === id);
+ assert.ok(index >= 0, `${id} is a job`);
+ return jobSection.slice(jobs[index].index, jobs[index + 1]?.index);
+ };
+ // `os: [ubuntu-latest, windows-latest, macos-latest]`, under the job's `matrix:`.
+ const list = (job, key) => {
+ const found = new RegExp(`^ {16}${key}:[ \\t]*\\[([^\\]\\r\\n]*)\\][ \\t]*\\r?$`, 'm').exec(job);
+ return found && found[1].split(',').map((item) => item.trim());
+ };
+ const scripts = block('test-pcf-scripts');
+ const evals = block('test-pcf-evals');
+ assert.deepStrictEqual(list(scripts, 'os'), ['ubuntu-latest', 'windows-latest', 'macos-latest']);
+ assert.deepStrictEqual(list(scripts, 'node'), ['20', '22']);
+ assert.deepStrictEqual(list(evals, 'os'), list(scripts, 'os'), 'the eval job runs on every system the script tests run on');
+ assert.deepStrictEqual(list(evals, 'node'), list(scripts, 'node'), 'and on every Node version');
+ assert.match(evals, /^ {8}runs-on: \$\{\{ matrix\.os \}\}[ \t]*\r?$/m, 'on the system of its matrix entry');
+ assert.match(evals, /^ {18}node-version: \$\{\{ matrix\.node \}\}[ \t]*\r?$/m, 'with the Node version of its matrix entry');
+});
diff --git a/scripts/tests/validate-no-real-environments.test.js b/scripts/tests/validate-no-real-environments.test.js
index 73d415017..e8008daf7 100644
--- a/scripts/tests/validate-no-real-environments.test.js
+++ b/scripts/tests/validate-no-real-environments.test.js
@@ -176,8 +176,18 @@ test('OData annotations are not mistaken for e-mail addresses', () => {
+ '_ownerid_value@Microsoft.Dynamics.CRM.associatednavigationproperty',
].join('\n');
assert.deepEqual(scanText(odata), []);
+ // Only the exact annotation names: a real-looking domain that merely begins with the spelling is an address.
+ for (const address of ['[email protected]', '[email protected]',
+ assert.equal(scanText(address).length, 1, address);
+ }
+ assert.equal(isPlaceholderEmailDomain('microsoft.dynamics.crm.example.net'), false);
+ assert.equal(isPlaceholderEmailDomain('Microsoft.Dynamics.CRM.lookuplogicalname'), true);
+ assert.equal(isPlaceholderEmailDomain('odata.nextLink'), true);
});
test('isPlaceholderEmailDomain: real vs illustrative', () => {
diff --git a/scripts/validate-no-real-environments.js b/scripts/validate-no-real-environments.js
index f387d0bf1..f59b95e74 100644
--- a/scripts/validate-no-real-environments.js
+++ b/scripts/validate-no-real-environments.js
@@ -93,9 +93,14 @@ const REAL_ORG_SHAPE = /^org[0-9a-f]{8}$/i;
const PLACEHOLDER_EMAIL_DOMAIN_ROOTS = ['contoso', 'fabrikam', 'example', 'company', 'your'];
// OData annotations parse as e-mail addresses but are not: `[email protected].
-// V1.FormattedValue`, `[email protected]`. Both begin their "domain" with `odata.`, which is
-// not a registrable domain, so skipping them costs no real coverage.
-const ODATA_ANNOTATION = /^odata\./i;
+// V1.FormattedValue`, `[email protected]`, `@odata.nextLink`. Dataverse's own instance annotations
+// read the same way under its `Microsoft.Dynamics.CRM.` namespace:
+// `[email protected]`, `…@Microsoft.Dynamics.CRM.associatednavigationproperty`
+// (https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/query/select-columns#lookup-property-data).
+// Only these exact annotation names are skipped, to the end of the "domain": a longer domain that merely
+// begins with one of the spellings (`[email protected]`, `[email protected]`) is
+// judged like any other address. Add a name here when a scanned file needs another annotation.
+const ODATA_ANNOTATION = /^(?:odata\.(?:bind|nextlink|context|count|etag|type|id)|odata\.community\.display\.v1\.formattedvalue|microsoft\.dynamics\.crm\.(?:lookuplogicalname|associatednavigationproperty|fetchxmlpagingcookie|morerecords|totalrecordcount|totalrecordcountlimitexceeded))$/i;
const HOST_RE = /\b([a-z0-9][a-z0-9-]*)\.crm[a-z0-9]*\.dynamics\.com\b/gi;
const TENANT_RE = /\b([a-z0-9][a-z0-9-]*)\.onmicrosoft\.com\b/gi;