A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
model-apps 2.20.1: pages convert a Map, Set or iterator with Array.from (#776)
Akshay Maloo696cac987b3e
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.tsxindex 027bc0b86..5abbc442b 100644--- a/evals/model-apps/genpage/fixtures/26-customer-lookup/customer-lookup.tsx+++ b/evals/model-apps/genpage/fixtures/26-customer-lookup/customer-lookup.tsx@@ -361,7 +361,7 @@ function PageBody(props: GeneratedComponentProps) {const choice = customerChoice(row);if (choice && !seen.has(`${choice.table}:${choice.id}`)) seen.set(`${choice.table}:${choice.id}`, choice);}- return [...seen.values()];+ return Array.from(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.diff --git a/evals/model-apps/genpage/tests/iteration-runtime.test.js b/evals/model-apps/genpage/tests/iteration-runtime.test.jsnew file mode 100644index 000000000..8e5aeef04--- /dev/null+++ b/evals/model-apps/genpage/tests/iteration-runtime.test.js@@ -0,0 +1,120 @@+'use strict';+// Eval 26's customer choices, run the way the page is compiled. The bundled SDK compiles every page with TypeScript's+// `transpileModule` and `{ target: ES5, module: ES2020, jsx: React }` — no `downlevelIteration` and no type check — and under+// those options a spread copies by `length` and index. A Map's iterator has neither, so `return [...seen.values()];`+// contributed nothing: the page's "Change customer" Dropdown opened with no options, and the compile reported nothing.+//+// The page's own `choices` callback and the trusted top-level helpers it calls are lifted out of the committed source with the+// vendored parser (never by line number), compiled alone with the SDK's options and run on the fixture's synthetic rows+// (lookup-rows.json). The page module itself is never executed. Values cross the vm boundary as JSON, so no assertion depends+// on another realm's prototypes.+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 { loadVendoredTypeScript } = require('../../../../plugins/model-apps/scripts/lib/typescript-compiler.js');++const FIXTURE = path.join(__dirname, '..', 'fixtures', '26-customer-lookup');+const PAGE = fs.readFileSync(path.join(FIXTURE, 'customer-lookup.tsx'), 'utf8');+const ROWS = JSON.parse(fs.readFileSync(path.join(FIXTURE, 'lookup-rows.json'), 'utf8'));+const LABEL = '[email protected]';+// The top-level declarations the callback reaches: the canonical lookup normalizer with its two patterns, and the page's+// label and choice helpers.+const HELPERS = ['LOOKUP_GUID', 'LOOKUP_QUALIFIED', 'normalizeLookupReference', 'customerLabel', 'customerChoice'];++let typescript;+const ts = () => (typescript ||= loadVendoredTypeScript());+// The vendored SDK's own compile options, exactly: a test is never made to pass by changing the target or adding downlevelIteration.+const sdkCompile = (source) => ts().transpileModule(source, {+ compilerOptions: { target: ts().ScriptTarget.ES5, module: ts().ModuleKind.ES2020, jsx: ts().JsxEmit.React },+ reportDiagnostics: true,+});++// The helpers' text, the `choices` callback (`React.useMemo(() => { … }, [opportunities])`) and its final `return`.+function pieces(source) {+ const file = ts().createSourceFile('customer-lookup.tsx', source, ts().ScriptTarget.Latest, true, ts().ScriptKind.TSX);+ const top = new Map();+ for (const statement of file.statements) {+ if (ts().isFunctionDeclaration(statement) && statement.name) top.set(statement.name.text, statement);+ if (ts().isVariableStatement(statement)) {+ for (const declaration of statement.declarationList.declarations) if (ts().isIdentifier(declaration.name)) top.set(declaration.name.text, statement);+ }+ }+ const found = [];+ const visit = (node) => {+ if (ts().isVariableDeclaration(node) && ts().isIdentifier(node.name) && node.name.text === 'choices'+ && node.initializer && ts().isCallExpression(node.initializer) && node.initializer.expression.getText(file) === 'React.useMemo') {+ found.push(node.initializer.arguments[0]);+ }+ ts().forEachChild(node, visit);+ };+ visit(file);+ assert.equal(found.length, 1, 'the page declares one `choices` memo');+ const callback = found[0];+ assert.ok(ts().isArrowFunction(callback) && callback.parameters.length === 0 && ts().isBlock(callback.body), 'its callback is a block-bodied arrow with no parameter');+ const last = callback.body.statements[callback.body.statements.length - 1];+ assert.ok(ts().isReturnStatement(last) && last.expression, 'the callback ends by returning its choices');+ for (const name of HELPERS) assert.ok(top.has(name), `the page declares ${name} at the top level`);+ return { file, helpers: HELPERS.map((name) => top.get(name).getText(file)), callback, returned: last.expression };+}++// The callback compiled with the SDK's options and called with `rows` — optionally with its final return expression replaced,+// which is how the control below puts the iterator spread back without touching the committed file.+function choicesOf(rows, { returnExpression } = {}) {+ const { file, helpers, callback, returned } = pieces(PAGE);+ let text = callback.getText(file);+ if (returnExpression !== undefined) {+ const start = returned.getStart(file) - callback.getStart(file);+ const end = returned.getEnd() - callback.getStart(file);+ text = `${text.slice(0, start)}${returnExpression}${text.slice(end)}`;+ }+ const source = `${helpers.join('\n\n')}\n\nconst choicesOf = (opportunities: any[]) => (${text})();\n`;+ const { outputText, diagnostics } = sdkCompile(source);+ assert.deepEqual((diagnostics || []).map((d) => `TS${d.code}`), [], 'the helpers and the callback compile without a diagnostic');+ const run = vm.runInNewContext(`${outputText}\n;choicesOf;`, {}, { filename: 'customer-lookup-choices.js' });+ return { choices: JSON.parse(JSON.stringify(run(rows))), outputText };+}++// What lookup-rows.json says the picker offers: each resolved customer once, by table and id, in row order, with its label.+function recordedChoices() {+ const seen = new Set();+ const out = [];+ for (const entry of ROWS.rows) {+ if (entry.expected.state !== 'resolved') continue;+ const { table, id } = entry.expected.reference;+ if (seen.has(`${table}:${id}`)) continue;+ seen.add(`${table}:${id}`);+ out.push({ table, id, label: entry.row[LABEL] });+ }+ return out;+}++test('eval 26: the customer choices, compiled as the SDK compiles the page, are every resolved customer once and in order', () => {+ const expected = recordedChoices();+ // The rows exercise a repeated customer, equal labels, and one GUID in two tables.+ assert.equal(expected.length, 4);+ assert.deepEqual(expected.map((choice) => choice.label), ['Fabrikam', 'Rene Valdes', 'Contoso', 'Contoso']);+ assert.deepEqual(expected.slice(2).map((choice) => choice.table), ['account', 'contact']);+ assert.equal(expected[2].id, expected[3].id, 'one GUID in two tables stays two choices');+ const { choices } = choicesOf(ROWS.rows.map((entry) => entry.row));+ assert.deepEqual(choices, expected);+});++test('eval 26: the same callback with the Map iterator spread back in offers no choice under the SDK options', () => {+ const { choices, outputText } = choicesOf(ROWS.rows.map((entry) => entry.row), { returnExpression: '[...seen.values()]' });+ assert.deepEqual(choices, [], 'the spread copies by length and index, which an iterator does not have');+ assert.match(outputText, /__spreadArray\(\[\], seen\.values\(\), true\)/, 'ES5 emit copies the iterator as an array-like');+});++test('eval 26: the committed callback converts the iterator before returning it, and keeps its dedupe loop', () => {+ const { file, callback, returned } = pieces(PAGE);+ assert.equal(returned.getText(file), 'Array.from(seen.values())');+ const body = callback.getText(file);+ assert.match(body, /const seen = new Map<string, Picked>\(\);/);+ assert.match(body, /if \(choice && !seen\.has\(`\$\{choice\.table\}:\$\{choice\.id\}`\)\) seen\.set\(`\$\{choice\.table\}:\$\{choice\.id\}`, choice\);/);+ const compiled = sdkCompile(PAGE);+ assert.deepEqual((compiled.diagnostics || []).map((d) => `TS${d.code}`), [], 'the whole page compiles without a diagnostic');+ assert.doesNotMatch(compiled.outputText, /__spreadArray\(\[\], seen\.values\(\)/, 'the compiled page no longer copies the iterator as an array-like');+ assert.match(compiled.outputText, /return Array\.from\(seen\.values\(\)\);/);+});diff --git a/plugins/model-apps/.claude-plugin/plugin.json b/plugins/model-apps/.claude-plugin/plugin.jsonindex a4e8ff780..639cd2494 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.20.0",+ "version": "2.20.1","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.jsonindex a4e8ff780..639cd2494 100644--- a/plugins/model-apps/.plugin/plugin.json+++ b/plugins/model-apps/.plugin/plugin.json@@ -1,6 +1,6 @@{"name": "model-apps",- "version": "2.20.0",+ "version": "2.20.1","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/CHANGELOG.md b/plugins/model-apps/CHANGELOG.mdindex bd7dcd9d8..32b36379a 100644--- a/plugins/model-apps/CHANGELOG.md+++ b/plugins/model-apps/CHANGELOG.md@@ -5,6 +5,16 @@ 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.1]++The bundled SDK is unchanged (power-platform-ux a3443479).++### Fixed++- **Pages convert a Map, Set or iterator with `Array.from` before spreading or looping over it.** Pages compile to ES5, where+ `[...map.values()]` or `for (const x of set)` silently yields nothing; the page rules and the `/genpage` and `/app-builder`+ agents now teach the safe form.+## [2.20.0]The bundled SDK is unchanged (power-platform-ux a3443479).diff --git a/plugins/model-apps/agents/genpage-page-builder.md b/plugins/model-apps/agents/genpage-page-builder.mdindex 41e6fdb2a..360aa398b 100644--- a/plugins/model-apps/agents/genpage-page-builder.md+++ b/plugins/model-apps/agents/genpage-page-builder.md@@ -192,6 +192,30 @@ and look at each match: one inside a `makeStyles` object is the defect, and onea string, a comment or an inline `style={{ … }}` is fine. Do not return a file thatstill has one in a `makeStyles` object.+## Step 2.7 — Iteration that compiles to nothing++The page compiler targets ES5 without iterator downleveling or full type checking.+Spreading, looping over, or array-destructuring a Map, Set or iterator reads length+and indices instead of the iterator: values can disappear, defaults can replace them,+or rest destructuring can throw. This includes `[...new Set(xs)]`, `[...m.values()]`,+`[...seen.values()]`, `for (const [k, v] of m)`, `new Set([...prev, id])`,+`[...selected]` and `[...text.matchAll(re)]`. Convert with `Array.from(...)` before+spreading, looping or destructuring; copy a Set with `new Set(prev)` then `.add(id)`.+Ordinary array spreads and loops remain valid. `Object.keys`, `Object.values` and+`Object.entries` return arrays. Spreads of `arguments` and ordinary indexed array-likes+work; rest destructuring of an array-like without `slice` does not. String spread+throws, and an ES5 string loop visits UTF-16 code units rather than Unicode code+points. See **Common Errors > 5. Iteration that compiles to nothing** in+`references/rules.md` for the pairs.++Before returning, review every spread (`...`), `for...of` loop and array destructure+you wrote. Wherever the value can be a Map, a Set, one of their `keys()`, `values()`+or `entries()` iterators, a generator, a `matchAll` result, `URLSearchParams`,+`FormData` or `Headers` — including one that arrives through props, React state, a+ref, a cache or another function — convert it with `Array.from(...)` first, or copy a+Set natively. Do not return a file that spreads, loops over or array-destructures one+directly.+## Step 3 — Read References and SamplesRead the code generation rules reference:diff --git a/plugins/model-apps/references/rules.md b/plugins/model-apps/references/rules.mdindex 2f9274fd4..7abe8c76a 100644--- a/plugins/model-apps/references/rules.md+++ b/plugins/model-apps/references/rules.md@@ -29,6 +29,7 @@ Comprehensive rules for generating generative page code. Read this file during c21. **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.+24. **Convert iterables to arrays**: The page compiler targets ES5 without iterator downleveling or full type checking. Spreading, looping over, or array-destructuring a Map, Set or iterator reads length and indices instead: values can disappear, defaults can replace them, or rest destructuring can throw. Never write `[...new Set(xs)]`, `[...m.values()]`, `for (const [k, v] of m)`, `new Set([...prev, id])`, `[...selected]` or `[...text.matchAll(re)]` directly; convert with `Array.from` or copy a Set natively. See **Common Errors > 5. Iteration that compiles to nothing**.---@@ -1329,3 +1330,149 @@ const useStyles = makeStyles({}});```++### 5. Iteration that compiles to nothing++The page compiler targets ES5 without iterator downleveling or full type checking. Spreading, looping over, or array-destructuring a Map, Set or iterator reads length and indices instead of the iterator: values can disappear, defaults can replace them, or rest destructuring can throw. This includes `[...new Set(xs)]`, `[...m.values()]`, `[...seen.values()]`, `for (const [k, v] of m)`, `new Set([...prev, id])`, `[...selected]` and `[...text.matchAll(re)]`. Convert with `Array.from(...)` before spreading, looping or destructuring; copy a Set with `new Set(prev)` then `.add(id)`. Ordinary array spreads and loops remain valid. `Object.keys`, `Object.values` and `Object.entries` return arrays. Spreads of `arguments` and ordinary indexed array-likes work; rest destructuring of an array-like without `slice` does not. String spread throws, and an ES5 string loop visits UTF-16 code units rather than Unicode code points. See **Common Errors > 5. Iteration that compiles to nothing** in `references/rules.md` for the pairs.++A Dropdown built from `[...seen.values()]` can open with no options despite a clean compile. The same problem affects native collection iterators, generators, native `matchAll` results, `URLSearchParams`, `FormData` and `Headers`. JSX expressions use the same emit.++**Map values**++```typescript+// WRONG — the spread contributes no values+const seen = new Map([["a", 1], ["b", 2]]);+const choices = [...seen.values()];+```++```typescript+// CORRECT+const seen = new Map([["a", 1], ["b", 2]]);+const choices = Array.from(seen.values());+```++**Unique values**++```typescript+// WRONG — unique becomes []+const xs = [1, 1, 2];+const unique = [...new Set(xs)];+```++```typescript+// CORRECT — insertion order is preserved+const xs = [1, 1, 2];+const unique = Array.from(new Set(xs));+```++**Map pairs**++```typescript+// WRONG — the loop runs zero times+const m = new Map([["a", 1], ["b", 2]]);+const rows: Array<[string, number]> = [];+for (const [k, v] of m) rows.push([k, v]);+```++```typescript+// CORRECT — keep loop control flow+const m = new Map([["a", 1], ["b", 2]]);+const rows: Array<[string, number]> = [];+for (const [k, v] of Array.from(m)) rows.push([k, v]);+```++A native Map's `m.forEach((v, k) => { rows.push([k, v]); })` is an alternative, not a second step. Its callback order is `(value, key)`. It is not a mechanical replacement for a loop with `break`, `continue` or an outer `return`.++**Selection state — component-body examples; state values are not statically inferred**++```typescript+// WRONG — the updater loses prior ids; chosen loses every selected value+const [selected, setSelected] = React.useState(new Set<string>());+function addSelected(id: string) {+ setSelected(prev => new Set([...prev, id]));+}+const chosen = [...selected];+```++```typescript+// CORRECT — call the handler from an event, never unconditionally during render+const [selected, setSelected] = React.useState(new Set<string>());+function addSelected(id: string) {+ setSelected(prev => {+ const next = new Set(prev);+ next.add(id);+ return next;+ });+}+const chosen = Array.from(selected);+```++The Map and Set constructors consume iterables natively: `new Set(prev)` and `new Map(entries)` are not the problematic spread. Do not mutate the previous React state.++**Native matchAll result**++```typescript+// WRONG — the match iterator has no array length+const text = "a1 b2";+const re = /\d/g;+const hits = [...text.matchAll(re)].map(match => match[0]);+```++```typescript+// CORRECT+const text = "a1 b2";+const re = /\d/g;+const hits = Array.from(text.matchAll(re)).map(match => match[0]);+```++**Destructuring**++```typescript+// WRONG — first is undefined+const [first] = new Set([1, 2]);+```++```typescript+// CORRECT+const [first] = Array.from(new Set([1, 2]));+```++```typescript+// WRONG — fallback replaces the actual value+const [first = "fallback"] = new Set(["actual"]);+```++```typescript+// CORRECT+const [first = "fallback"] = Array.from(new Set(["actual"]));+```++```typescript+// WRONG — throws because the emitted rest operation calls slice+const [...rest] = new Set([1, 2]);+```++```typescript+// CORRECT+const [...rest] = Array.from(new Set([1, 2]));+```++**String spread — a separate throw, not an empty iterable result**++```typescript+// WRONG+const name = "A😀";+const chars = [...name];+```++```typescript+// CORRECT — Array.from reads Unicode code points+const name = "A😀";+const chars = Array.from(name);+```++Call and constructor arguments need the same conversion: write `f(...Array.from(iterator))` and `new C(...Array.from(iterator))`, not direct iterator spreads.++These operations remain ordinary valid patterns: `[...rows]`, `[...Object.keys(row)]`, `for (const row of rows)`, `const [first] = rows`, `{ ...tokens }`, `<div {...props} />`, rest parameters, `selected.has(id)`, `seen.set(key, value)`, `new Set(prev)` and `new Map(entries)`. A first-element binding of a string reads its indexed UTF-16 element, not a whole Unicode code point.++The authoring rule also applies when an iterable comes from props, parameters, React state, a ref, a cache or another function. Static checks cannot prove all of those origins. Do not mistake a lack of findings for proof that arbitrary iteration is safe.diff --git a/plugins/model-apps/scripts/tests/genpage-dispatch-contract.test.js b/plugins/model-apps/scripts/tests/genpage-dispatch-contract.test.jsindex 665a1ecf3..d402fb4de 100644--- a/plugins/model-apps/scripts/tests/genpage-dispatch-contract.test.js+++ b/plugins/model-apps/scripts/tests/genpage-dispatch-contract.test.js@@ -1150,3 +1150,83 @@ test('every genpage-plan-provenance.js command the genpage flows document uses oconst 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');});++// Iteration that compiles to nothing (references/rules.md, Critical Rule 24 and Common Errors > 5). The SDK compiles a page to ES5 without+// iterator downleveling, so a spread, a for...of loop or an array destructure of a Map, a Set or an iterator reads length and indices: the+// values disappear with a clean compile (scripts/tests/iteration-emit.test.js runs that emit). Nothing executes these instructions, so as+// with the Griffel rule the one rule text is stated in the same words in every document that writes or edits a page (whitespace aside), and+// the WRONG/CORRECT examples live in rules.md alone.+const ITERATION_RULE = [+ 'The page compiler targets ES5 without iterator downleveling or full type checking.',+ 'Spreading, looping over, or array-destructuring a Map, Set or iterator reads length and indices instead of the iterator:',+ 'values can disappear, defaults can replace them, or rest destructuring can throw.',+ 'This includes `[...new Set(xs)]`, `[...m.values()]`, `[...seen.values()]`, `for (const [k, v] of m)`, `new Set([...prev, id])`,',+ '`[...selected]` and `[...text.matchAll(re)]`.',+ 'Convert with `Array.from(...)` before spreading, looping or destructuring; copy a Set with `new Set(prev)` then `.add(id)`.',+ 'Ordinary array spreads and loops remain valid. `Object.keys`, `Object.values` and `Object.entries` return arrays.',+ 'Spreads of `arguments` and ordinary indexed array-likes work; rest destructuring of an array-like without `slice` does not.',+ 'String spread throws, and an ES5 string loop visits UTF-16 code units rather than Unicode code points.',+ 'See **Common Errors > 5. Iteration that compiles to nothing** in `references/rules.md` for the pairs.',+].join(' ');+const ITERATION_SECTION = '**Common Errors > 5. Iteration that compiles to nothing**';++test('every instruction that writes or edits a page states the iteration rule in the same words, where it reviews the page', () => {+ const docs = griffelDocs();+ for (const [name, text] of Object.entries(docs)) {+ assert.ok(squash(text).includes(ITERATION_RULE), `${name} must state the iteration rule in the shared words`);+ }+ // rules.md: the section opens with it, after Common Errors 1-4, which keep their numbers.+ const section = docs.rules.split('\n### 5. Iteration that compiles to nothing\n');+ assert.equal(section.length, 2, 'rules.md has one canonical section');+ assert.ok(squash(section[1]).trimStart().startsWith(ITERATION_RULE), 'the section opens with the rule');+ const errors = docs.rules.slice(docs.rules.indexOf('\n## Common Errors\n'));+ const numbered = [...errors.matchAll(/^### (\d+)\. /gm)].map((match) => Number(match[1]));+ assert.deepEqual(numbered, [1, 2, 3, 4, 5], 'Common Errors 1-4 keep their numbers and 5 follows them');+ // Critical Rules 1-24, in order, ending with 24 before the separator.+ const critical = docs.rules.slice(docs.rules.indexOf('\n## Critical Rules\n'), docs.rules.indexOf('\n## Supported Libraries\n'));+ assert.deepEqual([...critical.matchAll(/^(\d+)\. \*\*/gm)].map((match) => Number(match[1])), Array.from({ length: 24 }, (_, i) => i + 1));+ assert.match(critical, /\n22\. \*\*Consistent errors\*\*[^\n]*\n23\. \*\*Lookup identities\*\*[^\n]*\n24\. \*\*Convert iterables to arrays\*\*[^\n]*\n\n---\n/);+ // The page-builder has no shell: its Step 2.7 gives the rule and a self-review, and no command.+ const builderStep = docs['page-builder'].split('## Step 2.7 — Iteration that compiles to nothing')[1].split('## Step 3')[0];+ assert.ok(squash(builderStep).includes(ITERATION_RULE), 'the page-builder states it in its own step');+ assert.ok(docs['page-builder'].indexOf('## Step 2.6') < docs['page-builder'].indexOf('## Step 2.7'), 'after the Griffel step');+ assert.doesNotMatch(builderStep, /node\s+"\$\{PLUGIN_ROOT\}/, 'no command for a worker to run');+ assert.match(squash(builderStep), /Do not return a file that spreads, loops over or array-destructures one directly\./);+ // /genpage, one page: step 9 beside the Griffel teaching, before the completeness gate of step 10.+ const fastPath = docs['create flow'].split(/#### 5b\. Single-page fast path/)[1].split(/#### 5c\. Multi-page/)[0];+ const step9 = fastPath.split(/\n9\. /)[1].split(/\n10\. /)[0];+ assert.ok(squash(step9).includes(ITERATION_RULE), 'single-page generation reviews the page it wrote');+ // An edit: before Edit Phase 6, keeping the requested scope.+ const edit = docs['edit flow'];+ const editRule = squash(edit).indexOf(ITERATION_RULE);+ assert.ok(editRule > 0 && editRule < squash(edit).indexOf('## Edit Phase 6: Deploy Updated Page'), 'an edited page is reviewed before it is uploaded');+ assert.match(squash(edit), /Do not silently expand an unrelated edit: convert an existing form only when the requested change needs it or the user asks for it, and state any resulting behavior change in the summary\./);+ // /app-builder: Phase 1.5 step 5, before promote-intent-pages.js commits the pages.+ const appBuilder = docs['app-builder'];+ const appRule = squash(appBuilder).indexOf(ITERATION_RULE);+ assert.ok(appRule > 0 && appRule < squash(appBuilder).indexOf('promote-intent-pages.js" \\'), 'generated pages are reviewed before they are promoted');+});++test('the multi-page, browser-fix and hand-edit paths point at the iteration rule, and only rules.md holds the examples', () => {+ const docs = griffelDocs();+ const multiPage = docs['create flow'].split(/#### 5c\. Multi-page/)[1].split(/### Phase 6: Deploy/)[0];+ assert.ok(squash(multiPage).includes(ITERATION_SECTION), 'multi-page generation points at the rule');+ const fix = readDoc(path.join(PLUGIN, 'skills', 'genpage', 'verify-flow.md')).split('## 7.5 Fix and Re-deploy')[1];+ assert.ok(squash(fix).includes(ITERATION_SECTION), 'a browser-verify fix points at the rule');+ const editing = docs['app-builder'].split('## Editing a deployed app')[1].split('## What the builder does')[0];+ const editStep = editing.split(/\n2\. /)[1].split(/\n3\. /)[0];+ assert.ok(squash(editStep).includes(ITERATION_SECTION), 'a page edited by hand points at the rule');+ for (const file of mdFiles()) {+ if (rel(file) === 'references/rules.md') continue;+ assert.ok(!readDoc(file).includes('// WRONG — the spread contributes no values'), `${rel(file)} must point at the rules.md examples, not copy them`);+ }+});++test('the iteration teaching promises no checker, gate code or result field', () => {+ for (const file of [...mdFiles(), path.join(PLUGIN, 'AGENTS.md')]) {+ const text = readDoc(file);+ for (const word of ['check-iteration', 'iteration-compile', 'iterationChecks']) {+ assert.ok(!text.includes(word), `${rel(file)} names ${word}, which this plugin does not ship`);+ }+ }+});diff --git a/plugins/model-apps/scripts/tests/iteration-emit.test.js b/plugins/model-apps/scripts/tests/iteration-emit.test.jsnew file mode 100644index 000000000..ae42d41ee--- /dev/null+++ b/plugins/model-apps/scripts/tests/iteration-emit.test.js@@ -0,0 +1,272 @@+'use strict';+// What the page compiler does with iteration, and the teaching that answers it (references/rules.md, Critical Rule 24 and+// Common Errors > 5. Iteration that compiles to nothing).+//+// The bundled SDK compiles a page with TypeScript's `transpileModule` and `{ target: ES5, module: ES2020, jsx: React }`+// (scripts/lib/typescript-compiler.js keeps the compiler the maker portal uses). Without `downlevelIteration`, ES5 emit+// reads an iterable by `length` and index: a spread becomes `__spreadArray([], value, true)`, a `for...of` becomes an+// indexed `for` loop, and an array destructure reads `value[0]` (and calls `value.slice` for a rest element). A Map, a Set,+// their iterators, a generator, a native `matchAll` result, URLSearchParams, FormData and Headers have no `length`, so the+// spread contributes nothing, the loop runs zero times, an element is undefined, a default replaces the real value and a+// rest element throws. `transpileModule` reports syntax only, so the TS2802 error a type check would give never appears.+//+// Every case here is compiled by the vendored compiler with exactly those options and run in a fresh vm context; the+// expected values are what that emit does, never what modern JavaScript would do. Results cross the context boundary as+// JSON (undefined and thrown errors are compared separately), so nothing depends on another realm's prototypes. The host's+// own URLSearchParams, FormData and Headers are handed in for their cases: nothing is fetched and no DOM is used.+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 { loadVendoredTypeScript } = require('../lib/typescript-compiler.js');++const RULES = fs.readFileSync(path.join(__dirname, '..', '..', 'references', 'rules.md'), 'utf8').replace(/\r\n?/g, '\n');+const HEADING = '### 5. Iteration that compiles to nothing';++let typescript;+const ts = () => (typescript ||= loadVendoredTypeScript());+// The SDK's options, exactly. A test here is never fixed by changing the target or adding downlevelIteration.+function compile(source) {+ const { outputText, diagnostics } = ts().transpileModule(source, {+ compilerOptions: { target: ts().ScriptTarget.ES5, module: ts().ModuleKind.ES2020, jsx: ts().JsxEmit.React },+ reportDiagnostics: true,+ });+ return { outputText, codes: (diagnostics || []).map((d) => d.code) };+}++const HOST_GLOBALS = { URLSearchParams, FormData, Headers };+// Compiles `source`, runs it in a fresh context (plus `prelude`, plain JavaScript run first in the same context) and reads the+// named top-level values back. A value is JSON-normalized; `undefined` stays undefined; a throw is { threw: <error name> }.+function run(source, names, { prelude = '', after = '' } = {}) {+ const { outputText, codes } = compile(source);+ assert.deepEqual(codes, [], 'the compile reports nothing — not even TS2802, which only a type check gives');+ const context = vm.createContext({ ...HOST_GLOBALS });+ try {+ vm.runInContext(`${prelude}\n${outputText}\n${after}`, context, { filename: 'iteration-case.js' });+ } catch (error) {+ return { threw: error && error.name, outputText };+ }+ const values = {};+ for (const name of names) {+ const value = context[name];+ values[name] = value === undefined ? undefined : JSON.parse(JSON.stringify(value));+ }+ return { values, outputText };+}++// ── The emit itself ──────────────────────────────────────────────────────────────────────────────────────────────────────────++// Each family the teaching names, made fresh for each arm (an iterator is spent once read).+const FAMILIES = [+ ['a Map', 'return new Map([["a", 1], ["b", 2]]);', [['a', 1], ['b', 2]]],+ ['a Set', 'return new Set([1, 2]);', [1, 2]],+ ['a Map\'s keys()', 'return new Map([["a", 1], ["b", 2]]).keys();', ['a', 'b']],+ ['a Map\'s values()', 'return new Map([["a", 1], ["b", 2]]).values();', [1, 2]],+ ['a Map\'s entries()', 'return new Map([["a", 1]]).entries();', [['a', 1]]],+ ['a Set\'s values()', 'return new Set([1, 2]).values();', [1, 2]],+ ['an array\'s values()', 'return [1, 2].values();', [1, 2]],+ ['an array\'s entries()', 'return ["x"].entries();', [[0, 'x']]],+ ['a generator', 'return (function* () { yield 1; yield 2; })();', [1, 2]],+ ['a native matchAll result', 'var text = "a1 b2"; var re = /\\d/g; return text.matchAll(re);', [['1'], ['2']]],+ ['URLSearchParams', 'return new URLSearchParams("a=1&b=2");', [['a', '1'], ['b', '2']]],+ ['FormData', 'var form = new FormData(); form.append("a", "1"); return form;', [['a', '1']]],+ ['Headers', 'return new Headers([["a", "1"]]);', [['a', '1']]],+];++test('a spread of each native collection, iterator, generator and host iterable contributes no element; Array.from reads them all', () => {+ for (const [label, body, values] of FAMILIES) {+ const { values: got, outputText } = run(`function make(): any { ${body} }\nconst wrong = [0, ...make()];\nconst right = [0, ...Array.from(make())];\n`, ['wrong', 'right']);+ assert.match(outputText, /__spreadArray\(\[0\], make\(\), true\)/, `${label}: ES5 emit copies it as an array-like`);+ assert.deepEqual(got.wrong, [0], `${label}: the spread adds nothing, and the elements around it survive`);+ assert.deepEqual(got.right, [0, ...values], `${label}: converted first, every value arrives in order`);+ }+});++test('a call or constructor argument spread of an iterable passes no argument; spreading Array.from passes them all', () => {+ const source = `function make(): any { return new Set(["a", "b"]); }+function collect(...items: string[]) { return items; }+function Collect(this: any, ...items: string[]) { this.items = items; }+const wrongCall = collect("x", ...make());+const rightCall = collect("x", ...Array.from(make()));+const wrongNew = new (Collect as any)(...make()).items;+const rightNew = new (Collect as any)(...Array.from(make())).items;+`;+ const { values } = run(source, ['wrongCall', 'rightCall', 'wrongNew', 'rightNew']);+ assert.deepEqual(values, { wrongCall: ['x'], rightCall: ['x', 'a', 'b'], wrongNew: [], rightNew: ['a', 'b'] });+});++test('a for...of over a Map runs zero times, pair binding included; looping over Array.from keeps the loop and its pairs', () => {+ const source = `const m = new Map([["a", 1], ["b", 2]]);+const wrong: Array<[string, number]> = [];+for (const [k, v] of m) wrong.push([k, v]);+const right: Array<[string, number]> = [];+for (const [k, v] of Array.from(m)) right.push([k, v]);+let early = "";+for (const [k] of Array.from(m)) { if (k === "b") { early = k; break; } }+`;+ const { values } = run(source, ['wrong', 'right', 'early']);+ assert.deepEqual(values, { wrong: [], right: [['a', 1], ['b', 2]], early: 'b' });+});++test('array destructuring of a Set reads indices: an element is undefined, a default replaces the value, a rest element throws', () => {+ const element = run('const [first] = new Set([1, 2]);\nconst [second] = Array.from(new Set([1, 2]));\n', ['first', 'second']);+ assert.equal(element.values.first, undefined);+ assert.equal(element.values.second, 1);+ const fallback = run('const [first = "fallback"] = new Set(["actual"]);\nconst [second = "fallback"] = Array.from(new Set(["actual"]));\n', ['first', 'second']);+ assert.deepEqual(fallback.values, { first: 'fallback', second: 'actual' });+ // A hole moves the index the element is read from; it is still not the iterator's value.+ const hole = run('const [, b] = new Set(["x", "y"]);\nconst [, c] = Array.from(new Set(["x", "y"]));\n', ['b', 'c']);+ assert.deepEqual(hole.values, { b: undefined, c: 'y' });+ const rest = run('const [...rest] = new Set([1, 2]);\n', ['rest']);+ assert.equal(rest.threw, 'TypeError', 'the emitted rest element calls slice, which a Set does not have');+ assert.match(rest.outputText, /\.slice\(0\)/);+ assert.deepEqual(run('const [...rest] = Array.from(new Set([1, 2]));\n', ['rest']).values.rest, [1, 2]);+ const assigned = run('let first: any = "before";\n([first] = new Set([1]) as any);\nlet second: any;\n([second] = Array.from(new Set([1])));\n', ['first', 'second']);+ assert.deepEqual(assigned.values, { first: undefined, second: 1 });+});++test('the unique-value idiom and a Set-based selection append lose every value; Array.from and a native Set copy keep them', () => {+ const unique = run('const xs = [1, 1, 2];\nconst wrong = [...new Set(xs)];\nconst right = Array.from(new Set(xs));\n', ['wrong', 'right']);+ assert.deepEqual(unique.values, { wrong: [], right: [1, 2] });+ const source = `const prev = new Set(["a"]);+const appended = new Set([...prev, "b"]);+const copied = new Set(prev);+copied.add("b");+const wrong = Array.from(appended);+const right = Array.from(copied);+`;+ assert.deepEqual(run(source, ['wrong', 'right']).values, { wrong: ['b'], right: ['a', 'b'] }, 'the prior selection is lost, then kept');+});++// ── Neighbours: what keeps working, and the distinct string and array-like behaviours the teaching states ───────────────────────++test('ordinary arrays, Object helpers, array-likes, arguments and native constructor copies are unaffected', () => {+ const source = `const rows = [1, 2];+const spread = [...rows, 3];+let looped = 0;+for (const row of rows) looped += row;+const [head] = rows;+const keys = [...Object.keys({ a: 1, b: 2 })];+const entries: Array<[string, number]> = [];+for (const [k, v] of Object.entries({ a: 1 })) entries.push([k, v]);+const like: any = { length: 2, 0: "x", 1: "y" };+const fromLike = [...like];+function args(..._: any[]) { return [...(arguments as any)]; }+const fromArguments = args(1, 2);+const copiedSet = Array.from(new Set(new Set([1, 2])));+const copiedMap = Array.from(new Map(new Map([["k", 1]])));+const objectSpread = { ...{ a: 1 }, b: 2 };+`;+ const { values } = run(source, ['spread', 'looped', 'head', 'keys', 'entries', 'fromLike', 'fromArguments', 'copiedSet', 'copiedMap', 'objectSpread']);+ assert.deepEqual(values, {+ spread: [1, 2, 3], looped: 3, head: 1, keys: ['a', 'b'], entries: [['a', 1]], fromLike: ['x', 'y'], fromArguments: [1, 2],+ copiedSet: [1, 2], copiedMap: [['k', 1]], objectSpread: { a: 1, b: 2 },+ });+});++test('a string spread throws, an ES5 string loop visits UTF-16 code units, and Array.from reads code points', () => {+ assert.equal(run('const name = "A😀";\nconst chars = [...name];\n', ['chars']).threw, 'TypeError');+ const { values } = run('const name = "A😀";\nconst units: string[] = [];\nfor (const c of name) units.push(c);\nconst points = Array.from(name);\nconst [first] = name;\n', ['units', 'points', 'first']);+ assert.equal(values.units.length, 3, 'the astral character is two units');+ assert.deepEqual(values.points, ['A', '😀']);+ assert.equal(values.first, 'A', 'a first-element binding reads the indexed UTF-16 element');+});++test('a rest destructure of an array-like without slice throws; a custom Symbol.matchAll that returns an array spreads fine', () => {+ assert.equal(run('const like: any = { length: 1, 0: "x" };\nconst [...rest] = like;\n', ['rest']).threw, 'TypeError');+ const source = `const matcher: any = { [Symbol.matchAll](text: string) { return [text.length]; } };+const hits = [..."abc".matchAll(matcher)];+`;+ assert.deepEqual(run(source, ['hits']).values.hits, [3], 'the string method delegates to the matcher, which may return an array');+});++// ── The teaching: Critical Rule 24 and Common Errors §5 ───────────────────────────────────────────────────────────────────────++// The section, its labelled fences in order, and each fence's role. Every fence is its own example: none shares a declaration+// with another, so each is compiled and run alone.+function teaching() {+ const at = RULES.indexOf(`\n${HEADING}\n`);+ assert.ok(at > 0, `rules.md has "${HEADING}"`);+ const rest = RULES.slice(at + 1);+ const next = rest.slice(HEADING.length).search(/\n#{2,3} /);+ const section = next < 0 ? rest : rest.slice(0, HEADING.length + next);+ const examples = [];+ let label = null;+ const pattern = /^\*\*(.+?)\*\*$|^```typescript\n([\s\S]*?)\n```$/gm;+ for (const match of section.matchAll(pattern)) {+ if (match[1] !== undefined) { label = match[1]; continue; }+ const code = match[2];+ const role = /^\/\/ (WRONG|CORRECT)\b/.exec(code);+ examples.push({ label, role: role && role[1], code });+ }+ return { section, examples };+}++// What each pair is taught to do: the WRONG example's emitted result, then the CORRECT one's.+const TAUGHT = {+ 'Map values': { name: 'choices', wrong: [], right: [1, 2] },+ 'Unique values': { name: 'unique', wrong: [], right: [1, 2] },+ 'Map pairs': { name: 'rows', wrong: [], right: [['a', 1], ['b', 2]] },+ 'Native matchAll result': { name: 'hits', wrong: [], right: ['1', '2'] },+ 'String spread — a separate throw, not an empty iterable result': { name: 'chars', wrong: 'throws', right: ['A', '😀'] },+};++test('Common Errors §5 holds separate WRONG and CORRECT fences, and each compiles under the SDK options and does what it says', () => {+ const { examples } = teaching();+ assert.ok(examples.length >= 16, 'the pairs are there');+ for (const example of examples) {+ assert.ok(example.role, `every fence in the section opens with // WRONG or // CORRECT (${example.label})`);+ assert.equal((example.code.match(/\/\/ (?:WRONG|CORRECT)\b/g) || []).length, 1, `one role per fence, never a WRONG and a CORRECT in one scope (${example.label})`);+ assert.deepEqual(compile(example.code).codes, [], `${example.label} ${example.role} compiles`);+ }+ for (const [label, { name, wrong, right }] of Object.entries(TAUGHT)) {+ const pair = examples.filter((example) => example.label === label);+ assert.deepEqual(pair.map((example) => example.role), ['WRONG', 'CORRECT'], `${label}: one WRONG, then one CORRECT`);+ const [bad, good] = pair.map((example) => run(example.code, [name]));+ if (wrong === 'throws') assert.equal(bad.threw, 'TypeError', `${label}: the WRONG example throws`);+ else assert.deepEqual(bad.values[name], wrong, `${label}: the WRONG example loses the values`);+ assert.deepEqual(good.values[name], right, `${label}: the CORRECT example keeps them`);+ }+});++test('the destructuring pairs: an undefined element, a default that replaces the value, and a rest element that throws', () => {+ const pairs = teaching().examples.filter((example) => example.label === 'Destructuring');+ assert.deepEqual(pairs.map((example) => example.role), ['WRONG', 'CORRECT', 'WRONG', 'CORRECT', 'WRONG', 'CORRECT']);+ const [elementBad, elementGood, defaultBad, defaultGood, restBad, restGood] = pairs.map((example) => run(example.code, /\.\.\.rest/.test(example.code) ? ['rest'] : ['first']));+ assert.equal(elementBad.values.first, undefined);+ assert.equal(elementGood.values.first, 1);+ assert.equal(defaultBad.values.first, 'fallback');+ assert.equal(defaultGood.values.first, 'actual');+ assert.equal(restBad.threw, 'TypeError');+ assert.deepEqual(restGood.values.rest, [1, 2]);+});++// The selection examples are component-body code: they run here under a controlled `React.useState` whose state already holds a+// prior selection, and the handler is called as an event would call it — never a setter called unconditionally during render.+test('the selection-state pair: the WRONG updater loses the prior ids and its render read loses every value; the CORRECT one keeps them', () => {+ const pair = teaching().examples.filter((example) => /^Selection state/.test(example.label || ''));+ assert.deepEqual(pair.map((example) => example.role), ['WRONG', 'CORRECT']);+ const prelude = `var __state = new Set(["a"]);+var React = { useState: function () { return [__state, function (next) { __state = typeof next === "function" ? next(__state) : next; }]; } };`;+ const after = 'addSelected("b"); var __after = Array.from(__state); var __render = chosen;';+ const [bad, good] = pair.map((example) => {+ assert.doesNotMatch(example.code, /^set[A-Z]\w*\(/m, 'no setter is called at the top level of the render');+ return run(example.code, ['__after', '__render'], { prelude, after });+ });+ assert.deepEqual(bad.values, { __after: ['b'], __render: [] }, 'the updater keeps only the new id, and the render read is empty');+ assert.deepEqual(good.values, { __after: ['a', 'b'], __render: ['a'] }, 'the native copy keeps the prior id, and Array.from reads the selection');+});++test('Critical Rule 24 names the forms, the conversion and the section, after Rule 23 and before the separator', () => {+ const critical = RULES.slice(RULES.indexOf('\n## Critical Rules\n'), RULES.indexOf('\n## Supported Libraries\n'));+ const rule = /\n24\. (\*\*Convert iterables to arrays\*\*: .*)\n/.exec(critical);+ assert.ok(rule, 'rules.md has Critical Rule 24');+ assert.ok(critical.indexOf('\n23. **Lookup identities**') < rule.index, 'it follows Rule 23');+ assert.match(critical.slice(rule.index), /^\n24\. [^\n]*\n\n---\n/, 'and is the last rule before the separator');+ for (const form of ['`[...new Set(xs)]`', '`[...m.values()]`', '`for (const [k, v] of m)`', '`new Set([...prev, id])`', '`[...selected]`', '`[...text.matchAll(re)]`', '`Array.from`']) {+ assert.ok(rule[1].includes(form), `Rule 24 names ${form}`);+ }+ assert.match(rule[1], /See \*\*Common Errors > 5\. Iteration that compiles to nothing\*\*\.$/);+ assert.equal(RULES.split(`\n${HEADING}\n`).length, 2, 'one canonical section');+});diff --git a/plugins/model-apps/skills/app-builder/SKILL.md b/plugins/model-apps/skills/app-builder/SKILL.mdindex d3a044d74..2fa6a8d51 100644--- a/plugins/model-apps/skills/app-builder/SKILL.md+++ b/plugins/model-apps/skills/app-builder/SKILL.md@@ -365,6 +365,21 @@ After plan-mode approval (before the full build):that starts with `--`, `&`, `:` or `@` is read); Fluent's `...shorthands.*(…)` and`...typographyStyles.*` may be spread as they are.+ Review every generated page for iteration that compiles to nothing as well:++ The page compiler targets ES5 without iterator downleveling or full type checking. Spreading,+ looping over, or array-destructuring a Map, Set or iterator reads length and indices instead of+ the iterator: values can disappear, defaults can replace them, or rest destructuring can throw.+ This includes `[...new Set(xs)]`, `[...m.values()]`, `[...seen.values()]`,+ `for (const [k, v] of m)`, `new Set([...prev, id])`, `[...selected]` and+ `[...text.matchAll(re)]`. Convert with `Array.from(...)` before spreading, looping or+ destructuring; copy a Set with `new Set(prev)` then `.add(id)`. Ordinary array spreads and loops+ remain valid. `Object.keys`, `Object.values` and `Object.entries` return arrays. Spreads of+ `arguments` and ordinary indexed array-likes work; rest destructuring of an array-like without+ `slice` does not. String spread throws, and an ES5 string loop visits UTF-16 code units rather+ than Unicode code points. See **Common Errors > 5. Iteration that compiles to nothing** in+ `references/rules.md` for the pairs.+Then validate and commit the transition — never flip `source` by hand, and neverflip pages one at a time as workers return. Run:```bash@@ -781,6 +796,10 @@ Then:A page you did not touch is sent again as it is, and akey it already has only draws a warning — and so does a page you changed in a workspace that holds no record of it (a new or moved one, oranother environment), where the build cannot tell what was sent: run the checker on that page yourself.+ A page you edit by hand also follows the iteration rule of Phase 1.5, step 5 (**Common Errors > 5.+ Iteration that compiles to nothing** in `references/rules.md`): convert a Map, Set or iterator with+ `Array.from` before spreading, looping over or destructuring it. Converting a form the page already+ had can make previously absent values appear, so do it only when the requested change needs it.3. **If the edit ADDS a page** (or resets a page's `source` back to `intent` to regenerate it),**re-run Phase 1.5 before Phase 2** — a downloaded spec contains only `kind: "tsx"` pages, so anadded `intent` page has no code and Phase 2's `deploy` profile rejects it. Phase 1.5 is safe todiff --git a/plugins/model-apps/skills/genpage/SKILL.md b/plugins/model-apps/skills/genpage/SKILL.mdindex 40803a6a5..811d6d71a 100644--- a/plugins/model-apps/skills/genpage/SKILL.md+++ b/plugins/model-apps/skills/genpage/SKILL.md@@ -911,6 +911,22 @@ subagent. Inline the page-builder workflow directly in the orchestrator:keys, and so is a key computed from an expression (`[key]: …`), whose name itcannot see (a template that starts with `--`, `&`, `:` or `@` is read); Fluent's`...shorthands.*(…)` and `...typographyStyles.*` may be spread as they are.++ Then review the page for iteration that compiles to nothing:++ The page compiler targets ES5 without iterator downleveling or full type checking.+ Spreading, looping over, or array-destructuring a Map, Set or iterator reads length+ and indices instead of the iterator: values can disappear, defaults can replace them,+ or rest destructuring can throw. This includes `[...new Set(xs)]`, `[...m.values()]`,+ `[...seen.values()]`, `for (const [k, v] of m)`, `new Set([...prev, id])`,+ `[...selected]` and `[...text.matchAll(re)]`. Convert with `Array.from(...)` before+ spreading, looping or destructuring; copy a Set with `new Set(prev)` then `.add(id)`.+ Ordinary array spreads and loops remain valid. `Object.keys`, `Object.values` and+ `Object.entries` return arrays. Spreads of `arguments` and ordinary indexed+ array-likes work; rest destructuring of an array-like without `slice` does not.+ String spread throws, and an ES5 string loop visits UTF-16 code units rather than+ Unicode code points. See **Common Errors > 5. Iteration that compiles to nothing**+ in `references/rules.md` for the pairs.10. Run the completeness gate on the page you wrote — the same one 5c runs on aworker's page, and this is also the page a 5c fallback produces:@@ -1014,7 +1030,9 @@ node "${PLUGIN_ROOT}/scripts/check-griffel-styles.js" --file '<working-dir>/<fil```and fix what it reports in the page yourself before Phase 6. A page that has not-exited 0 is not deployed.+exited 0 is not deployed. Review every generated page for iteration that compiles to+nothing as well, and fix it yourself: the workers follow the same rule+(`references/rules.md`, **Common Errors > 5. Iteration that compiles to nothing**).### Phase 6: Deploydiff --git a/plugins/model-apps/skills/genpage/edit-flow.md b/plugins/model-apps/skills/genpage/edit-flow.mdindex 82f77d6b2..b709a3a12 100644--- a/plugins/model-apps/skills/genpage/edit-flow.md+++ b/plugins/model-apps/skills/genpage/edit-flow.md@@ -560,6 +560,28 @@ the same, go ahead with a`warnings` entry, but the page then goes on rendering without it — do not rely on that toskip this step.)+Review the edited page for iteration that compiles to nothing as well:++The page compiler targets ES5 without iterator downleveling or full type checking.+Spreading, looping over, or array-destructuring a Map, Set or iterator reads length+and indices instead of the iterator: values can disappear, defaults can replace them,+or rest destructuring can throw. This includes `[...new Set(xs)]`, `[...m.values()]`,+`[...seen.values()]`, `for (const [k, v] of m)`, `new Set([...prev, id])`,+`[...selected]` and `[...text.matchAll(re)]`. Convert with `Array.from(...)` before+spreading, looping or destructuring; copy a Set with `new Set(prev)` then `.add(id)`.+Ordinary array spreads and loops remain valid. `Object.keys`, `Object.values` and+`Object.entries` return arrays. Spreads of `arguments` and ordinary indexed array-likes+work; rest destructuring of an array-like without `slice` does not. String spread+throws, and an ES5 string loop visits UTF-16 code units rather than Unicode code+points. See **Common Errors > 5. Iteration that compiles to nothing** in+`references/rules.md` for the pairs.++Write every form your edit adds with that conversion. A form the page already had+before your edit loses its values today, and converting it with `Array.from` can make+previously absent values appear or stop a throw — a change users see. Do not silently+expand an unrelated edit: convert an existing form only when the requested change needs+it or the user asks for it, and state any resulting behavior change in the summary.+## Edit Phase 6: Deploy Updated PageThis is an **update** (existing page-id), so the prompt must describe thediff --git a/plugins/model-apps/skills/genpage/verify-flow.md b/plugins/model-apps/skills/genpage/verify-flow.mdindex 4fe2b488f..ebac4252a 100644--- a/plugins/model-apps/skills/genpage/verify-flow.md+++ b/plugins/model-apps/skills/genpage/verify-flow.md@@ -111,6 +111,9 @@ deployed page did not already have, or gives one it had another value (`griffel-upload, not a shipped defect. A key the page already had before your fix, set the same, is reported as well:delete it to keep the page looking as it does, or write the longhands to make the style start torender (a visible change, so only when it is wanted).+A fix is held to the iteration rule too: convert a Map, Set or iterator with `Array.from` before+spreading, looping over or destructuring it (`references/rules.md`, **Common Errors > 5. Iteration+that compiles to nothing**).Per the "Prompt semantics" rule, the prompt for thisre-deploy describes the fix delta only — e.g.`"Fix sort handler on Name column; correct accidental DataGrid type prop"` —