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 SPA template flow to create-site (#329)
Priyanshu Agrawal4dac4f401f7b
diff --git a/plugins/power-pages/.claude-plugin/plugin.json b/plugins/power-pages/.claude-plugin/plugin.jsonindex 657bd9fb9..89a3893b1 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.6.6",+ "version": "2.7.0","description": "Create and deploy Power Pages sites using modern development approaches. Supports code sites (SPAs) with React, Angular, Vue, or Astro. 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 657bd9fb9..89a3893b1 100644--- a/plugins/power-pages/.plugin/plugin.json+++ b/plugins/power-pages/.plugin/plugin.json@@ -1,6 +1,6 @@{"name": "power-pages",- "version": "2.6.6",+ "version": "2.7.0","description": "Create and deploy Power Pages sites using modern development approaches. Supports code sites (SPAs) with React, Angular, Vue, or Astro. 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 43aa61232..6c8f61dab 100644--- a/plugins/power-pages/AGENTS.md+++ b/plugins/power-pages/AGENTS.md@@ -17,7 +17,7 @@ Read `PLUGIN_DEVELOPMENT_GUIDE.md` for UX and reliability standards when creatin- **Dataverse-backed validation** must stay opt-in for local runs only. Do not require live Dataverse connectivity in CI workflows or default test runs; gate it behind explicit local flags such as `--validate-dataverse-relationships`.- **Azure CLI `--allow-no-subscriptions`** — this flag is only valid on `az login`. Other `az` subcommands (`az account get-access-token`, `az account show`, etc.) reject it as an unrecognized argument and exit 2, so do NOT add it to anything other than `az login`. When the user is not logged in to the Azure CLI, suggest plain `az login` first; only suggest `az login --allow-no-subscriptions` as a fallback if they don't have any associated Azure subscription, since that variant lets subscription-less accounts sign in and still mint AAD-scoped Dataverse/Power Platform tokens via subsequent `az account get-access-token` calls. Reuse the shared `getAuthToken` helper in `scripts/lib/validation-helpers.js` instead of shelling out to `az` directly.- **Reference docs** shared across skills live in `references/` — reference via `${PLUGIN_ROOT}/references/` paths, don't duplicate.-- **Templates** use `__PLACEHOLDER__` tokens (e.g., `__SITE_NAME__`) replaced during scaffolding. The `gitignore` file is stored without the dot prefix and renamed to `.gitignore` during scaffolding.+- **Local scaffold templates** use `__PLACEHOLDER__` tokens (e.g., `__SITE_NAME__`) replaced during from-scratch scaffolding. The `gitignore` file is stored without the dot prefix and renamed to `.gitignore` during scaffolding.- **Hooks** are defined centrally in `hooks/hooks.json`, using `PostToolUse` with matcher `Skill` so validation runs when a tracked Power Pages skill completes.- **ALM split-decision thresholds** are intentionally tighter than the platform hard caps. `scripts/lib/alm-thresholds.js` recommends a split at 75 MB / 4000 components (vs platform caps of 95 MB / 6000), reserving ~20 MB / ~2000-component growth headroom in each split child. Override per-project via `.alm-config.json` if you have a justified reason to push closer to the caps.- **OAuth credential-style site settings** (ConsumerKey / ClientId / ClientSecret / etc.) are NOT excluded from solutions. `setup-solution` Phase 5 prompts per credential to choose between (a) Secret-typed env var (Key Vault per stage), (b) String-typed env var (plain text per stage), or (c) skip. The site-setting record is added to the solution and routed to an env var so secret values never ship in the solution zip. Plans generated before 2026-05-08 use the older `excluded` bucket — setup-solution's preloadedSettings handler treats those as `credentialNeedsDecision` for backward compatibility.@@ -190,7 +190,7 @@ Shared utility scripts live at `scripts/` and are referenced by multiple skills- `generate-uuid.js`: Generates a random UUID v4. Self-contained, no dependencies. Used by `create-webroles` and the main agent when creating table permission / site setting files from the `webapi-permissions` agent plan.- `update-skill-tracking.js`: Updates skill usage tracking site settings. Takes `--projectRoot`, `--skillName`, and `--authoringTool` args. The agent passes its own name as `--authoringTool` (e.g., `ClaudeCode`, `GitHubCopilot`). Creates/increments a per-skill counter (`Site-AI-<SkillName>.sitesetting.yml`) and records the authoring tool (`Site-AI-AuthoringTool.sitesetting.yml`). Exits silently if `.powerpages-site/site-settings/` does not exist. Used by every user-invocable skill (each skill calls it in its final phase per the skill-tracking convention).- `check-activation-status.js`: Checks whether a Power Pages site is already activated (provisioned) in the environment. Takes `--projectRoot` arg. **Site-identity resolution (`resolveSiteIdentity()`, exported + injectable for tests): (1) `powerpages.config.json` (code/SPA sites) → `siteName` + optional `websiteRecordId`; (2) else `.powerpages-site/website.yml` (declarative/data-model sites) → `name`→`siteName`, `id`→`websiteRecordId`; (3) `pac pages list` ONLY when the GUID is still unknown** — declarative sites (and code sites whose config included the GUID) skip the `pac pages list` exec entirely. Then queries the Power Platform GET websites API and matches by both `websiteRecordId` and `name`. Outputs JSON: `{ activated: true/false, siteName, websiteRecordId, websiteUrl }` or `{ error }`. The CLI flow is guarded by `require.main === module`; `module.exports = { resolveSiteIdentity, getWebsites }`. Used by `deploy-site` and `activate-site`.-- `poll-async-operation.js`: Polls a Dataverse `asyncoperations` record until it reaches a terminal state (Succeeded/Failed/Canceled) or times out. Args: `--asyncJobId`, `--envUrl`, `--token` (optional, refreshed via Azure CLI if omitted), `--intervalMs` (default 5000), `--maxAttempts` (default 60). Outputs JSON status. Used by `export-solution` and `import-solution`.+- `poll-async-operation.js`: Polls a Dataverse `asyncoperations` record until it reaches a terminal state (Succeeded/Failed/Canceled) or times out. Args: `--asyncJobId`, `--envUrl`, `--intervalMs` (default 5000), `--maxAttempts` (default 60). It acquires Azure CLI tokens internally so credentials never appear in process arguments. Outputs JSON status. Used by `export-solution` and `import-solution`.- `encode-solution-file.js`: Base64-encodes a solution zip file for use in Dataverse OData request bodies (`ImportSolutionAsync`, `StageSolution`). Args: `--zipPath`. Outputs `{ encoded, fileSizeBytes, fileName }`. Used by `import-solution`.- `parse-deployment-errors.js`: Parses PAC CLI stderr output or OData error JSON into structured findings array. Each finding has `{ patternId, type, severity, message, rawMatch, autoFixAvailable, suggestedFix }`. Reads from `--input`, `--file`, or stdin. Used by `diagnose-deployment`.@@ -277,7 +277,10 @@ Playwright MCP server for browser automation and live site previews during devel## Template System-Framework templates use `__PLACEHOLDER__` tokens (e.g., `__SITE_NAME__`, `__PRIMARY_COLOR__`, `__BG_COLOR__`) that get replaced during site scaffolding. The `gitignore` file is stored without the dot prefix to avoid git interference in the plugin repo — it gets renamed to `.gitignore` during scaffolding.+There are two template systems:++- **Local scaffold templates** live under `skills/create-site/assets/{react,vue,angular,astro}/`. These use `__PLACEHOLDER__` tokens (e.g., `__SITE_NAME__`, `__PRIMARY_COLOR__`, `__BG_COLOR__`) that get replaced during from-scratch site scaffolding. The `gitignore` file is stored without the dot prefix to avoid git interference in the plugin repo — it gets renamed to `.gitignore` during scaffolding.+- **Installable SPA templates** live outside this repo in `microsoft/power-pages-samples` under the `templates/` tree. `create-site` reads the central manifest, previews template cards, downloads artifacts from a pinned GitHub SHA, imports the selected template's **unmanaged** solution, applies optional seed data, activates the site, and opens the live URL. These are not `__PLACEHOLDER__` scaffolds; they are curated solution-backed starters.## Validation Scriptsdiff --git a/plugins/power-pages/PLUGIN_DEVELOPMENT_GUIDE.md b/plugins/power-pages/PLUGIN_DEVELOPMENT_GUIDE.mdindex b30954bd7..c694ae9e4 100644--- a/plugins/power-pages/PLUGIN_DEVELOPMENT_GUIDE.md+++ b/plugins/power-pages/PLUGIN_DEVELOPMENT_GUIDE.md@@ -52,11 +52,11 @@ When a skill deploys a site or audits permissions across many tables, the termin### The Solution-Every skill must implement **task-based progress tracking** using `TaskCreate` and `TaskUpdate`. Tasks are created upfront at Phase 1, one per phase, and marked `in_progress` / `completed` as the skill progresses.+Every skill must implement **task-based progress tracking** using `TaskCreate` and `TaskUpdate`. Tasks are created upfront at Phase 1, one per phase, and marked `in_progress` / `completed` as the skill progresses. For a skill with mutually exclusive branches, create the path-agnostic tasks upfront, then append the branch-specific phase tasks immediately after the branch is selected so the user never sees permanently skipped work.### Implementation Pattern-Every skill creates all phase tasks at the start:+Default pattern: every linear skill creates all phase tasks at the start:```Phase 1: TaskCreate → subject: "Verify prerequisites", activeForm: "Verifying prerequisites"@@ -72,7 +72,7 @@ Each task has three fields:- `activeForm` — Present continuous (shown in the spinner)- `description` — Brief explanation of the phase-For skills that process multiple entities (e.g., audit-permissions auditing many tables), create **per-entity sub-tasks** dynamically within the relevant phase.+For skills that process multiple entities (e.g., audit-permissions auditing many tables), create **per-entity sub-tasks** dynamically within the relevant phase. For skills that choose between mutually exclusive paths (for example, a template-backed path vs. a from-scratch path), create the common discovery/selection tasks first and append only the selected path's phases after the routing decision.### What This Means in Practice@@ -83,7 +83,7 @@ For skills that process multiple entities (e.g., audit-permissions auditing many| `/audit-permissions` | 7 phases (prereqs → discover → analyze → audit → cross-check → report → present) | Per-table tasks in Phase 4 (checklist A-K) || `/create-site` | 8 phases (prereqs → gather → plan → scaffold → implement → validate → deploy → summarize) | None |-> **Acceptance criterion:** Every skill must create all phase tasks upfront at Phase 1 start. Each task must have `subject`, `activeForm`, and `description`. Tasks must be marked `in_progress` when starting and `completed` when done.+> **Acceptance criterion:** Every linear skill must create all phase tasks upfront at Phase 1 start. A branching skill must create all path-agnostic tasks upfront and append the selected branch's tasks as soon as the branch is known. Each task must have `subject`, `activeForm`, and `description`. Tasks must be marked `in_progress` when starting and `completed` when done.---diff --git a/plugins/power-pages/README.md b/plugins/power-pages/README.mdindex 1ecfa2a0d..6baaee87f 100644--- a/plugins/power-pages/README.md+++ b/plugins/power-pages/README.md@@ -45,9 +45,12 @@ The plugin provides 34 skills that cover the full lifecycle of a Power Pages sit#### `/create-site`> "Create a Power Pages site with React for a job board"+>+> "Create a site from a Power Pages SPA template"-Scaffolds a complete code site from a framework template, applies your design direction (fonts, colors, layout), builds out pages and components, and provides a live preview in the browser throughout development.+Starts a complete code site either from a curated SPA template or from a fresh framework scaffold. The template path previews installable templates, imports the selected unmanaged solution into your environment, applies optional seed data, activates the site, and opens the live URL. The from-scratch path applies your design direction (fonts, colors, layout), builds out pages and components, and provides a live preview throughout development.+- Start from a curated SPA template or scaffold from scratch- Choose from React, Vue, Angular, or Astro- Real images from Unsplash (no placeholders)- Live browser preview during development@@ -466,7 +469,7 @@ The plugin host must provide an absolute `PLUGIN_ROOT` (GitHub Copilot) or `CLAUA common end-to-end workflow looks like this:```-1. /create-site → Scaffold + design + build pages+1. /create-site → Start from a SPA template or scaffold + design + build pages2. /deploy-site → Upload to Power Pages environment3. /activate-site → Provision a public URL4. /setup-datamodel → Create Dataverse tablesdiff --git a/plugins/power-pages/references/approval-gates.md b/plugins/power-pages/references/approval-gates.mdindex 91e721fc3..aaad5a3aa 100644--- a/plugins/power-pages/references/approval-gates.md+++ b/plugins/power-pages/references/approval-gates.md@@ -468,16 +468,33 @@ When **removing** a gate, also remove its catalog row in the same PR.----### 6.13 `create-site` (5 calls)--| ID | Kind | Category | Phase | Trigger / question | Cancel leaves |-|---|---|---|---|---|---|-| `create-site:1.purpose` | gate | plan | 1 | Site purpose unclear — multi-question prompt (site name, framework, purpose, audience, location) | nothing |+### 6.13 `create-site` (20 calls: 14 gates + 6 not-a-gates)++| ID | Kind | Category | Phase | Trigger / question | Cancel leaves |+|---|---|---|---|---|---|+| `create-site:1.purpose` | gate | plan | 1 | Site name, purpose, or audience unclear — path-agnostic discovery prompt | nothing |+| `create-site:1.5.creation-path` | not-a-gate | - | 1.5 | Route preference before catalog fetch; no project directory, Dataverse write, or durable skill state exists | - |+| `create-site:1.5.template-choice` | not-a-gate | — | 1.5 | Read-only route selection after template preview; only disposable temp preview files exist, with no project directory, Dataverse write, or durable skill state | — |+| `create-site:1.5.from-scratch-setup` | not-a-gate | — | 1.5 | Deferred framework and directory data-gathering before any scaffold files are written | — |+| `create-site:1.5.confirm-environment` | gate | consent | 1.5 | Target environment resolved from PAC/Azure auth — confirm before any environment preflight or import mutation | template-cache |+| `create-site:1.5.unblock-js` | gate | consent | 1.5 | Target environment blocks `.js` in `blockedattachments` — remove only `js` before uploading website code | attachment-block-modified |+| `create-site:1.5.language-requirement` | not-a-gate | - | 1.5 | Route selection after blocking template-declared Dataverse language preflight; no override option exists and no org mutation has happened | - |+| `create-site:1.5.template-import` | gate | consent | 1.5 | Discovered solutions and website code downloaded and target env resolved — confirm importing required supporting artifacts and creating the code site | template-cache |+| `create-site:1.5.update-installed` | gate | consent | 1.5 | One discovered solution is installed but the downloaded source is newer — confirm unmanaged update import; fires per matching solution iteration | template-cache |+| `create-site:1.5.clone-existing` | gate | consent | 1.5 | Every supporting solution is same/newer — confirm skipping all imports and creating a new site from website code | template-cache |+| `create-site:1.5.pack-failed` | gate | progress | 1.5 | Local validation or `pac solution pack` failed for one discovered solution before its Dataverse import attempt — retry, fall back, or stop; fires per failed solution iteration | template-cache |+| `create-site:1.5.template-clone-location` | not-a-gate | — | 1.5 | Local destination selection before cloning the template; no directory or environment state changes until the later provisioning step | — |+| `create-site:1.5.customize-template` | not-a-gate | — | 1.5 | Optional post-live choice to continue editing the local clone used to create the site | — |+| `create-site:1.5.clone-failed` | gate | progress | 1.5 | Packaged SPA clone, identity inspection, dependency installation, build/output validation, or code-site upload failed - choose retry, from-scratch fallback, or stop | partial-template-clone |+| `create-site:1.5.reinstall-unknown` | gate | consent | 1.5 | Installed-state detection failed for one discovered solution — confirm whether to import it anyway, start from scratch, or stop; fires per matching solution iteration | template-cache |+| `create-site:1.5.import-failed` | gate | progress | 1.5 | Import failed or partial — choose retry, from-scratch fallback, or stop; fires per failed solution iteration | partial-unmanaged-template-import || `create-site:3.requirements` | gate | plan | 3 | *"Which features? / Aesthetic / Mood"* — three sub-prompts sharing this gate; shape the rendered Phase 4 plan | nothing || `create-site:4.7.plan-approval` | gate | plan | 4.7 | HTML plan rendered — *"Approve and start building / I'd like to make changes"* | nothing || `create-site:7.review` | gate | plan | 7 | Live site ready — *"Would you like any changes?"* | nothing || `create-site:8.deploy` | gate | plan | 8 | *"Deploy now (Recommended) / Skip for now"* — invokes `/deploy-site` on Yes | nothing |+Template-path note: when Phase 1.5 selects and installs a template, the workflow stops after activation/live preview and does **not** enter the from-scratch Phase 4 plan approval or Phase 8 deploy prompt. Those gates fire only on the from-scratch branch.+---### 6.14 `deploy-site` (8 calls)diff --git a/plugins/power-pages/scripts/apply-seed-data.js b/plugins/power-pages/scripts/apply-seed-data.jsnew file mode 100644index 000000000..198bed692--- /dev/null+++ b/plugins/power-pages/scripts/apply-seed-data.js@@ -0,0 +1,36 @@+#!/usr/bin/env node+'use strict';++const { applySeedData } = require('./lib/apply-seed-data');+const { formatJsonResult, runBestEffortJsonCli } = require('./lib/template-cli-args');++// Accepted argv shape:+// --seedDir ~/.power-platform-skills/template-cache/<sha>/templates/spa/<id>/seed-data+// [--seedFile ~/.power-platform-skills/template-cache/<sha>/templates/spa/<id>/seed-data/data.json]+// --envUrl https://org.crm.dynamics.com+// Missing args are returned as `{ ok:false }` so create-site can continue to+// activation; seeding is best-effort and must never block go-live.+function parseArgs(argv) {+ const args = {};+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === '--seedDir') args.seedDir = argv[++i];+ else if (arg === '--seedFile') args.seedFile = argv[++i];+ else if (arg === '--envUrl') args.envUrl = argv[++i];+ }+ return args;+}++async function run(argv = process.argv.slice(2)) {+ const args = parseArgs(argv);+ if (!args.seedDir || !args.envUrl) {+ return { ok: false, inserted: 0, failed: 1, skipped: 0, errors: [{ scope: 'args', message: 'Usage: apply-seed-data.js --seedDir <dir> --envUrl <url>' }] };+ }+ return applySeedData(args);+}++if (require.main === module) {+ runBestEffortJsonCli(() => run());+}++module.exports = { parseArgs, run, formatJsonResult };diff --git a/plugins/power-pages/scripts/check-available-languages.js b/plugins/power-pages/scripts/check-available-languages.jsnew file mode 100644index 000000000..19c76422f--- /dev/null+++ b/plugins/power-pages/scripts/check-available-languages.js@@ -0,0 +1,126 @@+#!/usr/bin/env node+'use strict';++const {+ getAuthToken,+ makeRequest,+ validateDataverseEnvironmentUrl,+} = require('./lib/validation-helpers');+const { runBestEffortJsonCli } = require('./lib/template-cli-args');++const DEFAULT_REQUIRED_LOCALE_IDS = [1033];++function parseArgs(argv = process.argv.slice(2)) {+ const args = {};+ for (let i = 0; i < argv.length; i++) {+ if (argv[i] === '--envUrl') args.envUrl = argv[++i];+ else if (argv[i] === '--requiredLocaleIds') {+ args.requiredLocaleIds = argv[++i]+ .split(',')+ .map((value) => Number(value.trim()))+ .filter((value) => Number.isInteger(value));+ }+ }+ return args;+}++function normalizeRequiredLocaleIds(requiredLocaleIds) {+ const ids = Array.isArray(requiredLocaleIds) && requiredLocaleIds.length > 0+ ? requiredLocaleIds+ : DEFAULT_REQUIRED_LOCALE_IDS;+ return [...new Set(ids.filter((id) => Number.isInteger(id)))];+}++async function checkAvailableLanguages({+ envUrl,+ token,+ requiredLocaleIds,+ request = makeRequest,+ resolveToken = getAuthToken,+} = {}) {+ if (!envUrl) {+ return { ok: false, error: 'Missing --envUrl.' };+ }+ let normalizedEnvUrl;+ try {+ normalizedEnvUrl = validateDataverseEnvironmentUrl(envUrl);+ } catch (err) {+ return { ok: false, error: err.message };+ }+ token = token || resolveToken(normalizedEnvUrl);+ if (!token) {+ return { ok: false, error: `Azure CLI token unavailable for ${normalizedEnvUrl}. Run \`az login\` first.` };+ }++ const res = await request({+ url: `${normalizedEnvUrl}/api/data/v9.2/RetrieveAvailableLanguages`,+ method: 'GET',+ headers: {+ Authorization: `Bearer ${token}`,+ Accept: 'application/json',+ 'OData-MaxVersion': '4.0',+ 'OData-Version': '4.0',+ },+ timeout: 30000,+ });++ if (res.error) {+ return { ok: false, error: `RetrieveAvailableLanguages request failed: ${res.error}` };+ }+ if (res.statusCode < 200 || res.statusCode >= 300) {+ return {+ ok: false,+ error: `RetrieveAvailableLanguages returned HTTP ${res.statusCode}: ${(res.body || '').slice(0, 400)}`,+ };+ }++ let payload;+ try {+ payload = JSON.parse(res.body || '{}');+ } catch (err) {+ return { ok: false, error: `RetrieveAvailableLanguages returned invalid JSON: ${err.message}` };+ }++ const requiredIds = normalizeRequiredLocaleIds(requiredLocaleIds);+ if (requiredIds.length === 0) {+ return { ok: false, error: 'At least one required locale id must be provided.' };+ }++ // Dataverse returns available language LCIDs as:+ // { "LocaleIds": [1033, 1036, ...] }+ // See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/retrieveavailablelanguages+ // Each template declares the LCIDs its solution was authored against in+ // `requiredDataverseLanguages`; import is blocked if any required LCID is absent.+ if (!Array.isArray(payload.LocaleIds)) {+ return { ok: false, error: 'RetrieveAvailableLanguages response did not include a LocaleIds array.' };+ }++ const localeIds = payload.LocaleIds.filter((id) => Number.isInteger(id));+ const missingLocaleIds = requiredIds.filter((id) => !localeIds.includes(id));+ return {+ ok: true,+ hasRequiredLanguages: missingLocaleIds.length === 0,+ requiredLocaleIds: requiredIds,+ missingLocaleIds,+ localeIds,+ };+}++async function main(deps = {}) {+ const argv = deps.argv || process.argv.slice(2);+ await runBestEffortJsonCli(+ () => checkAvailableLanguages({ ...parseArgs(argv), ...(deps.checkOptions || {}) }),+ deps+ );+}++if (require.main === module) {+ main();+}++module.exports = {+ DEFAULT_REQUIRED_LOCALE_IDS,+ checkAvailableLanguages,+ main,+ parseArgs,+};diff --git a/plugins/power-pages/scripts/dataverse-request.js b/plugins/power-pages/scripts/dataverse-request.jsindex 978b1202a..7c44c2ec8 100644--- a/plugins/power-pages/scripts/dataverse-request.js+++ b/plugins/power-pages/scripts/dataverse-request.js@@ -1,7 +1,7 @@#!/usr/bin/env node// General-purpose Dataverse OData API request script with built-in auth and retry.-// Usage: node dataverse-request.js <envUrl> <method> <apiPath> [--body <json>]+// Usage: node dataverse-request.js <envUrl> <method> <apiPath> [--body <json> | --bodyFile <path>]//// Arguments:// envUrl - Dataverse environment URL (e.g., https://org123.crm.dynamics.com)@@ -10,6 +10,7 @@//// Options:// --body <json> Request body as JSON string+// --bodyFile <path> Request body read from a JSON file, for large payloads// --include-headers Include response headers in output (for OData-EntityId etc.)//// Output (JSON to stdout):@@ -21,36 +22,56 @@// 0 - Request completed (check status field for HTTP result)// 1 - Fatal error (no token, invalid args, network failure after retries)-const { getAuthToken, makeRequest } = require('./lib/validation-helpers');+const fs = require('fs');+const {+ getAuthToken,+ makeRequest,+ validateDataverseEnvironmentUrl,+} = require('./lib/validation-helpers');-function parseArgs() {- const args = process.argv.slice(2);+function parseArgs(argv = process.argv.slice(2), deps = {}) {+ const args = argv;if (args.length < 3) {- process.stderr.write(- 'Usage: node dataverse-request.js <envUrl> <method> <apiPath> [--body <json>] [--include-headers]\n'- );- process.exit(1);+ return { error: 'Usage: node dataverse-request.js <envUrl> <method> <apiPath> [--body <json> | --bodyFile <path>] [--include-headers]' };}const envUrl = args[0].replace(/\/+$/, '');const method = args[1].toUpperCase();const apiPath = args[2];let body = null;+ let bodyFile = null;let includeHeaders = false;for (let i = 3; i < args.length; i++) {if (args[i] === '--body' && args[i + 1]) {body = args[++i];+ } else if (args[i] === '--bodyFile' && args[i + 1]) {+ bodyFile = args[++i];} else if (args[i] === '--include-headers') {includeHeaders = true;}}+ if (body && bodyFile) {+ return { error: 'Use either --body or --bodyFile, not both.' };+ }+ if (bodyFile) {+ try {+ body = (deps.fs || fs).readFileSync(bodyFile, 'utf8');+ } catch (err) {+ return { error: `Failed to read --bodyFile ${bodyFile}: ${err.message}` };+ }+ }+return { envUrl, method, apiPath, body, includeHeaders };}-async function doRequest(envUrl, method, apiPath, body, token, includeHeaders) {- const url = `${envUrl}/api/data/v9.2/${apiPath}`;+async function doRequest(envUrl, method, apiPath, body, token, includeHeaders, request = makeRequest) {+ // doRequest is exported, so every caller must cross the same origin boundary+ // before a bearer token is attached. Validation in main() cannot protect+ // library callers that invoke this helper directly.+ const trustedEnvUrl = validateDataverseEnvironmentUrl(envUrl);+ const url = `${trustedEnvUrl}/api/data/v9.2/${apiPath}`;const headers = {Authorization: `Bearer ${token}`,Accept: 'application/json',@@ -59,7 +80,7 @@ async function doRequest(envUrl, method, apiPath, body, token, includeHeaders) {headers['Content-Type'] = 'application/json';}- const res = await makeRequest({+ const res = await request({url,method,headers,@@ -72,7 +93,11 @@ async function doRequest(envUrl, method, apiPath, body, token, includeHeaders) {}async function main() {- const { envUrl, method, apiPath, body, includeHeaders } = parseArgs();+ const { envUrl, method, apiPath, body, includeHeaders, error } = parseArgs();+ if (error) {+ process.stderr.write(`${error}\n`);+ process.exit(1);+ }let token = getAuthToken(envUrl);if (!token) {@@ -125,4 +150,8 @@ async function main() {}}-main();+if (require.main === module) {+ main();+}++module.exports = { parseArgs, doRequest };diff --git a/plugins/power-pages/scripts/emit-create-site-template-outcome.js b/plugins/power-pages/scripts/emit-create-site-template-outcome.jsnew file mode 100644index 000000000..53de6bdb7--- /dev/null+++ b/plugins/power-pages/scripts/emit-create-site-template-outcome.js@@ -0,0 +1,41 @@+#!/usr/bin/env node+'use strict';++const { emitTemplateOutcome } = require('./lib/create-site-template-telemetry');+const { formatJsonResult } = require('./lib/template-cli-args');++// Accepted argv shape:+// --eventName template_used --templateId company-portal --templateKind spa --framework react --audience internal+// --eventName template_import_success --templateId company-portal --templateKind spa --framework react --audience internal --seedApplied true+// --eventName template_import_failure --templateId company-portal --templateKind spa --framework react --audience internal --outcome failure --errorClass ImportSolutionAsync+// --eventName template_clone_success --templateId company-portal --templateKind spa --framework react --audience internal+// --eventName template_clone_failure --templateId company-portal --templateKind spa --framework react --audience internal --outcome failure --errorClass PacPagesClone+// Scratch branch sends:+// --eventName create_site_from_scratch --framework react --audience internal+// Values are fixed catalog/outcome enums. Free-form error text is intentionally+// unsupported because it can contain paths, URLs, stack traces, or user data.+function parseArgs(argv) {+ const args = {};+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg.startsWith('--')) args[arg.slice(2)] = argv[++i];+ }+ return args;+}++function run(argv = process.argv.slice(2)) {+ const args = parseArgs(argv);+ return emitTemplateOutcome(args);+}++function toCliResult(result) {+ // The emitted event can contain tenant-scoped identifiers. Keep it inside the+ // telemetry boundary and expose only whether the best-effort emission ran.+ return { ok: Boolean(result && result.ok === true) };+}++if (require.main === module) {+ process.stdout.write(formatJsonResult(toCliResult(run())));+}++module.exports = { parseArgs, run, toCliResult };diff --git a/plugins/power-pages/scripts/fetch-template-artifact.js b/plugins/power-pages/scripts/fetch-template-artifact.jsnew file mode 100644index 000000000..13017a4fc--- /dev/null+++ b/plugins/power-pages/scripts/fetch-template-artifact.js@@ -0,0 +1,38 @@+#!/usr/bin/env node+'use strict';++const { pathToFileURL } = require('url');+const { downloadArtifact, DEFAULT_OWNER, DEFAULT_REPO } = require('./lib/template-catalog');+const { parseTemplateRepoArgs, runBestEffortJsonCli } = require('./lib/template-cli-args');++// Accepted argv shape:+// --sha <40-char commit sha> --artifactPath templates/spa/<id>/previews/home.png+// [--owner microsoft] [--repo power-pages-samples] [--cacheRoot /tmp/cache]+// The script is best-effort: it prints `{ ok:false }` instead of throwing so+// create-site can keep the template browser usable even when a preview image is missing.+function parseArgs(argv) {+ return {+ owner: DEFAULT_OWNER,+ repo: DEFAULT_REPO,+ ...parseTemplateRepoArgs(argv, '--artifactPath'),+ };+}++async function run(argv = process.argv.slice(2)) {+ const args = parseArgs(argv);+ if (!args.sha || !args.artifactPath) {+ return { ok: false, error: 'Usage: fetch-template-artifact.js --sha <sha> --artifactPath <path>' };+ }+ try {+ const result = await downloadArtifact(args);+ return { ok: true, ...result, localUrl: pathToFileURL(result.localPath).href };+ } catch (err) {+ return { ok: false, artifactPath: args.artifactPath, error: err.message };+ }+}++if (require.main === module) {+ runBestEffortJsonCli(() => run());+}++module.exports = { parseArgs, run };diff --git a/plugins/power-pages/scripts/fetch-template-catalog.js b/plugins/power-pages/scripts/fetch-template-catalog.jsnew file mode 100644index 000000000..7d48cf7ec--- /dev/null+++ b/plugins/power-pages/scripts/fetch-template-catalog.js@@ -0,0 +1,35 @@+#!/usr/bin/env node+'use strict';++const { fetchCatalog, DEFAULT_OWNER, DEFAULT_REPO, DEFAULT_REF, DEFAULT_CATALOG_PATH } = require('./lib/template-catalog');+const { parseTemplateRepoArgs, runBestEffortJsonCli } = require('./lib/template-cli-args');++// Accepted argv shape:+// --owner microsoft --repo power-pages-samples --ref latest-release+// --catalogPath templates/manifest.json --cacheRoot ~/.power-platform-skills/template-cache+// `--ref` defaults to `latest-release`, which resolves GitHub's latest Release+// tag and then pins that tag to an immutable commit SHA for the run.+// All flags are optional; unknown flags are ignored so future callers can add+// wrapper-only options without breaking the best-effort catalog fetch.+function parseArgs(argv) {+ return {+ owner: DEFAULT_OWNER,+ repo: DEFAULT_REPO,+ ref: DEFAULT_REF,+ catalogPath: DEFAULT_CATALOG_PATH,+ ...parseTemplateRepoArgs(argv),+ };+}++async function run(argv = process.argv.slice(2)) {+ return fetchCatalog(parseArgs(argv));+}++if (require.main === module) {+ // Fetching templates is additive. Return process success even when the repo is+ // unavailable so create-site can inspect `{ ok:false }` and fall back to the+ // from-scratch path without treating the whole skill invocation as failed.+ runBestEffortJsonCli(() => run());+}++module.exports = { parseArgs, run };diff --git a/plugins/power-pages/scripts/fetch-template-seed-data.js b/plugins/power-pages/scripts/fetch-template-seed-data.jsnew file mode 100644index 000000000..0ae91ed01--- /dev/null+++ b/plugins/power-pages/scripts/fetch-template-seed-data.js@@ -0,0 +1,36 @@+#!/usr/bin/env node+'use strict';++const { downloadSeedDataDirectory, DEFAULT_OWNER, DEFAULT_REPO } = require('./lib/template-catalog');+const { parseTemplateRepoArgs, runBestEffortJsonCli } = require('./lib/template-cli-args');++// Accepted argv shape:+// --sha <40-char commit sha> --seedDataPath templates/spa/<id>/seed/data.json+// [--owner microsoft] [--repo power-pages-samples] [--cacheRoot /tmp/cache]+// The seed JSON file is downloaded directly from the pinned SHA. Any attachment+// files referenced by `__files` are downloaded from paths relative to that seed+// JSON file, avoiding GitHub REST tree API rate limits.+function parseArgs(argv) {+ const args = {+ owner: DEFAULT_OWNER,+ repo: DEFAULT_REPO,+ ...parseTemplateRepoArgs(argv),+ };+ const idx = argv.indexOf('--seedDataPath');+ if (idx !== -1) args.seedDataPath = argv[idx + 1];+ return args;+}++async function run(argv = process.argv.slice(2)) {+ const args = parseArgs(argv);+ if (!args.sha || !args.seedDataPath) {+ return { ok: false, error: 'Usage: fetch-template-seed-data.js --sha <sha> --seedDataPath <path>' };+ }+ return downloadSeedDataDirectory(args);+}++if (require.main === module) {+ runBestEffortJsonCli(() => run());+}++module.exports = { parseArgs, run };diff --git a/plugins/power-pages/scripts/fetch-template-variant.js b/plugins/power-pages/scripts/fetch-template-variant.jsnew file mode 100644index 000000000..6bca62a54--- /dev/null+++ b/plugins/power-pages/scripts/fetch-template-variant.js@@ -0,0 +1,37 @@+#!/usr/bin/env node+'use strict';++const { downloadTemplateVariant, DEFAULT_OWNER, DEFAULT_REPO } = require('./lib/template-catalog');+const { parseTemplateRepoArgs, runBestEffortJsonCli } = require('./lib/template-cli-args');++function parseArgs(argv) {+ const repoArgs = parseTemplateRepoArgs(argv);+ const kindIndex = argv.indexOf('--kind');+ const templateIdIndex = argv.indexOf('--templateId');+ const variantIndex = argv.indexOf('--variant');+ return {+ owner: DEFAULT_OWNER,+ repo: DEFAULT_REPO,+ ...repoArgs,+ kind: kindIndex >= 0 ? argv[kindIndex + 1] : undefined,+ templateId: templateIdIndex >= 0 ? argv[templateIdIndex + 1] : undefined,+ variant: variantIndex >= 0 ? argv[variantIndex + 1] : undefined,+ };+}++function run(argv = process.argv.slice(2), deps = {}) {+ const args = parseArgs(argv);+ if (!args.sha || !args.kind || !args.templateId || !args.variant) {+ return {+ ok: false,+ error: 'Usage: fetch-template-variant.js --sha <sha> --kind <spa|traditional> --templateId <id> --variant <name>',+ };+ }+ return downloadTemplateVariant(args, deps);+}++if (require.main === module) {+ runBestEffortJsonCli(() => run());+}++module.exports = { parseArgs, run };diff --git a/plugins/power-pages/scripts/inspect-template-solution.js b/plugins/power-pages/scripts/inspect-template-solution.jsnew file mode 100644index 000000000..baac45728--- /dev/null+++ b/plugins/power-pages/scripts/inspect-template-solution.js@@ -0,0 +1,53 @@+#!/usr/bin/env node+'use strict';++const {+ decideReinstall,+ inspectSolutionDirectory,+ inspectSolutionZip,+} = require('./lib/template-reinstall-policy');+const { formatJsonResult } = require('./lib/template-cli-args');++// Accepted argv shape:+// --solutionPath /tmp/template/solution [--installed true|false] [--installedVersion 1.0.0.0]+// The optional installed fields let create-site combine the source inspection with+// `check-solution-installed.js` output when computing the next re-install step.+function parseArgs(argv) {+ const args = {};+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === '--solutionPath') args.solutionPath = argv[++i];+ else if (arg === '--zipPath') args.zipPath = argv[++i];+ else if (arg === '--installed') args.installed = argv[++i] === 'true';+ else if (arg === '--installedVersion') args.installedVersion = argv[++i];+ }+ return args;+}++function run(argv = process.argv.slice(2)) {+ const args = parseArgs(argv);+ if (!args.solutionPath && !args.zipPath) {+ return { ok: false, error: 'Usage: inspect-template-solution.js --solutionPath <path>' };+ }+ const inspected = args.solutionPath+ ? inspectSolutionDirectory(args.solutionPath)+ : inspectSolutionZip(args.zipPath);+ if (!inspected.ok) return inspected;+ if (typeof args.installed === 'boolean') {+ return {+ ...inspected,+ decision: decideReinstall({+ installed: args.installed,+ installedVersion: args.installedVersion,+ availableVersion: inspected.version,+ }),+ };+ }+ return inspected;+}++if (require.main === module) {+ process.stdout.write(formatJsonResult(run()));+}++module.exports = { parseArgs, run };diff --git a/plugins/power-pages/scripts/lib/apply-seed-data.js b/plugins/power-pages/scripts/lib/apply-seed-data.jsnew file mode 100644index 000000000..113e8a7e3--- /dev/null+++ b/plugins/power-pages/scripts/lib/apply-seed-data.js@@ -0,0 +1,677 @@+'use strict';++const fs = require('fs');+const path = require('path');+const {+ getAuthToken,+ makeRequest,+ validateDataverseEnvironmentUrl,+} = require('./validation-helpers');+const generateUuid = require('../generate-uuid');++const FILE_BLOCK_SIZE_BYTES = 4 * 1024 * 1024;+// Large attachment seed runs can issue many Dataverse calls (record create ++// InitializeFileBlocksUpload + one UploadBlock per 4 MiB + Commit). Refreshing+// every 25 requests keeps long runs away from stale Azure CLI tokens without+// hammering `az account get-access-token` on every block. If refresh fails,+// callers receive the normal best-effort seed summary error; telemetry or site+// activation must never depend on seed upload success.+const TOKEN_REFRESH_EVERY_REQUESTS = 25;+const ALLOWED_ATTACHMENT_EXTENSIONS = new Set(['.pdf', '.png', '.jpg', '.jpeg', '.txt', '.csv', '.json', '.docx', '.xlsx']);+const ODATA_IDENTIFIER_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;+const DATAVERSE_GUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++function emptySummary() {+ return { ok: true, inserted: 0, failed: 0, skipped: 0, errors: [] };+}++function listSeedFiles(seedDir, deps = {}, seedFile = null) {+ const fsImpl = deps.fs || fs;+ if (!seedDir || !fsImpl.existsSync(seedDir)) return [];+ const rootStat = fsImpl.lstatSync(seedDir);+ if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) {+ throw new Error('Seed directory must be a regular directory and not a symbolic link');+ }+ if (seedFile) {+ const resolvedSeedFile = path.resolve(seedFile);+ if (path.extname(resolvedSeedFile).toLowerCase() !== '.json') {+ throw new Error(`Seed file must be JSON: ${seedFile}`);+ }+ const containmentError = validateContainedPath(seedDir, resolvedSeedFile, fsImpl);+ if (containmentError) throw new Error(containmentError.replace(/^Attachment path/, 'Seed file'));+ return [resolvedSeedFile];+ }+ return fsImpl.readdirSync(seedDir)+ .filter((name) => name.toLowerCase().endsWith('.json'))+ .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))+ .map((name) => {+ const filePath = path.join(seedDir, name);+ const fileStat = fsImpl.lstatSync(filePath);+ if (fileStat.isSymbolicLink() || !fileStat.isFile()) {+ throw new Error(`Seed JSON must be a regular file and not a symbolic link: ${name}`);+ }+ return filePath;+ });+}++function isDuplicateConflict(res) {+ // Dataverse duplicate-key conflicts arrive as HTTP 409 with either a JSON+ // OData envelope or plain text depending on the caller surface, e.g.:+ // { "error": { "code": "0x80040237", "message": "Cannot insert duplicate key." } }+ // "A record with matching key values already exists."+ // Only those duplicate shapes are treated as idempotent skips; other 409s+ // (for example concurrency/version conflicts) remain failures.+ if (res.statusCode !== 409) return false;+ const message = `${res.error || ''} ${res.body || ''}`;+ return /duplicate|already\s+exists|cannot\s+insert\s+duplicate/i.test(message);+}++function readSeedFile(filePath, deps = {}) {+ const fsImpl = deps.fs || fs;+ const fileStat = fsImpl.lstatSync(filePath);+ if (fileStat.isSymbolicLink() || !fileStat.isFile()) {+ throw new Error(`Seed JSON must be a regular file and not a symbolic link: ${path.basename(filePath)}`);+ }+ // Seed files are intentionally small authored JSON files. Supported shapes:+ // Flat:+ // { "entitySetName": "cr123_categories",+ // "records": [{ "cr123_categoryid": "<guid>", "cr123_name": "Announcements" }] }+ // Dataverse export:+ // { "schemaVersion": 1, "tables": { "accounts": {+ // "entitySet": "accounts", "idColumn": "accountid", "records": [...] } },+ // "fileExports": [{ "attachmentId": "<guid>", "fileColumn": "cr123_file", "path": "files/a.pdf" }] }+ // The numeric filename prefix (`010-...json`) is the ordering contract; the+ // file body names the OData entity set to POST records into.+ const parsed = JSON.parse(fsImpl.readFileSync(filePath, 'utf8'));+ if (parsed && typeof parsed.entitySetName === 'string' && Array.isArray(parsed.records)) {+ return parsed;+ }+ const normalizedExport = normalizeDataverseExportSeed(parsed);+ if (Array.isArray(normalizedExport) && normalizedExport.length > 0) return normalizedExport;+ throw new Error('Expected flat { entitySetName: string, records: array } or export { tables: object } seed data');+}++function splitReservedFiles(record) {+ const { __files: files = null, ...recordBody } = record;+ return { recordBody, files };+}++function splitCreateAndStateUpdate(seed, record) {+ const createRecord = { ...record };+ const stateUpdate = {};+ for (const field of ['statecode', 'statuscode']) {+ if (!Object.prototype.hasOwnProperty.call(createRecord, field)) continue;+ stateUpdate[field] = createRecord[field];+ delete createRecord[field];+ }+ if (Object.keys(stateUpdate).length === 0) {+ return { createRecord, stateUpdate: null, recordId: null };+ }++ const recordId = seed.primaryKey && record[seed.primaryKey];+ if (typeof recordId !== 'string' || !DATAVERSE_GUID_RE.test(recordId)) {+ throw new Error('Seed records with statecode or statuscode must declare a primaryKey containing a GUID');+ }+ return { createRecord, stateUpdate, recordId };+}++function isCamelCaseLookupKey(key) {+ // App-style lookup aliases can appear in hand-authored seed files:+ // { "categoryId": "<category-guid>", "serviceTypeId": "<type-guid>" }+ // Dataverse does not accept these aliases, and the exact navigation property+ // cannot be derived from either the alias or the target table's primary key.+ const match = String(key || '').match(/^([a-z][A-Za-z0-9]*)Id$/);+ return Boolean(match);+}++function indexSeedRecords(seed, idToTarget) {+ if (!seed || !seed.primaryKey) return;+ for (const record of Array.isArray(seed.records) ? seed.records : []) {+ const id = record && record[seed.primaryKey];+ if (typeof id === 'string') {+ idToTarget.set(id.toLowerCase(), {+ entitySetName: seed.entitySetName,+ });+ }+ }+}++function validateSeedLookupContract(seedEntries) {+ const idToTarget = new Map();+ for (const { seed } of seedEntries) indexSeedRecords(seed, idToTarget);++ const errors = [];+ for (const { file, seed } of seedEntries) {+ for (const record of seed.records) {+ for (const [key, value] of Object.entries(record || {})) {+ if (isCamelCaseLookupKey(key) && typeof value === 'string') {+ errors.push({+ file,+ entitySetName: seed.entitySetName,+ message: `Lookup ${key} is ambiguous; use the exact <NavigationProperty>@odata.bind name from the solution metadata`,+ });+ continue;+ }+ if (!key.endsWith('@odata.bind') || typeof value !== 'string') continue;+ // Seed lookups use the OData bind shape:+ // "[email protected]":+ // "/spa311_categories(11111111-1111-1111-1111-111111111111)"+ // Validate references to records in this seed set before any writes. The+ // navigation-property key itself remains authoritative solution metadata.+ const match = value.match(/^\/([^/()]+)\(([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\)$/i);+ if (!match) {+ errors.push({+ file,+ entitySetName: seed.entitySetName,+ message: `Lookup ${key} must use /<entitySetName>(<guid>)`,+ });+ continue;+ }+ const target = idToTarget.get(match[2].toLowerCase());+ if (target && target.entitySetName !== match[1]) {+ errors.push({+ file,+ entitySetName: seed.entitySetName,+ message: `Lookup ${key} targets ${match[1]}, but the referenced seed record belongs to ${target.entitySetName}`,+ });+ }+ }+ }+ }+ return errors;+}++function normalizeDataverseExportSeed(seed) {+ if (!seed || typeof seed !== 'object' || !seed.tables || typeof seed.tables !== 'object' || Array.isArray(seed.tables)) {+ return null;+ }+ const idToEntitySet = new Map();+ for (const table of Object.values(seed.tables)) {+ if (!table || typeof table !== 'object' || !Array.isArray(table.records) || typeof table.idColumn !== 'string' || typeof table.entitySet !== 'string') {+ continue;+ }+ for (const record of table.records) {+ const id = record && record[table.idColumn];+ if (typeof id === 'string') idToEntitySet.set(id.toLowerCase(), table.entitySet);+ }+ }+ const filesByRecordId = new Map();+ for (const fileExport of Array.isArray(seed.fileExports) ? seed.fileExports : []) {+ if (!fileExport || typeof fileExport !== 'object') continue;+ const { attachmentId, fileColumn, path: filePath } = fileExport;+ if (typeof attachmentId !== 'string' || typeof fileColumn !== 'string' || typeof filePath !== 'string') continue;+ const current = filesByRecordId.get(attachmentId.toLowerCase()) || {};+ current[fileColumn] = filePath;+ filesByRecordId.set(attachmentId.toLowerCase(), current);+ }+ return Object.values(seed.tables)+ .filter((table) => table && typeof table.entitySet === 'string' && typeof table.idColumn === 'string' && Array.isArray(table.records))+ .map((table) => ({+ entitySetName: table.entitySet,+ primaryKey: table.idColumn,+ records: table.records.map((record) => normalizeExportRecord(record, table.idColumn, idToEntitySet, filesByRecordId)),+ }));+}++function normalizeExportRecord(record, primaryKey, idToEntitySet, filesByRecordId) {+ const out = {};+ const lookupBinds = {};+ for (const [key, value] of Object.entries(record || {})) {+ if (key === '@odata.etag') continue;+ if (key.endsWith('@Microsoft.Dynamics.CRM.associatednavigationproperty')) continue;+ if (key.endsWith('@OData.Community.Display.V1.FormattedValue')) continue;+ if (key === 'createdon' || key === 'modifiedon') continue;++ const lookupMatch = key.match(/^_(.+)_value$/);+ if (lookupMatch) {+ if (typeof value !== 'string') continue;+ const navigationProperty = record[`${key}@Microsoft.Dynamics.CRM.associatednavigationproperty`];+ const targetEntitySet = idToEntitySet.get(value.toLowerCase());+ if (typeof navigationProperty === 'string' && targetEntitySet) {+ lookupBinds[`${navigationProperty}@odata.bind`] = `/${targetEntitySet}(${value})`;+ }+ continue;+ }+ out[key] = value;+ }+ Object.assign(out, lookupBinds);+ const recordId = record && record[primaryKey];+ const files = typeof recordId === 'string' ? filesByRecordId.get(recordId.toLowerCase()) : null;+ if (files) out.__files = files;+ return out;+}++function validateFilesContract({ seedDir, seed, record }, deps = {}) {+ const fsImpl = deps.fs || fs;+ // Attachment-bearing seed records use this raw shape:+ // {+ // "entitySetName": "cr123_invoices",+ // "primaryKey": "cr123_invoiceid",+ // "records": [{+ // "cr123_invoiceid": "<guid>",+ // "__files": { "cr123_invoicepdf": "files/invoices/inv-001.pdf" }+ // }]+ // }+ // `__files` is reserved metadata and must never be sent in the record POST.+ // Paths are seed-data-root-relative; absolute paths and `..` segments are+ // rejected so a template cannot read arbitrary local files.+ if (!Object.prototype.hasOwnProperty.call(record, '__files')) return null;+ if (!record.__files || typeof record.__files !== 'object' || Array.isArray(record.__files)) {+ return '__files must be an object mapping file column logical names to seed-data-relative paths';+ }+ if (!seed.primaryKey) return 'Seed file with __files must declare primaryKey';+ const recordId = record[seed.primaryKey];+ if (typeof recordId !== 'string' || !DATAVERSE_GUID_RE.test(recordId)) {+ return `Record with __files must include GUID primary key ${seed.primaryKey}`;+ }+ for (const [columnName, relativePath] of Object.entries(record.__files)) {+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(columnName)) return `Invalid file column name: ${columnName}`;+ if (typeof relativePath !== 'string' || path.isAbsolute(relativePath) || relativePath.split(/[\\/]+/).includes('..')) {+ return `Attachment path must stay under seed-data root: ${relativePath}`;+ }+ const seedRoot = path.resolve(seedDir);+ const absolutePath = path.resolve(seedDir, relativePath);+ if (!absolutePath.startsWith(seedRoot + path.sep)) return `Attachment path must stay under seed-data root: ${relativePath}`;+ const containmentError = validateContainedPath(seedRoot, absolutePath, fsImpl);+ if (containmentError) return containmentError;+ }+ return null;+}++function validateContainedPath(rootPath, targetPath, fsImpl = fs) {+ const root = path.resolve(rootPath);+ const target = path.resolve(targetPath);+ if (target === root || !target.startsWith(root + path.sep)) {+ return `Attachment path must stay under seed-data root: ${targetPath}`;+ }+ try {+ const rootStat = fsImpl.lstatSync(root);+ if (+ (typeof rootStat.isDirectory === 'function' && !rootStat.isDirectory()) ||+ (typeof rootStat.isSymbolicLink === 'function' && rootStat.isSymbolicLink())+ ) {+ return `Seed-data root must be a regular directory: ${root}`;+ }+ let current = root;+ for (const segment of path.relative(root, target).split(path.sep)) {+ current = path.join(current, segment);+ const stat = fsImpl.lstatSync(current);+ if (typeof stat.isSymbolicLink === 'function' && stat.isSymbolicLink()) {+ return `Attachment path contains a symbolic link: ${current}`;+ }+ }+ if (typeof fsImpl.realpathSync === 'function') {+ const realRoot = fsImpl.realpathSync(root);+ const realTarget = fsImpl.realpathSync(target);+ if (realTarget === realRoot || !realTarget.startsWith(realRoot + path.sep)) {+ return `Attachment path resolves outside seed-data root: ${targetPath}`;+ }+ }+ } catch (err) {+ return `Attachment path could not be inspected: ${targetPath} (${err.message})`;+ }+ return null;+}++function readFilePrefix(filePath, length, deps = {}) {+ const fsImpl = deps.fs || fs;+ if (typeof fsImpl.openSync === 'function' && typeof fsImpl.readSync === 'function' && typeof fsImpl.closeSync === 'function') {+ const buffer = Buffer.alloc(length);+ const handle = fsImpl.openSync(filePath, 'r');+ try {+ const bytesRead = fsImpl.readSync(handle, buffer, 0, length, 0);+ return buffer.subarray(0, bytesRead).toString('utf8');+ } finally {+ fsImpl.closeSync(handle);+ }+ }+ const content = fsImpl.readFileSync(filePath);+ return (Buffer.isBuffer(content) ? content : Buffer.from(String(content))).subarray(0, length).toString('utf8');+}++function validateAttachmentFile(filePath, deps = {}) {+ const fsImpl = deps.fs || fs;+ if (deps.seedDir) {+ const containmentError = validateContainedPath(deps.seedDir, filePath, fsImpl);+ if (containmentError) return containmentError;+ }+ const ext = path.extname(filePath).toLowerCase();+ if (!ALLOWED_ATTACHMENT_EXTENSIONS.has(ext)) return `Attachment extension is not allowed: ${ext || '(none)'}`;+ if (!fsImpl.existsSync(filePath)) return `Attachment file not found: ${filePath}`;+ const stat = fsImpl.lstatSync(filePath);+ if (!stat.isFile()) return `Attachment path is not a file: ${filePath}`;+ // Git LFS pointer files start with:+ // version https://git-lfs.github.com/spec/v1+ // Spec: https://github.com/git-lfs/git-lfs/blob/main/docs/spec.md+ // The real binary content is not present in that case. Reading only the+ // prefix is sufficient because the signature is the first line. Tests can+ // inject a minimal fs shim that only supports readFileSync; production uses+ // open/read/close to avoid loading large attachments just for pointer checks.+ const prefix = readFilePrefix(filePath, 200, deps);+ if (/^version https:\/\/git-lfs\.github\.com\/spec\/v1/m.test(prefix)) {+ return `Attachment file appears to be a Git LFS pointer: ${filePath}`;+ }+ return null;+}++async function postRecord({ envUrl, tokenProvider, entitySetName, record }, deps = {}) {+ // Dataverse Web API creates records by POSTing to the entity set collection:+ // POST /api/data/v9.2/accounts+ // See: https://learn.microsoft.com/power-apps/developer/data-platform/webapi/create-entity-web-api+ return postDataverseJson({ envUrl, tokenProvider, apiPath: entitySetName, body: record, includeHeaders: true }, deps);+}++async function patchRecordState({ envUrl, tokenProvider, entitySetName, recordId, stateUpdate }, deps = {}) {+ // Some Dataverse tables permit only their default state during create.+ // KnowledgeArticle, for example, is always created as Draft and must be+ // transitioned to Published through a separate Update containing only its+ // state fields. Mixing statecode/statuscode into the POST makes Dataverse+ // validate the published status reason against the forced Draft state.+ // See: https://learn.microsoft.com/power-apps/developer/data-platform/special-update-operation-behavior+ // See: https://learn.microsoft.com/power-apps/developer/data-platform/reference/entities/knowledgearticle+ return requestDataverseJson({+ envUrl,+ tokenProvider,+ apiPath: entitySetName,+ recordId,+ method: 'PATCH',+ body: stateUpdate,+ }, deps);+}++function defaultBlockId() {+ return Buffer.from(generateUuid()).toString('base64');+}++function contentTypeForFile(filePath) {+ const ext = path.extname(filePath).toLowerCase();+ const types = {+ '.pdf': 'application/pdf',+ '.png': 'image/png',+ '.jpg': 'image/jpeg',+ '.jpeg': 'image/jpeg',+ '.txt': 'text/plain',+ '.csv': 'text/csv',+ '.json': 'application/json',+ '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',+ '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',+ };+ return types[ext] || 'application/octet-stream';+}++function entityLogicalNameFromPrimaryKey(primaryKey) {+ // Dataverse primary keys conventionally use the table logical name plus `id`,+ // e.g. `accountid` -> `account`, `cr123_invoiceid` -> `cr123_invoice`.+ // See Microsoft's Web API examples for file-column upload targets:+ // https://learn.microsoft.com/power-apps/developer/data-platform/file-column-data+ return primaryKey.replace(/id$/i, '');+}++async function uploadFileColumn({ envUrl, tokenProvider, primaryKey, recordId, columnName, filePath }, deps = {}) {+ const fileName = path.basename(filePath);+ const entityLogicalName = entityLogicalNameFromPrimaryKey(primaryKey);+ // Dataverse file columns use actions rather than setting bytes in the record:+ // InitializeFileBlocksUpload -> UploadBlock* -> CommitFileBlocksUpload+ // See: https://learn.microsoft.com/power-apps/developer/data-platform/file-column-data+ const init = await postDataverseAction({ envUrl, tokenProvider, actionName: 'InitializeFileBlocksUpload', body: {+ Target: {+ [primaryKey]: recordId,+ '@odata.type': `Microsoft.Dynamics.CRM.${entityLogicalName}`,+ },+ FileName: fileName,+ FileAttributeName: columnName,+ } }, deps);+ if (init.error || init.statusCode < 200 || init.statusCode >= 300) {+ throw new Error(init.error || init.body || `InitializeFileBlocksUpload failed (${init.statusCode})`);+ }+ // InitializeFileBlocksUpload returns a JSON payload shaped as:+ // { "FileContinuationToken": "<opaque token>" }+ // Older/proxy-failed responses can be empty or non-JSON even with an HTTP+ // status, so parse defensively and report a missing token as an upload error.+ let tokenPayload;+ try {+ tokenPayload = JSON.parse(init.body || '{}');+ } catch (err) {+ throw new Error(`InitializeFileBlocksUpload returned invalid JSON: ${err.message}`);+ }+ const continuation = tokenPayload.FileContinuationToken;+ if (!continuation) throw new Error('InitializeFileBlocksUpload did not return FileContinuationToken');++ const blockIds = [];+ const randomBlockId = deps.randomBlockId || defaultBlockId;+ const fsImpl = deps.fs || fs;+ const fileSize = fsImpl.statSync(filePath).size || 0;+ const fileHandle = typeof fsImpl.openSync === 'function' ? fsImpl.openSync(filePath, 'r') : null;+ try {+ let offset = 0;+ while (offset < fileSize) {+ const block = Buffer.alloc(Math.min(FILE_BLOCK_SIZE_BYTES, fileSize - offset));+ if (fileHandle !== null && typeof fsImpl.readSync === 'function') {+ fsImpl.readSync(fileHandle, block, 0, block.length, offset);+ } else {+ fsImpl.readFileSync(filePath).copy(block, 0, offset, offset + block.length);+ }+ offset += block.length;+ const blockId = randomBlockId();+ blockIds.push(blockId);+ const res = await postDataverseAction({ envUrl, tokenProvider, actionName: 'UploadBlock', body: {+ BlockId: blockId,+ BlockData: block.toString('base64'),+ FileContinuationToken: continuation,+ } }, deps);+ if (res.error || res.statusCode < 200 || res.statusCode >= 300) {+ throw new Error(res.error || res.body || `UploadBlock failed (${res.statusCode})`);+ }+ }+ } finally {+ if (fileHandle !== null && typeof fsImpl.closeSync === 'function') fsImpl.closeSync(fileHandle);+ }+ const commit = await postDataverseAction({ envUrl, tokenProvider, actionName: 'CommitFileBlocksUpload', body: {+ BlockList: blockIds,+ FileContinuationToken: continuation,+ FileName: fileName,+ MimeType: contentTypeForFile(filePath),+ } }, deps);+ if (commit.error || commit.statusCode < 200 || commit.statusCode >= 300) {+ throw new Error(commit.error || commit.body || `CommitFileBlocksUpload failed (${commit.statusCode})`);+ }+}++function postDataverseAction({ envUrl, tokenProvider, actionName, body }, deps = {}) {+ return postDataverseJson({ envUrl, tokenProvider, apiPath: actionName, body }, deps);+}++function postDataverseJson({ envUrl, tokenProvider, apiPath, body, includeHeaders = false }, deps = {}) {+ return requestDataverseJson({+ envUrl,+ tokenProvider,+ apiPath,+ method: 'POST',+ body,+ includeHeaders,+ }, deps);+}++function requestDataverseJson({+ envUrl,+ tokenProvider,+ apiPath,+ recordId = null,+ method,+ body,+ includeHeaders = false,+}, deps = {}) {+ const request = deps.makeRequest || makeRequest;+ const trustedEnvUrl = validateDataverseEnvironmentUrl(envUrl);+ if (!ODATA_IDENTIFIER_RE.test(String(apiPath || ''))) {+ throw new Error(`Invalid Dataverse OData operation name: ${apiPath}`);+ }+ if (method !== 'POST' && method !== 'PATCH') {+ throw new Error(`Unsupported Dataverse JSON method: ${method}`);+ }+ if (recordId !== null && !DATAVERSE_GUID_RE.test(String(recordId))) {+ throw new Error(`Invalid Dataverse record id: ${recordId}`);+ }+ const headers = {+ Authorization: `Bearer ${tokenProvider()}`,+ Accept: 'application/json',+ 'Content-Type': 'application/json',+ };+ if (method === 'PATCH') {+ // The record was just created or was detected as an existing duplicate.+ // Prevent PATCH from silently upserting a replacement if it disappears.+ headers['If-Match'] = '*';+ }+ return request({+ url: `${trustedEnvUrl}/api/data/v9.2/${apiPath}${recordId === null ? '' : `(${recordId})`}`,+ method,+ headers,+ body: JSON.stringify(body),+ includeHeaders,+ timeout: 30000,+ });+}++function createTokenProvider({ envUrl, initialToken, resolveToken, refreshEvery = TOKEN_REFRESH_EVERY_REQUESTS }) {+ let token = initialToken;+ let calls = 0;+ return () => {+ if (!token || calls >= refreshEvery) {+ token = resolveToken(envUrl);+ calls = 0;+ }+ calls += 1;+ return token;+ };+}++async function applySeedData({ seedDir, seedFile, envUrl }, deps = {}) {+ const summary = emptySummary();+ try {+ envUrl = validateDataverseEnvironmentUrl(envUrl);+ const seedEntries = [];+ for (const filePath of listSeedFiles(seedDir, deps, seedFile)) {+ try {+ const seed = readSeedFile(filePath, deps);+ for (const seedEntry of (Array.isArray(seed) ? seed : [seed])) {+ seedEntries.push({ file: path.basename(filePath), seed: seedEntry });+ }+ } catch (err) {+ summary.errors.push({ file: path.basename(filePath), message: err.message });+ }+ }+ summary.errors.push(...validateSeedLookupContract(seedEntries));+ if (summary.errors.length > 0) {+ summary.ok = false;+ summary.failed = summary.errors.length;+ return summary;+ }++ const resolveToken = deps.getAuthToken || getAuthToken;+ const token = deps.token || resolveToken(envUrl);+ if (!token) {+ return { ...summary, ok: false, failed: 1, errors: [{ scope: 'auth', message: `Azure CLI token unavailable for ${envUrl}` }] };+ }+ const tokenProvider = deps.tokenProvider || createTokenProvider({ envUrl, initialToken: token, resolveToken, refreshEvery: deps.tokenRefreshEvery || TOKEN_REFRESH_EVERY_REQUESTS });+ for (const { file, seed: seedEntry } of seedEntries) {+ for (const record of seedEntry.records) {+ const context = { file, entitySetName: seedEntry.entitySetName };+ try {+ const validationError = validateFilesContract({ seedDir, seed: seedEntry, record }, deps);+ const { recordBody, files } = splitReservedFiles(record);+ if (validationError) {+ summary.failed += 1;+ summary.errors.push({ ...context, message: validationError });+ continue;+ }+ const { createRecord, stateUpdate, recordId } = splitCreateAndStateUpdate(seedEntry, recordBody);+ const res = await postRecord({ envUrl, tokenProvider, entitySetName: seedEntry.entitySetName, record: createRecord }, deps);+ let outcome = null;+ if (res.error) {+ summary.failed += 1;+ summary.errors.push({ ...context, message: res.error });+ } else if (isDuplicateConflict(res)) {+ outcome = 'skipped';+ } else if (res.statusCode >= 200 && res.statusCode < 300) {+ outcome = 'inserted';+ } else {+ summary.failed += 1;+ summary.errors.push({ ...context, statusCode: res.statusCode, message: res.body || `HTTP ${res.statusCode}` });+ }+ if (outcome && stateUpdate) {+ const stateRes = await patchRecordState({+ envUrl,+ tokenProvider,+ entitySetName: seedEntry.entitySetName,+ recordId,+ stateUpdate,+ }, deps);+ if (stateRes.error || stateRes.statusCode < 200 || stateRes.statusCode >= 300) {+ throw new Error(stateRes.error || stateRes.body || `State update failed (${stateRes.statusCode})`);+ }+ }+ if (outcome === 'inserted') summary.inserted += 1;+ if (outcome === 'skipped') summary.skipped += 1;+ if (outcome && files) {+ await uploadRecordFiles({ seedDir, seed: seedEntry, record, files, envUrl, tokenProvider, summary, context }, deps);+ }+ } catch (err) {+ summary.failed += 1;+ summary.errors.push({ ...context, message: err.message });+ }+ }+ }+ } catch (err) {+ summary.ok = false;+ summary.failed += 1;+ summary.errors.push({ scope: 'seedDir', message: err.message });+ }+ return summary;+}++async function uploadRecordFiles({ seedDir, seed, record, files, envUrl, tokenProvider, summary, context }, deps = {}) {+ for (const [columnName, relativePath] of Object.entries(files)) {+ try {+ const filePath = path.join(seedDir, relativePath);+ const fileError = validateAttachmentFile(filePath, { ...deps, seedDir });+ if (fileError) throw new Error(fileError);+ await uploadFileColumn({+ envUrl,+ tokenProvider,+ primaryKey: seed.primaryKey,+ recordId: record[seed.primaryKey],+ columnName,+ filePath,+ }, deps);+ } catch (err) {+ summary.failed += 1;+ summary.errors.push({ ...context, columnName, attachmentPath: relativePath, message: err.message });+ }+ }+}++module.exports = {+ applySeedData,+ emptySummary,+ listSeedFiles,+ readSeedFile,+ normalizeDataverseExportSeed,+ normalizeExportRecord,+ postRecord,+ isDuplicateConflict,+ splitReservedFiles,+ validateFilesContract,+ validateContainedPath,+ validateAttachmentFile,+ uploadFileColumn,+ uploadRecordFiles,+ postDataverseJson,+ createTokenProvider,+ validateSeedLookupContract,+ entityLogicalNameFromPrimaryKey,+ contentTypeForFile,+ postDataverseAction,+ FILE_BLOCK_SIZE_BYTES,+ ALLOWED_ATTACHMENT_EXTENSIONS,+ TOKEN_REFRESH_EVERY_REQUESTS,+};diff --git a/plugins/power-pages/scripts/lib/cli-tenant-alignment.js b/plugins/power-pages/scripts/lib/cli-tenant-alignment.jsnew file mode 100644index 000000000..994a65ac4--- /dev/null+++ b/plugins/power-pages/scripts/lib/cli-tenant-alignment.js@@ -0,0 +1,185 @@+'use strict';++const { execFileSync } = require('child_process');+const {+ getAuthToken,+ parseActiveAuthListEnvironmentUrl,+ parseEnvironmentUrl,+ runAzureCli,+ validateDataverseEnvironmentUrl,+} = require('./validation-helpers');++const GUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++function normalizeGuid(value) {+ const text = String(value || '').trim();+ return GUID_RE.test(text) ? text.toLowerCase() : null;+}++function parsePacTenantId(output) {+ // PAC auth banners are label/value text and vary slightly by version, e.g.:+ // Tenant ID: 72f988bf-86f1-41af-91ab-2d7cd011db47+ // Tenant: 72f988bf-86f1-41af-91ab-2d7cd011db47+ // Values can have extra spaces, so parse only known tenant labels and require+ // a GUID-shaped value before trusting it.+ const match = String(output || '').match(/^\s*(?:Tenant ID|Tenant)\s*:\s*([0-9a-f-]{36})\s*$/im);+ return match ? normalizeGuid(match[1]) : null;+}++function decodeJwtPayload(token) {+ const parts = String(token || '').split('.');+ if (parts.length < 2) return null;+ try {+ return JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'));+ } catch {+ return null;+ }+}++function tenantIdFromToken(token) {+ const payload = decodeJwtPayload(token);+ return normalizeGuid(payload && payload.tid);+}++function runPacAuthWho({ execFile = execFileSync, platform = process.platform } = {}) {+ if (platform === 'win32') {+ // PAC installs as pac.exe on Windows. Route through cmd.exe so PATH lookup+ // matches the user's terminal while keeping the executable literal fixed for+ // the secure-process validator.+ return execFile('cmd.exe', ['/d', '/s', '/c', 'pac.exe', 'auth', 'who'], { encoding: 'utf8', timeout: 15000 });+ }+ return execFile('pac', ['auth', 'who'], { encoding: 'utf8', timeout: 15000 });+}++function runPacEnvWho({ execFile = execFileSync, platform = process.platform } = {}) {+ if (platform === 'win32') {+ return execFile('cmd.exe', ['/d', '/s', '/c', 'pac.exe', 'env', 'who'], { encoding: 'utf8', timeout: 15000 });+ }+ return execFile('pac', ['env', 'who'], { encoding: 'utf8', timeout: 15000 });+}++function runPacAuthList({ execFile = execFileSync, platform = process.platform } = {}) {+ if (platform === 'win32') {+ return execFile('cmd.exe', ['/d', '/s', '/c', 'pac.exe', 'auth', 'list'], { encoding: 'utf8', timeout: 15000 });+ }+ return execFile('pac', ['auth', 'list'], { encoding: 'utf8', timeout: 15000 });+}++function runAzAccountShowTenant({ execFile = execFileSync, platform = process.platform } = {}) {+ return runAzureCli(+ ['account', 'show', '--query', 'tenantId', '-o', 'tsv'],+ { execFile, platform }+ );+}++function getPacTenantId(execFile = execFileSync, platform = process.platform) {+ try {+ return parsePacTenantId(runPacAuthWho({ execFile, platform }));+ } catch {+ return null;+ }+}++function getAzAccountTenantId(execFile = execFileSync, platform = process.platform) {+ try {+ return normalizeGuid(runAzAccountShowTenant({ execFile, platform }));+ } catch {+ return null;+ }+}++function getPacEnvironmentUrl(execFile = execFileSync, platform = process.platform) {+ try {+ const environmentUrl = parseEnvironmentUrl(runPacEnvWho({ execFile, platform }));+ if (environmentUrl) return environmentUrl;+ } catch {}+ try {+ return parseActiveAuthListEnvironmentUrl(runPacAuthList({ execFile, platform }));+ } catch {+ return null;+ }+}++function validateCliTenantAlignment({+ envUrl,+ token,+ pacTenantId,+ azTenantId,+ tokenTenantId,+ pacEnvironmentUrl,+} = {}, deps = {}) {+ const execFile = deps.execFile || execFileSync;+ const platform = deps.platform || process.platform;+ let expectedEnvironmentUrl = null;+ if (envUrl) {+ try {+ expectedEnvironmentUrl = validateDataverseEnvironmentUrl(envUrl);+ } catch (err) {+ return { ok: false, error: err.message };+ }+ }+ const activeEnvironmentUrl = expectedEnvironmentUrl+ ? (pacEnvironmentUrl+ ? (() => {+ try { return validateDataverseEnvironmentUrl(pacEnvironmentUrl); } catch { return null; }+ })()+ : getPacEnvironmentUrl(execFile, platform))+ : null;+ const pacTenant = normalizeGuid(pacTenantId) || getPacTenantId(execFile, platform);+ const azTenant = normalizeGuid(azTenantId) || getAzAccountTenantId(execFile, platform);+ const bearerToken = token || (expectedEnvironmentUrl+ ? (deps.getAuthToken+ ? deps.getAuthToken(expectedEnvironmentUrl)+ : getAuthToken(expectedEnvironmentUrl, { execFile, platform }))+ : null);+ const tokenTenant = normalizeGuid(tokenTenantId) || tenantIdFromToken(bearerToken);++ const missing = [];+ if (expectedEnvironmentUrl && !activeEnvironmentUrl) missing.push('pacEnvironmentUrl');+ if (!pacTenant) missing.push('pacTenantId');+ if (!azTenant) missing.push('azTenantId');+ if (!tokenTenant) missing.push('tokenTenantId');+ if (missing.length) {+ return {+ ok: false,+ error: `Could not determine ${missing.join(', ')}. Run pac auth who and az login, then retry.`,+ pacTenantId: pacTenant,+ azTenantId: azTenant,+ tokenTenantId: tokenTenant,+ expectedEnvironmentUrl,+ pacEnvironmentUrl: activeEnvironmentUrl,+ };+ }++ const mismatches = [];+ if (expectedEnvironmentUrl && expectedEnvironmentUrl !== activeEnvironmentUrl) {+ mismatches.push('pac-vs-environment');+ }+ if (pacTenant !== azTenant) mismatches.push('pac-vs-az');+ if (pacTenant !== tokenTenant) mismatches.push('pac-vs-token');+ if (azTenant !== tokenTenant) mismatches.push('az-vs-token');++ return {+ ok: mismatches.length === 0,+ pacTenantId: pacTenant,+ azTenantId: azTenant,+ tokenTenantId: tokenTenant,+ expectedEnvironmentUrl,+ pacEnvironmentUrl: activeEnvironmentUrl,+ mismatches,+ error: mismatches.length+ ? 'PAC CLI and Azure CLI are authenticated to different tenants or environments. Switch PAC auth or Azure CLI tenant before continuing.'+ : null,+ };+}++module.exports = {+ decodeJwtPayload,+ parsePacTenantId,+ runAzAccountShowTenant,+ runPacAuthList,+ runPacAuthWho,+ runPacEnvWho,+ tenantIdFromToken,+ validateCliTenantAlignment,+};diff --git a/plugins/power-pages/scripts/lib/create-site-template-telemetry.js b/plugins/power-pages/scripts/lib/create-site-template-telemetry.jsnew file mode 100644index 000000000..87edc4ea7--- /dev/null+++ b/plugins/power-pages/scripts/lib/create-site-template-telemetry.js@@ -0,0 +1,151 @@+'use strict';++const crypto = require('crypto');+const fs = require('fs');+const os = require('os');+const path = require('path');+const { pick } = require('./telemetry/lib/events');+const { fireAndForget } = require('./telemetry/lib/emit-spawn');+const { readPacAuth } = require('./telemetry/lib/pac-auth');+const { readPacCliVersion, readAiAgent } = require('./telemetry/lib/agent-info');+const { getSessionId } = require('./telemetry/lib/session');++const EVENT_STREAM = 'PagesAIPluginEvent';+const TEMPLATE_EVENT_NAMES = new Set(['template_used', 'template_import_success', 'template_import_failure', 'template_clone_success', 'template_clone_failure', 'create_site_from_scratch']);+const TEMPLATE_KINDS = new Set(['spa', 'traditional']);+const FRAMEWORKS = new Set(['react', 'vue', 'angular', 'astro']);+const AUDIENCES = new Set(['internal', 'external']);+const ERROR_CLASSES = new Set([+ 'ImportSolutionAsync',+ 'PacPagesClone',+ 'NpmInstall',+ 'NpmBuild',+ 'CompiledOutput',+ 'PacPagesUploadCodeSite',+]);+const COMMON_FIELDS = [+ 'pluginName',+ 'pluginVersion',+ 'sessionId',+ 'correlationId',+ 'osName',+ 'osVersion',+ 'nodeVersion',+ 'orgId',+ 'tenantId',+ 'pacCliVersion',+ 'aiAgentName',+ 'aiAgentVersion',+ 'eventInfo',+];+const SKILL_FIELDS = ['skillName'];+const COMPLETED_FIELDS = ['outcome', 'durationMs', 'errorClass'];++function normalizeBool(value) {+ return value === true || value === 'true' || value === '1';+}++function sanitizeTemplateOutcomeInfo(fields = {}) {+ const info = {};+ if (FRAMEWORKS.has(fields.framework)) info.framework = fields.framework;+ if (AUDIENCES.has(fields.audience)) info.audience = fields.audience;+ if (templateEventName(fields).startsWith('template_')) {+ if (/^[a-z0-9][a-z0-9-]*$/.test(fields.templateId || '')) info.templateId = fields.templateId;+ if (TEMPLATE_KINDS.has(fields.templateKind)) info.templateKind = fields.templateKind;+ if (templateEventName(fields) === 'template_import_success' && fields.seedApplied !== undefined) info.seedApplied = normalizeBool(fields.seedApplied);+ }+ return info;+}++function templateEventName(fields = {}) {+ if (TEMPLATE_EVENT_NAMES.has(fields.eventName)) return fields.eventName;+ return fields.templateId ? 'template_used' : 'create_site_from_scratch';+}++function osFriendlyName(platform) {+ if (platform === 'win32') return 'Windows';+ if (platform === 'darwin') return 'Mac';+ if (platform === 'linux') return 'Linux';+ return platform;+}++function readPluginVersion(deps = {}) {+ if (deps.pluginVersion) return deps.pluginVersion;+ const pluginJsonPath = deps.pluginJsonPath || path.join(__dirname, '..', '..', '.plugin', 'plugin.json');+ try {+ const parsed = JSON.parse((deps.fs || fs).readFileSync(pluginJsonPath, 'utf8'));+ return typeof parsed.version === 'string' ? parsed.version : 'unknown';+ } catch {+ return 'unknown';+ }+}++function resolveSessionId(fields = {}, env = process.env) {+ return fields.sessionId ||+ env.COPILOT_AGENT_SESSION_ID ||+ env.AGENCY_SESSION_ID ||+ env.CLAUDE_SESSION_ID ||+ '';+}++function buildTemplateOutcomeEvent(fields = {}, deps = {}) {+ // Privacy boundary: eventInfo is restricted to fixed catalog IDs/enums and+ // booleans. Do not add site name, URL, subdomain, free-text prompt content,+ // or user data here. Transmission remains governed by the shared telemetry+ // dispatcher opt-out (`/power-pages:telemetry off` and the per-plugin env var)+ // and fail-closed fire-and-forget behavior.+ const pacAuth = (deps.readPacAuth || readPacAuth)({ _exec: deps.execPacAuth });+ const agentInfo = typeof deps.readAgentInfo === 'function'+ ? deps.readAgentInfo()+ : { ...readAiAgent(deps.env || process.env), pacCliVersion: readPacCliVersion() };+ const payload = {+ pluginName: 'power-pages',+ pluginVersion: readPluginVersion({ ...deps, pluginVersion: fields.pluginVersion }),+ sessionId: getSessionId(resolveSessionId(fields, deps.env || process.env)),+ correlationId: fields.correlationId || (deps.randomUUID || crypto.randomUUID)(),+ osName: fields.osName || osFriendlyName(os.platform()),+ osVersion: fields.osVersion || os.release(),+ nodeVersion: fields.nodeVersion || `v${String(process.versions.node).split('.')[0]}`,+ skillName: 'create-site',+ outcome: fields.outcome || 'success',+ eventInfo: sanitizeTemplateOutcomeInfo(fields),+ };+ if (pacAuth && pacAuth.orgId) payload.orgId = pacAuth.orgId;+ if (pacAuth && pacAuth.tenantId) payload.tenantId = pacAuth.tenantId;+ if (agentInfo.aiAgentName) payload.aiAgentName = agentInfo.aiAgentName;+ if (agentInfo.aiAgentVersion) payload.aiAgentVersion = agentInfo.aiAgentVersion;+ if (agentInfo.pacCliVersion) payload.pacCliVersion = agentInfo.pacCliVersion;+ if (fields.durationMs) payload.durationMs = Number(fields.durationMs);+ if (ERROR_CLASSES.has(fields.errorClass)) payload.errorClass = fields.errorClass;++ const severity = payload.outcome === 'failure' ? 'Error' : 'Info';+ const eventName = templateEventName(fields);+ return {+ name: EVENT_STREAM,+ data: {+ eventName,+ eventType: 'Trace',+ severity,+ ...pick(payload, [...COMMON_FIELDS, ...SKILL_FIELDS, ...COMPLETED_FIELDS]),+ },+ };+}++function emitTemplateOutcome(fields = {}, deps = {}) {+ try {+ const pacAuth = deps.pacAuth || (deps.readPacAuth || readPacAuth)({ _exec: deps.execPacAuth });+ const event = buildTemplateOutcomeEvent(fields, { ...deps, readPacAuth: () => pacAuth });+ const emit = deps.fireAndForget || fireAndForget;+ emit(event, {+ cloud: (pacAuth && pacAuth.cloud) || '',+ configDir: process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR || '',+ fakeProbe: process.env.POWER_PLATFORM_SKILLS_FAKE_HTTPS || '',+ ikeyJsonPath: path.join(__dirname, 'telemetry', 'ikey.json'),+ });+ return { ok: true, event };+ } catch (err) {+ return { ok: false, error: err.message };+ }+}++module.exports = { buildTemplateOutcomeEvent, emitTemplateOutcome, normalizeBool, sanitizeTemplateOutcomeInfo, templateEventName };diff --git a/plugins/power-pages/scripts/lib/default-browser.js b/plugins/power-pages/scripts/lib/default-browser.jsnew file mode 100644index 000000000..98ba25138--- /dev/null+++ b/plugins/power-pages/scripts/lib/default-browser.js@@ -0,0 +1,28 @@+'use strict';++const os = require('os');+const { execFileSync } = require('child_process');++function openInDefaultBrowser(target, deps = {}) {+ const platform = (deps.os || os).platform();+ const execFile = deps.execFileSync || execFileSync;+ if (platform === 'darwin') {+ execFile('open', [target], { stdio: 'ignore' });+ } else if (platform === 'win32') {+ // Avoid `cmd /c start`: cmd.exe reparses metacharacters such as `&` in URL+ // query strings. Also avoid passing the URL as a positional PowerShell+ // argument after `-Command`; Windows PowerShell can treat it as an extra+ // command token instead of binding it to `param(...)`. An environment+ // variable keeps URLs and file paths as inert data while Start-Process still+ // uses the registered default handler.+ execFile('powershell.exe', ['-NoProfile', '-Command', 'Start-Process -FilePath $env:COPILOT_OPEN_TARGET'], {+ stdio: 'ignore',+ windowsHide: true,+ env: { ...process.env, COPILOT_OPEN_TARGET: target },+ });+ } else {+ execFile('xdg-open', [target], { stdio: 'ignore' });+ }+}++module.exports = { openInDefaultBrowser };diff --git a/plugins/power-pages/scripts/lib/fix-blocked-attachments.js b/plugins/power-pages/scripts/lib/fix-blocked-attachments.jsindex 7bed36ff9..57be8d876 100644--- a/plugins/power-pages/scripts/lib/fix-blocked-attachments.js+++ b/plugins/power-pages/scripts/lib/fix-blocked-attachments.js@@ -35,7 +35,7 @@'use strict';-const { execFileSync } = require('child_process');+const { runPac: runPacCommand } = require('./pac-command');const { validateDataverseEnvironmentUrl } = require('./validation-helpers');function parseArgs(argv) {@@ -61,19 +61,18 @@ function log(msg, quiet) {if (!quiet) process.stderr.write(`[fix-blocked-attachments] ${msg}\n`);}-function makePacRunner(execImpl) {- const exec = execImpl || execFileSync;+function makePacRunner(execImpl, platform = process.platform) {return function runPac(args) {- try {- const out = exec('pac', args, {- encoding: 'utf8',- stdio: ['ignore', 'pipe', 'pipe'],- shell: false,- });- return { ok: true, stdout: typeof out === 'string' ? out : (out || '') };- } catch (e) {- return { ok: false, stdout: e.stdout || '', stderr: e.stderr || '', error: e.message };- }+ const result = runPacCommand(args, {+ platform,+ ...(execImpl ? { runCommand: execImpl } : {}),+ });+ return {+ ok: result.status === 0,+ stdout: result.stdout || '',+ stderr: result.stderr || '',+ error: result.error && result.error.message,+ };};}@@ -92,8 +91,8 @@ function parseBlockedAttachmentsFromPacOutput(pacOutput) {return null;}-async function fixBlockedAttachments({ envUrl, extensions, dryRun, quiet, execImpl } = {}) {- const runPac = makePacRunner(execImpl);+async function fixBlockedAttachments({ envUrl, extensions, dryRun, quiet, execImpl, platform } = {}) {+ const runPac = makePacRunner(execImpl, platform);const trustedEnvUrl = envUrl ? validateDataverseEnvironmentUrl(envUrl) : null;const envArgs = trustedEnvUrl ? ['--environment', trustedEnvUrl] : [];diff --git a/plugins/power-pages/scripts/lib/pac-command.js b/plugins/power-pages/scripts/lib/pac-command.jsnew file mode 100644index 000000000..7473cb1e9--- /dev/null+++ b/plugins/power-pages/scripts/lib/pac-command.js@@ -0,0 +1,122 @@+'use strict';++const fs = require('fs');+const os = require('os');+const path = require('path');+const { execFileSync } = require('child_process');++const PAC_LOG_TAIL_BYTES = 32 * 1024;++function readFileTail(filePath, maxBytes = PAC_LOG_TAIL_BYTES, fsImpl = fs) {+ const size = fsImpl.statSync(filePath).size;+ const length = Math.min(size, maxBytes);+ if (length === 0) return '';+ const buffer = Buffer.alloc(length);+ const fd = fsImpl.openSync(filePath, 'r');+ try {+ fsImpl.readSync(fd, buffer, 0, length, size - length);+ } finally {+ fsImpl.closeSync(fd);+ }+ return buffer.toString('utf8');+}++function runPac(args, deps = {}) {+ const fsImpl = deps.fs || fs;+ const tmpRoot = deps.tmpRoot || os.tmpdir();+ let logDirectory;+ let logPath;+ let logFd;+ let error;+ let status = 0;+ let output = '';+ let commandOutput;++ try {+ logDirectory = fsImpl.mkdtempSync(path.join(tmpRoot, 'powerpages-pac-'));+ logPath = path.join(logDirectory, 'output.log');+ logFd = fsImpl.openSync(logPath, 'w');+ } catch (err) {+ if (logDirectory) {+ try {+ fsImpl.rmSync(logDirectory, { recursive: true, force: true });+ } catch {+ // Preserve the setup error; the returned failure is still actionable.+ }+ }+ return { status: 1, stdout: '', stderr: '', error: err };+ }++ const options = {+ timeout: deps.timeoutMs || 900000,+ shell: false,+ // PAC can emit more than execFileSync's maxBuffer during a code-site upload.+ // Redirect both streams to disk so Node never terminates a healthy mutation+ // because its captured output grew too large.+ // See: https://nodejs.org/api/child_process.html#maxbuffer-and-unicode+ stdio: ['ignore', logFd, logFd],+ };+ if (deps.cwd) options.cwd = deps.cwd;+ try {+ const isWindows = (deps.platform || process.platform) === 'win32';+ const command = isWindows ? 'pac.exe' : 'pac';+ if (deps.runCommand) {+ commandOutput = deps.runCommand(command, args, options);+ } else if (isWindows) {+ // PAC ships as pac.exe on Windows. Invoke it directly so paths and other+ // arguments never receive an additional cmd.exe parsing pass.+ execFileSync('pac.exe', args, options);+ } else {+ execFileSync('pac', args, options);+ }+ } catch (err) {+ status = Number.isInteger(err.status) ? err.status : 1;+ error = err;+ } finally {+ try {+ fsImpl.closeSync(logFd);+ } catch {+ // The command result remains authoritative if closing an already-closed+ // diagnostic file descriptor fails.+ }+ }++ try {+ output = readFileTail(logPath, PAC_LOG_TAIL_BYTES, fsImpl);+ if (!output && commandOutput !== undefined && commandOutput !== null) {+ output = String(commandOutput);+ }+ } catch (err) {+ if (!error) {+ status = 1;+ error = err;+ }+ } finally {+ try {+ fsImpl.rmSync(logDirectory, { recursive: true, force: true });+ } catch {+ // Diagnostic cleanup must not replace the PAC command's result.+ }+ }++ return {+ status,+ stdout: status === 0 ? output : '',+ stderr: status === 0 ? '' : output,+ ...(error ? { error } : {}),+ };+}++function commandError(step, result) {+ const detail = String(result.stderr || result.stdout || '').trim();+ if (detail) return `${step} failed: ${detail}`;+ if (result.error) return `${step} failed: ${result.error.message}`;+ return `${step} failed with exit code ${result.status}`;+}++module.exports = {+ PAC_LOG_TAIL_BYTES,+ commandError,+ readFileTail,+ runPac,+};diff --git a/plugins/power-pages/scripts/lib/render-template.js b/plugins/power-pages/scripts/lib/render-template.jsindex 8596462a8..2388bf049 100644--- a/plugins/power-pages/scripts/lib/render-template.js+++ b/plugins/power-pages/scripts/lib/render-template.js@@ -20,8 +20,9 @@ const PLACEHOLDER_RE = /__(?:(HTML|ATTR|JSON|RAW)_)?([A-Z][A-Z0-9_]*)__/g;* @param {string} [options.dataPath] - Absolute path to a JSON data file. Ignored if dataObject is provided.* @param {Object} [options.dataObject] - Data object passed directly. If provided, takes precedence over dataPath.* @param {string[]} options.requiredKeys - Keys that must be present in the data+ * @param {boolean} [options.emitStatus=true] - Print JSON status after writing the file*/-function renderTemplate({ templatePath, outputPath, dataPath, dataObject, requiredKeys }) {+function renderTemplate({ templatePath, outputPath, dataPath, dataObject, requiredKeys, emitStatus = true }) {// Validate inputs existif (!fs.existsSync(templatePath)) {console.error(`Template not found: ${templatePath}`);@@ -101,7 +102,9 @@ function renderTemplate({ templatePath, outputPath, dataPath, dataObject, requir// non-fatal}- console.log(JSON.stringify({ status: 'ok', output: outputPath }));+ if (emitStatus) {+ console.log(JSON.stringify({ status: 'ok', output: outputPath }));+ }}function escapeHtml(value) {diff --git a/plugins/power-pages/scripts/lib/template-catalog.js b/plugins/power-pages/scripts/lib/template-catalog.jsnew file mode 100644index 000000000..109b58328--- /dev/null+++ b/plugins/power-pages/scripts/lib/template-catalog.js@@ -0,0 +1,1130 @@+'use strict';++const crypto = require('crypto');+const fs = require('fs');+const https = require('https');+const os = require('os');+const path = require('path');+const { execFileSync } = require('child_process');+const { inspectSolutionDirectory } = require('./template-reinstall-policy');++const DEFAULT_OWNER = 'microsoft';+const DEFAULT_REPO = 'power-pages-samples';+const DEFAULT_REF = 'latest-release';+const DEFAULT_CATALOG_PATH = 'templates/manifest.json';+const FRAMEWORKS = new Set(['react', 'vue', 'angular', 'astro', 'none', 'other']);+const TEMPLATE_KINDS = new Set(['spa', 'traditional']);+const ID_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;+const CACHE_MARKER_FILE = '.powerpages-template-cache.json';+const CACHE_MARKER_VERSION = 1;++function getDefaultCacheRoot() {+ return path.join(os.homedir(), '.power-platform-skills', 'template-cache');+}++function encodePath(filePath) {+ return filePath.split('/').map(encodeURIComponent).join('/');+}++function buildRawUrl({ owner = DEFAULT_OWNER, repo = DEFAULT_REPO, sha, filePath }) {+ if (!sha) throw new Error('sha is required');+ assertValidSha(sha);+ if (!filePath) throw new Error('filePath is required');+ return `https://raw.githubusercontent.com/${owner}/${repo}/${sha}/${encodePath(filePath)}`;+}++function buildGitRemoteUrl({ owner = DEFAULT_OWNER, repo = DEFAULT_REPO }) {+ return `https://github.com/${owner}/${repo}.git`;+}++function cacheDirForSha(cacheRoot, sha) {+ assertValidSha(sha);+ return path.join(cacheRoot || getDefaultCacheRoot(), sha);+}++function artifactCachePath({ cacheRoot, sha, artifactPath }) {+ if (path.isAbsolute(artifactPath) || artifactPath.split(/[\\/]+/).includes('..')) {+ throw new Error(`Template artifact path must stay under the templates cache: ${artifactPath}`);+ }+ return path.join(cacheDirForSha(cacheRoot, sha), artifactPath);+}++function isPathInside(rootPath, candidatePath) {+ const relative = path.relative(rootPath, candidatePath);+ return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));+}++function assertOwnedPrivateCacheEntry(entryPath, stat, entryType) {+ if (typeof process.getuid === 'function' && stat.uid !== process.getuid()) {+ throw new Error(`Template cache ${entryType} must be owned by the current user: ${entryPath}`);+ }+ // POSIX permission bits are not meaningful on Windows. On POSIX, cached+ // package metadata and website source must not be readable or writable by+ // another local account because npm later executes content from this cache.+ if (process.platform !== 'win32' && (stat.mode & 0o077) !== 0) {+ throw new Error(`Template cache ${entryType} must be private to the current user: ${entryPath}`);+ }+}++function ensurePrivateCacheRoot(cacheRoot, fsImpl = fs) {+ const resolvedCacheRoot = path.resolve(cacheRoot || getDefaultCacheRoot());+ fsImpl.mkdirSync(resolvedCacheRoot, { recursive: true, mode: 0o700 });+ const rootStat = fsImpl.lstatSync(resolvedCacheRoot);+ if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) {+ throw new Error(`Template cache root must be a real directory: ${resolvedCacheRoot}`);+ }+ assertOwnedPrivateCacheEntry(resolvedCacheRoot, rootStat, 'root');++ const markerPath = path.join(resolvedCacheRoot, CACHE_MARKER_FILE);+ if (!fsImpl.existsSync(markerPath)) {+ const existingEntries = fsImpl.readdirSync(resolvedCacheRoot);+ if (existingEntries.length > 0) {+ throw new Error(`Template cache root is not owned by this tool: ${resolvedCacheRoot}`);+ }++ let markerDescriptor;+ try {+ markerDescriptor = fsImpl.openSync(markerPath, 'wx', 0o600);+ fsImpl.writeFileSync(markerDescriptor, JSON.stringify({+ schemaVersion: CACHE_MARKER_VERSION,+ ownerUid: typeof process.getuid === 'function' ? process.getuid() : null,+ }), 'utf8');+ fsImpl.closeSync(markerDescriptor);+ markerDescriptor = undefined;+ } catch (err) {+ // A concurrent template command may have initialized the same private+ // cache between the existence check and exclusive marker creation.+ if (err.code !== 'EEXIST') throw err;+ } finally {+ if (markerDescriptor !== undefined) {+ try { fsImpl.closeSync(markerDescriptor); } catch { /* best-effort */ }+ }+ }+ }++ const markerStat = fsImpl.lstatSync(markerPath);+ if (markerStat.isSymbolicLink() || !markerStat.isFile()) {+ throw new Error(`Template cache ownership marker must be a regular file: ${markerPath}`);+ }+ assertOwnedPrivateCacheEntry(markerPath, markerStat, 'ownership marker');++ let marker;+ try {+ marker = JSON.parse(fsImpl.readFileSync(markerPath, 'utf8'));+ } catch {+ throw new Error(`Template cache ownership marker is malformed: ${markerPath}`);+ }+ const currentUid = typeof process.getuid === 'function' ? process.getuid() : null;+ if (+ marker.schemaVersion !== CACHE_MARKER_VERSION ||+ marker.ownerUid !== currentUid+ ) {+ throw new Error(`Template cache ownership marker is invalid: ${markerPath}`);+ }++ return resolvedCacheRoot;+}++function ensureSafeCacheDirectory(cacheRoot, directoryPath, fsImpl = fs) {+ const resolvedCacheRoot = ensurePrivateCacheRoot(cacheRoot, fsImpl);+ const resolvedDirectory = path.resolve(directoryPath);+ if (!isPathInside(resolvedCacheRoot, resolvedDirectory)) {+ throw new Error(`Template cache directory must stay under the cache root: ${resolvedDirectory}`);+ }++ const canonicalCacheRoot = fsImpl.realpathSync(resolvedCacheRoot);++ let currentPath = resolvedCacheRoot;+ const relativeDirectory = path.relative(resolvedCacheRoot, resolvedDirectory);+ for (const segment of relativeDirectory ? relativeDirectory.split(path.sep) : []) {+ currentPath = path.join(currentPath, segment);+ if (!fsImpl.existsSync(currentPath)) {+ fsImpl.mkdirSync(currentPath);+ }+ const currentStat = fsImpl.lstatSync(currentPath);+ if (currentStat.isSymbolicLink() || !currentStat.isDirectory()) {+ throw new Error(`Template cache path must contain only real directories: ${currentPath}`);+ }+ const canonicalCurrentPath = fsImpl.realpathSync(currentPath);+ if (!isPathInside(canonicalCacheRoot, canonicalCurrentPath)) {+ throw new Error(`Template cache path resolves outside the cache root: ${currentPath}`);+ }+ }++ return resolvedDirectory;+}++function writeCacheFileAtomic(cacheRoot, filePath, content, fsImpl = fs) {+ const cacheDirectory = ensureSafeCacheDirectory(cacheRoot, path.dirname(filePath), fsImpl);+ if (fsImpl.existsSync(filePath)) {+ const existingStat = fsImpl.lstatSync(filePath);+ if (existingStat.isSymbolicLink() || !existingStat.isFile()) {+ throw new Error(`Template cache file must be a regular file: ${filePath}`);+ }+ }++ // Exclusive creation prevents a pre-planted symlink from redirecting the write.+ // Rename replaces the cache entry itself, so a destination swapped after the+ // lstat check is never opened or followed.+ const temporaryPath = path.join(+ cacheDirectory,+ `.${path.basename(filePath)}.partial-${process.pid}-${Date.now()}`+ );+ let fileDescriptor;+ try {+ fileDescriptor = fsImpl.openSync(temporaryPath, 'wx', 0o600);+ fsImpl.writeFileSync(fileDescriptor, content, 'utf8');+ fsImpl.closeSync(fileDescriptor);+ fileDescriptor = undefined;+ fsImpl.renameSync(temporaryPath, filePath);+ } finally {+ if (fileDescriptor !== undefined) {+ try { fsImpl.closeSync(fileDescriptor); } catch { /* best-effort */ }+ }+ try { fsImpl.rmSync(temporaryPath, { force: true }); } catch { /* best-effort */ }+ }+}++function isNonEmptyString(value) {+ return typeof value === 'string' && value.trim().length > 0;+}++function isNestedFamilyTemplate(template) {+ return template && typeof template.variants === 'object' && template.variants && !Array.isArray(template.variants);+}++function isSpaTemplate(template) {+ return template && template.kind === 'spa';+}++function assertValidSha(sha) {+ if (!/^[0-9a-f]{40}$/i.test(sha || '')) {+ throw new Error(`Expected an immutable 40-character commit sha, got: ${sha}`);+ }+}++function validateCatalogShape(catalog) {+ // Raw `templates/manifest.json` shape:+ // { "$schema": "./schemas/templates-manifest.schema.json", "templates": [+ // { "id": "311-portal", "displayName": "311 Portal",+ // "description": "…", "kind": "spa", "framework": "react",+ // "keywords": ["311", "citizen-services"],+ // "audience": ["makers", "developers"],+ // "requiredDataverseLanguages": [1033],+ // "previewImages": ["spa/311-portal/previews/home.png"],+ // "seedDataPath": "spa/311-portal/seed/data.json",+ // "author": "Microsoft" }+ // ] }+ // `audience` here is the *template's* target persona list (admins/developers/+ // makers/partners) and is an array per the upstream schema at+ // https://github.com/microsoft/power-pages-samples/blob/main/templates/schemas/templates-manifest.schema.json+ // Do not confuse it with create-site's internal/external site audience, which+ // comes from Phase 1 discovery and is what the telemetry event records.+ // Keep this structural, not semantic: the samples repo owns the full JSON+ // Schema, while create-site only needs enough validation to fail open before+ // previewing malformed entries or caching artifacts under a pinned SHA.+ if (!catalog || !Array.isArray(catalog.templates)) {+ return 'expected a templates array';+ }+ for (const [index, template] of catalog.templates.entries()) {+ if (!template || typeof template !== 'object') return `template at index ${index} is not an object`;+ const requiredStringFields = isNestedFamilyTemplate(template)+ ? ['id', 'displayName', 'description', 'kind', 'author']+ : [+ 'id', 'displayName', 'description', 'kind', 'framework',+ 'author',+ ];+ const missing = requiredStringFields.filter((field) => !isNonEmptyString(template[field]));+ if (missing.length > 0) return `template ${template.id || index} missing string field(s): ${missing.join(', ')}`;+ if (!TEMPLATE_KINDS.has(template.kind)) return `template ${template.id} has unsupported kind: ${template.kind}`;+ if (template.solutionPath !== undefined || template.websiteCodePath !== undefined) {+ return `template ${template.id || index} must not define derivable solutionPath or websiteCodePath`;+ }+ if (!ID_PATTERN.test(template.id)) return `template ${template.id} id must be kebab-case`;+ if (!Array.isArray(template.audience) || template.audience.length === 0 || !template.audience.every(isNonEmptyString)) {+ return `template ${template.id} audience must be a non-empty array of strings`;+ }+ if (+ !Array.isArray(template.requiredDataverseLanguages) ||+ template.requiredDataverseLanguages.length === 0 ||+ !template.requiredDataverseLanguages.every((id) => Number.isInteger(id) && id > 0)+ ) {+ return `template ${template.id} requiredDataverseLanguages must be a non-empty array of positive integers`;+ }+ if (!Array.isArray(template.keywords)) return `template ${template.id} keywords must be an array`;+ if (!Array.isArray(template.previewImages)) {+ return `template ${template.id} previewImages must be an array`;+ }+ if (isNestedFamilyTemplate(template)) {+ const seenFrameworks = new Set();+ const variantEntries = Object.entries(template.variants);+ if (variantEntries.length === 0) return `template ${template.id} variants must contain at least one framework`;+ for (const [framework, variant] of variantEntries) {+ const normalizedFramework = framework.toLowerCase();+ if (seenFrameworks.has(normalizedFramework)) return `template ${template.id} has duplicate framework variant: ${framework}`;+ seenFrameworks.add(normalizedFramework);+ if (!FRAMEWORKS.has(normalizedFramework)) return `template ${template.id} variant ${framework} has unsupported framework`;+ if (!variant || typeof variant !== 'object' || Array.isArray(variant)) return `template ${template.id} variant ${framework} is not an object`;+ if (variant.solutionPath !== undefined || variant.websiteCodePath !== undefined) {+ return `template ${template.id} variant ${framework} must not define derivable solutionPath or websiteCodePath`;+ }+ if (variant.previewImages !== undefined && !Array.isArray(variant.previewImages)) {+ return `template ${template.id} variant ${framework} previewImages must be an array`;+ }+ if (+ variant.requiredDataverseLanguages !== undefined &&+ (+ !Array.isArray(variant.requiredDataverseLanguages) ||+ variant.requiredDataverseLanguages.length === 0 ||+ !variant.requiredDataverseLanguages.every((id) => Number.isInteger(id) && id > 0)+ )+ ) {+ return `template ${template.id} variant ${framework} requiredDataverseLanguages must be a non-empty array of positive integers`;+ }+ }+ }+ }+ return null;+}++function catalogBasePath(catalogPath) {+ const dir = path.posix.dirname(catalogPath || '');+ return dir === '.' ? '' : dir.replace(/\/+$/, '');+}++function resolveCatalogArtifactPath(catalogPath, artifactPath) {+ if (!isNonEmptyString(artifactPath)) return artifactPath;+ const base = catalogBasePath(catalogPath);+ if (!base || artifactPath === base || artifactPath.startsWith(`${base}/`)) {+ return artifactPath;+ }+ return `${base}/${artifactPath.replace(/^\/+/, '')}`;+}++function materializeCatalogArtifactPaths(catalog, catalogPath) {+ return {+ ...catalog,+ templates: catalog.templates.map((template) => {+ // Manifest artifact paths are authored relative to the manifest folder.+ // For the default `templates/manifest.json`, a raw entry like:+ // "previewImages": ["spa/311-portal/previews/home.png"]+ // must download from:+ // templates/spa/311-portal/previews/home.png+ // Do this once after validation so the rest of create-site can treat every+ // artifact path as repository-root-relative.+ const materialized = {+ ...template,+ previewImages: template.previewImages.map((imagePath) => resolveCatalogArtifactPath(catalogPath, imagePath)),+ };+ if (template.seedDataPath) {+ materialized.seedDataPath = resolveCatalogArtifactPath(catalogPath, template.seedDataPath);+ }+ if (isNestedFamilyTemplate(template)) {+ materialized.variants = Object.fromEntries(Object.entries(template.variants).map(([framework, variant]) => {+ const materializedVariant = { ...variant };+ if (Array.isArray(variant.previewImages)) {+ materializedVariant.previewImages = variant.previewImages.map((imagePath) => resolveCatalogArtifactPath(catalogPath, imagePath));+ }+ if (variant.seedDataPath) {+ materializedVariant.seedDataPath = resolveCatalogArtifactPath(catalogPath, variant.seedDataPath);+ }+ return [framework.toLowerCase(), materializedVariant];+ }));+ }+ return materialized;+ }),+ };+}++function normalizeCatalogFamilies(catalog = {}) {+ const templates = Array.isArray(catalog.templates) ? catalog.templates : [];+ return templates.map((template) => {+ if (!isNestedFamilyTemplate(template)) {+ return {+ id: template.id,+ displayName: template.displayName,+ description: template.description,+ kind: template.kind,+ keywords: template.keywords || [],+ audience: template.audience || [],+ requiredDataverseLanguages: template.requiredDataverseLanguages || [],+ previewImages: template.previewImages || [],+ ...(template.seedDataPath ? { seedDataPath: template.seedDataPath } : {}),+ author: template.author,+ variants: [{+ familyId: template.id,+ variantKey: template.framework,+ variantId: `${template.id}/${template.framework}`,+ displayName: template.displayName,+ description: template.description,+ kind: template.kind,+ framework: template.framework,+ keywords: template.keywords || [],+ audience: template.audience || [],+ requiredDataverseLanguages: template.requiredDataverseLanguages || [],+ previewImages: template.previewImages || [],+ ...(template.seedDataPath ? { seedDataPath: template.seedDataPath } : {}),+ author: template.author,+ }],+ };+ }+ return {+ id: template.id,+ displayName: template.displayName,+ description: template.description,+ kind: template.kind,+ keywords: template.keywords || [],+ audience: template.audience || [],+ requiredDataverseLanguages: template.requiredDataverseLanguages || [],+ previewImages: template.previewImages || [],+ ...(template.seedDataPath ? { seedDataPath: template.seedDataPath } : {}),+ author: template.author,+ variants: Object.entries(template.variants).map(([framework, variant]) => {+ const variantKey = framework.toLowerCase();+ return {+ familyId: template.id,+ variantKey,+ variantId: `${template.id}/${variantKey}`,+ displayName: template.displayName,+ description: template.description,+ kind: template.kind,+ framework: variantKey,+ keywords: template.keywords || [],+ audience: template.audience || [],+ requiredDataverseLanguages: variant.requiredDataverseLanguages || template.requiredDataverseLanguages || [],+ previewImages: Array.isArray(variant.previewImages) ? variant.previewImages : (template.previewImages || []),+ ...(variant.seedDataPath || template.seedDataPath ? { seedDataPath: variant.seedDataPath || template.seedDataPath } : {}),+ author: template.author,+ };+ }),+ };+ });+}++function startHttpsGet({ url, headers, timeoutMs, deps, reject, onResponse }) {+ const httpsImpl = deps.https || https;+ const req = httpsImpl.get(url, {+ headers: {+ 'User-Agent': 'power-pages-template-catalog',+ ...headers,+ },+ timeout: timeoutMs,+ }, onResponse);+ req.on('error', reject);+ req.on('timeout', () => {+ req.destroy(new Error(`GET ${url} timed out`));+ });+ return req;+}++function requestJson(url, deps = {}) {+ return new Promise((resolve, reject) => {+ startHttpsGet({+ url,+ headers: {+ Accept: 'application/vnd.github+json, application/json',+ },+ timeoutMs: deps.timeoutMs || 10000,+ deps,+ reject,+ onResponse: (res) => {+ if (res.statusCode < 200 || res.statusCode >= 300) {+ res.resume();+ reject(new Error(`GET ${url} failed with ${res.statusCode}`));+ return;+ }+ let body = '';+ res.setEncoding('utf8');+ res.on('data', (chunk) => { body += chunk; });+ res.on('end', () => {+ try {+ resolve(JSON.parse(body));+ } catch (err) {+ reject(new Error(`GET ${url} returned invalid JSON: ${err.message}`));+ }+ });+ },+ });+ });+}++function downloadFile(url, outputPath, deps = {}) {+ const fsImpl = deps.fs || fs;+ return new Promise((resolve, reject) => {+ fsImpl.mkdirSync(path.dirname(outputPath), { recursive: true });+ const randomBytes = deps.randomBytes || crypto.randomBytes;+ const tmpPath = `${outputPath}.partial-${process.pid}-${randomBytes(8).toString('hex')}`;+ // `wx` maps to exclusive create. A pre-existing symlink or file makes the+ // open fail instead of redirecting downloaded bytes outside the cache.+ const file = fsImpl.createWriteStream(tmpPath, { flags: 'wx', mode: 0o600 });+ const cleanup = () => {+ try { fsImpl.rmSync(tmpPath, { force: true }); } catch { /* best-effort */ }+ };+ startHttpsGet({+ url,+ headers: {},+ timeoutMs: deps.timeoutMs || 30000,+ deps,+ reject: (err) => {+ file.destroy();+ cleanup();+ reject(err);+ },+ onResponse: (res) => {+ if (res.statusCode < 200 || res.statusCode >= 300) {+ res.resume();+ file.destroy();+ cleanup();+ reject(new Error(`GET ${url} failed with ${res.statusCode}`));+ return;+ }+ res.pipe(file);+ file.on('finish', () => {+ file.close((closeError) => {+ if (closeError) {+ cleanup();+ reject(closeError);+ return;+ }+ try {+ fsImpl.renameSync(tmpPath, outputPath);+ resolve(outputPath);+ } catch (err) {+ cleanup();+ reject(err);+ }+ });+ });+ },+ });+ file.on('error', (err) => {+ cleanup();+ reject(err);+ });+ });+}++function runGitLsRemote(args, deps = {}) {+ const execFile = deps.execFileSync || execFileSync;+ return execFile('git', ['ls-remote', ...args], { encoding: 'utf8', timeout: 15000 });+}++function resolveRefToSha({ owner = DEFAULT_OWNER, repo = DEFAULT_REPO, ref = DEFAULT_REF }, deps = {}) {+ const remoteUrl = buildGitRemoteUrl({ owner, repo });+ const output = runGitLsRemote([remoteUrl, ref], deps);+ // `git ls-remote <remote> <ref>` returns tab-delimited rows:+ // 49b0e74b386206c7682019110434f034fca2e129\trefs/heads/main+ // A release tag can return multiple rows for annotated tags; any leading+ // 40-character SHA is enough because raw.githubusercontent.com accepts the+ // object id for immutable content fetches.+ const match = String(output || '').match(/^([0-9a-f]{40})\s+/im);+ if (!match) {+ throw new Error(`git ls-remote did not resolve ${owner}/${repo}@${ref}`);+ }+ return match[1];+}++function versionKey(tagName) {+ const match = String(tagName || '').match(/(\d+)\.(\d+)\.(\d+)(?:\.(\d+))?/);+ if (!match) return null;+ return match.slice(1).map((part) => Number(part || 0));+}++function compareVersionKeys(left, right) {+ for (let i = 0; i < Math.max(left.length, right.length); i++) {+ const diff = (left[i] || 0) - (right[i] || 0);+ if (diff !== 0) return diff;+ }+ return 0;+}++function parseRemoteTags(output) {+ const byTag = new Map();+ for (const line of String(output || '').split(/\r?\n/)) {+ const match = line.match(/^([0-9a-f]{40})\s+refs\/tags\/(.+?)(\^\{\})?$/i);+ if (!match) continue;+ const [, sha, tagName, peeled] = match;+ const existing = byTag.get(tagName) || {};+ byTag.set(tagName, peeled ? { ...existing, peeledSha: sha } : { ...existing, sha });+ }+ return [...byTag.entries()]+ .map(([tagName, value]) => ({ tagName, sha: value.peeledSha || value.sha, version: versionKey(tagName) }))+ .filter((entry) => entry.sha && entry.version);+}++function resolveLatestRelease(options = {}, deps = {}) {+ const remoteUrl = buildGitRemoteUrl(options);+ const tags = parseRemoteTags(runGitLsRemote(['--tags', remoteUrl], deps));+ if (tags.length === 0) {+ return { ref: 'main', sha: resolveRefToSha({ ...options, ref: 'main' }, deps) };+ }+ tags.sort((a, b) => compareVersionKeys(b.version, a.version) || a.tagName.localeCompare(b.tagName));+ const latest = tags[0];+ return { ref: latest.tagName, sha: latest.sha, releaseName: latest.tagName, releaseUrl: `https://github.com/${options.owner || DEFAULT_OWNER}/${options.repo || DEFAULT_REPO}/releases/tag/${encodeURIComponent(latest.tagName)}` };+}++function resolveCatalogRef(options = {}, deps = {}) {+ const ref = options.ref || DEFAULT_REF;+ if (ref === 'latest-release') {+ return resolveLatestRelease(options, deps);+ }+ return { ref, sha: resolveRefToSha({ ...options, ref }, deps) };+}++async function fetchCatalog(options = {}, deps = {}) {+ const {+ owner = DEFAULT_OWNER,+ repo = DEFAULT_REPO,+ ref = DEFAULT_REF,+ catalogPath = DEFAULT_CATALOG_PATH,+ cacheRoot = getDefaultCacheRoot(),+ } = options;+ const fsImpl = deps.fs || fs;+ const request = deps.requestJson || ((url) => requestJson(url, deps));++ try {+ const resolved = resolveCatalogRef({ owner, repo, ref }, deps);+ const { sha } = resolved;+ const cacheDir = cacheDirForSha(cacheRoot, sha);+ const rawCatalog = await request(buildRawUrl({ owner, repo, sha, filePath: catalogPath }));+ const catalogError = validateCatalogShape(rawCatalog);+ if (catalogError) throw new Error(`Template catalog is malformed: ${catalogError}`);+ const catalog = materializeCatalogArtifactPaths(rawCatalog, catalogPath);+ // Traditional templates remain in the downloaded catalog so a mixed+ // marketplace stays valid. create-site only exposes SPA templates until the+ // traditional solution-import provisioning path is implemented.+ const selectableCatalog = {+ ...catalog,+ templates: normalizeCatalogFamilies({+ templates: catalog.templates.filter(isSpaTemplate),+ }),+ };+ const catalogLocalPath = artifactCachePath({ cacheRoot, sha, artifactPath: catalogPath });+ writeCacheFileAtomic(cacheRoot, catalogLocalPath, JSON.stringify(catalog, null, 2), fsImpl);+ return {+ ok: true,+ owner,+ repo,+ ref,+ resolvedRef: resolved.ref,+ sha,+ releaseName: resolved.releaseName,+ releaseUrl: resolved.releaseUrl,+ catalogPath,+ catalogLocalPath,+ cacheDir,+ catalog,+ selectableCatalog,+ };+ } catch (err) {+ return { ok: false, owner, repo, ref, catalogPath, error: err.message };+ }+}++function validateZipContainsSolution(zipPath, deps = {}) {+ try {+ const fsImpl = deps.fs || fs;+ return zipFileNames(fsImpl.readFileSync(zipPath)).some((name) => name.toLowerCase() === 'solution.xml');+ } catch {+ return false;+ }+}++function zipFileNames(buffer) {+ // ZIP stores each filename in local file headers:+ // 50 4b 03 04 ... [fileNameLength at +26] [extraLength at +28] [name at +30]+ // and again in central directory headers:+ // 50 4b 01 02 ... [fileNameLength at +28] [extraLength at +30] [commentLength at +32] [name at +46]+ // Read both forms so this remains independent of the host OS having `unzip`+ // installed. That matters in plugin hosts and CI images where external tools+ // are not guaranteed.+ const data = Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer);+ const names = [];+ for (let i = 0; i <= data.length - 4; i++) {+ const signature = data.readUInt32LE(i);+ if (signature === 0x04034b50 && i + 30 <= data.length) {+ const fileNameLength = data.readUInt16LE(i + 26);+ const extraLength = data.readUInt16LE(i + 28);+ const nameStart = i + 30;+ const nameEnd = nameStart + fileNameLength;+ if (nameEnd <= data.length) names.push(data.subarray(nameStart, nameEnd).toString('utf8'));+ i = Math.max(i, nameEnd + extraLength - 1);+ } else if (signature === 0x02014b50 && i + 46 <= data.length) {+ const fileNameLength = data.readUInt16LE(i + 28);+ const extraLength = data.readUInt16LE(i + 30);+ const commentLength = data.readUInt16LE(i + 32);+ const nameStart = i + 46;+ const nameEnd = nameStart + fileNameLength;+ if (nameEnd <= data.length) names.push(data.subarray(nameStart, nameEnd).toString('utf8'));+ i = Math.max(i, nameEnd + extraLength + commentLength - 1);+ }+ }+ return names;+}++async function downloadArtifact(options = {}, deps = {}) {+ const {+ owner = DEFAULT_OWNER,+ repo = DEFAULT_REPO,+ sha,+ artifactPath,+ cacheRoot = getDefaultCacheRoot(),+ } = options;+ if (!sha) throw new Error('sha is required');+ if (!artifactPath) throw new Error('artifactPath is required');+ const fsImpl = deps.fs || fs;+ const localPath = artifactCachePath({ cacheRoot, sha, artifactPath });+ ensureSafeCacheDirectory(cacheRoot, path.dirname(localPath), fsImpl);+ if (fsImpl.existsSync(localPath)) {+ const cachedStat = fsImpl.lstatSync(localPath);+ if (cachedStat.isSymbolicLink() || !cachedStat.isFile()) {+ throw new Error(`Cached template artifact must be a regular file: ${localPath}`);+ }+ return { localPath, cached: true };+ }+ const download = deps.downloadFile || ((url, dest) => downloadFile(url, dest, deps));+ await download(buildRawUrl({ owner, repo, sha, filePath: artifactPath }), localPath);+ const downloadedStat = fsImpl.lstatSync(localPath);+ if (downloadedStat.isSymbolicLink() || !downloadedStat.isFile()) {+ throw new Error(`Downloaded template artifact must be a regular file: ${localPath}`);+ }+ return { localPath, cached: false };+}++function validateRepositoryDirectoryPath(directoryPath, fieldName, label) {+ if (!isNonEmptyString(directoryPath)) return `${fieldName} is required`;+ if (path.isAbsolute(directoryPath) || directoryPath.includes('\\')) {+ return `${label} must be a repository-relative POSIX directory`;+ }+ const segments = directoryPath.split('/');+ if (segments.some((segment) => !segment || segment === '.' || segment === '..' || segment === '.git')) {+ return `${label} must stay inside the template repository`;+ }+ if (segments.some((segment) => !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(segment))) {+ return `${label} contains unsupported characters`;+ }+ return null;+}++function validateWebsiteCodeDirectory(localPath, options = {}, deps = {}) {+ const fsImpl = deps.fs || fs;+ if (!fsImpl.existsSync(localPath)) return 'Website code directory is missing';+ const rootStat = fsImpl.lstatSync(localPath);+ if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) {+ return 'Website code directory must be a regular directory';+ }+ // Both traditional and code sites keep PAC website source under+ // `.powerpages-site/website.yml`. Code sites also carry the package metadata+ // and project-local npm configuration needed to build and upload the SPA.+ // See: https://learn.microsoft.com/power-platform/developer/cli/reference/pages#pac-pages-download+ const requiredFiles = options.kind === 'traditional'+ ? []+ : ['powerpages.config.json', 'package.json', '.npmrc'];+ for (const requiredFile of requiredFiles) {+ const requiredPath = path.join(localPath, requiredFile);+ if (!fsImpl.existsSync(requiredPath)) {+ return `Website code directory is missing ${requiredFile}`;+ }+ const requiredStat = fsImpl.lstatSync(requiredPath);+ if (requiredStat.isSymbolicLink() || !requiredStat.isFile()) {+ return `Website code directory is missing ${requiredFile}`;+ }+ }+ const websiteMetadataPath = path.join(localPath, '.powerpages-site', 'website.yml');+ if (!fsImpl.existsSync(websiteMetadataPath)) {+ return 'Website code directory is missing .powerpages-site/website.yml';+ }+ const metadataStat = fsImpl.lstatSync(websiteMetadataPath);+ if (metadataStat.isSymbolicLink() || !metadataStat.isFile()) {+ return 'Website code directory is missing .powerpages-site/website.yml';+ }++ const queue = [localPath];+ while (queue.length > 0) {+ const current = queue.pop();+ for (const entry of fsImpl.readdirSync(current, { withFileTypes: true })) {+ if (entry.isSymbolicLink()) {+ return `Website code directory contains a symbolic link: ${path.relative(localPath, path.join(current, entry.name))}`;+ }+ if (entry.name === '.git' || entry.name === 'node_modules' || entry.name === '.DS_Store' || entry.name.endsWith('.tsbuildinfo')) {+ return `Website code directory contains generated or local-only content: ${path.relative(localPath, path.join(current, entry.name))}`;+ }+ if (entry.isDirectory()) queue.push(path.join(current, entry.name));+ }+ }+ return null;+}++function validateUnpackedSolutionDirectory(localPath, deps = {}) {+ const fsImpl = deps.fs || fs;+ if (!fsImpl.existsSync(localPath)) {+ return 'Template solution source is not a directory';+ }+ const rootStat = fsImpl.lstatSync(localPath);+ if (rootStat.isSymbolicLink()) {+ return 'Template solution source must not be a symbolic link';+ }+ if (!rootStat.isDirectory()) return 'Template solution source is not a directory';++ // `pac solution unpack` uses the SolutionPackager source layout and places+ // solution metadata under `Other/`.+ // See: https://learn.microsoft.com/power-platform/developer/cli/reference/solution#pac-solution-unpack+ const solutionXmlPath = path.join(localPath, 'Other', 'Solution.xml');+ const customizationsXmlPath = path.join(localPath, 'Other', 'Customizations.xml');+ const queue = [localPath];+ while (queue.length > 0) {+ const current = queue.pop();+ for (const entry of fsImpl.readdirSync(current, { withFileTypes: true })) {+ const entryPath = path.join(current, entry.name);+ const relativePath = path.relative(localPath, entryPath);+ if (entry.isSymbolicLink()) {+ return `Template solution source contains a symbolic link: ${relativePath}`;+ }+ if (+ entry.name === '.git' ||+ entry.name === 'node_modules' ||+ entry.name === '.DS_Store' ||+ entry.name.endsWith('.tsbuildinfo')+ ) {+ return `Template solution source contains generated or local-only content: ${relativePath}`;+ }+ if (entry.isFile() && path.extname(entry.name).toLowerCase() === '.zip') {+ return `Template solution source must not contain committed zip files: ${relativePath}`;+ }+ if (entry.isDirectory()) queue.push(entryPath);+ }+ }++ for (const requiredPath of [solutionXmlPath, customizationsXmlPath]) {+ if (!fsImpl.existsSync(requiredPath) || !fsImpl.lstatSync(requiredPath).isFile()) {+ return `Template solution source is missing ${path.relative(localPath, requiredPath)}`;+ }+ }++ const solutionXml = fsImpl.readFileSync(solutionXmlPath, 'utf8');+ if (!/<Managed>\s*0\s*<\/Managed>/i.test(solutionXml)) {+ return 'Template solution source must describe an unmanaged solution';+ }+ const customizationsXml = fsImpl.readFileSync(customizationsXmlPath, 'utf8');+ if (!deps.allowWebsiteComponents && /<powerpagecomponents(?:\s|>)/i.test(customizationsXml)) {+ return 'Template supporting solution must not contain Power Pages website components';+ }+ return null;+}++function repositoryDirectoryCheckoutRoot({ cacheRoot = getDefaultCacheRoot(), sha, directoryPath }) {+ assertValidSha(sha);+ const pathError = validateRepositoryDirectoryPath(+ directoryPath,+ 'directoryPath',+ 'Repository directory path'+ );+ if (pathError) throw new Error(pathError);+ // Keep cached content under a reserved leaf so a cached parent path and one of+ // its descendants cannot overwrite each other.+ return path.join(+ cacheDirForSha(cacheRoot, sha),+ '.directory-checkouts',+ ...directoryPath.split('/'),+ '.checkout'+ );+}++function runGitCheckoutCommand(args, deps = {}) {+ const execFile = deps.execFileSync || execFileSync;+ return execFile('git', args, {+ encoding: 'utf8',+ timeout: deps.gitTimeoutMs || 120000,+ stdio: ['ignore', 'pipe', 'pipe'],+ });+}++function downloadRepositoryDirectory(options = {}, validateDirectory, deps = {}) {+ const {+ owner = DEFAULT_OWNER,+ repo = DEFAULT_REPO,+ sha,+ directoryPath,+ cacheRoot = getDefaultCacheRoot(),+ } = options;+ const fsImpl = deps.fs || fs;+ assertValidSha(sha);+ const pathError = validateRepositoryDirectoryPath(+ directoryPath,+ 'directoryPath',+ 'Repository directory path'+ );+ if (pathError) throw new Error(pathError);+ const checkoutRoot = repositoryDirectoryCheckoutRoot({ cacheRoot, sha, directoryPath });+ const localPath = checkoutRoot;+ ensureSafeCacheDirectory(cacheRoot, path.dirname(checkoutRoot), fsImpl);+ if (fsImpl.existsSync(checkoutRoot)) {+ const checkoutStat = fsImpl.lstatSync(checkoutRoot);+ if (checkoutStat.isSymbolicLink() || !checkoutStat.isDirectory()) {+ fsImpl.rmSync(checkoutRoot, { recursive: true, force: true });+ } else {+ const canonicalCacheRoot = fsImpl.realpathSync(path.resolve(cacheRoot));+ const canonicalCheckoutRoot = fsImpl.realpathSync(checkoutRoot);+ if (!isPathInside(canonicalCacheRoot, canonicalCheckoutRoot)) {+ throw new Error(`Template checkout resolves outside the cache root: ${checkoutRoot}`);+ }+ const cachedError = validateDirectory(localPath);+ if (!cachedError) return { localPath, cached: true };+ fsImpl.rmSync(checkoutRoot, { recursive: true, force: true });+ }+ }++ const partialRoot = `${checkoutRoot}.partial-${process.pid}-${Date.now()}`;+ fsImpl.rmSync(partialRoot, { recursive: true, force: true });+ try {+ runGitCheckoutCommand(['init', '--quiet', partialRoot], deps);+ runGitCheckoutCommand(['-C', partialRoot, 'remote', 'add', 'origin', buildGitRemoteUrl({ owner, repo })], deps);+ runGitCheckoutCommand(['-C', partialRoot, 'sparse-checkout', 'set', '--cone', '--', directoryPath], deps);+ runGitCheckoutCommand(['-C', partialRoot, 'fetch', '--quiet', '--depth', '1', 'origin', sha], deps);+ runGitCheckoutCommand(['-C', partialRoot, 'checkout', '--quiet', '--detach', 'FETCH_HEAD'], deps);+ const partialPath = path.join(partialRoot, ...directoryPath.split('/'));+ const validationError = validateDirectory(partialPath);+ if (validationError) throw new Error(validationError);+ fsImpl.renameSync(partialPath, checkoutRoot);+ const checkoutStat = fsImpl.lstatSync(checkoutRoot);+ if (checkoutStat.isSymbolicLink() || !checkoutStat.isDirectory()) {+ throw new Error(`Downloaded template checkout must be a real directory: ${checkoutRoot}`);+ }+ const canonicalCacheRoot = fsImpl.realpathSync(path.resolve(cacheRoot));+ const canonicalCheckoutRoot = fsImpl.realpathSync(checkoutRoot);+ if (!isPathInside(canonicalCacheRoot, canonicalCheckoutRoot)) {+ throw new Error(`Downloaded template checkout resolves outside the cache root: ${checkoutRoot}`);+ }+ fsImpl.rmSync(partialRoot, { recursive: true, force: true });+ } catch (err) {+ fsImpl.rmSync(partialRoot, { recursive: true, force: true });+ throw err;+ }+ return { localPath, cached: false };+}++function templateFamilyRoot({ catalogPath = DEFAULT_CATALOG_PATH, kind, templateId }) {+ if (!TEMPLATE_KINDS.has(kind)) throw new Error(`Unsupported template kind: ${kind}`);+ if (!ID_PATTERN.test(templateId || '')) throw new Error(`Invalid template id: ${templateId}`);+ return path.posix.join(catalogBasePath(catalogPath), kind, templateId);+}++function templateVariantRoot({ catalogPath = DEFAULT_CATALOG_PATH, kind, templateId, variant }) {+ const normalizedVariant = String(variant || '').toLowerCase();+ if (!FRAMEWORKS.has(normalizedVariant)) throw new Error(`Unsupported template variant: ${variant}`);+ return path.posix.join(+ templateFamilyRoot({ catalogPath, kind, templateId }),+ 'variants',+ normalizedVariant+ );+}++function compareCaseInsensitivePathNames(left, right) {+ const normalizedLeft = left.toLowerCase();+ const normalizedRight = right.toLowerCase();+ if (normalizedLeft < normalizedRight) return -1;+ if (normalizedLeft > normalizedRight) return 1;+ if (left < right) return -1;+ if (left > right) return 1;+ return 0;+}++function inspectTemplateSolutions(localSolutionsPath, kind, deps = {}) {+ const fsImpl = deps.fs || fs;+ if (!fsImpl.existsSync(localSolutionsPath)) {+ return { ok: false, error: 'Template is missing solutions/' };+ }+ const rootStat = fsImpl.lstatSync(localSolutionsPath);+ if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {+ return { ok: false, error: 'Template solutions/ must be a directory and not a symbolic link' };+ }++ const entries = fsImpl.readdirSync(localSolutionsPath, { withFileTypes: true })+ .sort((left, right) => compareCaseInsensitivePathNames(left.name, right.name));+ if (entries.length === 0) {+ return { ok: false, error: 'Template solutions/ must contain at least one solution' };+ }++ const seenUniqueNames = new Set();+ const solutions = [];+ for (const entry of entries) {+ if (!entry.isDirectory() || entry.isSymbolicLink()) {+ return { ok: false, error: `Template solutions/ contains a non-directory entry: ${entry.name}` };+ }+ const solutionPath = path.join(localSolutionsPath, entry.name);+ const solutionError = validateUnpackedSolutionDirectory(solutionPath, {+ ...deps,+ fs: fsImpl,+ allowWebsiteComponents: kind === 'traditional',+ });+ if (solutionError) return { ok: false, error: `${entry.name}: ${solutionError}` };++ const inspected = inspectSolutionDirectory(solutionPath, { ...deps, fs: fsImpl });+ if (!inspected.ok) return { ok: false, error: `${entry.name}: ${inspected.error}` };+ if (entry.name !== inspected.uniqueName) {+ return {+ ok: false,+ error: `Solution folder ${entry.name} must match the Solution.xml unique name ${inspected.uniqueName}`,+ };+ }+ const normalizedUniqueName = inspected.uniqueName.toLowerCase();+ if (seenUniqueNames.has(normalizedUniqueName)) {+ return { ok: false, error: `Template contains duplicate solution unique name: ${inspected.uniqueName}` };+ }+ seenUniqueNames.add(normalizedUniqueName);+ solutions.push({+ uniqueName: inspected.uniqueName,+ version: inspected.version,+ solutionPath,+ });+ }+ return { ok: true, solutions };+}++function inspectTemplateVariantDirectory(localVariantPath, kind, deps = {}) {+ const websiteCodePath = path.join(localVariantPath, 'website-code');+ const websiteCodeError = validateWebsiteCodeDirectory(websiteCodePath, { kind }, deps);+ if (websiteCodeError) return { ok: false, error: websiteCodeError };+ return {+ ok: true,+ websiteCodePath,+ };+}++function validateTemplateVariantDirectory(localVariantPath, kind, deps = {}) {+ const result = inspectTemplateVariantDirectory(localVariantPath, kind, deps);+ return result.ok ? null : result.error;+}++function downloadTemplateVariant(options = {}, deps = {}) {+ const { catalogPath = DEFAULT_CATALOG_PATH, kind, templateId, variant } = options;+ try {+ const familyRoot = templateFamilyRoot({ catalogPath, kind, templateId });+ const variantRoot = templateVariantRoot({ catalogPath, kind, templateId, variant });+ const solutionsRoot = path.posix.join(familyRoot, 'solutions');+ const variantResult = downloadRepositoryDirectory(+ { ...options, directoryPath: variantRoot },+ (localPath) => validateTemplateVariantDirectory(localPath, kind, deps),+ deps+ );+ const solutionsResult = downloadRepositoryDirectory(+ { ...options, directoryPath: solutionsRoot },+ (localPath) => {+ const inspected = inspectTemplateSolutions(localPath, kind, deps);+ return inspected.ok ? null : inspected.error;+ },+ deps+ );+ const inspectedVariant = inspectTemplateVariantDirectory(variantResult.localPath, kind, deps);+ if (!inspectedVariant.ok) throw new Error(inspectedVariant.error);+ const inspectedSolutions = inspectTemplateSolutions(solutionsResult.localPath, kind, deps);+ if (!inspectedSolutions.ok) throw new Error(inspectedSolutions.error);+ return {+ ok: true,+ variantPath: variantResult.localPath,+ websiteCodePath: inspectedVariant.websiteCodePath,+ solutions: inspectedSolutions.solutions,+ cached: variantResult.cached && solutionsResult.cached,+ };+ } catch (err) {+ return { ok: false, kind, templateId, variant, error: err.message };+ }+}++async function downloadSeedDataDirectory(options = {}, deps = {}) {+ const {+ owner = DEFAULT_OWNER,+ repo = DEFAULT_REPO,+ sha,+ seedDataPath,+ cacheRoot = getDefaultCacheRoot(),+ } = options;+ if (!sha) throw new Error('sha is required');+ assertValidSha(sha);+ if (!seedDataPath) return { ok: true, localDir: null, files: [] };+ if (path.isAbsolute(seedDataPath) || seedDataPath.split(/[\\/]+/).includes('..')) {+ return { ok: false, seedDataPath, error: `Seed data path must stay under templates: ${seedDataPath}` };+ }+ const fsImpl = deps.fs || fs;+ try {+ if (path.posix.extname(seedDataPath).toLowerCase() === '.json') {+ const seedFile = (await downloadArtifact({ owner, repo, sha, artifactPath: seedDataPath, cacheRoot }, deps)).localPath;+ const seedRoot = path.posix.dirname(seedDataPath);+ const parsed = JSON.parse(fsImpl.readFileSync(seedFile, 'utf8'));+ const attachmentPaths = collectSeedAttachmentPaths(parsed)+ .map((relativePath) => {+ if (path.posix.isAbsolute(relativePath) || relativePath.split(/[\\/]+/).includes('..')) {+ throw new Error(`Seed attachment path must stay under seed-data root: ${relativePath}`);+ }+ return `${seedRoot}/${relativePath.replace(/^\/+/, '')}`;+ })+ .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));+ const downloaded = [seedFile];+ for (const artifactPath of attachmentPaths) {+ downloaded.push((await downloadArtifact({ owner, repo, sha, artifactPath, cacheRoot }, deps)).localPath);+ }+ return {+ ok: true,+ localDir: path.dirname(seedFile),+ seedFile,+ files: downloaded,+ };+ }+ return { ok: false, seedDataPath, error: `Seed data path must point to a JSON file: ${seedDataPath}` };+ } catch (err) {+ return { ok: false, seedDataPath, error: err.message };+ }+}++function collectSeedAttachmentPaths(seedData) {+ const paths = new Set();+ for (const fileExport of Array.isArray(seedData.fileExports) ? seedData.fileExports : []) {+ if (fileExport && typeof fileExport.path === 'string' && fileExport.path.trim()) paths.add(fileExport.path);+ }+ for (const record of Array.isArray(seedData.records) ? seedData.records : []) {+ if (!record || typeof record !== 'object' || !record.__files || typeof record.__files !== 'object' || Array.isArray(record.__files)) {+ continue;+ }+ for (const value of Object.values(record.__files)) {+ if (typeof value === 'string' && value.trim()) paths.add(value);+ }+ }+ return [...paths];+}++module.exports = {+ DEFAULT_OWNER,+ DEFAULT_REPO,+ DEFAULT_REF,+ DEFAULT_CATALOG_PATH,+ getDefaultCacheRoot,+ ensurePrivateCacheRoot,+ buildRawUrl,+ buildGitRemoteUrl,+ cacheDirForSha,+ artifactCachePath,+ requestJson,+ downloadFile,+ resolveRefToSha,+ resolveLatestRelease,+ parseRemoteTags,+ resolveCatalogRef,+ fetchCatalog,+ validateZipContainsSolution,+ downloadArtifact,+ downloadTemplateVariant,+ downloadSeedDataDirectory,+ validateWebsiteCodeDirectory,+ validateUnpackedSolutionDirectory,+ repositoryDirectoryCheckoutRoot,+ templateFamilyRoot,+ templateVariantRoot,+ inspectTemplateSolutions,+ inspectTemplateVariantDirectory,+ validateTemplateVariantDirectory,+ validateCatalogShape,+ normalizeCatalogFamilies,+ isSpaTemplate,+ zipFileNames,+ assertValidSha,+};diff --git a/plugins/power-pages/scripts/lib/template-cli-args.js b/plugins/power-pages/scripts/lib/template-cli-args.jsnew file mode 100644index 000000000..e7d64d884--- /dev/null+++ b/plugins/power-pages/scripts/lib/template-cli-args.js@@ -0,0 +1,41 @@+'use strict';++function parseTemplateRepoArgs(argv, pathFlagName) {+ // Shared parser for argv arrays shaped like:+ // ['--owner','microsoft','--repo','power-pages-samples','--ref','main',+ // '--sha','<40-char sha>','--cacheRoot','/tmp/cache',+ // '--solutionPath','templates/spa/<id>/solution']+ // `pathFlagName` lets callers map a domain-specific path flag (for example+ // `--solutionPath`) to the shared `artifactPath` option used by the cache.+ const args = {};+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === '--owner') args.owner = argv[++i];+ else if (arg === '--repo') args.repo = argv[++i];+ else if (arg === '--ref') args.ref = argv[++i];+ else if (arg === '--sha') args.sha = argv[++i];+ else if (arg === '--cacheRoot') args.cacheRoot = argv[++i];+ else if (arg === pathFlagName) args.artifactPath = argv[++i];+ else if (arg === '--catalogPath') args.catalogPath = argv[++i];+ }+ return args;+}++function formatJsonResult(result) {+ return `${JSON.stringify(result, null, 2)}\n`;+}++async function runBestEffortJsonCli(handler, deps = {}) {+ const proc = deps.process || process;+ const stdout = deps.stdout || process.stdout;+ try {+ stdout.write(formatJsonResult(await handler()));+ } catch (err) {+ stdout.write(formatJsonResult({ ok: false, error: err.message }));+ }+ // Setting exitCode lets Node flush JSON when stdout is a pipe. process.exit()+ // can terminate before a larger catalog or variant payload is fully written.+ proc.exitCode = 0;+}++module.exports = { parseTemplateRepoArgs, formatJsonResult, runBestEffortJsonCli };diff --git a/plugins/power-pages/scripts/lib/template-import-context.js b/plugins/power-pages/scripts/lib/template-import-context.jsnew file mode 100644index 000000000..2e98892f7--- /dev/null+++ b/plugins/power-pages/scripts/lib/template-import-context.js@@ -0,0 +1,22 @@+'use strict';++const { getEnvironmentUrl, getAuthToken } = require('./validation-helpers');++function resolveTemplateImportContext(deps = {}) {+ const resolveEnv = deps.getEnvironmentUrl || getEnvironmentUrl;+ const resolveToken = deps.getAuthToken || getAuthToken;+ const environmentUrl = resolveEnv();+ if (!environmentUrl) {+ return { ok: false, error: 'PAC CLI is not authenticated to a Dataverse environment. Run `pac auth create --environment <url>` first.' };+ }+ const token = resolveToken(environmentUrl);+ if (!token) {+ return { ok: false, environmentUrl, error: 'Azure CLI token unavailable. Run `az login` first.' };+ }+ // Token availability is checked here, but the credential stays in-process.+ // Each authenticated helper reacquires it rather than exposing it in JSON,+ // shell history, process listings, or subagent prompts.+ return { ok: true, environmentUrl };+}++module.exports = { resolveTemplateImportContext };diff --git a/plugins/power-pages/scripts/lib/template-reinstall-policy.js b/plugins/power-pages/scripts/lib/template-reinstall-policy.jsnew file mode 100644index 000000000..56586d62c--- /dev/null+++ b/plugins/power-pages/scripts/lib/template-reinstall-policy.js@@ -0,0 +1,155 @@+'use strict';++const fs = require('fs');+const path = require('path');+const zlib = require('zlib');+const { compareVersions, parseVersionToSegments } = require('./bump-solution-version');++function decideReinstall({ installed, installedVersion, availableVersion, detectionFailed } = {}) {+ if (detectionFailed) return 'ask';+ if (!availableVersion) return 'ask';+ try {+ parseVersionToSegments(availableVersion);+ } catch {+ return 'ask';+ }+ if (!installed) return 'import';+ if (!installedVersion) return 'ask';+ try {+ if (compareVersions(availableVersion, installedVersion) > 0) return 'confirm-update';+ } catch {+ // PAC output and Solution.xml are external inputs. If either version is+ // malformed, keep the decision explicit instead of crashing the inspector.+ return 'ask';+ }+ return 'offer-clone';+}++function decodeZipEntry({ method, bytes }) {+ if (method === 0) return bytes;+ if (method === 8) return zlib.inflateRawSync(bytes);+ throw new Error(`Unsupported ZIP compression method for solution.xml: ${method}`);+}++function readEntryFromCentralDirectory(data, wantedName) {+ for (let i = 0; i <= data.length - 46; i++) {+ if (data.readUInt32LE(i) !== 0x02014b50) continue;+ const method = data.readUInt16LE(i + 10);+ const compressedSize = data.readUInt32LE(i + 20);+ const fileNameLength = data.readUInt16LE(i + 28);+ const extraLength = data.readUInt16LE(i + 30);+ const commentLength = data.readUInt16LE(i + 32);+ const localHeaderOffset = data.readUInt32LE(i + 42);+ const nameStart = i + 46;+ const nameEnd = nameStart + fileNameLength;+ if (nameEnd > data.length) continue;+ const name = data.subarray(nameStart, nameEnd).toString('utf8');+ if (name.toLowerCase() !== wantedName) {+ i = Math.max(i, nameEnd + extraLength + commentLength - 1);+ continue;+ }+ if (localHeaderOffset + 30 > data.length || data.readUInt32LE(localHeaderOffset) !== 0x04034b50) {+ throw new Error('solution.xml ZIP local header is missing or invalid');+ }+ const localNameLength = data.readUInt16LE(localHeaderOffset + 26);+ const localExtraLength = data.readUInt16LE(localHeaderOffset + 28);+ const dataStart = localHeaderOffset + 30 + localNameLength + localExtraLength;+ const dataEnd = dataStart + compressedSize;+ if (dataEnd > data.length) throw new Error('solution.xml ZIP entry is truncated');+ return decodeZipEntry({ method, bytes: data.subarray(dataStart, dataEnd) }).toString('utf8');+ }+ return null;+}++function readEntryFromLocalHeaders(data, wantedName) {+ for (let i = 0; i <= data.length - 30; i++) {+ if (data.readUInt32LE(i) !== 0x04034b50) continue;+ const method = data.readUInt16LE(i + 8);+ const compressedSize = data.readUInt32LE(i + 18);+ const fileNameLength = data.readUInt16LE(i + 26);+ const extraLength = data.readUInt16LE(i + 28);+ const nameStart = i + 30;+ const nameEnd = nameStart + fileNameLength;+ if (nameEnd > data.length) continue;+ const name = data.subarray(nameStart, nameEnd).toString('utf8');+ const dataStart = nameEnd + extraLength;+ const dataEnd = dataStart + compressedSize;+ if (name.toLowerCase() === wantedName) {+ if (compressedSize === 0 || dataEnd > data.length) throw new Error('solution.xml ZIP entry is truncated');+ return decodeZipEntry({ method, bytes: data.subarray(dataStart, dataEnd) }).toString('utf8');+ }+ i = Math.max(i, dataEnd - 1);+ }+ return null;+}++function readSolutionXml(zipPath, deps = {}) {+ // Dataverse solution zips contain a root `solution.xml` descriptor with:+ // <UniqueName>contoso_template</UniqueName>+ // <Version>1.0.0.0</Version>+ // <Managed>0</Managed>+ // Read it directly from ZIP headers instead of shelling out to `unzip`: Windows+ // plugin hosts often do not have that utility on PATH.+ const fsImpl = deps.fs || fs;+ const data = fsImpl.readFileSync(zipPath);+ const xml = readEntryFromCentralDirectory(data, 'solution.xml') || readEntryFromLocalHeaders(data, 'solution.xml');+ if (!xml) throw new Error('solution.xml not found in template solution zip');+ return xml;+}++function getTag(xml, tagName) {+ const match = String(xml || '').match(new RegExp(`<${tagName}>\\s*([^<]+?)\\s*</${tagName}>`, 'i'));+ return match ? match[1].trim() : null;+}++function inspectSolutionXml(xml) {+ const uniqueName = getTag(xml, 'UniqueName');+ const version = getTag(xml, 'Version');+ const managed = getTag(xml, 'Managed');+ if (!uniqueName || !version) {+ return { ok: false, error: 'solution.xml did not include UniqueName and Version' };+ }+ try {+ parseVersionToSegments(version);+ } catch {+ return {+ ok: false,+ error: 'solution.xml Version must contain one to four non-negative integer segments',+ };+ }+ return { ok: true, uniqueName, version, managed: managed === '1' };+}++function inspectSolutionZip(zipPath, deps = {}) {+ try {+ return inspectSolutionXml(deps.solutionXml || readSolutionXml(zipPath, deps));+ } catch (err) {+ return { ok: false, error: err.message };+ }+}++function inspectSolutionDirectory(solutionPath, deps = {}) {+ try {+ const fsImpl = deps.fs || fs;+ const rootStat = fsImpl.lstatSync(solutionPath);+ if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {+ return { ok: false, error: 'Template solution source must be a directory and not a symbolic link' };+ }+ const solutionXmlPath = path.join(solutionPath, 'Other', 'Solution.xml');+ const xmlStat = fsImpl.lstatSync(solutionXmlPath);+ if (!xmlStat.isFile() || xmlStat.isSymbolicLink()) {+ return { ok: false, error: 'Template solution source is missing Other/Solution.xml' };+ }+ return inspectSolutionXml(fsImpl.readFileSync(solutionXmlPath, 'utf8'));+ } catch (err) {+ return { ok: false, error: err.message };+ }+}++module.exports = {+ decideReinstall,+ inspectSolutionDirectory,+ inspectSolutionXml,+ inspectSolutionZip,+ readSolutionXml,+};diff --git a/plugins/power-pages/scripts/lib/validation-helpers.js b/plugins/power-pages/scripts/lib/validation-helpers.jsindex 4378c8c46..ca1596a23 100644--- a/plugins/power-pages/scripts/lib/validation-helpers.js+++ b/plugins/power-pages/scripts/lib/validation-helpers.js@@ -307,13 +307,25 @@ function validateBapPollingUrl(location, initiatingUrl, purpose = 'BAP Location* signing in via `az login --allow-no-subscriptions`.* @returns {string|null} Access token, or null if unavailable*/-function getAuthToken(resourceUrl) {+function runAzureCli(args, deps = {}) {+ const execFile = deps.execFile || execFileSync;+ const platform = deps.platform || process.platform;+ const options = { encoding: 'utf8', timeout: 15000, shell: false };+ if (platform === 'win32') {+ // Azure CLI is exposed as az.cmd on Windows. Route the fixed argument array+ // through cmd.exe because Node cannot execute .cmd shims directly.+ // See: https://nodejs.org/api/child_process.html#spawning-bat-and-cmd-files-on-windows+ return execFile('cmd.exe', ['/d', '/s', '/c', 'az.cmd', ...args], options);+ }+ return execFile('az', args, options);+}++function getAuthToken(resourceUrl, deps = {}) {try {const trustedResourceUrl = validateTokenResourceUrl(resourceUrl);- return execFileSync(- 'az',+ return runAzureCli(['account', 'get-access-token', '--resource', trustedResourceUrl, '--query', 'accessToken', '-o', 'tsv'],- { encoding: 'utf8', timeout: 15000, shell: false }+ deps).trim();} catch {return null;@@ -344,10 +356,30 @@ function parseEnvironmentUrl(whoOutput) {}}+function parseActiveAuthListEnvironmentUrl(authListOutput) {+ for (const line of String(authListOutput || '').split(/\r?\n/)) {+ if (!/^\s*\[\d+\]\s+\*/.test(line)) continue;+ const urls = line.match(/https:\/\/[^\s]+/gi) || [];+ const environmentUrl = urls[urls.length - 1];+ if (!environmentUrl) continue;+ try {+ return validateDataverseEnvironmentUrl(environmentUrl);+ } catch {+ return null;+ }+ }+ return null;+}+function getEnvironmentUrl() {try {const output = execSync('pac env who', { encoding: 'utf8', timeout: 15000 });- return parseEnvironmentUrl(output);+ const envUrl = parseEnvironmentUrl(output);+ if (envUrl) return envUrl;+ } catch {}++ try {+ return parseActiveAuthListEnvironmentUrl(execSync('pac auth list', { encoding: 'utf8', timeout: 15000 }));} catch {return null;}@@ -513,12 +545,14 @@ module.exports = {validateAuthenticatedRequestUrl,validateBapUrl,validateBapPollingUrl,+ runAzureCli,getAuthToken,makeRequest,odataGet,odataGetAll,getEnvironmentUrl,parseEnvironmentUrl,+ parseActiveAuthListEnvironmentUrl,getPacAuthInfo,CLOUD_TO_API,CLOUD_TO_SITE_DOMAIN,diff --git a/plugins/power-pages/scripts/open-url.js b/plugins/power-pages/scripts/open-url.jsnew file mode 100644index 000000000..348f66c50--- /dev/null+++ b/plugins/power-pages/scripts/open-url.js@@ -0,0 +1,31 @@+#!/usr/bin/env node+'use strict';++const { openInDefaultBrowser } = require('./lib/default-browser');++// Accepted argv shape:+// --url https://contoso.powerappsportals.com+// Missing or malformed URLs are reported as JSON so the skill can still show+// the URL to the user even if default-browser opening fails.+function parseArgs(argv) {+ const args = {};+ const idx = argv.indexOf('--url');+ if (idx !== -1) args.url = argv[idx + 1];+ return args;+}++function openUrl({ url }, deps = {}) {+ if (!url || !/^https?:\/\//i.test(url)) return { ok: false, error: 'Usage: open-url.js --url <http(s)-url>' };+ try {+ openInDefaultBrowser(url, deps);+ return { ok: true, url };+ } catch (err) {+ return { ok: false, url, error: err.message };+ }+}++if (require.main === module) {+ process.stdout.write(`${JSON.stringify(openUrl(parseArgs(process.argv.slice(2))), null, 2)}\n`);+}++module.exports = { parseArgs, openUrl };diff --git a/plugins/power-pages/scripts/pack-template-solution.js b/plugins/power-pages/scripts/pack-template-solution.jsnew file mode 100644index 000000000..95bf4606b--- /dev/null+++ b/plugins/power-pages/scripts/pack-template-solution.js@@ -0,0 +1,204 @@+#!/usr/bin/env node+'use strict';++const crypto = require('crypto');+const fs = require('fs');+const os = require('os');+const path = require('path');+const { commandError, runPac } = require('./lib/pac-command');+const {+ validateUnpackedSolutionDirectory,+ validateZipContainsSolution,+} = require('./lib/template-catalog');++const WORK_DIRECTORY_PREFIX = 'powerpages-template-solution-';++function parseArgs(argv) {+ const args = {};+ for (let i = 0; i < argv.length; i++) {+ if (argv[i] === '--solutionPath') args.solutionPath = argv[++i];+ else if (argv[i] === '--cleanup') args.cleanup = true;+ else if (argv[i] === '--workDirectory') args.workDirectory = argv[++i];+ else if (argv[i] === '--cleanupMarker') args.cleanupMarker = argv[++i];+ else if (argv[i] === '--cleanupToken') args.cleanupToken = argv[++i];+ }+ return args;+}++function isGeneratedWorkDirectoryPath(workDirectory, tmpRoot = os.tmpdir()) {+ const resolved = path.resolve(workDirectory || '');+ return path.dirname(resolved) === path.resolve(tmpRoot) &&+ new RegExp(`^${WORK_DIRECTORY_PREFIX}[A-Za-z0-9_-]{6,}$`).test(path.basename(resolved));+}++function createWorkDirectoryOwnership(workDirectory, deps = {}) {+ const fsImpl = deps.fs || fs;+ const tmpRoot = deps.tmpRoot || os.tmpdir();+ const randomBytes = deps.randomBytes || crypto.randomBytes;+ if (!isGeneratedWorkDirectoryPath(workDirectory, tmpRoot)) {+ throw new Error('workDirectory is not a generated template solution directory');+ }+ const workStat = fsImpl.lstatSync(workDirectory);+ if (workStat.isSymbolicLink() || !workStat.isDirectory()) {+ throw new Error('workDirectory is not a regular directory');+ }+ const canonicalWorkDirectory = fsImpl.realpathSync(workDirectory);+ const canonicalTmpRoot = fsImpl.realpathSync(tmpRoot);+ if (path.dirname(canonicalWorkDirectory) !== canonicalTmpRoot) {+ throw new Error('workDirectory resolves outside the temporary directory');+ }++ const cleanupToken = randomBytes(16).toString('hex');+ const cleanupMarker = path.join(+ path.resolve(tmpRoot),+ `.${WORK_DIRECTORY_PREFIX}${path.basename(workDirectory)}-${process.pid}-${cleanupToken}.json`+ );+ fsImpl.writeFileSync(+ cleanupMarker,+ JSON.stringify({ workDirectory: canonicalWorkDirectory, cleanupToken }),+ { encoding: 'utf8', flag: 'wx', mode: 0o600 }+ );+ return { cleanupMarker, cleanupToken };+}++function isOwnedWorkDirectory(workDirectory, deps = {}) {+ const fsImpl = deps.fs || fs;+ const tmpRoot = deps.tmpRoot || os.tmpdir();+ const { cleanupMarker, cleanupToken } = deps;+ try {+ if (!cleanupMarker || !cleanupToken || !isGeneratedWorkDirectoryPath(workDirectory, tmpRoot)) {+ return false;+ }+ const resolvedMarker = path.resolve(cleanupMarker);+ if (path.dirname(resolvedMarker) !== path.resolve(tmpRoot)) return false;+ const markerStat = fsImpl.lstatSync(resolvedMarker);+ if (markerStat.isSymbolicLink() || !markerStat.isFile()) return false;+ const canonicalTmpRoot = fsImpl.realpathSync(tmpRoot);+ if (path.dirname(fsImpl.realpathSync(resolvedMarker)) !== canonicalTmpRoot) return false;+ const ownership = JSON.parse(fsImpl.readFileSync(resolvedMarker, 'utf8'));+ if (ownership.cleanupToken !== cleanupToken) return false;++ const resolvedWorkDirectory = path.resolve(workDirectory);+ const expectedCanonicalWorkDirectory = path.join(canonicalTmpRoot, path.basename(resolvedWorkDirectory));+ if (ownership.workDirectory !== expectedCanonicalWorkDirectory) return false;+ if (!fsImpl.existsSync(resolvedWorkDirectory)) return true;+ const workStat = fsImpl.lstatSync(resolvedWorkDirectory);+ return workStat.isDirectory() &&+ !workStat.isSymbolicLink() &&+ fsImpl.realpathSync(resolvedWorkDirectory) === ownership.workDirectory;+ } catch {+ return false;+ }+}++function cleanupPackedTemplateSolution(workDirectory, deps = {}) {+ const fsImpl = deps.fs || fs;+ try {+ if (!isOwnedWorkDirectory(workDirectory, deps)) {+ return { ok: false, error: 'workDirectory ownership could not be verified' };+ }+ let removed = false;+ if (fsImpl.existsSync(workDirectory)) {+ fsImpl.rmSync(workDirectory, { recursive: true, force: true });+ removed = true;+ }+ fsImpl.rmSync(deps.cleanupMarker, { force: true });+ return { ok: true, removed };+ } catch (err) {+ return { ok: false, error: `Could not remove generated template solution directory: ${err.message}` };+ }+}++function failureWithCleanup(primaryFailure, workDirectory, ownership, deps = {}) {+ const cleanup = cleanupPackedTemplateSolution(workDirectory, { ...deps, ...ownership });+ if (cleanup.ok) return primaryFailure;+ return {+ ...primaryFailure,+ workDirectory,+ cleanupError: cleanup.error,+ };+}++function packTemplateSolution(options = {}, deps = {}) {+ const fsImpl = deps.fs || fs;+ if (!options.solutionPath) {+ return { ok: false, step: 'validation', error: 'solutionPath is required' };+ }+ const solutionPath = path.resolve(options.solutionPath);+ let validationError;+ try {+ validationError = validateUnpackedSolutionDirectory(solutionPath, { fs: fsImpl });+ } catch (err) {+ validationError = err.message;+ }+ if (validationError) {+ return { ok: false, step: 'validation', error: validationError };+ }++ const tmpRoot = deps.tmpRoot || os.tmpdir();+ const workDirectory = fsImpl.mkdtempSync(path.join(tmpRoot, WORK_DIRECTORY_PREFIX));+ let ownership;+ try {+ ownership = createWorkDirectoryOwnership(workDirectory, deps);+ } catch (err) {+ fsImpl.rmSync(workDirectory, { recursive: true, force: true });+ return { ok: false, step: 'work-directory', error: `Could not own generated template solution directory: ${err.message}` };+ }+ const zipPath = path.join(workDirectory, 'supporting-solution.zip');+ const pac = deps.runPac || ((args) => runPac(args, deps));+ const packResult = pac([+ 'solution', 'pack',+ '--zipfile', zipPath,+ '--folder', solutionPath,+ '--packagetype', 'Unmanaged',+ ]);+ if (packResult.status !== 0) {+ return failureWithCleanup(+ { ok: false, step: 'pack', error: commandError('pac solution pack', packResult) },+ workDirectory,+ ownership,+ { fs: fsImpl, tmpRoot }+ );+ }++ let validZip = false;+ if (isOwnedWorkDirectory(workDirectory, { fs: fsImpl, tmpRoot, ...ownership }) && fsImpl.existsSync(zipPath)) {+ const zipStat = fsImpl.lstatSync(zipPath);+ validZip = !zipStat.isSymbolicLink() &&+ zipStat.isFile() &&+ zipStat.size > 0 &&+ validateZipContainsSolution(zipPath, { fs: fsImpl });+ }+ if (!validZip) {+ return failureWithCleanup(+ { ok: false, step: 'output', error: 'pac solution pack did not create a valid solution zip' },+ workDirectory,+ ownership,+ { fs: fsImpl, tmpRoot }+ );+ }++ return { ok: true, solutionPath, zipPath, workDirectory, ...ownership };+}++function main() {+ const args = parseArgs(process.argv.slice(2));+ const result = args.cleanup+ ? cleanupPackedTemplateSolution(args.workDirectory, args)+ : packTemplateSolution(args);+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);+ if (!result.ok) process.exitCode = 1;+}++if (require.main === module) main();++module.exports = {+ WORK_DIRECTORY_PREFIX,+ cleanupPackedTemplateSolution,+ createWorkDirectoryOwnership,+ failureWithCleanup,+ isGeneratedWorkDirectoryPath,+ isOwnedWorkDirectory,+ packTemplateSolution,+ parseArgs,+};diff --git a/plugins/power-pages/scripts/poll-async-operation.js b/plugins/power-pages/scripts/poll-async-operation.jsindex 4add51a17..ae9e50433 100644--- a/plugins/power-pages/scripts/poll-async-operation.js+++ b/plugins/power-pages/scripts/poll-async-operation.js@@ -4,12 +4,11 @@// Reusable across export-solution and import-solution skills.//// Usage:-// node poll-async-operation.js --asyncJobId "<guid>" --envUrl "https://contoso.crm.dynamics.com" --token "<bearer-token>"+// node poll-async-operation.js --asyncJobId "<guid>" --envUrl "https://contoso.crm.dynamics.com"//// Optional:// --intervalMs <ms> Poll interval in milliseconds (default: 5000)// --maxAttempts <n> Maximum poll attempts (default: 60 = ~5 minutes at 5s)-// --tokenResource <url> Resource URL for token refresh (default: envUrl)//// Output (JSON to stdout):// { "status": "Succeeded", "asyncJobId": "...", "attempts": 12 }@@ -18,7 +17,12 @@// { "status": "Timeout", "asyncJobId": "...", "message": "Still running after N attempts" }// { "error": "..." } — when arguments are missing or network errors prevent polling-const { getAuthToken, makeRequest } = require('./lib/validation-helpers');+const fs = require('fs');+const {+ getAuthToken,+ makeRequest,+ validateDataverseEnvironmentUrl,+} = require('./lib/validation-helpers');function output(obj) {process.stdout.write(JSON.stringify(obj));@@ -31,7 +35,7 @@ function sleep(ms) {function parseArgs(argv) {const args = {};- const keys = ['--asyncJobId', '--envUrl', '--token', '--intervalMs', '--maxAttempts', '--tokenResource'];+ const keys = ['--asyncJobId', '--envUrl', '--intervalMs', '--maxAttempts', '--statusFile'];for (const key of keys) {const idx = argv.indexOf(key);if (idx !== -1 && idx + 1 < argv.length) {@@ -43,17 +47,26 @@ function parseArgs(argv) {const args = parseArgs(process.argv.slice(2));-if (!args.asyncJobId) output({ error: 'Missing required argument: --asyncJobId' });-if (!args.envUrl) output({ error: 'Missing required argument: --envUrl' });+function normalizeEnvUrl(value) {+ return String(value || '').replace(/\/+$/, '').replace(/\/api\/data\/v[0-9.]+$/i, '');+}-const envUrl = args.envUrl.replace(/\/+$/, '');-const intervalMs = parseInt(args.intervalMs || '5000', 10);-const maxAttempts = parseInt(args.maxAttempts || '60', 10);-const tokenResource = args.tokenResource || envUrl;+function normalizeAsyncJobId(value) {+ const match = String(value || '').match(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/);+ return match ? match[0].toLowerCase() : '';+}-// Token may be passed in directly (to avoid redundant az CLI calls) or refreshed each cycle-let token = args.token || null;-const tokenRefreshEvery = Math.max(1, Math.floor(60000 / intervalMs)); // refresh every ~60s+function parsePositiveInteger(value, fallback, flagName) {+ const raw = value === undefined || value === null || value === '' ? String(fallback) : String(value);+ if (!/^[1-9][0-9]*$/.test(raw)) {+ return { error: `Invalid ${flagName}: expected a positive integer` };+ }+ const parsed = Number(raw);+ if (!Number.isSafeInteger(parsed)) {+ return { error: `Invalid ${flagName}: expected a positive integer` };+ }+ return { value: parsed };+}// Dataverse asyncoperations statecode/statuscode reference:// statecode 0: Open (0=Ready, 20=InProgress, 30=Pausing, 40=Canceling)@@ -66,27 +79,64 @@ const SUCCESS_STATUSCODES = new Set([30]);const FAILURE_STATUSCODES = new Set([31]);const CANCELED_STATUSCODES = new Set([32]);-const pollUrl = `${envUrl}/api/data/v9.2/asyncoperations(${args.asyncJobId})?$select=statecode,statuscode,message,friendlymessage,errorcode`;+function writeStatus(statusFile, status) {+ if (!statusFile) return;+ try {+ fs.writeFileSync(statusFile, JSON.stringify({ updatedAt: new Date().toISOString(), ...status }, null, 2), 'utf8');+ } catch {+ // The status page is best-effort; polling must never fail because the user+ // closed a temp folder or the status file could not be updated.+ }+}++async function pollAsyncOperation(rawArgs, deps = {}) {+ if (!rawArgs.asyncJobId) return { error: 'Missing required argument: --asyncJobId' };+ if (!rawArgs.envUrl) return { error: 'Missing required argument: --envUrl' };-(async () => {- // Acquire initial token if not provided+ let envUrl;+ try {+ envUrl = validateDataverseEnvironmentUrl(normalizeEnvUrl(rawArgs.envUrl));+ } catch (err) {+ return { error: err.message };+ }+ const asyncJobId = normalizeAsyncJobId(rawArgs.asyncJobId);+ if (!asyncJobId) return { error: `Invalid async operation id: ${rawArgs.asyncJobId}` };+ const intervalResult = parsePositiveInteger(rawArgs.intervalMs, 5000, '--intervalMs');+ if (intervalResult.error) return intervalResult;+ const attemptsResult = parsePositiveInteger(rawArgs.maxAttempts, 60, '--maxAttempts');+ if (attemptsResult.error) return attemptsResult;+ const intervalMs = intervalResult.value;+ const maxAttempts = attemptsResult.value;+ const tokenResource = envUrl;+ const pollUrl = `${envUrl}/api/data/v9.2/asyncoperations(${asyncJobId})?$select=statecode,statuscode,message,friendlymessage,errorcode`;+ const getToken = deps.getAuthToken || getAuthToken;+ const request = deps.makeRequest || makeRequest;+ const wait = deps.sleep || sleep;++ let token = null;+ const tokenRefreshEvery = Math.max(1, Math.floor(60000 / intervalMs)); // refresh every ~60s++ token = getToken(tokenResource);if (!token) {- token = getAuthToken(tokenResource);- if (!token) {- output({ error: `Azure CLI token not available for ${tokenResource}. Run "az login" first.` });- }+ const error = `Azure CLI token not available for ${tokenResource}. Run "az login" first.`;+ writeStatus(rawArgs.statusFile, {+ state: 'failed',+ message: 'Template import status check failed. Check the agent terminal.',+ });+ return { error };}+ let lastHttpStatus = null;for (let attempt = 1; attempt <= maxAttempts; attempt++) {// Refresh token periodicallyif (attempt > 1 && attempt % tokenRefreshEvery === 0) {- const refreshed = getAuthToken(tokenResource);+ const refreshed = getToken(tokenResource);if (refreshed) token = refreshed;}let pollBody;try {- const result = await makeRequest({+ const result = await request({url: pollUrl,method: 'GET',headers: {@@ -99,25 +149,33 @@ const pollUrl = `${envUrl}/api/data/v9.2/asyncoperations(${args.asyncJobId})?$seif (result.error) {// Network error — wait and retry (don't fail on transient issues)- await sleep(intervalMs);+ writeStatus(rawArgs.statusFile, { state: 'running', message: 'Waiting for Dataverse import status', attempt });+ await wait(intervalMs);continue;}if (result.statusCode === 401) {// Auth expired mid-poll — refresh and retry immediately- const refreshed = getAuthToken(tokenResource);+ const refreshed = getToken(tokenResource);if (refreshed) token = refreshed;continue;}if (result.statusCode !== 200 || !result.body) {- await sleep(intervalMs);+ lastHttpStatus = result.statusCode;+ writeStatus(rawArgs.statusFile, {+ state: 'running',+ message: 'Waiting for Dataverse import status',+ detail: `Dataverse async operation lookup returned HTTP ${result.statusCode}`,+ attempt,+ });+ await wait(intervalMs);continue;}pollBody = JSON.parse(result.body);} catch {- await sleep(intervalMs);+ await wait(intervalMs);continue;}@@ -128,34 +186,46 @@ const pollUrl = `${envUrl}/api/data/v9.2/asyncoperations(${args.asyncJobId})?$seif (!TERMINAL_STATECODES.has(statecode)) {// Still running — wait and poll again- await sleep(intervalMs);+ writeStatus(rawArgs.statusFile, { state: 'running', message: friendlyMessage || message || 'Import is still running', attempt });+ await wait(intervalMs);continue;}// Terminal state reachedif (SUCCESS_STATUSCODES.has(statuscode)) {- output({ status: 'Succeeded', asyncJobId: args.asyncJobId, attempts: attempt });+ writeStatus(rawArgs.statusFile, { state: 'succeeded', message: 'Template import completed. Check the agent terminal for the next step.', attempt });+ return { status: 'Succeeded', asyncJobId, attempts: attempt };}if (CANCELED_STATUSCODES.has(statuscode)) {- output({ status: 'Canceled', asyncJobId: args.asyncJobId, message, attempts: attempt });+ writeStatus(rawArgs.statusFile, { state: 'canceled', message: message || 'Template import was canceled. Check the agent terminal.', attempt });+ return { status: 'Canceled', asyncJobId, message, attempts: attempt };}// Failed (statuscode 31 or unknown terminal)- output({+ writeStatus(rawArgs.statusFile, { state: 'failed', message: friendlyMessage || message || 'Template import failed. Check the agent terminal.', attempt });+ return {status: 'Failed',- asyncJobId: args.asyncJobId,+ asyncJobId,message,friendlyMessage,statuscode,attempts: attempt,- });+ };}// Timed out- output({+ writeStatus(rawArgs.statusFile, { state: 'timeout', message: 'Template import is still running. Check the agent terminal.', attempt: maxAttempts });+ return {status: 'Timeout',- asyncJobId: args.asyncJobId,+ asyncJobId,+ lastHttpStatus,message: `Async operation still running after ${maxAttempts} attempts (~${Math.round(maxAttempts * intervalMs / 60000)} minutes). Check operation status manually.`,- });-})();+ };+}++if (require.main === module) {+ pollAsyncOperation(args).then(output);+}++module.exports = { normalizeAsyncJobId, normalizeEnvUrl, parseArgs, parsePositiveInteger, pollAsyncOperation };diff --git a/plugins/power-pages/scripts/provision-template-site.js b/plugins/power-pages/scripts/provision-template-site.jsnew file mode 100644index 000000000..ac23490fb--- /dev/null+++ b/plugins/power-pages/scripts/provision-template-site.js@@ -0,0 +1,447 @@+#!/usr/bin/env node+'use strict';++const fs = require('fs');+const path = require('path');+const { execFileSync } = require('child_process');+const { commandError, runPac } = require('./lib/pac-command');+const { readWebsiteYml } = require('./lib/detect-project-context');++const GUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+const CLONED_IDENTITY_PATH = path.join('.powerpages-site', 'website.yml');++function parseArgs(argv) {+ const args = {};+ for (let i = 0; i < argv.length; i++) {+ if (argv[i] === '--sourcePath') args.sourcePath = argv[++i];+ else if (argv[i] === '--outputDirectory') args.outputDirectory = argv[++i];+ else if (argv[i] === '--siteName') args.siteName = argv[++i];+ }+ return args;+}++function findCodeSiteRoot(outputDirectory, fsImpl = fs) {+ const queue = [{ dir: outputDirectory, depth: 0 }];+ const matches = [];+ while (queue.length > 0) {+ const { dir, depth } = queue.shift();+ if (fsImpl.existsSync(path.join(dir, 'powerpages.config.json'))) matches.push(dir);+ if (depth >= 3) continue;+ for (const entry of fsImpl.readdirSync(dir, { withFileTypes: true })) {+ if (entry.isDirectory() && entry.name !== '.git' && entry.name !== 'node_modules') {+ queue.push({ dir: path.join(dir, entry.name), depth: depth + 1 });+ }+ }+ }+ if (matches.length !== 1) {+ throw new Error(`Expected one cloned code-site root under ${outputDirectory}, found ${matches.length}`);+ }+ return matches[0];+}++function inspectClonedSiteIdentity(clonedPath, deps = {}) {+ const readWebsite = deps.readWebsiteYml || readWebsiteYml;+ const websiteMetadataPath = path.join(clonedPath, '.powerpages-site', 'website.yml');+ const website = readWebsite(websiteMetadataPath);+ if (!website || !GUID_PATTERN.test(website.id || '')) {+ throw new Error(`Cloned site metadata is missing a valid id in ${websiteMetadataPath}`);+ }+ return {+ siteName: website.name || null,+ websiteRecordId: website.id,+ };+}++function copyMissingTemplateFiles(sourcePath, clonedPath, fsImpl = fs) {+ const restoredFiles = [];+ const queue = [''];+ while (queue.length > 0) {+ const relativeDir = queue.shift();+ const sourceDir = path.join(sourcePath, relativeDir);+ for (const entry of fsImpl.readdirSync(sourceDir, { withFileTypes: true })) {+ const relativePath = path.join(relativeDir, entry.name);+ if (relativePath === CLONED_IDENTITY_PATH) continue;+ const sourceEntryPath = path.join(sourcePath, relativePath);+ const clonedEntryPath = path.join(clonedPath, relativePath);+ const sourceStat = fsImpl.lstatSync(sourceEntryPath);+ if (sourceStat.isSymbolicLink()) {+ throw new Error(`Template source contains a symbolic link: ${relativePath}`);+ }++ if (sourceStat.isDirectory()) {+ if (fsImpl.existsSync(clonedEntryPath)) {+ const clonedStat = fsImpl.lstatSync(clonedEntryPath);+ if (clonedStat.isSymbolicLink() || !clonedStat.isDirectory()) {+ throw new Error(`Clone path conflicts with template directory: ${relativePath}`);+ }+ } else {+ fsImpl.mkdirSync(clonedEntryPath, { recursive: true });+ }+ queue.push(relativePath);+ continue;+ }++ if (!sourceStat.isFile()) {+ throw new Error(`Template source contains an unsupported entry: ${relativePath}`);+ }+ if (fsImpl.existsSync(clonedEntryPath)) {+ const clonedStat = fsImpl.lstatSync(clonedEntryPath);+ if (clonedStat.isSymbolicLink() || !clonedStat.isFile()) {+ throw new Error(`Clone path conflicts with template file: ${relativePath}`);+ }+ continue;+ }+ fsImpl.copyFileSync(sourceEntryPath, clonedEntryPath);+ restoredFiles.push(relativePath);+ }+ }+ return restoredFiles;+}++function runNpm(args, cwd, deps = {}) {+ const isWindows = (deps.platform || process.platform) === 'win32';+ // npm is installed as npm.cmd on Windows, and Node cannot execute .cmd files+ // directly with execFile. Route the fixed argument array through cmd.exe while+ // keeping shell:false so no user-controlled command string is reparsed.+ // See: https://nodejs.org/api/child_process.html#spawning-bat-and-cmd-files-on-windows+ const command = isWindows ? 'cmd.exe' : 'npm';+ const commandArgs = isWindows ? ['/d', '/s', '/c', 'npm.cmd', ...args] : args;+ const options = {+ cwd,+ encoding: 'utf8',+ timeout: deps.timeoutMs || 900000,+ maxBuffer: 10 * 1024 * 1024,+ shell: false,+ };+ try {+ const stdout = (deps.runNpmCommand || execFileSync)(command, commandArgs, options);+ return { status: 0, stdout: String(stdout || ''), stderr: '' };+ } catch (err) {+ return {+ status: Number.isInteger(err.status) ? err.status : 1,+ stdout: String(err.stdout || ''),+ stderr: String(err.stderr || ''),+ error: err,+ };+ }+}++function inspectCompiledOutput(clonedPath, fsImpl = fs) {+ const configPath = path.join(clonedPath, 'powerpages.config.json');+ let config;+ try {+ config = JSON.parse(fsImpl.readFileSync(configPath, 'utf8'));+ } catch (err) {+ throw new Error(`Could not read compiledPath from ${configPath}: ${err.message}`);+ }+ // Power Pages code sites declare build output as, for example, { "compiledPath": "dist" }.+ // Keep inspection inside the cloned project so a malformed template cannot make this+ // pre-upload check accept source files or follow an output directory outside the clone.+ const compiledPath = String(config.compiledPath || '').trim();+ if (!compiledPath || path.isAbsolute(compiledPath) || compiledPath.split(/[\\/]+/).includes('..')) {+ throw new Error(`powerpages.config.json has an invalid compiledPath: ${compiledPath || '<empty>'}`);+ }+ const outputPath = path.resolve(clonedPath, compiledPath);+ const resolvedClonedPath = path.resolve(clonedPath);+ if (outputPath === resolvedClonedPath) {+ throw new Error(`powerpages.config.json has an invalid compiledPath: ${compiledPath}`);+ }++ const clonedStat = fsImpl.lstatSync(resolvedClonedPath);+ if (clonedStat.isSymbolicLink() || !clonedStat.isDirectory()) {+ throw new Error(`Cloned project path is not a regular directory: ${resolvedClonedPath}`);+ }+ const canonicalClonedPath = fsImpl.realpathSync(resolvedClonedPath);+ let currentPath = resolvedClonedPath;+ for (const segment of compiledPath.split(/[\\/]+/)) {+ currentPath = path.join(currentPath, segment);+ if (!fsImpl.existsSync(currentPath)) {+ throw new Error(`Build output path is not a regular directory: ${outputPath}`);+ }+ const currentStat = fsImpl.lstatSync(currentPath);+ if (currentStat.isSymbolicLink() || !currentStat.isDirectory()) {+ throw new Error(`Build output path must contain only real directories: ${currentPath}`);+ }+ }+ const canonicalOutputPath = fsImpl.realpathSync(outputPath);+ if (!pathContains(canonicalClonedPath, canonicalOutputPath)) {+ throw new Error(`Build output path resolves outside the cloned project: ${outputPath}`);+ }++ const queue = [outputPath];+ let containsFile = false;+ while (queue.length > 0) {+ const current = queue.shift();+ for (const entry of fsImpl.readdirSync(current, { withFileTypes: true })) {+ const entryPath = path.join(current, entry.name);+ if (entry.isSymbolicLink()) {+ throw new Error(`Build output must not contain symbolic links: ${entryPath}`);+ }+ if (entry.isFile()) {+ containsFile = true;+ } else if (entry.isDirectory()) {+ queue.push(entryPath);+ } else {+ throw new Error(`Build output contains an unsupported entry: ${entryPath}`);+ }+ }+ }+ if (containsFile) return { compiledPath, outputPath };+ throw new Error(`Build output directory is empty: ${outputPath}`);+}++function canonicalPathForCreation(targetPath, fsImpl = fs) {+ let current = path.resolve(targetPath);+ const missingSegments = [];+ while (!fsImpl.existsSync(current)) {+ const parent = path.dirname(current);+ if (parent === current) break;+ missingSegments.unshift(path.basename(current));+ current = parent;+ }+ const canonicalParent = fsImpl.realpathSync(current);+ return path.join(canonicalParent, ...missingSegments);+}++function pathContains(parentPath, childPath, platform = process.platform) {+ const normalize = (value) => {+ const resolved = path.resolve(value);+ return platform === 'win32' ? resolved.toLowerCase() : resolved;+ };+ const parent = normalize(parentPath);+ const child = normalize(childPath);+ return child === parent || child.startsWith(parent + path.sep);+}++function validateSeparateProjectPaths(sourcePath, outputDirectory, deps = {}) {+ const fsImpl = deps.fs || fs;+ const platform = deps.platform || process.platform;+ try {+ const sourceStat = fsImpl.lstatSync(sourcePath);+ if (!sourceStat.isDirectory() || sourceStat.isSymbolicLink()) {+ return 'sourcePath must be a regular directory';+ }+ const canonicalSource = fsImpl.realpathSync(sourcePath);+ const canonicalOutput = canonicalPathForCreation(outputDirectory, fsImpl);+ if (+ pathContains(canonicalSource, canonicalOutput, platform) ||+ pathContains(canonicalOutput, canonicalSource, platform)+ ) {+ return 'outputDirectory must be separate from sourcePath';+ }+ } catch (err) {+ return `Could not validate sourcePath and outputDirectory: ${err.message}`;+ }+ return null;+}++function removeScriptCreatedOutputDirectory(outputDirectory, existedBeforeRun, fsImpl = fs) {+ if (existedBeforeRun || !fsImpl.existsSync(outputDirectory)) return false;+ try {+ // PAC may have written partial content before failing. Remove only a root+ // this invocation created, and refuse if another process replaced it with+ // a symlink or non-directory entry.+ const outputStat = fsImpl.lstatSync(outputDirectory);+ if (outputStat.isSymbolicLink() || !outputStat.isDirectory()) return false;+ fsImpl.rmSync(outputDirectory, { recursive: true, force: true });+ return true;+ } catch {+ return false;+ }+}++function provisionTemplateSite(options, deps = {}) {+ const fsImpl = deps.fs || fs;+ const sourcePath = path.resolve(options.sourcePath || '');+ const outputDirectory = path.resolve(options.outputDirectory || '');+ const siteName = String(options.siteName || '').trim();+ const sourceNpmConfigPath = path.join(sourcePath, '.npmrc');+ if (!options.sourcePath || !options.outputDirectory || !siteName) {+ return { ok: false, step: 'validation', error: 'sourcePath, outputDirectory, and siteName are required' };+ }+ if (!fsImpl.existsSync(path.join(sourcePath, 'powerpages.config.json')) ||+ !fsImpl.existsSync(path.join(sourcePath, 'package.json')) ||+ !fsImpl.existsSync(sourceNpmConfigPath) ||+ !fsImpl.existsSync(path.join(sourcePath, '.powerpages-site'))) {+ return { ok: false, step: 'validation', error: 'sourcePath is not a downloaded Power Pages code site' };+ }+ let sourceNpmConfigStat;+ try {+ sourceNpmConfigStat = fsImpl.lstatSync(sourceNpmConfigPath);+ } catch (err) {+ return { ok: false, step: 'validation', error: `Could not inspect sourcePath .npmrc: ${err.message}` };+ }+ if (sourceNpmConfigStat.isSymbolicLink() || !sourceNpmConfigStat.isFile()) {+ return { ok: false, step: 'validation', error: 'sourcePath .npmrc must be a regular file' };+ }+ const separationError = validateSeparateProjectPaths(sourcePath, outputDirectory, deps);+ if (separationError) return { ok: false, step: 'validation', error: separationError };+ const outputDirectoryExisted = fsImpl.existsSync(outputDirectory);+ if (outputDirectoryExisted) {+ let outputStat;+ try {+ outputStat = fsImpl.lstatSync(outputDirectory);+ } catch (err) {+ return { ok: false, step: 'validation', error: `Could not inspect outputDirectory: ${err.message}` };+ }+ if (outputStat.isSymbolicLink() || !outputStat.isDirectory()) {+ return { ok: false, step: 'validation', error: 'outputDirectory must be a regular directory when it exists' };+ }+ try {+ if (fsImpl.readdirSync(outputDirectory).length > 0) {+ return { ok: false, step: 'validation', error: 'outputDirectory must be empty' };+ }+ } catch (err) {+ return { ok: false, step: 'validation', error: `Could not read outputDirectory: ${err.message}` };+ }+ }+ fsImpl.mkdirSync(outputDirectory, { recursive: true });++ let pacWorkingDirectory;+ try {+ // `pac pages clone --overwrite` can replace the selected output directory.+ // When that directory is also the wrapper's inherited CWD, later PAC calls+ // can fail because the process still holds a stale directory handle. Run+ // every PAC command from the canonical parent, which clone never replaces.+ pacWorkingDirectory = fsImpl.realpathSync(path.dirname(outputDirectory));+ } catch (err) {+ return { ok: false, step: 'validation', error: `Could not resolve a stable PAC working directory: ${err.message}` };+ }+ const pacCommandOptions = { cwd: pacWorkingDirectory };+ const pac = deps.runPac || ((args, commandOptions = {}) => runPac(args, { ...deps, ...commandOptions }));+ const cloneResult = pac([+ 'pages', 'clone',+ '--path', sourcePath,+ '--outputDirectory', outputDirectory,+ '--name', siteName,+ '--overwrite',+ ], pacCommandOptions);+ if (cloneResult.status !== 0) {+ return {+ ok: false,+ step: 'clone',+ outputDirectoryRemoved: removeScriptCreatedOutputDirectory(outputDirectory, outputDirectoryExisted, fsImpl),+ error: commandError('pac pages clone', cloneResult),+ };+ }++ let clonedPath;+ try {+ clonedPath = findCodeSiteRoot(outputDirectory, fsImpl);+ } catch (err) {+ return {+ ok: false,+ step: 'clone-output',+ outputDirectoryRemoved: removeScriptCreatedOutputDirectory(outputDirectory, outputDirectoryExisted, fsImpl),+ error: err.message,+ };+ }++ let clonedIdentity;+ try {+ clonedIdentity = inspectClonedSiteIdentity(clonedPath, deps);+ } catch (err) {+ return { ok: false, step: 'clone-output', clonedPath, error: err.message };+ }+ try {+ // `pac pages clone` reconstructs a known code-site file set and can omit+ // valid project extras such as .npmrc, tests, and imported JSON contracts.+ // Restore only missing source files so the clone's new website identity and+ // any files rewritten by PAC remain authoritative.+ copyMissingTemplateFiles(sourcePath, clonedPath, fsImpl);+ } catch (err) {+ return {+ ok: false,+ step: 'clone-output',+ clonedPath,+ ...clonedIdentity,+ error: `Could not restore template project files: ${err.message}`,+ };+ }++ const npm = deps.runNpm || ((args, cwd) => runNpm(args, cwd, deps));+ const installArgs = [+ fsImpl.existsSync(path.join(clonedPath, 'package-lock.json')) ? 'ci' : 'install',+ '--no-audit',+ '--no-fund',+ ];+ const installResult = npm(installArgs, clonedPath);+ if (installResult.status !== 0) {+ return {+ ok: false,+ step: 'install',+ clonedPath,+ ...clonedIdentity,+ error: commandError(`npm ${installArgs[0]}`, installResult),+ };+ }++ const buildResult = npm(['run', 'build'], clonedPath);+ if (buildResult.status !== 0) {+ return {+ ok: false,+ step: 'build',+ clonedPath,+ ...clonedIdentity,+ error: commandError('npm run build', buildResult),+ };+ }++ let compiledOutput;+ try {+ compiledOutput = inspectCompiledOutput(clonedPath, fsImpl);+ } catch (err) {+ return {+ ok: false,+ step: 'build-output',+ clonedPath,+ ...clonedIdentity,+ error: err.message,+ };+ }++ const uploadResult = pac([+ 'pages', 'upload-code-site',+ '--rootPath', clonedPath,+ '--siteName', siteName,+ ], pacCommandOptions);+ if (uploadResult.status !== 0) {+ return {+ ok: false,+ step: 'upload',+ clonedPath,+ ...clonedIdentity,+ error: commandError('pac pages upload-code-site', uploadResult),+ };+ }+ return {+ ok: true,+ clonedPath,+ siteName: clonedIdentity.siteName || siteName,+ websiteRecordId: clonedIdentity.websiteRecordId,+ compiledPath: compiledOutput.compiledPath,+ };+}++function main() {+ const result = provisionTemplateSite(parseArgs(process.argv.slice(2)));+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);+ if (!result.ok) process.exit(1);+}++if (require.main === module) main();++module.exports = {+ commandError,+ copyMissingTemplateFiles,+ findCodeSiteRoot,+ inspectCompiledOutput,+ inspectClonedSiteIdentity,+ parseArgs,+ pathContains,+ provisionTemplateSite,+ removeScriptCreatedOutputDirectory,+ runNpm,+ runPac,+ validateSeparateProjectPaths,+};diff --git a/plugins/power-pages/scripts/render-template-browser.js b/plugins/power-pages/scripts/render-template-browser.jsnew file mode 100644index 000000000..b9e8cab71--- /dev/null+++ b/plugins/power-pages/scripts/render-template-browser.js@@ -0,0 +1,208 @@+#!/usr/bin/env node+'use strict';++const fs = require('fs');+const path = require('path');+const { renderTemplate, escapeHtml, escapeHtmlAttribute } = require('./lib/render-template');+const { openInDefaultBrowser } = require('./lib/default-browser');++// Accepted argv shape:+// --templatesJsonPath /tmp/templates.json --outputPath /tmp/browser.html [--open]+// `--open` is a boolean switch; the JSON file must contain+// `{ "TEMPLATES_JSON": [ ...manifest entries with absolute preview image URLs... ] }`.+function parseArgs(argv) {+ const args = { open: false };+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === '--templatesJsonPath') args.templatesJsonPath = argv[++i];+ else if (arg === '--outputPath') args.outputPath = argv[++i];+ else if (arg === '--open') args.open = true;+ }+ return args;+}++function openFileInDefaultBrowser(filePath, deps = {}) {+ openInDefaultBrowser(filePath, deps);+}++function renderKeywordChips(keywords) {+ const items = Array.isArray(keywords) ? keywords : [];+ if (items.length === 0) return '<span class="muted">No keywords listed</span>';+ return items.map((item) => `<span class="chip">${escapeHtml(item)}</span>`).join('');+}++function renderPreviewImages(template) {+ const images = Array.isArray(template.previewImages) ? template.previewImages : [];+ if (images.length === 0) {+ return '<div class="preview-empty">No preview image yet</div>';+ }+ return images.map((image, imageIndex) => `+ <figure class="preview-boundary">+ <figcaption>Preview ${imageIndex + 1}</figcaption>+ <img class="preview-image" src="${escapeHtmlAttribute(image)}" alt="Preview ${imageIndex + 1} of ${escapeHtmlAttribute(template.displayName)}" loading="lazy" />+ </figure>+ `).join('');+}++function frameworkLabel(framework) {+ if (!framework) return '';+ return String(framework).slice(0, 1).toUpperCase() + String(framework).slice(1);+}++// The catalog manifest defines `variants` as an object map keyed by framework+// (e.g. { "react": { ... } }), but some inputs may already pass an array of+// { framework, ... } entries. Normalize both shapes to a single array so the+// hero label and the chip row stay in sync.+// See templates/manifest.json (variants object) in microsoft/power-pages-samples.+function normalizeVariants(template) {+ if (Array.isArray(template.variants)) return template.variants;+ return Object.entries(template.variants || {}).map(([framework, variant]) => ({ framework, ...variant }));+}++function frameworkSummaryLabel(template) {+ const frameworks = normalizeVariants(template)+ .map((variant) => variant.framework)+ .filter(Boolean);+ if (frameworks.length > 1) return `${frameworks.length} frameworks`;+ if (frameworks.length === 1) return frameworkLabel(frameworks[0]);+ // Fall back to a legacy top-level `framework` field when no variants exist.+ return frameworkLabel(template.framework);+}++function renderFrameworkVariants(template) {+ const variants = normalizeVariants(template);+ const frameworks = variants.length > 0 ? variants.map((variant) => variant.framework) : [template.framework].filter(Boolean);+ if (frameworks.length === 0) return '';+ return `+ <div class="template-meta">+ <div class="field-label">Available frameworks</div>+ <div class="chip-row">${frameworks.map((framework) => `<span class="chip chip-framework">${escapeHtml(frameworkLabel(framework))}</span>`).join('')}</div>+ </div>+ `;+}++function templateTabId(index) {+ return `template-${index + 1}`;+}++function renderTemplateTabsHtml(templates) {+ if (!Array.isArray(templates) || templates.length === 0) {+ return '<div class="nav-btn active"><span class="nav-icon">◉</span> No templates</div>';+ }+ return templates.map((template, index) => `+ <button class="nav-btn${index === 0 ? ' active' : ''}" type="button" data-tab="${templateTabId(index)}">+ <span class="nav-icon">◉</span>+ ${escapeHtml(template.displayName)}+ </button>+ `).join('');+}++function renderTemplateSectionsHtml(templates) {+ if (!Array.isArray(templates) || templates.length === 0) {+ return '<div class="empty-note">No templates are available right now.</div>';+ }+ return templates.map((template, index) => `+ <section class="template-section${index === 0 ? ' active' : ''}" id="${templateTabId(index)}">+ <div class="template-hero">+ <h2>${escapeHtml(template.displayName)}</h2>+ <div class="template-framework">${escapeHtml(frameworkSummaryLabel(template))}</div>+ </div>+ ${renderFrameworkVariants(template)}+ <div class="template-meta">+ <div class="field-label">Keywords</div>+ <div class="chip-row">${renderKeywordChips(template.keywords)}</div>+ </div>+ <p class="template-desc">${escapeHtml(template.description)}</p>+ <div class="field-label previews-label">Previews</div>+ <div class="preview-stack">+ ${renderPreviewImages(template)}+ </div>+ </section>+ `).join('');+}++function expectedFrameworks(template) {+ const variants = normalizeVariants(template);+ const frameworks = variants.length > 0 ? variants.map((variant) => variant.framework) : [template.framework].filter(Boolean);+ return frameworks.map(frameworkLabel).filter(Boolean);+}++function validateRenderedTemplateBrowser({ templates, html }) {+ const errors = [];+ const items = Array.isArray(templates) ? templates : [];+ if (items.length === 0) {+ errors.push('TEMPLATES_JSON must contain at least one template family before opening the browser preview');+ }+ if (/No templates are available right now/i.test(html || '')) {+ errors.push('Rendered template browser contains the empty-state message');+ }+ items.forEach((template, index) => {+ const displayName = escapeHtml(template.displayName);+ if (!displayName || !html.includes(displayName)) {+ errors.push(`Rendered template browser is missing template ${index + 1} displayName`);+ }+ for (const framework of expectedFrameworks(template)) {+ if (!html.includes(escapeHtml(framework))) {+ errors.push(`Rendered template browser is missing framework ${framework} for ${template.displayName || `template ${index + 1}`}`);+ }+ }+ });+ return { ok: errors.length === 0, errors };+}++function renderTemplateBrowser({ templatesJsonPath, outputPath, open = false }, deps = {}) {+ if (!templatesJsonPath || !outputPath) {+ throw new Error('Usage: render-template-browser.js --templatesJsonPath <path> --outputPath <path> [--open]');+ }+ const fsImpl = deps.fs || fs;+ const templatePath = path.join(__dirname, '..', 'skills', 'create-site', 'assets', 'template-browser.html');+ const data = JSON.parse(fsImpl.readFileSync(templatesJsonPath, 'utf8'));+ const templates = Array.isArray(data.TEMPLATES_JSON) ? data.TEMPLATES_JSON : [];+ renderTemplate({+ templatePath,+ outputPath,+ dataObject: {+ TEMPLATE_COUNT: String(templates.length),+ TEMPLATE_TABS_HTML: renderTemplateTabsHtml(templates),+ TEMPLATE_SECTIONS_HTML: renderTemplateSectionsHtml(templates),+ },+ requiredKeys: ['TEMPLATE_COUNT', 'TEMPLATE_TABS_HTML', 'TEMPLATE_SECTIONS_HTML'],+ emitStatus: false,+ });+ const validation = validateRenderedTemplateBrowser({ templates, html: fsImpl.readFileSync(outputPath, 'utf8') });+ if (!validation.ok) {+ return { status: 'invalid', output: outputPath, opened: false, validation };+ }+ let openError = null;+ if (open) {+ try {+ openFileInDefaultBrowser(outputPath, deps);+ } catch (err) {+ openError = err.message;+ }+ }+ return { status: 'ok', output: outputPath, opened: Boolean(open && !openError), ...(openError ? { openError } : {}) };+}++function main() {+ try {+ const result = renderTemplateBrowser(parseArgs(process.argv.slice(2)));+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);+ } catch (err) {+ process.stderr.write(`${err.message}\n`);+ process.exit(1);+ }+}++if (require.main === module) {+ main();+}++module.exports = {+ parseArgs,+ openFileInDefaultBrowser,+ renderTemplateBrowser,+ renderTemplateTabsHtml,+ renderTemplateSectionsHtml,+ validateRenderedTemplateBrowser,+};diff --git a/plugins/power-pages/scripts/render-template-import-status.js b/plugins/power-pages/scripts/render-template-import-status.jsnew file mode 100644index 000000000..eacad312a--- /dev/null+++ b/plugins/power-pages/scripts/render-template-import-status.js@@ -0,0 +1,142 @@+#!/usr/bin/env node+'use strict';++const fs = require('fs');+const path = require('path');+const { fileURLToPath, pathToFileURL } = require('url');+const { renderTemplate } = require('./lib/render-template');+const { openInDefaultBrowser } = require('./lib/default-browser');++const LOCAL_PREVIEW_SIGNATURES = {+ '.png': Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),+ '.jpg': Buffer.from([0xff, 0xd8, 0xff]),+ '.jpeg': Buffer.from([0xff, 0xd8, 0xff]),+};++function parseArgs(argv) {+ const args = { open: false, previewImages: [], solutionCount: 1 };+ for (let i = 0; i < argv.length; i++) {+ if (argv[i] === '--templateName') args.templateName = argv[++i];+ else if (argv[i] === '--statusPath') args.statusPath = argv[++i];+ else if (argv[i] === '--outputPath') args.outputPath = argv[++i];+ else if (argv[i] === '--previewImagesJson') args.previewImages = JSON.parse(argv[++i] || '[]');+ else if (argv[i] === '--solutionCount') args.solutionCount = Number(argv[++i]);+ else if (argv[i] === '--open') args.open = true;+ }+ return args;+}++function previewImageUrl(input, index, outputDir) {+ if (typeof input !== 'string' || !input.trim()) return null;+ if (/^https?:\/\//i.test(input)) return input;+ let sourcePath;+ try {+ sourcePath = input.startsWith('file://') ? fileURLToPath(input) : path.resolve(input);+ } catch {+ // A manifest or test fixture can contain a file URL that is not valid for the+ // current OS, e.g. `file:///tmp/a.png` when running on Windows. Leave it as-is+ // instead of failing the render; valid local file URLs are still copied below.+ return input;+ }+ if (!fs.existsSync(sourcePath)) return input;+ const ext = path.extname(sourcePath).toLowerCase();+ const signature = LOCAL_PREVIEW_SIGNATURES[ext];+ let stat;+ let prefix;+ try {+ stat = fs.lstatSync(sourcePath);+ if (!signature || stat.isSymbolicLink() || !stat.isFile()) return null;+ const handle = fs.openSync(sourcePath, 'r');+ try {+ prefix = Buffer.alloc(signature.length);+ const bytesRead = fs.readSync(handle, prefix, 0, prefix.length, 0);+ if (bytesRead !== signature.length || !prefix.equals(signature)) return null;+ } finally {+ fs.closeSync(handle);+ }+ } catch {+ return null;+ }+ const previewsDir = path.join(outputDir, 'preview-images');+ const destName = `preview-${String(index + 1).padStart(2, '0')}${ext}`;+ const destPath = path.join(previewsDir, destName);+ fs.mkdirSync(previewsDir, { recursive: true });+ // The status page is served over localhost so it can poll status.json. Browsers+ // do not reliably load file:// or absolute filesystem image paths from that+ // HTTP origin, so copy local preview assets beside the page and reference them+ // by relative URL instead.+ fs.copyFileSync(sourcePath, destPath);+ return `preview-images/${destName}`;+}++function localizePreviewImages(previewImages, outputPath) {+ const outputDir = path.dirname(path.resolve(outputPath));+ return previewImages+ .map((image, index) => previewImageUrl(image, index, outputDir))+ .filter(Boolean);+}++function jsonForScript(value) {+ return JSON.stringify(value).replace(/</g, '\\u003c');+}++function renderTemplateImportStatus({+ templateName,+ statusPath,+ outputPath,+ previewImages = [],+ solutionCount = 1,+ open = false,+}, deps = {}) {+ if (!templateName || !statusPath || !outputPath) {+ throw new Error('Usage: render-template-import-status.js --templateName <name> --statusPath <path> --outputPath <path> [--previewImagesJson <json>] [--solutionCount <count>] [--open]');+ }+ if (!Number.isSafeInteger(solutionCount) || solutionCount < 1) {+ throw new Error('solutionCount must be a positive integer');+ }+ const pluralSolutions = solutionCount > 1;+ const templatePath = path.join(__dirname, '..', 'skills', 'create-site', 'assets', 'template-import-status.html');+ const statusUrl = path.dirname(path.resolve(statusPath)) === path.dirname(path.resolve(outputPath))+ ? path.basename(statusPath)+ : pathToFileURL(path.resolve(statusPath)).href;+ renderTemplate({+ templatePath,+ outputPath,+ dataObject: {+ TEMPLATE_NAME: templateName,+ STATUS_URL: statusUrl,+ PREVIEW_IMAGES: localizePreviewImages(previewImages, outputPath),+ SOLUTION_INSTALLING_LABEL: pluralSolutions ? 'Installing solutions' : 'Installing solution',+ SOLUTION_INSTALLED_LABEL: pluralSolutions ? 'Solutions installed' : 'Solution installed',+ SOLUTION_NOUN: pluralSolutions ? 'solutions' : 'solution',+ },+ requiredKeys: [+ 'TEMPLATE_NAME',+ 'STATUS_URL',+ 'PREVIEW_IMAGES',+ 'SOLUTION_INSTALLING_LABEL',+ 'SOLUTION_INSTALLED_LABEL',+ 'SOLUTION_NOUN',+ ],+ emitStatus: false,+ });+ if (open) {+ try {+ (deps.openInDefaultBrowser || openInDefaultBrowser)(outputPath, deps);+ } catch {}+ }+ return { status: 'ok', output: outputPath, statusPath };+}++function main() {+ try {+ process.stdout.write(`${JSON.stringify(renderTemplateImportStatus(parseArgs(process.argv.slice(2))), null, 2)}\n`);+ } catch (err) {+ process.stderr.write(`${err.message}\n`);+ process.exit(1);+ }+}++if (require.main === module) main();++module.exports = { jsonForScript, localizePreviewImages, parseArgs, renderTemplateImportStatus };diff --git a/plugins/power-pages/scripts/resolve-template-import-context.js b/plugins/power-pages/scripts/resolve-template-import-context.jsnew file mode 100644index 000000000..22ce2346e--- /dev/null+++ b/plugins/power-pages/scripts/resolve-template-import-context.js@@ -0,0 +1,7 @@+#!/usr/bin/env node+'use strict';++const { resolveTemplateImportContext } = require('./lib/template-import-context');+const { formatJsonResult } = require('./lib/template-cli-args');++process.stdout.write(formatJsonResult(resolveTemplateImportContext()));diff --git a/plugins/power-pages/scripts/serve-static-dir.js b/plugins/power-pages/scripts/serve-static-dir.jsnew file mode 100644index 000000000..8072ee4ec--- /dev/null+++ b/plugins/power-pages/scripts/serve-static-dir.js@@ -0,0 +1,447 @@+#!/usr/bin/env node+'use strict';++const fs = require('fs');+const crypto = require('crypto');+const http = require('http');+const net = require('net');+const os = require('os');+const path = require('path');+const { fork } = require('child_process');++const DEFAULT_READY_TIMEOUT_MS = 5000;+const DEFAULT_IDLE_TIMEOUT_MS = 120000;+const DEFAULT_MAX_LIFETIME_MS = 3600000;+const DEFAULT_SUCCESS_GRACE_MS = 30000;+const DEFAULT_STATUS_POLL_MS = 500;++function parseArgs(argv = process.argv.slice(2)) {+ const args = { host: '127.0.0.1' };+ for (let i = 0; i < argv.length; i++) {+ if (argv[i] === '--root') args.root = argv[++i];+ else if (argv[i] === '--urlFile') args.urlFile = argv[++i];+ else if (argv[i] === '--host') args.host = argv[++i];+ else if (argv[i] === '--port') args.port = Number(argv[++i]);+ else if (argv[i] === '--statusPath') args.statusPath = argv[++i];+ else if (argv[i] === '--readyTimeoutMs') args.readyTimeoutMs = Number(argv[++i]);+ else if (argv[i] === '--idleTimeoutMs') args.idleTimeoutMs = Number(argv[++i]);+ else if (argv[i] === '--maxLifetimeMs') args.maxLifetimeMs = Number(argv[++i]);+ else if (argv[i] === '--successGraceMs') args.successGraceMs = Number(argv[++i]);+ else if (argv[i] === '--statusPollMs') args.statusPollMs = Number(argv[++i]);+ else if (argv[i] === '--cleanupMarker') args.cleanupMarker = argv[++i];+ else if (argv[i] === '--cleanupToken') args.cleanupToken = argv[++i];+ else if (argv[i] === '--cleanupRoot') args.cleanupRoot = true;+ else if (argv[i] === '--child') args.child = true;+ }+ return args;+}++function contentType(filePath) {+ const ext = path.extname(filePath).toLowerCase();+ if (ext === '.html') return 'text/html; charset=utf-8';+ if (ext === '.json') return 'application/json; charset=utf-8';+ if (ext === '.png') return 'image/png';+ if (ext === '.jpg' || ext === '.jpeg') return 'image/jpeg';+ if (ext === '.svg') return 'image/svg+xml';+ return 'application/octet-stream';+}++function safeResolve(root, urlPath) {+ let decoded;+ try {+ decoded = decodeURIComponent((urlPath || '/').split('?')[0]);+ } catch {+ return null;+ }+ const relative = decoded === '/' ? 'index.html' : decoded.replace(/^\/+/, '');+ if (path.isAbsolute(relative) || relative.split(/[\\/]+/).includes('..')) return null;+ const fullPath = path.resolve(root, relative);+ const rootPath = path.resolve(root);+ return fullPath === rootPath || fullPath.startsWith(rootPath + path.sep) ? fullPath : null;+}++function isServableFile(filePath, options = {}) {+ const fsImpl = options.fs || fs;+ const root = path.resolve(options.root || path.dirname(filePath));+ try {+ if (!fsImpl.existsSync(root) || !fsImpl.existsSync(filePath)) return false;+ const rootStat = fsImpl.lstatSync(root);+ if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) return false;+ const resolvedFile = path.resolve(filePath);+ if (resolvedFile === root || !resolvedFile.startsWith(root + path.sep)) return false;+ let current = root;+ for (const segment of path.relative(root, resolvedFile).split(path.sep)) {+ current = path.join(current, segment);+ if (fsImpl.lstatSync(current).isSymbolicLink()) return false;+ }+ const realRoot = fsImpl.realpathSync(root);+ const realFile = fsImpl.realpathSync(resolvedFile);+ if (realFile === realRoot || !realFile.startsWith(realRoot + path.sep)) return false;+ return fsImpl.lstatSync(resolvedFile).isFile();+ } catch {+ return false;+ }+}++function streamFile(filePath, res, deps = {}) {+ const fsImpl = deps.fs || fs;+ let stream;+ try {+ stream = fsImpl.createReadStream(filePath);+ } catch {+ if (!res.headersSent) res.writeHead(404);+ res.end('Not found');+ return;+ }+ stream.on('error', () => {+ if (!res.headersSent) res.writeHead(404);+ res.end();+ });+ stream.pipe(res);+}++function serverUrl(host, port) {+ // RFC 3986 requires IPv6 literals to be enclosed in brackets when used as+ // the host component of a URL. The unbracketed value remains correct for+ // server.listen(). See: https://www.rfc-editor.org/rfc/rfc3986#section-3.2.2+ const urlHost = net.isIP(host) === 6 ? `[${host}]` : host;+ return `http://${urlHost}:${port}/`;+}++function requestsServerShutdown(status) {+ return Boolean(status && status.state === 'succeeded' && status.shutdownServer === true);+}++function pathContains(parentPath, childPath) {+ const parent = path.resolve(parentPath);+ const child = path.resolve(childPath);+ return child === parent || child.startsWith(parent + path.sep);+}++function resolveNewFileWithinRoot(root, filePath, options = {}) {+ const fsImpl = options.fs || fs;+ const resolvedRoot = path.resolve(root);+ const resolvedFile = path.resolve(filePath);+ const rootStat = fsImpl.lstatSync(resolvedRoot);+ if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) {+ throw new Error('Static server root must be a regular directory');+ }+ if (resolvedFile === resolvedRoot || !pathContains(resolvedRoot, resolvedFile)) {+ throw new Error('urlFile must stay inside the static server root');+ }++ let current = resolvedRoot;+ const relativeParent = path.relative(resolvedRoot, path.dirname(resolvedFile));+ for (const segment of relativeParent.split(path.sep).filter((part) => part && part !== '.')) {+ current = path.join(current, segment);+ const stat = fsImpl.lstatSync(current);+ if (stat.isSymbolicLink() || !stat.isDirectory()) {+ throw new Error('urlFile parent directories must be regular directories');+ }+ }++ const canonicalRoot = fsImpl.realpathSync(resolvedRoot);+ const canonicalParent = fsImpl.realpathSync(path.dirname(resolvedFile));+ if (!pathContains(canonicalRoot, canonicalParent)) {+ throw new Error('urlFile must stay inside the static server root');+ }+ try {+ fsImpl.lstatSync(resolvedFile);+ throw new Error('urlFile must not already exist');+ } catch (err) {+ if (err.code !== 'ENOENT') throw err;+ }+ return path.join(canonicalParent, path.basename(resolvedFile));+}++function createCleanupOwnership(root, deps = {}) {+ const fsImpl = deps.fs || fs;+ const osImpl = deps.os || os;+ const randomBytes = deps.randomBytes || crypto.randomBytes;+ const resolvedRoot = path.resolve(root);+ const rootStat = fsImpl.lstatSync(resolvedRoot);+ if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) {+ throw new Error('Cleanup root must be a regular directory');+ }+ const canonicalRoot = fsImpl.realpathSync(resolvedRoot);+ const canonicalTemp = fsImpl.realpathSync(osImpl.tmpdir());+ if (canonicalRoot === canonicalTemp || !pathContains(canonicalTemp, canonicalRoot)) {+ throw new Error('Cleanup root must be a child of the operating-system temporary directory');+ }+ const token = randomBytes(16).toString('hex');+ const markerPath = path.join(+ path.dirname(canonicalRoot),+ `.power-pages-status-${path.basename(canonicalRoot)}-${process.pid}-${token}.json`+ );+ fsImpl.writeFileSync(+ markerPath,+ JSON.stringify({ root: canonicalRoot, token }),+ { encoding: 'utf8', flag: 'wx', mode: 0o600 }+ );+ return { root: canonicalRoot, markerPath, token };+}++function cleanupOwnedRoot({ root, cleanupMarker, cleanupToken }, deps = {}) {+ if (!cleanupMarker || !cleanupToken) return false;+ const fsImpl = deps.fs || fs;+ try {+ const markerStat = fsImpl.lstatSync(cleanupMarker);+ if (markerStat.isSymbolicLink() || !markerStat.isFile()) return false;+ const ownership = JSON.parse(fsImpl.readFileSync(cleanupMarker, 'utf8'));+ const canonicalRoot = path.resolve(root);+ if (ownership.root !== canonicalRoot || ownership.token !== cleanupToken) return false;+ if (fsImpl.existsSync(canonicalRoot)) {+ const rootStat = fsImpl.lstatSync(canonicalRoot);+ if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) return false;+ if (fsImpl.realpathSync(canonicalRoot) !== canonicalRoot) return false;+ fsImpl.rmSync(canonicalRoot, { recursive: true, force: true });+ }+ fsImpl.rmSync(cleanupMarker, { force: true });+ return true;+ } catch {+ return false;+ }+}++function startServer(options, deps = {}) {+ const fsImpl = deps.fs || fs;+ const httpImpl = deps.http || http;+ const requestedRoot = path.resolve(options.root);+ const host = options.host || '127.0.0.1';+ const port = Number.isInteger(options.port) ? options.port : 0;+ const idleTimeoutMs = options.idleTimeoutMs || DEFAULT_IDLE_TIMEOUT_MS;+ const maxLifetimeMs = options.maxLifetimeMs || DEFAULT_MAX_LIFETIME_MS;+ const successGraceMs = options.successGraceMs || DEFAULT_SUCCESS_GRACE_MS;+ const statusPollMs = options.statusPollMs || DEFAULT_STATUS_POLL_MS;+ const rootStat = fsImpl.lstatSync(requestedRoot);+ if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) {+ return Promise.reject(new Error('Static server root must be a regular directory'));+ }+ const root = fsImpl.realpathSync(requestedRoot);+ const requestedStatusPath = path.resolve(options.statusPath || path.join(root, 'status.json'));+ const statusPath = fsImpl.existsSync(requestedStatusPath)+ ? fsImpl.realpathSync(requestedStatusPath)+ : requestedStatusPath;+ if (!pathContains(root, statusPath)) {+ return Promise.reject(new Error('Status path must stay inside the static server root'));+ }++ let resetIdleTimer = () => {};+ const server = httpImpl.createServer((req, res) => {+ resetIdleTimer();+ const filePath = safeResolve(root, req.url);+ if (!filePath || !isServableFile(filePath, { root, fs: fsImpl })) {+ res.writeHead(404);+ res.end('Not found');+ return;+ }+ res.writeHead(200, {+ 'Content-Type': contentType(filePath),+ 'Cache-Control': 'no-store',+ });+ streamFile(filePath, res, { fs: fsImpl });+ });++ let closing = false;+ let idleTimer = null;+ let lifetimeTimer = null;+ let successTimer = null;+ let resolveClosed;+ const closed = new Promise((resolve) => {+ resolveClosed = resolve;+ });++ const clearLifecycle = () => {+ if (idleTimer) clearTimeout(idleTimer);+ if (lifetimeTimer) clearTimeout(lifetimeTimer);+ if (successTimer) clearTimeout(successTimer);+ fsImpl.unwatchFile(statusPath);+ };+ const finalize = () => {+ clearLifecycle();+ cleanupOwnedRoot({+ root,+ cleanupMarker: options.cleanupMarker,+ cleanupToken: options.cleanupToken,+ }, { fs: fsImpl });+ resolveClosed();+ };+ const shutdown = () => {+ if (closing) return;+ closing = true;+ clearLifecycle();+ server.close(finalize);+ };+ resetIdleTimer = () => {+ if (!idleTimeoutMs || closing) return;+ if (idleTimer) clearTimeout(idleTimer);+ idleTimer = setTimeout(shutdown, idleTimeoutMs);+ };++ return new Promise((resolve, reject) => {+ const onStartupError = (err) => {+ clearLifecycle();+ reject(err);+ };+ server.once('error', onStartupError);+ server.listen(port, host, () => {+ server.off('error', onStartupError);+ server.on('error', shutdown);+ const address = server.address();+ const url = serverUrl(host, address.port);+ resetIdleTimer();+ lifetimeTimer = setTimeout(shutdown, maxLifetimeMs);+ const inspectStatus = () => {+ if (closing || successTimer) return;+ try {+ const status = JSON.parse(fsImpl.readFileSync(statusPath, 'utf8'));+ if (requestsServerShutdown(status)) {+ successTimer = setTimeout(shutdown, successGraceMs);+ }+ } catch {+ // The status writer replaces this file during updates. A short-lived+ // missing or incomplete document is retried on the next watch poll.+ }+ };+ fsImpl.watchFile(statusPath, { interval: statusPollMs, persistent: false }, inspectStatus);+ inspectStatus();+ resolve({ server, url, shutdown, closed });+ });+ });+}++function waitForChildReady(child, timeoutMs = DEFAULT_READY_TIMEOUT_MS) {+ return new Promise((resolve, reject) => {+ const timer = setTimeout(() => {+ cleanup();+ reject(new Error(`Static server did not become ready within ${timeoutMs}ms`));+ }, timeoutMs);+ const cleanup = () => {+ clearTimeout(timer);+ child.removeListener('message', onMessage);+ child.removeListener('error', onError);+ child.removeListener('exit', onExit);+ };+ const onMessage = (message) => {+ if (!message || (message.type !== 'ready' && message.type !== 'error')) return;+ cleanup();+ if (message.type === 'error') {+ reject(new Error(message.error || 'Static server child failed during startup'));+ } else {+ resolve(message);+ }+ };+ const onError = (err) => {+ cleanup();+ reject(err);+ };+ const onExit = (code, signal) => {+ cleanup();+ reject(new Error(`Static server child exited before readiness (${signal || code})`));+ };+ child.on('message', onMessage);+ child.once('error', onError);+ child.once('exit', onExit);+ });+}++async function main(argv = process.argv.slice(2), deps = {}) {+ const args = parseArgs(argv);+ const fsImpl = deps.fs || fs;+ if (!args.root) return { ok: false, error: 'Usage: serve-static-dir.js --root <dir> [--urlFile <path>]' };+ if (args.child) {+ const started = await startServer(args, deps);+ const proc = deps.process || process;+ const stop = () => started.shutdown();+ proc.once('SIGTERM', stop);+ proc.once('SIGINT', stop);+ started.closed.finally(() => {+ proc.removeListener('SIGTERM', stop);+ proc.removeListener('SIGINT', stop);+ });+ if (typeof proc.send === 'function') {+ await new Promise((resolve) => {+ proc.send({ type: 'ready', url: started.url }, () => {+ if (typeof proc.disconnect === 'function') proc.disconnect();+ resolve();+ });+ });+ }+ return null;+ }++ let ownership = null;+ if (args.cleanupRoot) {+ ownership = createCleanupOwnership(args.root, deps);+ }+ const servedRoot = ownership ? ownership.root : path.resolve(args.root);+ const childArgs = [+ '--child',+ '--root', servedRoot,+ '--host', args.host,+ '--port', String(args.port || 0),+ '--statusPath', args.statusPath ? path.resolve(args.statusPath) : path.join(servedRoot, 'status.json'),+ '--idleTimeoutMs', String(args.idleTimeoutMs || DEFAULT_IDLE_TIMEOUT_MS),+ '--maxLifetimeMs', String(args.maxLifetimeMs || DEFAULT_MAX_LIFETIME_MS),+ '--successGraceMs', String(args.successGraceMs || DEFAULT_SUCCESS_GRACE_MS),+ '--statusPollMs', String(args.statusPollMs || DEFAULT_STATUS_POLL_MS),+ ];+ if (ownership) {+ childArgs.push('--cleanupMarker', ownership.markerPath, '--cleanupToken', ownership.token);+ }+ const child = (deps.fork || fork)(__filename, childArgs, {+ detached: true,+ stdio: ['ignore', 'ignore', 'ignore', 'ipc'],+ });+ try {+ const ready = await waitForChildReady(child, args.readyTimeoutMs || DEFAULT_READY_TIMEOUT_MS);+ if (args.urlFile) {+ const urlFile = resolveNewFileWithinRoot(servedRoot, args.urlFile, { fs: fsImpl });+ fsImpl.writeFileSync(urlFile, ready.url, { encoding: 'utf8', flag: 'wx', mode: 0o600 });+ }+ child.unref();+ return { ok: true, url: ready.url, pid: child.pid };+ } catch (err) {+ if (typeof child.kill === 'function') child.kill();+ if (ownership) {+ cleanupOwnedRoot({+ root: ownership.root,+ cleanupMarker: ownership.markerPath,+ cleanupToken: ownership.token,+ }, deps);+ }+ throw err;+ }+}++if (require.main === module) {+ main().then((result) => {+ if (result) process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);+ }).catch((err) => {+ if (typeof process.send === 'function') {+ process.send({ type: 'error', error: err.message }, () => {+ if (typeof process.disconnect === 'function') process.disconnect();+ process.exitCode = 1;+ });+ return;+ }+ process.stderr.write(`${err.message}\n`);+ process.exitCode = 1;+ });+}++module.exports = {+ cleanupOwnedRoot,+ contentType,+ createCleanupOwnership,+ isServableFile,+ main,+ parseArgs,+ resolveNewFileWithinRoot,+ requestsServerShutdown,+ safeResolve,+ serverUrl,+ startServer,+ streamFile,+ waitForChildReady,+};diff --git a/plugins/power-pages/scripts/tests/apply-seed-data.test.js b/plugins/power-pages/scripts/tests/apply-seed-data.test.jsnew file mode 100644index 000000000..76026511e--- /dev/null+++ b/plugins/power-pages/scripts/tests/apply-seed-data.test.js@@ -0,0 +1,1017 @@+'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 {+ applySeedData,+ listSeedFiles,+ readSeedFile,+ isDuplicateConflict,+ createTokenProvider,+ validateSeedLookupContract,+ validateAttachmentFile,+} = require('../lib/apply-seed-data');+const { parseArgs, run } = require('../apply-seed-data');++function tempDir() {+ return fs.mkdtempSync(path.join(os.tmpdir(), 'apply-seed-data-test-'));+}++function withSeedStats(fsImpl, seedDir) {+ const resolvedSeedDir = path.resolve(seedDir);+ const existingLstat = fsImpl.lstatSync;+ return {+ ...fsImpl,+ lstatSync(targetPath) {+ if (path.resolve(targetPath) === resolvedSeedDir) {+ return {+ isSymbolicLink: () => false,+ isDirectory: () => true,+ isFile: () => false,+ };+ }+ if (existingLstat) {+ const stat = existingLstat(targetPath);+ return {+ isSymbolicLink: () => typeof stat.isSymbolicLink === 'function' ? stat.isSymbolicLink() : false,+ isDirectory: () => typeof stat.isDirectory === 'function' ? stat.isDirectory() : false,+ isFile: () => typeof stat.isFile === 'function' ? stat.isFile() : false,+ };+ }+ return {+ isSymbolicLink: () => false,+ isDirectory: () => false,+ isFile: () => true,+ };+ },+ };+}++test('listSeedFiles sorts JSON files by filename and ignores non-json files', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ fs.writeFileSync(path.join(dir, '020-posts.json'), '{}');+ fs.writeFileSync(path.join(dir, '010-categories.json'), '{}');+ fs.writeFileSync(path.join(dir, 'notes.txt'), 'ignore');++ assert.deepEqual(listSeedFiles(dir).map((file) => path.basename(file)), ['010-categories.json', '020-posts.json']);+});++test('listSeedFiles uses an explicit seed file without treating JSON attachments as seeds', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const seedFile = path.join(dir, 'data.json');+ fs.writeFileSync(seedFile, '{}');+ fs.writeFileSync(path.join(dir, 'attachment.json'), '{"document":"content"}');++ assert.deepEqual(listSeedFiles(dir, {}, seedFile), [seedFile]);+});++test('applySeedData ignores a JSON attachment when an explicit seed file is provided', async (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const seedFile = path.join(dir, 'data.json');+ fs.writeFileSync(seedFile, JSON.stringify({+ entitySetName: 'cr123_categories',+ records: [{ cr123_name: 'Announcements' }],+ }));+ fs.writeFileSync(path.join(dir, 'attachment.json'), JSON.stringify({+ entitySetName: 'cr123_unintended',+ records: [{ cr123_name: 'Must not be inserted' }],+ }));+ const requestUrls = [];++ const result = await applySeedData({+ seedDir: dir,+ seedFile,+ envUrl: 'https://org.crm.dynamics.com',+ }, {+ token: 'token',+ makeRequest: async ({ url }) => {+ requestUrls.push(url);+ return { statusCode: 204 };+ },+ });++ assert.equal(result.inserted, 1);+ assert.equal(requestUrls.length, 1);+ assert.match(requestUrls[0], /\/cr123_categories$/);+});++test('listSeedFiles rejects symlinked seed roots and JSON files', (t) => {+ const parent = tempDir();+ t.after(() => fs.rmSync(parent, { recursive: true, force: true }));+ const realSeedDir = path.join(parent, 'real-seed');+ const linkedSeedDir = path.join(parent, 'linked-seed');+ fs.mkdirSync(realSeedDir);+ fs.writeFileSync(path.join(realSeedDir, '010-data.json'), '{}');+ try {+ fs.symlinkSync(realSeedDir, linkedSeedDir, process.platform === 'win32' ? 'junction' : 'dir');+ } catch (err) {+ if (err.code === 'EPERM' || err.code === 'EACCES') {+ t.skip(`directory symlinks are unavailable: ${err.code}`);+ return;+ }+ throw err;+ }+ assert.throws(() => listSeedFiles(linkedSeedDir), /symbolic link/);++ const outsideFile = path.join(parent, 'outside.json');+ const linkedFile = path.join(realSeedDir, '020-linked.json');+ fs.writeFileSync(outsideFile, '{}');+ try {+ fs.symlinkSync(outsideFile, linkedFile, 'file');+ } catch (err) {+ if (err.code === 'EPERM' || err.code === 'EACCES') {+ t.skip(`file symlinks are unavailable: ${err.code}`);+ return;+ }+ throw err;+ }+ assert.throws(() => listSeedFiles(realSeedDir), /symbolic link/);+ assert.throws(() => readSeedFile(linkedFile), /symbolic link/);+});++test('readSeedFile validates the seed file contract', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const file = path.join(dir, '010-categories.json');+ fs.writeFileSync(file, JSON.stringify({ entitySetName: 'cr123_categories', records: [{ cr123_name: 'Announcements' }] }));+ assert.deepEqual(readSeedFile(file), { entitySetName: 'cr123_categories', records: [{ cr123_name: 'Announcements' }] });++ fs.writeFileSync(file, JSON.stringify({ entitySetName: 'cr123_categories' }));+ assert.throws(() => readSeedFile(file), /Expected/);+});++test('readSeedFile normalizes Dataverse export seed shape', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const file = path.join(dir, 'data.json');+ fs.writeFileSync(file, JSON.stringify({+ schemaVersion: 1,+ tables: {+ contacts: {+ logicalName: 'contact',+ entitySet: 'contacts',+ idColumn: 'contactid',+ records: [{ contactid: '11111111-1111-1111-1111-111111111111', fullname: 'Amy Chen' }],+ },+ invoices: {+ logicalName: 'spnvc_invoice',+ entitySet: 'spnvc_invoices',+ idColumn: 'spnvc_invoiceid',+ records: [{+ '@odata.etag': 'W/"1"',+ spnvc_invoiceid: '22222222-2222-2222-2222-222222222222',+ _spnvc_contactid_value: '11111111-1111-1111-1111-111111111111',+ '_spnvc_contactid_value@Microsoft.Dynamics.CRM.associatednavigationproperty': 'spnvc_ContactId',+ createdon: '2026-01-01T00:00:00Z',+ }],+ },+ invoiceAttachments: {+ logicalName: 'spnvc_invoiceattachment',+ entitySet: 'spnvc_invoiceattachments',+ idColumn: 'spnvc_invoiceattachmentid',+ records: [{+ spnvc_invoiceattachmentid: '33333333-3333-3333-3333-333333333333',+ spnvc_name: 'invoice.pdf',+ }],+ },+ },+ fileExports: [{+ attachmentId: '33333333-3333-3333-3333-333333333333',+ fileColumn: 'spnvc_file',+ path: 'files/invoice.pdf',+ }],+ }));++ const normalized = readSeedFile(file);+ assert.deepEqual(normalized.map((entry) => entry.entitySetName), ['contacts', 'spnvc_invoices', 'spnvc_invoiceattachments']);+ assert.deepEqual(normalized[1].records[0], {+ spnvc_invoiceid: '22222222-2222-2222-2222-222222222222',+ '[email protected]': '/contacts(11111111-1111-1111-1111-111111111111)',+ });+ assert.deepEqual(normalized[2].records[0].__files, { spnvc_file: 'files/invoice.pdf' });+});++test('readSeedFile rejects exports without a valid table entry', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const file = path.join(dir, 'data.json');++ fs.writeFileSync(file, JSON.stringify({ schemaVersion: 1, tables: {} }));+ assert.throws(() => readSeedFile(file), /Expected/);++ fs.writeFileSync(file, JSON.stringify({+ schemaVersion: 1,+ tables: {+ broken: {+ entitySet: 'cr123_broken',+ records: [],+ },+ },+ }));+ assert.throws(() => readSeedFile(file), /Expected/);+});++test('applySeedData posts records, skips duplicates, and records failures without throwing', async (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ fs.writeFileSync(path.join(dir, '010-categories.json'), JSON.stringify({+ entitySetName: 'cr123_categories',+ records: [+ { cr123_categoryid: '11111111-1111-1111-1111-111111111111', cr123_name: 'Announcements' },+ { cr123_categoryid: '11111111-1111-1111-1111-111111111111', cr123_name: 'Duplicate' },+ { cr123_name: 'Broken' },+ ],+ }));+ const bodies = [];+ const responses = [+ { statusCode: 204 },+ { statusCode: 409, body: 'Cannot insert duplicate key' },+ { statusCode: 500, body: 'server error' },+ ];++ const result = await applySeedData({ seedDir: dir, envUrl: 'https://org.crm.dynamics.com' }, {+ token: 'token',+ makeRequest: async (req) => {+ bodies.push(JSON.parse(req.body));+ return responses.shift();+ },+ });++ assert.deepEqual(bodies.map((body) => body.cr123_name), ['Announcements', 'Duplicate', 'Broken']);+ assert.equal(result.inserted, 1);+ assert.equal(result.skipped, 1);+ assert.equal(result.failed, 1);+ assert.match(result.errors[0].message, /server error/);+});++test('applySeedData success path can run with injected fs and request function', async () => {+ const fsImpl = {+ existsSync: () => true,+ readdirSync: () => ['010-categories.json'],+ readFileSync: () => JSON.stringify({+ entitySetName: 'cr123_categories',+ records: [{ cr123_name: 'Announcements' }],+ }),+ };+ const requests = [];+ const result = await applySeedData({ seedDir: '/virtual/seed', envUrl: 'https://org.crm.dynamics.com' }, {+ token: 'token',+ fs: withSeedStats(fsImpl, '/virtual/seed'),+ makeRequest: async (req) => {+ requests.push(req);+ return { statusCode: 204 };+ },+ });++ assert.equal(result.inserted, 1);+ assert.equal(requests[0].url, 'https://org.crm.dynamics.com/api/data/v9.2/cr123_categories');+ assert.deepEqual(JSON.parse(requests[0].body), { cr123_name: 'Announcements' });+});++test('validateSeedLookupContract rejects inferred lookup aliases and mismatched entity sets', () => {+ const entries = [+ {+ file: '010-categories.json',+ seed: {+ entitySetName: 'spa311_categories',+ primaryKey: 'spa311_categoryid',+ records: [{ spa311_categoryid: '11111111-1111-1111-1111-111111111111' }],+ },+ },+ {+ file: '020-service-types.json',+ seed: {+ entitySetName: 'spa311_servicetypes',+ primaryKey: 'spa311_servicetypeid',+ records: [{+ spa311_servicetypeid: '22222222-2222-2222-2222-222222222222',+ categoryId: '11111111-1111-1111-1111-111111111111',+ '[email protected]': '/wrong_categories(11111111-1111-1111-1111-111111111111)',+ }],+ },+ },+ ];++ assert.deepEqual(validateSeedLookupContract(entries), [+ {+ file: '020-service-types.json',+ entitySetName: 'spa311_servicetypes',+ message: 'Lookup categoryId is ambiguous; use the exact <NavigationProperty>@odata.bind name from the solution metadata',+ },+ {+ file: '020-service-types.json',+ entitySetName: 'spa311_servicetypes',+ message: 'Lookup [email protected] targets wrong_categories, but the referenced seed record belongs to spa311_categories',+ },+ ]);+});++test('applySeedData preserves exact OData lookup navigation properties', async () => {+ const files = {+ '010-categories.json': {+ entitySetName: 'spa311_categories',+ primaryKey: 'spa311_categoryid',+ records: [{ spa311_categoryid: '11111111-1111-1111-1111-111111111111', spa311_name: 'Roads' }],+ },+ '020-service-types.json': {+ entitySetName: 'spa311_servicetypes',+ primaryKey: 'spa311_servicetypeid',+ records: [{+ spa311_servicetypeid: '22222222-2222-2222-2222-222222222222',+ spa311_name: 'Pothole',+ '[email protected]': '/spa311_categories(11111111-1111-1111-1111-111111111111)',+ }],+ },+ '030-service-requests.json': {+ entitySetName: 'spa311_servicerequests',+ primaryKey: 'spa311_servicerequestid',+ records: [{+ spa311_servicerequestid: '33333333-3333-3333-3333-333333333333',+ spa311_name: 'SR-001',+ '[email protected]': '/spa311_servicetypes(22222222-2222-2222-2222-222222222222)',+ }],+ },+ '040-status-updates.json': {+ entitySetName: 'spa311_statusupdates',+ primaryKey: 'spa311_statusupdateid',+ records: [{+ spa311_statusupdateid: '44444444-4444-4444-4444-444444444444',+ spa311_name: 'Created',+ '[email protected]': '/spa311_servicerequests(33333333-3333-3333-3333-333333333333)',+ }],+ },+ };+ const fsImpl = {+ existsSync: () => true,+ readdirSync: () => Object.keys(files),+ readFileSync: (filePath) => JSON.stringify(files[path.basename(filePath)]),+ };+ const requests = [];++ const result = await applySeedData({ seedDir: '/virtual/seed', envUrl: 'https://org.crm.dynamics.com' }, {+ token: 'token',+ fs: withSeedStats(fsImpl, '/virtual/seed'),+ makeRequest: async (req) => {+ requests.push(req);+ return { statusCode: 204 };+ },+ });++ assert.equal(result.failed, 0);+ assert.equal(result.inserted, 4);+ assert.deepEqual(JSON.parse(requests[1].body), {+ spa311_servicetypeid: '22222222-2222-2222-2222-222222222222',+ spa311_name: 'Pothole',+ '[email protected]': '/spa311_categories(11111111-1111-1111-1111-111111111111)',+ });+ assert.deepEqual(JSON.parse(requests[2].body), {+ spa311_servicerequestid: '33333333-3333-3333-3333-333333333333',+ spa311_name: 'SR-001',+ '[email protected]': '/spa311_servicetypes(22222222-2222-2222-2222-222222222222)',+ });+ assert.deepEqual(JSON.parse(requests[3].body), {+ spa311_statusupdateid: '44444444-4444-4444-4444-444444444444',+ spa311_name: 'Created',+ '[email protected]': '/spa311_servicerequests(33333333-3333-3333-3333-333333333333)',+ });+});++test('applySeedData rejects ambiguous lookup aliases before the first Dataverse write', async () => {+ const files = {+ '010-categories.json': {+ entitySetName: 'spa311_categories',+ primaryKey: 'spa311_categoryid',+ records: [{ spa311_categoryid: '11111111-1111-1111-1111-111111111111', spa311_name: 'Roads' }],+ },+ '020-service-types.json': {+ entitySetName: 'spa311_servicetypes',+ primaryKey: 'spa311_servicetypeid',+ records: [{+ spa311_servicetypeid: '22222222-2222-2222-2222-222222222222',+ categoryId: '11111111-1111-1111-1111-111111111111',+ }],+ },+ };+ const fsImpl = {+ existsSync: () => true,+ readdirSync: () => Object.keys(files),+ readFileSync: (filePath) => JSON.stringify(files[path.basename(filePath)]),+ };+ let requestCount = 0;++ const result = await applySeedData({ seedDir: '/virtual/seed', envUrl: 'https://org.crm.dynamics.com' }, {+ token: 'token',+ fs: withSeedStats(fsImpl, '/virtual/seed'),+ makeRequest: async () => {+ requestCount++;+ return { statusCode: 204 };+ },+ });++ assert.equal(result.ok, false);+ assert.equal(result.inserted, 0);+ assert.equal(result.failed, 1);+ assert.match(result.errors[0].message, /exact <NavigationProperty>@odata.bind/);+ assert.equal(requestCount, 0);+});++test('applySeedData posts Dataverse export seed tables and uploads fileExports', async () => {+ const seedDir = path.resolve('export-seed');+ const attachmentPath = path.join(seedDir, 'files', 'invoice.pdf');+ const fileBuffer = Buffer.from('pdf');+ const fsImpl = {+ existsSync: (p) => p === seedDir || p === attachmentPath,+ readdirSync: () => ['data.json'],+ readFileSync: (p) => {+ if (p.endsWith('data.json')) {+ return JSON.stringify({+ schemaVersion: 1,+ tables: {+ contacts: {+ logicalName: 'contact',+ entitySet: 'contacts',+ idColumn: 'contactid',+ records: [{ contactid: '11111111-1111-1111-1111-111111111111', fullname: 'Amy Chen' }],+ },+ invoices: {+ logicalName: 'spnvc_invoice',+ entitySet: 'spnvc_invoices',+ idColumn: 'spnvc_invoiceid',+ records: [{+ spnvc_invoiceid: '22222222-2222-2222-2222-222222222222',+ _contactid_value: '11111111-1111-1111-1111-111111111111',+ '_contactid_value@Microsoft.Dynamics.CRM.associatednavigationproperty': 'spnvc_ContactId',+ }],+ },+ attachments: {+ logicalName: 'spnvc_invoiceattachment',+ entitySet: 'spnvc_invoiceattachments',+ idColumn: 'spnvc_invoiceattachmentid',+ records: [{ spnvc_invoiceattachmentid: '33333333-3333-3333-3333-333333333333' }],+ },+ },+ fileExports: [{ attachmentId: '33333333-3333-3333-3333-333333333333', fileColumn: 'spnvc_file', path: 'files/invoice.pdf' }],+ });+ }+ return fileBuffer;+ },+ lstatSync: () => ({ isFile: () => true }),+ statSync: () => ({ size: fileBuffer.length }),+ };+ const requests = [];+ const result = await applySeedData({ seedDir, envUrl: 'https://org.crm.dynamics.com' }, {+ token: 'token',+ fs: withSeedStats(fsImpl, seedDir),+ randomBlockId: () => 'block-1',+ makeRequest: async (req) => {+ requests.push(req);+ if (req.url.endsWith('/InitializeFileBlocksUpload')) return { statusCode: 200, body: JSON.stringify({ FileContinuationToken: 'continuation' }) };+ return { statusCode: 204 };+ },+ });++ const invoicePost = requests.find((req) => req.url.endsWith('/spnvc_invoices'));+ assert.equal(result.failed, 0);+ assert.equal(result.inserted, 3);+ assert.deepEqual(JSON.parse(invoicePost.body), {+ spnvc_invoiceid: '22222222-2222-2222-2222-222222222222',+ '[email protected]': '/contacts(11111111-1111-1111-1111-111111111111)',+ });+ assert.equal(requests.some((req) => req.url.endsWith('/InitializeFileBlocksUpload')), true);+});++test('applySeedData creates stateful records before applying the desired state separately', async () => {+ const articleId = '50000000-0000-4000-8000-000000000001';+ const fsImpl = {+ existsSync: () => true,+ readdirSync: () => ['data.json'],+ readFileSync: () => JSON.stringify({+ schemaVersion: 1,+ tables: {+ knowledgearticles: {+ logicalName: 'knowledgearticle',+ entitySet: 'knowledgearticles',+ idColumn: 'knowledgearticleid',+ records: [{+ knowledgearticleid: articleId,+ title: 'How to Report a Pothole',+ statecode: 3,+ statuscode: 7,+ }],+ },+ },+ }),+ };+ const requests = [];++ const result = await applySeedData({ seedDir: '/virtual/seed', envUrl: 'https://org.crm.dynamics.com' }, {+ token: 'token',+ fs: withSeedStats(fsImpl, '/virtual/seed'),+ makeRequest: async (req) => {+ requests.push(req);+ if (req.method === 'POST' && Object.hasOwn(JSON.parse(req.body), 'statecode')) {+ return {+ statusCode: 400,+ body: '7 is not a valid status code for state code KnowledgeArticleState.Draft',+ };+ }+ return { statusCode: 204 };+ },+ });++ assert.deepEqual(result, {+ ok: true,+ inserted: 1,+ failed: 0,+ skipped: 0,+ errors: [],+ });+ assert.equal(requests.length, 2);+ assert.deepEqual({+ method: requests[0].method,+ url: requests[0].url,+ body: JSON.parse(requests[0].body),+ }, {+ method: 'POST',+ url: 'https://org.crm.dynamics.com/api/data/v9.2/knowledgearticles',+ body: {+ knowledgearticleid: articleId,+ title: 'How to Report a Pothole',+ },+ });+ assert.deepEqual({+ method: requests[1].method,+ url: requests[1].url,+ body: JSON.parse(requests[1].body),+ ifMatch: requests[1].headers['If-Match'],+ }, {+ method: 'PATCH',+ url: `https://org.crm.dynamics.com/api/data/v9.2/knowledgearticles(${articleId})`,+ body: {+ statecode: 3,+ statuscode: 7,+ },+ ifMatch: '*',+ });+});++test('applySeedData rejects stateful records without a GUID primary key before writing', async () => {+ const fsImpl = {+ existsSync: () => true,+ readdirSync: () => ['010-articles.json'],+ readFileSync: () => JSON.stringify({+ entitySetName: 'knowledgearticles',+ records: [{+ title: 'How to Report a Pothole',+ statecode: 3,+ statuscode: 7,+ }],+ }),+ };+ let requestCount = 0;++ const result = await applySeedData({ seedDir: '/virtual/seed', envUrl: 'https://org.crm.dynamics.com' }, {+ token: 'token',+ fs: withSeedStats(fsImpl, '/virtual/seed'),+ makeRequest: async () => {+ requestCount += 1;+ return { statusCode: 204 };+ },+ });++ assert.equal(result.inserted, 0);+ assert.equal(result.failed, 1);+ assert.match(result.errors[0].message, /must declare a primaryKey containing a GUID/);+ assert.equal(requestCount, 0);+});++test('applySeedData refreshes tokens across the whole seed run instead of per record', async () => {+ const fsImpl = {+ existsSync: () => true,+ readdirSync: () => ['010-categories.json'],+ readFileSync: () => JSON.stringify({+ entitySetName: 'cr123_categories',+ records: [+ { cr123_name: 'One' },+ { cr123_name: 'Two' },+ { cr123_name: 'Three' },+ ],+ }),+ };+ const authResources = [];+ const authHeaders = [];++ const result = await applySeedData({ seedDir: '/virtual/seed', envUrl: 'https://org.crm.dynamics.com' }, {+ fs: withSeedStats(fsImpl, '/virtual/seed'),+ token: 'initial-token',+ tokenRefreshEvery: 2,+ getAuthToken: (resource) => {+ authResources.push(resource);+ return `refreshed-${authResources.length}`;+ },+ makeRequest: async (req) => {+ authHeaders.push(req.headers.Authorization);+ return { statusCode: 204 };+ },+ });++ assert.equal(result.inserted, 3);+ assert.deepEqual(authHeaders, ['Bearer initial-token', 'Bearer initial-token', 'Bearer refreshed-1']);+ assert.deepEqual(authResources, ['https://org.crm.dynamics.com']);+});++test('applySeedData strips __files, requires primaryKey, and uploads file-column attachments in 4 MiB blocks', async () => {+ const seedDir = path.resolve('virtual-seed');+ const attachmentPath = path.join(seedDir, 'files', 'invoices', 'inv-001.pdf');+ const fileBuffer = Buffer.concat([+ Buffer.alloc(4 * 1024 * 1024, 1),+ Buffer.from('tail'),+ ]);+ const fsImpl = {+ existsSync: (p) => p === seedDir || p === attachmentPath,+ readdirSync: () => ['010-invoices.json'],+ readFileSync: (p) => {+ if (p.endsWith('010-invoices.json')) {+ return JSON.stringify({+ entitySetName: 'cr123_invoices',+ primaryKey: 'cr123_invoiceid',+ records: [{+ cr123_invoiceid: '11111111-1111-1111-1111-111111111111',+ cr123_name: 'INV-001',+ __files: {+ cr123_invoicepdf: 'files/invoices/inv-001.pdf',+ },+ }],+ });+ }+ return fileBuffer;+ },+ lstatSync: () => ({ isFile: () => true }),+ statSync: () => ({ size: fileBuffer.length }),+ };+ const requests = [];+ const result = await applySeedData({ seedDir, envUrl: 'https://org.crm.dynamics.com' }, {+ token: 'token',+ fs: withSeedStats(fsImpl, seedDir),+ randomBlockId: (() => {+ const ids = ['block-1', 'block-2'];+ return () => ids.shift();+ })(),+ makeRequest: async (req) => {+ requests.push(req);+ if (req.url.endsWith('/cr123_invoices')) return { statusCode: 204 };+ if (req.url.endsWith('/InitializeFileBlocksUpload')) {+ return { statusCode: 200, body: JSON.stringify({ FileContinuationToken: 'continuation' }) };+ }+ if (req.url.endsWith('/UploadBlock')) return { statusCode: 204 };+ if (req.url.endsWith('/CommitFileBlocksUpload')) return { statusCode: 200 };+ throw new Error(`unexpected request: ${req.url}`);+ },+ });++ const recordBody = JSON.parse(requests[0].body);+ assert.equal(recordBody.__files, undefined);+ assert.equal(result.inserted, 1);+ assert.equal(result.failed, 0);+ assert.equal(requests.filter((req) => req.url.endsWith('/UploadBlock')).length, 2);+ assert.deepEqual(JSON.parse(requests.at(-1).body).BlockList, ['block-1', 'block-2']);+});++test('applySeedData records attachment validation failures without blocking other records', async () => {+ const fsImpl = {+ existsSync: () => true,+ readdirSync: () => ['010-invoices.json'],+ readFileSync: () => JSON.stringify({+ entitySetName: 'cr123_invoices',+ records: [{+ cr123_name: 'INV-001',+ __files: {+ cr123_invoicepdf: '../outside.pdf',+ },+ }],+ }),+ };++ const result = await applySeedData({ seedDir: '/virtual/seed', envUrl: 'https://org.crm.dynamics.com' }, {+ token: 'token',+ fs: withSeedStats(fsImpl, '/virtual/seed'),+ makeRequest: async () => ({ statusCode: 204 }),+ });++ assert.equal(result.inserted, 0);+ assert.equal(result.failed, 1);+ assert.match(result.errors[0].message, /primaryKey/);+});++test('validateAttachmentFile rejects symbolic links without reading their targets', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const targetPath = path.join(dir, 'outside.pdf');+ const linkPath = path.join(dir, 'attachment.pdf');+ fs.writeFileSync(targetPath, 'sensitive content');+ try {+ fs.symlinkSync(targetPath, linkPath);+ } catch (err) {+ if (err.code === 'EPERM' || err.code === 'EACCES') {+ t.skip(`symlinks are unavailable: ${err.code}`);+ return;+ }+ throw err;+ }++ assert.match(validateAttachmentFile(linkPath), /not a file/);+});++test('validateAttachmentFile rejects files reached through a symlinked directory', (t) => {+ const seedDir = tempDir();+ const outside = tempDir();+ t.after(() => {+ fs.rmSync(seedDir, { recursive: true, force: true });+ fs.rmSync(outside, { recursive: true, force: true });+ });+ fs.writeFileSync(path.join(outside, 'invoice.pdf'), 'sensitive content');+ const linkedDir = path.join(seedDir, 'files');+ try {+ fs.symlinkSync(outside, linkedDir, 'dir');+ } catch (err) {+ if (err.code === 'EPERM' || err.code === 'EACCES') {+ t.skip(`directory symlinks are unavailable: ${err.code}`);+ return;+ }+ throw err;+ }++ assert.match(+ validateAttachmentFile(path.join(linkedDir, 'invoice.pdf'), { seedDir }),+ /symbolic link/+ );+});++test('applySeedData rejects invalid entity-set paths before sending authenticated requests', async (t) => {+ const seedDir = tempDir();+ t.after(() => fs.rmSync(seedDir, { recursive: true, force: true }));+ fs.writeFileSync(path.join(seedDir, '010-invalid.json'), JSON.stringify({+ entitySetName: '../WhoAmI',+ records: [{ name: 'invalid' }],+ }));+ let requests = 0;++ const result = await applySeedData({+ seedDir,+ envUrl: 'https://org.crm.dynamics.com',+ }, {+ token: 'token',+ makeRequest: async () => {+ requests += 1;+ return { statusCode: 204 };+ },+ });++ assert.equal(requests, 0);+ assert.equal(result.failed, 1);+ assert.match(result.errors[0].message, /Invalid Dataverse OData operation name/);+});++test('applySeedData rejects untrusted environment URLs before acquiring a token', async () => {+ let tokenCalls = 0;+ const result = await applySeedData({+ seedDir: '/tmp/missing',+ envUrl: 'https://attacker.invalid',+ }, {+ getAuthToken: () => {+ tokenCalls += 1;+ return 'token';+ },+ });++ assert.equal(result.ok, false);+ assert.match(result.errors[0].message, /not an allowed Microsoft Dataverse/);+ assert.equal(tokenCalls, 0);+});++test('applySeedData rejects non-object __files before posting', async () => {+ const fsImpl = {+ existsSync: () => true,+ readdirSync: () => ['010-invoices.json'],+ readFileSync: () => JSON.stringify({+ entitySetName: 'cr123_invoices',+ primaryKey: 'cr123_invoiceid',+ records: [{+ cr123_invoiceid: '11111111-1111-1111-1111-111111111111',+ cr123_name: 'INV-001',+ __files: null,+ }],+ }),+ };+ const requests = [];++ const result = await applySeedData({ seedDir: '/virtual/seed', envUrl: 'https://org.crm.dynamics.com' }, {+ token: 'token',+ fs: withSeedStats(fsImpl, '/virtual/seed'),+ makeRequest: async (req) => {+ requests.push(req);+ return { statusCode: 204 };+ },+ });++ assert.equal(result.inserted, 0);+ assert.equal(result.failed, 1);+ assert.equal(requests.length, 0);+ assert.match(result.errors[0].message, /__files must be an object/);+});++test('applySeedData accepts attachment paths under a relative seedDir', async (t) => {+ const dir = tempDir();+ const cwd = process.cwd();+ t.after(() => {+ process.chdir(cwd);+ fs.rmSync(dir, { recursive: true, force: true });+ });+ process.chdir(dir);+ fs.mkdirSync(path.join('seed-data', 'files'), { recursive: true });+ fs.writeFileSync(path.join('seed-data', 'files', 'invoice.pdf'), Buffer.from('pdf'));+ fs.writeFileSync(path.join('seed-data', '010-invoices.json'), JSON.stringify({+ entitySetName: 'cr123_invoices',+ primaryKey: 'cr123_invoiceid',+ records: [{+ cr123_invoiceid: '11111111-1111-1111-1111-111111111111',+ __files: { cr123_invoicepdf: 'files/invoice.pdf' },+ }],+ }));+ const result = await applySeedData({ seedDir: 'seed-data', envUrl: 'https://org.crm.dynamics.com' }, {+ token: 'token',+ randomBlockId: () => 'block-1',+ makeRequest: async (req) => {+ if (req.url.endsWith('/cr123_invoices')) return { statusCode: 204 };+ if (req.url.endsWith('/InitializeFileBlocksUpload')) return { statusCode: 200, body: JSON.stringify({ FileContinuationToken: 'continuation' }) };+ return { statusCode: 204 };+ },+ });++ assert.equal(result.failed, 0);+});++test('applySeedData uploads file attachments when the explicit-guid record already exists', async () => {+ const seedDir = path.resolve('virtual-seed');+ const attachmentPath = path.join(seedDir, 'files', 'invoices', 'inv-001.pdf');+ const fileBuffer = Buffer.from('pdf');+ const fsImpl = {+ existsSync: (p) => p === seedDir || p === attachmentPath,+ readdirSync: () => ['010-invoices.json'],+ readFileSync: (p) => {+ if (p.endsWith('010-invoices.json')) {+ return JSON.stringify({+ entitySetName: 'cr123_invoices',+ primaryKey: 'cr123_invoiceid',+ records: [{+ cr123_invoiceid: '11111111-1111-1111-1111-111111111111',+ cr123_name: 'INV-001',+ __files: { cr123_invoicepdf: 'files/invoices/inv-001.pdf' },+ }],+ });+ }+ return fileBuffer;+ },+ lstatSync: () => ({ isFile: () => true }),+ statSync: () => ({ size: fileBuffer.length }),+ };+ const requests = [];+ const result = await applySeedData({ seedDir, envUrl: 'https://org.crm.dynamics.com' }, {+ token: 'token',+ fs: withSeedStats(fsImpl, seedDir),+ randomBlockId: () => 'block-1',+ makeRequest: async (req) => {+ requests.push(req);+ if (req.url.endsWith('/cr123_invoices')) return { statusCode: 409, body: 'Cannot insert duplicate key' };+ if (req.url.endsWith('/InitializeFileBlocksUpload')) return { statusCode: 200, body: JSON.stringify({ FileContinuationToken: 'continuation' }) };+ if (req.url.endsWith('/UploadBlock')) return { statusCode: 204 };+ if (req.url.endsWith('/CommitFileBlocksUpload')) return { statusCode: 200 };+ throw new Error(`unexpected request: ${req.url}`);+ },+ });++ assert.equal(result.skipped, 1);+ assert.equal(requests.some((req) => req.url.endsWith('/InitializeFileBlocksUpload')), true);+});++test('applySeedData rejects disallowed attachment extensions and Git LFS pointers before posting', async () => {+ const fsImpl = {+ existsSync: () => true,+ readdirSync: () => ['010-invoices.json', '020-receipts.json'],+ readFileSync: (p) => {+ if (p.endsWith('010-invoices.json')) {+ return JSON.stringify({+ entitySetName: 'cr123_invoices',+ primaryKey: 'cr123_invoiceid',+ records: [{ cr123_invoiceid: '11111111-1111-1111-1111-111111111111', __files: { cr123_invoiceexe: 'files/bad.exe' } }],+ });+ }+ if (p.endsWith('020-receipts.json')) {+ return JSON.stringify({+ entitySetName: 'cr123_receipts',+ primaryKey: 'cr123_receiptid',+ records: [{ cr123_receiptid: '22222222-2222-2222-2222-222222222222', __files: { cr123_receiptpdf: 'files/lfs.pdf' } }],+ });+ }+ return Buffer.from('version https://git-lfs.github.com/spec/v1\n');+ },+ lstatSync: () => ({ isFile: () => true }),+ statSync: () => ({ size: 42 }),+ };+ const requests = [];+ const result = await applySeedData({ seedDir: '/virtual/seed', envUrl: 'https://org.crm.dynamics.com' }, {+ token: 'token',+ fs: withSeedStats(fsImpl, '/virtual/seed'),+ makeRequest: async (req) => {+ requests.push(req);+ return { statusCode: 204 };+ },+ });++ assert.equal(result.inserted, 2);+ assert.equal(result.failed, 2);+ assert.equal(requests.length, 2);+ assert.match(result.errors[0].message, /extension/);+ assert.match(result.errors[1].message, /Git LFS pointer/);+});++test('applySeedData reports auth failure as best-effort summary', async () => {+ assert.deepEqual(await applySeedData({ seedDir: '/tmp/missing', envUrl: 'https://org.crm.dynamics.com' }, {+ getAuthToken: () => null,+ }), {+ ok: false,+ inserted: 0,+ failed: 1,+ skipped: 0,+ errors: [{ scope: 'auth', message: 'Azure CLI token unavailable for https://org.crm.dynamics.com' }],+ });++});++test('applySeedData catches token and filesystem failures as summaries', async () => {+ assert.deepEqual(await applySeedData({ seedDir: '/tmp/seed', envUrl: 'https://org.crm.dynamics.com' }, {+ getAuthToken: () => { throw new Error('token exploded'); },+ }), {+ ok: false,+ inserted: 0,+ failed: 1,+ skipped: 0,+ errors: [{ scope: 'seedDir', message: 'token exploded' }],+ });++ const failingFs = {+ existsSync: () => true,+ readdirSync: () => { throw new Error('fs exploded'); },+ };+ const result = await applySeedData({ seedDir: '/virtual/seed', envUrl: 'https://org.crm.dynamics.com' }, {+ token: 'token',+ fs: withSeedStats(failingFs, '/virtual/seed'),+ });+ assert.equal(result.ok, false);+ assert.equal(result.failed, 1);+ assert.match(result.errors[0].message, /fs exploded/);+});++test('isDuplicateConflict only treats duplicate 409s as skipped candidates', () => {+ assert.equal(isDuplicateConflict({ statusCode: 409, body: 'Cannot insert duplicate key' }), true);+ assert.equal(isDuplicateConflict({ statusCode: 409, body: 'Concurrency version mismatch' }), false);+ assert.equal(isDuplicateConflict({ statusCode: 500, body: 'Cannot insert duplicate key' }), false);+});++test('createTokenProvider refreshes after the configured request cadence', () => {+ const tokens = ['fresh-1', 'fresh-2'];+ const provider = createTokenProvider({+ envUrl: 'https://org.crm.dynamics.com',+ initialToken: 'initial',+ refreshEvery: 2,+ resolveToken: () => tokens.shift(),+ });++ assert.equal(provider(), 'initial');+ assert.equal(provider(), 'initial');+ assert.equal(provider(), 'fresh-1');+ assert.equal(provider(), 'fresh-1');+ assert.equal(provider(), 'fresh-2');+});++test('apply-seed-data CLI parser and runner return best-effort summaries', async () => {+ assert.deepEqual(parseArgs(['--seedDir', '/tmp/seed', '--seedFile', '/tmp/seed/data.json', '--envUrl', 'https://org.crm.dynamics.com']), {+ seedDir: '/tmp/seed',+ seedFile: '/tmp/seed/data.json',+ envUrl: 'https://org.crm.dynamics.com',+ });+ assert.deepEqual(await run([]), {+ ok: false,+ inserted: 0,+ failed: 1,+ skipped: 0,+ errors: [{ scope: 'args', message: 'Usage: apply-seed-data.js --seedDir <dir> --envUrl <url>' }],+ });+});diff --git a/plugins/power-pages/scripts/tests/check-available-languages.test.js b/plugins/power-pages/scripts/tests/check-available-languages.test.jsnew file mode 100644index 000000000..cebd91023--- /dev/null+++ b/plugins/power-pages/scripts/tests/check-available-languages.test.js@@ -0,0 +1,131 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');++const {+ checkAvailableLanguages,+ main,+ parseArgs,+} = require('../check-available-languages');++test('checkAvailableLanguages allows template import when required template languages are enabled', async () => {+ const result = await checkAvailableLanguages({+ envUrl: 'https://org.crm.dynamics.com',+ token: 'token',+ requiredLocaleIds: [1033, 1036],+ request: async (options) => {+ assert.equal(options.url, 'https://org.crm.dynamics.com/api/data/v9.2/RetrieveAvailableLanguages');+ assert.equal(options.method, 'GET');+ assert.equal(options.headers.Authorization, 'Bearer token');+ return { statusCode: 200, body: JSON.stringify({ LocaleIds: [1033, 1036] }) };+ },+ });++ assert.deepEqual(result, {+ ok: true,+ hasRequiredLanguages: true,+ requiredLocaleIds: [1033, 1036],+ missingLocaleIds: [],+ localeIds: [1033, 1036],+ });+});++test('checkAvailableLanguages blocks template import when any template language is missing', async () => {+ const result = await checkAvailableLanguages({+ envUrl: 'https://org.crm.dynamics.com/',+ token: 'token',+ requiredLocaleIds: [1033, 1041],+ request: async () => ({ statusCode: 200, body: JSON.stringify({ LocaleIds: [1036, 1041] }) }),+ });++ assert.deepEqual(result, {+ ok: true,+ hasRequiredLanguages: false,+ requiredLocaleIds: [1033, 1041],+ missingLocaleIds: [1033],+ localeIds: [1036, 1041],+ });+});++test('checkAvailableLanguages defaults to en-US for older callers', async () => {+ const result = await checkAvailableLanguages({+ envUrl: 'https://org.crm.dynamics.com/',+ token: 'token',+ request: async () => ({ statusCode: 200, body: JSON.stringify({ LocaleIds: [1033] }) }),+ });++ assert.equal(result.ok, true);+ assert.equal(result.hasRequiredLanguages, true);+ assert.deepEqual(result.requiredLocaleIds, [1033]);+});++test('checkAvailableLanguages reports malformed language responses', async () => {+ const result = await checkAvailableLanguages({+ envUrl: 'https://org.crm.dynamics.com',+ token: 'token',+ request: async () => ({ statusCode: 200, body: JSON.stringify({ value: [1033] }) }),+ });++ assert.equal(result.ok, false);+ assert.match(result.error, /LocaleIds/);+});++test('checkAvailableLanguages reports request failures', async () => {+ const result = await checkAvailableLanguages({+ envUrl: 'https://org.crm.dynamics.com',+ token: 'token',+ request: async () => ({ error: 'network down' }),+ });++ assert.deepEqual(result, {+ ok: false,+ error: 'RetrieveAvailableLanguages request failed: network down',+ });+});++test('checkAvailableLanguages rejects untrusted environment URLs before acquiring a token', async () => {+ let tokenCalls = 0;+ const result = await checkAvailableLanguages({+ envUrl: 'https://attacker.invalid',+ requiredLocaleIds: [1033],+ resolveToken: () => {+ tokenCalls += 1;+ return 'token';+ },+ });++ assert.equal(result.ok, false);+ assert.match(result.error, /not an allowed Microsoft Dataverse/);+ assert.equal(tokenCalls, 0);+});++test('parseArgs reads environment and locale arguments without accepting a bearer token', () => {+ assert.deepEqual(parseArgs(['--envUrl', 'https://org.crm.dynamics.com/', '--requiredLocaleIds', '1033,1041']), {+ envUrl: 'https://org.crm.dynamics.com/',+ requiredLocaleIds: [1033, 1041],+ });+});++test('main uses the drain-safe JSON runner instead of forcing process exit', async () => {+ const output = [];+ const proc = {};++ await main({+ argv: ['--envUrl', 'https://org.crm.dynamics.com', '--requiredLocaleIds', '1033'],+ checkOptions: {+ token: 'token',+ request: async () => ({ statusCode: 200, body: JSON.stringify({ LocaleIds: [1033] }) }),+ },+ process: proc,+ stdout: {+ write(value) {+ output.push(value);+ },+ },+ });++ assert.equal(proc.exitCode, 0);+ assert.equal(output.length, 1);+ assert.equal(JSON.parse(output[0]).hasRequiredLanguages, true);+});diff --git a/plugins/power-pages/scripts/tests/clear-site-cache.test.js b/plugins/power-pages/scripts/tests/clear-site-cache.test.jsindex 1b0d2d427..2d9e58efd 100644--- a/plugins/power-pages/scripts/tests/clear-site-cache.test.js+++ b/plugins/power-pages/scripts/tests/clear-site-cache.test.js@@ -8,10 +8,11 @@ const { createTempProject, writeProjectFile } = require('./test-utils');const scriptPath = path.join(__dirname, '..', 'clear-site-cache.js');-function runClearSiteCache(args) {+function runClearSiteCache(args, options = {}) {return spawnSync(process.execPath, [scriptPath, ...args], {encoding: 'utf8',timeout: 30000,+ ...options,});}@@ -45,13 +46,13 @@ test('fails when powerpages.config.json is invalid JSON', (t) => {});test('fails gracefully when PAC CLI is not authenticated', (t) => {- // This test depends on the PAC CLI auth state.- // If PAC is authenticated, it will proceed further and fail at the API call.- // If not authenticated, it will fail at the PAC auth check.- // Either way, the script should exit 1 with success: false.const projectRoot = createTempProject(t);writeProjectFile(projectRoot, 'powerpages.config.json', JSON.stringify({ siteName: 'nonexistent-test-site' }));- const result = runClearSiteCache(['--projectRoot', projectRoot]);+ const result = runClearSiteCache(['--projectRoot', projectRoot], {+ // Hide locally installed CLIs so the test cannot inherit a developer's live+ // PAC session and turn this unit test into a network-dependent integration test.+ env: { ...process.env, PATH: '' },+ });assert.equal(result.status, 1);const parsed = JSON.parse(result.stdout);assert.equal(parsed.success, false);diff --git a/plugins/power-pages/scripts/tests/cli-tenant-alignment.test.js b/plugins/power-pages/scripts/tests/cli-tenant-alignment.test.jsnew file mode 100644index 000000000..beda05342--- /dev/null+++ b/plugins/power-pages/scripts/tests/cli-tenant-alignment.test.js@@ -0,0 +1,175 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');++const {+ parsePacTenantId,+ tenantIdFromToken,+ validateCliTenantAlignment,+} = require('../lib/cli-tenant-alignment');+const { parseArgs, run } = require('../validate-cli-tenant-alignment');++const TENANT_A = '72f988bf-86f1-41af-91ab-2d7cd011db47';+const TENANT_B = '11111111-2222-3333-4444-555555555555';++function fakeJwt(tenantId) {+ return [+ Buffer.from(JSON.stringify({ alg: 'none' })).toString('base64url'),+ Buffer.from(JSON.stringify({ tid: tenantId })).toString('base64url'),+ '',+ ].join('.');+}++function fakeExecFile({ pacTenant = TENANT_A, azTenant = TENANT_A } = {}) {+ return (command, args) => {+ if (command === 'pac' && args.join(' ') === 'auth who') {+ return `Connected as [email protected]\nTenant ID: ${pacTenant}\n`;+ }+ if (command === 'pac' && args.join(' ') === 'env who') {+ return 'Org URL: https://org.crm.dynamics.com/\n';+ }+ if (command === 'az' && args.join(' ') === 'account show --query tenantId -o tsv') {+ return `${azTenant}\n`;+ }+ throw new Error(`unexpected command: ${command} ${args.join(' ')}`);+ };+}++function fakeWindowsExecFile({ pacTenant = TENANT_A, azTenant = TENANT_A } = {}) {+ return (command, args) => {+ if (command === 'cmd.exe' && args.join(' ') === '/d /s /c pac.exe auth who') {+ return `Connected as [email protected]\nTenant ID: ${pacTenant}\n`;+ }+ if (command === 'cmd.exe' && args.join(' ') === '/d /s /c pac.exe env who') {+ return 'Org URL: https://org.crm.dynamics.com/\n';+ }+ if (command === 'cmd.exe' && args.join(' ') === '/d /s /c az.cmd account show --query tenantId -o tsv') {+ return `${azTenant}\n`;+ }+ if (command === 'pac' || command === 'az') {+ throw new Error('Windows cannot exec cmd shims directly');+ }+ throw new Error(`unexpected command: ${command} ${args.join(' ')}`);+ };+}++function fakeFallbackExecFile({ platform = 'linux' } = {}) {+ return (command, args) => {+ const joined = args.join(' ');+ if (platform === 'win32') {+ if (command === 'cmd.exe' && joined === '/d /s /c pac.exe auth who') {+ return `Tenant ID: ${TENANT_A}\n`;+ }+ if (command === 'cmd.exe' && joined === '/d /s /c pac.exe env who') {+ return 'Environment ID: 11111111-1111-1111-1111-111111111111\n';+ }+ if (command === 'cmd.exe' && joined === '/d /s /c pac.exe auth list') {+ return '[1] * Active user Public https://org.crm.dynamics.com\n';+ }+ if (command === 'cmd.exe' && joined === '/d /s /c az.cmd account show --query tenantId -o tsv') {+ return `${TENANT_A}\n`;+ }+ } else {+ if (command === 'pac' && joined === 'auth who') return `Tenant ID: ${TENANT_A}\n`;+ if (command === 'pac' && joined === 'env who') return 'Environment ID: 11111111-1111-1111-1111-111111111111\n';+ if (command === 'pac' && joined === 'auth list') return '[1] * Active user Public https://org.crm.dynamics.com\n';+ if (command === 'az' && joined === 'account show --query tenantId -o tsv') return `${TENANT_A}\n`;+ }+ throw new Error(`unexpected command: ${command} ${joined}`);+ };+}++test('parsePacTenantId extracts Tenant ID from PAC auth output', () => {+ assert.equal(parsePacTenantId(`User: u\nTenant ID: ${TENANT_A}\n`), TENANT_A);+ assert.equal(parsePacTenantId(`Tenant: ${TENANT_A}`), TENANT_A);+ assert.equal(parsePacTenantId('Tenant ID: not-a-guid'), null);+});++test('tenantIdFromToken extracts tid from an Azure CLI access token', () => {+ assert.equal(tenantIdFromToken(fakeJwt(TENANT_A)), TENANT_A);+ assert.equal(tenantIdFromToken('not.jwt'), null);+});++test('validateCliTenantAlignment succeeds when PAC, Azure account, and token tenants match', () => {+ assert.deepEqual(validateCliTenantAlignment({+ envUrl: 'https://org.crm.dynamics.com',+ token: fakeJwt(TENANT_A),+ }, {+ execFile: fakeExecFile(),+ platform: 'linux',+ }), {+ ok: true,+ pacTenantId: TENANT_A,+ azTenantId: TENANT_A,+ tokenTenantId: TENANT_A,+ expectedEnvironmentUrl: 'https://org.crm.dynamics.com',+ pacEnvironmentUrl: 'https://org.crm.dynamics.com',+ mismatches: [],+ error: null,+ });+});++test('validateCliTenantAlignment invokes Windows cmd shims through cmd.exe', () => {+ assert.equal(validateCliTenantAlignment({+ envUrl: 'https://org.crm.dynamics.com',+ token: fakeJwt(TENANT_A),+ }, {+ execFile: fakeWindowsExecFile(),+ platform: 'win32',+ }).ok, true);+});++test('validateCliTenantAlignment falls back to the active PAC auth profile on POSIX and Windows', () => {+ for (const platform of ['linux', 'win32']) {+ assert.equal(validateCliTenantAlignment({+ envUrl: 'https://org.crm.dynamics.com',+ token: fakeJwt(TENANT_A),+ }, {+ execFile: fakeFallbackExecFile({ platform }),+ platform,+ }).ok, true);+ }+});++test('validateCliTenantAlignment blocks when PAC and Azure tenants differ', () => {+ const result = validateCliTenantAlignment({+ envUrl: 'https://org.crm.dynamics.com',+ token: fakeJwt(TENANT_A),+ }, {+ execFile: fakeExecFile({ pacTenant: TENANT_B, azTenant: TENANT_A }),+ platform: 'linux',+ });++ assert.equal(result.ok, false);+ assert.deepEqual(result.mismatches, ['pac-vs-az', 'pac-vs-token']);+ assert.match(result.error, /different tenants/i);+});++test('validateCliTenantAlignment blocks when PAC targets a different environment', () => {+ const result = validateCliTenantAlignment({+ envUrl: 'https://target.crm.dynamics.com',+ token: fakeJwt(TENANT_A),+ }, {+ execFile: fakeExecFile(),+ platform: 'linux',+ });++ assert.equal(result.ok, false);+ assert.deepEqual(result.mismatches, ['pac-vs-environment']);+ assert.equal(result.expectedEnvironmentUrl, 'https://target.crm.dynamics.com');+ assert.equal(result.pacEnvironmentUrl, 'https://org.crm.dynamics.com');+});++test('run requires an environment URL and acquires the token internally', () => {+ assert.deepEqual(parseArgs(['--envUrl', 'https://org.crm.dynamics.com']), {+ envUrl: 'https://org.crm.dynamics.com',+ });+ assert.equal(run([]).ok, false);+ assert.match(run([]).error, /--envUrl <url>/);+ assert.equal(run(['--envUrl', 'https://org.crm.dynamics.com'], {+ execFile: fakeExecFile(),+ platform: 'linux',+ getAuthToken: () => fakeJwt(TENANT_A),+ }).ok, true);+});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.jsnew file mode 100644index 000000000..ac1c515a4--- /dev/null+++ b/plugins/power-pages/scripts/tests/create-site-template-telemetry.test.js@@ -0,0 +1,221 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');++const { buildTemplateOutcomeEvent, emitTemplateOutcome, normalizeBool, sanitizeTemplateOutcomeInfo } = require('../lib/create-site-template-telemetry');+const { parseArgs, toCliResult } = require('../emit-create-site-template-outcome');++test('buildTemplateOutcomeEvent emits non-PII template eventInfo through the existing skill event shape', () => {+ const event = buildTemplateOutcomeEvent({+ eventName: 'template_used',+ templateId: 'company-portal',+ templateKind: 'spa',+ framework: 'react',+ audience: 'internal',+ correlationId: 'corr',+ sessionId: 'session',+ osName: 'darwin',+ osVersion: '1',+ nodeVersion: 'v24',+ }, {+ 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.sessionId, 'session');+ assert.equal(event.data.aiAgentName, 'Copilot CLI');+ assert.equal(event.data.aiAgentVersion, '1.0.76-0');+ assert.equal(event.data.pacCliVersion, '2.10.1');+ assert.deepEqual(event.data.eventInfo, {+ framework: 'react',+ audience: 'internal',+ templateId: 'company-portal',+ templateKind: 'spa',+ });+ assert.equal('siteUrl' in event.data.eventInfo, false);+});++test('buildTemplateOutcomeEvent emits import result details separately from template selection', () => {+ const success = buildTemplateOutcomeEvent({+ eventName: 'template_import_success',+ templateId: 'company-portal',+ templateKind: 'spa',+ framework: 'react',+ audience: 'internal',+ seedApplied: 'true',+ correlationId: 'corr',+ }, {+ readPacAuth: () => null,+ readAgentInfo: () => ({}),+ randomUUID: () => 'corr',+ });+ assert.equal(success.data.eventName, 'template_import_success');+ assert.deepEqual(success.data.eventInfo, {+ framework: 'react',+ audience: 'internal',+ templateId: 'company-portal',+ templateKind: 'spa',+ seedApplied: true,+ });++ const failure = buildTemplateOutcomeEvent({+ eventName: 'template_import_failure',+ templateId: 'company-portal',+ templateKind: 'spa',+ framework: 'react',+ audience: 'internal',+ outcome: 'failure',+ errorClass: 'ImportSolutionAsync',+ errorDescription: 'https://example.crm.dynamics.com/private/path',+ correlationId: 'corr',+ }, {+ readPacAuth: () => null,+ readAgentInfo: () => ({}),+ randomUUID: () => 'corr',+ });+ assert.equal(failure.data.eventName, 'template_import_failure');+ assert.equal(failure.data.outcome, 'failure');+ assert.equal(failure.data.errorClass, 'ImportSolutionAsync');+ assert.equal('errorDescription' in failure.data, false);+ assert.equal(failure.data.severity, 'Error');+});++test('buildTemplateOutcomeEvent emits clone result events separately from import events', () => {+ const success = buildTemplateOutcomeEvent({+ eventName: 'template_clone_success',+ templateId: 'supplier-portal',+ templateKind: 'spa',+ framework: 'vue',+ audience: 'external',+ correlationId: 'corr',+ }, {+ readPacAuth: () => null,+ readAgentInfo: () => ({}),+ randomUUID: () => 'corr',+ });++ assert.equal(success.data.eventName, 'template_clone_success');+ assert.deepEqual(success.data.eventInfo, {+ framework: 'vue',+ audience: 'external',+ templateId: 'supplier-portal',+ templateKind: 'spa',+ });++ const failure = buildTemplateOutcomeEvent({+ eventName: 'template_clone_failure',+ templateId: 'supplier-portal',+ templateKind: 'spa',+ framework: 'vue',+ audience: 'external',+ outcome: 'failure',+ errorClass: 'PacPagesClone',+ errorDescription: '/Users/example/private/template',+ correlationId: 'corr',+ }, {+ readPacAuth: () => null,+ readAgentInfo: () => ({}),+ randomUUID: () => 'corr',+ });++ assert.equal(failure.data.eventName, 'template_clone_failure');+ assert.equal(failure.data.outcome, 'failure');+ assert.equal(failure.data.errorClass, 'PacPagesClone');+ assert.equal('errorDescription' in failure.data, false);+ assert.equal(failure.data.severity, 'Error');+});++test('buildTemplateOutcomeEvent drops unapproved error classes', () => {+ const failure = buildTemplateOutcomeEvent({+ eventName: 'template_clone_failure',+ outcome: 'failure',+ errorClass: 'Error at /private/path',+ correlationId: 'corr',+ }, {+ readPacAuth: () => null,+ readAgentInfo: () => ({}),+ randomUUID: () => 'corr',+ });++ assert.equal('errorClass' in failure.data, false);+});++test('buildTemplateOutcomeEvent emits scratch branch adoption signal', () => {+ const event = buildTemplateOutcomeEvent({+ eventName: 'create_site_from_scratch',+ framework: 'vue',+ audience: 'external',+ correlationId: 'corr',+ }, {+ readPacAuth: () => null,+ readAgentInfo: () => ({}),+ randomUUID: () => 'corr',+ env: { COPILOT_AGENT_SESSION_ID: 'copilot-session' },+ pluginVersion: '2.7.0',+ });++ assert.equal(event.data.eventName, 'create_site_from_scratch');+ assert.deepEqual(event.data.eventInfo, { framework: 'vue', audience: 'external' });+ assert.equal(event.data.sessionId, 'copilot-session');+});++test('emitTemplateOutcome is fail-closed and delegates to telemetry dispatcher seam', () => {+ const emitted = [];+ const opts = [];+ const result = emitTemplateOutcome({ eventName: 'create_site_from_scratch', framework: 'react', audience: 'internal' }, {+ readPacAuth: () => ({ cloud: 'Public' }),+ readAgentInfo: () => ({}),+ randomUUID: () => 'corr',+ fireAndForget: (event, options) => {+ emitted.push(event);+ opts.push(options);+ },+ });+ assert.equal(result.ok, true);+ assert.equal(emitted.length, 1);+ assert.equal(opts[0].cloud, 'Public');++ const failure = emitTemplateOutcome({}, { readPacAuth: () => null, fireAndForget: () => { throw new Error('nope'); } });+ assert.equal(failure.ok, false);+});++test('parseArgs and normalizeBool handle CLI values', () => {+ assert.deepEqual(parseArgs(['--eventName', 'template_import_success', '--templateKind', 'spa', '--seedApplied', '1']), { eventName: 'template_import_success', templateKind: 'spa', seedApplied: '1' });+ assert.equal(normalizeBool('1'), true);+ assert.equal(normalizeBool('false'), false);+});++test('telemetry CLI output excludes the emitted event and organization identifiers', () => {+ assert.deepEqual(toCliResult({+ ok: true,+ event: {+ data: {+ orgId: 'organization-guid',+ tenantId: 'tenant-guid',+ },+ },+ }), { ok: true });+ assert.deepEqual(toCliResult({ ok: false, error: 'private failure details' }), { ok: false });+ assert.deepEqual(toCliResult(null), { ok: false });+});++test('sanitizeTemplateOutcomeInfo drops invalid dynamic telemetry values', () => {+ assert.deepEqual(sanitizeTemplateOutcomeInfo({+ eventName: 'template_used',+ templateId: 'Company Portal',+ templateKind: 'liquid',+ framework: 'nextjs',+ audience: 'everyone',+ importOutcome: 'maybe',+ activationOutcome: 'pending',+ seedApplied: '0',+ siteUrl: 'https://example.test',+ }), {});+});diff --git a/plugins/power-pages/scripts/tests/dataverse-request.test.js b/plugins/power-pages/scripts/tests/dataverse-request.test.jsnew file mode 100644index 000000000..8bf3bae2b--- /dev/null+++ b/plugins/power-pages/scripts/tests/dataverse-request.test.js@@ -0,0 +1,87 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');++const { parseArgs, doRequest } = require('../dataverse-request');++test('parseArgs reads large request bodies from --bodyFile', () => {+ const result = parseArgs([+ 'https://org.crm.dynamics.com/',+ 'post',+ 'ImportSolutionAsync',+ '--bodyFile',+ '/tmp/body.json',+ '--include-headers',+ ], {+ fs: {+ readFileSync: (filePath, encoding) => {+ assert.equal(filePath, '/tmp/body.json');+ assert.equal(encoding, 'utf8');+ return '{"CustomizationFile":"large"}';+ },+ },+ });++ assert.deepEqual(result, {+ envUrl: 'https://org.crm.dynamics.com',+ method: 'POST',+ apiPath: 'ImportSolutionAsync',+ body: '{"CustomizationFile":"large"}',+ includeHeaders: true,+ });+});++test('parseArgs rejects ambiguous inline and file bodies', () => {+ assert.deepEqual(parseArgs([+ 'https://org.crm.dynamics.com',+ 'POST',+ 'ImportSolutionAsync',+ '--body',+ '{}',+ '--bodyFile',+ '/tmp/body.json',+ ]), { error: 'Use either --body or --bodyFile, not both.' });+});++test('doRequest sends parsed file body as JSON payload', async () => {+ const response = await doRequest(+ 'https://org.crm.dynamics.com',+ 'POST',+ 'ImportSolutionAsync',+ '{"CustomizationFile":"large"}',+ 'token',+ true,+ async (request) => {+ assert.equal(request.url, 'https://org.crm.dynamics.com/api/data/v9.2/ImportSolutionAsync');+ assert.equal(request.method, 'POST');+ assert.equal(request.headers.Authorization, 'Bearer token');+ assert.equal(request.headers['Content-Type'], 'application/json');+ assert.equal(request.body, '{"CustomizationFile":"large"}');+ assert.equal(request.includeHeaders, true);+ return { statusCode: 202, body: '{"ok":true}', headers: { location: 'async-url' } };+ },+ );++ assert.deepEqual(response, { statusCode: 202, body: '{"ok":true}', headers: { location: 'async-url' } });+});++test('doRequest rejects unapproved origins before attaching the bearer token', async () => {+ let requested = false;+ await assert.rejects(+ () => doRequest(+ 'https://attacker.example',+ 'POST',+ 'ImportSolutionAsync',+ '{}',+ 'token',+ false,+ async () => {+ requested = true;+ return { statusCode: 202, body: '{}' };+ },+ ),+ /allowed Microsoft Dataverse or Power Platform endpoint/+ );+ assert.equal(requested, false);+});diff --git a/plugins/power-pages/scripts/tests/fix-blocked-attachments.test.js b/plugins/power-pages/scripts/tests/fix-blocked-attachments.test.jsindex bbb834ab5..acab7ad62 100644--- a/plugins/power-pages/scripts/tests/fix-blocked-attachments.test.js+++ b/plugins/power-pages/scripts/tests/fix-blocked-attachments.test.js@@ -76,6 +76,7 @@ test('passes --environment as a literal argv value with shell disabled', async (envUrl: 'https://staging.crm.dynamics.com',extensions: ['js'],quiet: true,+ platform: 'linux',execImpl: (file, args, options) => {calls.push({ file, args, options });if (args.includes('list-settings')) return SAMPLE_PAC_OUTPUT;@@ -93,6 +94,22 @@ test('passes --environment as a literal argv value with shell disabled', async (}});+test('invokes pac.exe directly on Windows', async () => {+ const calls = [];+ await fixBlockedAttachments({+ extensions: ['css'],+ quiet: true,+ platform: 'win32',+ execImpl: (file, args, options) => {+ calls.push({ file, args, options });+ return SAMPLE_PAC_OUTPUT;+ },+ });++ assert.equal(calls[0].file, 'pac.exe');+ assert.equal(calls[0].options.shell, false);+});+test('passes Dataverse-derived setting metacharacters as one literal argv value', async () => {const currentValue = 'exe;dll;&marker|%PATH%!;js';let updateArgs = null;diff --git a/plugins/power-pages/scripts/tests/open-url.test.js b/plugins/power-pages/scripts/tests/open-url.test.jsnew file mode 100644index 000000000..399fa3661--- /dev/null+++ b/plugins/power-pages/scripts/tests/open-url.test.js@@ -0,0 +1,33 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');++const { openInDefaultBrowser } = require('../lib/default-browser');+const { parseArgs, openUrl } = require('../open-url');++test('openInDefaultBrowser uses platform-specific opener commands', () => {+ const calls = [];+ const execFileSync = (...args) => calls.push(args);++ openInDefaultBrowser('https://example.test', { os: { platform: () => 'darwin' }, execFileSync });+ openInDefaultBrowser('https://example.test/a path?q=1&x=2', { os: { platform: () => 'win32' }, execFileSync });+ openInDefaultBrowser('https://example.test', { os: { platform: () => 'linux' }, execFileSync });++ assert.deepEqual(calls[0], ['open', ['https://example.test'], { stdio: 'ignore' }]);+ assert.equal(calls[1][0], 'powershell.exe');+ assert.deepEqual(calls[1][1], ['-NoProfile', '-Command', 'Start-Process -FilePath $env:COPILOT_OPEN_TARGET']);+ assert.equal(calls[1][2].stdio, 'ignore');+ assert.equal(calls[1][2].windowsHide, true);+ assert.equal(calls[1][2].env.COPILOT_OPEN_TARGET, 'https://example.test/a path?q=1&x=2');+ assert.deepEqual(calls[2], ['xdg-open', ['https://example.test'], { stdio: 'ignore' }]);+});++test('openUrl validates URL shape and reports opener failures without throwing', () => {+ assert.deepEqual(parseArgs(['--url', 'https://example.test']), { url: 'https://example.test' });+ assert.deepEqual(openUrl({ url: 'ftp://example.test' }), { ok: false, error: 'Usage: open-url.js --url <http(s)-url>' });+ assert.deepEqual(openUrl({ url: 'https://example.test' }, {+ os: { platform: () => 'linux' },+ execFileSync: () => { throw new Error('no browser'); },+ }), { ok: false, url: 'https://example.test', error: 'no browser' });+});diff --git a/plugins/power-pages/scripts/tests/pack-template-solution.test.js b/plugins/power-pages/scripts/tests/pack-template-solution.test.jsnew file mode 100644index 000000000..5c6076a84--- /dev/null+++ b/plugins/power-pages/scripts/tests/pack-template-solution.test.js@@ -0,0 +1,299 @@+'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 {+ WORK_DIRECTORY_PREFIX,+ cleanupPackedTemplateSolution,+ isGeneratedWorkDirectoryPath,+ isOwnedWorkDirectory,+ packTemplateSolution,+ parseArgs,+} = require('../pack-template-solution');+const { PAC_LOG_TAIL_BYTES, commandError, runPac } = require('../lib/pac-command');++function tempDir() {+ return fs.mkdtempSync(path.join(os.tmpdir(), 'pack-template-solution-test-'));+}++function createSolutionSource(root) {+ const other = path.join(root, 'Other');+ fs.mkdirSync(other, { recursive: true });+ fs.writeFileSync(path.join(other, 'Solution.xml'), [+ '<ImportExportXml><SolutionManifest>',+ '<UniqueName>test_template</UniqueName>',+ '<Version>1.0.0.0</Version>',+ '<Managed>0</Managed>',+ '</SolutionManifest></ImportExportXml>',+ ].join(''));+ fs.writeFileSync(path.join(other, 'Customizations.xml'), '<ImportExportXml />');+}++function fakeSolutionZip() {+ const name = Buffer.from('solution.xml');+ const header = Buffer.alloc(30);+ header.writeUInt32LE(0x04034b50, 0);+ header.writeUInt16LE(name.length, 26);+ return Buffer.concat([header, name]);+}++test('parseArgs accepts pack and cleanup inputs', () => {+ assert.deepEqual(parseArgs(['--solutionPath', '/tmp/source']), {+ solutionPath: '/tmp/source',+ });+ assert.deepEqual(parseArgs(['--cleanup', '--workDirectory', '/tmp/work']), {+ cleanup: true,+ workDirectory: '/tmp/work',+ });+ assert.deepEqual(parseArgs([+ '--cleanup',+ '--workDirectory', '/tmp/work',+ '--cleanupMarker', '/tmp/marker.json',+ '--cleanupToken', 'secret',+ ]), {+ cleanup: true,+ workDirectory: '/tmp/work',+ cleanupMarker: '/tmp/marker.json',+ cleanupToken: 'secret',+ });+});++test('packTemplateSolution packs an unmanaged source tree into an owned temp directory', (t) => {+ const root = tempDir();+ const tmpRoot = path.join(root, 'tmp');+ const source = path.join(root, 'solution');+ fs.mkdirSync(tmpRoot);+ createSolutionSource(source);+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ const calls = [];++ const result = packTemplateSolution({ solutionPath: source }, {+ tmpRoot,+ runPac(args) {+ calls.push(args);+ fs.writeFileSync(args[args.indexOf('--zipfile') + 1], fakeSolutionZip());+ return { status: 0, stdout: 'packed', stderr: '' };+ },+ });++ assert.equal(result.ok, true);+ assert.equal(result.solutionPath, path.resolve(source));+ assert.equal(isGeneratedWorkDirectoryPath(result.workDirectory, tmpRoot), true);+ assert.equal(isOwnedWorkDirectory(result.workDirectory, {+ tmpRoot,+ cleanupMarker: result.cleanupMarker,+ cleanupToken: result.cleanupToken,+ }), true);+ assert.deepEqual(calls, [[+ 'solution', 'pack',+ '--zipfile', result.zipPath,+ '--folder', path.resolve(source),+ '--packagetype', 'Unmanaged',+ ]]);+ assert.equal(fs.existsSync(result.zipPath), true);+ assert.deepEqual(cleanupPackedTemplateSolution(result.workDirectory, {+ tmpRoot,+ cleanupMarker: result.cleanupMarker,+ cleanupToken: 'wrong-token',+ }), {+ ok: false,+ error: 'workDirectory ownership could not be verified',+ });+ assert.equal(fs.existsSync(result.workDirectory), true);+ assert.deepEqual(cleanupPackedTemplateSolution(result.workDirectory, {+ tmpRoot,+ cleanupMarker: result.cleanupMarker,+ cleanupToken: result.cleanupToken,+ }), {+ ok: true,+ removed: true,+ });+ assert.equal(fs.existsSync(result.workDirectory), false);+ assert.equal(fs.existsSync(result.cleanupMarker), false);+});++test('packTemplateSolution rejects invalid source and removes partial output after PAC failure', (t) => {+ const root = tempDir();+ const tmpRoot = path.join(root, 'tmp');+ fs.mkdirSync(tmpRoot);+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ let calls = 0;++ const invalid = packTemplateSolution({ solutionPath: path.join(root, 'missing') }, {+ tmpRoot,+ runPac() {+ calls++;+ return { status: 0, stdout: '', stderr: '' };+ },+ });+ assert.equal(invalid.ok, false);+ assert.equal(invalid.step, 'validation');+ assert.equal(calls, 0);++ const source = path.join(root, 'solution');+ createSolutionSource(source);+ const failed = packTemplateSolution({ solutionPath: source }, {+ tmpRoot,+ runPac() {+ calls++;+ return { status: 1, stdout: '', stderr: 'pack rejected' };+ },+ });+ assert.equal(failed.ok, false);+ assert.equal(failed.step, 'pack');+ assert.match(failed.error, /pack rejected/);+ assert.equal(fs.readdirSync(tmpRoot).length, 0);+});++test('cleanup rejects arbitrary paths outside generated work directories', (t) => {+ const root = tempDir();+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ assert.equal(isGeneratedWorkDirectoryPath(root, path.dirname(root)), false);+ assert.deepEqual(cleanupPackedTemplateSolution(root, { tmpRoot: path.dirname(root) }), {+ ok: false,+ error: 'workDirectory ownership could not be verified',+ });+});++test('cleanup rejects matching temporary directories without the ownership token', (t) => {+ const root = tempDir();+ const tmpRoot = path.join(root, 'tmp');+ const unrelated = path.join(tmpRoot, `${WORK_DIRECTORY_PREFIX}unrelated`);+ fs.mkdirSync(unrelated, { recursive: true });+ fs.writeFileSync(path.join(unrelated, 'keep.txt'), 'keep');+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));++ assert.equal(isGeneratedWorkDirectoryPath(unrelated, tmpRoot), true);+ assert.deepEqual(cleanupPackedTemplateSolution(unrelated, { tmpRoot }), {+ ok: false,+ error: 'workDirectory ownership could not be verified',+ });+ assert.equal(fs.readFileSync(path.join(unrelated, 'keep.txt'), 'utf8'), 'keep');+});++test('packTemplateSolution rejects a symlinked ZIP output without reading its target', (t) => {+ const root = tempDir();+ const tmpRoot = path.join(root, 'tmp');+ const source = path.join(root, 'solution');+ const outsideZip = path.join(root, 'outside.zip');+ fs.mkdirSync(tmpRoot);+ createSolutionSource(source);+ fs.writeFileSync(outsideZip, fakeSolutionZip());+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ let symlinksUnavailable = false;++ const result = packTemplateSolution({ solutionPath: source }, {+ tmpRoot,+ runPac(args) {+ const zipPath = args[args.indexOf('--zipfile') + 1];+ try {+ fs.symlinkSync(outsideZip, zipPath);+ } catch (err) {+ if (err.code === 'EPERM' || err.code === 'EACCES') {+ symlinksUnavailable = true;+ t.skip(`symlinks are unavailable: ${err.code}`);+ return { status: 1, stdout: '', stderr: err.message };+ }+ throw err;+ }+ return { status: 0, stdout: 'packed', stderr: '' };+ },+ });++ if (symlinksUnavailable) return;+ assert.equal(result.ok, false);+ assert.equal(result.step, 'output');+ assert.equal(fs.readFileSync(outsideZip).equals(fakeSolutionZip()), true);+ assert.deepEqual(fs.readdirSync(tmpRoot), []);+});++test('packTemplateSolution preserves the PAC error when cleanup also fails', (t) => {+ const root = tempDir();+ const tmpRoot = path.join(root, 'tmp');+ const source = path.join(root, 'solution');+ fs.mkdirSync(tmpRoot);+ createSolutionSource(source);+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ const fsWithBlockedCleanup = {+ ...fs,+ rmSync() {+ throw new Error('EPERM');+ },+ };++ const result = packTemplateSolution({ solutionPath: source }, {+ fs: fsWithBlockedCleanup,+ tmpRoot,+ runPac() {+ return { status: 1, stdout: '', stderr: 'pack rejected' };+ },+ });++ assert.equal(result.ok, false);+ assert.equal(result.step, 'pack');+ assert.match(result.error, /pack rejected/);+ assert.match(result.cleanupError, /EPERM/);+ assert.equal(result.workDirectory.startsWith(tmpRoot), true);+});++test('runPac invokes pac.exe directly on Windows without a command shell', () => {+ const calls = [];+ runPac(['solution', 'pack', '--folder', 'source'], {+ platform: 'win32',+ runCommand(command, args, options) {+ calls.push([command, args, options]);+ return 'ok';+ },+ });+ assert.equal(calls[0][0], 'pac.exe');+ assert.deepEqual(calls[0][1], ['solution', 'pack', '--folder', 'source']);+ assert.equal(calls[0][2].shell, false);+ assert.equal(calls[0][2].maxBuffer, undefined);+ assert.equal(calls[0][2].stdio[0], 'ignore');+ assert.equal(typeof calls[0][2].stdio[1], 'number');+ assert.equal(calls[0][2].stdio[1], calls[0][2].stdio[2]);+});++test('runPac streams verbose output to disk and returns only its bounded tail', (t) => {+ const root = tempDir();+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ const marker = 'PAC upload completed';++ const result = runPac(['pages', 'upload-code-site'], {+ tmpRoot: root,+ runCommand(command, args, options) {+ assert.equal(command, process.platform === 'win32' ? 'pac.exe' : 'pac');+ fs.writeSync(options.stdio[1], `${'x'.repeat(PAC_LOG_TAIL_BYTES * 2)}\n${marker}`);+ },+ });++ assert.equal(result.status, 0);+ assert.equal(Buffer.byteLength(result.stdout), PAC_LOG_TAIL_BYTES);+ assert.match(result.stdout, new RegExp(`${marker}$`));+ assert.deepEqual(fs.readdirSync(root), []);+});++test('runPac keeps the PAC log tail when the command fails', (t) => {+ const root = tempDir();+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));++ const result = runPac(['pages', 'upload-code-site'], {+ tmpRoot: root,+ runCommand(command, args, options) {+ fs.writeSync(options.stdio[2], 'Upload failed after processing site files');+ const error = new Error('Command failed without captured stdio');+ error.status = 1;+ throw error;+ },+ });++ assert.equal(result.status, 1);+ assert.match(result.stderr, /Upload failed after processing site files/);+ assert.match(commandError('pac pages upload-code-site', result), /processing site files/);+ assert.doesNotMatch(commandError('pac pages upload-code-site', result), /without captured stdio/);+ assert.deepEqual(fs.readdirSync(root), []);+});diff --git a/plugins/power-pages/scripts/tests/poll-async-operation.test.js b/plugins/power-pages/scripts/tests/poll-async-operation.test.jsnew file mode 100644index 000000000..978da7324--- /dev/null+++ b/plugins/power-pages/scripts/tests/poll-async-operation.test.js@@ -0,0 +1,162 @@+'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 { parsePositiveInteger, pollAsyncOperation } = require('../poll-async-operation');++test('parsePositiveInteger accepts positive integers and rejects invalid poll settings', () => {+ assert.deepEqual(parsePositiveInteger(undefined, 5000, '--intervalMs'), { value: 5000 });+ assert.deepEqual(parsePositiveInteger('25', 5000, '--intervalMs'), { value: 25 });+ for (const value of ['0', '-1', '1.5', '1ms', 'NaN']) {+ assert.deepEqual(+ parsePositiveInteger(value, 5000, '--intervalMs'),+ { error: 'Invalid --intervalMs: expected a positive integer' }+ );+ }+});++test('poll-async-operation rejects invalid polling arguments before requests', async () => {+ let requested = false;+ const baseArgs = {+ asyncJobId: '00000000-0000-0000-0000-000000000000',+ envUrl: 'https://org.crm.dynamics.com',+ token: 'token',+ };+ const deps = {+ getAuthToken: () => 'token',+ makeRequest: async () => {+ requested = true;+ return { statusCode: 200, body: '{}' };+ },+ };++ assert.deepEqual(+ await pollAsyncOperation({ ...baseArgs, intervalMs: 'bad' }, deps),+ { error: 'Invalid --intervalMs: expected a positive integer' }+ );+ assert.deepEqual(+ await pollAsyncOperation({ ...baseArgs, maxAttempts: '0' }, deps),+ { error: 'Invalid --maxAttempts: expected a positive integer' }+ );+ assert.equal(requested, false);+});+++test('poll-async-operation leaves progress indeterminate while import is running', async (t) => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'poll-async-operation-test-'));+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));++ let requests = 0;+ const makeRequest = async () => {+ requests += 1;+ return { statusCode: 200, body: JSON.stringify({+ statecode: 0,+ statuscode: 20,+ message: 'Import is still running',+ }) };+ };+ const statusFile = path.join(dir, 'status.json');++ const result = await pollAsyncOperation({+ asyncJobId: '00000000-0000-0000-0000-000000000000',+ envUrl: 'https://org.crm.dynamics.com',+ intervalMs: '1',+ maxAttempts: '1',+ statusFile,+ }, { getAuthToken: () => 'token', makeRequest, sleep: async () => {} });++ assert.equal(requests, 1);+ assert.equal(result.status, 'Timeout');++ const status = JSON.parse(fs.readFileSync(statusFile, 'utf8'));+ assert.equal(status.state, 'timeout');+ assert.equal('progressPercent' in status, false);+});++test('poll-async-operation writes a terminal status when the initial token is unavailable', async (t) => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'poll-async-operation-test-'));+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const statusFile = path.join(dir, 'status.json');+ fs.writeFileSync(statusFile, JSON.stringify({ state: 'running', message: 'Waiting for Dataverse import status' }));++ const result = await pollAsyncOperation({+ asyncJobId: '00000000-0000-0000-0000-000000000000',+ envUrl: 'https://org.crm.dynamics.com',+ statusFile,+ }, { getAuthToken: () => null });++ assert.match(result.error, /Azure CLI token not available/);+ const status = JSON.parse(fs.readFileSync(statusFile, 'utf8'));+ assert.equal(status.state, 'failed');+ assert.equal(status.message, 'Template import status check failed. Check the agent terminal.');+});++test('poll-async-operation normalizes envUrl and braced async operation ids', async (t) => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'poll-async-operation-test-'));+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));++ let requestedUrl = '';+ const makeRequest = async ({ url }) => {+ requestedUrl = new URL(url).pathname + new URL(url).search;+ return { statusCode: 200, body: JSON.stringify({+ statecode: 3,+ statuscode: 30,+ progress: 100,+ }) };+ };++ const result = await pollAsyncOperation({+ asyncJobId: '{ABCDEFAB-1234-5678-9ABC-ABCDEFABCDEF}',+ envUrl: 'https://org.crm.dynamics.com/api/data/v9.2',+ intervalMs: '1',+ maxAttempts: '1',+ statusFile: path.join(dir, 'status.json'),+ }, { getAuthToken: () => 'token', makeRequest, sleep: async () => {} });++ assert.equal(result.status, 'Succeeded');+ assert.match(requestedUrl, /^\/api\/data\/v9\.2\/asyncoperations\(abcdefab-1234-5678-9abc-abcdefabcdef\)\?/);+ assert.doesNotMatch(requestedUrl, /progress/);+});++test('poll-async-operation keeps transient HTTP status details out of the loader message', async (t) => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'poll-async-operation-test-'));+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));++ const makeRequest = async () => ({ statusCode: 400, body: JSON.stringify({ error: { message: 'Bad request' } }) });+ const statusFile = path.join(dir, 'status.json');++ const result = await pollAsyncOperation({+ asyncJobId: '00000000-0000-0000-0000-000000000000',+ envUrl: 'https://org.crm.dynamics.com',+ intervalMs: '1',+ maxAttempts: '1',+ statusFile,+ }, { getAuthToken: () => 'token', makeRequest, sleep: async () => {} });++ assert.equal(result.status, 'Timeout');+ assert.equal(result.lastHttpStatus, 400);++ const status = JSON.parse(fs.readFileSync(statusFile, 'utf8'));+ assert.equal(status.message, 'Template import is still running. Check the agent terminal.');+ assert.equal('progressPercent' in status, false);+});++test('poll-async-operation rejects an untrusted environment before acquiring a token', async () => {+ let tokenCalls = 0;+ const result = await pollAsyncOperation({+ asyncJobId: '00000000-0000-0000-0000-000000000000',+ envUrl: 'https://attacker.invalid',+ }, {+ getAuthToken: () => {+ tokenCalls += 1;+ return 'token';+ },+ });++ assert.match(result.error, /not an allowed Microsoft Dataverse/);+ assert.equal(tokenCalls, 0);+});diff --git a/plugins/power-pages/scripts/tests/provision-template-site.test.js b/plugins/power-pages/scripts/tests/provision-template-site.test.jsnew file mode 100644index 000000000..2a22675a1--- /dev/null+++ b/plugins/power-pages/scripts/tests/provision-template-site.test.js@@ -0,0 +1,720 @@+'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 {+ copyMissingTemplateFiles,+ findCodeSiteRoot,+ inspectCompiledOutput,+ inspectClonedSiteIdentity,+ parseArgs,+ provisionTemplateSite,+ runNpm,+ runPac,+} = require('../provision-template-site');++const SOURCE_ID = '11111111-1111-1111-1111-111111111111';+const CLONED_ID = '22222222-2222-2222-2222-222222222222';++function tempDir() {+ return fs.mkdtempSync(path.join(os.tmpdir(), 'provision-template-site-test-'));+}++function createSource(root, { id = SOURCE_ID, name = 'Template Site' } = {}) {+ fs.mkdirSync(path.join(root, '.powerpages-site'), { recursive: true });+ fs.writeFileSync(path.join(root, '.powerpages-site', 'website.yml'), `id: ${id}\nname: ${name}\n`);+ fs.writeFileSync(path.join(root, 'powerpages.config.json'), JSON.stringify({ compiledPath: 'dist' }));+ fs.writeFileSync(path.join(root, 'package.json'), JSON.stringify({ scripts: { build: 'vite build' } }));+ fs.writeFileSync(path.join(root, '.npmrc'), 'omit-lockfile-registry-resolved=true\n');+}++test('parseArgs accepts source, output, and site name', () => {+ assert.deepEqual(parseArgs([+ '--sourcePath', '/tmp/source',+ '--outputDirectory', '/tmp/output',+ '--siteName', 'Supplier Portal',+ ]), {+ sourcePath: '/tmp/source',+ outputDirectory: '/tmp/output',+ siteName: 'Supplier Portal',+ });+});++test('findCodeSiteRoot resolves one nested PAC clone output and rejects ambiguity', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const site = path.join(dir, 'supplier-portal');+ createSource(site);+ assert.equal(findCodeSiteRoot(dir), site);++ createSource(path.join(dir, 'another-site'));+ assert.throws(() => findCodeSiteRoot(dir), /found 2/);+});++test('inspectClonedSiteIdentity reads the new website record id from cloned metadata', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ createSource(dir, { id: CLONED_ID, name: 'Supplier Portal Clone' });++ assert.deepEqual(inspectClonedSiteIdentity(dir), {+ siteName: 'Supplier Portal Clone',+ websiteRecordId: CLONED_ID,+ });+});++test('inspectCompiledOutput requires the configured build directory to contain a file', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ createSource(dir);+ fs.mkdirSync(path.join(dir, 'dist', 'assets'), { recursive: true });+ fs.writeFileSync(path.join(dir, 'dist', 'assets', 'index.js'), 'built');++ assert.deepEqual(inspectCompiledOutput(dir), {+ compiledPath: 'dist',+ outputPath: path.join(dir, 'dist'),+ });+});++test('inspectCompiledOutput rejects a project root or parent path as compiled output', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ createSource(dir);++ fs.writeFileSync(path.join(dir, 'powerpages.config.json'), JSON.stringify({ compiledPath: '.' }));+ assert.throws(() => inspectCompiledOutput(dir), /invalid compiledPath/);++ fs.writeFileSync(path.join(dir, 'powerpages.config.json'), JSON.stringify({ compiledPath: '../dist' }));+ assert.throws(() => inspectCompiledOutput(dir), /invalid compiledPath/);+});++test('inspectCompiledOutput rejects symlinked compiled-path components', (t) => {+ const dir = tempDir();+ const outside = tempDir();+ t.after(() => {+ fs.rmSync(dir, { recursive: true, force: true });+ fs.rmSync(outside, { recursive: true, force: true });+ });+ createSource(dir);+ fs.mkdirSync(path.join(outside, 'assets'), { recursive: true });+ fs.writeFileSync(path.join(outside, 'assets', 'index.js'), 'outside');+ try {+ fs.symlinkSync(outside, path.join(dir, 'dist'), process.platform === 'win32' ? 'junction' : 'dir');+ } catch (err) {+ if (err.code === 'EPERM' || err.code === 'EACCES') {+ t.skip(`directory symlinks are unavailable: ${err.code}`);+ return;+ }+ throw err;+ }++ assert.throws(+ () => inspectCompiledOutput(dir),+ /Build output path must contain only real directories/+ );+});++test('inspectCompiledOutput rejects symlinks nested inside compiled output', (t) => {+ const dir = tempDir();+ const outside = tempDir();+ t.after(() => {+ fs.rmSync(dir, { recursive: true, force: true });+ fs.rmSync(outside, { recursive: true, force: true });+ });+ createSource(dir);+ fs.mkdirSync(path.join(dir, 'dist'), { recursive: true });+ fs.writeFileSync(path.join(dir, 'dist', 'index.html'), 'built');+ fs.writeFileSync(path.join(outside, 'secret.js'), 'outside');+ try {+ fs.symlinkSync(+ path.join(outside, 'secret.js'),+ path.join(dir, 'dist', 'secret.js'),+ 'file'+ );+ } catch (err) {+ if (err.code === 'EPERM' || err.code === 'EACCES') {+ t.skip(`file symlinks are unavailable: ${err.code}`);+ return;+ }+ throw err;+ }++ assert.throws(+ () => inspectCompiledOutput(dir),+ /Build output must not contain symbolic links/+ );+});++test('provisionTemplateSite clones, installs, builds, validates output, then uploads', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const source = path.join(dir, 'source');+ const output = path.join(dir, 'output');+ createSource(source);+ const pacCalls = [];+ const npmCalls = [];++ const result = provisionTemplateSite({+ sourcePath: source,+ outputDirectory: output,+ siteName: 'Supplier Portal',+ }, {+ runPac(args, commandOptions) {+ pacCalls.push({ args, cwd: commandOptions.cwd });+ if (args[1] === 'clone') {+ createSource(path.join(output, 'supplier-portal'), {+ id: CLONED_ID,+ name: 'Supplier Portal',+ });+ fs.writeFileSync(path.join(output, 'supplier-portal', 'package-lock.json'), '{}');+ }+ return { status: 0, stdout: 'ok', stderr: '' };+ },+ runNpm(args, cwd) {+ npmCalls.push([args, cwd]);+ if (args[0] === 'run') {+ fs.mkdirSync(path.join(cwd, 'dist'));+ fs.writeFileSync(path.join(cwd, 'dist', 'index.html'), '<html></html>');+ }+ return { status: 0, stdout: 'ok', stderr: '' };+ },+ });++ const clonedPath = path.join(output, 'supplier-portal');+ assert.deepEqual(result, {+ ok: true,+ clonedPath,+ siteName: 'Supplier Portal',+ websiteRecordId: CLONED_ID,+ compiledPath: 'dist',+ });+ assert.deepEqual(pacCalls, [+ {+ args: [+ 'pages', 'clone',+ '--path', source,+ '--outputDirectory', output,+ '--name', 'Supplier Portal',+ '--overwrite',+ ],+ cwd: fs.realpathSync(dir),+ },+ {+ args: [+ 'pages', 'upload-code-site',+ '--rootPath', clonedPath,+ '--siteName', 'Supplier Portal',+ ],+ cwd: fs.realpathSync(dir),+ },+ ]);+ assert.deepEqual(npmCalls, [+ [[+ 'ci',+ '--no-audit',+ '--no-fund',+ ], clonedPath],+ [['run', 'build'], clonedPath],+ ]);+});++test('provisionTemplateSite stops after clone failure and reports the failed step', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const source = path.join(dir, 'source');+ const output = path.join(dir, 'output');+ createSource(source);+ let calls = 0;++ const result = provisionTemplateSite({+ sourcePath: source,+ outputDirectory: output,+ siteName: '311 Portal',+ }, {+ runPac() {+ calls++;+ return { status: 1, stdout: '', stderr: 'clone rejected' };+ },+ });++ assert.equal(result.ok, false);+ assert.equal(result.step, 'clone');+ assert.equal(result.outputDirectoryRemoved, true);+ assert.match(result.error, /clone rejected/);+ assert.equal(calls, 1);+ assert.equal(fs.existsSync(output), false);+});++test('provisionTemplateSite preserves a pre-existing empty output directory after clone failure', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const source = path.join(dir, 'source');+ const output = path.join(dir, 'output');+ createSource(source);+ fs.mkdirSync(output);++ const result = provisionTemplateSite({+ sourcePath: source,+ outputDirectory: output,+ siteName: '311 Portal',+ }, {+ runPac() {+ fs.writeFileSync(path.join(output, 'partial.txt'), 'partial');+ return { status: 1, stdout: '', stderr: 'clone rejected' };+ },+ });++ assert.equal(result.outputDirectoryRemoved, false);+ assert.equal(fs.readFileSync(path.join(output, 'partial.txt'), 'utf8'), 'partial');+});++test('provisionTemplateSite runs PAC from the output parent for a pre-existing current-directory target', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const source = path.join(dir, 'source');+ const output = path.join(dir, 'current-directory');+ createSource(source);+ fs.mkdirSync(output);+ const pacWorkingDirectories = [];++ const result = provisionTemplateSite({+ sourcePath: source,+ outputDirectory: output,+ siteName: '311 Portal',+ }, {+ runPac(args, commandOptions) {+ pacWorkingDirectories.push(commandOptions && commandOptions.cwd);+ return { status: 1, stdout: '', stderr: 'clone rejected' };+ },+ });++ assert.equal(result.step, 'clone');+ assert.deepEqual(pacWorkingDirectories, [fs.realpathSync(dir)]);+});++test('provisionTemplateSite removes a new output directory when clone output cannot be resolved', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const source = path.join(dir, 'source');+ const output = path.join(dir, 'output');+ createSource(source);++ const result = provisionTemplateSite({+ sourcePath: source,+ outputDirectory: output,+ siteName: '311 Portal',+ }, {+ runPac() {+ fs.writeFileSync(path.join(output, 'unexpected.txt'), 'not a code site');+ return { status: 0, stdout: 'ok', stderr: '' };+ },+ });++ assert.equal(result.ok, false);+ assert.equal(result.step, 'clone-output');+ assert.equal(result.outputDirectoryRemoved, true);+ assert.equal(fs.existsSync(output), false);+});++test('provisionTemplateSite reports upload failure without retrying', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const source = path.join(dir, 'source');+ const output = path.join(dir, 'output');+ createSource(source);+ let calls = 0;++ const result = provisionTemplateSite({+ sourcePath: source,+ outputDirectory: output,+ siteName: 'Supplier Portal',+ }, {+ runPac(args) {+ calls++;+ if (args[1] === 'clone') {+ createSource(path.join(output, 'supplier-portal'), {+ id: CLONED_ID,+ name: 'Supplier Portal',+ });+ return { status: 0, stdout: 'cloned', stderr: '' };+ }+ return { status: 1, stdout: '', stderr: 'upload rejected' };+ },+ runNpm(args, cwd) {+ if (args[0] === 'run') {+ fs.mkdirSync(path.join(cwd, 'dist'));+ fs.writeFileSync(path.join(cwd, 'dist', 'index.html'), '<html></html>');+ }+ return { status: 0, stdout: 'ok', stderr: '' };+ },+ });++ assert.equal(result.ok, false);+ assert.equal(result.step, 'upload');+ assert.equal(result.clonedPath, path.join(output, 'supplier-portal'));+ assert.equal(result.websiteRecordId, CLONED_ID);+ assert.match(result.error, /upload rejected/);+ assert.equal(calls, 2);+});++test('provisionTemplateSite stops before upload when dependency installation fails', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const source = path.join(dir, 'source');+ const output = path.join(dir, 'output');+ createSource(source);+ const pacCalls = [];++ const result = provisionTemplateSite({+ sourcePath: source,+ outputDirectory: output,+ siteName: 'Supplier Portal',+ }, {+ runPac(args) {+ pacCalls.push(args);+ createSource(path.join(output, 'supplier-portal'), {+ id: CLONED_ID,+ name: 'Supplier Portal',+ });+ return { status: 0, stdout: 'ok', stderr: '' };+ },+ runNpm(args) {+ assert.equal(args[0], 'install');+ return { status: 1, stdout: '', stderr: 'install rejected' };+ },+ });++ assert.equal(result.ok, false);+ assert.equal(result.step, 'install');+ assert.match(result.error, /install rejected/);+ assert.equal(pacCalls.length, 1);+});++test('provisionTemplateSite stops before upload when the cloned project build fails', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const source = path.join(dir, 'source');+ const output = path.join(dir, 'output');+ createSource(source);+ const pacCalls = [];+ let npmCalls = 0;++ const result = provisionTemplateSite({+ sourcePath: source,+ outputDirectory: output,+ siteName: 'Supplier Portal',+ }, {+ runPac(args) {+ pacCalls.push(args);+ createSource(path.join(output, 'supplier-portal'), {+ id: CLONED_ID,+ name: 'Supplier Portal',+ });+ return { status: 0, stdout: 'ok', stderr: '' };+ },+ runNpm(args) {+ npmCalls++;+ return args[0] === 'run'+ ? { status: 1, stdout: '', stderr: 'build rejected' }+ : { status: 0, stdout: 'ok', stderr: '' };+ },+ });++ assert.equal(result.ok, false);+ assert.equal(result.step, 'build');+ assert.match(result.error, /build rejected/);+ assert.equal(npmCalls, 2);+ assert.equal(pacCalls.length, 1);+});++test('provisionTemplateSite stops before upload when build output is missing', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const source = path.join(dir, 'source');+ const output = path.join(dir, 'output');+ createSource(source);+ const pacCalls = [];++ const result = provisionTemplateSite({+ sourcePath: source,+ outputDirectory: output,+ siteName: 'Supplier Portal',+ }, {+ runPac(args) {+ pacCalls.push(args);+ createSource(path.join(output, 'supplier-portal'), {+ id: CLONED_ID,+ name: 'Supplier Portal',+ });+ return { status: 0, stdout: 'ok', stderr: '' };+ },+ runNpm() {+ return { status: 0, stdout: 'ok', stderr: '' };+ },+ });++ assert.equal(result.ok, false);+ assert.equal(result.step, 'build-output');+ assert.match(result.error, /not a regular directory/);+ assert.equal(pacCalls.length, 1);+});++test('provisionTemplateSite stops before upload when clone metadata has no valid website id', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const source = path.join(dir, 'source');+ const output = path.join(dir, 'output');+ createSource(source);+ let calls = 0;++ const result = provisionTemplateSite({+ sourcePath: source,+ outputDirectory: output,+ siteName: 'Supplier Portal',+ }, {+ runPac(args) {+ calls++;+ if (args[1] === 'clone') {+ createSource(path.join(output, 'supplier-portal'), {+ id: 'not-a-guid',+ name: 'Supplier Portal',+ });+ }+ return { status: 0, stdout: 'ok', stderr: '' };+ },+ });++ assert.equal(result.ok, false);+ assert.equal(result.step, 'clone-output');+ assert.match(result.error, /missing a valid id/);+ assert.equal(calls, 1);+});++test('provisionTemplateSite rejects non-empty output directories', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const source = path.join(dir, 'source');+ const output = path.join(dir, 'output');+ createSource(source);+ fs.mkdirSync(output);+ fs.writeFileSync(path.join(output, 'stale.txt'), 'stale');++ const result = provisionTemplateSite({+ sourcePath: source,+ outputDirectory: output,+ siteName: '311 Portal',+ });++ assert.deepEqual(result, { ok: false, step: 'validation', error: 'outputDirectory must be empty' });+});++test('provisionTemplateSite rejects an output path that is a file', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const source = path.join(dir, 'source');+ const outputFile = path.join(dir, 'output');+ createSource(source);+ fs.writeFileSync(outputFile, 'not a directory');++ assert.deepEqual(+ provisionTemplateSite({+ sourcePath: source,+ outputDirectory: outputFile,+ siteName: '311 Portal',+ }),+ {+ ok: false,+ step: 'validation',+ error: 'outputDirectory must be a regular directory when it exists',+ }+ );+});++test('provisionTemplateSite rejects case-variant output paths inside the source on Windows', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const source = path.join(dir, 'TemplateSource');+ createSource(source);++ const result = provisionTemplateSite({+ sourcePath: source,+ outputDirectory: path.join(dir, 'templatesource', 'clone'),+ siteName: '311 Portal',+ }, {+ platform: 'win32',+ });++ assert.deepEqual(result, {+ ok: false,+ step: 'validation',+ error: 'outputDirectory must be separate from sourcePath',+ });+});++test('provisionTemplateSite rejects output paths whose existing parent resolves into the source', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const source = path.join(dir, 'source');+ createSource(source);+ const linkedParent = path.join(dir, 'linked-source');+ try {+ fs.symlinkSync(source, linkedParent, 'dir');+ } catch (err) {+ if (err.code === 'EPERM' || err.code === 'EACCES') {+ t.skip(`directory symlinks are unavailable: ${err.code}`);+ return;+ }+ throw err;+ }++ const result = provisionTemplateSite({+ sourcePath: source,+ outputDirectory: path.join(linkedParent, 'clone'),+ siteName: '311 Portal',+ });++ assert.deepEqual(result, {+ ok: false,+ step: 'validation',+ error: 'outputDirectory must be separate from sourcePath',+ });+});++test('provisionTemplateSite requires project-local npm configuration', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const source = path.join(dir, 'source');+ createSource(source);+ fs.rmSync(path.join(source, '.npmrc'));++ const result = provisionTemplateSite({+ sourcePath: source,+ outputDirectory: path.join(dir, 'output'),+ siteName: '311 Portal',+ });++ assert.deepEqual(result, {+ ok: false,+ step: 'validation',+ error: 'sourcePath is not a downloaded Power Pages code site',+ });+});++test('provisionTemplateSite restores project files omitted by PAC without replacing cloned identity', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const source = path.join(dir, 'source');+ const output = path.join(dir, 'output');+ createSource(source);+ fs.writeFileSync(path.join(source, 'dataverse-choice-values.json'), '{"status":{"Open":100000000}}');+ fs.mkdirSync(path.join(source, 'tests'));+ fs.writeFileSync(path.join(source, 'tests', 'serviceRequests.test.mjs'), 'export {};\n');+ fs.mkdirSync(path.join(source, '.powerpages-site', '.portalconfig'));+ fs.writeFileSync(path.join(source, '.powerpages-site', '.portalconfig', 'manifest.yml'), 'portalVersion: 1\n');+ const npmCalls = [];+ let pacCalls = 0;++ const result = provisionTemplateSite({+ sourcePath: source,+ outputDirectory: output,+ siteName: '311 Portal',+ }, {+ runPac(args) {+ pacCalls++;+ if (args[1] === 'clone') {+ const clonedPath = path.join(output, '311-portal');+ createSource(clonedPath, { id: CLONED_ID, name: '311 Portal' });+ fs.rmSync(path.join(clonedPath, '.npmrc'));+ }+ return { status: 0, stdout: 'ok', stderr: '' };+ },+ runNpm(args, cwd) {+ npmCalls.push(args);+ assert.equal(fs.existsSync(path.join(cwd, '.npmrc')), true);+ assert.equal(fs.existsSync(path.join(cwd, 'dataverse-choice-values.json')), true);+ assert.equal(fs.existsSync(path.join(cwd, 'tests', 'serviceRequests.test.mjs')), true);+ assert.equal(fs.existsSync(path.join(cwd, '.powerpages-site', '.portalconfig', 'manifest.yml')), true);+ if (args[0] === 'run') {+ fs.mkdirSync(path.join(cwd, 'dist'));+ fs.writeFileSync(path.join(cwd, 'dist', 'index.html'), '<html></html>');+ }+ return { status: 0, stdout: 'ok', stderr: '' };+ },+ });++ assert.equal(result.ok, true);+ assert.equal(result.websiteRecordId, CLONED_ID);+ assert.equal(pacCalls, 2);+ assert.deepEqual(npmCalls.map((args) => args[0]), ['install', 'run']);+ assert.equal(+ fs.readFileSync(path.join(output, '311-portal', '.npmrc'), 'utf8'),+ fs.readFileSync(path.join(source, '.npmrc'), 'utf8')+ );+});++test('copyMissingTemplateFiles rejects source symlinks and preserves cloned website metadata', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const source = path.join(dir, 'source');+ const clone = path.join(dir, 'clone');+ createSource(source, { id: SOURCE_ID });+ createSource(clone, { id: CLONED_ID });+ fs.writeFileSync(path.join(source, 'extra.json'), '{}');++ assert.deepEqual(copyMissingTemplateFiles(source, clone), ['extra.json']);+ assert.match(+ fs.readFileSync(path.join(clone, '.powerpages-site', 'website.yml'), 'utf8'),+ new RegExp(CLONED_ID)+ );++ const target = path.join(dir, 'outside.json');+ const link = path.join(source, 'linked.json');+ fs.writeFileSync(target, '{}');+ try {+ fs.symlinkSync(target, link);+ } catch (err) {+ if (err.code === 'EPERM' || err.code === 'EACCES') {+ t.skip(`symlinks are unavailable: ${err.code}`);+ return;+ }+ throw err;+ }+ assert.throws(+ () => copyMissingTemplateFiles(source, clone),+ /symbolic link: linked\.json/+ );+});++test('runPac invokes pac.exe directly on Windows without a command shell', () => {+ const calls = [];+ runPac(['pages', 'clone', '--path', 'source'], {+ platform: 'win32',+ cwd: 'C:\\stable-parent',+ runCommand(command, args, options) {+ calls.push([command, args, options]);+ return 'ok';+ },+ });+ assert.equal(calls[0][0], 'pac.exe');+ assert.deepEqual(calls[0][1], ['pages', 'clone', '--path', 'source']);+ assert.equal(calls[0][2].cwd, 'C:\\stable-parent');+ assert.equal(calls[0][2].shell, false);+});++test('runNpm invokes the Windows npm.cmd shim through cmd.exe without a command shell', () => {+ const calls = [];+ runNpm(['run', 'build'], '/tmp/site', {+ platform: 'win32',+ runNpmCommand(command, args, options) {+ calls.push([command, args, options]);+ return 'ok';+ },+ });+ assert.equal(calls[0][0], 'cmd.exe');+ assert.deepEqual(calls[0][1], ['/d', '/s', '/c', 'npm.cmd', 'run', 'build']);+ assert.equal(calls[0][2].cwd, '/tmp/site');+ assert.equal(calls[0][2].shell, false);+});diff --git a/plugins/power-pages/scripts/tests/render-template-browser.test.js b/plugins/power-pages/scripts/tests/render-template-browser.test.jsnew file mode 100644index 000000000..e17944357--- /dev/null+++ b/plugins/power-pages/scripts/tests/render-template-browser.test.js@@ -0,0 +1,264 @@+'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 {+ parseArgs,+ renderTemplateBrowser,+ validateRenderedTemplateBrowser,+} = require('../render-template-browser');++function tempDir() {+ return fs.mkdtempSync(path.join(os.tmpdir(), 'template-browser-test-'));+}++test('parseArgs accepts templates JSON, output path, and open switch', () => {+ assert.deepEqual(parseArgs([+ '--templatesJsonPath', '/tmp/templates.json',+ '--outputPath', '/tmp/browser.html',+ '--open',+ ]), {+ templatesJsonPath: '/tmp/templates.json',+ outputPath: '/tmp/browser.html',+ open: true,+ });+});++test('renderTemplateBrowser renders static template details and preview images', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const dataPath = path.join(dir, 'templates.json');+ const outputPath = path.join(dir, 'browser.html');+ fs.writeFileSync(dataPath, JSON.stringify({+ TEMPLATES_JSON: [+ {+ displayName: 'Company "Portal"',+ description: 'Internal site',+ framework: 'react',+ audience: ['makers', 'developers'],+ keywords: ['portal', 'directory'],+ previewImages: [+ 'https://raw.githubusercontent.com/o/r/sha/templates/spa/company/previews/home.png',+ 'https://raw.githubusercontent.com/o/r/sha/templates/spa/company/previews/detail.png',+ 'https://example.test/image.png" onerror="globalThis.pwned=1',+ ],+ },+ {+ displayName: '311 Portal',+ description: 'Citizen service request portal',+ framework: 'react',+ audience: ['makers'],+ keywords: ['311'],+ previewImages: [+ 'https://raw.githubusercontent.com/o/r/sha/templates/spa/311/previews/home.png',+ ],+ },+ ],+ }));++ const result = renderTemplateBrowser({ templatesJsonPath: dataPath, outputPath, open: false });+ const html = fs.readFileSync(outputPath, 'utf8');++ assert.deepEqual(result, { status: 'ok', output: outputPath, opened: false });+ assert.match(html, /Browse Power Pages templates/);+ assert.match(html, /Company "Portal"/);+ assert.match(html, /311 Portal/);+ assert.match(html, /home\.png/);+ assert.match(html, /detail\.png/);+ assert.match(html, /data-tab="template-1"/);+ assert.match(html, /data-tab="template-2"/);+ assert.match(html, /class="template-section active" id="template-1"/);+ assert.match(html, /class="template-section" id="template-2"/);+ assert.match(html, /class="preview-boundary"/);+ assert.match(html, /<figcaption>Preview 2<\/figcaption>/);+ assert.match(html, /class="preview-image"/);+ assert.match(html, /Preview 2 of Company "Portal"/);+ assert.match(html, /src="https:\/\/example\.test\/image\.png" onerror="globalThis\.pwned=1"/);+ assert.doesNotMatch(html, /src="https:\/\/example\.test\/image\.png" onerror=/);+ assert.match(html, /border-bottom:2px solid transparent/);+ assert.match(html, /\.nav-btn\.active\{border-bottom-color:var\(--accent\);\}/);+ assert.match(html, /Citizen service request portal/);+ assert.doesNotMatch(html, /data-carousel/);+ assert.doesNotMatch(html, /carousel/);+ assert.doesNotMatch(html, /Audience/);+ assert.doesNotMatch(html, /makers/);+ assert.doesNotMatch(html, /developers/);+ assert.doesNotMatch(html, /picker/i);+ assert.doesNotMatch(html, /templates\.map/);+});++test('renderTemplateBrowser does not print the shared renderTemplate status line', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const dataPath = path.join(dir, 'templates.json');+ const outputPath = path.join(dir, 'browser.html');+ fs.writeFileSync(dataPath, JSON.stringify({+ TEMPLATES_JSON: [+ { displayName: 'Company Portal', description: 'Internal site', framework: 'react', previewImages: [] },+ ],+ }));+ const originalLog = console.log;+ const logs = [];+ console.log = (value) => logs.push(value);+ t.after(() => { console.log = originalLog; });++ renderTemplateBrowser({ templatesJsonPath: dataPath, outputPath, open: false });++ assert.deepEqual(logs, []);+});++test('renderTemplateBrowser renders one family with read-only framework variants', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const dataPath = path.join(dir, 'families.json');+ const outputPath = path.join(dir, 'browser.html');+ fs.writeFileSync(dataPath, JSON.stringify({+ TEMPLATES_JSON: [+ {+ id: 'supplier-portal',+ displayName: 'Supplier Portal',+ description: 'Supplier invoice portal',+ kind: 'spa',+ keywords: ['supplier', 'invoice'],+ previewImages: ['https://raw.githubusercontent.com/o/r/sha/templates/spa/supplier/previews/home.png'],+ variants: [+ { variantId: 'supplier-portal/react', variantKey: 'react', framework: 'react' },+ { variantId: 'supplier-portal/vue', variantKey: 'vue', framework: 'vue' },+ ],+ },+ ],+ }));++ const result = renderTemplateBrowser({ templatesJsonPath: dataPath, outputPath, open: false });+ const html = fs.readFileSync(outputPath, 'utf8');++ assert.deepEqual(result, { status: 'ok', output: outputPath, opened: false });+ assert.match(html, /Supplier Portal/);+ assert.match(html, /supplier invoice portal/i);+ assert.match(html, /React/);+ assert.match(html, /Vue/);+ assert.match(html, /Available frameworks/);+ assert.match(html, /data-tab="template-1"/);+ assert.doesNotMatch(html, /data-tab="template-2"/);+});++test('renderTemplateBrowser accepts raw nested variant maps from the manifest', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const dataPath = path.join(dir, 'families-raw.json');+ const outputPath = path.join(dir, 'browser.html');+ fs.writeFileSync(dataPath, JSON.stringify({+ TEMPLATES_JSON: [+ {+ id: 'supplier-portal',+ displayName: 'Supplier Portal',+ description: 'Supplier invoice portal',+ kind: 'spa',+ keywords: ['supplier'],+ previewImages: [],+ variants: {+ react: {},+ vue: {},+ },+ },+ ],+ }));++ renderTemplateBrowser({ templatesJsonPath: dataPath, outputPath, open: false });+ const html = fs.readFileSync(outputPath, 'utf8');++ assert.match(html, /Available frameworks/);+ assert.match(html, /React/);+ assert.match(html, /Vue/);+ // Regression: the hero summary label must also read the object-map variants,+ // not just the "Available frameworks" chip row. Multiple variants collapse to+ // a count in the hero.+ assert.match(html, /template-framework">2 frameworks</);+});++test('renderTemplateBrowser shows a single object-map variant in the hero label', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const dataPath = path.join(dir, 'families-single.json');+ const outputPath = path.join(dir, 'browser.html');+ fs.writeFileSync(dataPath, JSON.stringify({+ TEMPLATES_JSON: [+ {+ id: '311-portal',+ displayName: '311 Portal',+ description: 'Citizen service requests',+ kind: 'spa',+ keywords: ['311'],+ previewImages: [],+ variants: {+ react: {},+ },+ },+ ],+ }));++ renderTemplateBrowser({ templatesJsonPath: dataPath, outputPath, open: false });+ const html = fs.readFileSync(outputPath, 'utf8');++ // Regression for the empty hero label: a single-variant object map must render+ // the framework name (not an empty string) in the hero.+ assert.match(html, /template-framework">React</);+});++test('renderTemplateBrowser reports opener failures without failing render', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const dataPath = path.join(dir, 'templates.json');+ const outputPath = path.join(dir, 'browser.html');+ fs.writeFileSync(dataPath, JSON.stringify({+ TEMPLATES_JSON: [{+ displayName: 'Company Portal',+ description: 'Internal site',+ framework: 'react',+ keywords: ['portal'],+ previewImages: [],+ }],+ }));++ const result = renderTemplateBrowser({+ templatesJsonPath: dataPath,+ outputPath,+ open: true,+ }, {+ execFileSync: () => { throw new Error('no opener'); },+ });++ assert.deepEqual(result, { status: 'ok', output: outputPath, opened: false, openError: 'no opener' });+ assert.equal(fs.existsSync(outputPath), true);+});++test('renderTemplateBrowser refuses to open an empty template browser', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const dataPath = path.join(dir, 'templates.json');+ const outputPath = path.join(dir, 'browser.html');+ fs.writeFileSync(dataPath, JSON.stringify({ TEMPLATES_JSON: [] }));++ const result = renderTemplateBrowser({ templatesJsonPath: dataPath, outputPath, open: true }, {+ execFileSync: () => { throw new Error('should not open invalid browser'); },+ });++ assert.equal(result.status, 'invalid');+ assert.equal(result.opened, false);+ assert.match(result.validation.errors.join('\n'), /must contain at least one template family/);+ assert.match(result.validation.errors.join('\n'), /empty-state/);+});++test('validateRenderedTemplateBrowser catches missing framework labels', () => {+ const result = validateRenderedTemplateBrowser({+ templates: [{ displayName: 'Supplier Portal', variants: { react: {}, vue: {} } }],+ html: '<h2>Supplier Portal</h2><span>React</span>',+ });++ assert.equal(result.ok, false);+ assert.match(result.errors.join('\n'), /missing framework Vue/);+});diff --git a/plugins/power-pages/scripts/tests/render-template-import-status.test.js b/plugins/power-pages/scripts/tests/render-template-import-status.test.jsnew file mode 100644index 000000000..3e2935324--- /dev/null+++ b/plugins/power-pages/scripts/tests/render-template-import-status.test.js@@ -0,0 +1,204 @@+'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 { jsonForScript, localizePreviewImages, parseArgs, renderTemplateImportStatus } = require('../render-template-import-status');++function tempDir() {+ return fs.mkdtempSync(path.join(os.tmpdir(), 'template-import-status-test-'));+}++test('parseArgs accepts import status page inputs', () => {+ assert.deepEqual(parseArgs([+ '--templateName', 'Supplier Portal',+ '--statusPath', '/tmp/status.json',+ '--outputPath', '/tmp/import.html',+ '--previewImagesJson', '["file:///tmp/a.png"]',+ '--solutionCount', '2',+ '--open',+ ]), {+ templateName: 'Supplier Portal',+ statusPath: '/tmp/status.json',+ outputPath: '/tmp/import.html',+ previewImages: ['file:///tmp/a.png'],+ solutionCount: 2,+ open: true,+ });+});++test('renderTemplateImportStatus renders scaffold-style slideshow, progress, and toast status UI', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const outputPath = path.join(dir, 'import.html');+ const statusPath = path.join(dir, 'status.json');++ const result = renderTemplateImportStatus({+ templateName: 'Supplier Portal',+ statusPath,+ outputPath,+ previewImages: ['file:///tmp/a.png', 'file:///tmp/b.png'],+ solutionCount: 2,+ });+ const html = fs.readFileSync(outputPath, 'utf8');++ assert.deepEqual(result, { status: 'ok', output: outputPath, statusPath });+ assert.match(html, /Setting up Supplier Portal template/);+ assert.equal(html.includes('file:///tmp/a.png'), true);+ assert.equal(html.includes('const STATUS_URL = "status.json"'), true);+ assert.match(html, /loading-wrapper/);+ assert.match(html, /ambient/);+ assert.match(html, /orbit-system/);+ assert.match(html, /core-shape/);+ assert.match(html, /preview-showcase/);+ assert.match(html, /previewFrame/);+ assert.match(html, /preview-track/);+ assert.match(html, /preview-card/);+ assert.match(html, /previewPrev/);+ assert.match(html, /previewNext/);+ assert.match(html, /previewPaused/);+ assert.match(html, /mouseenter/);+ assert.match(html, /translateX/);+ assert.match(html, /role="status" aria-live="polite"/);+ assert.match(html, /role="alert"/);+ assert.match(html, /status\.awaitingInput/);+ assert.match(html, /Waiting for your input/);+ assert.match(html, /status\.inputPrompt/);+ assert.match(html, /hideToast\('waiting'\)/);+ assert.match(html, /progressFill/);+ assert.match(html, /pillProgress/);+ assert.match(html, /phase-step active/);+ assert.match(html, /Installing solutions/);+ assert.match(html, /Creating site/);+ assert.match(html, /Seeding data/);+ assert.match(html, /Activating site/);+ assert.match(html, /phaseForStatus/);+ assert.match(html, /renderPhase/);+ assert.match(html, /status\.phase/);+ assert.match(html, /status\.phase === 'siteAndSeed'/);+ assert.match(html, /phaseSite\.classList\.add\('active'\)/);+ assert.match(html, /phaseSeed\.classList\.add\('active'\)/);+ assert.match(html, /template site and seeding data/);+ assert.match(html, /const SOLUTION_INSTALLED_LABEL = "Solutions installed"/);+ assert.match(html, /const SOLUTION_NOUN = "solutions"/);+ assert.match(html, /phaseSolution\.textContent = SOLUTION_INSTALLED_LABEL/);+ assert.match(html, /'Installing ' \+ TEMPLATE_NAME \+ ' ' \+ SOLUTION_NOUN/);+ assert.match(html, /phaseSite\.textContent = 'Created site'/);+ assert.match(html, /'Creating ' \+ TEMPLATE_NAME \+ ' template site'/);+ assert.match(html, /'Seeding ' \+ TEMPLATE_NAME \+ ' template data'/);+ assert.match(html, /'Activating ' \+ TEMPLATE_NAME \+ ' template site'/);+ assert.match(html, /TEMPLATE_NAME \+ ' template is ready'/);+ assert.match(html, /status\.state === 'succeeded' && status\.redirectUrl/);+ assert.match(html, /max-height: calc\(100vh - 390px\)/);+ assert.match(html, /@media \(max-height: 760px\)/);+ assert.doesNotMatch(html, /progressFromStatus/);+ assert.doesNotMatch(html, /status\.progress/);+ assert.doesNotMatch(html, /status\.percentComplete/);+ assert.doesNotMatch(html, /--progress-scale/);+ assert.match(html, /setInterval\(pollStatus, 1500\)/);+ assert.match(html, /Template site is ready/);+ assert.match(html, /status\.redirectUrl/);+ assert.match(html, /window\.location\.assign/);+ assert.match(html, /\^https\?:/);+ assert.match(html, /Template setup needs attention/);+});++test('renderTemplateImportStatus uses singular solution copy for one solution', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const outputPath = path.join(dir, 'import.html');+ const statusPath = path.join(dir, 'status.json');++ renderTemplateImportStatus({+ templateName: '311 Portal',+ statusPath,+ outputPath,+ solutionCount: 1,+ });+ const html = fs.readFileSync(outputPath, 'utf8');++ assert.match(html, /Installing solution/);+ assert.match(html, /const SOLUTION_INSTALLED_LABEL = "Solution installed"/);+ assert.match(html, /const SOLUTION_NOUN = "solution"/);+});++test('renderTemplateImportStatus rejects invalid solution counts', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ assert.throws(+ () => renderTemplateImportStatus({+ templateName: '311 Portal',+ statusPath: path.join(dir, 'status.json'),+ outputPath: path.join(dir, 'import.html'),+ solutionCount: 0,+ }),+ /positive integer/+ );+});++test('renderTemplateImportStatus does not print the shared renderTemplate status line', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const outputPath = path.join(dir, 'import.html');+ const statusPath = path.join(dir, 'status.json');+ const originalLog = console.log;+ const logs = [];+ console.log = (value) => logs.push(value);+ t.after(() => { console.log = originalLog; });++ renderTemplateImportStatus({ templateName: 'Supplier Portal', statusPath, outputPath });++ assert.deepEqual(logs, []);+});++test('localizePreviewImages copies local preview images beside the served page', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const sourcePath = path.join(dir, 'preview.png');+ const outputPath = path.join(dir, 'site', 'import.html');+ const imageBytes = Buffer.concat([+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),+ Buffer.from('fake png payload'),+ ]);+ fs.writeFileSync(sourcePath, imageBytes);++ const localized = localizePreviewImages([sourcePath], outputPath);++ assert.deepEqual(localized, ['preview-images/preview-01.png']);+ assert.deepEqual(+ fs.readFileSync(path.join(dir, 'site', 'preview-images', 'preview-01.png')),+ imageBytes+ );+});++test('localizePreviewImages rejects non-images, directories, and symlinks', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const outputPath = path.join(dir, 'site', 'import.html');+ const textPath = path.join(dir, 'secret.txt');+ const fakePngPath = path.join(dir, 'fake.png');+ const imagePath = path.join(dir, 'preview.png');+ const imageLink = path.join(dir, 'preview-link.png');+ fs.writeFileSync(textPath, 'secret');+ fs.writeFileSync(fakePngPath, 'not a png');+ fs.writeFileSync(imagePath, Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]));+ const inputs = [textPath, fakePngPath, dir];+ try {+ fs.symlinkSync(imagePath, imageLink);+ inputs.push(imageLink);+ } catch (err) {+ if (err.code !== 'EPERM') throw err;+ }++ assert.deepEqual(+ localizePreviewImages(inputs, outputPath),+ []+ );+});++test('jsonForScript escapes script-closing characters', () => {+ assert.equal(jsonForScript('status<bad>.json'), '"status\\u003cbad>.json"');+});diff --git a/plugins/power-pages/scripts/tests/serve-static-dir.test.js b/plugins/power-pages/scripts/tests/serve-static-dir.test.jsnew file mode 100644index 000000000..e8927cc86--- /dev/null+++ b/plugins/power-pages/scripts/tests/serve-static-dir.test.js@@ -0,0 +1,266 @@+'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 { EventEmitter } = require('events');++const {+ cleanupOwnedRoot,+ contentType,+ createCleanupOwnership,+ isServableFile,+ main,+ parseArgs,+ resolveNewFileWithinRoot,+ requestsServerShutdown,+ safeResolve,+ serverUrl,+ startServer,+ streamFile,+ waitForChildReady,+} = require('../serve-static-dir');++test('parseArgs reads static server options', () => {+ assert.deepEqual(parseArgs(['--root', '/tmp/import', '--urlFile', '/tmp/url.txt', '--port', '8123']), {+ root: '/tmp/import',+ urlFile: '/tmp/url.txt',+ host: '127.0.0.1',+ port: 8123,+ });+});++test('safeResolve keeps requests inside the served root', () => {+ const root = path.resolve('/tmp/import');+ assert.equal(safeResolve(root, '/status.json'), path.join(root, 'status.json'));+ assert.equal(safeResolve(root, '/'), path.join(root, 'index.html'));+ assert.equal(safeResolve(root, '/../secret.txt'), null);+});++test('safeResolve rejects malformed percent-encoding without throwing', () => {+ const root = path.resolve('/tmp/import');+ assert.equal(safeResolve(root, '/%E0%A4%A'), null);+});++test('isServableFile treats stat failures as not found', () => {+ const originalExistsSync = fs.existsSync;+ const originalLstatSync = fs.lstatSync;+ try {+ fs.existsSync = () => true;+ fs.lstatSync = () => { throw new Error('permission denied'); };+ assert.equal(isServableFile('/tmp/import/status.json'), false);+ } finally {+ fs.existsSync = originalExistsSync;+ fs.lstatSync = originalLstatSync;+ }+});++test('isServableFile rejects symbolic links', (t) => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'serve-static-dir-test-'));+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const target = path.join(dir, 'target.json');+ const link = path.join(dir, 'status.json');+ fs.writeFileSync(target, '{}');+ try {+ fs.symlinkSync(target, link);+ } catch (err) {+ if (err.code === 'EPERM') {+ t.skip('File symlinks require additional privileges on this platform');+ return;+ }+ throw err;+ }++ assert.equal(isServableFile(target), true);+ assert.equal(isServableFile(link), false);+});++test('isServableFile rejects files reached through a symlinked parent', (t) => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'serve-static-dir-root-'));+ const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'serve-static-dir-outside-'));+ t.after(() => {+ fs.rmSync(root, { recursive: true, force: true });+ fs.rmSync(outside, { recursive: true, force: true });+ });+ fs.writeFileSync(path.join(outside, 'secret.json'), '{"secret":true}');+ const linkedDir = path.join(root, 'linked-dir');+ try {+ fs.symlinkSync(outside, linkedDir, 'dir');+ } catch (err) {+ if (err.code === 'EPERM' || err.code === 'EACCES') {+ t.skip(`directory symlinks are unavailable: ${err.code}`);+ return;+ }+ throw err;+ }++ assert.equal(+ isServableFile(path.join(linkedDir, 'secret.json'), { root }),+ false+ );+});++test('contentType returns useful types for import status assets', () => {+ assert.equal(contentType('index.html'), 'text/html; charset=utf-8');+ assert.equal(contentType('status.json'), 'application/json; charset=utf-8');+ assert.equal(contentType('preview.png'), 'image/png');+});++test('serverUrl brackets IPv6 literals without changing IPv4 hosts', () => {+ assert.equal(serverUrl('127.0.0.1', 8123), 'http://127.0.0.1:8123/');+ assert.equal(serverUrl('::1', 8123), 'http://[::1]:8123/');+});++test('server shutdown requires the final workflow success marker', () => {+ assert.equal(requestsServerShutdown({ state: 'succeeded' }), false);+ assert.equal(requestsServerShutdown({ state: 'failed', shutdownServer: true }), false);+ assert.equal(requestsServerShutdown({ state: 'succeeded', shutdownServer: true }), true);+});++test('streamFile ends the response when read stream creation throws', () => {+ const writes = [];+ const res = {+ headersSent: false,+ writeHead: (status) => writes.push(['head', status]),+ end: (body) => writes.push(['end', body]),+ };++ streamFile('/tmp/import/status.json', res, {+ fs: {+ createReadStream: () => { throw new Error('gone'); },+ },+ });++ assert.deepEqual(writes, [['head', 404], ['end', 'Not found']]);+});++test('streamFile handles stream errors after headers are written', () => {+ const stream = new EventEmitter();+ stream.pipe = () => {};+ const writes = [];+ const res = {+ headersSent: true,+ writeHead: (status) => writes.push(['head', status]),+ end: (body) => writes.push(['end', body]),+ };++ streamFile('/tmp/import/status.json', res, {+ fs: {+ createReadStream: () => stream,+ },+ });+ stream.emit('error', new Error('gone'));++ assert.deepEqual(writes, [['end', undefined]]);+});++test('waitForChildReady resolves only after the child reports a listening URL', async () => {+ const child = new EventEmitter();+ const pending = waitForChildReady(child, 1000);+ process.nextTick(() => child.emit('message', { type: 'ready', url: 'http://127.0.0.1:8123/' }));+ assert.deepEqual(await pending, { type: 'ready', url: 'http://127.0.0.1:8123/' });+});++test('waitForChildReady rejects child startup errors', async () => {+ const child = new EventEmitter();+ const pending = waitForChildReady(child, 1000);+ process.nextTick(() => child.emit('message', { type: 'error', error: 'bind failed' }));+ await assert.rejects(pending, /bind failed/);+});++test('main waits for child readiness before writing the URL file', async (t) => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'serve-static-dir-main-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ fs.writeFileSync(path.join(root, 'index.html'), '<html></html>');+ fs.writeFileSync(path.join(root, 'status.json'), '{"state":"running"}');+ const child = new EventEmitter();+ child.pid = 1234;+ child.unref = () => {};+ child.kill = () => {};+ const urlFile = path.join(root, 'url.txt');+ const pending = main(['--root', root, '--urlFile', urlFile], {+ fork() {+ process.nextTick(() => child.emit('message', { type: 'ready', url: 'http://127.0.0.1:8123/' }));+ return child;+ },+ });++ assert.equal(fs.existsSync(urlFile), false);+ assert.deepEqual(await pending, { ok: true, url: 'http://127.0.0.1:8123/', pid: 1234 });+ assert.equal(fs.readFileSync(urlFile, 'utf8'), 'http://127.0.0.1:8123/');+});++test('URL file creation rejects a symlinked parent directory', async (t) => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'serve-static-dir-url-root-'));+ const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'serve-static-dir-url-outside-'));+ t.after(() => {+ fs.rmSync(root, { recursive: true, force: true });+ fs.rmSync(outside, { recursive: true, force: true });+ });+ const linkedDir = path.join(root, 'linked-dir');+ try {+ fs.symlinkSync(outside, linkedDir, process.platform === 'win32' ? 'junction' : 'dir');+ } catch (err) {+ if (err.code === 'EPERM' || err.code === 'EACCES') {+ t.skip(`directory symlinks are unavailable: ${err.code}`);+ return;+ }+ throw err;+ }++ assert.throws(+ () => resolveNewFileWithinRoot(root, path.join(linkedDir, 'url.txt')),+ /parent directories must be regular directories/+ );+ assert.equal(fs.existsSync(path.join(outside, 'url.txt')), false);+});++test('cleanup ownership removes only the owned temporary root', (t) => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'serve-static-dir-owned-'));+ const ownership = createCleanupOwnership(root);+ t.after(() => {+ fs.rmSync(root, { recursive: true, force: true });+ fs.rmSync(ownership.markerPath, { force: true });+ });+ fs.writeFileSync(path.join(root, 'status.json'), '{"state":"running"}');++ assert.equal(cleanupOwnedRoot({+ root: ownership.root,+ cleanupMarker: ownership.markerPath,+ cleanupToken: ownership.token,+ }), true);+ assert.equal(fs.existsSync(root), false);+ assert.equal(fs.existsSync(ownership.markerPath), false);+});++test('startServer closes and removes its temporary root after success', async (t) => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'serve-static-dir-success-'));+ fs.writeFileSync(path.join(root, 'index.html'), '<html></html>');+ const statusPath = path.join(root, 'status.json');+ fs.writeFileSync(statusPath, '{"state":"running"}');+ const ownership = createCleanupOwnership(root);+ const started = await startServer({+ root,+ host: '127.0.0.1',+ port: 0,+ statusPath,+ cleanupMarker: ownership.markerPath,+ cleanupToken: ownership.token,+ idleTimeoutMs: 2000,+ maxLifetimeMs: 2000,+ successGraceMs: 20,+ statusPollMs: 10,+ });+ t.after(() => {+ started.shutdown();+ fs.rmSync(root, { recursive: true, force: true });+ fs.rmSync(ownership.markerPath, { force: true });+ });++ fs.writeFileSync(statusPath, '{"state":"succeeded","shutdownServer":true}');+ await started.closed;+ assert.equal(fs.existsSync(root), false);+ assert.equal(fs.existsSync(ownership.markerPath), false);+});diff --git a/plugins/power-pages/scripts/tests/template-catalog.test.js b/plugins/power-pages/scripts/tests/template-catalog.test.jsnew file mode 100644index 000000000..8c3eec45d--- /dev/null+++ b/plugins/power-pages/scripts/tests/template-catalog.test.js@@ -0,0 +1,1412 @@+'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 { EventEmitter } = require('events');+const { PassThrough } = require('stream');++const {+ buildRawUrl,+ buildGitRemoteUrl,+ cacheDirForSha,+ artifactCachePath,+ ensurePrivateCacheRoot,+ requestJson,+ downloadFile,+ fetchCatalog,+ downloadArtifact,+ downloadTemplateVariant,+ downloadSeedDataDirectory,+ validateZipContainsSolution,+ validateWebsiteCodeDirectory,+ validateUnpackedSolutionDirectory,+ repositoryDirectoryCheckoutRoot,+ inspectTemplateSolutions,+ templateFamilyRoot,+ templateVariantRoot,+ zipFileNames,+ validateCatalogShape,+ assertValidSha,+ resolveRefToSha,+ normalizeCatalogFamilies,+} = require('../lib/template-catalog');+const { parseArgs: parseCatalogArgs } = require('../fetch-template-catalog');+const { parseArgs: parseVariantArgs } = require('../fetch-template-variant');+const { parseArgs: parseArtifactArgs } = require('../fetch-template-artifact');+const { parseArgs: parseSeedArgs } = require('../fetch-template-seed-data');+const { parseTemplateRepoArgs, formatJsonResult, runBestEffortJsonCli } = require('../lib/template-cli-args');++function tempDir() {+ return fs.mkdtempSync(path.join(os.tmpdir(), 'template-catalog-test-'));+}++const SHA = '1234567890abcdef1234567890abcdef12345678';+const VALID_TEMPLATE = {+ id: 'company-portal',+ displayName: 'Company Portal',+ description: 'Internal portal',+ kind: 'spa',+ framework: 'react',+ keywords: ['portal'],+ audience: ['makers', 'developers'],+ requiredDataverseLanguages: [1033],+ previewImages: ['templates/spa/company-portal/previews/home.png'],+ author: 'Microsoft',+};++const VALID_TEMPLATE_FAMILY = {+ id: 'supplier-portal',+ displayName: 'Supplier Portal',+ description: 'Supplier invoice portal',+ kind: 'spa',+ keywords: ['supplier', 'invoice'],+ audience: ['makers', 'developers'],+ requiredDataverseLanguages: [1033],+ previewImages: ['templates/spa/supplier-portal/previews/home.png'],+ seedDataPath: 'templates/spa/supplier-portal/seed-data/data.json',+ author: 'Microsoft',+ variants: {+ react: {},+ vue: {+ previewImages: ['templates/spa/supplier-portal/variants/vue/previews/home.png'],+ },+ },+};++const VALID_TRADITIONAL_TEMPLATE_FAMILY = {+ id: 'customer-self-service',+ displayName: 'Customer self-service',+ description: 'A traditional Power Pages website template',+ kind: 'traditional',+ keywords: ['customer-service'],+ audience: ['makers'],+ requiredDataverseLanguages: [1033],+ previewImages: [],+ author: 'Microsoft',+ variants: {+ none: {},+ },+};++function fakeZipWithLocalFile(name) {+ const nameBytes = Buffer.from(name, 'utf8');+ const header = Buffer.alloc(30);+ header.writeUInt32LE(0x04034b50, 0);+ header.writeUInt16LE(nameBytes.length, 26);+ header.writeUInt16LE(0, 28);+ return Buffer.concat([header, nameBytes]);+}++function writeUnpackedSolution(solutionPath, uniqueName, options = {}) {+ const other = path.join(solutionPath, 'Other');+ fs.mkdirSync(other, { recursive: true });+ fs.writeFileSync(+ path.join(other, 'Solution.xml'),+ `<ImportExportXml><SolutionManifest><UniqueName>${uniqueName}</UniqueName><Version>${options.version || '1.0.0.0'}</Version><Managed>0</Managed></SolutionManifest></ImportExportXml>`+ );+ fs.writeFileSync(+ path.join(other, 'Customizations.xml'),+ options.websiteComponents+ ? '<ImportExportXml><powerpagecomponents /></ImportExportXml>'+ : '<ImportExportXml />'+ );+}++test('builds raw and git remote URLs from repo and template-relative paths', () => {+ assert.equal(buildGitRemoteUrl({ owner: 'microsoft', repo: 'power-pages-samples' }), 'https://github.com/microsoft/power-pages-samples.git');+ assert.equal(+ buildRawUrl({ owner: 'microsoft', repo: 'power-pages-samples', sha: SHA, filePath: 'templates/spa/hr portal/manifest.json' }),+ `https://raw.githubusercontent.com/microsoft/power-pages-samples/${SHA}/templates/spa/hr%20portal/manifest.json`+ );+});++test('rejects non-commit refs where a pinned sha is required', () => {+ assert.throws(() => assertValidSha('main'), /Expected an immutable 40-character commit sha/);+ assert.throws(+ () => buildRawUrl({ owner: 'o', repo: 'r', sha: '../escape', filePath: 'templates/manifest.json' }),+ /Expected an immutable 40-character commit sha/+ );+});++test('resolveRefToSha resolves refs with git ls-remote', async () => {+ const seen = [];+ const sha = resolveRefToSha({ owner: 'o', repo: 'r', ref: 'main' }, {+ execFileSync: (cmd, args) => {+ seen.push([cmd, args]);+ return `${SHA}\trefs/heads/main\n`;+ },+ });++ assert.equal(sha, SHA);+ assert.deepEqual(seen, [['git', ['ls-remote', 'https://github.com/o/r.git', 'main']]]);+});++test('fetchCatalog resolves the latest release to a sha, fetches the catalog at that sha, and creates a sha cache dir', async (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const seen = [];+ const gitCalls = [];+ const catalog = { manifestVersion: '1.0', templates: [VALID_TEMPLATE] };++ const result = await fetchCatalog({ owner: 'o', repo: 'r', cacheRoot: dir }, {+ execFileSync: (cmd, args) => {+ gitCalls.push([cmd, args]);+ assert.deepEqual(args, ['ls-remote', '--tags', 'https://github.com/o/r.git']);+ return [+ `${'0'.repeat(40)}\trefs/tags/templates-v0.9.0`,+ `${SHA}\trefs/tags/templates-v1.0.0`,+ ].join('\n');+ },+ requestJson: async (url) => {+ seen.push(url);+ if (url === `https://raw.githubusercontent.com/o/r/${SHA}/templates/manifest.json`) return catalog;+ throw new Error(`unexpected url: ${url}`);+ },+ });++ assert.deepEqual(result, {+ ok: true,+ owner: 'o',+ repo: 'r',+ ref: 'latest-release',+ resolvedRef: 'templates-v1.0.0',+ sha: SHA,+ releaseName: 'templates-v1.0.0',+ releaseUrl: 'https://github.com/o/r/releases/tag/templates-v1.0.0',+ catalogPath: 'templates/manifest.json',+ catalogLocalPath: path.join(dir, SHA, 'templates/manifest.json'),+ cacheDir: path.join(dir, SHA),+ catalog,+ selectableCatalog: {+ ...catalog,+ templates: normalizeCatalogFamilies(catalog),+ },+ });+ assert.deepEqual(gitCalls, [['git', ['ls-remote', '--tags', 'https://github.com/o/r.git']]]);+ assert.deepEqual(seen, [+ `https://raw.githubusercontent.com/o/r/${SHA}/templates/manifest.json`,+ ]);+ assert.equal(fs.existsSync(path.join(dir, SHA)), true);+ assert.deepEqual(JSON.parse(fs.readFileSync(path.join(dir, SHA, 'templates/manifest.json'), 'utf8')), catalog);+});++test('fetchCatalog rejects a symlinked catalog cache file without modifying its target', async (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ ensurePrivateCacheRoot(dir);+ const catalogPath = path.join(dir, SHA, 'templates', 'manifest.json');+ const outsidePath = path.join(dir, 'outside.json');+ fs.mkdirSync(path.dirname(catalogPath), { recursive: true });+ fs.writeFileSync(outsidePath, 'do not overwrite');+ try {+ fs.symlinkSync(outsidePath, catalogPath);+ } catch (err) {+ if (err.code === 'EPERM' || err.code === 'EACCES') {+ t.skip(`symlinks are unavailable: ${err.code}`);+ return;+ }+ throw err;+ }++ const result = await fetchCatalog({ owner: 'o', repo: 'r', ref: 'main', cacheRoot: dir }, {+ execFileSync: () => `${SHA}\trefs/heads/main\n`,+ requestJson: async () => ({ manifestVersion: '1.0', templates: [VALID_TEMPLATE] }),+ });++ assert.equal(result.ok, false);+ assert.match(result.error, /cache file must be a regular file/);+ assert.equal(fs.readFileSync(outsidePath, 'utf8'), 'do not overwrite');+});++test('fetchCatalog rejects symlinked directories inside the catalog cache path', async (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ ensurePrivateCacheRoot(dir);+ const outsideDir = path.join(dir, 'outside');+ const templatesPath = path.join(dir, SHA, 'templates');+ fs.mkdirSync(path.dirname(templatesPath), { recursive: true });+ fs.mkdirSync(outsideDir);+ try {+ fs.symlinkSync(outsideDir, templatesPath, process.platform === 'win32' ? 'junction' : 'dir');+ } catch (err) {+ if (err.code === 'EPERM' || err.code === 'EACCES') {+ t.skip(`symlinks are unavailable: ${err.code}`);+ return;+ }+ throw err;+ }++ const result = await fetchCatalog({ owner: 'o', repo: 'r', ref: 'main', cacheRoot: dir }, {+ execFileSync: () => `${SHA}\trefs/heads/main\n`,+ requestJson: async () => ({ manifestVersion: '1.0', templates: [VALID_TEMPLATE] }),+ });++ assert.equal(result.ok, false);+ assert.match(result.error, /cache path must contain only real directories/);+ assert.equal(fs.existsSync(path.join(outsideDir, 'manifest.json')), false);+});++test('fetchCatalog resolves non-derived artifact paths relative to the catalog folder', async (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const catalog = {+ manifestVersion: '1.0',+ templates: [{+ ...VALID_TEMPLATE,+ previewImages: ['spa/company-portal/previews/home.png', 'templates/spa/company-portal/previews/already-rooted.png'],+ seedDataPath: 'spa/company-portal/seed/data.json',+ }],+ };++ const result = await fetchCatalog({ owner: 'o', repo: 'r', ref: 'templates-v1.0.0', cacheRoot: dir }, {+ execFileSync: (cmd, args) => {+ assert.deepEqual([cmd, args], ['git', ['ls-remote', 'https://github.com/o/r.git', 'templates-v1.0.0']]);+ return `${SHA}\trefs/tags/templates-v1.0.0\n`;+ },+ requestJson: async (url) => {+ if (url === `https://raw.githubusercontent.com/o/r/${SHA}/templates/manifest.json`) return catalog;+ throw new Error(`unexpected url: ${url}`);+ },+ });++ assert.equal(result.ok, true);+ assert.deepEqual(result.catalog.templates[0].previewImages, [+ 'templates/spa/company-portal/previews/home.png',+ 'templates/spa/company-portal/previews/already-rooted.png',+ ]);+ assert.equal(result.catalog.templates[0].seedDataPath, 'templates/spa/company-portal/seed/data.json');+});++test('validateCatalogShape accepts nested template families with framework variants', () => {+ assert.equal(validateCatalogShape({ manifestVersion: '2.0', templates: [VALID_TEMPLATE_FAMILY] }), null);+});++test('validateCatalogShape rejects manifest paths that are derived from template identity', () => {+ const traditionalFlatTemplate = {+ ...VALID_TEMPLATE,+ id: 'traditional-flat-template',+ kind: 'traditional',+ framework: 'none',+ };++ assert.equal(+ validateCatalogShape({+ manifestVersion: '2.0',+ templates: [VALID_TEMPLATE_FAMILY, VALID_TRADITIONAL_TEMPLATE_FAMILY, traditionalFlatTemplate],+ }),+ null+ );+ assert.match(+ validateCatalogShape({+ manifestVersion: '2.0',+ templates: [{+ ...VALID_TEMPLATE_FAMILY,+ variants: {+ react: {+ solutionPath: 'templates/spa/supplier-portal/variants/react/solution',+ },+ },+ }],+ }),+ /must not define derivable solutionPath or websiteCodePath/+ );+ assert.match(+ validateCatalogShape({+ manifestVersion: '2.0',+ templates: [{+ ...VALID_TRADITIONAL_TEMPLATE_FAMILY,+ variants: {+ none: {+ websiteCodePath: 'templates/traditional/customer-self-service/variants/none/website-code',+ },+ },+ }],+ }),+ /must not define derivable solutionPath or websiteCodePath/+ );+});++test('fetchCatalog keeps traditional entries but exposes only SPA templates for selection', async (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const catalog = {+ manifestVersion: '2.0',+ templates: [+ VALID_TEMPLATE_FAMILY,+ VALID_TRADITIONAL_TEMPLATE_FAMILY,+ ],+ };++ const result = await fetchCatalog({ owner: 'o', repo: 'r', ref: 'templates-v2.0.0', cacheRoot: dir }, {+ execFileSync: () => `${SHA}\trefs/tags/templates-v2.0.0\n`,+ requestJson: async () => catalog,+ });++ assert.equal(result.ok, true);+ assert.equal(result.catalog.templates.length, 2);+ assert.deepEqual(result.selectableCatalog.templates.map((template) => template.id), ['supplier-portal']);+ assert.deepEqual(+ result.selectableCatalog.templates[0].variants.map((variant) => variant.variantKey),+ ['react', 'vue']+ );+ assert.equal(result.catalog.templates[1].variants.none.websiteCodePath, undefined);+ assert.equal(result.catalog.templates[1].variants.none.solutionPath, undefined);+});++test('validateCatalogShape rejects duplicate framework variants in a family', () => {+ const family = {+ ...VALID_TEMPLATE_FAMILY,+ variants: {+ react: VALID_TEMPLATE_FAMILY.variants.react,+ React: VALID_TEMPLATE_FAMILY.variants.react,+ },+ };++ assert.match(+ validateCatalogShape({ templates: [family] }),+ /duplicate framework variant/i+ );+});++test('fetchCatalog materializes nested preview and seed artifact paths', async (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const catalog = {+ manifestVersion: '2.0',+ templates: [{+ ...VALID_TEMPLATE_FAMILY,+ previewImages: ['spa/supplier-portal/previews/home.png'],+ seedDataPath: 'spa/supplier-portal/seed-data/data.json',+ variants: {+ react: {},+ vue: {+ previewImages: ['spa/supplier-portal/variants/vue/previews/home.png'],+ seedDataPath: 'spa/supplier-portal/variants/vue/seed-data/data.json',+ },+ },+ }],+ };++ const result = await fetchCatalog({ owner: 'o', repo: 'r', ref: 'templates-v2.0.0', cacheRoot: dir }, {+ execFileSync: () => `${SHA}\trefs/tags/templates-v2.0.0\n`,+ requestJson: async () => catalog,+ });++ assert.equal(result.ok, true);+ assert.deepEqual(result.catalog.templates[0].previewImages, ['templates/spa/supplier-portal/previews/home.png']);+ assert.equal(result.catalog.templates[0].seedDataPath, 'templates/spa/supplier-portal/seed-data/data.json');+ assert.deepEqual(result.catalog.templates[0].variants.vue.previewImages, ['templates/spa/supplier-portal/variants/vue/previews/home.png']);+ assert.equal(result.catalog.templates[0].variants.vue.seedDataPath, 'templates/spa/supplier-portal/variants/vue/seed-data/data.json');+});++test('normalizeCatalogFamilies exposes exact variant records with family metadata', () => {+ const families = normalizeCatalogFamilies({ templates: [VALID_TEMPLATE_FAMILY] });++ assert.deepEqual(families, [{+ id: 'supplier-portal',+ displayName: 'Supplier Portal',+ description: 'Supplier invoice portal',+ kind: 'spa',+ keywords: ['supplier', 'invoice'],+ audience: ['makers', 'developers'],+ requiredDataverseLanguages: [1033],+ previewImages: ['templates/spa/supplier-portal/previews/home.png'],+ seedDataPath: 'templates/spa/supplier-portal/seed-data/data.json',+ author: 'Microsoft',+ variants: [+ {+ familyId: 'supplier-portal',+ variantKey: 'react',+ variantId: 'supplier-portal/react',+ displayName: 'Supplier Portal',+ description: 'Supplier invoice portal',+ kind: 'spa',+ framework: 'react',+ keywords: ['supplier', 'invoice'],+ audience: ['makers', 'developers'],+ requiredDataverseLanguages: [1033],+ previewImages: ['templates/spa/supplier-portal/previews/home.png'],+ seedDataPath: 'templates/spa/supplier-portal/seed-data/data.json',+ author: 'Microsoft',+ },+ {+ familyId: 'supplier-portal',+ variantKey: 'vue',+ variantId: 'supplier-portal/vue',+ displayName: 'Supplier Portal',+ description: 'Supplier invoice portal',+ kind: 'spa',+ framework: 'vue',+ keywords: ['supplier', 'invoice'],+ audience: ['makers', 'developers'],+ requiredDataverseLanguages: [1033],+ previewImages: ['templates/spa/supplier-portal/variants/vue/previews/home.png'],+ seedDataPath: 'templates/spa/supplier-portal/seed-data/data.json',+ author: 'Microsoft',+ },+ ],+ }]);+});++test('fetchCatalog falls back to main when no semver tags exist yet', async (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const catalog = { manifestVersion: '1.0', templates: [VALID_TEMPLATE] };+ const seen = [];+ const gitCalls = [];++ const result = await fetchCatalog({ owner: 'o', repo: 'r', cacheRoot: dir }, {+ execFileSync: (cmd, args) => {+ gitCalls.push([cmd, args]);+ if (args[1] === '--tags') return '';+ assert.deepEqual(args, ['ls-remote', 'https://github.com/o/r.git', 'main']);+ return `${SHA}\trefs/heads/main\n`;+ },+ requestJson: async (url) => {+ seen.push(url);+ if (url === `https://raw.githubusercontent.com/o/r/${SHA}/templates/manifest.json`) return catalog;+ throw new Error(`unexpected url: ${url}`);+ },+ });++ assert.equal(result.ok, true);+ assert.equal(result.ref, 'latest-release');+ assert.equal(result.resolvedRef, 'main');+ assert.deepEqual(gitCalls, [+ ['git', ['ls-remote', '--tags', 'https://github.com/o/r.git']],+ ['git', ['ls-remote', 'https://github.com/o/r.git', 'main']],+ ]);+ assert.deepEqual(seen, [+ `https://raw.githubusercontent.com/o/r/${SHA}/templates/manifest.json`,+ ]);+});++test('fetchCatalog still accepts an explicit ref override for tests or pinned rollouts', async (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const catalog = { manifestVersion: '1.0', templates: [VALID_TEMPLATE] };+ const seen = [];++ const result = await fetchCatalog({ owner: 'o', repo: 'r', ref: 'templates-v0.9.0', cacheRoot: dir }, {+ execFileSync: (cmd, args) => {+ assert.deepEqual([cmd, args], ['git', ['ls-remote', 'https://github.com/o/r.git', 'templates-v0.9.0']]);+ return `${SHA}\trefs/tags/templates-v0.9.0\n`;+ },+ requestJson: async (url) => {+ seen.push(url);+ if (url === `https://raw.githubusercontent.com/o/r/${SHA}/templates/manifest.json`) return catalog;+ throw new Error(`unexpected url: ${url}`);+ },+ });++ assert.equal(result.ok, true);+ assert.equal(result.ref, 'templates-v0.9.0');+ assert.equal(result.resolvedRef, 'templates-v0.9.0');+ assert.deepEqual(seen, [+ `https://raw.githubusercontent.com/o/r/${SHA}/templates/manifest.json`,+ ]);+});++test('fetchCatalog returns ok:false so create-site can fall back when the catalog is unreachable', async (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const result = await fetchCatalog({ owner: 'o', repo: 'r', ref: 'main', cacheRoot: dir }, {+ execFileSync: () => `${SHA}\trefs/heads/main\n`,+ requestJson: async (url) => {+ throw new Error('network unavailable');+ },+ });++ assert.equal(result.ok, false);+ assert.equal(result.owner, 'o');+ assert.equal(result.repo, 'r');+ assert.equal(result.ref, 'main');+ assert.match(result.error, /network unavailable/);+ assert.equal(fs.existsSync(path.join(dir, SHA)), false, 'failed catalog fetch must not leave a sha cache dir');+});++test('fetchCatalog treats malformed catalogs as ok:false without creating a sha cache dir', async (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const result = await fetchCatalog({ owner: 'o', repo: 'r', ref: 'main', cacheRoot: dir }, {+ execFileSync: () => `${SHA}\trefs/heads/main\n`,+ requestJson: async (url) => {+ return { manifestVersion: '1.0' };+ },+ });++ assert.equal(result.ok, false);+ assert.match(result.error, /malformed/);+ assert.equal(fs.existsSync(path.join(dir, SHA)), false, 'malformed catalog must not leave a sha cache dir');+});++test('fetchCatalog treats malformed template entries as ok:false without creating a sha cache dir', async (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const result = await fetchCatalog({ owner: 'o', repo: 'r', ref: 'main', cacheRoot: dir }, {+ execFileSync: () => `${SHA}\trefs/heads/main\n`,+ requestJson: async (url) => {+ return { manifestVersion: '1.0', templates: [{ id: 'missing-fields' }] };+ },+ });++ assert.equal(result.ok, false);+ assert.match(result.error, /missing string field/);+ assert.equal(fs.existsSync(path.join(dir, SHA)), false, 'malformed entries must not leave a sha cache dir');+});++test('validateCatalogShape accepts a complete template entry and rejects broken entries', () => {+ assert.equal(validateCatalogShape({ templates: [VALID_TEMPLATE] }), null);+ assert.equal(validateCatalogShape({ templates: [{ ...VALID_TEMPLATE, previewImages: [] }] }), null);+ assert.match(validateCatalogShape({ templates: [{ ...VALID_TEMPLATE, previewImages: 'templates/spa/company/home.png' }] }), /previewImages/);+ assert.match(validateCatalogShape({ templates: [{ ...VALID_TEMPLATE, keywords: 'portal' }] }), /keywords/);+ assert.match(validateCatalogShape({ templates: [{ ...VALID_TEMPLATE, requiredDataverseLanguages: [] }] }), /requiredDataverseLanguages/);+ assert.match(validateCatalogShape({ templates: [{ ...VALID_TEMPLATE, requiredDataverseLanguages: ['1033'] }] }), /requiredDataverseLanguages/);+ assert.match(+ validateCatalogShape({ templates: [{ ...VALID_TEMPLATE, websiteCodePath: '' }] }),+ /must not define derivable solutionPath or websiteCodePath/+ );+ assert.match(+ validateCatalogShape({ templates: [{ ...VALID_TEMPLATE, solutionPath: 'templates/spa/company-portal/solution.zip' }] }),+ /must not define derivable solutionPath or websiteCodePath/+ );+});++// Regression: the published manifest declares `audience` as an array of personas+// (see templates/schemas/templates-manifest.schema.json in power-pages-samples).+// An earlier validator required a plain string, which rejected every real+// template and silently forced create-site down the from-scratch path.+test('validateCatalogShape accepts the 311 Portal audience array and rejects non-array shapes', () => {+ const portal311 = {+ ...VALID_TEMPLATE,+ id: '311-portal',+ displayName: '311 Portal',+ description: 'Citizen service request portal',+ keywords: ['311', 'citizen-services'],+ audience: ['makers', 'developers'],+ previewImages: ['spa/311-portal/previews/home.png'],+ };++ assert.equal(validateCatalogShape({ templates: [portal311] }), null);+ assert.match(+ validateCatalogShape({ templates: [{ ...portal311, audience: 'internal' }] }),+ /audience must be a non-empty array of strings/,+ );+ assert.match(validateCatalogShape({ templates: [{ ...portal311, audience: [] }] }), /audience/);+ assert.match(validateCatalogShape({ templates: [{ ...portal311, audience: ['makers', ''] }] }), /audience/);+});++test('requestJson uses an injected https boundary and parses response JSON', async () => {+ const fakeHttps = {+ get(url, options, callback) {+ assert.equal(url, 'https://example.test/catalog.json');+ assert.equal(options.headers['User-Agent'], 'power-pages-template-catalog');+ const req = new EventEmitter();+ req.destroy = (err) => req.emit('error', err);+ process.nextTick(() => {+ const res = new PassThrough();+ res.statusCode = 200;+ callback(res);+ res.end('{"templates":[{"id":"portal"}]}');+ });+ return req;+ },+ };++ assert.deepEqual(await requestJson('https://example.test/catalog.json', { https: fakeHttps }), {+ templates: [{ id: 'portal' }],+ });+});++test('downloadFile streams through injected https and fs boundaries', async () => {+ const writes = [];+ let renamed = null;+ const suffix = '0011223344556677';+ const temporaryPath = `/cache/template.zip.partial-${process.pid}-${suffix}`;+ const fakeFs = {+ mkdirSync(dir) { writes.push(['mkdir', dir]); },+ createWriteStream(dest, options) {+ writes.push(['stream', dest, options]);+ const stream = new PassThrough();+ stream.close = (callback) => callback();+ return stream;+ },+ renameSync(from, to) { renamed = [from, to]; },+ rmSync() {},+ };+ const fakeHttps = {+ get(url, options, callback) {+ assert.equal(url, 'https://example.test/template.zip');+ assert.equal(options.headers['User-Agent'], 'power-pages-template-catalog');+ const req = new EventEmitter();+ req.destroy = (err) => req.emit('error', err);+ process.nextTick(() => {+ const res = new PassThrough();+ res.statusCode = 200;+ callback(res);+ res.end(Buffer.from([0x50, 0x4b]));+ });+ return req;+ },+ };++ const output = await downloadFile('https://example.test/template.zip', '/cache/template.zip', {+ fs: fakeFs,+ https: fakeHttps,+ randomBytes: () => Buffer.from(suffix, 'hex'),+ });++ assert.equal(output, '/cache/template.zip');+ assert.deepEqual(writes, [+ ['mkdir', '/cache'],+ ['stream', temporaryPath, { flags: 'wx', mode: 0o600 }],+ ]);+ assert.deepEqual(renamed, [temporaryPath, '/cache/template.zip']);+});++test('downloadFile does not follow a pre-existing temporary-file symlink', async (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const outputPath = path.join(dir, 'template.zip');+ const outsidePath = path.join(dir, 'outside.zip');+ const suffix = '0011223344556677';+ const temporaryPath = `${outputPath}.partial-${process.pid}-${suffix}`;+ fs.writeFileSync(outsidePath, 'outside');+ try {+ fs.symlinkSync(outsidePath, temporaryPath);+ } catch (err) {+ if (err.code === 'EPERM' || err.code === 'EACCES') {+ t.skip(`symlinks are unavailable: ${err.code}`);+ return;+ }+ throw err;+ }+ const fakeHttps = {+ get() {+ const req = new EventEmitter();+ req.destroy = (err) => req.emit('error', err);+ return req;+ },+ };++ await assert.rejects(+ () => downloadFile('https://example.test/template.zip', outputPath, {+ https: fakeHttps,+ randomBytes: () => Buffer.from(suffix, 'hex'),+ }),+ /EEXIST|file already exists/i+ );+ assert.equal(fs.readFileSync(outsidePath, 'utf8'), 'outside');+});++test('downloadFile rejects and removes the temporary file when final rename fails', async () => {+ const removed = [];+ const suffix = '0011223344556677';+ const temporaryPath = `/cache/template.zip.partial-${process.pid}-${suffix}`;+ const fakeFs = {+ mkdirSync() {},+ createWriteStream() {+ const stream = new PassThrough();+ stream.close = (callback) => callback();+ return stream;+ },+ renameSync() {+ throw new Error('rename denied');+ },+ rmSync(target) {+ removed.push(target);+ },+ };+ const fakeHttps = {+ get(_url, _options, callback) {+ const req = new EventEmitter();+ req.destroy = (err) => req.emit('error', err);+ process.nextTick(() => {+ const res = new PassThrough();+ res.statusCode = 200;+ callback(res);+ res.end(Buffer.from([0x50, 0x4b]));+ });+ return req;+ },+ };++ await assert.rejects(+ () => downloadFile('https://example.test/template.zip', '/cache/template.zip', {+ fs: fakeFs,+ https: fakeHttps,+ randomBytes: () => Buffer.from(suffix, 'hex'),+ }),+ /rename denied/+ );+ assert.deepEqual(removed, [temporaryPath]);+});++test('downloadArtifact caches artifacts under the pinned sha and skips download when already cached', async (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const artifactPath = 'templates/spa/company/solution/Company_1_0_0_0.zip';+ const expectedPath = artifactCachePath({ cacheRoot: dir, sha: SHA, artifactPath });+ let downloads = 0;++ const first = await downloadArtifact({ owner: 'o', repo: 'r', sha: SHA, artifactPath, cacheRoot: dir }, {+ downloadFile: async (url, dest) => {+ downloads++;+ assert.equal(url, `https://raw.githubusercontent.com/o/r/${SHA}/${artifactPath}`);+ fs.mkdirSync(path.dirname(dest), { recursive: true });+ fs.writeFileSync(dest, 'zip-bytes');+ },+ });++ const second = await downloadArtifact({ owner: 'o', repo: 'r', sha: SHA, artifactPath, cacheRoot: dir }, {+ downloadFile: async () => { throw new Error('must not download cached artifact'); },+ });++ assert.deepEqual(first, { localPath: expectedPath, cached: false });+ assert.deepEqual(second, { localPath: expectedPath, cached: true });+ assert.equal(downloads, 1);+});++test('template cache root is private and carries an ownership marker', (t) => {+ const parent = tempDir();+ const dir = path.join(parent, 'cache');+ t.after(() => fs.rmSync(parent, { recursive: true, force: true }));++ assert.equal(ensurePrivateCacheRoot(dir), path.resolve(dir));+ const markerPath = path.join(dir, '.powerpages-template-cache.json');+ assert.deepEqual(JSON.parse(fs.readFileSync(markerPath, 'utf8')), {+ schemaVersion: 1,+ ownerUid: typeof process.getuid === 'function' ? process.getuid() : null,+ });+ if (process.platform !== 'win32') {+ assert.equal(fs.statSync(dir).mode & 0o077, 0);+ assert.equal(fs.statSync(markerPath).mode & 0o077, 0);+ }+});++test('template cache rejects an unclaimed pre-populated root', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ fs.writeFileSync(path.join(dir, 'preplanted.txt'), 'untrusted');++ assert.throws(+ () => ensurePrivateCacheRoot(dir),+ /cache root is not owned by this tool/+ );+});++test('template cache rejects roots accessible to other users', (t) => {+ if (process.platform === 'win32') {+ t.skip('POSIX permission bits are not meaningful on Windows');+ return;+ }+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ fs.chmodSync(dir, 0o755);++ assert.throws(+ () => ensurePrivateCacheRoot(dir),+ /cache root must be private to the current user/+ );+});++test('downloadArtifact rejects cached symlinks and non-files', async (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ ensurePrivateCacheRoot(dir);+ const artifactPath = 'templates/spa/company/previews/home.png';+ const cachedPath = artifactCachePath({ cacheRoot: dir, sha: SHA, artifactPath });+ fs.mkdirSync(path.dirname(cachedPath), { recursive: true });+ const target = path.join(dir, 'outside.png');+ fs.writeFileSync(target, 'outside');+ try {+ fs.symlinkSync(target, cachedPath);+ } catch (err) {+ if (err.code === 'EPERM' || err.code === 'EACCES') {+ t.skip(`symlinks are unavailable: ${err.code}`);+ return;+ }+ throw err;+ }++ await assert.rejects(+ () => downloadArtifact({ owner: 'o', repo: 'r', sha: SHA, artifactPath, cacheRoot: dir }),+ /regular file/+ );+});++test('artifactCachePath rejects paths that escape the sha cache directory', () => {+ assert.throws(+ () => artifactCachePath({ cacheRoot: '/tmp/cache', sha: SHA, artifactPath: '../secret.zip' }),+ /must stay under the templates cache/+ );+ assert.throws(+ () => artifactCachePath({ cacheRoot: '/tmp/cache', sha: SHA, artifactPath: '/tmp/secret.zip' }),+ /must stay under the templates cache/+ );+});++test('downloadTemplateVariant combines variant website code with family solutions in stable order', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const variantPath = 'templates/spa/company/variants/react';+ const solutionsPath = 'templates/spa/company/solutions';+ const calls = [];+ let partialRoot;++ const result = downloadTemplateVariant({+ owner: 'o',+ repo: 'r',+ sha: SHA,+ kind: 'spa',+ templateId: 'company',+ variant: 'react',+ cacheRoot: dir,+ }, {+ execFileSync(command, args) {+ calls.push([command, args]);+ if (args[0] === 'init') partialRoot = args[2];+ if (args.includes('checkout')) {+ const localVariant = path.join(partialRoot, ...variantPath.split('/'));+ const localSolutions = path.join(partialRoot, ...solutionsPath.split('/'));+ const localWebsiteCode = path.join(localVariant, 'website-code');+ fs.mkdirSync(path.join(localWebsiteCode, '.powerpages-site'), { recursive: true });+ fs.writeFileSync(path.join(localWebsiteCode, '.powerpages-site', 'website.yml'), 'adx_name: Company\n');+ fs.writeFileSync(path.join(localWebsiteCode, 'powerpages.config.json'), '{}');+ fs.writeFileSync(path.join(localWebsiteCode, 'package.json'), '{}');+ fs.writeFileSync(path.join(localWebsiteCode, '.npmrc'), 'omit-lockfile-registry-resolved=true\n');+ writeUnpackedSolution(path.join(localSolutions, 'CompanyBase'), 'CompanyBase', { version: '1.0.0.0' });+ writeUnpackedSolution(path.join(localSolutions, 'CompanyPortal'), 'CompanyPortal', { version: '2.0.0.0' });+ }+ return '';+ },+ });+ const cached = downloadTemplateVariant({+ owner: 'o',+ repo: 'r',+ sha: SHA,+ kind: 'spa',+ templateId: 'company',+ variant: 'react',+ cacheRoot: dir,+ }, {+ execFileSync() {+ throw new Error('cached variant must not run git');+ },+ });++ assert.equal(result.ok, true);+ assert.equal(result.cached, false);+ assert.equal(+ result.variantPath,+ repositoryDirectoryCheckoutRoot({ cacheRoot: dir, sha: SHA, directoryPath: variantPath })+ );+ const localSolutionsPath = repositoryDirectoryCheckoutRoot({+ cacheRoot: dir,+ sha: SHA,+ directoryPath: solutionsPath,+ });+ assert.equal(result.websiteCodePath, path.join(result.variantPath, 'website-code'));+ assert.deepEqual(result.solutions, [+ {+ uniqueName: 'CompanyBase',+ version: '1.0.0.0',+ solutionPath: path.join(localSolutionsPath, 'CompanyBase'),+ },+ {+ uniqueName: 'CompanyPortal',+ version: '2.0.0.0',+ solutionPath: path.join(localSolutionsPath, 'CompanyPortal'),+ },+ ]);+ assert.deepEqual(cached, { ...result, cached: true });+ assert.equal(calls.filter(([, args]) => args.includes('sparse-checkout')).length, 2);+ assert.equal(calls.some(([, args]) => args.join(' ').includes(`sparse-checkout set --cone -- ${variantPath}`)), true);+ assert.equal(calls.some(([, args]) => args.join(' ').includes(`sparse-checkout set --cone -- ${solutionsPath}`)), true);+});++test('downloadTemplateVariant replaces a symlinked checkout root instead of trusting its contents', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ ensurePrivateCacheRoot(dir);+ const variantPath = 'templates/spa/company/variants/react';+ const solutionsPath = 'templates/spa/company/solutions';+ const checkoutRoot = repositoryDirectoryCheckoutRoot({+ cacheRoot: dir,+ sha: SHA,+ directoryPath: variantPath,+ });+ const outsideDir = path.join(dir, 'outside-variant');+ fs.mkdirSync(path.join(outsideDir, 'website-code'), { recursive: true });+ fs.writeFileSync(path.join(outsideDir, 'sentinel.txt'), 'outside');+ fs.mkdirSync(path.dirname(checkoutRoot), { recursive: true });+ try {+ fs.symlinkSync(outsideDir, checkoutRoot, process.platform === 'win32' ? 'junction' : 'dir');+ } catch (err) {+ if (err.code === 'EPERM' || err.code === 'EACCES') {+ t.skip(`symlinks are unavailable: ${err.code}`);+ return;+ }+ throw err;+ }++ let partialRoot;+ let gitCalls = 0;+ const result = downloadTemplateVariant({+ owner: 'o',+ repo: 'r',+ sha: SHA,+ kind: 'spa',+ templateId: 'company',+ variant: 'react',+ cacheRoot: dir,+ }, {+ execFileSync(command, args) {+ gitCalls++;+ if (args[0] === 'init') partialRoot = args[2];+ if (args.includes('checkout')) {+ const localWebsiteCode = path.join(partialRoot, ...variantPath.split('/'), 'website-code');+ fs.mkdirSync(path.join(localWebsiteCode, '.powerpages-site'), { recursive: true });+ fs.writeFileSync(path.join(localWebsiteCode, '.powerpages-site', 'website.yml'), 'adx_name: Company\n');+ fs.writeFileSync(path.join(localWebsiteCode, 'powerpages.config.json'), '{}');+ fs.writeFileSync(path.join(localWebsiteCode, 'package.json'), '{}');+ fs.writeFileSync(path.join(localWebsiteCode, '.npmrc'), 'omit-lockfile-registry-resolved=true\n');+ writeUnpackedSolution(+ path.join(partialRoot, ...solutionsPath.split('/'), 'CompanyPortal'),+ 'CompanyPortal'+ );+ }+ return '';+ },+ });++ assert.equal(result.ok, true);+ assert.equal(result.cached, false);+ assert.ok(gitCalls > 0);+ assert.equal(fs.readFileSync(path.join(outsideDir, 'sentinel.txt'), 'utf8'), 'outside');+ assert.equal(fs.lstatSync(checkoutRoot).isSymbolicLink(), false);+});++test('downloadTemplateVariant rejects a symlinked checkout parent directory', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ ensurePrivateCacheRoot(dir);+ const outsideDir = path.join(dir, 'outside-checkouts');+ const symlinkedParent = path.join(dir, SHA, '.directory-checkouts', 'templates', 'spa');+ fs.mkdirSync(path.dirname(symlinkedParent), { recursive: true });+ fs.mkdirSync(outsideDir);+ try {+ fs.symlinkSync(outsideDir, symlinkedParent, process.platform === 'win32' ? 'junction' : 'dir');+ } catch (err) {+ if (err.code === 'EPERM' || err.code === 'EACCES') {+ t.skip(`symlinks are unavailable: ${err.code}`);+ return;+ }+ throw err;+ }++ let gitCalled = false;+ const result = downloadTemplateVariant({+ owner: 'o',+ repo: 'r',+ sha: SHA,+ kind: 'spa',+ templateId: 'company',+ variant: 'react',+ cacheRoot: dir,+ }, {+ execFileSync() {+ gitCalled = true;+ return '';+ },+ });++ assert.equal(result.ok, false);+ assert.match(result.error, /cache path must contain only real directories/);+ assert.equal(gitCalled, false);+});++test('downloadTemplateVariant accepts traditional website source with family solution components', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const variantPath = 'templates/traditional/customer-self-service/variants/none';+ const solutionsPath = 'templates/traditional/customer-self-service/solutions';+ let partialRoot;++ const result = downloadTemplateVariant({+ owner: 'o',+ repo: 'r',+ sha: SHA,+ kind: 'traditional',+ templateId: 'customer-self-service',+ variant: 'none',+ cacheRoot: dir,+ }, {+ execFileSync(command, args) {+ if (args[0] === 'init') partialRoot = args[2];+ if (args.includes('checkout')) {+ const localVariant = path.join(partialRoot, ...variantPath.split('/'));+ const localSolutions = path.join(partialRoot, ...solutionsPath.split('/'));+ const localWebsiteCode = path.join(localVariant, 'website-code');+ fs.mkdirSync(path.join(localWebsiteCode, '.powerpages-site'), { recursive: true });+ fs.writeFileSync(+ path.join(localWebsiteCode, '.powerpages-site', 'website.yml'),+ 'adx_name: Customer self-service\n'+ );+ writeUnpackedSolution(+ path.join(localSolutions, 'CustomerSelfService'),+ 'CustomerSelfService',+ { websiteComponents: true }+ );+ }+ return '';+ },+ });++ assert.equal(result.ok, true);+ assert.equal(result.websiteCodePath, path.join(result.variantPath, 'website-code'));+ assert.equal(result.solutions[0].uniqueName, 'CustomerSelfService');+});++test('template family and variant roots derive fixed paths from catalog identity', () => {+ assert.equal(+ templateFamilyRoot({+ catalogPath: 'templates/manifest.json',+ kind: 'spa',+ templateId: 'company',+ }),+ 'templates/spa/company'+ );+ assert.equal(+ templateVariantRoot({+ catalogPath: 'templates/manifest.json',+ kind: 'spa',+ templateId: 'company',+ variant: 'React',+ }),+ 'templates/spa/company/variants/react'+ );+ assert.throws(+ () => templateVariantRoot({+ catalogPath: 'templates/manifest.json',+ kind: 'spa',+ templateId: '../company',+ variant: 'react',+ }),+ /Invalid template id/+ );+});++test('downloadTemplateVariant rejects variant-local solutions when family solutions are missing', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const variantPath = 'templates/spa/company/variants/react';+ let partialRoot;++ const result = downloadTemplateVariant({+ owner: 'o',+ repo: 'r',+ sha: SHA,+ kind: 'spa',+ templateId: 'company',+ variant: 'react',+ cacheRoot: dir,+ }, {+ execFileSync(command, args) {+ if (args[0] === 'init') partialRoot = args[2];+ if (args.includes('checkout')) {+ const localVariant = path.join(partialRoot, ...variantPath.split('/'));+ const localWebsiteCode = path.join(localVariant, 'website-code');+ fs.mkdirSync(path.join(localWebsiteCode, '.powerpages-site'), { recursive: true });+ fs.writeFileSync(path.join(localWebsiteCode, '.powerpages-site', 'website.yml'), 'adx_name: Company\n');+ fs.writeFileSync(path.join(localWebsiteCode, 'powerpages.config.json'), '{}');+ fs.writeFileSync(path.join(localWebsiteCode, 'package.json'), '{}');+ fs.writeFileSync(path.join(localWebsiteCode, '.npmrc'), 'omit-lockfile-registry-resolved=true\n');+ writeUnpackedSolution(path.join(localVariant, 'solutions', 'CompanyPortal'), 'CompanyPortal');+ }+ return '';+ },+ });++ assert.equal(result.ok, false);+ assert.match(result.error, /Template is missing solutions/);+});++test('inspectTemplateSolutions rejects folder and Solution.xml unique-name drift', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ writeUnpackedSolution(path.join(dir, 'WrongFolder'), 'ActualUniqueName');++ const result = inspectTemplateSolutions(dir, 'spa');++ assert.equal(result.ok, false);+ assert.match(result.error, /WrongFolder must match .* ActualUniqueName/);+});++test('inspectTemplateSolutions requires a non-empty solutions directory containing only solution folders', (t) => {+ const missingDir = path.join(tempDir(), 'missing');+ t.after(() => fs.rmSync(path.dirname(missingDir), { recursive: true, force: true }));+ assert.match(inspectTemplateSolutions(missingDir, 'spa').error, /missing solutions/);++ const emptyDir = tempDir();+ t.after(() => fs.rmSync(emptyDir, { recursive: true, force: true }));+ assert.match(inspectTemplateSolutions(emptyDir, 'spa').error, /at least one solution/);++ fs.writeFileSync(path.join(emptyDir, 'README.md'), 'not a solution');+ assert.match(inspectTemplateSolutions(emptyDir, 'spa').error, /non-directory entry: README\.md/);+});++test('unpacked solution validation can allow website artifacts for traditional templates', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ assert.match(validateUnpackedSolutionDirectory(dir), /missing Other[/\\]Solution.xml/);+ const other = path.join(dir, 'Other');+ fs.mkdirSync(other);+ fs.writeFileSync(+ path.join(other, 'Solution.xml'),+ '<ImportExportXml><SolutionManifest><Managed>0</Managed></SolutionManifest></ImportExportXml>'+ );+ fs.writeFileSync(path.join(other, 'Customizations.xml'), '<ImportExportXml />');+ assert.equal(validateUnpackedSolutionDirectory(dir), null);++ fs.writeFileSync(path.join(other, 'Solution.xml'), '<SolutionManifest><Managed>1</Managed></SolutionManifest>');+ assert.match(validateUnpackedSolutionDirectory(dir), /unmanaged/);+ fs.writeFileSync(path.join(other, 'Solution.xml'), '<SolutionManifest><Managed>0</Managed></SolutionManifest>');+ fs.writeFileSync(path.join(other, 'Customizations.xml'), '<ImportExportXml><powerpagecomponents /></ImportExportXml>');+ assert.match(validateUnpackedSolutionDirectory(dir), /website components/);+ assert.equal(validateUnpackedSolutionDirectory(dir, { allowWebsiteComponents: true }), null);+ fs.writeFileSync(path.join(other, 'Customizations.xml'), '<ImportExportXml />');+ fs.writeFileSync(path.join(dir, 'committed.zip'), 'zip');+ assert.match(validateUnpackedSolutionDirectory(dir), /committed zip/);+});++test('website code validation handles SPA and traditional source layouts', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ fs.mkdirSync(path.join(dir, '.powerpages-site'));+ fs.writeFileSync(path.join(dir, '.powerpages-site', 'website.yml'), 'adx_name: Company\n');+ fs.writeFileSync(path.join(dir, 'powerpages.config.json'), '{}');+ fs.writeFileSync(path.join(dir, 'package.json'), '{}');+ assert.match(validateWebsiteCodeDirectory(dir, { kind: 'spa' }), /missing \.npmrc/);+ fs.writeFileSync(path.join(dir, '.npmrc'), 'omit-lockfile-registry-resolved=true\n');+ fs.mkdirSync(path.join(dir, 'node_modules'));+ assert.match(validateWebsiteCodeDirectory(dir, { kind: 'spa' }), /generated or local-only/);++ const traditionalDir = tempDir();+ t.after(() => fs.rmSync(traditionalDir, { recursive: true, force: true }));+ fs.mkdirSync(path.join(traditionalDir, '.powerpages-site'));+ fs.writeFileSync(+ path.join(traditionalDir, '.powerpages-site', 'website.yml'),+ 'adx_name: Traditional Site\n'+ );+ assert.equal(validateWebsiteCodeDirectory(traditionalDir, { kind: 'traditional' }), null);+});++test('website code validation rejects a symlinked root', (t) => {+ const dir = tempDir();+ const target = tempDir();+ t.after(() => {+ fs.rmSync(dir, { recursive: true, force: true });+ fs.rmSync(target, { recursive: true, force: true });+ });+ const link = path.join(dir, 'website-code');+ try {+ fs.symlinkSync(target, link, 'dir');+ } catch (err) {+ if (err.code === 'EPERM' || err.code === 'EACCES') {+ t.skip(`directory symlinks are unavailable: ${err.code}`);+ return;+ }+ throw err;+ }++ assert.match(validateWebsiteCodeDirectory(link, { kind: 'spa' }), /regular directory/);+});++test('downloadSeedDataDirectory downloads a seed JSON file and its referenced __files attachments without tree API', async (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const downloaded = [];++ const result = await downloadSeedDataDirectory({+ owner: 'o',+ repo: 'r',+ sha: SHA,+ seedDataPath: 'templates/spa/company/seed/data.json',+ cacheRoot: dir,+ }, {+ requestJson: async () => {+ throw new Error('tree API should not be called for seed JSON paths');+ },+ downloadFile: async (_url, dest) => {+ downloaded.push(path.basename(dest));+ fs.mkdirSync(path.dirname(dest), { recursive: true });+ if (dest.endsWith('data.json')) {+ fs.writeFileSync(dest, JSON.stringify({+ entitySetName: 'cr123_invoices',+ records: [+ { __files: { cr123_invoicepdf: 'files/invoice.pdf' } },+ { __files: { cr123_metadata: 'files/metadata.json' } },+ { __files: { cr123_terms: 'files/terms.docx' } },+ ],+ }));+ } else {+ fs.writeFileSync(dest, 'file-bytes');+ }+ },+ });++ assert.equal(result.ok, true);+ assert.equal(result.localDir, path.join(dir, SHA, 'templates/spa/company/seed'));+ assert.equal(result.seedFile, path.join(dir, SHA, 'templates/spa/company/seed/data.json'));+ assert.deepEqual(downloaded, ['data.json', 'invoice.pdf', 'metadata.json', 'terms.docx']);+});++test('downloadSeedDataDirectory rejects directory seed paths without calling the GitHub tree API', async () => {+ const result = await downloadSeedDataDirectory({+ owner: 'o',+ repo: 'r',+ sha: SHA,+ seedDataPath: 'templates/spa/company/seed-data',+ }, {+ requestJson: async () => {+ throw new Error('tree API should not be called');+ },+ });++ assert.deepEqual(result, {+ ok: false,+ seedDataPath: 'templates/spa/company/seed-data',+ error: 'Seed data path must point to a JSON file: templates/spa/company/seed-data',+ });+});++test('fetch-template-seed-data CLI parser accepts seed data path', () => {+ assert.deepEqual(parseSeedArgs([+ '--owner', 'contoso',+ '--repo', 'samples',+ '--sha', SHA,+ '--seedDataPath', 'templates/spa/company/seed/data.json',+ '--cacheRoot', '/tmp/cache',+ ]), {+ owner: 'contoso',+ repo: 'samples',+ sha: SHA,+ seedDataPath: 'templates/spa/company/seed/data.json',+ cacheRoot: '/tmp/cache',+ });+});++test('validateZipContainsSolution recognizes solution.xml without requiring external unzip', () => {+ assert.deepEqual(zipFileNames(fakeZipWithLocalFile('solution.xml')), ['solution.xml']);+ assert.equal(validateZipContainsSolution('/tmp/ok.zip', {+ fs: { readFileSync: () => fakeZipWithLocalFile('solution.xml') },+ }), true);+ assert.equal(validateZipContainsSolution('/tmp/nope.zip', {+ fs: { readFileSync: () => fakeZipWithLocalFile('customizations.xml') },+ }), false);+ assert.equal(validateZipContainsSolution('/tmp/nested.zip', {+ fs: { readFileSync: () => fakeZipWithLocalFile('folder/solution.xml') },+ }), false);+ assert.equal(validateZipContainsSolution('/tmp/broken.zip', {+ fs: { readFileSync: () => { throw new Error('not a zip'); } },+ }), false);+});++test('fetch-template-catalog CLI parser accepts repo/ref/cache options', () => {+ assert.deepEqual(parseCatalogArgs([+ '--owner', 'contoso',+ '--repo', 'samples',+ '--ref', 'release/v1',+ '--catalogPath', 'templates/custom.json',+ '--cacheRoot', '/tmp/cache',+ ]), {+ owner: 'contoso',+ repo: 'samples',+ ref: 'release/v1',+ catalogPath: 'templates/custom.json',+ cacheRoot: '/tmp/cache',+ });+});++test('fetch-template-catalog CLI parser defaults ref to latest-release', () => {+ assert.equal(parseCatalogArgs([]).ref, 'latest-release');+});++test('fetch-template-variant CLI parser accepts derivable variant identity', () => {+ assert.deepEqual(parseVariantArgs([+ '--owner', 'contoso',+ '--repo', 'samples',+ '--sha', SHA,+ '--kind', 'spa',+ '--templateId', 'company',+ '--variant', 'react',+ '--catalogPath', 'templates/manifest.json',+ '--cacheRoot', '/tmp/cache',+ ]), {+ owner: 'contoso',+ repo: 'samples',+ sha: SHA,+ kind: 'spa',+ templateId: 'company',+ variant: 'react',+ catalogPath: 'templates/manifest.json',+ cacheRoot: '/tmp/cache',+ });+});++test('fetch-template-artifact CLI parser maps artifactPath to the shared artifact option', () => {+ assert.deepEqual(parseArtifactArgs([+ '--owner', 'contoso',+ '--repo', 'samples',+ '--sha', SHA,+ '--artifactPath', 'templates/spa/company/previews/home.png',+ '--cacheRoot', '/tmp/cache',+ ]), {+ owner: 'contoso',+ repo: 'samples',+ sha: SHA,+ artifactPath: 'templates/spa/company/previews/home.png',+ cacheRoot: '/tmp/cache',+ });+});++test('shared template CLI arg parser handles common repo/cache and path flags', () => {+ assert.deepEqual(parseTemplateRepoArgs([+ '--owner', 'contoso',+ '--repo', 'samples',+ '--ref', 'main',+ '--sha', SHA,+ '--cacheRoot', '/tmp/cache',+ '--solutionPath', 'templates/spa/company/solution',+ ], '--solutionPath'), {+ owner: 'contoso',+ repo: 'samples',+ ref: 'main',+ sha: SHA,+ cacheRoot: '/tmp/cache',+ artifactPath: 'templates/spa/company/solution',+ });+});++test('shared JSON CLI runner formats success and fail-open errors', async () => {+ const writes = [];+ const processes = [{}, {}];+ await runBestEffortJsonCli(async () => ({ ok: true, value: 1 }), {+ stdout: { write: (value) => writes.push(value) },+ process: processes[0],+ });+ await runBestEffortJsonCli(async () => { throw new Error('boom'); }, {+ stdout: { write: (value) => writes.push(value) },+ process: processes[1],+ });++ assert.equal(formatJsonResult({ ok: true }), '{\n "ok": true\n}\n');+ assert.deepEqual(processes.map((proc) => proc.exitCode), [0, 0]);+ assert.match(writes[0], /"value": 1/);+ assert.match(writes[1], /"ok": false/);+ assert.match(writes[1], /"error": "boom"/);+});diff --git a/plugins/power-pages/scripts/tests/template-import-context.test.js b/plugins/power-pages/scripts/tests/template-import-context.test.jsnew file mode 100644index 000000000..77d08b210--- /dev/null+++ b/plugins/power-pages/scripts/tests/template-import-context.test.js@@ -0,0 +1,28 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');++const { resolveTemplateImportContext } = require('../lib/template-import-context');++test('resolveTemplateImportContext verifies token availability without returning the credential', () => {+ assert.deepEqual(resolveTemplateImportContext({+ getEnvironmentUrl: () => 'https://org.crm.dynamics.com',+ getAuthToken: (resource) => `token-for-${resource}`,+ }), {+ ok: true,+ environmentUrl: 'https://org.crm.dynamics.com',+ });+});++test('resolveTemplateImportContext reports missing PAC auth or Azure token', () => {+ assert.equal(resolveTemplateImportContext({ getEnvironmentUrl: () => null }).ok, false);+ assert.deepEqual(resolveTemplateImportContext({+ getEnvironmentUrl: () => 'https://org.crm.dynamics.com',+ getAuthToken: () => null,+ }), {+ ok: false,+ environmentUrl: 'https://org.crm.dynamics.com',+ error: 'Azure CLI token unavailable. Run `az login` first.',+ });+});diff --git a/plugins/power-pages/scripts/tests/template-reinstall-policy.test.js b/plugins/power-pages/scripts/tests/template-reinstall-policy.test.jsnew file mode 100644index 000000000..242610a86--- /dev/null+++ b/plugins/power-pages/scripts/tests/template-reinstall-policy.test.js@@ -0,0 +1,167 @@+'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 zlib = require('zlib');++const {+ decideReinstall,+ inspectSolutionDirectory,+ inspectSolutionZip,+} = require('../lib/template-reinstall-policy');+const { compareVersions } = require('../lib/bump-solution-version');+const { parseArgs, run } = require('../inspect-template-solution');++function fakeZipWithFile(name, content, method = 0) {+ const nameBytes = Buffer.from(name, 'utf8');+ const raw = Buffer.from(content, 'utf8');+ const data = method === 8 ? zlib.deflateRawSync(raw) : raw;+ const local = Buffer.alloc(30);+ local.writeUInt32LE(0x04034b50, 0);+ local.writeUInt16LE(method, 8);+ local.writeUInt32LE(data.length, 18);+ local.writeUInt32LE(raw.length, 22);+ local.writeUInt16LE(nameBytes.length, 26);+ const central = Buffer.alloc(46);+ central.writeUInt32LE(0x02014b50, 0);+ central.writeUInt16LE(method, 10);+ central.writeUInt32LE(data.length, 20);+ central.writeUInt32LE(raw.length, 24);+ central.writeUInt16LE(nameBytes.length, 28);+ central.writeUInt32LE(0, 42);+ return Buffer.concat([local, nameBytes, data, central, nameBytes]);+}++test('compareVersions orders dotted Dataverse solution versions numerically', () => {+ assert.equal(compareVersions('1.0.1.0', '1.0.0.9'), 1);+ assert.equal(compareVersions('1.0.0.0', '1.0.0.0'), 0);+ assert.equal(compareVersions('1.0.0.0', '1.0.0.1'), -1);+});++test('decideReinstall covers import, update, clone, and ask cases', () => {+ const cases = [+ [{ installed: false, availableVersion: '1.0.0.0' }, 'import'],+ [{ installed: true, installedVersion: '1.0.0.0', availableVersion: '1.0.1.0' }, 'confirm-update'],+ [{ installed: true, installedVersion: '1.0.1.0', availableVersion: '1.0.0.0' }, 'offer-clone'],+ [{ installed: true, installedVersion: null, availableVersion: '1.0.0.0' }, 'ask'],+ [{ detectionFailed: true }, 'ask'],+ ];+ for (const [input, expected] of cases) {+ assert.equal(decideReinstall(input), expected);+ }+});++test('decideReinstall asks when installed or available versions are malformed', () => {+ assert.equal(decideReinstall({+ installed: false,+ availableVersion: '1.0.preview',+ }), 'ask');+ assert.equal(decideReinstall({+ installed: true,+ installedVersion: 'unknown',+ availableVersion: '1.0.0.0',+ }), 'ask');+ assert.equal(decideReinstall({+ installed: true,+ installedVersion: '1.0.0.0',+ availableVersion: '1.0.preview',+ }), 'ask');+});++test('inspectSolutionDirectory reads unpacked Other/Solution.xml metadata', (t) => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'inspect-template-solution-test-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ fs.mkdirSync(path.join(root, 'Other'));+ fs.writeFileSync(path.join(root, 'Other', 'Solution.xml'), `+<ImportExportXml>+ <SolutionManifest>+ <UniqueName>contoso_template</UniqueName>+ <Version>2.0.0.0</Version>+ <Managed>0</Managed>+ </SolutionManifest>+</ImportExportXml>`);++ assert.deepEqual(inspectSolutionDirectory(root), {+ ok: true,+ uniqueName: 'contoso_template',+ version: '2.0.0.0',+ managed: false,+ });+ assert.deepEqual(run([+ '--solutionPath', root,+ '--installed', 'true',+ '--installedVersion', '1.0.0.0',+ ]), {+ ok: true,+ uniqueName: 'contoso_template',+ version: '2.0.0.0',+ managed: false,+ decision: 'confirm-update',+ });+});++test('inspectSolutionZip extracts unique name, version, and managed flag from solution.xml', () => {+ const xml = `+<ImportExportXml>+ <SolutionManifest>+ <UniqueName>contoso_template</UniqueName>+ <Version>1.2.3.4</Version>+ <Managed>0</Managed>+ </SolutionManifest>+</ImportExportXml>`;++ assert.deepEqual(inspectSolutionZip('/tmp/template.zip', { solutionXml: xml }), {+ ok: true,+ uniqueName: 'contoso_template',+ version: '1.2.3.4',+ managed: false,+ });++});++test('inspectSolutionZip reads solution.xml directly from zip bytes without unzip', () => {+ const xml = `+<ImportExportXml>+ <SolutionManifest>+ <UniqueName>contoso_template</UniqueName>+ <Version>1.2.3.4</Version>+ <Managed>0</Managed>+ </SolutionManifest>+</ImportExportXml>`;++ assert.deepEqual(inspectSolutionZip('/tmp/template.zip', {+ fs: { readFileSync: () => fakeZipWithFile('solution.xml', xml, 8) },+ }), {+ ok: true,+ uniqueName: 'contoso_template',+ version: '1.2.3.4',+ managed: false,+ });+});++test('inspectSolutionZip reports corrupt or unreadable solution.xml as ok:false', () => {+ assert.deepEqual(inspectSolutionZip('/tmp/template.zip', {+ fs: { readFileSync: () => { throw new Error('not a zip'); } },+ }), { ok: false, error: 'not a zip' });+ assert.deepEqual(inspectSolutionZip('/tmp/template.zip', {+ solutionXml: '<SolutionManifest><UniqueName>missing_version</UniqueName></SolutionManifest>',+ }), { ok: false, error: 'solution.xml did not include UniqueName and Version' });+ assert.deepEqual(inspectSolutionZip('/tmp/template.zip', {+ solutionXml: '<SolutionManifest><UniqueName>invalid_version</UniqueName><Version>1.0.preview</Version></SolutionManifest>',+ }), {+ ok: false,+ error: 'solution.xml Version must contain one to four non-negative integer segments',+ });+});++test('inspect-template-solution CLI parser and runner accept unpacked solution source', () => {+ assert.deepEqual(parseArgs(['--solutionPath', '/tmp/solution', '--installed', 'true', '--installedVersion', '1.0.0.0']), {+ solutionPath: '/tmp/solution',+ installed: true,+ installedVersion: '1.0.0.0',+ });+ assert.equal(run([]).ok, false);+});diff --git a/plugins/power-pages/scripts/tests/validation-helpers.test.js b/plugins/power-pages/scripts/tests/validation-helpers.test.jsindex 4f8526979..1ce6ce22d 100644--- a/plugins/power-pages/scripts/tests/validation-helpers.test.js+++ b/plugins/power-pages/scripts/tests/validation-helpers.test.js@@ -5,24 +5,16 @@ const childProcess = require('child_process');const helpersPath = path.join(__dirname, '..', 'lib', 'validation-helpers.js');-test('getAuthToken calls az account get-access-token without --allow-no-subscriptions (only az login accepts that flag)', (t) => {- const originalExecFileSync = childProcess.execFileSync;+test('getAuthToken calls az account get-access-token without --allow-no-subscriptions (only az login accepts that flag)', () => {let captured = null;-- childProcess.execFileSync = (file, args, options) => {- captured = { file, args, options };- const out = 'fake-token-value\n';- return options && options.encoding ? out : Buffer.from(out);- };- delete require.cache[require.resolve(helpersPath)];-- t.after(() => {- childProcess.execFileSync = originalExecFileSync;- delete require.cache[require.resolve(helpersPath)];- });-const { getAuthToken } = require(helpersPath);- const token = getAuthToken('https://example.crm.dynamics.com');+ const token = getAuthToken('https://example.crm.dynamics.com', {+ platform: 'linux',+ execFile(file, args, options) {+ captured = { file, args, options };+ return 'fake-token-value\n';+ },+ });assert.equal(token, 'fake-token-value');assert.equal(captured.file, 'az');@@ -37,22 +29,42 @@ test('getAuthToken calls az account get-access-token without --allow-no-subscrip);});-test('getAuthToken rejects POSIX and Windows metacharacter payloads before invoking az', (t) => {- const originalExecFileSync = childProcess.execFileSync;- let calls = 0;- childProcess.execFileSync = () => {- calls++;- return 'should-not-run';- };- delete require.cache[require.resolve(helpersPath)];- t.after(() => {- childProcess.execFileSync = originalExecFileSync;- delete require.cache[require.resolve(helpersPath)];+test('getAuthToken invokes the Azure CLI cmd shim safely on Windows', () => {+ const { getAuthToken } = require(helpersPath);+ const calls = [];+ const token = getAuthToken('https://org.crm.dynamics.com', {+ platform: 'win32',+ execFile(file, args, options) {+ calls.push({ file, args, options });+ return 'windows-token\n';+ },});+ assert.equal(token, 'windows-token');+ assert.equal(calls[0].file, 'cmd.exe');+ assert.deepEqual(calls[0].args, [+ '/d', '/s', '/c', 'az.cmd',+ 'account', 'get-access-token',+ '--resource', 'https://org.crm.dynamics.com',+ '--query', 'accessToken',+ '-o', 'tsv',+ ]);+ assert.equal(calls[0].options.shell, false);+});++test('getAuthToken rejects POSIX and Windows metacharacter payloads before invoking az', () => {const { getAuthToken } = require(helpersPath);- assert.equal(getAuthToken('https://org.crm.dynamics.com/;echo-marker'), null);- assert.equal(getAuthToken('https://org.crm.dynamics.com/&echo-marker%PATH%'), null);+ let calls = 0;+ const deps = {+ platform: 'linux',+ execFile() {+ calls++;+ return 'should-not-run';+ },+ };++ assert.equal(getAuthToken('https://org.crm.dynamics.com/;echo-marker', deps), null);+ assert.equal(getAuthToken('https://org.crm.dynamics.com/&echo-marker%PATH%', deps), null);assert.equal(calls, 0);});@@ -261,6 +273,16 @@ test('parseEnvironmentUrl returns null when no URL label is present (and on emptassert.equal(parseEnvironmentUrl(null), null);});+test('parseActiveAuthListEnvironmentUrl extracts the active auth profile Environment Url', () => {+ const { parseActiveAuthListEnvironmentUrl } = require(helpersPath);+ const output = [+ 'Index Active Kind Name User Cloud Type Environment Environment Url',+ '[1] * UNIVERSAL [email protected] Public OperatingSystem PowerPagesProDev https://powerpagesprodev.crm.dynamics.com/',+ '[2] UNIVERSAL [email protected] Public OperatingSystem OtherEnv https://other.crm.dynamics.com/',+ ].join('\n');+ assert.equal(parseActiveAuthListEnvironmentUrl(output), 'https://powerpagesprodev.crm.dynamics.com');+});+test('getEnvironmentUrl parses the 2.8.x "Org URL:" output via mocked execSync', (t) => {const originalExecSync = childProcess.execSync;childProcess.execSync = () => ' Org URL: https://orgABC.crm.dynamics.com/\n';@@ -271,3 +293,24 @@ test('getEnvironmentUrl parses the 2.8.x "Org URL:" output via mocked execSync',assert.equal(getEnvironmentUrl(), 'https://orgabc.crm.dynamics.com');delete require.cache[require.resolve(helpersPath)];});++test('getEnvironmentUrl falls back to active pac auth list Environment Url when pac env who has no URL', (t) => {+ const originalExecSync = childProcess.execSync;+ childProcess.execSync = (command) => {+ if (command === 'pac env who') return 'No organization selected\n';+ if (command === 'pac auth list') {+ return [+ 'Index Active Kind Name User Cloud Type Environment Environment Url',+ '[1] * UNIVERSAL [email protected] Public OperatingSystem PowerPagesProDev https://powerpagesprodev.crm.dynamics.com/',+ ].join('\n');+ }+ throw new Error(`unexpected command: ${command}`);+ };+ t.after(() => { childProcess.execSync = originalExecSync; });+ delete require.cache[require.resolve(helpersPath)];++ const { getEnvironmentUrl } = require(helpersPath);++ assert.equal(getEnvironmentUrl(), 'https://powerpagesprodev.crm.dynamics.com');+ delete require.cache[require.resolve(helpersPath)];+});diff --git a/plugins/power-pages/scripts/validate-cli-tenant-alignment.js b/plugins/power-pages/scripts/validate-cli-tenant-alignment.jsnew file mode 100644index 000000000..fd13f3d4d--- /dev/null+++ b/plugins/power-pages/scripts/validate-cli-tenant-alignment.js@@ -0,0 +1,31 @@+#!/usr/bin/env node+'use strict';++const { validateCliTenantAlignment } = require('./lib/cli-tenant-alignment');+const { formatJsonResult } = require('./lib/template-cli-args');++function parseArgs(argv) {+ const args = {};+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === '--envUrl') args.envUrl = argv[++i];+ }+ return args;+}++function run(argv = process.argv.slice(2), deps = {}) {+ const args = parseArgs(argv);+ if (!args.envUrl) {+ return {+ ok: false,+ error: 'Usage: validate-cli-tenant-alignment.js --envUrl <url>',+ };+ }+ return validateCliTenantAlignment(args, deps);+}++if (require.main === module) {+ process.stdout.write(formatJsonResult(run()));+}++module.exports = { parseArgs, run };diff --git a/plugins/power-pages/skills/activate-site/SKILL.md b/plugins/power-pages/skills/activate-site/SKILL.mdindex 6bfce0a20..0c7fe5f96 100644--- a/plugins/power-pages/skills/activate-site/SKILL.md+++ b/plugins/power-pages/skills/activate-site/SKILL.md@@ -5,7 +5,7 @@ description: >-via the Power Platform REST API. Use when the user wants to activate, provision,turn on, or enable a Power Pages website or portal.user-invocable: true-allowed-tools: Read, Bash, Glob, Grep, AskUserQuestion, TaskCreate, TaskUpdate, TaskList+allowed-tools: Read, Write, Bash, Glob, Grep, AskUserQuestion, TaskCreate, TaskUpdate, TaskListmodel: sonnet---@@ -20,8 +20,10 @@ Provision a new Power Pages website in a Power Platform environment via the Powe## Core Principles- **Cloud-aware URL resolution** — Never hardcode API base URLs or site URL domains. Always derive them from the Cloud value returned by `pac auth who`.-- **Token handling** — Scripts acquire and refresh Azure CLI tokens internally. The agent only needs to verify the user is logged in to Azure CLI.+- **Token handling** — The agent only needs to verify the user is logged in to Azure CLI.- **Confirm before mutating** — Always present the full activation parameters to the user and get explicit approval before POSTing to the websites API.+- **Preserve the caller's environment** — When another skill passes `environmentUrl`, verify PAC and Azure CLI still target that environment and tenant before activation.+- **Caller status updates** — When `/create-site` supplies a `statusPath`, update that file before and after activation prompts so the open template status page shows when user input is required.**Initial request:** $ARGUMENTS@@ -37,7 +39,7 @@ Provision a new Power Pages website in a Power Platform environment via the Powe## Phase 1: Verify Prerequisites-**Goal:** Ensure PAC CLI is installed and authenticated, and verify the user is logged in to Azure CLI (scripts handle token acquisition internally).+**Goal:** Ensure PAC CLI is installed and authenticated, and verify the user is logged in to Azure CLI.### Actions@@ -78,7 +80,7 @@ pac auth who#### 1.3 Verify Azure CLI Login-Verify the user is logged in to Azure CLI (the activation scripts acquire tokens internally):+Verify the user is logged in to Azure CLI:```bashaz account show@@ -88,7 +90,28 @@ az account show#### 1.4 Check If Already Activated-Before gathering parameters, check whether the site is already activated by running the shared activation status script:+First inspect `$ARGUMENTS` for explicit imported-site identity from another skill:++```text+siteName: <name>+websiteRecordId: <guid>+environmentUrl: <url>+statusPath: <path>+```++When both values are present, set `SITE_IDENTITY_SOURCE = "arguments"` immediately and **skip the local-project activation status check below**. That check resolves identity from `powerpages.config.json` / `.powerpages-site`, which may be absent or unrelated when `/create-site` activates an imported template site. Continue to Phase 2 with the explicit identity.++When `environmentUrl` is present, store it as `EXPECTED_ENVIRONMENT_URL` and verify the current CLI context before Phase 2:++```bash+node "${PLUGIN_ROOT}/scripts/validate-cli-tenant-alignment.js" --envUrl "<EXPECTED_ENVIRONMENT_URL>"+```++Continue only when the JSON result has `ok: true`. This check compares the active PAC environment URL with the caller's URL and verifies that PAC, the Azure account, and the Dataverse access token use the same tenant. If it fails, stop and ask the user to switch PAC or Azure CLI authentication. Do not activate the imported Website Record ID in a different environment.++When `source` is `create-site template path` and `statusPath` is present, store it as `ACTIVATION_STATUS_PATH`. This is the existing template status file created by `/create-site`; do not create a separate status page.++When `SITE_IDENTITY_SOURCE !== "arguments"`, check whether the local project site is already activated by running the shared activation status script:```bashnode "${PLUGIN_ROOT}/scripts/check-activation-status.js" --projectRoot "<PROJECT_ROOT>"@@ -101,12 +124,14 @@ Evaluate the JSON result:- **If `activated` is `false`**: Proceed to Phase 2.- **If `error` is present**: Proceed to Phase 2 (do not block the activation flow).+When `SITE_IDENTITY_SOURCE = "arguments"`, skip this entire local-project status check and continue to Phase 2 with the supplied site identity.+### Output- PAC CLI installed and authenticated- Environment ID, Organization ID, and Cloud value extracted- Azure CLI login confirmed-- Activation status checked (already activated → stop early, not activated → continue)+- Activation status checked for a local project, or skipped for an argument-based imported site---@@ -118,6 +143,22 @@ Evaluate the JSON result:#### 2.1 Read Site Name+If the skill was invoked by another skill with explicit imported-site identity in `$ARGUMENTS`, use it before local project discovery:++```text+siteName: <name>+websiteRecordId: <guid>+```++When both values are present:++- Set `siteName` from the explicit value.+- Set `websiteRecordId` from the explicit value.+- Set `SITE_IDENTITY_SOURCE = "arguments"`.+- Skip the `powerpages.config.json` lookup below and skip Phase 2.3 (`pac pages list`) because the caller already resolved the imported website record.++If either explicit value is missing, continue with the existing local-project discovery flow.+Look for `powerpages.config.json` in the current directory or one level of subdirectories using `Glob`:```text@@ -155,10 +196,37 @@ Present the generated subdomain to the user and ask them to accept or enter thei|----------|--------|---------|| Your site subdomain will be: **`<suggestion>`** (full URL: `https://<suggestion>.<siteUrlDomain>`). Would you like to use this subdomain or enter your own? | Subdomain | Use `<suggestion>` (Recommended), Enter a custom subdomain |+When `ACTIVATION_STATUS_PATH` is set, use `Write` to atomically overwrite it immediately before `AskUserQuestion`:++```json+{+ "state": "running",+ "phase": "activation",+ "message": "Waiting for subdomain selection",+ "awaitingInput": true,+ "inputPrompt": "Choose the site subdomain in the agent terminal."+}+```++Immediately after the user responds, overwrite the file again so the toast disappears:++```json+{+ "state": "running",+ "phase": "activation",+ "message": "Preparing site activation",+ "awaitingInput": false+}+```++If the user cancels the prompt, clear `awaitingInput` before stopping. Apply the same status updates whenever a subdomain conflict loops back to this step.+**If custom**: The user provides their own subdomain via "Other" free text input. Validate it is lowercase, alphanumeric with hyphens only, and 3-50 characters.#### 2.3 Get Website Record ID+Skip this step when `SITE_IDENTITY_SOURCE = "arguments"` and `websiteRecordId` is already set.+Run `pac pages list` to get the website record ID:```bash@@ -216,9 +284,7 @@ node "${PLUGIN_ROOT}/skills/activate-site/scripts/activate-site.js" --siteName "Omit `--websiteRecordId` if it is null/empty.-The script acquires an Azure CLI token, POSTs to the websites API, extracts the `Operation-Location` header, and polls every 10 seconds for up to 5 minutes (refreshing the token periodically). It outputs a JSON result to stdout.--> **Note:** This script may run for up to 5 minutes while polling. Use a Bash timeout of at least 360 seconds (6 minutes).+Treat the script's JSON result as the authoritative activation result. Run it in the foreground with a Bash timeout of at least 360 seconds, and do not continue to Phase 5 until it exits. Do not launch a separate readiness poll.#### 4.2 Handle Results@@ -236,6 +302,8 @@ Evaluate the JSON output:| **`Running`** | — | Provisioning still in progress after 5 minutes. Inform the user it may take up to 15 minutes and suggest checking the Power Platform admin center. || `error` field | — | Prerequisite failure (missing args, no token). Present the error and help troubleshoot. |+Do not start a second background poll against `siteUrl` after the activation script returns `Succeeded`. HTTP and DNS propagation can lag behind provisioning; report that caveat in Phase 5 instead of leaving a command that can trigger another assistant turn. If an extra reachability poll was started accidentally, stop it before presenting the activation summary.+### Output- Provisioning status resolved (Succeeded with `siteUrl`, Failed with error details, or Running with timeout advisory)diff --git a/plugins/power-pages/skills/create-site/SKILL.md b/plugins/power-pages/skills/create-site/SKILL.mdindex 7b4b01692..26b32cd5b 100644--- a/plugins/power-pages/skills/create-site/SKILL.md+++ b/plugins/power-pages/skills/create-site/SKILL.md@@ -1,10 +1,11 @@---name: create-sitedescription: >-- Creates a new Power Pages code site (SPA) using React, Angular, Vue, or Astro. Guides through- the full process from initial concept to deployed site: requirements discovery, scaffolding,- component planning, design, implementation, validation, and deployment. Use when the user- wants to create, build, or scaffold a new Power Pages website or portal.+ Creates a new Power Pages code site (SPA) from a curated template or from scratch using React,+ Angular, Vue, or Astro. Guides through the full process from initial concept to deployed site:+ requirements discovery, template selection or scaffolding, component planning, design,+ implementation, validation, and deployment. Use when the user wants to create, build, use a+ template for, or scaffold a new Power Pages website or portal.user-invocable: trueargument-hint: Optional site descriptionallowed-tools: Read, Write, Edit, Grep, Glob, Bash, WebSearch, AskUserQuestion, Task, TaskCreate, TaskUpdate, TaskList, mcp__plugin_power-pages_playwright__browser_navigate, mcp__plugin_power-pages_playwright__browser_snapshot, mcp__plugin_power-pages_playwright__browser_click@@ -20,7 +21,7 @@ Guide the user through creating a complete, production-quality Power Pages code## Core Principles- **Use best judgement for design details**: Once the user picks an aesthetic direction and mood, make confident decisions about specific fonts, colors, page layouts, and component behavior. Do not ask the user to specify every detail — use the design reference and your own taste to make creative, distinctive choices.-- **Use TaskCreate/TaskUpdate**: Track all progress throughout all phases — create the todo list upfront with all phases before starting any work.+- **Use TaskCreate/TaskUpdate**: Track all progress throughout all phases — create the path-agnostic upfront tasks first, then append branch-specific tasks after the creation path is selected.- **Scaffold early, design with intention**: Get the dev server running immediately after discovery so the user has something to look at. Then plan the design and features while the scaffold is live — apply the chosen aesthetic during implementation.- **Live preview feedback loop**: The dev server MUST be running before any customization begins. Browse the site via Playwright (`browser_navigate` + `browser_snapshot`) to verify every significant change. Do NOT take screenshots — only use accessibility snapshots to check page structure and content.- **Keep the scaffold loader in sync with reality**: The scaffold loader polls `public/scaffold-status.json`. Update this file before every `AskUserQuestion` (to raise the "waiting for your input" banner so the user doesn't miss a terminal prompt) and before each implementation step in Phase 5 (so the progress-bar label matches what you're actually doing while the decorative spinner continues its default cycle). See [Live Preview Status Protocol](#live-preview-status-protocol).@@ -74,47 +75,599 @@ Write the file with the `Write` tool (atomic overwrite). You do not need to read<!-- gate: create-site:1.purpose | category=plan | cancel-leaves=nothing -->-> 🚦 **Gate (plan · create-site:1.purpose):** Multi-question prompt collecting site name, framework, purpose, audience, and target directory. Determines what gets scaffolded. Fires only on the "site purpose unclear" branch (step 3 below).+> 🚦 **Gate (plan · create-site:1.purpose):** Path-agnostic discovery prompt collecting site name, purpose, and audience. Determines what kind of site the user needs before the skill decides between a template-backed path and the from-scratch scaffold path. Fires only on the "site purpose unclear" branch (step 3 below).>-> **Trigger:** Phase 1 when site purpose was not provided in `$ARGUMENTS`.-> **Why we ask:** Wrong framework picked → wrong template copied into the wrong directory; cleanup is annoying.+> **Trigger:** Phase 1 when site name, purpose, or audience was not provided in `$ARGUMENTS`.+> **Why we ask:** Wrong purpose/audience context → wrong branch decision and wrong generated site plan; cleanup is annoying.> **Cancel leaves:** Nothing — no scaffolding has started yet.-1. Create todo list with all 8 phases (see [Progress Tracking](#progress-tracking) table)-2. If site purpose is clear from arguments:+1. Create the minimal upfront todo list (see [Progress Tracking](#progress-tracking)):+ - Discover site requirements+ - Select template or choose from-scratch+2. If site name, purpose, and audience are clear from arguments:- Summarize understanding- Identify site type (portal, dashboard, landing page, blog, etc.)-3. If site purpose is unclear, use `AskUserQuestion`:+3. If site name, purpose, or audience is unclear, use `AskUserQuestion`:| Question | Header | Options ||----------|--------|---------|| What should the site be called? (e.g., "Contoso Portal", "HR Dashboard") | Site Name | *(free text — use a single generic option so the user types a custom name via "Other")* |- | Which frontend framework? | Framework | React (Recommended), Vue, Angular, Astro || What is the site's purpose? | Purpose | Company Portal, Blog/Content, Dashboard, Landing Page || Who is the target audience? | Audience | Internal (employees, partners), External (public-facing customers) |- | Where should the project be created? | Location | Current directory, New folder in current directory (Recommended), Any other directory |--4. Resolve the project location:- - **If "Current directory"**: Project root = `<cwd>`.- - **If "New folder in current directory"**: Create a folder named `__SITE_NAME__` inside the cwd. Project root = `<cwd>/__SITE_NAME__/`.- - **If "Any other directory"**: Ask for the full path. Verify/create it. Project root = provided path.-- After resolving, confirm: "The site will be created at `<resolved path>`."-- Store this as `PROJECT_ROOT`.-5. From the user's answers, derive:+4. From the user's answers, derive:- `__SITE_NAME__` (Title Case, e.g., `Contoso Portal`)- `__SITE_SLUG__` (kebab-case derived from site name, e.g., `contoso-portal`)- `__SITE_DESCRIPTION__` (one-line description based on name + purpose)-6. Summarize understanding and confirm with user before proceeding+5. Summarize the path-agnostic understanding and confirm with user before proceeding:+ - Site name+ - Site purpose/type+ - Target audience++ Do **not** ask for framework or project location in Phase 1. Each creation path asks for its location after Phase 1.5 selects that path.**Audience influences site generation:**- **Internal**: Prioritize data tables, dashboards, authentication, navigation depth, functional over flashy design- **External**: Prioritize landing page appeal, SEO-friendly structure, contact forms, clean marketing-oriented layout-**Output**: Clear statement of site purpose, framework, audience, derived naming values, and project location+**Output**: Clear statement of site purpose, audience, and derived naming values.++---++## Phase 1.5: Template Branch Decision++**Goal**: Route the user into the appropriate creation path after path-agnostic Discovery.++> **Current implementation state:** Template discovery, selection, supporting-solution import, packaged SPA cloning/upload, optional seed data, activation, live-site preview, and terminal telemetry are implemented for `kind: "spa"`. Traditional catalog entries are accepted but not shown until their solution-only provisioning flow is implemented. The user can always choose **Start from scratch** to continue into the existing scaffold flow.++**Actions**:++1. Mark **Select template or choose from-scratch** as `in_progress`.++2. Fetch the template catalog:++ ```bash+ node "${PLUGIN_ROOT}/scripts/fetch-template-catalog.js"+ ```+ Use the returned immutable commit SHA for every template artifact request in this run. Pass `--ref <tag-or-branch>` only for a deliberate test or rollback.++ Evaluate the JSON result:+ - **If `ok: false`**: tell the user templates are temporarily unavailable and continue with the from-scratch path. This is additive; a catalog failure must never block `create-site`.+ - **If `ok: true` but `selectableCatalog.templates` is empty**: tell the user no supported SPA templates are currently available and continue with the from-scratch path. Do not offer entries from `catalog.templates` whose `kind` is `traditional`.+ - **If supported SPA templates are available**: use `selectableCatalog.templates` for every matching, preview, browse, and selection step below. Keep `catalog.templates` only as the complete downloaded manifest.++3. Semantically match the template families against the Phase 1 context (`$ARGUMENTS`, site name, purpose, audience, and any framework mentioned by the user):+ - Use each family template's `displayName`, `description`, `keywords`, `audience`, available variant frameworks, and any variant-specific previews.+ - Do **not** compute a numeric score or invent a ranking script. Keywords guide agent judgement; they are not counted.+ - Treat a template family as the user-facing template and a framework variant as the installable package. A family can have multiple variants (`react`, `vue`, `angular`, `astro`).++<!-- not-a-gate: read-only route selection after semantic matching; no project directory, Dataverse write, or durable skill state exists yet -->++4. Ask the user how to proceed after semantic matching:++ | Match situation | Question | Header | Options |+ |-----------------|----------|--------|---------|+ | One or more clear matches | I found matching template(s) for your site. What would you like to do? | Creation Path | Show matching templates (Recommended), Browse all templates, Create from scratch |+ | No clear match | I couldn't find a matching template for your site. What would you like to do? | Creation Path | Browse all templates, Create from scratch (Recommended) |++ Branch on the answer:+ - **Show matching templates**: set `TEMPLATE_PREVIEW_FAMILIES` to the matched family or families and continue to browser preview.+ - **Browse all templates**: set `TEMPLATE_PREVIEW_FAMILIES` to all entries in `selectableCatalog.templates` and continue to browser preview.+ - **Create from scratch**: set `CREATION_PATH = "from-scratch"` and continue to the deferred framework/location questions.++5. Render `TEMPLATE_PREVIEW_FAMILIES` for browser preview:++ - Download each `previewImages` artifact into the SHA-keyed cache before rendering:+ ```bash+ node "${PLUGIN_ROOT}/scripts/fetch-template-artifact.js" --sha "<catalog-sha>" --artifactPath "<preview-image-path>"+ ```+ Replace each preview image path with the returned `localUrl`. If a preview download returns `ok: false`, omit that one image from the gallery and continue; a missing preview should not block using an otherwise-valid template.+ - Write a temporary JSON file containing a `TEMPLATES_JSON` array with the template families the user should preview and the cached preview image URLs. Include each family's available variants so the browser can show framework badges/tabs, but keep the browser read-only.+ - Run:+ ```bash+ node "${PLUGIN_ROOT}/scripts/render-template-browser.js" --templatesJsonPath "<temp-json>" --outputPath "<temp-html>" --open+ ```+ Evaluate the JSON result before telling the user to use the browser:+ - **`status: "ok"`**: continue; the browser preview was generated and opened.+ - **`status: "invalid"`**: do not continue with template selection. Surface the validation errors, rebuild the `TEMPLATES_JSON` file from the matched families, and rerun the render. If it is still invalid, fall back to from-scratch rather than showing an empty or incomplete template browser.+ - **`status: "ok"` with `opened: false`**: the HTML validated but the browser could not be opened automatically. Show the file path and continue with terminal selection only after the user has had a chance to open it manually.+ - The browser view is read-only and exists to browse template capabilities and available framework variants; the terminal `AskUserQuestion` remains the decision surface.++<!-- not-a-gate: read-only route selection after template preview; only disposable temp preview files exist, with no project directory, Dataverse write, or durable skill state -->++6. Ask one of the following `AskUserQuestion` prompts:++ | Match situation | Prompt options |+ |-----------------|----------------|+ | One strong family + framework match | Use `<displayName>` - `<framework>` (Recommended), Choose another framework, See all templates, Start from scratch |+ | One strong family but no framework match | One option per available framework, See all templates, Start from scratch |+ | Several plausible family matches | One option per shortlisted family, See all templates, Start from scratch |+ | Full catalog browse | One option per family, Start from scratch |++ When the user chooses **See all templates** from a matching-template branch, set `TEMPLATE_PREVIEW_FAMILIES` to all entries in `selectableCatalog.templates`, render the family-first SPA template gallery, and ask again with the **Full catalog browse** options. If the selected family has multiple variants, ask a second terminal question for the framework.++7. Branch on the user's selection:+ - **Template family and framework variant selected**:+ 1. Set `SELECTED_TEMPLATE` to the family entry and `SELECTED_TEMPLATE_VARIANT` to the exact framework variant. Resolve the selected template assets once from the pinned catalog SHA. The result combines the family's supporting solutions with the selected variant's website code:+ ```bash+ node "${PLUGIN_ROOT}/scripts/fetch-template-variant.js" \+ --sha "<catalog-sha>" \+ --catalogPath "<catalogPath from fetch-template-catalog.js>" \+ --kind "<SELECTED_TEMPLATE.kind>" \+ --templateId "<SELECTED_TEMPLATE.id>" \+ --variant "<SELECTED_TEMPLATE_VARIANT.variantKey>"+ ```+ Use the returned `websiteCodePath` and `solutions`. Process `solutions` in the returned order; do not rediscover, reorder, or revalidate the template assets in the skill.+ 2. If the result is `ok: false`, tell the user the selected framework variant is unavailable or invalid. If the same family has other available framework variants, offer those first; otherwise offer **Start from scratch** or **Stop**. Do not emit `template_used` for a variant whose package did not validate. If the user falls back to from-scratch, recommend the framework they had selected.+ 3. If the result is `ok: true`, set `CREATION_PATH = "template"`, `SELECTED_TEMPLATE_SOLUTIONS = <result.solutions>`, and `SELECTED_TEMPLATE_WEBSITE_CODE = <result.websiteCodePath>`. Run the `template_used` telemetry command silently (fail-closed), then append the template pre-install tasks now (see [Progress Tracking](#progress-tracking)); append the execution tasks after the reinstall policy is known. Do **not** proceed to Phase 2.+ Do not mention this telemetry command to the user and do not print its output.+ ```bash+ node "${PLUGIN_ROOT}/scripts/emit-create-site-template-outcome.js" \+ --eventName template_used \+ --templateId "<SELECTED_TEMPLATE.id>" \+ --templateKind "<SELECTED_TEMPLATE.kind>" \+ --framework "<SELECTED_TEMPLATE_VARIANT.framework>" \+ --audience "<internal|external from Phase 1 discovery>"+ ```+ `--audience` is the site audience captured in Phase 1 (`internal` or `external`), **not** the template's `audience` persona array from the catalog manifest. Do not include site name, URL, subdomain, free-text purpose, or any other user-identifying value.+ 4. Mark **Choose local template directory** as `in_progress`.++<!-- not-a-gate: read-only location selection for the later template clone; no directory is created and no environment change has started -->++ Ask where to create the local template project:++ | Question | Header | Options |+ |----------|--------|---------|+ | Where should I create the template site's local files? | Project Location | Current directory, New folder in current directory (Recommended), Any other directory |++ Resolve the clone destination:+ - **Current directory**: use `<cwd>`.+ - **New folder in current directory**: use `<cwd>/<__SITE_SLUG__>/`.+ - **Any other directory**: ask for a full path and resolve it to an absolute path.++ The destination must not exist or must be empty. Check it without creating it. If it is non-empty, ask the user to choose another directory. Store the resolved path as `TEMPLATE_CLONE_OUTPUT_DIRECTORY`, confirm "The template project will be created under `<resolved path>`.", and mark **Choose local template directory** as `completed`.+ - **Start from scratch** or catalog unavailable: set `CREATION_PATH = "from-scratch"` and continue below.++8. For the template path only:++ 1. Mark **Resolve target environment** as `in_progress`.+ 2. Resolve the target environment via the shared auth helpers:+ ```bash+ node "${PLUGIN_ROOT}/scripts/resolve-template-import-context.js"+ ```+ Use the returned `environmentUrl` for the remaining template workflow. Downstream preflight, import, seed, and polling helpers acquire Azure tokens internally so credentials are never returned in JSON or carried between tasks. If `ok: false`, surface the error and stop before import. Do not emit `template_import_failure` because no import was attempted; `template_used` was already emitted when the template path was selected.++<!-- gate: create-site:1.5.confirm-environment | category=consent | cancel-leaves=template-cache -->++> 🚦 **Gate (consent · create-site:1.5.confirm-environment):** Confirm the resolved target environment before running template install preflights.+>+> **Trigger:** Phase 1.5 after `resolve-template-import-context.js` returns `environmentUrl` and before any CLI-tenant, `.js` unblock, language, solution import, seed, or activation step.+> **Why we ask:** PAC auth can point at a different Dataverse environment than the user intended. Even preflights can inspect or modify environment-level settings, so the skill must not continue silently.+> **Cancel leaves:** `template-cache` — template catalog assets, the discovered solution sources, and website code may already be cached locally; no org mutation has happened if cancelled here.++ 3. Mark **Resolve target environment** as `completed` and **Confirm target environment** as `in_progress`, then ask the user to confirm the resolved target environment before any environment preflight:++ | Question | Header | Options |+ |----------|--------|---------|+ | Use **`<environmentUrl>`** as the target environment for this template install? | Confirm Environment | Yes, use this environment (Recommended), No, start from scratch, Cancel |++ - **Yes**: continue to the preflight checks below.+ - **No, start from scratch**: set `CREATION_PATH = "from-scratch"` and continue to the deferred framework/location questions. Do not run environment preflights or import the template.+ - **Cancel**: stop before environment preflights. Do not emit `template_import_failure` because no import was attempted; `template_used` was already emitted when the template path was selected.++ 4. Mark **Confirm target environment** as `completed` and **Validate CLI tenant alignment** as `in_progress`, then confirm PAC CLI and Azure CLI are authenticated to the same tenant before any import preflight that depends on both CLIs:+ ```bash+ node "${PLUGIN_ROOT}/scripts/validate-cli-tenant-alignment.js" --envUrl "<environmentUrl>"+ ```+ - **`ok: true`**: mark **Validate CLI tenant alignment** as `completed`.+ - **`ok: false`**: surface the error and the `pacTenantId`, `azTenantId`, and `tokenTenantId` fields when present. Stop before import and tell the user to switch either PAC auth or Azure CLI to the same tenant, then rerun the skill. Do not emit `template_import_failure` because no import was attempted.+ 5. Mark both **Validate JavaScript unblock requirement** and **Validate Dataverse language requirements** as `in_progress`. Run the `.js` blocked-attachment dry run and the Dataverse language check in parallel because both are read-only preflights against the confirmed target environment:+ ```bash+ node "${PLUGIN_ROOT}/scripts/lib/fix-blocked-attachments.js" --envUrl "<environmentUrl>" --extensions js --dry-run --quiet+ node "${PLUGIN_ROOT}/scripts/check-available-languages.js" --envUrl "<environmentUrl>" --requiredLocaleIds "<SELECTED_TEMPLATE_VARIANT.requiredDataverseLanguages or SELECTED_TEMPLATE.requiredDataverseLanguages comma-separated>"+ ```+ Capture both JSON results before deciding what to do next. Do not mutate `blockedattachments` until the language check has also completed; if the language check blocks import, route to the language-requirement question without changing attachment settings.+ Evaluate the `.js` result:+ - **`wasBlocked` does not include `js`**: mark **Validate JavaScript unblock requirement** as `completed`; JavaScript attachments are allowed.+ - **`wasBlocked` includes `js`**: keep **Validate JavaScript unblock requirement** as `in_progress`; this may need the `.js` unblock consent gate below, but handle language failures first because they block import without any environment mutation.+ Evaluate the language result:+ - **`ok: true` and `hasRequiredLanguages: true`**: mark **Validate Dataverse language requirements** as `completed`; the target environment has every LCID required by the selected variant, falling back to the family requirements when the variant does not override them.+ - **`ok: false`**: tell the user the skill could not verify available Dataverse languages, surface the script error, then ask whether to switch to from-scratch or stop. Do not import the template and do not mutate `blockedattachments`.+ - **`ok: true` and `hasRequiredLanguages: false`**: explain that the selected template requires the missing Dataverse language LCIDs from `missingLocaleIds`. Block before any solution import mutation. Do not provide a "proceed anyway" branch and do not mutate `blockedattachments`.++<!-- gate: create-site:1.5.unblock-js | category=consent | cancel-leaves=attachment-block-modified -->++> 🚦 **Gate (consent · create-site:1.5.unblock-js):** Preflight unblock of `.js` from the target environment's `blockedattachments` setting before uploading website code.+>+> **Trigger:** Phase 1.5 when `fix-blocked-attachments.js --dry-run --extensions js` reports `.js` is blocked in the target environment.+> **Why we ask:** The packaged SPA is uploaded with `pac pages upload-code-site` after its supporting solutions are ready. That upload includes JavaScript files and fails when `.js` is blocked. Checking before solution import avoids leaving supporting artifacts behind when the site cannot be created.+> **Cancel leaves:** `attachment-block-modified` is possible only if the user approved and the update partially completed. Pure Cancel here leaves the original `blockedattachments` value untouched and no template installation has started.++ Use `AskUserQuestion`:++ | Question | Header | Options |+ |----------|--------|---------|+ | This environment currently blocks `.js` attachments. The template site's code upload will fail unless `.js` is unblocked. Remove only `js` from `blockedattachments` now? | Unblock JavaScript | Yes, unblock `.js` and continue (Recommended), No, start from scratch, Cancel |++ - **Yes**: run the helper without `--dry-run`, preserving every other blocked extension:+ ```bash+ node "${PLUGIN_ROOT}/scripts/lib/fix-blocked-attachments.js" --envUrl "<environmentUrl>" --extensions js --quiet+ ```+ Confirm the JSON result has `removed` containing `js` or `changed: true`, then rerun the dry-run check and continue only if `.js` is no longer blocked.+ - **No, start from scratch**: set `CREATION_PATH = "from-scratch"` and continue to the deferred framework/location questions. Do not import the template.+ - **Cancel**: stop before template installation. Do not emit `template_import_failure` because no import was attempted; `template_used` was already emitted when the template path was selected.++<!-- not-a-gate: route selection after a blocking preflight; no org mutation has happened and there is no option to override missing template language requirements -->++ 6. Use `AskUserQuestion` only when the language preflight cannot continue:++ | Question | Header | Options |+ |----------|--------|---------|+ | This template requires Dataverse language LCID(s) `<requiredLocaleIds>`, but the target environment is missing `<missingLocaleIds>` or the language check could not be completed. What would you like to do? | Template Language Requirement | Start from scratch (Recommended), Cancel |++ - **Start from scratch**: set `CREATION_PATH = "from-scratch"` and continue to the deferred framework/location questions. Do not import the template.+ - **Cancel**: stop before template installation. Do not emit `template_import_failure` because no import was attempted; `template_used` was already emitted when the template path was selected.++<!-- gate: create-site:1.5.template-import | category=consent | cancel-leaves=template-cache -->++> 🚦 **Gate (consent · create-site:1.5.template-import):** Confirm installing the selected template in the current Power Platform environment.+>+> **Trigger:** Phase 1.5 after the template variant and its unpacked solutions are downloaded and the target environment is resolved.+> **Why we ask:** The install can import unmanaged supporting solutions and create a new code site. Choosing the wrong environment or template is disruptive and cannot be cleanly undone.+> **Cancel leaves:** `template-cache` — the discovered solution sources and preview images may remain in the private SHA-keyed template cache; no org mutation has occurred.++ 7. If the language preflight passed but `.js` was blocked and the user approved/verification passed, mark **Validate JavaScript unblock requirement** as `completed`. Then mark **Confirm template install** as `in_progress`, present the template and environment, and ask:++ | Question | Header | Options |+ |----------|--------|---------|+ | Install **`<SELECTED_TEMPLATE.displayName>`** into **`<environmentUrl>`**? This imports any required unmanaged supporting solutions, clones and builds the website code, and uploads the new code site. Seed data is applied before activation when available. | Install Template | Yes, install this template (Recommended), No, start from scratch, Cancel |++ - **No, start from scratch**: set `CREATION_PATH = "from-scratch"` and continue to the deferred framework/location questions.+ - **Cancel**: stop; no org mutation has happened. Do not emit `template_import_failure` because no import was attempted; `template_used` was already emitted when the template path was selected.+ 8. Mark **Confirm template install** as `completed`. Initialize `TEMPLATE_SOLUTIONS_TO_IMPORT = []` and `TEMPLATE_SOLUTIONS_TO_SKIP = []`, then process every entry in `SELECTED_TEMPLATE_SOLUTIONS` in the returned order:+ ```bash+ node "${PLUGIN_ROOT}/scripts/inspect-template-solution.js" --solutionPath "<solution.solutionPath>"+ node "${PLUGIN_ROOT}/scripts/check-solution-installed.js" --solutionName "<solution.uniqueName>" --envUrl "<environmentUrl>"+ node "${PLUGIN_ROOT}/scripts/inspect-template-solution.js" --solutionPath "<solution.solutionPath>" --installed "<true|false>" --installedVersion "<version-or-empty>"+ ```+ Do not derive a website name from a solution or expect supporting-solution import to add a `pac pages list -v` row. If metadata inspection returns `ok: false` after variant validation, or `check-solution-installed.js` exits 1, treat that solution as `decision: "ask"` rather than assuming it is absent.+ - **`decision: "import"`**: append the solution to `TEMPLATE_SOLUTIONS_TO_IMPORT`.+ - **`decision: "confirm-update"`**: tell the user that this specific solution has a newer version available and confirm before adding it to `TEMPLATE_SOLUTIONS_TO_IMPORT`.++ <!-- gate: create-site:1.5.update-installed | category=consent | cancel-leaves=template-cache -->++ > 🚦 **Gate (consent · create-site:1.5.update-installed):** Confirm updating an already-installed unmanaged template solution. Repeat for each solution that needs an update.+ >+ > **Trigger:** Phase 1.5 when one of the selected template solutions is already installed and the downloaded source has a newer version.+ > **Loop behavior:** Fires once per matching entry in `SELECTED_TEMPLATE_SOLUTIONS`; three solutions needing updates require three confirmations.+ > **Why we ask:** Updating an unmanaged solution merges changes into the environment and cannot be cleanly rolled back.+ > **Cancel leaves:** `template-cache` — downloaded template artifacts remain in the private SHA-keyed template cache; no org mutation happens if cancelled.++ Use `AskUserQuestion`:++ | Question | Header | Options |+ |----------|--------|---------|+ | Solution `<solution.uniqueName>` is installed at version `<installedVersion>`, and the template contains `<availableVersion>`. Update it in this environment? | Update Solution | Yes, update this solution (Recommended), No, cancel |++ If the user declines or cancels, stop before import; no org mutation has happened. Do not emit `template_import_failure` because no import was attempted; `template_used` was already emitted when the template path was selected.+ If the user confirms, append this solution to `TEMPLATE_SOLUTIONS_TO_IMPORT`.+ - **`decision: "offer-clone"`**: append the same-or-newer solution to `TEMPLATE_SOLUTIONS_TO_SKIP`.+ - **`decision: "ask"`** or detection failure: ask whether to import that solution anyway, start from scratch, or stop.++ <!-- gate: create-site:1.5.reinstall-unknown | category=consent | cancel-leaves=template-cache -->++ > 🚦 **Gate (consent · create-site:1.5.reinstall-unknown):** Confirm whether to import when installed-solution detection failed.+ >+ > **Trigger:** Phase 1.5 when `check-solution-installed.js` cannot determine whether one selected template solution already exists.+ > **Loop behavior:** Fires once per unknown entry in `SELECTED_TEMPLATE_SOLUTIONS`; an answer applies only to the named solution.+ > **Why we ask:** Importing an unmanaged solution that may already exist can merge components.+ > **Cancel leaves:** `template-cache` — downloaded template artifacts remain in the private SHA-keyed template cache; no org mutation happens if cancelled.++ Use `AskUserQuestion`:++ | Question | Header | Options |+ |----------|--------|---------|+ | I couldn't determine whether solution `<solution.uniqueName>` is installed. Importing it may merge unmanaged components. How would you like to proceed? | Solution Install Unknown | Import anyway (advanced), Start from scratch (Recommended), Stop |++ Branch on the answer:+ - **Import anyway**: append this solution to `TEMPLATE_SOLUTIONS_TO_IMPORT`.+ - **Start from scratch**: set `CREATION_PATH = "from-scratch"` and continue to the deferred framework/location questions.+ - **Stop**: stop before import; no org mutation has happened. Do not emit `template_import_failure` because no import was attempted; `template_used` was already emitted when the template path was selected.++ After all solutions are classified, append the full site-install tasks. Include **Import template supporting solutions** only when `TEMPLATE_SOLUTIONS_TO_IMPORT` is non-empty. If every solution was skipped, ask once before creating the site:++ <!-- gate: create-site:1.5.clone-existing | category=consent | cancel-leaves=template-cache -->++ > 🚦 **Gate (consent · create-site:1.5.clone-existing):** Confirm creating a new site while reusing already-installed supporting solutions.+ >+ > **Trigger:** Phase 1.5 when every selected template solution is installed at the same or a newer version.+ > **Why we ask:** The skill will skip all solution imports but still clone and upload a new code site.+ > **Cancel leaves:** `template-cache` — downloaded template artifacts remain in the private SHA-keyed template cache; no site clone/upload happens if cancelled.++ | Question | Header | Options |+ |----------|--------|---------|+ | All supporting solutions are already installed at the same or newer versions. Create a new `<SELECTED_TEMPLATE_VARIANT.framework>` site from the website code? | Create Template Site | Yes, create the site (Recommended), No, cancel |++ If the user confirms, set `SKIP_TEMPLATE_SOLUTION_IMPORT = true`. If the user declines, stop. Do not emit an import result event because no solution import was attempted.++ 6. Render and open a read-only status page:+ ```bash+ # Create <temp-import-status-dir>/ under the operating-system temporary directory,+ # then write this initial status JSON to <temp-import-status-dir>/status.json:+ # Import path:+ # Use "Installing solution" when TEMPLATE_SOLUTIONS_TO_IMPORT has one entry,+ # otherwise use "Installing solutions":+ # { "state": "running", "phase": "solution", "message": "<solution install label>" }+ # SKIP_TEMPLATE_SOLUTION_IMPORT path:+ # { "state": "running", "phase": "site", "message": "Preparing template site" }+ node "${PLUGIN_ROOT}/scripts/render-template-import-status.js" \+ --templateName "<SELECTED_TEMPLATE.displayName>" \+ --statusPath "<temp-import-status-dir>/status.json" \+ --previewImagesJson '<JSON array of SELECTED_TEMPLATE.previewImages localUrl values from the template browser step>' \+ --solutionCount "<TEMPLATE_SOLUTIONS_TO_IMPORT.length, or SELECTED_TEMPLATE_SOLUTIONS.length when imports are skipped>" \+ --outputPath "<temp-import-status-dir>/index.html"+ node "${PLUGIN_ROOT}/scripts/serve-static-dir.js" --root "<temp-import-status-dir>" --urlFile "<temp-import-status-dir>/url.txt" --cleanupRoot+ node "${PLUGIN_ROOT}/scripts/open-url.js" --url "<url from <temp-import-status-dir>/url.txt>"+ ```+ Reuse the already-downloaded local preview image URLs from the browser step; do not fetch preview images again for this page.+ The server command returns only after the listener is ready. It removes the temporary status directory after a successful redirect, after the browser stops polling, or when the maximum lifetime expires.+ 7. Unless `SKIP_TEMPLATE_SOLUTION_IMPORT = true`, mark **Import template supporting solutions** as `in_progress`. Process `TEMPLATE_SOLUTIONS_TO_IMPORT` sequentially in its existing case-insensitive lexical unique-name order. For each entry, set `CURRENT_TEMPLATE_SOLUTION` and prepare its unmanaged solution for import:+ ```bash+ # Update the status JSON:+ # { "state": "running", "phase": "solution", "message": "Preparing solution <CURRENT_TEMPLATE_SOLUTION.uniqueName>" }+ node "${PLUGIN_ROOT}/scripts/pack-template-solution.js" \+ --solutionPath "<CURRENT_TEMPLATE_SOLUTION.solutionPath>"+ ```+ Set `PACKED_TEMPLATE_SOLUTION_ZIP = <result.zipPath>`, `PACKED_TEMPLATE_SOLUTION_WORK_DIRECTORY = <result.workDirectory>`, `PACKED_TEMPLATE_SOLUTION_CLEANUP_MARKER = <result.cleanupMarker>`, and `PACKED_TEMPLATE_SOLUTION_CLEANUP_TOKEN = <result.cleanupToken>` for the current solution. The packer creates the ZIP only in a token-owned OS temporary directory. Never write a packed ZIP into the downloaded template cache or another repository path.++ If packing fails, do not call Dataverse and do not emit `template_import_failure` because no import was attempted. The packer removes partial output automatically.++ <!-- gate: create-site:1.5.pack-failed | category=progress | cancel-leaves=template-cache -->++ > 🚦 **Gate (progress · create-site:1.5.pack-failed):** Choose how to proceed after preparing the local solution package fails.+ >+ > **Trigger:** Phase 1.5 when local validation or `pac solution pack` fails for one discovered solution.+ > **Loop behavior:** Fires per failed iteration of `TEMPLATE_SOLUTIONS_TO_IMPORT`; an answer applies only to `CURRENT_TEMPLATE_SOLUTION`.+ > **Why we ask:** No environment mutation has happened, but template installation cannot continue without a valid temporary solution ZIP.+ > **Cancel leaves:** `template-cache` — downloaded template source remains in the private SHA-keyed template cache; partial pack output has been removed.++ Use `AskUserQuestion`:++ | Question | Header | Options |+ |----------|--------|---------|+ | Solution `<CURRENT_TEMPLATE_SOLUTION.uniqueName>` could not be prepared for import. How would you like to proceed? | Template Pack Failed | Retry packing, Fall back to from-scratch (Recommended), Stop |++ - **Retry packing**: return to the pack command above.+ - **Fall back to from-scratch**: set `CREATION_PATH = "from-scratch"` and continue to the deferred framework/location questions.+ - **Stop**: stop after showing the local pack error. Do not mark **Import template supporting solutions** as completed.++ After packing succeeds, import the temporary ZIP inline. Do not invoke `/import-solution` or write ALM artifacts. After `ImportSolutionAsync` returns the async operation id, immediately clean the packer's work directory, then launch a Task subagent to run `poll-async-operation.js` and write `<temp-import-status-dir>/status.json`:+ ```bash+ node "${PLUGIN_ROOT}/scripts/encode-solution-file.js" --zipPath "<PACKED_TEMPLATE_SOLUTION_ZIP>"+ # Write a temp JSON body file containing:+ # {+ # "CustomizationFile": "<encoded>",+ # "OverwriteUnmanagedCustomizations": true,+ # "PublishWorkflows": true,+ # "ConvertToManaged": false+ # }+ node "${PLUGIN_ROOT}/scripts/dataverse-request.js" "<environmentUrl>" POST "ImportSolutionAsync" \+ --bodyFile "<temp-import-body.json>" \+ --include-headers+ node "${PLUGIN_ROOT}/scripts/pack-template-solution.js" \+ --cleanup \+ --workDirectory "<PACKED_TEMPLATE_SOLUTION_WORK_DIRECTORY>" \+ --cleanupMarker "<PACKED_TEMPLATE_SOLUTION_CLEANUP_MARKER>" \+ --cleanupToken "<PACKED_TEMPLATE_SOLUTION_CLEANUP_TOKEN>"+ # Run this poll command in a Task subagent, not in the main conversation:+ node "${PLUGIN_ROOT}/scripts/poll-async-operation.js" \+ --asyncJobId "<AsyncOperationId from ImportSolutionAsync>" \+ --envUrl "<environmentUrl>" \+ --intervalMs 30000 \+ --maxAttempts 75 \+ --statusFile "<temp-import-status-dir>/status.json"+ ```+ If encoding or `ImportSolutionAsync` fails before returning an async operation id, clean `PACKED_TEMPLATE_SOLUTION_WORK_DIRECTORY` before retrying, falling back, or stopping. Treat a cleanup failure as a local warning and show the work-directory path so the user can remove it manually; do not hide the original failure.++ The subagent must return the poller's final JSON when the command exits. Do not rely only on that notification: read `<temp-import-status-dir>/status.json` every 30 seconds until `state` is `succeeded`, `failed`, `canceled`, or `timeout`. Do not start the next solution import until the current solution succeeds, and do not start site cloning until every solution in `TEMPLATE_SOLUTIONS_TO_IMPORT` succeeds.+ If the poll result is not `Succeeded`, query the import job (using the `ImportJobKey` returned by `ImportSolutionAsync`) and parse its component-level error XML, following `/import-solution`'s Phase 6 pattern. Do **not** auto-clean up the unmanaged partial import. Run the `template_import_failure` telemetry command silently before asking the recovery question. Do not mention this telemetry command to the user and do not print its output:+ ```bash+ node "${PLUGIN_ROOT}/scripts/emit-create-site-template-outcome.js" \+ --eventName template_import_failure \+ --templateId "<SELECTED_TEMPLATE.id>" \+ --templateKind "<SELECTED_TEMPLATE.kind>" \+ --framework "<SELECTED_TEMPLATE_VARIANT.framework>" \+ --audience "<internal|external from Phase 1 discovery>" \+ --outcome failure \+ --errorClass "ImportSolutionAsync"+ ```+ `--audience` is the site audience captured in Phase 1 (`internal` or `external`), **not** the template's `audience` persona array from the catalog manifest. Do not add free-form error text to telemetry; it can contain paths, URLs, stack traces, or user data.++ <!-- gate: create-site:1.5.import-failed | category=progress | cancel-leaves=partial-unmanaged-template-import -->++ > 🚦 **Gate (progress · create-site:1.5.import-failed):** Choose how to proceed after template solution import fails.+ >+ > **Trigger:** Phase 1.5 when `ImportSolutionAsync` fails, times out, or reports component-level failures.+ > **Loop behavior:** Fires per failed iteration of `TEMPLATE_SOLUTIONS_TO_IMPORT`; an answer applies only to `CURRENT_TEMPLATE_SOLUTION`.+ > **Why we ask:** The environment may contain the current partial unmanaged import plus any earlier solutions imported during this run; retrying or switching paths should be an explicit choice.+ > **Cancel leaves:** `partial-unmanaged-template-import` — downloaded template artifacts remain in the private SHA-keyed template cache; the current partial import and any earlier successful solution imports remain in Dataverse and are explained in the error summary.++ Use `AskUserQuestion`:++ | Question | Header | Options |+ |----------|--------|---------|+ | Supporting solution `<CURRENT_TEMPLATE_SOLUTION.uniqueName>` failed or partially completed. How would you like to proceed? | Template Import Failed | Retry import, Fall back to from-scratch (Recommended), Stop |++ Branch on the answer:+ - **Retry import**: return to the pack-and-import command sequence above and poll again.+ - **Fall back to from-scratch**: set `CREATION_PATH = "from-scratch"` and continue to the deferred framework/location questions. Tell the user the unmanaged partial import may remain in Dataverse. The eventual from-scratch branch emits the single terminal telemetry event.+ - **Stop**: stop after showing the error summary. Do not mark **Import template supporting solutions** as completed and do not clone or upload the site. The `template_import_failure` event was already emitted when the import failure was detected.++ If the error is `AttachmentBlocked`, point to `/import-solution` Phase 5b remediation.+ Only continue to the next step when the import poll result is `Succeeded`.+ 8. When every required solution import succeeds, mark **Import template supporting solutions** as `completed` and set `EMIT_TEMPLATE_IMPORT_SUCCESS = true`. Defer that telemetry event until the seed-data workstream joins so `seedApplied` reflects this run. If every solution import was skipped, mark the task as skipped and set `EMIT_TEMPLATE_IMPORT_SUCCESS = false`.+ 9. Start site provisioning and seed-data application concurrently after all required solution imports finish:+ - Mark **Clone, build, and upload template site** as `in_progress`.+ - If seed data is present, mark **Apply template seed data** as `in_progress` and launch the seed-data workstream with `Task` using `run_in_background: true`. The background task must only fetch, apply, and verify seed data. It must not clone, build, upload, activate, update the shared status file, ask the user questions, or retry failed writes.+ - Run the site-provisioning wrapper in the main conversation while the seed-data task runs. These workstreams are independent after the supporting solution import creates the required Dataverse tables.++ When seed data is present, update the status page:+ ```json+ { "state": "running", "phase": "siteAndSeed", "message": "Creating template site and seeding data" }+ ```+ When seed data is absent, update it with:+ ```json+ { "state": "running", "phase": "site", "message": "Cloning, building, and uploading template site" }+ ```+ Clone the packaged SPA source into the directory selected earlier, then upload the clone:+ ```bash+ node "${PLUGIN_ROOT}/scripts/provision-template-site.js" \+ --sourcePath "<SELECTED_TEMPLATE_WEBSITE_CODE>" \+ --outputDirectory "<TEMPLATE_CLONE_OUTPUT_DIRECTORY>" \+ --siteName "<__SITE_NAME__>"+ ```+ Treat the wrapper as the sole template-site provisioning entry point. Do not rerun its underlying `pac`, `npm`, or build commands directly for diagnosis. Never pipe a mutating command such as `pac pages clone` or `pac pages upload-code-site` through `head`, `tail`, or another consumer that can close the output stream before the command finishes. The wrapper safely captures a bounded diagnostic tail without interrupting the command. On success, save the returned `clonedPath` as both `CLONED_TEMPLATE_SITE_PATH` and `PROJECT_ROOT`, `siteName` as `IMPORTED_SITE_NAME`, and `websiteRecordId` as `IMPORTED_WEBSITE_RECORD_ID`.+ 10. In the seed-data background task, run:+ ```bash+ node "${PLUGIN_ROOT}/scripts/fetch-template-seed-data.js" --sha "<catalog-sha>" --seedDataPath "<SELECTED_TEMPLATE_VARIANT.seedDataPath or SELECTED_TEMPLATE.seedDataPath>"+ ```+ If the result is `ok: true`, use `localDir` as the attachment base and `seedFile` as the only seed JSON:+ ```bash+ node "${PLUGIN_ROOT}/scripts/apply-seed-data.js" \+ --seedDir "<localDir>" \+ --seedFile "<seedFile>" \+ --envUrl "<environmentUrl>"+ ```+ Return the JSON summary (`inserted`, `failed`, `skipped`, `errors`) to the main conversation. Seed records must use the exact table entity-set names, column logical names, and `<NavigationProperty>@odata.bind` lookup names from the template solution metadata. Never derive lookup navigation properties from a primary key, entity set, display name, or app-style alias such as `categoryId`; the seeder rejects ambiguous aliases before its first Dataverse write. For a lightweight read-only verification path, query each seeded `entitySetName` with `dataverse-request.js` using `GET "<entitySetName>?$top=1"` and report whether the seeded table is reachable. Prefer the selected variant's `seedDataPath` when present; otherwise use the family `seedDataPath`.+ 11. Wait for both workstreams to finish before showing the inactive-site summary or starting activation. Record the seed summary, then mark **Apply template seed data** as `completed`; if seed data is absent, mark it skipped. Seed fetch and insertion remain best-effort: surface their result, but do not fail site creation or block activation.++ If `EMIT_TEMPLATE_IMPORT_SUCCESS = true`, emit the import result now:+ ```bash+ node "${PLUGIN_ROOT}/scripts/emit-create-site-template-outcome.js" \+ --eventName template_import_success \+ --templateId "<SELECTED_TEMPLATE.id>" \+ --templateKind "<SELECTED_TEMPLATE.kind>" \+ --framework "<SELECTED_TEMPLATE_VARIANT.framework>" \+ --audience "<internal|external from Phase 1 discovery>" \+ --seedApplied "<true only when the seed summary has inserted > 0 and failed = 0; otherwise false>"+ ```+ `--audience` is the site audience captured in Phase 1 (`internal` or `external`), **not** the template's `audience` persona array from the catalog manifest. Do not include site name, URL, subdomain, free-text purpose, or any other user-identifying value.+ 12. If clone, cloned-identity inspection, dependency installation, build, build-output validation, or upload fails, run `template_clone_failure` telemetry silently. Map the returned `step` to `errorClass`: `clone`/`clone-output` → `PacPagesClone`, `install` → `NpmInstall`, `build` → `NpmBuild`, `build-output` → `CompiledOutput`, and `upload` → `PacPagesUploadCodeSite`:+ ```bash+ node "${PLUGIN_ROOT}/scripts/emit-create-site-template-outcome.js" \+ --eventName template_clone_failure \+ --templateId "<SELECTED_TEMPLATE.id>" \+ --templateKind "<SELECTED_TEMPLATE.kind>" \+ --framework "<SELECTED_TEMPLATE_VARIANT.framework>" \+ --audience "<internal|external from Phase 1 discovery>" \+ --outcome failure \+ --errorClass "<PacPagesClone|NpmInstall|NpmBuild|CompiledOutput|PacPagesUploadCodeSite>"+ ```+ Update the status page before firing the recovery gate:+ ```json+ { "state": "error", "phase": "site", "message": "Template site creation failed" }+ ```+ Diagnose the failure only from the wrapper's returned `step`, `error`, and preserved local path. Do not rerun the wrapper or any underlying command until the user chooses a recovery option.+ Then fire this gate:++ <!-- gate: create-site:1.5.clone-failed | category=progress | cancel-leaves=partial-template-clone -->++ > 🚦 **Gate (progress · create-site:1.5.clone-failed):** Choose how to proceed after cloning, building, or uploading the packaged template site fails.+ >+ > **Trigger:** Phase 1.5 when cloning, cloned identity inspection, dependency installation, the project build, compiled-output validation, or `pac pages upload-code-site` fails.+ > **Why we ask:** The selected project directory can contain partial clone or build output, the environment can contain a partial code-site upload, and supporting solutions may already be installed.+ > **Cancel leaves:** `partial-template-clone` — cached template artifacts and local files remain in the selected project directory; supporting solutions or a partial site upload may also remain in Dataverse.++ | Question | Header | Options |+ |----------|--------|---------|+ | The template site could not be cloned, built, or uploaded. How would you like to proceed? | Site Creation Failed | Retry site creation (Recommended), Fall back to from-scratch, Stop |++ Do not retry automatically. If the wrapper returned `outputDirectoryRemoved: true`, **Retry site creation** may reuse the same selected location. Otherwise, ask for a new empty directory using the same **Project Location** prompt, update `TEMPLATE_CLONE_OUTPUT_DIRECTORY`, and rerun the wrapper. If the user falls back to from-scratch, explain that local files, supporting solutions, or a partial site upload may remain and recommend `<SELECTED_TEMPLATE_VARIANT.framework>`.+ 13. When clone, build, and upload succeed, mark **Clone, build, and upload template site** as `completed` and run `template_clone_success` telemetry silently:+ ```bash+ node "${PLUGIN_ROOT}/scripts/emit-create-site-template-outcome.js" \+ --eventName template_clone_success \+ --templateId "<SELECTED_TEMPLATE.id>" \+ --templateKind "<SELECTED_TEMPLATE.kind>" \+ --framework "<SELECTED_TEMPLATE_VARIANT.framework>" \+ --audience "<internal|external from Phase 1 discovery>"+ ```+ Do not include the site name, clone path, URL, or Website Record ID in telemetry.+ 14. Mark **Show inactive template site** as `in_progress`. Tell the user: "Template `<displayName>` was created as `<IMPORTED_SITE_NAME>` (`<IMPORTED_WEBSITE_RECORD_ID>`). It is not activated yet. Seed-data processing is complete, and activation is next." If the template has no seed data, say that instead of implying records were inserted. Mark **Show inactive template site** as `completed`.+ 15. Mark **Activate template site** as `in_progress`. Before invoking `/activate-site`, update the status page:+ ```json+ { "state": "running", "phase": "activation", "message": "Activating template site", "awaitingInput": false }+ ```+ Then invoke `/activate-site`, passing the resolved identity and status path in the request so it skips local-project discovery and can show a toast while waiting for activation input:+ ```text+ Activate cloned template site:+ - siteName: <IMPORTED_SITE_NAME>+ - websiteRecordId: <IMPORTED_WEBSITE_RECORD_ID>+ - environmentUrl: <environmentUrl>+ - statusPath: <temp-import-status-dir>/status.json+ - source: create-site template path+ ```+ The activate-site skill owns subdomain selection, the waiting-for-input toast, final activation confirmation, provisioning-status polling, and recovery. Its foreground activation script is the only poll required by this flow.+ If activation fails, tell the user the cloned site exists but is not live and can be activated later by rerunning `/activate-site` with this identity. Do not treat activation failure as a failed supporting-solution import or site upload.+ 16. When `/activate-site` returns a `siteUrl`, mark **Activate template site** as `completed` and **Show live template site** as `in_progress`.+ 17. Redirect the already-open status page to the live site:+ ```json+ {+ "state": "succeeded",+ "message": "Template site is live. Opening it now...",+ "redirectUrl": "<siteUrl>",+ "shutdownServer": true+ }+ ```+ Do not open a second browser page for the template path. The status page polls this file and redirects the same tab to `redirectUrl` when the URL is `http` or `https`. `shutdownServer: true` tells the local server to remove the temporary status directory after a short redirect grace period. If the user closed the status page, show the `siteUrl` for manual opening.++ Always surface the activate-site DNS propagation caveat: the site may take a few minutes to load even after activation succeeds. Do not start a separate background command or Task to wait for the live URL to return HTTP 200. The status-page redirect and DNS note handle that delay without leaving work that can resume the conversation after the completion summary. If a reachability poll was started accidentally, stop it before marking **Show live template site** as `completed`.+ 18. Mark **Show live template site** as `completed`, then present the template-path summary:+ - Template name and framework+ - Cloned site name and Website Record ID+ - Live site URL+ - DNS propagation note: the site may take a few minutes to load everywhere+ - Local project path (`PROJECT_ROOT`)+ - "Your site is live. Want to keep customizing the local project?"++<!-- not-a-gate: optional post-live template customization branch; the local clone already exists and the site is live -->++ 19. Use `AskUserQuestion`:++ | Question | Header | Options |+ |----------|--------|---------|+ | Your template site is live. Do you want to customize the local project now? | Customize Template Site | Yes, customize now (Recommended), No, finish here |++ - **No, finish here**: mark **Select template or choose from-scratch** as `completed`, then stop.+ - **Yes, customize now**: append the template customization tasks (see [Progress Tracking](#progress-tracking)), then continue below.++ 20. Mark **Plan template customizations** as `in_progress`, then ask what the user wants changed in `PROJECT_ROOT`. Use the existing Phase 3/4/5/6/7 implementation, verification, and review flow against the cloned project; do **not** run Phase 2 scaffold/copy-template.+ 21. After the customization plan is approved, mark **Plan template customizations** as `completed`, **Implement pages and components** as `in_progress`, and make the requested changes.+ 22. Run the existing validation/review flow. Do not automatically deploy unless the user explicitly asks to run `/deploy-site`.++8. For the from-scratch path only, tell the user: "I'll scaffold this site from scratch."++<!-- not-a-gate: deferred data-gathering prompt for framework and directory before any scaffold files are written -->++9. Ask the from-scratch-only questions that were deferred from Phase 1:++ | Question | Header | Options |+ |----------|--------|---------|+ | Which frontend framework? | Framework | React (Recommended), Vue, Angular, Astro |+ | Where should the project be created? | Location | Current directory, New folder in current directory (Recommended), Any other directory |++10. Resolve the project location:+ - **If "Current directory"**: Project root = `<cwd>`.+ - **If "New folder in current directory"**: Create a folder named `__SITE_NAME__` inside the cwd. Project root = `<cwd>/__SITE_NAME__/`.+ - **If "Any other directory"**: Ask for the full path. Verify/create it. Project root = provided path.++ After resolving, confirm: "The site will be created at `<resolved path>`."++ Store this as `PROJECT_ROOT`.+11. Append the from-scratch task list (Phases 2-8) to the todo list (see [Progress Tracking](#progress-tracking)), then mark **Select template or choose from-scratch** as `completed`.++**Output**: cloned template site identity (`IMPORTED_SITE_NAME`, `IMPORTED_WEBSITE_RECORD_ID`) and a local project path ready for optional customization; or `CREATION_PATH = "from-scratch"` with selected framework and resolved project location.---@@ -570,7 +1123,7 @@ Run the audit script via `Bash`, passing the dev server URL and all site routes:node "${PLUGIN_ROOT}/skills/create-site/scripts/axe-audit.js" --url <DEV_SERVER_URL> --routes /,/about,/services,/contact --project-root "<PROJECT_ROOT>"```-The script launches a headless browser, navigates to each route, injects axe-core from CDN, runs the analysis, and outputs a JSON array of per-route results to stdout. Each result contains `violations` (with `id`, `impact`, `description`, `helpUrl`, and affected `nodes`), `passes` count, and `incomplete` count. The script exits with code 1 if any `critical` or `serious` violations are found.+Parse the returned JSON array of per-route results. Each result contains `violations` (with `id`, `impact`, `description`, `helpUrl`, and affected `nodes`), `passes` count, and `incomplete` count. A nonzero exit means at least one `critical` or `serious` violation was found.Parse the JSON output and record all violations.@@ -692,6 +1245,13 @@ Present a summary table to the user:- `/add-seo` — Add meta tags, robots.txt, sitemap.xml, favicon- `/add-tests` — Add unit tests (Vitest) and E2E tests (Playwright)- `/add-ai-webapi` — Add generative-AI summaries (Search Summary and Data Summarization). **Recommend first when `AI_SUMMARY_PLACEMENTS` from Phase 3 is non-empty** — the pages already carry `POWERPAGES:AI-SLOT` comment markers at the intended insertion points, so the follow-up skill's explore step finds them deterministically and the user gets the AI surface they picked during discovery without any page redesign.+7. Run the `create_site_from_scratch` telemetry command silently (fail-closed). Do not mention this telemetry command to the user and do not print its output:+ ```bash+ node "${PLUGIN_ROOT}/scripts/emit-create-site-template-outcome.js" \+ --eventName create_site_from_scratch \+ --framework "<framework>" \+ --audience "<audience>"+ ```**Output**: Deployed (or deployment-ready) site with clear next steps@@ -711,18 +1271,25 @@ Present a summary table to the user:### Key Decision Points (Wait for User)-1. After Phase 1: Confirm site purpose, framework, and project location-2. After Phase 4: Approve implementation plan-3. After Phase 7: Accept site or request changes-4. At Phase 8: Deploy or skip+1. After Phase 1: Confirm site purpose and audience+2. During Phase 1.5: Choose framework and project location for the from-scratch path+3. After Phase 4: Approve implementation plan+4. After Phase 7: Accept site or request changes+5. At Phase 8: Deploy or skip### Progress Tracking-Before starting Phase 1, create a task list with all phases using `TaskCreate`:+Before starting Phase 1, create only the path-agnostic upfront tasks using `TaskCreate`:++| Task subject | activeForm | Description |+|-------------|------------|-------------|+| Discover site requirements | Discovering requirements | Collect site name, purpose, audience, and derived naming values |+| Select template or choose from-scratch | Selecting creation path | Offer matching templates, or route the user into the from-scratch path |++After Phase 1.5 selects the from-scratch path, append the existing from-scratch phase tasks:| Task subject | activeForm | Description ||-------------|------------|-------------|-| Discover site requirements | Discovering requirements | Collect site name, framework, purpose, audience, and project location || Scaffold and launch dev server | Scaffolding project | Copy template, replace placeholders with defaults, git init, npm install, start dev server, share URL || Plan site components | Planning components | Determine pages, components, design direction, and routes while user previews scaffold || Approve implementation plan | Getting plan approval | Present implementation plan covering design and pages, get user approval |@@ -731,7 +1298,40 @@ Before starting Phase 1, create a task list with all phases using `TaskCreate`:| Review with user | Reviewing site | Navigate all pages, share URL, get user feedback, apply changes || Deploy and wrap up | Deploying site | Ask about deployment, present summary, suggest next steps |-Mark each task `in_progress` when starting it and `completed` when done via `TaskUpdate`. This gives the user visibility into progress and keeps the workflow deterministic.+After Phase 1.5 selects the template path, append the pre-install tasks immediately so the user can see each environment check:++| Task subject | activeForm | Description |+|-------------|------------|-------------|+| Choose local template directory | Choosing project location | Ask where the local template project should be cloned and require a new or empty destination |+| Resolve target environment | Resolving environment | Resolve the active PAC/Azure target environment and token before any environment preflight |+| Confirm target environment | Confirming environment | Ask whether the resolved environment is the one the user wants for the template install |+| Validate CLI tenant alignment | Checking CLI tenants | Verify PAC CLI and Azure CLI are authenticated to the same tenant before installation |+| Validate JavaScript unblock requirement | Checking JavaScript setting | Check `blockedattachments` for `.js` and, with consent, remove only `js` before site upload |+| Validate Dataverse language requirements | Checking language availability | Call `RetrieveAvailableLanguages` and require every LCID listed in the selected template's `requiredDataverseLanguages` |+| Confirm template install | Confirming template install | Show the selected template and target environment, then ask for final install consent |++After the reinstall policy chooses a normal import, update, or import-anyway path, append:++When `TEMPLATE_SOLUTIONS_TO_IMPORT` contains exactly one entry, use the task subject **Import template supporting solution** and active form **Importing supporting solution**. Use the plural forms in the table for two or more entries.++| Task subject | activeForm | Description |+|-------------|------------|-------------|+| Import template supporting solutions | Importing supporting solutions | Import each required unmanaged supporting solution in deterministic order and poll every async job to completion |+| Clone, build, and upload template site | Creating template site | Clone the packaged SPA source into the selected local directory, install dependencies, build and verify the configured compiled output, then upload the resulting code site |+| Apply template seed data | Applying seed data | In parallel with site creation, insert optional template seed records using the deterministic seed-data script; failures do not block activation |+| Show inactive template site | Showing template site | After site creation and seeding join, use the Website Record ID written by `pac pages clone` to `.powerpages-site/website.yml` and tell the user the uploaded site is not activated yet |+| Activate template site | Activating template site | Invoke activate-site with the resolved site name and Website Record ID |+| Show live template site | Showing live site | Open the activated site URL in the browser and invite the user to continue customizing |++If the user chooses to customize the live template, append:++| Task subject | activeForm | Description |+|-------------|------------|-------------|+| Plan template customizations | Planning customizations | Ask what the user wants changed and plan edits against the existing cloned project |++When every supporting solution is already installed at the same or newer version, append the same list without **Import template supporting solutions**. The packaged SPA clone/upload, site discovery, seed, activation, and live-preview tasks still run.++Mark each task `in_progress` when starting it and `completed` when done via `TaskUpdate`. This gives the user visibility into progress and keeps the workflow deterministic while avoiding permanently skipped tasks on future non-from-scratch branches.### Quality Standards@@ -759,9 +1359,13 @@ Every site must meet these standards before completion:### Phase 1: Discovery- Name: Partner Portal-- Framework: React- Purpose: Company Portal- Audience: Internal (partners, consultants)++### Phase 1.5: Template Branch Decision++- Creation path: From-scratch+- Framework: React- Location: New folder `partner-portal` in current directory### Phase 2: Scaffold & Launchdiff --git a/plugins/power-pages/skills/create-site/assets/template-browser.html b/plugins/power-pages/skills/create-site/assets/template-browser.htmlnew file mode 100644index 000000000..2122541df--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/template-browser.html@@ -0,0 +1,93 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8"/>+ <meta name="viewport" content="width=device-width,initial-scale=1.0"/>+ <title>Browse Power Pages templates</title>+ <link rel="icon" href="data:,">+ <style>+ :root{+ --bg:#faf9f8; --surface:#ffffff; --surface2:#f3f2f1; --border:#e1dfdd; --border-light:#c8c6c4;+ --text:#323130; --text-dim:#605e5c; --text-bright:#201f1e; --accent:#0078d4; --accent-bg:#0078d40a; --accent-border:#0078d425;+ --purple:#8764b8; --purple-bg:#8764b80a; --purple-border:#8764b820; --pass:#107c10; --pass-bg:#107c100a; --pass-border:#107c1020;+ --mono:'Cascadia Code','Consolas',monospace; --sans:'Segoe UI','Segoe UI Web (West European)',-apple-system,system-ui,sans-serif;+ --radius:8px; --radius-sm:4px; --shadow-4:0 1.6px 3.6px 0 rgba(0,0,0,0.132),0 0.3px 0.9px 0 rgba(0,0,0,0.108);+ }+ *{margin:0;padding:0;box-sizing:border-box;}+ body{font-family:var(--sans);background:var(--bg);color:var(--text);font-size:14px;line-height:1.6;}+ .topbar{z-index:100;background:var(--surface);box-shadow:var(--shadow-4);padding:14px 28px;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px;position:sticky;top:0;}+ .topbar-left{display:flex;align-items:center;gap:14px;}+ .logo{width:36px;height:36px;object-fit:contain;display:block;flex-shrink:0;}+ .topbar-title{font-size:16px;font-weight:700;color:var(--text-bright);}+ .topbar-sub{font-size:11px;color:var(--text-dim);margin-top:1px;}+ .pill{font-size:11px;padding:4px 10px;border-radius:999px;font-weight:600;letter-spacing:0.2px;border:1px solid var(--accent-border);background:var(--accent-bg);color:var(--accent);}+ .layout{display:flex;min-height:calc(100vh - 65px);}+ .sidebar{width:240px;background:var(--surface);border-right:1px solid var(--border);padding:20px 0;flex-shrink:0;}+ .nav-group-label{font-size:10px;font-weight:700;color:var(--text-dim);text-transform:uppercase;letter-spacing:1.2px;padding:16px 22px 6px;}+ .nav-btn{display:flex;align-items:center;gap:10px;width:100%;padding:11px 22px;background:none;border:none;border-left:2px solid transparent;color:var(--text-dim);font-size:13px;font-weight:500;font-family:var(--sans);text-align:left;}+ .nav-btn.active{color:var(--accent);font-weight:600;border-left-color:var(--accent);background:var(--accent-bg);}+ .nav-icon{font-size:15px;opacity:0.7;width:18px;text-align:center;}+ .content{flex:1;padding:32px 40px 72px;max-width:1180px;}+ h2{font-size:21px;font-weight:800;color:var(--text-bright);letter-spacing:-0.3px;margin-bottom:5px;}+ h3{font-size:18px;font-weight:800;color:var(--text-bright);letter-spacing:-0.2px;margin-bottom:6px;}+ .section-desc{font-size:13px;color:var(--text-dim);margin-bottom:20px;max-width:760px;}+ .summary-box{background:var(--surface);border:1px solid var(--border);border-radius:12px;padding:22px;margin-bottom:22px;font-size:14px;color:var(--text);line-height:1.75;}+ .template-section{display:none;}+ .template-section.active{display:block;animation:fadeIn 0.24s ease;}+ @keyframes fadeIn{from{opacity:0;transform:translateY(6px);}to{opacity:1;transform:translateY(0);}}+ .template-hero{display:flex;justify-content:space-between;gap:18px;align-items:flex-start;margin-bottom:16px;}+ .template-desc{font-size:14px;color:var(--text);margin:14px 0 24px;max-width:900px;}+ .template-framework{font-size:11px;padding:4px 10px;border-radius:999px;font-weight:700;text-transform:uppercase;letter-spacing:0.4px;background:var(--pass-bg);border:1px solid var(--pass-border);color:var(--pass);white-space:nowrap;}+ .template-meta{margin-bottom:12px;}+ .field-label{font-size:11px;font-weight:600;color:var(--text-dim);text-transform:uppercase;letter-spacing:0.5px;margin-bottom:7px;}+ .previews-label{margin-top:4px;}+ .chip-row{display:flex;flex-wrap:wrap;gap:6px;}+ .chip{font-size:11px;padding:3px 10px;border-radius:4px;font-weight:600;background:var(--surface2);border:1px solid var(--border);color:var(--text);}+ .muted{font-size:12px;color:var(--text-dim);}+ .empty-note{font-size:13px;color:var(--text-dim);background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:18px 20px;}+ .preview-stack{display:grid;gap:28px;}+ .preview-boundary{border:1px solid var(--border);background:var(--surface);box-shadow:var(--shadow-4);}+ .preview-boundary figcaption{font-size:11px;color:var(--text-dim);font-family:var(--mono);padding:8px 12px;border-bottom:1px solid var(--border);background:var(--surface2);}+ .preview-image{display:block;width:100%;height:auto;}+ @media(max-width:900px){+ .layout{flex-direction:column;}+ .sidebar{width:100%;border-right:none;border-bottom:1px solid var(--border);padding:8px;}+ .nav-group-label{padding:8px 14px 4px;}+ .nav-btn{border-left:none;border-bottom:2px solid transparent;width:auto;padding:10px 14px;}+ .nav-btn.active{border-bottom-color:var(--accent);}+ .content{padding:20px 16px 72px;}+ }+ </style>+</head>+<body>+ <div class="topbar">+ <div class="topbar-left">+ <img class="logo" src="./power-pages-icon.png" alt="Power Pages" />+ <div>+ <div class="topbar-title">Browse Power Pages templates</div>+ <div class="topbar-sub">Review capabilities here, then return to the terminal for the actual choice.</div>+ </div>+ </div>+ <span class="pill">__TEMPLATE_COUNT__ templates</span>+ </div>+ <div class="layout">+ <aside class="sidebar">+ <div class="nav-group-label">Templates</div>+ __RAW_TEMPLATE_TABS_HTML__+ </aside>+ <main class="content">+ __RAW_TEMPLATE_SECTIONS_HTML__+ </main>+ </div>+ <script>+ document.querySelectorAll('[data-tab]').forEach((button) => {+ button.addEventListener('click', () => {+ document.querySelectorAll('[data-tab]').forEach((item) => item.classList.remove('active'));+ document.querySelectorAll('.template-section').forEach((section) => section.classList.remove('active'));+ button.classList.add('active');+ document.getElementById(button.dataset.tab)?.classList.add('active');+ });+ });+ </script>+</body>+</html>diff --git a/plugins/power-pages/skills/create-site/assets/template-import-status.html b/plugins/power-pages/skills/create-site/assets/template-import-status.htmlnew file mode 100644index 000000000..bc3ca4fe7--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/template-import-status.html@@ -0,0 +1,526 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Setting up __TEMPLATE_NAME__ template</title>+ <link rel="preconnect" href="https://fonts.googleapis.com" />+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />+ <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600&family=DM+Sans:wght@400;500&display=swap" rel="stylesheet" />+ <link rel="icon" href="data:," />+ <style>+ :root {+ --pp-violet: #7B5EA7;+ --pp-purple: #8B6FC0;+ --pp-lavender: #A78BDB;+ --pp-periwinkle: #8088D9;+ --pp-sky: #5A9BD5;+ --pp-deep-violet: #5C3D8F;+ --pp-bg: #F7F5FA;+ --pp-surface: #FFFFFF;+ --pp-text: #2D1B4E;+ --pp-text-secondary: #6B5A82;+ --pp-text-muted: #9B8FB5;+ --pp-border: rgba(139, 111, 192, 0.12);+ --pp-error: #B42318;+ --pp-success: #087443;+ --pp-glow: rgba(139, 111, 192, 0.2);+ }+ * { margin: 0; padding: 0; box-sizing: border-box; }+ html, body { overflow: hidden; background: var(--pp-bg); color: var(--pp-text); font-family: 'DM Sans', sans-serif; }+ .loading-wrapper { position: fixed; inset: 0; display: flex; align-items: center; justify-content: center; background: var(--pp-bg); }+ .ambient { position: fixed; inset: 0; z-index: 0; overflow: hidden; }+ .ambient::before {+ content: ''; position: absolute; width: 160%; height: 160%; top: -30%; left: -30%;+ background:+ radial-gradient(ellipse 600px 600px at 25% 30%, rgba(167, 139, 219, 0.12) 0%, transparent 70%),+ radial-gradient(ellipse 500px 500px at 75% 70%, rgba(90, 155, 213, 0.08) 0%, transparent 70%),+ radial-gradient(ellipse 800px 400px at 50% 50%, rgba(139, 111, 192, 0.06) 0%, transparent 60%);+ animation: ambientDrift 25s ease-in-out infinite alternate;+ }+ @keyframes ambientDrift {+ 0% { transform: translate(0, 0) scale(1); }+ 50% { transform: translate(-3%, 2%) scale(1.04); }+ 100% { transform: translate(2%, -1%) scale(0.98); }+ }+ .particles { position: fixed; inset: 0; z-index: 1; pointer-events: none; }+ .particle { position: absolute; border-radius: 50%; opacity: 0; animation: particleFloat linear infinite; }+ @keyframes particleFloat {+ 0% { transform: translateY(100vh) scale(0); opacity: 0; }+ 10% { opacity: 0.6; }+ 90% { opacity: 0.6; }+ 100% { transform: translateY(-10vh) scale(1); opacity: 0; }+ }+ .center-stage { position: relative; z-index: 10; display: flex; flex-direction: column; align-items: center; gap: 16px; padding: 18px 40px 28px; min-height: 100vh; max-height: 100vh; overflow-y: auto; overflow-x: hidden; scrollbar-width: none; }+ .center-stage::-webkit-scrollbar { display: none; }+ .orbit-system { position: relative; width: 124px; height: 124px; display: flex; align-items: center; justify-content: center; flex: 0 0 auto; }+ .core-shape { position: absolute; width: 68px; height: 68px; z-index: 5; background: url('./power-pages-icon.png') center/contain no-repeat; animation: coreFloat 4s ease-in-out infinite; }+ @keyframes coreFloat { 0%, 100% { transform: translateY(0) scale(1); } 50% { transform: translateY(-3px) scale(1.025); } }+ .core-glow { position: absolute; width: 86px; height: 86px; border-radius: 50%; background: radial-gradient(circle, rgba(167, 139, 219, 0.18) 0%, transparent 70%); z-index: 3; animation: coreGlow 3s ease-in-out infinite alternate; filter: blur(18px); }+ @keyframes coreGlow { 0% { transform: scale(1); opacity: 0.5; } 100% { transform: scale(1.5); opacity: 0.9; } }+ .orbit-ring { position: absolute; border: 1px solid rgba(139, 111, 192, 0.15); border-radius: 50%; animation: ringRotate linear infinite; }+ .orbit-ring:nth-child(3) { width: 90px; height: 90px; animation-duration: 12s; }+ .orbit-ring:nth-child(4) { width: 114px; height: 114px; animation-duration: 18s; animation-direction: reverse; border-color: rgba(90, 155, 213, 0.12); }+ .orbit-ring:nth-child(5) { width: 138px; height: 138px; animation-duration: 25s; border-style: dashed; border-color: rgba(139, 111, 192, 0.08); }+ @keyframes ringRotate { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }+ .orbit-dot { position: absolute; width: 8px; height: 8px; border-radius: 50%; z-index: 6; }+ .orbit-dot:nth-child(6) { background: var(--pp-lavender); box-shadow: 0 2px 4px rgba(45, 27, 78, 0.18); animation: orbitA 12s linear infinite; }+ .orbit-dot:nth-child(7) { background: var(--pp-sky); box-shadow: 0 2px 4px rgba(45, 27, 78, 0.18); width: 6px; height: 6px; animation: orbitB 18s linear infinite reverse; }+ .orbit-dot:nth-child(8) { background: var(--pp-periwinkle); box-shadow: 0 2px 4px rgba(45, 27, 78, 0.18); width: 5px; height: 5px; animation: orbitC 25s linear infinite; }+ @keyframes orbitA { from { transform: rotate(0deg) translateX(45px) rotate(0deg); } to { transform: rotate(360deg) translateX(45px) rotate(-360deg); } }+ @keyframes orbitB { from { transform: rotate(0deg) translateX(57px) rotate(0deg); } to { transform: rotate(360deg) translateX(57px) rotate(-360deg); } }+ @keyframes orbitC { from { transform: rotate(0deg) translateX(69px) rotate(0deg); } to { transform: rotate(360deg) translateX(69px) rotate(-360deg); } }+ .text-content { text-align: center; display: flex; flex-direction: column; align-items: center; gap: 12px; }+ .brand-title { font-family: 'Outfit', sans-serif; font-weight: 300; font-size: 11px; letter-spacing: 3px; text-transform: uppercase; color: var(--pp-violet); opacity: 0; animation: fadeSlideUp 1s ease-out 0.5s forwards; }+ .main-heading { max-width: min(760px, calc(100vw - 48px)); overflow-wrap: anywhere; font-family: 'Outfit', sans-serif; font-weight: 600; font-size: 26px; line-height: 1.25; color: var(--pp-deep-violet); opacity: 0; animation: fadeSlideUp 1s ease-out 0.8s forwards; }+ .status-area { width: min(760px, calc(100vw - 48px)); min-height: 34px; display: flex; flex-direction: column; align-items: center; justify-content: center; position: relative; overflow: hidden; opacity: 0; animation: fadeSlideUp 1s ease-out 1.2s forwards; }+ .status-message { position: absolute; max-width: 100%; font-size: 13px; font-weight: 400; color: var(--pp-text-secondary); display: flex; align-items: center; justify-content: center; gap: 8px; opacity: 0; transform: translateY(20px); transition: all 0.7s cubic-bezier(0.22, 1, 0.36, 1); }+ .status-message.active { opacity: 1; transform: translateY(0); }+ .status-message.exiting { opacity: 0; transform: translateY(-20px); }+ .status-icon { width: 16px; height: 16px; border-radius: 50%; display: flex; align-items: center; justify-content: center; flex-shrink: 0; }+ .status-icon.working { border: 2px solid rgba(139, 111, 192, 0.2); border-top-color: var(--pp-violet); animation: spin 1s linear infinite; }+ @keyframes spin { to { transform: rotate(360deg); } }+ .preview-showcase { position: relative; width: min(900px, calc(100vw - 72px)); height: min(46vh, 500px); max-height: calc(100vh - 390px); min-height: 240px; opacity: 0; animation: fadeSlideUp 1s ease-out 1.35s forwards; flex: 0 0 auto; }+ .preview-frame { width: 100%; height: 100%; overflow: hidden; display: flex; align-items: center; }+ .preview-track { display: flex; width: 100%; height: 100%; transition: transform 0.7s cubic-bezier(0.22, 1, 0.36, 1); will-change: transform; }+ .preview-slide { flex: 0 0 100%; height: 100%; display: flex; align-items: center; justify-content: center; padding: 0 10px; }+ .preview-card { display: inline-flex; max-width: 100%; max-height: 100%; border: 1px solid rgba(139, 111, 192, 0.12); border-radius: 20px; background: var(--pp-surface); box-shadow: 0 2px 12px rgba(139, 111, 192, 0.06), 0 1px 3px rgba(0, 0, 0, 0.04); overflow: hidden; }+ .preview-card img { display: block; max-width: 100%; max-height: min(46vh, 500px); width: auto; height: auto; object-fit: contain; background: var(--pp-surface); }+ .preview-empty { padding: 20px; color: var(--pp-text-muted); font-size: 13px; text-align: center; }+ .preview-nav { position: absolute; top: 50%; z-index: 7; width: 34px; height: 34px; border-radius: 50%; border: 1px solid rgba(139, 111, 192, 0.16); background: rgba(255, 255, 255, 0.88); color: var(--pp-violet); box-shadow: 0 2px 12px rgba(139, 111, 192, 0.10), 0 1px 3px rgba(0, 0, 0, 0.04); cursor: pointer; font-size: 24px; line-height: 30px; display: flex; align-items: center; justify-content: center; transform: translateY(-50%); transition: background 0.2s ease, transform 0.2s ease; }+ .preview-nav:hover { background: var(--pp-surface); transform: translateY(-50%) scale(1.04); }+ .preview-nav:focus-visible { outline: 2px solid var(--pp-sky); outline-offset: 3px; }+ .preview-nav-prev { left: 8px; }+ .preview-nav-next { right: 8px; }+ .preview-showcase.single .preview-nav { display: none; }+ .progress-container { width: min(520px, calc(100vw - 72px)); opacity: 0; animation: fadeSlideUp 1s ease-out 1.5s forwards; display: flex; flex-direction: column; align-items: center; gap: 10px; }+ .progress-track { display: none; width: 100%; height: 3px; background: rgba(139, 111, 192, 0.1); border-radius: 4px; overflow: hidden; position: relative; }+ .progress-fill { height: 100%; width: 40%; border-radius: 4px; background: linear-gradient(90deg, transparent, var(--pp-violet), var(--pp-lavender), var(--pp-sky), transparent); position: absolute; top: 0; left: -40%; animation: infiniteSlide 2s cubic-bezier(0.4, 0, 0.2, 1) infinite; }+ .progress-fill::after { content: ''; position: absolute; right: 10%; top: -3px; width: 8px; height: 8px; border-radius: 50%; background: var(--pp-sky); box-shadow: 0 2px 4px rgba(45, 27, 78, 0.18); opacity: 0.9; }+ @keyframes infiniteSlide { 0% { left: -40%; } 100% { left: 100%; } }+ .progress-track.complete .progress-fill { width: 100%; left: 0; animation: none; background: linear-gradient(90deg, var(--pp-violet), var(--pp-lavender), var(--pp-sky)); transition: all 0.8s ease; }+ .progress-track.complete .progress-fill::after { display: none; }+ .progress-label-text { font-size: 11px; color: var(--pp-text-muted); font-family: 'DM Sans', sans-serif; letter-spacing: 0.3px; }+ .phase-steps { width: min(760px, calc(100vw - 72px)); display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; opacity: 0; animation: fadeSlideUp 1s ease-out 1.65s forwards; }+ .phase-step { position: relative; overflow: hidden; border: 1px solid rgba(139, 111, 192, 0.10); border-radius: 12px; background: rgba(255, 255, 255, 0.72); color: var(--pp-text-muted); font-family: 'Outfit', sans-serif; font-size: 11px; font-weight: 500; padding: 8px 10px; text-align: center; }+ .phase-step.active { border-color: rgba(139, 111, 192, 0.28); color: var(--pp-violet); background: linear-gradient(90deg, rgba(255,255,255,0.88), rgba(139,111,192,0.12), rgba(90,155,213,0.14), rgba(255,255,255,0.88)); background-size: 220% 100%; animation: pillProgress 2s cubic-bezier(0.4, 0, 0.2, 1) infinite; }+ .phase-step.done { color: #229E5C; border-color: rgba(34, 158, 92, 0.20); background: rgba(34, 158, 92, 0.06); }+ .connector-lines { position: fixed; inset: 0; z-index: 2; pointer-events: none; overflow: hidden; }+ .connector { position: absolute; height: 1px; background: linear-gradient(90deg, transparent, rgba(139, 111, 192, 0.12), transparent); animation: connectorSweep 6s ease-in-out infinite; }+ @keyframes connectorSweep { 0%, 100% { transform: translateX(-100%); opacity: 0; } 20% { opacity: 1; } 80% { opacity: 1; } 100% { transform: translateX(100vw); opacity: 0; } }+ .scanline { position: fixed; left: 0; right: 0; height: 1px; background: linear-gradient(90deg, transparent 0%, var(--pp-lavender) 50%, transparent 100%); opacity: 0.06; z-index: 2; animation: scanDrop 8s linear infinite; pointer-events: none; }+ @keyframes scanDrop { 0% { top: -2px; } 100% { top: 100%; } }+ .tip-area { text-align: center; margin-top: 2px; opacity: 0; animation: fadeSlideUp 1s ease-out 3s forwards; }+ .tip-label { font-size: 9px; letter-spacing: 1.8px; text-transform: uppercase; color: var(--pp-text-muted); margin-bottom: 6px; font-family: 'Outfit', sans-serif; }+ .tip-text { font-size: 11px; color: var(--pp-text-muted); max-width: 360px; line-height: 1.45; margin: 0 auto; min-height: 32px; transition: opacity 0.6s ease, transform 0.6s ease; }+ .toast { position: fixed; right: 24px; bottom: 24px; z-index: 100; max-width: 420px; background: var(--pp-surface); border: 1px solid var(--pp-border); border-radius: 16px; padding: 16px 18px; box-shadow: 0 10px 30px rgba(40, 24, 70, 0.14); text-align: left; color: var(--pp-text); animation: toastEnter 0.35s cubic-bezier(0.22, 1, 0.36, 1); }+ .toast[hidden] { display: none; }+ .toast.error .toast-title { color: var(--pp-error); }+ .toast.success .toast-title { color: var(--pp-success); }+ .toast.waiting .toast-title { color: var(--pp-violet); }+ .toast-title { font-weight: 700; margin-bottom: 4px; }+ .toast-message { font-size: 13px; color: var(--pp-text-secondary); }+ @keyframes toastEnter { from { opacity: 0; transform: translateY(12px); } to { opacity: 1; transform: translateY(0); } }+ @keyframes fadeSlideUp { from { opacity: 0; transform: translateY(16px); } to { opacity: 1; transform: translateY(0); } }+ @keyframes pillProgress { 0% { background-position: 140% 0; } 100% { background-position: -80% 0; } }+ @media (prefers-reduced-motion: reduce) { .preview-track { transition: none; } .phase-step.active { animation: none; } }+ @media (max-height: 760px) { .tip-area { display: none; } .preview-showcase { max-height: calc(100vh - 300px); } }+ @media (max-width: 600px) { .main-heading { font-size: 24px; } .preview-showcase { height: 220px; min-height: 180px; max-height: 220px; } .progress-container { width: 260px; } .phase-steps { grid-template-columns: 1fr; width: min(320px, calc(100vw - 48px)); } .tip-area { display: none; } .orbit-system { width: 124px; height: 124px; } }+ </style>+</head>+<body>+ <div class="loading-wrapper">+ <div class="ambient"></div>+ <div class="scanline"></div>+ <div class="particles" id="particles"></div>+ <div class="connector-lines" id="connectors"></div>++ <div class="center-stage" id="centerStage">+ <div class="orbit-system">+ <div class="core-glow"></div>+ <div class="core-shape" id="coreShape"></div>+ <div class="orbit-ring"></div>+ <div class="orbit-ring"></div>+ <div class="orbit-ring"></div>+ <div class="orbit-dot"></div>+ <div class="orbit-dot"></div>+ <div class="orbit-dot"></div>+ </div>++ <div class="text-content">+ <div class="brand-title">Power Pages</div>+ <div class="main-heading" id="mainHeading">Setting up __TEMPLATE_NAME__ template</div>++ <div class="status-area" id="statusArea" role="status" aria-live="polite"></div>++ <div class="preview-showcase" id="previewShowcase" aria-label="Template preview slideshow">+ <button class="preview-nav preview-nav-prev" id="previewPrev" type="button" aria-label="Previous template preview">‹</button>+ <div class="preview-frame" id="previewFrame"></div>+ <button class="preview-nav preview-nav-next" id="previewNext" type="button" aria-label="Next template preview">›</button>+ </div>++ <div class="progress-container">+ <div class="progress-track" id="progressTrack">+ <div class="progress-fill" id="progressFill"></div>+ </div>+ <span class="progress-label-text" id="progressLabel">Starting template setup...</span>+ </div>+ <div class="phase-steps" aria-label="Template setup phases">+ <div class="phase-step active" id="phaseSolution">__SOLUTION_INSTALLING_LABEL__</div>+ <div class="phase-step" id="phaseSite">Creating site</div>+ <div class="phase-step" id="phaseSeed">Seeding data</div>+ <div class="phase-step" id="phaseActivation">Activating site</div>+ </div>+ </div>++ <div class="tip-area">+ <div class="tip-label">Did you know</div>+ <div class="tip-text" id="tipText"></div>+ </div>+ </div>+ </div>++ <div class="toast" id="toast" role="alert" hidden>+ <div class="toast-title" id="toastTitle"></div>+ <div class="toast-message" id="toastMessage"></div>+ </div>++ <script>+ const PREVIEWS = __JSON_PREVIEW_IMAGES__;+ const STATUS_URL = __JSON_STATUS_URL__;+ const TEMPLATE_NAME = __JSON_TEMPLATE_NAME__;+ const SOLUTION_INSTALLING_LABEL = __JSON_SOLUTION_INSTALLING_LABEL__;+ const SOLUTION_INSTALLED_LABEL = __JSON_SOLUTION_INSTALLED_LABEL__;+ const SOLUTION_NOUN = __JSON_SOLUTION_NOUN__;++ (function () {+ var particlesEl = document.getElementById('particles');+ var connectorsEl = document.getElementById('connectors');+ var statusArea = document.getElementById('statusArea');+ var mainHeading = document.getElementById('mainHeading');+ var progressLabel = document.getElementById('progressLabel');+ var progressTrack = document.getElementById('progressTrack');+ var progressFill = document.getElementById('progressFill');+ var tipTextEl = document.getElementById('tipText');+ var previewShowcase = document.getElementById('previewShowcase');+ var previewFrame = document.getElementById('previewFrame');+ var previewPrev = document.getElementById('previewPrev');+ var previewNext = document.getElementById('previewNext');+ var toast = document.getElementById('toast');+ var toastTitle = document.getElementById('toastTitle');+ var toastMessage = document.getElementById('toastMessage');+ var phaseSolution = document.getElementById('phaseSolution');+ var phaseSite = document.getElementById('phaseSite');+ var phaseSeed = document.getElementById('phaseSeed');+ var phaseActivation = document.getElementById('phaseActivation');+ var currentStatusIndex = 0;+ var previewIndex = 0;+ var previewPaused = false;+ var toastShown = false;+ var toastKind = '';+ var redirectScheduled = false;+ var latestLiveMessage = '';++ function createParticle() {+ if (!particlesEl) return;+ var p = document.createElement('div');+ p.classList.add('particle');+ var size = Math.random() * 3 + 1;+ var colors = ['rgba(167,139,219,0.5)', 'rgba(128,136,217,0.5)', 'rgba(90,155,213,0.5)', 'rgba(139,111,192,0.5)'];+ var color = colors[Math.floor(Math.random() * colors.length)];+ p.style.cssText = 'width:' + size + 'px;height:' + size + 'px;left:' + (Math.random() * 100) + '%;background:' + color + ';box-shadow:0 0 ' + (size * 2) + 'px ' + color + ';animation-duration:' + (Math.random() * 15 + 12) + 's;animation-delay:' + (Math.random() * 10) + 's;';+ particlesEl.appendChild(p);+ setTimeout(function () { p.remove(); }, 30000);+ }++ function createConnector() {+ if (!connectorsEl) return;+ var c = document.createElement('div');+ c.classList.add('connector');+ c.style.cssText = 'top:' + (Math.random() * 100) + '%;width:' + (Math.random() * 300 + 200) + 'px;animation-duration:' + (Math.random() * 4 + 4) + 's;animation-delay:' + (Math.random() * 6) + 's;';+ connectorsEl.appendChild(c);+ setTimeout(function () { c.remove(); }, 12000);+ }++ function renderStatusMessage(text) {+ if (!statusArea) return;+ var existing = statusArea.querySelector('.status-message');+ var existingText = existing && existing.querySelector('span');+ if (existingText && existingText.textContent === text && !existing.classList.contains('exiting')) return;+ if (existing) {+ existing.classList.remove('active');+ existing.classList.add('exiting');+ setTimeout(function () { existing.remove(); }, 700);+ }+ var msg = document.createElement('div');+ msg.classList.add('status-message');+ var icon = document.createElement('div');+ icon.classList.add('status-icon', 'working');+ msg.appendChild(icon);+ var textEl = document.createElement('span');+ textEl.textContent = text;+ msg.appendChild(textEl);+ statusArea.appendChild(msg);+ requestAnimationFrame(function () { requestAnimationFrame(function () { msg.classList.add('active'); }); });+ }++ function updatePhaseLabel(text) {+ if (progressLabel) progressLabel.textContent = text;+ }++ function phaseForStatus(status) {+ if (status && (status.phase === 'siteAndSeed' || status.phase === 'creatingAndSeeding')) return 'siteAndSeed';+ if (status && (status.phase === 'site' || status.phase === 'cloning' || status.phase === 'uploading')) return 'site';+ if (status && (status.phase === 'seed' || status.phase === 'seeding')) return 'seed';+ if (status && (status.phase === 'activation' || status.phase === 'activating')) return 'activation';+ if (status && status.state === 'succeeded' && status.redirectUrl) return 'done';+ if (status && status.state === 'succeeded') return 'solutionDone';+ return 'solution';+ }++ function renderPhase(phase) {+ if (!phaseSolution || !phaseSite || !phaseSeed || !phaseActivation) return;+ phaseSolution.className = 'phase-step';+ phaseSite.className = 'phase-step';+ phaseSeed.className = 'phase-step';+ phaseActivation.className = 'phase-step';+ phaseSolution.textContent = SOLUTION_INSTALLING_LABEL;+ phaseSite.textContent = 'Creating site';+ phaseSeed.textContent = 'Seeding data';+ phaseActivation.textContent = 'Activating site';+ if (phase === 'siteAndSeed') {+ phaseSolution.classList.add('done');+ phaseSolution.textContent = SOLUTION_INSTALLED_LABEL;+ phaseSite.classList.add('active');+ phaseSeed.classList.add('active');+ if (mainHeading) mainHeading.textContent = 'Creating ' + TEMPLATE_NAME + ' template site and seeding data';+ return;+ }+ if (phase === 'site') {+ phaseSolution.classList.add('done');+ phaseSolution.textContent = SOLUTION_INSTALLED_LABEL;+ phaseSite.classList.add('active');+ if (mainHeading) mainHeading.textContent = 'Creating ' + TEMPLATE_NAME + ' template site';+ return;+ }+ if (phase === 'seed') {+ phaseSolution.classList.add('done');+ phaseSolution.textContent = SOLUTION_INSTALLED_LABEL;+ phaseSite.classList.add('done');+ phaseSite.textContent = 'Created site';+ phaseSeed.classList.add('active');+ if (mainHeading) mainHeading.textContent = 'Seeding ' + TEMPLATE_NAME + ' template data';+ return;+ }+ if (phase === 'solutionDone') {+ phaseSolution.classList.add('done');+ phaseSolution.textContent = SOLUTION_INSTALLED_LABEL;+ if (mainHeading) mainHeading.textContent = 'Template ' + SOLUTION_NOUN + (SOLUTION_NOUN === 'solution' ? ' is' : ' are') + ' installed';+ return;+ }+ if (phase === 'activation') {+ phaseSolution.classList.add('done');+ phaseSolution.textContent = SOLUTION_INSTALLED_LABEL;+ phaseSite.classList.add('done');+ phaseSite.textContent = 'Created site';+ phaseSeed.classList.add('done');+ phaseSeed.textContent = 'Seeded data';+ phaseActivation.classList.add('active');+ if (mainHeading) mainHeading.textContent = 'Activating ' + TEMPLATE_NAME + ' template site';+ return;+ }+ if (phase === 'done') {+ phaseSolution.classList.add('done');+ phaseSolution.textContent = SOLUTION_INSTALLED_LABEL;+ phaseSite.classList.add('done');+ phaseSite.textContent = 'Created site';+ phaseSeed.classList.add('done');+ phaseSeed.textContent = 'Seeded data';+ phaseActivation.classList.add('done');+ phaseActivation.textContent = 'Activated site';+ if (mainHeading) mainHeading.textContent = TEMPLATE_NAME + ' template is ready';+ return;+ }+ phaseSolution.classList.add('active');+ if (mainHeading) mainHeading.textContent = 'Installing ' + TEMPLATE_NAME + ' ' + SOLUTION_NOUN;+ }++ function showStatus(index) {+ var status = statuses[index];+ renderStatusMessage(latestLiveMessage || status.text);+ if (latestLiveMessage) {+ updatePhaseLabel(latestLiveMessage);+ return;+ }+ var phaseIndex = Math.min(Math.floor((index / statuses.length) * phaseLabels.length), phaseLabels.length - 1);+ updatePhaseLabel(phaseLabels[phaseIndex]);+ }++ function advanceStatus() {+ showStatus(currentStatusIndex % statuses.length);+ var duration = statuses[currentStatusIndex % statuses.length].duration;+ setTimeout(function () {+ currentStatusIndex++;+ advanceStatus();+ }, duration);+ }++ function buildPreviewCarousel() {+ if (!previewFrame) return;+ if (!PREVIEWS.length) {+ previewShowcase.classList.add('single');+ previewFrame.innerHTML = '<div class="preview-empty">No preview images are available for this template.</div>';+ return;+ }+ previewShowcase.classList.toggle('single', PREVIEWS.length < 2);+ var track = document.createElement('div');+ track.className = 'preview-track';+ PREVIEWS.forEach(function (src, index) {+ var slide = document.createElement('div');+ slide.className = 'preview-slide';+ var card = document.createElement('div');+ card.className = 'preview-card';+ var img = document.createElement('img');+ img.src = src;+ img.alt = 'Template preview ' + (index + 1);+ card.appendChild(img);+ slide.appendChild(card);+ track.appendChild(slide);+ });+ previewFrame.replaceChildren(track);+ }++ function setPreview(index) {+ var track = previewFrame && previewFrame.querySelector('.preview-track');+ if (!track) return;+ previewIndex = (index + PREVIEWS.length) % PREVIEWS.length;+ track.style.transform = 'translateX(-' + (previewIndex * 100) + '%)';+ }++ function showNextPreview() {+ setPreview(previewIndex + 1);+ }++ function showPreviousPreview() {+ setPreview(previewIndex - 1);+ }++ function showToast(kind, title, message) {+ toastShown = true;+ toastKind = kind;+ toast.className = 'toast ' + kind;+ toastTitle.textContent = title;+ toastMessage.textContent = message;+ toast.hidden = false;+ }++ function hideToast(kind) {+ if (!toastShown || (kind && toastKind !== kind)) return;+ toast.hidden = true;+ toast.className = 'toast';+ toastShown = false;+ toastKind = '';+ }++ function scheduleRedirect(url) {+ if (redirectScheduled || !/^https?:\/\//i.test(String(url || ''))) return;+ redirectScheduled = true;+ setTimeout(function () { window.location.assign(url); }, 1500);+ }++ async function pollStatus() {+ try {+ var res = await fetch(STATUS_URL + '?t=' + Date.now(), { cache: 'no-store' });+ if (!res.ok) return;+ var status = await res.json();+ renderPhase(phaseForStatus(status));+ if (status.message) {+ latestLiveMessage = status.message;+ renderStatusMessage(status.message);+ updatePhaseLabel(status.message);+ }+ if (status.awaitingInput) {+ showToast(+ 'waiting',+ 'Waiting for your input',+ status.inputPrompt || 'Check the agent terminal to respond.'+ );+ } else {+ hideToast('waiting');+ }+ if (status.state === 'failed' || status.state === 'canceled' || status.state === 'timeout') {+ showToast('error', 'Template setup needs attention', 'Check the agent terminal for details.');+ }+ if (status.state === 'succeeded' && status.redirectUrl) {+ progressTrack.classList.add('complete');+ showToast('success', 'Template site is ready', 'Opening the live site in this tab.');+ }+ if (status.redirectUrl) {+ scheduleRedirect(status.redirectUrl);+ }+ } catch {}+ }++ var statuses = [+ { text: 'Starting template setup', duration: 8000 },+ { text: 'Preparing supporting artifacts', duration: 10000 },+ { text: 'Creating the code site', duration: 12000 },+ { text: 'Applying sample data', duration: 10000 },+ { text: 'Preparing activation', duration: 12000 }+ ];++ var phaseLabels = [+ 'Starting template setup...', 'Preparing artifacts...', 'Creating site...',+ 'Applying sample data...', 'Preparing activation...'+ ];++ var tips = [+ 'Power Pages sites are built on Microsoft Dataverse, giving you enterprise-level data capabilities from day one.',+ 'Your site automatically includes responsive design - it looks great on phones, tablets, and desktops.',+ 'With role-based security, you can control exactly who sees what on your site.',+ 'Power Pages integrates seamlessly with Power Automate, Power BI, and the entire Microsoft ecosystem.',+ 'You can extend your site with custom code, and JavaScript for unlimited flexibility.',+ 'Built-in content delivery networks ensure your pages load fast for users worldwide.',+ 'Multi-language support lets you reach audiences across the globe with localized content.'+ ];++ var tipIndex = 0;+ function showTip() {+ if (!tipTextEl) return;+ tipTextEl.style.opacity = '0';+ tipTextEl.style.transform = 'translateY(8px)';+ setTimeout(function () {+ tipTextEl.textContent = tips[tipIndex % tips.length];+ tipTextEl.style.opacity = '1';+ tipTextEl.style.transform = 'translateY(0)';+ tipIndex++;+ }, 500);+ }++ for (var i = 0; i < 30; i++) { (function (n) { setTimeout(createParticle, n * 200); })(i); }+ setInterval(createParticle, 800);+ for (var j = 0; j < 8; j++) { (function (n) { setTimeout(createConnector, n * 1500); })(j); }+ setInterval(createConnector, 2000);++ setTimeout(advanceStatus, 2000);+ buildPreviewCarousel();+ setPreview(0);+ if (previewShowcase) {+ previewShowcase.addEventListener('mouseenter', function () { previewPaused = true; });+ previewShowcase.addEventListener('mouseleave', function () { previewPaused = false; });+ previewShowcase.addEventListener('focusin', function () { previewPaused = true; });+ previewShowcase.addEventListener('focusout', function () { previewPaused = false; });+ }+ if (previewPrev) previewPrev.addEventListener('click', showPreviousPreview);+ if (previewNext) previewNext.addEventListener('click', showNextPreview);+ setInterval(function () {+ if (!previewPaused) showNextPreview();+ }, 5000);+ setTimeout(showTip, 3500);+ setInterval(showTip, 12000);+ pollStatus();+ setInterval(pollStatus, 1500);+ })();+ </script>+</body>+</html>diff --git a/plugins/power-pages/skills/import-solution/SKILL.md b/plugins/power-pages/skills/import-solution/SKILL.mdindex 73a224d91..9e4c1e69b 100644--- a/plugins/power-pages/skills/import-solution/SKILL.md+++ b/plugins/power-pages/skills/import-solution/SKILL.md@@ -284,7 +284,6 @@ Run `scripts/poll-async-operation.js`:node "${PLUGIN_ROOT}/scripts/poll-async-operation.js" \--asyncJobId "{AsyncOperationId}" \--envUrl "{envUrl}" \- --token "{token}" \--intervalMs 8000 \--maxAttempts 75```