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
Add analyze-performance skill for non-SPA sites (#470)
poojalnub9786a154999
diff --git a/plugins/power-pages/.claude-plugin/plugin.json b/plugins/power-pages/.claude-plugin/plugin.jsonindex e1bf40dfb..7d9da0c6a 100644--- a/plugins/power-pages/.claude-plugin/plugin.json+++ b/plugins/power-pages/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "power-pages",- "version": "2.9.0",+ "version": "2.10.0","description": "Create and deploy Power Pages sites using modern development approaches. Supports code sites (SPAs) with React, Angular, Vue, or Astro. Adds multilingual localization and safe runtime LTR/RTL switching for React, Vue, and Angular runtime sites; Astro and Angular static localization are temporarily unavailable. Includes ALM orchestration (plan-alm) with a solution-splitting decision tree, per-solution pipelines, Azure Blob asset advisory, manifest schema v2 for multi-solution deployments, and force-link remediation for cross-host pipeline migrations.","author": {"name": "Microsoft",diff --git a/plugins/power-pages/.plugin/plugin.json b/plugins/power-pages/.plugin/plugin.jsonindex e1bf40dfb..7d9da0c6a 100644--- a/plugins/power-pages/.plugin/plugin.json+++ b/plugins/power-pages/.plugin/plugin.json@@ -1,6 +1,6 @@{"name": "power-pages",- "version": "2.9.0",+ "version": "2.10.0","description": "Create and deploy Power Pages sites using modern development approaches. Supports code sites (SPAs) with React, Angular, Vue, or Astro. Adds multilingual localization and safe runtime LTR/RTL switching for React, Vue, and Angular runtime sites; Astro and Angular static localization are temporarily unavailable. Includes ALM orchestration (plan-alm) with a solution-splitting decision tree, per-solution pipelines, Azure Blob asset advisory, manifest schema v2 for multi-solution deployments, and force-link remediation for cross-host pipeline migrations.","author": {"name": "Microsoft",diff --git a/plugins/power-pages/AGENTS.md b/plugins/power-pages/AGENTS.mdindex 6566a30f6..9fee93de5 100644--- a/plugins/power-pages/AGENTS.md+++ b/plugins/power-pages/AGENTS.md@@ -187,6 +187,7 @@ User-invocable via `/power-pages:<skill-name>`:- `add-sample-data`: 6-step workflow — verify prerequisites, discover tables (from `.datamodel-manifest.json` or OData API), select tables & configure record count, generate & review sample data plan, insert records via OData API with relationship handling, verify & summarize.- `activate-site`: 5-step workflow — verify prerequisites (PAC CLI auth + Azure CLI token + cloud-aware API URL resolution + activation status check via shared script), gather parameters (site name, subdomain, website record ID), confirm with user, activate & poll via `skills/activate-site/scripts/activate-site.js`, present summary with site URL.- `add-seo`: 7-step workflow — verify site exists, gather SEO config (production URL, exclusions, meta description), plan & approve, create robots.txt, generate sitemap.xml from discovered routes, add meta tags (title, description, viewport, Open Graph, Twitter Card, favicon) to index.html, verify via Playwright & commit.+- `analyze-performance`: 6-phase (+1.5 Learn grounding and 2.5 AI mitigation pass) workflow — locate an existing local non-SPA site folder (reject `powerpages.config.json`, the authoritative SPA marker; accept `.powerpages-site` or root-level `.portalconfig` / `website.yml` exports), scan the entire local codebase via the deterministic `skills/analyze-performance/scripts/analyze-performance.js` for performance anti-patterns (Power Pages lists without page size, FetchXML/entity-backed webpages used as JSON/XML APIs, FetchXML `all-attributes`/no-columns/many-columns/no-paging/large-count/N+1-in-loop/`returntotalrecordcount`/advanced query hints/cache bypassing/leading-wildcard filters/related-column ordering, Web API `$select=*`/no-`$select`/many-columns/no-page-bound/large-`$top`/`$count=true`/expanded rows without nested `$select`/contains-or-endswith filters/request-time date cache bypassing/related-column ordering/N+1, main-thread-blocking client JS — sync XHR, sync jQuery AJAX, `document.write`, short-interval `/_api/` polling — render-blocking `<head>` scripts, runtime CSS `@import`, header/footer output caching disabled, sign-in & page/file tracking, web-file/web-role counts, oversized assets), enrich each static finding with AI-generated `aiSuggestion` and `mitigation` text grounded in the affected customer-code snippet, present findings by severity, offer safe auto-fixes for the site-setting/tracking findings with explicit per-fix consent (surfacing the `{% substitution %}` output-cache caveat), re-scan to verify, then persist an HTML report under `<site>/docs/` via the shared `build-review-data.js` + `render-review.js` pipeline (`analyze-performance.json` → Performance section) and route the manual list/webpage/FetchXML/Web API/JS/CSS fixes. Read-only until consent; supports `--review <out-dir>` mode, including using that directory as the project root when it contains site source. Validator: `skills/analyze-performance/scripts/validate-analyze-performance.js`. Rule catalog: `skills/analyze-performance/references/performance-reference.md`.- `add-localization`: 8-phase workflow — detect framework/existing i18n, enforce centralized mode availability, validate BCP-47 locales and package choices, approve exact file delta, configure framework localization, extract/generate translations, add runtime selection, validate/build/browser-test, review, and conditionally deploy. React/Vue/Angular runtime are active; Angular static and Astro static remain documented dormant capabilities and must not enter a plan or pass validation.- `create-webroles`: 6-step workflow — verify `.powerpages-site/web-roles/` exists (redirect to deploy-site if missing), discover existing roles, determine new roles needed, create web role YAML files with UUIDs from shared `scripts/generate-uuid.js`, verify web roles (validate files, UUIDs, uniqueness constraints), review & prompt deployment via deploy-site skill.- `integrate-webapi`: 7-step workflow — verify site exists, use Explore agent to analyze code and identify tables needing Web API integration, review plan with user, invoke `webapi-integration` agent per table to create API client/types/services/hooks, verify integrations (validate all files exist, project builds), invoke `table-permissions-architect` and `webapi-settings-architect` agents (in parallel) to configure table permissions and site settings, review & deploy via `deploy-site` skill. Supports an `[AI-READ-ONLY]` sentinel that hardens the flow to read-only when invoked by `/add-ai-webapi`.@@ -315,7 +316,7 @@ Shared reference documents live at `references/` and are referenced by multiple- `solution-api-patterns.md`: OData body templates for publisher POST, solution POST, `AddSolutionComponent`, `ExportSolutionAsync`, `DownloadSolutionExportData`, `ImportSolutionAsync`, `StageSolution`. Also documents `.solution-manifest.json` format. Used by `setup-solution`, `export-solution`, and `import-solution`.- `deployment-error-catalog.md`: Catalog of 10 known deployment failure patterns (stale manifest, blocked JS, missing websiteRecordId, auth expiry, empty build output, solution missing dependencies, solution timeout, PAC CLI not installed, environment mismatch, duplicate component). Each entry includes root cause, severity, auto-fix availability, and fix procedure. Used by `diagnose-deployment`.- `cicd-pipeline-patterns.md`: PAC CLI service principal auth syntax; complete ADO `azure-pipelines.yml` template; complete GitHub Actions `deploy.yml` template; commented solution export/import blocks; secrets/variables setup tables; manual steps that cannot be automated; **Power Platform Pipelines API patterns** (HAR-confirmed): host env discovery via `RetrieveSetting`, `deploymentenvironments` create + `validationstatus` poll, `deploymentpipelines` create, `$ref` associate source (relative path format), `deploymentstages` create, `RetrieveDeploymentPipelineInfo`, stage run create + `ValidatePackageAsync` (204) + `operation` poll, `deploymentsettingsjson` PATCH, `DeployPackageAsync`, `stagerunstatus` terminal values, `docs/alm/last-pipeline.json` and `docs/alm/last-deploy.json` formats. Used by `setup-pipeline` and `deploy-pipeline`.-- `approval-gates.md`: Canonical terminology, marker syntax, and catalog of every user-confirmation point ("Approval Gate") across the **entire power-pages skill set** (12 ALM + 12 non-ALM). Defines six categories (`intent` / `plan` / `progress` / `consent` / `final` / `pause`), an explicit-pairing marker (`<!-- gate: skill:phase | category=X | cancel-leaves=Y -->` + human `> 🚦 Gate (...)` block), the `cancel-leaves` vocabulary, and the seven gate-related lint rules enforced by `scripts/lint-skills-alm.js` at hard-fail severity: `GATE-must-have-marker`, `GATE-id-must-be-unique`, `GATE-must-be-in-catalog`, `GATE-intent-must-call-helper`, `GATE-cancel-leaves-known-vocab`, `GATE-prose-block-required` (marker must be followed by a 🚦 prose block within 10 lines, outside any code fence), and `CATALOG-row-must-have-marker` (reverse of `GATE-must-be-in-catalog` — every `kind: gate` catalog row must have a SKILL.md marker). §6.1–§6.12 catalogue the ALM skills; §6.13–§6.24 catalogue the non-ALM skills (`create-site`, `deploy-site`, `add-server-logic`, `add-cloud-flow`, `setup-auth`, `integrate-webapi`, `setup-datamodel`, `add-sample-data`, `add-seo`, `create-webroles`, `audit-permissions`, `integrate-backend`). `report-issue` is excluded because its workflow lives in the cross-plugin shared file. **New skills must extend §6 in the same PR they introduce an `AskUserQuestion`** — lint will block the PR otherwise.+- `approval-gates.md`: Canonical terminology, marker syntax, and catalog of every user-confirmation point ("Approval Gate") across the **entire power-pages skill set**. Defines six categories (`intent` / `plan` / `progress` / `consent` / `final` / `pause`), an explicit-pairing marker (`<!-- gate: skill:phase | category=X | cancel-leaves=Y -->` + human `> 🚦 Gate (...)` block), the `cancel-leaves` vocabulary, and the seven gate-related lint rules enforced by `scripts/lint-skills-alm.js` at hard-fail severity: `GATE-must-have-marker`, `GATE-id-must-be-unique`, `GATE-must-be-in-catalog`, `GATE-intent-must-call-helper`, `GATE-cancel-leaves-known-vocab`, `GATE-prose-block-required` (marker must be followed by a 🚦 prose block within 10 lines, outside any code fence), and `CATALOG-row-must-have-marker` (reverse of `GATE-must-be-in-catalog` — every `kind: gate` catalog row must have a SKILL.md marker). §6.1–§6.12 catalogue the ALM skills; §6.13–§6.35 catalogue the non-ALM skills, including `analyze-performance`. `report-issue` is excluded because its workflow lives in the cross-plugin shared file. **New skills must extend §6 in the same PR they introduce an `AskUserQuestion`** — lint will block the PR otherwise.Skill-specific reference docs (e.g., `skills/setup-datamodel/references/odata-api-patterns.md`) contain only patterns unique to that skill and point to the shared docs via `${PLUGIN_ROOT}/references/` paths for common content.@@ -344,6 +345,10 @@ Checks created Dataverse data models by reading `.datamodel-manifest.json` (writChecks SEO assets added to Power Pages sites: verifies `robots.txt` exists in `public/` with proper `User-agent` and `Sitemap` directives, `sitemap.xml` exists with `<urlset>` and `<loc>` entries (no unreplaced placeholders), and `index.html` has `meta description` and `viewport` tags. Only runs validation when at least one SEO file (robots.txt or sitemap.xml) is detected — gracefully exits 0 otherwise to avoid blocking non-SEO sessions.+### `analyze-performance/scripts/validate-analyze-performance.js`++Validates the exact HTML report path passed with `--reportPath` after Phase 6.3 renders it. Blocks when that current report is missing, unreadable, suspiciously small (< 500 bytes), or still contains unreplaced `__PLACEHOLDER__` tokens from the shared report template. The auto-discovered Skill PostToolUse invocation has no report path and intentionally approves because it fires when the skill instructions are loaded, before rendering; it never inspects historical reports.+### `add-localization/scripts/validate-localization.js`Checks `.powerpages-localization.json`, framework/package/mode consistency,diff --git a/plugins/power-pages/README.md b/plugins/power-pages/README.mdindex 55cd9f69b..25fd32916 100644--- a/plugins/power-pages/README.md+++ b/plugins/power-pages/README.md@@ -40,7 +40,7 @@ This keeps hook behavior in one place and avoids relying on skill-frontmatter ho## Skills-The plugin provides 36 skills that cover the full lifecycle of a Power Pages site — scaffolding, deployment, data modeling, backend integration, authentication, localization, ALM and CI/CD, security review, testing, auditing, and platform migrations. Each skill is invoked conversationally — just describe what you want to do.+The plugin provides 37 skills that cover the full lifecycle of a Power Pages site — scaffolding, deployment, data modeling, backend integration, authentication, localization, ALM and CI/CD, security review, performance, testing, auditing, and platform migrations. Each skill is invoked conversationally — just describe what you want to do.### Site scaffolding and deployment@@ -463,6 +463,19 @@ Adds search engine optimization artifacts: `robots.txt`, `sitemap.xml`, and meta- Generates sitemap with production URLs- Adds viewport, charset, description, and social sharing meta tags+#### `/analyze-performance`++> "Check my site for performance anti-patterns"++Statically scans the entire local codebase for Power Pages performance anti-patterns — unpaginated lists, webpages/web templates used as APIs, FetchXML over-fetching, N+1 queries, wildcard/contains-style filters, advanced query hints, query cache bypassing, unbounded/over-expanded Web API calls, related-column ordering, disabled header/footer output caching, sign-in and page tracking, and oversized assets — then enriches the static checks with AI-driven suggestions and mitigations grounded in the affected customer-code snippets, produces an HTML report by severity, and offers safe auto-fixes with per-fix approval.++- Grounded in the Site Checker performance checklist and FetchXML/Web API best practices+- Supports non-SPA Power Pages websites; SPA projects with `powerpages.config.json` are rejected with a clear message+- Reviews list pagination, webpage-as-API endpoints, FetchXML hints, and cache-busting patterns+- Findings grouped by severity with concrete fixes, AI mitigation guidance, and precise `file:line` locations+- Auto-fixes site-setting/tracking issues on explicit per-finding consent; leaves code changes to you+- Persists the shared review-style HTML report under the website's `docs/` folder+### Migration#### `/migrate-bootstrap`diff --git a/plugins/power-pages/references/approval-gates.md b/plugins/power-pages/references/approval-gates.mdindex 29979c5f3..3f8cd58f9 100644--- a/plugins/power-pages/references/approval-gates.md+++ b/plugins/power-pages/references/approval-gates.md@@ -1,8 +1,8 @@# Approval Gates — Power Pages Skill Catalog (v3)-> **Status: v3 — extended to non-ALM skills.** v2 introduced the marker/lint design and catalogued the 12 ALM skills (§6.1–§6.12). v3 extends coverage to the 12 non-ALM skills (§6.13–§6.24), flips lint severity from warn-only to hard-fail across the plugin, and updates `AGENTS.md` so any new skill must add its gates here in the same PR.+> **Status: v3 — extended to non-ALM skills.** v2 introduced the marker/lint design and catalogued the 12 ALM skills (§6.1–§6.12). v3 extends coverage to non-ALM skills as well (currently catalogued through §6.35), flips lint severity from warn-only to hard-fail across the plugin, and updates `AGENTS.md` so any new skill must add its gates here in the same PR.>-> **Scope: all power-pages skills.** §6 enumerates every `AskUserQuestion` across the catalogued user-invocable skills. `report-issue` is a cross-plugin shared workflow — its wrapper SKILL.md contains no prompts (the workflow file at `shared/skills/report-issue/report-issue-workflow.md` lives outside the per-plugin lint scope) and is excluded from this catalog.+> **Scope: all power-pages skills.** §6 enumerates every `AskUserQuestion` prompt that is in per-plugin lint scope across the Power Pages skill set. `report-issue` is a cross-plugin shared workflow — its wrapper SKILL.md contains no prompts (the workflow file at `shared/skills/report-issue/report-issue-workflow.md` lives outside the per-plugin lint scope) and is excluded from this catalog.>> **Markers applied across all SKILL.md files.** Each gate has both a machine-readable `<!-- gate: ID | category=X | cancel-leaves=Y -->` HTML comment and a human-readable `> 🚦 **Gate (...)**` block. Each pure data-gathering prompt has a `<!-- not-a-gate: <reason> -->` comment.>@@ -770,6 +770,19 @@ Most prompts gather validated configuration before the Phase 3 plan gate.---+### 6.35 `analyze-performance` (1 loop-style gate + 1 plan gate)++Static performance-analysis skill. Scans the local codebase for performance anti-patterns (FetchXML/Web API over-fetching, disabled output caching, tracking, volume/asset issues), reports them, and offers safe auto-fixes with per-fix consent. Read-only until the Phase 4 loop, which mutates only the site-setting/tracking findings the user explicitly approves.++| ID | Kind | Category | Phase | Trigger / question | Cancel leaves |+|---|---|---|---|---|---|+| `analyze-performance:4.auto-fix` | gate | consent | 4 | Per-finding: each `autoFixAvailable` finding loops through this prompt template surfacing the tag and the exact change (site setting or YAML field). User answers Yes / No / Skip-all per finding. | nothing |+| `analyze-performance:6.next-action` | gate | plan | 6 (`### Step 6.4`) | Post-report prompt — *"Walk me through the manual fixes / Re-scan / Done"*. Drives whether the FetchXML/Web API code-fix walkthrough runs next. Reviewing and re-scanning are read-only. | nothing |++The `analyze-performance:4.auto-fix` template fires once per finding with `autoFixAvailable: true` (the output-cache and tracking findings), mirroring the `diagnose-deployment:6.auto-fix` loop-style pattern — one gate ID, content varies per finding. FetchXML/Web API findings are never auto-fixed (they need human judgment), so they are excluded from the loop and surfaced via the plan gate instead.++---+### Cross-plugin shared skills — out of catalog scope`report-issue` — Its prompts are cross-plugin, not power-pages-specific, so they are not catalogued here. If the shared workflow is ever governed by per-plugin approval-gate linting, add a `report-issue:*` section to this catalog.@@ -778,7 +791,7 @@ Most prompts gather validated configuration before the Phase 3 plan gate.## 8. Plugin-wide enforcement (was: non-ALM deferral)-> **v3 update.** This section previously listed 13 deferred non-ALM skills. Those skills are now catalogued in §6.13–§6.24 above (plus the security skills introduced by PR #151 in §6.25–§6.28) and the lint runs hard-fail across the whole plugin.+> **v3 update.** This section previously listed deferred non-ALM skills. Those skills are now catalogued in §6 alongside the ALM skills and the lint runs hard-fail across the whole plugin.The lint rules in §5 fire at `error` severity for **every** SKILL.md under `plugins/power-pages/skills/`. There is no skill-class carve-out. When you add a new skill:diff --git a/plugins/power-pages/references/skill-tracking-reference.md b/plugins/power-pages/references/skill-tracking-reference.mdindex 2080f8795..5f54827c3 100644--- a/plugins/power-pages/references/skill-tracking-reference.md+++ b/plugins/power-pages/references/skill-tracking-reference.md@@ -44,6 +44,7 @@ If the tracking script creates or updates site setting YAML files, include those| add-ai-webapi | AddAiWebapi | Site/AI/Skills/AddAiWebapi || integrate-backend | IntegrateBackend | Site/AI/Skills/IntegrateBackend || scan-site | ScanSite | Site/AI/Skills/ScanSite |+| analyze-performance | AnalyzePerformance | Site/AI/Skills/AnalyzePerformance || manage-headers | ManageHeaders | Site/AI/Skills/ManageHeaders || manage-firewall | ManageFirewall | Site/AI/Skills/ManageFirewall || security-review | SecurityReview | Site/AI/Skills/SecurityReview |diff --git a/plugins/power-pages/scripts/build-review-data.js b/plugins/power-pages/scripts/build-review-data.jsindex 5420a6e37..407762a84 100644--- a/plugins/power-pages/scripts/build-review-data.js+++ b/plugins/power-pages/scripts/build-review-data.js@@ -23,6 +23,7 @@ const SECTION_MAP = {},'audit-permissions.json': { id: 'permissions', label: 'Roles & Permissions', icon: '◇' },'setup-auth.json': { id: 'auth', label: 'Access & Identity', icon: '◈' },+ 'analyze-performance.json': { id: 'performance', label: 'Performance', icon: '⚡' },};// Every severity a finding may carry. `pass` is shown as a stat but excludeddiff --git a/plugins/power-pages/scripts/lib/templates/security-review-report.html b/plugins/power-pages/scripts/lib/templates/security-review-report.htmlindex bc0087cfb..c2ff8814f 100644--- a/plugins/power-pages/scripts/lib/templates/security-review-report.html+++ b/plugins/power-pages/scripts/lib/templates/security-review-report.html@@ -78,6 +78,8 @@ h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;margi.reasoning-block{background:var(--surface2);border-left:2px solid var(--accent);border-radius:var(--radius-sm);padding:10px 14px;margin-top:10px;font-size:12px;line-height:1.7;white-space:pre-wrap;}.fix-block{background:var(--pass-bg);border-left:2px solid var(--pass);border-radius:var(--radius-sm);padding:10px 14px;margin-top:8px;font-size:12px;line-height:1.7;}.fix-block strong{color:var(--pass);}+.ai-block{background:rgba(98,100,167,0.08);border-left:2px solid var(--accent);border-radius:var(--radius-sm);padding:10px 14px;margin-top:8px;font-size:12px;line-height:1.7;}+.mitigation-block{background:var(--surface2);border-left:2px solid var(--warning);border-radius:var(--radius-sm);padding:10px 14px;margin-top:8px;font-size:12px;line-height:1.7;}.detail-table{width:100%;border-collapse:collapse;font-size:13px;margin:10px 0;}.detail-table th{text-align:left;font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:0.8px;color:var(--text-dim);padding:10px 12px;border-bottom:2px solid var(--border);}@@ -165,6 +167,8 @@ function findingHtml(f, idx) {(f.location ? '<div style="margin-top:10px;font-size:12px;"><span class="field-label">Location:</span> <code style="background:var(--surface2);padding:1px 5px;border-radius:3px;">' + esc(f.location) + '</code></div>' : '') +(f.details ? '<div style="margin-top:10px;font-size:12px;line-height:1.7;">' + escMultiline(f.details) + '</div>' : '') +(f.reasoning ? '<div style="margin-top:10px;"><div class="field-label">Why this matters</div><div class="reasoning-block">' + escMultiline(f.reasoning) + '</div></div>' : '') ++ (f.aiSuggestion ? '<div style="margin-top:8px;"><div class="field-label">AI suggestion</div><div class="ai-block">' + escMultiline(f.aiSuggestion) + '</div></div>' : '') ++ (f.mitigation ? '<div style="margin-top:8px;"><div class="field-label">Mitigation</div><div class="mitigation-block">' + escMultiline(f.mitigation) + '</div></div>' : '') +(f.fix ? '<div style="margin-top:8px;"><div class="field-label">Suggested Fix</div><div class="fix-block">' + escMultiline(f.fix) + '</div></div>' : '') +'</div>' +'</div>';diff --git a/plugins/power-pages/scripts/tests/analyze-performance.test.js b/plugins/power-pages/scripts/tests/analyze-performance.test.jsnew file mode 100644index 000000000..f7b237ca2--- /dev/null+++ b/plugins/power-pages/scripts/tests/analyze-performance.test.js@@ -0,0 +1,710 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('fs');+const os = require('os');+const path = require('path');++const {+ analyze,+ scanFetchXmlContent,+ scanListContent,+ scanWebpageApiContent,+ scanWebApiContent,+ scanClientScript,+ scanHtmlHead,+ scanCssContent,+ scanSiteSettings,+ evaluateCounts,+ scanLargeAssets,+ FETCHXML_MAX_COUNT,+ FETCHXML_MAX_ATTRIBUTES,+ WEBAPI_MAX_TOP,+ WEBAPI_MAX_SELECT_COLUMNS,+ WEB_FILE_WARN_THRESHOLD,+ WEB_ROLE_WARN_THRESHOLD,+ LARGE_ASSET_BYTES,+ SHORT_POLL_INTERVAL_MS,+} = require('../../skills/analyze-performance/scripts/analyze-performance');++// Collect the `tag`s a rule function produced — every assertion below is about+// which anti-pattern tags fire (or don't) for a given input, so this keeps the+// tests focused on behavior rather than message wording.+function tags(findings) {+ return findings.map((f) => f.tag);+}++// ── FetchXML rules ───────────────────────────────────────────────────────────++test('scanFetchXmlContent flags <all-attributes/> as PERF-FETCHXML-ALLATTR', () => {+ const xml = '<fetch count="10"><entity name="contact"><all-attributes /></entity></fetch>';+ const found = tags(scanFetchXmlContent(xml, 'a.html'));+ assert.ok(found.includes('PERF-FETCHXML-ALLATTR'));+ // all-attributes is present, so the "no explicit columns" rule must NOT also fire.+ assert.ok(!found.includes('PERF-FETCHXML-NO-COLUMNS'));+});++test('scanFetchXmlContent flags an entity with no attributes as PERF-FETCHXML-NO-COLUMNS', () => {+ const xml = '<fetch count="10"><entity name="contact"><filter><condition attribute="statecode" operator="eq" value="0"/></filter></entity></fetch>';+ assert.ok(tags(scanFetchXmlContent(xml, 'a.html')).includes('PERF-FETCHXML-NO-COLUMNS'));+});++test('scanFetchXmlContent flags a fetch with no count as PERF-FETCHXML-NO-PAGING', () => {+ const xml = '<fetch><entity name="contact"><attribute name="fullname"/></entity></fetch>';+ assert.ok(tags(scanFetchXmlContent(xml, 'a.html')).includes('PERF-FETCHXML-NO-PAGING'));+});++test('scanFetchXmlContent flags a large count as PERF-FETCHXML-LARGE-COUNT', () => {+ const xml = `<fetch count="${FETCHXML_MAX_COUNT + 1}"><entity name="contact"><attribute name="fullname"/></entity></fetch>`;+ const found = tags(scanFetchXmlContent(xml, 'a.html'));+ assert.ok(found.includes('PERF-FETCHXML-LARGE-COUNT'));+ assert.ok(!found.includes('PERF-FETCHXML-NO-PAGING')); // a count is present+});++test('scanFetchXmlContent does NOT flag a reasonable count', () => {+ const xml = `<fetch count="${FETCHXML_MAX_COUNT}"><entity name="contact"><attribute name="fullname"/></entity></fetch>`;+ const found = tags(scanFetchXmlContent(xml, 'a.html'));+ assert.ok(!found.includes('PERF-FETCHXML-LARGE-COUNT'));+ assert.ok(!found.includes('PERF-FETCHXML-NO-PAGING'));+});++test('scanFetchXmlContent exempts aggregate fetches from paging/columns rules', () => {+ // Aggregate queries return a single summary row — no paging or projection needed.+ const xml = '<fetch aggregate="true"><entity name="contact"><attribute name="contactid" alias="c" aggregate="count"/></entity></fetch>';+ const found = tags(scanFetchXmlContent(xml, 'a.html'));+ assert.deepEqual(found, []);+});++test('scanFetchXmlContent flags a fetch inside a Liquid for-loop as PERF-FETCHXML-IN-LOOP', () => {+ const liquid = '{% for c in contacts %}<fetch count="5"><entity name="task"><attribute name="subject"/></entity></fetch>{% endfor %}';+ assert.ok(tags(scanFetchXmlContent(liquid, 'a.liquid')).includes('PERF-FETCHXML-IN-LOOP'));+});++test('scanFetchXmlContent does NOT flag a fetch after a closed for-loop', () => {+ const liquid = '{% for c in contacts %}{{ c.name }}{% endfor %}<fetch count="5"><entity name="task"><attribute name="subject"/></entity></fetch>';+ assert.ok(!tags(scanFetchXmlContent(liquid, 'a.liquid')).includes('PERF-FETCHXML-IN-LOOP'));+});++test('scanFetchXmlContent returns nothing for content without a fetch element', () => {+ assert.deepEqual(scanFetchXmlContent('<div>no fetch here</div>', 'a.html'), []);+});++test('scanFetchXmlContent flags returntotalrecordcount="true" as PERF-FETCHXML-TOTALRECORDCOUNT', () => {+ const xml = '<fetch count="10" returntotalrecordcount="true"><entity name="contact"><attribute name="fullname"/></entity></fetch>';+ const found = tags(scanFetchXmlContent(xml, 'a.html'));+ assert.ok(found.includes('PERF-FETCHXML-TOTALRECORDCOUNT'));+});++test('scanFetchXmlContent does NOT flag returntotalrecordcount when absent', () => {+ const xml = '<fetch count="10"><entity name="contact"><attribute name="fullname"/></entity></fetch>';+ assert.ok(!tags(scanFetchXmlContent(xml, 'a.html')).includes('PERF-FETCHXML-TOTALRECORDCOUNT'));+});++test('scanFetchXmlContent flags advanced query hints for review', () => {+ const xml = [+ '<fetch count="10" options="ForceOrder" latematerialize="true">',+ '<entity name="contact"><attribute name="fullname"/>',+ '<filter type="or" hint="union"><condition attribute="statecode" operator="eq" value="0"/></filter>',+ '</entity></fetch>',+ ].join('');+ const found = scanFetchXmlContent(xml, 'a.html');+ const hint = found.find((f) => f.tag === 'PERF-FETCHXML-QUERY-HINT');+ assert.ok(hint);+ assert.match(hint.details, /ForceOrder/);+ assert.match(hint.details, /latematerialize/);+ assert.match(hint.details, /union/);+});++test('scanFetchXmlContent flags request-time cache busting', () => {+ const xml = [+ '<fetch count="10"><entity name="contact"><attribute name="fullname"/>',+ '<filter><condition attribute="createdon" operator="lt" ',+ 'value="{{ \"now\" | date: \"yyyy-MM-dd HH:mm:ss\" }}"/></filter>',+ '</entity></fetch>',+ ].join('');+ assert.ok(tags(scanFetchXmlContent(xml, 'a.html')).includes('PERF-FETCHXML-CACHE-BYPASS'));+});++test('scanFetchXmlContent does not flag a static date filter as cache bypassing', () => {+ const xml = [+ '<fetch count="10"><entity name="contact"><attribute name="fullname"/>',+ '<filter><condition attribute="createdon" operator="lt" value="2026-01-01"/></filter>',+ '</entity></fetch>',+ ].join('');+ assert.ok(!tags(scanFetchXmlContent(xml, 'a.html')).includes('PERF-FETCHXML-CACHE-BYPASS'));+});++test('scanFetchXmlContent flags wide projections as PERF-FETCHXML-MANY-COLUMNS', () => {+ const attrs = Array.from(+ { length: FETCHXML_MAX_ATTRIBUTES + 1 },+ (_, i) => `<attribute name="field${i}" />`,+ ).join('');+ const xml = `<fetch count="10"><entity name="contact">${attrs}</entity></fetch>`;+ assert.ok(tags(scanFetchXmlContent(xml, 'a.html')).includes('PERF-FETCHXML-MANY-COLUMNS'));+});++test('scanFetchXmlContent flags leading-wildcard like filters', () => {+ const xml = [+ '<fetch count="10"><entity name="contact"><attribute name="fullname"/>',+ '<filter><condition attribute="fullname" operator="like" value="%smith"/></filter>',+ '</entity></fetch>',+ ].join('');+ assert.ok(tags(scanFetchXmlContent(xml, 'a.html')).includes('PERF-FETCHXML-LEADING-WILDCARD'));+});++test('scanFetchXmlContent flags related-column ordering', () => {+ const xml = [+ '<fetch count="10"><entity name="account"><attribute name="name"/>',+ '<link-entity name="contact" from="contactid" to="primarycontactid" alias="pc">',+ '<order attribute="fullname" />',+ '</link-entity></entity></fetch>',+ ].join('');+ assert.ok(tags(scanFetchXmlContent(xml, 'a.html')).includes('PERF-FETCHXML-ORDER-RELATED'));+});++// ── Power Pages list and webpage-as-API rules ───────────────────────────────++test('scanListContent flags a list with no page size', () => {+ const yaml = 'adx_entitylistid: 11111111-1111-4111-8111-111111111111\nadx_name: Cases\n';+ const found = scanListContent(yaml, 'lists/Cases.list.yml');+ assert.equal(found.length, 1);+ assert.equal(found[0].tag, 'PERF-LIST-NO-PAGING');+});++test('scanListContent accepts a positive page size', () => {+ const yaml = [+ 'adx_entitylistid: 11111111-1111-4111-8111-111111111111',+ 'adx_name: Cases',+ 'adx_pagesize: 10',+ '',+ ].join('\n');+ assert.deepEqual(scanListContent(yaml, 'lists/Cases.list.yml'), []);+});++test('scanWebpageApiContent flags a FetchXML-backed JSON web template', () => {+ const template = [+ '{% fetchxml rows %}',+ '<fetch count="10"><entity name="contact"><attribute name="fullname"/></entity></fetch>',+ '{% endfetchxml %}',+ '{ "items": [{% for row in rows.results.entities %}',+ '{ "name": "{{ row.fullname }}" }{% unless forloop.last %},{% endunless %}',+ '{% endfor %}] }',+ ].join('\n');+ const found = scanWebpageApiContent(+ template,+ 'web-templates/contact-api/Contact-API.webtemplate.source.html',+ );+ assert.equal(found.length, 1);+ assert.equal(found[0].tag, 'PERF-WEBPAGE-AS-API');+});++test('scanWebpageApiContent ignores a normal HTML web template', () => {+ const template = [+ '{% fetchxml rows %}',+ '<fetch count="10"><entity name="contact"><attribute name="fullname"/></entity></fetch>',+ '{% endfetchxml %}',+ '<section><ul>{% for row in rows.results.entities %}<li>{{ row.fullname }}</li>{% endfor %}</ul></section>',+ ].join('\n');+ assert.deepEqual(+ scanWebpageApiContent(template, 'web-templates/list/List.webtemplate.source.html'),+ [],+ );+});++// ── Client-side script rules (blocking / anti-pattern JS) ────────────────────++test('scanClientScript flags a synchronous XMLHttpRequest as PERF-SYNC-XHR', () => {+ const code = 'const xhr = new XMLHttpRequest(); xhr.open("GET", url, false); xhr.send();';+ const found = scanClientScript(code, 'a.js');+ const hit = found.find((f) => f.tag === 'PERF-SYNC-XHR');+ assert.ok(hit);+ assert.equal(hit.severity, 'high');+});++test('scanClientScript does NOT flag an async XMLHttpRequest', () => {+ const code = 'xhr.open("GET", url, true); xhr.open("POST", url);';+ assert.ok(!tags(scanClientScript(code, 'a.js')).includes('PERF-SYNC-XHR'));+});++test('scanClientScript flags jQuery async:false as PERF-JQUERY-SYNC-AJAX only when an .ajax( call is present', () => {+ const ajax = '$.ajax({ url: "/x", async: false, success: fn });';+ assert.ok(tags(scanClientScript(ajax, 'a.js')).includes('PERF-JQUERY-SYNC-AJAX'));+ // No .ajax( call ⇒ a stray async:false in another config object is not flagged.+ const other = 'const opts = { async: false };';+ assert.ok(!tags(scanClientScript(other, 'a.js')).includes('PERF-JQUERY-SYNC-AJAX'));+ // `isAsync: false` must not be mistaken for the async option.+ const substr = '$.ajax({ url: "/x" }); const isAsync = false;';+ assert.ok(!tags(scanClientScript(substr, 'a.js')).includes('PERF-JQUERY-SYNC-AJAX'));+});++test('scanClientScript flags document.write as PERF-DOCUMENT-WRITE', () => {+ assert.ok(tags(scanClientScript('document.write("<b>x</b>");', 'a.js')).includes('PERF-DOCUMENT-WRITE'));+ assert.ok(tags(scanClientScript('document.writeln("x");', 'a.js')).includes('PERF-DOCUMENT-WRITE'));+});++test('scanClientScript flags short-interval Web API polling as PERF-SHORT-POLL', () => {+ const code = `setInterval(() => { fetch("/_api/tasks?$select=subject"); }, ${SHORT_POLL_INTERVAL_MS - 1});`;+ assert.ok(tags(scanClientScript(code, 'a.js')).includes('PERF-SHORT-POLL'));+});++test('scanClientScript does NOT flag polling at/above the interval threshold or without a Web API call', () => {+ const slow = `setInterval(() => { fetch("/_api/tasks"); }, ${SHORT_POLL_INTERVAL_MS});`;+ assert.ok(!tags(scanClientScript(slow, 'a.js')).includes('PERF-SHORT-POLL'));+ // A tight interval that doesn't touch the Web API is out of scope for this rule.+ const noApi = 'setInterval(() => { updateClock(); }, 1000);';+ assert.ok(!tags(scanClientScript(noApi, 'a.js')).includes('PERF-SHORT-POLL'));+});++test('scanClientScript returns nothing for clean client code', () => {+ assert.deepEqual(scanClientScript('const x = await fetch("/_api/c?$select=n&$top=5");', 'a.js'), []);+});++// ── Render-blocking <head> script rule ───────────────────────────────────────++test('scanHtmlHead flags a render-blocking script in <head> as PERF-RENDER-BLOCKING-SCRIPT', () => {+ const html = '<html><head><script src="/lib/big.js"></script></head><body></body></html>';+ assert.ok(tags(scanHtmlHead(html, 'index.html')).includes('PERF-RENDER-BLOCKING-SCRIPT'));+});++test('scanHtmlHead does NOT flag async/defer/module head scripts or scripts outside <head>', () => {+ assert.deepEqual(scanHtmlHead('<head><script src="/a.js" defer></script></head>', 'p.html'), []);+ assert.deepEqual(scanHtmlHead('<head><script src="/a.js" async></script></head>', 'p.html'), []);+ assert.deepEqual(scanHtmlHead('<head><script type="module" src="/a.js"></script></head>', 'p.html'), []);+ // A blocking script in <body> is not this rule's concern.+ assert.deepEqual(scanHtmlHead('<head></head><body><script src="/a.js"></script></body>', 'p.html'), []);+});++test('scanHtmlHead does not mistake async/defer/type words inside src values for attributes', () => {+ for (const src of ['/assets/async.js', '/assets/defer.js', '/bundle.js?type=module']) {+ const html = `<head><script src="${src}"></script></head>`;+ assert.ok(+ tags(scanHtmlHead(html, 'p.html')).includes('PERF-RENDER-BLOCKING-SCRIPT'),+ `${src} must remain blocking without an actual async/defer/type attribute`,+ );+ }+});++// ── Runtime CSS rule (render-blocking @import) ───────────────────────────────++test('scanCssContent flags @import as PERF-CSS-IMPORT', () => {+ assert.ok(tags(scanCssContent('@import url("base.css");\nbody { color: red; }', 'site.css')).includes('PERF-CSS-IMPORT'));+});++test('scanCssContent does NOT flag a commented-out @import and keeps accurate line numbers', () => {+ const css = 'body { color: red; }\n/* @import "old.css"; */\n@import "real.css";';+ const found = scanCssContent(css, 'site.css');+ // Only the real (uncommented) @import is flagged.+ assert.equal(found.length, 1);+ // It sits on line 3 of the source, not line 2 (the comment).+ assert.equal(found[0].location, 'site.css:3');+});++// ── Web API rules ────────────────────────────────────────────────────────────++test('scanWebApiContent flags $select=* as PERF-WEBAPI-SELECT-STAR', () => {+ const code = 'fetch("/_api/contacts?$select=*&$filter=statecode eq 0")';+ assert.ok(tags(scanWebApiContent(code, 'a.js')).includes('PERF-WEBAPI-SELECT-STAR'));+});++test('scanWebApiContent flags a query with options but no $select as PERF-WEBAPI-NO-SELECT', () => {+ const code = 'fetch("/_api/contacts?$filter=statecode eq 0&$top=10")';+ const found = tags(scanWebApiContent(code, 'a.js'));+ assert.ok(found.includes('PERF-WEBAPI-NO-SELECT'));+ assert.ok(!found.includes('PERF-WEBAPI-NO-TOP')); // $top present+});++test('scanWebApiContent flags a collection query with no $top as PERF-WEBAPI-NO-TOP', () => {+ const code = 'fetch("/_api/contacts?$select=fullname&$orderby=createdon desc")';+ assert.ok(tags(scanWebApiContent(code, 'a.js')).includes('PERF-WEBAPI-NO-TOP'));+});++test('scanWebApiContent accepts Prefer maxpagesize cursor pagination without $top', () => {+ const code = [+ 'fetch("/_api/contacts?$select=fullname&$orderby=createdon desc", {',+ ' headers: { Prefer: "odata.maxpagesize=25" },',+ '});',+ ].join('\n');+ const found = tags(scanWebApiContent(code, 'a.js'));+ assert.ok(!found.includes('PERF-WEBAPI-NO-TOP'));+});++test('scanWebApiContent accepts template-based Prefer maxpagesize cursor pagination', () => {+ const code = [+ 'powerPagesFetch("/_api/contacts?$select=fullname", {',+ ' headers: { Prefer: `odata.include-annotations="*",odata.maxpagesize=${pageSize}` },',+ '});',+ ].join('\n');+ const found = tags(scanWebApiContent(code, 'a.js'));+ assert.ok(!found.includes('PERF-WEBAPI-NO-TOP'));+});++test('scanWebApiContent flags a bare collection request as missing $select and $top', () => {+ const code = 'fetch("/_api/contacts")';+ const found = tags(scanWebApiContent(code, 'a.js'));+ assert.ok(found.includes('PERF-WEBAPI-NO-SELECT'));+ assert.ok(found.includes('PERF-WEBAPI-NO-TOP'));+});++test('scanWebApiContent does NOT require $top for a single-record request', () => {+ const code = 'fetch("/_api/contacts(11111111-1111-4111-8111-111111111111)?$select=fullname")';+ const found = tags(scanWebApiContent(code, 'a.js'));+ assert.ok(!found.includes('PERF-WEBAPI-NO-TOP'));+ assert.ok(!found.includes('PERF-WEBAPI-NO-SELECT'));+});++test('scanWebApiContent flags large $top values as PERF-WEBAPI-LARGE-TOP', () => {+ const code = `fetch("/_api/contacts?$select=fullname&$top=${WEBAPI_MAX_TOP + 1}")`;+ const found = tags(scanWebApiContent(code, 'a.js'));+ assert.ok(found.includes('PERF-WEBAPI-LARGE-TOP'));+ assert.ok(!found.includes('PERF-WEBAPI-NO-TOP'));+});++test('scanWebApiContent flags $count=true as PERF-WEBAPI-COUNT', () => {+ const code = 'fetch("/_api/contacts?$select=fullname&$top=20&$count=true")';+ assert.ok(tags(scanWebApiContent(code, 'a.js')).includes('PERF-WEBAPI-COUNT'));+});++test('scanWebApiContent flags $expand without nested $select', () => {+ const missingNestedSelect = 'fetch("/_api/accounts?$select=name&$top=10&$expand=primarycontactid")';+ assert.ok(tags(scanWebApiContent(missingNestedSelect, 'a.js')).includes('PERF-WEBAPI-EXPAND-NO-SELECT'));++ const nestedSelect = 'fetch("/_api/accounts?$select=name&$top=10&$expand=primarycontactid($select=fullname)")';+ assert.ok(!tags(scanWebApiContent(nestedSelect, 'a.js')).includes('PERF-WEBAPI-EXPAND-NO-SELECT'));+});++test('scanWebApiContent flags wide $select lists as PERF-WEBAPI-MANY-COLUMNS', () => {+ const columns = Array.from({ length: WEBAPI_MAX_SELECT_COLUMNS + 1 }, (_, i) => `field${i}`).join(',');+ const code = `fetch("/_api/contacts?$select=${columns}&$top=20")`;+ assert.ok(tags(scanWebApiContent(code, 'a.js')).includes('PERF-WEBAPI-MANY-COLUMNS'));+});++test('scanWebApiContent flags contains and endswith filters', () => {+ const contains = 'fetch("/_api/contacts?$select=fullname&$top=20&$filter=contains(fullname,\\\'smith\\\')")';+ assert.ok(tags(scanWebApiContent(contains, 'a.js')).includes('PERF-WEBAPI-WILDCARD-FILTER'));++ const startswith = 'fetch("/_api/contacts?$select=fullname&$top=20&$filter=startswith(fullname,\\\'s\\\')")';+ assert.ok(!tags(scanWebApiContent(startswith, 'a.js')).includes('PERF-WEBAPI-WILDCARD-FILTER'));+});++test('scanWebApiContent flags request-time date filters as cache bypassing', () => {+ const code = 'fetch(`/_api/tasks?$select=subject&$top=20&$filter=createdon ge ${new Date().toISOString()}`)';+ assert.ok(tags(scanWebApiContent(code, 'a.js')).includes('PERF-WEBAPI-CACHE-BYPASS'));+});++test('scanWebApiContent flags related-column ordering', () => {+ const code = 'fetch("/_api/accounts?$select=name&$top=20&$orderby=primarycontactid/fullname asc")';+ assert.ok(tags(scanWebApiContent(code, 'a.js')).includes('PERF-WEBAPI-ORDER-RELATED'));+});++test('scanWebApiContent does NOT flag a well-formed bounded query', () => {+ const code = 'fetch("/_api/contacts?$select=fullname&$top=20")';+ const found = tags(scanWebApiContent(code, 'a.js'));+ assert.ok(!found.includes('PERF-WEBAPI-SELECT-STAR'));+ assert.ok(!found.includes('PERF-WEBAPI-NO-SELECT'));+ assert.ok(!found.includes('PERF-WEBAPI-NO-TOP'));+});++test('scanWebApiContent flags an async map calling the Web API as PERF-WEBAPI-IN-LOOP', () => {+ const code = 'ids.map(async (id) => { return fetch(`/_api/contacts(${id})?$select=fullname`); })';+ assert.ok(tags(scanWebApiContent(code, 'a.js')).includes('PERF-WEBAPI-IN-LOOP'));+});++test('scanWebApiContent does NOT flag a plain map over already-fetched results', () => {+ const code = 'rows.map((r) => r.fullname).join(", ")';+ assert.deepEqual(scanWebApiContent(code, 'a.js'), []);+});++test('scanWebApiContent returns nothing for code without /_api/', () => {+ assert.deepEqual(scanWebApiContent('const x = fetch("/other/endpoint")', 'a.js'), []);+});++// ── Site-settings rules ──────────────────────────────────────────────────────++function settingsMap(entries) {+ const m = new Map();+ for (const [name, value] of entries) {+ m.set(name.toLowerCase(), { name, value, filePath: `.powerpages-site/site-settings/${name.replace(/\//g, '-')}.sitesetting.yml` });+ }+ return m;+}++test('scanSiteSettings returns nothing when the site-settings dir is absent', () => {+ assert.deepEqual(scanSiteSettings(new Map(), null), []);+});++test('scanSiteSettings flags header cache present-and-false as a warning with a set-site-setting autofix', () => {+ const found = scanSiteSettings(settingsMap([['Header/OutputCache/Enabled', false]]), '.powerpages-site/site-settings');+ const header = found.find((f) => f.tag === 'PERF-HEADER-OUTPUTCACHE');+ assert.ok(header);+ assert.equal(header.severity, 'warning');+ assert.equal(header.autoFixAvailable, true);+ assert.equal(header.fixAction.type, 'set-site-setting');+ assert.equal(header.fixAction.value, 'true');+});++test('scanSiteSettings flags absent footer cache as info with a create-site-setting autofix', () => {+ const found = scanSiteSettings(settingsMap([['Header/OutputCache/Enabled', true]]), '.powerpages-site/site-settings');+ const footer = found.find((f) => f.tag === 'PERF-FOOTER-OUTPUTCACHE');+ assert.ok(footer);+ assert.equal(footer.severity, 'info');+ assert.equal(footer.fixAction.type, 'create-site-setting');+});++test('scanSiteSettings does not flag caching when both are explicitly enabled', () => {+ const found = scanSiteSettings(+ settingsMap([['Header/OutputCache/Enabled', true], ['Footer/OutputCache/Enabled', 'true']]),+ '.powerpages-site/site-settings',+ );+ assert.ok(!tags(found).includes('PERF-HEADER-OUTPUTCACHE'));+ assert.ok(!tags(found).includes('PERF-FOOTER-OUTPUTCACHE'));+});++test('scanSiteSettings flags sign-in tracking enabled as PERF-SIGNIN-TRACKING', () => {+ const found = scanSiteSettings(+ settingsMap([+ ['Header/OutputCache/Enabled', true],+ ['Footer/OutputCache/Enabled', true],+ ['Authentication/LoginTrackingEnabled', true],+ ]),+ '.powerpages-site/site-settings',+ );+ const signin = found.find((f) => f.tag === 'PERF-SIGNIN-TRACKING');+ assert.ok(signin);+ assert.equal(signin.fixAction.value, 'false');+});++test('scanSiteSettings keeps absent non-SPA aggregate settings manual-only', () => {+ const found = scanSiteSettings(new Map(), 'sitesetting.yml', 'non-spa');+ const header = found.find((f) => f.tag === 'PERF-HEADER-OUTPUTCACHE');+ assert.ok(header);+ assert.equal(header.autoFixAvailable, false);+ assert.equal(header.fixAction, null);+ assert.match(header.fix, /non-SPA sitesetting\.yml export/);+});++// ── Count rules ──────────────────────────────────────────────────────────────++test('evaluateCounts flags web-file and web-role counts over threshold', () => {+ const found = tags(evaluateCounts({+ webFileCount: WEB_FILE_WARN_THRESHOLD + 1,+ webRoleCount: WEB_ROLE_WARN_THRESHOLD + 1,+ }));+ assert.ok(found.includes('PERF-WEBFILE-COUNT'));+ assert.ok(found.includes('PERF-WEBROLE-COUNT'));+});++test('evaluateCounts does not flag counts at or below threshold', () => {+ const found = evaluateCounts({ webFileCount: WEB_FILE_WARN_THRESHOLD, webRoleCount: WEB_ROLE_WARN_THRESHOLD });+ assert.deepEqual(found, []);+});++// ── Large asset rule ─────────────────────────────────────────────────────────++test('scanLargeAssets flags oversized assets and caps/sorts the output', () => {+ const found = scanLargeAssets([+ { relPath: 'small.png', size: 1024 },+ { relPath: 'big.png', size: LARGE_ASSET_BYTES * 3 },+ { relPath: 'medium.png', size: LARGE_ASSET_BYTES * 2 },+ ]);+ assert.equal(found.length, 2);+ assert.equal(found[0].location, 'big.png'); // largest first+ assert.ok(found.every((f) => f.tag === 'PERF-LARGE-STATIC-ASSET'));+});++// ── analyze() integration over a temp project ────────────────────────────────++test('analyze() walks a project, assigns perf-N ids, and aggregates findings', (t) => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'perf-analyze-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));++ fs.mkdirSync(path.join(root, '.powerpages-site', 'web-templates', 'home'), { recursive: true });+ fs.mkdirSync(path.join(root, '.powerpages-site', 'site-settings'), { recursive: true });+ fs.mkdirSync(path.join(root, 'src'), { recursive: true });++ fs.writeFileSync(+ path.join(root, '.powerpages-site', 'web-templates', 'home', 'Home.webtemplate.source.html'),+ '{% for i in items %}<fetch><entity name="p"><all-attributes /></entity></fetch>{% endfor %}',+ );+ fs.writeFileSync(+ path.join(root, '.powerpages-site', 'site-settings', 'Header-OutputCache-Enabled.sitesetting.yml'),+ 'name: Header/OutputCache/Enabled\nvalue: false\n',+ );+ fs.writeFileSync(path.join(root, 'src', 'api.js'), 'fetch("/_api/products?$select=*")');+ fs.writeFileSync(path.join(root, 'src', 'legacy.js'), 'var xhr=new XMLHttpRequest();xhr.open("GET", u, false);xhr.send();');+ fs.writeFileSync(path.join(root, 'src', 'site.css'), '@import "reset.css";\nbody{color:red}');+ fs.writeFileSync(path.join(root, 'index.html'), '<html><head><script src="/lib/big.js"></script></head><body></body></html>');++ const result = analyze(root);+ assert.equal(result.status, 'ok');+ const found = tags(result.findings);+ assert.ok(found.includes('PERF-FETCHXML-ALLATTR'));+ assert.ok(found.includes('PERF-FETCHXML-IN-LOOP'));+ assert.ok(found.includes('PERF-HEADER-OUTPUTCACHE'));+ assert.ok(found.includes('PERF-WEBAPI-SELECT-STAR'));+ assert.ok(found.includes('PERF-SYNC-XHR'));+ assert.ok(found.includes('PERF-CSS-IMPORT'));+ assert.ok(found.includes('PERF-RENDER-BLOCKING-SCRIPT'));+ // Ids are sequential perf-1, perf-2, ...+ result.findings.forEach((f, i) => assert.equal(f.id, `perf-${i + 1}`));+ // details is the kv envelope the shared report pipeline expects.+ assert.equal(result.details.kind, 'kv');+});++test('analyze() supports a non-SPA PAC download with root-level metadata', (t) => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'perf-non-spa-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));++ fs.mkdirSync(path.join(root, '.portalconfig'), { recursive: true });+ fs.mkdirSync(path.join(root, 'web-files'), { recursive: true });+ fs.writeFileSync(path.join(root, 'website.yml'), 'adx_name: Example Site\n');+ fs.writeFileSync(+ path.join(root, 'sitesetting.yml'),+ [+ '- adx_name: Header/OutputCache/Enabled',+ ' adx_sitesettingid: 11111111-1111-4111-8111-111111111111',+ ' adx_value: false',+ '- adx_name: Footer/OutputCache/Enabled',+ ' adx_sitesettingid: 22222222-2222-4222-8222-222222222222',+ ' adx_value: true',+ '- adx_name: Authentication/LoginTrackingEnabled',+ ' adx_sitesettingid: 33333333-3333-4333-8333-333333333333',+ ' adx_value: true',+ '',+ ].join('\n'),+ );+ fs.writeFileSync(+ path.join(root, 'webrole.yml'),+ [+ '- adx_name: Anonymous Users',+ ' adx_webroleid: 44444444-4444-4444-8444-444444444444',+ '- adx_name: Authenticated Users',+ ' adx_webroleid: 55555555-5555-4555-8555-555555555555',+ '',+ ].join('\n'),+ );+ fs.writeFileSync(path.join(root, 'web-files', 'one.webfile.yml'), 'adx_name: one\n');+ fs.writeFileSync(path.join(root, 'web-files', 'two.webfile.yml'), 'adx_name: two\n');++ const result = analyze(root);+ const found = tags(result.findings);+ assert.ok(found.includes('PERF-HEADER-OUTPUTCACHE'));+ assert.ok(found.includes('PERF-SIGNIN-TRACKING'));+ assert.ok(!found.includes('PERF-FOOTER-OUTPUTCACHE'));++ const header = result.findings.find((f) => f.tag === 'PERF-HEADER-OUTPUTCACHE');+ assert.equal(header.location, 'sitesetting.yml:3');+ assert.equal(header.fixAction.type, 'set-yaml-field');+ assert.equal(header.fixAction.field, 'adx_value');+ assert.equal(header.fixAction.recordName, 'Header/OutputCache/Enabled');++ const coverage = Object.fromEntries(+ result.details.entries.map((entry) => [entry.key, entry.value]),+ );+ assert.equal(coverage['Web files'], '2');+ assert.equal(coverage['Web roles'], '2');+});++test('analyze() preserves the detected tracking field and target type in auto-fixes', (t) => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'perf-tracking-fields-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ fs.mkdirSync(path.join(root, 'web-files'), { recursive: true });+ fs.mkdirSync(path.join(root, 'web-pages'), { recursive: true });+ fs.writeFileSync(+ path.join(root, 'web-files', 'asset.webfile.yml'),+ 'adx_name: Asset\nenabletracking: true\n',+ );+ fs.writeFileSync(+ path.join(root, 'web-pages', 'home.webpage.yml'),+ 'adx_name: Home\nadx_enabletracking: true\n',+ );++ const result = analyze(root);+ const webFile = result.findings.find((finding) => finding.tag === 'PERF-WEBFILE-TRACKING');+ const webPage = result.findings.find((finding) => finding.tag === 'PERF-WEBPAGE-TRACKING');++ assert.equal(webFile.fixAction.field, 'enabletracking');+ assert.match(webFile.title, /file tracking/);+ assert.equal(webPage.fixAction.field, 'adx_enabletracking');+ assert.match(webPage.title, /page tracking/);+});++test('analyze() rejects SPA websites', (t) => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'perf-spa-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ fs.writeFileSync(+ path.join(root, 'powerpages.config.json'),+ JSON.stringify({ siteName: 'SPA Site' }),+ );++ assert.throws(+ () => analyze(root),+ /supports non-SPA Power Pages websites only.*powerpages\.config\.json/i,+ );+});++test('analyze() wires list pagination and webpage-as-API checks into the project scan', (t) => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'perf-new-rules-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));++ fs.mkdirSync(path.join(root, 'lists'), { recursive: true });+ fs.mkdirSync(path.join(root, 'web-templates', 'data-api'), { recursive: true });+ fs.mkdirSync(path.join(root, 'web-templates', 'liquid-api'), { recursive: true });+ fs.writeFileSync(+ path.join(root, 'lists', 'Unpaged.list.yml'),+ 'adx_entitylistid: 11111111-1111-4111-8111-111111111111\nadx_name: Unpaged\n',+ );+ fs.writeFileSync(+ path.join(root, 'web-templates', 'data-api', 'Data.webtemplate.source.html'),+ [+ '{% fetchxml rows %}',+ '<fetch count="10"><entity name="contact"><attribute name="fullname"/></entity></fetch>',+ '{% endfetchxml %}',+ '{ "items": [{% for row in rows.results.entities %}"{{ row.fullname }}"{% unless forloop.last %},{% endunless %}{% endfor %}] }',+ ].join('\n'),+ );+ fs.writeFileSync(+ path.join(root, 'web-templates', 'liquid-api', 'Liquid.webtemplate.source.liquid'),+ [+ '{% assign rows = entities["contacts"] %}',+ '{ "items": [{% for row in rows %}"{{ row.fullname }}"{% unless forloop.last %},{% endunless %}{% endfor %}] }',+ ].join('\n'),+ );++ const result = analyze(root);+ const found = tags(result.findings);+ assert.ok(found.includes('PERF-LIST-NO-PAGING'));+ assert.equal(found.filter((tag) => tag === 'PERF-WEBPAGE-AS-API').length, 2);+ const coverage = Object.fromEntries(+ result.details.entries.map((entry) => [entry.key, entry.value]),+ );+ assert.equal(coverage['Power Pages list files scanned'], '1');+});++test('analyze() emits a single PERF-NONE finding for a clean project', (t) => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'perf-clean-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ fs.mkdirSync(path.join(root, 'src'), { recursive: true });+ fs.writeFileSync(path.join(root, 'src', 'app.js'), 'export const x = 1;');++ const result = analyze(root);+ assert.equal(result.findings.length, 1);+ assert.equal(result.findings[0].tag, 'PERF-NONE');+ assert.deepEqual(result.severityCounts, { info: 1 });+ const coverage = Object.fromEntries(+ result.details.entries.map((entry) => [entry.key, entry.value]),+ );+ assert.equal(coverage['Total findings'], '1');+});++test('analyze() skips build-output directories', (t) => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'perf-dist-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ fs.mkdirSync(path.join(root, '.powerpages-site'), { recursive: true }); // makes it a PP project root+ fs.mkdirSync(path.join(root, 'dist'), { recursive: true });+ // A select-star call that lives ONLY in build output must not be reported.+ fs.writeFileSync(path.join(root, 'dist', 'bundle.js'), 'fetch("/_api/products?$select=*")');++ const result = analyze(root);+ assert.ok(!tags(result.findings).includes('PERF-WEBAPI-SELECT-STAR'));+});diff --git a/plugins/power-pages/scripts/tests/build-review-data.test.js b/plugins/power-pages/scripts/tests/build-review-data.test.jsindex 401eaba3d..34242c076 100644--- a/plugins/power-pages/scripts/tests/build-review-data.test.js+++ b/plugins/power-pages/scripts/tests/build-review-data.test.js@@ -31,7 +31,7 @@ function runCli(args, env = {}) {});}-test('SECTION_MAP recognizes the six known per-skill files', () => {+test('SECTION_MAP recognizes the known per-skill files', () => {const expected = ['scan-code.json','scan-site.json',@@ -39,6 +39,7 @@ test('SECTION_MAP recognizes the six known per-skill files', () => {'manage-firewall.json','audit-permissions.json','setup-auth.json',+ 'analyze-performance.json',];for (const file of expected) {assert.ok(SECTION_MAP[file], `${file} missing from SECTION_MAP`);diff --git a/plugins/power-pages/scripts/tests/create-site-template-telemetry.test.js b/plugins/power-pages/scripts/tests/create-site-template-telemetry.test.jsindex 56b06976d..3e21abd79 100644--- a/plugins/power-pages/scripts/tests/create-site-template-telemetry.test.js+++ b/plugins/power-pages/scripts/tests/create-site-template-telemetry.test.js@@ -9,6 +9,7 @@ const { spawnSync } = require('node:child_process');const { buildTemplateOutcomeEvent, emitTemplateOutcome, normalizeBool, sanitizeTemplateOutcomeInfo } = require('../lib/create-site-template-telemetry');const { parseArgs, toCliResult } = require('../emit-create-site-template-outcome');+const { version: PLUGIN_VERSION } = require('../../.plugin/plugin.json');test('buildTemplateOutcomeEvent emits non-PII template eventInfo through the existing skill event shape', () => {const event = buildTemplateOutcomeEvent({@@ -25,14 +26,13 @@ test('buildTemplateOutcomeEvent emits non-PII template eventInfo through the exi}, {readPacAuth: () => ({ orgId: 'org', tenantId: 'tenant' }),readAgentInfo: () => ({ aiAgentName: 'Copilot CLI', aiAgentVersion: '1.0.76-0', pacCliVersion: '2.10.1' }),- pluginVersion: '2.7.0',randomUUID: () => 'ignored',});assert.equal(event.name, 'PagesAIPluginEvent');assert.equal(event.data.eventName, 'template_used');assert.equal(event.data.skillName, 'create-site');- assert.equal(event.data.pluginVersion, '2.7.0');+ assert.equal(event.data.pluginVersion, PLUGIN_VERSION);assert.equal(event.data.sessionId, 'session');assert.equal(event.data.aiAgentName, 'Copilot CLI');assert.equal(event.data.aiAgentVersion, '1.0.76-0');@@ -162,7 +162,6 @@ test('buildTemplateOutcomeEvent emits scratch branch adoption signal', () => {readAgentInfo: () => ({}),randomUUID: () => 'corr',env: { COPILOT_AGENT_SESSION_ID: 'copilot-session' },- pluginVersion: '2.7.0',});assert.equal(event.data.eventName, 'create_site_from_scratch');diff --git a/plugins/power-pages/scripts/tests/render-review.test.js b/plugins/power-pages/scripts/tests/render-review.test.jsindex 7c80bb84f..fd8bb8541 100644--- a/plugins/power-pages/scripts/tests/render-review.test.js+++ b/plugins/power-pages/scripts/tests/render-review.test.js@@ -41,7 +41,15 @@ function fullDataPayload() {id: 'site-scan',icon: '◐',label: 'Live Site Scan',- findings: [],+ findings: [+ {+ id: 'perf-1',+ severity: 'warning',+ title: 'Power Pages Web API query is unbounded',+ aiSuggestion: 'Add a page-size limit that matches this list UI instead of loading every row.',+ mitigation: 'Use $top with paging or infinite scroll, then verify the page still renders all expected records.',+ },+ ],details: {},},],@@ -129,6 +137,10 @@ test('renders the shared security-review template when given a full data payload// regression that drops REVIEW_DATA substitution is caught even when the// placeholder is also removed.['REVIEW_DATA section label', 'Live Site Scan'],+ ['AI suggestion label', 'AI suggestion'],+ ['AI suggestion text', 'Add a page-size limit that matches this list UI'],+ ['Mitigation label', 'Mitigation'],+ ['Mitigation text', 'Use $top with paging or infinite scroll'],];for (const [label, value] of expectedSubstrings) {assert.ok(html.includes(value), `rendered HTML must include ${label} value "${value}"`);diff --git a/plugins/power-pages/scripts/tests/validate-analyze-performance.test.js b/plugins/power-pages/scripts/tests/validate-analyze-performance.test.jsnew file mode 100644index 000000000..b988d2c82--- /dev/null+++ b/plugins/power-pages/scripts/tests/validate-analyze-performance.test.js@@ -0,0 +1,165 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');+const { spawnSync } = require('child_process');+const fs = require('fs');+const os = require('os');+const path = require('path');++const { createTempProject, writeProjectFile } = require('./test-utils');++const VALIDATOR_PATH = path.join(+ __dirname,+ '..',+ '..',+ 'skills',+ 'analyze-performance',+ 'scripts',+ 'validate-analyze-performance.js',+);++function runValidator(projectRoot, reportPath = null) {+ const args = [VALIDATOR_PATH];+ if (reportPath) args.push('--reportPath', reportPath);+ return spawnSync(process.execPath, args, {+ input: JSON.stringify({ cwd: projectRoot }),+ encoding: 'utf8',+ });+}++// A minimally realistic rendered report: >500 bytes and free of __KEY__ tokens.+const GOOD_REPORT = '<!doctype html><html><head><title>Performance Analysis</title></head><body>' ++ '<h1>Performance Analysis</h1>' + 'x'.repeat(600) + '</body></html>';++function createNonSpaProject(t) {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'perf-non-spa-validator-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ fs.mkdirSync(path.join(root, '.portalconfig'), { recursive: true });+ fs.mkdirSync(path.join(root, 'web-pages'), { recursive: true });+ fs.writeFileSync(path.join(root, 'website.yml'), 'adx_name: Non-SPA Site\n');+ return root;+}++test('approves when the cwd is outside any Power Pages project', (t) => {+ // createTempProject seeds .powerpages-site/, so write to a bare tmp dir instead.+ const bare = fs.mkdtempSync(path.join(os.tmpdir(), 'perf-noproj-'));+ t.after(() => fs.rmSync(bare, { recursive: true, force: true }));++ const result = runValidator(bare);+ assert.equal(result.status, 0, result.stderr);+});++test('approves when the project has no performance report yet (in-progress / prereqs failed)', (t) => {+ const projectRoot = createTempProject(t);+ // No docs/performance-analysis-*.html written.+ const result = runValidator(projectRoot);+ assert.equal(result.status, 0, result.stderr);+});++test('approves a well-formed timestamped performance report', (t) => {+ const projectRoot = createTempProject(t);+ const reportPath = writeProjectFile(+ projectRoot,+ 'docs/performance-analysis-2026-05-14-053805.html',+ GOOD_REPORT,+ );++ const result = runValidator(projectRoot, reportPath);+ assert.equal(result.status, 0, result.stderr);+});++test('validates the explicit report instead of historical reports', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'docs/performance-analysis-2026-01-01-000000.html', 'tiny');+ const currentReport = writeProjectFile(+ projectRoot,+ 'docs/performance-analysis-2026-05-14-053805.html',+ GOOD_REPORT,+ );++ const result = runValidator(projectRoot, currentReport);+ assert.equal(result.status, 0, result.stderr);+});++test('hook mode ignores historical malformed reports', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'docs/performance-analysis-2026-01-01-000000.html', 'tiny');++ const result = runValidator(projectRoot);+ assert.equal(result.status, 0, result.stderr);+});++test('blocks when the explicit report was not created', (t) => {+ const projectRoot = createTempProject(t);+ const missing = path.join(projectRoot, 'docs', 'performance-analysis-2026-05-14-053805.html');++ const result = runValidator(projectRoot, missing);+ assert.equal(result.status, 2);+ assert.match(result.stderr, /was not created/);+});++test('blocks a report with unreplaced template placeholders', (t) => {+ const projectRoot = createTempProject(t);+ // __REVIEW_DATA__ left in place means render-template.js could not populate it.+ const broken = '<html><body>' + 'y'.repeat(600) + '__REVIEW_DATA__</body></html>';+ const reportPath = writeProjectFile(+ projectRoot,+ 'docs/performance-analysis-2026-05-14-053805.html',+ broken,+ );++ const result = runValidator(projectRoot, reportPath);+ assert.equal(result.status, 2);+ assert.match(result.stderr, /unreplaced template placeholders/);+});++test('blocks a suspiciously small report', (t) => {+ const projectRoot = createTempProject(t);+ const reportPath = writeProjectFile(+ projectRoot,+ 'docs/performance-analysis-2026-05-14-053805.html',+ '<html></html>',+ );++ const result = runValidator(projectRoot, reportPath);+ assert.equal(result.status, 2);+ assert.match(result.stderr, /suspiciously small/);+});++test('approves a non-SPA site (only .powerpages-site, no config) with a good report', (t) => {+ const projectRoot = createTempProject(t); // seeds .powerpages-site/ but no config+ const reportPath = writeProjectFile(+ projectRoot,+ 'docs/performance-analysis-2026-05-14-053805.html',+ GOOD_REPORT,+ );++ const result = runValidator(projectRoot, reportPath);+ assert.equal(result.status, 0, result.stderr);+});++test('approves a non-SPA PAC download with a good report', (t) => {+ const projectRoot = createNonSpaProject(t);+ const reportPath = writeProjectFile(+ projectRoot,+ 'docs/performance-analysis-2026-05-14-053805.html',+ GOOD_REPORT,+ );++ const result = runValidator(projectRoot, reportPath);+ assert.equal(result.status, 0, result.stderr);+});++test('blocks a suspiciously small non-SPA PAC download report', (t) => {+ const projectRoot = createNonSpaProject(t);+ const reportPath = writeProjectFile(+ projectRoot,+ 'docs/performance-analysis-2026-05-14-053805.html',+ '<html></html>',+ );++ const result = runValidator(projectRoot, reportPath);+ assert.equal(result.status, 2);+ assert.match(result.stderr, /suspiciously small/);+});diff --git a/plugins/power-pages/skills/analyze-performance/SKILL.md b/plugins/power-pages/skills/analyze-performance/SKILL.mdnew file mode 100644index 000000000..966ccdb8b--- /dev/null+++ b/plugins/power-pages/skills/analyze-performance/SKILL.md@@ -0,0 +1,332 @@+---+name: analyze-performance+description: >-+ Statically scans the entire local Power Pages codebase for performance+ anti-patterns — unpaginated Power Pages lists, webpages/web templates used as+ custom data APIs, FetchXML over-fetching / N+1 / advanced query hints / cache+ bypassing, unbounded Web API queries, disabled header/footer output caching,+ sign-in and page tracking, main-thread-blocking JS, CSS @import, frequent Web+ API polling, and oversized assets — then enriches findings with AI-driven+ suggestions and mitigations grounded in the affected customer-code snippets,+ reports them, and offers safe auto-fixes with per-fix approval.+ Use when the user wants to: "check performance", "perf check", "find+ performance issues", "why is my site slow", "optimize my Power Pages site",+ "find anti-patterns", "review FetchXML performance", "is my site over-fetching+ data", or "audit site performance".+user-invocable: true+argument-hint: "[optional: --review <out-dir>]"+allowed-tools: Read, Write, Edit, Bash, Glob, Grep, AskUserQuestion, TaskCreate, TaskUpdate, TaskList, mcp__plugin_power-pages_microsoft-learn__microsoft_docs_search, mcp__plugin_power-pages_microsoft-learn__microsoft_docs_fetch+model: opus+---++> **Plugin check**: Run `node "${PLUGIN_ROOT}/scripts/check-version.js"` — if it outputs a message, show it to the user before proceeding.++# analyze-performance++Statically analyzes the **entire local Power Pages codebase** for known performance anti-patterns, enriches the static findings with **AI-driven, code-aware suggestions and mitigations**, presents them by severity in an HTML report + plain-language summary, and offers **safe auto-fixes with per-fix approval**. Never applies a fix without explicit consent.++This skill reads local source only — it does not call the deployed site. For a live security/vulnerability scan use `/scan-site`.++**Initial request:** $ARGUMENTS++## Prerequisites++- An existing local **non-SPA** Power Pages project or PAC CLI site download.+ `.powerpages-site/`, root-level `.portalconfig/`, `website.yml`, and portal+ content folders are useful discovery markers, but they are not all required+ when the user supplies an existing site folder.+- SPA websites are not supported yet. `powerpages.config.json` is the+ authoritative local SPA marker; if it exists at the selected project root,+ tell the user this skill currently supports non-SPA websites only and stop.+- Node.js (bundled scripts run under `node`).++No sign-in, PAC CLI, or Azure CLI is required — the analysis is fully offline.++## What it detects++See `references/performance-reference.md` for the authoritative rule catalog (tags,+severities, detection, fixes, thresholds, and Microsoft Learn sources). The scan+must cover all of these categories:++- **List pagination** — Power Pages list definitions with no positive+ `adx_pagesize` / `pagesize`.+- **Webpages used as APIs** — FetchXML/entity-backed web templates or webpage+ content that emit JSON/XML instead of a normal HTML page.+- **FetchXML anti-patterns** — `all-attributes`, no explicit columns, too many+ columns, no paging, oversized `count`/`top`, N+1 queries inside Liquid loops,+ unnecessary `returntotalrecordcount`, leading-wildcard `like` filters, and+ related-table ordering.+- **FetchXML query controls** — advanced query hints (`options`,+ `latematerialize`, `no-lock`, `useraworderby`, filter `hint`) and request-time+ values or explicit settings that bypass server-side query caching.+- **Web API anti-patterns** — `$select=*`, missing `$select`, no page bound+ (`$top` safety cap or `Prefer: odata.maxpagesize=N` cursor paging),+ too many selected columns, oversized `$top`, `$count=true`, `$expand` without+ a nested `$select`, `contains`/`endswith` filters, request-time date filters,+ related-table ordering, request-per-item/N+1 loops, and short-interval polling.+- **Rendering and caching** — disabled Header/Footer output caching,+ render-blocking `<head>` scripts, runtime CSS `@import`, synchronous XHR/jQuery,+ and `document.write`.+- **Tracking and volume** — sign-in/page/file tracking, excessive web-file or+ web-role counts, and oversized static assets.++## Phases++1. **Prerequisites** — locate the project, confirm the site exists, detect review mode+1.5. **Ground in current performance guidance** — optional Microsoft Learn cross-check (capped, offline-safe)+2. **Scan** — run the deterministic analyzer over the codebase+2.5. **AI mitigation pass** — inspect customer-code snippets behind each finding and add code-aware suggestions/mitigations+3. **Present findings** — severity table + coverage stats + AI suggestions+4. **Offer auto-fixes** — per-finding consent loop for the safely-automatable findings+5. **Verify** — re-run the analyzer to confirm fixes resolved their findings+6. **Report & next action** — render the HTML report, summarize, and route follow-ups++## Task Tracking++Create tasks in three groups. Mark each `in_progress` when starting, `completed` when done.++| Group | When to create | Tasks |+|-------|----------------|-------|+| 1 | At start | Verify prerequisites and locate project |+| 2 | After prerequisites pass | Scan codebase for anti-patterns · Add AI-driven suggestions and mitigations · Present findings |+| 3 | After findings presented (skip all three in review mode) | Offer auto-fixes (only if any `autoFixAvailable`) · Verify fixes · Render report and route follow-ups |++---++## Phase 1 — Verify Prerequisites and Locate Project++1. **Detect review mode first**: if `$ARGUMENTS` contains `--review <out-dir>`,+ remember `<REVIEW_DIR>`.+2. Resolve `<PROJECT_ROOT>` in this order:+ - If `<REVIEW_DIR>` itself contains recognizable Power Pages source, use it as+ both `<PROJECT_ROOT>` and `<REVIEW_DIR>`. This supports orchestrated reviews+ that pass the downloaded site folder directly.+ - Otherwise use an explicitly supplied project directory, then the current+ working directory. Use `Glob` to locate `**/powerpages.config.json`,+ `**/.powerpages-site`, `**/.portalconfig`, or `**/website.yml` when needed.+3. Treat any of these as recognizable Power Pages source:+ `.powerpages-site/`, root-level `.portalconfig/`, `website.yml`, or a+ characteristic portal export layout containing folders such as `web-pages/`,+ `web-templates/`, or `web-files/`. Do **not** reject an explicitly supplied+ existing site folder merely because it lacks `.powerpages-site/`.+4. If `<PROJECT_ROOT>/powerpages.config.json` exists, tell the user that the+ selected path is a SPA website and this skill currently supports non-SPA+ Power Pages websites only, then **stop**.+5. If no existing directory with recognizable non-SPA Power Pages source can be located,+ tell the user and recommend `/create-site`, then **stop**.+6. In review mode Phases 3, 4, and 6-presentation are skipped: Phase 2 runs,+ Step 6.2 writes JSON only, and the skill stops after writing it.++Report: "Found project: `<PROJECT_ROOT>`. Scanning for performance anti-patterns."++## Phase 1.5 — Ground in current performance guidance++> Skip in **review mode**. Cap this step at ~30 seconds. If MCP search / fetch errors out or is unavailable, log a one-line note and continue — this skill must remain runnable offline.++1. Run `microsoft_docs_search` with the query: `Power Pages Site Checker performance FetchXML output caching best practices`.+2. Optionally `microsoft_docs_fetch` `https://learn.microsoft.com/en-us/power-pages/admin/site-checker-performance`.+3. Extract a one-paragraph summary of what Microsoft Learn currently says. Compare it against the rule catalog in `references/performance-reference.md`. If Learn documents a performance pattern not covered by any analyzer rule, surface it to the user in Phase 6 as a **manual** follow-up — do not silently invent findings the analyzer did not produce.++## Phase 2 — Scan the codebase++Run the deterministic analyzer over the whole project:++```bash+node "${PLUGIN_ROOT}/skills/analyze-performance/scripts/analyze-performance.js" --projectRoot "<PROJECT_ROOT>"+```++The analyzer prints a single JSON object `{ status, findings, details, severityCounts }` to stdout. Parse it. Each finding has `id`, `tag`, `severity`, `title`, `location`, `details`, `fix`, `autoFixAvailable`, and (when auto-fixable) `fixAction`. See `references/performance-reference.md` for the finding envelope and every tag's meaning.++If the only finding is `PERF-NONE`, the codebase is clean — note this and skip Phase 4/5 (still render the report in Phase 6 so the user has a record).++## Phase 2.5 — Add AI-driven suggestions and mitigations++Run this after every deterministic scan result that will be presented or written+to `analyze-performance.json` (including **review mode**). Skip only `PERF-NONE`.++For each finding, inspect the relevant customer-code context before writing the+final JSON:++1. Read the file named by `finding.location` and capture a tight snippet around+ the line (about 20 lines before/after, capped so the report stays readable).+ If the file no longer exists or the finding has no location, use the finding's+ `details` and `fix` only.+2. Add these fields to the finding object:+ - `aiSuggestion`: one or two sentences explaining the best next change for+ this specific code path, grounded in the snippet and the rule catalog.+ - `mitigation`: a concrete mitigation plan that preserves behavior. Name the+ likely code/config edit, the safer alternative when there are tradeoffs, and+ anything the user must verify manually.+3. Keep the deterministic fields (`tag`, `severity`, `fix`, `fixAction`,+ `autoFixAvailable`) unchanged. Do **not** downgrade, suppress, or invent+ analyzer findings during this AI pass.+4. For heuristic findings (for example webpage-as-API, Web API N+1, cache+ bypassing, related-column ordering), say that the suggestion is conditional+ and name the observation that would confirm it.+5. For auto-fixable site-setting/tracking findings, keep `mitigation` aligned+ with the existing `fixAction` and repeat any important caveat, especially the+ Header/Footer output-cache substitution requirement.++The report renderer displays `aiSuggestion` and `mitigation` as separate fields,+so write them into the JSON rather than only mentioning them in chat. If the+current AI context cannot safely inspect a file because it is restricted or too+large, add a conservative mitigation based on `details`/`fix` and explicitly say+the source snippet was not inspected.++## Phase 3 — Present findings++> Skip in **review mode** (go straight to Step 5.1's JSON write).++Present all findings grouped by severity, highest first. Include the AI+suggestion and mitigation under each row (or immediately after the table for long+items) so the user sees both the static check and the code-aware recommendation:++| # | Severity | Tag | Issue | Location | Auto-fix? |+|---|----------|-----|-------|----------|-----------|+| 1 | high | PERF-FETCHXML-ALLATTR | FetchXML retrieves all attributes | `...:2` | No |+| 2 | warning | PERF-HEADER-OUTPUTCACHE | Header output caching disabled | `...sitesetting.yml` | Yes |++Then show the coverage stats from `details.entries` (FetchXML/Liquid, list,+Web API/script and CSS files scanned; web-file/web-role counts; total findings).+Keep the language plain; explain a tag only when asked. Make clear that AI+suggestions are grounded in the local snippet but still require developer+judgment for business-specific behavior.++## Phase 4 — Offer auto-fixes++> Skip in **review mode**. Skip entirely if no finding has `autoFixAvailable: true`.++Only the site-setting and tracking findings are safely automatable (`PERF-HEADER-OUTPUTCACHE`, `PERF-FOOTER-OUTPUTCACHE`, `PERF-SIGNIN-TRACKING`, `PERF-WEBPAGE-TRACKING`, `PERF-WEBFILE-TRACKING`). List pagination, webpage-as-API, FetchXML, Web API, query-hint, cache-bypass, and asset findings require human judgment — present those as manual fixes only.++For each finding with `autoFixAvailable: true`, in order:++<!-- gate: analyze-performance:4.auto-fix | category=consent | cancel-leaves=nothing -->+> 🚦 **Gate (consent · analyze-performance:4.auto-fix):** Per-finding consent before applying any auto-fix. **Loops once per `autoFixAvailable` finding** — each gets its own Yes / No / Skip-all `AskUserQuestion` naming the finding's tag and the exact change. **Never batch fixes** — three fixable findings = three separate prompts (unless the user picks "Skip all", which short-circuits the loop). Each fix has its own blast radius (a different site setting or YAML file), so approving one does not approve the next.+>+> **Trigger:** Phase 4, once per fixable finding.+> **Why we ask:** Enabling output caching alone can break header/footer rendering unless the web templates also use `{% substitution %}` (see caveat below); toggling tracking edits committed YAML. The user must consent to each concrete change.+> **Cancel leaves:** Nothing — declining a fix leaves that finding untouched and reported as manual.++For the approved finding, apply its `fixAction`:++- **`create-site-setting`** (setting is absent from a per-record `.powerpages-site`+ layout): create it with the shared helper —+ ```bash+ node "${PLUGIN_ROOT}/scripts/create-site-setting.js" --projectRoot "<PROJECT_ROOT>" --name "<fixAction.name>" --value "<fixAction.value>" --type boolean --description "<short why>"+ ```+ If it reports the setting already exists, treat it as already handled and switch to the `set-site-setting` path.+- **`set-site-setting`** (setting exists but is wrong): use `Edit` on the finding's `location` file to flip the `value:` line (`false` → `true`, or tracking `true` → `false`). Do **not** call `create-site-setting.js` — it refuses to overwrite.+- **`set-yaml-field`**: use `Edit` at the finding's precise `location` to set+ `<fixAction.field>: <fixAction.value>` (e.g., `adx_enabletracking: false`).+ For a non-SPA aggregate `sitesetting.yml`, `fixAction.recordName` identifies the+ setting record and the location points at its exact `adx_value` line. Do not+ replace another record's matching boolean.++> **Output-cache caveat (always surface this):** enabling `Header/Footer/OutputCache/Enabled` is **not** sufficient on its own — the Header, Footer, and Languages-Dropdown web templates must also use the `{% substitution %}` Liquid tag, or those regions stop rendering. After applying an output-cache fix, tell the user to update those templates and verify the site still renders.++Mark each finding **Fixed**, **Skipped**, or **Manual required** as you go.++## Phase 5 — Verify fixes++> Skip in **review mode**. Skip if no auto-fix was applied.++Re-run the analyzer to confirm the applied fixes resolved their findings:++```bash+node "${PLUGIN_ROOT}/skills/analyze-performance/scripts/analyze-performance.js" --projectRoot "<PROJECT_ROOT>"+```++Confirm each fixed finding's tag/location is gone (or downgraded from `warning` to `info` for the absent→present caching case). If a fix did not take, report it and offer to retry or hand it to the user. Use this re-scanned result set as the basis for the Phase 6 report so it reflects the post-fix state.++## Phase 6 — Report & next action++### 6.1 Review mode short-circuit++Handled at Step 6.2 below — review mode never reaches the HTML render or the follow-up walk-through.++### Step 6.2 — Write the review JSON++Write the enriched `{ status, findings, details }` object (the Phase 5 re-scan result if a re-scan ran, otherwise the Phase 2 result, with Phase 2.5 `aiSuggestion`/`mitigation` fields applied) to a JSON file:++- **Review mode**: write to `<REVIEW_DIR>/analyze-performance.json`, then **stop**. The orchestrating skill (e.g., `security-review`) handles presentation.+- **Interactive mode**: write to `<TEMP_DIR>/analyze-performance.json` where `<TEMP_DIR>` is a scratch directory containing only this file.++The filename **must** be `analyze-performance.json` — that is the key+`build-review-data.js` maps to the Performance section.++### Step 6.3 — Render the HTML report++Skip in **review mode**. Reuse the shared report pipeline (same template as the security review and site scan):++The final HTML report is a persistent website artifact under+`<PROJECT_ROOT>/docs/`, consistent with the other review reports. Only+`analyze-performance.json` and `data.json` are temporary scratch files; delete their+temporary directory after the HTML render succeeds.++```bash+node "${PLUGIN_ROOT}/scripts/build-review-data.js" \+ --reportName "Performance Analysis" \+ --inputDir "<TEMP_DIR>" \+ --siteName "<SITE_NAME>" \+ --goalLabel "Performance" \+ --scopeLabel "Local codebase" \+ --summary "<SUMMARY_TEXT>" \+ --output "<TEMP_DIR>/data.json"++node "${PLUGIN_ROOT}/scripts/render-review.js" \+ --data "<TEMP_DIR>/data.json" \+ --output "<PROJECT_ROOT>/docs/performance-analysis-<YYYY-MM-DD-HHMMSS>.html"++node "${PLUGIN_ROOT}/skills/analyze-performance/scripts/validate-analyze-performance.js" \+ --reportPath "<PROJECT_ROOT>/docs/performance-analysis-<YYYY-MM-DD-HHMMSS>.html"+```++`<SITE_NAME>` comes from the site's `website.yml`; fall back to the folder name.+The filename **must** include the local timestamp (e.g.,+`performance-analysis-2026-05-14-053805.html`). Delete `<TEMP_DIR>` after the+render and explicit validation succeed, then open the report in the browser.++### Step 6.4 — Summarize and route follow-ups++<!-- gate: analyze-performance:6.next-action | category=plan | cancel-leaves=nothing -->+> 🚦 **Gate (plan · analyze-performance:6.next-action):** After the report, recommend the single most useful next step and let the user accept or choose differently via `AskUserQuestion` — walk through the manual (non-auto-fixable) findings one at a time, re-scan, or finish. Reviewing findings and re-scanning are read-only; nothing is changed without a later Phase 4 consent.+>+> **Trigger:** Phase 6, after the report is rendered (interactive mode only).+> **Why we ask:** The manual list, webpage-as-API, FetchXML, Web API, query-hint,+> cache-bypass, and asset fixes need edits the user must drive; auto-walking every+> finding would be noisy if they only wanted the report.+> **Cancel leaves:** Nothing — the report is already written; declining ends the skill cleanly.++Give a plain-language summary: total findings, count by severity, and how many+were auto-fixed. For manual findings (list pagination, webpage-as-API patterns,+FetchXML/Web API anti-patterns, query hints, cache bypassing, volume counts, and+large assets), offer to walk through them one at a time with the concrete edit+each needs. If nothing meaningful remains, end the skill — do not ask just to ask.++### Record Skill Usage++> Reference: `${PLUGIN_ROOT}/references/skill-tracking-reference.md`+>+> Use `--skillName "AnalyzePerformance"`.++## Constraints++- **Read-only until consent.** The analyzer never mutates anything. The only writes are the HTML report, the scratch JSON, and auto-fixes the user explicitly approves in Phase 4.+- **High-signal findings.** Heuristics (Web API N+1, missing-but-defaultable caching) are intentionally conservative to avoid false positives. When a finding is a heuristic, say so.+- **Plain language.** Explain a tag only when asked; lead with the impact, not the internal name.+- **Offline-safe.** Phase 1.5 is best-effort; the skill must complete with no network access.++## References++- `references/performance-reference.md` — authoritative rule catalog: tags, severities, detection logic, fixes, auto-fix actions, thresholds, manual-only checks, key nuances, and Microsoft Learn sources. Read when explaining a finding or deciding whether a fix is safe.++## Progress Tracking Table++| Task subject | activeForm | Description |+|---|---|---|+| Verify prerequisites and locate project | Verifying prerequisites | Locate an explicit/current code-site or PAC-download folder, confirm recognizable Power Pages source, detect review mode |+| Scan codebase for anti-patterns | Scanning codebase | Run analyze-performance.js over the project, parse findings JSON |+| Present findings | Presenting findings | Show severity table and coverage stats |+| Offer auto-fixes | Applying auto-fixes | Per-finding consent loop; apply site-setting/tracking fixes, surface substitution caveat |+| Verify fixes | Verifying fixes | Re-run analyzer, confirm fixed findings are gone |+| Render report and route follow-ups | Rendering report | Build review JSON, render HTML, summarize, route manual follow-ups |diff --git a/plugins/power-pages/skills/analyze-performance/references/performance-reference.md b/plugins/power-pages/skills/analyze-performance/references/performance-reference.mdnew file mode 100644index 000000000..eccc310d5--- /dev/null+++ b/plugins/power-pages/skills/analyze-performance/references/performance-reference.md@@ -0,0 +1,264 @@+# Performance Reference++Rule catalog for `scripts/analyze-performance.js` — the deterministic analyzer+behind `/power-pages:analyze-performance`. Use this when explaining a finding,+deciding whether an auto-fix is safe, or extending the analyzer.++> **Terminology**: the analyzer emits **findings**. Each finding carries a stable `tag` (e.g., `PERF-FETCHXML-ALLATTR`), a `severity`, a plain-language `title`/`details`/`fix`, and — for the subset that is safely automatable — `autoFixAvailable: true` plus a machine-readable `fixAction`.++## Table of contents++- [Finding envelope](#finding-envelope)+- [Severity scale](#severity-scale)+- [Rule catalog](#rule-catalog)+ - [FetchXML rules](#fetchxml-rules)+ - [List & webpage API rules](#list--webpage-api-rules)+ - [Web API rules](#web-api-rules)+ - [Client-side script rules](#client-side-script-rules)+ - [Render-blocking & CSS rules](#render-blocking--css-rules)+ - [Output caching & tracking rules](#output-caching--tracking-rules)+ - [Volume rules](#volume-rules)+- [Auto-fix actions](#auto-fix-actions)+- [Manual-only checks](#manual-only-checks)+- [Key nuances](#key-nuances)+- [Thresholds](#thresholds)+- [Microsoft Learn sources](#microsoft-learn-sources)++---++## Finding envelope++`analyze-performance.js` prints a single JSON object to stdout:++```json+{+ "status": "ok",+ "findings": [+ {+ "id": "perf-1",+ "tag": "PERF-FETCHXML-ALLATTR",+ "severity": "high",+ "title": "FetchXML retrieves all attributes",+ "location": ".powerpages-site/web-templates/home/Home.webtemplate.source.html:2",+ "details": "...",+ "aiSuggestion": "Code-aware recommendation generated after inspecting the local snippet.",+ "mitigation": "Concrete mitigation plan that preserves behavior and names manual validation.",+ "fix": "...",+ "autoFixAvailable": false,+ "fixSkill": null,+ "fixAction": null+ }+ ],+ "details": { "kind": "kv", "label": "Scan coverage", "entries": [ { "key": "...", "value": "..." } ] },+ "severityCounts": { "high": 3, "warning": 3, "info": 1 }+}+```++The deterministic analyzer emits the stable rule fields (`tag`, `severity`, `details`, `fix`, `autoFixAvailable`, `fixAction`). The skill then enriches every non-`PERF-NONE` finding with `aiSuggestion` and `mitigation` after inspecting the customer-code snippet at `location`. This enriched `{ status, findings, details }` shape is what `scripts/build-review-data.js` (via the `analyze-performance.json` `SECTION_MAP` entry, id `performance`, icon ⚡) and `scripts/render-review.js` consume — the same shared HTML report pipeline `scan-site` uses. `severityCounts` is an analyzer convenience for the in-chat summary; the renderer ignores it.++When no anti-pattern is found the analyzer still emits one `info` finding tagged `PERF-NONE` so the report is never empty.++## Severity scale++| `severity` | Meaning in this skill |+|------------|-----------------------|+| `high` | A pattern that materially multiplies data volume or round-trips (over-fetching, N+1). Fix before shipping. |+| `warning` | A likely performance cost that depends on data size (unbounded queries, disabled caching, large volume counts). |+| `info` | A nudge or context-dependent item (missing-but-defaultable settings, deprecated tracking, large assets). |++The analyzer never emits `critical` — these are code-quality/perf issues, not outages. The severity vocabulary itself is the shared set (`critical|high|warning|medium|info|low|pass`) understood by `build-review-data.js`.++---++## Rule catalog++Each rule is a pure function in `analyze-performance.js` (unit-tested in+`scripts/tests/analyze-performance.test.js`). `location` is a repo-relative+`path:line` wherever a source offset exists.++### FetchXML rules++Scanned in files with extensions `.html/.htm/.liquid/.xml/.yml/.yaml` (web-template Liquid source ships as `<name>.webtemplate.source.html`; FetchXML can also be embedded in list/form YAML).++| Tag | Detect | Severity | Auto-fix | Why it matters |+|-----|--------|----------|----------|----------------|+| `PERF-FETCHXML-ALLATTR` | `<all-attributes/>` or `all-attributes="true"` inside a `<fetch>` | high | No | Returns every column — inflates payload, slows the query, over-exposes data. |+| `PERF-FETCHXML-NO-COLUMNS` | `<entity>` with no `<attribute>` and not an aggregate | warning | No | No explicit projection ⇒ platform returns a default column set, more than the page needs. |+| `PERF-FETCHXML-MANY-COLUMNS` | more than `FETCHXML_MAX_ATTRIBUTES` (20) explicit `<attribute>` elements | info | No | Wide projections increase payload size and query cost, even when they avoid `all-attributes`. |+| `PERF-FETCHXML-NO-PAGING` | `<fetch>` with no `count`/`top` and not an aggregate | warning | No | Unbounded list query — a common cause of slow pages and portal timeouts on large tables. |+| `PERF-FETCHXML-LARGE-COUNT` | `count`/`top` > `FETCHXML_MAX_COUNT` (100) | warning | No | Large single-page fetch increases render time and timeout risk; prefer smaller pages. |+| `PERF-FETCHXML-IN-LOOP` | `<fetch` appears while inside a Liquid `{% for %}`…`{% endfor %}` | high | No | N+1: the query runs once per iteration, multiplying round-trips. The single biggest Liquid perf pitfall. |+| `PERF-FETCHXML-TOTALRECORDCOUNT` | `returntotalrecordcount="true"` on a `<fetch>` | info | No | Forces the platform to compute the total matching row count (capped at 5000) alongside the page — only worth it when the UI shows a total; adds overhead on large tables. |+| `PERF-FETCHXML-QUERY-HINT` | `options`, `latematerialize="true"`, `no-lock="true"`, `useraworderby="true"`, or a filter `hint` | warning | No | Advanced optimization switches are workload-specific. Microsoft warns that unsupported/incorrect query options can reduce performance. |+| `PERF-FETCHXML-CACHE-BYPASS` | explicit no-cache attribute or request-time `"now" \| date` value inside FetchXML | warning | No | Makes the query text change per request, preventing server-side cache reuse and increasing Dataverse load. |+| `PERF-FETCHXML-LEADING-WILDCARD` | `operator="like"` / `not-like` with a value beginning `%` or `*` | warning | No | Leading-wildcard string searches cannot use a normal prefix seek and can become expensive on large tables. |+| `PERF-FETCHXML-ORDER-RELATED` | `<order>` inside a `<link-entity>` or with a related entity/alias | info | No | Sorting by a related table column can force extra join/sort work compared with sorting on the base table. |++Aggregate fetches (`aggregate="true"`) are **exempt** from the no-columns, no-paging, and large-count rules — they return a single summary row, so paging/projection do not apply.++### List & webpage API rules++| Tag | Detect | Severity | Auto-fix | Why it matters |+|-----|--------|----------|----------|----------------|+| `PERF-LIST-NO-PAGING` | a `*.list.yml` definition with no positive `adx_pagesize` / `pagesize` | warning | No | An unbounded list can retrieve and render too many rows in one response. |+| `PERF-WEBPAGE-AS-API` | a FetchXML/entity-backed `.webtemplate.source.html` or `.webpage.copy.html` that emits JSON/XML and has no normal HTML shell | warning | No | Treating a Liquid webpage as a custom API adds server rendering overhead and scales worse than the native Web API or Server Logic. |++`PERF-WEBPAGE-AS-API` is intentionally conservative and heuristic: it requires+both a Dataverse data-query signal and structured JSON/XML output without a+normal HTML shell. Review the finding before changing an intentional endpoint.++### Web API rules++Scanned in code files (`.ts/.tsx/.js/.jsx/.mjs/.cjs/.vue/.svelte/.astro/.html/.htm`) for the Power Pages Web API path segment `/_api/`.++| Tag | Detect | Severity | Auto-fix | Why it matters |+|-----|--------|----------|----------|----------------|+| `PERF-WEBAPI-SELECT-STAR` | `/_api/` URL with `$select=*` | high | No | Returns every column; list only the columns the UI binds. |+| `PERF-WEBAPI-NO-SELECT` | `/_api/` URL with query options but no `$select` | warning | No | Default projection returns all columns — more data than needed. |+| `PERF-WEBAPI-MANY-COLUMNS` | `$select` lists more than `WEBAPI_MAX_SELECT_COLUMNS` (20) columns | info | No | Wide projections increase payload size and client parsing cost. |+| `PERF-WEBAPI-NO-TOP` | `/_api/` collection query with neither a `$top` safety cap nor a `Prefer: odata.maxpagesize=N` cursor-page size in the enclosing request | warning | No | An unbounded result set slows the page and can hit throttling limits. Use `Prefer` + `@odata.nextLink` for page navigation; reserve `$top` for a total-result cap. |+| `PERF-WEBAPI-LARGE-TOP` | `$top` > `WEBAPI_MAX_TOP` (100) | warning | No | Large single-response payloads slow rendering and increase throttling risk; prefer smaller pages. |+| `PERF-WEBAPI-COUNT` | `$count=true` on a Web API request | info | No | Forces Dataverse to compute the total matching row count; only worth it when the UI displays a total. |+| `PERF-WEBAPI-EXPAND-NO-SELECT` | `$expand=...` without a nested `$select` | warning | No | Expanded related rows can return more columns than the page needs. |+| `PERF-WEBAPI-WILDCARD-FILTER` | `$filter` uses `contains(...)` or `endswith(...)` | warning | No | Contains/ends-with searches are leading-wildcard-like and can be expensive on large tables. |+| `PERF-WEBAPI-CACHE-BYPASS` | `$filter` appears to include request-time date values (`new Date`, `Date.now`, `toISOString`, `now()`) | warning | No | A changing query string prevents cache reuse and increases Dataverse load under traffic. |+| `PERF-WEBAPI-ORDER-RELATED` | `$orderby` uses a related property path (`relationship/column`) | info | No | Related-column sorts can require extra join/sort work compared with sorting on the base table. |+| `PERF-WEBAPI-IN-LOOP` | async `.map`/`.forEach`/`.filter`/`.reduce` callback whose body calls `/_api/` | info | No | Possible N+1: one request per array element. Heuristic — verify before acting. |++### Client-side script rules++Scanned in JS/HTML code files (`.ts/.tsx/.js/.jsx/.mjs/.cjs/.vue/.svelte/.astro/.html/.htm`) — the same population as the Web API scan (inline `<script>` in HTML is covered). These flag main-thread-blocking JS and aggressive Web API polling.++| Tag | Detect | Severity | Auto-fix | Why it matters |+|-----|--------|----------|----------|----------------|+| `PERF-SYNC-XHR` | `XMLHttpRequest.open(method, url, false)` (async flag `false`) | high | No | Synchronous XHR freezes the UI thread until the request returns; deprecated. |+| `PERF-JQUERY-SYNC-AJAX` | `async: false` inside a file that calls `.ajax(` | high | No | Synchronous jQuery AJAX blocks the UI thread the same way sync XHR does. |+| `PERF-DOCUMENT-WRITE` | `document.write(` / `document.writeln(` | warning | No | Forces a synchronous parse/reflow and, post-load, can blank the page; browsers de-prioritize it. |+| `PERF-SHORT-POLL` | `setInterval(…, <10000ms)` whose inline callback references `/_api/` | warning | No | Frequent Web API polling consumes licensed capacity and adds Dataverse load; can approach service limits. |++The sync-ajax rule gates on an `.ajax(` call being present and uses a `\basync\b` word boundary, so a stray `async: false` in an unrelated config object (or a `isAsync` substring) is not flagged. The short-poll rule only catches the **inline-callback** shape (`setInterval(() => { fetch("/_api/…") }, 3000)`) — a named-function reference is left alone — to stay high-signal.++### Render-blocking & CSS rules++| Tag | Detect | Severity | Auto-fix | Why it matters | Scanned in |+|-----|--------|----------|----------|----------------|------------|+| `PERF-RENDER-BLOCKING-SCRIPT` | external `<script src=…>` inside `<head>` with no `async`/`defer`/`type="module"` | warning | No | Blocks HTML parsing until the script downloads and executes — delays first paint. | `.html/.htm` |+| `PERF-CSS-IMPORT` | `@import` in a runtime `.css` file | warning | No | The browser fetches an `@import`ed sheet only after parsing the parent CSS, serializing downloads and delaying render. | `.css` only |++Only runtime `.css` is scanned for `@import`; pre-processor sources (`.scss`/`.less`) are excluded because their `@import` is resolved at build time. Commented-out `@import`s (inside `/* … */`) are ignored while line numbers for real ones stay accurate.++### Output caching & tracking rules++These read either `.powerpages-site/site-settings/*.sitesetting.yml` (via the+shared `loadSiteSettings` parser) or a non-SPA PAC download's root-level+`sitesetting.yml` aggregate list. Page/file tracking reads the per-record YAML in+either export layout. The rules run only when the relevant metadata exists.++| Tag | Detect | Severity | Auto-fix | Why it matters |+|-----|--------|----------|----------|----------------|+| `PERF-HEADER-OUTPUTCACHE` | `Header/OutputCache/Enabled` present & false | warning | **Yes** (`set-site-setting`) | Header web template re-parsed/rendered on every page load. |+| `PERF-HEADER-OUTPUTCACHE` | `Header/OutputCache/Enabled` absent | info | **Yes** (`create-site-setting`) | Upgraded sites default this off; new sites default on. |+| `PERF-FOOTER-OUTPUTCACHE` | `Footer/OutputCache/Enabled` present & false | warning | **Yes** (`set-site-setting`) | Footer web template re-parsed/rendered on every page load. |+| `PERF-FOOTER-OUTPUTCACHE` | `Footer/OutputCache/Enabled` absent | info | **Yes** (`create-site-setting`) | Same default-on/off nuance as header. |+| `PERF-SIGNIN-TRACKING` | `Authentication/LoginTrackingEnabled` true | warning | **Yes** (`set-site-setting`) | Writes a tracking record on every sign-in — avoidable write pressure. |+| `PERF-WEBPAGE-TRACKING` | web-page YAML with `adx_enabletracking: true` | info | **Yes** (`set-yaml-field`) | Deprecated page tracking (retired 9.3.4.x+); Site Checker flags it. |+| `PERF-WEBFILE-TRACKING` | web-file YAML with `adx_enabletracking: true` | info | **Yes** (`set-yaml-field`) | Deprecated file tracking (retired 9.3.4.x+); Site Checker flags it. |++### Volume rules++| Tag | Detect | Severity | Auto-fix | Why it matters |+|-----|--------|----------|----------|----------------|+| `PERF-WEBFILE-COUNT` | `.webfile.yml` count across `.powerpages-site/web-files/` or non-SPA root `web-files/` > `WEB_FILE_WARN_THRESHOLD` (500) | warning | No | Large web-file table slows website startup. Move static content to Blob/CDN. |+| `PERF-WEBROLE-COUNT` | per-record `.webrole.yml` count or non-SPA root `webrole.yml` record count > `WEB_ROLE_WARN_THRESHOLD` (100) | warning | No | Many roles evaluated per request affect every page. Consolidate roles. |+| `PERF-LARGE-STATIC-ASSET` | any media/binary asset > `LARGE_ASSET_BYTES` (1 MiB) | info | No | Large unoptimized assets slow first load, especially on mobile. Compress or move to CDN. |++`PERF-LARGE-STATIC-ASSET` reports at most the 20 largest offenders so a media-heavy project cannot drown the report.++---++## Auto-fix actions++For findings with `autoFixAvailable: true`, `fixAction` tells the SKILL.md Phase 4 loop exactly what deterministic change to apply. **Every fix is gated by per-finding consent** (`analyze-performance:4.auto-fix`, category=consent) — the analyzer never mutates anything.++| `fixAction.type` | Fields | How the skill applies it |+|------------------|--------|--------------------------|+| `create-site-setting` | `name`, `value`, `valueType` | Per-record `.powerpages-site` layout only: `node "${PLUGIN_ROOT}/scripts/create-site-setting.js" --projectRoot <root> --name <name> --value <value> --type boolean --description "<why>"`. Errors if the setting already exists — treat that as "already handled". A missing setting in a non-SPA aggregate `sitesetting.yml` remains manual because creating a second metadata layout would be unsafe. |+| `set-site-setting` | `name`, `value`, `valueType` | The setting file already exists; use `Edit` to flip the `value:` line (e.g., `false` → `true`, or tracking `true` → `false`). Do **not** call `create-site-setting.js` (it refuses to overwrite). |+| `set-yaml-field` | `field`, `value`, optional `recordName` | Use `Edit` at the finding's precise `location` to set `<field>: <value>` (e.g., `adx_enabletracking: false`). For a non-SPA aggregate `sitesetting.yml`, `recordName` identifies the record and the location points at its exact `adx_value` line. |++**Output-cache fixes carry a mandatory caveat** (already baked into the finding's `fix` text): enabling `Header/Footer/OutputCache/Enabled` alone is **not** sufficient — the Header, Footer, and Languages-Dropdown web templates must also use the `{% substitution %}` Liquid tag, or those regions stop rendering. Always surface this caveat when applying the fix and recommend verifying the templates.++## AI-driven suggestions and mitigations++The analyzer stays deterministic; it does **not** call an AI service or mutate source. The `/power-pages:analyze-performance` workflow performs a separate AI mitigation pass over analyzer results:++- Read the local customer-code snippet behind each finding (`location`, about 20 lines on either side when available).+- Preserve static fields exactly as emitted; do not hide, downgrade, or invent findings.+- Add `aiSuggestion` with a snippet-grounded recommendation and `mitigation` with the safest behavior-preserving edit path plus manual validation notes.+- Mark heuristic findings as conditional when the snippet is not enough to prove the issue.+- Keep auto-fixable findings aligned with their `fixAction`, and repeat required caveats such as Header/Footer `{% substitution %}` after enabling output caching.++The shared review template renders `aiSuggestion` and `mitigation` as first-class fields under each finding, so review-mode JSON and interactive HTML reports both carry the static check plus the AI-driven guidance.++---++## Manual-only checks++Documented here for completeness; **not** emitted by the analyzer because they require live Dataverse data the static scan cannot see:++- **Basic/advanced form lookup dropdown with > 200 records.** A lookup rendered as a dropdown that binds a table with more than ~200 rows loads slowly. Site Checker flags this at runtime. Recommend switching the control to a modal lookup / search, or filtering the source view. Route the user to review the form in Power Pages Studio.+- **Missing table indexes / slow custom Dataverse views.** Query plans are a server-side concern; recommend the Power Platform admin center and Site Checker for these.+- **Ordering by choice columns.** Static source only has logical column names, not Dataverse attribute metadata, so the analyzer cannot reliably know whether `<order attribute="statuscode">` or `$orderby=statuscode` is a choice column. Treat this as a Dataverse metadata/live review item.+- **Filtering on multiline text columns.** The analyzer can detect leading-wildcard/contains-style filters, but it cannot reliably know whether a filtered logical name is a multiline text column without metadata. Avoid guessing from names like `description` because that creates noisy false positives.+- **Apostrophes/special characters in search text.** This is usually an escaping/correctness or search-quality concern rather than a stable performance finding in local source. The analyzer flags the expensive query shapes around it (`contains`, `endswith`, leading wildcards), not arbitrary apostrophe characters.++---++## Key nuances++- **Non-SPA scope.** The skill and analyzer reject projects containing+ `powerpages.config.json`, the authoritative local marker for a Power Pages SPA+ website. The current rules target Liquid, portal metadata, and non-SPA export+ layouts; accepting a SPA would produce an incomplete performance assessment.+ Supported non-SPA exports may store settings under+ `.powerpages-site/site-settings/` or in root-level `sitesetting.yml`.+- **Default-on vs default-off caching.** New sites default header/footer output caching **on**; upgraded sites default it **off** when the setting is absent. Hence: present-and-false ⇒ `warning` (confident), absent ⇒ `info` (a nudge).+- **`adx_enabletracking` is deprecated, not removed.** The field is retired on portal versions 9.3.4.x and later, but older exports still carry it; Site Checker continues to flag it, so the analyzer does too (at `info`).+- **Heuristics are intentionally conservative.** `PERF-WEBAPI-IN-LOOP` requires an `async` callback and a `/_api/` reference within the same statement window to stay high-signal; a plain `.map` over already-fetched results is not flagged.+- **Query hints are review findings, not automatic removals.** `options`,+ `latematerialize`, and `hint="union"` can help specific measured workloads.+ The analyzer flags their presence because Microsoft recommends support-guided+ use; it does not claim every hint is wrong.+- **Cache-bypass detection is narrow.** It flags explicit no-cache variants and+ current-time Liquid inside FetchXML. User-input filters are not treated as+ cache bypassing because they are usually legitimate query parameters.+- **Build output is skipped.** Content scans prune `dist/build/out/bin/obj/.astro/...` so minified bundles don't create duplicate, un-fixable noise — the actionable location is always the source file.++## Thresholds++Defined and exported from `analyze-performance.js` (tests assert against the real constants, not copies):++| Constant | Value | Rule |+|----------|-------|------|+| `FETCHXML_MAX_COUNT` | 100 | `PERF-FETCHXML-LARGE-COUNT` |+| `FETCHXML_MAX_ATTRIBUTES` | 20 | `PERF-FETCHXML-MANY-COLUMNS` |+| `WEBAPI_MAX_TOP` | 100 | `PERF-WEBAPI-LARGE-TOP` |+| `WEBAPI_MAX_SELECT_COLUMNS` | 20 | `PERF-WEBAPI-MANY-COLUMNS` |+| `SHORT_POLL_INTERVAL_MS` | 10000 (10s) | `PERF-SHORT-POLL` |+| `WEB_FILE_WARN_THRESHOLD` | 500 | `PERF-WEBFILE-COUNT` |+| `WEB_ROLE_WARN_THRESHOLD` | 100 | `PERF-WEBROLE-COUNT` |+| `LARGE_ASSET_BYTES` | 1 MiB (1048576) | `PERF-LARGE-STATIC-ASSET` |++## Microsoft Learn sources++- Site Checker — performance checks: <https://learn.microsoft.com/en-us/power-pages/admin/site-checker-performance>+- Enable header and footer output caching: <https://learn.microsoft.com/en-us/power-pages/configure/enable-header-footer-output-caching>+- Use FetchXML to retrieve data (Liquid): <https://learn.microsoft.com/en-us/power-pages/configure/liquid/liquid-tags#fetchxml>+- Page large result sets with FetchXML (`returntotalrecordcount`): <https://learn.microsoft.com/en-us/power-apps/developer/data-platform/fetchxml/page-results>+- Optimize FetchXML and review query hints: <https://learn.microsoft.com/en-us/power-apps/developer/data-platform/fetchxml/optimize-performance>+- Power Pages server-side caching: <https://learn.microsoft.com/en-us/power-pages/admin/clear-server-side-cache>+- Power Pages Web API overview & limits: <https://learn.microsoft.com/en-us/power-pages/configure/web-api-overview>+- Eliminate render-blocking resources (scripts & CSS): <https://web.dev/articles/render-blocking-resources>+- Avoid `document.write()`: <https://web.dev/articles/no-document-write>+- `XMLHttpRequest.open()` (synchronous request deprecation): <https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/open>+- CSS `@import`: <https://developer.mozilla.org/en-US/docs/Web/CSS/@import>diff --git a/plugins/power-pages/skills/analyze-performance/scripts/analyze-performance.js b/plugins/power-pages/skills/analyze-performance/scripts/analyze-performance.jsnew file mode 100644index 000000000..c502b2701--- /dev/null+++ b/plugins/power-pages/skills/analyze-performance/scripts/analyze-performance.js@@ -0,0 +1,1526 @@+#!/usr/bin/env node++// Static performance analyzer for Power Pages projects. Walks the local code base+// and flags known performance anti-patterns, emitting a findings JSON envelope on+// stdout in the SAME shape the shared report pipeline consumes+// (scripts/build-review-data.js → scripts/render-review.js):+//+// { status: "ok", findings: [ { id, tag, severity, title, location, details,+// fix, autoFixAvailable, fixSkill, fixAction } ],+// details: { kind: "kv", label, entries: [ { key, value } ] } }+//+// Usage:+// node analyze-performance.js --projectRoot <path> # defaults to cwd+// node analyze-performance.js --review # (flag ignored here; SKILL.md branches)+//+// Exit codes: 0 on success (including "no issues"), 1 only on a fatal I/O error.+//+// Design: the pure rule functions (FetchXML, lists, webpage-as-API, Web API,+// client/rendering, settings, counts, and assets) take already-read strings/data+// and return findings WITHOUT ids or fs access, so they are unit-testable in+// isolation. analyze() does the directory walking, calls each rule function, then+// assigns sequential `perf-N` ids. This mirrors scan-site/transform-report.js+// (deterministic transform → findings) so the SKILL.md stays orchestration-only.+//+// Anti-patterns are grounded in Microsoft Learn:+// - Site Checker performance: https://learn.microsoft.com/en-us/power-pages/admin/site-checker-performance+// - Header/footer output caching: https://learn.microsoft.com/en-us/power-pages/configure/enable-header-footer-output-caching+// - FetchXML with Liquid: https://learn.microsoft.com/en-us/power-pages/configure/liquid/liquid-operators (and fetchxml tag docs)++'use strict';++const fs = require('fs');+const path = require('path');++// loadSiteSettings is the single source of truth for parsing `.sitesetting.yml`+// files (quoting rules, boolean coercion). Reuse it rather than re-parsing YAML+// here — DRY per AGENTS.md ("reuse scripts/lib/powerpages-config.js anywhere a+// script reads .powerpages-site ... site-setting YAML").+const {+ loadSiteSettings,+ parseSimpleYaml,+} = require('../../../scripts/lib/powerpages-config');++// ── Thresholds (documented, overridable only by editing here) ───────────────+// count/top above this is treated as "retrieving too much data per page". Power+// Pages FetchXML best practice keeps page sizes small and pages via+// count + page/nextpagecookie rather than one large fetch.+const FETCHXML_MAX_COUNT = 100;+const FETCHXML_MAX_ATTRIBUTES = 20;+// Keep Web API collection pages in the same conservative range as FetchXML pages.+// Larger `$top` values can be legitimate for admin screens, but they are usually a+// sign that the UI should page, virtualize, or fetch on demand instead.+const WEBAPI_MAX_TOP = 100;+const WEBAPI_MAX_SELECT_COLUMNS = 20;+// Site Checker flags "Large number of web file records" at > 500 active web files+// (startup slowness). See site-checker-performance "Large number of web file records".+const WEB_FILE_WARN_THRESHOLD = 500;+// Site Checker flags web-role counts > 100 (per-request permission evaluation cost).+// See site-checker-performance "Number of web roles".+const WEB_ROLE_WARN_THRESHOLD = 100;+// Unoptimized media is a common first-load regression. 1 MiB is a conservative+// "worth a look" bar for a single static asset shipped with the site.+const LARGE_ASSET_BYTES = 1024 * 1024;+// Cap the large-asset findings so a media-heavy project can't drown the report.+const LARGE_ASSET_MAX_FINDINGS = 20;+// setInterval delays below this (10s) that poll the portals Web API are treated as+// aggressive polling. The portals Web API "isn't optimized for third-party services+// or application integration" and every call consumes licensed user capacity, so a+// tight poll loop adds avoidable Dataverse load. Kept conservative (sub-10s) to stay+// high-signal. See: https://learn.microsoft.com/en-us/power-pages/configure/web-api-overview+const SHORT_POLL_INTERVAL_MS = 10000;++// Directories we never descend into for ANY scan.+const ALWAYS_SKIP_DIRS = new Set([+ 'node_modules', '.git', '.github', '.vs', '.vscode', 'coverage', '.idea', 'docs',+]);+// Additional directories skipped for SOURCE-content scans (FetchXML / Web API):+// these hold compiled/minified output — the actionable location is the source,+// and scanning minified bundles produces duplicate, un-fixable noise.+const BUILD_OUTPUT_DIRS = new Set([+ 'dist', 'build', 'out', '.output', 'public-output', 'bin', 'obj', '.astro',+]);++// Extensions that may embed FetchXML / Liquid. Web-template Liquid source ships as+// `<name>.webtemplate.source.html`; entity list / form config can embed fetchxml in+// `.yml`. `.xml` covers standalone fetch snippets.+const FETCHXML_EXTS = new Set(['.html', '.htm', '.liquid', '.xml', '.yml', '.yaml']);+// Extensions that may contain Power Pages Web API (`/_api/`) calls.+const WEBAPI_EXTS = new Set([+ '.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.vue', '.svelte', '.astro', '.html', '.htm',+]);+// Extensions whose files ship as runtime CSS the browser must parse before render.+// Only `.css` (not `.scss`/`.less`) — pre-processor @import is resolved at build time,+// whereas a runtime `@import` inside a served stylesheet blocks rendering.+const STYLE_EXTS = new Set(['.css']);+// Extensions that can carry a render-blocking <head> (declarative HTML pages). The+// client-script scan (sync XHR, document.write, jQuery sync ajax, short polling) reuses+// WEBAPI_EXTS — the same JS/HTML population that can call the Web API.+const HTML_EXTS = new Set(['.html', '.htm']);+// Media / binary asset extensions checked for oversized files.+const ASSET_EXTS = new Set([+ '.png', '.jpg', '.jpeg', '.gif', '.bmp', '.tif', '.tiff', '.webp', '.svg', '.ico',+ '.mp4', '.webm', '.mov', '.avi', '.mkv', '.mp3', '.wav', '.ogg',+ '.pdf', '.woff', '.woff2', '.ttf', '.otf', '.eot',+]);++const SEVERITY = Object.freeze({+ CRITICAL: 'critical', HIGH: 'high', WARNING: 'warning',+ MEDIUM: 'medium', INFO: 'info', LOW: 'low',+});++function getArg(name, fallback = null) {+ const idx = process.argv.indexOf('--' + name);+ return idx !== -1 && idx + 1 < process.argv.length ? process.argv[idx + 1] : fallback;+}++// 1-based line number of a character offset — used to point findings at a precise+// `path:line` so the report and the agent can jump straight to the offending code.+function lineOf(content, index) {+ return content.slice(0, index).split(/\r?\n/).length;+}++// Rule-function output helper. Findings are id-less here; analyze() numbers them.+function finding(fields) {+ return {+ tag: fields.tag,+ severity: fields.severity,+ title: fields.title,+ location: fields.location || null,+ details: fields.details,+ fix: fields.fix,+ autoFixAvailable: Boolean(fields.autoFixAvailable),+ fixSkill: fields.fixSkill || null,+ // fixAction is a machine-readable descriptor the SKILL.md auto-fix loop uses to+ // apply a deterministic change (only set for autoFixAvailable findings).+ fixAction: fields.fixAction || null,+ };+}++// Tiny attribute parser for the XML/HTML fragments this analyzer inspects. Raw+// shapes handled:+// <condition attribute="name" operator="like" value="%abc" />+// <fetch count='50' returntotalrecordcount='true'>+// Unquoted values are accepted defensively because exported snippets are sometimes+// hand-edited; malformed tags simply produce fewer attributes rather than failing+// the whole scan.+function parseTagAttributes(tag) {+ const attrs = {};+ const attrRe = /([:\w-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s/>]+))/g;+ let match;+ while ((match = attrRe.exec(tag)) !== null) {+ attrs[match[1].toLowerCase()] = match[2] ?? match[3] ?? match[4] ?? '';+ }+ return attrs;+}++function safeDecodeURIComponent(value) {+ try {+ return decodeURIComponent(value);+ } catch {+ return value;+ }+}++// ── FetchXML rules ──────────────────────────────────────────────────────────+// Parses `<fetch ...> ... </fetch>` blocks. Example raw shapes handled:+// Liquid web template:+// {% fetchxml products %}+// <fetch count="200" returntotalrecordcount="true">+// <entity name="cr123_product"><all-attributes /></entity>+// </fetch>+// {% endfetchxml %}+// Aggregate count (GOOD — must NOT be flagged for paging/columns):+// <fetch aggregate="true"><entity name="contact">+// <attribute name="contactid" alias="c" aggregate="count"/></entity></fetch>+function scanFetchXmlContent(content, relPath) {+ const out = [];+ if (!content.includes('<fetch')) {+ // No fetch element means nothing to flag in this file.+ return out;+ }++ // Each fetch block, with its start offset for line numbers.+ const blockRe = /<fetch\b[\s\S]*?<\/fetch>/gi;+ let m;+ while ((m = blockRe.exec(content)) !== null) {+ const block = m[0];+ const at = `${relPath}:${lineOf(content, m.index)}`;++ const openTag = (block.match(/<fetch\b([^>]*)>/i) || [, ''])[1];+ const isAggregate = /\baggregate\s*=\s*["']?true/i.test(openTag);+ const hasAllAttributes = /all-attributes/i.test(block);+ const attributeMatches = [...block.matchAll(/<attribute\b[^>]*>/gi)];+ const hasAttribute = attributeMatches.length > 0;+ const countMatch = openTag.match(/\b(?:count|top)\s*=\s*["']?(\d+)/i);++ if (hasAllAttributes) {+ out.push(finding({+ tag: 'PERF-FETCHXML-ALLATTR',+ severity: SEVERITY.HIGH,+ title: 'FetchXML retrieves all attributes',+ location: at,+ details:+ 'This FetchXML uses <all-attributes /> (or all-attributes="true"), so every ' ++ 'column on the table is returned. That inflates the payload, slows the query, ' ++ 'and can expose columns not meant for the portal audience.',+ fix:+ 'Replace <all-attributes /> with explicit <attribute name="..."/> entries listing ' ++ 'only the columns the page renders.',+ autoFixAvailable: false, // needs human knowledge of which columns are used+ }));+ } else if (!hasAttribute && !isAggregate) {+ out.push(finding({+ tag: 'PERF-FETCHXML-NO-COLUMNS',+ severity: SEVERITY.WARNING,+ title: 'FetchXML selects no explicit columns',+ location: at,+ details:+ 'The <entity> declares no <attribute> elements, so the platform returns a default ' ++ 'column set — more data than the page likely needs.',+ fix: 'Add explicit <attribute name="..."/> entries for only the columns you render.',+ autoFixAvailable: false,+ }));+ } else if (!isAggregate && attributeMatches.length > FETCHXML_MAX_ATTRIBUTES) {+ out.push(finding({+ tag: 'PERF-FETCHXML-MANY-COLUMNS',+ severity: SEVERITY.INFO,+ title: `FetchXML selects many columns (${attributeMatches.length})`,+ location: at,+ details:+ `This FetchXML explicitly selects ${attributeMatches.length} attributes (threshold ` ++ `${FETCHXML_MAX_ATTRIBUTES}). Wide projections increase payload size and query cost, ` ++ 'even when they avoid all-attributes.',+ fix:+ 'Review the page binding and remove attributes that are not rendered or needed for ' ++ 'client logic.',+ autoFixAvailable: false,+ }));+ }++ // Aggregate queries return a single summary row, so paging / count limits do+ // not apply — skip both the no-paging and large-count checks for them.+ if (!isAggregate) {+ if (!/\b(?:count|top)\s*=/i.test(openTag)) {+ out.push(finding({+ tag: 'PERF-FETCHXML-NO-PAGING',+ severity: SEVERITY.WARNING,+ title: 'FetchXML has no page size (count)',+ location: at,+ details:+ 'The <fetch> element sets no count/top, so it relies on the default page size and ' ++ 'has no explicit upper bound. Unbounded list queries are a common cause of slow ' ++ 'pages and portal timeouts on large tables.',+ fix:+ 'Add a count (e.g. count="10") and page via the page attribute + nextpagecookie, or ' ++ 'use aggregate="true" when you only need a count.',+ autoFixAvailable: false,+ }));+ } else if (countMatch && Number(countMatch[1]) > FETCHXML_MAX_COUNT) {+ out.push(finding({+ tag: 'PERF-FETCHXML-LARGE-COUNT',+ severity: SEVERITY.WARNING,+ title: `FetchXML page size is large (${countMatch[1]})`,+ location: at,+ details:+ `The <fetch> requests ${countMatch[1]} records in one page (threshold ` ++ `${FETCHXML_MAX_COUNT}). Large single-page fetches increase render time and risk ` ++ 'timeouts; prefer smaller pages with pagination.',+ fix: `Reduce count to ${FETCHXML_MAX_COUNT} or fewer and paginate.`,+ autoFixAvailable: false,+ }));+ }++ // returntotalrecordcount="true" makes the platform compute the total matching+ // row count (capped at 5000) alongside the page. That extra counting work is+ // only worth paying when the UI actually shows a total, and it adds measurable+ // overhead on large tables. Raw shape: <fetch returntotalrecordcount="true" ...>+ // See FetchXML paging: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/fetchxml/page-results+ if (/\breturntotalrecordcount\s*=\s*["']?true/i.test(openTag)) {+ out.push(finding({+ tag: 'PERF-FETCHXML-TOTALRECORDCOUNT',+ severity: SEVERITY.INFO,+ title: 'FetchXML requests a total record count',+ location: at,+ details:+ 'This <fetch> sets returntotalrecordcount="true", so the platform computes the total ' ++ 'matching row count (capped at 5000) in addition to returning the page. That counting ' ++ 'work is only worth paying when the page actually displays a total, and it adds ' ++ 'overhead on large tables.',+ fix:+ 'Remove returntotalrecordcount="true" unless the UI shows a total count; rely on paging ' ++ '(page + nextpagecookie) to load more records on demand.',+ autoFixAvailable: false,+ }));+ }+ }++ // Advanced FetchXML optimization switches are not universally beneficial.+ // Microsoft explicitly recommends using SQL query options only when support+ // advises it, and notes that incorrect hints can make a query slower. Surface+ // every use for review rather than assuming it is an optimization.+ // See: https://learn.microsoft.com/power-apps/developer/data-platform/fetchxml/optimize-performance#query-hints+ const queryHints = [];+ const optionsMatch = openTag.match(/\boptions\s*=\s*["']([^"']+)["']/i);+ if (optionsMatch) queryHints.push(`options="${optionsMatch[1]}"`);+ for (const [pattern, label] of [+ [/\blatematerialize\s*=\s*["']?true/i, 'latematerialize="true"'],+ [/\bno-lock\s*=\s*["']?true/i, 'no-lock="true"'],+ [/\buseraworderby\s*=\s*["']?true/i, 'useraworderby="true"'],+ ]) {+ if (pattern.test(openTag)) queryHints.push(label);+ }+ for (const hintMatch of block.matchAll(/<filter\b[^>]*\bhint\s*=\s*["']([^"']+)["'][^>]*>/gi)) {+ queryHints.push(`filter hint="${hintMatch[1]}"`);+ }+ if (queryHints.length > 0) {+ out.push(finding({+ tag: 'PERF-FETCHXML-QUERY-HINT',+ severity: SEVERITY.WARNING,+ title: 'FetchXML uses advanced query hints',+ location: at,+ details:+ `This query uses ${queryHints.join(', ')}. Query hints are workload-specific; ` ++ 'Microsoft recommends applying SQL query options only when technical support advises ' ++ 'them because an incorrect hint can reduce performance.',+ fix:+ 'Confirm the hint is documented for this exact slow query and supported by measured ' ++ 'before/after timings. Otherwise remove it and let Dataverse optimize the query.',+ autoFixAvailable: false,+ }));+ }++ // Power Pages caches Dataverse query results. A request-time value such as+ // `"now" | date` inside the FetchXML makes the query text change on every+ // request, which is a common cache-busting technique. Explicit cache=false+ // variants are included defensively even though they are not standard+ // FetchXML attributes.+ const explicitNoCache =+ /\b(?:cache|usecache|enablecache)\s*=\s*["']?(?:false|0|no)\b/i.test(openTag);+ const requestTimeValue =+ /\{\{[\s\S]{0,200}(?:(?:["']now["']|\bnow\b)\s*\|\s*date)\b[\s\S]{0,200}\}\}/i.test(block) ||+ /{%-?[\s\S]{0,200}(?:(?:["']now["']|\bnow\b)\s*\|\s*date)\b[\s\S]{0,200}-?%}/i.test(block);+ if (explicitNoCache || requestTimeValue) {+ out.push(finding({+ tag: 'PERF-FETCHXML-CACHE-BYPASS',+ severity: SEVERITY.WARNING,+ title: 'FetchXML appears to bypass server-side cache',+ location: at,+ details:+ 'This query contains an explicit no-cache setting or a request-time date value that ' ++ 'changes the FetchXML text on every request. That prevents cache reuse and increases ' ++ 'Dataverse load under traffic.',+ fix:+ 'Remove cache-busting values unless the page has a measured real-time freshness ' ++ 'requirement. Prefer normal Power Pages cache invalidation, the native Web API, or ' ++ 'Server Logic for intentionally fresh data.',+ autoFixAvailable: false,+ }));+ }++ // Leading-wildcard LIKE filters (`%term`) are non-sargable in Dataverse-backed+ // searches: the engine cannot seek by the beginning of the string, so large+ // tables can degrade into broad scans. Raw shape:+ // <condition attribute="name" operator="like" value="%contoso" />+ for (const conditionMatch of block.matchAll(/<condition\b[^>]*>/gi)) {+ const attrs = parseTagAttributes(conditionMatch[0]);+ const operator = String(attrs.operator || '').toLowerCase();+ const value = String(attrs.value || '').trim();+ if ((operator === 'like' || operator === 'not-like') && /^[%*]/.test(value)) {+ out.push(finding({+ tag: 'PERF-FETCHXML-LEADING-WILDCARD',+ severity: SEVERITY.WARNING,+ title: 'FetchXML uses a leading-wildcard string filter',+ location: `${relPath}:${lineOf(content, m.index + conditionMatch.index)}`,+ details:+ `This FetchXML condition uses operator="${operator}" with a value beginning with ` ++ `${JSON.stringify(value[0])}. Leading-wildcard searches cannot use a normal prefix ` ++ 'seek and can become expensive on large Dataverse tables.',+ fix:+ 'Prefer an exact/prefix filter, a constrained search experience, or a dedicated ' ++ 'Dataverse Search-backed feature when users need contains-style search.',+ autoFixAvailable: false,+ }));+ }+ }++ // Ordering by a linked entity's column often requires a wider join/sort than+ // ordering by the primary entity. Choice-column ordering cannot be identified+ // without metadata, but related-column ordering is visible in FetchXML.+ const relatedOrderOffsets = new Set();+ for (const linkMatch of block.matchAll(/<link-entity\b[\s\S]*?<\/link-entity>/gi)) {+ const orderInLink = linkMatch[0].match(/<order\b[^>]*>/i);+ if (orderInLink) {+ relatedOrderOffsets.add(linkMatch.index + orderInLink.index);+ }+ }+ for (const orderMatch of block.matchAll(/<order\b[^>]*>/gi)) {+ const attrs = parseTagAttributes(orderMatch[0]);+ const isRelatedOrder =+ attrs.entityname ||+ attrs.alias ||+ relatedOrderOffsets.has(orderMatch.index);+ if (!isRelatedOrder) continue;+ out.push(finding({+ tag: 'PERF-FETCHXML-ORDER-RELATED',+ severity: SEVERITY.INFO,+ title: 'FetchXML orders by a related table column',+ location: `${relPath}:${lineOf(content, m.index + orderMatch.index)}`,+ details:+ 'This FetchXML appears to sort on a linked/related table column. Related-column sorts ' ++ 'can force extra join and sort work compared with sorting on the base table.',+ fix:+ 'Verify the sort is required for the visible UI. If possible, sort on an indexed base ' ++ 'table column, precompute the display order, or page before applying expensive sorts.',+ autoFixAvailable: false,+ }));+ }+ }++ // N+1: a fetch that executes inside a Liquid {% for %} loop runs once per+ // iteration. Walk for-open / for-close / fetch-start tokens in document order and+ // flag any `<fetch` seen while for-depth > 0. Counting `<fetch` (not the wrapping+ // `{% fetchxml %}`) avoids double-counting the same query.+ const tokenRe = /({%-?\s*for\b)|({%-?\s*endfor\b)|(<fetch\b)/gi;+ let depth = 0;+ let t;+ while ((t = tokenRe.exec(content)) !== null) {+ if (t[1]) depth += 1;+ else if (t[2]) depth = Math.max(0, depth - 1);+ else if (t[3] && depth > 0) {+ out.push(finding({+ tag: 'PERF-FETCHXML-IN-LOOP',+ severity: SEVERITY.HIGH,+ title: 'FetchXML query runs inside a Liquid loop',+ location: `${relPath}:${lineOf(content, t.index)}`,+ details:+ 'A FetchXML query is placed inside a {% for %} loop, so it executes once per iteration ' ++ '(an N+1 query pattern). This multiplies database round-trips and is one of the biggest ' ++ 'Liquid performance pitfalls.',+ fix:+ 'Move the query outside the loop and fetch all rows at once (use <link-entity> to join ' ++ 'related data in a single query), then iterate over the in-memory results.',+ autoFixAvailable: false,+ }));+ }+ }++ return out;+}++// ── Power Pages list pagination ──────────────────────────────────────────────+// List exports use one `*.list.yml` record with fields such as:+// adx_entitylistid: <guid>+// adx_name: Active cases+// adx_pagesize: 10+// A missing, non-numeric, or non-positive page size leaves the list without an+// explicit pagination bound and can render a large result set at once.+function scanListContent(content, relPath) {+ const out = [];+ const pageSizeMatch = content.match(/^\s*(?:adx_)?pagesize\s*:\s*(.*?)\s*$/im);+ if (pageSizeMatch) {+ const pageSize = Number(String(pageSizeMatch[1]).replace(/^['"]|['"]$/g, '').trim());+ if (Number.isFinite(pageSize) && pageSize > 0) return out;+ }++ const nameMatch = content.match(/^\s*(?:adx_)?name\s*:\s*(.*?)\s*$/im);+ const idMatch = content.match(/^\s*(?:adx_)?entitylistid\s*:/im);+ const at = `${relPath}:${lineOf(content, pageSizeMatch?.index ?? idMatch?.index ?? 0)}`;+ const listName = nameMatch ? nameMatch[1].trim().replace(/^['"]|['"]$/g, '') : relPath;++ out.push(finding({+ tag: 'PERF-LIST-NO-PAGING',+ severity: SEVERITY.WARNING,+ title: 'Power Pages list has no valid page size',+ location: at,+ details:+ `${listName} does not define a positive pagesize/adx_pagesize value. Without an explicit ` ++ 'page size, a list can request and render too many records in one response.',+ fix:+ 'Set adx_pagesize/pagesize to a bounded value appropriate for the UI (commonly 10-50) ' ++ 'and keep the list paging controls enabled.',+ autoFixAvailable: false,+ }));+ return out;+}++// ── Web template/page used as a data API ────────────────────────────────────+// A legacy Power Pages pattern exposes a headerless webpage/web template that+// runs FetchXML and writes JSON/XML, then treats that route as a custom API.+// Detect only data-query templates whose rendered body is structured data and+// has no normal HTML shell; this keeps the heuristic conservative.+function scanWebpageApiContent(content, relPath) {+ if (!/\.(?:webtemplate\.source|webpage\.copy)\.(?:html?|liquid)$/i.test(relPath)) {+ return [];+ }++ const hasDataQuery =+ /{%-?\s*fetchxml\b/i.test(content) ||+ /\bentities\s*\[/i.test(content) ||+ /\bentityview\b/i.test(content);+ if (!hasDataQuery) return [];++ const responseBody = content+ .replace(/{%-?\s*fetchxml\b[\s\S]*?{%-?\s*endfetchxml\s*-?%}/gi, '')+ .replace(/{%-?\s*comment\s*-?%}[\s\S]*?{%-?\s*endcomment\s*-?%}/gi, '');+ const hasHtmlShell =+ /<(?:html|body|main|header|footer|section|article|div|table|form|ul|ol|nav)\b/i+ .test(responseBody);+ const withoutLiquid = responseBody+ .replace(/{%[\s\S]*?%}/g, '')+ .replace(/{{[\s\S]*?}}/g, '"value"')+ .trim();+ const hasStructuredMime = /\b(?:application|text)\/(?:json|xml)\b/i.test(content);+ const looksJson =+ /^[\[{]/.test(withoutLiquid) &&+ /["'][^"'\r\n]+["']\s*:/.test(withoutLiquid);+ const looksXml = /^<\?xml\b/i.test(withoutLiquid);++ if (hasHtmlShell || (!hasStructuredMime && !looksJson && !looksXml)) return [];++ const marker =+ content.search(/\b(?:application|text)\/(?:json|xml)\b/i) >= 0+ ? content.search(/\b(?:application|text)\/(?:json|xml)\b/i)+ : content.search(/{%-?\s*fetchxml\b|\bentities\s*\[|\bentityview\b/i);+ return [finding({+ tag: 'PERF-WEBPAGE-AS-API',+ severity: SEVERITY.WARNING,+ title: 'Webpage/web template appears to be used as a data API',+ location: `${relPath}:${lineOf(content, Math.max(0, marker))}`,+ details:+ 'This template queries Dataverse and emits JSON/XML without a normal HTML page shell. ' ++ 'Using a webpage route as a custom API adds Liquid rendering overhead and can scale poorly.',+ fix:+ 'Prefer the native Power Pages Web API for Dataverse CRUD, Server Logic for secure custom ' ++ 'endpoints, or a dedicated backend. If this endpoint must remain, add strict paging, ' ++ 'document its cache behavior, and verify table permissions.',+ autoFixAvailable: false,+ })];+}++// ── Web API rules ────────────────────────────────────────────────────────────+// Scans code for Power Pages Web API (`/_api/`) calls. Raw shapes handled:+// fetch("/_api/cr123_products?$select=*&$filter=statecode eq 0")+// fetch(`/_api/contacts?$filter=...&$orderby=createdon desc`) // no $top / no $select+// The webapi-integration agent enforces explicit projections and a page bound+// (`$top` for a total cap or `Prefer: odata.maxpagesize=N` for cursor paging), so+// these fire on hand-written calls that drifted from that convention.+function scanWebApiContent(content, relPath) {+ const out = [];+ if (!content.includes('/_api/')) return out;++ // Capture quoted/backticked string literals that contain `/_api/`. The+ // backreference \1 matches the same quote char that opened the string; `\\.`+ // consumes escaped chars so an escaped quote inside doesn't end the match early.+ const urlRe = /(['"`])((?:\\.|(?!\1)[\s\S])*?\/_api\/(?:\\.|(?!\1)[\s\S])*?)\1/g;+ let m;+ while ((m = urlRe.exec(content)) !== null) {+ const url = m[2];+ const decodedUrl = safeDecodeURIComponent(url);+ const at = `${relPath}:${lineOf(content, m.index)}`;+ const hasSelect = /[?&]\$select=/i.test(url);+ const selectStar = /[?&]\$select=\*/i.test(url);+ // Collection query heuristic: a bare entity-set path such as `/_api/contacts`+ // is already a multi-row read even when it has no query string. A record path+ // like `/_api/contacts(<id>)` is a single-row read and should not require $top.+ const apiPathMatch = decodedUrl.match(/\/_api\/([^?#'"`\s\\]+)/i);+ const firstPathSegment = apiPathMatch ? apiPathMatch[1].split('/')[0] : '';+ const isServicePath = firstPathSegment === '' || firstPathSegment.startsWith('$');+ const isSingleRecordPath = /\([^)]*\)/.test(firstPathSegment);+ const isCollectionQuery = Boolean(firstPathSegment) && !isServicePath && !isSingleRecordPath;+ const hasAnyOption = /[?&]\$(filter|orderby|expand|apply|select|top|count)=/i.test(url);+ const topMatch = url.match(/[?&]\$top=(\d+)/i);+ const hasTop = Boolean(topMatch);+ // Power Pages cursor pagination intentionally omits `$top`: the page size is+ // carried in the request's `Prefer: odata.maxpagesize=N` header and subsequent+ // pages follow `@odata.nextLink`. Inspect the enclosing request expression+ // rather than the URL alone so compliant list calls are not reported as+ // unbounded. The window is capped to avoid borrowing a header from a distant+ // unrelated request in the same source file.+ const requestStart = Math.max(+ 0,+ content.lastIndexOf(';', m.index) + 1,+ content.lastIndexOf('\n\n', m.index) + 2,+ );+ const nextSemicolon = content.indexOf(';', m.index + m[0].length);+ const requestEnd = Math.min(+ content.length,+ nextSemicolon >= 0 ? nextSemicolon + 1 : m.index + m[0].length + 1200,+ m.index + m[0].length + 1200,+ );+ const requestExpression = content.slice(requestStart, requestEnd);+ const hasMaxPageSize = /odata\.maxpagesize\s*=\s*(?:\d+|\$\{[^}]+\})/i.test(requestExpression);+ const expandMatch = url.match(/[?&]\$expand=([^&]+)/i);+ const selectMatch = url.match(/[?&]\$select=([^&]+)/i);+ const filterMatch = decodedUrl.match(/[?&]\$filter=([^&]+)/i);+ const orderByMatch = decodedUrl.match(/[?&]\$orderby=([^&]+)/i);++ if (selectStar) {+ out.push(finding({+ tag: 'PERF-WEBAPI-SELECT-STAR',+ severity: SEVERITY.HIGH,+ title: 'Web API request selects all columns ($select=*)',+ location: at,+ details:+ 'This /_api/ request uses $select=*, returning every column. Power Pages Web API best ' ++ 'practice is to list only the columns the UI binds, to shrink the payload and avoid ' ++ 'over-exposing data.',+ fix: 'Replace $select=* with an explicit $select=col1,col2,... list.',+ autoFixAvailable: false,+ }));+ } else if ((hasAnyOption || isCollectionQuery) && !hasSelect) {+ out.push(finding({+ tag: 'PERF-WEBAPI-NO-SELECT',+ severity: SEVERITY.WARNING,+ title: 'Web API request has no $select',+ location: at,+ details:+ 'This /_api/ request specifies query options but no $select, so every column is ' ++ 'returned by default — more data than the page needs.',+ fix: 'Add an explicit $select=col1,col2,... listing only the columns you render.',+ autoFixAvailable: false,+ }));+ }++ if (isCollectionQuery && !hasTop && !hasMaxPageSize) {+ out.push(finding({+ tag: 'PERF-WEBAPI-NO-TOP',+ severity: SEVERITY.WARNING,+ title: 'Web API collection query has no page bound',+ location: at,+ details:+ 'This /_api/ collection query has neither a $top safety cap nor a ' ++ 'Prefer: odata.maxpagesize=N cursor-page size. Large responses slow the page and can ' ++ 'hit throttling limits.',+ fix:+ 'For page-by-page navigation, send Prefer: odata.maxpagesize=<n> and follow ' ++ '@odata.nextLink. Use $top=<n> only when the total result set should be capped.',+ autoFixAvailable: false,+ }));+ }++ if (topMatch && Number(topMatch[1]) > WEBAPI_MAX_TOP) {+ out.push(finding({+ tag: 'PERF-WEBAPI-LARGE-TOP',+ severity: SEVERITY.WARNING,+ title: `Web API page size is large ($top=${topMatch[1]})`,+ location: at,+ details:+ `This /_api/ request asks for ${topMatch[1]} rows in one response (threshold ` ++ `${WEBAPI_MAX_TOP}). Large single-response payloads slow the page and increase ` ++ 'throttling risk under load.',+ fix:+ `Reduce $top to ${WEBAPI_MAX_TOP} or fewer, then page with @odata.nextLink or load ` ++ 'additional rows on demand.',+ autoFixAvailable: false,+ }));+ }++ if (selectMatch && !selectStar) {+ const columns = selectMatch[1]+ .split(',')+ .map((column) => column.trim())+ .filter(Boolean);+ if (columns.length > WEBAPI_MAX_SELECT_COLUMNS) {+ out.push(finding({+ tag: 'PERF-WEBAPI-MANY-COLUMNS',+ severity: SEVERITY.INFO,+ title: `Web API request selects many columns (${columns.length})`,+ location: at,+ details:+ `This /_api/ request selects ${columns.length} columns (threshold ` ++ `${WEBAPI_MAX_SELECT_COLUMNS}). Wide projections increase payload size and parsing ` ++ 'cost even when they avoid $select=*.',+ fix:+ 'Review the UI binding and remove columns that are not rendered or needed for client logic.',+ autoFixAvailable: false,+ }));+ }+ }++ if (/[?&]\$count=true\b/i.test(url)) {+ out.push(finding({+ tag: 'PERF-WEBAPI-COUNT',+ severity: SEVERITY.INFO,+ title: 'Web API request asks for a total count',+ location: at,+ details:+ 'This /_api/ request sets $count=true, so Dataverse computes the total matching row ' ++ 'count in addition to returning data. That work is only worth paying when the UI ' ++ 'actually displays a total.',+ fix:+ 'Remove $count=true unless the page renders a total count; use paging state or ' ++ '@odata.nextLink for load-more experiences.',+ autoFixAvailable: false,+ }));+ }++ if (expandMatch && !/\(\s*\$select\s*=/i.test(expandMatch[1])) {+ out.push(finding({+ tag: 'PERF-WEBAPI-EXPAND-NO-SELECT',+ severity: SEVERITY.WARNING,+ title: 'Web API $expand has no nested $select',+ location: at,+ details:+ 'This /_api/ request expands related records without a nested $select, so the related ' ++ 'payload can include more columns than the page needs.',+ fix:+ 'Add a nested projection such as $expand=relationship($select=col1,col2), or remove ' ++ '$expand and request only the related data the UI renders.',+ autoFixAvailable: false,+ }));+ }++ if (filterMatch && /\b(?:contains|endswith)\s*\(/i.test(filterMatch[1])) {+ out.push(finding({+ tag: 'PERF-WEBAPI-WILDCARD-FILTER',+ severity: SEVERITY.WARNING,+ title: 'Web API filter uses contains/endswith string search',+ location: at,+ details:+ 'This /_api/ request filters with contains(...) or endswith(...), which is similar to ' ++ 'a leading-wildcard search and can be expensive on large Dataverse tables.',+ fix:+ 'Prefer exact/prefix filters, constrain the search scope, or use a search feature built ' ++ 'for contains-style matching.',+ autoFixAvailable: false,+ }));+ }++ if (filterMatch && /\$\{[^}]*\b(?:Date|Date\.now|toISOString)\b[^}]*\}|\bnow\s*\(/i.test(filterMatch[1])) {+ out.push(finding({+ tag: 'PERF-WEBAPI-CACHE-BYPASS',+ severity: SEVERITY.WARNING,+ title: 'Web API filter appears to use request-time date values',+ location: at,+ details:+ 'This /_api/ request appears to build a filter with the current date/time. A changing ' ++ 'query string prevents cache reuse and increases Dataverse load under traffic.',+ fix:+ 'Avoid request-time date filters unless the page truly needs real-time freshness; use ' ++ 'coarser time buckets or normal cache invalidation where possible.',+ autoFixAvailable: false,+ }));+ }++ if (orderByMatch && /\//.test(orderByMatch[1])) {+ out.push(finding({+ tag: 'PERF-WEBAPI-ORDER-RELATED',+ severity: SEVERITY.INFO,+ title: 'Web API orders by a related table column',+ location: at,+ details:+ 'This /_api/ request appears to sort by a related table property. Related-column sorts ' ++ 'can require extra join and sort work compared with sorting on the base table.',+ fix:+ 'Verify the sort is required. Prefer sorting by an indexed base table column, or ' ++ 'precompute/simplify the display order for large result sets.',+ autoFixAvailable: false,+ }));+ }+ }++ // Conservative N+1: `items.map(async ...)` / `.forEach(async ...)` whose body+ // calls the Web API. Requiring the `async` callback keeps this high-signal —+ // a plain `.map` over already-fetched results is not matched.+ const loopRe = /\.(map|forEach|filter|reduce)\s*\(\s*async\b/gi;+ let l;+ while ((l = loopRe.exec(content)) !== null) {+ // Look ahead within the same statement region for a Web API call.+ const window = content.slice(l.index, l.index + 400);+ if (/\/_api\//.test(window)) {+ out.push(finding({+ tag: 'PERF-WEBAPI-IN-LOOP',+ severity: SEVERITY.INFO,+ title: 'Web API call inside an array iteration (possible N+1)',+ location: `${relPath}:${lineOf(content, l.index)}`,+ details:+ 'An async .map/.forEach callback appears to call the Web API, which issues one request ' ++ 'per element (an N+1 pattern). This can flood the server on larger arrays.',+ fix:+ 'Fetch the data in a single query (use $filter with an in-list or $expand), or batch the ' ++ 'requests, instead of one call per item.',+ autoFixAvailable: false,+ }));+ }+ }++ return out;+}++// ── Client-side script rules (blocking / anti-pattern JS) ────────────────────+// Scans standalone JS and inline <script> in HTML for patterns that block the main+// thread or hammer the Web API. Pure over a string so it unit-tests in isolation.+function scanClientScript(content, relPath) {+ const out = [];++ // Synchronous XMLHttpRequest: the 3rd argument to .open(method, url, async) being+ // `false` makes the request block the main thread until it returns. Deprecated and+ // a well-known jank source. Raw shapes handled:+ // xhr.open("GET", url, false)+ // req.open('POST', '/_api/x', false, user, pass)+ // The URL arg is matched as a single comma-free token, so a literal URL containing a+ // comma simply won't match (conservative — a miss, never a false positive).+ // See: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/open+ const syncXhrRe = /\.open\s*\(\s*(['"`])(?:GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\1\s*,\s*[^,;)]+,\s*false\b/gi;+ let x;+ while ((x = syncXhrRe.exec(content)) !== null) {+ out.push(finding({+ tag: 'PERF-SYNC-XHR',+ severity: SEVERITY.HIGH,+ title: 'Synchronous XMLHttpRequest blocks the main thread',+ location: `${relPath}:${lineOf(content, x.index)}`,+ details:+ 'This XMLHttpRequest.open(...) call passes async=false, so the browser freezes the UI ' ++ 'thread until the request completes. Synchronous XHR is deprecated and a common cause of ' ++ 'unresponsive pages, especially on slow connections.',+ fix:+ 'Make the request asynchronous (async=true) and handle the result in a callback/Promise, ' ++ 'or use fetch().',+ autoFixAvailable: false,+ }));+ }++ // jQuery synchronous AJAX: `async: false` inside a $.ajax(...) options object blocks+ // the UI thread the same way sync XHR does. Power Pages ships jQuery, so this pattern+ // is common in hand-written portal JS. Gate on an .ajax( call being present so a stray+ // `async: false` in an unrelated config object isn't flagged; \basync\b avoids matching+ // substrings like `isAsync: false`.+ if (/\.ajax\s*\(/.test(content)) {+ const syncAjaxRe = /(['"])?\basync\b\1?\s*:\s*false\b/gi;+ let a;+ while ((a = syncAjaxRe.exec(content)) !== null) {+ out.push(finding({+ tag: 'PERF-JQUERY-SYNC-AJAX',+ severity: SEVERITY.HIGH,+ title: 'Synchronous jQuery AJAX blocks the main thread',+ location: `${relPath}:${lineOf(content, a.index)}`,+ details:+ 'A jQuery AJAX call sets async: false, which freezes the UI thread until the request ' ++ 'returns. This is deprecated behavior and hurts responsiveness under load.',+ fix:+ 'Remove async: false and use the done()/fail() callbacks (or a Promise) to handle the ' ++ 'response asynchronously.',+ autoFixAvailable: false,+ }));+ }+ }++ // document.write() / document.writeln() forces a synchronous parse/reflow and, when+ // called after the initial parse, can wipe the document. Browsers penalize it and it+ // blocks rendering. See: https://web.dev/articles/no-document-write+ const docWriteRe = /\bdocument\s*\.\s*write(?:ln)?\s*\(/gi;+ let d;+ while ((d = docWriteRe.exec(content)) !== null) {+ out.push(finding({+ tag: 'PERF-DOCUMENT-WRITE',+ severity: SEVERITY.WARNING,+ title: 'document.write() blocks rendering',+ location: `${relPath}:${lineOf(content, d.index)}`,+ details:+ 'document.write() (or writeln) forces a synchronous parser pause and reflow, and used after ' ++ 'load it can blank the page. Browsers actively de-prioritize it.',+ fix:+ 'Build the markup with DOM APIs (createElement/append) or a template render instead of ' ++ 'document.write().',+ autoFixAvailable: false,+ }));+ }++ // Aggressive Web API polling: setInterval(..., <delay>) whose inline callback hits the+ // portals Web API (`/_api/`) with a delay below SHORT_POLL_INTERVAL_MS. Heuristic — only+ // the inline-callback case is caught (a named-function reference is left alone), so this+ // stays high-signal. Raw shape:+ // setInterval(() => { fetch("/_api/tasks?$select=..."); }, 3000)+ const intervalRe = /setInterval\s*\(/gi;+ let s;+ while ((s = intervalRe.exec(content)) !== null) {+ // A 400-char window comfortably spans a small inline callback + its delay arg.+ const win = content.slice(s.index, s.index + 400);+ if (!/\/_api\//.test(win)) continue;+ // The delay is setInterval's LAST argument. Take the last `, <digits>)` in the+ // window — an inner call like foo(a, 5) sorts before the outer setInterval delay.+ const delayMatches = [...win.matchAll(/,\s*(\d{1,7})\s*\)/g)];+ if (delayMatches.length === 0) continue;+ const delayMs = Number(delayMatches[delayMatches.length - 1][1]);+ if (delayMs > 0 && delayMs < SHORT_POLL_INTERVAL_MS) {+ out.push(finding({+ tag: 'PERF-SHORT-POLL',+ severity: SEVERITY.WARNING,+ title: `Frequent Web API polling (every ${delayMs} ms)`,+ location: `${relPath}:${lineOf(content, s.index)}`,+ details:+ `A setInterval loop appears to call the portals Web API roughly every ${delayMs} ms ` ++ `(threshold ${SHORT_POLL_INTERVAL_MS} ms). The Web API isn't built for high-frequency ` ++ 'programmatic polling — each call consumes licensed user capacity and adds Dataverse ' ++ 'load, so a tight loop can degrade the site and approach service limits.',+ fix:+ 'Increase the interval, poll only while the tab is visible, or switch to an on-demand ' ++ 'refresh instead of a fixed short poll.',+ autoFixAvailable: false,+ }));+ }+ }++ return out;+}++// ── Render-blocking <head> script rule ───────────────────────────────────────+// Flags external <script src=...> tags inside <head> that lack async/defer/module,+// which block HTML parsing until the script downloads and executes. Only declarative+// HTML pages have a controllable <head>; code sites inject their own bundle.+// See: https://web.dev/articles/render-blocking-resources+function scanHtmlHead(content, relPath) {+ const out = [];+ const headMatch = content.match(/<head\b[^>]*>([\s\S]*?)<\/head>/i);+ if (!headMatch) return out;+ const headInner = headMatch[1];+ // Absolute offset where the inner head content begins, so findings point at the real+ // line in the file (the script regex below runs over headInner, not the whole file).+ const headStart = headMatch.index + headMatch[0].indexOf(headInner);++ const scriptRe = /<script\b[^>]*\bsrc\s*=[^>]*>/gi;+ let m;+ while ((m = scriptRe.exec(headInner)) !== null) {+ const tag = m[0];+ // Parse attribute names and values so words inside `src` (for example+ // `/assets/async.js`) cannot masquerade as actual async/defer/type attributes.+ const attributes = new Map();+ const attributeRe = /\s([^\s=/>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g;+ let attributeMatch;+ while ((attributeMatch = attributeRe.exec(tag)) !== null) {+ attributes.set(+ attributeMatch[1].toLowerCase(),+ attributeMatch[2] ?? attributeMatch[3] ?? attributeMatch[4] ?? '',+ );+ }+ // async / defer make the download non-blocking; type="module" is deferred by spec.+ const nonBlocking =+ attributes.has('async') ||+ attributes.has('defer') ||+ String(attributes.get('type')).toLowerCase() === 'module';+ if (nonBlocking) continue;+ out.push(finding({+ tag: 'PERF-RENDER-BLOCKING-SCRIPT',+ severity: SEVERITY.WARNING,+ title: 'Render-blocking script in <head>',+ location: `${relPath}:${lineOf(content, headStart + m.index)}`,+ details:+ 'A <script src="..."> in <head> has neither async nor defer, so the browser must download ' ++ 'and execute it before it can continue parsing the page — delaying first paint.',+ fix:+ 'Add defer (preserves execution order) or async to the tag, use type="module", or move the ' ++ 'script to the end of <body>.',+ autoFixAvailable: false,+ }));+ }+ return out;+}++// ── Runtime CSS rule (render-blocking @import) ───────────────────────────────+// A runtime `@import` inside a served stylesheet is fetched only after the parent CSS+// parses, serializing stylesheet downloads and delaying render. Pre-processor sources+// (.scss/.less) are excluded upstream because their @import is resolved at build time.+// See: https://developer.mozilla.org/en-US/docs/Web/CSS/@import+function scanCssContent(content, relPath) {+ const out = [];+ // Blank out block comments while preserving length AND newlines (replace every+ // non-newline char with a space) so a commented-out @import isn't flagged but the+ // reported line numbers for real ones stay accurate.+ const masked = content.replace(/\/\*[\s\S]*?\*\//g, (c) => c.replace(/[^\n]/g, ' '));+ const importRe = /@import\b/gi;+ let m;+ while ((m = importRe.exec(masked)) !== null) {+ out.push(finding({+ tag: 'PERF-CSS-IMPORT',+ severity: SEVERITY.WARNING,+ title: 'CSS @import blocks parallel stylesheet download',+ location: `${relPath}:${lineOf(content, m.index)}`,+ details:+ 'This stylesheet uses @import, which the browser can only fetch after it has downloaded and ' ++ 'parsed the parent CSS. That serializes stylesheet loading and delays first render.',+ fix:+ 'Replace @import with a <link rel="stylesheet"> in the page head, or bundle the imported CSS ' ++ 'into one file at build time.',+ autoFixAvailable: false,+ }));+ }+ return out;+}++// ── Site-settings rules (output caching, sign-in tracking) ───────────────────+// settingsByName: Map<lowercaseName, { value, filePath, name, valueField? }>.+// siteSettingsSource is either a per-record directory, a non-SPA aggregate file,+// or null when the project has no local site-setting metadata.+function scanSiteSettings(settingsByName, siteSettingsSource, siteSettingsLayout = 'per-record') {+ const out = [];+ if (!siteSettingsSource) return out; // nothing to check without site-setting metadata++ const isTrue = (v) => v === true || String(v).trim().toLowerCase() === 'true';+ const settingFixAction = (rec, name, value) => {+ // Non-SPA PAC downloads can store every setting in one root-level sitesetting.yml.+ // The parser records the exact adx_value line, so set-yaml-field remains a+ // precise, single-record edit instead of replacing the first matching boolean.+ if (rec && rec.valueField === 'adx_value') {+ return {+ type: 'set-yaml-field',+ field: 'adx_value',+ value,+ recordName: name,+ };+ }+ return { type: 'set-site-setting', name, value, valueType: 'boolean' };+ };++ // Header/Footer output caching. On NEW sites these default to true; on UPGRADED+ // sites they default to false (disabled) when absent — hence: present-and-false+ // is a confident warning; absent is an info-level nudge. Enabling the site+ // setting ALONE is not sufficient — the Header/Footer/Languages-Dropdown web+ // templates must also use the {% substitution %} tag or parts stop rendering.+ // See: https://learn.microsoft.com/en-us/power-pages/configure/enable-header-footer-output-caching+ for (const [label, name] of [['Header', 'Header/OutputCache/Enabled'], ['Footer', 'Footer/OutputCache/Enabled']]) {+ const rec = settingsByName.get(name.toLowerCase());+ const tag = label === 'Header' ? 'PERF-HEADER-OUTPUTCACHE' : 'PERF-FOOTER-OUTPUTCACHE';+ const substitutionCaveat =+ ` Note: enabling this setting alone is not enough — update the ${label} (and Languages ` ++ 'Dropdown) web templates to use the {% substitution %} tag, or parts of the ' ++ `${label.toLowerCase()} will fail to render.`;++ if (rec && !isTrue(rec.value)) {+ out.push(finding({+ tag,+ severity: SEVERITY.WARNING,+ title: `${label} output caching is disabled`,+ location: rec.filePath,+ details:+ `${label} output caching is turned off (${name} = ${JSON.stringify(rec.value)}). The ` ++ `${label} web template is then parsed and rendered on every page load, which hurts ` ++ 'performance under load.',+ fix: `Set ${name} to true.` + substitutionCaveat,+ autoFixAvailable: true,+ fixAction: settingFixAction(rec, name, 'true'),+ }));+ } else if (!rec) {+ // create-site-setting.js writes the per-record `.powerpages-site` format.+ // It must not be used against a non-SPA aggregate sitesetting.yml because+ // that would create a second, incompatible metadata layout beside the site.+ const canAutoCreate = siteSettingsLayout !== 'non-spa';+ out.push(finding({+ tag,+ severity: SEVERITY.INFO,+ title: `${label} output caching is not explicitly enabled`,+ location: `${siteSettingsSource}`,+ details:+ `No ${name} site setting was found. New sites default this on, but upgraded sites ` ++ `default it off — parsing and rendering the ${label} on every page load.`,+ fix:+ (canAutoCreate+ ? `Create ${name} = true to guarantee caching.`+ : `Add ${name} with adx_value: true to the non-SPA sitesetting.yml export.`) ++ substitutionCaveat,+ autoFixAvailable: canAutoCreate,+ fixAction: canAutoCreate+ ? { type: 'create-site-setting', name, value: 'true', valueType: 'boolean' }+ : null,+ }));+ }+ }++ // Sign-in tracking writes a record on every login — Site Checker flags it as a+ // performance issue. See site-checker-performance "Sign-in tracking enabled".+ const signin = settingsByName.get('authentication/logintrackingenabled');+ if (signin && isTrue(signin.value)) {+ out.push(finding({+ tag: 'PERF-SIGNIN-TRACKING',+ severity: SEVERITY.WARNING,+ title: 'Sign-in tracking is enabled',+ location: signin.filePath,+ details:+ 'Authentication/LoginTrackingEnabled is true, so the platform writes a tracking record on ' ++ 'every sign-in. Under load this adds avoidable write pressure.',+ fix: 'Set Authentication/LoginTrackingEnabled to false (or delete the site setting).',+ autoFixAvailable: true,+ fixAction: settingFixAction(+ signin,+ 'Authentication/LoginTrackingEnabled',+ 'false',+ ),+ }));+ }++ return out;+}++// ── Count-based rules (web files, web roles) ─────────────────────────────────+function evaluateCounts({ webFileCount, webRoleCount }) {+ const out = [];+ if (webFileCount > WEB_FILE_WARN_THRESHOLD) {+ out.push(finding({+ tag: 'PERF-WEBFILE-COUNT',+ severity: SEVERITY.WARNING,+ title: `Large number of web files (${webFileCount})`,+ details:+ `The site has ${webFileCount} web files (threshold ${WEB_FILE_WARN_THRESHOLD}). A large ` ++ 'web-file table slows website startup.',+ fix:+ 'Move static content (CSS/JS/images) to Azure Blob Storage or a CDN, or reparent files off ' ++ 'the home page so they load on demand.',+ autoFixAvailable: false,+ }));+ }+ if (webRoleCount > WEB_ROLE_WARN_THRESHOLD) {+ out.push(finding({+ tag: 'PERF-WEBROLE-COUNT',+ severity: SEVERITY.WARNING,+ title: `Large number of web roles (${webRoleCount})`,+ details:+ `The site has ${webRoleCount} web roles (threshold ${WEB_ROLE_WARN_THRESHOLD}). Evaluating ` ++ 'many roles per request affects the performance of all pages.',+ fix: 'Consolidate overlapping web roles; keep the number of distinct permission combinations small.',+ autoFixAvailable: false,+ }));+ }+ return out;+}++// ── Large static asset rule ──────────────────────────────────────────────────+// assets: [{ relPath, size }]. Returns at most LARGE_ASSET_MAX_FINDINGS, largest first.+function scanLargeAssets(assets) {+ return assets+ .filter((a) => a.size > LARGE_ASSET_BYTES)+ .sort((a, b) => b.size - a.size)+ .slice(0, LARGE_ASSET_MAX_FINDINGS)+ .map((a) => finding({+ tag: 'PERF-LARGE-STATIC-ASSET',+ severity: SEVERITY.INFO,+ title: `Large static asset (${(a.size / (1024 * 1024)).toFixed(1)} MB)`,+ location: a.relPath,+ details:+ `${a.relPath} is ${(a.size / (1024 * 1024)).toFixed(1)} MB. Large unoptimized assets slow ` ++ 'first load, especially on mobile connections.',+ fix:+ 'Compress/resize the asset, serve modern formats (WebP/AVIF), or move it to a CDN and ' ++ 'reference it by URL.',+ autoFixAvailable: false,+ }));+}++// ── Directory walking ────────────────────────────────────────────────────────+// Recursively lists files under root. `skipBuild` also prunes compiled-output dirs.+function walkFiles(root, { skipBuild } = { skipBuild: true }) {+ const results = [];+ const stack = [root];+ while (stack.length) {+ const dir = stack.pop();+ let entries;+ try {+ entries = fs.readdirSync(dir, { withFileTypes: true });+ } catch {+ continue; // unreadable dir (permissions / race) — skip rather than crash+ }+ for (const ent of entries) {+ const abs = path.join(dir, ent.name);+ if (ent.isDirectory()) {+ if (ALWAYS_SKIP_DIRS.has(ent.name)) continue;+ if (skipBuild && BUILD_OUTPUT_DIRS.has(ent.name)) continue;+ stack.push(abs);+ } else if (ent.isFile()) {+ results.push(abs);+ }+ }+ }+ return results;+}++function readSafe(absPath) {+ try {+ return fs.readFileSync(absPath, 'utf8');+ } catch {+ return null; // binary/locked/oversized — the rule scans simply skip it+ }+}++// Parse the non-SPA PAC download list shape, where all records of one table are+// stored in a single root-level YAML file, for example:+// - adx_name: Header/OutputCache/Enabled+// adx_sitesettingid: <guid>+// adx_value: false+// A new record starts only at column zero (`- `), so indented block-scalar or+// nested-list lines remain part of their current record. Each record is then+// delegated to the shared parseSimpleYaml helper so scalar coercion and quoting+// stay consistent with the per-record `.powerpages-site` loader.+function parseNonSpaYamlRecordList(content, filePath) {+ const lines = content.split(/\r?\n/);+ const records = [];+ let current = null;++ const flush = () => {+ if (!current) return;++ const normalized = current.lines+ .map((line, index) => (index === 0 ? line.replace(/^-\s+/, '') : line))+ .join('\n');++ try {+ const parsed = parseSimpleYaml(normalized, filePath);+ const lineByKey = {};+ current.lines.forEach((rawLine, offset) => {+ const line = rawLine.trim().replace(/^-\s+/, '');+ const separatorIndex = line.indexOf(':');+ if (separatorIndex <= 0) return;+ const key = line.slice(0, separatorIndex).trim();+ if (!(key in lineByKey)) {+ lineByKey[key] = current.startLine + offset;+ }+ });+ records.push({ ...parsed, lineByKey });+ } catch {+ // One malformed exported record must not abort the full performance scan.+ // Valid neighboring records remain useful for settings and volume checks.+ }+ };++ lines.forEach((line, index) => {+ if (/^-\s+/.test(line)) {+ flush();+ current = { startLine: index + 1, lines: [line] };+ } else if (current) {+ current.lines.push(line);+ }+ });+ flush();++ return records;+}++// Load site settings into Map<lowercaseName, {value, filePath, name}> from either+// the per-record `.powerpages-site/site-settings/*.sitesetting.yml` layout or the+// non-SPA root-level `sitesetting.yml` list. `rel` prevents machine-specific+// absolute paths from leaking into the shared HTML report.+function loadSiteSettingsMap(projectRoot, rel) {+ const map = new Map();++ const dir = path.join(projectRoot, '.powerpages-site', 'site-settings');+ if (fs.existsSync(dir)) {+ const relDir = rel(dir);+ let records = [];+ try {+ records = loadSiteSettings(dir);+ } catch {+ // If the site-settings metadata can't be parsed, skip settings-based rules rather than+ // emitting "missing setting" findings that could drive unsafe auto-fixes.+ return { map, source: null, layout: null };+ }+ for (const r of records) {+ if (typeof r.name === 'string') {+ map.set(r.name.toLowerCase(), {+ value: r.value,+ filePath: rel(r.filePath),+ name: r.name,+ });+ }+ }+ return { map, source: relDir, layout: 'per-record' };+ }++ const nonSpaFile = path.join(projectRoot, 'sitesetting.yml');+ if (fs.existsSync(nonSpaFile)) {+ const relFile = rel(nonSpaFile);+ const content = readSafe(nonSpaFile);+ const records = content == null+ ? []+ : parseNonSpaYamlRecordList(content, nonSpaFile);++ for (const r of records) {+ if (typeof r.adx_name !== 'string') continue;+ const valueLine = r.lineByKey.adx_value || r.lineByKey.adx_name;+ map.set(r.adx_name.toLowerCase(), {+ value: r.adx_value,+ filePath: valueLine ? `${relFile}:${valueLine}` : relFile,+ name: r.adx_name,+ valueField: 'adx_value',+ });+ }+ return { map, source: relFile, layout: 'non-spa' };+ }++ return { map, source: null, layout: null };+}++// Count records across both supported non-SPA export layouts. Per-record+// metadata uses one descriptor file per record; aggregate downloads keep web-file+// descriptors in a root folder and web roles in one aggregate `webrole.yml`.+function countPortalRecords(+ projectRoot,+ { subDir, suffix, aggregateFile = null, aggregateIdField = null },+) {+ for (const dir of [+ path.join(projectRoot, '.powerpages-site', subDir),+ path.join(projectRoot, subDir),+ ]) {+ if (!fs.existsSync(dir)) continue;+ return walkFiles(dir, { skipBuild: false })+ .filter((f) => f.toLowerCase().endsWith(suffix))+ .length;+ }++ if (!aggregateFile || !aggregateIdField) return 0;+ const filePath = path.join(projectRoot, aggregateFile);+ const content = readSafe(filePath);+ if (content == null) return 0;+ return parseNonSpaYamlRecordList(content, filePath)+ .filter((record) => record[aggregateIdField] != null)+ .length;+}++function analyze(projectRoot) {+ const root = path.resolve(projectRoot || process.cwd());+ const findings = [];++ // powerpages.config.json is the authoritative local marker for a Power Pages+ // code/SPA site. The current rules target Liquid/portal metadata and would give+ // incomplete guidance for a SPA, so fail explicitly instead of returning a+ // success-shaped partial scan.+ if (fs.existsSync(path.join(root, 'powerpages.config.json'))) {+ throw new Error(+ 'This performance analyzer currently supports non-SPA Power Pages websites only. ' ++ `The selected path is a SPA website because it contains powerpages.config.json: ${root}`,+ );+ }++ // Single directory walk for content scans (source only), reused for FetchXML,+ // Web API, and deprecated-tracking checks.+ const contentFiles = walkFiles(root, { skipBuild: true });+ const rel = (abs) => path.relative(root, abs).split(path.sep).join('/');++ let fetchxmlFilesScanned = 0;+ let webapiFilesScanned = 0;+ let cssFilesScanned = 0;+ let listFilesScanned = 0;++ for (const abs of contentFiles) {+ const ext = path.extname(abs).toLowerCase();+ const base = path.basename(abs).toLowerCase();+ const wantsFetch = FETCHXML_EXTS.has(ext);+ const wantsWebapi = WEBAPI_EXTS.has(ext);+ const wantsStyle = STYLE_EXTS.has(ext);+ const wantsHtml = HTML_EXTS.has(ext);+ const wantsList = /\.list\.ya?ml$/i.test(base) || base === 'list.yml' || base === 'list.yaml';+ if (!wantsFetch && !wantsWebapi && !wantsStyle && !wantsList) continue;++ const content = readSafe(abs);+ if (content == null) continue;+ const relPath = rel(abs);+ const wantsWebpageApi =+ /\.(?:webtemplate\.source|webpage\.copy)\.(?:html?|liquid)$/i.test(relPath);++ if (wantsFetch) {+ fetchxmlFilesScanned += 1;+ for (const f of scanFetchXmlContent(content, relPath)) findings.push(f);+ }+ if (wantsList) {+ listFilesScanned += 1;+ for (const f of scanListContent(content, relPath)) findings.push(f);+ }+ if (wantsWebapi) {+ webapiFilesScanned += 1;+ for (const f of scanWebApiContent(content, relPath)) findings.push(f);+ // Same JS/HTML population also gets the blocking-script scan (sync XHR,+ // document.write, jQuery sync ajax, short-interval Web API polling).+ for (const f of scanClientScript(content, relPath)) findings.push(f);+ }+ if (wantsHtml) {+ // Render-blocking <head> scripts — declarative HTML pages only. Keep this+ // outside the broader Web API/client-script scan so JSX/template literals+ // that happen to contain a `<head>` snippet are not treated as served HTML.+ for (const f of scanHtmlHead(content, relPath)) findings.push(f);+ }+ if (wantsWebpageApi) {+ // Headerless JSON/XML templates backed by FetchXML or entity/list data are+ // a legacy custom-API pattern. Keep this separate from the native `/_api/`+ // rules and from the HTML-only <head> scan so `.liquid` templates are+ // checked without treating them as served HTML documents.+ for (const f of scanWebpageApiContent(content, relPath)) findings.push(f);+ }+ if (wantsStyle) {+ cssFilesScanned += 1;+ for (const f of scanCssContent(content, relPath)) findings.push(f);+ }++ // Deprecated page/file tracking (retired on 9.3.4.x+ but still a Site Checker+ // finding). Raw YAML shape: `adx_enabletracking: true` (or `enabletracking: true`).+ if ((ext === '.yml' || ext === '.yaml') && /(?:adx_)?enabletracking\s*:\s*(?:true|"true"|'true')/i.test(content)) {+ const isWebFile = base.includes('webfile') || relPath.includes('/web-files/');+ const isWebPage = base.includes('webpage') || relPath.includes('/web-pages/');+ if (isWebFile || isWebPage) {+ const which = isWebFile ? 'web file' : 'web page';+ const trackingKind = isWebFile ? 'file' : 'page';+ const tag = isWebFile ? 'PERF-WEBFILE-TRACKING' : 'PERF-WEBPAGE-TRACKING';+ const trackMatch = content.match(/((?:adx_)?enabletracking)\s*:/i);+ const trackingField = trackMatch ? trackMatch[1] : 'adx_enabletracking';+ findings.push(finding({+ tag,+ severity: SEVERITY.INFO,+ title: `Deprecated ${trackingKind} tracking enabled on a ${which}`,+ location: `${relPath}:${trackMatch ? lineOf(content, trackMatch.index) : 1}`,+ details:+ `This ${which} has Enable Tracking (deprecated) turned on, which Site Checker flags as ` ++ 'a performance risk. The feature is retired on portal versions 9.3.4.x and later.',+ fix: `Set ${trackingField} to false on this ${which}.`,+ autoFixAvailable: true,+ fixAction: { type: 'set-yaml-field', field: trackingField, value: 'false' },+ }));+ }+ }+ }++ // Site settings (output caching, sign-in tracking).+ const {+ map: settingsMap,+ source: settingsSource,+ layout: settingsLayout,+ } = loadSiteSettingsMap(root, rel);+ for (const f of scanSiteSettings(settingsMap, settingsSource, settingsLayout)) findings.push(f);++ // Count-based rules.+ const webFileCount = countPortalRecords(root, {+ subDir: 'web-files',+ suffix: '.webfile.yml',+ });+ const webRoleCount = countPortalRecords(root, {+ subDir: 'web-roles',+ suffix: '.webrole.yml',+ aggregateFile: 'webrole.yml',+ aggregateIdField: 'adx_webroleid',+ });+ for (const f of evaluateCounts({ webFileCount, webRoleCount })) findings.push(f);++ // Large static assets (scan source dirs only; compiled copies are not actionable).+ const assets = [];+ for (const abs of contentFiles) {+ if (!ASSET_EXTS.has(path.extname(abs).toLowerCase())) continue;+ let size = 0;+ try { size = fs.statSync(abs).size; } catch { continue; }+ if (size > LARGE_ASSET_BYTES) assets.push({ relPath: rel(abs), size });+ }+ for (const f of scanLargeAssets(assets)) findings.push(f);++ if (findings.length === 0) {+ findings.push({+ tag: 'PERF-NONE',+ severity: SEVERITY.INFO,+ title: 'No performance anti-patterns detected',+ location: null,+ details: 'The analyzer found no known Power Pages performance anti-patterns in the scanned files.',+ fix: null,+ autoFixAvailable: false,+ fixSkill: null,+ fixAction: null,+ });+ }++ // Assign stable sequential ids AFTER all rules and the clean-scan sentinel run,+ // so counts and coverage describe the same final finding collection.+ findings.forEach((f, i) => { f.id = `perf-${i + 1}`; });++ const severityCounts = findings.reduce((acc, f) => {+ acc[f.severity] = (acc[f.severity] || 0) + 1;+ return acc;+ }, {});++ const details = {+ kind: 'kv',+ label: 'Scan coverage',+ entries: [+ { key: 'FetchXML/Liquid files scanned', value: String(fetchxmlFilesScanned) },+ { key: 'Power Pages list files scanned', value: String(listFilesScanned) },+ { key: 'Web API / script files scanned', value: String(webapiFilesScanned) },+ { key: 'CSS files scanned', value: String(cssFilesScanned) },+ { key: 'Web files', value: String(webFileCount) },+ { key: 'Web roles', value: String(webRoleCount) },+ { key: 'Total findings', value: String(findings.length) },+ ],+ };++ return { status: 'ok', findings, details, severityCounts };+}++function main() {+ const projectRoot = getArg('projectRoot', process.cwd());+ let result;+ try {+ result = analyze(projectRoot);+ } catch (err) {+ process.stderr.write(`analyze-performance.js failed: ${err.message}\n`);+ process.exit(1);+ }+ process.stdout.write(JSON.stringify(result) + '\n');+}++// CLI guard so the pure functions can be required from tests without executing main.+if (require.main === module) {+ main();+}++module.exports = {+ analyze,+ scanFetchXmlContent,+ scanListContent,+ scanWebpageApiContent,+ scanWebApiContent,+ scanClientScript,+ scanHtmlHead,+ scanCssContent,+ scanSiteSettings,+ evaluateCounts,+ scanLargeAssets,+ // thresholds exported so tests assert against the real constants, not copies.+ FETCHXML_MAX_COUNT,+ FETCHXML_MAX_ATTRIBUTES,+ WEB_FILE_WARN_THRESHOLD,+ WEB_ROLE_WARN_THRESHOLD,+ LARGE_ASSET_BYTES,+ SHORT_POLL_INTERVAL_MS,+ WEBAPI_MAX_TOP,+ WEBAPI_MAX_SELECT_COLUMNS,+};diff --git a/plugins/power-pages/skills/analyze-performance/scripts/validate-analyze-performance.js b/plugins/power-pages/skills/analyze-performance/scripts/validate-analyze-performance.jsnew file mode 100644index 000000000..09ed94a3b--- /dev/null+++ b/plugins/power-pages/skills/analyze-performance/scripts/validate-analyze-performance.js@@ -0,0 +1,64 @@+#!/usr/bin/env node++// Validates one explicitly named analyze-performance HTML report.+//+// The generic Skill PostToolUse hook fires when the skill instructions are loaded,+// before this workflow renders a report. It therefore invokes this script without+// `--reportPath`, which must approve instead of inspecting historical files. Phase+// 6.3 calls this script explicitly with the report it just rendered; only that path+// is validated, so an old malformed/good report cannot affect the current run.++const fs = require('fs');+const path = require('path');+const { approve, block, runValidation } = require('../../../scripts/lib/validation-helpers');++// render-template.js leaves __KEY__ tokens verbatim when a required value was not+// supplied, so their presence in the output is a definitive render failure.+// See scripts/lib/render-template.js (placeholder = `__${key}__`).+const UNREPLACED_PLACEHOLDER = /__[A-Z][A-Z0-9_]+__/;+// Guard against a truncated/empty write masquerading as a real report.+const MIN_REPORT_BYTES = 500;++function getArg(name) {+ const flag = `--${name}`;+ const index = process.argv.indexOf(flag);+ return index >= 0 ? process.argv[index + 1] : null;+}++function validateReport(reportPath) {+ const resolved = path.resolve(reportPath);+ if (!fs.existsSync(resolved)) {+ return `Performance report was not created at ${resolved}. Re-run /power-pages:analyze-performance.`;+ }++ let content = '';+ try {+ content = fs.readFileSync(resolved, 'utf8');+ } catch (error) {+ return `Performance report could not be read at ${resolved}: ${error.message}`;+ }++ const reportBytes = Buffer.byteLength(content, 'utf8');+ if (reportBytes < MIN_REPORT_BYTES) {+ return `Performance report ${path.basename(resolved)} is suspiciously small (${reportBytes} bytes) — the render likely failed. Re-run /power-pages:analyze-performance.`;+ }+ if (UNREPLACED_PLACEHOLDER.test(content)) {+ return `Performance report ${path.basename(resolved)} has unreplaced template placeholders — the report data was not populated. Re-run the render step in /power-pages:analyze-performance.`;+ }++ return null;+}++const reportPath = getArg('reportPath');+if (reportPath) {+ const error = validateReport(reportPath);+ if (error) block(error);+ approve();+} else {+ // Hook mode: no report exists for the current invocation yet. Never inspect an+ // older report because that could block a prerequisite/review-mode run or mask+ // a missing current render.+ runValidation(() => approve());+}++module.exports = { validateReport };