A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
model-apps 2.10.0: remove the connectors flag, bind destructive approvals, fix retest findings, refresh the SDK (#630)
Akshay Malooc97753299937
diff --git a/.github/workflows/model-apps-script-tests.yml b/.github/workflows/model-apps-script-tests.ymlindex b2673a0a3..45d4df1ff 100644--- a/.github/workflows/model-apps-script-tests.yml+++ b/.github/workflows/model-apps-script-tests.yml@@ -21,12 +21,30 @@ on:# The eval harness lives at the repo root but is owned by this plugin, so# an eval-only change must still trigger the eval job below.- "evals/model-apps/**"+ # The plugin ships physical copies of the shared telemetry library and the shared skill+ # workflows, and scripts/tests/telemetry-lib-copy.test.js fails when a copy drifts from its+ # source. That guard is only useful if a change to the SOURCE runs it too.+ - "shared/telemetry/**"+ - "shared/skills/**"- ".github/workflows/model-apps-script-tests.yml"+# The jobs only read the checkout; the token needs nothing more, whatever the repository default is.+permissions:+ contents: read++# A new push to the same PR supersedes the run in flight: without this, all seven jobs of the old run+# kept going to completion for a result nobody reads.+concurrency:+ group: model-apps-script-tests-${{ github.event.pull_request.number || github.ref }}+ cancel-in-progress: true+jobs:test-model-apps-scripts:name: test-model-apps-scripts (${{ matrix.os }}, node ${{ matrix.node }})runs-on: ${{ matrix.os }}+ # The suite takes about a minute on every runner. A test that hangs (a child process waiting on+ # stdin, say) would otherwise hold the job for the six-hour default.+ timeout-minutes: 20# Defense-in-depth: opt this CI job out of telemetry transmission so a test# that forgets to isolate emission can never POST to a real collector. The# plugin's committed ikey.json currently ships `disabled: true`, but that is@@ -70,6 +88,7 @@ jobs:test-model-apps-evals:name: test-model-apps-evalsruns-on: ubuntu-latest+ timeout-minutes: 10env:POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: "1"steps:diff --git a/AGENTS.md b/AGENTS.mdindex c2a4ce52f..81b6de5e9 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -93,9 +93,11 @@ No root-level build, lint, or test commands exist. Build/test tooling lives insiBoth are repo-wide and enforce metadata/marketplace rules, not behavior.**Every test workflow is path-filtered to a single plugin** (`power-pages` → `plugins/power-pages/**`;-`model-apps` → `plugins/model-apps/**` + `evals/model-apps/**`). This is deliberate — a PR should not-spend CI on a plugin it never touched — but it has a corollary: *a green PR does not mean the repo is-green*, only that the paths you touched are.+`model-apps` → `plugins/model-apps/**` + `evals/model-apps/**` + the `shared/` sources it bundles).+This is deliberate — a PR should not spend CI on a plugin it never touched — but it has a corollary:+*a green PR does not mean the repo is green*, only that the paths you touched are. A plugin that ships+copies of `shared/` sources may list those sources too, so a change to one runs that plugin's drift+test in the PR that made it rather than in the plugin's next, unrelated PR.**A test suite with no workflow silently never runs.** When you add tests to a plugin, add or extendthat plugin's own path-filtered workflow in the same PR; do not widen another plugin's filter to@@ -148,7 +150,7 @@ Per-plugin iKey/collector routing is pluggable via a `resolver.js` placed next t### CI must opt out of telemetry transmission-An adopting plugin's committed `ikey.json` ships **enabled** (`disabled: false`) with a real production instrumentation key, so any process that runs a telemetry-emitting hook or script **without isolating emission** will POST a real (but fake-in-content) event to the production collector. CI runs are not real usage, and such events pollute the production telemetry stream.+A transmitting adopter's committed `ikey.json` ships **enabled** (`disabled: false`) with a real production instrumentation key, so any process that runs a telemetry-emitting hook or script **without isolating emission** will POST a real (but fake-in-content) event to the production collector. CI runs are not real usage, and such events pollute the production telemetry stream. An adopter that still ships `disabled: true` (model-apps today) sets the opt-out too, so enabling it later cannot turn its CI into a leak.**Therefore: every GitHub Actions job that runs the test suite — or any step that could execute a telemetry-emitting hook/script for an adopting plugin — MUST set the plugin's opt-out env var at the job (or workflow) level.** For `power-pages`:@@ -163,7 +165,7 @@ jobs:This opt-out suppresses **transmission only** (the local diagnostic mirror is still written), so it is safe and has no effect on what the job actually tests. Tests that need to assert that emission *happens* clear the var in their own spawned-process env and route the event to a local `POWER_PLATFORM_SKILLS_FAKE_HTTPS` probe instead of the real collector — so the job-level opt-out never breaks them. Existing reference: `.github/workflows/power-pages-script-tests.yml`. When you add a new such workflow (or a new emitting step to an existing one), add this env var in the same change; treat a CI job that runs the tests without it as a production-telemetry leak.-Current adopters: `power-pages`. Others adopt on demand.+Current adopters: `power-pages` and `mobile-apps` (transmitting), and `model-apps` (bundled, with its committed `ikey.json` still `disabled: true`). Others adopt on demand. power-pages and model-apps each keep a `scripts/tests/telemetry-lib-copy.test.js` that fails when the bundled copy differs from `shared/telemetry/lib`. model-apps also lists `shared/telemetry/**` in its test workflow's path filter, so an edit to the source alone still runs that test.## Legacy Marketplace Compatibilitydiff --git a/evals/model-apps/genpage/EVAL_GUIDE.md b/evals/model-apps/genpage/EVAL_GUIDE.mdindex 2cf4d4ee2..78d48353b 100644--- a/evals/model-apps/genpage/EVAL_GUIDE.md+++ b/evals/model-apps/genpage/EVAL_GUIDE.md@@ -221,6 +221,10 @@ node run-layer-1.js --tier full # 9 full evalsnode run-layer-1.js --tier stress # 3 stress evals```+A tier runs the fixtures that exist for its evals. The committed fixtures cover only some evals (none+of the stress ones), so a tier with no captured fixture reports `no fixtures matched the filter` and+exits 2; point `--fixtures <dir>` at your own captures to run it.+### Filter by eval id (debugging)```bashdiff --git a/evals/model-apps/genpage/lib/assertions-layer-1.js b/evals/model-apps/genpage/lib/assertions-layer-1.jsindex ebee6178a..ff413f700 100644--- a/evals/model-apps/genpage/lib/assertions-layer-1.js+++ b/evals/model-apps/genpage/lib/assertions-layer-1.js@@ -1091,8 +1091,8 @@ PHASE_EXPECTATIONS.set(// Eval 17: mock-data page — regression guard confirming the planner does NOT run// connector discovery for a page with no connector data source, leaving-// ## Connector Bindings as the exact sentinel. (Connector authoring is GA and-// always available, so the thing worth pinning is that it stays OFF THE PATH when+// ## Connector Bindings as the exact sentinel. (Connector authoring has no feature+// flag and is always available, so the thing worth pinning is that it stays OFF THE PATH when// the maker asked for mock data — otherwise every mock page pays for a `pac// connection list` round trip and risks inventing a binding nobody asked for.)PHASE_EXPECTATIONS.set(diff --git a/evals/model-apps/lib/eval-args.js b/evals/model-apps/lib/eval-args.jsindex 6161c927a..6d64a0206 100644--- a/evals/model-apps/lib/eval-args.js+++ b/evals/model-apps/lib/eval-args.js@@ -11,7 +11,7 @@// with each runner./** Tiers an eval fixture can declare. A typo must be rejected here rather than matching nothing. */-const TIERS = ['smoke', 'full'];+const TIERS = ['smoke', 'full', 'stress'];/*** @param {string[]} argv - process.argv.slice(2)diff --git a/evals/model-apps/tests/eval-args.test.js b/evals/model-apps/tests/eval-args.test.jsindex 154155af5..88129cd36 100644--- a/evals/model-apps/tests/eval-args.test.js+++ b/evals/model-apps/tests/eval-args.test.js@@ -61,3 +61,19 @@ test('eval-args: --tier accepts only a known tier and names the choices', () =>for (const t of TIERS) assert.match(errors[0], new RegExp(t), `the error lists ${t}`);for (const t of TIERS) assert.equal(parse(['--tier', t]).args.tier, t);});++test('eval-args: every tier an eval definition declares can be selected with --tier', () => {+ // The genpage suite declares `stress` evals, but the list here once held only smoke and full, so+ // the documented `--tier stress` exited 2 and those evals could only be run one by one.+ const fs = require('node:fs');+ const path = require('node:path');+ const declared = new Set();+ for (const file of ['genpage/evals.json', 'app-builder/evals.json']) {+ const full = path.join(__dirname, '..', file);+ if (!fs.existsSync(full)) continue;+ const parsed = JSON.parse(fs.readFileSync(full, 'utf8'));+ for (const ev of Array.isArray(parsed) ? parsed : (parsed.evals || [])) if (ev.tier) declared.add(ev.tier);+ }+ assert.ok(declared.has('stress'), 'the genpage suite declares stress evals');+ for (const t of declared) assert.equal(parse(['--tier', t]).args.tier, t, `--tier ${t} must be accepted`);+});\ No newline at end of filediff --git a/plugins/mobile-apps/scripts/lib/telemetry/lib/agent-info.js b/plugins/mobile-apps/scripts/lib/telemetry/lib/agent-info.jsindex 3904f5bc1..aa6ec840b 100644--- a/plugins/mobile-apps/scripts/lib/telemetry/lib/agent-info.js+++ b/plugins/mobile-apps/scripts/lib/telemetry/lib/agent-info.js@@ -2,11 +2,12 @@const fs = require("node:fs");const path = require("node:path");-const { execFileSync } = require("node:child_process");+const { runNative } = require("./native-exec");let pacCliVersionCache;-// Reads the PAC CLI version once per process via `pac --version`. Best-effort+// Reads the PAC CLI version once per process via `pac --version`, started by+// absolute path from PATH (see native-exec.js). Best-effort// and fail-closed: missing executable, timeout, or unparseable output all// resolve to "".//@@ -20,7 +21,7 @@ function readPacCliVersion(opts = {}) {pacCliVersionCache = "";return "";}- const exec = typeof opts._exec === "function" ? opts._exec : execFileSync;+ const exec = typeof opts._exec === "function" ? opts._exec : runNative;let stdout = "";try {stdout = exec("pac", ["--version"], {diff --git a/plugins/mobile-apps/scripts/lib/telemetry/lib/native-exec.js b/plugins/mobile-apps/scripts/lib/telemetry/lib/native-exec.jsnew file mode 100644index 000000000..0b11f96e6--- /dev/null+++ b/plugins/mobile-apps/scripts/lib/telemetry/lib/native-exec.js@@ -0,0 +1,100 @@+"use strict";++const fs = require("node:fs");+const path = require("node:path");+const { execFileSync } = require("node:child_process");++// Starts a native command-line tool (pac) by absolute path, never by bare name.+//+// The telemetry hooks run in the user's project folder. Given a bare name,+// Node 20 on Windows looks for the executable in the working directory before+// PATH (measured: a `pac.exe` in the working directory ran; Node 22 no longer+// looks there), so a `pac.exe` left in a project would run instead of the real+// one. Resolving the name here, against absolute PATH entries only, gives the+// same answer on every Node version and platform.+//+// Only native executables are considered. These calls run without a shell, and+// Windows cannot start a .cmd or .bat that way, so a pac.cmd install is not+// found, as it was not before either.++function isFile(p) {+ try {+ return fs.statSync(p).isFile();+ } catch {+ return false;+ }+}++// A candidate the OS would actually start: a regular file and, off Windows,+// one the user may execute. Node's own lookup skips a non-executable `pac`+// earlier on PATH and keeps searching, so this does too.+function isRunnable(p, platform) {+ if (!isFile(p)) return false;+ if (platform === "win32") return true;+ try {+ fs.accessSync(p, fs.constants.X_OK);+ return true;+ } catch {+ return false;+ }+}++// Windows variable names are case-insensitive. When an env object carries+// several spellings (a copied `Path` plus an added `PATH`), Node passes the+// child the lexicographically first one, so read that same one.+function envValue(env, name, platform) {+ if (platform !== "win32") return env[name];+ const key = Object.keys(env)+ .filter((k) => k.toUpperCase() === name.toUpperCase())+ .sort()[0];+ return key === undefined ? undefined : env[key];+}++/**+ * Absolute path of a native executable found on PATH, or null. Relative PATH+ * entries (an empty entry means "the current directory" on POSIX) are skipped.+ * On Windows `.com` then `.exe` is tried whatever PATHEXT says, as Node's own+ * shell-free lookup does.+ */+function resolveNative(+ name,+ { platform = process.platform, env = process.env, exists = (p) => isRunnable(p, platform) } = {}+) {+ const win = platform === "win32";+ const p = win ? path.win32 : path.posix;+ const dirs = String(envValue(env, "PATH", platform) || "")+ .split(win ? ";" : ":")+ .map((d) => d.trim().replace(/^"(.*)"$/, "$1"))+ .filter((d) => d && p.isAbsolute(d));+ const exts = win ? [".com", ".exe"] : [""];+ for (const dir of dirs) {+ for (const ext of exts) {+ const candidate = p.join(dir, name + ext);+ if (exists(candidate)) return candidate;+ }+ }+ return null;+}++/**+ * execFileSync-shaped: returns stdout, and throws when the tool is not on PATH+ * (code ENOENT) or the run fails (with err.stdout attached, as execFileSync+ * does). Callers treat any throw as "no data".+ */+function runNative(name, args, options = {}, deps = {}) {+ const file = resolveNative(name, deps);+ if (!file) {+ const err = new Error(`${name} was not found on PATH`);+ err.code = "ENOENT";+ throw err;+ }+ return execFileSync(file, args, {+ encoding: options.encoding,+ timeout: options.timeout,+ stdio: options.stdio,+ windowsHide: true,+ shell: false,+ });+}++module.exports = { resolveNative, runNative };diff --git a/plugins/mobile-apps/scripts/lib/telemetry/lib/pac-auth.js b/plugins/mobile-apps/scripts/lib/telemetry/lib/pac-auth.jsindex 71b268b59..0eb4ec6a3 100644--- a/plugins/mobile-apps/scripts/lib/telemetry/lib/pac-auth.js+++ b/plugins/mobile-apps/scripts/lib/telemetry/lib/pac-auth.js@@ -1,11 +1,13 @@"use strict";-const { execFileSync } = require("node:child_process");+const { runNative } = require("./native-exec");-// Reads PAC CLI auth state by shelling out to `pac auth who` and parsing the+// Reads PAC CLI auth state by running `pac auth who` and parsing the// banner output. Matches the convention used by// plugins/power-pages/scripts/lib/validation-helpers.js (getPacAuthInfo /// getEnvironmentUrl) so telemetry stays consistent with the rest of the repo.+// pac is started by absolute path from PATH, never by bare name (see+// native-exec.js).//// PAC's JSON profile files are an internal/undocumented format that varies// across versions. The banner output is stable and is what other code paths@@ -40,7 +42,7 @@ function readPacAuth(opts = {}) {cache = null;return null;}- const exec = typeof opts._exec === "function" ? opts._exec : execFileSync;+ const exec = typeof opts._exec === "function" ? opts._exec : runNative;let output;try {output = exec("pac", ["auth", "who"], {diff --git a/plugins/model-apps/.claude-plugin/plugin.json b/plugins/model-apps/.claude-plugin/plugin.jsonindex 8c24c0350..352459352 100644--- a/plugins/model-apps/.claude-plugin/plugin.json+++ b/plugins/model-apps/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "model-apps",- "version": "2.9.0",+ "version": "2.10.0","description": "Build model-driven Power Apps end to end: /app-builder authors whole apps (tables, relationships, forms, views, charts, security roles, app + sitemap) from a natural-language intent, and /genpage builds generative pages with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI > 2.10.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.","author": {"name": "Microsoft",diff --git a/plugins/model-apps/.plugin/plugin.json b/plugins/model-apps/.plugin/plugin.jsonindex 8c24c0350..352459352 100644--- a/plugins/model-apps/.plugin/plugin.json+++ b/plugins/model-apps/.plugin/plugin.json@@ -1,6 +1,6 @@{"name": "model-apps",- "version": "2.9.0",+ "version": "2.10.0","description": "Build model-driven Power Apps end to end: /app-builder authors whole apps (tables, relationships, forms, views, charts, security roles, app + sitemap) from a natural-language intent, and /genpage builds generative pages with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI > 2.10.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.","author": {"name": "Microsoft",diff --git a/plugins/model-apps/AGENTS.md b/plugins/model-apps/AGENTS.mdindex 2a5d09232..1526a34d8 100644--- a/plugins/model-apps/AGENTS.md+++ b/plugins/model-apps/AGENTS.md@@ -24,10 +24,11 @@ neither leaves state the other depends on**. Keep it that way — shared **agentfine, a skill-to-skill call is not, and neither may write a file the other treats as authoritative(this is why `write-page-plan.js` emits `app-builder-page-plan.md`, not `genpage-plan.md`).-Plus **`/report-issue`** to file bugs against this repo. All Dataverse mutation flows through the-shared, vendored SDK (`scripts/vendor/cds-maker-sdk.cjs`) — see `## Building & Testing`.+Plus **`/report-issue`** to file bugs against this repo. Dataverse mutation flows through the+shared, vendored SDK (`scripts/vendor/cds-maker-sdk.cjs`) — see `## Building & Testing` — except for+the few surfaces it does not model, which use `dataverseRequest()` (see `## Dataverse Access From+Scripts`).-**Requirements:****Requirements:**- **PAC CLI > 2.10.0** — for app and generative-page deploy operations (incl. the genpage `upload` connector/Custom API flags)- **Azure CLI (`az`)** — Dataverse Web API auth (SDK + entity builder); must be logged in with the@@ -139,7 +140,26 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo`updateElement('/siteMap')`, a dashboard tile is `addElement('/components')`. Form reconcile adds thespec's fields and — for an author-controlled **explicit** layout — prunes fields it dropped (never theprimary) via `findFieldCellPointer`+`removeElement`, keyed by a declared semantic identity so a rebuild- never duplicates a control. Every push routes through `requireSuccessfulPush` (a 412 version conflict+ never duplicates a control. A row that a pruned or moved cell leaves holding nothing is removed too+ (`strandedRows` in `lib/form-occupancy.js`, shared by the prune pass and both move paths). A row that+ a row-spanning cell above still reserves is kept, and so is a row that was already empty. On `build --apply`, the destructive preflight writes `.maker-workspace/destructive-approval.json`+ when it refuses form-field or sitemap removals, and also when an approved destructive run starts so+ retries and later failures stay bound to that gate-time list — an empty list included, when the run+ includes the removal phases. A later `--allow-destructive` run may+ remove only that recorded set; the record is consumed only after a successful run that included both+ removal phases (`forms` and `app-shell`) and kept no field, and is otherwise kept on failure, partial+ runs, changed-only runs, or when the fence kept a field. An approved run consumes or rewrites only a record it+ found at its start or wrote itself (each record carries its run id, compared by content fingerprint),+ checked and changed under the workspace lease the apply snapshot uses, so two builds sharing a+ workspace cannot consume each other's record. A refusal still replaces the record with the list it+ just showed, because that is the list the maker is looking at, and a halt naming new removals refreshes+ it with the full current list (the halt shows only the new ones). An approved+ run halts before any write if the record+ changed after it was read, or if the lease stays held. The gate fails closed if the record is+ unreadable or if discovery fails while a record exists, because live removals cannot be compared with+ the approved list. If live state contains a new removal, the build halts, lists only that new removal,+ refreshes the record, and the engine keeps any field or sitemap target that appears during the run+ rather than pruning beyond the preflight-approved set. Every push routes through `requireSuccessfulPush` (a 412 version conflicthalts the build for a fresh download instead of silently dropping the edit) — so new, existing, and mixedenvs all work. The data model is **complete** (all column types, global choices, status reasons,alternate keys, N:N). It also builds **quick-create/quick-view forms** (`formType`) with **quick-view@@ -479,8 +499,9 @@ the pipeline and delegates each script's **behavioral spec** to the entries beloagainst what actually deployed; exits non-zero and lists anything missing, catching silent partialbuilds. Checks **existence** (entities/columns/views/charts/forms + sitemap subareas + icons + pages byid) AND, best-effort, **content** so an *unapplied edit* is caught (not just a missing artifact): a- view's **column set** (parsed from `layoutxml` — the additive `reconcileView` won't drop a removed spec- column, so this flags it), plus **relationship** and **command-bar existence** (previously unchecked).+ view's **column set** (parsed from `layoutxml`; every spec column must be deployed — an extra deployed+ column passes by design, so a column REMOVED from the spec, which the additive `reconcileView` leaves+ in place, is not flagged), plus **relationship** and **command-bar existence** (previously unchecked).Content checks are additive + reader-gated (they only fire when the reader supplies `layoutxml` /`entityRelationships` / `commandBar`), so existence-only callers are unaffected. **Dashboards** arechecked too (#586): each declared dashboard must exist. A name can also match another app's@@ -609,7 +630,7 @@ AGENTS.md ← Plugin guidance for AI agents (this file)CLAUDE.md ← Symlink → AGENTS.mdREADME.md ← User-facing intro and prereqsCHANGELOG.md ← Keep-a-Changelog-feature-flags.json ← Feature flags (connectors=ga/on, custom-api, custom-telemetry)+feature-flags.json ← Feature flags (custom-api, custom-telemetry).claude-plugin/plugin.json ← Legacy plugin metadata mirrordocs/architecture.md ← Wiring/flow diagrams for BOTH skills (/genpage + /app-builder)@@ -628,6 +649,10 @@ references/ ← Shared reference docspage-telemetry.md ← props.appInsights page telemetry contract (custom-telemetry gated; loaded only when the maker asked to measure something)connectors.md ← GenPage connector binding contract and runtime patternsplan-schema.md ← Schema contract for genpage-plan.md+ app-spec-schema.md ← The App Spec contract (always-present fields) — /app-builder+ app-spec-schema-advanced.md ← Conditional App Spec fields (business rules, BPFs, commands, web resources, global choices, dashboards, roleGrants)+ authoring-flow.md ← /app-builder Phase 1 authoring playbook, run in the main loop (not a subagent)+ agent-interaction-contract.md ← Agents are headless: no AskUserQuestion / plan mode inside a Task subagentdata-caching.md ← Rule 15 on-mount fetch: de-dupe + cache (loaded conditionally)localization.md ← Multi-language + RTL pattern (loaded conditionally)supported-dependencies.md ← Versioned package list for generated pages@@ -638,7 +663,10 @@ scripts/launch-playwright-mcp.js ← Playwright MCP server launcher (fullscreen; uses lib/detect-browser.js)playwright-mcp-fullscreen.config.json ← Fullscreen browser config for the launcherregenerate-verified-icons.js ← Regenerates references/verified-icons.txt from npm- check-auth.js ← Pre-flight: az present + logged in, pac identity, WhoAmI, identity match+ check-auth.js ← Pre-flight: az present + logged in, pac identity, WhoAmI, identity match (pac overlaps the az probes)+ check-version.js ← Skill-start update notice: compares the plugin clone with its origin/main (git runs in the plugin, never the user's repo)+ resolve-interaction-mode.js ← Reports whether a human can answer in this run (unattended defaults)+ lint-app-spec.js ← Validate + lint an App Spec without touching an environmentdataverse-request.js ← General Dataverse Web API wrapper (escape hatch)list-connections.js ← Connector discovery: PAC connections + Dataverse connection referencescreate-connection-reference.js ← Creates Dataverse connectionreference rows for connector bindings@@ -659,7 +687,7 @@ scripts/run-tests.js ← one-command plugin + SDK regression runnersmoke-eval.js ← scripted live smoke eval (build → assert → teardown)generate-page-manifest.js ← Phase 0.5: writes working-dir package.json + genpage.d.ts- genpage-upload.js ← /genpage: deploy one page via the shared wrapper (prompt passed BY FILE, never on a command line)+ genpage-upload.js ← /genpage: deploy one page via the shared wrapper (prompt passed BY FILE, never on a command line; an update must name the app the page is placed in)genpage-plan-provenance.js ← /genpage: quarantine a stale plan before the planner writes, then verify the written plan targets the pages the approval namedcheck-page-files.js ← /genpage: pre-dispatch gate — the page file names of the plan's one ## Pages table are safe write targets (lib/page-file-targets.js)genpage-worker-output.js ← /genpage: accept a parallel worker's page only if complete (default export, balanced, no elided code)@@ -667,15 +695,21 @@ scripts/lib/entity-provision.js ← Shared entity-provisioning core (solution + data-model + sample-data)provision-input.js ← Input validation for entity provisioning- dataverse-auth.js ← Shared auth + HTTP helpers (uses `az account get-access-token`), plus the CLI arg contract (parseArgs/validateFlags)+ dataverse-auth.js ← Shared auth + HTTP helpers (`az account get-access-token`, memoized per process and replaced on a 401; responses decoded as UTF-8 once; an environment URL is used only as a Dataverse https origin, `dataverseOrigin`), plus the CLI arg contract (parseArgs/validateFlags)+ process-runner.js ← how every script starts az/pac/npm/npx/git: the executable is resolved to an absolute path on PATH, never the project folder, and started without a shell (a Windows batch shim runs through cmd.exe with its arguments checked)nearest-name.js ← pure single-edit "did you mean" matcher for closed vocabularies (CLI flags, FetchXML operators)supported-dependencies.js ← Single source of truth for runtime + dev deps versions- feature-flags.js ← Default-OFF feature flag probe + connector script backstop+ feature-flags.js ← Default-OFF feature flag probe + Custom API script backstopsdk-build.js ← app-builder build engine (idempotent; incl. the pages phase)stages.js ← stage→phase-range mapping + PHASES/STAGES constantsop-diff.js ← destructive-op diff + --allow-destructive / --non-interactive gatingartifact-intent.js ← pure App Spec → canonical SDK intent compiler (new form topology; no SDK calls)+ form-occupancy.js ← pure row occupancy (own cells + columns reserved by row-spanning cells above), shared by build and verify+ form-container-match.js ← how an authored tab/section is matched to a deployed one (shared by build and verify)+ ai-app-settings.js ← single source of truth for the per-app AI feature contract+ interaction-mode.js ← whether a human is reachable in this run (shared by both skills)page-plan.js ← pure App Spec → plan-document projection used by write-page-plan.js+ page-structure.js ← the one structural gate a generated page must pass (empty, truncated, prose, elided), shared by genpage-worker-output.js and promote-intent-pages.jspage-file-targets.js ← the one page-filename rule (absolute/backslash/traversal/.tsx only/links/case collision, incl. with files already there), shared with check-page-files.js and the evalssource-literals.js ← TSX lexer (code/comment/string/template/regex/JSX) — see "Known limits" belowsdk-teardown.js ← app-builder teardown engine (planTeardown is pure)@@ -712,11 +746,14 @@ scripts/projection.js ← changed-only: pure post-apply verifiers (form placement / sitemap / page dual-hash)detect-browser.js ← System Chromium/Edge/Chrome detection (used by the launcher)modelapps-hook-utils.js ← Tracked-skill discovery + validator lookup for the hooks+ utf8-stream.js ← reads a hook's stdin as UTF-8 without splitting a multibyte character across pipe chunkstelemetry/ ← Bundled 1DS telemetry: ikey.json (this plugin's config) + lib/ (copy of shared/telemetry/lib)vendor/cds-maker-sdk.cjs ← headless vendored SDK bundle (rebuilt via _vendor-build/)_vendor-build/ ← esbuild vendoring tooling (build.js + pinned deps)tests/ ← node --test coverage for the scripts + hooks-hooks/ ← Lifecycle hooks (registered in hooks/hooks.json)+hooks/ ← Lifecycle hooks+ hooks.json ← Hook registrations (closed schema — documentation lives in README.md)+ README.md ← What hooks.json wires up, and whyrun-skill-posttool-validation.js ← Runs a skill's validate*.js after the Skill tool returnsvalidate-icon-imports.js ← PostToolUse: blocks unverified @fluentui/react-icons in generated .tsxvalidate-write-safety.js ← PreToolUse: flags (non-blocking) out-of-cwd writes in model-apps sessions@@ -752,7 +789,7 @@ Agents are invoked by skills via the `Task` tool — they are not user-invocable| `genpage-entity-builder` | `genpage` (create flow) | Provisions Dataverse tables, columns, relationships, choices, and sample data via `scripts/provision-entities.js` (the shared SDK-backed core). Bulk inserts use OData `$batch`. Writes a transactional log for recovery || `genpage-page-builder` | `genpage` (create flow) **and** `app-builder` (Phase 1.5) | Generates one complete `.tsx` page from a plan document and schema; runs in parallel with other builders for multi-page requests. `/app-builder` projects its App Spec into that plan format via `scripts/write-page-plan.js` and dispatches this same agent || `genpage-edit-planner` | `genpage` (edit flow) | Reads the downloaded page artifacts (page.tsx, config.json, prompt.txt), gathers change requirements, presents edit plan, writes `genpage-edit-plan.md`. The orchestrator applies the edit inline. |-| `genpage-connector-builder` | `genpage` orchestrator (create **and** edit flows) | **Single owner of the connectors feature gate.** Performs connector discovery (connections, connection references, datasets, tables, operations, schema), creates Dataverse connection references, and writes the `## Connector Bindings` contract + `connectors.json`. The orchestrator forwards its output into the planner or edit-planner prompt. |+| `genpage-connector-builder` | `genpage` orchestrator (create **and** edit flows) | Performs connector discovery (connections, connection references, datasets, tables, operations, schema), creates Dataverse connection references, and writes the `## Connector Bindings` contract + `connectors.json`. The orchestrator forwards its output into the planner or edit-planner prompt. || `genpage-customapi-builder` | `genpage` orchestrator (create **and** edit flows) | **Single owner of the custom-api feature gate.** Discovers the Dataverse Custom APIs a page can bind to (Global + entity-bound Actions/Functions) plus their parameter kinds via `list-custom-apis.js`, and writes the `## Custom API Bindings` contract + `actions.json`. The orchestrator forwards its output into the planner or edit-planner prompt. |## Key Concepts@@ -778,21 +815,22 @@ is about runtime/deploy output, not that every authoring artifact is byte-for-byunchanged. The mechanism lives in `scripts/lib/feature-flags.js` with the committedvalues in `feature-flags.json` at the plugin root.-**A GA flag is flipped to `true` FIRST and removed in a LATER change, not both at once.**+**A flag is flipped to `true` FIRST and removed in a LATER change, not both at once.**Flipping is reversible in one line if the rollout turns out to be incomplete in some tenant;deleting the gate in the same change that enables the feature leaves no way back except arevert. Once a release has shipped with the flag on and no rollback was needed, remove it —a permanently-on gate is dead weight that still has to be probed, branched on and reasonedabout at every call site.-`connectors` is in that window now: **GA, shipping `true`, gate retained as a rollback-switch, scheduled for removal in the next release.**+Connector authoring no longer has a feature flag (the feature itself is in public preview). The+remaining flags are `custom-api` and `custom-telemetry`; both currently ship **OFF** while their+dependencies finish rolling out.- **Source of truth:** `feature-flags.json` (e.g. `{ "custom-api": false }`). Flip aflag to `true` in a one-line PR once its dependencies are GA in PROD, then removeit in a follow-up that deletes its gates.- **Precedence (highest first):** env var `GENPAGE_ENABLE_<FLAG>` (e.g.- `GENPAGE_ENABLE_CONNECTORS=0` to roll connectors back) → committed+ `GENPAGE_ENABLE_CUSTOM_API=1` for a single run) → committed`feature-flags.json` → default `false`(fail-closed). This mirrors the telemetry opt-out env-over-config convention.- **LLM gate:** skill/agent markdown probes a flag with@@ -801,19 +839,19 @@ switch, scheduled for removal in the next release.**flag's lifecycle **status** (experimental / in-progress / ga), effective state +source (env/file/default), summary, how to enable, plus config-validation warnings.Flags are catalogued with that metadata in the `FLAGS` map in `feature-flags.js`- (the committed `feature-flags.json` carries only the on/off value).-- **Script backstop:** connector entrypoints call the shared- `exitIfConnectorsDisabled()` helper (DRY — no inlined gate) and fail closed with- exit 3 when OFF: `list-connections.js`, `create-connection-reference.js`, and the- `--connection-refs` branch of `add-page-to-solution.js`. Custom API entrypoints call- the parallel `exitIfCustomApiDisabled()` helper the same way: `list-custom-apis.js`.+ (the committed `feature-flags.json` carries only the on/off value). Unknown flags+ are disabled even when a matching env var is set.+- **Script backstop:** Custom API entrypoints call the shared+ `exitIfCustomApiDisabled()` helper (DRY — no inlined gate) and fail closed with+ exit 3 when OFF: `list-custom-apis.js`. Connector scripts have no feature-flag+ backstop because connector authoring is always on.- **Validation:** `KNOWN_FLAGS` + `validateFlags()` warn on unknown keys / non-booleanvalues in the committed file (so a typo can't silently do nothing, or — after a flipto `true` — accidentally enable the wrong thing).**Each gated feature has a SINGLE OWNER agent, and every entry point must go through it or the-shared helper.** The currently-gated features gate at the same five places, so the rule is stated-once here and only the per-feature specifics are tabled below:+shared helper.** Gate a feature at the same five places, so the rule is stated once here and+only the per-feature specifics are tabled below:1. **Discovery** — the owner agent runs the probe first; planners/edit-planners delegate to it andnever gate inline.@@ -825,21 +863,20 @@ once here and only the per-feature specifics are tabled below:5. **Codegen** — `genpage-page-builder` emits feature code **only** when the plan carries an actualbinding table, never on an absent/sentinel section.-| | `connectors` | `custom-api` | `custom-telemetry` |-|---|---|---|---|-| **Owner agent** | `genpage-connector-builder` | `genpage-customapi-builder` | none — codegen-only |-| **Plan section** | `## Connector Bindings` | `## Custom API Bindings` | none — driven by the maker request, not the plan |-| **Gated scripts** | `list-connections.js`, `create-connection-reference.js` | `list-custom-apis.js` | none |-| **Deploy phase** | SKILL Phase 4.5 | SKILL Phase 4.6 | SKILL Phase 4.7 (probe only) |-| **ALM** | the `--connection-refs` branch of `add-page-to-solution.js` | none needed — `config.json`'s `actionBindings` travels inside the page's `uxagentprojectfile` rows automatically (the Custom APIs themselves are a separate deployment prerequisite, bound by name) | none — telemetry rides the host runtime, nothing is packaged |-| **Emits** | connector code | `executeAction` / `executeFunction` / `listBoundActions` | `props.appInsights` calls (`trackEvent` / `trackMetric` / `trackTrace` / `trackException` / `trackDependency` / `startTrack` / `stopTrack`) |+| | `custom-api` | `custom-telemetry` |+|---|---|---|+| **Owner agent** | `genpage-customapi-builder` | none — codegen-only |+| **Plan section** | `## Custom API Bindings` | none — driven by the maker request, not the plan |+| **Gated scripts** | `list-custom-apis.js` | none |+| **Deploy phase** | SKILL Phase 4.6 | SKILL Phase 4.7 (probe only) |+| **ALM** | none needed — `config.json`'s `actionBindings` travels inside the page's `uxagentprojectfile` rows automatically (the Custom APIs themselves are a separate deployment prerequisite, bound by name) | none — telemetry rides the host runtime, nothing is packaged |+| **Emits** | `executeAction` / `executeFunction` / `listBoundActions` | `props.appInsights` calls (`trackEvent` / `trackMetric` / `trackTrace` / `trackException` / `trackDependency` / `startTrack` / `stopTrack`) |At Phase 4.7 the `/genpage` orchestrator probes and passes the verbatim result as`Telemetry: enabled|disabled` in every page-builder dispatch — **that dispatch value wins overthe plan.** Phase 4.5 passes a `Connectors: none|<n> binding(s)` line the same way, but note the-difference: that value is the **binding count**, not the flag state. A disabled gate and an empty-binding table both yield `none`, because the page-builder only needs to know how many bindings it-may call — which keeps the dispatch stable when the flag is eventually removed.+difference: that value is the **binding count**, not a flag state. An empty binding table yields+`none`, because the page-builder only needs to know how many bindings it may call.`custom-telemetry` is the odd one out: it has no owner agent, no discovery script, no plansection and no deploy or ALM step. It gates **code generation only** — steps 2-4 of the@@ -848,10 +885,8 @@ produces the dispatch line. It also carries a second gate the other flags do notwhen `enabled`, `genpage-page-builder` instruments a page **only** when the maker explicitlyasked to measure or track something. `enabled` is permission, not instruction.-All three flags currently ship **OFF**, each waiting on cross-repo dependencies:+The two remaining flags currently ship **OFF**, each waiting on cross-repo dependencies:-- **`connectors`** — the pac CLI connector verbs (PowerPlatform-Scale-AdminTools), the GenUX- authoring control (power-platform-ux), and the maker/admin ECS setting must all release first.- **`custom-api`** — the AIBuilder CoderAgent action prompt, the shared `pai-gen-ux-action-runtime`plus the UCI and Controls host runtimes, a pac CLI `model genpage upload --actions` verb topersist `actionBindings` into `config.json`, and the `GenUxPluginActionAllowList` ECS setting.@@ -866,13 +901,13 @@ All three flags currently ship **OFF**, each waiting on cross-repo dependencies:**`scripts/lib/source-literals.js` — known limits.** It is a hand-rolled TSX lexer, not aparser: the plugin ships dependency-free, so there is no TypeScript to call. It trackscode / line comment / block comment / string / template / regex / JSX tag / JSX text, and-backs the `promote-intent-pages.js` structural gate plus the eval's effect scoper. It also+backs the page structural gate (`lib/page-structure.js`, shared by `promote-intent-pages.js` and+`genpage-worker-output.js`) plus the eval's effect scoper. It alsobacks the navigation oracle (`pageref-resolver.js`), which finds each call AND parses its objectin the lexer's mask — executable code inside a template's `${…}` is visible, template text and-string bodies are not — and reads each value from the source at the same offsets, so one lexer-drives both. It also backs the worker-output gate-(`genpage-worker-output.js`), and `findElisionMarker` — the one "was code elided?" rule the-worker gate and the Layer 2 eval share (a `FIXME` comment, a `TODO` that opens a comment or takes+string bodies are not — and reads each value, and each quoted key (`"pageId"`), from the source at+the same offsets, so one lexer drives both. It also backs `findElisionMarker` — the one "was code+elided?" rule the page gate and the Layer 2 eval share (a `FIXME` comment, a `TODO` that opens a comment or takesa colon, a comment opening with `...`, "omitted for brevity", or a bare `...` line; the same wordsas UI copy — "Loading…", a `'TODO'` status value — are not elision). A template's `${…}` body iscode and is read by the same lexer (`lexInto`), JSX and comments included, never by a lighter@@ -1090,8 +1125,9 @@ NODE20_BIN=/path/to/node20/bin node scripts/run-tests.js --with-sdk /path/to/pow```- `run-tests.js` runs the full `scripts/tests/*.test.js` suite and prints a combined PASS/FAIL.- **CI runs this same command** (`.github/workflows/model-apps-script-tests.yml`) on any PR touching- `plugins/model-apps/**` or `evals/model-apps/**`, across ubuntu × windows × macos and Node 20 × 22.+ **CI runs this same command** (`.github/workflows/model-apps-script-tests.yml`) on any PR into `main`+ touching `plugins/model-apps/**`, `evals/model-apps/**`, `shared/telemetry/**`, `shared/skills/**` or the+ workflow itself, across ubuntu × windows × macos and Node 20 × 22.Keep `POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: "1"` on any new job that could run atelemetry-emitting hook or script.- The SDK's Jest suite needs **Node 20** (its `canvas` native module is built for the Node-20 ABI).diff --git a/plugins/model-apps/CHANGELOG.md b/plugins/model-apps/CHANGELOG.mdindex d022d0c05..3750e38c3 100644--- a/plugins/model-apps/CHANGELOG.md+++ b/plugins/model-apps/CHANGELOG.md@@ -5,366 +5,120 @@ All notable changes to the **model-apps** plugin.Entries are deliberately short: what changed and why it matters to you. The reasoning,evidence and trade-offs behind a change live in its PR, in `docs/`, or in the linked issue.-## [Unreleased] — 2.9.0+## [Unreleased] — 2.10.0++Connector authoring loses its feature flag, `--allow-destructive` removes only what a maker was+shown, and the vendored SDK is refreshed.++### Changed++- **The `connectors` feature flag is removed**, with `GENPAGE_ENABLE_CONNECTORS`: it was on by default+ for a release with no rollback needed. Connector authoring stays in public preview. An unknown flag+ now stays off even when a matching env var is set.+- **Faster preflight and `/genpage` updates.** `check-auth` overlaps its CLI cold starts (24–32 s →+ 16–19 s on Windows), scripts reuse one `az` token per process, and an update's two target checks+ run together (10.6 s → 5.6 s).+- **The vendored SDK is refreshed.** *Contains data* and *does not contain data* conditions in+ business rules are sent in the shape the platform's designer writes, and the bundle stays under 1 MB.++### Fixed++- **`--allow-destructive` removes only what a maker was shown.** A refusal records its list in+ `.maker-workspace/destructive-approval.json`; the approved re-run halts, naming the new ones, if+ anything else would now be removed.+- **`prune: false` forms** no longer report, or demand approval for, removals that never happen.+- **Switching a table's default Main form** clears the old default; verify fails while two hold it.+- **Row-spanning cells** count wherever the build fits a layout, and a removed field no longer leaves+ an empty form row.+- **A `/genpage` update must name the page's own app**; another app's id used to rename the page.+- **Non-ASCII text** split across response or hook chunks is no longer turned into U+FFFD.+- **pac on Windows**: a path ending in `\` no longer swallows the next argument, and a malformed page+ listing or page id is no longer trusted.+- **Navigation keys**: a quoted key resolves like a bare one, a duplicated key counts where it takes+ effect, and a target a later spread could replace is refused.+- **Downloads** refuse a malformed page `dataSources`, keep a page prompt's exact text, and read past+ 1,000 components.+- **The version check** no longer fetches your project's repository.++### Removed++- Dead helpers, and duplicate copies of shared ones.++### Documentation++- Corrected what a rebuild re-applies to existing artifacts, what `--verify` proves (it does not catch+ a removed view column), and BPF security-role grants. A page's connector and Custom API bindings+ survive only a same-environment rebuild. The telemetry disclosure matches its shared source again.++## [2.9.0]A dry run that says what an apply would really do, sample data that can express a hierarchy, anddownloads that round-trip Choice columns.### Added-- **`app.aiDescription` — a routing description for agents** ([#583]). The text an orchestrator reads- to choose between sibling apps over the same tables, kept apart from the tile's `app.description`.- It is written to the platform's `appmodule.aiappdescription` at create, and on an existing app when- it differs. A download carries it back, and `--verify` checks it. Leave it out and the build never- touches the deployed value. If the app has an unpublished change in Maker, the build halts and tells- you to publish first, rather than failing with a remedy that cannot work. A workspace copy of the app- holding an earlier run's unpushed edits — an interrupted build, say — is refused before anything is- applied, rather than pushed along with this run's changes, and a failed push of the app resets it.-- **`personas[].excludes[]` records what the app deliberately leaves out** ([#583]), rendered as- **Deliberately out of scope** beside the traceability table. Documentary only.-- **Richer form layouts**: multi-column tabs (`tabs[].columns[]` with a `width`), cell- `colspan`/`rowspan`, and author-controlled `expanded`/`visible`/`showLabel`. Layout keys are- allow-listed, so a typo fails instead of silently vanishing.-- **The dry run resolves create-vs-reuse against the live environment** ([#559]) — each item is- `+ create`, `= reuse` or `? unknown`, never guessed. `--no-live-plan` restores the offline listing.-- **Sample data can express a hierarchy on one table** ([#544]). `$parent` may target the row's own- entity; rows seed in dependency waves and a cycle fails the lint. `$parent.lookup` picks the- relationship when two connect the same pair — now required there instead of guessed.-- **`minimumPluginVersion`** lets a spec declare the oldest plugin that can build it, so a newer spec- is refused rather than mis-compiled.-- **The vendored SDK moves to injected storage.** `createNodeWorkspaceStorage(...)` replaces- `workspacePath` — no change for authors, breaking for anything calling these scripts as a library.+- **`app.aiDescription`**, a routing description agents read to choose between sibling apps+ ([#583]). It is written, downloaded and verified; leave it out and the deployed value is untouched.+- **`personas[].excludes[]`** records what an app deliberately leaves out ([#583]).+- **Richer form layouts**: multi-column tabs, cell `colspan`/`rowspan`, and+ `expanded`/`visible`/`showLabel`.+- **A live dry run** marks each item create, reuse or unknown ([#559]); `--no-live-plan` keeps the+ offline listing.+- **Hierarchies in sample data**: `$parent` may target the row's own table ([#544]), and+ `$parent.lookup` is now required when two relationships connect the same pair.+- **`minimumPluginVersion`** refuses a spec newer than the plugin.+- **The vendored SDK uses injected storage** (`createNodeWorkspaceStorage`), a breaking change only+ for library callers.++### Changed++- **`/app-builder` is GA**; `--changed-only` stays experimental and off by default.+- **Connector authoring is on by default** (public preview); the `connectors` flag stays for one+ release as a rollback switch.+- **The App Spec schema is split** (the always-read half is 82 KB, down from 105 KB), and every script+ shares one CLI flag contract.+- **`write-page-plan.js` no longer takes `--out`**; it writes only a plain file in the working+ directory.### Fixed-- **A named form section moves to the tab the spec puts it in.** A section found elsewhere on the- deployed form — dragged in Maker, or moved in the spec — used to be updated where it stood, so the- build succeeded, the section stayed in the old tab, and `--verify` failed the form. It is now moved- (the same section, fields and all), and a neighbour with the same label can no longer take it over.- A section of yours that shares its name with the engine's own host (`section_notes`) never takes- the timeline or a sub-grid host — by name, label or position, and even after a maker added a field to- the host: it gets a section of its own. With notes on, the timeline no longer takes over a- `section_notes` of yours, or a section a maker added, either — their fields stay put, and an existing- form gets its timeline too — and a section you declared with no fields keeps its name even after a- maker puts a web resource or sub-grid in it. An emptied copy of a section you named like a generated- one (`section_1_0`) is no longer reported with advice to give it a name.-- **A page NAME can no longer forge the page listing.** The "Found N pages" summary was matched- anywhere in pac's output, so a page called `Found 1 generated page` made a listing with no real- summary read as authoritative — and a truncated-but-authoritative listing is what drives a- duplicate page create. The whole line must be the summary, so a name that merely *starts* with it- is rejected too.-- **A malformed page id is refused instead of stored.** The old pattern accepted 36 characters from- an alphabet containing `-`, so a row of dashes passed and an over-long id was silently *truncated*- into a plausible one. Any identifier character following the id now disqualifies it, not just a- hex digit. An unparsable id goes through the existing uncertain-create recovery.-- **A sample-data row that is not an object is rejected up front.** `null` crashed, a string became- `{"0":"a","1":"b"}` and a number became `{}` — all after tables, forms and views had deployed.- Both provisioning entry points share one gate; `provision-entities` previously checked only that- the value was an array.-- **A failed PAC command reports what PAC actually said.** The real error was replaced by the last- line of the help dump that follows it, and a deterministic failure (a bad argument, a missing file)- was retried three times before reporting anything — on an ordinary page update it still was, since- the stop condition only covered creates.-- **A path ending in `\` no longer swallows the flags after it** on Windows, where a trailing- backslash escaped its own closing quote.-- **A crashed browser-automation server reports failure**, instead of exiting 0 because the process- was killed by a signal rather than by its own choice.-- **`generate-page-manifest --force` never writes outside the working directory or through a link.**- A `package.json` that is a symlink (even a dangling one) or a hard link is refused, and so is a- working directory that is itself a link or junction; a linked ancestor is still followed. A file is- replaced atomically and keeps its file mode, and a read-only one is refused rather than replaced.-- **`--clear-workspace` refuses a UNC/network path**, which could otherwise block on an unreachable- share with no way to interrupt it. A mapped drive is unaffected.-- **A transient discovery failure no longer certifies a `--changed-only` baseline as fresh**, which- could let a later page edit skip a full build it actually needed.-- **An explicit form layout reshapes a form instead of flattening it** ([#575]). Every field was- appended to the first section, containers were never created or resized, and declaring `tabs`- silently switched pruning on. Containers now match by `name`, then `label`, then position, and a- misplaced field is moved rather than duplicated.-- **A section emptied by a layout move is reclaimed** instead of surviving as a blank twin.-- **A field added or moved on an existing form packs to the section's grid**, so the same spec no- longer produces a different form depending on whether the form already existed.-- **Cell spans converge on an existing form, and are clamped against the grid that is really- deployed.** A declared span reaches the deployed cell; an undeclared one is still never sent, so a- cell widened by hand survives. Clamping used the grid the spec compiled to rather than the live- one, so an auto layout could narrow a maker's four-column cell to one; and narrowing a section- left an over-wide cell behind, unchanged on the next apply too. `rowspan` is rejected unless it is- inline on the last field in its section ([#581]), and a form-level `fieldOptions` span is now- validated too instead of a bad value being dropped.-- **Re-flowing a section no longer breaks a maker's row-spanning layout.** Once a field follows a- `rowspan`, re-flowing by reading order moved it into the reserved slot. Such a section now keeps- its grid when the rows cannot follow a narrowing, a span change that would overflow its row is- skipped, and a `rowspan` is never raised on a deployed cell that other cells follow. Trailing spans- (the stock-form shape) re-flow normally. Every refusal is reported and recorded in the build- result's `skipped.layout`.-- **A form field can be narrowed again.** An explicit `colspan`/`rowspan` of `1` was- indistinguishable from omitting it, so changing `2` back to `1` never reached the form.-- **Widening a field on a deployed form re-packs its row.** The span was patched in place but the- row was not re-packed, leaving three columns of content in a two-column section. Displaced fields- move down rather than to the bottom of the section; a span that still fits writes nothing.-- **`--verify` judges widths and spans by the build's own rule.** It used to derive them separately:- a too-narrow section could excuse its own span (`columns: 4, colspan: 4` arriving as 1 and 1- verified PASS), while a section that omits `columns`, a QuickCreate section, or a span set through- `fieldOptions` was misjudged. Verify now uses the compiler's width and field-option rules, and it- counts the slot a row-spanning cell reserves beneath it, so a full row under a `rowspan` fails.-- **`--verify` no longer fails a reshape the build performed correctly.** The build reuses deployed- containers and deliberately does not rename them (form scripts and business rules reference- section names), but verify looked them up by the authored name — so a section it had just reused- read as "absent". Both sides now share one matcher.-- **The form wireframe shows authored `hidden` and `readOnly` state** ([#591]), so the approval gate- no longer draws every field as visible and editable.-- **`/genpage` deploys through the same quoting-safe upload path as `/app-builder`** ([#589]). A- prompt containing quotes, newlines, `%VAR%` or non-ASCII could fail to deploy — and editing the- approved prompt until it parses builds the page from text nobody approved. `--add-to-sitemap` is- now refused alongside `--page-id`.-- **A multi-line page prompt is no longer flattened on upload** ([#565]). Prompt files are now- delivered byte-for-byte, including a trailing newline; only a leading byte-order mark is stripped,- because that is an encoding marker rather than content.-- **`/genpage` refuses to "update" a page that does not exist.** `pac` treats an unknown `--page-id`- as a create and returns the new id, so a stale one silently produced a second, unplaced page and- reported it as an update.-- **An explicitly empty prompt or agent message is refused, not replaced** with generated text.- Omitting the value still gets the default, on both `/genpage` and `/app-builder`.-- **A `/genpage` update no longer silently unbinds the page.** `pac` rewrites the binding list from- the flags it is given, so omitting `--data-sources` persisted `[]` while the source went on- querying the table. An update now preserves the page's existing bindings; `--clear-data-sources`- unbinds deliberately.-- **`/genpage` Phase 1 is reachable again** ([#541]) — its interactive flow no longer runs inside a- headless subagent.-- **A downloaded page keeps its table bindings.** `pac` writes `config.json` with a BOM, which- `JSON.parse` rejects, and the failure was read as "no data sources". A config that is present but- unreadable now stops the download unless you pass `--allow-lossy-download`.-- **Choice and MultiChoice columns round-trip on download** ([#564]). They were emitted untyped, so- a fresh rebuild created Text, and a MultiChoice column was dropped entirely. Option *values* still- do not round-trip: labels and order do, and a fresh rebuild re-bases them to `100000000 + index`.-- **`relationships[]` is reconstructed on download** ([#567]). The block was absent and nothing said- so, so a rebuild produced tables with no lookups and reported success.-- **A download no longer invents columns** — a polymorphic lookup's shadow attributes ([#574]) and a- Money column's `_base` twin were emitted as real columns a fresh rebuild would then create.-- **A downloaded spec no longer fails its own lint** ([#572]).-- **A renamed N:N relationship carries its deployed name**, so a rebuild does not create a second- intersect beside it, and it is reported as renamed rather than lost.-- **Every dropped dashboard tile is reported**, naming the parameter it lacks, and id-passthrough- tiles are validated per tile type.-- **`--clear-workspace` no longer recursively deletes whatever `--workspace` named** ([#587]). It ran- `rm -rf` on the caller's path with no check that it was a workspace, immediately after a- *successful* teardown. It now requires the directory to carry the SDK's own workspace manifest —- the conventional name alone is not proof — and rejects roots and symlink escapes.-- **Teardown stops instead of stripping a live app when the app delete fails** ([#587]). This- **reverses earlier best-effort behaviour**; continue-on-error still applies to every later step.-- **A security role whose sharing check cannot be read is retained, not deleted** ([#587]).-- **A plain `--apply` halts when the changed-only snapshot cannot be invalidated** ([#587]) —- otherwise a later `--changed-only` run trusts a stale snapshot and skips work.-- **Teardown no longer reports a false failure for a self-referencing relationship** ([#544]).-- **A mistyped flag fails instead of quietly changing what the command does.** An unrecognised flag- was dropped *and* swallowed the token after it, so `--stagee ui` planned all 9 phases and exited 0.-- **`--verify` proves the deployed form LAYOUT**, not just that a form exists — every wrong-layout- failure previously finished with an unqualified PASS. It checks the authored tabs, sections and- field placement, that no row carries more content than its section's grid allows, and that a span- you declared is the span that deployed. A span you did *not* declare is left alone, so a cell- widened by hand in the designer still verifies.-- **`--verify` proves sort PRECEDENCE, not just membership**, so two views that return rows in- different orders are no longer both accepted.-- **`--verify` checks that a sitemap-visible table really belongs to the app**, and fails closed when- the component list cannot be read.-- **`--verify` gained three oracles**: the deployed default Main form, a view's filters/sort parsed- from `fetchxml`, and app-role associations. Each fails closed.-- **`--verify` no longer demands a default form the build never promotes** on a reused or stock table.-- **A tab's `columns` must be a list of form-columns.** `"columns": 2` on a tab validated clean and- was then discarded, silently shipping a one-column form.-- **Duplicate sample-data names fail at author time**, not after tables and forms are deployed.-- **`_seedKey` in `sampleData` is rejected** instead of reaching Dataverse as an attribute no table- has; the error names the real mechanism, a single-column alternate key.-- **An explicit layout with no tabs, or a tab with no sections, is rejected** — it previously passed- the build gate and silently dropped every field the form declared.-- **A form layout may not place the same field twice, or reuse a tab/section `name`.** A duplicated- field deployed two cells on a fresh build and one on the next.-- **A business rule's `dataType` reaches Dataverse as a real type.** The platform *accepts* the wrong- value rather than rejecting it, so affected rules deployed and activated with a wrongly-typed- condition — rebuild any app with `businessRules[]` built against the previous release.-- **A build no longer reports a default form it failed to set**, and a failed promotion warns with- the reason instead of being swallowed. An **existing** view's authored filters/sort are still not- reapplied, and that is now said out loud.-- **A test file in a `scripts/tests/` subdirectory is no longer silently skipped.**-- **The vendored SDK is refreshed** for upstream wire-correctness fixes (view joins, `addElement`- re-keying, dashboard parsing, duplicate sort attributes, a flow left disabled when an edit fails)- and a patched `@xmldom/xmldom` (0.8.15, parser denial-of-service fixes). Two change what you see:- **an app whose sitemap has an unpublished edit can now be torn down** — the delete carried a token- the platform refuses while an edit is pending, so it failed with 412 every time — and **each write- in a business process flow's create is conditioned on the token the previous write returned**, so- a concurrent edit is refused rather than activated or overwritten.-- **A slow write is waited for, not abandoned and re-sent.** Writes now get up to 5 minutes (reads- keep 60 s), and a conditional write that gets no answer is reported rather than re-sent: it may- still commit, and a re-send could only be refused as a false version conflict. Activating a- business process flow on a newly created table can take longer than the old 60 s.-- **`/genpage` runs only the plan you approved** ([#585]). An edit plan is read as an edit, by its file name,- and the approval preview by its own Current State block and the written plan by its own File Being Edited- section, so a Pages table or an edit section quoted from the page's prompt cannot make an edit of another- page pass. A plan left over from an earlier run is- quarantined before the planner writes, and the new file must build exactly the pages the approved- plan named — so a planner that failed to write, or wrote a different plan, halts instead of running it.- A link at the plan path, its approval sidecar or the quarantine folder (a dangling one included), or a- hard link at either file, is refused rather than written through, and an overlong or conflicting page- id is refused, not truncated to a valid-looking one. An edit's target is the page the preview's own- File line names, so neither a path quoted from the page's prompt nor another file in its folder- (`page.tsx.bak`) can stand in for it.-- **A truncated page is caught before deploy** ([#585]). Every page — each parallel worker's, and one- written inline — is checked for a complete default export, balanced brackets and elided code- (`// TODO`, `// ...`, "omitted for brevity"). A write cut off where every bracket still balances- fails too: inside its own export line (`export default function Page(props)` with no body),- inside JSX, a string or a comment, or right after an operator — in `/app-builder`'s page promotion- as well. A failing worker page is rebuilt inline, and an inline page that still fails halts.- "Loading…" in a label is UI copy, not elision.-- **A missing `## Custom API Bindings` section halts instead of meaning "none"** ([#585]). Only the- exact `No custom API bindings.` sentinel says a page has none, so a broken plan can no longer drop- an approved binding. A plan made while `custom-api` was on halts too once the flag is off, instead- of generating Custom API calls that deploy with no bindings.-- **Solution packaging checks every connection reference before changing anything** ([#585]). A- missing reference used to fail after the app and pages had already been added to the solution.-- **Connections without both ids are no longer offered for binding** ([#585]). A listing where no row- has a connection and a connector id is an error, not "no connections" — in every table layout PAC- prints, including a connection row that matches none of its columns.-- **Right-to-left layout follows PAC's RTL column** ([#585]), not a list of six Arabic and Hebrew- LCIDs — Persian, Urdu, other Arabic regions and the rest now render right to left.-- **Re-running the manifest generator with a new feature no longer reports success over a stale- `package.json`** ([#585]). A missing package fails with the fix, and `/genpage` halts there for you- to merge it or rerun with `--force`; a version you changed is kept and reported as `versionDrift`. A- manifest saved with a UTF-8 byte-order mark (Windows PowerShell's default) is read as usual.-- **The code-generation rules list exactly the packages the page installs** ([#585]), and a test- fails when they drift from the dependency map. Three libraries the rules offered but the package- never installed are gone from the list.-- **Icons are verified however they are imported** ([#585]). A namespace, default, `require` or- dynamic `import()` of `@fluentui/react-icons` is blocked — in any quote style, anywhere on a line,- combined with a named import, or with a trailing comma or import options — since only named- imports can be checked.- A shipped sample that used two unverified sized icons is fixed, and every sample must now pass.-- **Navigation checks read code, not prose** ([#588]). A `navigateTo` in help text no longer counts- as a link, and one inside a template's `${…}` is no longer invisible to the portability check. An- emoji in a comment or a template, or a regex holding `/*`, `//` or a backtick- (`u.replace(/\/*$/, "")`), no longer hides every call after it — which had left a placeholder link- unresolved in the deployed page while verification passed.-- **A complete page is no longer rejected as truncated** ([#585]). `/app-builder`'s page promotion- read these as unbalanced brackets and refused a finished page: braces in a nested template's text,- a comment right before JSX or a regex, and a `/` after a property named like a keyword- (`counts.new / total`), a non-null assertion (`closed! / total`) or `i++`, a division after a type- cast (`total as NonNullable<number> / count`, its type arguments nested or across lines, and the- name they belong to one part of a union, an intersection or a conditional type's false branch), and a- file that ends in a member export such as `export default pages.Home` or a self-closing element- with a callback prop. Two shapes the text alone cannot tell from a cut-off page are refused on- purpose, and the page rules tell workers to avoid them: a line holding only `...` is always a- placeholder, even where TypeScript would read a spread of the next line, and a file whose last- statement ends in type arguments (`export default Page<string>`, a `type` alias) needs its `;`.- The same checks back `/genpage`'s new gate.-- **A page's display name reaches the upload by file** ([#588]). `genpage-upload.js` takes `--name-file`, and- `/genpage` writes the name to a file as it does the prompt: substituted into `--name "<name>"`, a shell expanded- `$(…)` in it before the script ran, and `Revenue $100` arrived as `Revenue `.-- **`/genpage` single-quotes every value it fills into a command.** A working directory with a space in its- path became two arguments, and a `$` in an app or solution name was expanded; the skill now states the rule- once, every command template follows it, and a test fails when one drifts back.-- **The maker's text never passes through a shell, and the upload's input files never through a link.**- `/genpage` writes the prompt, agent-message and page-name files with its file tool, not a shell command — even a- single-quoted here-string ends at a line that begins with `'@`, and the rest of that line runs — after checking- that none of those names is a link. `genpage-upload.js` refuses any of its input files (those three,- `--connectors`, `--actions`) that is a link, a hard link or a folder, since a write through one rewrites the file- it points to.-- **Page file names are checked before any worker writes** ([#588]). Absolute and drive-relative paths,- `..`, backslash aliases, a character a shell would expand or split on (a space, `$`, a backtick, `;` —- names use letters, digits, `.`, `-` and `_`), a name Windows cannot store (`CON.tsx`, a `:` — an NTFS alternate stream — or- a trailing dot), a name that is not a `.tsx` page (`package.json`), a page path that is itself a link- or not a regular file, a folder that links outside the working directory or cannot be read, and- names that collide ignoring case (`Page.tsx` / `page.tsx`, with each other or with a file or folder- already there) halt the build, as does a new page that is an already-built one reached through a link- or junction, or a working directory that is a link or not a folder at all. A plan with a second Pages- table naming files — one quoted in the requirements, fenced, quoted or not, and each table counted on its own,- however many share a heading — halts too, instead of only the- first being checked. So does a Pages section with any other table row beside its File table (a- delimiter row repeated under a page row had made that row a header, and its page vanished from- both checks) or a table with two File columns; a row written without its outer pipes is read like- any other. `/app-builder` writes its page plan only as a plain file in the working- directory, never through a link, hard link or folder at its path (`write-page-plan.js` no longer takes- `--out`). The same rule covers the- pages `/app-builder` generates — which now- runs the disk checks too, before its workers — and the evals. A worker's page that is a folder or- cannot be read fails its check instead of crashing it.-- **An `already-exists` halt names the step that clears it.** A plain re-run keeps the workspace copy- that was never recorded as pushed and halts again; the message now says to delete `.maker-workspace`- first.-- **Same-named charts on different tables no longer cross-wire a dashboard tile** ([#586]). A tile- plotted one table's chart over another table's view. Chart identity now includes its table; a tile- whose view name exists on several tables must say which with `entity`, and verify checks that each- chart tile's chart and view belong to the tile's table — on the published dashboard: one with- unpublished changes is reported unverified, and the tiles are read into a throwaway workspace, never- through the build's copy, which may hold unpushed edits. A draft saved and put back while the tiles are- read is caught too, by the draft's version rather than its content.-- **Two dashboards whose names Dataverse treats as one are refused** ([#586]) — it compares names- ignoring case, accents and trailing spaces — because a rebuild would collapse them into one and drop- the other from the nav. A download withholds such a pair and says why, and it withholds a dashboard- whose name cannot be read rather than naming it after its sitemap title.-- **A dashboard belongs to the app through the app's solution** ([#586]). A name can also match another- app's dashboard, and teardown used to delete every match. It now deletes only the dashboards the app's- solution holds, none when the spec has no real solution to ask, and keeps the solution while any step- failed — a solution it could not read counts as one — so a re-run can still tell. When several- match, the build reuses the solution's own or halts instead of reusing an arbitrary one, and verify- checks that same one — including the sitemap entry that opens it, which took the first match and- failed a correctly wired app. A dashboard the build cannot add to its solution is removed again- rather than left outside it; if that fails too, the build halts naming it and does not auto-retry,- since a retry would reuse it outside the solution. A lone match outside the solution is still reused- (a downloaded app's dashboard may never have joined the solution that holds the app), and the build- now warns that nothing proves it is this app's rather than another app's namesake.-- **A Choice written as a label, its translation, or its number is one sample-data key** ([#586]). The- loader always saw them that way; the spec gate compared them as written, so a duplicate passed it- and the seed then failed after tables and forms had deployed. A Choice column with no `schemaName`- on a table with sample data is now reported by name instead of crashing validation.-- **A download reports only the app's own global choices as not round-tripped** ([#586]) — the ones- its solution owns or its columns bind — instead of every unmanaged option set in the environment.-- **A teardown fences any `--changed-only` run already in flight** ([#587]). Its tombstone kept the- snapshot's generation, so a run that had read the snapshot first could re-bless it over the- tombstone. A first build, which has no snapshot yet, is fenced too: it claims one before it builds,- and a teardown tombstones even a workspace with none. When two teardowns of one workspace overlap,- the fence stays until the last of them finishes, a `--changed-only` build waits while one is still- running — and a build that cannot resolve its live identity also refuses when one began while it was- looking — and `--clear-workspace` leaves a workspace that still holds the fence. Teardown now also- **refuses to delete anything when it cannot write that fence**, instead of warning and carrying on.- The workspace lease that guards the fence is never taken from a holder that is still alive, however- long it has held it: one paused mid-write, on a machine that slept, would otherwise commit its stale- view over the fence when it resumed. An old lease names the file to delete if its holder's pid was- reused by another process, and so does a reclaim of it abandoned by a crash: it is never removed by- another writer, which let two writers hold the lease. `--clear-workspace` clears under the same lease,- and only when no fence has appeared since the teardown finished. A build that another build or a- teardown ran alongside fails, and makes whatever snapshot it then finds ineligible; when even that is- refused, because the other writer holds the lease or the snapshot cannot be read, the refusal is- recorded beside the snapshot and the next `--changed-only` run builds in full.-- **Tearing down a downloaded spec keeps its relationships and global choices** ([#587]), as it- already kept its tables: a download flags all three `existing: true`. Deleting a relationship- removed its lookup column — and that column's data — from a table teardown kept.-- **An app in several unmanaged solutions downloads the same way every time** ([#587]). The spec keeps- `Default` and names the candidates in `solutionCandidates` — never whichever row the server happened- to return first, which teardown would then delete. Its business rules and option sets are still- reported across all of them, and a membership that cannot be read is reported as unknown. When the- candidates' publishers do not share one prefix, or the solutions or a publisher cannot be read — the- one solution's included — the spec's publisher prefix is not guessed from the app name: it stays the- unverified `new`, relationships keep their deployed names, and the download says to set it.-- **The teardown summary no longer calls every skip "not found".** Steps kept on purpose and steps- never attempted after a failed app delete are counted as what they are.-- **A failure after the app is already deleted no longer strands the rest of the teardown.** The SDK- tidies its local copy after the remote delete; when that step failed, teardown stopped as though- the app still existed. It now asks the platform, and carries on when the app is gone.+- **Forms**: an explicit layout reshapes a form instead of flattening it ([#575]); a named section+ moves to the tab the spec puts it in; spans converge against the live grid ([#581]) without breaking+ a maker's row-spanning layout; the wireframe shows `hidden` and `readOnly` fields ([#591]).+- **Business rules**: `dataType` reaches Dataverse as a real type. Rebuild any app whose+ `businessRules[]` were built on an earlier release.+- **Verify** checks form layout, sort precedence, sitemap-table membership, the default Main form,+ view filters and app roles, and judges spans by the build's own rules.+- **`/genpage`** deploys through the quoting-safe upload path ([#589]), keeps multi-line prompts+ ([#565]) and a page's bindings on update, refuses to update a page that does not exist, runs only+ the approved plan ([#585]), catches truncated pages, and checks page file names before any worker+ writes ([#588]).+- **Page listings, page ids and PAC errors** are parsed strictly, so a page name cannot forge a+ listing and PAC's real error is reported.+- **Icons and navigation calls are checked from code, not prose** ([#585], [#588]), and right-to-left+ layout follows PAC's RTL column rather than a fixed list of languages ([#585]).+- **Downloads** round-trip Choice columns ([#564]), relationships ([#567]) and page table bindings,+ invent no columns ([#574]), pass their own lint ([#572]), and pick an app's solution+ deterministically ([#587]).+- **Dashboards**: same-named charts on different tables no longer cross-wire a tile, and a dashboard+ belongs to an app through its solution ([#586]).+- **Teardown and workspaces**: `--clear-workspace` deletes only a real workspace; teardown stops when+ the app delete fails, keeps a downloaded spec's relationships and choices and any security role whose+ sharing check cannot be read, and fences in-flight `--changed-only` runs ([#587]).+- **Links**: `generate-page-manifest --force` refuses to write through a symlink or hard link, and+ `genpage-upload.js` refuses an input file that is a link, a hard link or a folder.+- **Writes**: a slow one is waited for (up to 5 minutes) rather than re-sent.+- **Validation**: a mistyped flag fails instead of changing the command, and sample data is checked+ before anything deploys.+- **The vendored SDK is refreshed** (including `@xmldom/xmldom` 0.8.15); an app with an unpublished+ sitemap edit can now be torn down.-### Changed+### Known limitations++- **Choice option values do not round-trip**: labels and order do, and a fresh rebuild re-bases the+ values to `100000000 + index`.+- **An existing view's authored filters and sort are not re-applied** by a rebuild.-- **`/app-builder` is GA.** The App Spec shape, the CLI flags and the build phases are now a stable- contract. `--changed-only` remains experimental and off by default.-- **Connector authoring is GA and on by default.** The `connectors` flag is flipped to `true` and- kept for one release as a rollback switch (`GENPAGE_ENABLE_CONNECTORS=0`), then removed.- `custom-api` and `custom-telemetry` are unaffected and still default-OFF.-- **The Phase 4.5 dispatch value is the binding count, not the flag state**, so the dispatch stays- stable when the flag is removed.-- **The App Spec schema is split** so the always-read half is smaller: 105 KB → 82 KB.-- **The CLI flag contract is shared** rather than per-script, so the rules and the "did you mean"- suggestion cannot drift between commands.-- **Deeper tests on the paths connectors GA made live**, including a connector *edit* eval.--[#541]: https://github.com/microsoft/power-platform-skills/issues/541[#544]: https://github.com/microsoft/power-platform-skills/issues/544[#559]: https://github.com/microsoft/power-platform-skills/issues/559[#564]: https://github.com/microsoft/power-platform-skills/issues/564@@ -381,51 +135,23 @@ downloads that round-trip Choice columns.[#588]: https://github.com/microsoft/power-platform-skills/issues/588[#589]: https://github.com/microsoft/power-platform-skills/issues/589[#591]: https://github.com/microsoft/power-platform-skills/issues/591-## [2.7.1]Three defects an author hits before reaching an environment, and a session-start warning.### Added-- **`scripts/lint-app-spec.js` — lint and validate a spec without touching an environment** ([#560]).- `validateAppSpec` (the gate `--apply` enforces) and `lintAppSpec` (the authoring guardrails) were- library exports with no entry point, so a headless author or a CI job had to reach in with- `node -e`. The CLI runs migrate → validate → lint, tags each finding `schema:` or `lint:`, and- exits non-zero on errors. `--profile` defaults to `plan` (pages may still be intents), so gate a- final, deployable spec with `--profile deploy`. `--strict` also fails on warnings; `--json`- emits the report. Argument handling is deliberately strict — an unknown flag, or `--spec`/- `--profile` given without a value, is a usage error, never a silent fall back to the default- profile a CI job did not ask for.+- **`scripts/lint-app-spec.js`** lints and validates a spec without an environment ([#560]). Use+ `--profile deploy` for a final spec, `--strict` to fail on warnings, and `--json` for a report.### Fixed-- **A spec that declares `schemaVersion` per page but not at the top level no longer breaks every- page reference** ([#545]). Migration mints a stable key per page, and it did so *unconditionally* —- overwriting hand-authored keys with a slug of the page name. The references hold keys, not names,- so nothing rewrote them and validation reported one "not a known page key" / "unknown page" error- per page, none of which named the cause. Authored keys now survive migration; a key is minted only- for a page that has none, and every authored key is reserved first so a minted one cannot steal it.-- **A `//` or `/* */` comment inside a JSX opening tag no longer makes a valid page look truncated**- ([#542]). `jsxTag` mode had no comment handling, so an apostrophe in the comment prose was read as- an attribute-value quote — and that scanner does not stop at a newline, because a JSX attribute- value legitimately may span lines. It ran to end of file, blanking the real `export default` and- miscounting every bracket after it, so `promote-intent-pages` rejected a complete page as- truncated. Promotion is transactional, so one such page blocked the whole batch. Block comments- had the same defect, which the report did not cover.-- **`eq-businessid` / `ne-businessid` are accepted in a view filter** ([#546]). Both are value-less- FetchXML operators — the business-unit equivalents of `eq-userid` / `ne-userid` — and the lint- demanded a value they must not carry. The operator list is now the documented value-less set,- which also adds `eq-userlanguage`, the user-hierarchy operators, and the relative fiscal-period- ones. The reverse case now warns: a value-less operator that *carries* a value is not rejected by- Dataverse, it is ignored — so the filter silently does not do what the value says. An operator- outside the documented set also warns, with a "did you mean" hint, instead of being reported as- needing a value it cannot take.-- **No more `hooks.json: unknown key "_comment" ignored` at every session start** ([#555], [#558],- affects `model-apps` and `mobile-apps`). The hooks manifest is validated against a closed schema,- so the documentation key it carried was reported as a misconfiguration on every launch. The prose- moved to `hooks/README.md`, and a repo-wide CI check now fails any manifest with an unrecognised- top-level key — the symptom is otherwise invisible to both tests and review.+- **A per-page `schemaVersion` no longer breaks page references** ([#545]): migration keeps+ authored page keys.+- **A comment inside a JSX tag** no longer makes a valid page look truncated ([#542]).+- **Value-less FetchXML operators** such as `eq-businessid` are accepted ([#546]), and one given a+ value now warns.+- **No more `hooks.json: unknown key "_comment"` warning** at session start ([#555], [#558]).[#542]: https://github.com/microsoft/power-platform-skills/issues/542[#545]: https://github.com/microsoft/power-platform-skills/issues/545@@ -433,7 +159,6 @@ Three defects an author hits before reaching an environment, and a session-start[#555]: https://github.com/microsoft/power-platform-skills/issues/555[#558]: https://github.com/microsoft/power-platform-skills/issues/558[#560]: https://github.com/microsoft/power-platform-skills/issues/560-## [2.7.0]Multi-language Dataverse labels, granting access on roles this spec does not own, and the@@ -441,101 +166,44 @@ app-builder defects found while rebuilding a real app into a second environment.### Added-- **Localized Dataverse metadata labels** (AB#6686428, [#537]). Any author-facing name — a table's- `displayName`/`pluralName`, its primary column's, a column's, a lookup's, an alternate key's, an- inline Choice option's — may be a map keyed by LCID instead of a string:-- ```jsonc- "displayName": { "1033": "Project Baseline", "3082": "Línea base del proyecto" }- ```-- A single-language label stays a plain string, so no existing spec changes shape. Three rules:- `globalChoices[]` is **rejected** (Dataverse stores only the base language there — use an inline- Choice on the column); a language **tag** (`"es-ES"`) is rejected rather than guessed; and a- localized `displayName` requires an explicit `pluralName`, because appending `"s"` is not a plural- rule outside English. An LCID the organization has not provisioned halts the build.- See `references/app-spec-schema.md` → *Localized labels*.-- **`roleGrants[]` — extend a security role you did not author** (AB#6686429). Adds privileges to a- role that already exists, typically the ones an existing solution ships; `personas[]` remains the- surface for roles the spec owns. **Additive and one-way**: dropping the entry does not revoke, and- teardown never removes one. An unknown, ambiguous or stale role halts the build rather than- skipping, because granting on the wrong role is a silent access defect.-- **`businessProcessFlows[].securityRoles` — who may run a flow** ([#513]). Same persona idiom as- `forms[].securityRoles`. The grant lands on the flow's activation-created backing table, so there- is no `scope` to author, and `securityRoles` on a **Draft** flow is rejected — the table does not- exist until activation.+- **Localized labels** (AB#6686428, [#537]): an author-facing name may be a map keyed by LCID, e.g.+ `{ "1033": "Project Baseline", "3082": "Línea base del proyecto" }`. Not for `globalChoices[]`;+ see `references/app-spec-schema.md` → *Localized labels*.+- **`roleGrants[]`** adds privileges to an existing role the spec does not own (AB#6686429). It is+ additive and one-way.+- **`businessProcessFlows[].securityRoles`** chooses who may run a flow ([#513]).### Fixed-- **AI features are written even when an org readiness gate reads off** (AB#6688904). The gate was a- precondition, and for four of the seven features that "gate" is the per-app row the write is about- to set — so a new app looked forbidden and the build reported success having written nothing. Every- write is now attempted and verified, a gate is read only to explain an absence, and the write is- re-issued after publish (no app-scope write persists before that).-- **Localized labels were silently discarded on the real build path.** A broad metadata read issued- immediately before a create makes Dataverse keep only the base-language label, and the request body- is identical either way, so nothing reported the loss. The three create paths now use narrow reads.- The column path is the one reached when adding a column to an existing table.-- **A requested row summary that was never created now FAILS verification** (AB#6689110). Build,- verify and teardown share one selector and one AI opt-in test, so what is verified is exactly what- was asked for, and a spec with no `ai` block is not checked for summaries at all.-- **Teardown removes a row summary the build created by default.** It planned that removal only for- an explicit `ai.summaries` block, so for a spec carrying only `ai.appFeatures` the orphaned AI model- blocked the table delete — teardown finished *with errors* and left the table and its data behind.-- **An SVG in a sitemap subarea's legacy `icon` is flagged** (AB#6688906), naming the `vectorIcon`- replacement; a raster `icon` beside a vector one stays legal as a deliberate fallback. A sitemap- attribute you remove from the spec is now removed from the deployed sitemap instead of surviving.-- **A workspace-metadata race no longer halts a multi-form build** (AB#6688905). Wiring form events- could start before the SDK had persisted that form's metadata file, failing with a bare `UNKNOWN`.- The read is retried; a persistent failure says it is a local race and that a re-run clears it.-- **`appendTo` no longer reports a false verification failure** — the access token was matched- case-sensitively against a lower-cased lookup, so a correctly granted role reported it as missing.-- **A download says what it did not bring back** (AB#6686423). `download-model-app` does not- reconstruct `forms[]`, `views[]`, `charts[]`, `businessRules[]` or `globalChoices[]`, and a spec- with `"forms": []` was indistinguishable from an app that has none. Runs now name the counts and- artifacts and return a `notRoundTripped` block. It is a note, not a gate: the loss is real only- when rebuilding into a *different* environment. Every inventory read that **fails** — a failed- table-label read, an unreadable business-rule or global-choice list, or a component page that hit- its cap — is reported as an UNKNOWN class rather than an empty one, so "we could not look" never- reads as "the app has none".-- **An inactive row-summary model no longer verifies clean.** The AI model row is created before it- is published, so an environment that does not license the capability leaves a committed but- unusable row behind; matching on the name alone reported PASS for a summary nobody can run.-- **The Azure CLI identity is checked before any Dataverse read** (AB#6686427). A token from the- wrong tenant surfaced as an *empty download* — every best-effort read swallowed its 401. A terminal- 401 now names the identity, tenant and environment (AB#6686424); a re-`az login` is the only fix,- because `az account get-access-token` is MSAL-cached.-- **Default-form promotion is deterministic** (AB#6686426) — building several Main forms in parallel- could leave whichever finished last as the default. It now honours `forms[].isDefault`.-- **The complete form-id map is signposted** (AB#6686425): `created.formIds`, keyed- `entity|type|name`. The ids were never lost — `created.forms` is a Main-form-only convenience map.-- **A download no longer emits a raw Dataverse Label object as a column name**; an unlabelled- synthetic lookup column is omitted instead of failing the spec's own validation.+- **AI features are written and verified even when a readiness gate reads off** (AB#6688904).+- **Localized labels are no longer discarded** when a table or column is created.+- **Row summaries**: a missing one fails verification (AB#6689110), an inactive model no longer+ verifies clean, and teardown removes one the build created by default.+- **Sitemap**: an SVG in a legacy `icon` is flagged (AB#6688906), and a removed attribute is removed.+- **A multi-form build no longer halts on a workspace-metadata race** (AB#6688905).+- **`appendTo` grants** no longer fail verification on letter case.+- **A download names what it did not bring back** (AB#6686423), and a failed read never reads as+ "none".+- **The Azure CLI identity is checked before any Dataverse read** (AB#6686427), and a 401 names it+ (AB#6686424).+- **Default-form promotion is deterministic** (AB#6686426), and `created.formIds` maps every form+ (AB#6686425).+- **A download no longer emits a raw Label object** as a column name.### Changed-- **SDK uptake `cds-maker-sdk 331b9f56`** — the platform halves of the bugs above: multi-language- label serialization, `formTypes` on the form listing, the additive `addEntityPrivilegesToRole`,- `setAppAiFeatures` no longer pre-empting a write, sitemap attribute removal, and retries around the- workspace file pair.-- **Two label rules relaxed** after they were measured to break specs that build correctly: a blank- plain-string label is accepted (every create site falls back to the schema name), and a duplicate- **plain** option label is a warning. A blank entry inside a localized map, and a cross-language- collision, still fail.-- **The role-privilege read moved onto the SDK's `getEntityPrivileges`**, retiring the last raw-HTTP- escape hatch in the app-builder scripts. No behaviour change — an unreadable privilege set still- fails the check closed.+- **SDK uptake `cds-maker-sdk 331b9f56`** for the platform halves of these fixes.+- **Two label rules are relaxed**: a blank plain label is accepted, and a duplicate plain option+ label warns.+- **The role-privilege read uses the SDK's `getEntityPrivileges`**, with no behaviour change.### Known limitations-- **A single-language label loses its LCID on download.** A table labelled only in, say, 3082 comes- back as a plain string, and a rebuild applies it at the target build's resolved language — correct- in the same organization, wrong in one with a different base language. Pin `languageCode` in the- spec before a cross-organization rebuild.+- **A single-language label loses its LCID on download.** Pin `languageCode` before a+ cross-organization rebuild.[#537]: https://github.com/microsoft/power-platform-skills/issues/537[#513]: https://github.com/microsoft/power-platform-skills/issues/513-## [2.6.1]### Fixed@@ -596,57 +264,34 @@ an environment that supports them**.### Changed-- **Business rules are environment-gated.** An environment that does not declare the SDK's bound- `CreateProcessWithWfomJson` member **cannot host business rules at all** — the common case. Such- rules are skipped with a warning, and `--verify` reports them as *not applicable on this- environment*.+- **Business rules are environment-gated.** Where the environment cannot host them they are skipped+ with a warning, and `--verify` reports them as not applicable.### Added-- **Generated pages can report to the customer's Application Insights** — behind the new default-OFF- `custom-telemetry` feature flag, via an optional `props.appInsights` surface. The flag is- permission, not instruction: even with it on, a page is instrumented only when the maker asked to- measure something, so existing prompts are unaffected. Ships OFF pending the host runtime,- authoring control, agent prompt and ECS setting. See `references/page-telemetry.md`. Unrelated to- the plugin's own usage telemetry (`/model-apps:telemetry`).-- **Per-form security roles** — `forms[].securityRoles`: offer a form to named `personas[]` or to- `everyone`. A form with no assignment is visible to **every** role, so this *restricts* a form; undo- with `everyone: true`, not by deleting the block. (AB#6648526)-- **Boolean `defaultValue`, whole-number `integerFormat`, and per-column `isValidForCreate` /- `isValidForUpdate` / `isValidForRead`** — the last is how you make a column read-only.- ([#495], AB#6648523, AB#6648522, AB#6651276)-- **Twelve more business-rule operators** and **multi-condition rules** (ANDed). Spelling matters:- `IsGreaterThan`, not `GreaterThan` — the SDK silently resolves an unknown operator to `Equals`, so- the spec rejects anything outside its table.-- **A `description` on every artifact that accepts one**, written at create time and omitted when- absent, so a rebuild never blanks text typed in the maker.-- **Per-field form control** — `readOnly`, `hidden` and `after`, via a form-level `fieldOptions` map- or inline on an explicit layout. `prune: false` edits part of a form without re-declaring it.-- **The AI form-fill family is controllable per capability** — assist toolbar, edit-form predictions,- smart paste and file upload, instead of one flag that only governed the toolbar.+- **Page telemetry to the customer's Application Insights**, behind the default-OFF+ `custom-telemetry` flag; see `references/page-telemetry.md`.+- **Per-form security roles**: `forms[].securityRoles` (AB#6648526).+- **Column options**: boolean `defaultValue`, whole-number `integerFormat`, and+ `isValidForCreate`/`isValidForUpdate`/`isValidForRead` ([#495], AB#6648523, AB#6648522, AB#6651276).+- **Twelve more business-rule operators**, and multi-condition rules.+- **A `description` on every artifact that accepts one**; leaving it out never blanks text typed in+ the maker.+- **Per-field form control**: `readOnly`, `hidden`, `after`, and `prune: false`.+- **AI form fill is controllable per capability.**### Fixed-- **A `businessRules[]`-only edit is no longer treated as "nothing changed"** under `--changed-only`- ([#478], which also fixes downloads losing dashboard tiles).-- **Descriptions converge on existing views and charts** — previously written only at create, so the- auto-created *"Active <Plural>"* view never got one ([#496]); **downloaded specs preserve- deployed descriptions** ([#494]).-- **Teardown removes the activated copy of a business rule**, previously stranding an undeletable- row ([#493]), and clears column visualizations for a table the spec keeps.-- **Existing columns honour an explicit `required` change on rebuild**; an omitted one leaves the- live column alone.-- **Big Integer columns are no longer auto-placed on forms** — they have no Unified Interface control- and rendered *"Error loading control"* on every record.-- **AI on/off is read with the platform's semantics** — `0` = platform default, `1` = disabled,- `2` = enabled. Treating any non-zero value as "on" reported a disabled feature as enabled.-- **Presence operators** (`ContainsData` / `DoesNotContainData`) deploy ([#481]).-- **`ai.summaries.default: "off"` no longer discards a per-table `enabled: true`**, and a- differently-cased `tables[]` key keeps its `instruction` and `columns`.-- **A row summary an environment cannot license is skipped, not fatal** — and the row the refused- publish leaves behind is swept, so a rebuild does not fail on a duplicate key.-- **A spec with no `appShell` reports what to add** instead of dying after the app was half-created.-- **A malformed `businessRules` is a validation error**, not a raw `TypeError`.+- **`--changed-only` notices a `businessRules[]`-only edit** ([#478]).+- **Descriptions converge** on existing views and charts ([#496]) and survive a download ([#494]).+- **Teardown removes a business rule's activated copy** ([#493]).+- **Rebuilds honour an explicit `required` change**, and Big Integer columns are no longer+ auto-placed on forms.+- **AI on/off settings are read with the platform's semantics.**+- **Presence operators deploy** ([#481]).+- **Row summaries**: per-table settings survive `default: "off"`, and one the environment cannot+ license is skipped.+- **A missing `appShell` or a malformed `businessRules`** is a validation error, not a crash.[#478]: https://github.com/microsoft/power-platform-skills/issues/478[#481]: https://github.com/microsoft/power-platform-skills/issues/481@@ -654,7 +299,6 @@ an environment that supports them**.[#494]: https://github.com/microsoft/power-platform-skills/issues/494[#495]: https://github.com/microsoft/power-platform-skills/issues/495[#496]: https://github.com/microsoft/power-platform-skills/issues/496-## [2.5.0]Takes up the current maker SDK, adds modern-shell and navigation controls, labels Dataverse@@ -663,94 +307,42 @@ and jobs-to-be-done checkable.### Added-- **`businessRules[]` — declarative form logic, no code.** Show/hide, lock/unlock, set-required and- set-value, gated on a condition over the record, activated on create. Every field is checked- against the rule's own entity, because a rule naming a column that does not exist is accepted by- the platform and then simply never fires. Operators `Equals` · `DoesNotEqual`.-- **Custom grid rendering (preview) — `entities[].columns[].visualization`.** Render a column as a- radial dial, line chart, heat map or star rating in every grid and view that shows it. Where the- platform has not provisioned the preview the build skips it and everything else still deploys.-- **`app.newLook` — opt into the modern ("new look") shell**, written as the per-app- `NewLookAlwaysOn` setting so the result is deterministic rather than a per-user preference.- Best-effort: a tenant without the definition still gets a working app, with a warning.-- **`app.headerNavigationRefresh` — control the Wave 2 header and navigation refresh.** A separate,- independent setting from `app.newLook`. The platform default is **ON**, so this exists as much to- turn the refresh off as on — `false` is written actively rather than treated as "do nothing".-- **Labels honour the authoring language everywhere** ([#447], [#455]) — tables, columns, choices,- **form, dashboard and sitemap labels**. Previously only the data-model phase respected it, so- `--language-code 1031` produced German columns and English form labels. Precedence:- `--language-code` → App Spec `languageCode` → the organization's base language → 1033.-- **An unprovisioned `languageCode` stops the build before any label is written** ([#456]), naming- the LCID you asked for and the ones the organization has. Dataverse otherwise fails- *inconsistently* — accepting it on tables and choices, rejecting it on `DateTime` and `Memo` — so- the build died phases away from the flag that caused it.-- **A hand-pinned `languageCode` survives download.**-- **`directEntry` on `pages[]`.** A page declaring `pageInput` must say what a no-input entry- renders: `{ "behavior": "selector" }` or `{ "behavior": "emptyState" }`. Every key in- `pageInput.data` must also be supplied by an incoming `navigatesTo[].data` edge.-- **`verify` proves what a persona security role GRANTS**, not just that the role exists — a subset- check by design, failing closed on an unreadable role or table.-- **`personas[].jobs[].surfaces[]` is checked, not documentary** — `spec-lint` warns when a surface- matches nothing, and `verify` reports a failure as the job it broke.-- **Automatic plugin update notice** — a non-blocking preflight when a newer version is available.+- **`businessRules[]`**: declarative show/hide, lock, require and set-value form logic.+- **Custom grid rendering (preview)** with `entities[].columns[].visualization`.+- **`app.newLook`** and **`app.headerNavigationRefresh`** settings.+- **Labels honour the authoring language everywhere** ([#447], [#455]), and an unprovisioned+ `languageCode` stops the build before any label is written ([#456]).+- **`directEntry` on `pages[]`** says what a page with `pageInput` shows without input.+- **`verify` checks persona role grants and `personas[].jobs[].surfaces[]`.**+- **An automatic plugin update notice.**### Fixed-- **Command buttons now actually run.** A JS command was created with no on-click parameters, so the- usual `function doThing(primaryControl)` shape threw on its first property access and the button- silently did nothing — with the build, the deployed rows and `--verify` all looking correct.- Buttons now receive the standard parameters for their location, overridable via `parameters`.-- **Business rules no longer mistake the platform's activated copy for a duplicate**, which made the- build warn about a duplicate that did not exist and teardown fail on it.-- **AI preflight no longer reports a running feature as disabled.** The readiness gate and a- feature's actual setting are different rows; preflight now resolves the effective value and stops- emitting an admin action for a feature that is already on.-- **Rebuilds no longer duplicate sub-grids or skip field removals.** The SDK's artifact surface became- asynchronous upstream, and un-awaited that fails *silently* — a promise is truthy, so guards never- fired, producing duplicate sub-grids, re-added fields and removals that never landed, all behind- `2xx` responses and a green build.-- **Dashboard chart tiles no longer fail the `dashboards` phase** — the tile emitted `ChartId` where- the FormXML schema requires `VisualizationId`.-- **Publish failures are no longer silent**, and **a partially-wrong push no longer reads as a clean- success** — including the case where an app's system-administrator role assignment fails, which- yields an app nobody can open.-- **A 412 version conflict could be swallowed**, dropping a concurrent Maker edit with no error.-- **A sitemap subarea targeting a custom web resource round-trips** ([#430]) — `$webresource:<name>`- was rejected by the URL guard, so **no spec file was written at all**, blocking the whole- download → edit → rebuild flow over one nav entry.-- **Malformed specs produce validation errors instead of raw `TypeError`s**, naming the exact path,- and can no longer pass validation and then crash *after* the solution and data model were written.-- **`verify-model-app` reports a missing table as a finding**, not a raw Dataverse HTTP 400.+- **Command buttons run**: they now receive their standard parameters.+- **Rebuilds no longer duplicate sub-grids or skip field removals.**+- **Dashboard chart tiles, publish failures, 412 conflicts and a failed admin-role assignment** are+ no longer silent.+- **A `$webresource:` sitemap subarea round-trips** ([#430]).+- **Malformed specs and missing tables** are reported as findings, not crashes.+- **AI preflight and business-rule duplicate detection** no longer misreport.### Changed-- **An app now requires an image icon.** The SDK's auto-resolve demands an **image** web resource,- failing with `APP_ICON_UNRESOLVED` rather than falling back to any unmanaged web resource- (including a **JavaScript** file, which the platform then rejected opaquely). No change for- `/app-builder`, which always passes one explicitly.-- **The vendored SDK records its provenance.** `scripts/vendor/PROVENANCE.json` carries the upstream- SHA and the bundle's own sha256, and the bundler **refuses** a stale, dirty or unidentifiable- source. "Built from master" is not provenance: a previously shipped bundle was built from a stale- build output several commits behind its nominal source, and nothing could reveal it.-- **Three SDK contract changes are user-visible**: `deleteAppCascade` no longer deletes generative- pages (they are *referenced* by an app, not owned by one, and are reported in `retained[]`);- unconditional artifact writes are refused (`ARTIFACT_UPDATE_NO_ETAG`); and `pushArtifact` /- `publishArtifact` report failure by value instead of throwing.-- **`download-model-app.js --app` accepts a display name**, and fails closed when one matches more- than one app.+- **An app requires an image icon** (`APP_ICON_UNRESOLVED` otherwise).+- **The vendored SDK records its provenance** in `scripts/vendor/PROVENANCE.json`.+- **SDK contract changes**: `deleteAppCascade` keeps generative pages, unconditional writes are+ refused, and push and publish report failure by value.+- **`download-model-app.js --app` accepts a display name.**### Known limitations-- **A classic dashboard does not survive `download-model-app.js`** — the vendored SDK throws while- deserializing the `<parameters>` block it itself serialized, so no tiles are recovered and the- download fails unless `--allow-lossy-download` is passed. Not a regression from this release's SDK- uptake; tracked upstream.+- **A classic dashboard's tiles are not recovered on download**; the download fails unless+ `--allow-lossy-download` accepts that loss.[#430]: https://github.com/microsoft/power-platform-skills/issues/430[#447]: https://github.com/microsoft/power-platform-skills/issues/447[#455]: https://github.com/microsoft/power-platform-skills/issues/455[#456]: https://github.com/microsoft/power-platform-skills/issues/456-## [2.4.2]Fixes a malformed app module: generated apps did not actually contain their tables.diff --git a/plugins/model-apps/README.md b/plugins/model-apps/README.mdindex db09ae273..9b8a7af79 100644--- a/plugins/model-apps/README.md+++ b/plugins/model-apps/README.md@@ -39,13 +39,10 @@ status) in `scripts/lib/feature-flags.js`; their on/off value lives in| Flag | Status | Enables | Depends on ||---|---|---|---|-| `connectors` | **ga (on by default)** | GenPage connector authoring (SharePoint, weather, Office 365, SQL, custom REST) + ALM packaging of connection references | pac CLI connector verbs, the GenUX authoring control, and the maker/admin ECS setting — all live in PROD || `custom-api` | in-progress | Calling a Dataverse Custom API Action or Function from a generated page (`executeAction` / `executeFunction` / `listBoundActions`) | the AIBuilder action prompt, the shared action runtime, the UCI and Controls host runtimes, a pac CLI `model genpage upload --actions` verb, and the `GenUxPluginActionAllowList` setting — all live in PROD || `custom-telemetry` | in-progress | A generated page reporting its own events, metrics, traces and exceptions to your Application Insights resource via `props.appInsights` | the page telemetry facade in the UCI host runtime, the GenUX authoring control, the AIBuilder telemetry prompt, and the `GenUxEnableCustomTelemetry` setting — all live in PROD |-Connector authoring is **GA and on by default**. Its flag is kept for one release as a-rollback switch: set `GENPAGE_ENABLE_CONNECTORS=0` (or `"connectors": false`) if your-environment turns out to be missing one of the dependencies above.+Connector authoring is in **public preview** and no longer has a feature flag. Connector discovery, binding, deploy, and ALM packaging are always available when the required PAC and host capabilities are present.**See the current state** (status, whether each flag is on, and why):@@ -74,7 +71,9 @@ export GENPAGE_ENABLE_CUSTOM_API=1Precedence is **env var → `feature-flags.json` → default OFF** (fail-closed). Onlyturn a flag on once its "Depends on" items are actually available in yourenvironment — otherwise the feature's commands will fail with a clear "disabled" or-capability error. The env var name is always `GENPAGE_ENABLE_<FLAG>` (uppercased).+capability error. The env var name is always `GENPAGE_ENABLE_` plus the flag name in upper case, with+`-` turned into `_` (`custom-api` → `GENPAGE_ENABLE_CUSTOM_API`), and unknown flags stay disabled even if+a matching env var is set.## Skillsdiff --git a/plugins/model-apps/agents/genpage-connector-builder.md b/plugins/model-apps/agents/genpage-connector-builder.mdindex 7b88dd4a8..a079a3b92 100644--- a/plugins/model-apps/agents/genpage-connector-builder.md+++ b/plugins/model-apps/agents/genpage-connector-builder.md@@ -1,9 +1,8 @@---name: genpage-connector-builderdescription: >-- Owns ALL GenPage connector work: it is the single owner of the connectors- rollback gate, performs connector discovery (connections, connection- references, datasets, tables, operations, and schema), creates Dataverse+ Owns ALL GenPage connector work: performs connector discovery (connections,+ connection references, datasets, tables, operations, and schema), creates Dataverseconnection references when needed, and produces the ## Connector Bindingscontract. Invoked only by the top-level genpage orchestrator from BOTH thecreate and edit flows; never invoked by planners or directly by users.@@ -51,9 +50,9 @@ not repeat the reads. Full contract: `references/agent-interaction-contract.md`.# Genpage Connector BuilderYou are the connector specialist for generative pages. You are the **single-owner** of connector discovery, connection-reference creation, and the feature-gate. Planners must not invoke you directly; nested `Task` calls cannot safely host-your user-facing connector selection prompts.+owner** of connector discovery and connection-reference creation. Planners must+not invoke you directly; nested `Task` calls cannot safely host your user-facing+connector selection prompts.Your discovery is **mutating** (it can create a connection reference), and areference created in the wrong environment or the wrong mode cannot be undone. So@@ -106,33 +105,7 @@ forward the entire `connector-bindings.md` body and the `connectors.json` path (Log every command you run (with its purpose) into the working directory's`workflow-log.md`.-## Step 1 — Rollback gate (you own it; run it FIRST, always)--Probe the flag before ANY discovery, for both create and edit:--```powershell-node "${PLUGIN_ROOT}/scripts/lib/feature-flags.js" connectors-```--Record the result in `workflow-log.md` (e.g. `feature-flags.js connectors → enabled`).--Connectors are **GA and the flag ships ON**, so this normally prints `enabled` and you-continue to Step 2. The gate is retained for one release as a rollback switch, so handle-the off case:--**If it prints `disabled` (exit 1)** — connector support has been explicitly turned off-(`GENPAGE_ENABLE_CONNECTORS=0`, or `"connectors": false` in `feature-flags.json`):--- Do **not** run `list-connections.js` or any other connector discovery.-- **create:** write `connector-bindings.md` containing exactly- `No connector bindings.` and `connectors.json` containing `[]`. Return- `connectors disabled — no bindings`.-- **edit:** you must **not add or discover** new bindings. **Preserve** the existing- bindings passed to you: write them unchanged to `connectors.json` (bare array) and- reproduce them in `connector-bindings.md`. Return- `connectors disabled — existing bindings preserved, none added`.--## Step 2 — Connection discovery (enabled only)+## Step 1 — Connection discoveryIf the intent implies a non-Dataverse source (SharePoint, Teams, weather, Office365, SQL via connector, a custom REST connector, …), enumerate what exists:diff --git a/plugins/model-apps/agents/genpage-edit-planner.md b/plugins/model-apps/agents/genpage-edit-planner.mdindex b554b76ca..02cc60587 100644--- a/plugins/model-apps/agents/genpage-edit-planner.md+++ b/plugins/model-apps/agents/genpage-edit-planner.md@@ -154,7 +154,7 @@ at a time (you are headless — see the interaction contract below):> **Connector data changes** (SharePoint, weather, Office 365, SQL, custom REST):> Do **not** run connector discovery here — the orchestrator delegates that to the-> `genpage-connector-builder` agent (which owns connector discovery and its rollback gate).+> `genpage-connector-builder` agent (which owns connector discovery).>> - **Preserving or clearing** existing connectors needs no discovery: capture it> in the plan's `### Connector Changes` and continue.diff --git a/plugins/model-apps/agents/genpage-planner.md b/plugins/model-apps/agents/genpage-planner.mdindex d5ad73816..beb4552e7 100644--- a/plugins/model-apps/agents/genpage-planner.md+++ b/plugins/model-apps/agents/genpage-planner.md@@ -292,9 +292,8 @@ Two cases:environment or the wrong mode cannot be undone. Return this only after yourauth/environment steps have run, so both values are real.-`genpage-connector-builder` remains the single owner of the connectors rollback gate,-connection / connection-ref discovery, connection-reference creation, and the binding-contract. When no connectors are involved, write the exact sentinel+`genpage-connector-builder` remains the single owner of connection / connection-ref+discovery, connection-reference creation, and the binding contract. When no connectors are involved, write the exact sentinel`No connector bindings.` into the plan.When the orchestrator forwards results it provides:diff --git a/plugins/model-apps/docs/app-builder-capabilities.md b/plugins/model-apps/docs/app-builder-capabilities.mdindex 0af4a2ea2..ba873586a 100644--- a/plugins/model-apps/docs/app-builder-capabilities.md+++ b/plugins/model-apps/docs/app-builder-capabilities.md@@ -109,6 +109,12 @@ apart deliberately.(AB#6648526)- Form JS event handlers (`onload`/`onsave`/`onchange`) wired via web resources.- Views with rich filters (`eq-userid`/`this-week`/`in`/`not-in`/… + Choice-label resolution); default Active/Inactive view **column enrichment** via the SDK's `enrichDefaultViews`.+- **Editing an existing view is additive.** A rebuild appends spec columns the view lacks and keeps+ every column already there, so a column a maker added in the designer survives — and a column+ removed from the spec, or a new order, does not apply. Filters and sort are not re-applied either+ (the build warns). `--verify` fails on a missing spec column, filter condition or sort key (or+ authored sort keys out of order), but not on extra deployed ones, so it cannot confirm a removal. Remove or reorder view columns in Maker, or+ tear down and rebuild.- Choice-column charts.### Custom grid rendering (preview) — ✅ SDK live-verified, environment-gated@@ -213,15 +219,19 @@ apart deliberately.(by logical name) and **halts** naming whichever owns it, instead of letting the create fail with aplatform error about a table the author never mentioned. It runs only on the create path, never onreuse, and is best-effort — a diagnostic must never be the thing that breaks a build.-- **v1 is single-entity and linear on purpose.** The SDK also models cross-entity stages, branching,- stage actions and security-role grants; the spec gate **rejects** those keys — as an allow-list at- flow, stage *and* step level — rather than ignoring them, so a flow never quietly deploys as- something other than what was authored. The allow-list shape matters: the SDK's normalizers copy a- fixed key set and discard the rest, so a stage `branch` or a step's `fieldLogicalName` (instead of- `field`) would otherwise pass validation and deploy bound to nothing. `securityRoles` needs role ids- and belongs to the `security` phase (a BPF's grants are privileges on the backing table that- activation creates) — tracked in- [#513](https://github.com/microsoft/power-platform-skills/issues/513).+- **v1 is single-entity and linear on purpose.** The SDK also models cross-entity stages, branching+ and stage actions; the spec gate **rejects** those keys — as an allow-list at flow, stage *and* step+ level — rather than ignoring them, so a flow never quietly deploys as something other than what was+ authored. The allow-list shape matters: the SDK's normalizers copy a fixed key set and discard the+ rest, so a stage `branch` or a step's `fieldLogicalName` (instead of `field`) would otherwise pass+ validation and deploy bound to nothing.+- **Who may run a flow** — `securityRoles: { "personas": [...] }` (#513). A flow's grants are+ `create/read/write/delete` privileges on the backing table that activation creates, so they are+ applied in the `security` phase once both the flow and the personas' roles exist, against the+ flow's deployed `uniquename` read back rather than derived. `verify-model-app` proves each persona+ holds them (`bpf-roles`) and fails closed when the backing table cannot be read. Rejected: an empty+ `personas` list, the form-only keys `everyone`/`fallbackForm`/`order`, and grants on a Draft flow+ (there is no backing table until activation).- **Live-verified**: build (11 created, verify 8/8), rebuild (flow reused, solution componentre-added), and teardown (exit 0, with an independent query confirming both the workflow row and itsactivation-created backing table are gone). An invalid spec is refused pre-flight with no writes.@@ -238,7 +248,7 @@ apart deliberately.test here and by a `@jest-environment node` regression upstream.### Edit flow (download → edit → rebuild) — ✅ verified live-- `download-model-app.js` pulls a **deployed app** back into an editable App Spec (+ page code, icons, referenced entities, and the app's **real unmanaged solution** — `recoverAppSolution` enumerates the app's solution memberships and excludes the built-in `Active`/`Default`/`Basic` system solutions, so the spec names the right container for a later clean teardown); edit the spec and re-run the idempotent build — **create and edit share one path** (reuses app/tables, updates pages in place, keeps `GenPage` subareas). The app-shell phase **re-syncs the sitemap + components of any existing app** (fetch → recompute-from-spec → push → publish), so subarea add/rename/reorder edits land for **page-less apps too** — not just generative-page apps — and `--only app-shell` can force the rewrite. **Classic DashBoard subareas are *designed* to round-trip** — the dashboard is reconstructed into `dashboards[]` with **id-passthrough tiles** (each tile carries the deployed view/chart ids), so a rebuild recreates it against the existing views/charts without re-declaring them. **This now works end to end.** It previously did not: the vendored SDK’s `fetchArtifact(‘dashboard’, …)` threw `Cannot read properties of null (reading ‘length’)` while deserializing the `<parameters>` block it had itself serialized, so no tiles were recovered and the subarea was dropped — which failed the whole download unless `--allow-lossy-download` was passed. Root cause upstream: the grammar walk descended into **text** nodes, and the bundled XML parser returns `null` for a text node’s children. Fixed in the SDK and re-vendored; measured across the re-vendor as **0/4 → 4/4** round-trips (list tile, both chart-parameter spellings, and a tile with an empty parameter value), and pinned by `scripts/tests/dashboard-roundtrip.test.js`, which feeds a serialized dashboard straight back in. ([#478](https://github.com/microsoft/power-platform-skills/issues/478)) **Round-trip scope (not yet "complete"):** tables, sitemap/appShell, generative pages, icons, dashboards, and solution round-trip; **forms, views, charts, and commands do NOT yet** — view hydration was tried and reverted (LIVE-verified the deployed savedquery set can't reliably distinguish author views from Dataverse's auto-generated Active/Inactive/QuickFind system views). All survive on the live app (a rebuild preserves them by discovery) but are absent from the downloaded spec, so edit them in Maker or a fresh spec. **Column types round-trip too, including Choice/MultiChoice** — their option sets are read per table, a local set becoming inline `options[]` (localizations preserved) and a shared one a `globalChoice` reference plus a `globalChoices[]` declaration; a column whose option set cannot be read is left untyped *and named*, and the App Spec cannot express option **values**, so a fresh rebuild re-bases them to `100000000 + index`. **`relationships[]` are NOT reconstructed** and their omission is not yet reported ([#567](https://github.com/microsoft/power-platform-skills/issues/567)) — a downloaded spec rebuilt into a fresh environment creates the tables without the lookups between them.+- `download-model-app.js` pulls a **deployed app** back into an editable App Spec (+ page code, icons, referenced entities, and the app's **real unmanaged solution** — `recoverAppSolution` enumerates the app's solution memberships and excludes the built-in `Active`/`Default`/`Basic` system solutions, so the spec names the right container for a later clean teardown); edit the spec and re-run the idempotent build — **create and edit share one path** (reuses app/tables, updates pages in place, keeps `GenPage` subareas). The app-shell phase **re-syncs the sitemap + components of any existing app** (fetch → recompute-from-spec → push → publish), so subarea add/rename/reorder edits land for **page-less apps too** — not just generative-page apps — and `--only app-shell` can force the rewrite. **Classic DashBoard subareas are *designed* to round-trip** — the dashboard is reconstructed into `dashboards[]` with **id-passthrough tiles** (each tile carries the deployed view/chart ids), so a rebuild recreates it against the existing views/charts without re-declaring them. **This now works end to end.** It previously did not: the vendored SDK’s `fetchArtifact(‘dashboard’, …)` threw `Cannot read properties of null (reading ‘length’)` while deserializing the `<parameters>` block it had itself serialized, so no tiles were recovered and the subarea was dropped — which failed the whole download unless `--allow-lossy-download` was passed. Root cause upstream: the grammar walk descended into **text** nodes, and the bundled XML parser returns `null` for a text node’s children. Fixed in the SDK and re-vendored; measured across the re-vendor as **0/4 → 4/4** round-trips (list tile, both chart-parameter spellings, and a tile with an empty parameter value), and pinned by `scripts/tests/dashboard-roundtrip.test.js`, which feeds a serialized dashboard straight back in. ([#478](https://github.com/microsoft/power-platform-skills/issues/478)) **Round-trip scope (not yet "complete"):** tables, sitemap/appShell, generative pages (code, prompt and data sources; a page's connector and Custom API bindings stay on the deployed page but are not carried in the spec, so they survive a same-environment rebuild only), icons, dashboards, and solution round-trip; **forms, views, charts, and commands do NOT yet** — view hydration was tried and reverted (LIVE-verified the deployed savedquery set can't reliably distinguish author views from Dataverse's auto-generated Active/Inactive/QuickFind system views). All survive on the live app (a rebuild preserves them by discovery) but are absent from the downloaded spec, so edit them in Maker or a fresh spec. **Column types round-trip too, including Choice/MultiChoice** — their option sets are read per table, a local set becoming inline `options[]` (localizations preserved) and a shared one a `globalChoice` reference plus a `globalChoices[]` declaration; a column whose option set cannot be read is left untyped *and named*, and the App Spec cannot express option **values**, so a fresh rebuild re-bases them to `100000000 + index`. **`relationships[]` are NOT reconstructed** and their omission is not yet reported ([#567](https://github.com/microsoft/power-platform-skills/issues/567)) — a downloaded spec rebuilt into a fresh environment creates the tables without the lookups between them.- Live regression on the edit path found + fixed **4 bugs**, then re-verified clean.- `verify-model-app.js` — read-only reconcile of spec vs deployed (exits non-zero on anything missing). Sitemap checks are **element-scoped**: an area/subarea icon is matched on its own `<Area>`/`<SubArea>` element, and a **dashboard subarea** is verified by resolving the dashboard id (systemform type 0, by name) and matching the sitemap's `DefaultDashboard` — so a value reused elsewhere can't produce a false pass. **Multi-area sitemaps** and the dashboard-subarea path were re-verified live (positive + negative).diff --git a/plugins/model-apps/docs/app-builder-design.md b/plugins/model-apps/docs/app-builder-design.mdindex e2b602269..909a484db 100644--- a/plugins/model-apps/docs/app-builder-design.md+++ b/plugins/model-apps/docs/app-builder-design.md@@ -299,12 +299,12 @@ Reuse `/genpage`'s navigation contract (`references/rules.md` 299–356): naviga**Source stays symbolic.** Code-gen emits `PAGEREF_<page-key>` and the **canonical `.tsx` is nevermutated** with a GUID (mutation would bake environment-specific ids into source and breakcross-env deploy / recreate — reviewer C4, SDK **T5** opaque-identity). Because `genpageCli.upload`-takes a **file path**, not in-memory content (`genpage-cli.js:77-86`), the resolver writes a+takes a **file path**, not in-memory content (`genpage-cli.js`, `upload()`), the resolver writes a**staging file** (a deployment copy adjacent to `RuntimeTypes.ts`); the canonical source is leftuntouched.**Deployment protocol (safe recovery — new Critical from R2).** `listPages` currently turns any PAC-failure into `[]` (`genpage-cli.js:67-70`), which the engine treats as "no pages" — risking+failure into `[]` (`genpage-cli.js`, `listPages()`), which the engine treats as "no pages" — riskingduplicates and orphans. The `app` stage instead:1. **Enumerate fail-closed** — page listing retries and **distinguishes failure from empty**; a@@ -347,9 +347,9 @@ the model-driven shell today. Scope honestly:Consent is mode-aware; **autopilot mode is also eval mode** (both non-interactive).**The problem the first draft missed:** `--allow-destructive` was not tied to any real diff, and-`--non-interactive` on the CLI cannot gate main-loop questions. Meanwhile updates already remove-content — collision is warning-only (`build-model-app.js:111-119`), explicit-form fields are-pruned (`sdk-build.js:690-725`), and the sitemap is fully replaced (`:995-1007`); teardown is+`--non-interactive` on the CLI cannot gate main-loop questions. Meanwhile updates already removed+content — collision was warning-only (`build-model-app.js:111-119`), explicit-form fields were+pruned (`sdk-build.js:690-725`), and the sitemap was fully replaced (`:995-1007`); teardown wasgated by `--apply` alone (`teardown-model-app.js:62-95`).**The fix — a read-only operation-diff planner (`op-diff.js`, new pure module):**@@ -370,8 +370,12 @@ gated by `--apply` alone (`teardown-model-app.js:62-95`).- **Hard gate + TOCTOU:** any destructive op without `--allow-destructive` **halts before writes**(incl. teardown). Recompute the diff **immediately before apply** so a state change between planand apply can't slip through.-- **Approval binding:** bound to **env/app identity + spec hash + op hash**; not replayable against a- different target.+- **Approval binding:** a refused apply records the exact removals it listed in+ `.maker-workspace/destructive-approval.json` (each form's fields, the sitemap targets, and the run+ that wrote it). The approved re-run removes only those and halts, naming the new ones, if anything+ else would now be removed. An approved run rewrites or consumes the record only if it found it at+ its start or wrote it, so a concurrent build cannot consume it; a new refusal replaces it with the list+ that refusal showed, and a halt naming new removals refreshes it with the full current list.- **Env var suppresses questions only** — never grants destructive authority; `--allow-destructive`is always explicit, even in autopilot.diff --git a/plugins/model-apps/feature-flags.json b/plugins/model-apps/feature-flags.jsonindex b02f3f463..b7d1f7705 100644--- a/plugins/model-apps/feature-flags.json+++ b/plugins/model-apps/feature-flags.json@@ -1,6 +1,5 @@{- "_comment": "Feature flags for the /genpage skill. Unreleased features ship OFF so the skill behaves identically to production until the full cross-repo stack is live in PROD. connectors is GA and ships ON; its gate is kept for one release as a rollback switch and is scheduled for removal.",- "connectors": true,+ "_comment": "Feature flags for the /genpage skill. Unreleased features ship OFF so the skill behaves identically to production until the full cross-repo stack is live in PROD.","custom-api": false,"custom-telemetry": false}diff --git a/plugins/model-apps/hooks/run-skill-posttool-validation.js b/plugins/model-apps/hooks/run-skill-posttool-validation.jsindex a34652922..dbcb59190 100644--- a/plugins/model-apps/hooks/run-skill-posttool-validation.js+++ b/plugins/model-apps/hooks/run-skill-posttool-validation.js@@ -21,6 +21,7 @@ const { spawnSync } = require('child_process');const {getTrackedSkillFromToolInput,getValidatorScript,+ readUtf8Stream,} = require('../scripts/lib/modelapps-hook-utils');const DEBUG = process.env.DEBUG === '1' || process.env.DEBUG === 'true';@@ -38,13 +39,7 @@ function debug(msg) {debug('[model-apps hook] run-skill-posttool-validation.js started\n');-let inputData = '';--process.stdin.on('data', (chunk) => {- inputData += chunk;-});--process.stdin.on('end', () => {+readUtf8Stream(process.stdin).then((inputData) => {debug(`[model-apps hook] stdin closed, received ${inputData.length} bytes\n`);try {const input = JSON.parse(inputData);@@ -79,4 +74,7 @@ process.stdin.on('end', () => {process.stderr.write(`[model-apps hook] Unexpected error: ${err.message}\n`);process.exit(0);}+}).catch((err) => {+ process.stderr.write(`[model-apps hook] Unexpected error: ${err.message}\n`);+ process.exit(0);});diff --git a/plugins/model-apps/hooks/validate-icon-imports.js b/plugins/model-apps/hooks/validate-icon-imports.jsindex eb32c9093..1c3c1b990 100644--- a/plugins/model-apps/hooks/validate-icon-imports.js+++ b/plugins/model-apps/hooks/validate-icon-imports.js@@ -43,6 +43,8 @@ if (process.env.MODEL_APPS_DISABLE_HOOKS === '1' || process.env.MODEL_APPS_DISABprocess.exit(0);}+const { readUtf8Stream } = require('../scripts/lib/utf8-stream.js');+function isWriteTool(toolName) {return toolName === 'Write' || toolName === 'Edit' || toolName === 'MultiEdit';}@@ -287,11 +289,7 @@ function buildBlockMessage(relPath, invalid) {return lines.join('\n');}-let inputData = '';-process.stdin.on('data', (chunk) => {- inputData += chunk;-});-process.stdin.on('end', () => {+readUtf8Stream(process.stdin).then((inputData) => {let input;try {input = JSON.parse(inputData || '{}');@@ -340,4 +338,6 @@ process.stdin.on('end', () => {process.stderr.write(buildBlockMessage(relPath, invalid) + '\n');process.exit(2);+}).catch(() => {+ process.exit(0); // stdin failure → don't block});diff --git a/plugins/model-apps/hooks/validate-write-safety.js b/plugins/model-apps/hooks/validate-write-safety.jsindex 50391b224..5fe937578 100644--- a/plugins/model-apps/hooks/validate-write-safety.js+++ b/plugins/model-apps/hooks/validate-write-safety.js@@ -46,6 +46,8 @@ if (process.env.MODEL_APPS_DISABLE_HOOKS === '1' || process.env.MODEL_APPS_DISABprocess.exit(0);}+const { readUtf8Stream } = require('../scripts/lib/utf8-stream.js');+function debug(msg) {if (DEBUG) process.stderr.write(`[write-safety] ${msg}\n`);}@@ -132,9 +134,7 @@ function extractWritePaths(toolName, toolInput) {return [];}-let inputData = '';-process.stdin.on('data', (c) => { inputData += c; });-process.stdin.on('end', () => {+readUtf8Stream(process.stdin).then((inputData) => {if (SKIP) {debug('MODEL_APPS_SKIP_WRITE_GUARD=1 — bypassing');process.exit(0);@@ -176,4 +176,7 @@ process.stdin.on('end', () => {debug(`OK ${toolName} ${extractWritePaths(toolName, toolInput).join(',')}`);process.exit(0);+}).catch((err) => {+ debug(`stdin read failed: ${err.message}`);+ process.exit(0);});diff --git a/plugins/model-apps/references/app-spec-schema-advanced.md b/plugins/model-apps/references/app-spec-schema-advanced.mdindex 2a266feaa..042e93921 100644--- a/plugins/model-apps/references/app-spec-schema-advanced.md+++ b/plugins/model-apps/references/app-spec-schema-advanced.md@@ -209,10 +209,10 @@ works through.- **`status`** matters more than it does for a rule: an inactive BPF is not merely inert, it is**invisible** — the stage bar does not render at all. `Active` is the default for that reason.- **v1 is single-entity and linear.** Every stage must be on the flow's own `entity`. The SDK also- models cross-entity stages, branching, stage actions and security-role grants; keys carrying them- are **rejected** at flow, stage **and** step level (the allowed keys are `name`/`entity`/- `description`/`status`/`order`/`stages`; per stage `name`/`entity`/`steps`; per step- `name`/`field`/`required`). The rejection is an allow-list rather than a list of known-bad names+ models cross-entity stages, branching and stage actions; keys carrying them are **rejected** at+ flow, stage **and** step level (the allowed keys are `name`/`entity`/`description`/`status`/+ `order`/`stages`/`securityRoles` — the last is covered in its own section below; per stage+ `name`/`entity`/`steps`; per step `name`/`field`/`required`). The rejection is an allow-list rather than a list of known-bad namesbecause the SDK's own normalizers silently discard any key they do not copy — so an unguarded`branch` on a stage, or `fieldLogicalName` instead of `field` on a step, would validate clean anddeploy as though it had never been written. Configure those in Maker after the flow deploys.diff --git a/plugins/model-apps/references/app-spec-schema.md b/plugins/model-apps/references/app-spec-schema.mdindex 7cafe3aed..fe291e0df 100644--- a/plugins/model-apps/references/app-spec-schema.md+++ b/plugins/model-apps/references/app-spec-schema.md@@ -665,7 +665,10 @@ why they need naming here at all.selection is order-independent either way (it is applied once, after every form exists, rather thaneach form racing to promote itself). A promotion the environment refuses is reported as a warningand fails `--verify`, which proves the deployed `systemform.isdefault` independently — so a build- can no longer record a default it did not actually set.+ can no longer record a default it did not actually set. Moving the default to another form **clears**+ it on the table's other spec-declared Main forms (measured: setting the flag on one form does not+ clear it on another, so both stayed default), and `--verify` fails while any of them still holds+ it. Forms the spec does not declare, and their activation state, are never touched.- **Form resolution is by `(entity, name, formType)`** — a Dataverse form name is unique only per`(entity, type)`, so a table's auto-created **Main**, **Quick View**, and **Card** forms can all benamed "Information" without colliding. A `formType:"Main"` edit reconciles **only** the Main form;@@ -740,16 +743,18 @@ declared after a spanning one would land in the reserved slot. Every stock DatavThis is a **compiler limitation, not a platform one.** Positioning a field beside a vertical spanrequires emitting an empty *spacer* cell to occupy the reserved slot, which the SDK serializes-correctly; the compiler does not emit one yet. The restriction can be lifted once it does — tracked-in [#581](https://github.com/microsoft/power-platform-skills/issues/581).+correctly; the compiler does not emit one yet. The restriction can be lifted once it does.A **deployed** `rowspan` — one a maker added by hand, which the authored restriction above cannotprevent — can make the rows of a section positionally meaningful in the same way: once any cell**follows** a row-spanning cell, re-flowing the section by reading order could move that cell into-the reserved slot. In such a section the build therefore never re-flows. Narrowing its grid is-applied only when every row already fits the new width; otherwise the section **keeps its current-grid** and the refusal is reported. A span change that would overflow a row there is skipped (and-reported), rather than applied without the re-flow. Likewise a `rowspan` is never **raised** on a+the reserved slot. In such a section the build therefore never re-flows. Every fit below counts a+row's own cells **plus** the columns a row-spanning cell above still reserves in it — the same rule+`--verify` applies, so the build never writes a layout verify rejects. Narrowing the grid is applied+only when every row already fits the new width that way; otherwise the section **keeps its current+grid** and the refusal is reported. A span change that would overflow the rows its cell occupies is+skipped (and reported), rather than applied without the re-flow. A field added to the section goes+into the last row if it fits there, otherwise into the first new row with room. Likewise a `rowspan` is never **raised** on adeployed cell that other cells follow, even when its row still fits: the build keeps a field wherethe form already has it, so the field you list last is not necessarily last on the form. A sectionwhose row spans are all **trailing** — stock Main forms put `rowspan` on the last cell — re-flows@@ -804,7 +809,10 @@ below.⚠ Declaring explicit `tabs` also switches **pruning** on: a field the deployed form carries and thelayout does not list is removed (never the primary field). Set `"prune": false` to restyle or-reorder a subset without re-declaring every other field.+reorder a subset without re-declaring every other field. A row that a removed or moved field leaves+holding nothing goes with it, so no blank line is left behind. The exceptions are a row that a+row-spanning cell above still reserves, which stays because the span occupies it, and a row that was+already empty, which is left as it is.### Per-field control options — `readOnly`, `hidden`, `after`@@ -972,6 +980,14 @@ custom control), but the spec validator emits a warning.spec **omits** `pageId` — it is portable across environments. On rebuild the spec `pageId` is thehighest identity authority (outranks the manifest), confirmed against EXISTENCE — so a downloadedapp (including Maker-added pages) rebuilds against the correct existing page without duplication.+- **What a page round-trip carries — and what it does not.** A download brings back each page's+ code, prompt, `dataSources` and identity. A page's **connector and Custom API bindings** and the id+ of the **model** that generated it have no App Spec field, so they are not in the spec. The build+ uploads without them, and pac leaves a page's existing bindings in place when they are omitted: a+ rebuild in the **same environment** keeps the bindings working, but that is preservation, not+ reconstruction — the same spec rebuilt in **another environment** deploys the page without them+ (bind them there with `/genpage`). The model id is stored empty whenever a rebuild re-uploads the+ page.- **Safety HALTs (pages phase).** The build halts on identity/safety violations rather thanproceeding with potentially wrong state:- `pages-identity-conflict` — spec `pageId` and manifest disagree on a key, or a duplicate id isdiff --git a/plugins/model-apps/references/authoring-flow.md b/plugins/model-apps/references/authoring-flow.mdindex 2d8a079cd..04cb74bb6 100644--- a/plugins/model-apps/references/authoring-flow.md+++ b/plugins/model-apps/references/authoring-flow.md@@ -33,9 +33,8 @@ outcomes — because the eval harness greps the log for these tokens. Concretely`AskUserQuestion` is required.- The plan-presentation call is recorded as `EnterPlanMode called` followedby the user's response (`approved` / `revised`).-- The PAC CLI version output is recorded explicitly (the assertion checks- for `>= 2.7.0`-shaped text — `PAC CLI Version 2.7.x` is the canonical- form).+- The PAC CLI version output is recorded explicitly (the assertion parses the recorded version and+ requires `> 2.10.0`, e.g. `PAC CLI Version 2.11.0`; an older pac fails).Decisions and outcomes can be summarized at the end of the section, but theydo **not** substitute for command-level entries. See an existing fixture@@ -55,8 +54,8 @@ node --versionpac help```-`pac help` output includes the version number. Verify the version is **>= 2.7.0**-(required for `pac model create` support). If the version is older, instruct the+`pac help` output includes the version number. Verify the version is **> 2.10.0**+(the plugin's minimum; see the README prerequisites). If the version is older, instruct theuser to update: `dotnet tool update --global Microsoft.PowerApps.CLI.Tool`.If either command fails, inform the user and provide installation instructions.diff --git a/plugins/model-apps/references/connectors.md b/plugins/model-apps/references/connectors.mdindex 5bbee8a62..06ef5b00a 100644--- a/plugins/model-apps/references/connectors.md+++ b/plugins/model-apps/references/connectors.md@@ -5,9 +5,8 @@ name. The `connectorLogicalName` string in TSX **MUST** equal a`connectorBindings[].logicalName` value in the page `config.json`, and thatlogical name must exist as a connection reference in the target environment.-> **GA.** Connector authoring is on by default. A `connectors` flag is retained for one-> release as a rollback switch — when it is off, pages are Dataverse / mock-data only and-> no connector code is emitted. See the Feature Flags section in the plugin `AGENTS.md`.+> **No feature flag.** Connector authoring is always available. Pages emit connector code only when+> the plan carries actual connector bindings.## Binding shape: `connectors.json` (array) vs page `config.json` (object)diff --git a/plugins/model-apps/references/troubleshooting.md b/plugins/model-apps/references/troubleshooting.mdindex da73bc988..b658d4057 100644--- a/plugins/model-apps/references/troubleshooting.md+++ b/plugins/model-apps/references/troubleshooting.md@@ -8,10 +8,11 @@ Deployment, runtime, and environment issues. For generation-time anti-patterns## User Wants to Create a New Model-Driven App-This plugin creates **pages within existing** model-driven apps — it cannot create a new app. If the user asks to create a new model-driven app:+Both skills can create one:-- Direct them to [Power Apps maker portal](https://make.powerapps.com) to create the app: **New App → Start with Design → Blank page with Navigation**-- Once the app exists, they can use `/genpage` to add pages to it+- `/genpage` creates an app to host its pages when the plan chooses a new app (Phase 3 runs `pac model create`), then adds the pages to it.+- `/app-builder` builds a whole app from a description: tables, forms, views, the app and its sitemap.+- An app created in the [Power Apps maker portal](https://make.powerapps.com) (**New App → Start with Design → Blank page with Navigation**) works too; `/genpage` can then add pages to it.---diff --git a/plugins/model-apps/scripts/_vendor-build/build.js b/plugins/model-apps/scripts/_vendor-build/build.jsindex ad0405814..43db83203 100644--- a/plugins/model-apps/scripts/_vendor-build/build.js+++ b/plugins/model-apps/scripts/_vendor-build/build.js@@ -74,8 +74,8 @@ const { sanitizeSubject } = require('./sanitize-subject.js');function sdkProvenance(root) {const git = (args) => {try {- return require('node:child_process')- .execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] })+ return require('../lib/process-runner.js')+ .runSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();} catch {return null;@@ -230,6 +230,14 @@ esbuildoutfile: OUTFILE,logLevel: 'info',minify: true,+ // The SDK compiles generative pages with a TypeScript compiler its HOST supplies+ // (`MakerSdkOptions.typescript`); its `/node` entry offers `loadNodeTypeScript`, which loads+ // `typescript` with a dynamic import. esbuild follows that import and inlined the whole compiler:+ // 3.5 MB of a 4.4 MB bundle, measured with a metafile. The plugin supplies no compiler, since it+ // still deploys pages through `pac`, so nothing ever calls that loader. Left external, the import+ // stays a lazy runtime require, and a caller of `loadNodeTypeScript` gets "Cannot find module+ // 'typescript'" instead of a compiler nobody asked for.+ external: ['typescript'],// The bundle is entirely Microsoft's cds-maker-sdk + its designer packages; esbuild's extracted// legal comments were 100% redundant Microsoft copyright headers (no third-party notices — the// bundled OSS deps ship pre-stripped), so we drop the sidecar and carry a single copyright bannerdiff --git a/plugins/model-apps/scripts/add-page-to-solution.js b/plugins/model-apps/scripts/add-page-to-solution.jsindex 67ca48b2b..adfc36fe2 100644--- a/plugins/model-apps/scripts/add-page-to-solution.js+++ b/plugins/model-apps/scripts/add-page-to-solution.js@@ -26,32 +26,11 @@ const {validateFlags,emitResult,} = require('./lib/dataverse-auth');-const { isConnectorsEnabled, exitIfConnectorsDisabled } = require('./lib/feature-flags');--// Connection references are connector state. When the connectors flag is OFF (the GA rollback-// switch), ALM must not add them. Two distinct cases, and conflating them is what made this-// silently lossy:-// 1. The caller passed NO --connection-refs → nothing to gate; non-connector page packaging-// (appmodule + uxagentproject) proceeds normally whether the flag is on or off.-// 2. The caller EXPLICITLY passed --connection-refs while the flag is OFF → this is the-// documented fail-closed backstop: exit 3, BEFORE any AddSolutionComponent call. Previously-// the refs were dropped and the script still reported `ok: true`, so an out-of-band/stale-plan-// call packaged a solution WITHOUT the connection references the caller asked for and looked-// like it succeeded — the resulting solution imports with unbound connectors.-// The gate runs before the first mutation so a refused run leaves the solution untouched rather-// than half-populated (app + pages added, refs missing).-function connectionRefsToAdd(refs, connectorsEnabled) {- return connectorsEnabled ? refs : [];-}-+const { odataLit } = require('./lib/odata');const APPMODULE_COMPONENT_TYPE = 80;const UXAGENTPROJECT_LOGICAL_NAME = 'uxagentproject';const CONNECTION_REFERENCE_LOGICAL_NAME = 'connectionreference';-function escapeODataString(value) {- return String(value).replace(/'/g, "''");-}-async function addComponent(envUrl, solutionUniqueName, componentId, componentType, addRequired) {const body = {ComponentId: componentId,@@ -64,7 +43,7 @@ async function addComponent(envUrl, solutionUniqueName, componentId, componentTy}async function resolveEntityComponentType(envUrl, logicalName) {- const path = `EntityDefinitions(LogicalName='${escapeODataString(logicalName)}')?$select=ObjectTypeCode`;+ const path = `EntityDefinitions(LogicalName='${odataLit(logicalName)}')?$select=ObjectTypeCode`;const res = await dataverseRequest(envUrl, 'GET', path);ensureOk(res, `Resolve component type for ${logicalName}`);const componentType = Number(res.data?.ObjectTypeCode);@@ -78,7 +57,7 @@ async function resolveConnectionReferences(envUrl, refs) {const resolved = [];for (const logicalName of refs) {const query =- `connectionreferences?$filter=connectionreferencelogicalname eq '${escapeODataString(logicalName)}'` ++ `connectionreferences?$filter=connectionreferencelogicalname eq '${odataLit(logicalName)}'` +'&$select=connectionreferenceid&$top=1';const lookup = await dataverseRequest(envUrl, 'GET', query);ensureOk(lookup, `Lookup connection reference ${logicalName}`);@@ -110,7 +89,7 @@ async function main() {const [envUrl, solutionUniqueName, appId] = positional;const added = [];- // Parsed BEFORE the first mutation so the fail-closed gate can refuse the whole run rather+ // Parsed BEFORE the first mutation so lookup failures refuse the whole run rather// than leaving a half-packaged solution (app + pages added, refs missing).const refs = (flags['connection-refs'] || '').split(',')@@ -120,13 +99,6 @@ async function main() {.split(',').map((s) => s.trim()).filter(Boolean);- const connectorsOn = isConnectorsEnabled();- // Explicitly-requested refs while the feature is OFF = the documented exit-3 backstop.- if (refs.length && !connectorsOn) {- exitIfConnectorsDisabled();- return; // exitIfConnectorsDisabled() exits; `return` keeps the flow explicit for tests.- }-try {// ObjectTypeCode for custom tables is allocated per environment. Resolve both// types before the first AddSolutionComponent so a metadata failure leaves the@@ -154,14 +126,12 @@ async function main() {added.push({ type: 'uxagentproject', id: pageId });}- const refsToAdd = connectionRefsToAdd(refs, connectorsOn);- const skippedConnectionRefs = connectorsOn ? [] : refs;- for (const { logicalName, id } of resolvedConnectionRefs.filter((ref) => refsToAdd.includes(ref.logicalName))) {+ for (const { logicalName, id } of resolvedConnectionRefs) {await addComponent(envUrl, solutionUniqueName, id, connectionReferenceComponentType, false);added.push({ type: 'connectionreference', logicalName, id });}- emitResult(true, { ok: true, added, skippedConnectionRefs });+ emitResult(true, { ok: true, added });} catch (e) {emitResult(false, e);}@@ -176,8 +146,6 @@ if (require.main === module) {// Exported for unit tests. AppModule is a stable system component type; the two custom-table// component types are deliberately resolved per environment by resolveEntityComponentType.module.exports = {- connectionRefsToAdd,- escapeODataString,APPMODULE_COMPONENT_TYPE,UXAGENTPROJECT_LOGICAL_NAME,CONNECTION_REFERENCE_LOGICAL_NAME,diff --git a/plugins/model-apps/scripts/build-model-app.js b/plugins/model-apps/scripts/build-model-app.jsindex 4fa8a3386..3d3d8e9d6 100644--- a/plugins/model-apps/scripts/build-model-app.js+++ b/plugins/model-apps/scripts/build-model-app.js@@ -13,8 +13,10 @@const os = require('node:os');const fs = require('node:fs');const path = require('node:path');+const { randomUUID } = require('node:crypto');+const { sha256 } = require('./lib/hash.js');const { validateAppSpec, migrateAppSpec, normalizePageSource, normalizeLanguageCode } = require('./lib/app-spec.js');-const { runSdkBuild, planFor, appUniqueName, compileFormIntent, resolveExistingFormId } = require('./lib/sdk-build.js');+const { runSdkBuild, planFor, appUniqueName, compileFormIntent, resolveExistingFormId, normalizeFormId } = require('./lib/sdk-build.js');const { stagePhasesOrResolve, PHASES, STAGES } = require('./lib/stages.js');// #455: resolves the authoring LCID over the transport hatch, BEFORE constructing the SDK that// bakes it into the App/Form/Dashboard adapters.@@ -170,14 +172,14 @@ async function discoverOpDiffState(spec, provision) {const forms = [];for (const f of spec.forms || []) {const def = compileFormIntent(spec, f, {});- if (!def.__explicitLayout) continue;+ if (!def.__explicitLayout || def.__prune === false) continue;// Resolve by (entity, name, TYPE) — NOT name alone. A table routinely has same-named Main / Quick View// / Card forms, so a name-only lookup matched multiple rows and the SDK's AmbiguousArtifactError halted// this preflight (fail-closed), blocking the edit. Type-scoped resolution targets the requested form.const id = await resolveExistingFormId(provision, def);if (!id) continue; // not deployed yet → nothing to pruneawait provision.fetchArtifact('form', id); // seed the workspace copy so getArtifact can read it- forms.push({ label: `form "${f.name || f.entity}" (${String(f.entity).toLowerCase()})`, deployedForm: await provision.getArtifact('form', id) || {}, def });+ forms.push({ formId: id, label: `form "${f.name || f.entity}" (${String(f.entity).toLowerCase()})`, deployedForm: await provision.getArtifact('form', id) || {}, def });}// Sitemap removals only make sense when the app already exists (a fresh app has no deployed sitemap).let sitemap = null;@@ -192,6 +194,152 @@ async function discoverOpDiffState(spec, provision) {return { collision, forms, sitemap };}+const DESTRUCTIVE_APPROVAL_FILE = 'destructive-approval.json';++function destructiveApprovalPath(workspaceDir) {+ return workspaceDir ? path.join(workspaceDir, DESTRUCTIVE_APPROVAL_FILE) : null;+}++// Approval records are deliberately tiny and human-readable because they bind a later+// `--allow-destructive` run to the exact refusal list a maker reviewed:+// {+// "schemaVersion": 1,+// "generatedAt": "2026-01-01T00:00:00.000Z",+// "formRemovals": { "<form-id>": { "label": "form \"Main\" (new_table)", "fields": ["new_field"] } },+// "sitemapRemovals": ["entity:new_table", "url:https://contoso.crm.dynamics.com/help"],+// "runId": "<the build that wrote it>"+// }+// `runId` makes every record's bytes unique, so a record's content fingerprint says which build wrote+// it (see approvalFingerprint). Reading ignores it.+// Treat every malformed shape as unreadable: guessing at a damaged approval would widen destructive+// authority, which is exactly what this file is meant to prevent.+function normalizeApprovalRecord(value) {+ if (!value || value.schemaVersion !== 1 || !value.formRemovals || Array.isArray(value.formRemovals) || typeof value.formRemovals !== 'object' || !Array.isArray(value.sitemapRemovals)) return null;+ const formRemovals = {};+ for (const [formId, entry] of Object.entries(value.formRemovals)) {+ if (!entry || !Array.isArray(entry.fields)) return null;+ const normalizedFormId = normalizeFormId(formId);+ if (!normalizedFormId) return null;+ formRemovals[normalizedFormId] = {+ label: typeof entry.label === 'string' ? entry.label : normalizedFormId,+ fields: entry.fields.map((f) => String(f).toLowerCase()),+ };+ }+ return {+ schemaVersion: 1,+ generatedAt: typeof value.generatedAt === 'string' ? value.generatedAt : '',+ formRemovals,+ sitemapRemovals: value.sitemapRemovals.map((target) => String(target)),+ };+}++// One read yields both the record and the fingerprint of the bytes it was parsed from, so the record a+// build compares with and the one it later claims as "the record I saw" cannot differ.+function readApprovalRecord(workspaceDir) {+ const file = destructiveApprovalPath(workspaceDir);+ if (!file) return { exists: false, file, record: null, fingerprint: null };+ let raw;+ try {+ raw = fs.readFileSync(file);+ } catch (err) {+ if (err && err.code === 'ENOENT') return { exists: false, file, record: null, fingerprint: null };+ return { exists: true, file, error: err, fingerprint: `unreadable:${(err && err.code) || 'error'}` };+ }+ const fingerprint = sha256(raw);+ try {+ const record = normalizeApprovalRecord(JSON.parse(raw.toString('utf8')));+ if (!record) throw new Error('record has an unsupported shape');+ return { exists: true, file, record, fingerprint };+ } catch (err) {+ return { exists: true, file, error: err, fingerprint };+ }+}++// The content fingerprint of the record on disk, or null when there is none. A file that cannot be+// read gets a fingerprint no build ever wrote, so an owner check never consumes or replaces it.+function approvalFingerprint(workspaceDir) {+ return readApprovalRecord(workspaceDir).fingerprint;+}++// Writes atomically and returns the fingerprint of what it wrote.+function writeApprovalRecord(workspaceDir, removals, runId) {+ const file = destructiveApprovalPath(workspaceDir);+ if (!file) return null;+ fs.mkdirSync(workspaceDir, { recursive: true });+ const text = JSON.stringify({ schemaVersion: 1, generatedAt: new Date().toISOString(), ...removals, runId }, null, 2) + '\n';+ const tmp = path.join(workspaceDir, `.${DESTRUCTIVE_APPROVAL_FILE}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`);+ try {+ fs.writeFileSync(tmp, text, 'utf8');+ fs.renameSync(tmp, file);+ } finally {+ try { if (fs.existsSync(tmp)) fs.unlinkSync(tmp); } catch { /* best-effort cleanup only */ }+ }+ return sha256(text);+}++function deleteApprovalRecord(workspaceDir) {+ const file = destructiveApprovalPath(workspaceDir);+ if (!file) return;+ try { fs.unlinkSync(file); } catch (err) { if (!err || err.code !== 'ENOENT') throw err; }+}++function removalRecordFromOps(removals) {+ const byForm = new Map();+ const sitemap = [];+ for (const op of removals || []) {+ if (op.kind === 'form-field-removal') {+ const formId = normalizeFormId(op.formId);+ if (!formId) continue;+ if (!byForm.has(formId)) byForm.set(formId, { formId, label: op.label, fields: [] });+ byForm.get(formId).fields.push(...(op.fields || []));+ } else if (op.kind === 'sitemap-removal') {+ sitemap.push(...(op.targets || []));+ }+ }+ const formRemovals = {};+ for (const entry of byForm.values()) {+ formRemovals[entry.formId] = { label: entry.label, fields: [...new Set(entry.fields.map((f) => String(f).toLowerCase()))] };+ }+ return {+ formRemovals,+ sitemapRemovals: [...new Set(sitemap.map((target) => String(target)))],+ };+}++function authorizedFormRemovalMap(state, removals) {+ const map = new Map();+ for (const f of (state && state.forms) || []) {+ if (f && f.formId && f.def && f.def.__explicitLayout && f.def.__prune !== false) map.set(normalizeFormId(f.formId), new Set());+ }+ for (const [formId, entry] of Object.entries(removalRecordFromOps(removals).formRemovals)) {+ const normalizedFormId = normalizeFormId(formId);+ if (!normalizedFormId) continue;+ if (!map.has(normalizedFormId)) map.set(normalizedFormId, new Set());+ for (const field of entry.fields || []) map.get(normalizedFormId).add(field);+ }+ return map;+}++function findNewlyUnapprovedRemovals(current, approved) {+ const approvedSitemap = new Set(approved.sitemapRemovals || []);+ const newOps = [];+ for (const [formId, entry] of Object.entries(current.formRemovals || {})) {+ const normalizedFormId = normalizeFormId(formId);+ const approvedEntry = (approved.formRemovals || {})[normalizedFormId];+ const ok = new Set((approvedEntry && approvedEntry.fields) || []);+ const fields = (entry.fields || []).filter((field) => !ok.has(field));+ if (fields.length) newOps.push({ kind: 'form-field-removal', label: entry.label, fields });+ }+ const sitemap = (current.sitemapRemovals || []).filter((target) => !approvedSitemap.has(target));+ if (sitemap.length) newOps.push({ kind: 'sitemap-removal', label: 'app sitemap', targets: sitemap });+ return newOps;+}++function formatNewRemovalDetail(op) {+ if (op.kind === 'form-field-removal') return `removes field(s): ${op.fields.join(', ')} — not on the list the maker approved (another maker may have added them, or the spec changed since)`;+ return `drops navigation target(s): ${op.targets.join(', ')} — not on the list the maker approved (another maker may have added them, or the spec changed since)`;+}+async function buildModelApp(spec, opts, deps) {const v = validateAppSpec(spec, { profile: opts.profile || 'deploy' });if (!v.ok) {@@ -210,6 +358,51 @@ async function buildModelApp(spec, opts, deps) {const baseEmit = deps.emit || cliEmit(log, { apply: opts.apply, counts });const emit = journal ? (e) => { baseEmit(e); journal.record(e); } : baseEmit;const sleep = deps.sleep || ((ms) => new Promise((res) => setTimeout(res, ms)));+ let authorizedFormRemovals;+ let authorizedSitemapRemovals;+ let currentDestructiveApproval;+ // The approval record binds the run that SHOWED a list. Two builds can share a workspace, so this run+ // consumes or replaces only a record it found at its start (`seen`) or wrote itself (`owned`), by+ // content fingerprint, and does the check and the change under the workspace lease the apply snapshot+ // uses (lib/apply-snapshot-store.js). Without that, a build that finished with nothing kept deleted+ // the record another build had just written for its refusal, and that build's approved re-run was+ // bound to nothing. Captured before any discovery, from the same read the gate compares with.+ const approvalAtStart = opts.apply && opts.workspaceDir ? readApprovalRecord(opts.workspaceDir) : { exists: false, fingerprint: null };+ const approvalRun = { id: randomUUID(), seen: approvalAtStart.fingerprint, owned: new Set() };+ // What a record on disk is to this run: 'none'; 'ours' (the one it started with, or one it wrote);+ // 'unreadable', whose content is unknown, so it never proves ownership (two unreadable reads say+ // nothing about whether it is the same file); or 'foreign', another build's.+ const approvalOwnership = (fingerprint) => {+ if (fingerprint === null) return 'none';+ if (typeof fingerprint === 'string' && fingerprint.startsWith('unreadable:')) return 'unreadable';+ return fingerprint === approvalRun.seen || approvalRun.owned.has(fingerprint) ? 'ours' : 'foreign';+ };+ // Every writer holds the lease for milliseconds, so a few short waits ride out a collision. A lease+ // that stays held is reported, and each caller decides what is safe without it.+ const withApprovalLease = async (fn) => {+ const attempts = deps.approvalLeaseAttempts || 10;+ let reason = 'held';+ for (let i = 0; i < attempts; i += 1) {+ const lease = applySnapshotStore.acquireLease(opts.workspaceDir);+ if (lease.ok) {+ try { return { locked: true, value: fn() }; } finally { applySnapshotStore.releaseLease(lease); }+ }+ reason = lease.reason || reason;+ if (i < attempts - 1) await sleep(200);+ }+ return { locked: false, reason };+ };+ // Write this run's record under the lease. `ifOurs` refuses to replace another build's record, or one+ // it cannot read.+ const recordApproval = (record, { ifOurs = false } = {}) => withApprovalLease(() => {+ const owner = ifOurs ? approvalOwnership(approvalFingerprint(opts.workspaceDir)) : 'none';+ if (owner === 'unreadable' || owner === 'foreign') return owner;+ approvalRun.owned.add(writeApprovalRecord(opts.workspaceDir, record, approvalRun.id));+ return 'written';+ });+ // Only the forms and app-shell phases remove anything, and a changed-only fast apply runs neither.+ const runsRemovalPhases = (opts.phases || PHASES).includes('forms') && (opts.phases || PHASES).includes('app-shell')+ && !(opts.changedOnly && opts.changedOnly.fastApply);// I1: on APPLY, the ONLY safe phase selections are the FULL build or EXACTLY the `data` stage// (solution+data-model+sample-data). Every other partial range (--from/--to/--only/--skip, or any other@@ -250,6 +443,13 @@ async function buildModelApp(spec, opts, deps) {const allowDestructive = opts.allowDestructive === true;let state;let discoveryError = null;+ const priorApproval = allowDestructive && opts.workspaceDir ? approvalAtStart : { exists: false };+ if (priorApproval.error) {+ const msg = `${priorApproval.file} could not be read as a destructive approval record — delete it or re-run without --allow-destructive to see the list again.`;+ log(`\n✗ ${msg}`);+ if (journal) journal.close({ status: 'halt', phase: 'preflight', label: 'destructive-approval-unreadable', detail: priorApproval.file, ...counts });+ return { ok: false, errors: [msg] };+ }try {state = deps.discoverOpDiffState? await deps.discoverOpDiffState(spec, deps.provisionSdk)@@ -262,6 +462,12 @@ async function buildModelApp(spec, opts, deps) {// the environment is unhealthy, letting an unattended-collision overwrite or a form/sitemap removal// slip through (design §11 — "can't verify safety ⇒ refuse", not "⇒ proceed"). Re-running usually// clears a transient read failure; --allow-destructive is the explicit escape hatch.+ if (discoveryError && priorApproval.exists) {+ const msg = `preflight safety check could not run (discovery failed: ${(discoveryError && discoveryError.message) || discoveryError}) — live removals cannot be compared with the approved list in ${DESTRUCTIVE_APPROVAL_FILE}. Re-run to retry before writing.`;+ log(`\n✗ ${msg}`);+ if (journal) journal.close({ status: 'halt', phase: 'preflight', label: 'destructive-approval-compare-failed', detail: String((discoveryError && discoveryError.message) || discoveryError), ...counts });+ return { ok: false, errors: [msg] };+ }if (discoveryError && !allowDestructive) {const msg = `preflight safety check could not run (discovery failed: ${(discoveryError && discoveryError.message) || discoveryError}) — refusing to write without verifying the apply is non-destructive. Re-run to retry, or pass --allow-destructive to proceed without the check.`;log(`\n✗ ${msg}`);@@ -290,13 +496,73 @@ async function buildModelApp(spec, opts, deps) {// app-collision op is handled above (interactive/non-interactive nuance), so exclude it here.const diff = classifyOps(spec, state, { teardown: false });const removals = diff.destructive.filter((o) => o.kind === 'form-field-removal' || o.kind === 'sitemap-removal');+ authorizedFormRemovals = authorizedFormRemovalMap(state, removals);+ const currentApproval = removalRecordFromOps(removals);+ currentDestructiveApproval = currentApproval;+ if (state.sitemap) authorizedSitemapRemovals = new Set(currentApproval.sitemapRemovals);if (removals.length && !allowDestructive) {const lines = removals.map((o) => ` • ${o.label} — ${o.detail}`);const msg = `refusing ${removals.length} destructive operation(s) without --allow-destructive:\n${lines.join('\n')}`;+ if (opts.workspaceDir) {+ try {+ // The newest refusal is the list the maker is looking at, so it replaces any older record.+ const lock = await recordApproval(currentApproval);+ if (!lock.locked) log(`\n⚠ could not lock the workspace to write ${DESTRUCTIVE_APPROVAL_FILE} (${lock.reason}) — re-run this refusal before approving it with --allow-destructive.`);+ } catch (err) {+ // Approval records are a safety aid for the NEXT invocation. The refusal itself is the+ // primary guard, so a disk failure must not replace the exact destructive-op list the maker+ // needs to review now.+ log(`\n⚠ could not write ${DESTRUCTIVE_APPROVAL_FILE}: ${(err && err.message) || err}`);+ }+ }log(`\n✗ ${msg}`);if (journal) journal.close({ status: 'halt', phase: 'preflight', label: 'destructive-ops', detail: removals.map((o) => o.kind).join(','), ...counts });return { ok: false, errors: [msg] };}+ if (allowDestructive && opts.workspaceDir) {+ if (priorApproval.exists) {+ const newlyUnapproved = findNewlyUnapprovedRemovals(currentApproval, priorApproval.record);+ if (newlyUnapproved.length) {+ try {+ const lock = await recordApproval(currentApproval);+ if (!lock.locked) log(`\n⚠ could not lock the workspace to refresh ${DESTRUCTIVE_APPROVAL_FILE} (${lock.reason})`);+ } catch (err) { log(`\n⚠ could not refresh ${DESTRUCTIVE_APPROVAL_FILE}: ${(err && err.message) || err}`); }+ const lines = newlyUnapproved.map((o) => ` • ${o.label} — ${formatNewRemovalDetail(o)}`);+ const msg = `refusing ${newlyUnapproved.length} destructive operation(s) that were not on the list the maker approved:\n${lines.join('\n')}`;+ log(`\n✗ ${msg}`);+ if (journal) journal.close({ status: 'halt', phase: 'preflight', label: 'destructive-ops-new', detail: newlyUnapproved.map((o) => o.kind).join(','), ...counts });+ return { ok: false, errors: [msg] };+ }+ }+ // Persist the gate-time list BEFORE the first mutation. If the engine later keeps a new field+ // and then fails, the next approved run must still be bound to what this run saw. That holds+ // for an EMPTY list too: with nothing recorded, a retry after a failure that kept a field+ // another maker added would have removed it without showing it. A run without the removal+ // phases can keep nothing, so it records only a list it actually has.+ if (removals.length || runsRemovalPhases) {+ let lock = null;+ let writeError = null;+ try { lock = await recordApproval(currentApproval, { ifOurs: true }); } catch (err) { writeError = err; }+ // Fail closed: only a list that is verifiably on disk binds a retry. The comparison above was+ // with the record this run read; a record some other build wrote since then (or one that can+ // no longer be read) means that comparison no longer describes what is on disk. Either way,+ // stop before any write rather than run unbound.+ const halt = writeError+ ? `could not record what this run may remove in ${DESTRUCTIVE_APPROVAL_FILE} (${(writeError && writeError.message) || writeError}) — nothing was changed; fix the workspace folder and re-run.`+ : !lock.locked+ ? `could not lock the workspace to record what this run may remove (${lock.reason}) — re-run once no other build or teardown of this workspace is running.`+ : lock.value === 'unreadable'+ ? `${DESTRUCTIVE_APPROVAL_FILE} could not be read while this build was starting — nothing was changed; check the workspace folder and re-run.`+ : lock.value !== 'written'+ ? `${DESTRUCTIVE_APPROVAL_FILE} changed while this build was starting — another build may be using this workspace. Re-run once it has finished.`+ : null;+ if (halt) {+ log(`\n✗ ${halt}`);+ if (journal) journal.close({ status: 'halt', phase: 'preflight', label: 'destructive-approval-changed', detail: halt, ...counts });+ return { ok: false, errors: [halt] };+ }+ }+ }}}// Transient env errors (429 EntityCustomization lock, 503 SQL timeout, concurrent-op guards) are@@ -331,6 +597,8 @@ async function buildModelApp(spec, opts, deps) {warn: deps.warn,genpageCli: deps.genpageCli, // injectable seam for tests; else constructed from envworkspaceDir: opts.workspaceDir, // lease/staging live under the real workspace dir+ authorizedFormRemovals,+ authorizedSitemapRemovals,allowDestructive: opts.allowDestructive, // pages phase gates destructive page removals (Imp6)changedOnly: opts.changedOnly, // #changed-only: pages-only fast-apply seams (resolvedAppId + skipSitemapFinalize)emit,@@ -442,6 +710,40 @@ async function buildModelApp(spec, opts, deps) {} else if (journal) {journal.close({ status: r && r.dryRun ? 'dry-run' : 'done', ...counts });}+ if (opts.apply && r && r.ok && !r.dryRun && (!r.verify || r.verify.ok) && opts.workspaceDir) {+ const kept = (((r.skipped || {}).unauthorizedRemovals) || []);+ if (kept.length) {+ const record = currentDestructiveApproval || { formRemovals: {}, sitemapRemovals: [] };+ const names = kept.map((x) => `${x.form || x.formId || 'form'}:${x.field}`).join(', ');+ try {+ const lock = await recordApproval(record, { ifOurs: true });+ if (!lock.locked) {+ log(`\n⚠ kept unauthorized form removal(s) (${names}), but could not lock the workspace to record them (${lock.reason}).`);+ } else if (lock.value === 'unreadable') {+ log(`\n⚠ kept unauthorized form removal(s) (${names}), but ${DESTRUCTIVE_APPROVAL_FILE} could not be read, so it was left as it is.`);+ } else if (lock.value === 'foreign') {+ // That build's list binds its own approval; any kept field it does not name is still new to it.+ log(`\n⚠ kept unauthorized form removal(s) (${names}); ${DESTRUCTIVE_APPROVAL_FILE} was written by another build since this one started, so it was left as it is.`);+ } else {+ log(`\n⚠ kept unauthorized form removal(s) (${names}); ${DESTRUCTIVE_APPROVAL_FILE} was left for review, so the next run will ask about them before removing anything.`);+ }+ } catch (err) {+ log(`\n⚠ kept unauthorized form removal(s), but could not write ${DESTRUCTIVE_APPROVAL_FILE}: ${(err && err.message) || err}`);+ }+ } else if (runsRemovalPhases) {+ try {+ const lock = await withApprovalLease(() => {+ const owner = approvalOwnership(approvalFingerprint(opts.workspaceDir));+ if (owner !== 'ours') return owner;+ deleteApprovalRecord(opts.workspaceDir);+ return 'deleted';+ });+ if (!lock.locked) log(`\n⚠ could not lock the workspace to consume ${DESTRUCTIVE_APPROVAL_FILE} (${lock.reason}); it was left, so the next run may ask about its removals again.`);+ else if (lock.value === 'unreadable') log(`\n⚠ left ${DESTRUCTIVE_APPROVAL_FILE}: it could not be read, so this build cannot tell whose it is.`);+ else if (lock.value === 'foreign') log(`\n⚠ left ${DESTRUCTIVE_APPROVAL_FILE}: another build wrote it after this one started.`);+ } catch (err) { log(`\n⚠ could not delete ${DESTRUCTIVE_APPROVAL_FILE}: ${(err && err.message) || err}`); }+ }+ }// Attach non-blocking validation advisories to the result JSON so programmatic callers see them too// (they were already narrated via `log` above). Never overrides an error result's shape.if (r && typeof r === 'object' && (v.warnings || []).length) r.warnings = v.warnings;diff --git a/plugins/model-apps/scripts/check-auth.js b/plugins/model-apps/scripts/check-auth.jsindex 968ca89b7..e1b675fae 100644--- a/plugins/model-apps/scripts/check-auth.js+++ b/plugins/model-apps/scripts/check-auth.js@@ -32,8 +32,8 @@//// Exit code 0 always (so callers can parse stdout). Use `ok` field to gate.-const { execFileSync } = require('child_process');-const { dataverseRequest, parseArgs, validateFlags } = require('./lib/dataverse-auth');+const { execFileAsync } = require('./lib/process-runner.js');+const { dataverseRequest, getAuthTokenAsync, parseArgs, validateFlags } = require('./lib/dataverse-auth');// Read the env URL from either `--env <url>` (the flag the build/verify/teardown scripts use) or// the first positional arg, so a caller can copy the `--env` form here without silently passing@@ -55,17 +55,37 @@ function parseEnvUrl(argv) {return positional || null;}-function runQuiet(cmd, args) {- try {- return execFileSync(cmd, args, {- encoding: 'utf8',- timeout: 15000,- stdio: ['ignore', 'pipe', 'pipe'],- shell: process.platform === 'win32',- }).trim();- } catch {- return null;- }+// Trimmed stdout, or null on any failure. The child runs in the background so the event loop stays+// free to drain other CLI stdout and service their timeout timers while Azure CLI and PAC cold-start.+function runQuietAsync(cmd, args) {+ let child = null;+ let settled = false;+ const promise = new Promise((resolve) => {+ try {+ child = execFileAsync(cmd, args, {+ encoding: 'utf8',+ timeout: 15000,+ windowsHide: true,+ }, (error, stdout) => {+ settled = true;+ resolve(error ? null : String(stdout || '').trim());+ });+ // execFile always opens a stdin pipe; close it (the effect of stdio 'ignore'), so a CLI that+ // checks stdin can never wait on it.+ if (child && child.stdin) child.stdin.end();+ } catch {+ settled = true;+ resolve(null);+ }+ });+ return {+ promise,+ cancel() {+ if (!settled && child && typeof child.kill === 'function') {+ child.kill();+ }+ },+ };}function emit(payload) {@@ -111,18 +131,30 @@ async function main() {const requirePac = argv.includes('--require-pac');const warnings = [];- // 1) az presence + login- const azVersion = runQuiet('az', ['--version']);- if (azVersion == null) {- return emit(- buildResult({- blocker: 'az_missing',- message: 'Azure CLI (`az`) is not installed. Install it from https://aka.ms/azure-cli and run `az login`.',- })- );- }- const azUser = runQuiet('az', ['account', 'show', '--query', 'user.name', '-o', 'tsv']);+ // Every probe below is a cold CLI start. Measured on Windows: `pac org who` ~7 s, and each `az`+ // call ~3-5 s. Run one after another (az --version, az account show, pac, then az again for the+ // WhoAmI token), the preflight cost ~19 s at the start of every /genpage and /app-builder run.+ // pac needs nothing from az, so it is started FIRST and runs while the az probes run.+ const pacOrgProbe = runQuietAsync('pac', ['org', 'who']);++ // 1) az login. `az account show` answers "installed?" and "logged in?" together on the happy path,+ // so `az --version` runs only to tell those two failures apart.+ const azUser = await runQuietAsync('az', ['account', 'show', '--query', 'user.name', '-o', 'tsv']).promise;if (!azUser) {+ if (await runQuietAsync('az', ['--version']).promise == null) {+ // This branch returns before the pac probe is awaited. Kill the child explicitly so a+ // non-detached PAC process cannot outlive the preflight after its parent exits.+ pacOrgProbe.cancel();+ return emit(+ buildResult({+ blocker: 'az_missing',+ message: 'Azure CLI (`az`) is not installed. Install it from https://aka.ms/azure-cli and run `az login`.',+ })+ );+ }+ // Same early-return hazard as az_missing: once we know az is installed but logged out, the+ // pending PAC result cannot affect this verdict, so cancel it before emitting.+ pacOrgProbe.cancel();return emit(buildResult({blocker: 'az_not_logged_in',@@ -131,8 +163,15 @@ async function main() {);}+ // Acquire the WhoAmI token while pac is still running. getAuthToken memoizes per process, so the+ // dataverseRequest below reuses it instead of paying another az cold start after pac returns. A+ // failure here is not reported: WhoAmI acquires again and reports it with the right blocker.+ if (envUrl) {+ try { await getAuthTokenAsync(envUrl); } catch { /* reported by WhoAmI */ }+ }+// 2) pac user + env URL (best-effort — pac is NOT required for the Dataverse build path)- const pacOrg = runQuiet('pac', ['org', 'who']);+ const pacOrg = await pacOrgProbe.promise;let pacUser = null;if (pacOrg) {const m = pacOrg.match(/Connected as\s+([^\s\r\n]+)/i);diff --git a/plugins/model-apps/scripts/check-version.js b/plugins/model-apps/scripts/check-version.jsindex a500031a8..05cf127e0 100644--- a/plugins/model-apps/scripts/check-version.js+++ b/plugins/model-apps/scripts/check-version.js@@ -9,7 +9,8 @@* Functions are also exported for testing.*/-const { execFileSync, execSync } = require('child_process');+// git is resolved to an absolute path on PATH: this runs from the user's project directory.+const { runSync } = require('./lib/process-runner.js');const path = require('path');const fs = require('fs');@@ -73,10 +74,11 @@ function readMarketplaceName(gitRoot) {return marketplace?.name || null;}-function readJsonFromGit(ref, relativePaths) {+function readJsonFromGit(ref, relativePaths, cwd) {for (const relativePath of relativePaths) {try {- const content = execFileSync('git', ['show', `${ref}:${relativePath}`], {+ const content = runSync('git', ['show', `${ref}:${relativePath}`], {+ cwd,encoding: 'utf8',timeout: 5000,stdio: ['pipe', 'pipe', 'pipe'],@@ -101,18 +103,35 @@ if (require.main === module) {const localVersion = localPlugin.version;if (!localVersion) process.exit(0);- const gitRoot = execSync('git rev-parse --show-toplevel', {+ // Every git call is anchored to the plugin directory. The skills run this script from the+ // USER's project directory, so a git command without `cwd` operated on the user's repository:+ // it fetched their `origin main` at every skill start (network, and a possible credential+ // prompt) and then compared against a manifest path that does not exist there, so the notice+ // could never fire. A marketplace install is a plain copy, not a clone, so `rev-parse` fails+ // there and the script exits silently, as it does on any other error.+ const gitRoot = runSync('git', ['rev-parse', '--show-toplevel'], {+ cwd: pluginRoot,encoding: 'utf8',timeout: 5000,stdio: ['pipe', 'pipe', 'pipe'],}).trim();- const remoteManifestPaths = PLUGIN_MANIFEST_PATHS.map((manifestPath) =>- path.relative(gitRoot, path.join(pluginRoot, manifestPath)).replace(/\\/g, '/')- );+ // The plugin's path inside the repository, as git itself computes it (e.g. "plugins/model-apps/").+ // Deriving it with path.relative(gitRoot, pluginRoot) broke whenever the two spelled the same folder+ // differently: git reports the long Windows name (C:/Users/runneradmin/...) while __dirname can carry+ // the 8.3 short name (C:\Users\RUNNER~1\...), so the relative path pointed outside the repository+ // and the check silently found nothing.+ const prefix = runSync('git', ['rev-parse', '--show-prefix'], {+ cwd: pluginRoot,+ encoding: 'utf8',+ timeout: 5000,+ stdio: ['pipe', 'pipe', 'pipe'],+ }).trim();+ const remoteManifestPaths = PLUGIN_MANIFEST_PATHS.map((manifestPath) => `${prefix}${manifestPath}`);try {- execSync('git fetch origin main --quiet', {+ runSync('git', ['fetch', 'origin', 'main', '--quiet'], {+ cwd: pluginRoot,encoding: 'utf8',timeout: 10000,stdio: ['pipe', 'pipe', 'pipe'],@@ -121,7 +140,7 @@ if (require.main === module) {// A cached origin/main is sufficient when the network is unavailable.}- const remotePlugin = readJsonFromGit('origin/main', remoteManifestPaths);+ const remotePlugin = readJsonFromGit('origin/main', remoteManifestPaths, pluginRoot);if (!remotePlugin?.version) process.exit(0);if (compareSemver(localVersion, remotePlugin.version) > 0) {diff --git a/plugins/model-apps/scripts/create-connection-reference.js b/plugins/model-apps/scripts/create-connection-reference.jsindex fae1eb64a..3688bf700 100644--- a/plugins/model-apps/scripts/create-connection-reference.js+++ b/plugins/model-apps/scripts/create-connection-reference.js@@ -24,13 +24,8 @@ const {validateFlags,emitResult,} = require('./lib/dataverse-auth');-const { exitIfConnectorsDisabled } = require('./lib/feature-flags');async function main() {- // Rollback gate (fail closed) — see lib/feature-flags.js. connectors is GA and ships ON, so- // this normally passes; exit 3 = "feature off" stays distinct from 1 = runtime/usage error.- exitIfConnectorsDisabled();-const argv = process.argv.slice(2);const { positional, flags } = parseArgs(argv);const USAGE = 'Usage: node create-connection-reference.js <envUrl> <logicalName> <connectorId> [--connection-id <id>] [--display-name <name>]';diff --git a/plugins/model-apps/scripts/download-model-app.js b/plugins/model-apps/scripts/download-model-app.jsindex cdb2ffc52..ff05c74d9 100644--- a/plugins/model-apps/scripts/download-model-app.js+++ b/plugins/model-apps/scripts/download-model-app.js@@ -485,11 +485,6 @@ const APP_COMPONENT_ENTITY_SOURCES = [// Dataverse entity set -> the App Spec artifact class it inventories, so a failed read is reported// in the author's vocabulary ("forms could not be inventoried") rather than Dataverse's.const INVENTORY_KIND_BY_SET = { savedquery: 'views', savedqueryvisualization: 'charts', systemform: 'forms' };-// Dataverse honors `$top` as a HARD cap and omits `@odata.nextLink`, so this is the point past which-// components of one type stop being inspected. Generous for a real app (a 70-table app has ~1000-// views), and exceeded only with a warning.-const COMPONENT_PAGE_CAP = 1000;-async function appComponentEntities(sdk, appId) {if (!appId) return [];try {@@ -502,21 +497,16 @@ async function appComponentEntities(sdk, appId) {const rows = await sdk.queryRecords('appmodulecomponent', {select: ['objectid', 'componenttype'],filter: `_appmoduleidunique_value eq ${parent} and componenttype eq ${src.componentType}`,- top: COMPONENT_PAGE_CAP,+ paginate: true,});- // `$top` is a HARD cap in Dataverse (the SDK refuses to combine `top` with `paginate` for- // exactly this reason: `@odata.nextLink` is omitted, so the tail is lost with no signal). An- // app with more than this many components of one type would silently lose the remainder —- // the same silent-drop class as ADO 6603388, just at a higher threshold — so say so rather- // than quietly returning a partial set.- if ((rows || []).length >= COMPONENT_PAGE_CAP) {- process.stderr.write(`WARNING: this app has at least ${COMPONENT_PAGE_CAP} ${src.set} components; only the first ${COMPONENT_PAGE_CAP} were inspected, so a table referenced only beyond that point may be missing from the spec.\n`);- }+ // The component list decides which hidden tables belong in the downloaded spec, so a capped+ // read would silently drop tables reachable only through forms/views/charts. Page the whole+ // list and then batch only the follow-up id lookups to keep URLs bounded.const ids = [...new Set((rows || []).map((r) => r && r.objectid).filter(Boolean).map((id) => String(id).replace(/[{}]/g, '')))];// Chunk the OR-batched id lookups so a many-component app cannot build an over-long URL.for (let i = 0; i < ids.length; i += 20) {const filter = ids.slice(i, i + 20).map((id) => `${src.idField} eq ${id}`).join(' or ');- const recs = await sdk.queryRecords(src.set, { select: [src.idField, src.entityField], filter, top: 1000 });+ const recs = await sdk.queryRecords(src.set, { select: [src.idField, src.entityField], filter, paginate: true });// A dashboard is a `systemform` row too, and its `objecttypecode` is NOT an entity logical// name ('none' / ''). Filtering it here keeps a bogus name out of the metadata fetch loop// instead of relying on that fetch 404-ing into a bare catch.@@ -537,7 +527,7 @@ async function rowsByIds(sdk, set, idField, ids, select, mapRow) {const clean = [...new Set((ids || []).map((id) => String(id || '').replace(/[{}]/g, '')).filter(Boolean))];for (let i = 0; i < clean.length; i += 20) {const filter = clean.slice(i, i + 20).map((id) => `${idField} eq ${id}`).join(' or ');- const rows = await sdk.queryRecords(set, { select, filter, top: 1000 });+ const rows = await sdk.queryRecords(set, { select, filter, paginate: true });for (const r of rows || []) out.push(mapRow(r));}return out;@@ -573,7 +563,7 @@ async function readAppShellSettings(sdk, appId) {const byId = new Map((defs || []).map((d) => [odataGuid(d.settingdefinitionid).toLowerCase(), d.uniquename]));if (!byId.size) return out;// Bound the read by the two DEFINITIONS, not by `$top`. Dataverse honours `$top` as a hard cap and- // omits `@odata.nextLink` (see COMPONENT_PAGE_CAP above), so an app-scoped read that leans on a row+ // omits `@odata.nextLink`, so an app-scoped read that leans on a row// limit can return a partial page — and here a partial page is not a visible truncation but a WRONG// ANSWER, because an absent row is indistinguishable from "inherits the environment". The app would// round-trip without its override and rebuild into the classic shell, silently, which is the exact@@ -624,20 +614,10 @@ async function readDescriptionInventory(sdk, appId, solutionScope, referencedGloconst rows = await sdk.queryRecords('appmodulecomponent', {select: ['objectid', 'componenttype'],filter: `_appmoduleidunique_value eq ${parent} and componenttype eq ${src.componentType}`,- top: COMPONENT_PAGE_CAP,+ paginate: true,});- // A FULL page is indistinguishable from a truncated one, so treat it as truncated. `$top` is- // a HARD cap and Dataverse omits `@odata.nextLink` when it is honoured, so there is no- // signal to read afterwards. `appComponentEntities` warns about the same cap on its own- // query, but THIS list feeds `notRoundTrippedSummary`, which reports a count — so a- // truncated read there is not merely a missing table, it is a smaller number presented as- // the whole truth. Marking the class incomplete makes the report say it cannot vouch for- // the class instead. A false positive at exactly the cap costs one honest- // "could not be inventoried" line; the alternative is a silent undercount.- if ((rows || []).length >= COMPONENT_PAGE_CAP) {- fail(INVENTORY_KIND_BY_SET[src.set] || src.set,- new Error(`more than ${COMPONENT_PAGE_CAP} app components of this type; the list was truncated, so this class is incomplete`));- }+ // This inventory feeds the not-round-tripped report; a capped component read would turn+ // "unknown tail" into a smaller authoritative count. Page completely instead.const ids = (rows || []).map((r) => r && r.objectid).filter(Boolean);if (src.set === 'savedquery') {inventory.views.push(...await rowsByIds(sdk, 'savedquery', 'savedqueryid', ids, ['savedqueryid', 'name', 'returnedtypecode', 'description'], (r) =>@@ -714,7 +694,7 @@ async function readDescriptionInventory(sdk, appId, solutionScope, referencedGlo// mislabelling somebody's classic workflow as a business rule is the failure mode here.const ids = [];for (const solId of solIds) {- const comps = await sdk.queryRecords('solutioncomponent', { select: ['objectid', 'componenttype'], filter: `_solutionid_value eq ${solId} and componenttype eq 29`, top: 1000 });+ const comps = await sdk.queryRecords('solutioncomponent', { select: ['objectid', 'componenttype'], filter: `_solutionid_value eq ${solId} and componenttype eq 29`, paginate: true });ids.push(...(comps || []).map((r) => r && r.objectid).filter(Boolean));}// rowsByIds de-duplicates, so a rule in two of the candidate solutions is listed once.@@ -776,11 +756,8 @@ async function readDescriptionInventory(sdk, appId, solutionScope, referencedGlo// See: https://learn.microsoft.com/power-apps/developer/data-platform/reference/entities/solutioncomponentif (solutionError) throw solutionError;const owned = new Set();- let truncated = null;for (const solId of solIds) {- const comps = await sdk.queryRecords('solutioncomponent', { select: ['objectid'], filter: `_solutionid_value eq ${solId} and componenttype eq 9`, top: COMPONENT_PAGE_CAP });- // A full page is indistinguishable from a truncated one — same rule as the app components above.- if ((comps || []).length >= COMPONENT_PAGE_CAP) truncated = new Error(`more than ${COMPONENT_PAGE_CAP} option sets in one of the app's solutions; the list was truncated, so this class is incomplete`);+ const comps = await sdk.queryRecords('solutioncomponent', { select: ['objectid'], filter: `_solutionid_value eq ${solId} and componenttype eq 9`, paginate: true });for (const r of comps || []) if (r && r.objectid) owned.add(odataGuid(r.objectid).toLowerCase());}const referenced = new Set([...(referencedGlobalChoices || [])].map((n) => String(n).toLowerCase()));@@ -798,7 +775,6 @@ async function readDescriptionInventory(sdk, appId, solutionScope, referencedGlo.map((r) => withDescription({ name: r.Name }, r.Description)));}- if (truncated) fail('globalChoices', truncated);} catch (err) {fail('globalChoices', err);}@@ -836,6 +812,11 @@ function parseDownloadedPages(pagesRoot, outDir, nameById, unreadable) {// table bindings vanished from the emitted spec. A BOM is an encoding marker, not content.config = JSON.parse(fs.readFileSync(configPath, 'utf8').replace(/^\uFEFF/, ''));if (!config || typeof config !== 'object' || Array.isArray(config)) throw new Error('config.json is not a JSON object');+ if (Object.prototype.hasOwnProperty.call(config, 'dataSources')) {+ if (!Array.isArray(config.dataSources)) throw new Error('config.json dataSources is present but is not an array');+ const bad = config.dataSources.find((value) => typeof value !== 'string' || !value.trim());+ if (bad !== undefined) throw new Error('config.json dataSources must be an array of non-empty table logical names');+ }} catch (e) {config = {};// Present but unreadable — report it rather than inventing empty metadata. A genuinely absent@@ -850,14 +831,14 @@ function parseDownloadedPages(pagesRoot, outDir, nameById, unreadable) {// A file that EXISTS but is blank or unreadable stays explicit, so it still fails closed.let prompt;try {- prompt = fs.readFileSync(path.join(dir, 'prompt.txt'), 'utf8').replace(/^\uFEFF/, '').trim();+ prompt = fs.readFileSync(path.join(dir, 'prompt.txt'), 'utf8').replace(/^\uFEFF/, '');} catch (e) {prompt = (e && e.code === 'ENOENT') ? undefined : '';}pages.push({pageId: entry,name: (nameById && nameById.get(String(entry).toLowerCase())) || entry,- dataSources: config.dataSources || [],+ dataSources: Object.prototype.hasOwnProperty.call(config, 'dataSources') ? config.dataSources : [],prompt,codeFile: path.relative(outDir, tsx).replace(/\\/g, '/'),});diff --git a/plugins/model-apps/scripts/genpage-plan-provenance.js b/plugins/model-apps/scripts/genpage-plan-provenance.jsindex 4fb2936f2..441140d5b 100644--- a/plugins/model-apps/scripts/genpage-plan-provenance.js+++ b/plugins/model-apps/scripts/genpage-plan-provenance.js@@ -20,14 +20,10 @@// what the run will touch — the page files of a create, the page id of an edit — and that is what is// compared: a stale plan from an earlier run, or one the planner re-derived, targets other pages.-const crypto = require('node:crypto');const fs = require('node:fs');const path = require('node:path');const { pagesTables } = require('./lib/page-file-targets.js');--function sha256(text) {- return crypto.createHash('sha256').update(String(text), 'utf8').digest('hex');-}+const { sha256 } = require('./lib/hash.js');// What a plan document targets.// create: the Pages table's File column — `## Pages` in the written plan, `### Pages (N total)`diff --git a/plugins/model-apps/scripts/genpage-upload.js b/plugins/model-apps/scripts/genpage-upload.jsindex d1a24ad5d..4bab7a783 100644--- a/plugins/model-apps/scripts/genpage-upload.js+++ b/plugins/model-apps/scripts/genpage-upload.js@@ -213,7 +213,20 @@ async function main(argv = process.argv.slice(2), deps = {}) {+ 'unknown --page-id as a create and would make a new page and report it as an update.',});}- const known = await enumerate();+ const enumeratePages = typeof cli.enumeratePages === 'function' ? cli.enumeratePages.bind(cli) : null;+ // The existence and membership listings are independent reads, each its own pac process of about+ // five seconds, so they run together. Measured live: a pair run one after the other averaged+ // 10.6 s and an overlapped pair 5.6 s, and all 20 overlapped listings succeeded. The VERDICTS are+ // still reached in the original order (existence first), so a given failure is reported as it+ // was before, and a listing that throws surfaces only when its verdict is reached: a page that+ // does not exist is reported as absent even if the app listing also broke.+ const settle = (fn) => Promise.resolve().then(fn).then((value) => ({ value }), (error) => ({ failed: true, error }));+ const [existence, membership] = await Promise.all([+ settle(enumerate),+ enumeratePages ? settle(() => enumeratePages(flags['app-id'], { includeUnpublished: true })) : null,+ ]);+ if (existence.failed) throw existence.error;+ const known = existence.value;if (!known || known.ok !== true) {return emit(false, {error: `cannot verify that page ${flags['page-id']} exists before updating it `@@ -228,6 +241,39 @@ async function main(argv = process.argv.slice(2), deps = {}) {+ '--page-id to create a page deliberately.',});}+ // EXISTENCE is not enough for an update: pac accepts a real page id together with ANY app id+ // and then writes the page under that app context, which renames it and attaches its table+ // bindings to the wrong app. The app-scoped list is sitemap/navigation membership, so prove the+ // page is actually placed in THIS app before the binding probe downloads content or upload writes.+ if (!enumeratePages) {+ return emit(false, {+ error: `cannot verify that page ${flags['page-id']} belongs to app ${flags['app-id']} — this pac `+ + 'wrapper exposes no app-scoped page listing. Refusing to upload, because updating a '+ + 'page through the wrong app id would rename it and attach its tables to that app.',+ });+ }+ if (membership.failed) throw membership.error;+ const appPages = membership.value;+ if (!appPages || appPages.ok !== true) {+ return emit(false, {+ error: `cannot verify that page ${flags['page-id']} belongs to app ${flags['app-id']} `+ + `(${(appPages && appPages.error) || 'unknown reason'})`,+ });+ }+ const pages = Array.isArray(appPages.pages) ? appPages.pages : [];+ if (!pages.length) {+ return emit(false, {+ error: `app ${flags['app-id']} has no generative pages, or could not be found — cannot verify `+ + `that page ${flags['page-id']} belongs to it`,+ });+ }+ const pageInApp = pages.some((p) => String(p && p.pageId || '').toLowerCase() === String(flags['page-id']).toLowerCase());+ if (!pageInApp) {+ return emit(false, {+ error: `page ${flags['page-id']} is not in app ${flags['app-id']}'s navigation — updating it `+ + 'with this app id would rename it and attach its tables to that app; use the id of the app the page belongs to',+ });+ }}// An UPDATE that says NOTHING about data sources must not DESTROY them. pac rewrites the page's@@ -270,6 +316,12 @@ async function main(argv = process.argv.slice(2), deps = {}) {if (cfg.dataSources !== undefined && !Array.isArray(cfg.dataSources)) {throw new Error(`config.json dataSources is ${typeof cfg.dataSources}, not an array`);}+ if (Array.isArray(cfg.dataSources)) {+ const bad = cfg.dataSources.find((value) => typeof value !== 'string' || !value.trim());+ if (bad !== undefined) {+ throw new Error('config.json dataSources must be an array of non-empty table logical names');+ }+ }preservedDataSources = Array.isArray(cfg.dataSources) ? cfg.dataSources : [];} catch (e) {// Fail CLOSED: guessing "probably none" is exactly the silent unbinding this exists to stop.diff --git a/plugins/model-apps/scripts/genpage-worker-output.js b/plugins/model-apps/scripts/genpage-worker-output.jsindex 18c33317d..f10a1b81e 100644--- a/plugins/model-apps/scripts/genpage-worker-output.js+++ b/plugins/model-apps/scripts/genpage-worker-output.js@@ -9,8 +9,8 @@const fs = require('node:fs');const path = require('node:path');-const crypto = require('node:crypto');-const { blankLiterals, endsMidStatement, findElisionMarker, hasDefaultExport, hasUnbalancedBrackets } = require('./lib/source-literals.js');+// The structural gate is shared with promote-intent-pages.js (see lib/page-structure.js).+const { pageStructureProblems: structuralProblems } = require('./lib/page-structure.js');// A worker that returns without writing leaves whatever was at its path before, and a complete page an// earlier attempt left there passes every content check: the stale page was deployed instead of taking@@ -22,7 +22,7 @@ const { blankLiterals, endsMidStatement, findElisionMarker, hasDefaultExport, ha// check with no stamp checks the content alone.const STAMP_SUFFIX = '.dispatch-stamp.json';const stampPathFor = (abs) => path.join(path.dirname(abs), `.${path.basename(abs)}${STAMP_SUFFIX}`);-const sha256 = (buf) => crypto.createHash('sha256').update(buf).digest('hex');+const { sha256 } = require('./lib/hash.js');function stampPageTarget({ filePath }) {if (!filePath) return { ok: false, action: 'stamp', problems: ['--file is required'] };@@ -87,24 +87,6 @@ function consumeStamp(abs) {try { fs.rmSync(stampPathFor(abs), { force: true }); } catch { /* best-effort: the next --stamp overwrites it */ }}-function structuralProblems(code) {- const text = String(code || '');- const problems = [];- if (!text.trim()) return ['file is empty'];- // hasDefaultExport also refuses a file cut off INSIDE its export (`export default function P(props)`- // with no body), so say so: the one inline rewrite should write the whole page, not add an export.- if (!hasDefaultExport(text)) problems.push('no complete default export — missing, or the file ends inside it');- if (hasUnbalancedBrackets(text)) problems.push('unbalanced brackets — output looks truncated');- // A cut that leaves every bracket balanced: inside JSX, a template or a comment, or after `a +`.- if (endsMidStatement(text)) problems.push('stops mid-statement — output looks truncated');- // On the blanked source, so a fence inside a template literal (a page rendering markdown help) is- // data; a fence wrapping the file — the model answered in markdown — is code-position text.- if (/^\s*(```|~~~)/m.test(blankLiterals(text))) problems.push('contains a markdown code fence');- const elision = findElisionMarker(text);- if (elision) problems.push(`contains ${elision}`);- return problems;-}-// Every outcome is a result, never a throw: `ok:false` is what sends the orchestrator to its one inline// rewrite, and a folder or an unreadable file at the page path used to throw out of readFileSync — an// uncaught CLI failure instead of that recovery. lstat, not existsSync, so a link there (dangling onesdiff --git a/plugins/model-apps/scripts/launch-playwright-mcp.js b/plugins/model-apps/scripts/launch-playwright-mcp.jsindex 0af8c1f30..36d71490b 100644--- a/plugins/model-apps/scripts/launch-playwright-mcp.js+++ b/plugins/model-apps/scripts/launch-playwright-mcp.js@@ -5,28 +5,14 @@// then falls back to Playwright's bundled Chromium.// Self-contained — no external dependencies required.-const { spawn } = require('child_process');const os = require('os');const path = require('path');const { detectBrowser } = require('./lib/detect-browser');--function quoteShellArg(value, platform = process.platform) {- const argument = String(value);-- if (platform === 'win32') {- if (argument.includes('"')) {- throw new Error('Cannot quote an argument containing double quotes for cmd.exe.');- }-- return `"${argument}"`;- }-- return `'${argument.replace(/'/g, "'\\''")}'`;-}+// npx is a batch shim on Windows; the runner starts it without a shell (see lib/process-runner.js).+const { spawnProcess } = require('./lib/process-runner');function buildMcpArgs(browser, {configPath = path.join(__dirname, 'playwright-mcp-fullscreen.config.json'),- platform = process.platform,} = {}) {return ['-y',@@ -34,13 +20,13 @@ function buildMcpArgs(browser, {'--browser',browser,'--config',- quoteShellArg(configPath, platform),+ configPath,];}function launch({browser = detectBrowser(),- spawnFn = spawn,+ spawnFn = spawnProcess,// Node passes (code, signal): on a SIGNAL termination `code` is null and `signal` is e.g.// 'SIGTERM'/'SIGSEGV'. `code || 0` therefore turned every crash and every kill into exit 0, so an// MCP host saw a server that had died as one that had shut down cleanly.@@ -66,10 +52,14 @@ function launch({process.exit(1);},} = {}) {- const child = spawnFn('npx', buildMcpArgs(browser), {- stdio: 'inherit',- shell: true,- });+ let child;+ try {+ child = spawnFn('npx', buildMcpArgs(browser), { stdio: 'inherit' });+ } catch (err) {+ // npx is not on PATH, or the config path cannot reach the npx shim unchanged.+ onError(err);+ return null;+ }child.on('exit', onExit);child.on('error', onError);@@ -80,4 +70,4 @@ if (require.main === module) {launch();}-module.exports = { buildMcpArgs, launch, quoteShellArg };+module.exports = { buildMcpArgs, launch };diff --git a/plugins/model-apps/scripts/lib/app-spec.js b/plugins/model-apps/scripts/lib/app-spec.jsindex 08c8cebd5..82dfc67c4 100644--- a/plugins/model-apps/scripts/lib/app-spec.js+++ b/plugins/model-apps/scripts/lib/app-spec.js@@ -524,13 +524,13 @@ const BUSINESS_RULE_SCOPES = ['Entity'];//// v1 is deliberately a SINGLE-ENTITY, linear flow: ordered stages, each with ordered steps bound to// columns of that same entity. The SDK's artifact additionally models `category`, `nextStageId`,-// `relationshipName`, `branch`, stage `actions` and `securityRoles`, and those are NOT exposed here:-// * cross-entity stages / branching change what the flow MEANS and need live verification per-// shape before being offered;-// * `securityRoles` needs role IDs (the SDK grants CRUD privileges on the backing table that-// ACTIVATION creates, via `reconcileBpfSecurityRoles({ roleId, access })`) — that is the-// `security` phase's job, not this one, and is tracked as a follow-up.-// Offering a knob the build cannot verify is how a spec deploys something the author did not mean.+// `relationshipName`, `branch` and stage `actions`, and those are NOT exposed here: cross-entity+// stages and branching change what the flow MEANS and need live verification per shape before being+// offered. Offering a knob the build cannot verify is how a spec deploys something the author did not+// mean. The SDK's `securityRoles` started on this list and has since shipped, in a different shape:+// persona names rather than role ids (validateBpfSecurityRoles below), applied by the `security`+// phase — the grants are privileges on the backing table that ACTIVATION creates, so they can only be+// written once both the flow and the personas' roles exist.const BPF_STATUSES = ['Active', 'Draft'];// `businessProcessFlows[].securityRoles` — who may run a flow. #513.diff --git a/plugins/model-apps/scripts/lib/apply-snapshot-store.js b/plugins/model-apps/scripts/lib/apply-snapshot-store.jsindex f0e0aa36e..60515a510 100644--- a/plugins/model-apps/scripts/lib/apply-snapshot-store.js+++ b/plugins/model-apps/scripts/lib/apply-snapshot-store.js@@ -255,14 +255,6 @@ function casWriteSnapshot(workspaceDir, envelope, expectedGeneration, deps = {})}}-// Unconditional persist under the lease (no CAS) — used to seed the very first snapshot or to write a-// freshly-minted envelope where no read-modify-write ordering matters. Prefer casWriteSnapshot on any-// update path.-function persistSnapshot(workspaceDir, envelope) {- writeSnapshotAtomic(workspaceDir, envelope);- return { ok: true };-}-// INVALIDATE-before-write: force eligible:false and persist, under the lease, ROTATING the generation so a// concurrent reader that captured the pre-invalidate generation can no longer win the re-bless CAS (Sol #6// fencing — invalidate/apply/re-bless without a long-held lease). Returns { ok, generation } where@@ -700,7 +692,6 @@ module.exports = {acquireLease,releaseLease,casWriteSnapshot,- persistSnapshot,invalidateSnapshot,tombstoneSnapshot,claimBaselineSnapshot,diff --git a/plugins/model-apps/scripts/lib/apply-snapshot.js b/plugins/model-apps/scripts/lib/apply-snapshot.jsindex 9c9cf89f3..fd5f737f0 100644--- a/plugins/model-apps/scripts/lib/apply-snapshot.js+++ b/plugins/model-apps/scripts/lib/apply-snapshot.js@@ -105,14 +105,6 @@ function identityMatches(envelope, live) {return { ok: true, reason: 'identity matches' };}-function hasDebt(envelope) {- return isEnvelope(envelope) && envelope.debt.length > 0;-}--function listDebt(envelope) {- return isEnvelope(envelope) ? envelope.debt.slice() : [];-}-// Record a debt: an artifact whose intended state could NOT be safely applied incrementally (an// unsupported edit, a removal, a chart/command/dashboard/web-resource-content change). While ANY debt is// present the snapshot can never become eligible. Deduped by (artifactType|identity|reason) so re-running@@ -222,8 +214,6 @@ module.exports = {parseEnvelope,serializeEnvelope,identityMatches,- hasDebt,- listDebt,addDebt,clearDebtMatching,markIneligible,diff --git a/plugins/model-apps/scripts/lib/artifact-intent.js b/plugins/model-apps/scripts/lib/artifact-intent.jsindex 5bd6f77b8..4297eaf31 100644--- a/plugins/model-apps/scripts/lib/artifact-intent.js+++ b/plugins/model-apps/scripts/lib/artifact-intent.js@@ -32,10 +32,13 @@ function clampedCellSpan(cell, columns) {// True when `cell` still fits on the END of `row`. This is the exact complement of the// "start a new row" test in rowsFromCells (`used + span > cols && current.length`): an EMPTY row// always accepts the cell, because a span wider than the section is clamped to it rather than-// overflowing into a row of its own.-function cellFitsInRow(row, cell, columns) {+// overflowing into a row of its own. `reserved` lets the reconcile path apply the SAME packing rule+// to rows under a row-spanning cell: those carried columns count as used capacity, so a visually empty+// row fully reserved by a span above must not accept another cell.+function cellFitsInRow(row, cell, columns, reserved = 0) {const cols = Math.max(1, Math.min(4, columns || 1));- const used = ((row && row.cells) || []).reduce((n, c) => n + clampedCellSpan(c, cols), 0);+ const own = ((row && row.cells) || []).reduce((n, c) => n + clampedCellSpan(c, cols), 0);+ const used = own + Math.max(0, Number(reserved) || 0);return used === 0 || used + clampedCellSpan(cell, cols) <= cols;}@@ -912,6 +915,9 @@ module.exports = {mergeFieldOptions,clampedCellSpan,cellFitsInRow,+ // Shared with projection.js, whose changed-only verifier must skip exactly the controls this+ // compiler skips; a second copy of the class-id set had to be kept in sync by hand.+ isNonFieldControl,// Exported for the build's in-place repack: a span widened on a DEPLOYED form can overflow its// row, and the reconcile must re-pack it with the SAME rule the create path uses, not a second// implementation that can drift.diff --git a/plugins/model-apps/scripts/lib/dataverse-auth.js b/plugins/model-apps/scripts/lib/dataverse-auth.jsindex 3e789e4d1..16cd7ba63 100644--- a/plugins/model-apps/scripts/lib/dataverse-auth.js+++ b/plugins/model-apps/scripts/lib/dataverse-auth.js@@ -4,42 +4,135 @@// Uses Azure CLI (`az account get-access-token`) for auth — same MSAL cache that pac CLI uses.// All operation scripts (provision-entities.js, provision-solution.js, etc.) import from this module.-const { execFileSync } = require('child_process');// Shared with the App Spec + CLI so the provisioned-language probe and the validator cannot disagree// about what counts as an LCID. app-spec.js does not require this module, so there is no cycle.const { normalizeLanguageCode } = require('./app-spec.js');const { nearestName } = require('./nearest-name.js');+const { execFileAsync, runSync } = require('./process-runner.js');++// Dataverse environment hosts, one family per cloud (the same families power-pages accepts in+// scripts/lib/validation-helpers.js, plus the non-numbered `crm<ring>` labels such as crmtest):+// Commercial/GCC: <org>[.api].crm<region>.dynamics.com e.g. contoso.crm.dynamics.com, contoso.crm4.dynamics.com+// GCC High: <org>[.api].crm.microsoftdynamics.us+// DoD: <org>[.api].crm.appsplatform.us+// China: <org>[.api].crm.dynamics.cn+// See: https://learn.microsoft.com/power-apps/developer/data-platform/discovery-service#global-discovery-service+const DATAVERSE_HOST = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.(?:api\.)?(?:crm[a-z0-9]*\.dynamics\.com|crm\.microsoftdynamics\.us|crm\.appsplatform\.us|crm\.dynamics\.cn)$/;++/**+ * The canonical origin of a Dataverse environment URL, or null when the value is anything else.+ *+ * Every Dataverse call starts here: the result is the `--resource` a token is requested for, the base+ * every request URL is built on, and the only origin a token is ever sent to. So the RAW text is+ * checked, not a parsed-and-reserialised URL: it must be literally `https://` + a host of letters,+ * digits, dots and hyphens, optionally followed by slashes. Parsing first would not do: the URL+ * parser accepts characters in a path, and in some hosts, that must never reach a command line.+ * @returns {string|null} e.g. "https://contoso.crm.dynamics.com"+ */+function dataverseOrigin(value) {+ if (typeof value !== 'string') return null;+ const m = /^https:\/\/([A-Za-z0-9.-]+)\/*$/i.exec(value.trim());+ if (!m) return null;+ const host = m[1].toLowerCase();+ return DATAVERSE_HOST.test(host) ? `https://${host}` : null;+}++function requireDataverseOrigin(value) {+ const origin = dataverseOrigin(value);+ if (!origin) {+ throw new Error(+ `'${value}' is not a Dataverse environment URL. Pass the environment's https origin only, `+ + 'for example https://contoso.crm.dynamics.com (no path, query, port or credentials).'+ );+ }+ return origin;+}/*** Gets an Azure CLI access token for the given Dataverse environment URL.- * Returns null if `az` is missing, the user isn't logged in, or the resource is unreachable.+ * Returns null if `az` is missing, the user isn't logged in, the resource is unreachable, or the+ * value is not a Dataverse environment origin (then no process is started at all).* @param {string} envUrl - e.g. "https://contoso.crm.dynamics.com"+ * @param {object} [opts]+ * @param {boolean} [opts.fresh=false] bypass the process memo and replace it with a new token+ * @param {Function} [opts.exec=runSync] test seam for the Azure CLI subprocess* @returns {string|null}*/-function getAuthToken(envUrl) {+const authTokenMemo = new Map();++function getAuthToken(envUrl, opts = {}) {+ const resource = dataverseOrigin(envUrl);+ if (!resource) return null;+ const exec = opts.exec || runSync;+ if (!opts.fresh && authTokenMemo.has(resource)) {+ return authTokenMemo.get(resource);+ }try {- const out = execFileSync(+ const out = exec('az',- ['account', 'get-access-token', '--resource', envUrl, '--query', 'accessToken', '-o', 'tsv'],- { encoding: 'utf8', timeout: 30000, stdio: ['ignore', 'pipe', 'pipe'], shell: process.platform === 'win32' }+ ['account', 'get-access-token', '--resource', resource, '--query', 'accessToken', '-o', 'tsv'],+ { encoding: 'utf8', timeout: 30000, stdio: ['ignore', 'pipe', 'pipe'] });- return out.trim() || null;+ const token = out.trim() || null;+ // `az account get-access-token` is expensive on a cold Windows process, but an immediate+ // re-call returns the same MSAL-cached token (see the ensureOk 401 note below). Reusing that+ // non-null token within this Node process removes repeated CLI cold-starts without changing+ // Dataverse semantics; a caller that just saw a 401 passes `{ fresh: true }` to replace it.+ if (token) authTokenMemo.set(resource, token);+ else authTokenMemo.delete(resource);+ return token;} catch {+ if (opts.fresh) authTokenMemo.delete(resource);return null;}}+function getAuthTokenAsync(envUrl, opts = {}) {+ const resource = dataverseOrigin(envUrl);+ if (!resource) return Promise.resolve(null);+ const exec = opts.execFile || execFileAsync;+ if (!opts.fresh && authTokenMemo.has(resource)) {+ return Promise.resolve(authTokenMemo.get(resource));+ }+ return new Promise((resolve) => {+ try {+ exec(+ 'az',+ ['account', 'get-access-token', '--resource', resource, '--query', 'accessToken', '-o', 'tsv'],+ { encoding: 'utf8', timeout: 30000, windowsHide: true },+ (error, stdout) => {+ if (error) {+ if (opts.fresh) authTokenMemo.delete(resource);+ resolve(null);+ return;+ }+ const token = String(stdout || '').trim() || null;+ // Shares the synchronous helper's memo deliberately: check-auth can pre-warm the token+ // without blocking the event loop, and later synchronous Dataverse callers in the same+ // process still avoid a second Azure CLI cold start.+ if (token) authTokenMemo.set(resource, token);+ else authTokenMemo.delete(resource);+ resolve(token);+ }+ );+ } catch {+ if (opts.fresh) authTokenMemo.delete(resource);+ resolve(null);+ }+ });+}+/*** Reads the Azure CLI identity that will supply the Dataverse token. Best-effort and never throws —* it exists to make a failure explicable, so it must not become a failure of its own.* @returns {{user: string, tenantId: string}|null}*/-function azIdentity() {+function azIdentity(deps = {}) {try {- const out = execFileSync(+ const out = (deps.exec || runSync)('az',['account', 'show', '--query', '{user:user.name,tenantId:tenantId}', '-o', 'json'],- { encoding: 'utf8', timeout: 30000, stdio: ['ignore', 'pipe', 'pipe'], shell: process.platform === 'win32' }+ { encoding: 'utf8', timeout: 30000, stdio: ['ignore', 'pipe', 'pipe'] });const parsed = JSON.parse(out);return parsed && parsed.user ? { user: parsed.user, tenantId: parsed.tenantId || '(unknown)' } : null;@@ -68,38 +161,6 @@ function azIdentity() {* and never throws — it is a diagnostic.* WhoAmI: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/whoami*/-/**- * Reject anything that is not an absolute HTTPS origin BEFORE a token is acquired or sent.- *- * This is STRICTER than `createAzHttpClient`, deliberately, and the difference matters. That client- * requires an absolute `https:` org URL and refuses to send its token to a different ORIGIN — but it- * compares origins, so a path-bearing `--env` passes construction untouched. This gate additionally- * rejects a path, query or fragment, because the preflight runs earlier and goes through- * `dataverseRequest`, whose transport picks plain `http` for any non-HTTPS scheme- * (`u.protocol === 'https:' ? https : http`). Without it a malformed `--env` could put a bearer token- * on the wire in clear text before the client's fail-closed validation ever ran — the preflight would- * have become a hole in the credential boundary it sits in front of.- * @returns {string|null} the normalized origin, or null when the value is unusable- */-function httpsOriginOrNull(envUrl) {- try {- const raw = String(envUrl == null ? '' : envUrl).trim();- if (!raw) return null;- const u = new URL(raw);- if (u.protocol !== 'https:') return null;- // An ORIGIN, strictly. A value carrying a path, query or fragment is REJECTED rather than- // silently trimmed to its origin: `dataverseRequest` appends `/api/data/...` to whatever it is- // given, so `https://org.crm.dynamics.com/some/path` would produce `.../some/path/api/data/...`- // and the preflight would report a misleading result about a URL nobody asked for. Rejecting is- // also the tighter credential boundary — this function's whole job is to decide where a bearer- // token may be sent, so "close enough" is the wrong disposition.- if ((u.pathname && u.pathname !== '/') || u.search || u.hash) return null;- return u.origin;- } catch {- return null;- }-}-async function preflightAuth(envUrl, deps = {}) {const getToken = deps.getToken || getAuthToken;const request = deps.request || dataverseRequest;@@ -120,11 +181,11 @@ async function preflightAuth(envUrl, deps = {}) {// Normalize to the validated ORIGIN and use it from here on. Validating one string and then// requesting with another is how a check becomes decorative.- const origin = httpsOriginOrNull(envUrl);+ const origin = dataverseOrigin(envUrl);if (!origin) {return {ok: false,- error: `refusing to authenticate against '${envUrl}': the environment must be an absolute https:// ORIGIN `+ error: `refusing to authenticate against '${envUrl}': the environment must be a Dataverse https:// ORIGIN `+ '(scheme + host only, no path, query or fragment). A bearer token is attached to this request, so a '+ 'non-HTTPS, path-bearing or malformed target is rejected before any token is acquired.',};@@ -230,9 +291,10 @@ function makeRequest({ url, method = 'GET', headers = {}, body = null, includeHetimeout,},(res) => {- let data = '';- res.on('data', (chunk) => (data += chunk));+ const chunks = [];+ res.on('data', (chunk) => chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)));res.on('end', () => {+ const data = Buffer.concat(chunks).toString('utf8');const result = { statusCode: res.statusCode, body: data };if (includeHeaders) result.headers = res.headers;resolve(result);@@ -263,7 +325,8 @@ function makeRequest({ url, method = 'GET', headers = {}, body = null, includeHe* @returns {Promise<{status: number, data: any, headers?: object}>}*/async function dataverseRequest(envUrl, method, apiPath, body = null, opts = {}) {- const cleanUrl = envUrl.replace(/\/+$/, '');+ // The validated origin, never the caller's text, is what the token is requested for and sent to.+ const cleanUrl = requireDataverseOrigin(envUrl);const url = `${cleanUrl}/api/data/v9.2/${apiPath}`;const bodyStr = body == null ? null : typeof body === 'string' ? body : JSON.stringify(body);const { includeHeaders = false, extraHeaders = {}, timeout = 60000, token: presetToken = null } = opts;@@ -279,7 +342,7 @@ async function dataverseRequest(envUrl, method, apiPath, body = null, opts = {})// different diagnoses — and would otherwise fetch the very same token twice in a row.// The 401 refresh path below still re-acquires from the CLI, because a preset token that has just// been rejected is exactly the thing that must not be retried.- let token = presetToken || acquireToken(cleanUrl);+ let token = presetToken || acquireToken(cleanUrl, { fresh: false });if (!token) {throw new Error(`Failed to get Azure CLI token for ${cleanUrl}. Run 'az login' first.`);}@@ -303,7 +366,7 @@ async function dataverseRequest(envUrl, method, apiPath, body = null, opts = {})}if (res.statusCode === 401 && attempt < maxRetries) {- token = acquireToken(cleanUrl);+ token = acquireToken(cleanUrl, { fresh: true });if (!token) throw new Error("Token refresh failed. Run 'az login' again.");continue;}@@ -386,26 +449,6 @@ function requiredLevel(level = 'None') {};}-/**- * Discovers the publisher prefix for the default solution in this env.- * Falls back to "new" if the query fails.- * @param {string} envUrl- * @returns {Promise<string>}- */-async function getDefaultPublisherPrefix(envUrl) {- try {- const res = await dataverseRequest(- envUrl,- 'GET',- "solutions?$select=uniquename&$filter=uniquename eq 'Default'&$expand=publisherid($select=customizationprefix)&$top=1"- );- const prefix = res?.data?.value?.[0]?.publisherid?.customizationprefix;- return prefix || 'new';- } catch {- return 'new';- }-}-/*** The set of LCIDs this organization actually has provisioned.*@@ -673,15 +716,17 @@ function emitResult(ok, payload) {}module.exports = {+ dataverseOrigin,+ requireDataverseOrigin,preflightAuth,azIdentity,getAuthToken,+ getAuthTokenAsync,makeRequest,dataverseRequest,ensureOk,label,requiredLevel,- getDefaultPublisherPrefix,readProvisionedLanguages,readOrgLanguageCode,parseArgs,diff --git a/plugins/model-apps/scripts/lib/feature-flags.js b/plugins/model-apps/scripts/lib/feature-flags.jsindex 5ab43d0d4..1f92a8d03 100644--- a/plugins/model-apps/scripts/lib/feature-flags.js+++ b/plugins/model-apps/scripts/lib/feature-flags.js@@ -10,15 +10,15 @@// ahead of GA and flip it on in a one-line follow-up PR (or per-run via env var)// once the dependencies are released — instead of carrying an un-merged branch.//-// A GA flag is flipped to `true` FIRST and removed in a later change, not both at once.+// A flag is flipped to `true` FIRST and removed in a later change, not both at once.// Flipping is reversible in one line if the rollout turns out to be incomplete in some// tenant; deleting the gate in the same change that enables the feature leaves no way-// back except a revert. `connectors` is in that window now: GA, shipping `true`, gate-// retained as a rollback switch.+// back except a revert. Once a release has shipped with the flag on and no rollback was+// needed, remove it so unknown flags fail closed instead of staying permanently probed.//// Precedence (highest first), mirroring the telemetry opt-out convention in// AGENTS.md where an env var overrides committed config:-// 1. env var GENPAGE_ENABLE_<FLAG> (e.g. GENPAGE_ENABLE_CONNECTORS)+// 1. env var GENPAGE_ENABLE_<FLAG>// 2. committed feature-flags.json at the plugin root// 3. default: false (fail-closed — unknown/unset flags are OFF)//@@ -33,6 +33,44 @@ const path = require('node:path');// The committed flag file lives at the plugin root; from scripts/lib that's two up.const FLAGS_PATH = path.resolve(__dirname, '..', '..', 'feature-flags.json');+// Catalog of every flag the skill knows about, with lifecycle status so makers+// and devs can see what is experimental / in-progress vs GA. `status` is one of+// 'experimental' | 'in-progress' | 'ga'. Keep this the single source of truth —+// feature-flags.json only carries the on/off value; this catalog carries the+// metadata (what it enables, what it depends on, how to turn it on).+const FLAGS = {+ 'custom-api': {+ status: 'in-progress',+ summary:+ 'GenPage Dataverse Custom API (plug-in) invocation — calling a Custom API Action or Function ' ++ 'from a generated page via dataApi.executeAction / executeFunction / listBoundActions, gated by ' ++ "the page's revision-bound actionBindings manifest.",+ dependencies:+ 'the AIBuilder CoderAgent action prompt, the shared pai-gen-ux-action-runtime plus the UCI ' ++ 'and Controls host runtimes, a pac CLI `model genpage upload --actions` verb ' ++ '(PowerPlatform-Scale-AdminTools) to persist actionBindings into config.json, and the ' ++ 'GenUxPluginActionAllowList ECS setting — all live in PROD.',+ enableEnv: 'GENPAGE_ENABLE_CUSTOM_API=1',+ },+ 'custom-telemetry': {+ status: 'in-progress',+ summary:+ 'Custom page telemetry — a generated page reporting its own events, metrics, traces and ' ++ "exceptions to the customer's Application Insights resource via an optional props.appInsights " ++ 'surface, emitted only when the maker explicitly asks to measure or track something.',+ dependencies:+ 'the page telemetry facade in the UCI host runtime, the GenUX authoring control ' ++ '(power-platform-ux), the AIBuilder CoderAgent telemetry prompt, and the ' ++ 'GenUxEnableCustomTelemetry ECS setting — all live in PROD.',+ enableEnv: 'GENPAGE_ENABLE_CUSTOM_TELEMETRY=1',+ },+};++// Flag names the skill knows about, derived from the catalog. Used to validate the+// committed file (catch typo'd keys that would silently stay OFF — or, after a flip+// to true, an unintended key) and to enumerate state via `describe()`.+const KNOWN_FLAGS = Object.keys(FLAGS);+// Truthy env values follow the common CLI convention (dotnet/bash style):// 1/true/yes/on enable; 0/false/no/off disable; anything else (including unset// or empty) returns null so the caller defers to the next precedence layer@@ -46,7 +84,7 @@ function parseBool(value) {return null;}-// 'connectors' -> GENPAGE_ENABLE_CONNECTORS. Non-alphanumeric runs in a flag name+// 'custom-api' -> GENPAGE_ENABLE_CUSTOM_API. Non-alphanumeric runs in a flag name// collapse to a single '_' so multi-word flags still map to a legal env var name.function envVarName(flag) {return 'GENPAGE_ENABLE_' + String(flag).toUpperCase().replace(/[^A-Z0-9]+/g, '_');@@ -75,91 +113,21 @@ function readFlagsFile(flagsPath) {* @returns {boolean}*/function isEnabled(flag, opts = {}) {+ if (!Object.prototype.hasOwnProperty.call(FLAGS, flag)) return false;+const env = opts.env || process.env;const envValue = parseBool(env[envVarName(flag)]);- if (envValue !== null) return envValue; // env override wins+ if (envValue !== null) return envValue; // env override wins for known flags onlyconst flags = opts.flags || readFlagsFile(opts.flagsPath || FLAGS_PATH);// Strictly === true; anything else (false, missing, non-boolean) is OFF.return flags[flag] === true;}-function isConnectorsEnabled(opts) {- return isEnabled('connectors', opts);-}-function isCustomApiEnabled(opts) {return isEnabled('custom-api', opts);}-// Catalog of every flag the skill knows about, with lifecycle status so makers-// and devs can see what is experimental / in-progress vs GA. `status` is one of-// 'experimental' | 'in-progress' | 'ga'. Keep this the single source of truth —-// feature-flags.json only carries the on/off value; this catalog carries the-// metadata (what it enables, what it depends on, how to turn it on).-const FLAGS = {- connectors: {- status: 'ga',- summary:- 'GenPage connector authoring (SharePoint, weather, Office 365, SQL, custom REST) ' +- 'and ALM packaging of connection references.',- dependencies:- 'pac CLI connector verbs (PowerPlatform-Scale-AdminTools), the GenUX authoring ' +- 'control (power-platform-ux), and the maker/admin ECS setting — all live in PROD.',- enableEnv: 'GENPAGE_ENABLE_CONNECTORS=1',- },- 'custom-api': {- status: 'in-progress',- summary:- 'GenPage Dataverse Custom API (plug-in) invocation — calling a Custom API Action or Function ' +- 'from a generated page via dataApi.executeAction / executeFunction / listBoundActions, gated by ' +- "the page's revision-bound actionBindings manifest.",- dependencies:- 'the AIBuilder CoderAgent action prompt, the shared pai-gen-ux-action-runtime plus the UCI ' +- 'and Controls host runtimes, a pac CLI `model genpage upload --actions` verb ' +- '(PowerPlatform-Scale-AdminTools) to persist actionBindings into config.json, and the ' +- 'GenUxPluginActionAllowList ECS setting — all live in PROD.',- enableEnv: 'GENPAGE_ENABLE_CUSTOM_API=1',- },- 'custom-telemetry': {- status: 'in-progress',- summary:- 'Custom page telemetry — a generated page reporting its own events, metrics, traces and ' +- "exceptions to the customer's Application Insights resource via an optional props.appInsights " +- 'surface, emitted only when the maker explicitly asks to measure or track something.',- dependencies:- 'the page telemetry facade in the UCI host runtime, the GenUX authoring control ' +- '(power-platform-ux), the AIBuilder CoderAgent telemetry prompt, and the ' +- 'GenUxEnableCustomTelemetry ECS setting — all live in PROD.',- enableEnv: 'GENPAGE_ENABLE_CUSTOM_TELEMETRY=1',- },-};--// Flag names the skill knows about, derived from the catalog. Used to validate the-// committed file (catch typo'd keys that would silently stay OFF — or, after a flip-// to true, an unintended key) and to enumerate state via `describe()`.-const KNOWN_FLAGS = Object.keys(FLAGS);--// Fail-closed gate shared by every connector script entry point. Centralizing it-// (instead of each script inlining the same `if (!isConnectorsEnabled()) exit 3`)-// keeps the disabled message and exit code (3 = "feature off", distinct from-// 1 = runtime/usage error) consistent and prevents drift. `exit`/`write` are-// injectable for unit testing.-//-// connectors is GA and ships ON, so this normally does nothing. It is retained for one-// release as the rollback path: if the cross-repo dependencies turn out to be incomplete-// in some tenant, `"connectors": false` restores the previous behaviour in one line-// rather than requiring a revert.-function exitIfConnectorsDisabled(opts = {}) {- const exit = opts.exit || process.exit;- const write = opts.write || ((s) => process.stderr.write(s));- if (!isConnectorsEnabled(opts)) {- write(connectorsDisabledMessage() + '\n');- return exit(3);- }- return undefined;-}-// Fail-closed gate shared by every Custom API (Dataverse Action/Function) script entry// point: exit 3 = "feature off", distinct from 1 = runtime/usage error, so a caller can tell// "not released" from "it broke". Centralizing it (instead of each script inlining the same@@ -209,18 +177,6 @@ function validateFlags(flags) {return warnings;}-// Standard operator-facing message printed when a connector entrypoint is invoked-// while the flag is OFF. Centralized so every connector script speaks with one voice.-function connectorsDisabledMessage() {- return (- 'Connector support is disabled (feature flag "connectors" is OFF). ' +- 'It is GA and ships ON, so this means it was explicitly turned off — either ' +- 'GENPAGE_ENABLE_CONNECTORS=0 in this environment, or "connectors": false in ' +- 'plugins/model-apps/feature-flags.json. Set it back to true (or unset the env var) ' +- 'to re-enable connector authoring.'- );-}-// Standard operator-facing message printed when a Custom API entrypoint is invoked while// the flag is OFF. Centralized so every Custom API script speaks with one voice about why it// stopped and how to turn the feature on.@@ -237,11 +193,8 @@ function customApiDisabledMessage() {module.exports = {isEnabled,- isConnectorsEnabled,isCustomApiEnabled,- connectorsDisabledMessage,customApiDisabledMessage,- exitIfConnectorsDisabled,exitIfCustomApiDisabled,describe,validateFlags,diff --git a/plugins/model-apps/scripts/lib/form-occupancy.js b/plugins/model-apps/scripts/lib/form-occupancy.jsnew file mode 100644index 000000000..8f9e7658c--- /dev/null+++ b/plugins/model-apps/scripts/lib/form-occupancy.js@@ -0,0 +1,60 @@+'use strict';+// One FormXML row-occupancy model shared by build and verify. Row-spanning cells reserve+// capacity in later rows, and the build must make the same calculation verify enforces so it+// never writes a layout that verify rejects. Raw shape in a two-column section:+// rows: [a rowspan=2] / [b, c]+// row 2: own 2 + reserved 1 (a) = 3 columns++function cellWidth(cell) {+ return Number(cell && cell.colspan) || 1;+}++function rowOccupancy(rows) {+ const occupancy = [];+ let carried = [];+ for (const row of rows || []) {+ const own = ((row && row.cells) || []).reduce((n, cell) => n + cellWidth(cell), 0);+ const reserved = carried.reduce((n, reservation) => n + reservation.width, 0);+ occupancy.push({ own, reserved, used: own + reserved });++ carried = carried+ .map((reservation) => ({ width: reservation.width, left: reservation.left - 1 }))+ .filter((reservation) => reservation.left > 0);+ for (const cell of ((row && row.cells) || [])) {+ const rowspan = Number(cell && cell.rowspan) || 1;+ if (rowspan > 1) carried.push({ width: cellWidth(cell), left: rowspan - 1 });+ }+ }+ return occupancy;+}++function fitsGrid(rows, width) {+ const gridWidth = Number(width);+ if (!Number.isFinite(gridWidth) || gridWidth < 1) return false;+ return rowOccupancy(rows).every((row) => row.used <= gridWidth);+}++// The rows a departing cell left holding nothing, as indexes into `rows` (the section's rows AFTER the+// cell was pruned or moved away), bottom-up so removing them in that order keeps every earlier index valid.+//+// A cell occupies its own row and, with rowspan r, a slot in each of the r - 1 rows beneath it. Any of+// those rows that now has no cell AND no slot reserved by a row-spanning cell still above it renders as+// a blank line. A row that is empty but still reserved is NOT blank: the span above occupies it, and+// deleting it would pull every row beneath it up under that span. In a 2-column section:+// before: [x, b rs2] / [c] / [d]+// after c moves away: [x, b rs2] / [] / [d] row 2 keeps b's reserved slot, so it stays+// deleting row 2 instead gives [x, b rs2] / [d], which puts d beside b's span: a different layout.+// Only the rows this cell touched are considered, so an empty row that was already there stays.+function strandedRows(rows, rowIndex, span = 1) {+ const list = rows || [];+ const occupancy = rowOccupancy(list);+ const last = Math.min(list.length - 1, rowIndex + Math.max(1, Number(span) || 1) - 1);+ const stranded = [];+ for (let i = last; i >= rowIndex; i -= 1) {+ const cells = (list[i] && list[i].cells) || [];+ if (!cells.length && occupancy[i] && occupancy[i].reserved === 0) stranded.push(i);+ }+ return stranded;+}++module.exports = { rowOccupancy, fitsGrid, strandedRows };diff --git a/plugins/model-apps/scripts/lib/genpage-cli.js b/plugins/model-apps/scripts/lib/genpage-cli.jsindex d31059388..d16b31359 100644--- a/plugins/model-apps/scripts/lib/genpage-cli.js+++ b/plugins/model-apps/scripts/lib/genpage-cli.js@@ -2,57 +2,72 @@// Injectable wrapper around `pac model genpage upload/list` — the seam the build's pages phase uses// to author/deploy generative pages. Page CONTENT only: uploads run WITHOUT --add-to-sitemap because// the SDK owns the sitemap (it writes the GenPage subareas). Real impl spawns pac; tests inject `run`.-const { spawnSync } = require('node:child_process');+const { invocation, spawnProcess } = require('./process-runner.js');const fs = require('node:fs');const os = require('node:os');const path = require('node:path');-// Quote an arg for a Windows/POSIX shell command line (needed because pac resolves as pac.cmd on-// Windows, which requires shell:true — and shell:true does not quote an args array). Embedded-// newlines terminate the Windows command line (pac then sees a truncated command and dumps its-// help), so collapse them to spaces first. This is now purely a DEFENSIVE net for whatever args-// still flow inline — e.g. a page --name; it is NOT how multi-line prompts survive. upload() passes-// the prompt and agent-message to pac BY FILE (--prompt-file/--agent-message-file) precisely because-// collapsing THEIR newlines was lossy (a downloaded prompt is a multi-line conversation transcript).-function quoteArg(a) {- const s = String(a).replace(/\r\n|[\r\n]/g, ' ');- const q = s.replace(/"/g, '""').replace(/%/g, '"^%"');- // cmd.exe expands %VAR% even inside double quotes; break out of the quoted segment and caret-escape- // each percent so prompts/names containing environment-variable syntax round-trip literally.- if (!/[\s"'&|<>^()%]/.test(s)) return s;- // A run of backslashes immediately before the closing quote must be DOUBLED. Windows command-line- // parsing treats `\"` as an escaped quote, so a directory argument ending in a separator —- // --output-directory "C:\Users\Power User\download\"- // — escaped its own closing quote and swallowed the following flags into the path. MEASURED via a- // real cmd.exe parse:- // ["--output-directory", "C:\\Users\\Power User\\download\" --app-id after"]- // Only the trailing run matters: an interior `\` is literal to the parser, so escaping those would- // corrupt every ordinary Windows path.- // See: https://learn.microsoft.com/cpp/cpp/main-function-command-line-args#parsing-c-command-line-arguments- const trailingSlashesDoubled = q.replace(/(\\+)$/, (m) => m + m);- return `"${trailingSlashesDoubled}"`;+// Build the spawn call for a `pac` call. `pac` is resolved to an absolute path on PATH, never from+// the project directory, and started without a shell: `pac.exe` (a dotnet-tool install) directly,+// with every argument passed as-is, and a `pac.cmd` shim through cmd.exe with each argument checked+// or refused (lib/process-runner.js explains the rules). Embedded newlines are collapsed to spaces on+// every arg — a DEFENSIVE net for any arg that still flows inline (e.g. a page --name), since a+// newline would end a batch shim's command line. It is not relied on for prompts: upload() passes+// prompt/agent-message via file precisely because collapsing THEIR newlines was lossy for multi-line+// transcripts.+// @returns {{file: string, args: string[], options: object}}+// @throws when pac is not on PATH, or an argument cannot reach a pac.cmd shim unchanged+const cleanPacArgs = (args) => args.map((a) => String(a).replace(/\r\n|[\r\n]/g, ' '));+function buildPacInvocation(args, deps = {}) {+ return invocation('pac', cleanPacArgs(args), deps);}--// Build the spawnSync invocation for a `pac` call, per platform. Windows: pac resolves as pac.cmd,-// which requires a shell; shell:true ignores an args array, so pass a single cmd-quoted command-// line ("" escapes an embedded quote). POSIX: spawn pac directly with the args array (no shell) so-// embedded quotes and other shell metacharacters round-trip verbatim instead of being mangled by-// cmd-style quoting. Embedded newlines are still collapsed to spaces on every arg — a DEFENSIVE net-// for any arg that still flows inline (e.g. a page --name), since a newline truncates the Windows-// command line. It is no longer relied on for prompts: upload() passes prompt/agent-message via file-// precisely because collapsing THEIR newlines was lossy for multi-line transcripts.-function buildPacInvocation(args, platform = process.platform) {- const clean = args.map((a) => String(a).replace(/\r\n|[\r\n]/g, ' '));- if (platform === 'win32') {- return { command: 'pac ' + clean.map(quoteArg).join(' '), args: undefined, options: { encoding: 'utf8', shell: true } };- }- return { command: 'pac', args: clean, options: { encoding: 'utf8' } };-}-function runPac(args) {- const inv = buildPacInvocation(args);- const r = inv.args ? spawnSync(inv.command, inv.args, inv.options) : spawnSync(inv.command, inv.options);- return { status: r.status == null ? 1 : r.status, stdout: r.stdout || '', stderr: r.stderr || '' };+ // Asynchronous, and it NEVER rejects. It was spawnSync, which froze the whole process for the+ // length of every pac call — about five seconds for one `pac model genpage list` — so two+ // independent listings could not overlap even when a caller awaited them together (an update in+ // genpage-upload.js does). Every caller already awaits `run`, and branches on `status` without a+ // catch, so a child that cannot be started resolves as a failed result, as spawnSync's did.+ //+ // Output is collected as raw Buffers and decoded ONCE, when the child closes. Decoding each chunk+ // as it arrives corrupts a multibyte UTF-8 character that a pipe read happens to split, and pac+ // prints page names, which are user text; spawnSync's `encoding: 'utf8'` decoded the whole buffer,+ // so this keeps that behaviour. It also drops spawnSync's 1 MiB maxBuffer, past which the child+ // was killed and its output truncated.+ return new Promise((resolve) => {+ const out = [];+ const err = [];+ let settled = false;+ const finish = (status, launchError) => {+ if (settled) return;+ settled = true;+ const stderr = Buffer.concat(err).toString('utf8');+ resolve({+ status: status == null ? 1 : status,+ stdout: Buffer.concat(out).toString('utf8'),+ // POSIX reports a missing pac as a spawn 'error' (ENOENT) with nothing on stderr; carry its+ // message so the diagnostic says why instead of "pac exited 1 with no output".+ stderr: stderr || (launchError ? String(launchError.message || launchError) : ''),+ });+ };+ let child;+ try {+ // Resolution and argument checks throw here too, and resolve as a failed result like a launch error.+ child = spawnProcess('pac', cleanPacArgs(args), { stdio: ['ignore', 'pipe', 'pipe'] });+ } catch (e) {+ finish(1, e);+ return;+ }+ // EMFILE/ENFILE leave the stdio pipes unset, hence the guards.+ if (child.stdout) child.stdout.on('data', (c) => out.push(c));+ if (child.stderr) child.stderr.on('data', (c) => err.push(c));+ // 'error' (the child could not be started) may or may not be followed by 'close'; `finish`+ // keeps whichever comes first. 'close' rather than 'exit': 'exit' fires as soon as pac itself+ // ends, while a process it started can still hold the pipes and write. 'close' waits for every+ // holder to let go, which is also when spawnSync returned (measured: a grandchild writing 1 s+ // after its parent exited was captured by spawnSync and 'close', and missed by 'exit').+ child.on('error', (e) => finish(1, e));+ child.on('close', (code) => finish(code));+ });}// Extract the "Page ID: <guid>" pac prints on a successful upload.@@ -72,13 +87,16 @@ function runPac(args) {// IDENTIFIER character so a too-long token is REFUSED rather than trimmed. Restricting the boundary// to the GUID alphabet was not enough: `6e0c28a2-cdbf-41ec-9186-d10fd5de6e35oops` has a non-hex// character next, so the lookahead passed and the id was accepted with the suffix silently dropped.-// `[\w-]` is the right class — a following `.` or `,` or `)` genuinely ends the token (pac prints the-// id inside prose), while any letter, digit, underscore or hyphen means the token continues.-// Returning null is the safe outcome: the caller treats a zero exit with no parsable id as an-// UNCERTAIN create and reconciles by env-wide id diff.+// The boundary must be Unicode-aware: a suffix such as `東京` is still a continuing identifier+// token even though JavaScript `\w` is ASCII-only. A following `.` or `,` or `)` genuinely ends the+// token (pac prints the id inside prose), while any Unicode letter/number/mark, underscore or hyphen+// means the token continues. Returning null is the safe outcome: the caller treats a zero exit with+// no parsable id as an UNCERTAIN create and reconciles by env-wide id diff.const GUID_RE = /[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/;+// The end of a GUID token, for a RegExp built with the 'u' flag. Shared by both parsers below.+const GUID_END = '(?![\\p{L}\\p{N}\\p{M}_-])';function parsePageId(out) {- const m = new RegExp('Page ID:\\s*(' + GUID_RE.source + ')(?![\\w-])').exec(String(out || ''));+ const m = new RegExp('Page ID:\\s*(' + GUID_RE.source + ')' + GUID_END, 'u').exec(String(out || ''));return m ? m[1] : null;}@@ -92,12 +110,17 @@ function parsePageId(out) {// 13ecbc57-a3a4-4132-b0a2-a6c6b12691e8 Overview -//// Column boundaries are derived from the header's "Name"/"Published" offsets so a Name containing spaces-// (e.g. "Order Detail") is not split on whitespace. A data row is matched by a leading 36-char GUID.+// (e.g. "Order Detail") is not split on whitespace. A data row is matched by a leading 36-char GUID that+// ENDS there, by the same Unicode-aware rule as parsePageId: `<guid>東京` or `<guid>_x` is a longer token,+// not a page id plus a name, so the row is skipped and the count check below fails the listing closed.+// An ASCII `\b` accepted those, because JavaScript counts `東` as a non-word character.// Returns [{ pageId, name }]. NOTE (live-confirmed): pac lists only pages reachable from the app SITEMAP —// a headless nav-target page (declared in pages[] but not an appShell subarea) is NOT returned here.+// With --app-id, `name` is the page's SITEMAP TITLE, not the page record's own name (measured: after an+// update renamed the page with --name, the app-scoped listing still showed the subarea title), so a+// listed name is never evidence of what the page itself is called.function parseList(out) {- const GUID = '[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}';- const rowRe = new RegExp(`^\\s*(${GUID})\\b`);+ const rowRe = new RegExp('^\\s*(' + GUID_RE.source + ')' + GUID_END, 'u');const lines = String(out || '').split('\n');// Locate the header row to find the Name (and Published) column offsets. pac auto-sizes columns to the// longest value, so the offsets must be read from THIS output, not hard-coded.@@ -181,8 +204,24 @@ function classifyListOutput(stdout) {// download. An explicit "Found 0" is trustworthy only when no row was actually parsed (else it is a// contradictory/truncated listing → fail-closed 'unrecognized').if (count === 0) return pages.length === 0 ? { kind: 'empty', pages: [] } : { kind: 'unrecognized', pages: [] };- if (count === null && pages.length === 0 && /\bno\s+(?:generated\s+)?pages?\b/i.test(s)) return { kind: 'empty', pages: [] };- // A complete, authoritative listing: at least one page, every page has a name, count matches+ // Older pac builds have printed a no-pages marker as its own line. Treat only that complete,+ // trimmed line as authoritative:+ // No generated pages found.+ // No pages found+ // A warning such as "no pages could be retrieved" means the service failed to enumerate, not+ // that the app is empty, so it must fail closed.+ if (count === null && pages.length === 0 && /^[^\S\r\n]*no[^\S\r\n]+(?:generated[^\S\r\n]+)?pages[^\S\r\n]+found\.?[^\S\r\n]*$/im.test(s)) {+ return { kind: 'empty', pages: [] };+ }+ const seenIds = new Set();+ const hasDuplicateIds = pages.some((p) => {+ const key = String(p.pageId || '').toLowerCase();+ if (seenIds.has(key)) return true;+ seenIds.add(key);+ return false;+ });+ if (hasDuplicateIds) return { kind: 'unrecognized', pages: [] };+ // A complete, authoritative listing: at least one DISTINCT page, every page has a name, count matchesconst allNamed = pages.length > 0 && pages.every((p) => p.name && String(p.name).trim());if (allNamed && count !== null && count === pages.length) return { kind: 'pages', pages };return { kind: 'unrecognized', pages: [] };@@ -269,10 +308,12 @@ function makeGenpageCli(env, deps = {}) {// UNRECOGNIZED/INCOMPLETE output (count mismatch, blank,// help banner, unnamed page) — never masquerade as empty.// Callers that drive a create decision MUST check ok before trusting pages:[] as "truly empty".- async function enumeratePages(appId) {+ async function enumeratePages(appId, options = {}) {let lastErr = '';for (let i = 0; i < attempts; i += 1) {- const r = await run(['model', 'genpage', 'list', '--environment', env, '--app-id', appId]);+ const args = ['model', 'genpage', 'list', '--environment', env, '--app-id', appId];+ if (options && options.includeUnpublished === true) args.push('--include-unpublished');+ const r = await run(args);if (r.status === 0) {const c = classifyListOutput(r.stdout);if (c.kind !== 'unrecognized') return { ok: true, pages: c.pages, empty: c.kind === 'empty' };@@ -329,8 +370,8 @@ function makeGenpageCli(env, deps = {}) {// (preserving the historical defaults) ONCE, then hand both to pac BY FILE via --prompt-file /// --agent-message-file rather than inline --prompt / --agent-message. A downloaded page prompt is// a multi-line conversation transcript ("Conversation with N prompts:\r\n1. …\r\n2. …"); passed- // inline it hits the newline-collapsing in quoteArg/buildPacInvocation (a defensive guard so a- // stray newline can't truncate the Windows command line) and silently loses every line break on+ // inline it hits the newline-collapsing in buildPacInvocation (a defensive guard so a stray+ // newline can't truncate a Windows batch shim's command line) and silently loses every line break on// an edit-rebuild. A file round-trips the text verbatim. See `pac model genpage upload --help`.const promptText = prompt && String(prompt).trim() ? String(prompt) : `Generative page ${name || ''}`.trim();// The default applies only when NO agent message was supplied. An explicitly EMPTY one (a@@ -483,6 +524,9 @@ function makeGenpageCli(env, deps = {}) {enumerate({ appId }) {return enumeratePages(appId);},+ enumeratePages(appId, options) {+ return enumeratePages(appId, options);+ },enumerateEnv() {return enumerateEnv();},@@ -507,4 +551,4 @@ function makeGenpageCli(env, deps = {}) {function suppliedButBlank(value) {return value !== undefined && value !== null && !String(value).trim();}-module.exports = { makeGenpageCli, suppliedButBlank, parsePageId, parseList, parseListCount, classifyListOutput, quoteArg, buildPacInvocation, runPac };+module.exports = { makeGenpageCli, suppliedButBlank, parsePageId, parseList, parseListCount, classifyListOutput, buildPacInvocation, runPac };diff --git a/plugins/model-apps/scripts/lib/hydrate-spec.js b/plugins/model-apps/scripts/lib/hydrate-spec.jsindex 457a95692..e3476bfd3 100644--- a/plugins/model-apps/scripts/lib/hydrate-spec.js+++ b/plugins/model-apps/scripts/lib/hydrate-spec.js@@ -267,7 +267,7 @@ async function hydrateSpec(read) {...(p.navigatesTo ? { navigatesTo: p.navigatesTo } : {}),...(p.pageInput !== undefined ? { pageInput: p.pageInput } : {}),...directEntryOf(p),- ...(p.prompt ? { prompt: p.prompt } : {}),+ ...(p.prompt !== undefined ? { prompt: p.prompt } : {}),source: { kind: 'tsx', codeFile: p.codeFile },}// Legacy shape: name + optional fields + top-level codeFile (back-compat with hydrate callers@@ -275,7 +275,7 @@ async function hydrateSpec(read) {: {name: p.name,...(p.dataSources && p.dataSources.length ? { dataSources: p.dataSources } : {}),- ...(p.prompt ? { prompt: p.prompt } : {}),+ ...(p.prompt !== undefined ? { prompt: p.prompt } : {}),codeFile: p.codeFile,})),appShell,diff --git a/plugins/model-apps/scripts/lib/modelapps-hook-utils.js b/plugins/model-apps/scripts/lib/modelapps-hook-utils.jsindex ebcb809ae..7a0ddafe4 100644--- a/plugins/model-apps/scripts/lib/modelapps-hook-utils.js+++ b/plugins/model-apps/scripts/lib/modelapps-hook-utils.js@@ -10,6 +10,7 @@const fs = require('fs');const path = require('path');+const { readUtf8Stream } = require('./utf8-stream.js');const PLUGIN_ROOT = path.resolve(__dirname, '..', '..');const SKILLS_DIR = path.join(PLUGIN_ROOT, 'skills');@@ -135,4 +136,5 @@ module.exports = {detectTrackedSkill,getTrackedSkillFromToolInput,getValidatorScript,+ readUtf8Stream,};diff --git a/plugins/model-apps/scripts/lib/op-diff.js b/plugins/model-apps/scripts/lib/op-diff.jsindex 0c9945a65..11d188d56 100644--- a/plugins/model-apps/scripts/lib/op-diff.js+++ b/plugins/model-apps/scripts/lib/op-diff.js@@ -39,9 +39,11 @@ function sitemapTargets(container) {// reconcileForm prune (sdk-build.js:707-733): only an explicit layout prunes; an auto layout is purely// additive and never removes, so it can never be destructive. `def` is a compiled form intent// (compileFormIntent); `deployedForm` is the fetched deployed form. Never counts the primary field-// (reconcile never prunes it). Returns [] for an auto layout or when nothing is removed.+// (reconcile never prunes it). Returns [] for an auto layout, prune:false, or when nothing is removed.function formRemovals(deployedForm, def) {- if (!def || !def.__explicitLayout) return [];+ // Keep the read-only classifier tied to the engine's own destructive gate: sdk-build.js only enters+ // the prune pass for explicit layouts whose compiled intent has `__prune !== false`.+ if (!def || !def.__explicitLayout || def.__prune === false) return [];const want = new Set(formFieldLogicals(def));const primary = def.__primaryField;const removed = [];@@ -85,7 +87,7 @@ function classifyOps(spec, discovered = {}, opts = {}) {for (const f of discovered.forms || []) {const removed = formRemovals(f.deployedForm, f.def);if (removed.length) {- destructive.push({ kind: 'form-field-removal', label: f.label, detail: `removes field(s): ${removed.join(', ')}` });+ destructive.push({ kind: 'form-field-removal', formId: f.formId, label: f.label, fields: removed, detail: `removes field(s): ${removed.join(', ')}` });}}@@ -93,7 +95,7 @@ function classifyOps(spec, discovered = {}, opts = {}) {const want = new Set(discovered.sitemap.wantTargets || []);const dropped = (discovered.sitemap.deployedTargets || []).filter((t) => !want.has(t));if (dropped.length) {- destructive.push({ kind: 'sitemap-removal', label: 'app sitemap', detail: `drops navigation target(s): ${dropped.join(', ')}` });+ destructive.push({ kind: 'sitemap-removal', label: 'app sitemap', targets: dropped, detail: `drops navigation target(s): ${dropped.join(', ')}` });}}diff --git a/plugins/model-apps/scripts/lib/page-structure.js b/plugins/model-apps/scripts/lib/page-structure.jsnew file mode 100644index 000000000..6206a2b03--- /dev/null+++ b/plugins/model-apps/scripts/lib/page-structure.js@@ -0,0 +1,47 @@+'use strict';++// The structural checks a generated page must pass before it is accepted: ONE list for the two gates+// that accept a page.+// * genpage-worker-output.js — /genpage accepts one parallel worker's page file;+// * promote-intent-pages.js — /app-builder flips a page from `intent` to `tsx`, which is sticky:+// a promoted page is marked implemented and skipped on the next run.+// They were two copies with the same checks and different wording, and they had already drifted once:+// the elision-marker check and the fence check on BLANKED source were added to one gate and had to be+// found missing from the other. A page one gate refuses, the other now refuses too, with the same words.+//+// Deliberately NOT a type check: the plugin ships with no dependencies, so there is no TypeScript+// parser to call, and type checking is the deploy's job. This catches the realistic worker failures —+// an empty file, a truncated write, prose instead of code, elided code.+//+// Every check runs over literal-blanked source (see source-literals.js). A substring search, even over+// a copy that keeps ordinary string bodies, accepted prose that merely MENTIONS an export:+// /* export default */ -> accepted+// const prose = "export default GeneratedComponent"; -> accepted+const { blankLiterals, endsMidStatement, findElisionMarker, hasDefaultExport, hasUnbalancedBrackets } = require('./source-literals.js');++function pageStructureProblems(code) {+ const text = String(code == null ? '' : code);+ if (!text.trim()) return ['file is empty'];+ const problems = [];+ // hasDefaultExport also refuses a file cut off INSIDE its export (`export default function P(props)`+ // with no body), so the message says so: the fix is to write the whole page, not to add an export.+ if (!hasDefaultExport(text)) {+ problems.push('no complete default export — no real `export default` (or `export { X as default }`), '+ + 'or the file ends inside it, so the host cannot mount the page');+ }+ if (hasUnbalancedBrackets(text)) problems.push('unbalanced brackets — the file looks truncated');+ // A cut that leaves every bracket balanced: inside JSX, a template or a comment, or after `a +`.+ if (endsMidStatement(text)) problems.push('stops mid-statement — the file looks truncated');+ // A worker that answers in prose usually still opens a fence, and a real .tsx never has one in CODE.+ // Both CommonMark fence markers count. On the blanked source, a fence inside a template literal (a page+ // rendering markdown help) is data, while a fence wrapping the file is code-position text.+ if (/^\s*(```|~~~)/m.test(blankLiterals(text))) {+ problems.push('contains a markdown code fence — the worker returned prose, not a module');+ }+ // Elided code (`// TODO: …`, `// ...`, "omitted for brevity"), the same rule the genpage evals apply.+ const elision = findElisionMarker(text);+ if (elision) problems.push(`contains ${elision} — the page is incomplete`);+ return problems;+}++module.exports = { pageStructureProblems };diff --git a/plugins/model-apps/scripts/lib/pageref-resolver.js b/plugins/model-apps/scripts/lib/pageref-resolver.jsindex 95263c82a..f90b64427 100644--- a/plugins/model-apps/scripts/lib/pageref-resolver.js+++ b/plugins/model-apps/scripts/lib/pageref-resolver.js@@ -63,40 +63,44 @@ function objectArgAt(code, open) {// whole string literal (escape-aware); an unquoted value (or a quoted string followed by '+', which// indicates a concat expression) runs to the next top-level ',' or the closing '}'. The char-before// check rejects a false hit inside a longer identifier (e.g. `myPageId`).-function topLevelValue(objText, key) {+function topLevelValue(objText, key, sourceObjText = objText) {let depth = 0;let inStr = null;// `key` is always a code-controlled literal ('pageType' or 'pageId'), never user-supplied,// so no regex-escape is needed before interpolating into the pattern.const keyRe = new RegExp('^' + key + '\\s*:');- for (let i = 0; i < objText.length; i += 1) {- const c = objText[i];- if (inStr) { if (c === '\\') { i += 1; continue; } if (c === inStr) inStr = null; continue; }- // inStr handles quoted values (delimiters kept, bodies blanked by the mask) so a value is never- // misread as key or bracket content when scanning for the target key.- if (c === '"' || c === "'" || c === '`') { inStr = c; continue; }- if (c === '{' || c === '[' || c === '(') { depth += 1; continue; }- if (c === '}' || c === ']' || c === ')') { depth -= 1; continue; }- if (depth !== 1 || c !== key[0]) continue;- if (!keyRe.test(objText.slice(i))) continue;- // Reject a false hit inside a longer identifier (e.g. the "p" of "myPageId" — c is 'p'- // but the character before the match in objText must be a key-boundary: '{', ',', or whitespace).- const before = objText[i - 1];- if (before !== undefined && !/[{,\s]/.test(before)) continue;- let j = i + keyRe.exec(objText.slice(i))[0].length;+ const scanStringEnd = (from) => {+ const q = objText[from];+ for (let k = from + 1; k < objText.length; k += 1) {+ if (objText[k] === '\\') { k += 1; continue; }+ if (objText[k] === q) return k + 1;+ }+ return null;+ };+ const followsPropertyBoundary = (from) => {+ // Object keys begin immediately after `{` or `,` once whitespace is skipped. The mask blanks+ // comments to same-length whitespace, so this deliberately walks the mask rather than the source:+ // { /* note */ "pageId": "..." } -> previous non-space is `{`+ // c ? "pageId" : "..." -> previous non-space is `?`, not a key boundary+ // An identifier character before the match (`myPageId`) therefore still fails.+ let p = from - 1;+ while (p >= 0 && /\s/.test(objText[p])) p -= 1;+ return p < 0 || objText[p] === '{' || objText[p] === ',';+ };+ const readValue = (colonEnd) => {+ let j = colonEnd;while (j < objText.length && /\s/.test(objText[j])) j += 1;const q = objText[j];if (q === '"' || q === "'" || q === '`') {// Quoted value: scan to the matching closing quote, respecting escape sequences.- let k = j + 1;- for (; k < objText.length; k += 1) { if (objText[k] === '\\') { k += 1; continue; } if (objText[k] === q) { k += 1; break; } }+ const end = scanStringEnd(j) || objText.length;// If the quoted string is followed (after optional whitespace) by '+', it is a concat// expression — fall through to unquoted scanning to capture the full span, so the// tightened QUOTED regex correctly classifies it as `dynamic` rather than `literal`.- let kk = k;+ let kk = end;while (kk < objText.length && /\s/.test(objText[kk])) kk++;if (!(kk < objText.length && objText[kk] === '+')) {- return { raw: objText.slice(j, k), valueStart: j, valueEnd: k };+ return { raw: objText.slice(j, end), valueStart: j, valueEnd: end };}// Falls through to the unquoted scanning below.}@@ -111,8 +115,56 @@ function topLevelValue(objText, key) {else if (cc === ',' && d2 === 0) break;}return { raw: objText.slice(j, k).trim(), valueStart: j, valueEnd: k };+ };+ let lastMatch = null;+ const markRuntimeOverride = () => {+ if (lastMatch) lastMatch.hasRuntimeOverrideAfter = true;+ };+ for (let i = 0; i < objText.length; i += 1) {+ const c = objText[i];+ if (inStr) { if (c === '\\') { i += 1; continue; } if (c === inStr) inStr = null; continue; }+ if (depth === 1 && followsPropertyBoundary(i) && c === '.' && objText[i + 1] === '.' && objText[i + 2] === '.') {+ markRuntimeOverride();+ i += 2;+ continue;+ }+ if (depth === 1 && followsPropertyBoundary(i) && c === '[') {+ // A later computed property can be `["pageId"]` or `["pageType"]` at runtime. Without+ // evaluating arbitrary JavaScript, the only safe answer is to treat any explicit key before it+ // as possibly overridden; an explicit key after it still wins by normal object-literal order.+ markRuntimeOverride();+ }+ if ((c === '"' || c === "'") && depth === 1) {+ const keyEnd = scanStringEnd(i);+ if (keyEnd !== null) {+ let colon = keyEnd;+ while (colon < objText.length && /\s/.test(objText[colon])) colon += 1;+ // The lexer mask blanks string bodies but preserves delimiters, so quoted property names are+ // validated against the original source at the same offsets. Only literal "pageId"/'pageId'+ // keys are in scope; computed keys (["pageId"]) and template-literal keys are deliberately+ // left unmatched because supporting them would require evaluating property expressions.+ const rawKey = sourceObjText.slice(i, keyEnd);+ if (objText[colon] === ':' && followsPropertyBoundary(i) && (rawKey === `"${key}"` || rawKey === `'${key}'`)) {+ lastMatch = readValue(colon + 1);+ }+ i = keyEnd - 1;+ continue;+ }+ }+ // inStr handles quoted values (delimiters kept, bodies blanked by the mask) so a value is never+ // misread as key or bracket content when scanning for the target key. Template-literal keys are+ // out of scope for the same reason as computed keys above.+ if (c === '"' || c === "'" || c === '`') { inStr = c; continue; }+ if (c === '{' || c === '[' || c === '(') { depth += 1; continue; }+ if (c === '}' || c === ']' || c === ')') { depth -= 1; continue; }+ if (depth !== 1 || c !== key[0]) continue;+ if (!keyRe.test(objText.slice(i))) continue;+ // Reject false hits inside longer identifiers or value expressions; after skipping whitespace,+ // a real top-level key must follow the object's `{` or the previous property's `,`.+ if (!followsPropertyBoundary(i)) continue;+ lastMatch = readValue(i + keyRe.exec(objText.slice(i))[0].length);}- return null;+ return lastMatch;}// Parse every generative navigateTo(...) call site into a classified pageId descriptor (see the module@@ -137,16 +189,21 @@ function extractNavTargets(code) {// pv.valueStart / pv.valueEnd are relative to obj.text, which starts at `open`; adding `open`// makes them absolute offsets into the mask and, equally, into the original source.const valueAt = (v) => src.slice(open + v.valueStart, open + v.valueEnd).trim();- const pt = topLevelValue(obj.text, 'pageType');+ const sourceObjText = src.slice(open, obj.end);+ const pt = topLevelValue(obj.text, 'pageType', sourceObjText);const ptQ = pt && QUOTED.exec(valueAt(pt));if (!ptQ || ptQ[2] !== 'generative') continue;- const pv = topLevelValue(obj.text, 'pageId');+ const pv = topLevelValue(obj.text, 'pageId', sourceObjText);if (!pv) continue;const valueStart = open + pv.valueStart;const valueEnd = open + pv.valueEnd;// Classify from the ORIGINAL source span: the mask blanks every string body, so a backtick-quoted// `PAGEREF_x` is found (and classified as pageref-malformed) only in `src`.const rawOrig = valueAt(pv);+ if (pt.hasRuntimeOverrideAfter || pv.hasRuntimeOverrideAfter) {+ out.push({ kind: 'dynamic', raw: rawOrig, valueStart, valueEnd });+ continue;+ }const canon = CANON.exec(rawOrig);if (canon) { out.push({ kind: 'pageref', key: canon[1], valueStart, valueEnd }); continue; }// A PAGEREF token in any non-canonical form is malformed (single/back-tick quoted, concatenated)diff --git a/plugins/model-apps/scripts/lib/process-runner.js b/plugins/model-apps/scripts/lib/process-runner.jsnew file mode 100644index 000000000..80364e1bb--- /dev/null+++ b/plugins/model-apps/scripts/lib/process-runner.js@@ -0,0 +1,231 @@+'use strict';+// The one place model-apps production code starts an external CLI (az, pac, npm, npx, git).+//+// Every call goes through `invocation()`, which returns an ABSOLUTE executable and an argv array, and+// is always spawned with `shell: false`. Two Windows facts shape it:+//+// 1. `az`, `npm` and `npx` are batch shims (`az.cmd`, `npm.cmd`, `npx.cmd`), and `pac` is `pac.exe`+// or a `pac.cmd` shim depending on how it was installed. Node refuses to start a `.cmd`/`.bat`+// with `shell: false` (EINVAL since Node 18.20.2 / 20.12.2), so a shim has to run under cmd.exe.+// See: https://nodejs.org/api/child_process.html#spawning-bat-and-cmd-files-on-windows+// `shell: true` is not the answer: it joins the arguments with spaces and hands the string to+// cmd.exe without quoting any of them. So a shim runs as `cmd.exe /d /s /v:off /c <shim> <args>`,+// and every argument must be INERT for cmd.exe — see CMD_INERT_ARG.+// 2. A bare name ("git", "pac") is looked up in the CURRENT DIRECTORY before PATH, both by Node's own+// launcher and by cmd.exe, and the current directory is usually the user's project. So the name+// is resolved here, against absolute PATH entries only, before anything is started.+//+// A native `.exe` on Windows, and everything on macOS/Linux, is started directly, so its arguments+// reach the program exactly as given (libuv applies the C-runtime quoting rules on Windows).+const childProcess = require('node:child_process');+const fs = require('node:fs');+const path = require('node:path');++// An argument handed to a batch shim is parsed by cmd.exe twice: once on the `/c` command line, and+// again when the shim forwards `%*`. The arguments that survive both parses unchanged, with no+// quoting at all, are the ones made only of characters cmd.exe gives no meaning to. Everything the+// shims are given today fits: fixed flags, an https origin, a GUID, a JMESPath query such as+// `{user:user.name,tenantId:tenantId}`. Anything else is refused BEFORE a process starts.+const CMD_INERT_ARG = /^[A-Za-z0-9_.,:/{}@=+-]+$/;++// How one argument is written on a batch shim's command line, or null when it cannot be.+// Inert text goes bare. Anything else is wrapped in double quotes, inside which cmd.exe treats+// & | < > ^ ( ) and spaces as plain text in both parses (the shim's `%*` keeps the quotes). What+// still acts inside quotes is refused: a double quote (it would end the quoting) and `%` (variable+// expansion happens before quotes are considered). `!` is literal on this command line (/v:off),+// so it is refused only when `bangExpands` says the shim turns delayed expansion back on. Control+// characters are refused because a line break ends the command.+// A trailing backslash run is doubled: the program's C runtime would read `\"` as an escaped quote.+// See: https://learn.microsoft.com/cpp/cpp/main-function-command-line-args#parsing-c-command-line-arguments+function cmdArgument(value, { bangExpands = false } = {}) {+ if (CMD_INERT_ARG.test(value)) return value;+ if (value === '') return '""';+ if (/["%\u0000-\u001f\u007f]/.test(value) || (bangExpands && value.includes('!'))) return null;+ return `"${value.replace(/(\\+)$/, '$1$1')}"`;+}++// Whether a batch shim turns delayed expansion on for itself (`setlocal enabledelayedexpansion`),+// in which case `!NAME!` in a forwarded argument would be replaced by that variable's value. The+// shims this plugin runs (az.cmd, npm.cmd, npx.cmd) do not. An unreadable shim is assumed to.+function shimExpandsBang(file, readFile = (p) => fs.readFileSync(p, 'latin1')) {+ try { return /enabledelayedexpansion/i.test(readFile(file)); } catch { return true; }+}++// The value of an environment variable the way Node passes it to a child on Windows, where names+// are case-insensitive: when an env object carries several spellings (a copied `Path` plus an added+// `PATH`), Node sends the lexicographically first one, so resolution must read that same one.+// See: https://nodejs.org/api/child_process.html#child_processspawncommand-args-options (options.env)+function envValue(env, name, platform) {+ if (platform !== 'win32') return env[name];+ const key = Object.keys(env).filter((k) => k.toUpperCase() === name.toUpperCase()).sort()[0];+ return key === undefined ? undefined : env[key];+}++/**+ * A copy of `env` with `dir` first on the path. On Windows every spelling of PATH is replaced by one+ * `PATH` holding the value Node would have passed the child; on POSIX, where `Path` and `PATH` are+ * different variables, only `PATH` changes.+ */+function withPathFirst(env, dir, platform = process.platform) {+ const out = { ...env };+ if (platform !== 'win32') {+ out.PATH = out.PATH ? `${dir}:${out.PATH}` : dir;+ return out;+ }+ const current = envValue(env, 'PATH', platform);+ for (const k of Object.keys(out)) if (k.toUpperCase() === 'PATH') delete out[k];+ out.PATH = current ? `${dir};${current}` : dir;+ return out;+}++const WINDOWS_BATCH = /\.(?:cmd|bat)$/i;+const WINDOWS_NATIVE = /\.(?:exe|com)$/i;++function isFile(p) {+ try { return fs.statSync(p).isFile(); } catch { return false; }+}++// Absolute directories on PATH, in order. Relative entries (including an empty entry, which POSIX+// shells read as "the current directory") are skipped for the same reason as the current directory.+function pathDirectories({ platform, env }) {+ const win = platform === 'win32';+ const raw = envValue(env, 'PATH', platform) || '';+ const isAbs = win ? path.win32.isAbsolute : path.posix.isAbsolute;+ return raw.split(win ? ';' : ':')+ .map((d) => d.trim().replace(/^"(.*)"$/, '$1'))+ .filter((d) => d && isAbs(d));+}++/**+ * Resolve a command name to an absolute file on PATH, never from the current directory.+ * On Windows the PATHEXT order decides between, say, `pac.exe` and `pac.cmd` in the same folder,+ * as cmd.exe would, but only native executables and batch files are accepted.+ * @returns {string|null}+ */+function resolveExecutable(name, { platform = process.platform, env = process.env, exists = isFile } = {}) {+ const join = platform === 'win32' ? path.win32.join : path.posix.join;+ const exts = platform === 'win32'+ ? String(envValue(env, 'PATHEXT', platform) || '.COM;.EXE;.BAT;.CMD').split(';').map((e) => e.trim())+ .filter((e) => WINDOWS_BATCH.test(e) || WINDOWS_NATIVE.test(e))+ : [''];+ for (const dir of pathDirectories({ platform, env })) {+ for (const ext of exts) {+ const candidate = join(dir, name + ext.toLowerCase());+ if (exists(candidate)) return candidate;+ }+ }+ return null;+}++// cmd.exe itself, by absolute path. ComSpec is what Node's own `shell: true` uses; it is only+// trusted when it is an absolute path to a file named cmd.exe.+function windowsCmd(env = process.env) {+ const comspec = String(envValue(env, 'ComSpec', 'win32') || '');+ if (path.win32.isAbsolute(comspec) && /(?:^|\\)cmd\.exe$/i.test(comspec)) return comspec;+ return path.win32.join(envValue(env, 'SystemRoot', 'win32') || envValue(env, 'windir', 'win32') || 'C:\\Windows', 'System32', 'cmd.exe');+}++function codeError(message, code) {+ const e = new Error(message);+ e.code = code;+ return e;+}++/**+ * Build the call that starts `name` with `args`: an absolute file, an argv array, and the options+ * that must accompany them. Callers add their own options (encoding, timeout, stdio, cwd) on top.+ * @throws {Error} code 'ENOENT' when `name` is not on PATH; code 'EARGUMENT' when an argument+ * cannot be passed through a Windows batch shim unchanged.+ */+function invocation(name, args = [], { platform = process.platform, env = process.env, exists = isFile, readFile } = {}) {+ const argv = args.map((a) => String(a));+ const file = resolveExecutable(name, { platform, env, exists });+ // Worded like Node's own launch failure (`spawn pac ENOENT`) so existing diagnostics read the same.+ if (!file) throw codeError(`spawn ${name} ENOENT: not found on PATH`, 'ENOENT');+ if (platform !== 'win32' || !WINDOWS_BATCH.test(file)) {+ return { file, args: argv, options: { shell: false, windowsHide: true } };+ }+ const bangExpands = argv.some((a) => a.includes('!')) && shimExpandsBang(file, readFile);+ const refused = argv.find((a) => cmdArgument(a, { bangExpands }) === null);+ if (refused !== undefined || /[%!"]/.test(file)) {+ throw codeError(+ `cannot pass ${JSON.stringify(refused === undefined ? file : refused)} to ${path.win32.basename(file)}: `+ + `a Windows batch file cannot receive a double quote, %, a control character${bangExpands ? ' or (for this one) !' : ''} unchanged`,+ 'EARGUMENT'+ );+ }+ // The command line is written out in full, and `windowsVerbatimArguments` stops libuv from quoting+ // it a second time. This is the shape Node's own `shell: true` produces — `/d /s /c "<line>"`, where+ // /s strips exactly the outer pair of quotes — with the difference that the shim is quoted by+ // absolute path and every argument has already been checked. /d skips AutoRun commands; /v:off+ // keeps `!` literal even where delayed expansion is on by default.+ // See: https://learn.microsoft.com/windows-server/administration/windows-commands/cmd+ return {+ file: windowsCmd(env),+ args: ['/d', '/s', '/v:off', '/c', `""${file}" ${argv.map((a) => cmdArgument(a, { bangExpands })).join(' ')}"`],+ options: {+ shell: false,+ windowsHide: true,+ windowsVerbatimArguments: true,+ // Stops cmd.exe itself from preferring a same-named file in the current directory for any+ // command the shim runs. It does not govern Node's own lookup, which is why `file` is absolute.+ env: { ...env, NoDefaultCurrentDirectoryInExePath: '1' },+ },+ };+}++// Merge the invocation's required options over the caller's, so a caller cannot turn the shell on+// or drop the verbatim flag by accident.+//+// The four calls below are the only child_process calls in model-apps production code, and each is+// an exact, reviewed exception in scripts/validate-secure-process-execution.js (their executable is+// resolved at run time and their options are merged, so the validator cannot prove them statically).+function withOptions(inv, options = {}) {+ const merged = { ...options, ...inv.options };+ if (options.env && inv.options.env) merged.env = { ...options.env, NoDefaultCurrentDirectoryInExePath: '1' };+ return merged;+}++function runSync(name, args, options = {}, deps = {}) {+ const inv = invocation(name, args, deps);+ return childProcess.execFileSync(inv.file, inv.args, withOptions(inv, options));+}++// spawnSync-shaped: never throws, reports a launch failure through `error` as spawnSync does.+function spawnResultSync(name, args, options = {}, deps = {}) {+ let inv;+ try { inv = invocation(name, args, deps); } catch (error) {+ return { status: null, signal: null, stdout: '', stderr: '', error };+ }+ return childProcess.spawnSync(inv.file, inv.args, withOptions(inv, options));+}++// execFile-shaped: the callback receives a resolution failure as its error, asynchronously.+function execFileAsync(name, args, options, callback, deps = {}) {+ let inv;+ try { inv = invocation(name, args, deps); } catch (error) {+ process.nextTick(() => callback(error, '', ''));+ return null;+ }+ return childProcess.execFile(inv.file, inv.args, withOptions(inv, options), callback);+}++function spawnProcess(name, args, options = {}, deps = {}) {+ const inv = invocation(name, args, deps);+ return childProcess.spawn(inv.file, inv.args, withOptions(inv, options));+}++module.exports = {+ CMD_INERT_ARG,+ cmdArgument,+ envValue,+ withOptions,+ execFileAsync,+ invocation,+ resolveExecutable,+ runSync,+ spawnProcess,+ spawnResultSync,+ windowsCmd,+ withPathFirst,+};\ No newline at end of filediff --git a/plugins/model-apps/scripts/lib/projection.js b/plugins/model-apps/scripts/lib/projection.jsindex 031f938b8..13441a3bc 100644--- a/plugins/model-apps/scripts/lib/projection.js+++ b/plugins/model-apps/scripts/lib/projection.js@@ -15,14 +15,9 @@const { stableStringify } = require('./phase-diff.js');const { sha256 } = require('./hash.js');--// Dataverse control class ids that occupy a cell but are NOT bound form fields (a quick-view even-// carries a fieldName). Kept in sync with artifact-intent.js NON_FIELD_CONTROL_CLASS_IDS.-const NON_FIELD_CONTROL_CLASS_IDS = new Set([- '5C5600E0-1D6E-4205-A272-BE80DA87FD42', // QuickView- 'E7A81278-8635-4D9E-8D4D-59480B391C5B', // Subgrid / Grid- '06375649-C143-495E-A496-C962E5B4488E', // Notes / Timeline-]);+// The non-field control rule (quick-view, sub-grid, notes/timeline class ids) lives in the compiler+// that places those controls, so the verifier and the compiler cannot disagree about what counts.+const { isNonFieldControl } = require('./artifact-intent.js');// Normalize a GUID for comparison: drop braces, lowercase. Non-guid strings pass through lowercased-trim.function normId(s) {@@ -33,10 +28,6 @@ function normClassId(id) {return String(id || '').replace(/[{}]/g, '').toUpperCase();}-function isNonFieldControl(ctrl) {- return !!(ctrl && ctrl.classId && NON_FIELD_CONTROL_CLASS_IDS.has(normClassId(ctrl.classId)));-}-// One cell's projection: a bound field (name + required), a sub-grid (relationship/target/view/label,// id-normalized), a notes/quick-view control (class + label), or empty. NO layout ids.function cellProjection(cell) {diff --git a/plugins/model-apps/scripts/lib/sdk-build.js b/plugins/model-apps/scripts/lib/sdk-build.jsindex 5f28a39cb..bdffab783 100644--- a/plugins/model-apps/scripts/lib/sdk-build.js+++ b/plugins/model-apps/scripts/lib/sdk-build.js@@ -78,6 +78,7 @@ const {} = require('./artifact-intent.js');const { makeGenpageCli, suppliedButBlank } = require('./genpage-cli.js');const { matchContainer, isEngineOwnedSection, isEngineHostSection, holdsControlOf, claimedByAuthoredName } = require('./form-container-match.js');+const { rowOccupancy, fitsGrid, strandedRows } = require('./form-occupancy.js');const { manifestResourceName, buildManifest, serializeManifest, parseManifestBase64, reconcilePageIds } = require('./page-manifest.js');// MEMBERSHIP authority (the app's live sitemap) + the cross-app shared-page scan. fetchSitemap is// fail-closed & discriminated (C4); fetchAppsForPages is the only way to prove a generative page is not@@ -1642,6 +1643,40 @@ async function annotateLivePlan(plan, { spec, provision, warn } = {}) {}// --- orchestrator ----------------------------------------------------------------------+function normalizeFormId(value) {+ return String(value || '').trim().replace(/^\{+|\}+$/g, '').toLowerCase();+}++function authorizedFormRemovalEntry(map, formId, createdThisRun) {+ if (!(map instanceof Map)) return { fenced: false, authorized: null, normalizedFormId: normalizeFormId(formId) };+ const normalized = normalizeFormId(formId);+ if (map.has(normalized)) return { fenced: true, authorized: map.get(normalized), normalizedFormId: normalized };+ for (const [key, value] of map) {+ if (normalizeFormId(key) === normalized) return { fenced: true, authorized: value, normalizedFormId: normalized };+ }+ if (createdThisRun && createdThisRun.has(normalized)) return { fenced: false, authorized: null, normalizedFormId: normalized };+ return { fenced: true, authorized: new Set(), normalizedFormId: normalized };+}++function sitemapTargetsForFence(container) {+ // Use the destructive-op classifier's target vocabulary so the preflight record and the engine fence+ // cannot drift (entity:<logical>, url:<url>). Required lazily to avoid a module-load cycle: op-diff+ // reaches sdk-build through sdk-teardown, while this helper runs only after sdk-build is initialized.+ return require('./op-diff.js').sitemapTargets(container);+}++async function assertAuthorizedSitemapRewrite(provision, appId, nextSiteMap, authorized, phase) {+ if (!(authorized instanceof Set)) return;+ await provision.fetchArtifact('app', appId, { overwrite: true });+ const live = await provision.getArtifact('app', appId) || {};+ const want = new Set(sitemapTargetsForFence(nextSiteMap || {}));+ const dropped = sitemapTargetsForFence(live.siteMap || {}).filter((target) => !want.has(target));+ const unauthorized = dropped.filter((target) => !authorized.has(target));+ if (unauthorized.length) {+ throw new BuildHalt(`refusing to rewrite the app sitemap because ${unauthorized.join(', ')} appeared after the run's approval and would be removed. Re-run to review it.`, { phase, code: 'sitemap-removal-unapproved', recoverable: true });+ }+}+async function runSdkBuild(spec, opts = {}) {const { sdk, apply = false, sampleData = false, publish = false } = opts;const emit = opts.emit || (() => undefined);@@ -1679,7 +1714,8 @@ async function runSdkBuild(spec, opts = {}) {};}- const result = { ok: true, created: { entities: {}, relationships: {}, records: {}, webResources: {}, views: {}, charts: {}, forms: {}, formIds: {}, businessRules: {}, businessProcessFlows: {}, bpfBackingTables: {}, commands: {}, dashboards: {}, pages: {}, pageDeployedShas: {}, ai: { appFeatures: null, summaries: {} }, roles: {}, roleGrants: {}, bpfRoleGrants: {}, app: null }, skipped: { businessRules: [], aiSummaries: [], layout: [] } };+ const createdFormsThisRun = new Set();+ const result = { ok: true, created: { entities: {}, relationships: {}, records: {}, webResources: {}, views: {}, charts: {}, forms: {}, formIds: {}, businessRules: {}, businessProcessFlows: {}, bpfBackingTables: {}, commands: {}, dashboards: {}, pages: {}, pageDeployedShas: {}, ai: { appFeatures: null, summaries: {} }, roles: {}, roleGrants: {}, bpfRoleGrants: {}, app: null }, skipped: { businessRules: [], aiSummaries: [], layout: [], unauthorizedRemovals: [] } };// #changed-only (pages-only fast apply): seed the LIVE app id (discovered by unique name upstream) so the// pages phase's `pages-requires-app` guard passes WITHOUT running the app-shell phase in this invocation.// The full-build path never sets opts.changedOnly, so result.created.app stays null and app-shell@@ -1931,17 +1967,23 @@ async function runSdkBuild(spec, opts = {}) {}};- // Resolve a `/tabs/T/columns/C/sections/S/rows/R` pointer to the row object. Deliberately narrow —- // it exists only so the reconcile can tell whether a cell move emptied the row it came from.- const jsonPointerRow = (formJson, pointer) => {- const t = String(pointer).split('/').filter(Boolean);- // ['tabs', T, 'columns', C, 'sections', S, 'rows', R]- if (t.length !== 8 || t[0] !== 'tabs' || t[2] !== 'columns' || t[4] !== 'sections' || t[6] !== 'rows') return null;- const tab = (formJson.tabs || [])[Number(t[1])];- const col = tab && (tab.columns || [])[Number(t[3])];- const sec = col && (col.sections || [])[Number(t[5])];- return (sec && (sec.rows || [])[Number(t[7])]) || null;+ // Remove the rows a cell's departure left holding nothing: its own row, and the rows its row-span+ // covered. An empty `<row/>` renders as a blank line, and one would accumulate per pruned or+ // relocated field. `strandedRows` keeps a row that a row-spanning cell above still reserves (it is+ // occupied, not empty) and never looks at a row this departure did not touch, so an empty row that+ // was already on the form stays. Shared by the prune pass and both move paths.+ const removeStrandedRows = async (formId, sectionPointer, rowIndex, span) => {+ const form = await provision.getArtifact('form', formId) || {};+ const section = sectionAt(form, sectionPointer);+ if (!section) return;+ // Bottom-up, so each removal leaves the earlier indexes valid without a re-read.+ for (const i of strandedRows(section.rows || [], rowIndex, span)) {+ await provision.removeElement('form', formId, `${sectionPointer}/rows/${i}`);+ }};+ // The departing cell's rowspan, read BEFORE it leaves: once it is gone, the rows it covered can only+ // be found from this number.+ const departingSpan = (form, location) => Number((cellAt(form, location) || {}).rowspan) || 1;// Move each anchored field so it immediately follows its anchor (`fieldOptions[x].after`).//@@ -2013,17 +2055,12 @@ async function runSdkBuild(spec, opts = {}) {let index = to.cellIndex + 1;if (from.cellsPointer === to.cellsPointer && from.cellIndex < index) index -= 1;+ const span = departingSpan(form, from);await provision.moveElement('form', formId, from.cellPointer, to.cellsPointer, { index });- // Moving the only cell out of a row leaves an empty `<row/>`, which renders as a blank line and- // would accumulate one per anchored field. Row indices are unchanged by a cell move (cells- // move between rows; the row count does not change), so the source row is still where it was.- if (from.rowCellCount === 1 && from.rowPointer !== to.rowPointer) {- const after = await provision.getArtifact('form', formId) || {};- const stranded = jsonPointerRow(after, from.rowPointer);- if (stranded && (stranded.cells || []).length === 0) {- await provision.removeElement('form', formId, from.rowPointer);- }- }+ // The rows the move left holding nothing go (see removeStrandedRows). Row indices are unchanged+ // by a cell move (cells move between rows; the row count does not change), so the source rows+ // are still where they were.+ if (from.rowPointer !== to.rowPointer) await removeStrandedRows(formId, from.sectionPointer, from.rowIndex, span);}};@@ -2278,7 +2315,7 @@ async function runSdkBuild(spec, opts = {}) {// apply sees the width already applied and has nothing to do.const width = Number(patch.columns);reflow = false;- if (!(live.rows || []).every((r) => rowWidth((r && r.cells) || []) <= width)) {+ if (!fitsGrid(live.rows || [], width)) {delete patch.columns;reportLayoutSkip(`form section '${live.name || pointer}' keeps its ${live.columns}-column grid: narrowing it `+ `to ${width} would overflow rows that cannot be re-flowed without moving a cell into a row-spanning `@@ -2404,6 +2441,25 @@ async function runSdkBuild(spec, opts = {}) {return false;};const rowWidth = (cells) => (cells || []).reduce((n, c) => n + (Number(c.colspan) || 1), 0);+ const maxRowspan = (rows) => Math.max(1, ...(rows || []).flatMap((r) => ((r && r.cells) || []).map((c) => Number(c.rowspan) || 1)));+ const rowReservationAt = (rows, rowIndex) => {+ const padded = (rows || []).slice();+ while (padded.length <= rowIndex) padded.push({ cells: [] });+ const occupancy = rowOccupancy(padded)[rowIndex];+ return occupancy ? occupancy.reserved : 0;+ };+ const fitsWithCellAtRow = (rows, rowIndex, cell, width) => {+ const row = ((rows || [])[rowIndex]) || { cells: [] };+ return cellFitsInRow(row, cell, width, rowReservationAt(rows, rowIndex));+ };+ const firstAppendRowThatFits = (rows, cell, width) => {+ const start = Math.max(0, (rows || []).length - 1);+ const limit = (rows || []).length + maxRowspan(rows);+ for (let rowIndex = start; rowIndex <= limit; rowIndex += 1) {+ if (fitsWithCellAtRow(rows, rowIndex, cell, width)) return rowIndex;+ }+ return Math.max(0, (rows || []).length);+ };// Whether any cell — a field or an empty spacer — comes after (rowIndex, cellIndex) in reading order.const cellFollows = (rows, rowIndex, cellIndex) => (rows || []).some((r, ri) => ri >= rowIndex&& ((r && r.cells) || []).some((_, ci) => ri > rowIndex || ci > cellIndex));@@ -2478,8 +2534,15 @@ async function runSdkBuild(spec, opts = {}) {const row = rows[location.rowIndex];const beforeCells = (row && row.cells) || [];const afterCells = beforeCells.map((c, i) => (i === location.cellIndex ? { ...c, ...patch } : c));- const overflows = rowsFromCells(afterCells, sec.columns).length > 1;- const unsafe = reflowBreaksReservation(rows.map((r, i) => (i === location.rowIndex ? { ...r, cells: afterCells } : r)));+ const afterRows = rows.map((r, i) => (i === location.rowIndex ? { ...r, cells: afterCells } : r));+ const patchedCell = afterCells[location.cellIndex] || live;+ const occupiedUntil = location.rowIndex + Math.max(1, Number(patchedCell && patchedCell.rowspan) || 1) - 1;+ const paddedAfterRows = afterRows.slice();+ while (paddedAfterRows.length <= occupiedUntil) paddedAfterRows.push({ cells: [] });+ const occupancy = rowOccupancy(paddedAfterRows);+ const overflows = occupancy.slice(location.rowIndex, occupiedUntil + 1)+ .some((row) => row && row.used > (Number(sec.columns) || 1));+ const unsafe = reflowBreaksReservation(afterRows);if (overflows && unsafe) {if (rowWidth(afterCells) > rowWidth(beforeCells)) {// A WIDENING into an overflow: skipped whole, not half-applied. Applying it without the@@ -2553,7 +2616,8 @@ async function runSdkBuild(spec, opts = {}) {// two single-width fields per row. The reconcile path used to ignore that entirely — every ADDED// field became its own single-cell row and every MOVED field was appended to the last row whatever// its width — so the same spec deployed a different shape depending only on whether the form- // already existed. `cellFitsInRow` is the create path's own rule, shared rather than restated.+ // already existed. The effective-capacity check below is the create path's width rule plus+ // any columns still reserved by row-spanning cells above the target row.//// MEASURED against the vendored bundle: `addElement` REFUSES a `.../rows/<i>/cells` pointer// ("Path not found in form/<id>"), so a cell cannot be appended to an existing row that way. The@@ -2563,10 +2627,14 @@ async function runSdkBuild(spec, opts = {}) {const appendCellPacked = async (formId, form, sectionPointer, wantCell) => {const section = sectionAt(form, sectionPointer) || {};const rows = section.rows || [];- const lastIndex = rows.length - 1;- if (lastIndex >= 0 && cellFitsInRow(rows[lastIndex], wantCell, section.columns)) {- await provision.updateElement('form', formId, sectionPointer + '/rows/' + lastIndex,- { cells: [...(rows[lastIndex].cells || []), wantCell] });+ const rowIndex = firstAppendRowThatFits(rows, wantCell, section.columns);+ while ((section.rows || []).length < rowIndex) {+ await provision.addElement('form', formId, sectionPointer + '/rows', { cells: [] });+ section.rows = [...(section.rows || []), { cells: [] }];+ }+ if (rowIndex < rows.length) {+ await provision.updateElement('form', formId, sectionPointer + '/rows/' + rowIndex,+ { cells: [...(rows[rowIndex].cells || []), wantCell] });return;}await provision.addElement('form', formId, sectionPointer + '/rows', { cells: [wantCell] });@@ -2633,13 +2701,13 @@ async function runSdkBuild(spec, opts = {}) {// reading `.length` afterwards would yield the POST-add count and target a row one past the end,// which silently skips the move (the `if (!row) return` guard below).const priorRowCount = targetRows.length;- let rowIndex = priorRowCount - 1;- if (rowIndex < 0 || !cellFitsInRow(targetRows[rowIndex], wantCell, targetSection.columns)) {- // Either the section this run just created has no row yet, or the last row is full. The SDK- // accepts a row with an empty cells array and serializes it correctly, so seed one and target- // it. `addElement` appends, so the new row's index is the PRE-add length.+ let rowIndex = firstAppendRowThatFits(targetRows, wantCell, targetSection.columns);+ while (rowIndex >= priorRowCount && ((targetSection.rows || []).length <= rowIndex)) {+ // Either the section this run just created has no row yet, or all existing rows whose carried+ // row-span reservations leave enough capacity are behind us. The SDK accepts a row with an+ // empty cells array and serializes it correctly, so seed rows until the chosen target exists.await provision.addElement('form', formId, targetPointer + '/rows', { cells: [] });- rowIndex = priorRowCount;+ targetSection.rows = [...(targetSection.rows || []), { cells: [] }];}form = await provision.getArtifact('form', formId) || {};const from = findFieldCellLocation(form, logical);@@ -2647,17 +2715,11 @@ async function runSdkBuild(spec, opts = {}) {if (!from || !liveTarget) return;const row = ((sectionAt(form, liveTarget) || {}).rows || [])[rowIndex];if (!row) return;+ const span = departingSpan(form, from);await provision.moveElement('form', formId, from.cellPointer, liveTarget + '/rows/' + rowIndex + '/cells', { index: (row.cells || []).length });- // Moving the only cell out of a row leaves an empty `<row/>` that renders as a blank line and- // would accumulate one per relocated field. Row indices are unchanged by a cell move, so the- // source row is still where it was.- if (from.rowCellCount === 1) {- const after = await provision.getArtifact('form', formId) || {};- const stranded = jsonPointerRow(after, from.rowPointer);- if (stranded && (stranded.cells || []).length === 0) {- await provision.removeElement('form', formId, from.rowPointer);- }- }+ // The rows the move left holding nothing go (see removeStrandedRows). Row indices are unchanged by+ // a cell move, so the source rows are still where they were.+ await removeStrandedRows(formId, from.sectionPointer, from.rowIndex, span);// Converge the span NOW, in the destination, so it is clamped and packed against the section the// cell actually landed in rather than the one it left. Re-resolve the location: the move (and a@@ -2726,8 +2788,18 @@ async function runSdkBuild(spec, opts = {}) {if (def.__explicitLayout && def.__prune !== false) {const wantSet = new Set(want);const primary = def.__primaryField ? String(def.__primaryField).toLowerCase() : null;+ const { fenced, authorized, normalizedFormId } = authorizedFormRemovalEntry(opts.authorizedFormRemovals, formId, createdFormsThisRun);for (const logical of formFieldLogicals(await provision.getArtifact('form', formId) || {})) {if (wantSet.has(logical) || logical === primary) continue;+ if (fenced && (!authorized || !authorized.has(logical))) {+ // The preflight gate records the exact live field list the maker approved before this run.+ // If a later form read sees more fields, deleting them would exceed that approval (another+ // maker may have added the field while this build was starting), so keep the field and make+ // the skipped destructive change visible on the build result.+ result.skipped.unauthorizedRemovals.push({ formId: normalizedFormId, form: def.name, field: logical });+ reportLayoutSkip(`form ${def.name}: kept field '${logical}' because it was not among the removals authorized when this run started. Another maker may have added it; re-run to review it.`);+ continue;+ }const pruneForm = await provision.getArtifact('form', formId) || {};const loc = findFieldCellLocation(pruneForm, logical);// Pruning can empty a section too, so it feeds the vacated set on the same terms as a move.@@ -2736,7 +2808,14 @@ async function runSdkBuild(spec, opts = {}) {if (sec && sec.name) vacatedSections.add(String(sec.name).toLowerCase());}const ptr = loc ? loc.cellPointer : findFieldCellPointer(pruneForm, logical);- if (ptr) await provision.removeElement('form', formId, ptr);+ if (ptr) {+ // Read the span first: getArtifact can hand back the live artifact, so the cell is gone from+ // `pruneForm` once removeElement returns.+ const span = loc ? departingSpan(pruneForm, loc) : 1;+ await provision.removeElement('form', formId, ptr);+ // Pruning a field must not leave a blank line where it was (see removeStrandedRows).+ if (loc) await removeStrandedRows(formId, loc.sectionPointer, loc.rowIndex, span);+ }}}// Reclaim a section the layout VACATED (#581). A generated section name encodes position@@ -2873,7 +2952,7 @@ async function runSdkBuild(spec, opts = {}) {// before deleting ours so the table can be torn down — note that is a delete-enabler, NOT a perfect// restore of pre-build activation state (a form that was inactive before this build may be left// active after teardown).- const promoteDefaultForm = async (formId, entityLogical, deactivateOthers) => {+ const promoteDefaultForm = async (formId, entityLogical, deactivateOthers, siblingFormIds = []) => {// Deactivating the OTHER main forms is only safe once OUR form is the entity default: if the// isdefault promote failed we must NOT deactivate the others, or the entity could be left with its// (now-deactivated) stock form still the default and no active default — a bricked form experience.@@ -2890,7 +2969,27 @@ async function runSdkBuild(spec, opts = {}) {const reason = (err && err.message) ? String(err.message).slice(0, 200) : 'unknown error';if (typeof opts.warn === 'function') opts.warn(`could not make form the default for '${entityLogical}': ${reason} — the table keeps its previous default form`);}- if (!deactivateOthers || !promoted) return promoted;+ if (!promoted) return promoted;+ if (typeof provision.queryRecords === 'function') {+ for (const siblingId of siblingFormIds || []) {+ if (!siblingId || String(siblingId) === String(formId)) continue;+ try {+ const rows = await provision.queryRecords('systemform', {+ select: ['formid', 'isdefault'],+ filter: `formid eq ${siblingId}`,+ top: 1,+ });+ const sibling = rows && rows[0];+ if (sibling && sibling.isdefault === true) {+ await provision.updateRecord('systemform', String(sibling.formid || siblingId), { isdefault: false });+ }+ } catch (err) {+ const reason = (err && err.message) ? String(err.message).slice(0, 200) : 'unknown error';+ if (typeof opts.warn === 'function') opts.warn(`could not clear the previous default Main form for '${entityLogical}': ${reason}`);+ }+ }+ }+ if (!deactivateOthers) return promoted;if (typeof provision.queryRecords !== 'function') return promoted;try {// Main forms only (systemform.type == 2). Every other ACTIVE main form is deactivated@@ -2942,6 +3041,7 @@ async function runSdkBuild(spec, opts = {}) {let id;if (type === 'form') {id = await createFormShell(def);+ createdFormsThisRun.add(normalizeFormId(id));await addSubgrids(id, def.__subgrids);} else {id = (await provision.createArtifact(type, def)).id;@@ -3139,9 +3239,12 @@ async function runSdkBuild(spec, opts = {}) {// table is an environment-wide side effect.const promotedEntities = new Set();const mainByEntity = new Map(); // entity -> { id, f } chosen for promotion+ const mainIdsByEntity = new Map(); // entity -> spec-declared Main form ids for sibling demotiondefs.forEach((d, i) => {if ((d.f.formType || 'Main') !== 'Main') return;const key = d.f.entity.toLowerCase();+ if (!mainIdsByEntity.has(key)) mainIdsByEntity.set(key, []);+ if (ids[i]) mainIdsByEntity.get(key).push(ids[i]);const current = mainByEntity.get(key);// An explicit isDefault always wins; otherwise the first Main form in spec order holds the slot.if (!current || (d.f.isDefault === true && current.f.isDefault !== true)) {@@ -3157,7 +3260,7 @@ async function runSdkBuild(spec, opts = {}) {// Serialized deliberately: two promotions racing is the bug being fixed. `promoted` gates the// bookkeeping below — a build that could not set the flag must not report a default form it// did not set, which is what `result.created.defaultForms` claims.- const promoted = await promoteDefaultForm(chosen.id, entityLogical, chosen.f.deactivateOtherMainForms === true);+ const promoted = await promoteDefaultForm(chosen.id, entityLogical, chosen.f.deactivateOtherMainForms === true, mainIdsByEntity.get(entityLogical) || []);if (promoted) promotedEntities.add(entityLogical);}if (promotedEntities.size) result.created.defaultForms = Object.fromEntries(@@ -3835,6 +3938,7 @@ async function runSdkBuild(spec, opts = {}) {const liveSm = await fetchSitemap(provision, appUniqueName(spec));if (!liveSm.ok) throw new BuildHalt(`cannot verify the existing app's live generative pages before rewriting its sitemap (${liveSm.reason}) — refusing to proceed (would risk orphaning pages)`, { phase: 'app-shell', code: 'pages-sitemap-read-failed', recoverable: true });if (liveSm.ids.length && opts.allowDestructive !== true) throw new BuildHalt(`refusing to rewrite a page-less sitemap over an existing app that still has ${liveSm.ids.length} live generative page(s) (would orphan them: ${liveSm.ids.join(', ')}). Include the pages phase to reconcile them, or re-run with --allow-destructive to detach.`, { phase: 'app-shell', code: 'pages-removed', recoverable: false });+ await assertAuthorizedSitemapRewrite(provision, existingId, def.siteMap, opts.authorizedSitemapRemovals, 'app-shell');await provision.updateElement('app', existingId, '/siteMap', def.siteMap);const aiDescriptionChanged = await applyAppAiDescription(provision, spec, existingId);requireSuccessfulPush(await pushAppHeader(provision, existingId, def.name, aiDescriptionChanged), `app ${def.name}`, opts.warn);@@ -3847,6 +3951,8 @@ async function runSdkBuild(spec, opts = {}) {// refused above (refuseUnpushedAppCopy): replaying a stale sitemap rewrite detached live pages// with no gate and no --allow-destructive, and the copy's routing description may be this very// edit, left unpushed, so "unchanged" against it would skip the push the server still needs.+ const current = await provision.getArtifact('app', existingId) || {};+ await assertAuthorizedSitemapRewrite(provision, existingId, current.siteMap || {}, opts.authorizedSitemapRemovals, 'app-shell');if (await applyAppAiDescription(provision, spec, existingId)) {requireSuccessfulPush(await pushAppHeader(provision, existingId, def.name, true), `app ${def.name} routing description`, opts.warn);reportPartialPush(await provision.publishArtifact('app', existingId), `app ${def.name}`, opts.warn);@@ -4117,6 +4223,7 @@ async function runSdkBuild(spec, opts = {}) {await runner.run('pages', 'finalize sitemap (genpage subareas)', async () => {await provision.fetchArtifact('app', result.created.app);const full = appDef(spec, result.created);+ await assertAuthorizedSitemapRewrite(provision, result.created.app, full.siteMap, opts.authorizedSitemapRemovals, 'pages');await provision.updateElement('app', result.created.app, '/siteMap', full.siteMap);// #583: the routing description rides THIS push whenever the pages phase runs (the app-shell// branch defers it here). A fresh app already carries it from its create, so this is a no-op there.@@ -4836,4 +4943,4 @@ async function runSdkBuild(spec, opts = {}) {return result;}-module.exports = { runSdkBuild, planFor, annotateLivePlan, resolvePhases, PHASES, BuildHalt, SDK_COLUMN_TYPE, viewDef, defaultViewColumns, subgridLabel, enrichesDefaultViews, dashboardsInSolution, findDashboardsByName, artifactIdentityQuery, resolveExistingFormId, FORM_TYPE_CODE, chartDef, dashboardTileOpts, dashboardComponent, compileFormIntent, formFieldLogicals, appDef, appUniqueName, applyAppAiDescription, haltOnUnpublishedAppHeader, pushAppHeader, commandsByEntity, commandDef, businessRuleDef, businessRuleFilter, bpfDef, bpfFilter, webResourceOpts, WEB_RESOURCE_KINDS, FORM_EVENTS, acquireAppPagesLease, personaRoleSpecFor, resolveRoleBusinessUnit, roleBuClause, roleGrantLabel, resolveRoleGrantTarget };+module.exports = { runSdkBuild, normalizeFormId, planFor, annotateLivePlan, resolvePhases, PHASES, BuildHalt, SDK_COLUMN_TYPE, viewDef, defaultViewColumns, subgridLabel, enrichesDefaultViews, dashboardsInSolution, findDashboardsByName, artifactIdentityQuery, resolveExistingFormId, FORM_TYPE_CODE, chartDef, dashboardTileOpts, dashboardComponent, compileFormIntent, formFieldLogicals, appDef, appUniqueName, applyAppAiDescription, haltOnUnpublishedAppHeader, pushAppHeader, commandsByEntity, commandDef, businessRuleDef, businessRuleFilter, bpfDef, bpfFilter, webResourceOpts, WEB_RESOURCE_KINDS, FORM_EVENTS, acquireAppPagesLease, personaRoleSpecFor, resolveRoleBusinessUnit, roleBuClause, roleGrantLabel, resolveRoleGrantTarget };diff --git a/plugins/model-apps/scripts/lib/sdk-http-client.js b/plugins/model-apps/scripts/lib/sdk-http-client.jsindex 79dca0da7..6e7429253 100644--- a/plugins/model-apps/scripts/lib/sdk-http-client.js+++ b/plugins/model-apps/scripts/lib/sdk-http-client.js@@ -10,7 +10,7 @@// (ensureToken) or when the underlying transport itself fails — a network/timeout error (res.error)// after exhausting retries, or at once for a write that must not be re-sent (see `call`). We never// throw purely on a non-2xx HTTP status.-const { getAuthToken, makeRequest } = require('./dataverse-auth.js');+const { dataverseOrigin, getAuthToken, makeRequest } = require('./dataverse-auth.js');/*** Build an HttpClient bound to one Dataverse org.@@ -19,19 +19,16 @@ const { getAuthToken, makeRequest } = require('./dataverse-auth.js');* @returns {{get,post,patch,delete,put,postRaw}}*/function createAzHttpClient(orgUrl, deps = {}) {- const clean = String(orgUrl).replace(/\/+$/, '');- // Same-origin guard (security): this client obtains and attaches an Azure bearer token scoped to- // `clean` (the user-supplied --env org URL), and the SDK always calls back with a FULL URL under that- // same origin (instanceUrl + /api/data/v9.x/...). To keep the credential boundary FAIL-CLOSED we (1)- // require the org URL itself to be a valid absolute https:// URL — rejecting construction otherwise, so- // a malformed/hostile --env can never silently disable the guard — and (2) refuse any request whose- // absolute URL resolves to a different origin, so the Dataverse token can never leak to another host.- let orgUrlParsed;- try { orgUrlParsed = new URL(clean); } catch { orgUrlParsed = null; }- if (!orgUrlParsed || orgUrlParsed.protocol !== 'https:') {- throw new Error(`Invalid Dataverse org URL "${orgUrl}": expected an absolute https:// URL (e.g. https://contoso.crm.dynamics.com).`);+ // Same-origin guard: this client attaches an Azure bearer token for the org, and the SDK always+ // calls back with a FULL URL under that org (instanceUrl + /api/data/v9.x/...). To keep the+ // credential boundary fail-closed, construction requires a Dataverse environment ORIGIN (the same+ // check every token request makes, see `dataverseOrigin`), the token is requested for that+ // validated origin rather than the caller's text, and any request to a different origin is refused.+ const expectedOrigin = dataverseOrigin(String(orgUrl));+ if (!expectedOrigin) {+ throw new Error(`Invalid Dataverse org URL "${orgUrl}": expected the environment's https:// origin only (e.g. https://contoso.crm.dynamics.com).`);}- const expectedOrigin = orgUrlParsed.origin;+ const clean = expectedOrigin;function assertSameOrigin(url) {let target;try { target = new URL(url); } catch { throw new Error(`Refusing to send the Dataverse token to a non-absolute URL: ${url}`); }@@ -39,7 +36,7 @@ function createAzHttpClient(orgUrl, deps = {}) {throw new Error(`Refusing to send the Dataverse token for ${expectedOrigin} to a different origin (${target.origin}); the request URL must be under the --env org URL.`);}}- const getToken = deps.getToken || ((u) => getAuthToken(u));+ const getToken = deps.getToken || ((u, options) => getAuthToken(u, options));const request = deps.request || makeRequest;const sleep = deps.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));const random = deps.random || Math.random;@@ -85,9 +82,9 @@ function createAzHttpClient(orgUrl, deps = {}) {};let token = null;- function ensureToken() {+ function ensureToken(options = {}) {if (!token) {- token = getToken(clean);+ token = getToken(clean, options);if (!token) {throw new Error(`Failed to get Azure CLI token for ${clean}. Run 'az login' first.`);}@@ -169,7 +166,13 @@ function createAzHttpClient(orgUrl, deps = {}) {continue;}if (res.statusCode === 401 && !last) {- token = null; // force a token refresh and retry immediately+ // The process-wide token memo is safe for ordinary repeats, but a 401 is the server telling+ // us this token was rejected. The retry must bypass that memo or it can only resend the same+ // rejected bearer value and convert a refresh path into a guaranteed second 401.+ token = getToken(clean, { fresh: true });+ if (!token) {+ throw new Error(`Failed to refresh Azure CLI token for ${clean}. Run 'az login' first.`);+ }continue;}if (TRANSIENT.has(res.statusCode) && !last && !noRetry) {diff --git a/plugins/model-apps/scripts/lib/telemetry/lib/agent-info.js b/plugins/model-apps/scripts/lib/telemetry/lib/agent-info.jsindex 3904f5bc1..aa6ec840b 100644--- a/plugins/model-apps/scripts/lib/telemetry/lib/agent-info.js+++ b/plugins/model-apps/scripts/lib/telemetry/lib/agent-info.js@@ -2,11 +2,12 @@const fs = require("node:fs");const path = require("node:path");-const { execFileSync } = require("node:child_process");+const { runNative } = require("./native-exec");let pacCliVersionCache;-// Reads the PAC CLI version once per process via `pac --version`. Best-effort+// Reads the PAC CLI version once per process via `pac --version`, started by+// absolute path from PATH (see native-exec.js). Best-effort// and fail-closed: missing executable, timeout, or unparseable output all// resolve to "".//@@ -20,7 +21,7 @@ function readPacCliVersion(opts = {}) {pacCliVersionCache = "";return "";}- const exec = typeof opts._exec === "function" ? opts._exec : execFileSync;+ const exec = typeof opts._exec === "function" ? opts._exec : runNative;let stdout = "";try {stdout = exec("pac", ["--version"], {diff --git a/plugins/model-apps/scripts/lib/telemetry/lib/native-exec.js b/plugins/model-apps/scripts/lib/telemetry/lib/native-exec.jsnew file mode 100644index 000000000..0b11f96e6--- /dev/null+++ b/plugins/model-apps/scripts/lib/telemetry/lib/native-exec.js@@ -0,0 +1,100 @@+"use strict";++const fs = require("node:fs");+const path = require("node:path");+const { execFileSync } = require("node:child_process");++// Starts a native command-line tool (pac) by absolute path, never by bare name.+//+// The telemetry hooks run in the user's project folder. Given a bare name,+// Node 20 on Windows looks for the executable in the working directory before+// PATH (measured: a `pac.exe` in the working directory ran; Node 22 no longer+// looks there), so a `pac.exe` left in a project would run instead of the real+// one. Resolving the name here, against absolute PATH entries only, gives the+// same answer on every Node version and platform.+//+// Only native executables are considered. These calls run without a shell, and+// Windows cannot start a .cmd or .bat that way, so a pac.cmd install is not+// found, as it was not before either.++function isFile(p) {+ try {+ return fs.statSync(p).isFile();+ } catch {+ return false;+ }+}++// A candidate the OS would actually start: a regular file and, off Windows,+// one the user may execute. Node's own lookup skips a non-executable `pac`+// earlier on PATH and keeps searching, so this does too.+function isRunnable(p, platform) {+ if (!isFile(p)) return false;+ if (platform === "win32") return true;+ try {+ fs.accessSync(p, fs.constants.X_OK);+ return true;+ } catch {+ return false;+ }+}++// Windows variable names are case-insensitive. When an env object carries+// several spellings (a copied `Path` plus an added `PATH`), Node passes the+// child the lexicographically first one, so read that same one.+function envValue(env, name, platform) {+ if (platform !== "win32") return env[name];+ const key = Object.keys(env)+ .filter((k) => k.toUpperCase() === name.toUpperCase())+ .sort()[0];+ return key === undefined ? undefined : env[key];+}++/**+ * Absolute path of a native executable found on PATH, or null. Relative PATH+ * entries (an empty entry means "the current directory" on POSIX) are skipped.+ * On Windows `.com` then `.exe` is tried whatever PATHEXT says, as Node's own+ * shell-free lookup does.+ */+function resolveNative(+ name,+ { platform = process.platform, env = process.env, exists = (p) => isRunnable(p, platform) } = {}+) {+ const win = platform === "win32";+ const p = win ? path.win32 : path.posix;+ const dirs = String(envValue(env, "PATH", platform) || "")+ .split(win ? ";" : ":")+ .map((d) => d.trim().replace(/^"(.*)"$/, "$1"))+ .filter((d) => d && p.isAbsolute(d));+ const exts = win ? [".com", ".exe"] : [""];+ for (const dir of dirs) {+ for (const ext of exts) {+ const candidate = p.join(dir, name + ext);+ if (exists(candidate)) return candidate;+ }+ }+ return null;+}++/**+ * execFileSync-shaped: returns stdout, and throws when the tool is not on PATH+ * (code ENOENT) or the run fails (with err.stdout attached, as execFileSync+ * does). Callers treat any throw as "no data".+ */+function runNative(name, args, options = {}, deps = {}) {+ const file = resolveNative(name, deps);+ if (!file) {+ const err = new Error(`${name} was not found on PATH`);+ err.code = "ENOENT";+ throw err;+ }+ return execFileSync(file, args, {+ encoding: options.encoding,+ timeout: options.timeout,+ stdio: options.stdio,+ windowsHide: true,+ shell: false,+ });+}++module.exports = { resolveNative, runNative };diff --git a/plugins/model-apps/scripts/lib/telemetry/lib/pac-auth.js b/plugins/model-apps/scripts/lib/telemetry/lib/pac-auth.jsindex 71b268b59..0eb4ec6a3 100644--- a/plugins/model-apps/scripts/lib/telemetry/lib/pac-auth.js+++ b/plugins/model-apps/scripts/lib/telemetry/lib/pac-auth.js@@ -1,11 +1,13 @@"use strict";-const { execFileSync } = require("node:child_process");+const { runNative } = require("./native-exec");-// Reads PAC CLI auth state by shelling out to `pac auth who` and parsing the+// Reads PAC CLI auth state by running `pac auth who` and parsing the// banner output. Matches the convention used by// plugins/power-pages/scripts/lib/validation-helpers.js (getPacAuthInfo /// getEnvironmentUrl) so telemetry stays consistent with the rest of the repo.+// pac is started by absolute path from PATH, never by bare name (see+// native-exec.js).//// PAC's JSON profile files are an internal/undocumented format that varies// across versions. The banner output is stable and is what other code paths@@ -40,7 +42,7 @@ function readPacAuth(opts = {}) {cache = null;return null;}- const exec = typeof opts._exec === "function" ? opts._exec : execFileSync;+ const exec = typeof opts._exec === "function" ? opts._exec : runNative;let output;try {output = exec("pac", ["auth", "who"], {diff --git a/plugins/model-apps/scripts/lib/utf8-stream.js b/plugins/model-apps/scripts/lib/utf8-stream.jsnew file mode 100644index 000000000..679f7c157--- /dev/null+++ b/plugins/model-apps/scripts/lib/utf8-stream.js@@ -0,0 +1,16 @@+'use strict';++function readUtf8Stream(stream) {+ return new Promise((resolve, reject) => {+ let data = '';+ // Hook payloads are JSON and can include generated page text. Node's stream decoder buffers an+ // incomplete UTF-8 sequence between `data` events, so a page containing e.g. `東京` or `😀` is not+ // rewritten as U+FFFD when the host splits the pipe in the middle of a multibyte character.+ stream.setEncoding('utf8');+ stream.on('data', (chunk) => { data += chunk; });+ stream.on('end', () => resolve(data));+ stream.on('error', reject);+ });+}++module.exports = { readUtf8Stream };diff --git a/plugins/model-apps/scripts/lib/verify-spec.js b/plugins/model-apps/scripts/lib/verify-spec.jsindex 288155e3f..dd141471b 100644--- a/plugins/model-apps/scripts/lib/verify-spec.js+++ b/plugins/model-apps/scripts/lib/verify-spec.js@@ -17,6 +17,7 @@ const { resolveSurfaces } = require('./surface-resolver.js');const { selectSummaryTables } = require('./ai-candidates.js');const { isVisualizationUnsupported } = require('./entity-provision.js');const { sectionGridWidth, mergeFieldOptions, fieldOptionsMap, normalizeFieldEntry } = require('./artifact-intent.js');+const { rowOccupancy } = require('./form-occupancy.js');// The PER-APP setting each AI feature writes now lives in ./ai-app-settings.js, together with the// flag-resolution and override-proof helpers the BUILD uses — see that module for why one source of@@ -55,6 +56,7 @@ async function verifySpec(spec, read, opts = {}) {const phaseSkipped = [];const selectedDefaultForms = new Map();+ const declaredMainFormsByEntity = new Map();for (const f of spec.forms || []) {const formType = f.formType || 'Main';if (formType !== 'Main') continue;@@ -70,6 +72,8 @@ async function verifySpec(spec, read, opts = {}) {const isOwnCustomTable = !!(entSpec && entSpec.existing !== true && prefix &&String(entSpec.schemaName).toLowerCase().startsWith(String(prefix).toLowerCase() + '_'));if (!isOwnCustomTable) continue;+ if (!declaredMainFormsByEntity.has(entity)) declaredMainFormsByEntity.set(entity, []);+ declaredMainFormsByEntity.get(entity).push(f);const current = selectedDefaultForms.get(entity);if (!current || (f.isDefault === true && current.isDefault !== true)) selectedDefaultForms.set(entity, f);}@@ -115,10 +119,11 @@ async function verifySpec(spec, read, opts = {}) {// Views / charts / forms — by (entity, name) identity.for (const v of spec.views || []) {const viewName = `${String(v.entity).toLowerCase()}.${v.name}`;- // Also select layoutxml so a CONTENT check can catch a view whose column set drifted from the spec- // (reconcileView is additive-union, so a removed/renamed spec column would otherwise silently NOT- // apply and still pass an existence-only verify). Best-effort: the column check only runs when the- // deployed row actually carries layoutxml — an existence-only reader (no layoutxml) skips it.+ // Also select layoutxml so a CONTENT check can catch a spec column the view does not carry (an+ // added or renamed column that never landed would otherwise pass an existence-only verify). It+ // cannot catch a column REMOVED from the spec: reconcileView is additive-union, so the column stays+ // deployed, and an extra deployed column is deliberately not a failure (see below). Best-effort: the+ // column check only runs when the deployed row actually carries layoutxml.let rows = [];let readError = null;try {@@ -262,6 +267,7 @@ async function verifySpec(spec, read, opts = {}) {}add('dashboard', d.name, problems.length === 0, problems.join('; '));}+ const resolvedMainFormsByEntity = new Map();for (const f of spec.forms || []) {const name = f.name || `${f.entity} form`;// Resolve with the SAME identity the build reconcile uses — (entity, name, TYPE) or a validated pinned@@ -275,6 +281,10 @@ async function verifySpec(spec, read, opts = {}) {} catch { id = null; }add('form', name, id);const entityLogical = String(f.entity || '').toLowerCase();+ if (id && declaredMainFormsByEntity.has(entityLogical) && (f.formType || 'Main') === 'Main') {+ if (!resolvedMainFormsByEntity.has(entityLogical)) resolvedMainFormsByEntity.set(entityLogical, []);+ resolvedMainFormsByEntity.get(entityLogical).push({ form: f, name, id });+ }if (id && selectedDefaultForms.get(entityLogical) === f && typeof read.formDefaultState === 'function') {let state = null;let readError = null;@@ -290,6 +300,24 @@ async function verifySpec(spec, read, opts = {}) {: `expected this Main form to be the table default, but deployed systemform.isdefault is ${state && state.isDefault === false ? 'false' : 'unreadable'}`);}}+ if (typeof read.formDefaultState === 'function') {+ for (const [entityLogical, selected] of selectedDefaultForms) {+ const selectedName = selected.name || `${selected.entity} form`;+ for (const sibling of resolvedMainFormsByEntity.get(entityLogical) || []) {+ if (sibling.form === selected) continue;+ let state = null;+ let readError = null;+ try { state = await read.formDefaultState(entityLogical, sibling.id); } catch (e) { readError = (e && e.message) || String(e); }+ const present = !!(state && state.isDefault !== true && !readError);+ add('form-default-unique', `${entityLogical}.${sibling.name}`, present, present ? '' :+ readError+ ? `could not read deployed systemform.isdefault: ${readError}`+ : state && state.isDefault === true+ ? `another spec-declared Main form is also default; expected only '${selectedName}' to be default`+ : 'could not prove this spec-declared Main form is not also default');+ }+ }+ }// Relationships (existence) — currently a build can declare a relationship that silently fails to// materialize and still pass verify (relationships weren't checked at all). Best-effort: only when the@@ -455,21 +483,12 @@ async function verifySpec(spec, read, opts = {}) {// sitting under a rowspan — live, `[name rowspan=2, tier] / [code, zeta]` in a 2-column// section passed, with row 2 needing three columns.if (Number.isFinite(secCols) && secCols >= 1) {- let carried = []; // one entry per reserving cell: its width and the rows it still covers- for (const [ri, drow] of (secHit.item.rows || []).entries()) {- const own = (drow.cells || []).reduce((n, c) => n + (Number(c.colspan) || 1), 0);- const reserved = carried.reduce((n, r) => n + r.width, 0);- const used = own + reserved;- if (used > secCols) {- problems.push(`section '${secName}' row ${ri + 1} carries ${used} columns of content`- + (reserved ? ` (${reserved} reserved by a row-spanning cell above)` : '')+ for (const [ri, occupancy] of rowOccupancy(secHit.item.rows || []).entries()) {+ if (occupancy.used > secCols) {+ problems.push(`section '${secName}' row ${ri + 1} carries ${occupancy.used} columns of content`+ + (occupancy.reserved ? ` (${occupancy.reserved} reserved by a row-spanning cell above)` : '')+ ` in a ${secCols}-column section`);}- carried = carried.map((r) => ({ width: r.width, left: r.left - 1 })).filter((r) => r.left > 0);- for (const c of drow.cells || []) {- const rs = Number(c.rowspan) || 1;- if (rs > 1) carried.push({ width: Number(c.colspan) || 1, left: rs - 1 });- }}}// A span the author DECLARED must be the deployed span. An UNDECLARED one is notdiff --git a/plugins/model-apps/scripts/list-connections.js b/plugins/model-apps/scripts/list-connections.jsindex 15fb79c69..6f4ca11e8 100644--- a/plugins/model-apps/scripts/list-connections.js+++ b/plugins/model-apps/scripts/list-connections.js@@ -11,7 +11,7 @@// Output:// { "ok": true, "connections": [...], "connectionReferences": [...] }-const { spawnSync } = require('node:child_process');+const { spawnResultSync } = require('./lib/process-runner.js');const {dataverseRequest,ensureOk,@@ -19,7 +19,6 @@ const {validateFlags,emitResult,} = require('./lib/dataverse-auth');-const { exitIfConnectorsDisabled } = require('./lib/feature-flags');function normalizeHeader(header) {return String(header).toLowerCase().replace(/[^a-z0-9]/g, '');@@ -215,10 +214,6 @@ function pacFailureMessage(pac) {}async function main() {- // Rollback gate (fail closed) — see lib/feature-flags.js. connectors is GA and ships ON, so- // this normally passes; exit 3 = "feature off" stays distinct from 1 = runtime/usage error.- exitIfConnectorsDisabled();-const argv = process.argv.slice(2);const { positional } = parseArgs(argv);const USAGE = 'Usage: node list-connections.js <envUrl>';@@ -238,10 +233,9 @@ async function main() {const [envUrl] = positional;try {- const pac = spawnSync('pac', ['connection', 'list'], {+ const pac = spawnResultSync('pac', ['connection', 'list'], {encoding: 'utf8',stdio: ['ignore', 'pipe', 'pipe'],- shell: process.platform === 'win32',});if (pac.error || pac.status !== 0) {throw new Error(pacFailureMessage(pac));diff --git a/plugins/model-apps/scripts/list-custom-apis.js b/plugins/model-apps/scripts/list-custom-apis.jsindex b69ea093e..aa745dd9b 100644--- a/plugins/model-apps/scripts/list-custom-apis.js+++ b/plugins/model-apps/scripts/list-custom-apis.js@@ -31,6 +31,7 @@ const {emitResult,} = require('./lib/dataverse-auth');const { exitIfCustomApiDisabled } = require('./lib/feature-flags');+const { odataLit } = require('./lib/odata');// customapi.bindingtype is a Dataverse option set. Only the value→meaning mapping matters here;// a page invokes a record-bound API via boundTo, so we surface Entity as bound and Global as unbound.@@ -68,11 +69,6 @@ function mapParameterKind(typeValue) {return PARAMETER_KIND_BY_TYPE[typeValue];}-function escapeODataString(value) {- // OData string literals escape a single quote by doubling it, e.g. O'Brien -> 'O''Brien'.- return String(value).replace(/'/g, "''");-}-// Builds the $filter for the customapi query: every Global API (bindingtype 0), plus the entity-bound// APIs for the page's tables when `entities` is non-empty. When NO tables are supplied, return ONLY// Global APIs — returning every entity-bound API in the environment can explode the result set (and@@ -86,7 +82,7 @@ function buildCustomApiFilter(entities) {return 'bindingtype eq 0';}const bound = list- .map((e) => `boundentitylogicalname eq '${escapeODataString(e)}'`)+ .map((e) => `boundentitylogicalname eq '${odataLit(e)}'`).join(' or ');return `bindingtype eq 0 or (${bound})`;}@@ -193,5 +189,4 @@ module.exports = {buildCustomApiFilter,parameterKindsFromRows,toCustomApiEntry,- escapeODataString,};diff --git a/plugins/model-apps/scripts/promote-intent-pages.js b/plugins/model-apps/scripts/promote-intent-pages.jsindex e374478b3..687bbbf80 100644--- a/plugins/model-apps/scripts/promote-intent-pages.js+++ b/plugins/model-apps/scripts/promote-intent-pages.js@@ -22,43 +22,9 @@ const { parseArgs, validateFlags, readJsonArg, emitResult } = require('./lib/datconst { migrateAppSpec } = require('./lib/app-spec.js');const { pageKey, pageFile } = require('./lib/page-plan.js');const { navReferencedKeys, navMalformedRefs, navTargetParity } = require('./lib/pageref-resolver.js');-const { blankLiterals, endsMidStatement, findElisionMarker, hasDefaultExport, hasUnbalancedBrackets } = require('./lib/source-literals.js');--// A generated page must be a real React module. We deliberately do NOT typecheck here (the plugin-// ships with no dependencies, so there is no TS parser to call, and typechecking is the build's-// job) — this is the structural gate that catches the realistic worker failures: an empty file, a-// truncated write, or prose returned instead of code.-//-// Every check runs over literal-blanked source (see lib/source-literals.js). A substring search —-// even one over a copy that deliberately PRESERVES ordinary string bodies — accepted prose that-// merely MENTIONS an export:-// /* export default */ -> promoted-// const prose = "export default GeneratedComponent"; -> promoted-// Promotion is sticky (the page is then marked implemented and skipped on the next run), so a-// fail-open here corrupts the state the user would otherwise retry from.-function structuralProblems(code) {- const out = [];- if (!code.trim()) return ['file is empty'];- if (!hasDefaultExport(code)) {- out.push('no real `export default` (or `export { X as default }`) — the host cannot mount the page');- }- if (hasUnbalancedBrackets(code)) {- out.push('unbalanced brackets — the file looks truncated');- }- // A cut that leaves every bracket balanced: inside JSX, a template or a comment, or after `a +`.- if (endsMidStatement(code)) out.push('stops mid-statement — the file looks truncated');- // A worker that answers in prose usually still opens a fence; a real .tsx never has one in CODE.- // Both CommonMark fence markers count. On the blanked source, as genpage-worker-output.js checks it: a- // fence inside a template literal (a page rendering markdown help) is data, and refusing it here made the- // two gates disagree about the same page.- if (/^\s*(```|~~~)/m.test(blankLiterals(code))) out.push('contains a markdown code fence — the worker returned prose, not a module');- // Elided code — `// TODO: …`, `// ...`, "omitted for brevity" — the same shared rule the worker gate and- // Layer 2 apply. Promotion checked only the structure, so a page that elided its body was promoted and- // went on through /app-builder.- const elision = findElisionMarker(code);- if (elision) out.push(`contains ${elision} — the page is incomplete`);- return out;-}+// The structural gate (empty, truncated, prose, elided) is shared with genpage-worker-output.js, so a+// page one gate refuses the other refuses too. See lib/page-structure.js for each check and why.+const { pageStructureProblems: structuralProblems } = require('./lib/page-structure.js');function validatePage(page, absWorkingDir) {const key = pageKey(page);diff --git a/plugins/model-apps/scripts/regenerate-verified-icons.js b/plugins/model-apps/scripts/regenerate-verified-icons.jsindex 370db1e17..59d529dd7 100644--- a/plugins/model-apps/scripts/regenerate-verified-icons.js+++ b/plugins/model-apps/scripts/regenerate-verified-icons.js@@ -14,7 +14,8 @@* - npm (for the one-time install in a temp dir)* - Network access to npm registry*/-const { execFileSync } = require('child_process');+// npm is a batch shim on Windows; the runner starts it without a shell (see lib/process-runner.js).+const { runSync } = require('./lib/process-runner');const fs = require('fs');const os = require('os');const path = require('path');@@ -28,12 +29,11 @@ const OUTPUT = path.join(__dirname, '..', 'references', 'verified-icons.txt');const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'verify-icons-'));console.log(`Installing ${ICON_PKG} into ${tmpDir}...`);-// On Windows, npm is a shim invoked through cmd. execFile needs shell:true there.-const npmShellOpts = { cwd: tmpDir, stdio: 'inherit', shell: process.platform === 'win32' };+const npmOpts = { cwd: tmpDir, stdio: 'inherit' };try {- execFileSync('npm', ['init', '-y'], { ...npmShellOpts, stdio: 'ignore' });- execFileSync('npm', ['install', ICON_PKG, '--no-save', '--silent'], npmShellOpts);+ runSync('npm', ['init', '-y'], { ...npmOpts, stdio: 'ignore' });+ runSync('npm', ['install', ICON_PKG, '--no-save', '--silent'], npmOpts);// Load the module from the temp dir and enumerate exports.const iconsPath = path.join(tmpDir, 'node_modules', '@fluentui', 'react-icons');diff --git a/plugins/model-apps/scripts/run-tests.js b/plugins/model-apps/scripts/run-tests.jsindex 6242539f4..cf7aac316 100644--- a/plugins/model-apps/scripts/run-tests.js+++ b/plugins/model-apps/scripts/run-tests.js@@ -11,6 +11,7 @@// NODE20_BIN=C:/path/to/node20/dir node scripts/run-tests.js --with-sdk <ppux>const { spawnSync } = require('node:child_process');+const { spawnResultSync, withPathFirst } = require('./lib/process-runner.js');const fs = require('node:fs');const path = require('node:path');@@ -83,8 +84,11 @@ function main(argv) {results.push({ name: 'cds-maker-sdk Jest', ok: true, skipped: 'no Node 20 (set NODE20_BIN)' });} else {process.stdout.write('\n=== cds-maker-sdk Jest (Node 20) ===\n');- const env = { ...process.env, PATH: `${spec.node20Bin}${path.delimiter}${process.env.PATH}` };- const sdk = spawnSync('npm', ['test'], { cwd: spec.pkgDir, stdio: 'inherit', env, shell: true });+ // Node 20 first on the path. On Windows, where names are case-insensitive, an added `PATH` beside the+ // inherited `Path` would leave two values, of which Node passes the child only one.+ const env = withPathFirst(process.env, spec.node20Bin);+ // npm is resolved from the Node 20 PATH above, and started without a shell.+ const sdk = spawnResultSync('npm', ['test'], { cwd: spec.pkgDir, stdio: 'inherit', env }, { env });results.push({ name: 'cds-maker-sdk Jest', ok: sdk.status === 0 });}}diff --git a/plugins/model-apps/scripts/tests/add-page-to-solution.test.js b/plugins/model-apps/scripts/tests/add-page-to-solution.test.jsindex 6ffc820d4..6e12dc93f 100644--- a/plugins/model-apps/scripts/tests/add-page-to-solution.test.js+++ b/plugins/model-apps/scripts/tests/add-page-to-solution.test.js@@ -225,47 +225,13 @@ test('a failing AddSolutionComponent surfaces as a failure, not a silent partial);});-test('--connection-refs while the rollback switch is off exits 3 before any mutation', () => {- // The gate's whole purpose: refuse BEFORE the first AddSolutionComponent, so a refused run- // leaves the solution untouched rather than half-packaged (app + pages added, refs missing).- // Dropping the refs while still reporting ok:true is what made this silently lossy before —- // the solution then imports with unbound connectors.- const res = spawnSync(- process.execPath,- [scriptPath, 'https://contoso.crm.dynamics.com', 'sol', 'app-1', '--connection-refs', 'new_a'],- { encoding: 'utf8', env: { ...process.env, GENPAGE_ENABLE_CONNECTORS: '0' } }- );- assert.equal(res.status, 3, 'exit 3 = feature off (distinct from 1 = usage/runtime error)');- assert.match(res.stderr, /Connector support is disabled/);- assert.doesNotMatch(res.stdout || '', /"ok":\s*true/, 'must not report success');-});--test('packaging WITHOUT --connection-refs is not gated by the rollback switch', () => {- // Only an explicit connector request is refused; ordinary page packaging must still work.- // Reaching a Dataverse/auth failure (not exit 3) proves the gate did not fire.- const res = spawnSync(- process.execPath,- [scriptPath, 'https://example.invalid', 'sol', 'app-1', '--page-ids', 'p1'],- { encoding: 'utf8', env: { ...process.env, GENPAGE_ENABLE_CONNECTORS: '0' } }- );- assert.notEqual(res.status, 3, 'the gate must not fire without --connection-refs');-});--test('connectionRefsToAdd drops refs only when the switch is off', () => {- const { connectionRefsToAdd } = require(scriptPath);- assert.deepEqual(connectionRefsToAdd(['new_a', 'new_b'], true), ['new_a', 'new_b']);- assert.deepEqual(connectionRefsToAdd(['new_a', 'new_b'], false), []);-});-test('the stable app component type and dynamic entity names are pinned', () => {const {APPMODULE_COMPONENT_TYPE,UXAGENTPROJECT_LOGICAL_NAME,CONNECTION_REFERENCE_LOGICAL_NAME,- escapeODataString,} = require(scriptPath);assert.equal(APPMODULE_COMPONENT_TYPE, 80);assert.equal(UXAGENTPROJECT_LOGICAL_NAME, 'uxagentproject');assert.equal(CONNECTION_REFERENCE_LOGICAL_NAME, 'connectionreference');- assert.equal(escapeODataString("a'b'c"), "a''b''c");});diff --git a/plugins/model-apps/scripts/tests/build-model-app.test.js b/plugins/model-apps/scripts/tests/build-model-app.test.jsindex 36ecbf50f..3c8d714c8 100644--- a/plugins/model-apps/scripts/tests/build-model-app.test.js+++ b/plugins/model-apps/scripts/tests/build-model-app.test.js@@ -324,6 +324,37 @@ test('transient auto-retry: no retries in dry-run', async () => {const cell = (fn) => ({ control: { fieldName: fn } });const formOf = (fields) => ({ tabs: [{ columns: [{ sections: [{ rows: fields.map((f) => ({ cells: [cell(f)] })) }] }] }] });+function makeTestWorkspace(name) {+ const dir = path.join(__dirname, '.tmp-prune-approvals', `${name}-${process.pid}-${Date.now()}`);+ fs.rmSync(dir, { recursive: true, force: true });+ fs.mkdirSync(dir, { recursive: true });+ return dir;+}++function cleanupTestWorkspace(dir) {+ fs.rmSync(dir, { recursive: true, force: true });+}++function approvalRecordPath(workspaceDir) {+ return path.join(workspaceDir, 'destructive-approval.json');+}++function readApprovalRecord(workspaceDir) {+ return JSON.parse(fs.readFileSync(approvalRecordPath(workspaceDir), 'utf8'));+}++function writeApprovalRecord(workspaceDir, record) {+ fs.mkdirSync(workspaceDir, { recursive: true });+ fs.writeFileSync(approvalRecordPath(workspaceDir), JSON.stringify(record, null, 2) + '\n', 'utf8');+}++function successfulRunBuild(capture) {+ return async (spec, runOpts) => {+ if (capture) capture.push(runOpts);+ return { ok: true, created: {}, skipped: { layout: [] } };+ };+}+test('envTruthy: only 1/true (case-insensitive) count as set', () => {const { envTruthy } = require(path.join(__dirname, '..', 'build-model-app.js'));assert.strictEqual(envTruthy('1'), true);@@ -363,6 +394,512 @@ test('destructive gate: build halts on a form-field removal without --allow-destassert.ok(!calls.some((c) => c[0] === 'createSolution'), 'halted before any write');});+test('destructive gate: prune:false form removal is not refused and reaches runBuild', async () => {+ const { sdk } = mockSdk();+ const def = Object.assign(formOf(['new_name']), { __explicitLayout: true, __prune: false, __primaryField: 'new_name' });+ const deployedForm = formOf(['new_name', 'new_priority']);+ const state = { collision: { appExists: false, solutionExists: false }, forms: [{ formId: 'form-1', label: 'form "Ticket" (new_ticket)', deployedForm, def }], sitemap: null };+ const runOpts = [];+ const r = await buildModelApp(desk, { apply: true, env: 'https://x', retryDelayMs: 0 }, { sdk, provisionSdk: sdk, discoverOpDiffState: async () => state, runBuild: successfulRunBuild(runOpts) });+ assert.strictEqual(r.ok, true);+ assert.strictEqual(runOpts.length, 1, 'runBuild was reached');+});++test('destructive gate: refusal writes the approval record without changing the refusal message', async () => {+ const { sdk } = mockSdk();+ const workspaceDir = makeTestWorkspace('refusal-record');+ try {+ const def = Object.assign(formOf(['new_name']), { __explicitLayout: true, __primaryField: 'new_name' });+ const deployedForm = formOf(['new_name', 'new_priority']);+ const state = { collision: { appExists: false, solutionExists: false }, forms: [{ formId: 'form-1', label: 'form "Ticket" (new_ticket)', deployedForm, def }], sitemap: { deployedTargets: ['entity:new_customer', 'entity:new_ticket'], wantTargets: ['entity:new_customer'] } };+ const r = await buildModelApp(desk, { apply: true, env: 'https://x', retryDelayMs: 0, workspaceDir }, { sdk, provisionSdk: sdk, discoverOpDiffState: async () => state, runBuild: successfulRunBuild() });+ assert.strictEqual(r.ok, false);+ assert.ok(r.errors.some((e) => e.includes('refusing 2 destructive operation(s) without --allow-destructive:\n • form "Ticket" (new_ticket) — removes field(s): new_priority\n • app sitemap — drops navigation target(s): entity:new_ticket')), 'refusal text stays the maker-facing list');+ const record = readApprovalRecord(workspaceDir);+ assert.strictEqual(record.schemaVersion, 1);+ assert.deepStrictEqual(record.formRemovals, { 'form-1': { label: 'form "Ticket" (new_ticket)', fields: ['new_priority'] } });+ assert.deepStrictEqual(record.sitemapRemovals, ['entity:new_ticket']);+ assert.match(record.generatedAt, /^\d{4}-\d{2}-\d{2}T/);+ // The run id makes two builds' records differ even when they list the same removals in the same+ // millisecond, which is what lets a build tell its own record from another's by content.+ assert.match(record.runId, /^[0-9a-f-]{36}$/);+ } finally {+ cleanupTestWorkspace(workspaceDir);+ }+});++test('destructive gate: approved unchanged removals proceed with an authorized map and consume the record', async () => {+ const { sdk } = mockSdk();+ const workspaceDir = makeTestWorkspace('approved-unchanged');+ try {+ writeApprovalRecord(workspaceDir, { schemaVersion: 1, generatedAt: '2026-01-01T00:00:00.000Z', formRemovals: { 'form-1': { label: 'form "Ticket" (new_ticket)', fields: ['new_priority'] } }, sitemapRemovals: [] });+ const def = Object.assign(formOf(['new_name']), { __explicitLayout: true, __primaryField: 'new_name' });+ const deployedForm = formOf(['new_name', 'new_priority']);+ const state = { collision: { appExists: false, solutionExists: false }, forms: [{ formId: 'form-1', label: 'form "Ticket" (new_ticket)', deployedForm, def }], sitemap: null };+ const runOpts = [];+ const r = await buildModelApp(desk, { apply: true, env: 'https://x', retryDelayMs: 0, allowDestructive: true, workspaceDir }, { sdk, provisionSdk: sdk, discoverOpDiffState: async () => state, runBuild: successfulRunBuild(runOpts) });+ assert.strictEqual(r.ok, true);+ assert.ok(runOpts[0].authorizedFormRemovals instanceof Map, 'authorized removals are passed to the engine');+ assert.deepStrictEqual([...runOpts[0].authorizedFormRemovals.get('form-1')], ['new_priority']);+ assert.strictEqual(fs.existsSync(approvalRecordPath(workspaceDir)), false, 'record consumed only after success');+ } finally {+ cleanupTestWorkspace(workspaceDir);+ }+});++test('destructive gate: a newly discovered field removal after approval halts and refreshes the record', async () => {+ const { sdk } = mockSdk();+ const workspaceDir = makeTestWorkspace('new-field');+ try {+ writeApprovalRecord(workspaceDir, { schemaVersion: 1, generatedAt: '2026-01-01T00:00:00.000Z', formRemovals: { 'form-1': { label: 'form "Ticket" (new_ticket)', fields: ['new_priority'] } }, sitemapRemovals: [] });+ const def = Object.assign(formOf(['new_name']), { __explicitLayout: true, __primaryField: 'new_name' });+ const deployedForm = formOf(['new_name', 'new_priority', 'new_newmakerfield']);+ const state = { collision: { appExists: false, solutionExists: false }, forms: [{ formId: 'form-1', label: 'form "Ticket" (new_ticket)', deployedForm, def }], sitemap: null };+ let ran = false;+ const r = await buildModelApp(desk, { apply: true, env: 'https://x', retryDelayMs: 0, allowDestructive: true, workspaceDir }, { sdk, provisionSdk: sdk, discoverOpDiffState: async () => state, runBuild: async () => { ran = true; return { ok: true }; } });+ assert.strictEqual(r.ok, false);+ assert.strictEqual(ran, false, 'halted before runBuild');+ assert.ok(r.errors.some((e) => /new_newmakerfield/.test(e) && !/new_priority/.test(e)), 'only the new field is listed');+ assert.deepStrictEqual(readApprovalRecord(workspaceDir).formRemovals['form-1'].fields, ['new_priority', 'new_newmakerfield']);+ } finally {+ cleanupTestWorkspace(workspaceDir);+ }+});++test('destructive gate: a newly discovered sitemap drop after approval halts and refreshes the record', async () => {+ const { sdk } = mockSdk();+ const workspaceDir = makeTestWorkspace('new-sitemap');+ try {+ writeApprovalRecord(workspaceDir, { schemaVersion: 1, generatedAt: '2026-01-01T00:00:00.000Z', formRemovals: {}, sitemapRemovals: ['entity:new_ticket'] });+ const state = { collision: { appExists: true, appUnique: 'new_supportdesk' }, forms: [], sitemap: { deployedTargets: ['entity:new_customer', 'entity:new_ticket', 'url:https://contoso.example/help'], wantTargets: ['entity:new_customer'] } };+ let ran = false;+ const r = await buildModelApp(desk, { apply: true, env: 'https://x', retryDelayMs: 0, allowDestructive: true, workspaceDir }, { sdk, provisionSdk: sdk, discoverOpDiffState: async () => state, runBuild: async () => { ran = true; return { ok: true }; } });+ assert.strictEqual(r.ok, false);+ assert.strictEqual(ran, false, 'halted before runBuild');+ assert.ok(r.errors.some((e) => /url:https:\/\/contoso\.example\/help/.test(e) && !/entity:new_ticket/.test(e)), 'only the new sitemap drop is listed');+ assert.deepStrictEqual(readApprovalRecord(workspaceDir).sitemapRemovals, ['entity:new_ticket', 'url:https://contoso.example/help']);+ } finally {+ cleanupTestWorkspace(workspaceDir);+ }+});++test('destructive gate: an unreadable approval record fails closed', async () => {+ const { sdk } = mockSdk();+ const workspaceDir = makeTestWorkspace('bad-record');+ try {+ fs.writeFileSync(approvalRecordPath(workspaceDir), '{not json', 'utf8');+ const def = Object.assign(formOf(['new_name']), { __explicitLayout: true, __primaryField: 'new_name' });+ const state = { collision: { appExists: false, solutionExists: false }, forms: [{ formId: 'form-1', label: 'form "Ticket" (new_ticket)', deployedForm: formOf(['new_name', 'new_priority']), def }], sitemap: null };+ let ran = false;+ const r = await buildModelApp(desk, { apply: true, env: 'https://x', retryDelayMs: 0, allowDestructive: true, workspaceDir }, { sdk, provisionSdk: sdk, discoverOpDiffState: async () => state, runBuild: async () => { ran = true; return { ok: true }; } });+ assert.strictEqual(r.ok, false);+ assert.strictEqual(ran, false, 'halted before runBuild');+ assert.ok(r.errors.some((e) => /destructive-approval\.json/.test(e) && /delete it|re-run without --allow-destructive/.test(e)));+ } finally {+ cleanupTestWorkspace(workspaceDir);+ }+});++test('destructive gate: --allow-destructive without a record proceeds but still fences this run', async () => {+ const { sdk } = mockSdk();+ const workspaceDir = makeTestWorkspace('no-record');+ try {+ const def = Object.assign(formOf(['new_name']), { __explicitLayout: true, __primaryField: 'new_name' });+ const deployedForm = formOf(['new_name', 'new_priority']);+ const state = { collision: { appExists: false, solutionExists: false }, forms: [{ formId: 'form-1', label: 'form "Ticket" (new_ticket)', deployedForm, def }], sitemap: null };+ const runOpts = [];+ const r = await buildModelApp(desk, { apply: true, env: 'https://x', retryDelayMs: 0, allowDestructive: true, workspaceDir }, { sdk, provisionSdk: sdk, discoverOpDiffState: async () => state, runBuild: successfulRunBuild(runOpts) });+ assert.strictEqual(r.ok, true);+ assert.deepStrictEqual([...runOpts[0].authorizedFormRemovals.get('form-1')], ['new_priority']);+ } finally {+ cleanupTestWorkspace(workspaceDir);+ }+});++test('destructive gate: a successful apply that kept an unauthorized field preserves a prior approval record', async () => {+ const { sdk } = mockSdk();+ const workspaceDir = makeTestWorkspace('kept-field-prior-record');+ try {+ writeApprovalRecord(workspaceDir, { schemaVersion: 1, generatedAt: '2026-01-01T00:00:00.000Z', formRemovals: { 'form-1': { label: 'form "Ticket" (new_ticket)', fields: ['new_priority'] } }, sitemapRemovals: [] });+ const def = Object.assign(formOf(['new_name']), { __explicitLayout: true, __primaryField: 'new_name' });+ const approvedState = { collision: { appExists: false, solutionExists: false }, forms: [{ formId: 'form-1', label: 'form "Ticket" (new_ticket)', deployedForm: formOf(['new_name', 'new_priority']), def }], sitemap: null };+ const logs = [];+ const r = await buildModelApp(desk, { apply: true, env: 'https://x', retryDelayMs: 0, allowDestructive: true, workspaceDir }, {+ sdk,+ provisionSdk: sdk,+ discoverOpDiffState: async () => approvedState,+ log: (m) => logs.push(m),+ runBuild: async () => ({ ok: true, created: {}, skipped: { layout: [], unauthorizedRemovals: [{ formId: 'form-1', form: 'Ticket', field: 'new_midrun' }] } }),+ });+ assert.strictEqual(r.ok, true);+ assert.deepStrictEqual(readApprovalRecord(workspaceDir).formRemovals, { 'form-1': { label: 'form "Ticket" (new_ticket)', fields: ['new_priority'] } });+ assert.ok(logs.some((l) => /new_midrun/.test(l) && /next run will ask/.test(l)), 'log names the kept field and next review');++ const laterState = { collision: { appExists: false, solutionExists: false }, forms: [{ formId: 'form-1', label: 'form "Ticket" (new_ticket)', deployedForm: formOf(['new_name', 'new_priority', 'new_midrun']), def }], sitemap: null };+ let ran = false;+ const rerun = await buildModelApp(desk, { apply: true, env: 'https://x', retryDelayMs: 0, allowDestructive: true, workspaceDir }, { sdk, provisionSdk: sdk, discoverOpDiffState: async () => laterState, runBuild: async () => { ran = true; return { ok: true }; } });+ assert.strictEqual(rerun.ok, false);+ assert.strictEqual(ran, false, 'next run halts before writes');+ assert.ok(rerun.errors.some((e) => /new_midrun/.test(e) && !/new_priority/.test(e)), 'only the kept field is newly listed');+ } finally {+ cleanupTestWorkspace(workspaceDir);+ }+});++test('destructive gate: a successful blanket apply that kept an unauthorized field creates an approval record', async () => {+ const { sdk } = mockSdk();+ const workspaceDir = makeTestWorkspace('kept-field-blanket');+ try {+ const def = Object.assign(formOf(['new_name']), { __explicitLayout: true, __primaryField: 'new_name' });+ const approvedState = { collision: { appExists: false, solutionExists: false }, forms: [{ formId: 'form-1', label: 'form "Ticket" (new_ticket)', deployedForm: formOf(['new_name', 'new_priority']), def }], sitemap: null };+ const r = await buildModelApp(desk, { apply: true, env: 'https://x', retryDelayMs: 0, allowDestructive: true, workspaceDir }, {+ sdk,+ provisionSdk: sdk,+ discoverOpDiffState: async () => approvedState,+ runBuild: async () => ({ ok: true, created: {}, skipped: { layout: [], unauthorizedRemovals: [{ formId: 'form-1', form: 'Ticket', field: 'new_midrun' }] } }),+ });+ assert.strictEqual(r.ok, true);+ assert.deepStrictEqual(readApprovalRecord(workspaceDir).formRemovals, { 'form-1': { label: 'form "Ticket" (new_ticket)', fields: ['new_priority'] } });++ const laterState = { collision: { appExists: false, solutionExists: false }, forms: [{ formId: 'form-1', label: 'form "Ticket" (new_ticket)', deployedForm: formOf(['new_name', 'new_priority', 'new_midrun']), def }], sitemap: null };+ let ran = false;+ const rerun = await buildModelApp(desk, { apply: true, env: 'https://x', retryDelayMs: 0, allowDestructive: true, workspaceDir }, { sdk, provisionSdk: sdk, discoverOpDiffState: async () => laterState, runBuild: async () => { ran = true; return { ok: true }; } });+ assert.strictEqual(rerun.ok, false);+ assert.strictEqual(ran, false, 'next run halts before writes');+ assert.ok(rerun.errors.some((e) => /new_midrun/.test(e) && !/new_priority/.test(e)), 'the kept field is shown before it can be removed');+ } finally {+ cleanupTestWorkspace(workspaceDir);+ }+});++test('destructive gate: a failed blanket apply leaves the gate-time approval record for the next run', async () => {+ const { sdk } = mockSdk();+ const workspaceDir = makeTestWorkspace('failed-blanket-record');+ try {+ const def = Object.assign(formOf(['new_name']), { __explicitLayout: true, __primaryField: 'new_name' });+ const approvedState = { collision: { appExists: false, solutionExists: false }, forms: [{ formId: 'form-1', label: 'form "Ticket" (new_ticket)', deployedForm: formOf(['new_name', 'new_priority']), def }], sitemap: null };+ await assert.rejects(buildModelApp(desk, { apply: true, env: 'https://x', retryDelayMs: 0, allowDestructive: true, workspaceDir }, {+ sdk,+ provisionSdk: sdk,+ discoverOpDiffState: async () => approvedState,+ runBuild: async () => { throw new Error('forms failed after keeping new_midrun'); },+ }), /forms failed/);+ assert.deepStrictEqual(readApprovalRecord(workspaceDir).formRemovals, { 'form-1': { label: 'form "Ticket" (new_ticket)', fields: ['new_priority'] } });++ const laterState = { collision: { appExists: false, solutionExists: false }, forms: [{ formId: 'form-1', label: 'form "Ticket" (new_ticket)', deployedForm: formOf(['new_name', 'new_priority', 'new_midrun']), def }], sitemap: null };+ let ran = false;+ const rerun = await buildModelApp(desk, { apply: true, env: 'https://x', retryDelayMs: 0, allowDestructive: true, workspaceDir }, { sdk, provisionSdk: sdk, discoverOpDiffState: async () => laterState, runBuild: async () => { ran = true; return { ok: true }; } });+ assert.strictEqual(rerun.ok, false);+ assert.strictEqual(ran, false, 'next run halts before writes');+ assert.ok(rerun.errors.some((e) => /new_midrun/.test(e) && !/new_priority/.test(e)), 'newly live field is shown before it can be removed');+ } finally {+ cleanupTestWorkspace(workspaceDir);+ }+});++test('destructive gate: retry keeps the same gate-time form fence when a later form id appears', async () => {+ const { sdk } = mockSdk();+ const workspaceDir = makeTestWorkspace('retry-new-form-id');+ try {+ const def = Object.assign(formOf(['new_name']), { __explicitLayout: true, __primaryField: 'new_name' });+ const state = { collision: { appExists: false, solutionExists: false }, forms: [{ formId: 'form-1', label: 'form "Ticket" (new_ticket)', deployedForm: formOf(['new_name', 'new_priority']), def }], sitemap: null };+ let attempts = 0;+ const r = await buildModelApp(desk, { apply: true, env: 'https://x', retryDelayMs: 0, allowDestructive: true, workspaceDir }, {+ sdk,+ provisionSdk: sdk,+ discoverOpDiffState: async () => state,+ runBuild: async (spec, runOpts) => {+ attempts += 1;+ assert.ok(runOpts.authorizedFormRemovals instanceof Map, 'the retry receives the gate-time fence');+ assert.deepStrictEqual([...runOpts.authorizedFormRemovals.keys()], ['form-1']);+ if (attempts === 1) {+ const err = new Error('HTTP 503 while publishing after creating a form');+ err.statusCode = 503;+ throw err;+ }+ return { ok: true, created: {}, skipped: { layout: [], unauthorizedRemovals: [{ formId: 'form-2', form: 'Ticket', field: 'new_midretry' }] } };+ },+ });+ assert.strictEqual(r.ok, true);+ assert.strictEqual(attempts, 2, 'transient retry ran');+ assert.deepStrictEqual(readApprovalRecord(workspaceDir).formRemovals, { 'form-1': { label: 'form "Ticket" (new_ticket)', fields: ['new_priority'] } });+ } finally {+ cleanupTestWorkspace(workspaceDir);+ }+});++test('destructive gate: a data-stage apply does not consume an approval record', async () => {+ const { sdk } = mockSdk();+ const workspaceDir = makeTestWorkspace('partial-keeps-record');+ try {+ writeApprovalRecord(workspaceDir, { schemaVersion: 1, generatedAt: '2026-01-01T00:00:00.000Z', formRemovals: { 'form-1': { label: 'form "Ticket" (new_ticket)', fields: ['new_priority'] } }, sitemapRemovals: [] });+ const def = Object.assign(formOf(['new_name']), { __explicitLayout: true, __primaryField: 'new_name' });+ const approvedState = { collision: { appExists: false, solutionExists: false }, forms: [{ formId: 'form-1', label: 'form "Ticket" (new_ticket)', deployedForm: formOf(['new_name', 'new_priority']), def }], sitemap: null };+ const r = await buildModelApp(desk, { apply: true, env: 'https://x', retryDelayMs: 0, allowDestructive: true, workspaceDir, phases: ['solution', 'data-model', 'sample-data'] }, {+ sdk, provisionSdk: sdk, discoverOpDiffState: async () => approvedState, runBuild: successfulRunBuild(),+ });+ assert.strictEqual(r.ok, true);+ assert.deepStrictEqual(readApprovalRecord(workspaceDir).formRemovals['form-1'].fields, ['new_priority']);++ const laterState = { collision: { appExists: false, solutionExists: false }, forms: [{ formId: 'form-1', label: 'form "Ticket" (new_ticket)', deployedForm: formOf(['new_name', 'new_priority', 'new_midrun']), def }], sitemap: null };+ let ran = false;+ const rerun = await buildModelApp(desk, { apply: true, env: 'https://x', retryDelayMs: 0, allowDestructive: true, workspaceDir }, { sdk, provisionSdk: sdk, discoverOpDiffState: async () => laterState, runBuild: async () => { ran = true; return { ok: true }; } });+ assert.strictEqual(rerun.ok, false);+ assert.strictEqual(ran, false, 'full run halts before writes');+ assert.ok(rerun.errors.some((e) => /new_midrun/.test(e) && !/new_priority/.test(e)), 'new field is still reviewed after the partial run');+ } finally {+ cleanupTestWorkspace(workspaceDir);+ }+});++// --- The record binds the run that showed it, and only that run consumes it ------------------------+const ticketState = (fields, def) => ({ collision: { appExists: false, solutionExists: false }, forms: [{ formId: 'form-1', label: 'form "Ticket" (new_ticket)', deployedForm: formOf(fields), def }], sitemap: null });+const ticketDef = () => Object.assign(formOf(['new_name']), { __explicitLayout: true, __primaryField: 'new_name' });+// Another build's record, as that build would write it, with its own run id.+const OTHER_RECORD = JSON.stringify({ schemaVersion: 1, generatedAt: '2026-01-02T00:00:00.000Z', runId: 'another-build', formRemovals: { 'form-1': { label: 'form "Ticket" (new_ticket)', fields: ['new_priority'] } }, sitemapRemovals: [] }, null, 2) + '\n';+const rawRecord = (dir) => fs.readFileSync(approvalRecordPath(dir), 'utf8');++test('destructive gate: a failed approved apply with nothing to remove still binds the retry to that empty list', async () => {+ const { sdk } = mockSdk();+ const workspaceDir = makeTestWorkspace('failed-empty-list');+ try {+ const def = ticketDef();+ await assert.rejects(buildModelApp(desk, { apply: true, env: 'https://x', retryDelayMs: 0, allowDestructive: true, workspaceDir }, {+ sdk, provisionSdk: sdk, discoverOpDiffState: async () => ticketState(['new_name'], def),+ runBuild: async () => { throw new Error('app-shell failed after the forms phase kept new_midrun'); },+ }), /app-shell failed/);+ const recorded = readApprovalRecord(workspaceDir);+ assert.deepStrictEqual([recorded.formRemovals, recorded.sitemapRemovals], [{}, []], 'the empty gate-time list is recorded before any write');++ let ran = false;+ const rerun = await buildModelApp(desk, { apply: true, env: 'https://x', retryDelayMs: 0, allowDestructive: true, workspaceDir }, {+ sdk, provisionSdk: sdk, discoverOpDiffState: async () => ticketState(['new_name', 'new_midrun'], def), runBuild: async () => { ran = true; return { ok: true }; },+ });+ assert.strictEqual(rerun.ok, false);+ assert.strictEqual(ran, false, 'the retry halts before writes');+ assert.ok(rerun.errors.some((e) => /new_midrun/.test(e)), 'the field the failed run kept is shown before it can be removed');+ } finally {+ cleanupTestWorkspace(workspaceDir);+ }+});++test('destructive gate: a successful approved apply with nothing to remove leaves no record behind', async () => {+ const { sdk } = mockSdk();+ const workspaceDir = makeTestWorkspace('empty-list-consumed');+ try {+ const r = await buildModelApp(desk, { apply: true, env: 'https://x', retryDelayMs: 0, allowDestructive: true, workspaceDir }, {+ sdk, provisionSdk: sdk, discoverOpDiffState: async () => ticketState(['new_name'], ticketDef()), runBuild: successfulRunBuild(),+ });+ assert.strictEqual(r.ok, true);+ assert.strictEqual(fs.existsSync(approvalRecordPath(workspaceDir)), false);+ } finally {+ cleanupTestWorkspace(workspaceDir);+ }+});++test('destructive gate: an approved data-stage apply with nothing to remove writes no record', async () => {+ // The data stage runs no prune pass, so it can keep nothing, and an empty record would only make the+ // next full apply ask again about removals nobody was ever shown.+ const { sdk } = mockSdk();+ const workspaceDir = makeTestWorkspace('data-stage-empty');+ try {+ const r = await buildModelApp(desk, { apply: true, env: 'https://x', retryDelayMs: 0, allowDestructive: true, workspaceDir, phases: ['solution', 'data-model', 'sample-data'] }, {+ sdk, provisionSdk: sdk, discoverOpDiffState: async () => ticketState(['new_name'], ticketDef()), runBuild: successfulRunBuild(),+ });+ assert.strictEqual(r.ok, true);+ assert.strictEqual(fs.existsSync(approvalRecordPath(workspaceDir)), false);+ } finally {+ cleanupTestWorkspace(workspaceDir);+ }+});++test('destructive gate: a successful plain apply consumes the record it started with', async () => {+ // A maker who was refused, then changed the spec so that nothing is removed, rebuilds without+ // --allow-destructive. The old list no longer describes anything, so it goes.+ const { sdk } = mockSdk();+ const workspaceDir = makeTestWorkspace('plain-consumes-seen');+ try {+ writeApprovalRecord(workspaceDir, { schemaVersion: 1, generatedAt: '2026-01-01T00:00:00.000Z', formRemovals: { 'form-1': { label: 'form "Ticket" (new_ticket)', fields: ['new_priority'] } }, sitemapRemovals: [] });+ const r = await buildModelApp(desk, { apply: true, env: 'https://x', retryDelayMs: 0, workspaceDir }, {+ sdk, provisionSdk: sdk, discoverOpDiffState: async () => ticketState(['new_name'], ticketDef()), runBuild: successfulRunBuild(),+ });+ assert.strictEqual(r.ok, true);+ assert.strictEqual(fs.existsSync(approvalRecordPath(workspaceDir)), false);+ } finally {+ cleanupTestWorkspace(workspaceDir);+ }+});++test('destructive gate: a finishing build leaves a record another build wrote while it ran', async () => {+ // Two builds share a workspace. This one started with nothing to remove; meanwhile another build,+ // with an edited spec, refused and recorded its list. Consuming that record would leave the other+ // build's approved re-run bound to nothing.+ const { sdk } = mockSdk();+ const workspaceDir = makeTestWorkspace('other-build-record');+ try {+ const r = await buildModelApp(desk, { apply: true, env: 'https://x', retryDelayMs: 0, workspaceDir }, {+ sdk, provisionSdk: sdk, discoverOpDiffState: async () => ticketState(['new_name'], ticketDef()),+ runBuild: async () => { fs.writeFileSync(approvalRecordPath(workspaceDir), OTHER_RECORD, 'utf8'); return { ok: true, created: {}, skipped: { layout: [] } }; },+ });+ assert.strictEqual(r.ok, true);+ assert.strictEqual(rawRecord(workspaceDir), OTHER_RECORD, "the other build's record is left exactly as written");+ } finally {+ cleanupTestWorkspace(workspaceDir);+ }+});++test('destructive gate: a finishing build that kept a field does not overwrite a record another build wrote', async () => {+ const { sdk } = mockSdk();+ const workspaceDir = makeTestWorkspace('kept-other-record');+ try {+ const logs = [];+ const r = await buildModelApp(desk, { apply: true, env: 'https://x', retryDelayMs: 0, allowDestructive: true, workspaceDir }, {+ sdk, provisionSdk: sdk, log: (m) => logs.push(m), discoverOpDiffState: async () => ticketState(['new_name', 'new_priority'], ticketDef()),+ runBuild: async () => {+ fs.writeFileSync(approvalRecordPath(workspaceDir), OTHER_RECORD, 'utf8');+ return { ok: true, created: {}, skipped: { layout: [], unauthorizedRemovals: [{ formId: 'form-1', form: 'Ticket', field: 'new_midrun' }] } };+ },+ });+ assert.strictEqual(r.ok, true);+ assert.strictEqual(rawRecord(workspaceDir), OTHER_RECORD, "the other build's record is not replaced");+ assert.ok(logs.some((l) => /another build/.test(l)), 'the log says why the record was left alone');+ } finally {+ cleanupTestWorkspace(workspaceDir);+ }+});++test('destructive gate: an approved build halts before any write when the record changed after it was read', async () => {+ // This build compared its removals with the record it read. If another build replaces that record+ // before this one persists its own, the comparison no longer means anything.+ const { sdk } = mockSdk();+ const workspaceDir = makeTestWorkspace('record-changed');+ try {+ writeApprovalRecord(workspaceDir, { schemaVersion: 1, generatedAt: '2026-01-01T00:00:00.000Z', formRemovals: { 'form-1': { label: 'form "Ticket" (new_ticket)', fields: ['new_priority'] } }, sitemapRemovals: [] });+ let ran = false;+ const r = await buildModelApp(desk, { apply: true, env: 'https://x', retryDelayMs: 0, allowDestructive: true, workspaceDir }, {+ sdk, provisionSdk: sdk,+ discoverOpDiffState: async () => { fs.writeFileSync(approvalRecordPath(workspaceDir), OTHER_RECORD, 'utf8'); return ticketState(['new_name', 'new_priority'], ticketDef()); },+ runBuild: async () => { ran = true; return { ok: true }; },+ });+ assert.strictEqual(r.ok, false);+ assert.strictEqual(ran, false, 'nothing is written');+ assert.ok(r.errors.some((e) => /changed while this build was starting/.test(e)), JSON.stringify(r.errors));+ assert.strictEqual(rawRecord(workspaceDir), OTHER_RECORD);+ } finally {+ cleanupTestWorkspace(workspaceDir);+ }+});++test('destructive gate: a record the build cannot lock is left in place, and an approved build halts', async () => {+ // The record's check and change happen under the workspace lease. A lease another writer holds+ // (the test holds it here) means the record may be changing under this build.+ const { acquireLease, releaseLease } = require('../lib/apply-snapshot-store.js');+ const { sdk } = mockSdk();+ const workspaceDir = makeTestWorkspace('lease-held');+ const lease = acquireLease(workspaceDir);+ assert.strictEqual(lease.ok, true);+ try {+ writeApprovalRecord(workspaceDir, { schemaVersion: 1, generatedAt: '2026-01-01T00:00:00.000Z', formRemovals: { 'form-1': { label: 'form "Ticket" (new_ticket)', fields: ['new_priority'] } }, sitemapRemovals: [] });+ const before = rawRecord(workspaceDir);+ const logs = [];+ const plain = await buildModelApp(desk, { apply: true, env: 'https://x', retryDelayMs: 0, workspaceDir }, {+ sdk, provisionSdk: sdk, sleep: async () => {}, log: (m) => logs.push(m), discoverOpDiffState: async () => ticketState(['new_name'], ticketDef()), runBuild: successfulRunBuild(),+ });+ assert.strictEqual(plain.ok, true, 'the build itself still succeeds');+ assert.strictEqual(rawRecord(workspaceDir), before, 'the record is not consumed without the lease');+ assert.ok(logs.some((l) => /could not lock/.test(l)), 'the log says the record was left');++ let ran = false;+ const approved = await buildModelApp(desk, { apply: true, env: 'https://x', retryDelayMs: 0, allowDestructive: true, workspaceDir }, {+ sdk, provisionSdk: sdk, sleep: async () => {}, discoverOpDiffState: async () => ticketState(['new_name', 'new_priority'], ticketDef()), runBuild: async () => { ran = true; return { ok: true }; },+ });+ assert.strictEqual(approved.ok, false);+ assert.strictEqual(ran, false, 'an approved build does not mutate without recording what it may remove');+ assert.ok(approved.errors.some((e) => /could not lock the workspace/.test(e)), JSON.stringify(approved.errors));+ assert.strictEqual(rawRecord(workspaceDir), before);+ } finally {+ releaseLease(lease);+ cleanupTestWorkspace(workspaceDir);+ }+});++// Fail on one file only, for the duration of `fn`: the build's other reads and writes are real.+async function withFsFault(method, isTarget, code, fn) {+ const original = fs[method];+ fs[method] = function faulty(target, ...rest) {+ if (isTarget(String(target), ...rest)) { const err = new Error(`${code}: injected on ${path.basename(String(target))}`); err.code = code; throw err; }+ return original.call(this, target, ...rest);+ };+ try { return await fn(); } finally { fs[method] = original; }+}+const isApprovalFile = (p) => path.basename(p) === 'destructive-approval.json';++test('destructive gate: a record that cannot be read is never consumed, even when it was unreadable at the start too', async () => {+ // Two unreadable reads say nothing about whether the file is the same one: it may have been replaced+ // in between. Only a record whose bytes this build read and matched is its to consume.+ const { sdk } = mockSdk();+ const workspaceDir = makeTestWorkspace('unreadable-record');+ try {+ writeApprovalRecord(workspaceDir, { schemaVersion: 1, generatedAt: '2026-01-01T00:00:00.000Z', formRemovals: {}, sitemapRemovals: [] });+ const logs = [];+ const r = await withFsFault('readFileSync', isApprovalFile, 'EACCES', () => buildModelApp(desk, { apply: true, env: 'https://x', retryDelayMs: 0, workspaceDir }, {+ sdk, provisionSdk: sdk, log: (m) => logs.push(m), discoverOpDiffState: async () => ticketState(['new_name'], ticketDef()), runBuild: successfulRunBuild(),+ }));+ assert.strictEqual(r.ok, true, 'a plain build is not stopped by an unreadable record');+ assert.strictEqual(fs.existsSync(approvalRecordPath(workspaceDir)), true, 'the unreadable record is left');+ assert.ok(logs.some((l) => /could not be read/.test(l)), 'the log says why it was left');+ } finally {+ cleanupTestWorkspace(workspaceDir);+ }+});++test('destructive gate: an approved build halts when the record becomes unreadable before its list is recorded', async () => {+ // Read fine at the start (and compared), unreadable by the time this build would replace it: what is+ // on disk may no longer be what it compared with, and it must not be written over blind.+ const { sdk } = mockSdk();+ const workspaceDir = makeTestWorkspace('record-turns-unreadable');+ const original = fs.readFileSync;+ let fault = false;+ fs.readFileSync = function faulty(target, ...rest) {+ if (fault && isApprovalFile(String(target))) { const err = new Error('EACCES: injected'); err.code = 'EACCES'; throw err; }+ return original.call(this, target, ...rest);+ };+ try {+ writeApprovalRecord(workspaceDir, { schemaVersion: 1, generatedAt: '2026-01-01T00:00:00.000Z', formRemovals: { 'form-1': { label: 'form "Ticket" (new_ticket)', fields: ['new_priority'] } }, sitemapRemovals: [] });+ const before = original.call(fs, approvalRecordPath(workspaceDir), 'utf8');+ let ran = false;+ const r = await buildModelApp(desk, { apply: true, env: 'https://x', retryDelayMs: 0, allowDestructive: true, workspaceDir }, {+ sdk, provisionSdk: sdk,+ discoverOpDiffState: async () => { fault = true; return ticketState(['new_name', 'new_priority'], ticketDef()); },+ runBuild: async () => { ran = true; return { ok: true }; },+ });+ assert.strictEqual(r.ok, false);+ assert.strictEqual(ran, false, 'nothing runs unbound');+ assert.ok(r.errors.some((e) => /could not be read while this build was starting/.test(e)), JSON.stringify(r.errors));+ fs.readFileSync = original;+ assert.strictEqual(fs.readFileSync(approvalRecordPath(workspaceDir), 'utf8'), before, 'the record is not written over');+ } finally {+ fs.readFileSync = original;+ cleanupTestWorkspace(workspaceDir);+ }+});++test('destructive gate: an approved build halts before any write when its list cannot be recorded', async () => {+ const { sdk } = mockSdk();+ const workspaceDir = makeTestWorkspace('record-write-fails');+ try {+ let ran = false;+ const r = await withFsFault('renameSync', (from, to) => isApprovalFile(String(to)), 'ENOSPC', () => buildModelApp(desk, { apply: true, env: 'https://x', retryDelayMs: 0, allowDestructive: true, workspaceDir }, {+ sdk, provisionSdk: sdk, discoverOpDiffState: async () => ticketState(['new_name', 'new_priority'], ticketDef()), runBuild: async () => { ran = true; return { ok: true }; },+ }));+ assert.strictEqual(r.ok, false);+ assert.strictEqual(ran, false, 'nothing runs unbound');+ assert.ok(r.errors.some((e) => /could not record what this run may remove/.test(e) && /ENOSPC/.test(e)), JSON.stringify(r.errors));+ } finally {+ cleanupTestWorkspace(workspaceDir);+ }+});+test('destructive gate: --allow-destructive lets the same build proceed', async () => {const { sdk, calls } = mockSdk();const def = Object.assign(formOf(['new_name']), { __explicitLayout: true, __primaryField: 'new_name' });@@ -404,6 +941,27 @@ test('safety gate: --allow-destructive lets a build proceed even when discoveryassert.ok(calls.some((c) => c[0] === 'createSolution'), 'proceeded into the build');});+test('safety gate: an existing approval record plus discovery failure halts even with --allow-destructive', async () => {+ const { sdk } = mockSdk();+ const workspaceDir = makeTestWorkspace('record-discovery-failure');+ try {+ writeApprovalRecord(workspaceDir, { schemaVersion: 1, generatedAt: '2026-01-01T00:00:00.000Z', formRemovals: { 'form-1': { label: 'form "Ticket" (new_ticket)', fields: ['new_priority'] } }, sitemapRemovals: [] });+ let ran = false;+ const r = await buildModelApp(desk, { apply: true, env: 'https://x', retryDelayMs: 0, allowDestructive: true, workspaceDir }, {+ sdk,+ provisionSdk: sdk,+ discoverOpDiffState: async () => { throw new Error('429 transient'); },+ runBuild: async () => { ran = true; return { ok: true }; },+ });+ assert.strictEqual(r.ok, false);+ assert.strictEqual(ran, false, 'halted before runBuild');+ assert.ok(r.errors.some((e) => /cannot be compared with the approved list|live removals/i.test(e)));+ assert.deepStrictEqual(readApprovalRecord(workspaceDir).formRemovals['form-1'].fields, ['new_priority']);+ } finally {+ cleanupTestWorkspace(workspaceDir);+ }+});+test('collision preflight: warns and journals when the app already exists', async () => {const { sdk } = mockSdk();sdk.queryRecords = async (set) => (set === 'appmodule' ? [{ appmoduleid: 'app-x' }] : set === 'solution' ? [] : [{ publisherid: 'pub-1' }]);@@ -422,6 +980,24 @@ test('collision preflight: silent when nothing collides', async () => {assert.ok(!logs.some((l) => /already exist/.test(l)), 'no false-positive collision warning');});+test('discoverOpDiffState skips deployed form reads when prune:false means nothing can be removed', async () => {+ const provision = {+ queryRecords: async (set) => (set === 'solution' || set === 'appmodule' ? [] : [{ publisherid: 'pub-1' }]),+ findArtifact: async () => { throw new Error('should not resolve a prune:false form'); },+ fetchArtifact: async () => { throw new Error('should not fetch a prune:false form'); },+ getArtifact: async () => { throw new Error('should not read a prune:false form'); },+ };+ const spec = {+ solution: { uniqueName: 'S', publisherPrefix: 'new' },+ app: { name: 'A' },+ entities: [{ schemaName: 'new_ticket', primaryAttribute: { schemaName: 'new_name' }, columns: [] }],+ forms: [{ entity: 'new_ticket', name: 'Ticket', layout: 'explicit', prune: false, tabs: [{ sections: [{ fields: ['new_name'] }] }] }],+ appShell: { areas: [] },+ };+ const state = await discoverOpDiffState(spec, provision);+ assert.deepStrictEqual(state.forms, []);+});+test('discoverOpDiffState resolves an explicit-layout form by (entity, name, TYPE) — no name-ambiguity halt on same-named Main/QuickView/Card', async () => {// The reported bug: a table with same-named Main + Quick View + Card forms made the name-only lookup// match multiple rows → AmbiguousArtifactError → the preflight halted. The type-scoped query mustdiff --git a/plugins/model-apps/scripts/tests/business-rules.test.js b/plugins/model-apps/scripts/tests/business-rules.test.jsindex 4ece2cdad..64db74a09 100644--- a/plugins/model-apps/scripts/tests/business-rules.test.js+++ b/plugins/model-apps/scripts/tests/business-rules.test.js@@ -203,12 +203,18 @@ test('REAL BUNDLE: the mapped rule reaches the wire as WfomJson naming the authoassert.match(wfom, /new_ticket/, 'the rule is bound to the authored table');});-test('REAL BUNDLE: a valueless operator emits an EMPTY operand list and the IsNull/NotNull opcode', async () => {+test('REAL BUNDLE: a valueless operator emits a unary condition with the IsNull/NotNull opcode', async () => {// A presence operator has nothing to compare against, so the SDK must emit NO right-hand operand// and the dedicated opcode — not `Equals` against an empty string, which is a different question// and would silently answer false for a populated column.//// Measured opcodes (WorkflowConditionOperator in the bundle): NotNull "1", IsNull "0".+ //+ // The SDK used to emit these as a BinaryExpression with an EMPTY `right` list. The platform's+ // BinaryExpression rejects a unary operator ("Operator in a binary expression must be a binary+ // operator"), so the vendored SDK now emits the UnaryExpression the platform's own designer does:+ // {"__class":"UnaryExpression:#Microsoft.Crm.Workflow.Expressions","conditionOperatoroperator":"1",+ // "operand":{"__class":"EntityAttributeExpression:#...","attributeName":"new_notes",...}}const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'br-null-'));dirs.push(dir);@@ -245,8 +251,9 @@ test('REAL BUNDLE: a valueless operator emits an EMPTY operand list and the IsNuconst expr = wfom.steps.list[0].steps.list[0].conditionExpression;assert.strictEqual(expr.conditionOperatoroperator, expectedOpcode,`${operator} must emit opcode ${expectedOpcode}, got ${expr.conditionOperatoroperator}`);- assert.deepStrictEqual(expr.right, [], `${operator} must carry NO right-hand operand`);- assert.strictEqual(expr.left.attributeName, 'new_notes');+ assert.match(String(expr.__class), /^UnaryExpression:/, `${operator} must be a unary condition`);+ assert.strictEqual(expr.right, undefined, `${operator} must carry NO right-hand operand`);+ assert.strictEqual(expr.operand.attributeName, 'new_notes');}});diff --git a/plugins/model-apps/scripts/tests/check-auth.test.js b/plugins/model-apps/scripts/tests/check-auth.test.jsindex 4efb09093..c8f02640f 100644--- a/plugins/model-apps/scripts/tests/check-auth.test.js+++ b/plugins/model-apps/scripts/tests/check-auth.test.js@@ -119,35 +119,123 @@ const { loadCli } = require('./helpers/cli-harness.js');const ENVURL = 'https://contoso.crm.dynamics.com';// runQuiet() shells out via execFileSync and treats a throw as "absent". These stubs therefore-// model each CLI as either returning stdout or throwing, exactly as a missing binary would.-function makeExec({ azVersion = 'azure-cli 2.60.0', azUser = '[email protected]', pacOrg = null }) {+// model each CLI as either returning stdout or throwing, exactly as a missing binary would — and a+// missing binary fails EVERY invocation, not only `--version`. Each call is recorded in order.+function makeExec({ azVersion = 'azure-cli 2.60.0', azUser = '[email protected]' }, calls) {return (cmd, args) => {const argv = (args || []).join(' ');- if (cmd === 'az' && argv.includes('--version')) {- if (azVersion === null) throw new Error('spawn az ENOENT');- return azVersion;- }+ calls.push(`${cmd} ${argv}`);+ if (cmd === 'az' && azVersion === null) throw new Error('spawn az ENOENT');+ if (cmd === 'az' && argv.includes('--version')) return azVersion;if (cmd === 'az' && argv.includes('account show')) {if (azUser === null) throw new Error('Please run az login');return azUser;}- if (cmd === 'pac' && argv.includes('org who')) {- if (pacOrg === null) throw new Error('spawn pac ENOENT');- return pacOrg;- }throw new Error(`unexpected command: ${cmd} ${argv}`);};}+// `pac org who` runs through the async execFile so its cold start overlaps the az probes. The+// callback is deferred with setImmediate, like a real child that exits while the synchronous az+// calls hold the event loop.+function makeExecFile({ pacOrg = null, azUser = '[email protected]', azVersion = 'azure-cli 2.60.0' }, calls) {+ return (cmd, args, _opts, cb) => {+ const argv = (args || []).join(' ');+ if (cmd === 'az' && argv.includes('account show')) {+ calls.push(`az ${argv}`);+ process.nextTick(() => {+ if (azVersion === null) cb(new Error('spawn az ENOENT'), '', '');+ else if (azUser === null) cb(new Error('Please run az login'), '', '');+ else cb(null, azUser, '');+ });+ return { stdin: { end() {} }, kill() {} };+ }+ if (cmd === 'az' && argv.includes('--version')) {+ calls.push(`az ${argv}`);+ process.nextTick(() => {+ if (azVersion === null) cb(new Error('spawn az ENOENT'), '', '');+ else cb(null, azVersion, '');+ });+ return { stdin: { end() {} }, kill() {} };+ }+ calls.push(`start ${cmd} ${argv}`);+ setTimeout(() => {+ calls.push(`done ${cmd}`);+ if (cmd !== 'pac' || pacOrg === null) cb(new Error(`spawn ${cmd} ENOENT`), '', '');+ else cb(null, pacOrg, '');+ }, 0);+ return { stdin: { end() {} }, kill() { calls.push(`kill ${cmd} ${argv}`); } };+ };+}++function makeCancelableExecFile({ pacOrg = null, azUser = '[email protected]', azVersion = 'azure-cli 2.60.0', pacTimer = false, pacDelayMs = null }, calls) {+ return (cmd, args, _opts, cb) => {+ const argv = (args || []).join(' ');+ calls.push(`start ${cmd} ${argv}`);+ const child = {+ killed: false,+ stdin: { end() {} },+ kill() { this.killed = true; calls.push(`kill ${cmd} ${argv}`); },+ };+ if (cmd === 'pac') {+ let settled = false;+ const finish = (fn) => {+ if (settled || child.killed) return;+ settled = true;+ fn();+ };+ if (pacTimer) {+ setTimeout(() => finish(() => {+ calls.push(`timeout ${cmd}`);+ cb(new Error('pac timed out'), '', '');+ }), 5);+ }+ const finishSuccess = () => finish(() => {+ calls.push(`done ${cmd}`);+ if (pacOrg === null) cb(new Error(`spawn ${cmd} ENOENT`), '', '');+ else cb(null, pacOrg, '');+ });+ if (pacDelayMs !== null) setTimeout(finishSuccess, pacDelayMs);+ else setImmediate(finishSuccess);+ return child;+ }+ setImmediate(() => {+ if (child.killed) return;+ calls.push(`done ${cmd}`);+ if (cmd === 'az' && argv.includes('--version')) {+ if (azVersion === null) cb(new Error('spawn az ENOENT'), '', '');+ else cb(null, azVersion, '');+ } else if (cmd === 'az' && argv.includes('account show')) {+ if (azUser === null) cb(new Error('Please run az login'), '', '');+ else cb(null, azUser, '');+ } else {+ cb(new Error(`unexpected command: ${cmd} ${argv}`), '', '');+ }+ });+ return child;+ };+}+async function run({ argv = [], exec = {}, whoAmI, whoAmIThrows }) {+ const calls = [];const cli = loadCli(scriptPath, {argv,requires: {- 'child_process': { execFileSync: makeExec(exec) },+ // check-auth starts every CLI through the process runner; its execFileAsync keeps execFile's shape.+ './lib/process-runner': { execFileAsync: makeExecFile(exec, calls), runSync: makeExec(exec, calls) },'./lib/dataverse-auth': {parseArgs: require('../lib/dataverse-auth.js').parseArgs,validateFlags: require('../lib/dataverse-auth.js').validateFlags,+ getAuthToken: (url) => {+ calls.push(`token ${url}`);+ return 'token-value';+ },+ getAuthTokenAsync: async (url) => {+ calls.push(`token ${url}`);+ return 'token-value';+ },dataverseRequest: async () => {+ calls.push('whoami');if (whoAmIThrows) throw new Error(whoAmIThrows);return whoAmI || { status: 200, data: { UserId: 'u-1', OrganizationId: 'o-1' } };},@@ -160,20 +248,117 @@ async function run({ argv = [], exec = {}, whoAmI, whoAmIThrows }) {} catch (e) {if (e.exitCode === undefined) throw e;}- return JSON.parse(cli.stdoutText());++ const result = JSON.parse(cli.stdoutText());+ // Non-enumerable, so assertions on the emitted payload never see it.+ Object.defineProperty(result, 'calls', { value: calls });+ return result;+}++async function runWithAsyncChildren({ argv = [], exec = {}, token, whoAmI } = {}) {+ const calls = [];+ const cli = loadCli(scriptPath, {+ argv,+ requires: {+ './lib/process-runner': {+ runSync: () => { throw new Error('sync child processes must not be used by check-auth'); },+ execFileAsync: makeCancelableExecFile(exec, calls),+ },+ './lib/dataverse-auth': {+ parseArgs: require('../lib/dataverse-auth.js').parseArgs,+ validateFlags: require('../lib/dataverse-auth.js').validateFlags,+ getAuthToken: () => { throw new Error('sync token acquisition must not be used by check-auth'); },+ getAuthTokenAsync: async (url) => {+ calls.push(`token ${url}`);+ return typeof token === 'function' ? token(calls) : 'token-value';+ },+ dataverseRequest: async () => {+ calls.push('whoami');+ return whoAmI || { status: 200, data: { UserId: 'u-1', OrganizationId: 'o-1' } };+ },+ },+ },+ });+ try {+ await cli.main();+ } catch (e) {+ if (e.exitCode === undefined) throw e;+ }+ const result = JSON.parse(cli.stdoutText());+ Object.defineProperty(result, 'calls', { value: calls });+ return result;}-test('a missing az CLI blocks with az_missing before anything else is probed', async () => {+test('a missing az CLI blocks with az_missing, and no token or WhoAmI is attempted', async () => {const r = await run({ argv: ['--env', ENVURL], exec: { azVersion: null } });assert.equal(r.ok, false);assert.equal(r.blocker, 'az_missing');assert.match(r.message, /aka\.ms\/azure-cli/);+ assert.ok(!r.calls.some((c) => c.startsWith('token ') || c === 'whoami'), r.calls.join(' | '));});test('az installed but logged out blocks with az_not_logged_in', async () => {const r = await run({ argv: ['--env', ENVURL], exec: { azUser: null } });assert.equal(r.blocker, 'az_not_logged_in');assert.match(r.message, /az login/);+ // `az --version` is what tells "logged out" apart from "not installed".+ assert.ok(r.calls.includes('az --version'), r.calls.join(' | '));+});++test('a working az login costs ONE az call before WhoAmI: `az --version` only classifies a failure', async () => {+ const r = await run({ argv: ['--env', ENVURL], exec: { pacOrg: 'Connected as [email protected]\n' } });+ assert.equal(r.ok, true);+ assert.deepEqual(r.calls.filter((c) => c.startsWith('az ')), ['az account show --query user.name -o tsv']);+});++test('pac org who starts before the az probes, and the WhoAmI token is warmed while it runs', async () => {+ // Measured cold starts on Windows: pac org who ~7 s, each az call ~3-5 s. Run one after another the+ // preflight cost ~19 s at the start of every run; overlapped it costs about the slower branch.+ const r = await run({ argv: ['--env', ENVURL], exec: { pacOrg: 'Connected as [email protected]\n' } });+ assert.equal(r.ok, true);+ assert.deepEqual(r.calls, [+ 'start pac org who',+ 'az account show --query user.name -o tsv',+ `token ${ENVURL}`,+ 'done pac',+ 'whoami',+ ]);+});++test('pac success is delivered even when async az/token work takes longer than pac timeout', async () => {+ const r = await runWithAsyncChildren({+ argv: ['--env', ENVURL, '--require-pac'],+ exec: { pacOrg: 'Connected as [email protected]\n', pacTimer: true },+ token: () => new Promise((resolve) => setTimeout(() => resolve('token-value'), 20)),+ });+ assert.equal(r.ok, true);+ assert.equal(r.pacUser, '[email protected]');+ assert.notEqual(r.blocker, 'pac_not_logged_in');+});++test('az_missing cancels the pending pac probe before emitting', async () => {+ const r = await runWithAsyncChildren({+ argv: ['--env', ENVURL],+ exec: { azUser: null, azVersion: null, pacOrg: 'Connected as [email protected]\n', pacDelayMs: 50 },+ });+ assert.equal(r.blocker, 'az_missing');+ assert.ok(r.calls.indexOf('kill pac org who') !== -1, r.calls.join(' | '));+ assert.ok(!r.calls.includes('done pac'), r.calls.join(' | '));+});++test('az_not_logged_in cancels the pending pac probe before emitting', async () => {+ const r = await runWithAsyncChildren({+ argv: ['--env', ENVURL],+ exec: { azUser: null, azVersion: 'azure-cli 2.60.0', pacOrg: 'Connected as [email protected]\n', pacDelayMs: 50 },+ });+ assert.equal(r.blocker, 'az_not_logged_in');+ assert.ok(r.calls.includes('kill pac org who'), r.calls.join(' | '));+});++test('without --env the token is not warmed early, because the env URL comes from pac', async () => {+ const r = await run({ exec: { pacOrg: `Connected as [email protected]\nOrg URL: ${ENVURL}/\n` } });+ assert.equal(r.ok, true);+ assert.ok(!r.calls.some((c) => c.startsWith('token ')), r.calls.join(' | '));});test('a missing pac login is a WARNING for the app-builder path, not a blocker', async () => {diff --git a/plugins/model-apps/scripts/tests/check-version.test.js b/plugins/model-apps/scripts/tests/check-version.test.jsindex bdb2c9cdf..b13646f7b 100644--- a/plugins/model-apps/scripts/tests/check-version.test.js+++ b/plugins/model-apps/scripts/tests/check-version.test.js@@ -3,6 +3,7 @@ const assert = require('node:assert/strict');const fs = require('node:fs');const os = require('node:os');const path = require('node:path');+const { execFileSync, spawnSync } = require('node:child_process');const {compareSemver,@@ -83,3 +84,112 @@ test('readMarketplaceName returns null when no marketplace exists', () => {const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'model-apps-version-'));assert.equal(readMarketplaceName(tempDir), null);});++// End-to-end: the skills run `node "${PLUGIN_ROOT}/scripts/check-version.js"` from the USER's project+// directory, so every git call must be anchored to the plugin, never to process.cwd().+const SCRIPT = path.join(__dirname, '..', 'check-version.js');+// check-version.js starts git through the plugin's process runner, so a copied plugin needs it too.+const copyRunner = (pluginDir) => {+ fs.mkdirSync(path.join(pluginDir, 'scripts', 'lib'), { recursive: true });+ fs.copyFileSync(path.join(__dirname, '..', 'lib', 'process-runner.js'), path.join(pluginDir, 'scripts', 'lib', 'process-runner.js'));+};++function git(cwd, ...args) {+ return execFileSync('git', ['-c', '[email protected]', '-c', 'user.name=test', ...args], {+ cwd,+ encoding: 'utf8',+ stdio: ['ignore', 'pipe', 'pipe'],+ });+}++// On Windows, spell a folder with its 8.3 short name when it has one (C:\Users\RUNNER~1\...). The+// GitHub Windows runner's temp directory is spelled that way while git reports the long name, which is+// how the version check once pointed outside its own repository; spelling it short here reproduces that+// on any Windows machine, not only on the runner.+function shortPathOnWindows(p) {+ if (process.platform !== 'win32') return p;+ // A shell string, not an argv array: Node would escape the inner quotes and cmd would read them+ // literally, so `for` would echo a mangled path instead of the short name.+ const r = spawnSync(`for %I in ("${p}") do @echo %~sI`, { shell: true, encoding: 'utf8' });+ const out = String(r.stdout || '').trim();+ return out && fs.existsSync(out) ? out : p;+}++function writePluginManifest(pluginDir, version) {+ fs.mkdirSync(path.join(pluginDir, '.plugin'), { recursive: true });+ fs.writeFileSync(path.join(pluginDir, '.plugin', 'plugin.json'), JSON.stringify({ name: 'model-apps', version }));+}++// A user project that is a git repo with its own origin: the script must never fetch it.+function makeUserProject(tmp) {+ git(tmp, 'init', '-q', '--bare', 'user-origin.git');+ git(tmp, 'init', '-q', '-b', 'main', 'project');+ const project = path.join(tmp, 'project');+ git(project, 'commit', '-q', '--allow-empty', '-m', 'init');+ git(project, 'remote', 'add', 'origin', path.join(tmp, 'user-origin.git'));+ git(project, 'push', '-q', 'origin', 'main');+ fs.rmSync(path.join(project, '.git', 'FETCH_HEAD'), { force: true });+ return project;+}++function runScript(scriptPath, cwd) {+ return execFileSync(process.execPath, [scriptPath], {+ cwd,+ encoding: 'utf8',+ env: { ...process.env, COPILOT_CLI: '1' },+ stdio: ['ignore', 'pipe', 'pipe'],+ });+}++test('check-version compares against the PLUGIN clone, not the git repo it is run from', () => {+ const tmp = shortPathOnWindows(fs.mkdtempSync(path.join(os.tmpdir(), 'check-version-e2e-')));+ try {+ // The plugin's own repository: origin/main publishes 1.1.0 after this clone was taken at 1.0.0.+ git(tmp, 'init', '-q', '--bare', 'origin.git');+ git(tmp, 'init', '-q', '-b', 'main', 'seed');+ const seed = path.join(tmp, 'seed');+ fs.writeFileSync(path.join(seed, 'marketplace.json'), JSON.stringify({ name: 'test-market' }));+ const seedPlugin = path.join(seed, 'plugins', 'model-apps');+ writePluginManifest(seedPlugin, '1.0.0');+ fs.mkdirSync(path.join(seedPlugin, 'scripts'), { recursive: true });+ fs.copyFileSync(SCRIPT, path.join(seedPlugin, 'scripts', 'check-version.js'));+ copyRunner(seedPlugin);+ git(seed, 'add', '-A');+ git(seed, 'commit', '-q', '-m', 'v1.0.0');+ git(seed, 'remote', 'add', 'origin', path.join(tmp, 'origin.git'));+ git(seed, 'push', '-q', 'origin', 'main');+ git(tmp, 'clone', '-q', '-b', 'main', path.join(tmp, 'origin.git'), 'clone');+ writePluginManifest(seedPlugin, '1.1.0');+ git(seed, 'commit', '-q', '-am', 'v1.1.0');+ git(seed, 'push', '-q', 'origin', 'main');++ const project = makeUserProject(tmp);+ const out = runScript(path.join(tmp, 'clone', 'plugins', 'model-apps', 'scripts', 'check-version.js'), project);++ assert.match(out, /Plugin update available: model-apps 1\.0\.0 -> 1\.1\.0\./);+ assert.match(out, /copilot plugin marketplace update test-market/);+ assert.equal(fs.existsSync(path.join(project, '.git', 'FETCH_HEAD')), false, 'the user project must not be fetched');+ } finally {+ fs.rmSync(tmp, { recursive: true, force: true });+ }+});++test('check-version exits silently, touching no repository, when the plugin is not a git clone', () => {+ // Marketplace installs are plain copies of the plugin directory, not clones.+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'check-version-copy-'));+ try {+ const plugin = path.join(tmp, 'installed', 'model-apps');+ writePluginManifest(plugin, '1.0.0');+ fs.mkdirSync(path.join(plugin, 'scripts'), { recursive: true });+ fs.copyFileSync(SCRIPT, path.join(plugin, 'scripts', 'check-version.js'));+ copyRunner(plugin);+ const project = makeUserProject(tmp);++ const out = runScript(path.join(plugin, 'scripts', 'check-version.js'), project);++ assert.equal(out, '');+ assert.equal(fs.existsSync(path.join(project, '.git', 'FETCH_HEAD')), false, 'the user project must not be fetched');+ } finally {+ fs.rmSync(tmp, { recursive: true, force: true });+ }+});diff --git a/plugins/model-apps/scripts/tests/create-connection-reference.test.js b/plugins/model-apps/scripts/tests/create-connection-reference.test.jsindex 1a148ad85..188a689e6 100644--- a/plugins/model-apps/scripts/tests/create-connection-reference.test.js+++ b/plugins/model-apps/scripts/tests/create-connection-reference.test.js@@ -23,15 +23,6 @@ test('missing args exits 1 with usage', () => {assert.match(res.stderr, /Usage:/);});-test('the rollback switch still works end to end (exit 3 before any Dataverse call)', () => {- const res = spawnSync(- process.execPath,- [scriptPath, 'https://contoso.crm.dynamics.com', 'new_x', '/providers/Microsoft.PowerApps/apis/shared_x'],- { encoding: 'utf8', env: { ...process.env, GENPAGE_ENABLE_CONNECTORS: '0' } }- );- assert.equal(res.status, 3);- assert.match(res.stderr, /disabled/i);-});// --- Wire-level contract ----------------------------------------------------diff --git a/plugins/model-apps/scripts/tests/dataverse-auth.test.js b/plugins/model-apps/scripts/tests/dataverse-auth.test.jsindex 386d6bc9b..48a8d6f67 100644--- a/plugins/model-apps/scripts/tests/dataverse-auth.test.js+++ b/plugins/model-apps/scripts/tests/dataverse-auth.test.js@@ -1,6 +1,7 @@'use strict';const { test } = require('node:test');const assert = require('node:assert/strict');+const http = require('node:http');const { parseArgs, readJsonArg, label, requiredLevel } = require('../lib/dataverse-auth');@@ -92,6 +93,140 @@ test('requiredLevel: respects argument', () => {assert.equal(requiredLevel('ApplicationRequired').Value, 'ApplicationRequired');});+test('makeRequest preserves UTF-8 characters split across response chunks', async () => {+ const { makeRequest } = require('../lib/dataverse-auth.js');+ const body = JSON.stringify({ city: '東京', emoji: '😀', cafe: 'Café' });+ const bodyBytes = Buffer.from(body, 'utf8');+ const server = http.createServer((req, res) => {+ res.setHeader('Content-Type', 'application/json; charset=utf-8');+ if (req.url === '/split') {+ for (let i = 0; i < bodyBytes.length; i += 1) {+ res.write(bodyBytes.subarray(i, i + 1));+ }+ res.end();+ return;+ }+ if (req.url === '/whole') {+ res.end(bodyBytes);+ return;+ }+ res.statusCode = 404;+ res.end('not found');+ });+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));+ const { port } = server.address();+ try {+ const whole = await makeRequest({ url: `http://127.0.0.1:${port}/whole` });+ const split = await makeRequest({ url: `http://127.0.0.1:${port}/split` });+ assert.equal(whole.body, body);+ assert.equal(split.body, body);+ } finally {+ await new Promise((resolve) => server.close(resolve));+ }+});++test('getAuthToken reuses a non-empty token per normalized resource URL', () => {+ const { getAuthToken } = require('../lib/dataverse-auth.js');+ const calls = [];+ const exec = (_file, args) => {+ calls.push(args[args.indexOf('--resource') + 1]);+ return 'TOK\n';+ };+ const oldPath = process.env.PATH;+ process.env.PATH = '';+ try {+ assert.equal(getAuthToken('https://contoso.crm.dynamics.com/', { exec, fresh: true }), 'TOK');+ assert.equal(getAuthToken('https://contoso.crm.dynamics.com', { exec }), 'TOK');+ assert.equal(getAuthToken('https://fabrikam.crm.dynamics.com', { exec, fresh: true }), 'TOK');+ } finally {+ process.env.PATH = oldPath;+ }+ assert.deepEqual(calls, ['https://contoso.crm.dynamics.com', 'https://fabrikam.crm.dynamics.com']);+});++test('a fresh acquire bypasses the memo and replaces the token it holds', () => {+ const { getAuthToken } = require('../lib/dataverse-auth.js');+ const tokens = ['OLD\n', 'NEW\n'];+ let calls = 0;+ const exec = () => tokens[Math.min(calls++, tokens.length - 1)];+ const url = 'https://fabrikam.crm4.dynamics.com';+ const oldPath = process.env.PATH;+ process.env.PATH = '';+ try {+ assert.equal(getAuthToken(url, { exec, fresh: true }), 'OLD');+ assert.equal(getAuthToken(url, { exec }), 'OLD', 'an ordinary repeat is served from the memo');+ // A 401 refresh must not be handed the token the server just rejected.+ assert.equal(getAuthToken(url, { exec, fresh: true }), 'NEW');+ assert.equal(getAuthToken(url, { exec }), 'NEW', 'the refreshed token replaces the memoized one');+ } finally {+ process.env.PATH = oldPath;+ }+ assert.equal(calls, 2);+});+test('getAuthToken does not cache a null token result', () => {+ const { getAuthToken } = require('../lib/dataverse-auth.js');+ let calls = 0;+ const exec = () => {+ calls += 1;+ if (calls === 1) return '\n';+ return 'TOK\n';+ };+ const oldPath = process.env.PATH;+ process.env.PATH = '';+ try {+ assert.equal(getAuthToken('https://example.crm.dynamics.com', { exec, fresh: true }), null);+ assert.equal(getAuthToken('https://example.crm.dynamics.com', { exec }), 'TOK');+ } finally {+ process.env.PATH = oldPath;+ }+ assert.equal(calls, 2);+});++test('getAuthTokenAsync is served from a memo that getAuthToken filled', async () => {+ // The other direction of sharing: check-auth warms the memo asynchronously, but a synchronous caller+ // may have filled it first, and the async path must then not start the CLI again.+ const { getAuthToken, getAuthTokenAsync } = require('../lib/dataverse-auth.js');+ let asyncCalls = 0;+ const exec = () => 'SYNC\n';+ const execFile = (_file, _args, _opts, cb) => { asyncCalls += 1; setImmediate(() => cb(null, 'ASYNC\n')); };+ const url = 'https://fabrikam.crm5.dynamics.com';+ const oldPath = process.env.PATH;+ process.env.PATH = '';+ try {+ assert.equal(getAuthToken(url, { exec, fresh: true }), 'SYNC');+ assert.equal(await getAuthTokenAsync(url, { execFile }), 'SYNC');+ } finally {+ process.env.PATH = oldPath;+ }+ assert.equal(asyncCalls, 0);+});+test('getAuthTokenAsync shares the token memo with getAuthToken and honors fresh replacement', async () => {+ const { getAuthToken, getAuthTokenAsync } = require('../lib/dataverse-auth.js');+ const calls = [];+ const exec = (_file, args) => {+ calls.push(`sync:${args[args.indexOf('--resource') + 1]}`);+ return 'SYNC\n';+ };+ const execFile = (_file, args, _opts, cb) => {+ calls.push(`async:${args[args.indexOf('--resource') + 1]}`);+ setImmediate(() => cb(null, calls.length === 1 ? 'ASYNC\n' : 'FRESH\n'));+ };+ const oldPath = process.env.PATH;+ process.env.PATH = '';+ try {+ assert.equal(await getAuthTokenAsync('https://contoso.crm.dynamics.com/', { execFile, fresh: true }), 'ASYNC');+ assert.equal(getAuthToken('https://contoso.crm.dynamics.com', { exec }), 'ASYNC');+ assert.equal(await getAuthTokenAsync('https://contoso.crm.dynamics.com', { execFile, fresh: true }), 'FRESH');+ assert.equal(getAuthToken('https://contoso.crm.dynamics.com', { exec }), 'FRESH');+ } finally {+ process.env.PATH = oldPath;+ }+ assert.deepEqual(calls, [+ 'async:https://contoso.crm.dynamics.com',+ 'async:https://contoso.crm.dynamics.com',+ ]);+});+test('emitResult: partial-failure object writes JSON to stdout (not [object Object])', () => {// Spawn a tiny script that calls emitResult(false, {errors:[...]}) and// verify that stdout contains the JSON payload — not the literal string@@ -164,6 +299,28 @@ test('dataverseRequest USES a preset token and skips the CLI entirely', async ()assert.strictEqual(sentAuth, 'Bearer tok-from-cli');});++test('dataverseRequest bypasses the token memo after a 401 before retrying', async () => {+ const { dataverseRequest } = require('../lib/dataverse-auth.js');+ const tokenCalls = [];+ const sent = [];+ const res = await dataverseRequest('https://contoso.crm.dynamics.com', 'GET', 'WhoAmI', null, {+ getToken: (_url, options) => {+ tokenCalls.push(Boolean(options && options.fresh));+ return tokenCalls.length === 1 ? 'OLD' : 'NEW';+ },+ request: async ({ headers }) => {+ sent.push(headers.Authorization);+ return sent.length === 1+ ? { statusCode: 401, body: '' }+ : { statusCode: 200, body: '{"ok":true}' };+ },+ });+ assert.strictEqual(res.status, 200);+ assert.deepStrictEqual(tokenCalls, [false, true]);+ assert.deepStrictEqual(sent, ['Bearer OLD', 'Bearer NEW']);+});+test('a path-bearing or query-bearing env is refused, not silently trimmed to its origin', async () => {// `dataverseRequest` appends `/api/data/...` to whatever it is given, so a trimmed// `https://org.crm.dynamics.com/some/path` would probe `.../some/path/api/data/...` and report a@@ -456,3 +613,125 @@ test('AB#6686424: a bodyless error does not print "null" as the server message',);}});++// --- environment URLs: only a Dataverse https origin is ever used -------------------------------+// The origin is the `--resource` a token is requested for, the base of every request URL, and the+// only place a token is sent. Anything else is refused before a process starts or a request is sent.+test('dataverseOrigin accepts a Dataverse origin in any cloud and returns it canonically', () => {+ const { dataverseOrigin } = require('../lib/dataverse-auth.js');+ for (const [input, expected] of [+ ['https://contoso.crm.dynamics.com', 'https://contoso.crm.dynamics.com'],+ ['https://Contoso.CRM.Dynamics.com/', 'https://contoso.crm.dynamics.com'],+ [' https://contoso.crm4.dynamics.com// ', 'https://contoso.crm4.dynamics.com'],+ ['HTTPS://contoso.api.crm.dynamics.com', 'https://contoso.api.crm.dynamics.com'],+ ['https://contoso.crmtest.dynamics.com', 'https://contoso.crmtest.dynamics.com'],+ ['https://contoso.crm.microsoftdynamics.us', 'https://contoso.crm.microsoftdynamics.us'],+ ['https://contoso.crm.appsplatform.us', 'https://contoso.crm.appsplatform.us'],+ ['https://contoso.crm.dynamics.cn', 'https://contoso.crm.dynamics.cn'],+ ]) {+ assert.equal(dataverseOrigin(input), expected, input);+ }+});++test('dataverseOrigin refuses anything that is not exactly an https Dataverse origin', () => {+ const { dataverseOrigin } = require('../lib/dataverse-auth.js');+ for (const input of [+ 'http://contoso.crm.dynamics.com',+ 'https://contoso.crm.dynamics.com/main.aspx',+ 'https://contoso.crm.dynamics.com/?x=1',+ 'https://contoso.crm.dynamics.com/#x',+ 'https://contoso.crm.dynamics.com:443',+ 'https://[email protected]',+ 'https://contoso.crm.dynamics.com/&whoami',+ 'https://contoso.crm.dynamics.com&whoami',+ 'https://contoso.crm.dynamics.com\\x',+ 'https://contoso.crm.dynamics.com%20',+ 'https://contoso.crm.dynamics.com\nx',+ 'https://contoso.example.com',+ 'https://crm.dynamics.com',+ 'https://contoso.crm.dynamics.com.example.com',+ '',+ null,+ undefined,+ ]) {+ assert.equal(dataverseOrigin(input), null, JSON.stringify(input));+ }+});++test('a non-origin environment URL starts no Azure CLI process and sends no request', async () => {+ const { getAuthToken, getAuthTokenAsync, dataverseRequest } = require('../lib/dataverse-auth.js');+ let started = 0;+ const exec = () => { started += 1; return 'TOK\n'; };+ const execFile = (_f, _a, _o, cb) => { started += 1; cb(null, 'TOK\n'); };+ const bad = 'https://contoso.crm.dynamics.com/&whoami';+ assert.equal(getAuthToken(bad, { exec, fresh: true }), null);+ assert.equal(await getAuthTokenAsync(bad, { execFile, fresh: true }), null);+ let sent = 0;+ await assert.rejects(+ dataverseRequest(bad, 'GET', 'WhoAmI', null, { getToken: exec, request: async () => { sent += 1; return { statusCode: 200, body: '{}' }; } }),+ /is not a Dataverse environment URL/+ );+ assert.equal(started, 0);+ assert.equal(sent, 0);+});++test('dataverseRequest builds the request on the validated origin and requests the token for it', async () => {+ const { dataverseRequest } = require('../lib/dataverse-auth.js');+ let resource;+ let url;+ await dataverseRequest('https://Contoso.crm.dynamics.com/', 'GET', 'WhoAmI', null, {+ getToken: (r) => { resource = r; return 'TOK'; },+ request: async (o) => { url = o.url; return { statusCode: 200, body: '{}' }; },+ });+ assert.equal(resource, 'https://contoso.crm.dynamics.com');+ assert.equal(url, 'https://contoso.crm.dynamics.com/api/data/v9.2/WhoAmI');+});++test('createAzHttpClient requests its token for the validated origin, never the text it was given', async () => {+ const { createAzHttpClient } = require('../lib/sdk-http-client.js');+ assert.throws(() => createAzHttpClient('https://contoso.crm.dynamics.com/&whoami', { getToken: () => 'TOK' }), /Invalid Dataverse org URL/);+ let resource;+ const http = createAzHttpClient('https://CONTOSO.crm.dynamics.com/', {+ getToken: (r) => { resource = r; return 'TOK'; },+ request: async () => ({ statusCode: 200, body: '{}' }),+ });+ await http.get('https://contoso.crm.dynamics.com/api/data/v9.2/WhoAmI');+ assert.equal(resource, 'https://contoso.crm.dynamics.com');+});++test('azIdentity reads the identity through the process runner seam', () => {+ const { azIdentity } = require('../lib/dataverse-auth.js');+ const seen = [];+ const id = azIdentity({ exec: (cmd, args) => { seen.push([cmd, ...args].join(' ')); return '{"user":"[email protected]","tenantId":"t"}'; } });+ assert.deepEqual(id, { user: '[email protected]', tenantId: 't' });+ assert.deepEqual(seen, ['az account show --query {user:user.name,tenantId:tenantId} -o json']);+});++// End to end on Windows, where the Azure CLI is a batch shim: the entry-point CLIs refuse an+// environment URL that is not an origin, and nothing but the (fake) Azure CLI ever runs.+test('the Dataverse entry points refuse a non-origin URL before anything runs (real CLI, Windows)', { skip: process.platform !== 'win32' }, () => {+ const { spawnSync } = require('node:child_process');+ const fs = require('node:fs');+ const os = require('node:os');+ const path = require('node:path');+ const scripts = path.join(__dirname, '..');+ const work = fs.mkdtempSync(path.join(os.tmpdir(), 'dv-origin-e2e-'));+ try {+ const bin = path.join(work, 'bin');+ fs.mkdirSync(bin);+ const azLog = path.join(work, 'az-calls.txt');+ fs.writeFileSync(path.join(bin, 'az.cmd'), `@echo %*>>"${azLog}"\r\n@exit /b 1\r\n`, 'utf8');+ const env = { ...process.env, Path: `${bin};${process.env.SystemRoot}\\System32`, PATH: `${bin};${process.env.SystemRoot}\\System32` };+ const url = 'https://contoso.crm.dynamics.com/&md,MARKER';+ const runs = [+ spawnSync(process.execPath, [path.join(scripts, 'dataverse-request.js'), url, 'GET', 'WhoAmI'], { cwd: work, env, encoding: 'utf8', timeout: 60000 }),+ spawnSync(process.execPath, [path.join(scripts, 'check-auth.js'), '--env', url], { cwd: work, env, encoding: 'utf8', timeout: 60000 }),+ ];+ assert.equal(fs.existsSync(path.join(work, 'MARKER')), false, 'no second command ran');+ assert.match(runs[0].stderr, /is not a Dataverse environment URL/);+ const logged = fs.existsSync(azLog) ? fs.readFileSync(azLog, 'utf8') : '';+ assert.doesNotMatch(logged, /MARKER/, `the URL never reached the Azure CLI: ${logged}`);+ } finally {+ fs.rmSync(work, { recursive: true, force: true });+ }+});\ No newline at end of filediff --git a/plugins/model-apps/scripts/tests/download-model-app.test.js b/plugins/model-apps/scripts/tests/download-model-app.test.jsindex fe058d685..b33406345 100644--- a/plugins/model-apps/scripts/tests/download-model-app.test.js+++ b/plugins/model-apps/scripts/tests/download-model-app.test.js@@ -1025,11 +1025,11 @@ test('the global-choice inventory is scoped to the app: its solution\'s sets andconst failed = await readDescriptionInventory(sdkFor({ throwOnSolution: true }), 'app-1', 'ContosoSolution', new Set(['contoso_bound']));assert.deepStrictEqual((failed.incomplete || []).filter((i) => /403/.test(i.reason)).map((i) => i.kind).sort(), ['businessRules', 'globalChoices']);- // A FULL page of owned sets is indistinguishable from a truncated one: say so, and keep what was read.- const full = Array.from({ length: 1000 }, (_, i) => (i === 0 ? OWNED : `e5e5e5e5-0000-4000-8000-${String(i).padStart(12, '0')}`));- const truncated = await readDescriptionInventory(sdkFor({ owned: full }), 'app-1', 'ContosoSolution', new Set());- assert.deepStrictEqual(names(truncated), ['contoso_owned']);- assert.match((unknown(truncated)[0] || {}).reason || '', /truncated/);+ // The solution-component read is paginated, not capped, so a large solution-owned option-set+ // list is read completely instead of being reported as an unknowable full page.+ const seen = [];+ const paged = await readDescriptionInventory(sdkFor({ gets: seen }), 'app-1', 'ContosoSolution', new Set());+ assert.deepStrictEqual(unknown(paged), [], 'a paginated read should not report a truncation warning');});// An app in several solutions (#587 item 9) is inventoried across EVERY candidate — each contains the@@ -3055,8 +3055,8 @@ test('a page with NO prompt.txt omits prompt entirely, rather than claiming an eassert.strictEqual(byId.get('11111111-1111-1111-1111-111111111111').prompt, undefined,'a missing prompt.txt is an OMISSION — the wrapper default applies, the build must not refuse');- assert.strictEqual(byId.get('22222222-2222-2222-2222-222222222222').prompt, '',- 'a present-but-blank file stays explicit so the blank-provenance guard still fails closed');+ assert.strictEqual(byId.get('22222222-2222-2222-2222-222222222222').prompt, ' \n',+ 'a present-but-blank file stays explicit, including its whitespace, so the blank-provenance guard still fails closed');assert.strictEqual(byId.get('33333333-3333-3333-3333-333333333333').prompt, 'real prompt');// The emitted spec must not carry the key at all for the omitted case — `undefined` is dropped by@@ -3087,3 +3087,96 @@ test('a config that exists but cannot be READ is recorded unreadable, not treatefs.rmSync(root, { recursive: true, force: true });});+++// --- Task D: downloaded page config and prompt must be exact and fail closed ----------------------++test('parseDownloadedPages treats present malformed dataSources as unreadable config, while absent means unbound', () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'dlds-shapes-'));+ try {+ const mk = (id, config) => {+ const d = path.join(root, id);+ fs.mkdirSync(d, { recursive: true });+ fs.writeFileSync(path.join(d, 'page.tsx'), 'export default () => null;', 'utf8');+ if (config !== undefined) fs.writeFileSync(path.join(d, 'config.json'), JSON.stringify(config), 'utf8');+ };+ mk('11111111-1111-1111-1111-111111111111', { dataSources: 'contoso_ticket' });+ mk('22222222-2222-2222-2222-222222222222', { dataSources: null });+ mk('33333333-3333-3333-3333-333333333333', { dataSources: ['contoso_ticket', 18] });+ mk('44444444-4444-4444-4444-444444444444', { dataSources: ['contoso_ticket', 'contoso_asset'] });+ mk('55555555-5555-5555-5555-555555555555', { model: 'm' });++ const unreadable = [];+ const pages = parseDownloadedPages(root, root, null, unreadable);+ const byId = new Map(pages.map((p) => [p.pageId, p]));+ assert.deepStrictEqual(unreadable.map((u) => u.pageId).sort(), [+ '11111111-1111-1111-1111-111111111111',+ '22222222-2222-2222-2222-222222222222',+ '33333333-3333-3333-3333-333333333333',+ ]);+ // The reason is shown to the maker, so it must name the problem rather than a JavaScript error+ // such as "config.dataSources.find is not a function".+ const reason = (id) => unreadable.find((u) => u.pageId === id).reason;+ assert.match(reason('11111111-1111-1111-1111-111111111111'), /dataSources is present but is not an array/);+ assert.match(reason('22222222-2222-2222-2222-222222222222'), /dataSources is present but is not an array/);+ assert.match(reason('33333333-3333-3333-3333-333333333333'), /non-empty table logical names/);+ assert.deepStrictEqual(byId.get('44444444-4444-4444-4444-444444444444').dataSources, ['contoso_ticket', 'contoso_asset']);+ assert.deepStrictEqual(byId.get('55555555-5555-5555-5555-555555555555').dataSources, [], 'an absent key is a valid unbound page');+ } finally {+ fs.rmSync(root, { recursive: true, force: true });+ }+});++test('parseDownloadedPages keeps downloaded prompt text exact except for a leading BOM', () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'dlprompt-exact-'));+ try {+ const mk = (id, prompt) => {+ const d = path.join(root, id);+ fs.mkdirSync(d, { recursive: true });+ fs.writeFileSync(path.join(d, 'page.tsx'), 'export default () => null;', 'utf8');+ fs.writeFileSync(path.join(d, 'config.json'), JSON.stringify({ dataSources: [] }), 'utf8');+ fs.writeFileSync(path.join(d, 'prompt.txt'), prompt, 'utf8');+ };+ const exact = ' Conversation with 1 prompts:\r\n1. Keep surrounding whitespace.\r\n';+ mk('11111111-1111-1111-1111-111111111111', exact);+ mk('22222222-2222-2222-2222-222222222222', '\uFEFF' + exact);++ const pages = parseDownloadedPages(root, root, null, []);+ const byId = new Map(pages.map((p) => [p.pageId, p]));+ assert.strictEqual(byId.get('11111111-1111-1111-1111-111111111111').prompt, exact);+ assert.strictEqual(byId.get('22222222-2222-2222-2222-222222222222').prompt, exact, 'only the BOM is stripped');+ } finally {+ fs.rmSync(root, { recursive: true, force: true });+ }+});++test('complete reads use SDK pagination where truncation would change download decisions', async () => {+ const calls = [];+ const sdk = {+ queryRecords: async (set, opts) => {+ calls.push({ set, opts });+ if (set === 'appmodule') return [{ appmoduleidunique: 'app-unique' }];+ if (set === 'appmodulecomponent') return [];+ if (set === 'solution') return [{ solutionid: 'sol-1' }];+ if (set === 'solutioncomponent') return [];+ return [];+ },+ dataverse: { get: async () => ({ status: 200, body: { value: [] } }) },+ };++ await appComponentEntities(sdk, 'app-1');+ await readDescriptionInventory(sdk, 'app-1', 'ContosoSolution', new Set());++ const appComponentReads = calls.filter((c) => c.set === 'appmodulecomponent');+ assert.ok(appComponentReads.length >= 4, 'component reads should be exercised');+ for (const call of appComponentReads) {+ assert.strictEqual(call.opts.paginate, true, `${call.opts.filter} must paginate`);+ assert.strictEqual(call.opts.top, undefined, `${call.opts.filter} must not cap with top`);+ }+ const solutionComponentReads = calls.filter((c) => c.set === 'solutioncomponent');+ assert.ok(solutionComponentReads.length >= 1, 'solution component reads should be exercised');+ for (const call of solutionComponentReads) {+ assert.strictEqual(call.opts.paginate, true, `${call.opts.filter} must paginate`);+ assert.strictEqual(call.opts.top, undefined, `${call.opts.filter} must not cap with top`);+ }+});diff --git a/plugins/model-apps/scripts/tests/feature-flags.test.js b/plugins/model-apps/scripts/tests/feature-flags.test.jsindex 934438a45..15e9ef8a6 100644--- a/plugins/model-apps/scripts/tests/feature-flags.test.js+++ b/plugins/model-apps/scripts/tests/feature-flags.test.js@@ -8,13 +8,10 @@ const { spawnSync } = require('node:child_process');const libPath = path.join(__dirname, '..', 'lib', 'feature-flags.js');const {isEnabled,- isConnectorsEnabled,isCustomApiEnabled,- connectorsDisabledMessage,customApiDisabledMessage,envVarName,parseBool,- exitIfConnectorsDisabled,exitIfCustomApiDisabled,describe,validateFlags,@@ -24,21 +21,19 @@ const {// --- Default OFF (fail-closed) ----------------------------------------------test('connectors is GA and ships ON, with the rollback switch still working', () => {- // connectors was flipped to true rather than removed, so the gate survives one release as a- // rollback path. Pin BOTH halves: shipping ON (a regression to false silently disables a GA- // feature for every user) and still gate-able (if the switch stopped working there would be no- // way back short of a revert, which is the whole reason the flag was kept).+test('connectors flag is retired and unknown fail-closed', () => {const json = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'feature-flags.json'), 'utf8'));- assert.equal(json.connectors, true, 'feature-flags.json must ship connectors: true');- assert.equal(isConnectorsEnabled({ env: {} }), true);- assert.equal(FLAGS.connectors.status, 'ga');- // The rollback path: an env override must still be able to turn it off.- assert.equal(isEnabled('connectors', { env: { GENPAGE_ENABLE_CONNECTORS: '0' } }), false);+ assert.equal(Object.prototype.hasOwnProperty.call(json, 'connectors'), false);+ assert.equal(KNOWN_FLAGS.includes('connectors'), false);+ assert.equal(isEnabled('connectors', { env: { GENPAGE_ENABLE_CONNECTORS: '1' } }), false);+ assert.match(validateFlags({ connectors: true })[0], /unknown flag/i);+ const lib = require(libPath);+ for (const removed of ['isConnectorsEnabled', 'exitIfConnectorsDisabled', 'connectorsDisabledMessage']) {+ assert.equal(lib[removed], undefined, `${removed} must stay removed now that connectors have no flag`);+ }});-test('custom-api flag is OFF by default (no env override)', () => {// Same fail-closed contract every gated feature relies on: an empty env falls through to the// committed feature-flags.json, which ships custom-api:false until the runtime stack is GA in PROD.@@ -110,20 +105,6 @@ test('customApiDisabledMessage explains how to enable', () => {// --- Committed config actually ships OFF -------------------------------------test('the retired connectors flag is gone from every surface', () => {- // Intentionally inverted from its original form: connectors is GA but the gate was KEPT for one- // release as a rollback switch, so the flag, its helpers and its catalog entry must all still- // exist. When the follow-up change removes them, flip these assertions back.- assert.ok(KNOWN_FLAGS.includes('connectors'), 'connectors stays in the catalog until the gate is removed');- const lib = require(libPath);- for (const present of ['isConnectorsEnabled', 'exitIfConnectorsDisabled', 'connectorsDisabledMessage']) {- assert.equal(typeof lib[present], 'function', `${present} must still be exported while the gate exists`);- }- // And it must NOT be an unknown key — a leftover value the validator rejects would mean the- // committed file and the catalog had drifted apart.- assert.deepEqual(validateFlags({ connectors: true }), []);-});-test('committed feature-flags.json ships custom-api: false', () => {const json = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'feature-flags.json'), 'utf8')@@ -164,35 +145,7 @@ test('CLI without a flag name exits 2 with usage', () => {assert.match(res.stderr, /Usage:/);});-// --- exitIfConnectorsDisabled / exitIfCustomApiDisabled (DRY gate helpers) ----test('exitIfConnectorsDisabled exits 3 and writes the message when OFF', () => {- let exitCode = null;- let written = '';- exitIfConnectorsDisabled({- env: { GENPAGE_ENABLE_CONNECTORS: '0' },- exit: (c) => { exitCode = c; },- write: (s) => { written += s; },- });- assert.equal(exitCode, 3);- assert.match(written, /disabled/i);-});--test('exitIfConnectorsDisabled is a no-op in the shipped (ON) configuration', () => {- let exitCalled = false;- exitIfConnectorsDisabled({- env: {},- exit: () => { exitCalled = true; },- write: () => {},- });- assert.equal(exitCalled, false, 'connectors ships ON, so the gate must not fire by default');-});--test('connectorsDisabledMessage explains that it was explicitly turned off', () => {- const m = connectorsDisabledMessage();- assert.match(m, /GENPAGE_ENABLE_CONNECTORS/);- assert.match(m, /feature-flags\.json/);-});+// --- exitIfCustomApiDisabled (DRY gate helper) -------------------------------test('exitIfCustomApiDisabled exits 3 and writes the message when OFF', () => {let exitCode = null;diff --git a/plugins/model-apps/scripts/tests/form-occupancy.test.js b/plugins/model-apps/scripts/tests/form-occupancy.test.jsnew file mode 100644index 000000000..8205bb37c--- /dev/null+++ b/plugins/model-apps/scripts/tests/form-occupancy.test.js@@ -0,0 +1,65 @@+'use strict';+const test = require('node:test');+const assert = require('node:assert');+const { rowOccupancy, fitsGrid, strandedRows } = require('../lib/form-occupancy.js');++test('rowOccupancy carries row-spanning reservations into later rows', () => {+ const rows = [+ { cells: [{ control: { fieldName: 'new_a' }, rowspan: 3, colspan: 2 }, { control: { fieldName: 'new_b' } }] },+ { cells: [{ control: { fieldName: 'new_c' } }] },+ { cells: [{ id: 'maker-spacer' }, { control: { fieldName: 'new_d' }, colspan: 2 }] },+ { cells: [{ control: { fieldName: 'new_e' } }] },+ ];++ assert.deepStrictEqual(rowOccupancy(rows), [+ { own: 3, reserved: 0, used: 3 },+ { own: 1, reserved: 2, used: 3 },+ { own: 3, reserved: 2, used: 5 },+ { own: 1, reserved: 0, used: 1 },+ ]);+});++test('fitsGrid counts spacers and carried reservations', () => {+ const rows = [+ { cells: [{ control: { fieldName: 'new_a' }, rowspan: 2 }] },+ { cells: [{ id: 'maker-spacer' }, { control: { fieldName: 'new_b' } }] },+ ];++ assert.strictEqual(fitsGrid(rows, 2), false);+ assert.strictEqual(fitsGrid(rows, 3), true);+});++// The rows a departing cell leaves holding nothing. `rows` is the section AFTER the cell left.+const f = (n, extra = {}) => ({ control: { fieldName: `new_${n}` }, ...extra });++test('strandedRows: the row a cell left empty, when nothing above reserves it', () => {+ // before: [a, b] / [c] / [d] after d left: [a, b] / [c] / []+ assert.deepStrictEqual(strandedRows([{ cells: [f('a'), f('b')] }, { cells: [f('c')] }, { cells: [] }], 2, 1), [2]);+});++test('strandedRows: an emptied row that a span above still reserves is kept', () => {+ // [a rs2] / [] / [b, c]: row 2 holds a's reserved slot. Deleting it would pull [b, c] up beside a.+ assert.deepStrictEqual(strandedRows([{ cells: [f('a', { rowspan: 2 })] }, { cells: [] }, { cells: [f('b'), f('c')] }], 1, 1), []);+});++test('strandedRows: a departing span also frees the rows it covered, listed bottom-up', () => {+ // before: [a, b] / [d rs2] / [] after d left: [a, b] / [] / []+ assert.deepStrictEqual(strandedRows([{ cells: [f('a'), f('b')] }, { cells: [] }, { cells: [] }], 1, 2), [2, 1]);+});++test('strandedRows: a covered row that still holds a cell is kept', () => {+ assert.deepStrictEqual(strandedRows([{ cells: [f('a')] }, { cells: [] }, { cells: [f('c')] }], 1, 2), [1]);+});++test('strandedRows: an empty row outside the departing cell\'s rows is never touched', () => {+ // [a, b] / [] / [] where row 1 was ALREADY empty and the cell left row 2.+ assert.deepStrictEqual(strandedRows([{ cells: [f('a'), f('b')] }, { cells: [] }, { cells: [] }], 2, 1), [2]);+ // ...and below it: the cell left row 1 of [a] / [] / [] / [c], where row 2 was already empty.+ assert.deepStrictEqual(strandedRows([{ cells: [f('a')] }, { cells: [] }, { cells: [] }, { cells: [f('c')] }], 1, 1), [1]);+});++test('strandedRows: indexes past the end and a missing span are safe', () => {+ assert.deepStrictEqual(strandedRows([{ cells: [f('a')] }], 5, 1), []);+ assert.deepStrictEqual(strandedRows([{ cells: [] }], 0, undefined), [0]);+ assert.deepStrictEqual(strandedRows([{ cells: [] }], 0, 4), [0], 'a span running past the last row is clamped');+});diff --git a/plugins/model-apps/scripts/tests/genpage-cli.test.js b/plugins/model-apps/scripts/tests/genpage-cli.test.jsindex 1c79eac15..abb9e7f13 100644--- a/plugins/model-apps/scripts/tests/genpage-cli.test.js+++ b/plugins/model-apps/scripts/tests/genpage-cli.test.js@@ -1,9 +1,23 @@'use strict';const { test } = require('node:test');const assert = require('node:assert');-const { makeGenpageCli, parsePageId, parseList, quoteArg, buildPacInvocation, classifyListOutput, parseListCount } = require('../lib/genpage-cli.js');+const { spawnSync } = require('node:child_process');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const { makeGenpageCli, parsePageId, parseList, buildPacInvocation, classifyListOutput, parseListCount, runPac } = require('../lib/genpage-cli.js');const GUID = '6e0c28a2-cdbf-41ec-9186-d10fd5de6e35';+// Scratch goes in the OS temp dir, never beside this file. Tests that walk scripts/ (the await scan in+// sdk-async-surface.test.js) list every .js file first and read each one seconds later, so a scratch+// directory this file deletes in between failed them with ENOENT.+const scratchDirs = [];+const scratch = (prefix) => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));+ scratchDirs.push(dir);+ return dir;+};+test.after(() => { for (const d of scratchDirs) fs.rmSync(d, { recursive: true, force: true }); });// REAL `pac model genpage list` output — a fixed-width TABLE (header + GUID/Name/Published rows), captured// LIVE from a Dataverse test environment (2026-07). Columns auto-size to the longest name. `listText` reproduces@@ -35,46 +49,156 @@ function envList(rows) {return `Connected as [email protected]\nRetrieving generated pages...\nFound ${count} generated page(s):\n\n${header}\n${body}\n`;}-test('quoteArg quotes args with spaces/specials, leaves plain args', () => {- assert.strictEqual(quoteArg('Overview'), 'Overview');- assert.strictEqual(quoteArg('A responsive cards overview'), '"A responsive cards overview"');- assert.strictEqual(quoteArg('has"quote'), '"has""quote"');- assert.strictEqual(quoteArg('https://x'), 'https://x');+// A Windows machine where pac is either the dotnet-tool pac.exe or an MSI-style pac.cmd shim.+// The fake pac.cmd forwards %* like an MSI install's shim, without turning delayed expansion on.+const winPac = (file) => ({ platform: 'win32', env: { Path: 'C:\\pac', PATHEXT: '.EXE;.CMD', SystemRoot: 'C:\\Windows' }, exists: (p) => p === file, readFile: () => '@"%~dp0tools\\pac.exe" %*\r\n' });+const PAC_EXE = winPac('C:\\pac\\pac.exe');+const PAC_CMD = winPac('C:\\pac\\pac.cmd');++// A listing row whose GUID runs straight into more identifier text is not a page id followed by a+// name. The row parser used an ASCII `\b`, which JavaScript places before `東`, so `<guid>東京` was+// read as a valid id and a count-matched listing was accepted as authoritative.+test('parseList skips a row whose GUID runs into more identifier text, and the listing fails closed', () => {+ for (const suffix of ['東京', 'é', '_x', '-x']) {+ const out = listText([{ pageId: GUID + suffix, name: 'Overview' }]);+ assert.deepStrictEqual(parseList(out), [], `a row starting ${JSON.stringify(GUID + suffix)} is not a page`);+ assert.strictEqual(classifyListOutput(out).kind, 'unrecognized', `suffix ${JSON.stringify(suffix)} must fail closed`);+ }+ const mixed = listText([{ pageId: GUID, name: 'Overview' }, { pageId: GP_A + '東京', name: 'Detail' }]);+ assert.strictEqual(classifyListOutput(mixed).kind, 'unrecognized', 'one bad row makes the whole listing untrustworthy');+ // Control: the same listing with a clean id is authoritative, so the refusals above are about the suffix.+ assert.deepStrictEqual(classifyListOutput(listText([{ pageId: GUID, name: 'Overview' }])),+ { kind: 'pages', pages: [{ pageId: GUID, name: 'Overview' }] });+});+test('buildPacInvocation starts pac.exe directly with every argument unchanged, and no shell', () => {+ const inv = buildPacInvocation(['model', 'genpage', 'upload', '--name', 'a "quote" & 50%!'], PAC_EXE);+ assert.strictEqual(inv.file, 'C:\\pac\\pac.exe');+ assert.deepStrictEqual(inv.args, ['model', 'genpage', 'upload', '--name', 'a "quote" & 50%!']);+ assert.strictEqual(inv.options.shell, false);+});++test('buildPacInvocation runs a pac.cmd shim through cmd.exe and refuses what cmd.exe would reinterpret', () => {+ const inv = buildPacInvocation(['model', 'genpage', 'list', '--name', 'Order Detail'], PAC_CMD);+ assert.strictEqual(inv.file, 'C:\\Windows\\System32\\cmd.exe');+ assert.strictEqual(inv.args[4], '""C:\\pac\\pac.cmd" model genpage list --name "Order Detail""');+ assert.strictEqual(inv.options.windowsVerbatimArguments, true);+ for (const name of ['50% off', 'a "quote"']) {+ assert.throws(() => buildPacInvocation(['--name', name], PAC_CMD), (e) => e.code === 'EARGUMENT', name);+ }+ assert.ok(buildPacInvocation(['--name', 'Hello!'], PAC_CMD).args[4].endsWith('--name "Hello!""'), '! is literal with delayed expansion off');});-test('quoteArg collapses newlines to spaces (a multi-line prompt must not break the command line)', () => {- assert.strictEqual(quoteArg('Conversation with 2 prompts:\r\n1. A\r\n2. B'), '"Conversation with 2 prompts: 1. A 2. B"');- assert.strictEqual(quoteArg('line1\nline2'), '"line1 line2"');- assert.ok(!quoteArg('a\r\nb').includes('\n'), 'no raw newline survives into the command line');+test('buildPacInvocation (posix) spawns pac directly with an args array and no shell', () => {+ const posix = { platform: 'linux', env: { PATH: '/usr/bin' }, exists: (p) => p === '/usr/bin/pac' };+ const inv = buildPacInvocation(['model', 'genpage', 'upload', '--prompt', 'a "quote" & more'], posix);+ assert.strictEqual(inv.file, '/usr/bin/pac');+ assert.strictEqual(inv.options.shell, false, 'no shell on POSIX so metacharacters round-trip verbatim');+ assert.deepStrictEqual(inv.args, ['model', 'genpage', 'upload', '--prompt', 'a "quote" & more']);});-test('quoteArg caret-escapes % so cmd.exe does not expand %VAR% inside the quoted arg (Windows)', () => {- // cmd.exe expands %VAR% even inside double quotes; breaking out of the quotes and caret-escaping each- // % (verified to round-trip literally through cmd.exe) keeps prompts/names with env-var syntax intact.- assert.strictEqual(quoteArg('plain%PATH%end'), '"plain"^%"PATH"^%"end"');- assert.ok(quoteArg('50% off').includes('"^%"'), 'a bare % triggers quoting + escaping');-});+test('buildPacInvocation collapses embedded newlines in args (every platform and pac form)', () => {+ const posix = buildPacInvocation(['--prompt', 'l1\r\nl2\nl3'], { platform: 'linux', env: { PATH: '/b' }, exists: () => true });+ assert.deepStrictEqual(posix.args, ['--prompt', 'l1 l2 l3'], 'multi-line prompt collapsed to spaces');+ const win = buildPacInvocation(['--prompt', 'l1\r\nl2'], PAC_CMD);+ assert.ok(!win.args[4].includes('\n'), 'no raw newline survives into a batch shim command line');+});+// Put a directory first on PATH for the duration of `fn`, so `pac` resolves to whatever it holds.+async function withPathFirst(dir, fn, { only = false } = {}) {+ const saved = process.env.PATH;+ process.env.PATH = only ? dir : dir + path.delimiter + saved;+ try { return await fn(); } finally { process.env.PATH = saved; }+}-test('buildPacInvocation (win32) builds a shell command line with cmd-style quoting', () => {- const inv = buildPacInvocation(['model', 'genpage', 'upload', '--prompt', 'a "quote"'], 'win32');- assert.strictEqual(inv.options.shell, true);- assert.strictEqual(inv.args, undefined);- assert.ok(inv.command.startsWith('pac '));- assert.ok(inv.command.includes('"a ""quote"""'), 'embedded quotes are cmd-escaped by doubling');-});+// A fake `pac` to put first on PATH: `pac.cmd` on Windows, reached through cmd.exe exactly as the+// real one is, and an executable script elsewhere. By default it writes a multibyte character in two+// pieces 200 ms apart, then its argv, then an error, and exits 3. With `--big` it writes 1.5 MiB.+// With `--late` it starts a process that shares its stdout and writes 300 ms after the fake exits.+const BIG_OUTPUT_BYTES = 1536 * 1024;+function makeFakePac() {+ const dir = scratch('genpage-cli-fakepac-');+ const script = path.join(dir, 'fake-pac.js');+ fs.writeFileSync(script, [+ `if (process.argv.includes('--big')) process.stdout.write('x'.repeat(${BIG_OUTPUT_BYTES}));`,+ "else if (process.argv.includes('--late')) {",+ " require('child_process').spawn(process.execPath, ['-e', \"setTimeout(() => process.stdout.write('late'), 300)\"],",+ " { stdio: ['ignore', 'inherit', 'inherit'], detached: true, windowsHide: true }).unref();",+ " process.stdout.write('early ');",+ '} else {',+ " const bytes = Buffer.from('東京', 'utf8');",+ ' process.stdout.write(bytes.subarray(0, 1));',+ ' setTimeout(() => {',+ " process.stdout.write(Buffer.concat([bytes.subarray(1), Buffer.from(' ' + JSON.stringify(process.argv.slice(2)) + '\\n', 'utf8')]));",+ " process.stderr.write('Error: fake failure\\n');",+ ' process.exitCode = 3;',+ ' }, 200);',+ '}',+ '',+ ].join('\n'), 'utf8');+ if (process.platform === 'win32') {+ fs.writeFileSync(path.join(dir, 'pac.cmd'), `@"${process.execPath}" "${script}" %*\r\n`, 'utf8');+ } else {+ fs.writeFileSync(path.join(dir, 'pac'), `#!/bin/sh\nexec "${process.execPath}" "${script}" "$@"\n`, { mode: 0o755 });+ }+ return dir;+}-test('buildPacInvocation (posix) spawns pac directly with an args array and no shell', () => {- const inv = buildPacInvocation(['model', 'genpage', 'upload', '--prompt', 'a "quote" & more'], 'linux');- assert.strictEqual(inv.command, 'pac');- assert.strictEqual(inv.options.shell, undefined, 'no shell on POSIX so metacharacters round-trip verbatim');- assert.deepStrictEqual(inv.args, ['model', 'genpage', 'upload', '--prompt', 'a "quote" & more']);+// The default runner must YIELD while pac runs. genpage-upload.js overlaps an update's two+// listings, which saves nothing if every pac call freezes the process the way spawnSync did. The+// fake's split character catches a runner that decodes each chunk as it arrives.+test('runPac lets the event loop run while pac runs, and decodes output split mid-character', async () => {+ const dir = makeFakePac();+ const args = ['model', 'genpage', 'list', '--name', 'Order Detail'];+ let ticks = 0;+ const timer = setInterval(() => { ticks += 1; }, 10);+ try {+ const r = await withPathFirst(dir, () => runPac(args));+ assert.strictEqual(r.status, 3, 'the exit code is passed through');+ assert.strictEqual(r.stdout, `東京 ${JSON.stringify(args)}\n`, 'the split character arrives whole, and the args intact');+ assert.match(r.stderr, /Error: fake failure/);+ assert.ok(ticks > 0, 'timers fired while pac was running, so the process was not blocked');+ } finally {+ clearInterval(timer);+ }});-test('buildPacInvocation collapses embedded newlines in args (both platforms)', () => {- const posix = buildPacInvocation(['--prompt', 'l1\r\nl2\nl3'], 'linux');- assert.deepStrictEqual(posix.args, ['--prompt', 'l1 l2 l3'], 'multi-line prompt collapsed to spaces');- const win = buildPacInvocation(['--prompt', 'l1\r\nl2'], 'win32');- assert.ok(!win.command.includes('\n'), 'no raw newline survives into the Windows command line');+// spawnSync capped output at 1 MiB (its maxBuffer): past that it killed pac and returned a+// truncated listing as a failure. The runner keeps everything, and reads each pipe to its end before+// settling — pac can exit while the tail of a large write is still unread in the pipe.+test('runPac keeps output past 1 MiB, read to the end of the pipe', async () => {+ const dir = makeFakePac();+ const r = await withPathFirst(dir, () => runPac(['model', 'genpage', 'list', '--big']));+ assert.strictEqual(r.status, 0, r.stderr);+ assert.strictEqual(r.stdout.length, BIG_OUTPUT_BYTES);+});++// Settling when pac EXITS would lose output a process it started writes afterwards. spawnSync+// returned only once the pipes closed, and so does the runner.+test('runPac settles when the pipes close, as spawnSync did, not when pac exits', async () => {+ const r = await withPathFirst(makeFakePac(), () => runPac(['model', 'genpage', 'list', '--late']));+ assert.strictEqual(r.stdout, 'early late');+ assert.strictEqual(r.status, 0, r.stderr);+});++// A pac that cannot be started must come back as an ordinary failed result — every caller branches+// on `status` and none of them catches. That is spawn's 'error' event (ENOENT), which spawnSync+// reported as status 1 with no text at all. On Windows pac runs through cmd.exe, which would print+// its own "not recognized" and exit, so the shell itself is made unstartable to reach that path.+test('runPac resolves with a non-zero status and the launch error when pac cannot be started', async () => {+ const empty = scratch('genpage-cli-nopac-');+ const savedComSpec = process.env.ComSpec;+ if (process.platform === 'win32') process.env.ComSpec = path.join(empty, 'no-such-shell.exe');+ let r;+ try {+ r = await withPathFirst(empty, () => runPac(['model', 'genpage', 'list']), { only: true });+ } finally {+ if (process.platform === 'win32') {+ if (savedComSpec === undefined) delete process.env.ComSpec;+ else process.env.ComSpec = savedComSpec;+ }+ }+ assert.notStrictEqual(r.status, 0);+ assert.strictEqual(r.stdout, '');+ assert.match(r.stderr, /ENOENT/, `the failure must say why; got ${JSON.stringify(r)}`);});test('parsePageId extracts the guid from upload output', () => {@@ -286,6 +410,9 @@ test('classifyListOutput: pages / empty / unrecognized (tri-state, COMPLETE-listassert.deepStrictEqual(classifyListOutput(LIST_EMPTY).pages, []);// recognized-empty: "no pages" phrase variant (observed in older pac builds)assert.strictEqual(classifyListOutput('No generated pages found.\n').kind, 'empty');+ assert.strictEqual(classifyListOutput(' No pages found \n').kind, 'empty', 'a standalone no-pages line is accepted');+ assert.strictEqual(classifyListOutput('Warning: no pages could be retrieved because the service is unavailable\n').kind, 'unrecognized', 'a warning sentence is not proof of an empty app');+ assert.strictEqual(classifyListOutput('Status: No generated pages found after retry\n').kind, 'unrecognized', 'the no-pages phrase must occupy the whole trimmed line');// unrecognized: blank output (not proof of empty — could be a timeout or help-dump with no banner)assert.strictEqual(classifyListOutput('').kind, 'unrecognized');// unrecognized: help/usage banner (pac dumps usage on a flag error but exits 0 on some builds)@@ -301,6 +428,16 @@ test('classifyListOutput: pages / empty / unrecognized (tri-state, COMPLETE-list// stdout (names + descriptions), so a page NAMED or DESCRIBED with "no page(s)" text must NOT force an app// WITH live pages to classify as EMPTY. A false 'empty' → reconcile sees zero live → duplicate CREATE on// build + silent page-drop on download. Empty requires NO positive page evidence.+test('classifyListOutput: repeated page ids make a matching-count listing unrecognized', () => {+ const duplicateId = listText([+ { pageId: GUID, name: 'Overview' },+ { pageId: GUID.toUpperCase(), name: 'Summary' },+ ], 2);+ const k = classifyListOutput(duplicateId);+ assert.strictEqual(k.kind, 'unrecognized', `duplicate page identity must fail closed; got ${JSON.stringify(k)}`);+ assert.deepStrictEqual(k.pages, [], 'duplicate identities are not an authoritative set of pages');+});+test('classifyListOutput: a page NAMED "no pages" does NOT force empty when real pages are listed', () => {// A page literally named "No Pages" with a valid 1-page summary → 'pages', not 'empty'. The "no pages"// phrase is tested against the whole stdout (which includes page NAMES), so it must not fire here.@@ -786,25 +923,24 @@ test('a trailing backslash is doubled so it cannot escape the closing quote', ()// `String.raw` cannot be used here: a template literal may not END with a backslash, because it// escapes the closing backtick. Ordinary escapes it is.const dir = 'C:\\Users\\Power User\\download\\';- const inv = buildPacInvocation(['model', 'genpage', 'download', '--output-directory', dir, '--app-id', 'after'], 'win32');+ const inv = buildPacInvocation(['model', 'genpage', 'download', '--output-directory', dir, '--app-id', 'after'], PAC_CMD);// The run before the closing quote is doubled; the following flag stays a separate argument.- assert.match(inv.command, /--output-directory "C:\\Users\\Power User\\download\\\\" --app-id after$/,- `the trailing separator must be escaped; got ${inv.command}`);+ assert.match(inv.args[4], /--output-directory "C:\\Users\\Power User\\download\\\\" --app-id after"$/,+ `the trailing separator must be escaped; got ${inv.args[4]}`);});test('interior backslashes are left alone (every Windows path has them)', () => {- const inv = buildPacInvocation(['model', 'genpage', 'download', '--output-directory', String.raw`C:\Users\Power User\download`], 'win32');- assert.match(inv.command, /"C:\\Users\\Power User\\download"/,- `an ordinary path must round-trip unchanged; got ${inv.command}`);+ const inv = buildPacInvocation(['model', 'genpage', 'download', '--output-directory', String.raw`C:\Users\Power User\download`], PAC_CMD);+ assert.match(inv.args[4], /"C:\\Users\\Power User\\download"/,+ `an ordinary path must round-trip unchanged; got ${inv.args[4]}`);});test('POSIX passes args verbatim, with no cmd-style quoting at all', () => {const dir = '/home/user/download\\';- const inv = buildPacInvocation(['model', 'genpage', 'download', '--output-directory', dir], 'linux');+ const inv = buildPacInvocation(['model', 'genpage', 'download', '--output-directory', dir], { platform: 'linux', env: { PATH: '/b' }, exists: () => true });assert.deepStrictEqual(inv.args, ['model', 'genpage', 'download', '--output-directory', dir],'the POSIX path spawns pac directly, so nothing may be rewritten');});-// --- review follow-up: a TRANSIENT message must NOT be mistaken for a deterministic one --------// The first version matched the bare phrases "does not exist" and "could not be found", so a// service message like "The resource does not exist yet; please retry." aborted the retry loop —@@ -892,6 +1028,8 @@ test('parsePageId refuses a GUID followed by any identifier character, not just`a token continuing with ${JSON.stringify(suffix)} must be refused, not trimmed to the GUID`);}// ...but punctuation genuinely ENDS the token — pac prints the id inside prose.+ assert.strictEqual(parsePageId(`Page ID: ${G}東京`), null,+ 'a Unicode letter continues the token and must not be silently dropped');for (const suffix of ['.', ',', ')', ' ', '\n']) {assert.strictEqual(parsePageId(`Page ID: ${G}${suffix}`), G,`${JSON.stringify(suffix)} terminates the id and must still parse`);@@ -985,3 +1123,17 @@ test('a deterministic-looking error on a CREATE that landed is still adopted andassert.ok(!uploads[0].includes('--page-id'), 'the first attempt was the create');assert.ok(uploads[1].includes('--page-id') && uploads[1].includes(GUID), 'the second attempt updated the adopted id');});+++test('enumeratePages can include unpublished app-scoped pages without changing the default enumerate call', async () => {+ const seen = [];+ const run = async (args) => { seen.push(args); return { status: 0, stdout: LIST_ONE, stderr: '' }; };+ const cli = makeGenpageCli('https://x', { run, sleep: async () => {} });+ await cli.enumerate({ appId: 'app-1' });+ await cli.enumeratePages('app-1', { includeUnpublished: true });++ assert.ok(seen[0].includes('--app-id') && seen[0].includes('app-1'), 'default enumerate stays app-scoped');+ assert.ok(!seen[0].includes('--include-unpublished'), 'default enumerate call is unchanged for existing callers');+ assert.ok(seen[1].includes('--app-id') && seen[1].includes('app-1'), 'option still combines with --app-id');+ assert.ok(seen[1].includes('--include-unpublished'), 'the requested option reaches pac argv');+});diff --git a/plugins/model-apps/scripts/tests/genpage-dispatch-contract.test.js b/plugins/model-apps/scripts/tests/genpage-dispatch-contract.test.jsindex 69d06fc0b..a77a538aa 100644--- a/plugins/model-apps/scripts/tests/genpage-dispatch-contract.test.js+++ b/plugins/model-apps/scripts/tests/genpage-dispatch-contract.test.js@@ -71,25 +71,31 @@ test('the orchestrator emits the exact token the page-builder triggers on', () =}});-test('the connectors rollback gate is documented where the scripts enforce it', () => {- // connectors is GA and ships ON, but the gate was kept for one release as a rollback switch.- // The scripts fail closed with exit 3 when it is off, so the prose has to tell an agent that- // path exists — otherwise a run that hits exit 3 looks like a crash rather than a switch.- //- // This assertion is the inverse of the one that stood here while the flag was being retired.- // When the follow-up change removes the gate, invert it again: assert NO prose references the- // flag, because a probe of a removed flag prints `disabled` (unknown flags are fail-closed) and- // would silently turn connector authoring back off.- const builder = readDoc(path.join(PLUGIN, 'agents', 'genpage-connector-builder.md'));- const skill = readDoc(path.join(PLUGIN, 'skills', 'genpage', 'SKILL.md'));- const probe = /feature-flags\.js"?\s+connectors\b/;- assert.match(builder, probe, 'the connector-builder owns the gate and must probe it');- assert.match(skill, probe, 'Phase 4.5 must re-probe the gate before deploying bindings');- // Both must describe the OFF outcome, or an agent has no defined behaviour for it.- assert.match(builder, /\bdisabled\b/, 'connector-builder must define the disabled path');- assert.match(skill, /\bdisabled\b/, 'Phase 4.5 must define the disabled path');+test('connector docs do not probe the retired feature flag', () => {+ const docs = [+ path.join(PLUGIN, 'agents', 'genpage-connector-builder.md'),+ path.join(PLUGIN, 'agents', 'genpage-planner.md'),+ path.join(PLUGIN, 'agents', 'genpage-edit-planner.md'),+ path.join(PLUGIN, 'skills', 'genpage', 'SKILL.md'),+ path.join(PLUGIN, 'skills', 'genpage', 'edit-flow.md'),+ path.join(PLUGIN, 'references', 'connectors.md'),+ ];+ for (const doc of docs) {+ const text = readDoc(doc);+ assert.doesNotMatch(text, /feature-flags\.js"?\s+connectors\b/, `${rel(doc)} must not probe the retired connectors flag`);+ assert.doesNotMatch(text, /GENPAGE_ENABLE_CONNECTORS/, `${rel(doc)} must not document the retired connectors env var`);+ // Prose that still describes a connectors "rollback gate" tells an agent to probe for it, and the+ // retired flag now always reports disabled, which would silently drop the page's connectors.+ // Matched in any word order: "the builder owns the rollback gate" slipped past a pattern that+ // required "connectors" before it.+ assert.doesNotMatch(text, /rollback\s+gate|connector\s+discovery\s+and\s+its\s+rollback\s+gate|probes\s+first,\s+writes\s+`No connector bindings/i,+ `${rel(doc)} must not describe a connectors rollback gate`);+ // Nor may it describe a connectors-off mode, or a connector builder that gates on a flag.+ assert.doesNotMatch(text, /connectors\s+(?:are|is)\s+(?:off|disabled)/i, `${rel(doc)} must not describe connectors being off`);+ assert.doesNotMatch(text, /genpage-connector-builder`?[\s\S]{0,40}?gated\s+on\s+the\s+flag/i,+ `${rel(doc)} must not say the connector builder gates on a flag`);+ }});-test('connector metadata discovery uses the PAC connector name, not the full API resource path', () => {const builder = readDoc(path.join(PLUGIN, 'agents', 'genpage-connector-builder.md'));assert.match(diff --git a/plugins/model-apps/scripts/tests/genpage-upload.test.js b/plugins/model-apps/scripts/tests/genpage-upload.test.jsindex c91e61b4b..fd978d7c9 100644--- a/plugins/model-apps/scripts/tests/genpage-upload.test.js+++ b/plugins/model-apps/scripts/tests/genpage-upload.test.js@@ -49,6 +49,7 @@ function capturingCli(opts = {}) {upload: async (o) => { calls.push(o); return { pageId: '13ecbc57-a3a4-4132-b0a2-a6c6b12691e8' }; },// Default: the requested page exists. Tests that care override this.enumerateEnvironment: async () => ({ ok: true, ids: ['9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d'] }),+ enumeratePages: async () => ({ ok: true, pages: [{ pageId: '9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d', name: 'Current Page' }] }),// An update reads the page's CURRENT bindings so omitting `--data-sources` preserves them// instead of persisting `[]`. pac writes this config UTF-8 with a BOM, so the fixture does too.download: async ({ outputDir, pageIds }) => {@@ -398,7 +399,7 @@ test('WINDOWS: the prompt never appears on the command line pac is invoked with'// Fragments must be unique to the PROMPT: `--name` is legitimately passed inline (a short,// caller-controlled value), and the first version of this test matched the quoted name instead// of the prompt — a test that would have failed on correct code.- const win = buildPacInvocation(args, 'win32');+ const win = { command: buildPacInvocation(args, { platform: 'win32', env: { Path: 'C:\\pac', PATHEXT: '.CMD', SystemRoot: 'C:\\Windows' }, exists: (p) => p === 'C:\\pac\\pac.cmd' }).args[4] };for (const fragment of ['résumé', '$(whoami)', '<b>bold</b>', '%PATH%', "apostrophe's"]) {assert.ok(!win.command.includes(fragment),`prompt fragment ${JSON.stringify(fragment)} leaked onto the command line:\n${win.command}`);@@ -695,6 +696,7 @@ test('--clear-data-sources really unbinds, and does not read the old list first'let probed = false;const factory = () => ({enumerateEnvironment: async () => ({ ok: true, ids: ['9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d'] }),+ enumeratePages: async () => ({ ok: true, pages: [{ pageId: '9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d', name: 'Current Page' }] }),download: async () => { probed = true; return true; },upload: async (o) => { probed = probed || false; return { pageId: o.pageId, _ds: o.dataSources }; },});@@ -718,6 +720,7 @@ test('an unreadable current binding list refuses the update rather than unbindinlet uploads = 0;const factory = () => ({enumerateEnvironment: async () => ({ ok: true, ids: ['9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d'] }),+ enumeratePages: async () => ({ ok: true, pages: [{ pageId: '9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d', name: 'Current Page' }] }),download: async () => true, // writes nothing — the config is then missingupload: async () => { uploads += 1; return { pageId: 'x' }; },});@@ -756,6 +759,7 @@ test('a page whose config has no dataSources key updates normally (it simply hasconst seen = [];const factory = () => ({enumerateEnvironment: async () => ({ ok: true, ids: ['9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d'] }),+ enumeratePages: async () => ({ ok: true, pages: [{ pageId: '9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d', name: 'Current Page' }] }),download: async ({ outputDir, pageIds }) => {for (const pid of (pageIds || [])) {fs.mkdirSync(path.join(outputDir, pid), { recursive: true });@@ -783,6 +787,7 @@ test('a config that is PRESENT but unparseable refuses the update', async () =>let uploads = 0;const factory = () => ({enumerateEnvironment: async () => ({ ok: true, ids: ['9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d'] }),+ enumeratePages: async () => ({ ok: true, pages: [{ pageId: '9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d', name: 'Current Page' }] }),download: async ({ outputDir, pageIds }) => {for (const pid of (pageIds || [])) {fs.mkdirSync(path.join(outputDir, pid), { recursive: true });@@ -815,6 +820,7 @@ test('the current bindings are found even when --page-id casing differs from pacconst seen = [];const factory = () => ({enumerateEnvironment: async () => ({ ok: true, ids: [canonical] }),+ enumeratePages: async () => ({ ok: true, pages: [{ pageId: canonical, name: 'Current Page' }] }),download: async ({ outputDir }) => {// pac writes the directory in ITS casing, not the caller's.fs.mkdirSync(path.join(outputDir, canonical), { recursive: true });@@ -854,6 +860,7 @@ test('--clear-data-sources combined with --data-sources is refused, not silentlylet uploads = 0;const factory = () => ({enumerateEnvironment: async () => ({ ok: true, ids: ['9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d'] }),+ enumeratePages: async () => ({ ok: true, pages: [{ pageId: '9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d', name: 'Current Page' }] }),upload: async () => { uploads += 1; return { pageId: 'x' }; },});const r = await new Promise((resolve) => {@@ -874,6 +881,7 @@ test('a dataSources value of the wrong type refuses the update, rather than unbilet uploads = 0;const factory = () => ({enumerateEnvironment: async () => ({ ok: true, ids: ['9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d'] }),+ enumeratePages: async () => ({ ok: true, pages: [{ pageId: '9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d', name: 'Current Page' }] }),download: async ({ outputDir, pageIds }) => {for (const pid of (pageIds || [])) {fs.mkdirSync(path.join(outputDir, pid), { recursive: true });@@ -902,6 +910,7 @@ test('the probe directory is removed even when the read fails', async () => {const probes = [];const factory = () => ({enumerateEnvironment: async () => ({ ok: true, ids: ['9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d'] }),+ enumeratePages: async () => ({ ok: true, pages: [{ pageId: '9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d', name: 'Current Page' }] }),download: async ({ outputDir }) => { probes.push(outputDir); return true; }, // writes no configupload: async () => ({ pageId: 'x' }),});@@ -985,3 +994,207 @@ test('a BOM is still stripped even though the rest of the file is passed through});assert.strictEqual(onDisk, 'keep this\n', 'the BOM goes, the trailing newline stays');});++// --- Task D: an update must target a page placed in the supplied app -----------------------------++test('an update refuses a page that exists but is not in the supplied app navigation, without probing or uploading', async () => {+ let downloads = 0;+ let uploads = 0;+ const factory = () => ({+ enumerateEnvironment: async () => ({ ok: true, ids: ['9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d'] }),+ enumeratePages: async () => ({ ok: true, pages: [{ pageId: 'aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa', name: 'Other Page' }] }),+ download: async () => { downloads += 1; return true; },+ upload: async () => { uploads += 1; return { pageId: 'x' }; },+ });+ const r = await new Promise((resolve) => {+ main(['--env', 'https://contoso.crm.dynamics.com/', '--app-id', 'app-a', '--code-file', 'c.tsx',+ '--page-id', '9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d', '--prompt', 'p'],+ { makeGenpageCli: factory, emit: (ok, payload) => resolve({ ok, payload }) });+ });+ assert.strictEqual(r.ok, false);+ assert.match(r.payload.error, /page 9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d is not in app app-a's navigation/);+ assert.match(r.payload.error, /would rename it and attach its tables to that app/);+ assert.strictEqual(downloads, 0, 'membership refusal must happen before the data-source probe');+ assert.strictEqual(uploads, 0, 'membership refusal must happen before upload');+});++test('an update refuses an app that lists no generative pages, without probing or uploading', async () => {+ let downloads = 0;+ let uploads = 0;+ const factory = () => ({+ enumerateEnvironment: async () => ({ ok: true, ids: ['9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d'] }),+ enumeratePages: async () => ({ ok: true, pages: [], empty: true }),+ download: async () => { downloads += 1; return true; },+ upload: async () => { uploads += 1; return { pageId: 'x' }; },+ });+ const r = await new Promise((resolve) => {+ main(['--env', 'https://contoso.crm.dynamics.com/', '--app-id', 'missing-app', '--code-file', 'c.tsx',+ '--page-id', '9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d', '--prompt', 'p'],+ { makeGenpageCli: factory, emit: (ok, payload) => resolve({ ok, payload }) });+ });+ assert.strictEqual(r.ok, false);+ assert.match(r.payload.error, /app missing-app has no generative pages, or could not be found/);+ assert.strictEqual(downloads, 0);+ assert.strictEqual(uploads, 0);+});++test('an update refuses when the app-scoped page listing cannot be read', async () => {+ let downloads = 0;+ let uploads = 0;+ const factory = () => ({+ enumerateEnvironment: async () => ({ ok: true, ids: ['9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d'] }),+ enumeratePages: async () => ({ ok: false, error: 'pac list failed' }),+ download: async () => { downloads += 1; return true; },+ upload: async () => { uploads += 1; return { pageId: 'x' }; },+ });+ const r = await new Promise((resolve) => {+ main(['--env', 'https://contoso.crm.dynamics.com/', '--app-id', 'app-a', '--code-file', 'c.tsx',+ '--page-id', '9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d', '--prompt', 'p'],+ { makeGenpageCli: factory, emit: (ok, payload) => resolve({ ok, payload }) });+ });+ assert.strictEqual(r.ok, false);+ assert.match(r.payload.error, /cannot verify that page 9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d belongs to app app-a \(pac list failed\)/);+ assert.strictEqual(downloads, 0);+ assert.strictEqual(uploads, 0);+});++test('an update whose page is a member of the supplied app proceeds, case-insensitively', async () => {+ const canonical = '9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d';+ const seen = [];+ const factory = () => ({+ enumerateEnvironment: async () => ({ ok: true, ids: [canonical] }),+ enumeratePages: async () => ({ ok: true, pages: [{ pageId: canonical.toUpperCase(), name: 'Current Page' }] }),+ download: async ({ outputDir }) => {+ fs.mkdirSync(path.join(outputDir, canonical), { recursive: true });+ fs.writeFileSync(path.join(outputDir, canonical, 'config.json'), JSON.stringify({ dataSources: ['contoso_ticket'] }));+ return true;+ },+ upload: async (o) => { seen.push(o); return { pageId: o.pageId }; },+ });+ const r = await new Promise((resolve) => {+ main(['--env', 'https://contoso.crm.dynamics.com/', '--app-id', 'app-a', '--code-file', 'c.tsx',+ '--page-id', canonical.toUpperCase(), '--prompt', 'p'],+ { makeGenpageCli: factory, emit: (ok, payload) => resolve({ ok, payload }) });+ });+ assert.strictEqual(r.ok, true, JSON.stringify(r.payload));+ assert.strictEqual(seen.length, 1);+ assert.deepStrictEqual(seen[0].dataSources, ['contoso_ticket']);+});++test('a wrapper exposing no app-scoped enumeratePages is refused for updates', async () => {+ let uploads = 0;+ const factory = () => ({+ enumerateEnvironment: async () => ({ ok: true, ids: ['9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d'] }),+ upload: async () => { uploads += 1; return { pageId: 'x' }; },+ });+ const r = await new Promise((resolve) => {+ main(['--env', 'https://contoso.crm.dynamics.com/', '--app-id', 'app-a', '--code-file', 'c.tsx',+ '--page-id', '9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d', '--prompt', 'p'],+ { makeGenpageCli: factory, emit: (ok, payload) => resolve({ ok, payload }) });+ });+ assert.strictEqual(r.ok, false);+ assert.match(r.payload.error, /exposes no app-scoped page listing/);+ assert.strictEqual(uploads, 0);+});++// Each listing is its own pac process of about five seconds, so an update runs the existence and+// membership listings together. The overlap must not change what the guard DECIDES: verdicts are+// still reached existence-first, so each failure is reported exactly as it was when the listings+// ran one after the other.+const OVERLAP_PAGE = '9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d';+function updateWith(factory) {+ return new Promise((resolve, reject) => {+ main(['--env', 'https://contoso.crm.dynamics.com/', '--app-id', 'app-a', '--code-file', 'c.tsx',+ '--page-id', OVERLAP_PAGE, '--prompt', 'p'],+ { makeGenpageCli: factory, emit: (ok, payload) => resolve({ ok, payload }) }).catch(reject);+ });+}++test('an update starts its existence and membership listings together', async () => {+ const started = [];+ const release = new Map();+ const held = (name, value) => new Promise((resolve) => {+ started.push(name);+ release.set(name, () => resolve(value));+ });+ const base = capturingCli().factory();+ const factory = () => ({+ ...base,+ enumerateEnvironment: () => held('existence', { ok: true, ids: [OVERLAP_PAGE] }),+ enumeratePages: () => held('membership', { ok: true, pages: [{ pageId: OVERLAP_PAGE, name: 'Current Page' }] }),+ });+ const done = updateWith(factory);+ // Neither listing has answered yet, so a guard that awaited them in turn would still be on the first.+ const deadline = Date.now() + 2000;+ while (started.length < 2 && Date.now() < deadline) await new Promise((r) => setImmediate(r));+ assert.deepStrictEqual([...started].sort(), ['existence', 'membership'],+ 'both listings must be in flight before either answers');+ // Membership answers FIRST: which listing finishes first must not matter.+ release.get('membership')();+ release.get('existence')();+ const r = await done;+ assert.strictEqual(r.ok, true, JSON.stringify(r.payload));+ assert.strictEqual(r.payload.updated, true);+});++test('when both update listings fail, the existence failure is the one reported', async () => {+ const factory = () => ({+ enumerateEnvironment: async () => ({ ok: false, error: 'EXISTENCE-LISTING-DOWN' }),+ enumeratePages: async () => ({ ok: false, error: 'MEMBERSHIP-LISTING-DOWN' }),+ upload: async () => { throw new Error('must not upload'); },+ });+ const r = await updateWith(factory);+ assert.strictEqual(r.ok, false);+ assert.match(r.payload.error, /cannot verify that page \S+ exists before updating it \(EXISTENCE-LISTING-DOWN\)/);+ assert.doesNotMatch(r.payload.error, /MEMBERSHIP-LISTING-DOWN/);+});++// Running the membership listing early must not let ITS failure pre-empt the existence verdict. A+// listing that throws surfaces only once the guard reaches its verdict, as it did when it ran second.+test('a listing that throws surfaces only when the guard reaches its verdict', async () => {+ const absent = () => ({+ enumerateEnvironment: async () => ({ ok: true, ids: ['aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa'] }),+ enumeratePages: async () => { throw new Error('MEMBERSHIP-THREW'); },+ upload: async () => { throw new Error('must not upload'); },+ });+ const r = await updateWith(absent);+ assert.strictEqual(r.ok, false);+ assert.match(r.payload.error, /does not exist in this environment/);++ const present = () => ({ ...absent(), enumerateEnvironment: async () => ({ ok: true, ids: [OVERLAP_PAGE] }) });+ await assert.rejects(updateWith(present), /MEMBERSHIP-THREW/);++ const existenceThrows = () => ({+ ...absent(),+ enumerateEnvironment: async () => { throw new Error('EXISTENCE-THREW'); },+ enumeratePages: async () => ({ ok: true, pages: [{ pageId: OVERLAP_PAGE, name: 'Current Page' }] }),+ });+ await assert.rejects(updateWith(existenceThrows), /EXISTENCE-THREW/);+});++test('preserved data-source bindings must be non-empty strings', async () => {+ for (const dataSources of [[null], [{}], [18], ['contoso_ticket', '']]) {+ let uploads = 0;+ const factory = () => ({+ enumerateEnvironment: async () => ({ ok: true, ids: ['9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d'] }),+ enumeratePages: async () => ({ ok: true, pages: [{ pageId: '9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d', name: 'Current Page' }] }),+ download: async ({ outputDir, pageIds }) => {+ for (const pid of pageIds) {+ fs.mkdirSync(path.join(outputDir, pid), { recursive: true });+ fs.writeFileSync(path.join(outputDir, pid, 'config.json'), JSON.stringify({ dataSources }));+ }+ return true;+ },+ upload: async () => { uploads += 1; return { pageId: 'x' }; },+ });+ // eslint-disable-next-line no-await-in-loop+ const r = await new Promise((resolve) => {+ main(['--env', 'https://contoso.crm.dynamics.com/', '--app-id', 'app-a', '--code-file', 'c.tsx',+ '--page-id', '9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d', '--prompt', 'p'],+ { makeGenpageCli: factory, emit: (ok, payload) => resolve({ ok, payload }) });+ });+ assert.strictEqual(r.ok, false, `must refuse ${JSON.stringify(dataSources)}`);+ assert.match(r.payload.error, /cannot read the current data-source bindings/);+ assert.strictEqual(uploads, 0, `must not upload ${JSON.stringify(dataSources)}`);+ }+});diff --git a/plugins/model-apps/scripts/tests/genpage-worker-output.test.js b/plugins/model-apps/scripts/tests/genpage-worker-output.test.jsindex 0f9e8e09f..3eea64310 100644--- a/plugins/model-apps/scripts/tests/genpage-worker-output.test.js+++ b/plugins/model-apps/scripts/tests/genpage-worker-output.test.js@@ -27,7 +27,7 @@ test('validatePageOutput rejects a truncated worker file before dispatch is acce// sees that the function never closed.const balancedTail = validatePageOutput({ filePath: write('export default function GeneratedComponent() {\n const a = 1;\n return null;\n') });assert.equal(balancedTail.ok, false);- assert.deepEqual(balancedTail.problems, ['unbalanced brackets — output looks truncated']);+ assert.deepEqual(balancedTail.problems, ['unbalanced brackets — the file looks truncated']);// Cut INSIDE the export statement, nothing is open yet, so the brackets balance — the export// itself has to be complete: a function reaches its body, a bare name is one the module has.diff --git a/plugins/model-apps/scripts/tests/hydrate-spec.test.js b/plugins/model-apps/scripts/tests/hydrate-spec.test.jsindex 535212caf..faf12c4d7 100644--- a/plugins/model-apps/scripts/tests/hydrate-spec.test.js+++ b/plugins/model-apps/scripts/tests/hydrate-spec.test.js@@ -490,3 +490,23 @@ test('#583 hydrateSpec carries app.aiDescription only when the deployed app hasassert.ok(!('aiDescription' in (await hydrateSpec(white)).app), `whitespace-only ${JSON.stringify(ws)} is omitted`);}});+++test('hydrateSpec preserves a downloaded prompt exactly, and includes an explicitly blank prompt', async () => {+ const exact = ' Conversation with 1 prompts:\r\n1. Keep me exact.\r\n';+ const base = {+ app: async () => ({ name: 'A', description: '', siteMap: { areas: [] } }),+ entities: async () => [], webResources: async () => [], solution: async () => ({ uniqueName: 'S', publisherPrefix: 'new' }),+ };+ const withExact = await hydrateSpec({ ...base, pages: async () => [{ name: 'P', prompt: exact, codeFile: 'p.tsx' }] });+ assert.strictEqual(withExact.pages[0].prompt, exact);+ const withEmpty = await hydrateSpec({ ...base, pages: async () => [{ name: 'P', prompt: '', codeFile: 'p.tsx' }] });+ assert.strictEqual(withEmpty.pages[0].prompt, '', 'a present empty prompt is different from a missing prompt');+ const missing = await hydrateSpec({ ...base, pages: async () => [{ name: 'P', codeFile: 'p.tsx' }] });+ assert.ok(!('prompt' in missing.pages[0]), 'missing prompt.txt remains omitted');+ // The keyed (schemaVersion 2) page shape is built by a separate branch; it must agree.+ const keyed = await hydrateSpec({ ...base, pages: async () => [{ key: 'p', name: 'P', prompt: '', codeFile: 'p.tsx' }] });+ assert.strictEqual(keyed.pages[0].prompt, '', 'a keyed page keeps a present empty prompt too');+ const keyedExact = await hydrateSpec({ ...base, pages: async () => [{ key: 'p', name: 'P', prompt: exact, codeFile: 'p.tsx' }] });+ assert.strictEqual(keyedExact.pages[0].prompt, exact);+});diff --git a/plugins/model-apps/scripts/tests/launch-playwright-mcp.test.js b/plugins/model-apps/scripts/tests/launch-playwright-mcp.test.jsindex 0889af915..8a0da2012 100644--- a/plugins/model-apps/scripts/tests/launch-playwright-mcp.test.js+++ b/plugins/model-apps/scripts/tests/launch-playwright-mcp.test.js@@ -7,8 +7,8 @@ const { EventEmitter } = require('node:events');const {buildMcpArgs,launch,- quoteShellArg,} = require('../launch-playwright-mcp');+const { invocation } = require('../lib/process-runner');test('buildMcpArgs launches Playwright MCP with fullscreen config', () => {const expectedConfigPath = path.join(__dirname, '..', 'playwright-mcp-fullscreen.config.json');@@ -18,17 +18,19 @@ test('buildMcpArgs launches Playwright MCP with fullscreen config', () => {assert.deepEqual(args.slice(0, 4), ['-y', '@playwright/mcp@latest', '--browser', 'chrome']);assert.equal(args.includes('--viewport-size'), false);assert.notEqual(configIndex, -1);- assert.equal(args[configIndex + 1], quoteShellArg(expectedConfigPath));+ assert.equal(args[configIndex + 1], expectedConfigPath, 'the path is passed as-is; the process runner quotes it where needed');});-test('buildMcpArgs quotes Windows config paths containing spaces', () => {+test('a Windows config path containing spaces reaches the npx shim as one quoted argument', () => {const configPath = 'C:\\Users\\Power User\\.claude\\plugins\\model-apps\\scripts\\playwright-mcp-fullscreen.config.json';- const args = buildMcpArgs('msedge', { configPath, platform: 'win32' });- const configIndex = args.indexOf('--config');-- assert.equal(args[configIndex + 1], `"${configPath}"`);+ const inv = invocation('npx', buildMcpArgs('msedge', { configPath }), {+ platform: 'win32',+ env: { Path: 'C:\\nodejs', PATHEXT: '.EXE;.CMD', SystemRoot: 'C:\\Windows' },+ exists: (p) => p === 'C:\\nodejs\\npx.cmd',+ });+ assert.equal(inv.options.shell, false);+ assert.ok(inv.args[4].endsWith(`--config "${configPath}""`), inv.args[4]);});-test('fullscreen config maximizes the browser and uses the real viewport size', () => {const configPath = path.join(__dirname, '..', 'playwright-mcp-fullscreen.config.json');const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));@@ -54,7 +56,7 @@ test('launch wires spawn and process exit handling', () => {assert.equal(spawnCall.command, 'npx');assert.deepEqual(spawnCall.args.slice(0, 4), ['-y', '@playwright/mcp@latest', '--browser', 'msedge']);- assert.deepEqual(spawnCall.options, { stdio: 'inherit', shell: true });+ assert.deepEqual(spawnCall.options, { stdio: 'inherit' }, 'no shell: the process runner decides how npx starts');child.emit('exit', 7);assert.equal(spawnCall.exitCode, 7);@@ -72,6 +74,16 @@ test('launch handles the child error event (npx fails to spawn)', () => {assert.equal(handled, 'spawn npx ENOENT');});+test('launch reports a launch that cannot start (npx not on PATH) through onError', () => {+ let handled;+ const child = launch({+ browser: 'chrome',+ spawnFn: () => { const e = new Error('spawn npx ENOENT: not found on PATH'); e.code = 'ENOENT'; throw e; },+ onError: (err) => { handled = err.code; },+ });+ assert.equal(handled, 'ENOENT');+ assert.equal(child, null);+});// --- #588.7: a signal termination is a failure, not a clean shutdown -----------------------------// Node calls the exit handler with (code, signal); on a SIGNAL death `code` is null and `signal`// carries the name. `process.exit(code || 0)` therefore reported every crash and every kill as exitdiff --git a/plugins/model-apps/scripts/tests/list-connections.test.js b/plugins/model-apps/scripts/tests/list-connections.test.jsindex 0e81116ca..573540687 100644--- a/plugins/model-apps/scripts/tests/list-connections.test.js+++ b/plugins/model-apps/scripts/tests/list-connections.test.js@@ -40,18 +40,6 @@ test('an unknown flag is a usage error, not a token the CLI silently swallows',assert.match(res.stderr, /Usage:/);});-test('the rollback switch still works end to end (exit 3, distinct from a usage error)', () => {- // connectors ships ON, so this is the path that only runs if someone turns it off. Exercise it- // for real: a gate that has quietly stopped working is worthless as a rollback, and nothing else- // would notice until it was needed.- const res = spawnSync(process.execPath, [scriptPath, 'https://contoso.crm.dynamics.com'], {- encoding: 'utf8',- env: { ...process.env, GENPAGE_ENABLE_CONNECTORS: '0' },- });- assert.equal(res.status, 3, 'exit 3 = feature off, distinct from 1 = usage/runtime error');- assert.match(res.stderr, /disabled/i);-});-// --- Unit tests for the pure helpers (require.main guard keeps main() from running) ---const { sortReadyToBindFirst, pacFailureMessage } = require(scriptPath);diff --git a/plugins/model-apps/scripts/tests/modelapps-hook-utils.test.js b/plugins/model-apps/scripts/tests/modelapps-hook-utils.test.jsindex 6b58edb7a..7d2f0e140 100644--- a/plugins/model-apps/scripts/tests/modelapps-hook-utils.test.js+++ b/plugins/model-apps/scripts/tests/modelapps-hook-utils.test.js@@ -1,12 +1,13 @@const test = require('node:test');const assert = require('node:assert/strict');-+const { Readable } = require('node:stream');const {TRACKED_SKILLS,TRACKED_SKILL_NAMES,detectTrackedSkill,getTrackedSkillFromToolInput,getValidatorScript,+ readUtf8Stream,} = require('../lib/modelapps-hook-utils');test('discovers genpage and report-issue as tracked skills', () => {@@ -66,3 +67,11 @@ test('getValidatorScript returns null when a skill has no validator', () => {assert.equal(getValidatorScript('genpage'), null);assert.equal(getValidatorScript('nope'), null);});++test('readUtf8Stream preserves a multibyte character split across Buffer chunks', async () => {+ const text = 'payload: 東京 😀 Café';+ const bytes = Buffer.from(text, 'utf8');+ const split = bytes.indexOf(Buffer.from('😀', 'utf8')) + 1;+ const stream = Readable.from([bytes.subarray(0, split), bytes.subarray(split)]);+ assert.equal(await readUtf8Stream(stream), text);+});diff --git a/plugins/model-apps/scripts/tests/op-diff.test.js b/plugins/model-apps/scripts/tests/op-diff.test.jsindex 20dd95684..a9f0bbe73 100644--- a/plugins/model-apps/scripts/tests/op-diff.test.js+++ b/plugins/model-apps/scripts/tests/op-diff.test.js@@ -47,6 +47,19 @@ test('formRemovals is empty for an auto layout (auto never prunes)', () => {assert.deepStrictEqual(formRemovals(deployed, def), []);});+test('formRemovals is empty when an explicit layout opts out with prune:false', () => {+ const def = Object.assign(formOf(['new_subject']), { __explicitLayout: true, __prune: false, __primaryField: 'new_name' });+ const deployed = formOf(['new_name', 'new_subject', 'new_priority']);+ assert.deepStrictEqual(formRemovals(deployed, def), []);+});++test('formRemovals still lists removals when prune is absent or true', () => {+ const deployed = formOf(['new_name', 'new_subject', 'new_priority']);+ const base = { __explicitLayout: true, __primaryField: 'new_name' };+ assert.deepStrictEqual(formRemovals(deployed, Object.assign(formOf(['new_name']), base)), ['new_subject', 'new_priority']);+ assert.deepStrictEqual(formRemovals(deployed, Object.assign(formOf(['new_name']), base, { __prune: true })), ['new_subject', 'new_priority']);+});+test('classifyOps: no destructive ops when nothing is discovered', () => {assert.deepStrictEqual(classifyOps({ app: { name: 'X' } }, {}), { destructive: [], hasDestructive: false });});@@ -86,6 +99,13 @@ test('classifyOps: an auto-layout form in discovered.forms is never destructive'assert.deepStrictEqual(r, { destructive: [], hasDestructive: false });});+test('classifyOps: a prune:false explicit-layout form in discovered.forms is never destructive', () => {+ const def = Object.assign(formOf(['new_name']), { __explicitLayout: true, __prune: false, __primaryField: 'new_name' });+ const deployed = formOf(['new_name', 'new_priority', 'new_stale']);+ const r = classifyOps({}, { forms: [{ formId: 'form-1', label: 'form "Ticket" (new_ticket)', deployedForm: deployed, def }] });+ assert.deepStrictEqual(r, { destructive: [], hasDestructive: false });+});+test('classifyOps: a dropped sitemap target is destructive', () => {const r = classifyOps({}, { sitemap: { deployedTargets: ['entity:new_customer', 'entity:new_ticket'], wantTargets: ['entity:new_customer'] } });assert.strictEqual(r.hasDestructive, true);diff --git a/plugins/model-apps/scripts/tests/page-structure.test.js b/plugins/model-apps/scripts/tests/page-structure.test.jsnew file mode 100644index 000000000..2dbd20739--- /dev/null+++ b/plugins/model-apps/scripts/tests/page-structure.test.js@@ -0,0 +1,38 @@+'use strict';+// The two gates that accept a generated page must refuse exactly the same pages with exactly the same+// words: they were two copies once, and a check added to one had to be found missing from the other.+const { test } = require('node:test');+const assert = require('node:assert/strict');+const { pageStructureProblems } = require('../lib/page-structure.js');+const workerGate = require('../genpage-worker-output.js').structuralProblems;+const promotionGate = require('../promote-intent-pages.js').structuralProblems;++const CASES = [+ ['complete page', 'export default function P() {\n return <div>ok</div>;\n}\n'],+ ['empty file', ' \n'],+ ['no default export', 'export function P() { return null; }\n'],+ ['cut inside the export', 'import * as React from "react";\nexport default function P(props: Props)'],+ ['unbalanced brackets', 'export default function P() {\n return <div>\n'],+ ['stops mid-statement', 'const P = () => <div/>;\nexport default P;\nconst total = count *'],+ ['fenced prose', '\u0060\u0060\u0060tsx\nexport default function P() { return null; }\n\u0060\u0060\u0060\n'],+ // A tilde fence needs no escaping inside a template literal, which is how a page embeds markdown help.+ ['fence inside a template literal is data', 'const help = \u0060\n~~~md\nx\n~~~\n\u0060;\nexport default function P() { return <div>{help}</div>; }\n'],+ ['elided body', 'export default function P() {\n // ... rest of the component\n return null;\n}\n'],+];++for (const [name, code] of CASES) {+ test(`both page gates give the same verdict: ${name}`, () => {+ const expected = pageStructureProblems(code);+ assert.deepEqual(workerGate(code), expected);+ assert.deepEqual(promotionGate(code), expected);+ });+}++test('a complete page passes and each failure is named', () => {+ assert.deepEqual(pageStructureProblems(CASES[0][1]), []);+ assert.deepEqual(pageStructureProblems(' \n'), ['file is empty']);+ assert.match(pageStructureProblems(CASES[2][1]).join('\n'), /no complete default export — no real `export default`/);+ assert.match(pageStructureProblems(CASES[6][1]).join('\n'), /markdown code fence/);+ assert.deepEqual(pageStructureProblems(CASES[7][1]), []);+ assert.match(pageStructureProblems(CASES[8][1]).join('\n'), /the page is incomplete/);+});diff --git a/plugins/model-apps/scripts/tests/pageref-resolver.test.js b/plugins/model-apps/scripts/tests/pageref-resolver.test.jsindex 9d6a92328..f2c3c9783 100644--- a/plugins/model-apps/scripts/tests/pageref-resolver.test.js+++ b/plugins/model-apps/scripts/tests/pageref-resolver.test.js@@ -52,6 +52,108 @@ test('extractNavTargets handles pageId BEFORE pageType and a nested data:{} objeassert.strictEqual(t[0].key, 'detail', 'the top-level pageId is the target — a PAGEREF-looking string inside data:{} is NOT');});++test('extractNavTargets supports quoted property keys and preserves value offsets', () => {+ const calls = [+ 'Xrm.Navigation.navigateTo({"pageType":"generative","pageId":"PAGEREF_detail"});',+ "Xrm.Navigation.navigateTo({ 'pageType': 'generative', 'pageId': \"PAGEREF_gallery\" });",+ ];+ const code = calls.join('\n');+ const t = extractNavTargets(code);+ assert.deepStrictEqual(t.map((target) => [target.kind, target.key]), [['pageref', 'detail'], ['pageref', 'gallery']]);+ for (const target of t) {+ const literal = `\"PAGEREF_${target.key}\"`;+ assert.strictEqual(code.slice(target.valueStart, target.valueEnd), literal, `${target.key} value span maps to the original source`);+ }+});++test('extractNavTargets ignores quoted value text named like a key', () => {+ const code = 'Xrm.Navigation.navigateTo({ "pageType": "generative", label: "pageId", "pageId": "PAGEREF_detail" });';+ const t = extractNavTargets(code);+ assert.strictEqual(t.length, 1);+ assert.strictEqual(t[0].key, 'detail');+ assert.strictEqual(code.slice(t[0].valueStart, t[0].valueEnd), '"PAGEREF_detail"');+});++test('extractNavTargets keeps quoted-key offsets exact after a leading emoji comment', () => {+ const code = '// 🔎 inspect navigation\nXrm.Navigation.navigateTo({"pageType":"generative","pageId":"PAGEREF_detail"});';+ const [target] = extractNavTargets(code);+ assert.strictEqual(target.key, 'detail');+ assert.strictEqual(target.valueStart, code.indexOf('"PAGEREF_detail"'));+ assert.strictEqual(target.valueEnd, target.valueStart + '"PAGEREF_detail"'.length);+});++test('extractNavTargets supports mixed quoted and bare keys', () => {+ const code = 'Xrm.Navigation.navigateTo({ "pageType": "generative", pageId: "PAGEREF_detail" });';+ assert.deepStrictEqual(navReferencedKeys(code), ['detail']);+});++test('extractNavTargets ignores quoted pageId text in a ternary value and uses the real key', () => {+ const code = 'Xrm.Navigation.navigateTo({ pageType: "generative", foo: c ? "pageId" : "PAGEREF_wrong", pageId: "PAGEREF_detail" });';+ const [target] = extractNavTargets(code);+ assert.strictEqual(target.key, 'detail');+ assert.strictEqual(code.slice(target.valueStart, target.valueEnd), '"PAGEREF_detail"');+});++test('extractNavTargets ignores bare pageId identifiers in a ternary value and uses the real key', () => {+ const code = 'Xrm.Navigation.navigateTo({ pageType: "generative", foo: c ? pageId : other, pageId: "PAGEREF_detail" });';+ const [target] = extractNavTargets(code);+ assert.strictEqual(target.key, 'detail');+ assert.strictEqual(code.slice(target.valueStart, target.valueEnd), '"PAGEREF_detail"');+});++test('a ternary decoy AFTER the real key is not read as a later, overriding key', () => {+ // The last occurrence of a key takes effect, so a decoy that followed the real key and was taken for+ // a key would silently win. Only a boundary rule keeps it out: a key must follow `{` or `,`.+ for (const decoy of ['c ? "pageId" : "PAGEREF_wrong"', 'c ? pageId : other']) {+ const code = `Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "PAGEREF_detail", label: ${decoy} });`;+ const [target] = extractNavTargets(code);+ assert.strictEqual(target.key, 'detail', decoy);+ assert.strictEqual(code.slice(target.valueStart, target.valueEnd), '"PAGEREF_detail"', decoy);+ }+});++test('extractNavTargets matches keys after comments, newlines, and spreads', () => {+ const cases = [+ '{ /* note */ "pageId": "PAGEREF_detail", pageType: "generative" }',+ '{\n "pageId": "PAGEREF_detail", pageType: "generative" }',+ '{ ...base, "pageId": "PAGEREF_detail", pageType: "generative" }',+ ];+ for (const obj of cases) {+ const code = `Xrm.Navigation.navigateTo(${obj});`;+ const [target] = extractNavTargets(code);+ assert.strictEqual(target.key, 'detail', obj);+ assert.strictEqual(code.slice(target.valueStart, target.valueEnd), '"PAGEREF_detail"', obj);+ }+});++test('extractNavTargets does not match pageId inside a longer bare identifier', () => {+ const code = 'Xrm.Navigation.navigateTo({ pageType: "generative", myPageId: "PAGEREF_wrong", pageId: "PAGEREF_detail" });';+ const [target] = extractNavTargets(code);+ assert.strictEqual(target.key, 'detail');+ assert.strictEqual(code.slice(target.valueStart, target.valueEnd), '"PAGEREF_detail"');+});++test('extractNavTargets treats later runtime pageId overrides as dynamic', () => {+ const cases = [+ 'Xrm.Navigation.navigateTo({ pageType: "generative", "pageId": "PAGEREF_detail", ...options });',+ 'Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "PAGEREF_detail", ...options });',+ 'Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "PAGEREF_detail", [name]: other });',+ ];+ for (const code of cases) {+ const [target] = extractNavTargets(code);+ assert.strictEqual(target.kind, 'dynamic', code);+ assert.strictEqual(code.slice(target.valueStart, target.valueEnd), '"PAGEREF_detail"', code);+ }+});++test('extractNavTargets treats a later runtime pageType override as dynamic', () => {+ const code = 'Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "PAGEREF_detail", ...options });';+ const [target] = extractNavTargets(code);+ assert.strictEqual(target.kind, 'dynamic');+ assert.strictEqual(code.slice(target.valueStart, target.valueEnd), '"PAGEREF_detail"');+});+// ─── Comment and template-literal stripping ──────────────────────────────────//// A navigateTo inside a comment or template literal is NOT a real call site. The@@ -241,6 +343,53 @@ test('resolvePageRefs replaces each canonical nav pageId with the quoted genPageassert.deepStrictEqual(unresolved, []);});++test('resolvePageRefs rewrites only the PAGEREF literal inside a quoted-key call', () => {+ const code = [+ 'const decoy = "PAGEREF_detail";',+ 'Xrm.Navigation.navigateTo({"pageType":"generative","pageId":"PAGEREF_detail", data: { label: "pageId" }});',+ ].join('\n');+ const expected = [+ 'const decoy = "PAGEREF_detail";',+ 'Xrm.Navigation.navigateTo({"pageType":"generative","pageId":"gp-detail", data: { label: "pageId" }});',+ ].join('\n');+ const { deployment, unresolved } = resolvePageRefs(new Map([['overview', { code }]]), new Map([['detail', 'gp-detail']]));+ assert.deepStrictEqual(unresolved, []);+ assert.strictEqual(deployment.get('overview'), expected);+});++test('resolvePageRefs rewrites the real quoted-key pageId after a ternary decoy', () => {+ const code = 'Xrm.Navigation.navigateTo({"pageType":"generative", foo: c ? "pageId" : "PAGEREF_wrong", "pageId":"PAGEREF_detail"});';+ const expected = 'Xrm.Navigation.navigateTo({"pageType":"generative", foo: c ? "pageId" : "PAGEREF_wrong", "pageId":"gp-detail"});';+ const { deployment, unresolved } = resolvePageRefs(new Map([['overview', { code }]]), new Map([['detail', 'gp-detail'], ['wrong', 'gp-wrong']]));+ assert.deepStrictEqual(unresolved, []);+ assert.strictEqual(deployment.get('overview'), expected);+});++test('resolvePageRefs rewrites a key after an earlier spread but not before a later spread', () => {+ const safe = 'Xrm.Navigation.navigateTo({ ...base, pageType: "generative", "pageId": "PAGEREF_detail" });';+ const unsafe = 'Xrm.Navigation.navigateTo({ pageType: "generative", "pageId": "PAGEREF_detail", ...base });';+ const { deployment, unresolved } = resolvePageRefs(new Map([['safe', { code: safe }], ['unsafe', { code: unsafe }]]), new Map([['detail', 'gp-detail']]));+ assert.deepStrictEqual(unresolved, []);+ assert.strictEqual(deployment.get('safe'), 'Xrm.Navigation.navigateTo({ ...base, pageType: "generative", "pageId": "gp-detail" });');+ assert.strictEqual(deployment.get('unsafe'), unsafe);+});++test('resolvePageRefs rewrites the last duplicate pageId key only', () => {+ const code = 'Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "PAGEREF_a", pageId: "PAGEREF_b" });';+ const expected = 'Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "PAGEREF_a", pageId: "gp-b" });';+ const { deployment, unresolved } = resolvePageRefs(new Map([['overview', { code }]]), new Map([['a', 'gp-a'], ['b', 'gp-b']]));+ assert.deepStrictEqual(unresolved, []);+ assert.strictEqual(deployment.get('overview'), expected);+});++test('resolvePageRefs leaves navigateTo text inside a string inert and unchanged', () => {+ const code = 'const help = \'navigateTo({"pageType":"generative","pageId":"PAGEREF_detail"})\';';+ const { deployment, unresolved } = resolvePageRefs(new Map([['help', { code }]]), new Map([['detail', 'gp-detail']]));+ assert.deepStrictEqual(unresolved, []);+ assert.strictEqual(deployment.get('help'), code);+});+test('resolvePageRefs collects dangling targets (sorted, unique) and leaves them verbatim', () => {const sources = new Map([['a', { code: `${NAV('"PAGEREF_missing"')}\n${NAV('"PAGEREF_gone"')}` }],@@ -266,6 +415,19 @@ test('reverseResolveNavIds rewrites ONLY the nav pageId literal back to "PAGEREFassert.ok(out.includes('recordId: "5d29d8ce-1111-2222-3333-444455556666"'), 'the SAME guid used as a recordId is NOT reversed (scoped to nav pageId)');});++test('reverseResolveNavIds maps a quoted-key literal id back to a PAGEREF token', () => {+ const code = 'Xrm.Navigation.navigateTo({"pageType":"generative","pageId":"gp-detail"});';+ const out = reverseResolveNavIds(code, new Map([['gp-detail', 'detail']]));+ assert.strictEqual(out, 'Xrm.Navigation.navigateTo({"pageType":"generative","pageId":"PAGEREF_detail"});');+});++test('reverseResolveNavIds rewrites only the last duplicate pageId key', () => {+ const code = 'Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "gp-a", pageId: "gp-b" });';+ const out = reverseResolveNavIds(code, new Map([['gp-a', 'a'], ['gp-b', 'b']]));+ assert.strictEqual(out, 'Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "gp-a", pageId: "PAGEREF_b" });');+});+test('resolve then reverse round-trips the navigation literal', () => {const original = NAV('"PAGEREF_detail"');const resolved = resolvePageRefs(new Map([['x', { code: original }]]), new Map([['detail', 'gp-42']])).deployment.get('x');diff --git a/plugins/model-apps/scripts/tests/process-runner.test.js b/plugins/model-apps/scripts/tests/process-runner.test.jsnew file mode 100644index 000000000..0aee405a7--- /dev/null+++ b/plugins/model-apps/scripts/tests/process-runner.test.js@@ -0,0 +1,182 @@+'use strict';+const { test } = require('node:test');+const assert = require('node:assert');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const runner = require('../lib/process-runner.js');++const scratchDirs = [];+const scratch = (prefix) => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));+ scratchDirs.push(dir);+ return dir;+};+// Best effort: Windows can hold a just-exited executable (the copied node.exe below) open for a moment,+// and a cleanup error would fail the whole file rather than any test in it.+test.after(() => {+ for (const d of scratchDirs) {+ try { fs.rmSync(d, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }); } catch { /* left in the OS temp dir */ }+ }+});++const winEnv = (Path, extra = {}) => ({ Path, PATHEXT: '.COM;.EXE;.BAT;.CMD;.VBS;.JS', SystemRoot: 'C:\\Windows', ...extra });++test('resolveExecutable skips relative PATH entries and never looks in the current directory', () => {+ const seen = [];+ const exists = (p) => { seen.push(p); return false; };+ assert.strictEqual(runner.resolveExecutable('az', { platform: 'win32', env: winEnv('.;tools;;C:\\bin'), exists }), null);+ assert.ok(seen.every((p) => p.startsWith('C:\\bin\\')), `only the absolute entry is probed: ${seen}`);+ seen.length = 0;+ assert.strictEqual(runner.resolveExecutable('git', { platform: 'linux', env: { PATH: ':.:bin:/usr/bin' }, exists }), null);+ assert.deepStrictEqual(seen, ['/usr/bin/git']);+});++test('resolveExecutable follows PATH order, then PATHEXT order, and ignores script extensions', () => {+ const files = new Set(['C:\\b\\pac.cmd', 'C:\\b\\pac.exe', 'C:\\c\\pac.exe', 'C:\\a\\az.js']);+ const exists = (p) => files.has(p);+ const env = winEnv('C:\\a;C:\\b;C:\\c');+ assert.strictEqual(runner.resolveExecutable('pac', { platform: 'win32', env, exists }), 'C:\\b\\pac.exe');+ assert.strictEqual(runner.resolveExecutable('az', { platform: 'win32', env, exists }), null, '.JS is not something the runner will start');+});++test('invocation starts a native executable directly, with its arguments untouched', () => {+ const exists = (p) => p === 'C:\\tools\\pac.exe';+ const inv = runner.invocation('pac', ['model', 'genpage', 'upload', '--name', 'a "b" & 50%!'], { platform: 'win32', env: winEnv('C:\\tools'), exists });+ assert.strictEqual(inv.file, 'C:\\tools\\pac.exe');+ assert.deepStrictEqual(inv.args, ['model', 'genpage', 'upload', '--name', 'a "b" & 50%!']);+ assert.strictEqual(inv.options.shell, false);+ assert.strictEqual(inv.options.windowsVerbatimArguments, undefined);+});++test('invocation runs a batch shim through an absolute cmd.exe with a checked command line', () => {+ const exists = (p) => p === 'C:\\Program Files\\CLI2\\wbin\\az.cmd';+ const env = winEnv('C:\\Program Files\\CLI2\\wbin', { ComSpec: 'cmd.exe' });+ const inv = runner.invocation('az', ['account', 'get-access-token', '--resource', 'https://contoso.crm.dynamics.com', '--query', 'accessToken'], { platform: 'win32', env, exists });+ assert.strictEqual(inv.file, 'C:\\Windows\\System32\\cmd.exe', 'a relative ComSpec is not trusted');+ assert.deepStrictEqual(inv.args, ['/d', '/s', '/v:off', '/c',+ '""C:\\Program Files\\CLI2\\wbin\\az.cmd" account get-access-token --resource https://contoso.crm.dynamics.com --query accessToken"']);+ assert.strictEqual(inv.options.shell, false);+ assert.strictEqual(inv.options.windowsVerbatimArguments, true);+ assert.strictEqual(inv.options.env.NoDefaultCurrentDirectoryInExePath, '1');+});++test('a batch shim refuses what cmd.exe would reinterpret, before anything starts', () => {+ const exists = (p) => p === 'C:\\bin\\az.cmd';+ const opts = { platform: 'win32', env: winEnv('C:\\bin'), exists };+ for (const bad of ['a"b', '100%', '%PATH%', 'line\nbreak', 'tab\there', 'nul\u0000']) {+ assert.throws(() => runner.invocation('az', ['--x', bad], opts), (e) => e.code === 'EARGUMENT', JSON.stringify(bad));+ }+ assert.throws(() => runner.invocation('missing', [], opts), (e) => e.code === 'ENOENT');+});++test('! passes a shim that leaves delayed expansion off, and is refused by one that turns it on', () => {+ const exists = (p) => p === 'C:\\bin\\pac.cmd';+ const plain = { platform: 'win32', env: winEnv('C:\\bin'), exists, readFile: () => '@"%~dp0pac.exe" %*\r\n' };+ const inv = runner.invocation('pac', ['--name', 'Hello!', 'C:\\Users\\hello!\\page.tsx'], plain);+ assert.ok(inv.args[4].endsWith(' --name "Hello!" "C:\\Users\\hello!\\page.tsx""'), inv.args[4]);+ const expanding = { ...plain, readFile: () => '@setlocal EnableDelayedExpansion\r\n@"%~dp0pac.exe" %*\r\n' };+ assert.throws(() => runner.invocation('pac', ['--name', 'Hello!'], expanding), (e) => e.code === 'EARGUMENT' && /for this one/.test(e.message));+ const unreadable = { ...plain, readFile: () => { throw new Error('EACCES'); } };+ assert.throws(() => runner.invocation('pac', ['--name', 'Hello!'], unreadable), (e) => e.code === 'EARGUMENT');+ assert.doesNotThrow(() => runner.invocation('pac', ['--name', 'Hello'], unreadable), 'the shim is only read when an argument has a !');+});++test('when an env object spells PATH twice, resolution reads the one Node passes the child', () => {+ // Node sends a Windows child the lexicographically first spelling: `PATH` sorts before `Path`.+ const env = { Path: 'C:\\old', PATH: 'C:\\new', PATHEXT: '.CMD' };+ assert.strictEqual(runner.envValue(env, 'PATH', 'win32'), 'C:\\new');+ const exists = (p) => p === 'C:\\old\\npm.cmd' || p === 'C:\\new\\npm.cmd';+ assert.strictEqual(runner.resolveExecutable('npm', { platform: 'win32', env, exists }), 'C:\\new\\npm.cmd');+ assert.strictEqual(runner.envValue({ Path: 'C:\\only' }, 'PATH', 'win32'), 'C:\\only');+ assert.strictEqual(runner.envValue({ Path: 'x' }, 'PATH', 'linux'), undefined, 'POSIX names are case-sensitive');+});+test('withPathFirst puts a directory first on the path the child will actually receive', () => {+ // Windows: every spelling collapses into one PATH carrying the value Node would pass.+ const win = runner.withPathFirst({ Path: 'C:\\old', PATH: 'C:\\sys', X: '1' }, 'C:\\node20', 'win32');+ assert.deepStrictEqual(win, { X: '1', PATH: 'C:\\node20;C:\\sys' });+ assert.deepStrictEqual(runner.withPathFirst({ Path: 'C:\\sys' }, 'C:\\node20', 'win32'), { PATH: 'C:\\node20;C:\\sys' });+ // POSIX: Path and PATH are different variables; only PATH changes.+ const posix = runner.withPathFirst({ Path: '/not-the-path', PATH: '/usr/bin' }, '/opt/node20/bin', 'linux');+ assert.deepStrictEqual(posix, { Path: '/not-the-path', PATH: '/opt/node20/bin:/usr/bin' });+ assert.deepStrictEqual(runner.withPathFirst({}, '/opt/node20/bin', 'linux'), { PATH: '/opt/node20/bin' });+});+test('a batch shim whose own path cmd.exe would expand is refused', () => {+ for (const dir of ['C:\\100%\\bin', 'C:\\wow!\\bin']) {+ const exists = (p) => p === `${dir}\\az.cmd`;+ assert.throws(() => runner.invocation('az', ['--version'], { platform: 'win32', env: winEnv(dir), exists }), (e) => e.code === 'EARGUMENT', dir);+ }+});++test('cmdArgument quotes what needs quoting and doubles a trailing backslash run', () => {+ assert.strictEqual(runner.cmdArgument('{user:user.name,tenantId:tenantId}'), '{user:user.name,tenantId:tenantId}');+ assert.strictEqual(runner.cmdArgument('Order Detail'), '"Order Detail"');+ assert.strictEqual(runner.cmdArgument('a&b|c<d>e^f(g)'), '"a&b|c<d>e^f(g)"');+ assert.strictEqual(runner.cmdArgument('C:\\out dir\\'), '"C:\\out dir\\\\"');+ assert.strictEqual(runner.cmdArgument(''), '""');+ assert.strictEqual(runner.cmdArgument('x"y'), null);+});++test('caller options are merged under the invocation, so a shell cannot be turned back on', () => {+ const exists = (p) => p === 'C:\\bin\\az.cmd';+ const inv = runner.invocation('az', ['--version'], { platform: 'win32', env: winEnv('C:\\bin'), exists });+ const merged = runner.withOptions(inv, { shell: true, windowsVerbatimArguments: false, encoding: 'utf8', env: { X: '1' } });+ assert.strictEqual(merged.shell, false);+ assert.strictEqual(merged.windowsVerbatimArguments, true);+ assert.strictEqual(merged.encoding, 'utf8');+ assert.deepStrictEqual(merged.env, { X: '1', NoDefaultCurrentDirectoryInExePath: '1' }, 'a caller env is kept, with the lookup guard added');+ const native = runner.invocation('az', [], { platform: 'linux', env: { PATH: '/usr/bin' }, exists: (p) => p === '/usr/bin/az' });+ assert.deepStrictEqual(runner.withOptions(native, { shell: '/bin/sh', env: { X: '1' } }), { shell: false, windowsHide: true, env: { X: '1' } });+});++test('spawnResultSync reports a command missing from PATH the way spawnSync reports a launch failure', () => {+ const r = runner.spawnResultSync('nope', [], {}, { platform: 'linux', env: { PATH: '/x' }, exists: () => false });+ assert.strictEqual(r.status, null);+ assert.strictEqual(r.error.code, 'ENOENT');+ assert.match(r.error.message, /spawn nope ENOENT/);+});+test('execFileAsync reports an unresolvable command through its callback, asynchronously', async () => {+ let sync = true;+ const err = await new Promise((resolve) => {+ runner.execFileAsync('nope', [], {}, (e) => resolve({ e, sync }), { platform: 'linux', env: { PATH: '/x' }, exists: () => false });+ sync = false;+ });+ assert.strictEqual(err.e.code, 'ENOENT');+ assert.strictEqual(err.sync, false);+});++// The real thing: a batch shim that forwards %* to node, exactly as az.cmd and npm.cmd do, reached+// through the runner. Every accepted value must arrive byte-for-byte, and nothing may run besides it.+test('a batch shim receives accepted arguments unchanged through a real cmd.exe', { skip: process.platform !== 'win32' }, () => {+ const dir = scratch('process-runner-shim-');+ const script = path.join(dir, 'argv.js');+ fs.writeFileSync(script, "process.stdout.write(JSON.stringify(process.argv.slice(2)));\n", 'utf8');+ fs.writeFileSync(path.join(dir, 'fakecli.cmd'), `@echo off\r\n"${process.execPath}" "${script}" %*\r\n`, 'utf8');+ const marker = path.join(dir, 'MARKER');+ const env = { ...process.env, Path: dir, PATH: dir };+ const values = [+ 'https://contoso.crm.dynamics.com',+ '{user:user.name,tenantId:tenantId}',+ 'Order Detail',+ `a & echo x> ${marker}`,+ 'a | b < c > d ^ e ( f )',+ 'C:\\Users\\Power User\\download\\',+ '東京 page',+ '',+ 'trailing space ',+ 'Hello!',+ 'C:\\Users\\hello!\\page.tsx',+ ];+ const out = runner.runSync('fakecli', [...values, 'after'], { encoding: 'utf8', timeout: 30000 }, { env });+ assert.deepStrictEqual(JSON.parse(out), [...values, 'after']);+ assert.ok(!fs.existsSync(marker), 'no command other than the shim ran');+});++test('a native executable receives any argument unchanged through the runner', { skip: process.platform !== 'win32' }, () => {+ const dir = scratch('process-runner-native-');+ fs.copyFileSync(process.execPath, path.join(dir, 'fakenode.exe'));+ const env = { ...process.env, Path: dir, PATH: dir };+ const values = ['a "quoted" value', '100% & more!', 'C:\\dir with space\\', 'x\\"y'];+ const out = runner.runSync('fakenode', ['-e', 'process.stdout.write(JSON.stringify(process.argv.slice(1)))', ...values], { encoding: 'utf8', timeout: 30000 }, { env });+ assert.deepStrictEqual(JSON.parse(out), values);+});diff --git a/plugins/model-apps/scripts/tests/review-findings.test.js b/plugins/model-apps/scripts/tests/review-findings.test.jsindex 8337b2ddd..1a8e3e9c2 100644--- a/plugins/model-apps/scripts/tests/review-findings.test.js+++ b/plugins/model-apps/scripts/tests/review-findings.test.js@@ -350,38 +350,31 @@ test('#6a4 a failed BUSINESS-RULE read is UNKNOWN, not "this app has no businessassert.ok(!(clean.incomplete || []).some((i) => i.kind === 'businessRules'), JSON.stringify(clean.incomplete));});-test('#6a5 a TRUNCATED component page marks the class incomplete, not undercounted', async () => {- // `$top` is a hard cap and Dataverse omits `@odata.nextLink` when it is honoured, so a full page is- // indistinguishable from a truncated one and there is no signal to read afterwards. This list feeds- // `notRoundTrippedSummary`, which reports a COUNT — so a truncated read there is not merely a- // missing artifact, it is a smaller number presented as the whole truth.- //- // Written after a mutation run showed the guard was shipped untested: disabling it changed no test.+test('#6a5 app component inventory reads are paginated, not capped and undercounted', async () => {+ // These component rows decide which deployed forms/views/charts are reported as not round-tripped.+ // A capped read turns the tail into an authoritative undercount, so the query must ask the SDK to+ // follow every page instead of relying on `$top`.const { readDescriptionInventory } = require('../download-model-app.js');const APP = '11111111-1111-1111-1111-111111111111';- const CAP = 1000; // COMPONENT_PAGE_CAP — module-private, so pinned here deliberately.- const full = Array.from({ length: CAP }, (_, i) => ({ objectid: `v-${i}`, componenttype: 26 }));- const sdk = (rows) => ({+ const calls = [];+ const sdk = {dataverse: { get: async () => ({ status: 200, headers: {}, body: { value: [] } }) },queryRecords: async (logical, opts) => {+ calls.push({ logical, opts });if (logical === 'appmodule') return [{ appmoduleidunique: APP }];- // Only the VIEW class (componenttype 26) is saturated; the others return a short page.- if (logical === 'appmodulecomponent') return /componenttype eq 26/.test((opts && opts.filter) || '') ? rows : [];- if (logical === 'savedquery') return [];+ if (logical === 'appmodulecomponent') return [];return [];},- });-- const truncated = await readDescriptionInventory(sdk(full), APP, null);- const v = (truncated.incomplete || []).find((i) => i.kind === 'views');- assert.ok(v, `views must be marked incomplete at the cap, got ${JSON.stringify(truncated.incomplete)}`);- assert.match(v.reason, /truncated/i, v.reason);- // Scoped: the classes that read a SHORT page are not tarred with it.- assert.ok(!(truncated.incomplete || []).some((i) => i.kind === 'charts'), JSON.stringify(truncated.incomplete));+ };- // One row under the cap is a complete read and must stay silent, or the warning cries wolf.- const under = await readDescriptionInventory(sdk(full.slice(0, CAP - 1)), APP, null);- assert.ok(!(under.incomplete || []).some((i) => i.kind === 'views'), JSON.stringify(under.incomplete));+ const inv = await readDescriptionInventory(sdk, APP, null);+ assert.ok(!(inv.incomplete || []).some((i) => i.kind === 'views'), JSON.stringify(inv.incomplete));+ const componentReads = calls.filter((c) => c.logical === 'appmodulecomponent');+ assert.ok(componentReads.length >= 3, `expected reads for views/charts/forms, got ${JSON.stringify(componentReads)}`);+ for (const call of componentReads) {+ assert.strictEqual(call.opts.paginate, true, `${call.opts.filter} must paginate`);+ assert.strictEqual(call.opts.top, undefined, `${call.opts.filter} must not cap with top`);+ }});test('#6a2 an unreadable app-component list marks EVERY class unknown', async () => {diff --git a/plugins/model-apps/scripts/tests/run-tests.test.js b/plugins/model-apps/scripts/tests/run-tests.test.jsindex e0656f70f..4bd668425 100644--- a/plugins/model-apps/scripts/tests/run-tests.test.js+++ b/plugins/model-apps/scripts/tests/run-tests.test.js@@ -76,8 +76,12 @@ test('summarize fails the run when any non-skipped suite failed', () => {// failure. This is a text assertion rather than a YAML parse because the repo ships no YAML// dependency and the properties that matter are all line-level.const WORKFLOW = path.resolve(__dirname, '..', '..', '..', '..', '.github', 'workflows', 'model-apps-script-tests.yml');+// The one exception: the `shared/` sources this plugin ships physical copies of. A change to one is+// NOT unrelated — telemetry-lib-copy.test.js fails when a copy drifts from its source, and it should+// fail in the PR that edited the source, not in the next model-apps PR, whose author did not cause it.+const BUNDLED_SHARED_SOURCES = new Set(['shared/telemetry/**', 'shared/skills/**']);-test('the model-apps CI workflow triggers ONLY on model-apps paths', () => {+test('the model-apps CI workflow triggers ONLY on model-apps paths and the shared sources it bundles', () => {const wf = fs.readFileSync(WORKFLOW, 'utf8');// The `paths:` block ends at the first non-list line (the blank line before `jobs:`).// paths:@@ -95,12 +99,19 @@ test('the model-apps CI workflow triggers ONLY on model-apps paths', () => {assert.ok(globs.length > 0, 'the workflow must declare a paths filter, not run on every PR');for (const g of globs) {assert.ok(- g.startsWith('plugins/model-apps/') || g.startsWith('evals/model-apps/') || g.endsWith('model-apps-script-tests.yml'),+ g.startsWith('plugins/model-apps/') || g.startsWith('evals/model-apps/') || g.endsWith('model-apps-script-tests.yml')+ || BUNDLED_SHARED_SOURCES.has(g),`path filter "${g}" is not scoped to model-apps — this workflow must not run for other plugins`);}// And it must not be scoped so tightly that the plugin's own code stops triggering it.assert.ok(globs.some((g) => g.startsWith('plugins/model-apps/')), 'the plugin source must trigger the workflow');+ // Every shared source the plugin copies from must trigger it, and each one must exist: a renamed+ // or removed source would otherwise leave an allowed glob that matches nothing.+ for (const source of BUNDLED_SHARED_SOURCES) {+ assert.ok(globs.includes(source), `a change to ${source} must run the drift test`);+ assert.ok(fs.existsSync(path.resolve(__dirname, '..', '..', '..', '..', source.replace(/\/\*\*$/, ''))), `${source} names no directory`);+ }});test('the model-apps CI workflow opts out of telemetry transmission on every job', () => {@@ -113,6 +124,20 @@ test('the model-apps CI workflow opts out of telemetry transmission on every jobassert.strictEqual(optOuts, jobCount, `every job must set the opt-out (${optOuts} set / ${jobCount} jobs)`);});+test('the model-apps CI workflow has a read-only token, cancels superseded runs, and bounds every job', () => {+ const wf = fs.readFileSync(WORKFLOW, 'utf8');+ // Declared at the top level so no job inherits whatever the repository default grants, and no+ // job widens it again with a write scope of its own.+ assert.match(wf, /^permissions:[ \t]*\r?\n[ \t]+contents:[ \t]*read[ \t]*\r?$/m, 'the token must be read-only');+ assert.doesNotMatch(wf, /^\s+[a-z-]+:[ \t]*write[ \t]*\r?$/m, 'no scope may be write');+ assert.match(wf, /^concurrency:[ \t]*\r?\n(?:[ \t]+.*\r?\n)*?[ \t]+cancel-in-progress:[ \t]*true\b/m,+ 'a new push must cancel the run it supersedes');+ // Without a limit a hung test holds its runner for GitHub's six-hour default.+ const jobCount = (wf.match(/^ {4}[a-z0-9-]+:\s*$/gim) || []).length;+ const timeouts = (wf.match(/^ {8}timeout-minutes:[ \t]*\d+[ \t]*\r?$/gm) || []).length;+ assert.strictEqual(timeouts, jobCount, `every job must set timeout-minutes (${timeouts} set / ${jobCount} jobs)`);+});+// --- committed lock files must not carry a registry URL ---------------------------------------// `resolved` records the exact feed a package came from. Public npm is blocked on some Microsoft// networks, so a contributor installing through an internal Azure Artifacts feed would rewritediff --git a/plugins/model-apps/scripts/tests/sdk-build-layout-default.test.js b/plugins/model-apps/scripts/tests/sdk-build-layout-default.test.jsnew file mode 100644index 000000000..5cadfaa21--- /dev/null+++ b/plugins/model-apps/scripts/tests/sdk-build-layout-default.test.js@@ -0,0 +1,320 @@+'use strict';+const test = require('node:test');+const assert = require('node:assert');+const { runSdkBuild } = require('../lib/sdk-build.js');+const { validateAppSpec } = require('../lib/app-spec.js');+const { fitsGrid } = require('../lib/form-occupancy.js');++const clone = (v) => JSON.parse(JSON.stringify(v));+function jpTokens(ptr) { return ptr === '' ? [] : ptr.split('/').slice(1).map((t) => t.replace(/~1/g, '/').replace(/~0/g, '~')); }+function jpGet(obj, ptr) { let cur = obj; for (const t of jpTokens(ptr)) { if (cur == null) return undefined; cur = cur[t]; } return cur; }+function jpSet(obj, ptr, val) { const toks = jpTokens(ptr); const last = toks.pop(); let cur = obj; for (const t of toks) cur = cur[t]; cur[last] = val; }+function jpRemove(obj, ptr) { const toks = jpTokens(ptr); const last = toks.pop(); let cur = obj; for (const t of toks) cur = cur[t]; if (Array.isArray(cur)) cur.splice(Number(last), 1); else delete cur[last]; }++function mockSdk({ existingFormJson, formsByName = { Probe: { id: 'form-existing', entity: 'new_project', isdefault: false } }, failPromoteIds = new Set() } = {}) {+ const calls = [];+ const store = {};+ const systemForms = new Map(Object.entries(formsByName).map(([name, row]) => [name, { name, ...row }]));+ const formById = (id) => [...systemForms.values()].find((f) => String(f.id) === String(id));+ const seed = (id) => Object.assign(clone(existingFormJson), { id });+ const sdk = {+ queryRecords: async (set, opts = {}) => {+ calls.push({ name: 'queryRecords', args: [set, opts] });+ const filter = opts.filter || '';+ if (set === 'solution') return [{ solutionid: 'solution-id' }];+ if (set === 'publisher') return [{ publisherid: 'publisher-id' }];+ if (set === 'systemform') {+ const byId = /formid eq (\S+)/.exec(filter);+ if (byId) {+ const row = formById(byId[1]);+ return row ? [{ formid: row.id, objecttypecode: row.entity, isdefault: row.isdefault === true, formactivationstate: row.formactivationstate }] : [];+ }+ const byName = /name eq '([^']+)'/.exec(filter);+ if (byName) {+ const row = systemForms.get(byName[1]);+ return row ? [{ formid: row.id, objecttypecode: row.entity, isdefault: row.isdefault === true }] : [];+ }+ if (/type eq 2/.test(filter)) {+ return [...systemForms.values()].map((row) => ({ formid: row.id, objecttypecode: row.entity, isdefault: row.isdefault === true, formactivationstate: row.formactivationstate }));+ }+ }+ return [];+ },+ fetchArtifact: async (type, id) => {+ calls.push({ name: 'fetchArtifact', args: [type, id] });+ if (type === 'form' && !store[`${type}:${id}`]) store[`${type}:${id}`] = seed(id);+ return store[`${type}:${id}`] || { id };+ },+ getArtifact: async (type, id) => {+ calls.push({ name: 'getArtifact', args: [type, id] });+ return store[`${type}:${id}`] || (type === 'form' ? seed(id) : { id });+ },+ updateElement: async (type, id, ptr, patch) => {+ calls.push({ name: 'updateElement', args: [type, id, ptr, patch] });+ const art = store[`${type}:${id}`] || (store[`${type}:${id}`] = seed(id));+ const current = jpGet(art, ptr);+ const mergeable = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);+ jpSet(art, ptr, mergeable(current) && mergeable(patch) ? Object.assign({}, current, clone(patch)) : clone(patch));+ return clone(art);+ },+ addElement: async (type, id, ptr, element, opts = {}) => {+ calls.push({ name: 'addElement', args: [type, id, ptr, element, opts] });+ const art = store[`${type}:${id}`] || (store[`${type}:${id}`] = seed(id));+ const arr = jpGet(art, ptr);+ if (!Array.isArray(arr)) return clone(art);+ const pos = opts.position;+ let at = arr.length;+ if (pos === 'start') at = 0;+ else if (pos && typeof pos === 'object' && 'index' in pos) at = Math.max(0, Math.min(pos.index, arr.length));+ arr.splice(at, 0, clone(element));+ return clone(art);+ },+ moveElement: async (type, id, fromPtr, toPtr, opts = {}) => {+ calls.push({ name: 'moveElement', args: [type, id, fromPtr, toPtr, opts] });+ const art = store[`${type}:${id}`] || (store[`${type}:${id}`] = seed(id));+ const el = jpGet(art, fromPtr);+ const target = jpGet(art, toPtr);+ if (el === undefined || !Array.isArray(target)) return clone(art);+ jpRemove(art, fromPtr);+ target.splice(opts.index === undefined ? target.length : opts.index, 0, el);+ return clone(art);+ },+ removeElement: async (type, id, ptr) => {+ calls.push({ name: 'removeElement', args: [type, id, ptr] });+ const art = store[`${type}:${id}`];+ if (art) jpRemove(art, ptr);+ return clone(art || { id });+ },+ updateRecord: async (set, id, data) => {+ calls.push({ name: 'updateRecord', args: [set, id, data] });+ if (data && data.isdefault === true && failPromoteIds.has(String(id))) throw new Error('promotion failed');+ const row = formById(id);+ if (row && data && Object.prototype.hasOwnProperty.call(data, 'isdefault')) row.isdefault = data.isdefault;+ },+ pushArtifact: async (type, id) => { calls.push({ name: 'pushArtifact', args: [type, id] }); return { type, id, saved: true, shipped: false, publish: { kind: 'notRequested' } }; },+ publishArtifact: async (type, id) => { calls.push({ name: 'publishArtifact', args: [type, id] }); return { type, id, shipped: true, publish: { kind: 'verified' } }; },+ addSolutionComponent: async (component) => { calls.push({ name: 'addSolutionComponent', args: [component] }); },+ };+ return { sdk, calls, systemForms };+}++function cell(name, extra = {}) {+ return { id: `cell-${name}`, ...extra, control: { fieldName: `new_${name}`, id: `control-${name}` } };+}+function spacer(extra = {}) { return { id: 'maker-spacer', ...extra }; }+function existingForm(columns, rows) {+ return { id: 'form-existing', name: 'Probe', tabs: [{ name: 'probe', label: 'Probe', columns: [{ width: '100%', sections: [{ name: 'fields', label: 'Fields', columns, rows: rows.map((cells) => ({ cells })) }] }] }], bag: { a: [], c: [] } };+}+function specFor({ columns, fields, forms = null }) {+ const spec = {+ solution: { uniqueName: 'LayoutProbe', displayName: 'Layout Probe', publisherPrefix: 'new' },+ app: { name: 'Layout Probe' },+ entities: [{ schemaName: 'new_project', displayName: 'Project', primaryAttribute: { schemaName: 'new_a', displayName: 'A' }, columns: ['b', 'c', 'd', 'e', 'f'].map((f) => ({ schemaName: `new_${f}`, displayName: f.toUpperCase(), type: 'Text' })) }],+ views: [], charts: [],+ forms: forms || [{ entity: 'new_project', name: 'Probe', formType: 'Main', layout: 'explicit', tabs: [{ name: 'probe', label: 'Probe', sections: [{ name: 'fields', label: 'Fields', columns, fields }] }] }],+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'Work', subAreas: [{ entity: 'new_project', title: 'Projects' }] }] }] },+ };+ const validation = validateAppSpec(spec);+ assert.strictEqual(validation.ok, true, JSON.stringify(validation.errors));+ return spec;+}+function sectionOf(form) { return form.tabs[0].columns[0].sections[0]; }+async function runTwice(spec, existing, options = {}) {+ const mock = mockSdk({ existingFormJson: existing, ...options });+ const warnings = [];+ const first = await runSdkBuild(spec, { sdk: mock.sdk, provisionSdk: mock.sdk, apply: true, phases: ['forms'], warn: (m) => warnings.push(String(m)) });+ const second = await runSdkBuild(spec, { sdk: mock.sdk, provisionSdk: mock.sdk, apply: true, phases: ['forms'], warn: (m) => warnings.push(String(m)) });+ const form = await mock.sdk.getArtifact('form', 'form-existing');+ return { ...mock, first, second, warnings, form, section: sectionOf(form) };+}+function assertFits(section) {+ assert.ok(fitsGrid(section.rows || [], Number(section.columns)), `rows must fit ${section.columns} columns: ${JSON.stringify(section.rows)}`);+}++for (const [name, existing, desired, wantColumns, wantSkip] of [+ ['ordinary shrink', existingForm(4, [[cell('a'), cell('b'), cell('c'), cell('d')]]), ['new_a', 'new_b', 'new_c', 'new_d'], 2, false],+ ['trailing-span shrink', existingForm(4, [[cell('a'), cell('b'), cell('c'), cell('d', { rowspan: 3 })]]), ['new_a', 'new_b', 'new_c', 'new_d'], 2, false],+ ['following row own overflow', existingForm(4, [[cell('a', { rowspan: 2 })], [cell('b'), cell('c'), cell('d')]]), ['new_a', 'new_b', 'new_c', 'new_d'], 4, true],+ ['carried-reservation-only overflow', existingForm(4, [[cell('a', { rowspan: 2 })], [cell('b'), cell('c')], [cell('d')]]), ['new_a', 'new_b', 'new_c', 'new_d'], 4, true],+ ['spacer carried overflow', existingForm(4, [[cell('a', { rowspan: 2 })], [spacer(), cell('b')], [cell('c'), cell('d')]]), ['new_a', 'new_b', 'new_c', 'new_d'], 4, true],+ ['safe reservation shrink', existingForm(4, [[cell('a', { rowspan: 2 })], [cell('b')], [cell('c'), cell('d')]]), ['new_a', 'new_b', 'new_c', 'new_d'], 2, false],+]) {+ test(`form layout row occupancy: ${name}`, async () => {+ const spec = specFor({ columns: 2, fields: desired });+ const { section, second } = await runTwice(spec, existing);+ assert.strictEqual(Number(section.columns), wantColumns);+ assertFits(section);+ assert.strictEqual(second.skipped.layout.length > 0, wantSkip, JSON.stringify(second.skipped.layout));+ });+}++test('form layout row occupancy: raise a span on a followed cell is skipped', async () => {+ const spec = specFor({ columns: 2, fields: ['new_b', 'new_c', 'new_d', { name: 'new_a', rowspan: 2 }] });+ const { section, second } = await runTwice(spec, existingForm(2, [[cell('a'), cell('b')], [cell('c'), cell('d')]]));+ const a = section.rows.flatMap((r) => r.cells || []).find((c) => c.control && c.control.fieldName === 'new_a');+ assert.strictEqual(Number(a.rowspan) || 1, 1);+ assert.ok(second.skipped.layout.some((m) => /rowspan/.test(m)), JSON.stringify(second.skipped.layout));+ assertFits(section);+});++test('form layout row occupancy: widening beside a span is skipped', async () => {+ const spec = specFor({ columns: 2, fields: ['new_a', { name: 'new_b', colspan: 2 }, 'new_c', 'new_d'] });+ const { section, second } = await runTwice(spec, existingForm(2, [[cell('a', { rowspan: 2 }), cell('b')], [cell('c')], [cell('d')]]));+ const b = section.rows.flatMap((r) => r.cells || []).find((c) => c.control && c.control.fieldName === 'new_b');+ assert.strictEqual(Number(b.colspan) || 1, 1);+ assert.ok(second.skipped.layout.length > 0, 'a layout skip must be reported');+ assertFits(section);+});++test('form layout row occupancy: new fields after a trailing span choose rows with effective capacity', async () => {+ const spec = specFor({ columns: 2, fields: ['new_a', 'new_b', 'new_c', 'new_d'] });+ const { section } = await runTwice(spec, existingForm(2, [[cell('a', { rowspan: 3 })]]));+ assertFits(section);+ for (const f of ['new_a', 'new_b', 'new_c', 'new_d']) {+ assert.ok(section.rows.flatMap((r) => r.cells || []).some((c) => c.control && c.control.fieldName === f), `${f} exists`);+ }+});++test('form layout row occupancy: pre-existing overflow does not force new-field placement to a new row', async () => {+ const spec = specFor({ columns: 2, fields: ['new_a', 'new_b', 'new_c', 'new_d', 'new_e'] });+ const { section } = await runTwice(spec, existingForm(2, [[cell('a'), cell('b'), cell('c')], [cell('d')]]));++ assert.deepStrictEqual(section.rows.map((r) => (r.cells || []).map((c) => c.control && c.control.fieldName)),+ [['new_a', 'new_b', 'new_c'], ['new_d', 'new_e']],+ 'the unrelated row-1 overflow must not stop placement from using the roomy last row');+});++test('form layout row occupancy: a too-wide new field can use an empty row despite an unrelated overflow', async () => {+ const spec = specFor({ columns: 2, fields: ['new_a', 'new_b', 'new_c', { name: 'new_e', colspan: 4 }] });+ const { section } = await runTwice(spec, existingForm(2, [[cell('a'), cell('b'), cell('c')], []]));++ const eRow = section.rows.find((r) => (r.cells || []).some((c) => c.control && c.control.fieldName === 'new_e'));+ assert.ok(eRow, 'the new field must be placed');+ assert.strictEqual(section.rows.indexOf(eRow), 1, 'the existing empty last row accepts the clamped wide cell');+});++test('form layout row occupancy: a safe span change is not skipped because another row already overflows', async () => {+ const spec = specFor({ columns: 3, fields: ['new_a', { name: 'new_b', colspan: 2 }, 'new_c', 'new_d', 'new_e', 'new_f'] });+ const { section, second } = await runTwice(spec, existingForm(3, [+ [cell('a', { rowspan: 2 })],+ [cell('b')],+ [cell('c'), cell('d'), cell('e'), cell('f')],+ ]));++ const b = section.rows.flatMap((r) => r.cells || []).find((c) => c.control && c.control.fieldName === 'new_b');+ assert.strictEqual(Number(b.colspan) || 1, 2, "row 2 uses one reserved column plus b's two columns, which fits grid 3");+ assert.deepStrictEqual(second.skipped.layout, [], 'the unrelated row-3 overflow must not make the safe span change look unsafe');+});++test('default Main form promotion demotes only declared sibling defaults', async () => {+ const forms = [+ { entity: 'new_project', name: 'Operations', formType: 'Main' },+ { entity: 'new_project', name: 'Manager', formType: 'Main', isDefault: true },+ ];+ const existing = existingForm(2, [[cell('a')]]);+ const spec = specFor({ columns: 2, fields: ['new_a'], forms });+ const { calls } = await runTwice(spec, existing, { formsByName: {+ Operations: { id: 'form-ops', entity: 'new_project', isdefault: true },+ Manager: { id: 'form-manager', entity: 'new_project', isdefault: false },+ Outside: { id: 'form-outside', entity: 'new_project', isdefault: true },+ Review: { id: 'form-review', entity: 'new_project', isdefault: false },+ } });+ const updates = calls.filter((c) => c.name === 'updateRecord').map((c) => c.args);+ assert.ok(updates.some(([set, id, data]) => set === 'systemform' && id === 'form-manager' && data.isdefault === true), 'chosen form is promoted');+ assert.ok(updates.some(([set, id, data]) => set === 'systemform' && id === 'form-ops' && data.isdefault === false), 'declared default sibling is demoted');+ assert.ok(!updates.some(([, id, data]) => id === 'form-outside' && data.isdefault === false), 'non-spec form is untouched');+ assert.ok(!updates.some(([, id, data]) => id === 'form-review' && data.isdefault === false), 'non-default sibling is untouched');+});++test('default Main form promotion failure skips sibling demotion', async () => {+ const spec = specFor({ columns: 2, fields: ['new_a'], forms: [+ { entity: 'new_project', name: 'Operations', formType: 'Main' },+ { entity: 'new_project', name: 'Manager', formType: 'Main', isDefault: true },+ ] });+ const { calls, warnings } = await runTwice(spec, existingForm(2, [[cell('a')]]), { failPromoteIds: new Set(['form-manager']), formsByName: {+ Operations: { id: 'form-ops', entity: 'new_project', isdefault: true },+ Manager: { id: 'form-manager', entity: 'new_project', isdefault: false },+ } });+ assert.ok(warnings.some((w) => /could not make form the default/.test(w)), JSON.stringify(warnings));+ assert.ok(!calls.some((c) => c.name === 'updateRecord' && c.args[1] === 'form-ops' && c.args[2].isdefault === false), 'no demotion after failed promote');+});++// --- Rows a removal leaves empty -------------------------------------------------------------------+// An empty <row/> renders as a blank line, so a row a pruned or moved field leaves holding nothing is+// removed. A row still holding a slot reserved by a row-spanning cell above is NOT empty, and a row+// that was already empty before this run is not this run's to remove.++const rowShape = (section) => (section.rows || []).map((r) => ((r && r.cells) || []).map((c) => {+ const fn = c.control && c.control.fieldName ? c.control.fieldName.replace(/^new_/, '') : 'spacer';+ return (Number(c.rowspan) || 1) > 1 ? `${fn} rs${c.rowspan}` : fn;+}));+const rowRemovals = (calls) => calls.filter((c) => c.name === 'removeElement' && /\/rows\/\d+$/.test(c.args[2]));++for (const [name, columns, rows, fields, wantShape, wantRowRemovals] of [+ ['pruning the only field in a row removes the row', 2,+ [[cell('a'), cell('b')], [cell('c')], [cell('d')]], ['new_a', 'new_b', 'new_c'], [['a', 'b'], ['c']], 1],+ ['pruning two fields in adjacent rows removes both rows', 4,+ [[cell('a', { rowspan: 2 })], [cell('b'), cell('c')], [cell('d')], [cell('e')]], ['new_a', 'new_b', 'new_c'], [['a rs2'], ['b', 'c']], 2],+ ['an emptied row a span above still reserves is kept', 4,+ [[cell('a', { rowspan: 2 })], [cell('d')], [cell('b'), cell('c')]], ['new_a', 'new_b', 'new_c'], [['a rs2'], [], ['b', 'c']], 0],+ ['pruning a spanning field removes the rows its span left empty', 2,+ [[cell('a'), cell('b')], [cell('d', { rowspan: 2 })], []], ['new_a', 'new_b'], [['a', 'b']], 2],+ ['a row that was already empty is left alone', 2,+ [[cell('a'), cell('b')], [], [cell('c')]], ['new_a', 'new_b'], [['a', 'b'], []], 1],+]) {+ test(`form rows after a prune: ${name}`, async () => {+ const spec = specFor({ columns, fields });+ const { section, calls } = await runTwice(spec, existingForm(columns, rows));+ assert.deepStrictEqual(rowShape(section), wantShape);+ // Both applies ran: the second finds nothing left to remove.+ assert.strictEqual(rowRemovals(calls).length, wantRowRemovals, JSON.stringify(rowRemovals(calls).map((c) => c.args[2])));+ assertFits(section);+ });+}++// The move paths (`fieldOptions[x].after`) remove a row they empty too, and must keep one a span above+// still reserves: deleting it pulled every row beneath it up under the span.+function movedSpec(fields) {+ return specFor({ columns: 2, fields, forms: [{ entity: 'new_project', name: 'Probe', formType: 'Main', layout: 'explicit', prune: false,+ fieldOptions: { new_c: { after: 'new_d' } },+ tabs: [{ name: 'probe', label: 'Probe', sections: [{ name: 'fields', label: 'Fields', columns: 2, fields }] }] }] });+}++test('form rows after a move: a row the moved field emptied is removed', async () => {+ const { section } = await runTwice(movedSpec(['new_a', 'new_b', 'new_d', 'new_e']), existingForm(2, [[cell('a'), cell('b')], [cell('c')], [cell('d'), cell('e')]]));+ assert.deepStrictEqual(rowShape(section), [['a', 'b'], ['d', 'c', 'e']]);+});++test('form rows after a move: an emptied row a span above still reserves is kept', async () => {+ const { section } = await runTwice(movedSpec(['new_a', 'new_b', 'new_d', 'new_e']), existingForm(2, [[cell('a', { rowspan: 2 }), cell('b')], [cell('c')], [cell('d'), cell('e')]]));+ assert.deepStrictEqual(rowShape(section), [['a rs2', 'b'], [], ['d', 'c', 'e']]);+});++test('form rows after a move: a moved spanning field frees the rows its span covered', async () => {+ // Row 2 holds nothing but c's reserved slot. Once c leaves, both of its rows are blank.+ const { section } = await runTwice(movedSpec(['new_a', 'new_b', 'new_d', 'new_e']), existingForm(2, [[cell('a'), cell('b')], [cell('c', { rowspan: 2 })], [], [cell('d'), cell('e')]]));+ assert.deepStrictEqual(rowShape(section), [['a', 'b'], ['d', 'c rs2', 'e']]);+});++// The other move path: a field the layout puts in ANOTHER section is relocated there, and the rows it+// leaves behind in its old section go the same way.+function relocatedSpec() {+ return specFor({ columns: 2, fields: [], forms: [{ entity: 'new_project', name: 'Probe', formType: 'Main', layout: 'explicit',+ tabs: [{ name: 'probe', label: 'Probe', sections: [+ { name: 'fields', label: 'Fields', columns: 2, fields: ['new_a', 'new_b'] },+ { name: 'other', label: 'Other', columns: 1, fields: ['new_c'] },+ ] }] }] });+}+const namedSection = (form, name) => form.tabs.flatMap((t) => t.columns.flatMap((c) => c.sections)).find((s) => s.name === name);++for (const [name, rows, wantShape] of [+ ['the row it emptied is removed', [[cell('a'), cell('b')], [cell('c')]], [['a', 'b']]],+ ['a spanning field frees the rows its span covered', [[cell('a'), cell('b')], [cell('c', { rowspan: 2 })], []], [['a', 'b']]],+ ['an emptied row a span above still reserves is kept', [[cell('a', { rowspan: 2 }), cell('b')], [cell('c')]], [['a rs2', 'b'], []]],+]) {+ test(`form rows after a relocation: ${name}`, async () => {+ const { form } = await runTwice(relocatedSpec(), existingForm(2, rows));+ assert.deepStrictEqual(rowShape(namedSection(form, 'fields')), wantShape);+ assert.deepStrictEqual(rowShape(namedSection(form, 'other')).flat().map((c) => c.split(' ')[0]), ['c'], 'the field did move');+ });+}diff --git a/plugins/model-apps/scripts/tests/sdk-build-pages-deploy.test.js b/plugins/model-apps/scripts/tests/sdk-build-pages-deploy.test.jsindex 11c3a0ea9..548f2053b 100644--- a/plugins/model-apps/scripts/tests/sdk-build-pages-deploy.test.js+++ b/plugins/model-apps/scripts/tests/sdk-build-pages-deploy.test.js@@ -291,6 +291,22 @@ test('deploy: two duplicate-named pages BOTH live (fresh download) build as UPDA// OVERRIDE 2 (new-Important-1): a DYNAMIC nav pageId (e.g. pageId: someVar — a variable, not a literal)// must be rejected BEFORE any write, even when navigatesTo:[] so the existing parity check sees no mismatch.// Only extractNavTargets-based structural detection (kind:'dynamic') catches it. Error code: pages-nav-parity.+test('deploy: trailing spread after nav pageId HALTS before any write', async () => {+ const { appDir, spec } = makeTwoPageApp();+ try {+ fs.writeFileSync(path.join(appDir, 'overview.tsx'),+ `export default function O(){ const options = JSON.parse('{"pageId":"PAGEREF_other"}'); Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "PAGEREF_detail", ...options }); return null; }`,+ 'utf8');+ const { sdk } = mockSdk();+ const genpageCli = mockGenpageCli();+ await assert.rejects(+ runSdkBuild(spec, { sdk, apply: true, env: 'https://x', appDir, genpageCli, phases: PHASES }),+ (e) => e && e.phase === 'pages' && e.code === 'pages-nav-parity'+ );+ assert.strictEqual(genpageCli.uploads.length, 0, 'trailing spread can override pageId at runtime, so the page is rejected before upload');+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }+});+test('deploy: DYNAMIC nav pageId (variable expression) HALTS before any write — new-Important-1 override-2', async () => {const appDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pages-dynav-'));try {diff --git a/plugins/model-apps/scripts/tests/sdk-build.test.js b/plugins/model-apps/scripts/tests/sdk-build.test.jsindex 849c58f45..89ab1e24a 100644--- a/plugins/model-apps/scripts/tests/sdk-build.test.js+++ b/plugins/model-apps/scripts/tests/sdk-build.test.js@@ -1599,6 +1599,21 @@ test('dashboards: chart + list tiles resolve the created view/visualization ids'assert.ok(find(calls, 'addSolutionComponent').some((c) => c.args[0].componentType === 60));});+test('app-shell: a live sitemap target absent from the gate approval halts before the app push', async () => {+ const spec = makeSpec();+ const existingSitemap = { areas: [{ groups: [{ subAreas: [+ { entity: 'new_customer', title: 'Customers' },+ { entity: 'new_ticket', title: 'Tickets' },+ { entity: 'new_late', title: 'Late table' },+ ] }] }] };+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingSitemap });+ await assert.rejects(+ runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'app-shell'], authorizedSitemapRemovals: new Set(['entity:new_ticket']) }),+ (err) => err && /entity:new_late/.test(err.message) && /appeared after the run's approval/.test(err.message)+ );+ assert.ok(!find(calls, 'pushArtifact').some((c) => c.args[0] === 'app'), 'the app is not pushed after an unapproved sitemap removal appears');+});+// Descriptions must survive the BUILD, not just the def builder. A def-builder unit test cannot see// a phase that constructs its own createArtifact payload inline and forgets to forward the field —// which is exactly what both of these did before they were wired.@@ -2245,7 +2260,8 @@ test('form reconcile: an explicit-layout edit REMOVES a field dropped from the sawait runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'] });// Fields are removed via removeElement (retired removeField); pointer encodes field positionconst removals = find(calls, 'removeElement');- assert.deepStrictEqual(removals.map((c) => c.args[2]), ['/tabs/0/columns/0/sections/0/rows/2/cells/0'], 'only the cell for new_obsolete (row 2) is removed');+ // The cell goes, then the row it left holding nothing (a blank <row/> would otherwise stay behind).+ assert.deepStrictEqual(removals.map((c) => c.args[2]), ['/tabs/0/columns/0/sections/0/rows/2/cells/0', '/tabs/0/columns/0/sections/0/rows/2'], 'only new_obsolete (row 2) and the row it emptied are removed');});test('form reconcile: an AUTO layout is additive — a deployed field not in the spec is NOT pruned (Maker adds survive)', async () => {@@ -3059,6 +3075,67 @@ test('form reconcile: an explicit layout still prunes BY DEFAULT (prune:false isassert.ok(find(calls, 'removeElement').length > 0, 'default explicit-layout pruning regressed');});+test('form reconcile: authorized removals prune only fields approved when the run started', async () => {+ const spec = makeSpec();+ spec.forms = [{ entity: 'new_customer', name: 'Customer', layout: 'explicit',+ tabs: [{ label: 'General', sections: [{ label: 'Details', columns: 1, fields: ['new_name'] }] }] }];+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormFields: ['new_name', 'new_tier', 'new_manual'] });+ const warnings = [];+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'], authorizedFormRemovals: new Map([['form-existing', new Set(['new_tier'])]]), warn: (m) => warnings.push(m) });+ // new_tier's cell, then the row it left empty; new_manual's cell and row stay.+ assert.deepStrictEqual(find(calls, 'removeElement').map((c) => c.args[2]), ['/tabs/0/columns/0/sections/0/rows/1/cells/0', '/tabs/0/columns/0/sections/0/rows/1']);+ assert.ok(warnings.some((w) => /new_manual/.test(w) && /not among the removals authorized when this run started/.test(w)), 'the kept field is reported');+});++test('form reconcile: authorized-removal form ids are normalized before fencing', async () => {+ const spec = makeSpec();+ spec.forms = [{ entity: 'new_customer', name: 'Customer', layout: 'explicit',+ tabs: [{ label: 'General', sections: [{ label: 'Details', columns: 1, fields: ['new_name'] }] }] }];+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormFields: ['new_name', 'new_tier', 'new_manual'] });+ const result = await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'], authorizedFormRemovals: new Map([['{FORM-EXISTING}', new Set(['new_tier'])]]) });+ assert.deepStrictEqual(find(calls, 'removeElement').map((c) => c.args[2]), ['/tabs/0/columns/0/sections/0/rows/1/cells/0', '/tabs/0/columns/0/sections/0/rows/1']);+ assert.deepStrictEqual(result.skipped.unauthorizedRemovals, [{ formId: 'form-existing', form: 'Customer', field: 'new_manual' }]);+});++test('form reconcile: an empty authorized set keeps mid-run fields on a form seen by the gate', async () => {+ const spec = makeSpec();+ spec.forms = [{ entity: 'new_customer', name: 'Customer', layout: 'explicit',+ tabs: [{ label: 'General', sections: [{ label: 'Details', columns: 1, fields: ['new_name'] }] }] }];+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormFields: ['new_name', 'new_manual'] });+ const warnings = [];+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'], authorizedFormRemovals: new Map([['form-existing', new Set()]]), warn: (m) => warnings.push(m) });+ assert.strictEqual(find(calls, 'removeElement').length, 0, 'newly appeared field is fenced off');+ assert.ok(warnings.some((w) => /new_manual/.test(w)), 'kept field is reported');+});++test('form reconcile: a supplied authorized-removals map fences forms absent from it', async () => {+ const spec = makeSpec();+ spec.forms = [{ entity: 'new_customer', name: 'Customer', layout: 'explicit',+ tabs: [{ label: 'General', sections: [{ label: 'Details', columns: 1, fields: ['new_name'] }] }] }];+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormFields: ['new_name', 'new_tier'] });+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'], authorizedFormRemovals: new Map() });+ assert.strictEqual(find(calls, 'removeElement').length, 0, 'forms outside a supplied map are fenced with an empty approval set');+});++test('form reconcile: a supplied map fences a form id absent from the gate snapshot', async () => {+ const spec = makeSpec();+ spec.forms = [{ entity: 'new_customer', name: 'Customer', layout: 'explicit',+ tabs: [{ label: 'General', sections: [{ label: 'Details', columns: 1, fields: ['new_name'] }] }] }];+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormFields: ['new_name', 'new_late'] });+ const result = await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'], authorizedFormRemovals: new Map() });+ assert.strictEqual(find(calls, 'removeElement').length, 0, 'a form absent from the gate-time map is fenced with an empty set');+ assert.deepStrictEqual(result.skipped.unauthorizedRemovals, [{ formId: 'form-existing', form: 'Customer', field: 'new_late' }]);+});++test('form reconcile: no authorized-removals map prunes as before', async () => {+ const spec = makeSpec();+ spec.forms = [{ entity: 'new_customer', name: 'Customer', layout: 'explicit',+ tabs: [{ label: 'General', sections: [{ label: 'Details', columns: 1, fields: ['new_name'] }] }] }];+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormFields: ['new_name', 'new_tier'] });+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'] });+ assert.ok(find(calls, 'removeElement').length > 0, 'legacy behavior remains when the gate did not supply a fence');+});+test('form build: a BigInt column is never added to a form by the auto layout', async () => {const spec = makeSpec();spec.entities[0].columns.push({ schemaName: 'new_tracking', displayName: 'Tracking', type: 'BigInt' });@@ -5440,7 +5517,7 @@ test('form topology: WIDENING a section grid leaves its existing rows untouched'// cannot express that reservation — and the authored-rowspan restriction does not help, because// the span belongs to the fetched MAKER form, not to the spec. Refusing is the recoverable// outcome; silently rearranging a maker's form is not.-test('form topology: a narrowing that the rows already fit is applied without moving any cell', async () => {+test('form topology: a narrowing whose carried spacer would overflow keeps the old grid', async () => {const spec = makeSpec();spec.entities[0].columns.push({ schemaName: 'new_code', displayName: 'Code', type: 'Text' },@@ -5464,15 +5541,16 @@ test('form topology: a narrowing that the rows already fit is applied without moconst { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: deployed });const res = await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'], warn: (m) => warnings.push(String(m)) });- const formCall = calls.find((c) => (c.name === 'updateElement' || c.name === 'addElement') && c.args[0] === 'form');- const finalForm = await sdk.getArtifact('form', formCall.args[1]);+ assert.ok(!calls.some((c) => (c.name === 'updateElement' || c.name === 'addElement') && c.args[0] === 'form'),+ `no form write may be issued; got ${JSON.stringify(calls.filter((c) => c.args && c.args[0] === 'form').map((c) => c.name))}`);+ const finalForm = await sdk.getArtifact('form', 'form-existing');const sec = finalForm.tabs[0].columns[0].sections[0];const shape = (sec.rows || []).map((r) => (r.cells || []).map((c) => (c.control && c.control.fieldName) || '(spacer)'));assert.deepStrictEqual(shape,[['new_name'], ['(spacer)', 'new_tier'], ['new_code', 'new_note']],- `no cell may move — every row already fits the narrower grid; got ${JSON.stringify(shape)}`);- assert.strictEqual(Number(sec.columns), 2, 'the narrower grid IS applied: nothing about it needs a reflow');- assert.deepStrictEqual(res.skipped.layout, [], 'nothing was refused, so nothing is reported as skipped');+ `no cell may move when the narrowing is skipped; got ${JSON.stringify(shape)}`);+ assert.strictEqual(Number(sec.columns), 4, 'the old grid is kept because row 2 needs one reserved plus two own columns');+ assert.ok(res.skipped.layout.some((m) => /narrowing it/.test(m)), `the refusal must be recorded; got ${JSON.stringify(res.skipped.layout)}`);});// When the rows would NOT fit the narrower grid, the width must not be written either. Writing itdiff --git a/plugins/model-apps/scripts/tests/sdk-http-client.test.js b/plugins/model-apps/scripts/tests/sdk-http-client.test.jsindex 3d089b4f7..f2a696aee 100644--- a/plugins/model-apps/scripts/tests/sdk-http-client.test.js+++ b/plugins/model-apps/scripts/tests/sdk-http-client.test.js@@ -38,16 +38,16 @@ test('POST stringifies the body and sets Content-Type', async () => {test('merges per-call headers (solution + If-Match) and keeps caller Content-Type', async () => {const { request, calls } = fakeTransport({ statusCode: 204, headers: {}, body: '' });- const http = createAzHttpClient('https://org', { getToken: () => 'TOK', request });- await http.patch('https://org/x', { a: 1 }, { headers: { 'MSCRM.SolutionUniqueName': 'MyS', 'If-Match': 'W/"7"' } });+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request });+ await http.patch('https://org.crm.dynamics.com/x', { a: 1 }, { headers: { 'MSCRM.SolutionUniqueName': 'MyS', 'If-Match': 'W/"7"' } });assert.strictEqual(calls[0].headers['MSCRM.SolutionUniqueName'], 'MyS');assert.strictEqual(calls[0].headers['If-Match'], 'W/"7"');});test('does NOT throw on non-2xx — passes status/body through (412 version conflict)', async () => {const { request } = fakeTransport({ statusCode: 412, headers: {}, body: '{"error":{"message":"conflict"}}' });- const http = createAzHttpClient('https://org', { getToken: () => 'TOK', request });- const res = await http.put('https://org/x', { a: 1 });+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request });+ const res = await http.put('https://org.crm.dynamics.com/x', { a: 1 });assert.strictEqual(res.status, 412);assert.strictEqual(res.body.error.message, 'conflict');});@@ -59,28 +59,49 @@ test('refreshes token once on 401 then succeeds', async () => {? { statusCode: 401, headers: {}, body: '' }: { statusCode: 200, headers: {}, body: '{"ok":true}' };});- const http = createAzHttpClient('https://org', { getToken: () => `T${++tokens}`, request });- const res = await http.get('https://org/x');+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => `T${++tokens}`, request });+ const res = await http.get('https://org.crm.dynamics.com/x');assert.strictEqual(res.status, 200);assert.strictEqual(calls.length, 2);assert.strictEqual(calls[0].headers.Authorization, 'Bearer T1');assert.strictEqual(calls[1].headers.Authorization, 'Bearer T2'); // refreshed});++test('refreshes token with a fresh acquire on 401, bypassing any process memo', async () => {+ const tokenCalls = [];+ const { request, calls } = fakeTransport(() => {+ return calls.length === 1+ ? { statusCode: 401, headers: {}, body: '' }+ : { statusCode: 200, headers: {}, body: '{"ok":true}' };+ });+ const http = createAzHttpClient('https://org.crm.dynamics.com', {+ getToken: (_url, options) => {+ tokenCalls.push(Boolean(options && options.fresh));+ return tokenCalls.length === 1 ? 'OLD' : 'NEW';+ },+ request,+ });+ const res = await http.get('https://org.crm.dynamics.com/api/data/v9.2/accounts');+ assert.strictEqual(res.status, 200);+ assert.deepStrictEqual(tokenCalls, [false, true]);+ assert.deepStrictEqual(calls.map((c) => c.headers.Authorization), ['Bearer OLD', 'Bearer NEW']);+});+test('retries a transient 500 (SQL deadlock) with backoff, then succeeds', async () => {const { request, calls } = fakeTransport(() =>calls.length <= 2 ? { statusCode: 500, headers: {}, body: 'deadlock 1205' } : { statusCode: 200, headers: {}, body: '{"ok":true}' });- const http = createAzHttpClient('https://org', { getToken: () => 'TOK', request, sleep: async () => {} });- const res = await http.post('https://org/x', { a: 1 });+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request, sleep: async () => {} });+ const res = await http.post('https://org.crm.dynamics.com/x', { a: 1 });assert.strictEqual(res.status, 200);assert.strictEqual(calls.length, 3); // 500, 500, 200});test('gives up after max attempts on a persistent 500 — surfaces it (no throw)', async () => {const { request, calls } = fakeTransport({ statusCode: 500, headers: {}, body: 'boom' });- const http = createAzHttpClient('https://org', { getToken: () => 'TOK', request, sleep: async () => {} });- const res = await http.get('https://org/x');+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request, sleep: async () => {} });+ const res = await http.get('https://org.crm.dynamics.com/x');assert.strictEqual(res.status, 500); // the SDK decides what to do with itassert.strictEqual(calls.length, 6);});@@ -91,8 +112,8 @@ test('retries a 429 EntityCustomization lock and eventually succeeds', async ()? { statusCode: 429, headers: {}, body: 'Cannot start another [EntityCustomization]' }: { statusCode: 200, headers: {}, body: '{"ok":true}' });- const http = createAzHttpClient('https://org', { getToken: () => 'TOK', request, sleep: async () => {} });- const res = await http.post('https://org/x', { a: 1 });+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request, sleep: async () => {} });+ const res = await http.post('https://org.crm.dynamics.com/x', { a: 1 });assert.strictEqual(res.status, 200);assert.strictEqual(calls.length, 5); // 429 x4, then 200 — needs the extra attempts (>4)});@@ -101,19 +122,19 @@ test('applies jittered, capped backoff on transient retries (de-syncs lockstep cconst slept = [];// random() = 0.5 -> +12.5% jitter; caps exponential at 8000ms.const { request } = fakeTransport({ statusCode: 503, headers: {}, body: '' });- const http = createAzHttpClient('https://org', {+ const http = createAzHttpClient('https://org.crm.dynamics.com', {getToken: () => 'TOK', request, random: () => 0.5,sleep: async (ms) => { slept.push(ms); },});- await http.get('https://org/x');+ await http.get('https://org.crm.dynamics.com/x');// 5 sleeps before the 6th (final) attempt: base 1s,2s,4s,8s,8s each + 12.5% jitter.assert.deepStrictEqual(slept, [1125, 2250, 4500, 9000, 9000]);});test('does NOT retry a RECORD delete on a transient status (avoids the async concurrent-delete wedge)', async () => {const { request, calls } = fakeTransport({ statusCode: 503, headers: {}, body: '' });- const http = createAzHttpClient('https://org', { getToken: () => 'TOK', request, sleep: async () => {} });- const res = await http.delete('https://org/api/data/v9.0/webresourceset(1)');+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request, sleep: async () => {} });+ const res = await http.delete('https://org.crm.dynamics.com/api/data/v9.0/webresourceset(1)');assert.strictEqual(res.status, 503, 'the transient status surfaces instead of being retried');assert.strictEqual(calls.length, 1, 'exactly one record DELETE was sent (no retry)');});@@ -121,8 +142,8 @@ test('does NOT retry a RECORD delete on a transient status (avoids the async contest('does NOT retry a RECORD delete on a network error either (single delete, no wedge)', async () => {let calls = 0;const request = async () => { calls += 1; return { error: 'ETIMEDOUT' }; };- const http = createAzHttpClient('https://org', { getToken: () => 'TOK', request, sleep: async () => {} });- await assert.rejects(() => http.delete('https://org/api/data/v9.0/webresourceset(1)'), /Request failed: ETIMEDOUT/);+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request, sleep: async () => {} });+ await assert.rejects(() => http.delete('https://org.crm.dynamics.com/api/data/v9.0/webresourceset(1)'), /Request failed: ETIMEDOUT/);assert.strictEqual(calls, 1, 'exactly one record DELETE was sent (no network-error retry)');});@@ -130,8 +151,8 @@ test('DOES retry a METADATA delete (EntityDefinitions) on a network error — asconst { request, calls } = fakeTransport(() =>calls.length <= 1 ? { error: 'ETIMEDOUT' } : { statusCode: 404, headers: {}, body: '' });- const http = createAzHttpClient('https://org', { getToken: () => 'TOK', request, sleep: async () => {} });- const res = await http.delete("https://org/api/data/v9.0/EntityDefinitions(LogicalName='new_x')");+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request, sleep: async () => {} });+ const res = await http.delete("https://org.crm.dynamics.com/api/data/v9.0/EntityDefinitions(LogicalName='new_x')");assert.strictEqual(res.status, 404, 'a slow metadata delete is retried rather than surfacing a false timeout');assert.strictEqual(calls.length, 2);});@@ -140,12 +161,12 @@ test('DOES retry a METADATA delete (EntityDefinitions) on a network error — as// reads. Measured live: a business process flow activation on a fresh table ran past the old 60 s.test('a WRITE waits far longer than a read before giving up', async () => {const { request, calls } = fakeTransport({ statusCode: 204, headers: {}, body: '' });- const http = createAzHttpClient('https://org', { getToken: () => 'TOK', request });- await http.get('https://org/x');- await http.post('https://org/x', { a: 1 });- await http.patch('https://org/x', { a: 1 });- await http.put('https://org/x', { a: 1 });- await http.delete('https://org/x');+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request });+ await http.get('https://org.crm.dynamics.com/x');+ await http.post('https://org.crm.dynamics.com/x', { a: 1 });+ await http.patch('https://org.crm.dynamics.com/x', { a: 1 });+ await http.put('https://org.crm.dynamics.com/x', { a: 1 });+ await http.delete('https://org.crm.dynamics.com/x');const [get, ...writes] = calls.map((c) => c.timeout);assert.strictEqual(get, 60000, 'a read keeps the short timeout — it is safe to abandon and re-issue');for (const t of writes) assert.ok(t >= 120000, `every write must wait well past 60 s; got ${t}`);@@ -156,9 +177,9 @@ test('a WRITE waits far longer than a read before giving up', async () => {test('a CONDITIONAL write that got no answer is NOT re-sent (it may still commit)', async () => {for (const header of ['If-Match', 'if-match']) {const { request, calls } = fakeTransport({ error: 'Request timed out' });- const http = createAzHttpClient('https://org', { getToken: () => 'TOK', request, sleep: async () => {} });+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request, sleep: async () => {} });await assert.rejects(- () => http.patch('https://org/api/data/v9.2/workflows(1)', { statecode: 1 }, { headers: { [header]: 'W/"5"' } }),+ () => http.patch('https://org.crm.dynamics.com/api/data/v9.2/workflows(1)', { statecode: 1 }, { headers: { [header]: 'W/"5"' } }),/Request failed: Request timed out .*not re-sent/);assert.strictEqual(calls.length, 1, `exactly one conditional PATCH may be sent (header spelled ${header})`);}@@ -166,24 +187,24 @@ test('a CONDITIONAL write that got no answer is NOT re-sent (it may still committest('the no-re-send rule is scoped: an UNCONDITIONAL write that got no answer is still retried', async () => {const { request, calls } = fakeTransport(() => (calls.length <= 1 ? { error: 'ETIMEDOUT' } : { statusCode: 204, headers: {}, body: '' }));- const http = createAzHttpClient('https://org', { getToken: () => 'TOK', request, sleep: async () => {} });- const res = await http.patch('https://org/api/data/v9.2/workflows(1)', { statecode: 1 });+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request, sleep: async () => {} });+ const res = await http.patch('https://org.crm.dynamics.com/api/data/v9.2/workflows(1)', { statecode: 1 });assert.strictEqual(res.status, 204);assert.strictEqual(calls.length, 2);});test('a CONDITIONAL write that got an ANSWER keeps the status retry (429 means it was never processed)', async () => {const { request, calls } = fakeTransport(() => (calls.length <= 1 ? { statusCode: 429, headers: {}, body: '' } : { statusCode: 204, headers: {}, body: '' }));- const http = createAzHttpClient('https://org', { getToken: () => 'TOK', request, sleep: async () => {} });- const res = await http.patch('https://org/x', { a: 1 }, { headers: { 'If-Match': 'W/"5"' } });+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request, sleep: async () => {} });+ const res = await http.patch('https://org.crm.dynamics.com/x', { a: 1 }, { headers: { 'If-Match': 'W/"5"' } });assert.strictEqual(res.status, 204, 'a throttled conditional write is retried');assert.strictEqual(calls.length, 2);});test('throws only when no token is available', async () => {const { request } = fakeTransport({ statusCode: 200, headers: {}, body: '{}' });- const http = createAzHttpClient('https://org', { getToken: () => null, request });- await assert.rejects(() => http.get('https://org/x'), /Failed to get Azure CLI token/);+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => null, request });+ await assert.rejects(() => http.get('https://org.crm.dynamics.com/x'), /Failed to get Azure CLI token/);});test('refuses to send the Dataverse token to a different origin (same-origin guard)', async () => {@@ -259,8 +280,8 @@ test('postRaw never JSON-parses a body that happens to be valid JSON', async ()// parseBody() would turn this into an object and the SDK would throw ConnectionError// ("body is not a string"). postRaw must bypass parsing unconditionally, not by accident.const { request } = fakeTransport({ statusCode: 200, headers: {}, body: '{"not":"multipart"}' });- const http = createAzHttpClient('https://org', { getToken: () => 'TOK', request });- const res = await http.postRaw('https://org/api/data/v9.2/$batch', 'x', { headers: { 'Content-Type': 'multipart/mixed;boundary=b' } });+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request });+ const res = await http.postRaw('https://org.crm.dynamics.com/api/data/v9.2/$batch', 'x', { headers: { 'Content-Type': 'multipart/mixed;boundary=b' } });assert.strictEqual(typeof res.body, 'string');assert.strictEqual(res.body, '{"not":"multipart"}');});@@ -270,17 +291,17 @@ test('postRaw does NOT retry a $batch on a transient status (the change set cont// detected" guard permanently wedges a row when a retry races the still-in-flight first delete.// A $batch carries DELETEs inside a POST, so the method-based noRetry rule must cover it too.const { request, calls } = fakeTransport({ statusCode: 503, headers: {}, body: 'busy' });- const http = createAzHttpClient('https://org', { getToken: () => 'TOK', request, sleep: async () => {} });- const res = await http.postRaw('https://org/api/data/v9.2/$batch', 'x', { headers: { 'Content-Type': 'multipart/mixed;boundary=b' } });+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request, sleep: async () => {} });+ const res = await http.postRaw('https://org.crm.dynamics.com/api/data/v9.2/$batch', 'x', { headers: { 'Content-Type': 'multipart/mixed;boundary=b' } });assert.strictEqual(calls.length, 1, 'a $batch is issued exactly once');assert.strictEqual(res.status, 503, 'the transient status is surfaced, not retried away');});test('postRaw does NOT retry a $batch on a network error either', async () => {const { request, calls } = fakeTransport({ error: 'ETIMEDOUT' });- const http = createAzHttpClient('https://org', { getToken: () => 'TOK', request, sleep: async () => {} });+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request, sleep: async () => {} });await assert.rejects(- () => http.postRaw('https://org/api/data/v9.2/$batch', 'x', { headers: { 'Content-Type': 'multipart/mixed;boundary=b' } }),+ () => http.postRaw('https://org.crm.dynamics.com/api/data/v9.2/$batch', 'x', { headers: { 'Content-Type': 'multipart/mixed;boundary=b' } }),/Request failed/);assert.strictEqual(calls.length, 1, 'an ambiguous batch outcome is never re-issued blindly');@@ -291,8 +312,8 @@ test('postRaw still refreshes the token once on 401 (rejected before processing,calls.length <= 1 ? { statusCode: 401, headers: {}, body: '' } : { statusCode: 200, headers: {}, body: BATCH_RESPONSE });let tokens = 0;- const http = createAzHttpClient('https://org', { getToken: () => `TOK${++tokens}`, request, sleep: async () => {} });- const res = await http.postRaw('https://org/api/data/v9.2/$batch', 'x', { headers: { 'Content-Type': 'multipart/mixed;boundary=b' } });+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => `TOK${++tokens}`, request, sleep: async () => {} });+ const res = await http.postRaw('https://org.crm.dynamics.com/api/data/v9.2/$batch', 'x', { headers: { 'Content-Type': 'multipart/mixed;boundary=b' } });assert.strictEqual(calls.length, 2);assert.strictEqual(calls[1].headers.Authorization, 'Bearer TOK2', 'the retry carries a fresh token');assert.strictEqual(res.body, BATCH_RESPONSE);diff --git a/plugins/model-apps/scripts/tests/telemetry-lib-copy.test.js b/plugins/model-apps/scripts/tests/telemetry-lib-copy.test.jsnew file mode 100644index 000000000..ca4d0c5b6--- /dev/null+++ b/plugins/model-apps/scripts/tests/telemetry-lib-copy.test.js@@ -0,0 +1,77 @@+'use strict';++// Guards the plugin's BUNDLED copies of shared code and shared skill text.+//+// Marketplace installs copy only the plugin directory, so model-apps carries physical copies of+// * `shared/telemetry/lib` at `scripts/lib/telemetry/lib` (the 1DS library its hooks require), and+// * the shared skill workflows at `skills/telemetry/` and `skills/report-issue/`.+// Nothing else in model-apps CI compares them with their source: `shared/telemetry/tests` has no+// workflow of its own. So an edit to one side that forgets the other gives a green build while the+// plugin ships stale code, or a stale disclosure. That happened to the telemetry workflow's+// disclosure: a Power Pages change updated its own copy and not the shared source. This suite turns+// that silent drift into a failure. It mirrors the Power Pages guard of the same name. The workflow's+// path filter includes `shared/telemetry/**` and `shared/skills/**`, so a change on either side runs it.+//+// This plugin's own `ikey.json` is deliberately NOT compared: each plugin provisions its own key and+// event stream, and copying another plugin's is exactly the mistake the repo rules forbid.++const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const { spawnSync } = require('node:child_process');++const PLUGIN_ROOT = path.resolve(__dirname, '..', '..');+const REPO_ROOT = path.resolve(PLUGIN_ROOT, '..', '..');+const PLUGIN_LIB = path.join(PLUGIN_ROOT, 'scripts', 'lib', 'telemetry', 'lib');+const SHARED_LIB = path.join(REPO_ROOT, 'shared', 'telemetry', 'lib');++// Line endings are a checkout detail (a Windows checkout may convert them), so text is compared with+// them normalized. The library comparison is byte-for-byte as committed, like the Power Pages guard.+const text = (file) => fs.readFileSync(file, 'utf8').replace(/\r\n/g, '\n');++test('bundled telemetry lib is identical to shared/telemetry/lib', (t) => {+ // An installed plugin has no `shared/` next to it; the check means something only in a repo checkout.+ if (!fs.existsSync(SHARED_LIB)) {+ t.skip('shared/telemetry/lib not present (installed plugin, not a repo checkout)');+ return;+ }+ const sharedFiles = fs.readdirSync(SHARED_LIB).filter((f) => f.endsWith('.js')).sort();+ const pluginFiles = fs.readdirSync(PLUGIN_LIB).filter((f) => f.endsWith('.js')).sort();+ assert.deepEqual(pluginFiles, sharedFiles, 'plugin copy and shared source must contain the same modules — refresh the copy');+ const drifted = sharedFiles.filter((f) => text(path.join(SHARED_LIB, f)) !== text(path.join(PLUGIN_LIB, f)));+ assert.deepEqual(drifted, [], 'bundled copy has drifted from shared/telemetry/lib — re-copy these files');+});++test('bundled shared skill workflows match their shared source', (t) => {+ const pairs = [+ ['telemetry', 'telemetry-workflow.md'],+ ['report-issue', 'report-issue-workflow.md'],+ ];+ if (!fs.existsSync(path.join(REPO_ROOT, 'shared', 'skills'))) {+ t.skip('shared/skills not present (installed plugin, not a repo checkout)');+ return;+ }+ const drifted = pairs.filter(([skill, file]) =>+ text(path.join(REPO_ROOT, 'shared', 'skills', skill, file)) !== text(path.join(PLUGIN_ROOT, 'skills', skill, file)));+ assert.deepEqual(drifted.map(([skill, file]) => `skills/${skill}/${file}`), [],+ 'edit shared/skills first, then copy the workflow into every plugin that bundles it');+});++test('the telemetry status disclosure says Model Apps sends no user identifier', () => {+ // The /telemetry skill shows this output verbatim, so it is the user-facing privacy statement. The+ // Power Pages-only fields (the Entra object id and the site framework) must never be claimed here.+ const configDir = fs.mkdtempSync(path.join(os.tmpdir(), 'model-apps-disclosure-'));+ try {+ const result = spawnSync(process.execPath, [path.join(PLUGIN_LIB, 'telemetry-config.js'), '--action', 'status', '--plugin', 'model-apps'], {+ encoding: 'utf8',+ env: { ...process.env, POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir, POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: '' },+ });+ assert.equal(result.status, 0, result.stderr);+ assert.match(result.stdout, /Model Apps excludes the signed-in user's Entra object ID/);+ assert.doesNotMatch(result.stdout, /aadObjectId|eventInfo\.framework/);+ } finally {+ fs.rmSync(configDir, { recursive: true, force: true });+ }+});diff --git a/plugins/model-apps/scripts/tests/telemetry-native-exec.test.js b/plugins/model-apps/scripts/tests/telemetry-native-exec.test.jsnew file mode 100644index 000000000..5c0cd6da0--- /dev/null+++ b/plugins/model-apps/scripts/tests/telemetry-native-exec.test.js@@ -0,0 +1,94 @@+'use strict';+// The bundled shared telemetry library starts pac through native-exec.js: by absolute path from+// PATH, never by bare name. The hooks run in the user's project folder, and Node 20 on Windows looks+// for a bare command name in the working directory before PATH, so a `pac.exe` in a project would+// otherwise run instead of the real one. (This file tests the model-apps copy, which+// telemetry-lib-copy.test.js keeps identical to shared/telemetry/lib.)+const { test } = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');++const LIB = path.join(__dirname, '..', 'lib', 'telemetry', 'lib');+const { resolveNative, runNative } = require(path.join(LIB, 'native-exec.js'));++test('resolveNative looks only in absolute PATH entries, never the working directory', () => {+ const probed = [];+ const exists = (p) => { probed.push(p); return false; };+ assert.equal(resolveNative('pac', { platform: 'win32', env: { Path: '.;tools;;C:\\bin' }, exists }), null);+ assert.deepEqual(probed, ['C:\\bin\\pac.com', 'C:\\bin\\pac.exe']);+ probed.length = 0;+ assert.equal(resolveNative('pac', { platform: 'linux', env: { PATH: ':.:bin:/usr/bin' }, exists }), null);+ assert.deepEqual(probed, ['/usr/bin/pac'], 'an empty POSIX entry means the current directory, and is skipped');+});++test('resolveNative tries .com then .exe on Windows whatever PATHEXT says, and never a batch file', () => {+ const files = new Set(['C:\\a\\pac.cmd', 'C:\\b\\pac.com', 'C:\\b\\pac.exe', 'C:\\c\\pac.exe']);+ const exists = (p) => files.has(p);+ const env = { Path: 'C:\\a;C:\\b', PATHEXT: '.COM;.EXE;.BAT;.CMD' };+ assert.equal(resolveNative('pac', { platform: 'win32', env, exists }), 'C:\\b\\pac.com', 'a pac.cmd earlier on PATH is not a native executable');+ // Node's shell-free lookup ignores PATHEXT, so an unusual value must not hide a working pac.exe.+ assert.equal(resolveNative('pac', { platform: 'win32', env: { Path: 'C:\\c', PATHEXT: '.CMD;.BAT' }, exists }), 'C:\\c\\pac.exe');+});++test('a non-executable pac earlier on PATH does not hide a runnable one (macOS/Linux)', { skip: process.platform === 'win32' }, () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'native-exec-x-'));+ try {+ const first = path.join(root, 'first');+ const second = path.join(root, 'second');+ fs.mkdirSync(first);+ fs.mkdirSync(second);+ fs.writeFileSync(path.join(first, 'pac'), '#!/bin/sh\n', { mode: 0o644 });+ fs.writeFileSync(path.join(second, 'pac'), '#!/bin/sh\n', { mode: 0o755 });+ assert.equal(resolveNative('pac', { env: { PATH: `${first}:${second}` } }), path.join(second, 'pac'));+ } finally {+ fs.rmSync(root, { recursive: true, force: true });+ }+});++test('the default predicate is what skips a candidate that cannot be run', () => {+ // Platform-independent: the second candidate is chosen when the first is rejected.+ const exists = (p) => p === '/b/pac';+ assert.equal(resolveNative('pac', { platform: 'linux', env: { PATH: '/a:/b' }, exists }), '/b/pac');+});++test('resolveNative reads the PATH spelling Node passes a Windows child', () => {+ const exists = (p) => p === 'C:\\new\\pac.exe' || p === 'C:\\old\\pac.exe';+ assert.equal(resolveNative('pac', { platform: 'win32', env: { Path: 'C:\\old', PATH: 'C:\\new' }, exists }), 'C:\\new\\pac.exe');+});++test('runNative reports a missing tool as ENOENT without starting anything', () => {+ assert.throws(() => runNative('pac', ['auth', 'who'], {}, { platform: 'linux', env: { PATH: '/nowhere' }, exists: () => false }),+ (e) => e.code === 'ENOENT');+});++test('pac-auth and agent-info start pac only through native-exec', () => {+ for (const file of ['pac-auth.js', 'agent-info.js']) {+ const src = fs.readFileSync(path.join(LIB, file), 'utf8');+ assert.doesNotMatch(src, /require\(["'](?:node:)?child_process["']\)/, `${file} must not start processes itself`);+ assert.match(src, /require\("\.\/native-exec"\)/, `${file} must use native-exec`);+ }+});++test('a pac.exe in the working directory is never run (real Windows lookup)', { skip: process.platform !== 'win32' }, () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'native-exec-'));+ const project = path.join(root, 'project');+ const tools = path.join(root, 'tools');+ fs.mkdirSync(project);+ fs.mkdirSync(tools);+ // A copy of node stands in for a planted pac: if it ran, `-p` would print its own path.+ fs.copyFileSync(process.execPath, path.join(project, 'nativeprobe.exe'));+ const saved = process.cwd();+ try {+ process.chdir(project);+ assert.throws(() => runNative('nativeprobe', ['-p', 'process.execPath'], { encoding: 'utf8' }, { env: { Path: tools, PATHEXT: '.EXE' } }),+ (e) => e.code === 'ENOENT', 'the copy in the working directory must not be found');+ fs.copyFileSync(process.execPath, path.join(tools, 'nativeprobe.exe'));+ const out = runNative('nativeprobe', ['-p', 'process.execPath'], { encoding: 'utf8', timeout: 30000 }, { env: { Path: tools, PATHEXT: '.EXE' } });+ assert.equal(String(out).trim(), path.join(tools, 'nativeprobe.exe'), 'the one on PATH runs');+ } finally {+ process.chdir(saved);+ try { fs.rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }); } catch { /* left in the OS temp dir */ }+ }+});diff --git a/plugins/model-apps/scripts/tests/validate-icon-imports.test.js b/plugins/model-apps/scripts/tests/validate-icon-imports.test.jsindex 980205ef1..638d7bd9d 100644--- a/plugins/model-apps/scripts/tests/validate-icon-imports.test.js+++ b/plugins/model-apps/scripts/tests/validate-icon-imports.test.js@@ -377,6 +377,58 @@ test('MODEL_APPS_DISABLE_HOOKS=1 disables the validator (exit 0 despite bad iconassert.equal(status, 0);});+test('MODEL_APPS_DISABLE_HOOKS=1 exits 0 even when skill discovery would throw', () => {+ const preload = path.join(__dirname, 'hook-readdir-throw-preload.js');+ fs.writeFileSync(preload, [+ "const fs = require('node:fs');",+ 'const real = fs.readdirSync;',+ "fs.readdirSync = function patched(p, ...args) {",+ " if (String(p).includes('plugins' + require('node:path').sep + 'model-apps' + require('node:path').sep + 'skills')) {",+ " const err = new Error('EACCES: permission denied, scandir skills');",+ " err.code = 'EACCES';",+ " throw err;",+ ' }',+ ' return real.call(this, p, ...args);',+ '};',+ ].join('\n'));+ try {+ const res = spawnSync(process.execPath, ['-r', preload, HOOK], {+ input: 'not json',+ encoding: 'utf8',+ env: { ...process.env, MODEL_APPS_DISABLE_HOOKS: '1' },+ });+ assert.equal(res.status, 0, res.stderr);+ } finally {+ fs.rmSync(preload, { force: true });+ }+});++test('icon validator: an unreadable skills folder cannot crash the ENABLED hook', () => {+ // The hook needs only the stdin reader, not skill discovery. Loading discovery would scan the skills+ // folder at require time, so an EACCES there would crash the hook even though it never uses it.+ const preload = path.join(__dirname, 'hook-readdir-throw-preload-enabled.js');+ fs.writeFileSync(preload, [+ "const fs = require('node:fs');",+ 'const real = fs.readdirSync;',+ "fs.readdirSync = function patched(p, ...args) {",+ " if (String(p).includes('plugins' + require('node:path').sep + 'model-apps' + require('node:path').sep + 'skills')) {",+ " const err = new Error('EACCES: permission denied, scandir skills');",+ " err.code = 'EACCES';",+ " throw err;",+ ' }',+ ' return real.call(this, p, ...args);',+ '};',+ ].join('\n'));+ try {+ const env = { ...process.env };+ delete env.MODEL_APPS_DISABLE_HOOKS;+ const res = spawnSync(process.execPath, ['-r', preload, HOOK], { input: 'not json', encoding: 'utf8', env });+ assert.equal(res.status, 0, res.stderr);+ } finally {+ fs.rmSync(preload, { force: true });+ }+});+test('unparseable stdin does not block (exit 0)', () => {const res = spawnSync(process.execPath, [HOOK], { input: 'not json', encoding: 'utf8' });assert.equal(res.status, 0);diff --git a/plugins/model-apps/scripts/tests/validate-write-safety.test.js b/plugins/model-apps/scripts/tests/validate-write-safety.test.jsindex 20ab1e988..a46b6a66a 100644--- a/plugins/model-apps/scripts/tests/validate-write-safety.test.js+++ b/plugins/model-apps/scripts/tests/validate-write-safety.test.js@@ -16,6 +16,33 @@ function runHook(payload, env) {return { status: res.status, stderr: res.stderr || '' };}+function runHookWithSplitStdin(payload, splitNeedle) {+ return new Promise((resolve, reject) => {+ const child = require('node:child_process').spawn(process.execPath, [HOOK], {+ env: { ...process.env },+ stdio: ['pipe', 'pipe', 'pipe'],+ });+ const stdout = [];+ const stderr = [];+ child.stdout.on('data', (chunk) => stdout.push(chunk));+ child.stderr.on('data', (chunk) => stderr.push(chunk));+ child.on('error', reject);+ child.on('close', (status) => {+ resolve({+ status,+ stdout: Buffer.concat(stdout).toString('utf8'),+ stderr: Buffer.concat(stderr).toString('utf8'),+ });+ });+ const bytes = Buffer.from(JSON.stringify(payload), 'utf8');+ const needle = Buffer.from(splitNeedle, 'utf8');+ const at = bytes.indexOf(needle);+ assert.notEqual(at, -1, 'payload must contain the split needle');+ child.stdin.write(bytes.subarray(0, at + 1));+ setImmediate(() => child.stdin.end(bytes.subarray(at + 1)));+ });+}+let cwd;test.beforeEach(() => {cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'genpage-ws-'));@@ -143,6 +170,69 @@ test('MODEL_APPS_DISABLE_HOOKS=1 disables the guard (exit 0 for an outside writeassert.equal(runHook(payload, { MODEL_APPS_DISABLE_HOOKS: '1' }).status, 0);});+test('MODEL_APPS_DISABLE_HOOKS=1 exits 0 even when skill discovery would throw', () => {+ const preload = path.join(__dirname, 'hook-readdir-throw-preload.js');+ fs.writeFileSync(preload, [+ "const fs = require('node:fs');",+ 'const real = fs.readdirSync;',+ "fs.readdirSync = function patched(p, ...args) {",+ " if (String(p).includes('plugins' + require('node:path').sep + 'model-apps' + require('node:path').sep + 'skills')) {",+ " const err = new Error('EACCES: permission denied, scandir skills');",+ " err.code = 'EACCES';",+ " throw err;",+ ' }',+ ' return real.call(this, p, ...args);',+ '};',+ ].join('\n'));+ try {+ const outside = path.join(path.parse(cwd).root, 'model-apps-guard-evil', 'evil.ts');+ const payload = { tool_name: 'Write', tool_input: { file_path: outside, content: 'x' }, cwd };+ const res = spawnSync(process.execPath, ['-r', preload, HOOK], {+ input: JSON.stringify(payload),+ encoding: 'utf8',+ env: { ...process.env, MODEL_APPS_DISABLE_HOOKS: '1' },+ });+ assert.equal(res.status, 0, res.stderr);+ } finally {+ fs.rmSync(preload, { force: true });+ }+});++test('write-safety guard: an unreadable skills folder cannot crash the ENABLED hook', () => {+ // The hook needs only the stdin reader, not skill discovery. Loading discovery would scan the skills+ // folder at require time, so an EACCES there would crash the hook even though it never uses it.+ const preload = path.join(__dirname, 'hook-readdir-throw-preload-enabled.js');+ fs.writeFileSync(preload, [+ "const fs = require('node:fs');",+ 'const real = fs.readdirSync;',+ "fs.readdirSync = function patched(p, ...args) {",+ " if (String(p).includes('plugins' + require('node:path').sep + 'model-apps' + require('node:path').sep + 'skills')) {",+ " const err = new Error('EACCES: permission denied, scandir skills');",+ " err.code = 'EACCES';",+ " throw err;",+ ' }',+ ' return real.call(this, p, ...args);',+ '};',+ ].join('\n'));+ try {+ const env = { ...process.env };+ delete env.MODEL_APPS_DISABLE_HOOKS;+ const res = spawnSync(process.execPath, ['-r', preload, HOOK], { input: 'not json', encoding: 'utf8', env });+ assert.equal(res.status, 0, res.stderr);+ } finally {+ fs.rmSync(preload, { force: true });+ }+});++test('hook stdin decoding preserves multibyte paths split across pipe chunks', async () => {+ const outside = path.join(path.parse(cwd).root, 'model-apps-guard-東京', 'evil.ts');+ const payload = { tool_name: 'Write', tool_input: { file_path: outside, content: 'x' }, cwd };+ const { status, stderr } = await runHookWithSplitStdin(payload, '東京');+ assert.equal(status, 1);+ assert.match(stderr, /outside your project folder/);+ assert.match(stderr, new RegExp(outside.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')));+});+test('unparseable stdin does not block (exit 0)', () => {const res = spawnSync(process.execPath, [HOOK], { input: 'not json', encoding: 'utf8' });assert.equal(res.status, 0);diff --git a/plugins/model-apps/scripts/tests/vendor-sdk-smoke.test.js b/plugins/model-apps/scripts/tests/vendor-sdk-smoke.test.jsindex c8d932eca..f664f222f 100644--- a/plugins/model-apps/scripts/tests/vendor-sdk-smoke.test.js+++ b/plugins/model-apps/scripts/tests/vendor-sdk-smoke.test.js@@ -66,6 +66,22 @@ test('vendored bundle exports createMakerSdk', () => {assert.strictEqual(typeof mod.createMakerSdk, 'function');});+// The SDK's genPage compiler takes TypeScript from its host, and its `loadNodeTypeScript` helper loads+// it with a dynamic import that esbuild would otherwise follow: the compiler then made up 3.5 MB of a+// 4.4 MB bundle. The plugin supplies no compiler, so `_vendor-build/build.js` marks `typescript`+// external. A rebuild that drops that flag inlines it again, and this fails on the size of the text.+test('the vendored bundle does not carry the TypeScript compiler, and loading one fails closed', async () => {+ const text = fs.readFileSync(BUNDLE, 'utf8');+ assert.ok(text.length < 2 * 1024 * 1024, `bundle is ${Math.round(text.length / 1024)} KB — was the TypeScript compiler inlined?`);+ const mod = require(BUNDLE);+ assert.strictEqual(typeof mod.loadNodeTypeScript, 'function', 'the SDK still offers the loader');+ // Only while `typescript` cannot be resolved from the bundle's folder: then the loader must reject+ // with the resolution error, never resolve to something the bundle carried itself.+ let resolvable = true;+ try { require.resolve('typescript', { paths: [path.dirname(BUNDLE)] }); } catch { resolvable = false; }+ if (!resolvable) await assert.rejects(mod.loadNodeTypeScript(), /Cannot find module 'typescript'/);+});+test('createArtifact serializes every artifact type headlessly (no browser)', async () => {const sdk = await freshSdk();for (const [type, def] of [diff --git a/plugins/model-apps/scripts/tests/verify-default-form.test.js b/plugins/model-apps/scripts/tests/verify-default-form.test.jsnew file mode 100644index 000000000..c87f15c5d--- /dev/null+++ b/plugins/model-apps/scripts/tests/verify-default-form.test.js@@ -0,0 +1,93 @@+'use strict';+const test = require('node:test');+const assert = require('node:assert');+const { verifySpec } = require('../lib/verify-spec.js');+const { readerFor } = require('../verify-model-app.js');++function spec() {+ return {+ solution: { publisherPrefix: 'new' },+ app: { name: 'Default Probe', uniqueName: 'new_defaultprobe' },+ entities: [{ schemaName: 'new_project', columns: [] }],+ views: [], charts: [], appShell: { areas: [] },+ forms: [+ { entity: 'new_project', name: 'Operations', formType: 'Main' },+ { entity: 'new_project', name: 'Manager', formType: 'Main', isDefault: true },+ { entity: 'new_project', name: 'Quick', formType: 'QuickCreate' },+ ],+ };+}++function readWith(defaultIds, failIds = new Set()) {+ const ids = { Operations: 'form-ops', Manager: 'form-manager', Quick: 'form-quick' };+ return {+ findTable: async () => ({ logicalName: 'new_project' }),+ findColumns: async () => [],+ sitemapXml: async () => '',+ queryRecords: async (set, opts) => {+ if (set !== 'systemform') return [];+ for (const [name, id] of Object.entries(ids)) {+ if (opts.filter.includes(`name eq '${name}'`)) return [{ formid: id }];+ }+ return [];+ },+ formDefaultState: async (_entity, formId) => {+ if (failIds.has(formId)) throw new Error(`cannot read ${formId}`);+ return { isDefault: defaultIds.has(formId) };+ },+ };+}++test('verifySpec fails when another spec-declared Main form is still default', async () => {+ const result = await verifySpec(spec(), readWith(new Set(['form-manager', 'form-ops'])));++ assert.strictEqual(result.ok, false);+ assert.ok(result.checks.some((c) => c.kind === 'form-default' && c.name === 'new_project.Manager' && c.present), 'the chosen form is default');+ const sibling = result.checks.find((c) => c.kind === 'form-default-unique' && c.name === 'new_project.Operations');+ assert.ok(sibling && sibling.present === false, JSON.stringify(result.checks.filter((c) => /^form-default/.test(c.kind))));+ assert.match(sibling.detail, /also default/);+});++test('verifySpec passes default-form uniqueness when only the selected Main form is default', async () => {+ const result = await verifySpec(spec(), readWith(new Set(['form-manager'])));++ assert.strictEqual(result.ok, true, JSON.stringify(result.missing));+ assert.ok(result.checks.some((c) => c.kind === 'form-default-unique' && c.name === 'new_project.Operations' && c.present));+ assert.ok(!result.checks.some((c) => c.name === 'new_project.Quick' && c.kind === 'form-default-unique'), 'non-Main sibling is not part of the uniqueness check');+});++test('verifySpec reports sibling default-state read failures as failures', async () => {+ const result = await verifySpec(spec(), readWith(new Set(['form-manager']), new Set(['form-ops'])));++ assert.strictEqual(result.ok, false);+ const sibling = result.checks.find((c) => c.kind === 'form-default-unique' && c.name === 'new_project.Operations');+ assert.ok(sibling && sibling.present === false);+ assert.match(sibling.detail, /could not read deployed systemform\.isdefault/);+});++test('readerFor supplies sibling form default state through the real reader seam', async () => {+ const calls = [];+ const sdk = {+ findTables: async () => [{ logicalName: 'new_project' }],+ findColumns: async () => [],+ queryRecords: async (set, opts) => {+ calls.push({ set, opts });+ if (set !== 'systemform') return [];+ if (/name eq 'Operations'/.test(opts.filter)) return [{ formid: 'form-ops' }];+ if (/name eq 'Manager'/.test(opts.filter)) return [{ formid: 'form-manager' }];+ if (/name eq 'Quick'/.test(opts.filter)) return [{ formid: 'form-quick' }];+ if (/formid eq form-manager/.test(opts.filter)) return [{ formid: 'form-manager', isdefault: true }];+ if (/formid eq form-ops/.test(opts.filter)) return [{ formid: 'form-ops', isdefault: true }];+ return [];+ },+ fetchEntityMetadata: async () => ({ Relationships: [] }),+ resolveArtifact: async () => [],+ retrieveSetting: async () => null,+ };++ const result = await verifySpec(spec(), readerFor(sdk, 'new_defaultprobe', {}));++ assert.strictEqual(result.ok, false);+ assert.ok(result.missing.some((m) => m.kind === 'form-default-unique' && /also default/.test(m.detail)), JSON.stringify(result.missing));+ assert.ok(calls.some((c) => c.set === 'systemform' && /formid eq form-ops/.test(c.opts.filter) && c.opts.select.includes('isdefault')), 'sibling default proof reads systemform by id');+});diff --git a/plugins/model-apps/scripts/vendor/PROVENANCE.json b/plugins/model-apps/scripts/vendor/PROVENANCE.jsonindex 48e6bfdc6..096ad7d14 100644--- a/plugins/model-apps/scripts/vendor/PROVENANCE.json+++ b/plugins/model-apps/scripts/vendor/PROVENANCE.json@@ -1,14 +1,14 @@{- "commit": "e3483d6951cefa0876ce943501b9980317163856",- "subject": "fix(cds-maker-sdk): condition every BPF write on the token the previous write produced",+ "commit": "0f263094d8fe3acd74049a6dfa336932682f8324",+ "subject": "AB#39863285 Configure executive summary block UX","dirtySdkPackage": 0,- "libBuiltAt": "2026-09-23T16:22:40.381Z",- "newestSrcAt": "2026-09-23T16:18:15.285Z",+ "libBuiltAt": "2026-09-28T20:54:48.427Z",+ "newestSrcAt": "2026-09-28T18:13:56.883Z","libIsStale": false,"nostub": false,"esbuildVersion": "0.28.1","nodeVersion": "v20.20.2",- "builtAt": "2026-09-23T16:23:33.084Z",- "bundleSha256": "7a64e8b1962d4845f7ea7b1cdb753b8934dbb16a2d2bad510843d32911a3a2b8",- "bundleBytes": 723384+ "builtAt": "2026-09-28T20:57:40.665Z",+ "bundleSha256": "83939ecfb8c1e936c322ad71bfb60394e9ccbbe0a729452ed8f5f4eee9ce72f7",+ "bundleBytes": 790605}diff --git a/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs b/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjsindex 7b87fd179..e63145ad3 100644--- a/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs+++ b/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs@@ -25,37 +25,339 @@}globalThis.document=globalThis.document||globalThis.window.document;})();-var yP=Object.create;var Ss=Object.defineProperty;var bP=Object.getOwnPropertyDescriptor;var wP=Object.getOwnPropertyNames;var AP=Object.getPrototypeOf,CP=Object.prototype.hasOwnProperty;var I=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var v=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},zr=(e,t)=>{for(var r in t)Ss(e,r,{get:t[r],enumerable:!0})},Es=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of wP(t))!CP.call(e,i)&&i!==r&&Ss(e,i,{get:()=>t[i],enumerable:!(n=bP(t,i))||n.enumerable});return e},bn=(e,t,r)=>(Es(e,t,"default"),r&&Es(r,t,"default")),ie=(e,t,r)=>(r=e!=null?yP(AP(e)):{},Es(t||!e||!e.__esModule?Ss(r,"default",{value:e,enumerable:!0}):r,e)),br=e=>Es(Ss({},"__esModule",{value:!0}),e);var Yn=v(E=>{"use strict";Object.defineProperty(E,"__esModule",{value:!0});E.DateTimeBehavior=E.PrecisionSource=E.StringFormatName=E.SourceType=E.ImeMode=E.SolutionEntityTypeCodeExtToComponentTypeCode=E.SolutionComponentTypeCodeToEntityTypeCodeExt=E.SolutionComponentVirtualAttributeSubtype=E.EntityTypeCode=E.SolutionComponentTypeCodeExt=E.RootComponentBehavior=E.SolutionComponentTypeCode=E.EntityKeyIndexStatus=E.ViewStateCode=E.ViewStatusCode=E.RelationshipSecurityTypes=E.CascadeType=E.RelationshipTypeExt=E.RelationshipType=E.AppSubType=E.BusinessProcessType=E.WorkflowCategory=E.WorkflowScope=E.WorkflowTypeCode=E.StatusCodeEnabledDisabled=E.StateCodeEnabledDisabled=E.StatusCode=E.StateCode=E.OptionSetType=E.AttributeTypeCodeNum=E.AttributeFormatName=E.AttributeFormatCode=E.AttributeTypeName=E.AttributeTypeCode=E.PluginSourceType=E.AuthType=E.PluginIsolationMode=E.ComponentState=E.ChartType=E.ChartsType=E.ViewType=E.AttributeType=E.ActivationState=E.FormPresentation=E.FormType=E.TableTypeCode=E.TableTypes=E.ActivityTypeMask=E.PrincipalType=E.OwnershipTypes=void 0;E.QueryType=E.KnownCustomSolutionComponentEntitySetName=E.TeamTypeEnum=E.EnvironmentVariableDefinitionTypeEnum=E.ConnectorTypeEnum=E.RoleInheritance=E.DefaultRoleTemplates=E.DeleteDependencyErrorCode=E.ServiceEndpointConnectionMode=E.ServiceEndpointContract=E.ServiceNamespaceFormat=E.ConnectionRoleCategory=E.ReportTypeCode=E.SdkMessageProcessingMode=E.SupportedDeployment=E.SdkMessageProcessingStage=E.WebResourceTypeCode=E.IntegerFormat=E.DateTimeFormat=void 0;var vh;(function(e){e.None="None",e.UserOwned="UserOwned",e.TeamOwned="TeamOwned",e.BusinessOwned="BusinessOwned",e.OrganizationOwned="OrganizationOwned",e.BusinessParented="BusinessParented",e.Filtered="Filtered"})(vh||(E.OwnershipTypes=vh={}));var yh;(function(e){e.User="Microsoft.Dynamics.CRM.systemuser",e.Team="Microsoft.Dynamics.CRM.team"})(yh||(E.PrincipalType=yh={}));var bh;(function(e){e[e.DoNotDisplayInActivityMenus=0]="DoNotDisplayInActivityMenus",e[e.DisplayInActivityMenus=1]="DisplayInActivityMenus"})(bh||(E.ActivityTypeMask=bh={}));var wh;(function(e){e.Activity="Activity",e.Virtual="Virtual",e.Standard="Standard",e.Elastic="Elastic"})(wh||(E.TableTypes=wh={}));var Ah;(function(e){e.Standard="Standard",e.Virtual="Virtual",e.Elastic="Elastic"})(Ah||(E.TableTypeCode=Ah={}));var Ch;(function(e){e[e.Dashboard=0]="Dashboard",e[e.AppointmentBook=1]="AppointmentBook",e[e.Main=2]="Main",e[e.MiniCampaignBO=3]="MiniCampaignBO",e[e.Preview=4]="Preview",e[e.MobileExpress=5]="MobileExpress",e[e.QuickViewForm=6]="QuickViewForm",e[e.QuickCreate=7]="QuickCreate",e[e.Dialog=8]="Dialog",e[e.TaskFlowForm=9]="TaskFlowForm",e[e.InteractionCentricDashboard=10]="InteractionCentricDashboard",e[e.Card=11]="Card",e[e.MainInteractiveExperience=12]="MainInteractiveExperience",e[e.Other=100]="Other",e[e.MainBackup=101]="MainBackup",e[e.AppointmentBookBackup=102]="AppointmentBookBackup",e[e.PowerBIDashboard=103]="PowerBIDashboard"})(Ch||(E.FormType=Ch={}));var Eh;(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(Eh||(E.FormPresentation=Eh={}));var Sh;(function(e){e[e.Inactive=0]="Inactive",e[e.Active=1]="Active"})(Sh||(E.ActivationState=Sh={}));var Nh;(function(e){e[e.String=0]="String",e[e.Number=1]="Number",e[e.Picklist=2]="Picklist"})(Nh||(E.AttributeType=Nh={}));var Dh;(function(e){e[e.Public=0]="Public",e[e.AdvancedFind=1]="AdvancedFind",e[e.Associated=2]="Associated",e[e.QuickFind=4]="QuickFind",e[e.Lookup=64]="Lookup"})(Dh||(E.ViewType=Dh={}));var Ih;(function(e){e[e.ASPChart=0]="ASPChart",e[e.PowerBI=1]="PowerBI"})(Ih||(E.ChartsType=Ih={}));var _h;(function(e){e[e.DataAndInteractionCentric=0]="DataAndInteractionCentric",e[e.InteractionCentric=1]="InteractionCentric"})(_h||(E.ChartType=_h={}));var Th;(function(e){e[e.Published=0]="Published",e[e.Unpublished=1]="Unpublished",e[e.Deleted=2]="Deleted",e[e.DeletedUnpublished=3]="DeletedUnpublished"})(Th||(E.ComponentState=Th={}));var Ph;(function(e){e[e.None=1]="None",e[e.Sandbox=2]="Sandbox",e[e.External=3]="External"})(Ph||(E.PluginIsolationMode=Ph={}));var Oh;(function(e){e[e.BasicAuth=0]="BasicAuth"})(Oh||(E.AuthType=Oh={}));var Rh;(function(e){e[e.Database=0]="Database",e[e.Disk=1]="Disk",e[e.Normal=2]="Normal",e[e.AzureWebApp=3]="AzureWebApp"})(Rh||(E.PluginSourceType=Rh={}));var Fh;(function(e){e.Boolean="Boolean",e.Customer="Customer",e.Date="Date",e.DateTime="DateTime",e.DateTimeNoTimeZone="DateTimeNoTimeZone",e.Decimal="Decimal",e.Double="Double",e.Integer="Integer",e.Lookup="Lookup",e.Memo="Memo",e.Money="Money",e.Owner="Owner",e.PartyList="PartyList",e.Picklist="Picklist",e.State="State",e.Status="Status",e.String="String",e.Uniqueidentifier="Uniqueidentifier",e.CalendarRules="CalendarRules",e.Virtual="Virtual",e.BigInt="BigInt",e.ManagedProperty="ManagedProperty",e.EntityName="EntityName"})(Fh||(E.AttributeTypeCode=Fh={}));var xh;(function(e){e.DateTimeType="DateTimeType",e.ImageType="ImageType",e.IntegerType="IntegerType",e.FileType="FileType",e.BooleanType="BooleanType",e.CustomerType="CustomerType",e.MemoType="MemoType",e.MultiSelectPicklistType="MultiSelectPicklistType",e.MoneyType="MoneyType",e.DecimalType="DecimalType",e.DoubleType="DoubleType",e.LookupType="LookupType",e.BigIntType="BigIntType",e.UniqueidentifierType="UniqueidentifierType",e.StringType="StringType",e.OwnerType="OwnerType",e.PicklistType="PicklistType",e.StateType="StateType",e.StatusType="StatusType",e.EntityNameType="EntityNameType"})(xh||(E.AttributeTypeName=xh={}));var Lh;(function(e){e.Email="Email",e.Text="Text",e.TextArea="TextArea",e.Url="Url",e.TickerSymbol="TickerSymbol",e.PhoneticGuide="PhoneticGuide",e.VersionNumber="VersionNumber",e.Phone="Phone",e.Json="Json",e.RichText="RichText",e.DateOnly="DateOnly",e.DateAndTime="DateAndTime",e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale"})(Lh||(E.AttributeFormatCode=Lh={}));var kh;(function(e){e.Text="Text",e.TextArea="TextArea",e.Email="Email",e.Url="Url",e.Phone="Phone",e.Json="Json",e.RichText="RichText",e.TickerSymbol="TickerSymbol",e.PhoneticGuide="PhoneticGuide",e.VersionNumber="VersionNumber",e.DateOnly="DateOnly",e.DateAndTime="DateAndTime"})(kh||(E.AttributeFormatName=kh={}));var Mh;(function(e){e[e.Boolean=0]="Boolean",e[e.Customer=1]="Customer",e[e.DateTime=2]="DateTime",e[e.Decimal=3]="Decimal",e[e.Double=4]="Double",e[e.Integer=5]="Integer",e[e.Lookup=6]="Lookup",e[e.Memo=7]="Memo",e[e.Money=8]="Money",e[e.Owner=9]="Owner",e[e.PartyList=10]="PartyList",e[e.Picklist=11]="Picklist",e[e.State=12]="State",e[e.Status=13]="Status",e[e.String=14]="String",e[e.Uniqueidentifier=15]="Uniqueidentifier",e[e.CalendarRules=16]="CalendarRules",e[e.Virtual=17]="Virtual",e[e.BigInt=18]="BigInt",e[e.ManagedProperty=19]="ManagedProperty",e[e.EntityName=20]="EntityName"})(Mh||(E.AttributeTypeCodeNum=Mh={}));var Uh;(function(e){e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean"})(Uh||(E.OptionSetType=Uh={}));var Bh;(function(e){e[e.Draft=0]="Draft",e[e.Activated=1]="Activated"})(Bh||(E.StateCode=Bh={}));var $h;(function(e){e[e.Draft=1]="Draft",e[e.Activated=2]="Activated"})($h||(E.StatusCode=$h={}));var qh;(function(e){e[e.Enabled=0]="Enabled",e[e.Disabled=1]="Disabled"})(qh||(E.StateCodeEnabledDisabled=qh={}));var Vh;(function(e){e[e.Enabled=1]="Enabled",e[e.Disabled=2]="Disabled"})(Vh||(E.StatusCodeEnabledDisabled=Vh={}));var Gh;(function(e){e[e.Definition=1]="Definition",e[e.Activation=2]="Activation",e[e.Template=3]="Template"})(Gh||(E.WorkflowTypeCode=Gh={}));var zh;(function(e){e[e.User=1]="User",e[e.BusinessUnit=2]="BusinessUnit",e[e.ParentChildBusinessUnit=3]="ParentChildBusinessUnit",e[e.Organization=4]="Organization"})(zh||(E.WorkflowScope=zh={}));var Wh;(function(e){e[e.Workflow=0]="Workflow",e[e.Dialog=1]="Dialog",e[e.BusinessRule=2]="BusinessRule",e[e.Action=3]="Action",e[e.BusinessProcessFlow=4]="BusinessProcessFlow",e[e.Flow=5]="Flow",e[e.UIFlow=6]="UIFlow"})(Wh||(E.WorkflowCategory=Wh={}));var Hh;(function(e){e[e.None=-1]="None",e[e.BusinessFlow=0]="BusinessFlow",e[e.TaskFlow=1]="TaskFlow"})(Hh||(E.BusinessProcessType=Hh={}));var jh;(function(e){e[e.CanvasApp=0]="CanvasApp",e[e.ComponentLibrary=1]="ComponentLibrary",e[e.CustomCanvasPage=2]="CustomCanvasPage",e[e.UnifiedApp=3]="UnifiedApp",e[e.CodeApp=4]="CodeApp",e[e.MobileApp=5]="MobileApp"})(jh||(E.AppSubType=jh={}));var Jh;(function(e){e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(Jh||(E.RelationshipType=Jh={}));var Qh;(function(e){e.ManyToOneRelationship="ManyToOneRelationship",e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(Qh||(E.RelationshipTypeExt=Qh={}));var Kh;(function(e){e.NoCascade="NoCascade",e.Cascade="Cascade",e.Active="Active",e.UserOwned="UserOwned",e.RemoveLink="RemoveLink",e.Restrict="Restrict"})(Kh||(E.CascadeType=Kh={}));var Xh;(function(e){e.None="None",e.Append="Append",e.ParentChild="ParentChild",e.Pointer="Pointer",e.Inheritance="Inheritance"})(Xh||(E.RelationshipSecurityTypes=Xh={}));var Yh;(function(e){e[e.Active=1]="Active",e[e.Inactive=2]="Inactive"})(Yh||(E.ViewStatusCode=Yh={}));var Zh;(function(e){e[e.Active=0]="Active",e[e.Inactive=1]="Inactive"})(Zh||(E.ViewStateCode=Zh={}));var eg;(function(e){e.Active="Active",e.Failed="Failed",e.InProgress="InProgress",e.Pending="Pending"})(eg||(E.EntityKeyIndexStatus=eg={}));var tg;(function(e){e[e.Entity=1]="Entity",e[e.Attribute=2]="Attribute",e[e.OptionSet=9]="OptionSet",e[e.EntityRelationship=10]="EntityRelationship",e[e.EntityKey=14]="EntityKey",e[e.Role=20]="Role",e[e.DisplayString=22]="DisplayString",e[e.SavedQuery=26]="SavedQuery",e[e.Workflow=29]="Workflow",e[e.Report=31]="Report",e[e.Template=36]="Template",e[e.ContractTemplate=37]="ContractTemplate",e[e.KbArticleTemplate=38]="KbArticleTemplate",e[e.MailMergeTemplate=39]="MailMergeTemplate",e[e.RibbonCustomization=50]="RibbonCustomization",e[e.SavedQueryVisualization=59]="SavedQueryVisualization",e[e.SystemForm=60]="SystemForm",e[e.WebResource=61]="WebResource",e[e.SiteMap=62]="SiteMap",e[e.ConnectionRole=63]="ConnectionRole",e[e.HierarchyRule=65]="HierarchyRule",e[e.CustomControl=66]="CustomControl",e[e.FieldSecurityProfile=70]="FieldSecurityProfile",e[e.AppModule=80]="AppModule",e[e.PluginAssembly=91]="PluginAssembly",e[e.SdkMessageProcessingStep=92]="SdkMessageProcessingStep",e[e.ServiceEndpoint=95]="ServiceEndpoint",e[e.RoutingRule=150]="RoutingRule",e[e.SLA=152]="SLA",e[e.ConvertRule=154]="ConvertRule",e[e.MobileOfflineProfile=161]="MobileOfflineProfile",e[e.EntityDataProvider=181]="EntityDataProvider",e[e.EntityDataSource=183]="EntityDataSource",e[e.SdkMessage=201]="SdkMessage",e[e.CanvasApp=300]="CanvasApp",e[e.Connector=372]="Connector",e[e.EnvironmentVariableDefinition=380]="EnvironmentVariableDefinition",e[e.EnvironmentVariableValue=381]="EnvironmentVariableValue",e[e.AIModel=401]="AIModel",e[e.Dataflow=418]="Dataflow",e[e.DataflowEntities=419]="DataflowEntities",e[e.DualWriteEntityMap=500]="DualWriteEntityMap",e[e.DataIntegrationConnection=501]="DataIntegrationConnection",e[e.ExportToDataLakeConfig=510]="ExportToDataLakeConfig",e[e.Tour=10061]="Tour"})(tg||(E.SolutionComponentTypeCode=tg={}));var rg;(function(e){e[e.IncludeSubcomponents=0]="IncludeSubcomponents",e[e.DoNotIncludeSubcomponents=1]="DoNotIncludeSubcomponents",e[e.IncludeAsShellOnly=2]="IncludeAsShellOnly"})(rg||(E.RootComponentBehavior=rg={}));var Ns;(function(e){e[e.Entity=1]="Entity",e[e.Attribute=2]="Attribute",e[e.OptionSet=9]="OptionSet",e[e.EntityRelationship=10]="EntityRelationship",e[e.EntityKey=14]="EntityKey",e[e.Role=20]="Role",e[e.DisplayString=22]="DisplayString",e[e.SavedQuery=26]="SavedQuery",e[e.Workflow=29]="Workflow",e[e.Report=31]="Report",e[e.Template=36]="Template",e[e.ContractTemplate=37]="ContractTemplate",e[e.KbArticleTemplate=38]="KbArticleTemplate",e[e.MailMergeTemplate=39]="MailMergeTemplate",e[e.RibbonCustomization=50]="RibbonCustomization",e[e.SavedQueryVisualization=59]="SavedQueryVisualization",e[e.SystemForm=60]="SystemForm",e[e.WebResource=61]="WebResource",e[e.SiteMap=62]="SiteMap",e[e.ConnectionRole=63]="ConnectionRole",e[e.HierarchyRule=65]="HierarchyRule",e[e.CustomControl=66]="CustomControl",e[e.FieldSecurityProfile=70]="FieldSecurityProfile",e[e.AppModule=80]="AppModule",e[e.PluginAssembly=91]="PluginAssembly",e[e.SdkMessageProcessingStep=92]="SdkMessageProcessingStep",e[e.ServiceEndpoint=95]="ServiceEndpoint",e[e.RoutingRule=150]="RoutingRule",e[e.SLA=152]="SLA",e[e.ConvertRule=154]="ConvertRule",e[e.MobileOfflineProfile=161]="MobileOfflineProfile",e[e.EntityDataProvider=181]="EntityDataProvider",e[e.EntityDataSource=183]="EntityDataSource",e[e.SdkMessage=201]="SdkMessage",e[e.CanvasApp=300]="CanvasApp",e[e.Connector=372]="Connector",e[e.EnvironmentVariableDefinition=380]="EnvironmentVariableDefinition",e[e.EnvironmentVariableValue=381]="EnvironmentVariableValue",e[e.AIModel=401]="AIModel",e[e.Dataflow=418]="Dataflow",e[e.DataflowEntities=419]="DataflowEntities",e[e.DualWriteEntityMap=500]="DualWriteEntityMap",e[e.DataIntegrationConnection=501]="DataIntegrationConnection",e[e.ExportToDataLakeConfig=510]="ExportToDataLakeConfig",e[e.DataWorkspace=10282]="DataWorkspace",e[e.Dashboard=100001]="Dashboard",e[e.InteractionCentricDashboard=100002]="InteractionCentricDashboard",e[e.Dialog=100003]="Dialog",e[e.PowerBIDashboard=100004]="PowerBIDashboard",e[e.BusinessRule=100021]="BusinessRule",e[e.ProcessFlow=100024]="ProcessFlow",e[e.Flow=100025]="Flow",e[e.UIFlow=100026]="UIFlow",e[e.ProcessNoFlow=100031]="ProcessNoFlow",e[e.AllDashboards=100032]="AllDashboards",e[e.FormsOnly=100033]="FormsOnly",e[e.ComponentLibrary=100034]="ComponentLibrary",e[e.CanvasAppsOnly=100035]="CanvasAppsOnly",e[e.CustomCanvasPage=100038]="CustomCanvasPage",e[e.CodeApp=100039]="CodeApp",e[e.MobileApp=100046]="MobileApp",e[e.ProcessNoFlowNoUIFlowNoBusinessRule=100036]="ProcessNoFlowNoUIFlowNoBusinessRule",e[e.ActionDefinition=100040]="ActionDefinition",e[e.ActionTemplate=100041]="ActionTemplate",e[e.DialogDefinition=100042]="DialogDefinition",e[e.DialogTemplate=100043]="DialogTemplate",e[e.WorkflowDefinition=100044]="WorkflowDefinition",e[e.WorkflowTemplate=100045]="WorkflowTemplate"})(Ns||(E.SolutionComponentTypeCodeExt=Ns={}));var Ds;(function(e){e[e.Entity=9801]="Entity",e[e.Attribute=9802]="Attribute",e[e.OptionSet=9804]="OptionSet",e[e.EntityRelationship=9805]="EntityRelationship",e[e.EntityKey=9812]="EntityKey",e[e.Role=1036]="Role",e[e.DisplayString=4102]="DisplayString",e[e.SavedQuery=1039]="SavedQuery",e[e.Workflow=4703]="Workflow",e[e.Report=9100]="Report",e[e.Template=2010]="Template",e[e.ContractTemplate=2011]="ContractTemplate",e[e.KbArticleTemplate=1016]="KbArticleTemplate",e[e.MailMergeTemplate=9106]="MailMergeTemplate",e[e.SavedQueryVisualization=1111]="SavedQueryVisualization",e[e.SystemForm=1030]="SystemForm",e[e.WebResource=9333]="WebResource",e[e.SiteMap=4709]="SiteMap",e[e.ConnectionRole=3231]="ConnectionRole",e[e.HierarchyRule=8840]="HierarchyRule",e[e.CustomControl=9753]="CustomControl",e[e.FieldSecurityProfile=1200]="FieldSecurityProfile",e[e.AppModule=9006]="AppModule",e[e.PluginAssembly=4605]="PluginAssembly",e[e.SdkMessageProcessingStep=4608]="SdkMessageProcessingStep",e[e.ServiceEndpoint=4618]="ServiceEndpoint",e[e.RoutingRule=8181]="RoutingRule",e[e.SLA=9750]="SLA",e[e.ConvertRule=9300]="ConvertRule",e[e.MobileOfflineProfile=9866]="MobileOfflineProfile",e[e.EntityDataSource=85]="EntityDataSource",e[e.SdkMessage=4606]="SdkMessage",e[e.RibbonCustomization=1120]="RibbonCustomization",e[e.EntityDataProvider=181]="EntityDataProvider",e[e.CanvasApp=300]="CanvasApp",e[e.Connector=372]="Connector",e[e.MaskingRule=373]="MaskingRule",e[e.AttributeMaskingRule=374]="AttributeMaskingRule",e[e.EnvironmentVariableDefinition=380]="EnvironmentVariableDefinition",e[e.EnvironmentVariableValue=381]="EnvironmentVariableValue",e[e.AIModel=401]="AIModel",e[e.Plan=10283]="Plan",e[e.Dataflow=418]="Dataflow",e[e.DataflowEntities=419]="DataflowEntities",e[e.DualWriteEntityMap=500]="DualWriteEntityMap",e[e.DataIntegrationConnection=501]="DataIntegrationConnection",e[e.ExportToDataLakeConfig=510]="ExportToDataLakeConfig",e[e.TeamTemplate=511]="TeamTemplate",e[e.DataWorkspace=10282]="DataWorkspace",e[e.Dashboard=1030]="Dashboard",e[e.InteractionCentricDashboard=1032]="InteractionCentricDashboard",e[e.PowerBIDashboard=1034]="PowerBIDashboard",e[e.Dialog=1030]="Dialog",e[e.WebResourceImage=9333]="WebResourceImage",e[e.WebResourceSilverlight=9333]="WebResourceSilverlight",e[e.WebResourceCode=9333]="WebResourceCode",e[e.WebResourceData=9333]="WebResourceData",e[e.BusinessRule=4703]="BusinessRule",e[e.ActionDefinition=4703]="ActionDefinition",e[e.ActionTemplate=4703]="ActionTemplate",e[e.DialogDefinition=4703]="DialogDefinition",e[e.DialogTemplate=4703]="DialogTemplate",e[e.WorkflowDefinition=4703]="WorkflowDefinition",e[e.WorkflowTemplate=4703]="WorkflowTemplate",e[e.ProcessFlow=4703]="ProcessFlow",e[e.Flow=4703]="Flow",e[e.UIFlow=4703]="UIFlow",e[e.ProcessNoFlow=4703]="ProcessNoFlow",e[e.ProcessNoFlowNoUIFlowNoBusinessRule=4703]="ProcessNoFlowNoUIFlowNoBusinessRule",e[e.AllDashboards=1030]="AllDashboards",e[e.FormsOnly=1030]="FormsOnly",e[e.ComponentLibrary=300]="ComponentLibrary",e[e.CanvasAppsOnly=300]="CanvasAppsOnly",e[e.CustomCanvasPage=300]="CustomCanvasPage",e[e.CodeApp=300]="CodeApp",e[e.MobileApp=300]="MobileApp",e[e.Chatbot=10030]="Chatbot",e[e.Card=10276]="Card"})(Ds||(E.EntityTypeCode=Ds={}));var ng;(function(e){e.MultiSelectPicklist="MultiSelectPicklist",e.File="File",e.Image="Image"})(ng||(E.SolutionComponentVirtualAttributeSubtype=ng={}));function EP(e){let t=Ns[e];return Ds[t]}E.SolutionComponentTypeCodeToEntityTypeCodeExt=EP;function SP(e){let t=Ds[e];return Ns[t]}E.SolutionEntityTypeCodeExtToComponentTypeCode=SP;var ig;(function(e){e.Active="Active",e.Auto="Auto",e.Disabled="Disabled",e.Inactive="Inactive"})(ig||(E.ImeMode=ig={}));var ag;(function(e){e[e.Simple=0]="Simple",e[e.Calculated=1]="Calculated",e[e.Rollup=2]="Rollup",e[e.Formula=3]="Formula",e[e.Prompt=4]="Prompt"})(ag||(E.SourceType=ag={}));var og;(function(e){e.Email="Email",e.Phone="Phone",e.PhoneticGuide="PhoneticGuide",e.Text="Text",e.TextArea="TextArea",e.TickerSymbol="TickerSymbol",e.Url="Url",e.VersionNumber="VersionNumber"})(og||(E.StringFormatName=og={}));var sg;(function(e){e[e.PrecisionProperty=0]="PrecisionProperty",e[e.Organization=1]="Organization",e[e.TransactionCurrency=2]="TransactionCurrency"})(sg||(E.PrecisionSource=sg={}));var lg;(function(e){e.UserLocal="UserLocal",e.DateOnly="DateOnly",e.TimeZoneIndependent="TimeZoneIndependent"})(lg||(E.DateTimeBehavior=lg={}));var ug;(function(e){e.DateOnly="DateOnly",e.DateAndTime="DateAndTime"})(ug||(E.DateTimeFormat=ug={}));var cg;(function(e){e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale"})(cg||(E.IntegerFormat=cg={}));var dg;(function(e){e[e.HTML=1]="HTML",e[e.CSS=2]="CSS",e[e.JScript=3]="JScript",e[e.XML=4]="XML",e[e.PNG=5]="PNG",e[e.JPG=6]="JPG",e[e.GIF=7]="GIF",e[e.Silverlight=8]="Silverlight",e[e.XSL=9]="XSL",e[e.ICO=10]="ICO",e[e.SVG=11]="SVG",e[e.RESX=12]="RESX"})(dg||(E.WebResourceTypeCode=dg={}));var pg;(function(e){e[e.Initial=5]="Initial",e[e.PreValidation=10]="PreValidation",e[e.InternalPreOperationBeforeExternal=15]="InternalPreOperationBeforeExternal",e[e.PreOperation=20]="PreOperation",e[e.InternalPreOperationAfterExternal=25]="InternalPreOperationAfterExternal",e[e.MainOperation=30]="MainOperation",e[e.InternalPostOperationBeforeExternal=35]="InternalPostOperationBeforeExternal",e[e.PostOperation=40]="PostOperation",e[e.InternalPostOperationAfterExternal=45]="InternalPostOperationAfterExternal",e[e.PostOperationDeprecated=50]="PostOperationDeprecated",e[e.FinalPostOperation=55]="FinalPostOperation"})(pg||(E.SdkMessageProcessingStage=pg={}));var fg;(function(e){e[e.ServerOnly=0]="ServerOnly",e[e.OutlookClientOnly=1]="OutlookClientOnly",e[e.Both=2]="Both"})(fg||(E.SupportedDeployment=fg={}));var mg;(function(e){e[e.Synchronous=0]="Synchronous",e[e.Asynchronous=1]="Asynchronous"})(mg||(E.SdkMessageProcessingMode=mg={}));var hg;(function(e){e[e.ReportingServicesReport=1]="ReportingServicesReport",e[e.OtherReport=2]="OtherReport",e[e.LinkedReport=3]="LinkedReport"})(hg||(E.ReportTypeCode=hg={}));var gg;(function(e){e[e.Business=1]="Business",e[e.Family=2]="Family",e[e.Social=3]="Social",e[e.Sales=4]="Sales",e[e.Other=5]="Other",e[e.Stakeholder=1e3]="Stakeholder",e[e.SalesTeam=1001]="SalesTeam",e[e.Service=1002]="Service"})(gg||(E.ConnectionRoleCategory=gg={}));var vg;(function(e){e[e.Name=1]="Name",e[e.Address=2]="Address"})(vg||(E.ServiceNamespaceFormat=vg={}));var yg;(function(e){e[e.OneWay=1]="OneWay",e[e.Queue=2]="Queue",e[e.Rest=3]="Rest",e[e.TwoWay=4]="TwoWay",e[e.Topic=5]="Topic",e[e.PersistentQueue=6]="PersistentQueue",e[e.EventHub=7]="EventHub",e[e.WebHook=8]="WebHook"})(yg||(E.ServiceEndpointContract=yg={}));var bg;(function(e){e[e.Normal=1]="Normal",e[e.Federated=2]="Federated"})(bg||(E.ServiceEndpointConnectionMode=bg={}));var wg;(function(e){e.CannotDeleteInUseComponent="0x8004f01f",e.CannotDeleteInUseAttribute="0x80048418",e.CannotDeleteInUseOptionSet="0x80048417",e.CannotDeleteInUseEntity="0x80048420",e.CannotUninstallWithDependencies="0x8004F01D"})(wg||(E.DeleteDependencyErrorCode=wg={}));var Ag;(function(e){e.SystemAdministrator="627090FF-40A3-4053-8790-584EDC5BE201",e.SystemCustomizer="119F245C-3CC8-4B62-B31C-D1A046CED15D"})(Ag||(E.DefaultRoleTemplates=Ag={}));var Cg;(function(e){e[e.DefaultTeamPrivilege=0]="DefaultTeamPrivilege",e[e.DirectUserAndTeamPrivilege=1]="DirectUserAndTeamPrivilege"})(Cg||(E.RoleInheritance=Cg={}));var Eg;(function(e){e[e.NotSpecified=0]="NotSpecified",e[e.CustomConnector=1]="CustomConnector"})(Eg||(E.ConnectorTypeEnum=Eg={}));var Sg;(function(e){e[e.String=1e8]="String",e[e.Number=100000001]="Number",e[e.Boolean=100000002]="Boolean",e[e.JSON=100000003]="JSON",e[e.ConnectionReference=100000004]="ConnectionReference",e[e.Secret=100000005]="Secret"})(Sg||(E.EnvironmentVariableDefinitionTypeEnum=Sg={}));var Ng;(function(e){e[e.Owner=0]="Owner",e[e.Access=1]="Access",e[e.AADSecurityGroup=2]="AADSecurityGroup",e[e.AADOfficeGroup=3]="AADOfficeGroup"})(Ng||(E.TeamTypeEnum=Ng={}));var Dg;(function(e){e.Bots="bots"})(Dg||(E.KnownCustomSolutionComponentEntitySetName=Dg={}));var Ig;(function(e){e[e.MainApplicationView=0]="MainApplicationView",e[e.AdvancedSearch=1]="AdvancedSearch",e[e.SubGrid=2]="SubGrid",e[e.QuickFindSearch=4]="QuickFindSearch",e[e.Reporting=8]="Reporting",e[e.OfflineFilters=16]="OfflineFilters",e[e.MASearch=32]="MASearch",e[e.LookupView=64]="LookupView",e[e.SMAppointmentBookView=128]="SMAppointmentBookView",e[e.OutlookFilters=256]="OutlookFilters",e[e.AddressBookFilters=512]="AddressBookFilters",e[e.SavedQueryTypeOther=2048]="SavedQueryTypeOther",e[e.InteractiveWorkflowView=4096]="InteractiveWorkflowView",e[e.OfflineTemplate=8192]="OfflineTemplate",e[e.OutlookTemplate=131072]="OutlookTemplate",e[e.CustomDefinedView=16384]="CustomDefinedView"})(Ig||(E.QueryType=Ig={}))});var te=v(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.IncompatibleWorkspaceError=Y.PathTraversalError=Y.AmbiguousArtifactError=Y.JsonPointerError=Y.NotImplementedError=Y.WorkspaceNotInitializedError=Y.ConnectionError=Y.VersionConflictError=Y.LocalEditsWouldBeLostError=Y.StaleArtifactError=Y.InvalidArgumentError=Y.ValidationError=Y.PathNotFoundError=Y.ArtifactNotFoundError=Y.readPartialTokens=Y.withPartialTokens=Y.SdkError=void 0;var Ke=class extends Error{constructor(t,r){super(r),this.code=t,Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}};Y.SdkError=Ke;var _g=Symbol.for("cds-maker-sdk.partialWriteTokens");function NP(e,t){return typeof e=="object"&&e!==null&&(e[_g]=t),e}Y.withPartialTokens=NP;function DP(e){let t=e;for(let r=0;t&&typeof t=="object"&&r<8;r++){let n=t[_g];if(n&&typeof n=="object")return n;t=t.cause}}Y.readPartialTokens=DP;var bc=class extends Ke{constructor(t,r){super("ARTIFACT_NOT_FOUND",`Artifact ${t}/${r} not found in workspace`),this.type=t,this.id=r}};Y.ArtifactNotFoundError=bc;var wc=class extends Ke{constructor(t,r,n){super("PATH_NOT_FOUND",`Path ${n} not found in ${t}/${r}`),this.type=t,this.id=r,this.pointer=n}};Y.PathNotFoundError=wc;var Ac=class extends Ke{constructor(t,r,n,i){var a,o,s,l;let u=Array.isArray(n)?n:[{pointer:n,rule:i??"invalid",message:i??"invalid"}];super("VALIDATION_ERROR",`Validation failed for ${t}/${r}:+var cO=Object.create;var Hs=Object.defineProperty;var dO=Object.getOwnPropertyDescriptor;var pO=Object.getOwnPropertyNames;var fO=Object.getPrototypeOf,mO=Object.prototype.hasOwnProperty;var T=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var y=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},Zr=(e,t)=>{for(var r in t)Hs(e,r,{get:t[r],enumerable:!0})},js=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of pO(t))!mO.call(e,i)&&i!==r&&Hs(e,i,{get:()=>t[i],enumerable:!(n=dO(t,i))||n.enumerable});return e},Pn=(e,t,r)=>(js(e,t,"default"),r&&js(r,t,"default")),se=(e,t,r)=>(r=e!=null?cO(fO(e)):{},js(t||!e||!e.__esModule?Hs(r,"default",{value:e,enumerable:!0}):r,e)),_r=e=>js(Hs({},"__esModule",{value:!0}),e);var si=y(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.DateTimeBehavior=N.PrecisionSource=N.StringFormatName=N.SourceType=N.ImeMode=N.SolutionEntityTypeCodeExtToComponentTypeCode=N.SolutionComponentTypeCodeToEntityTypeCodeExt=N.SolutionComponentVirtualAttributeSubtype=N.EntityTypeCode=N.SolutionComponentTypeCodeExt=N.RootComponentBehavior=N.SolutionComponentTypeCode=N.EntityKeyIndexStatus=N.ViewStateCode=N.ViewStatusCode=N.RelationshipSecurityTypes=N.CascadeType=N.RelationshipTypeExt=N.RelationshipType=N.AppSubType=N.BusinessProcessType=N.WorkflowCategory=N.WorkflowScope=N.WorkflowTypeCode=N.StatusCodeEnabledDisabled=N.StateCodeEnabledDisabled=N.StatusCode=N.StateCode=N.OptionSetType=N.AttributeTypeCodeNum=N.AttributeFormatName=N.AttributeFormatCode=N.AttributeTypeName=N.AttributeTypeCode=N.PluginSourceType=N.AuthType=N.PluginIsolationMode=N.ComponentState=N.ChartType=N.ChartsType=N.ViewType=N.AttributeType=N.ActivationState=N.FormPresentation=N.FormType=N.TableTypeCode=N.TableTypes=N.ActivityTypeMask=N.PrincipalType=N.OwnershipTypes=void 0;N.QueryType=N.KnownCustomSolutionComponentEntitySetName=N.TeamTypeEnum=N.EnvironmentVariableDefinitionTypeEnum=N.ConnectorTypeEnum=N.RoleInheritance=N.DefaultRoleTemplates=N.DeleteDependencyErrorCode=N.ServiceEndpointConnectionMode=N.ServiceEndpointContract=N.ServiceNamespaceFormat=N.ConnectionRoleCategory=N.ReportTypeCode=N.SdkMessageProcessingMode=N.SupportedDeployment=N.SdkMessageProcessingStage=N.WebResourceTypeCode=N.IntegerFormat=N.DateTimeFormat=void 0;var pg;(function(e){e.None="None",e.UserOwned="UserOwned",e.TeamOwned="TeamOwned",e.BusinessOwned="BusinessOwned",e.OrganizationOwned="OrganizationOwned",e.BusinessParented="BusinessParented",e.Filtered="Filtered"})(pg||(N.OwnershipTypes=pg={}));var fg;(function(e){e.User="Microsoft.Dynamics.CRM.systemuser",e.Team="Microsoft.Dynamics.CRM.team"})(fg||(N.PrincipalType=fg={}));var mg;(function(e){e[e.DoNotDisplayInActivityMenus=0]="DoNotDisplayInActivityMenus",e[e.DisplayInActivityMenus=1]="DisplayInActivityMenus"})(mg||(N.ActivityTypeMask=mg={}));var hg;(function(e){e.Activity="Activity",e.Virtual="Virtual",e.Standard="Standard",e.Elastic="Elastic"})(hg||(N.TableTypes=hg={}));var gg;(function(e){e.Standard="Standard",e.Virtual="Virtual",e.Elastic="Elastic"})(gg||(N.TableTypeCode=gg={}));var vg;(function(e){e[e.Dashboard=0]="Dashboard",e[e.AppointmentBook=1]="AppointmentBook",e[e.Main=2]="Main",e[e.MiniCampaignBO=3]="MiniCampaignBO",e[e.Preview=4]="Preview",e[e.MobileExpress=5]="MobileExpress",e[e.QuickViewForm=6]="QuickViewForm",e[e.QuickCreate=7]="QuickCreate",e[e.Dialog=8]="Dialog",e[e.TaskFlowForm=9]="TaskFlowForm",e[e.InteractionCentricDashboard=10]="InteractionCentricDashboard",e[e.Card=11]="Card",e[e.MainInteractiveExperience=12]="MainInteractiveExperience",e[e.Other=100]="Other",e[e.MainBackup=101]="MainBackup",e[e.AppointmentBookBackup=102]="AppointmentBookBackup",e[e.PowerBIDashboard=103]="PowerBIDashboard"})(vg||(N.FormType=vg={}));var yg;(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(yg||(N.FormPresentation=yg={}));var bg;(function(e){e[e.Inactive=0]="Inactive",e[e.Active=1]="Active"})(bg||(N.ActivationState=bg={}));var wg;(function(e){e[e.String=0]="String",e[e.Number=1]="Number",e[e.Picklist=2]="Picklist"})(wg||(N.AttributeType=wg={}));var Ag;(function(e){e[e.Public=0]="Public",e[e.AdvancedFind=1]="AdvancedFind",e[e.Associated=2]="Associated",e[e.QuickFind=4]="QuickFind",e[e.Lookup=64]="Lookup"})(Ag||(N.ViewType=Ag={}));var Cg;(function(e){e[e.ASPChart=0]="ASPChart",e[e.PowerBI=1]="PowerBI"})(Cg||(N.ChartsType=Cg={}));var Eg;(function(e){e[e.DataAndInteractionCentric=0]="DataAndInteractionCentric",e[e.InteractionCentric=1]="InteractionCentric"})(Eg||(N.ChartType=Eg={}));var Sg;(function(e){e[e.Published=0]="Published",e[e.Unpublished=1]="Unpublished",e[e.Deleted=2]="Deleted",e[e.DeletedUnpublished=3]="DeletedUnpublished"})(Sg||(N.ComponentState=Sg={}));var Ng;(function(e){e[e.None=1]="None",e[e.Sandbox=2]="Sandbox",e[e.External=3]="External"})(Ng||(N.PluginIsolationMode=Ng={}));var Dg;(function(e){e[e.BasicAuth=0]="BasicAuth"})(Dg||(N.AuthType=Dg={}));var Ig;(function(e){e[e.Database=0]="Database",e[e.Disk=1]="Disk",e[e.Normal=2]="Normal",e[e.AzureWebApp=3]="AzureWebApp"})(Ig||(N.PluginSourceType=Ig={}));var _g;(function(e){e.Boolean="Boolean",e.Customer="Customer",e.Date="Date",e.DateTime="DateTime",e.DateTimeNoTimeZone="DateTimeNoTimeZone",e.Decimal="Decimal",e.Double="Double",e.Integer="Integer",e.Lookup="Lookup",e.Memo="Memo",e.Money="Money",e.Owner="Owner",e.PartyList="PartyList",e.Picklist="Picklist",e.State="State",e.Status="Status",e.String="String",e.Uniqueidentifier="Uniqueidentifier",e.CalendarRules="CalendarRules",e.Virtual="Virtual",e.BigInt="BigInt",e.ManagedProperty="ManagedProperty",e.EntityName="EntityName"})(_g||(N.AttributeTypeCode=_g={}));var Tg;(function(e){e.DateTimeType="DateTimeType",e.ImageType="ImageType",e.IntegerType="IntegerType",e.FileType="FileType",e.BooleanType="BooleanType",e.CustomerType="CustomerType",e.MemoType="MemoType",e.MultiSelectPicklistType="MultiSelectPicklistType",e.MoneyType="MoneyType",e.DecimalType="DecimalType",e.DoubleType="DoubleType",e.LookupType="LookupType",e.BigIntType="BigIntType",e.UniqueidentifierType="UniqueidentifierType",e.StringType="StringType",e.OwnerType="OwnerType",e.PicklistType="PicklistType",e.StateType="StateType",e.StatusType="StatusType",e.EntityNameType="EntityNameType"})(Tg||(N.AttributeTypeName=Tg={}));var Pg;(function(e){e.Email="Email",e.Text="Text",e.TextArea="TextArea",e.Url="Url",e.TickerSymbol="TickerSymbol",e.PhoneticGuide="PhoneticGuide",e.VersionNumber="VersionNumber",e.Phone="Phone",e.Json="Json",e.RichText="RichText",e.DateOnly="DateOnly",e.DateAndTime="DateAndTime",e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale"})(Pg||(N.AttributeFormatCode=Pg={}));var Rg;(function(e){e.Text="Text",e.TextArea="TextArea",e.Email="Email",e.Url="Url",e.Phone="Phone",e.Json="Json",e.RichText="RichText",e.TickerSymbol="TickerSymbol",e.PhoneticGuide="PhoneticGuide",e.VersionNumber="VersionNumber",e.DateOnly="DateOnly",e.DateAndTime="DateAndTime"})(Rg||(N.AttributeFormatName=Rg={}));var Og;(function(e){e[e.Boolean=0]="Boolean",e[e.Customer=1]="Customer",e[e.DateTime=2]="DateTime",e[e.Decimal=3]="Decimal",e[e.Double=4]="Double",e[e.Integer=5]="Integer",e[e.Lookup=6]="Lookup",e[e.Memo=7]="Memo",e[e.Money=8]="Money",e[e.Owner=9]="Owner",e[e.PartyList=10]="PartyList",e[e.Picklist=11]="Picklist",e[e.State=12]="State",e[e.Status=13]="Status",e[e.String=14]="String",e[e.Uniqueidentifier=15]="Uniqueidentifier",e[e.CalendarRules=16]="CalendarRules",e[e.Virtual=17]="Virtual",e[e.BigInt=18]="BigInt",e[e.ManagedProperty=19]="ManagedProperty",e[e.EntityName=20]="EntityName"})(Og||(N.AttributeTypeCodeNum=Og={}));var xg;(function(e){e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean"})(xg||(N.OptionSetType=xg={}));var Lg;(function(e){e[e.Draft=0]="Draft",e[e.Activated=1]="Activated"})(Lg||(N.StateCode=Lg={}));var Fg;(function(e){e[e.Draft=1]="Draft",e[e.Activated=2]="Activated"})(Fg||(N.StatusCode=Fg={}));var kg;(function(e){e[e.Enabled=0]="Enabled",e[e.Disabled=1]="Disabled"})(kg||(N.StateCodeEnabledDisabled=kg={}));var Mg;(function(e){e[e.Enabled=1]="Enabled",e[e.Disabled=2]="Disabled"})(Mg||(N.StatusCodeEnabledDisabled=Mg={}));var Bg;(function(e){e[e.Definition=1]="Definition",e[e.Activation=2]="Activation",e[e.Template=3]="Template"})(Bg||(N.WorkflowTypeCode=Bg={}));var Ug;(function(e){e[e.User=1]="User",e[e.BusinessUnit=2]="BusinessUnit",e[e.ParentChildBusinessUnit=3]="ParentChildBusinessUnit",e[e.Organization=4]="Organization"})(Ug||(N.WorkflowScope=Ug={}));var $g;(function(e){e[e.Workflow=0]="Workflow",e[e.Dialog=1]="Dialog",e[e.BusinessRule=2]="BusinessRule",e[e.Action=3]="Action",e[e.BusinessProcessFlow=4]="BusinessProcessFlow",e[e.Flow=5]="Flow",e[e.UIFlow=6]="UIFlow"})($g||(N.WorkflowCategory=$g={}));var qg;(function(e){e[e.None=-1]="None",e[e.BusinessFlow=0]="BusinessFlow",e[e.TaskFlow=1]="TaskFlow"})(qg||(N.BusinessProcessType=qg={}));var Vg;(function(e){e[e.CanvasApp=0]="CanvasApp",e[e.ComponentLibrary=1]="ComponentLibrary",e[e.CustomCanvasPage=2]="CustomCanvasPage",e[e.UnifiedApp=3]="UnifiedApp",e[e.CodeApp=4]="CodeApp",e[e.MobileApp=5]="MobileApp"})(Vg||(N.AppSubType=Vg={}));var Gg;(function(e){e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(Gg||(N.RelationshipType=Gg={}));var zg;(function(e){e.ManyToOneRelationship="ManyToOneRelationship",e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(zg||(N.RelationshipTypeExt=zg={}));var Wg;(function(e){e.NoCascade="NoCascade",e.Cascade="Cascade",e.Active="Active",e.UserOwned="UserOwned",e.RemoveLink="RemoveLink",e.Restrict="Restrict"})(Wg||(N.CascadeType=Wg={}));var jg;(function(e){e.None="None",e.Append="Append",e.ParentChild="ParentChild",e.Pointer="Pointer",e.Inheritance="Inheritance"})(jg||(N.RelationshipSecurityTypes=jg={}));var Hg;(function(e){e[e.Active=1]="Active",e[e.Inactive=2]="Inactive"})(Hg||(N.ViewStatusCode=Hg={}));var Jg;(function(e){e[e.Active=0]="Active",e[e.Inactive=1]="Inactive"})(Jg||(N.ViewStateCode=Jg={}));var Kg;(function(e){e.Active="Active",e.Failed="Failed",e.InProgress="InProgress",e.Pending="Pending"})(Kg||(N.EntityKeyIndexStatus=Kg={}));var Qg;(function(e){e[e.Entity=1]="Entity",e[e.Attribute=2]="Attribute",e[e.OptionSet=9]="OptionSet",e[e.EntityRelationship=10]="EntityRelationship",e[e.EntityKey=14]="EntityKey",e[e.Role=20]="Role",e[e.DisplayString=22]="DisplayString",e[e.SavedQuery=26]="SavedQuery",e[e.Workflow=29]="Workflow",e[e.Report=31]="Report",e[e.Template=36]="Template",e[e.ContractTemplate=37]="ContractTemplate",e[e.KbArticleTemplate=38]="KbArticleTemplate",e[e.MailMergeTemplate=39]="MailMergeTemplate",e[e.RibbonCustomization=50]="RibbonCustomization",e[e.SavedQueryVisualization=59]="SavedQueryVisualization",e[e.SystemForm=60]="SystemForm",e[e.WebResource=61]="WebResource",e[e.SiteMap=62]="SiteMap",e[e.ConnectionRole=63]="ConnectionRole",e[e.HierarchyRule=65]="HierarchyRule",e[e.CustomControl=66]="CustomControl",e[e.FieldSecurityProfile=70]="FieldSecurityProfile",e[e.AppModule=80]="AppModule",e[e.PluginAssembly=91]="PluginAssembly",e[e.SdkMessageProcessingStep=92]="SdkMessageProcessingStep",e[e.ServiceEndpoint=95]="ServiceEndpoint",e[e.RoutingRule=150]="RoutingRule",e[e.SLA=152]="SLA",e[e.ConvertRule=154]="ConvertRule",e[e.MobileOfflineProfile=161]="MobileOfflineProfile",e[e.EntityDataProvider=181]="EntityDataProvider",e[e.EntityDataSource=183]="EntityDataSource",e[e.SdkMessage=201]="SdkMessage",e[e.CanvasApp=300]="CanvasApp",e[e.Connector=372]="Connector",e[e.EnvironmentVariableDefinition=380]="EnvironmentVariableDefinition",e[e.EnvironmentVariableValue=381]="EnvironmentVariableValue",e[e.AIModel=401]="AIModel",e[e.Dataflow=418]="Dataflow",e[e.DataflowEntities=419]="DataflowEntities",e[e.DualWriteEntityMap=500]="DualWriteEntityMap",e[e.DataIntegrationConnection=501]="DataIntegrationConnection",e[e.ExportToDataLakeConfig=510]="ExportToDataLakeConfig",e[e.Tour=10061]="Tour"})(Qg||(N.SolutionComponentTypeCode=Qg={}));var Xg;(function(e){e[e.IncludeSubcomponents=0]="IncludeSubcomponents",e[e.DoNotIncludeSubcomponents=1]="DoNotIncludeSubcomponents",e[e.IncludeAsShellOnly=2]="IncludeAsShellOnly"})(Xg||(N.RootComponentBehavior=Xg={}));var Js;(function(e){e[e.Entity=1]="Entity",e[e.Attribute=2]="Attribute",e[e.OptionSet=9]="OptionSet",e[e.EntityRelationship=10]="EntityRelationship",e[e.EntityKey=14]="EntityKey",e[e.Role=20]="Role",e[e.DisplayString=22]="DisplayString",e[e.SavedQuery=26]="SavedQuery",e[e.Workflow=29]="Workflow",e[e.Report=31]="Report",e[e.Template=36]="Template",e[e.ContractTemplate=37]="ContractTemplate",e[e.KbArticleTemplate=38]="KbArticleTemplate",e[e.MailMergeTemplate=39]="MailMergeTemplate",e[e.RibbonCustomization=50]="RibbonCustomization",e[e.SavedQueryVisualization=59]="SavedQueryVisualization",e[e.SystemForm=60]="SystemForm",e[e.WebResource=61]="WebResource",e[e.SiteMap=62]="SiteMap",e[e.ConnectionRole=63]="ConnectionRole",e[e.HierarchyRule=65]="HierarchyRule",e[e.CustomControl=66]="CustomControl",e[e.FieldSecurityProfile=70]="FieldSecurityProfile",e[e.AppModule=80]="AppModule",e[e.PluginAssembly=91]="PluginAssembly",e[e.SdkMessageProcessingStep=92]="SdkMessageProcessingStep",e[e.ServiceEndpoint=95]="ServiceEndpoint",e[e.RoutingRule=150]="RoutingRule",e[e.SLA=152]="SLA",e[e.ConvertRule=154]="ConvertRule",e[e.MobileOfflineProfile=161]="MobileOfflineProfile",e[e.EntityDataProvider=181]="EntityDataProvider",e[e.EntityDataSource=183]="EntityDataSource",e[e.SdkMessage=201]="SdkMessage",e[e.CanvasApp=300]="CanvasApp",e[e.Connector=372]="Connector",e[e.EnvironmentVariableDefinition=380]="EnvironmentVariableDefinition",e[e.EnvironmentVariableValue=381]="EnvironmentVariableValue",e[e.AIModel=401]="AIModel",e[e.Dataflow=418]="Dataflow",e[e.DataflowEntities=419]="DataflowEntities",e[e.DualWriteEntityMap=500]="DualWriteEntityMap",e[e.DataIntegrationConnection=501]="DataIntegrationConnection",e[e.ExportToDataLakeConfig=510]="ExportToDataLakeConfig",e[e.DataWorkspace=10282]="DataWorkspace",e[e.Dashboard=100001]="Dashboard",e[e.InteractionCentricDashboard=100002]="InteractionCentricDashboard",e[e.Dialog=100003]="Dialog",e[e.PowerBIDashboard=100004]="PowerBIDashboard",e[e.BusinessRule=100021]="BusinessRule",e[e.ProcessFlow=100024]="ProcessFlow",e[e.Flow=100025]="Flow",e[e.UIFlow=100026]="UIFlow",e[e.ProcessNoFlow=100031]="ProcessNoFlow",e[e.AllDashboards=100032]="AllDashboards",e[e.FormsOnly=100033]="FormsOnly",e[e.ComponentLibrary=100034]="ComponentLibrary",e[e.CanvasAppsOnly=100035]="CanvasAppsOnly",e[e.CustomCanvasPage=100038]="CustomCanvasPage",e[e.CodeApp=100039]="CodeApp",e[e.MobileApp=100046]="MobileApp",e[e.ProcessNoFlowNoUIFlowNoBusinessRule=100036]="ProcessNoFlowNoUIFlowNoBusinessRule",e[e.ActionDefinition=100040]="ActionDefinition",e[e.ActionTemplate=100041]="ActionTemplate",e[e.DialogDefinition=100042]="DialogDefinition",e[e.DialogTemplate=100043]="DialogTemplate",e[e.WorkflowDefinition=100044]="WorkflowDefinition",e[e.WorkflowTemplate=100045]="WorkflowTemplate"})(Js||(N.SolutionComponentTypeCodeExt=Js={}));var Ks;(function(e){e[e.Entity=9801]="Entity",e[e.Attribute=9802]="Attribute",e[e.OptionSet=9804]="OptionSet",e[e.EntityRelationship=9805]="EntityRelationship",e[e.EntityKey=9812]="EntityKey",e[e.Role=1036]="Role",e[e.DisplayString=4102]="DisplayString",e[e.SavedQuery=1039]="SavedQuery",e[e.Workflow=4703]="Workflow",e[e.Report=9100]="Report",e[e.Template=2010]="Template",e[e.ContractTemplate=2011]="ContractTemplate",e[e.KbArticleTemplate=1016]="KbArticleTemplate",e[e.MailMergeTemplate=9106]="MailMergeTemplate",e[e.SavedQueryVisualization=1111]="SavedQueryVisualization",e[e.SystemForm=1030]="SystemForm",e[e.WebResource=9333]="WebResource",e[e.SiteMap=4709]="SiteMap",e[e.ConnectionRole=3231]="ConnectionRole",e[e.HierarchyRule=8840]="HierarchyRule",e[e.CustomControl=9753]="CustomControl",e[e.FieldSecurityProfile=1200]="FieldSecurityProfile",e[e.AppModule=9006]="AppModule",e[e.PluginAssembly=4605]="PluginAssembly",e[e.SdkMessageProcessingStep=4608]="SdkMessageProcessingStep",e[e.ServiceEndpoint=4618]="ServiceEndpoint",e[e.RoutingRule=8181]="RoutingRule",e[e.SLA=9750]="SLA",e[e.ConvertRule=9300]="ConvertRule",e[e.MobileOfflineProfile=9866]="MobileOfflineProfile",e[e.EntityDataSource=85]="EntityDataSource",e[e.SdkMessage=4606]="SdkMessage",e[e.RibbonCustomization=1120]="RibbonCustomization",e[e.EntityDataProvider=181]="EntityDataProvider",e[e.CanvasApp=300]="CanvasApp",e[e.Connector=372]="Connector",e[e.MaskingRule=373]="MaskingRule",e[e.AttributeMaskingRule=374]="AttributeMaskingRule",e[e.EnvironmentVariableDefinition=380]="EnvironmentVariableDefinition",e[e.EnvironmentVariableValue=381]="EnvironmentVariableValue",e[e.AIModel=401]="AIModel",e[e.Plan=10283]="Plan",e[e.Dataflow=418]="Dataflow",e[e.DataflowEntities=419]="DataflowEntities",e[e.DualWriteEntityMap=500]="DualWriteEntityMap",e[e.DataIntegrationConnection=501]="DataIntegrationConnection",e[e.ExportToDataLakeConfig=510]="ExportToDataLakeConfig",e[e.TeamTemplate=511]="TeamTemplate",e[e.DataWorkspace=10282]="DataWorkspace",e[e.Dashboard=1030]="Dashboard",e[e.InteractionCentricDashboard=1032]="InteractionCentricDashboard",e[e.PowerBIDashboard=1034]="PowerBIDashboard",e[e.Dialog=1030]="Dialog",e[e.WebResourceImage=9333]="WebResourceImage",e[e.WebResourceSilverlight=9333]="WebResourceSilverlight",e[e.WebResourceCode=9333]="WebResourceCode",e[e.WebResourceData=9333]="WebResourceData",e[e.BusinessRule=4703]="BusinessRule",e[e.ActionDefinition=4703]="ActionDefinition",e[e.ActionTemplate=4703]="ActionTemplate",e[e.DialogDefinition=4703]="DialogDefinition",e[e.DialogTemplate=4703]="DialogTemplate",e[e.WorkflowDefinition=4703]="WorkflowDefinition",e[e.WorkflowTemplate=4703]="WorkflowTemplate",e[e.ProcessFlow=4703]="ProcessFlow",e[e.Flow=4703]="Flow",e[e.UIFlow=4703]="UIFlow",e[e.ProcessNoFlow=4703]="ProcessNoFlow",e[e.ProcessNoFlowNoUIFlowNoBusinessRule=4703]="ProcessNoFlowNoUIFlowNoBusinessRule",e[e.AllDashboards=1030]="AllDashboards",e[e.FormsOnly=1030]="FormsOnly",e[e.ComponentLibrary=300]="ComponentLibrary",e[e.CanvasAppsOnly=300]="CanvasAppsOnly",e[e.CustomCanvasPage=300]="CustomCanvasPage",e[e.CodeApp=300]="CodeApp",e[e.MobileApp=300]="MobileApp",e[e.Chatbot=10030]="Chatbot",e[e.Card=10276]="Card"})(Ks||(N.EntityTypeCode=Ks={}));var Yg;(function(e){e.MultiSelectPicklist="MultiSelectPicklist",e.File="File",e.Image="Image"})(Yg||(N.SolutionComponentVirtualAttributeSubtype=Yg={}));function hO(e){let t=Js[e];return Ks[t]}N.SolutionComponentTypeCodeToEntityTypeCodeExt=hO;function gO(e){let t=Ks[e];return Js[t]}N.SolutionEntityTypeCodeExtToComponentTypeCode=gO;var Zg;(function(e){e.Active="Active",e.Auto="Auto",e.Disabled="Disabled",e.Inactive="Inactive"})(Zg||(N.ImeMode=Zg={}));var e0;(function(e){e[e.Simple=0]="Simple",e[e.Calculated=1]="Calculated",e[e.Rollup=2]="Rollup",e[e.Formula=3]="Formula",e[e.Prompt=4]="Prompt"})(e0||(N.SourceType=e0={}));var t0;(function(e){e.Email="Email",e.Phone="Phone",e.PhoneticGuide="PhoneticGuide",e.Text="Text",e.TextArea="TextArea",e.TickerSymbol="TickerSymbol",e.Url="Url",e.VersionNumber="VersionNumber"})(t0||(N.StringFormatName=t0={}));var r0;(function(e){e[e.PrecisionProperty=0]="PrecisionProperty",e[e.Organization=1]="Organization",e[e.TransactionCurrency=2]="TransactionCurrency"})(r0||(N.PrecisionSource=r0={}));var n0;(function(e){e.UserLocal="UserLocal",e.DateOnly="DateOnly",e.TimeZoneIndependent="TimeZoneIndependent"})(n0||(N.DateTimeBehavior=n0={}));var i0;(function(e){e.DateOnly="DateOnly",e.DateAndTime="DateAndTime"})(i0||(N.DateTimeFormat=i0={}));var a0;(function(e){e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale"})(a0||(N.IntegerFormat=a0={}));var o0;(function(e){e[e.HTML=1]="HTML",e[e.CSS=2]="CSS",e[e.JScript=3]="JScript",e[e.XML=4]="XML",e[e.PNG=5]="PNG",e[e.JPG=6]="JPG",e[e.GIF=7]="GIF",e[e.Silverlight=8]="Silverlight",e[e.XSL=9]="XSL",e[e.ICO=10]="ICO",e[e.SVG=11]="SVG",e[e.RESX=12]="RESX"})(o0||(N.WebResourceTypeCode=o0={}));var s0;(function(e){e[e.Initial=5]="Initial",e[e.PreValidation=10]="PreValidation",e[e.InternalPreOperationBeforeExternal=15]="InternalPreOperationBeforeExternal",e[e.PreOperation=20]="PreOperation",e[e.InternalPreOperationAfterExternal=25]="InternalPreOperationAfterExternal",e[e.MainOperation=30]="MainOperation",e[e.InternalPostOperationBeforeExternal=35]="InternalPostOperationBeforeExternal",e[e.PostOperation=40]="PostOperation",e[e.InternalPostOperationAfterExternal=45]="InternalPostOperationAfterExternal",e[e.PostOperationDeprecated=50]="PostOperationDeprecated",e[e.FinalPostOperation=55]="FinalPostOperation"})(s0||(N.SdkMessageProcessingStage=s0={}));var l0;(function(e){e[e.ServerOnly=0]="ServerOnly",e[e.OutlookClientOnly=1]="OutlookClientOnly",e[e.Both=2]="Both"})(l0||(N.SupportedDeployment=l0={}));var u0;(function(e){e[e.Synchronous=0]="Synchronous",e[e.Asynchronous=1]="Asynchronous"})(u0||(N.SdkMessageProcessingMode=u0={}));var c0;(function(e){e[e.ReportingServicesReport=1]="ReportingServicesReport",e[e.OtherReport=2]="OtherReport",e[e.LinkedReport=3]="LinkedReport"})(c0||(N.ReportTypeCode=c0={}));var d0;(function(e){e[e.Business=1]="Business",e[e.Family=2]="Family",e[e.Social=3]="Social",e[e.Sales=4]="Sales",e[e.Other=5]="Other",e[e.Stakeholder=1e3]="Stakeholder",e[e.SalesTeam=1001]="SalesTeam",e[e.Service=1002]="Service"})(d0||(N.ConnectionRoleCategory=d0={}));var p0;(function(e){e[e.Name=1]="Name",e[e.Address=2]="Address"})(p0||(N.ServiceNamespaceFormat=p0={}));var f0;(function(e){e[e.OneWay=1]="OneWay",e[e.Queue=2]="Queue",e[e.Rest=3]="Rest",e[e.TwoWay=4]="TwoWay",e[e.Topic=5]="Topic",e[e.PersistentQueue=6]="PersistentQueue",e[e.EventHub=7]="EventHub",e[e.WebHook=8]="WebHook"})(f0||(N.ServiceEndpointContract=f0={}));var m0;(function(e){e[e.Normal=1]="Normal",e[e.Federated=2]="Federated"})(m0||(N.ServiceEndpointConnectionMode=m0={}));var h0;(function(e){e.CannotDeleteInUseComponent="0x8004f01f",e.CannotDeleteInUseAttribute="0x80048418",e.CannotDeleteInUseOptionSet="0x80048417",e.CannotDeleteInUseEntity="0x80048420",e.CannotUninstallWithDependencies="0x8004F01D"})(h0||(N.DeleteDependencyErrorCode=h0={}));var g0;(function(e){e.SystemAdministrator="627090FF-40A3-4053-8790-584EDC5BE201",e.SystemCustomizer="119F245C-3CC8-4B62-B31C-D1A046CED15D"})(g0||(N.DefaultRoleTemplates=g0={}));var v0;(function(e){e[e.DefaultTeamPrivilege=0]="DefaultTeamPrivilege",e[e.DirectUserAndTeamPrivilege=1]="DirectUserAndTeamPrivilege"})(v0||(N.RoleInheritance=v0={}));var y0;(function(e){e[e.NotSpecified=0]="NotSpecified",e[e.CustomConnector=1]="CustomConnector"})(y0||(N.ConnectorTypeEnum=y0={}));var b0;(function(e){e[e.String=1e8]="String",e[e.Number=100000001]="Number",e[e.Boolean=100000002]="Boolean",e[e.JSON=100000003]="JSON",e[e.ConnectionReference=100000004]="ConnectionReference",e[e.Secret=100000005]="Secret"})(b0||(N.EnvironmentVariableDefinitionTypeEnum=b0={}));var w0;(function(e){e[e.Owner=0]="Owner",e[e.Access=1]="Access",e[e.AADSecurityGroup=2]="AADSecurityGroup",e[e.AADOfficeGroup=3]="AADOfficeGroup"})(w0||(N.TeamTypeEnum=w0={}));var A0;(function(e){e.Bots="bots"})(A0||(N.KnownCustomSolutionComponentEntitySetName=A0={}));var C0;(function(e){e[e.MainApplicationView=0]="MainApplicationView",e[e.AdvancedSearch=1]="AdvancedSearch",e[e.SubGrid=2]="SubGrid",e[e.QuickFindSearch=4]="QuickFindSearch",e[e.Reporting=8]="Reporting",e[e.OfflineFilters=16]="OfflineFilters",e[e.MASearch=32]="MASearch",e[e.LookupView=64]="LookupView",e[e.SMAppointmentBookView=128]="SMAppointmentBookView",e[e.OutlookFilters=256]="OutlookFilters",e[e.AddressBookFilters=512]="AddressBookFilters",e[e.SavedQueryTypeOther=2048]="SavedQueryTypeOther",e[e.InteractiveWorkflowView=4096]="InteractiveWorkflowView",e[e.OfflineTemplate=8192]="OfflineTemplate",e[e.OutlookTemplate=131072]="OutlookTemplate",e[e.CustomDefinedView=16384]="CustomDefinedView"})(C0||(N.QueryType=C0={}))});var ee=y(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.IncompatibleWorkspaceError=Z.PathTraversalError=Z.AmbiguousArtifactError=Z.JsonPointerError=Z.NotImplementedError=Z.WorkspaceNotInitializedError=Z.ConnectionError=Z.VersionConflictError=Z.LocalEditsWouldBeLostError=Z.StaleArtifactError=Z.InvalidArgumentError=Z.ValidationError=Z.PathNotFoundError=Z.ArtifactNotFoundError=Z.readPartialTokens=Z.withPartialTokens=Z.SdkError=void 0;var nt=class extends Error{constructor(t,r){super(r),this.code=t,Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}};Z.SdkError=nt;var E0=Symbol.for("cds-maker-sdk.partialWriteTokens");function vO(e,t){return typeof e=="object"&&e!==null&&(e[E0]=t),e}Z.withPartialTokens=vO;function yO(e){let t=e;for(let r=0;t&&typeof t=="object"&&r<8;r++){let n=t[E0];if(n&&typeof n=="object")return n;t=t.cause}}Z.readPartialTokens=yO;var rd=class extends nt{constructor(t,r){super("ARTIFACT_NOT_FOUND",`Artifact ${t}/${r} not found in workspace`),this.type=t,this.id=r}};Z.ArtifactNotFoundError=rd;var nd=class extends nt{constructor(t,r,n){super("PATH_NOT_FOUND",`Path ${n} not found in ${t}/${r}`),this.type=t,this.id=r,this.pointer=n}};Z.PathNotFoundError=nd;var id=class extends nt{constructor(t,r,n,i){var a,o,s,l;let u=Array.isArray(n)?n:[{pointer:n,rule:i??"invalid",message:i??"invalid"}];super("VALIDATION_ERROR",`Validation failed for ${t}/${r}:`+u.map(c=>` \u2022 ${c.pointer}: ${c.message} [${c.rule}]`).join(`-`)),this.type=t,this.id=r,this.issues=u,this.pointer=(o=(a=u[0])===null||a===void 0?void 0:a.pointer)!==null&&o!==void 0?o:"",this.rule=(l=(s=u[0])===null||s===void 0?void 0:s.rule)!==null&&l!==void 0?l:"invalid"}};Y.ValidationError=Ac;var Cc=class extends Ke{constructor(t){super("INVALID_ARGUMENT",t)}};Y.InvalidArgumentError=Cc;var Ec=class extends Ke{constructor(t,r,n){super("STALE_ARTIFACT",`Cannot apply the edit at ${n} to ${t}/${r}: the cached copy was stale and the server copy has since changed, so any pointer derived from the old copy may now identify a different node. The local copy has been refreshed \u2014 re-read the artifact, re-derive the pointer, and retry.`),this.type=t,this.id=r,this.pointer=n}};Y.StaleArtifactError=Ec;var Sc=class extends Ke{constructor(t,r,n,i){super("LOCAL_EDITS_WOULD_BE_LOST",`Refusing to fetch ${t}/${r}: the local copy has unpushed edits AND the server has moved since it was fetched (local=${n??"(none)"}, server=${i??"(none)"}). Overwriting now would discard your edits and replace them with another writer's changes. Push or discard your edits first, or pass { overwrite: true } to deliberately reset the local copy to the server version.`),this.type=t,this.id=r,this.localEtag=n,this.serverEtag=i}};Y.LocalEditsWouldBeLostError=Sc;var Nc=class extends Ke{constructor(t,r,n,i,a){super("VERSION_CONFLICT",`Version conflict for ${t}/${r}: local=${n??"(none)"}, server=${i??"(none)"}. Re-fetch and reapply changes.${a?` ${a}`:""}`),this.type=t,this.id=r,this.localEtag=n,this.serverEtag=i,this.detail=a}};Y.VersionConflictError=Nc;var Dc=class extends Ke{constructor(t,r,n,i){super("CONNECTION_ERROR",r>0?`HTTP ${r} from ${t}: ${n}`:`Transport failure reaching ${t}: ${n}`),this.url=t,this.statusCode=r,this.cause=i}};Y.ConnectionError=Dc;var Ic=class extends Ke{constructor(t){super("WORKSPACE_NOT_INITIALIZED",`Workspace not initialized at ${t}. Call initWorkspace() first.`),this.workspacePath=t}};Y.WorkspaceNotInitializedError=Ic;var _c=class extends Ke{constructor(t,r){super("NOT_IMPLEMENTED",`Operation '${t}' is not implemented yet${r?`: ${r}`:""}.`),this.operation=t}};Y.NotImplementedError=_c;var Tc=class extends Ke{constructor(t,r){super("INVALID_JSON_POINTER",`Invalid JSON Pointer '${t}': ${r}`),this.pointer=t}};Y.JsonPointerError=Tc;var Pc=class extends Ke{constructor(t,r,n){super("AMBIGUOUS_ARTIFACT",`Found ${n} ${t} rows matching '${r}'; a name is not a unique key. Resolve by id / alternate key instead of relying on name-based idempotency.`),this.kind=t,this.identity=r,this.matchCount=n}};Y.AmbiguousArtifactError=Pc;var Oc=class extends Ke{constructor(t,r){super("PATH_TRAVERSAL",`Refusing to resolve a path outside the workspace root: '${t}' is not within '${r}'.`),this.target=t,this.root=r}};Y.PathTraversalError=Oc;var Rc=class extends Ke{constructor(t,r){super("INCOMPATIBLE_WORKSPACE",`Workspace schema version ${t} is newer than this SDK supports (v${r}). Upgrade the SDK, or re-create the workspace with this version.`),this.workspaceVersion=t,this.supportedVersion=r}};Y.IncompatibleWorkspaceError=Rc});var ae=v(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.odataQuery=Pe.normalizeGuid=Pe.createSafeXmlElement=Pe.assertNoControlChars=Pe.assertODataName=Pe.assertXmlName=Pe.xmlText=Pe.odataPathLiteral=Pe.odataLiteral=void 0;var Is=te();function Tg(e){return String(e??"").replace(/'/g,"''")}Pe.odataLiteral=Tg;function IP(e){return encodeURIComponent(Tg(e))}Pe.odataPathLiteral=IP;function _P(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}Pe.xmlText=_P;function Pg(e,t){let r=String(e??""),n=/^[A-Za-z_][0-9A-Za-z_.-]*$/,i=r.split(":");if(!(i.length<=2&&i.every(o=>n.test(o))&&!/^xmlns/i.test(r)))throw new Is.InvalidArgumentError(`${t} must be a valid XML element name (got '${e}')`);return e}Pe.assertXmlName=Pg;function TP(e,t){let r=String(e??"");if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw new Is.InvalidArgumentError(`${t} must be a valid OData identifier (letters, digits, underscore): got '${e}'`);return e}Pe.assertODataName=TP;function PP(e,t){if(/[\u0000-\u001F\u007F]/.test(String(e??"")))throw new Is.InvalidArgumentError(`${t} must not contain control characters (including CR/LF): they would inject additional lines into the request`);return e}Pe.assertNoControlChars=PP;function OP(e,t,r){return e.createElement(Pg(t,r))}Pe.createSafeXmlElement=OP;var RP=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;function FP(e,t){let r=String(e??""),n=r.length===38&&r.startsWith("{")&&r.endsWith("}")?r.slice(1,-1):r;if(!RP.test(n))throw new Is.InvalidArgumentError(`${t} must be a valid GUID (got '${e}')`);return n.toLowerCase()}Pe.normalizeGuid=FP;function xP(e){let t=[];for(let[r,n]of e)n!=null&&n!==""&&t.push(`${r}=${encodeURIComponent(String(n))}`);return t.length>0?`?${t.join("&")}`:""}Pe.odataQuery=xP});var be=v(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.nowIso=oe.isAlreadyDeleted=oe.deleteRecord=oe.ensureSuccess=oe.resolveCreatedId=oe.requireCreatedId=oe.withClientMintedId=oe.readCreatedId=oe.readEtag=oe.requireEtag=oe.echoWrite=oe.UPDATE_NO_ETAG_CODE=oe.VERSION_CONFLICT_CODE=void 0;var Ni=te(),Ka=ae();oe.VERSION_CONFLICT_CODE="VERSION_CONFLICT";oe.UPDATE_NO_ETAG_CODE="ARTIFACT_UPDATE_NO_ETAG";function LP(e,t){return{query:`?$select=${encodeURIComponent(e)}`,options:{headers:{...t??{},Prefer:"return=representation"}}}}oe.echoWrite=LP;function kP(e,t,r){if(!e)throw new Ni.SdkError(oe.UPDATE_NO_ETAG_CODE,`Refusing to push ${t} '${r}': no concurrency token is held for it, so the write could not be made conditional and would silently overwrite a concurrent edit. Re-fetch the ${t} and re-apply the change.`);return e}oe.requireEtag=kP;function MP(e){var t;let r=(t=e.headers)!==null&&t!==void 0?t:{};for(let i of Object.keys(r))if(i.toLowerCase()==="etag")return r[i];let n=e.body;return n&&typeof n["@odata.etag"]=="string"?n["@odata.etag"]:null}oe.readEtag=MP;function Fc(e,t){var r;let n=e.body;if(n&&typeof n[t]=="string")return(0,Ka.normalizeGuid)(n[t],t);let i=(r=e.headers)!==null&&r!==void 0?r:{};for(let a of Object.keys(i))if(a.toLowerCase()==="odata-entityid"){let o=/\(([0-9a-fA-F-]{36})\)/.exec(i[a]);if(o)return(0,Ka.normalizeGuid)(o[1],t)}return null}oe.readCreatedId=Fc;function UP(e,t,r){return r?{...e,[t]:(0,Ka.normalizeGuid)(r,t)}:e}oe.withClientMintedId=UP;function BP(e,t,r){let n=Fc(e,t);if(!n)throw new Ni.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`);return n}oe.requireCreatedId=BP;function $P(e,t,r,n){let i=Fc(e,t);if(i)return i;if(n)return(0,Ka.normalizeGuid)(n,t);throw new Ni.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`)}oe.resolveCreatedId=$P;function Og(e,t){if(e.status===412)throw new Ni.SdkError(oe.VERSION_CONFLICT_CODE,`Version conflict (412) from ${t}`);if(e.status<200||e.status>=300)throw new Ni.ConnectionError(t,e.status,qP(e.body),e.body);return e}oe.ensureSuccess=Og;function qP(e){if(typeof e=="string"&&e.length>0)return e;if(e!==null&&typeof e=="object"){let t=e;if(t.error&&typeof t.error.message=="string")return t.error.message;if(typeof t.Message=="string")return t.Message;if(typeof t.message=="string")return t.message}return"request failed"}async function VP(e,t,r,n){let i=(0,Ka.normalizeGuid)(r,"id"),a=`/${t}(${i})`;Og(await e.delete(a,n?{headers:{"If-Match":n}}:void 0),e.apiUrl(a))}oe.deleteRecord=VP;function GP(e){return e instanceof Ni.ConnectionError&&e.statusCode===404}oe.isAlreadyDeleted=GP;function zP(){return new Date().toISOString()}oe.nowIso=zP});var qt=v(Di=>{"use strict";Object.defineProperty(Di,"__esModule",{value:!0});Di.describeMalformedValue=Di.collectPages=void 0;var Rg=be(),xc=te();async function WP(e,t,r,n){let i=[],a=new Set,o=e.apiUrl(t),s=(0,Rg.ensureSuccess)(await e.get(t),o);for(n?.(s);;){let l=s.body,u=l?.value;if(!Array.isArray(u))throw new xc.ConnectionError(o,s.status,`${r}: paginated read returned a malformed page \u2014 expected an OData 'value' array but got ${Lc(u)}; refusing to return partial results.`);for(let d of u)i.push(d);let c=l?.["@odata.nextLink"];if(c==null)break;if(typeof c!="string"||c.length===0)throw new xc.ConnectionError(o,s.status,`${r}: paginated read returned a malformed @odata.nextLink (${Lc(c)}); cannot follow it, and refusing to return partial results.`);if(a.has(c))throw new xc.InvalidArgumentError(`${r}: aborting pagination \u2014 the server returned a repeated @odata.nextLink ('${c}'), which would loop indefinitely.`);a.add(c),o=c,s=(0,Rg.ensureSuccess)(await e.getAbsolute(c),c)}return i}Di.collectPages=WP;function Lc(e){return e===null?"null":e===void 0?"undefined (missing)":`a ${typeof e}`}Di.describeMalformedValue=Lc});var kc=v(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.businessRuleApi=wr.BUSINESS_RULE_LEFT_DEACTIVATED_CODE=wr.WFOM_API_UNAVAILABLE_CODE=void 0;var Wr=Yn(),HP=qt(),Xe=be(),wn=ae(),Ts=te();wr.WFOM_API_UNAVAILABLE_CODE="BUSINESS_RULE_API_UNAVAILABLE";wr.BUSINESS_RULE_LEFT_DEACTIVATED_CODE="BUSINESS_RULE_LEFT_DEACTIVATED";async function Fg(e,t,r,n){let i=`/workflows(${QP})/Microsoft.Dynamics.CRM.${t}`;try{return(0,Xe.ensureSuccess)(await e.post(i,{Entity:r.Entity,WfomJson:r.WfomJson},{headers:n}),e.apiUrl(i))}catch(a){throw a?.statusCode!==404?a:new Ts.SdkError(wr.WFOM_API_UNAVAILABLE_CODE,`Business-rule authoring (preview) is not enabled on this environment yet: it does not expose 'Microsoft.Dynamics.CRM.${t}'. The bound members are still rolling out, so re-check once the release flag reaches this environment. Nothing was written. The SDK does NOT fall back to generating workflow XAML: that covered only 4 of the 7 action types and would silently save a rule different from the one you wrote.`)}}async function jP(e,t){let r=`/workflows(${t})${(0,wn.odataQuery)([["$select","workflowid,statecode,statuscode"]])}`;try{let n=await e.get(r);if(n.status<200||n.status>=300)return null;let i=n.body;return{etag:(0,Xe.readEtag)(n),statecode:typeof i?.statecode=="number"?i.statecode:null,statuscode:typeof i?.statuscode=="number"?i.statuscode:null}}catch{return null}}async function JP(e,t,r){let n=await jP(e,t);if(n===null||n.etag===null)throw new Ts.SdkError(Xe.VERSION_CONFLICT_CODE,`Refusing to update business rule '${t}': its current version could not be read, so the write could not be verified as conditional. The supported update api does not enforce If-Match, so proceeding would risk silently overwriting a concurrent edit. Re-fetch the rule and try again.`);if(n.etag!==r)throw new Ts.SdkError(Xe.VERSION_CONFLICT_CODE,`Version conflict updating business rule '${t}': it changed on the server since it was fetched (held ${r}, server ${n.etag}). Re-fetch the rule and re-apply the change.`);return{statecode:n.statecode,statuscode:n.statuscode}}var QP="00000000-0000-0000-0000-000000000000",_s={"Content-Type":"application/json",Accept:"application/json","OData-Version":"4.0","OData-MaxVersion":"4.0"},KP="workflowid,name,description,primaryentity,statecode,category,type",XP="category eq 2 and type eq 1";async function xg(e,t,r){var n;if(r==="Draft")return null;let i=(0,wn.normalizeGuid)(t,"workflowid"),a=r==="Active",o={statecode:a?Wr.StateCode.Activated:Wr.StateCode.Draft,statuscode:a?Wr.StatusCode.Activated:Wr.StatusCode.Draft},s=`/workflows(${i})`,l=(0,Xe.ensureSuccess)(await e.patch(s,o,{headers:_s}),e.apiUrl(s));return(n=(0,Xe.readEtag)(l))!==null&&n!==void 0?n:await Xa(e,i)}async function Xa(e,t){let r=`/workflows(${t})${(0,wn.odataQuery)([["$select","workflowid"]])}`;try{let n=await e.get(r);return n.status>=200&&n.status<300?(0,Xe.readEtag)(n):null}catch{return null}}async function YP(e,t,r){let n=await Xa(e,t),i=await r(),a=(0,Xe.readEtag)(i);if(a)return{response:i,etag:a};let o=await Xa(e,t);return{response:i,etag:n!==null&&n===o?o:null}}wr.businessRuleApi={async get(e,t){let r=(0,wn.normalizeGuid)(t,"id"),n=`/workflows(${r})/Microsoft.Dynamics.CRM.RetrieveProcessWithWfomJson`,{response:i,etag:a}=await YP(e,r,async()=>(0,Xe.ensureSuccess)(await e.get(n),e.apiUrl(n)));return{raw:i.body,etag:a}},async list(e,t){let r=[XP];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,wn.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,wn.odataQuery)([["$select",KP],["$filter",r.join(" and ")]])}`;return(await(0,HP.collectPages)(e,n,"listArtifacts('businessRule')")).map(a=>{var o,s;return{type:"businessRule",id:(o=a.workflowid)!==null&&o!==void 0?o:"",name:(s=a.name)!==null&&s!==void 0?s:"",entityLogicalName:a.primaryentity,isDirty:!1}})},async create(e,t){var r;let n=t,i=(0,wn.normalizeGuid)(n.Entity.workflowid,"workflowid"),a=await Fg(e,"CreateProcessWithWfomJson",n,_s),o=(0,Xe.resolveCreatedId)(a,"workflowid","business rule",i),s=null;try{s=await xg(e,o,n.status)}catch(l){try{await(0,Xe.deleteRecord)(e,"workflows",o)}catch{}throw l}return{id:o,etag:(r=s??(0,Xe.readEtag)(a))!==null&&r!==void 0?r:await Xa(e,o)}},async update(e,t,r,n){var i,a;let o=r,s=(0,wn.normalizeGuid)(t,"id"),l=`/workflows(${s})`,u={..._s,"If-Match":(0,Xe.requireEtag)(n,"business rule",s)},c=await JP(e,s,u["If-Match"]),d=c.statecode===Wr.StateCode.Activated;d&&(0,Xe.ensureSuccess)(await e.patch(l,{statecode:Wr.StateCode.Draft,statuscode:Wr.StatusCode.Draft},{headers:u}),e.apiUrl(l));let p;try{p=await Fg(e,"UpdateProcessWithWfomJson",o,u)}catch(m){if(d)try{(0,Xe.ensureSuccess)(await e.patch(l,{statecode:Wr.StateCode.Activated,statuscode:(i=c.statuscode)!==null&&i!==void 0?i:Wr.StatusCode.Activated},{headers:_s}),e.apiUrl(l))}catch(g){throw new Ts.SdkError(wr.BUSINESS_RULE_LEFT_DEACTIVATED_CODE,`The business-rule write failed AND the rule could not be re-activated, so '${s}' is left DEACTIVATED (Draft) on the server. Re-activate it before relying on it. Original write failure: ${m instanceof Error?m.message:String(m)}. Restore failure: ${g instanceof Error?g.message:String(g)}`)}throw m}let f=await xg(e,s,o.status);return{id:s,etag:(a=f??(0,Xe.readEtag)(p))!==null&&a!==void 0?a:await Xa(e,s)}},delete(e,t){return(0,Xe.deleteRecord)(e,"workflows",t)}}});var Rs=v(Os=>{"use strict";Object.defineProperty(Os,"__esModule",{value:!0});Os.JsonPointer=void 0;var Ft=te(),Ps=class e{static isReservedToken(t){return e.RESERVED_TOKENS.has(t)}static decodeToken(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}static encodeToken(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}static parse(t){if(t==="")return[];if(t[0]!=="/")throw new Ft.JsonPointerError(t,'non-empty pointers must start with "/"');return t.substring(1).split("/").map(r=>{if(/~(?![01])/.test(r))throw new Ft.JsonPointerError(t,`invalid '~' escape in token '${r}' (expected ~0 or ~1)`);return e.decodeToken(r)})}static compile(t){return t.length===0?"":"/"+t.map(r=>e.encodeToken(r)).join("/")}static resolve(t,r){let n=e.parse(r),i=t;for(let a of n)if(Array.isArray(i)){let o=e.toArrayIndex(a,i.length);if(o===void 0)return;i=i[o]}else if(i!==null&&typeof i=="object"){let o=i;if(e.isReservedToken(a)||!Object.prototype.hasOwnProperty.call(o,a))return;i=o[a]}else return;return i}static set(t,r,n){let i=e.parse(r);if(i.length===0)throw new Ft.JsonPointerError(r,"cannot set the document root");let{parent:a,lastToken:o}=e.resolveParent(t,i,r);if(Array.isArray(a)){let s=e.toArrayIndex(o,a.length);if(s===void 0)throw new Ft.JsonPointerError(r,`'${o}' is not a valid array index`);if(s>a.length)throw new Ft.JsonPointerError(r,`array index '${o}' is out of range`);a[s]=n}else{if(e.isReservedToken(o))throw new Ft.JsonPointerError(r,`refusing to write reserved property '${o}'`);a[o]=n}}static remove(t,r){let n=e.parse(r);if(n.length===0)throw new Ft.JsonPointerError(r,"cannot remove the document root");let{parent:i,lastToken:a}=e.resolveParent(t,n,r);if(Array.isArray(i)){let o=e.toArrayIndex(a,i.length);if(o===void 0||o>=i.length)throw new Ft.JsonPointerError(r,`array index '${a}' is out of range`);i.splice(o,1)}else{if(e.isReservedToken(a))throw new Ft.JsonPointerError(r,`refusing to remove reserved property '${a}'`);delete i[a]}}static add(t,r,n,i){let a=e.parse(r);if(a.length>0&&a[a.length-1]==="-"){let l=e.compile(a.slice(0,-1)),u=e.resolve(t,l);if(!Array.isArray(u))throw new Ft.JsonPointerError(r,"add target must be an array");u.push(n);return}let o=e.resolve(t,r);if(!Array.isArray(o))throw new Ft.JsonPointerError(r,"add target must be an array");let s=i===void 0?o.length:i;if(s<0||s>o.length)throw new Ft.JsonPointerError(r,`insert index ${s} is out of range`);o.splice(s,0,n)}static parent(t){let r=e.parse(t);return r.pop(),e.compile(r)}static lastToken(t){let r=e.parse(t);return r.length===0?"":r[r.length-1]}static append(t,r){return`${t}/${e.encodeToken(String(r))}`}static resolveParent(t,r,n){let i=r[r.length-1],a=e.compile(r.slice(0,-1)),o=e.resolve(t,a);if(o===null||typeof o!="object")throw new Ft.JsonPointerError(n,"parent path does not resolve to an object or array");return{parent:o,lastToken:i}}static toArrayIndex(t,r){if(t==="-")return r;if(/^(0|[1-9][0-9]*)$/.test(t))return Number(t)}};Os.JsonPointer=Ps;Ps.RESERVED_TOKENS=new Set(["__proto__","prototype","constructor"])});var kg=v(Fs=>{"use strict";Object.defineProperty(Fs,"__esModule",{value:!0});Fs.findElements=void 0;var Lg=Rs();function ZP(e,t){let r=[];return Mc(e,"",t,r),r}Fs.findElements=ZP;function Mc(e,t,r,n){if(!(e===null||typeof e!="object"))if(r(e,t)&&n.push({pointer:t,value:e}),Array.isArray(e))e.forEach((i,a)=>{Mc(i,Lg.JsonPointer.append(t,a),r,n)});else for(let i of Object.keys(e))Mc(e[i],Lg.JsonPointer.append(t,i),r,n)}});var Uc=v(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.assertMutationResult=Ar.assertExistsResult=Ar.assertReadResult=Ar.assertStorageContract=void 0;var e1=["readText","writeTextAtomic","deleteFile","deleteByPrefix"],t1=["ensureContainer","exists"];function r1(e){if(typeof e!="object"||e===null)throw new Error("workspaceStorage must be an object implementing WorkspaceStorage.");for(let t of e1)if(typeof e[t]!="function")throw new Error(`workspaceStorage is missing the required method '${t}'.`);for(let t of t1){let r=e[t];if(r!==void 0&&typeof r!="function")throw new Error(`workspaceStorage.${t} must be a function when present.`)}return e}Ar.assertStorageContract=r1;function n1(e,t){if(e===null||typeof e=="string")return e;throw new Error(`workspaceStorage.readText must resolve to a string or null for ${t}; got ${typeof e}. Absence is null \u2014 resolving undefined would make a present value look absent.`)}Ar.assertReadResult=n1;function i1(e,t){if(typeof e=="boolean")return e;throw new Error(`workspaceStorage.exists must resolve to a boolean for ${t}; got ${typeof e}. A truthy non-boolean would make an absent value look present.`)}Ar.assertExistsResult=i1;function a1(e,t){if(e!==void 0)throw new Error(`workspaceStorage.${t} must resolve to undefined; got ${typeof e}. A status-returning implementation would let a failed write be reported as a completed one.`)}Ar.assertMutationResult=a1});var Bc=v(Ii=>{"use strict";Object.defineProperty(Ii,"__esModule",{value:!0});Ii.retryTransientIoAsync=Ii.retryTransientIo=void 0;var o1=new Set(["EPERM","EACCES","EBUSY","UNKNOWN"]),s1=5,Mg=10;function l1(e){for(let t=1;;t+=1)try{return e()}catch(r){if(!Ug(r,t))throw r;c1(Mg*t)}}Ii.retryTransientIo=l1;async function u1(e){for(let t=1;;t+=1)try{return await e()}catch(r){if(!Ug(r,t))throw r;await new Promise(n=>setTimeout(n,Mg*t))}}Ii.retryTransientIoAsync=u1;function Ug(e,t){let r=e.code;return t<s1&&!!r&&o1.has(r)}function c1(e){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}catch{let t=Date.now()+e;for(;Date.now()<t;);}}});var Vg=v(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.canonicalArtifactId=xt.WorkspaceManager=xt.WORKSPACE_SCHEMA_VERSION=xt.retryTransientIo=void 0;var ar=Uc(),xs=te(),d1=Bc();Object.defineProperty(xt,"retryTransientIo",{enumerable:!0,get:function(){return d1.retryTransientIo}});function Bg(e){let t=e;return typeof t.pathFor=="function"&&typeof t.getRoot=="function"?e:null}xt.WORKSPACE_SCHEMA_VERSION=1;var An={form:"forms",view:"views",businessRule:"business-rules",app:"apps",command:"commands",chart:"charts",dashboard:"dashboards",genPage:"gen-pages",bpf:"business-process-flows"},p1="manifest.json",Ya=".metadata",$g="entities";function qg(e){try{return Promise.resolve(e())}catch(t){return Promise.reject(t)}}var $c=class{withManifest(t){let r=this.manifestQueue.then(t,t);return this.manifestQueue=r.then(()=>{},()=>{}),r}constructor(t,r,n){if(this.workspaceLabel=t,this.instanceUrl=r,this.manifestQueue=Promise.resolve(),n==null)throw new Error("WorkspaceManager requires a WorkspaceStorage. Node callers can build one with `createNodeWorkspaceStorage(path)` from '@maker-studio/cds-maker-sdk/node'.");this.storage=n}artifactKey(t,r){return this.assertSafeId(r),[An[t],`${Za(r)}.json`]}metaKey(t,r){return this.assertSafeId(r),[Ya,An[t],`${Za(r)}.meta.json`]}entityKey(t){return this.assertSafeId(t),[Ya,$g,`${t}.json`]}fsStore(){let t=Bg(this.storage);if(!t)throw new Error("This workspace is not filesystem-backed, so it has no physical paths. Use the artifact/metadata/manifest accessors instead of the path helpers.");return t}getRoot(){let t=Bg(this.storage);return t?t.getRoot():this.workspaceLabel}getArtifactDir(t){return this.fsStore().pathFor([An[t]])}getArtifactFilePath(t,r){return this.fsStore().pathFor(this.artifactKey(t,r))}getMetaFilePath(t,r){return this.fsStore().pathFor(this.metaKey(t,r))}getEntityMetaFilePath(t){return this.fsStore().pathFor(this.entityKey(t))}assertSafeId(t){if(typeof t!="string"||t.length===0||/[\u0000-\u001f]/.test(t)||t.includes("/")||t.includes("\\")||t.includes(":")||t==="."||t===".."||t.includes(".."))throw new xs.PathTraversalError(String(t),this.workspaceLabel)}get manifestKey(){return[p1]}async init(){if(this.storage.ensureContainer){let t=this.storage.ensureContainer.bind(this.storage),r=[[Ya,$g]];for(let i of Object.keys(An))r.push([An[i]],[Ya,An[i]]);let n=await Promise.allSettled(r.map(i=>qg(()=>t(i))));for(let i of n){if(i.status==="rejected")throw i.reason;(0,ar.assertMutationResult)(i.value,"ensureContainer")}}await this.withManifest(async()=>{if(await this.isInitialized())return;let t={instanceUrl:this.instanceUrl,createdAt:new Date().toISOString(),artifacts:[]};await this.writeManifest(t)})}async isInitialized(){return this.storage.exists?(0,ar.assertExistsResult)(await this.storage.exists(this.manifestKey),"manifest.json"):(0,ar.assertReadResult)(await this.storage.readText(this.manifestKey),"manifest.json")!==null}async ensureInitialized(){if(!await this.isInitialized())throw new xs.WorkspaceNotInitializedError(this.workspaceLabel)}async clean(){let t=Object.keys(An).map(i=>[An[i]]);t.push([Ya]);let r=await Promise.allSettled(t.map(i=>qg(()=>this.storage.deleteByPrefix(i))));for(let i of r){if(i.status==="rejected")throw i.reason;(0,ar.assertMutationResult)(i.value,"deleteByPrefix")}let n=await this.getManifest();n.artifacts=[],n.lastSyncAt=void 0,await this.init(),await this.writeManifest(n)}async readArtifact(t,r){return await this.ensureInitialized(),this.readJson(this.artifactKey(t,r))}async writeArtifact(t,r,n){await this.ensureInitialized(),await this.writeJson(this.artifactKey(t,r),n),await this.upsertManifestEntry(t,r,n)}async deleteArtifact(t,r){await this.ensureInitialized(),(0,ar.assertMutationResult)(await this.storage.deleteFile(this.artifactKey(t,r)),"deleteFile"),(0,ar.assertMutationResult)(await this.storage.deleteFile(this.metaKey(t,r)),"deleteFile");let n=Za(r);await this.withManifest(async()=>{let i=await this.getManifest();i.artifacts=i.artifacts.filter(a=>!(a.type===t&&a.id===n)),await this.writeManifest(i)})}async readMeta(t,r){return this.readJson(this.metaKey(t,r))}async writeMeta(t,r,n){await this.writeJson(this.metaKey(t,r),n)}async listArtifacts(t,r){return await this.ensureInitialized(),(await this.getManifest()).artifacts.filter(n=>!(t&&n.type!==t||r?.entityLogicalName&&n.entityLogicalName!==r.entityLogicalName))}async readEntityMetadata(t){await this.ensureInitialized();let r=await this.readJson(this.entityKey(t));return!r||typeof r.schemaName!="string"||typeof r.primaryNameAttribute!="string"||typeof r.primaryIdAttribute!="string"||typeof r.isCustomEntity!="boolean"?null:r}async writeEntityMetadata(t,r){await this.ensureInitialized(),await this.writeJson(this.entityKey(t),r)}async getManifest(){await this.ensureInitialized();let t=await this.readJson(this.manifestKey);if(!t)throw new xs.WorkspaceNotInitializedError(this.workspaceLabel);if(t.schemaVersion!==void 0&&t.schemaVersion>xt.WORKSPACE_SCHEMA_VERSION)throw new xs.IncompatibleWorkspaceError(t.schemaVersion,xt.WORKSPACE_SCHEMA_VERSION);return t}async writeManifest(t){await this.writeJson(this.manifestKey,{...t,schemaVersion:xt.WORKSPACE_SCHEMA_VERSION})}async updateManifest(t){await this.withManifest(async()=>{let r=await this.getManifest();await this.writeManifest({...r,...t})})}async upsertManifestEntry(t,r,n){await this.withManifest(async()=>{let i=await this.getManifest(),a=Za(r),o=n,s=typeof o.name=="string"?o.name:`${t}:${a}`,l=typeof o.entityLogicalName=="string"?o.entityLogicalName:void 0,u=i.artifacts.find(c=>c.type===t&&c.id===a);u?(u.name=s,u.entityLogicalName=l):i.artifacts.push({type:t,id:a,name:s,entityLogicalName:l,isDirty:!1}),await this.writeManifest(i)})}async readJson(t){let r=(0,ar.assertReadResult)(await this.storage.readText(t),t.join("/"));return r===null?null:JSON.parse(r)}async writeJson(t,r){(0,ar.assertMutationResult)(await this.storage.writeTextAtomic(t,`${JSON.stringify(r,null,2)}-`),"writeTextAtomic")}async removeFile(t){(0,ar.assertMutationResult)(await this.storage.deleteFile(t),"deleteFile")}async exists(t){return this.storage.exists?(0,ar.assertExistsResult)(await this.storage.exists(t),t.join("/")):(0,ar.assertReadResult)(await this.storage.readText(t),t.join("/"))!==null}};xt.WorkspaceManager=$c;function Za(e){let r=/^\{?([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})\}?$/.exec(e);return r?r[1].toLowerCase():e.toLowerCase()}xt.canonicalArtifactId=Za});var qc=v(_i=>{"use strict";Object.defineProperty(_i,"__esModule",{value:!0});_i.deepEqual=_i.deepDiff=void 0;var f1=Rs();function m1(e,t){let r=[];return zg(e,t,"",r,0),r}_i.deepDiff=m1;var Ls=Symbol("missing"),ks=512;function zg(e,t,r,n,i){if(e===t)return;if(i>ks)throw new RangeError(`deepDiff exceeded the maximum supported depth of ${ks}`);let a=Ms(e),o=Ms(t);if(a&&o&&Array.isArray(e)===Array.isArray(t)){let s=h1(e,t);for(let l of s){let u=Gg(e,l),c=Gg(t,l),d=f1.JsonPointer.append(r,l);u===Ls?n.push({pointer:d,type:"added",newValue:c}):c===Ls?n.push({pointer:d,type:"removed",oldValue:u}):zg(u,c,d,n,i+1)}return}Wg(e,t)||n.push({pointer:r,type:"modified",oldValue:e,newValue:t})}function Ms(e){return e!==null&&typeof e=="object"}function h1(e,t){if(Array.isArray(e)&&Array.isArray(t)){let n=Math.max(e.length,t.length),i=[];for(let a=0;a<n;a++)i.push(String(a));return i}let r=new Set([...Object.keys(e),...Object.keys(t)]);return Array.from(r)}function Gg(e,t){if(Array.isArray(e)){let r=Number(t);return r<e.length?e[r]:Ls}return t in e?e[t]:Ls}function Wg(e,t){return Hg(e,t,0)}_i.deepEqual=Wg;function Hg(e,t,r){if(e===t)return!0;if(r>ks)throw new RangeError(`deepEqual exceeded the maximum supported depth of ${ks}`);if(!Ms(e)||!Ms(t)||Array.isArray(e)!==Array.isArray(t))return!1;let n=Object.keys(e),i=Object.keys(t);return n.length!==i.length?!1:n.every(a=>a in t&&Hg(e[a],t[a],r+1))}});var Jg=v(Ti=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});Ti.VersionManager=Ti.PROJECTION_VERSION=void 0;var jg=qc();Ti.PROJECTION_VERSION=3;var Vc=class{constructor(t){this.workspace=t}async storeMeta(t,r,n){var i;let a=await this.getMeta(t,r),o=((i=n.snapshot)===null||i===void 0?void 0:i.status)==="Active",s=a?.everActivated===!0||o;await this.workspace.writeMeta(t,r,s?{...n,everActivated:s}:n)}async getMeta(t,r){return this.workspace.readMeta(t,r)}async isDirty(t,r){let n=await this.workspace.readArtifact(t,r);if(n===null)return!1;let i=await this.getMeta(t,r);return i?!(0,jg.deepEqual)(i.snapshot,n):!0}async diff(t,r){let n=await this.workspace.readArtifact(t,r),i=await this.getMeta(t,r),a;return n===null?a=i?[{pointer:"",type:"removed",oldValue:i.snapshot}]:[]:i?a=(0,jg.deepDiff)(i.snapshot,n):a=[{pointer:"",type:"added",newValue:n}],{artifactType:t,artifactId:r,changes:a}}async checkConflict(t,r,n){let i=await this.getMeta(t,r);return!i||i.etag===null?!1:i.etag!==n}};Ti.VersionManager=Vc});var Kg=v((Gc,Qg)=>{(function(e,t){typeof define=="function"&&define.amd?define([],t):typeof Gc=="object"?Qg.exports=t():e.compareVersions=t()})(Gc,function(){var e=/^v?(?:\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+))?(?:-[\da-z\-]+(?:\.[\da-z\-]+)*)?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;function t(a,o){return a.indexOf(o)===-1?a.length:a.indexOf(o)}function r(a){var o=a.replace(/^v/,"").replace(/\+.*$/,""),s=t(o,"-"),l=o.substring(0,s).split(".");return l.push(o.substring(s+1)),l}function n(a){return isNaN(Number(a))?a:Number(a)}function i(a){if(typeof a!="string")throw new TypeError("Invalid argument expected string");if(!e.test(a))throw new Error("Invalid argument not valid semver ('"+a+"' received)")}return function(o,s){[o,s].forEach(i);for(var l=r(o),u=r(s),c=0;c<Math.max(l.length-1,u.length-1);c++){var d=parseInt(l[c]||0,10),p=parseInt(u[c]||0,10);if(d>p)return 1;if(p>d)return-1}var f=l[l.length-1],m=u[u.length-1];if(f&&m){var g=f.split(".").map(n),y=m.split(".").map(n);for(c=0;c<Math.max(g.length,y.length);c++){if(g[c]===void 0||typeof y[c]=="string"&&typeof g[c]=="number")return-1;if(y[c]===void 0||typeof g[c]=="string"&&typeof y[c]=="number"||g[c]>y[c])return 1;if(y[c]>g[c])return-1}}else if(f||m)return f?-1:1;return 0}})});var t0=v(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.EnvironmentFlowHostingType=Ee.EnvironmentDisableReasonCode=Ee.EnvironmentMigrationConstants=Ee.EnvironmentProvisioningStates=Ee.EnvironmentLocations=Ee.EnvironmentCreationTypeConstants=Ee.EnvironmentType=Ee.EnvironmentSkuConstants=Ee.environmentPermissions=Ee.DatabaseType=void 0;var Xg;(function(e){e.CommonDataService="CommonDataService",e.None="None"})(Xg||(Ee.DatabaseType=Xg={}));Ee.environmentPermissions={CreatePowerApp:"CreatePowerApp",ReadEnvironment:"ReadEnvironment",GenerateResourceStorage:"GenerateResourceStorage",CreateGateway:"CreateGateway",CreateFlow:"CreateFlow",CreateCustomApi:"CreateCustomApi",AdminReadEnvironment:"AdminReadEnvironment",UpdateEnvironment:"UpdateEnvironment",DeleteEnvironment:"DeleteEnvironment",ExportEnvironmentPackage:"ExportEnvironmentPackage",SetDLPPolicy:"SetDLPPolicy",ListAnyPowerApp:"ListAnyPowerApp",ListAnyFlow:"ListAnyFlow",DeleteAnyPowerApp:"DeleteAnyPowerApp",DeleteAnyFlow:"DeleteAnyFlow",AddEnvironmentRoleAssignment:"AddEnvironmentRoleAssignment",ReadEnvironmentRoleInformation:"ReadEnvironmentRoleInformation",RemoveEnvironmentRoleAssignment:"RemoveEnvironmentRoleAssignment",ModifyDatabaseRoleAssignments:"ModifyDatabaseRoleAssignments",CreateDatabase:"CreateDatabase",ListDatabaseEntities:"ListDatabaseEntities",CreateDatabaseEntities:"CreateDatabaseEntities",UpdateDatabaseEntities:"UpdateDatabaseEntities",DeleteDatabaseEntities:"DeleteDatabaseEntities"};Ee.EnvironmentSkuConstants={NotSpecified:"NotSpecified",Standard:"Standard",Premium:"Premium",Developer:"Developer",Basic:"Basic",Production:"Production",Sandbox:"Sandbox",Trial:"Trial",Default:"Default",Teams:"Teams",Platform:"Platform"};var Yg;(function(e){e[e.CDS2=0]="CDS2",e[e.CDS1=1]="CDS1",e[e.Empty=2]="Empty"})(Yg||(Ee.EnvironmentType=Yg={}));Ee.EnvironmentCreationTypeConstants={NotSpecified:"NotSpecified",Legacy:"Legacy",DefaultTenant:"DefaultTenant",User:"User",CommonDataModelLegacy:"CommonDataModelLegacy"};Ee.EnvironmentLocations={global:"global",unitedStates:"unitedstates",southamerica:"southamerica",europe:"europe",canada:"canada",preview:"unitedstatesfirstrelease",asia:"asia",japan:"japan",australia:"australia",india:"india",unitedkingdom:"unitedkingdom",france:"france",germany:"germany",brazil:"brazil",usgov:"usgov",usgovhigh:"usgovhigh",uae:"unitedarabemirates",switzerland:"switzerland",mooncake:"china",korea:"korea",norway:"norway",southafrica:"southafrica",dod:"usdod",singapore:"singapore",sweden:"sweden",italy:"italy",poland:"poland"};Ee.EnvironmentProvisioningStates={NotSpecified:"NotSpecified",Succeeded:"Succeeded",Deleting:"Deleting",Deleted:"Deleted",FailedDeleting:"FailedDeleting",LinkedDatabaseProvisioning:"LinkedDatabaseProvisioning",LinkedDatabaseFailedProvisioning:"LinkedDatabaseFailedProvisioning",LinkedDatabaseFailedConfiguring:"LinkedDatabaseFailedConfiguring",LinkedDatabaseUnavailable:"LinkedDatabaseUnavailable",Creating:"Creating"};Ee.EnvironmentMigrationConstants={phases:{completed:"Completed"}};var Zg;(function(e){e.NotSpecified="NotSpecified",e.NoValidLicense="NoValidLicense",e.SuspendedLicense="SuspendedLicense",e.TrialExpiration="TrialExpiration",e.UserRequested="UserRequested",e.InstanceStateUpdate="InstanceStateUpdated",e.InactivityThreshold="InactivityThreshold",e.OperationsInitiated="OperationsInitiated",e.EnvironmentLifecycleOperation="EnvironmentLifecycleOperation",e.TenantPolicyEvaluation="TenantPolicyEvaluation"})(Zg||(Ee.EnvironmentDisableReasonCode=Zg={}));var e0;(function(e){e.LogicApps="LogicApps",e.SelfHostSingleTenant="SelfHostSingleTenant",e.SelfHostMultiTenant="SelfHostMultiTenant"})(e0||(Ee.EnvironmentFlowHostingType=e0={}))});var u0=v(C=>{"use strict";var g1=C&&C.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(C,"__esModule",{value:!0});C.hasCommonDataServiceDatabase=C.getEnvironmentDiscoveryUrl=C.getEnvironmentWebApiUrl=C.getEnvironmentInstanceApiUrl=C.getEnvironmentLanguageCode=C.getEnvironmentUpdateCadence=C.checkVersions=C.isCds2EnvironmentVersionAtLeast=C.getSecurityOrConnectedGroupId=C.hasSecurityGroupId=C.doesCds2VersionSupportApiVersion9_1=C.doesCds2EnvironmentSupportApiVersion9_1=C.cdsVersionSupportingOSColorEdit=C.getEnvironmentDisplayName=C.getEnvironmentName=C.isEnvironmentInFirstReleaseCluster=C.isEnvironmentInPreprodCluster=C.isEnvironmentInTestCluster=C.isLiteEnvironmentUpgrading=C.isEnvironmentExpired=C.isEnvironmentInDeletedState=C.isEnvironmentInCreatingState=C.isDatabaseInProvisioningState=C.canUserCreateDatabase=C.isDisabledEnvironment=C.isDefaultEnvironment=C.isTrialEnvironment=C.isPlatformEnvironment=C.isTeamsEnvironment=C.isSandboxEnvironment=C.isProdEnvironment=C.isDevEnvironment=C.getEnvironmentType=C.getCrmInstanceName=C.getCrmInstanceUrl=C.getCrmAppDesignerUrl=C.getDevResourcesUrl=C.isEnvironmentInSuccessfulState=C.getAllThemesUrl=C.getAllPublishersUrl=C.getAllSolutionsUrl=C.getSecurityRolesUrl=C.getSecurityUsersUrl=C.environmentHasCds2Database=C.DEFAULT_SOLUTION_UNIQUE_NAME=C.DEFAULT_SOLUTION_ID=C.crmBapSolutionId=C.doesUserHavePermission=C.getLinkedEnvironmentMetadata=C.getCrmVersion=void 0;C.doesUserHaveFlowRunOnlyPermission=C.isUserPautoMakerWithoutDataAccess=C.isUserPautoMakerWithDataAccess=C.doesUserHaveCreateFlowPermission=C.equalsIgnoreCase=C.doesUserHaveCreateDatabasePermission=C.doesUserHaveDatabaseTablePermissions=C.isUserMakerWithoutDataAccess=C.isUserMakerWithDataAccess=C.doesUserHaveCreateAppPermission=C.doesUserHaveAdminPermission=void 0;var v1=g1(Kg()),de=t0(),eo=Wc();function y1(e){let t=jr(e);return t&&t.version}C.getCrmVersion=y1;function jr(e){return e&&e.properties&&e.properties.linkedEnvironmentMetadata}C.getLinkedEnvironmentMetadata=jr;function Hr(e,t){return e?!!e[t]:!1}C.doesUserHavePermission=Hr;C.crmBapSolutionId="00000001-0000-0000-0001-00000000009b";C.DEFAULT_SOLUTION_ID="fd140aaf-4df4-11dd-bd17-0019b9312238";C.DEFAULT_SOLUTION_UNIQUE_NAME="Default";function Zn(e){return!!jr(e)&&r0(e)}C.environmentHasCds2Database=Zn;function b1(e){if(e&&Zn(e)){let t=Cn(e);return(0,eo.getCrmAdminSecurityRolesUrl)(t)}return""}C.getSecurityUsersUrl=b1;function w1(e){if(e&&Zn(e)){let t=Cn(e);return(0,eo.getCrmAdminSecurityUsersUrl)(t)}return""}C.getSecurityRolesUrl=w1;function A1(e){if(e&&Zn(e)){let t=Cn(e);(0,eo.getCrmAllSolutionsUrl)(t)}return""}C.getAllSolutionsUrl=A1;function C1(e){if(e&&Zn(e)){let t=Cn(e);return(0,eo.getCrmAllPublishersUrl)(t)}return""}C.getAllPublishersUrl=C1;function E1(e){return e&&Zn(e)?Cn(e):""}C.getAllThemesUrl=E1;function r0(e){return!!e&&e.properties&&!!e.properties.provisioningState&&e.properties.provisioningState.toUpperCase()===de.EnvironmentProvisioningStates.Succeeded.toUpperCase()}C.isEnvironmentInSuccessfulState=r0;function S1(e){if(e&&Zn(e)){let t=Cn(e);return(0,eo.getCrmDevResourcesUrl)(t)}return""}C.getDevResourcesUrl=S1;function N1(e){return`${e}designer/app/{${C.crmBapSolutionId}}/CreateNewApp}}`}C.getCrmAppDesignerUrl=N1;function Cn(e){let t=jr(e);if(t){let r=t.instanceUrl;return r?r.endsWith("/")?r:r+"/":""}return""}C.getCrmInstanceUrl=Cn;function D1(e){let t=jr(e);return t?t.uniqueName:""}C.getCrmInstanceName=D1;function I1(e){return jr(e)?de.EnvironmentType.CDS2:e&&e.properties&&e.properties.namespace?de.EnvironmentType.CDS1:de.EnvironmentType.Empty}C.getEnvironmentType=I1;function _1(e){return e&&e.properties&&e.properties.environmentSku===de.EnvironmentSkuConstants.Developer}C.isDevEnvironment=_1;function T1(e){return e&&e.properties&&e.properties.environmentSku===de.EnvironmentSkuConstants.Production}C.isProdEnvironment=T1;function P1(e){return e&&e.properties&&e.properties.environmentSku===de.EnvironmentSkuConstants.Sandbox}C.isSandboxEnvironment=P1;function to(e){return e&&e.properties&&e.properties.environmentSku===de.EnvironmentSkuConstants.Teams}C.isTeamsEnvironment=to;function O1(e){return e&&e.properties&&e.properties.environmentSku===de.EnvironmentSkuConstants.Platform}C.isPlatformEnvironment=O1;var R1=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.environmentSku)===de.EnvironmentSkuConstants.Trial};C.isTrialEnvironment=R1;function F1(e){return e&&e.properties&&(e.properties.isDefault||e.properties.creationType===de.EnvironmentCreationTypeConstants.DefaultTenant)}C.isDefaultEnvironment=F1;function x1(e){return e&&e.properties&&!!e.properties.states&&!!e.properties.states.runtime&&e.properties.states.runtime.id==="Disabled"}C.isDisabledEnvironment=x1;function L1(e){return e&&e.properties&&Hr(e.properties.permissions,de.environmentPermissions.CreateDatabase)}C.canUserCreateDatabase=L1;function k1(e){return!!(e&&e.properties&&e.properties.provisioningState&&l0(e.properties.provisioningState,de.EnvironmentProvisioningStates.LinkedDatabaseProvisioning))}C.isDatabaseInProvisioningState=k1;function M1(e){return!!e&&!!e.properties&&e.properties.provisioningState===de.EnvironmentProvisioningStates.Creating}C.isEnvironmentInCreatingState=M1;function U1(e){return e&&e.properties&&(e.properties.provisioningState===de.EnvironmentProvisioningStates.Deleted||e.properties.provisioningState===de.EnvironmentProvisioningStates.Deleting||e.properties.provisioningState===de.EnvironmentProvisioningStates.FailedDeleting)}C.isEnvironmentInDeletedState=U1;function B1(e){return!!e&&!!e.properties&&!!e.properties.expirationTime&&Date.parse(e.properties.expirationTime)<Date.now()}C.isEnvironmentExpired=B1;function $1(e){return!!e&&!!e.properties&&!!e.properties.linkedEnvironmentMetadata&&e.properties.linkedEnvironmentMetadata.platformSku==="Lite"&&!!e.properties.states&&!!e.properties.states.management&&e.properties.states.management.id==="Running"&&!!e.properties.ongoingOperation&&!!e.properties.ongoingOperation.type&&e.properties.ongoingOperation.type.id==="Promote"}C.isLiteEnvironmentUpgrading=$1;function q1(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Test"}C.isEnvironmentInTestCluster=q1;function V1(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Preprod"}C.isEnvironmentInPreprodCluster=V1;function G1(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="FirstRelease"}C.isEnvironmentInFirstReleaseCluster=G1;function z1(e){return e&&e.name||""}C.getEnvironmentName=z1;function W1(e){return e&&e.properties&&e.properties.displayName||""}C.getEnvironmentDisplayName=W1;var n0="9.1.0.8202";C.cdsVersionSupportingOSColorEdit="9.1.0000.20708";function H1(e){return o0(e,n0)}C.doesCds2EnvironmentSupportApiVersion9_1=H1;function j1(e){return zc(e,n0)}C.doesCds2VersionSupportApiVersion9_1=j1;function i0(e){let t=jr(e);if(t)return t.securityGroupId}function a0(e){return e&&e.properties&&e.properties.connectedGroups}function J1(e,t){let r=a0(e);return!!r&&!!r.find(n=>n.id===t)||i0(e)===t}C.hasSecurityGroupId=J1;function Q1(e){let t=a0(e);return t&&t.length>0&&t[0].id?t[0].id:i0(e)}C.getSecurityOrConnectedGroupId=Q1;function o0(e,t){let r=e.version;return r?zc(r,t):!1}C.isCds2EnvironmentVersionAtLeast=o0;function zc(e,t){return t?e?(0,v1.default)(e,t)>=0:!1:!0}C.checkVersions=zc;function K1(e){return e&&e.properties&&e.properties.updateCadence&&e.properties.updateCadence.id||"NotSpecified"}C.getEnvironmentUpdateCadence=K1;function X1(e){let t=jr(e);return t?Number(t.baseLanguage):0}C.getEnvironmentLanguageCode=X1;function s0(e){let t=jr(e);return t?t.instanceApiUrl:void 0}C.getEnvironmentInstanceApiUrl=s0;function Y1(e){let t=s0(e);return t?t+"/api/data/v9.2":""}C.getEnvironmentWebApiUrl=Y1;function Z1(e){let t=Cn(e);if(t==="")return"";let r=t.split("/");if(r.length!==4)return"";let n=r[2].split(".");return n[0]="globaldisco",r[2]=n.join("."),r.join("/")+"api/discovery/v2.0/Instances"}C.getEnvironmentDiscoveryUrl=Z1;var eO=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.databaseType)===de.DatabaseType.CommonDataService};C.hasCommonDataServiceDatabase=eO;var tO=e=>{var t;return Hr((t=e.properties)===null||t===void 0?void 0:t.permissions,de.environmentPermissions.AdminReadEnvironment)};C.doesUserHaveAdminPermission=tO;var rO=e=>{var t;return Hr((t=e.properties)===null||t===void 0?void 0:t.permissions,de.environmentPermissions.CreatePowerApp)};C.doesUserHaveCreateAppPermission=rO;var nO=e=>(0,C.doesUserHaveAdminPermission)(e)&&(0,C.hasCommonDataServiceDatabase)(e)?!0:(0,C.doesUserHaveCreateAppPermission)(e)?to(e)||(0,C.doesUserHaveDatabaseTablePermissions)(e):!1;C.isUserMakerWithDataAccess=nO;var iO=e=>(0,C.doesUserHaveCreateAppPermission)(e)&&!to(e)&&!(0,C.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,C.doesUserHaveAdminPermission)(e)||!(0,C.hasCommonDataServiceDatabase)(e));C.isUserMakerWithoutDataAccess=iO;var aO=e=>[de.environmentPermissions.CreateDatabaseEntities,de.environmentPermissions.ListDatabaseEntities,de.environmentPermissions.UpdateDatabaseEntities,de.environmentPermissions.DeleteDatabaseEntities].every(t=>{var r;return Hr((r=e.properties)===null||r===void 0?void 0:r.permissions,t)});C.doesUserHaveDatabaseTablePermissions=aO;var oO=e=>{var t;return Hr((t=e.properties)===null||t===void 0?void 0:t.permissions,de.environmentPermissions.CreateDatabase)};C.doesUserHaveCreateDatabasePermission=oO;function l0(e,t){return!e&&!t?!0:!e||!t?!1:e.toUpperCase()===t.toUpperCase()}C.equalsIgnoreCase=l0;var sO=e=>{var t;return Hr((t=e.properties)===null||t===void 0?void 0:t.permissions,de.environmentPermissions.CreateFlow)};C.doesUserHaveCreateFlowPermission=sO;var lO=e=>(0,C.doesUserHaveAdminPermission)(e)&&(0,C.hasCommonDataServiceDatabase)(e)?!0:(0,C.doesUserHaveCreateFlowPermission)(e)?to(e)||(0,C.doesUserHaveDatabaseTablePermissions)(e):!1;C.isUserPautoMakerWithDataAccess=lO;var uO=e=>(0,C.doesUserHaveCreateFlowPermission)(e)&&!to(e)&&!(0,C.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,C.doesUserHaveAdminPermission)(e)||!(0,C.hasCommonDataServiceDatabase)(e));C.isUserPautoMakerWithoutDataAccess=uO;var cO=e=>{var t,r;return!Hr((t=e.properties)===null||t===void 0?void 0:t.permissions,de.environmentPermissions.CreateFlow)&&Hr((r=e.properties)===null||r===void 0?void 0:r.permissions,de.environmentPermissions.ReadEnvironment)};C.doesUserHaveFlowRunOnlyPermission=cO});var Wc=v(w=>{"use strict";Object.defineProperty(w,"__esModule",{value:!0});w.getRequiredComponentsQueryUrl=w.solutionComponentCountSummariesQueryUrl=w.solutionComponentSummariesQueryUrl=w.solutionComponentConfigurationsQueryUrl=w.chartsQueryUrl=w.workflowsQueryUrl=w.entityDefinitionsQueryUrl=w.solutionComponentDefinitionsQueryUrl=w.getCreateNewArticleTemplateUrl=w.getCreateNewPublisherUrl=w.getEnableSecurityRolesUrl=w.getArticleTemplateUrl=w.getFieldSecurityProfileDesignerUrl=w.getSecurityRoleDesignerUrl=w.getMailMergeTemplateDesignerUrl=w.getEmailTemplateDesignerUrl=w.getConnectionRoleDesignerUrl=w.getSiteMapDesignerUrl=w.getWebResourceFileUrl=w.getWebResourceDesignerUrl=w.getReportDesignerUrl=w.getBusinessProcessFlowDesignerUrl=w.getProcessShareUrl=w.getProcessDesignerUrl=w.getChartDesignerUrl=w.getOpenModernEntityDashboardUrl=w.getNewModernEntityDashboardUrl=w.getNewModernDashboardUrl=w.getOpenModernDashboardUrl=w.getDashboardDesignerUrl=w.getAppModuleDesignerUrl=w.privilegesQueryUrls=w.xrmApiUrl=w.getPlayAppModuleUrl=w.getCrmAdminSecurityUsersUrl=w.getCrmAdminSecurityRolesUrl=w.getCrmMyAppsUrl=w.getCrmAppDesignerUrl=w.getCrmDevResourcesUrl=w.getCrmAllPublishersUrl=w.getCrmAllSolutionsUrl=w.getSolutionPublisherUrl=w.getExportTranslationFileName=w.getExportSolutionTranslationUrl=w.getImportSolutionTranslationUrl=w.getShowSolutionDependenciesUrl=w.getShowComponentDependenciesUrl=w.cdsServiceUrl=w.ODATA_NEXT_LINK=w.ODATA_MAX_PAGE_SIZE=void 0;w.retrieveOrganizationResources=w.getUCIEntityRecordEditUrl=w.getUCIEntityRecordBaseUrl=w.getBusinessRuleDesignerUri=w.retrieveUnpublishedSuffix=w.getSavePowerSettingUri=w.getPowerSettingUri=w.getPowerSettingsUri=w.RetrievePlatform=w.getAppSettingOverrideUri=w.AppSettingOverrideName=w.getOrgSettingOverrideUri=w.OrgSettingOverrideName=w.getSettingDefinitionsUri=w.retrieveFeatureControlSettingsByNamespaceUrl=w.retrieveDeploymentPipelineConfigAppUrl=w.SPNPrincipalIdUrl=w.retrieveDeploymentEnvironmentInfoUrl=w.devSolutionInfoUrl=w.deployOperationStatusUrl=w.getAIGeneratedDeploymentNotesUrl=w.deploymentStageRunUrl=w.validatePackageAsyncUrl=w.deployPackageAsyncUrl=w.updateDeploymentStageRunUrl=w.createDeploymentStageRunUrl=w.retrieveDeploymentStagesUrl=w.retrievePipelinesUrl=w.retrieveDeploymentPipelineInfoUrl=w.getDeploymentStageRunsUrl=w.appDeploymentUrls=w.getProvisionLanguageUrl=w.getSolutionQueryUrl=w.getSolutionsByUniqueNameQueryUrl=w.solutionsQueryUrl=w.getDependentComponentsWithMetadataQueryUrl=void 0;var c0=u0();w.ODATA_MAX_PAGE_SIZE="odata.maxpagesize";w.ODATA_NEXT_LINK="@odata.nextLink";w.cdsServiceUrl="https://cds-org/";var no;(function(e){e.AllSolutions="11",e.AllPublishers="10",e.DevResources="05"})(no||(no={}));function dO(e,t,r,n){return`${e}tools/dependency/dependencyviewdialog.aspx?appSolutionId=%7b${t}%7d&dType=1&objectid=%7b${r}%7d&objecttype=${n}&operationtype=showdependency`}w.getShowComponentDependenciesUrl=dO;function pO(e,t){let r=`dType=1&isproactivecheck=true&objecttype=7100&operationtype=dependenciesforuninstall&objectid=${t}`;return`${e}tools/dependency/dependencyviewdialog.aspx?${r}`}w.getShowSolutionDependenciesUrl=pO;function fO(e,t){return`${e}tools/muiProvisioning/Dialogs/LangTranslationsImport.aspx?dType=1&appSolutionId=${t}`}w.getImportSolutionTranslationUrl=fO;function mO(e,t){return`${e}_grid/cmds/dlg_exportsolution.aspx?command=exporttranslation&appSolutionId=${t}`}w.getExportSolutionTranslationUrl=mO;function hO(e,t){return e!==void 0&&t!==void 0&&`CrmTranslations_${e}_${t.replace(/[.]/g,"_")}.zip`||""}w.getExportTranslationFileName=hO;function gO(e,t,r){return r?`${e}tools/publisher/edit.aspx?appSolutionId=%7b${r}%7d&id=%7b${t}%7d`:`${e}tools/publisher/edit.aspx?id=%7b${t}%7d`}w.getSolutionPublisherUrl=gO;function Hc(e,t){return`${e}tools/systemcustomization/systemCustomization.aspx?pid=${t}`}function vO(e){return Hc(e,no.AllSolutions)}w.getCrmAllSolutionsUrl=vO;function yO(e){return Hc(e,no.AllPublishers)}w.getCrmAllPublishersUrl=yO;function bO(e){return Hc(e,no.DevResources)}w.getCrmDevResourcesUrl=bO;function wO(e,t=c0.crmBapSolutionId){return`${e}designer/app/${t}#/CreateNewApp`}w.getCrmAppDesignerUrl=wO;function AO(e){return`${e}apps`}w.getCrmMyAppsUrl=AO;function CO(e){return d0(e,"role")+"&forceUCI=0"}w.getCrmAdminSecurityRolesUrl=CO;function EO(e){return`${d0(e,"systemuser")}&forceclassic=1`}w.getCrmAdminSecurityUsersUrl=EO;function d0(e,t){return`${e}main.aspx?pagetype=entitylist&etn=${t}`}function SO(e,t){return`${e}main.aspx?appid=${t}`}w.getPlayAppModuleUrl=SO;w.xrmApiUrl="api/data/v9.0";w.privilegesQueryUrls={systemUserInfo:e=>`${e}${w.xrmApiUrl}/WhoAmI`,userPrivileges:(e,t)=>`${e}${w.xrmApiUrl}/systemusers(${t})/Microsoft.Dynamics.CRM.RetrieveUserPrivileges`,systemPrivileges:e=>`${e}${w.xrmApiUrl}/privileges/Microsoft.Dynamics.CRM.RetrievePrivilegeSet`};function NO(e,t,r=c0.crmBapSolutionId){return`${e}designer/app/${r}/${t}/AppDesignerCanvas/${t}`}w.getAppModuleDesignerUrl=NO;function DO(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${r}%7d&extraqs=%26formId%3d%7b${t}%7d%26dashboardType%3d1030&pagetype=${`${n?"ic":""}dashboardeditor`}`}w.getDashboardDesignerUrl=DO;function IO(e,t,r){return`/e/${e}/s/${t}/dashboard/${r}`}w.getOpenModernDashboardUrl=IO;function _O(e,t,r){let n=r!==void 0?r.toString():void 0;return`/e/${e}/s/${t}/dashboard/new${n?`/${n}`:""}`}w.getNewModernDashboardUrl=_O;function TO(e,t,r,n){let i=n!==void 0?n.toString():void 0;return`/e/${e}/s/${t}/n/${r}/dashboard/new${i?`/${i}`:""}`}w.getNewModernEntityDashboardUrl=TO;function PO(e,t,r,n){return`/e/${e}/s/${t}/n/${r}/dashboard/${n}`}w.getOpenModernEntityDashboardUrl=PO;function OO(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${t}%7d&extraqs=etc=${r||""}`+(n?`%26id=${n}`:"")+"&pagetype=vizdesigner"}w.getChartDesignerUrl=OO;function RO(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}w.getProcessDesignerUrl=RO;function FO(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}w.getProcessShareUrl=FO;function xO(e,t){return`${e}Tools/ProcessControl/UnifiedProcessDesigner.aspx?id=${t}`}w.getBusinessProcessFlowDesignerUrl=xO;function LO(e,t,r){return`${e}CRMReports/reportproperty.aspx?appSolutionId=%7b${r}%7d&disablePersonal=true&id=%7b${t}%7d`}w.getReportDesignerUrl=LO;function kO(e,t,r){return`${e}main.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&etc=9333&id=%7b${t}%7d&pagetype=webresourceedit`}w.getWebResourceDesignerUrl=kO;function MO(e,t){return`${e}WebResources/${t}`}w.getWebResourceFileUrl=MO;function UO(e,t,r){return`${e}designer/sitemap/${r}/${t}/SiteMapHome/${t}`}w.getSiteMapDesignerUrl=UO;function BO(e,t,r){return`${e}connections/connectionroles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}w.getConnectionRoleDesignerUrl=BO;function $O(e,t,r){return`${e}tools/emailtemplateeditor/emailtemplateeditor.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}w.getEmailTemplateDesignerUrl=$O;function qO(e,t,r){return`${e}tools/mailmerge/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}w.getMailMergeTemplateDesignerUrl=qO;function VO(e,t,r){return`${e}biz/roles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}w.getSecurityRoleDesignerUrl=VO;function GO(e,t,r){return`${e}biz/fieldsecurityprofiles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}w.getFieldSecurityProfileDesignerUrl=GO;function zO(e,t,r){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?_CreateFromId=%7b${t}%7d&_CreateFromType=7100&appSolutionId=%7b${t}%7d&id=%7b${r}%7d`}w.getArticleTemplateUrl=zO;function WO(e,t,r,n){return`${e}tools/FormEditor/Dialogs/FormRoleAssignment.aspx?appSolutionId=%7b${t}%7d&dType=1&formId=%7b${r}%7d&objectTypeCode=0&type=${n}`}w.getEnableSecurityRolesUrl=WO;function HO(e){return`${e}tools/publisher/edit.aspx`}w.getCreateNewPublisherUrl=HO;function jO(e,t){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?appSolutionId=${t}`}w.getCreateNewArticleTemplateUrl=jO;w.solutionComponentDefinitionsQueryUrl="api/data/v9.0/solutioncomponentdefinitions";w.entityDefinitionsQueryUrl="api/data/v9.0/EntityDefinitions?$select=EntitySetName,DisplayName,LogicalName&$filter=";w.workflowsQueryUrl="api/data/v9.0/workflows";w.chartsQueryUrl="/api/data/v9.0/savedqueryvisualizations";w.solutionComponentConfigurationsQueryUrl="/api/data/v9.1/solutioncomponentconfigurations?$filter=isdisplayable eq true&$select=name";w.solutionComponentSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentsummaries";w.solutionComponentCountSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentcountsummaries";function JO(e,t){return`${w.xrmApiUrl}/RetrieveRequiredComponents(ObjectId=${e},ComponentType=${t})`}w.getRequiredComponentsQueryUrl=JO;function QO(e,t){return`${w.cdsServiceUrl}${w.xrmApiUrl}/RetrieveDependentComponentsWithMetadata(ObjectId=${e},ComponentType=${t})`}w.getDependentComponentsWithMetadataQueryUrl=QO;w.solutionsQueryUrl="/api/data/v9.0/solutions?$expand=publisherid&$filter=(isvisible eq true)";function KO(e){return`/api/data/v9.0/solutions?$expand=publisherid&$filter=(uniquename eq '${e}')`}w.getSolutionsByUniqueNameQueryUrl=KO;function XO(e){return`/api/data/v9.0/solutions(${e})?$expand=publisherid`}w.getSolutionQueryUrl=XO;function YO(e){return`${e}api/data/v9.1/ProvisionLanguageForUser`}w.getProvisionLanguageUrl=YO;w.appDeploymentUrls={associateEnvironmentToPipelineUrl:e=>`/api/data/v9.0/deploymentpipelines(${e})/deploymentpipeline_deploymentenvironment/$ref`,deploymentArtifactsUrl:"/api/data/v9.0/deploymentartifacts",deploymentEnvironmentUrl:"/api/data/v9.0/deploymentenvironments",deploymentPipelinesUrl:"/api/data/v9.0/deploymentpipelines",deploymentStagesUrl:"/api/data/v9.0/deploymentstages",retrieveDeploymentPipelinesUrl:e=>`/api/data/v9.0/RetrieveDeploymentPipelines(SourceEnvironmentId='${e}')`,deletePipelinesUrl:e=>`/api/data/v9.0/deploymentpipelines(${e})`};function ZO(e,t,r,n=!1,i=!1,a=!1,o=!1,s=!1,l=!1,u=!1){return`/api/data/v9.1/deploymentstageruns+`)),this.type=t,this.id=r,this.issues=u,this.pointer=(o=(a=u[0])===null||a===void 0?void 0:a.pointer)!==null&&o!==void 0?o:"",this.rule=(l=(s=u[0])===null||s===void 0?void 0:s.rule)!==null&&l!==void 0?l:"invalid"}};Z.ValidationError=id;var ad=class extends nt{constructor(t){super("INVALID_ARGUMENT",t)}};Z.InvalidArgumentError=ad;var od=class extends nt{constructor(t,r,n){super("STALE_ARTIFACT",`Cannot apply the edit at ${n} to ${t}/${r}: the cached copy was stale and the server copy has since changed, so any pointer derived from the old copy may now identify a different node. The local copy has been refreshed \u2014 re-read the artifact, re-derive the pointer, and retry.`),this.type=t,this.id=r,this.pointer=n}};Z.StaleArtifactError=od;var sd=class extends nt{constructor(t,r,n,i){super("LOCAL_EDITS_WOULD_BE_LOST",`Refusing to fetch ${t}/${r}: the local copy has unpushed edits AND the server has moved since it was fetched (local=${n??"(none)"}, server=${i??"(none)"}). Overwriting now would discard your edits and replace them with another writer's changes. Push or discard your edits first, or pass { overwrite: true } to deliberately reset the local copy to the server version.`),this.type=t,this.id=r,this.localEtag=n,this.serverEtag=i}};Z.LocalEditsWouldBeLostError=sd;var ld=class extends nt{constructor(t,r,n,i,a){super("VERSION_CONFLICT",`Version conflict for ${t}/${r}: local=${n??"(none)"}, server=${i??"(none)"}. Re-fetch and reapply changes.${a?` ${a}`:""}`),this.type=t,this.id=r,this.localEtag=n,this.serverEtag=i,this.detail=a}};Z.VersionConflictError=ld;var ud=class extends nt{constructor(t,r,n,i){super("CONNECTION_ERROR",r>0?`HTTP ${r} from ${t}: ${n}`:`Transport failure reaching ${t}: ${n}`),this.url=t,this.statusCode=r,this.cause=i}};Z.ConnectionError=ud;var cd=class extends nt{constructor(t){super("WORKSPACE_NOT_INITIALIZED",`Workspace not initialized at ${t}. Call initWorkspace() first.`),this.workspacePath=t}};Z.WorkspaceNotInitializedError=cd;var dd=class extends nt{constructor(t,r){super("NOT_IMPLEMENTED",`Operation '${t}' is not implemented yet${r?`: ${r}`:""}.`),this.operation=t}};Z.NotImplementedError=dd;var pd=class extends nt{constructor(t,r){super("INVALID_JSON_POINTER",`Invalid JSON Pointer '${t}': ${r}`),this.pointer=t}};Z.JsonPointerError=pd;var fd=class extends nt{constructor(t,r,n){super("AMBIGUOUS_ARTIFACT",`Found ${n} ${t} rows matching '${r}'; a name is not a unique key. Resolve by id / alternate key instead of relying on name-based idempotency.`),this.kind=t,this.identity=r,this.matchCount=n}};Z.AmbiguousArtifactError=fd;var md=class extends nt{constructor(t,r){super("PATH_TRAVERSAL",`Refusing to resolve a path outside the workspace root: '${t}' is not within '${r}'.`),this.target=t,this.root=r}};Z.PathTraversalError=md;var hd=class extends nt{constructor(t,r){super("INCOMPATIBLE_WORKSPACE",`Workspace schema version ${t} is newer than this SDK supports (v${r}). Upgrade the SDK, or re-create the workspace with this version.`),this.workspaceVersion=t,this.supportedVersion=r}};Z.IncompatibleWorkspaceError=hd});var le=y(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.odataQuery=Me.normalizeGuid=Me.createSafeXmlElement=Me.assertNoControlChars=Me.assertODataName=Me.assertXmlName=Me.xmlText=Me.odataPathLiteral=Me.odataLiteral=void 0;var Qs=ee();function S0(e){return String(e??"").replace(/'/g,"''")}Me.odataLiteral=S0;function bO(e){return encodeURIComponent(S0(e))}Me.odataPathLiteral=bO;function wO(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}Me.xmlText=wO;function N0(e,t){let r=String(e??""),n=/^[A-Za-z_][0-9A-Za-z_.-]*$/,i=r.split(":");if(!(i.length<=2&&i.every(o=>n.test(o))&&!/^xmlns/i.test(r)))throw new Qs.InvalidArgumentError(`${t} must be a valid XML element name (got '${e}')`);return e}Me.assertXmlName=N0;function AO(e,t){let r=String(e??"");if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw new Qs.InvalidArgumentError(`${t} must be a valid OData identifier (letters, digits, underscore): got '${e}'`);return e}Me.assertODataName=AO;function CO(e,t){if(/[\u0000-\u001F\u007F]/.test(String(e??"")))throw new Qs.InvalidArgumentError(`${t} must not contain control characters (including CR/LF): they would inject additional lines into the request`);return e}Me.assertNoControlChars=CO;function EO(e,t,r){return e.createElement(N0(t,r))}Me.createSafeXmlElement=EO;var SO=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;function NO(e,t){let r=String(e??""),n=r.length===38&&r.startsWith("{")&&r.endsWith("}")?r.slice(1,-1):r;if(!SO.test(n))throw new Qs.InvalidArgumentError(`${t} must be a valid GUID (got '${e}')`);return n.toLowerCase()}Me.normalizeGuid=NO;function DO(e){let t=[];for(let[r,n]of e)n!=null&&n!==""&&t.push(`${r}=${encodeURIComponent(String(n))}`);return t.length>0?`?${t.join("&")}`:""}Me.odataQuery=DO});var Ee=y(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.nowIso=ue.isAlreadyDeleted=ue.deleteRecord=ue.ensureSuccess=ue.resolveCreatedId=ue.requireCreatedId=ue.withClientMintedId=ue.readCreatedId=ue.readEtag=ue.requireEtag=ue.echoWrite=ue.UPDATE_NO_ETAG_CODE=ue.VERSION_CONFLICT_CODE=void 0;var Vi=ee(),fo=le();ue.VERSION_CONFLICT_CODE="VERSION_CONFLICT";ue.UPDATE_NO_ETAG_CODE="ARTIFACT_UPDATE_NO_ETAG";function IO(e,t){return{query:`?$select=${encodeURIComponent(e)}`,options:{headers:{...t??{},Prefer:"return=representation"}}}}ue.echoWrite=IO;function _O(e,t,r){if(!e)throw new Vi.SdkError(ue.UPDATE_NO_ETAG_CODE,`Refusing to push ${t} '${r}': no concurrency token is held for it, so the write could not be made conditional and would silently overwrite a concurrent edit. Re-fetch the ${t} and re-apply the change.`);return e}ue.requireEtag=_O;function TO(e){var t;let r=(t=e.headers)!==null&&t!==void 0?t:{};for(let i of Object.keys(r))if(i.toLowerCase()==="etag")return r[i];let n=e.body;return n&&typeof n["@odata.etag"]=="string"?n["@odata.etag"]:null}ue.readEtag=TO;function gd(e,t){var r;let n=e.body;if(n&&typeof n[t]=="string")return(0,fo.normalizeGuid)(n[t],t);let i=(r=e.headers)!==null&&r!==void 0?r:{};for(let a of Object.keys(i))if(a.toLowerCase()==="odata-entityid"){let o=/\(([0-9a-fA-F-]{36})\)/.exec(i[a]);if(o)return(0,fo.normalizeGuid)(o[1],t)}return null}ue.readCreatedId=gd;function PO(e,t,r){return r?{...e,[t]:(0,fo.normalizeGuid)(r,t)}:e}ue.withClientMintedId=PO;function RO(e,t,r){let n=gd(e,t);if(!n)throw new Vi.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`);return n}ue.requireCreatedId=RO;function OO(e,t,r,n){let i=gd(e,t);if(i)return i;if(n)return(0,fo.normalizeGuid)(n,t);throw new Vi.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`)}ue.resolveCreatedId=OO;function D0(e,t){if(e.status===412)throw new Vi.SdkError(ue.VERSION_CONFLICT_CODE,`Version conflict (412) from ${t}`);if(e.status<200||e.status>=300)throw new Vi.ConnectionError(t,e.status,xO(e.body),e.body);return e}ue.ensureSuccess=D0;function xO(e){if(typeof e=="string"&&e.length>0)return e;if(e!==null&&typeof e=="object"){let t=e;if(t.error&&typeof t.error.message=="string")return t.error.message;if(typeof t.Message=="string")return t.Message;if(typeof t.message=="string")return t.message}return"request failed"}async function LO(e,t,r,n){let i=(0,fo.normalizeGuid)(r,"id"),a=`/${t}(${i})`;D0(await e.delete(a,n?{headers:{"If-Match":n}}:void 0),e.apiUrl(a))}ue.deleteRecord=LO;function FO(e){return e instanceof Vi.ConnectionError&&e.statusCode===404}ue.isAlreadyDeleted=FO;function kO(){return new Date().toISOString()}ue.nowIso=kO});var $t=y(Gi=>{"use strict";Object.defineProperty(Gi,"__esModule",{value:!0});Gi.describeMalformedValue=Gi.collectPages=void 0;var I0=Ee(),vd=ee();async function MO(e,t,r,n,i){let a=[],o=new Set,s=e.apiUrl(t),l=(0,I0.ensureSuccess)(await e.get(t,i),s);for(n?.(l);;){let u=l.body,c=u?.value;if(!Array.isArray(c))throw new vd.ConnectionError(s,l.status,`${r}: paginated read returned a malformed page \u2014 expected an OData 'value' array but got ${yd(c)}; refusing to return partial results.`);for(let p of c)a.push(p);let d=u?.["@odata.nextLink"];if(d==null)break;if(typeof d!="string"||d.length===0)throw new vd.ConnectionError(s,l.status,`${r}: paginated read returned a malformed @odata.nextLink (${yd(d)}); cannot follow it, and refusing to return partial results.`);if(o.has(d))throw new vd.InvalidArgumentError(`${r}: aborting pagination \u2014 the server returned a repeated @odata.nextLink ('${d}'), which would loop indefinitely.`);o.add(d),s=d,l=(0,I0.ensureSuccess)(await e.getAbsolute(d,i),d)}return a}Gi.collectPages=MO;function yd(e){return e===null?"null":e===void 0?"undefined (missing)":`a ${typeof e}`}Gi.describeMalformedValue=yd});var bd=y(Tr=>{"use strict";Object.defineProperty(Tr,"__esModule",{value:!0});Tr.businessRuleApi=Tr.BUSINESS_RULE_LEFT_DEACTIVATED_CODE=Tr.WFOM_API_UNAVAILABLE_CODE=void 0;var en=si(),BO=$t(),it=Ee(),Rn=le(),Ys=ee();Tr.WFOM_API_UNAVAILABLE_CODE="BUSINESS_RULE_API_UNAVAILABLE";Tr.BUSINESS_RULE_LEFT_DEACTIVATED_CODE="BUSINESS_RULE_LEFT_DEACTIVATED";async function _0(e,t,r,n){let i=`/workflows(${qO})/Microsoft.Dynamics.CRM.${t}`;try{return(0,it.ensureSuccess)(await e.post(i,{Entity:r.Entity,WfomJson:r.WfomJson},{headers:n}),e.apiUrl(i))}catch(a){throw a?.statusCode!==404?a:new Ys.SdkError(Tr.WFOM_API_UNAVAILABLE_CODE,`Business-rule authoring (preview) is not enabled on this environment yet: it does not expose 'Microsoft.Dynamics.CRM.${t}'. The bound members are still rolling out, so re-check once the release flag reaches this environment. Nothing was written. The SDK does NOT fall back to generating workflow XAML: that covered only 4 of the 7 action types and would silently save a rule different from the one you wrote.`)}}async function UO(e,t){let r=`/workflows(${t})${(0,Rn.odataQuery)([["$select","workflowid,statecode,statuscode"]])}`;try{let n=await e.get(r);if(n.status<200||n.status>=300)return null;let i=n.body;return{etag:(0,it.readEtag)(n),statecode:typeof i?.statecode=="number"?i.statecode:null,statuscode:typeof i?.statuscode=="number"?i.statuscode:null}}catch{return null}}async function $O(e,t,r){let n=await UO(e,t);if(n===null||n.etag===null)throw new Ys.SdkError(it.VERSION_CONFLICT_CODE,`Refusing to update business rule '${t}': its current version could not be read, so the write could not be verified as conditional. The supported update api does not enforce If-Match, so proceeding would risk silently overwriting a concurrent edit. Re-fetch the rule and try again.`);if(n.etag!==r)throw new Ys.SdkError(it.VERSION_CONFLICT_CODE,`Version conflict updating business rule '${t}': it changed on the server since it was fetched (held ${r}, server ${n.etag}). Re-fetch the rule and re-apply the change.`);return{statecode:n.statecode,statuscode:n.statuscode}}var qO="00000000-0000-0000-0000-000000000000",Xs={"Content-Type":"application/json",Accept:"application/json","OData-Version":"4.0","OData-MaxVersion":"4.0"},VO="workflowid,name,description,primaryentity,statecode,category,type",GO="category eq 2 and type eq 1";async function T0(e,t,r){var n;if(r==="Draft")return null;let i=(0,Rn.normalizeGuid)(t,"workflowid"),a=r==="Active",o={statecode:a?en.StateCode.Activated:en.StateCode.Draft,statuscode:a?en.StatusCode.Activated:en.StatusCode.Draft},s=`/workflows(${i})`,l=(0,it.ensureSuccess)(await e.patch(s,o,{headers:Xs}),e.apiUrl(s));return(n=(0,it.readEtag)(l))!==null&&n!==void 0?n:await mo(e,i)}async function mo(e,t){let r=`/workflows(${t})${(0,Rn.odataQuery)([["$select","workflowid"]])}`;try{let n=await e.get(r);return n.status>=200&&n.status<300?(0,it.readEtag)(n):null}catch{return null}}async function zO(e,t,r){let n=await mo(e,t),i=await r(),a=(0,it.readEtag)(i);if(a)return{response:i,etag:a};let o=await mo(e,t);return{response:i,etag:n!==null&&n===o?o:null}}Tr.businessRuleApi={async get(e,t){let r=(0,Rn.normalizeGuid)(t,"id"),n=`/workflows(${r})/Microsoft.Dynamics.CRM.RetrieveProcessWithWfomJson`,{response:i,etag:a}=await zO(e,r,async()=>(0,it.ensureSuccess)(await e.get(n),e.apiUrl(n)));return{raw:i.body,etag:a}},async list(e,t){let r=[GO];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,Rn.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,Rn.odataQuery)([["$select",VO],["$filter",r.join(" and ")]])}`;return(await(0,BO.collectPages)(e,n,"listArtifacts('businessRule')")).map(a=>{var o,s;return{type:"businessRule",id:(o=a.workflowid)!==null&&o!==void 0?o:"",name:(s=a.name)!==null&&s!==void 0?s:"",entityLogicalName:a.primaryentity,isDirty:!1}})},async create(e,t){var r;let n=t,i=(0,Rn.normalizeGuid)(n.Entity.workflowid,"workflowid"),a=await _0(e,"CreateProcessWithWfomJson",n,Xs),o=(0,it.resolveCreatedId)(a,"workflowid","business rule",i),s=null;try{s=await T0(e,o,n.status)}catch(l){try{await(0,it.deleteRecord)(e,"workflows",o)}catch{}throw l}return{id:o,etag:(r=s??(0,it.readEtag)(a))!==null&&r!==void 0?r:await mo(e,o)}},async update(e,t,r,n){var i,a;let o=r,s=(0,Rn.normalizeGuid)(t,"id"),l=`/workflows(${s})`,u={...Xs,"If-Match":(0,it.requireEtag)(n,"business rule",s)},c=await $O(e,s,u["If-Match"]),d=c.statecode===en.StateCode.Activated;d&&(0,it.ensureSuccess)(await e.patch(l,{statecode:en.StateCode.Draft,statuscode:en.StatusCode.Draft},{headers:u}),e.apiUrl(l));let p;try{p=await _0(e,"UpdateProcessWithWfomJson",o,u)}catch(m){if(d)try{(0,it.ensureSuccess)(await e.patch(l,{statecode:en.StateCode.Activated,statuscode:(i=c.statuscode)!==null&&i!==void 0?i:en.StatusCode.Activated},{headers:Xs}),e.apiUrl(l))}catch(h){throw new Ys.SdkError(Tr.BUSINESS_RULE_LEFT_DEACTIVATED_CODE,`The business-rule write failed AND the rule could not be re-activated, so '${s}' is left DEACTIVATED (Draft) on the server. Re-activate it before relying on it. Original write failure: ${m instanceof Error?m.message:String(m)}. Restore failure: ${h instanceof Error?h.message:String(h)}`)}throw m}let f=await T0(e,s,o.status);return{id:s,etag:(a=f??(0,it.readEtag)(p))!==null&&a!==void 0?a:await mo(e,s)}},delete(e,t){return(0,it.deleteRecord)(e,"workflows",t)}}});var tl=y(el=>{"use strict";Object.defineProperty(el,"__esModule",{value:!0});el.JsonPointer=void 0;var qt=ee(),Zs=class e{static isReservedToken(t){return e.RESERVED_TOKENS.has(t)}static decodeToken(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}static encodeToken(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}static parse(t){if(t==="")return[];if(t[0]!=="/")throw new qt.JsonPointerError(t,'non-empty pointers must start with "/"');return t.substring(1).split("/").map(r=>{if(/~(?![01])/.test(r))throw new qt.JsonPointerError(t,`invalid '~' escape in token '${r}' (expected ~0 or ~1)`);return e.decodeToken(r)})}static compile(t){return t.length===0?"":"/"+t.map(r=>e.encodeToken(r)).join("/")}static resolve(t,r){let n=e.parse(r),i=t;for(let a of n)if(Array.isArray(i)){let o=e.toArrayIndex(a,i.length);if(o===void 0)return;i=i[o]}else if(i!==null&&typeof i=="object"){let o=i;if(e.isReservedToken(a)||!Object.prototype.hasOwnProperty.call(o,a))return;i=o[a]}else return;return i}static set(t,r,n){let i=e.parse(r);if(i.length===0)throw new qt.JsonPointerError(r,"cannot set the document root");let{parent:a,lastToken:o}=e.resolveParent(t,i,r);if(Array.isArray(a)){let s=e.toArrayIndex(o,a.length);if(s===void 0)throw new qt.JsonPointerError(r,`'${o}' is not a valid array index`);if(s>a.length)throw new qt.JsonPointerError(r,`array index '${o}' is out of range`);a[s]=n}else{if(e.isReservedToken(o))throw new qt.JsonPointerError(r,`refusing to write reserved property '${o}'`);a[o]=n}}static remove(t,r){let n=e.parse(r);if(n.length===0)throw new qt.JsonPointerError(r,"cannot remove the document root");let{parent:i,lastToken:a}=e.resolveParent(t,n,r);if(Array.isArray(i)){let o=e.toArrayIndex(a,i.length);if(o===void 0||o>=i.length)throw new qt.JsonPointerError(r,`array index '${a}' is out of range`);i.splice(o,1)}else{if(e.isReservedToken(a))throw new qt.JsonPointerError(r,`refusing to remove reserved property '${a}'`);delete i[a]}}static add(t,r,n,i){let a=e.parse(r);if(a.length>0&&a[a.length-1]==="-"){let l=e.compile(a.slice(0,-1)),u=e.resolve(t,l);if(!Array.isArray(u))throw new qt.JsonPointerError(r,"add target must be an array");u.push(n);return}let o=e.resolve(t,r);if(!Array.isArray(o))throw new qt.JsonPointerError(r,"add target must be an array");let s=i===void 0?o.length:i;if(s<0||s>o.length)throw new qt.JsonPointerError(r,`insert index ${s} is out of range`);o.splice(s,0,n)}static parent(t){let r=e.parse(t);return r.pop(),e.compile(r)}static lastToken(t){let r=e.parse(t);return r.length===0?"":r[r.length-1]}static append(t,r){return`${t}/${e.encodeToken(String(r))}`}static resolveParent(t,r,n){let i=r[r.length-1],a=e.compile(r.slice(0,-1)),o=e.resolve(t,a);if(o===null||typeof o!="object")throw new qt.JsonPointerError(n,"parent path does not resolve to an object or array");return{parent:o,lastToken:i}}static toArrayIndex(t,r){if(t==="-")return r;if(/^(0|[1-9][0-9]*)$/.test(t))return Number(t)}};el.JsonPointer=Zs;Zs.RESERVED_TOKENS=new Set(["__proto__","prototype","constructor"])});var R0=y(rl=>{"use strict";Object.defineProperty(rl,"__esModule",{value:!0});rl.findElements=void 0;var P0=tl();function WO(e,t){let r=[];return wd(e,"",t,r),r}rl.findElements=WO;function wd(e,t,r,n){if(!(e===null||typeof e!="object"))if(r(e,t)&&n.push({pointer:t,value:e}),Array.isArray(e))e.forEach((i,a)=>{wd(i,P0.JsonPointer.append(t,a),r,n)});else for(let i of Object.keys(e))wd(e[i],P0.JsonPointer.append(t,i),r,n)}});var Ad=y(Pr=>{"use strict";Object.defineProperty(Pr,"__esModule",{value:!0});Pr.assertMutationResult=Pr.assertExistsResult=Pr.assertReadResult=Pr.assertStorageContract=void 0;var jO=["readText","writeTextAtomic","deleteFile","deleteByPrefix"],HO=["ensureContainer","exists"];function JO(e){if(typeof e!="object"||e===null)throw new Error("workspaceStorage must be an object implementing WorkspaceStorage.");for(let t of jO)if(typeof e[t]!="function")throw new Error(`workspaceStorage is missing the required method '${t}'.`);for(let t of HO){let r=e[t];if(r!==void 0&&typeof r!="function")throw new Error(`workspaceStorage.${t} must be a function when present.`)}return e}Pr.assertStorageContract=JO;function KO(e,t){if(e===null||typeof e=="string")return e;throw new Error(`workspaceStorage.readText must resolve to a string or null for ${t}; got ${typeof e}. Absence is null \u2014 resolving undefined would make a present value look absent.`)}Pr.assertReadResult=KO;function QO(e,t){if(typeof e=="boolean")return e;throw new Error(`workspaceStorage.exists must resolve to a boolean for ${t}; got ${typeof e}. A truthy non-boolean would make an absent value look present.`)}Pr.assertExistsResult=QO;function XO(e,t){if(e!==void 0)throw new Error(`workspaceStorage.${t} must resolve to undefined; got ${typeof e}. A status-returning implementation would let a failed write be reported as a completed one.`)}Pr.assertMutationResult=XO});var Cd=y(zi=>{"use strict";Object.defineProperty(zi,"__esModule",{value:!0});zi.retryTransientIoAsync=zi.retryTransientIo=void 0;var YO=new Set(["EPERM","EACCES","EBUSY","UNKNOWN"]),ZO=5,O0=10;function e1(e){for(let t=1;;t+=1)try{return e()}catch(r){if(!x0(r,t))throw r;r1(O0*t)}}zi.retryTransientIo=e1;async function t1(e){for(let t=1;;t+=1)try{return await e()}catch(r){if(!x0(r,t))throw r;await new Promise(n=>setTimeout(n,O0*t))}}zi.retryTransientIoAsync=t1;function x0(e,t){let r=e.code;return t<ZO&&!!r&&YO.has(r)}function r1(e){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}catch{let t=Date.now()+e;for(;Date.now()<t;);}}});var M0=y(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:!0});Vt.canonicalArtifactId=Vt.WorkspaceManager=Vt.WORKSPACE_SCHEMA_VERSION=Vt.retryTransientIo=void 0;var pr=Ad(),nl=ee(),n1=Cd();Object.defineProperty(Vt,"retryTransientIo",{enumerable:!0,get:function(){return n1.retryTransientIo}});function L0(e){let t=e;return typeof t.pathFor=="function"&&typeof t.getRoot=="function"?e:null}Vt.WORKSPACE_SCHEMA_VERSION=1;var On={form:"forms",view:"views",businessRule:"business-rules",app:"apps",command:"commands",chart:"charts",dashboard:"dashboards",genPage:"gen-pages",bpf:"business-process-flows"},i1="manifest.json",ho=".metadata",F0="entities";function k0(e){try{return Promise.resolve(e())}catch(t){return Promise.reject(t)}}var Ed=class{withManifest(t){let r=this.manifestQueue.then(t,t);return this.manifestQueue=r.then(()=>{},()=>{}),r}constructor(t,r,n){if(this.workspaceLabel=t,this.instanceUrl=r,this.manifestQueue=Promise.resolve(),n==null)throw new Error("WorkspaceManager requires a WorkspaceStorage. Node callers can build one with `createNodeWorkspaceStorage(path)` from '@maker-studio/cds-maker-sdk/node'.");this.storage=n}artifactKey(t,r){return this.assertSafeId(r),[On[t],`${go(r)}.json`]}metaKey(t,r){return this.assertSafeId(r),[ho,On[t],`${go(r)}.meta.json`]}entityKey(t){return this.assertSafeId(t),[ho,F0,`${t}.json`]}fsStore(){let t=L0(this.storage);if(!t)throw new Error("This workspace is not filesystem-backed, so it has no physical paths. Use the artifact/metadata/manifest accessors instead of the path helpers.");return t}getRoot(){let t=L0(this.storage);return t?t.getRoot():this.workspaceLabel}getArtifactDir(t){return this.fsStore().pathFor([On[t]])}getArtifactFilePath(t,r){return this.fsStore().pathFor(this.artifactKey(t,r))}getMetaFilePath(t,r){return this.fsStore().pathFor(this.metaKey(t,r))}getEntityMetaFilePath(t){return this.fsStore().pathFor(this.entityKey(t))}assertSafeId(t){if(typeof t!="string"||t.length===0||/[\u0000-\u001f]/.test(t)||t.includes("/")||t.includes("\\")||t.includes(":")||t==="."||t===".."||t.includes(".."))throw new nl.PathTraversalError(String(t),this.workspaceLabel)}get manifestKey(){return[i1]}async init(){if(this.storage.ensureContainer){let t=this.storage.ensureContainer.bind(this.storage),r=[[ho,F0]];for(let i of Object.keys(On))r.push([On[i]],[ho,On[i]]);let n=await Promise.allSettled(r.map(i=>k0(()=>t(i))));for(let i of n){if(i.status==="rejected")throw i.reason;(0,pr.assertMutationResult)(i.value,"ensureContainer")}}await this.withManifest(async()=>{if(await this.isInitialized())return;let t={instanceUrl:this.instanceUrl,createdAt:new Date().toISOString(),artifacts:[]};await this.writeManifest(t)})}async isInitialized(){return this.storage.exists?(0,pr.assertExistsResult)(await this.storage.exists(this.manifestKey),"manifest.json"):(0,pr.assertReadResult)(await this.storage.readText(this.manifestKey),"manifest.json")!==null}async ensureInitialized(){if(!await this.isInitialized())throw new nl.WorkspaceNotInitializedError(this.workspaceLabel)}async clean(){let t=Object.keys(On).map(i=>[On[i]]);t.push([ho]);let r=await Promise.allSettled(t.map(i=>k0(()=>this.storage.deleteByPrefix(i))));for(let i of r){if(i.status==="rejected")throw i.reason;(0,pr.assertMutationResult)(i.value,"deleteByPrefix")}let n=await this.getManifest();n.artifacts=[],n.lastSyncAt=void 0,await this.init(),await this.writeManifest(n)}async readArtifact(t,r){return await this.ensureInitialized(),this.readJson(this.artifactKey(t,r))}async writeArtifact(t,r,n){await this.ensureInitialized(),await this.writeJson(this.artifactKey(t,r),n),await this.upsertManifestEntry(t,r,n)}async deleteArtifact(t,r){await this.ensureInitialized(),(0,pr.assertMutationResult)(await this.storage.deleteFile(this.artifactKey(t,r)),"deleteFile"),(0,pr.assertMutationResult)(await this.storage.deleteFile(this.metaKey(t,r)),"deleteFile");let n=go(r);await this.withManifest(async()=>{let i=await this.getManifest();i.artifacts=i.artifacts.filter(a=>!(a.type===t&&a.id===n)),await this.writeManifest(i)})}async readMeta(t,r){return this.readJson(this.metaKey(t,r))}async writeMeta(t,r,n){await this.writeJson(this.metaKey(t,r),n)}async listArtifacts(t,r){return await this.ensureInitialized(),(await this.getManifest()).artifacts.filter(n=>!(t&&n.type!==t||r?.entityLogicalName&&n.entityLogicalName!==r.entityLogicalName))}async readEntityMetadata(t){await this.ensureInitialized();let r=await this.readJson(this.entityKey(t));return!r||typeof r.schemaName!="string"||typeof r.primaryNameAttribute!="string"||typeof r.primaryIdAttribute!="string"||typeof r.isCustomEntity!="boolean"?null:r}async writeEntityMetadata(t,r){await this.ensureInitialized(),await this.writeJson(this.entityKey(t),r)}async getManifest(){await this.ensureInitialized();let t=await this.readJson(this.manifestKey);if(!t)throw new nl.WorkspaceNotInitializedError(this.workspaceLabel);if(t.schemaVersion!==void 0&&t.schemaVersion>Vt.WORKSPACE_SCHEMA_VERSION)throw new nl.IncompatibleWorkspaceError(t.schemaVersion,Vt.WORKSPACE_SCHEMA_VERSION);return t}async writeManifest(t){await this.writeJson(this.manifestKey,{...t,schemaVersion:Vt.WORKSPACE_SCHEMA_VERSION})}async updateManifest(t){await this.withManifest(async()=>{let r=await this.getManifest();await this.writeManifest({...r,...t})})}async upsertManifestEntry(t,r,n){await this.withManifest(async()=>{let i=await this.getManifest(),a=go(r),o=n,s=typeof o.name=="string"?o.name:`${t}:${a}`,l=typeof o.entityLogicalName=="string"?o.entityLogicalName:void 0,u=i.artifacts.find(c=>c.type===t&&c.id===a);u?(u.name=s,u.entityLogicalName=l):i.artifacts.push({type:t,id:a,name:s,entityLogicalName:l,isDirty:!1}),await this.writeManifest(i)})}async readJson(t){let r=(0,pr.assertReadResult)(await this.storage.readText(t),t.join("/"));return r===null?null:JSON.parse(r)}async writeJson(t,r){(0,pr.assertMutationResult)(await this.storage.writeTextAtomic(t,`${JSON.stringify(r,null,2)}+`),"writeTextAtomic")}async removeFile(t){(0,pr.assertMutationResult)(await this.storage.deleteFile(t),"deleteFile")}async exists(t){return this.storage.exists?(0,pr.assertExistsResult)(await this.storage.exists(t),t.join("/")):(0,pr.assertReadResult)(await this.storage.readText(t),t.join("/"))!==null}};Vt.WorkspaceManager=Ed;function go(e){let r=/^\{?([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})\}?$/.exec(e);return r?r[1].toLowerCase():e.toLowerCase()}Vt.canonicalArtifactId=go});var Sd=y(Wi=>{"use strict";Object.defineProperty(Wi,"__esModule",{value:!0});Wi.deepEqual=Wi.deepDiff=void 0;var a1=tl();function o1(e,t){let r=[];return U0(e,t,"",r,0),r}Wi.deepDiff=o1;var il=Symbol("missing"),al=512;function U0(e,t,r,n,i){if(e===t)return;if(i>al)throw new RangeError(`deepDiff exceeded the maximum supported depth of ${al}`);let a=ol(e),o=ol(t);if(a&&o&&Array.isArray(e)===Array.isArray(t)){let s=s1(e,t);for(let l of s){let u=B0(e,l),c=B0(t,l),d=a1.JsonPointer.append(r,l);u===il?n.push({pointer:d,type:"added",newValue:c}):c===il?n.push({pointer:d,type:"removed",oldValue:u}):U0(u,c,d,n,i+1)}return}$0(e,t)||n.push({pointer:r,type:"modified",oldValue:e,newValue:t})}function ol(e){return e!==null&&typeof e=="object"}function s1(e,t){if(Array.isArray(e)&&Array.isArray(t)){let n=Math.max(e.length,t.length),i=[];for(let a=0;a<n;a++)i.push(String(a));return i}let r=new Set([...Object.keys(e),...Object.keys(t)]);return Array.from(r)}function B0(e,t){if(Array.isArray(e)){let r=Number(t);return r<e.length?e[r]:il}return t in e?e[t]:il}function $0(e,t){return q0(e,t,0)}Wi.deepEqual=$0;function q0(e,t,r){if(e===t)return!0;if(r>al)throw new RangeError(`deepEqual exceeded the maximum supported depth of ${al}`);if(!ol(e)||!ol(t)||Array.isArray(e)!==Array.isArray(t))return!1;let n=Object.keys(e),i=Object.keys(t);return n.length!==i.length?!1:n.every(a=>a in t&&q0(e[a],t[a],r+1))}});var G0=y(ji=>{"use strict";Object.defineProperty(ji,"__esModule",{value:!0});ji.VersionManager=ji.PROJECTION_VERSION=void 0;var V0=Sd();ji.PROJECTION_VERSION=3;var Nd=class{constructor(t){this.workspace=t}async storeMeta(t,r,n){var i;let a=await this.getMeta(t,r),o=((i=n.snapshot)===null||i===void 0?void 0:i.status)==="Active",s=a?.everActivated===!0||o;await this.workspace.writeMeta(t,r,s?{...n,everActivated:s}:n)}async getMeta(t,r){return this.workspace.readMeta(t,r)}async isDirty(t,r){let n=await this.workspace.readArtifact(t,r);if(n===null)return!1;let i=await this.getMeta(t,r);return i?!(0,V0.deepEqual)(i.snapshot,n):!0}async diff(t,r){let n=await this.workspace.readArtifact(t,r),i=await this.getMeta(t,r),a;return n===null?a=i?[{pointer:"",type:"removed",oldValue:i.snapshot}]:[]:i?a=(0,V0.deepDiff)(i.snapshot,n):a=[{pointer:"",type:"added",newValue:n}],{artifactType:t,artifactId:r,changes:a}}async checkConflict(t,r,n){let i=await this.getMeta(t,r);return!i||i.etag===null?!1:i.etag!==n}};ji.VersionManager=Nd});var W0=y((Dd,z0)=>{(function(e,t){typeof define=="function"&&define.amd?define([],t):typeof Dd=="object"?z0.exports=t():e.compareVersions=t()})(Dd,function(){var e=/^v?(?:\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+))?(?:-[\da-z\-]+(?:\.[\da-z\-]+)*)?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;function t(a,o){return a.indexOf(o)===-1?a.length:a.indexOf(o)}function r(a){var o=a.replace(/^v/,"").replace(/\+.*$/,""),s=t(o,"-"),l=o.substring(0,s).split(".");return l.push(o.substring(s+1)),l}function n(a){return isNaN(Number(a))?a:Number(a)}function i(a){if(typeof a!="string")throw new TypeError("Invalid argument expected string");if(!e.test(a))throw new Error("Invalid argument not valid semver ('"+a+"' received)")}return function(o,s){[o,s].forEach(i);for(var l=r(o),u=r(s),c=0;c<Math.max(l.length-1,u.length-1);c++){var d=parseInt(l[c]||0,10),p=parseInt(u[c]||0,10);if(d>p)return 1;if(p>d)return-1}var f=l[l.length-1],m=u[u.length-1];if(f&&m){var h=f.split(".").map(n),v=m.split(".").map(n);for(c=0;c<Math.max(h.length,v.length);c++){if(h[c]===void 0||typeof v[c]=="string"&&typeof h[c]=="number")return-1;if(v[c]===void 0||typeof h[c]=="string"&&typeof v[c]=="number"||h[c]>v[c])return 1;if(v[c]>h[c])return-1}}else if(f||m)return f?-1:1;return 0}})});var Q0=y(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.EnvironmentFlowHostingType=Te.EnvironmentDisableReasonCode=Te.EnvironmentMigrationConstants=Te.EnvironmentProvisioningStates=Te.EnvironmentLocations=Te.EnvironmentCreationTypeConstants=Te.EnvironmentType=Te.EnvironmentSkuConstants=Te.environmentPermissions=Te.DatabaseType=void 0;var j0;(function(e){e.CommonDataService="CommonDataService",e.None="None"})(j0||(Te.DatabaseType=j0={}));Te.environmentPermissions={CreatePowerApp:"CreatePowerApp",ReadEnvironment:"ReadEnvironment",GenerateResourceStorage:"GenerateResourceStorage",CreateGateway:"CreateGateway",CreateFlow:"CreateFlow",CreateCustomApi:"CreateCustomApi",AdminReadEnvironment:"AdminReadEnvironment",UpdateEnvironment:"UpdateEnvironment",DeleteEnvironment:"DeleteEnvironment",ExportEnvironmentPackage:"ExportEnvironmentPackage",SetDLPPolicy:"SetDLPPolicy",ListAnyPowerApp:"ListAnyPowerApp",ListAnyFlow:"ListAnyFlow",DeleteAnyPowerApp:"DeleteAnyPowerApp",DeleteAnyFlow:"DeleteAnyFlow",AddEnvironmentRoleAssignment:"AddEnvironmentRoleAssignment",ReadEnvironmentRoleInformation:"ReadEnvironmentRoleInformation",RemoveEnvironmentRoleAssignment:"RemoveEnvironmentRoleAssignment",ModifyDatabaseRoleAssignments:"ModifyDatabaseRoleAssignments",CreateDatabase:"CreateDatabase",ListDatabaseEntities:"ListDatabaseEntities",CreateDatabaseEntities:"CreateDatabaseEntities",UpdateDatabaseEntities:"UpdateDatabaseEntities",DeleteDatabaseEntities:"DeleteDatabaseEntities"};Te.EnvironmentSkuConstants={NotSpecified:"NotSpecified",Standard:"Standard",Premium:"Premium",Developer:"Developer",Basic:"Basic",Production:"Production",Sandbox:"Sandbox",Trial:"Trial",Default:"Default",Teams:"Teams",Platform:"Platform"};var H0;(function(e){e[e.CDS2=0]="CDS2",e[e.CDS1=1]="CDS1",e[e.Empty=2]="Empty"})(H0||(Te.EnvironmentType=H0={}));Te.EnvironmentCreationTypeConstants={NotSpecified:"NotSpecified",Legacy:"Legacy",DefaultTenant:"DefaultTenant",User:"User",CommonDataModelLegacy:"CommonDataModelLegacy"};Te.EnvironmentLocations={global:"global",unitedStates:"unitedstates",southamerica:"southamerica",europe:"europe",canada:"canada",preview:"unitedstatesfirstrelease",asia:"asia",japan:"japan",australia:"australia",india:"india",unitedkingdom:"unitedkingdom",france:"france",germany:"germany",brazil:"brazil",usgov:"usgov",usgovhigh:"usgovhigh",uae:"unitedarabemirates",switzerland:"switzerland",mooncake:"china",korea:"korea",norway:"norway",southafrica:"southafrica",dod:"usdod",singapore:"singapore",sweden:"sweden",italy:"italy",poland:"poland"};Te.EnvironmentProvisioningStates={NotSpecified:"NotSpecified",Succeeded:"Succeeded",Deleting:"Deleting",Deleted:"Deleted",FailedDeleting:"FailedDeleting",LinkedDatabaseProvisioning:"LinkedDatabaseProvisioning",LinkedDatabaseFailedProvisioning:"LinkedDatabaseFailedProvisioning",LinkedDatabaseFailedConfiguring:"LinkedDatabaseFailedConfiguring",LinkedDatabaseUnavailable:"LinkedDatabaseUnavailable",Creating:"Creating"};Te.EnvironmentMigrationConstants={phases:{completed:"Completed"}};var J0;(function(e){e.NotSpecified="NotSpecified",e.NoValidLicense="NoValidLicense",e.SuspendedLicense="SuspendedLicense",e.TrialExpiration="TrialExpiration",e.UserRequested="UserRequested",e.InstanceStateUpdate="InstanceStateUpdated",e.InactivityThreshold="InactivityThreshold",e.OperationsInitiated="OperationsInitiated",e.EnvironmentLifecycleOperation="EnvironmentLifecycleOperation",e.TenantPolicyEvaluation="TenantPolicyEvaluation"})(J0||(Te.EnvironmentDisableReasonCode=J0={}));var K0;(function(e){e.LogicApps="LogicApps",e.SelfHostSingleTenant="SelfHostSingleTenant",e.SelfHostMultiTenant="SelfHostMultiTenant"})(K0||(Te.EnvironmentFlowHostingType=K0={}))});var iv=y(S=>{"use strict";var l1=S&&S.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(S,"__esModule",{value:!0});S.hasCommonDataServiceDatabase=S.getEnvironmentDiscoveryUrl=S.getEnvironmentWebApiUrl=S.getEnvironmentInstanceApiUrl=S.getEnvironmentLanguageCode=S.getEnvironmentUpdateCadence=S.checkVersions=S.isCds2EnvironmentVersionAtLeast=S.getSecurityOrConnectedGroupId=S.hasSecurityGroupId=S.doesCds2VersionSupportApiVersion9_1=S.doesCds2EnvironmentSupportApiVersion9_1=S.cdsVersionSupportingOSColorEdit=S.getEnvironmentDisplayName=S.getEnvironmentName=S.isEnvironmentInFirstReleaseCluster=S.isEnvironmentInPreprodCluster=S.isEnvironmentInTestCluster=S.isLiteEnvironmentUpgrading=S.isEnvironmentExpired=S.isEnvironmentInDeletedState=S.isEnvironmentInCreatingState=S.isDatabaseInProvisioningState=S.canUserCreateDatabase=S.isDisabledEnvironment=S.isDefaultEnvironment=S.isTrialEnvironment=S.isPlatformEnvironment=S.isTeamsEnvironment=S.isSandboxEnvironment=S.isProdEnvironment=S.isDevEnvironment=S.getEnvironmentType=S.getCrmInstanceName=S.getCrmInstanceUrl=S.getCrmAppDesignerUrl=S.getDevResourcesUrl=S.isEnvironmentInSuccessfulState=S.getAllThemesUrl=S.getAllPublishersUrl=S.getAllSolutionsUrl=S.getSecurityRolesUrl=S.getSecurityUsersUrl=S.environmentHasCds2Database=S.DEFAULT_SOLUTION_UNIQUE_NAME=S.DEFAULT_SOLUTION_ID=S.crmBapSolutionId=S.doesUserHavePermission=S.getLinkedEnvironmentMetadata=S.getCrmVersion=void 0;S.doesUserHaveFlowRunOnlyPermission=S.isUserPautoMakerWithoutDataAccess=S.isUserPautoMakerWithDataAccess=S.doesUserHaveCreateFlowPermission=S.equalsIgnoreCase=S.doesUserHaveCreateDatabasePermission=S.doesUserHaveDatabaseTablePermissions=S.isUserMakerWithoutDataAccess=S.isUserMakerWithDataAccess=S.doesUserHaveCreateAppPermission=S.doesUserHaveAdminPermission=void 0;var u1=l1(W0()),fe=Q0(),vo=_d();function c1(e){let t=rn(e);return t&&t.version}S.getCrmVersion=c1;function rn(e){return e&&e.properties&&e.properties.linkedEnvironmentMetadata}S.getLinkedEnvironmentMetadata=rn;function tn(e,t){return e?!!e[t]:!1}S.doesUserHavePermission=tn;S.crmBapSolutionId="00000001-0000-0000-0001-00000000009b";S.DEFAULT_SOLUTION_ID="fd140aaf-4df4-11dd-bd17-0019b9312238";S.DEFAULT_SOLUTION_UNIQUE_NAME="Default";function li(e){return!!rn(e)&&X0(e)}S.environmentHasCds2Database=li;function d1(e){if(e&&li(e)){let t=xn(e);return(0,vo.getCrmAdminSecurityRolesUrl)(t)}return""}S.getSecurityUsersUrl=d1;function p1(e){if(e&&li(e)){let t=xn(e);return(0,vo.getCrmAdminSecurityUsersUrl)(t)}return""}S.getSecurityRolesUrl=p1;function f1(e){if(e&&li(e)){let t=xn(e);(0,vo.getCrmAllSolutionsUrl)(t)}return""}S.getAllSolutionsUrl=f1;function m1(e){if(e&&li(e)){let t=xn(e);return(0,vo.getCrmAllPublishersUrl)(t)}return""}S.getAllPublishersUrl=m1;function h1(e){return e&&li(e)?xn(e):""}S.getAllThemesUrl=h1;function X0(e){return!!e&&e.properties&&!!e.properties.provisioningState&&e.properties.provisioningState.toUpperCase()===fe.EnvironmentProvisioningStates.Succeeded.toUpperCase()}S.isEnvironmentInSuccessfulState=X0;function g1(e){if(e&&li(e)){let t=xn(e);return(0,vo.getCrmDevResourcesUrl)(t)}return""}S.getDevResourcesUrl=g1;function v1(e){return`${e}designer/app/{${S.crmBapSolutionId}}/CreateNewApp}}`}S.getCrmAppDesignerUrl=v1;function xn(e){let t=rn(e);if(t){let r=t.instanceUrl;return r?r.endsWith("/")?r:r+"/":""}return""}S.getCrmInstanceUrl=xn;function y1(e){let t=rn(e);return t?t.uniqueName:""}S.getCrmInstanceName=y1;function b1(e){return rn(e)?fe.EnvironmentType.CDS2:e&&e.properties&&e.properties.namespace?fe.EnvironmentType.CDS1:fe.EnvironmentType.Empty}S.getEnvironmentType=b1;function w1(e){return e&&e.properties&&e.properties.environmentSku===fe.EnvironmentSkuConstants.Developer}S.isDevEnvironment=w1;function A1(e){return e&&e.properties&&e.properties.environmentSku===fe.EnvironmentSkuConstants.Production}S.isProdEnvironment=A1;function C1(e){return e&&e.properties&&e.properties.environmentSku===fe.EnvironmentSkuConstants.Sandbox}S.isSandboxEnvironment=C1;function yo(e){return e&&e.properties&&e.properties.environmentSku===fe.EnvironmentSkuConstants.Teams}S.isTeamsEnvironment=yo;function E1(e){return e&&e.properties&&e.properties.environmentSku===fe.EnvironmentSkuConstants.Platform}S.isPlatformEnvironment=E1;var S1=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.environmentSku)===fe.EnvironmentSkuConstants.Trial};S.isTrialEnvironment=S1;function N1(e){return e&&e.properties&&(e.properties.isDefault||e.properties.creationType===fe.EnvironmentCreationTypeConstants.DefaultTenant)}S.isDefaultEnvironment=N1;function D1(e){return e&&e.properties&&!!e.properties.states&&!!e.properties.states.runtime&&e.properties.states.runtime.id==="Disabled"}S.isDisabledEnvironment=D1;function I1(e){return e&&e.properties&&tn(e.properties.permissions,fe.environmentPermissions.CreateDatabase)}S.canUserCreateDatabase=I1;function _1(e){return!!(e&&e.properties&&e.properties.provisioningState&&nv(e.properties.provisioningState,fe.EnvironmentProvisioningStates.LinkedDatabaseProvisioning))}S.isDatabaseInProvisioningState=_1;function T1(e){return!!e&&!!e.properties&&e.properties.provisioningState===fe.EnvironmentProvisioningStates.Creating}S.isEnvironmentInCreatingState=T1;function P1(e){return e&&e.properties&&(e.properties.provisioningState===fe.EnvironmentProvisioningStates.Deleted||e.properties.provisioningState===fe.EnvironmentProvisioningStates.Deleting||e.properties.provisioningState===fe.EnvironmentProvisioningStates.FailedDeleting)}S.isEnvironmentInDeletedState=P1;function R1(e){return!!e&&!!e.properties&&!!e.properties.expirationTime&&Date.parse(e.properties.expirationTime)<Date.now()}S.isEnvironmentExpired=R1;function O1(e){return!!e&&!!e.properties&&!!e.properties.linkedEnvironmentMetadata&&e.properties.linkedEnvironmentMetadata.platformSku==="Lite"&&!!e.properties.states&&!!e.properties.states.management&&e.properties.states.management.id==="Running"&&!!e.properties.ongoingOperation&&!!e.properties.ongoingOperation.type&&e.properties.ongoingOperation.type.id==="Promote"}S.isLiteEnvironmentUpgrading=O1;function x1(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Test"}S.isEnvironmentInTestCluster=x1;function L1(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Preprod"}S.isEnvironmentInPreprodCluster=L1;function F1(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="FirstRelease"}S.isEnvironmentInFirstReleaseCluster=F1;function k1(e){return e&&e.name||""}S.getEnvironmentName=k1;function M1(e){return e&&e.properties&&e.properties.displayName||""}S.getEnvironmentDisplayName=M1;var Y0="9.1.0.8202";S.cdsVersionSupportingOSColorEdit="9.1.0000.20708";function B1(e){return tv(e,Y0)}S.doesCds2EnvironmentSupportApiVersion9_1=B1;function U1(e){return Id(e,Y0)}S.doesCds2VersionSupportApiVersion9_1=U1;function Z0(e){let t=rn(e);if(t)return t.securityGroupId}function ev(e){return e&&e.properties&&e.properties.connectedGroups}function $1(e,t){let r=ev(e);return!!r&&!!r.find(n=>n.id===t)||Z0(e)===t}S.hasSecurityGroupId=$1;function q1(e){let t=ev(e);return t&&t.length>0&&t[0].id?t[0].id:Z0(e)}S.getSecurityOrConnectedGroupId=q1;function tv(e,t){let r=e.version;return r?Id(r,t):!1}S.isCds2EnvironmentVersionAtLeast=tv;function Id(e,t){return t?e?(0,u1.default)(e,t)>=0:!1:!0}S.checkVersions=Id;function V1(e){return e&&e.properties&&e.properties.updateCadence&&e.properties.updateCadence.id||"NotSpecified"}S.getEnvironmentUpdateCadence=V1;function G1(e){let t=rn(e);return t?Number(t.baseLanguage):0}S.getEnvironmentLanguageCode=G1;function rv(e){let t=rn(e);return t?t.instanceApiUrl:void 0}S.getEnvironmentInstanceApiUrl=rv;function z1(e){let t=rv(e);return t?t+"/api/data/v9.2":""}S.getEnvironmentWebApiUrl=z1;function W1(e){let t=xn(e);if(t==="")return"";let r=t.split("/");if(r.length!==4)return"";let n=r[2].split(".");return n[0]="globaldisco",r[2]=n.join("."),r.join("/")+"api/discovery/v2.0/Instances"}S.getEnvironmentDiscoveryUrl=W1;var j1=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.databaseType)===fe.DatabaseType.CommonDataService};S.hasCommonDataServiceDatabase=j1;var H1=e=>{var t;return tn((t=e.properties)===null||t===void 0?void 0:t.permissions,fe.environmentPermissions.AdminReadEnvironment)};S.doesUserHaveAdminPermission=H1;var J1=e=>{var t;return tn((t=e.properties)===null||t===void 0?void 0:t.permissions,fe.environmentPermissions.CreatePowerApp)};S.doesUserHaveCreateAppPermission=J1;var K1=e=>(0,S.doesUserHaveAdminPermission)(e)&&(0,S.hasCommonDataServiceDatabase)(e)?!0:(0,S.doesUserHaveCreateAppPermission)(e)?yo(e)||(0,S.doesUserHaveDatabaseTablePermissions)(e):!1;S.isUserMakerWithDataAccess=K1;var Q1=e=>(0,S.doesUserHaveCreateAppPermission)(e)&&!yo(e)&&!(0,S.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,S.doesUserHaveAdminPermission)(e)||!(0,S.hasCommonDataServiceDatabase)(e));S.isUserMakerWithoutDataAccess=Q1;var X1=e=>[fe.environmentPermissions.CreateDatabaseEntities,fe.environmentPermissions.ListDatabaseEntities,fe.environmentPermissions.UpdateDatabaseEntities,fe.environmentPermissions.DeleteDatabaseEntities].every(t=>{var r;return tn((r=e.properties)===null||r===void 0?void 0:r.permissions,t)});S.doesUserHaveDatabaseTablePermissions=X1;var Y1=e=>{var t;return tn((t=e.properties)===null||t===void 0?void 0:t.permissions,fe.environmentPermissions.CreateDatabase)};S.doesUserHaveCreateDatabasePermission=Y1;function nv(e,t){return!e&&!t?!0:!e||!t?!1:e.toUpperCase()===t.toUpperCase()}S.equalsIgnoreCase=nv;var Z1=e=>{var t;return tn((t=e.properties)===null||t===void 0?void 0:t.permissions,fe.environmentPermissions.CreateFlow)};S.doesUserHaveCreateFlowPermission=Z1;var ex=e=>(0,S.doesUserHaveAdminPermission)(e)&&(0,S.hasCommonDataServiceDatabase)(e)?!0:(0,S.doesUserHaveCreateFlowPermission)(e)?yo(e)||(0,S.doesUserHaveDatabaseTablePermissions)(e):!1;S.isUserPautoMakerWithDataAccess=ex;var tx=e=>(0,S.doesUserHaveCreateFlowPermission)(e)&&!yo(e)&&!(0,S.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,S.doesUserHaveAdminPermission)(e)||!(0,S.hasCommonDataServiceDatabase)(e));S.isUserPautoMakerWithoutDataAccess=tx;var rx=e=>{var t,r;return!tn((t=e.properties)===null||t===void 0?void 0:t.permissions,fe.environmentPermissions.CreateFlow)&&tn((r=e.properties)===null||r===void 0?void 0:r.permissions,fe.environmentPermissions.ReadEnvironment)};S.doesUserHaveFlowRunOnlyPermission=rx});var _d=y(A=>{"use strict";Object.defineProperty(A,"__esModule",{value:!0});A.getRequiredComponentsQueryUrl=A.solutionComponentCountSummariesQueryUrl=A.solutionComponentSummariesQueryUrl=A.solutionComponentConfigurationsQueryUrl=A.chartsQueryUrl=A.workflowsQueryUrl=A.entityDefinitionsQueryUrl=A.solutionComponentDefinitionsQueryUrl=A.getCreateNewArticleTemplateUrl=A.getCreateNewPublisherUrl=A.getEnableSecurityRolesUrl=A.getArticleTemplateUrl=A.getFieldSecurityProfileDesignerUrl=A.getSecurityRoleDesignerUrl=A.getMailMergeTemplateDesignerUrl=A.getEmailTemplateDesignerUrl=A.getConnectionRoleDesignerUrl=A.getSiteMapDesignerUrl=A.getWebResourceFileUrl=A.getWebResourceDesignerUrl=A.getReportDesignerUrl=A.getBusinessProcessFlowDesignerUrl=A.getProcessShareUrl=A.getProcessDesignerUrl=A.getChartDesignerUrl=A.getOpenModernEntityDashboardUrl=A.getNewModernEntityDashboardUrl=A.getNewModernDashboardUrl=A.getOpenModernDashboardUrl=A.getDashboardDesignerUrl=A.getAppModuleDesignerUrl=A.privilegesQueryUrls=A.xrmApiUrl=A.getPlayAppModuleUrl=A.getCrmAdminSecurityUsersUrl=A.getCrmAdminSecurityRolesUrl=A.getCrmMyAppsUrl=A.getCrmAppDesignerUrl=A.getCrmDevResourcesUrl=A.getCrmAllPublishersUrl=A.getCrmAllSolutionsUrl=A.getSolutionPublisherUrl=A.getExportTranslationFileName=A.getExportSolutionTranslationUrl=A.getImportSolutionTranslationUrl=A.getShowSolutionDependenciesUrl=A.getShowComponentDependenciesUrl=A.cdsServiceUrl=A.ODATA_NEXT_LINK=A.ODATA_MAX_PAGE_SIZE=void 0;A.retrieveOrganizationResources=A.getUCIEntityRecordEditUrl=A.getUCIEntityRecordBaseUrl=A.getBusinessRuleDesignerUri=A.retrieveUnpublishedSuffix=A.getSavePowerSettingUri=A.getPowerSettingUri=A.getPowerSettingsUri=A.RetrievePlatform=A.getAppSettingOverrideUri=A.AppSettingOverrideName=A.getOrgSettingOverrideUri=A.OrgSettingOverrideName=A.getSettingDefinitionsUri=A.retrieveFeatureControlSettingsByNamespaceUrl=A.retrieveDeploymentPipelineConfigAppUrl=A.SPNPrincipalIdUrl=A.retrieveDeploymentEnvironmentInfoUrl=A.devSolutionInfoUrl=A.deployOperationStatusUrl=A.getAIGeneratedDeploymentNotesUrl=A.deploymentStageRunUrl=A.validatePackageAsyncUrl=A.deployPackageAsyncUrl=A.updateDeploymentStageRunUrl=A.createDeploymentStageRunUrl=A.retrieveDeploymentStagesUrl=A.retrievePipelinesUrl=A.retrieveDeploymentPipelineInfoUrl=A.getDeploymentStageRunsUrl=A.appDeploymentUrls=A.getProvisionLanguageUrl=A.getSolutionQueryUrl=A.getSolutionsByUniqueNameQueryUrl=A.solutionsQueryUrl=A.getDependentComponentsWithMetadataQueryUrl=void 0;var av=iv();A.ODATA_MAX_PAGE_SIZE="odata.maxpagesize";A.ODATA_NEXT_LINK="@odata.nextLink";A.cdsServiceUrl="https://cds-org/";var wo;(function(e){e.AllSolutions="11",e.AllPublishers="10",e.DevResources="05"})(wo||(wo={}));function nx(e,t,r,n){return`${e}tools/dependency/dependencyviewdialog.aspx?appSolutionId=%7b${t}%7d&dType=1&objectid=%7b${r}%7d&objecttype=${n}&operationtype=showdependency`}A.getShowComponentDependenciesUrl=nx;function ix(e,t){let r=`dType=1&isproactivecheck=true&objecttype=7100&operationtype=dependenciesforuninstall&objectid=${t}`;return`${e}tools/dependency/dependencyviewdialog.aspx?${r}`}A.getShowSolutionDependenciesUrl=ix;function ax(e,t){return`${e}tools/muiProvisioning/Dialogs/LangTranslationsImport.aspx?dType=1&appSolutionId=${t}`}A.getImportSolutionTranslationUrl=ax;function ox(e,t){return`${e}_grid/cmds/dlg_exportsolution.aspx?command=exporttranslation&appSolutionId=${t}`}A.getExportSolutionTranslationUrl=ox;function sx(e,t){return e!==void 0&&t!==void 0&&`CrmTranslations_${e}_${t.replace(/[.]/g,"_")}.zip`||""}A.getExportTranslationFileName=sx;function lx(e,t,r){return r?`${e}tools/publisher/edit.aspx?appSolutionId=%7b${r}%7d&id=%7b${t}%7d`:`${e}tools/publisher/edit.aspx?id=%7b${t}%7d`}A.getSolutionPublisherUrl=lx;function Td(e,t){return`${e}tools/systemcustomization/systemCustomization.aspx?pid=${t}`}function ux(e){return Td(e,wo.AllSolutions)}A.getCrmAllSolutionsUrl=ux;function cx(e){return Td(e,wo.AllPublishers)}A.getCrmAllPublishersUrl=cx;function dx(e){return Td(e,wo.DevResources)}A.getCrmDevResourcesUrl=dx;function px(e,t=av.crmBapSolutionId){return`${e}designer/app/${t}#/CreateNewApp`}A.getCrmAppDesignerUrl=px;function fx(e){return`${e}apps`}A.getCrmMyAppsUrl=fx;function mx(e){return ov(e,"role")+"&forceUCI=0"}A.getCrmAdminSecurityRolesUrl=mx;function hx(e){return`${ov(e,"systemuser")}&forceclassic=1`}A.getCrmAdminSecurityUsersUrl=hx;function ov(e,t){return`${e}main.aspx?pagetype=entitylist&etn=${t}`}function gx(e,t){return`${e}main.aspx?appid=${t}`}A.getPlayAppModuleUrl=gx;A.xrmApiUrl="api/data/v9.0";A.privilegesQueryUrls={systemUserInfo:e=>`${e}${A.xrmApiUrl}/WhoAmI`,userPrivileges:(e,t)=>`${e}${A.xrmApiUrl}/systemusers(${t})/Microsoft.Dynamics.CRM.RetrieveUserPrivileges`,systemPrivileges:e=>`${e}${A.xrmApiUrl}/privileges/Microsoft.Dynamics.CRM.RetrievePrivilegeSet`};function vx(e,t,r=av.crmBapSolutionId){return`${e}designer/app/${r}/${t}/AppDesignerCanvas/${t}`}A.getAppModuleDesignerUrl=vx;function yx(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${r}%7d&extraqs=%26formId%3d%7b${t}%7d%26dashboardType%3d1030&pagetype=${`${n?"ic":""}dashboardeditor`}`}A.getDashboardDesignerUrl=yx;function bx(e,t,r){return`/e/${e}/s/${t}/dashboard/${r}`}A.getOpenModernDashboardUrl=bx;function wx(e,t,r){let n=r!==void 0?r.toString():void 0;return`/e/${e}/s/${t}/dashboard/new${n?`/${n}`:""}`}A.getNewModernDashboardUrl=wx;function Ax(e,t,r,n){let i=n!==void 0?n.toString():void 0;return`/e/${e}/s/${t}/n/${r}/dashboard/new${i?`/${i}`:""}`}A.getNewModernEntityDashboardUrl=Ax;function Cx(e,t,r,n){return`/e/${e}/s/${t}/n/${r}/dashboard/${n}`}A.getOpenModernEntityDashboardUrl=Cx;function Ex(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${t}%7d&extraqs=etc=${r||""}`+(n?`%26id=${n}`:"")+"&pagetype=vizdesigner"}A.getChartDesignerUrl=Ex;function Sx(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getProcessDesignerUrl=Sx;function Nx(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getProcessShareUrl=Nx;function Dx(e,t){return`${e}Tools/ProcessControl/UnifiedProcessDesigner.aspx?id=${t}`}A.getBusinessProcessFlowDesignerUrl=Dx;function Ix(e,t,r){return`${e}CRMReports/reportproperty.aspx?appSolutionId=%7b${r}%7d&disablePersonal=true&id=%7b${t}%7d`}A.getReportDesignerUrl=Ix;function _x(e,t,r){return`${e}main.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&etc=9333&id=%7b${t}%7d&pagetype=webresourceedit`}A.getWebResourceDesignerUrl=_x;function Tx(e,t){return`${e}WebResources/${t}`}A.getWebResourceFileUrl=Tx;function Px(e,t,r){return`${e}designer/sitemap/${r}/${t}/SiteMapHome/${t}`}A.getSiteMapDesignerUrl=Px;function Rx(e,t,r){return`${e}connections/connectionroles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getConnectionRoleDesignerUrl=Rx;function Ox(e,t,r){return`${e}tools/emailtemplateeditor/emailtemplateeditor.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getEmailTemplateDesignerUrl=Ox;function xx(e,t,r){return`${e}tools/mailmerge/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getMailMergeTemplateDesignerUrl=xx;function Lx(e,t,r){return`${e}biz/roles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getSecurityRoleDesignerUrl=Lx;function Fx(e,t,r){return`${e}biz/fieldsecurityprofiles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getFieldSecurityProfileDesignerUrl=Fx;function kx(e,t,r){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?_CreateFromId=%7b${t}%7d&_CreateFromType=7100&appSolutionId=%7b${t}%7d&id=%7b${r}%7d`}A.getArticleTemplateUrl=kx;function Mx(e,t,r,n){return`${e}tools/FormEditor/Dialogs/FormRoleAssignment.aspx?appSolutionId=%7b${t}%7d&dType=1&formId=%7b${r}%7d&objectTypeCode=0&type=${n}`}A.getEnableSecurityRolesUrl=Mx;function Bx(e){return`${e}tools/publisher/edit.aspx`}A.getCreateNewPublisherUrl=Bx;function Ux(e,t){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?appSolutionId=${t}`}A.getCreateNewArticleTemplateUrl=Ux;A.solutionComponentDefinitionsQueryUrl="api/data/v9.0/solutioncomponentdefinitions";A.entityDefinitionsQueryUrl="api/data/v9.0/EntityDefinitions?$select=EntitySetName,DisplayName,LogicalName&$filter=";A.workflowsQueryUrl="api/data/v9.0/workflows";A.chartsQueryUrl="/api/data/v9.0/savedqueryvisualizations";A.solutionComponentConfigurationsQueryUrl="/api/data/v9.1/solutioncomponentconfigurations?$filter=isdisplayable eq true&$select=name";A.solutionComponentSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentsummaries";A.solutionComponentCountSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentcountsummaries";function $x(e,t){return`${A.xrmApiUrl}/RetrieveRequiredComponents(ObjectId=${e},ComponentType=${t})`}A.getRequiredComponentsQueryUrl=$x;function qx(e,t){return`${A.cdsServiceUrl}${A.xrmApiUrl}/RetrieveDependentComponentsWithMetadata(ObjectId=${e},ComponentType=${t})`}A.getDependentComponentsWithMetadataQueryUrl=qx;A.solutionsQueryUrl="/api/data/v9.0/solutions?$expand=publisherid&$filter=(isvisible eq true)";function Vx(e){return`/api/data/v9.0/solutions?$expand=publisherid&$filter=(uniquename eq '${e}')`}A.getSolutionsByUniqueNameQueryUrl=Vx;function Gx(e){return`/api/data/v9.0/solutions(${e})?$expand=publisherid`}A.getSolutionQueryUrl=Gx;function zx(e){return`${e}api/data/v9.1/ProvisionLanguageForUser`}A.getProvisionLanguageUrl=zx;A.appDeploymentUrls={associateEnvironmentToPipelineUrl:e=>`/api/data/v9.0/deploymentpipelines(${e})/deploymentpipeline_deploymentenvironment/$ref`,deploymentArtifactsUrl:"/api/data/v9.0/deploymentartifacts",deploymentEnvironmentUrl:"/api/data/v9.0/deploymentenvironments",deploymentPipelinesUrl:"/api/data/v9.0/deploymentpipelines",deploymentStagesUrl:"/api/data/v9.0/deploymentstages",retrieveDeploymentPipelinesUrl:e=>`/api/data/v9.0/RetrieveDeploymentPipelines(SourceEnvironmentId='${e}')`,deletePipelinesUrl:e=>`/api/data/v9.0/deploymentpipelines(${e})`};function Wx(e,t,r,n=!1,i=!1,a=!1,o=!1,s=!1,l=!1,u=!1){return`/api/data/v9.1/deploymentstageruns?$select=artifactname,artifactversion,deploymentstagerunid,devenvironmentid,endtime,errormessage,${s?"_artifactid_value,isredeployment,":""}${n?"deploymentnotes,":""}operation,operationdetails,operationstatus,${l?"retrycount,":""}${i?"scheduledtime,":""}${u?"solutionid,":""}stagerunstatus,starttime,suboperation,targetenvironmentid,${a?"predeploymentstepnotes,":""}validationresults,${o?"approvalcomments,":""}_devdeploymentenvironment_value,_targetdeploymentenvironment_value&$expand=deploymentstageid($select=deploymentstageid,name,_deploymentpipelineid_value),targetdeploymentenvironment($select=deploymentenvironmentid,environmentid,name),createdby($select=azureactivedirectoryobjectid,fullname,ownerid,systemuserid)${l?",RetryUser($select=azureactivedirectoryobjectid,fullname,ownerid,systemuserid)":""}&$filter=deploymentstageid/_deploymentpipelineid_value eq ${e} and devenvironmentid eq '${t}' and artifactname eq '${r}' and ((operation ne 200000201) or (operation eq 200000201 and operationstatus eq 200000003))- &$orderby=starttime desc`}w.getDeploymentStageRunsUrl=ZO;function eR(e,t,r){return`/api/data/v9.1/RetrieveDeploymentPipelineInfo(DeploymentPipelineId=${e},SourceEnvironmentId='${t}',ArtifactName='${r}')`}w.retrieveDeploymentPipelineInfoUrl=eR;function tR(e){return`/api/data/v9.0/deploymentenvironments+ &$orderby=starttime desc`}A.getDeploymentStageRunsUrl=Wx;function jx(e,t,r){return`/api/data/v9.1/RetrieveDeploymentPipelineInfo(DeploymentPipelineId=${e},SourceEnvironmentId='${t}',ArtifactName='${r}')`}A.retrieveDeploymentPipelineInfoUrl=jx;function Hx(e){return`/api/data/v9.0/deploymentenvironments?$select=deploymentenvironmentid,environmentid,environmenttype,name&$expand=deploymentpipeline_deploymentenvironment($select=name,description,deploymentpipelineid;$orderby=name asc)- &$filter=(environmentid eq '${e}')`}w.retrievePipelinesUrl=tR;function rR(e){return`/api/data/v9.0/deploymentstages+ &$filter=(environmentid eq '${e}')`}A.retrievePipelinesUrl=Hx;function Jx(e){return`/api/data/v9.0/deploymentstages?$filter=(_deploymentpipelineid_value eq ${e})&$select=name,description,deploymentstageid,_previousdeploymentstageid_value- &$expand=targetdeploymentenvironmentid($select=deploymentenvironmentid,environmentid,name)`}w.retrieveDeploymentStagesUrl=rR;function nR(){return"/api/data/v9.0/deploymentstageruns?$select=deploymentstagerunid"}w.createDeploymentStageRunUrl=nR;function iR(e){return`/api/data/v9.0/deploymentstageruns(${e})`}w.updateDeploymentStageRunUrl=iR;function aR(){return"/api/data/v9.0/DeployPackageAsync"}w.deployPackageAsyncUrl=aR;function oR(){return"/api/data/v9.0/ValidatePackageAsync"}w.validatePackageAsyncUrl=oR;function sR(e,t=!1,r=!1){return`/api/data/v9.0/deploymentstageruns(${e})- ?$select=deploymentstagerunid,stagerunstatus,errormessage,operation,operationdetails,operationstatus,${t?"scheduledtime,":""}targetenvironmentid,validationresults,artifactname,deploymentsettingsjson${r?"&$expand=createdby($select=azureactivedirectoryobjectid,fullname,ownerid,systemuserid)":""}`}w.deploymentStageRunUrl=sR;function lR(e){return`/api/data/v9.0/deploymentstageruns(${e})- ?$select=aigenerateddeploymentnotes,deploymentstagerunid`}w.getAIGeneratedDeploymentNotesUrl=lR;function uR(e){let t="";for(let r=0;r<e.length;r++)r===e.length-1?t=t.concat(`deploymentstagerunid eq ${e[r]}`):t=t.concat(`deploymentstagerunid eq ${e[r]} or `);return`/api/data/v9.0/deploymentstageruns+ &$expand=targetdeploymentenvironmentid($select=deploymentenvironmentid,environmentid,name)`}A.retrieveDeploymentStagesUrl=Jx;function Kx(){return"/api/data/v9.0/deploymentstageruns?$select=deploymentstagerunid"}A.createDeploymentStageRunUrl=Kx;function Qx(e){return`/api/data/v9.0/deploymentstageruns(${e})`}A.updateDeploymentStageRunUrl=Qx;function Xx(){return"/api/data/v9.0/DeployPackageAsync"}A.deployPackageAsyncUrl=Xx;function Yx(){return"/api/data/v9.0/ValidatePackageAsync"}A.validatePackageAsyncUrl=Yx;function Zx(e,t=!1,r=!1){return`/api/data/v9.0/deploymentstageruns(${e})+ ?$select=deploymentstagerunid,stagerunstatus,errormessage,operation,operationdetails,operationstatus,${t?"scheduledtime,":""}targetenvironmentid,validationresults,artifactname,deploymentsettingsjson${r?"&$expand=createdby($select=azureactivedirectoryobjectid,fullname,ownerid,systemuserid)":""}`}A.deploymentStageRunUrl=Zx;function eL(e){return`/api/data/v9.0/deploymentstageruns(${e})+ ?$select=aigenerateddeploymentnotes,deploymentstagerunid`}A.getAIGeneratedDeploymentNotesUrl=eL;function tL(e){let t="";for(let r=0;r<e.length;r++)r===e.length-1?t=t.concat(`deploymentstagerunid eq ${e[r]}`):t=t.concat(`deploymentstagerunid eq ${e[r]} or `);return`/api/data/v9.0/deploymentstageruns?$filter=(${t})- &$select=_deploymentstageid_value,deploymentstagerunid,stagerunstatus,operation,operationstatus,suboperation,artifactname`}w.deployOperationStatusUrl=uR;function cR(e){return`/api/data/v9.0/solutions(${e})- ?$select=solutionid,uniquename,version`}w.devSolutionInfoUrl=cR;function dR(e){return`/api/data/v9.0/deploymentenvironments+ &$select=_deploymentstageid_value,deploymentstagerunid,stagerunstatus,operation,operationstatus,suboperation,artifactname`}A.deployOperationStatusUrl=tL;function rL(e){return`/api/data/v9.0/solutions(${e})+ ?$select=solutionid,uniquename,version`}A.devSolutionInfoUrl=rL;function nL(e){return`/api/data/v9.0/deploymentenvironments?$select=deploymentenvironmentid,environmentid,environmenttype,name- &$filter=(environmentid eq '${e}')`}w.retrieveDeploymentEnvironmentInfoUrl=dR;var pR=e=>`/api/data/v9.0/systemusers+ &$filter=(environmentid eq '${e}')`}A.retrieveDeploymentEnvironmentInfoUrl=nL;var iL=e=>`/api/data/v9.0/systemusers?$select=azureactivedirectoryobjectid- &$filter=(applicationid eq '${e}')`;w.SPNPrincipalIdUrl=pR;function fR(){return"/api/data/v9.0/appmodules?$filter=(uniquename eq 'AppDeploymentConfiguration')"}w.retrieveDeploymentPipelineConfigAppUrl=fR;w.retrieveFeatureControlSettingsByNamespaceUrl="/api/data/v9.1/RetrieveFeatureControlSettingsByNamespace";function mR(e){return`/api/data/v9.0/settingdefinitions${e}`}w.getSettingDefinitionsUri=mR;w.OrgSettingOverrideName="organizationsettings";function hR(e,t=!1){let r=`/api/data/v9.0/${w.OrgSettingOverrideName}${e}`;return t?`${w.cdsServiceUrl}${r}`:r}w.getOrgSettingOverrideUri=hR;w.AppSettingOverrideName="appsettings";function gR(e,t=!1){let r=`/api/data/v9.0/${w.AppSettingOverrideName}${e}`;return t?`${w.cdsServiceUrl.replace("/$","")}${r}`:r}w.getAppSettingOverrideUri=gR;var ro;(function(e){e[e.All=0]="All",e[e.IsPlatformOnly=1]="IsPlatformOnly",e[e.NotPlatformOnly=2]="NotPlatformOnly"})(ro||(w.RetrievePlatform=ro={}));function vR(e,t,r,n=ro.All,i=!1){let a=[];e&&a.push(`AppUniqueName='${e}'`),t!=null&&a.push(`ReleaseLevel=${t}`),r&&a.push(`RetrieveHiddenSettings=${r}`),n!==ro.All&&a.push(`RetrievePlatformSettings=${n===ro.IsPlatformOnly?1:0}`);let o="/api/data/v9.0/RetrieveUnpublishedOverridableSettingsInfo";return a.length&&(o=`${o}(${a.join(",")})`),i?`${w.cdsServiceUrl}${o}`:o}w.getPowerSettingsUri=vR;function yR(e,t,r,n=!1){let i=[`SettingName='${e}'`];t!==void 0&&i.push(`SolutionName='${t}'`),r!==void 0&&i.push(`AppUniqueName='${r}'`);let a="/api/data/v9.0/RetrieveUnpublishedSettingInfo";return i.length&&(a=`${a}(${i.join(",")})`),n?`${w.cdsServiceUrl}${a}`:a}w.getPowerSettingUri=yR;function bR(e=!1){let t="/api/data/v9.0/SaveSettingValue()";return e?`${w.cdsServiceUrl}${t}`:t}w.getSavePowerSettingUri=bR;w.retrieveUnpublishedSuffix="Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()";function wR(e){return`tools/systemcustomization/businessrules/businessRulesDesigner.aspx?BRlaunchpoint=BRGrid&appSolutionId={${e}}`}w.getBusinessRuleDesignerUri=wR;function p0({environmentInstanceUrl:e,entityLogicalName:t}){return e&&t?`${e}main.aspx?cmdbar=true&forceUCI=1&navbar=off&newWindow=true&pageType=entityRecord&etn=${t}`:void 0}w.getUCIEntityRecordBaseUrl=p0;function AR({baseUrl:e,environmentInstanceUrl:t,entityLogicalName:r,recordId:n}){let i=e||p0({environmentInstanceUrl:t,entityLogicalName:r});return i&&n?`${i}&id=${n}`:void 0}w.getUCIEntityRecordEditUrl=AR;w.retrieveOrganizationResources=`${w.cdsServiceUrl}api/data/v9.0/RetrieveOrganizationResources`});var f0=v(Us=>{"use strict";Object.defineProperty(Us,"__esModule",{value:!0});Us.DataverseClient=void 0;var CR=Wc(),ei=te(),jc=class{constructor(t,r,n){this.instanceUrl=t,this.httpClient=r,this.solutionUniqueName=n}withSolution(t){return this.solutionUniqueName?{...t,headers:{...t?.headers,"MSCRM.SolutionUniqueName":this.solutionUniqueName}}:t}apiUrl(t){let r=this.instanceUrl.replace(/\/+$/,""),n=t.startsWith("/")?t:`/${t}`;return`${r}/${CR.xrmApiUrl}${n}`}async send(t,r){try{return await r()}catch(n){throw n instanceof ei.SdkError?n:new ei.ConnectionError(t,0,n instanceof Error?n.message:String(n),n)}}get(t,r){let n=this.apiUrl(t);return this.send(n,()=>this.httpClient.get(n,r))}getAbsolute(t,r){return this.assertSameOrigin(t),this.send(t,()=>this.httpClient.get(t,r))}assertSameOrigin(t){let r,n;try{r=new URL(t),n=new URL(this.instanceUrl)}catch{throw new ei.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${t}'`)}if(r.protocol!==n.protocol||r.host!==n.host)throw new ei.InvalidArgumentError(`Refusing to follow a cross-origin link ('${r.origin}' is not the configured instance '${n.origin}'); server-driven pagination must stay on-instance.`)}post(t,r,n){let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.post(i,r,this.withSolution(n)))}get supportsAtomicBatch(){return typeof this.httpClient.postRaw=="function"}get solutionName(){return this.solutionUniqueName}postBatch(t,r,n){if(!this.httpClient.postRaw)throw new ei.InvalidArgumentError("The injected HttpClient does not implement postRaw(), required for atomic $batch change sets");let i=this.apiUrl("/$batch"),a={...n,headers:{...n?.headers,"Content-Type":`multipart/mixed;boundary=${r}`}};return this.send(i,()=>this.httpClient.postRaw(i,t,a))}patch(t,r,n){let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.patch(i,r,this.withSolution(n)))}get supportsBinaryPatch(){return typeof this.httpClient.patchRaw=="function"}patchRaw(t,r,n){if(!this.httpClient.patchRaw)throw new ei.InvalidArgumentError("The injected HttpClient does not implement patchRaw(), required to upload file content (a Dataverse File column cannot be written through a JSON body)");let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.patchRaw(i,r,this.withSolution(n)))}put(t,r,n){if(!this.httpClient.put)throw new ei.InvalidArgumentError("The injected HttpClient does not implement put(), required for metadata replace operations (e.g. updateColumn)");let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.put(i,r,this.withSolution(n)))}delete(t,r){let n=this.apiUrl(t);return this.send(n,()=>this.httpClient.delete(n,this.withSolution(r)))}};Us.DataverseClient=jc});var m0=v(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.findColumns=Sn.findTables=Sn.fetchEntityMetadataFromApi=void 0;var Jc=be(),Cr=ae();function io(e){var t,r;return(r=(t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)!==null&&r!==void 0?r:""}function Pi(e){let t=e?.LocalizedLabels;if(!Array.isArray(t)||t.length<2)return;let r={};for(let n of t)typeof n?.LanguageCode=="number"&&typeof n.Label=="string"&&(r[n.LanguageCode]=n.Label);return Object.keys(r).length?r:void 0}async function Oi(e,t){var r,n;let i=await e.get(t);return i.status<200||i.status>=300?[]:(n=(r=i.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[]}function En(e){return`/EntityDefinitions(LogicalName='${(0,Cr.odataPathLiteral)(e)}')`}async function ER(e,t,r){let n=await Oi(e,`${En(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata${(0,Cr.odataQuery)([["$select","LogicalName,MaxLength"]])}`);for(let i of n){let a=r.get(i.LogicalName);a&&typeof i.MaxLength=="number"&&(a.maxLength=i.MaxLength)}}async function SR(e,t,r){var n;let i=await Oi(e,`${En(t)}/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata${(0,Cr.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`);for(let a of i){let o=r.get(a.LogicalName);o&&(!((n=a.OptionSet)===null||n===void 0)&&n.Options)&&(o.options=a.OptionSet.Options.map(s=>{var l;return{value:(l=s.Value)!==null&&l!==void 0?l:0,label:io(s.Label),...Pi(s.Label)?{localizedLabel:Pi(s.Label)}:{}}}))}}async function NR(e,t,r){let n=await Oi(e,`${En(t)}/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata${(0,Cr.odataQuery)([["$select","LogicalName,Targets"]])}`);for(let i of n){let a=r.get(i.LogicalName);a&&i.Targets&&(a.targets=i.Targets)}}async function DR(e,t){var r,n,i,a;let o=[],s=await Oi(e,`${En(t)}/OneToManyRelationships${(0,Cr.odataQuery)([["$select","SchemaName,ReferencingEntity,ReferencingAttribute"]])}`);for(let c of s)o.push({schemaName:c.SchemaName,type:"OneToMany",relatedEntity:(r=c.ReferencingEntity)!==null&&r!==void 0?r:"",relatedAttribute:(n=c.ReferencingAttribute)!==null&&n!==void 0?n:""});let l=await Oi(e,`${En(t)}/ManyToOneRelationships${(0,Cr.odataQuery)([["$select","SchemaName,ReferencedEntity,ReferencedAttribute"]])}`);for(let c of l)o.push({schemaName:c.SchemaName,type:"ManyToOne",relatedEntity:(i=c.ReferencedEntity)!==null&&i!==void 0?i:"",relatedAttribute:(a=c.ReferencedAttribute)!==null&&a!==void 0?a:""});let u=await Oi(e,`${En(t)}/ManyToManyRelationships${(0,Cr.odataQuery)([["$select","SchemaName,Entity1LogicalName,Entity2LogicalName"]])}`);for(let c of u){let d=c.Entity1LogicalName===t?c.Entity2LogicalName:c.Entity1LogicalName;o.push({schemaName:c.SchemaName,type:"ManyToMany",relatedEntity:d??"",relatedAttribute:""})}return o}async function IR(e,t){var r,n,i,a,o;let s=`${En(t)}`+(0,Cr.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,EntitySetName,IsCustomEntity,PrimaryNameAttribute,PrimaryIdAttribute"],["$expand","Attributes($select=LogicalName,DisplayName,AttributeType,IsCustomAttribute)"]]),u=(0,Jc.ensureSuccess)(await e.get(s),e.apiUrl(s)).body,c=((r=u.Attributes)!==null&&r!==void 0?r:[]).map(f=>{var m;return{logicalName:f.LogicalName,displayName:io(f.DisplayName),...Pi(f.DisplayName)?{localizedDisplayName:Pi(f.DisplayName)}:{},attributeType:(m=f.AttributeType)!==null&&m!==void 0?m:"Unknown",isCustomAttribute:!!f.IsCustomAttribute}}),d=new Map(c.map(f=>[f.logicalName,f])),[,,,p]=await Promise.all([ER(e,t,d),SR(e,t,d),NR(e,t,d),DR(e,t)]);return{logicalName:u.LogicalName,schemaName:(n=u.SchemaName)!==null&&n!==void 0?n:u.LogicalName,displayName:io(u.DisplayName),...Pi(u.DisplayName)?{localizedDisplayName:Pi(u.DisplayName)}:{},entitySetName:(i=u.EntitySetName)!==null&&i!==void 0?i:"",primaryNameAttribute:(a=u.PrimaryNameAttribute)!==null&&a!==void 0?a:"",primaryIdAttribute:(o=u.PrimaryIdAttribute)!==null&&o!==void 0?o:"",isCustomEntity:!!u.IsCustomEntity,attributes:c,relationships:p}}Sn.fetchEntityMetadataFromApi=IR;async function _R(e,t,r){var n,i;let a=`/EntityDefinitions${(0,Cr.odataQuery)([["$select","LogicalName,SchemaName,EntitySetName,DisplayName,IsCustomEntity"]])}`,s=(i=(n=(0,Jc.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[],l=(t??"").toLowerCase(),u=s.filter(c=>!r?.customOnly||c.IsCustomEntity).map(c=>{var d,p;return{logicalName:c.LogicalName,schemaName:(d=c.SchemaName)!==null&&d!==void 0?d:c.LogicalName,displayName:io(c.DisplayName),entitySetName:(p=c.EntitySetName)!==null&&p!==void 0?p:"",isCustom:!!c.IsCustomEntity}}).filter(c=>c.logicalName.toLowerCase().includes(l)||c.schemaName.toLowerCase().includes(l)||c.displayName.toLowerCase().includes(l));return typeof r?.top=="number"?u.slice(0,r.top):u}Sn.findTables=_R;async function TR(e,t,r,n){var i,a;let o=`${En(t)}/Attributes`+(0,Cr.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute"]]),l=(a=(i=(0,Jc.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||i===void 0?void 0:i.value)!==null&&a!==void 0?a:[],u=(r??"").toLowerCase(),c=l.map(d=>{var p,f;return{logicalName:d.LogicalName,schemaName:(p=d.SchemaName)!==null&&p!==void 0?p:d.LogicalName,displayName:io(d.DisplayName),attributeType:(f=d.AttributeType)!==null&&f!==void 0?f:"Unknown",isCustom:!!d.IsCustomAttribute}}).filter(d=>d.logicalName.toLowerCase().includes(u)||d.schemaName.toLowerCase().includes(u)||d.displayName.toLowerCase().includes(u));return typeof n?.top=="number"?c.slice(0,n.top):c}Sn.findColumns=TR});var Ri=v(Bs=>{"use strict";Object.defineProperty(Bs,"__esModule",{value:!0});Bs.DEFAULT_LCID=void 0;Bs.DEFAULT_LCID=1033});var pt=v(Fi=>{"use strict";Object.defineProperty(Fi,"__esModule",{value:!0});Fi.assignMissingIds=Fi.newId=void 0;function h0(){return globalThis.crypto.randomUUID().toLowerCase()}Fi.newId=h0;function PR(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var OR=new Set(["parameters","bag","expression","rawExpression","lookupValue","stepLabels"]);function RR(e){return Qc(e),e}Fi.assignMissingIds=RR;function Qc(e){if(Array.isArray(e)){e.forEach(t=>Qc(t));return}if(PR(e)){(typeof e.id!="string"||e.id.length===0)&&(e.id=h0());for(let t of Object.keys(e))t==="id"||OR.has(t)||Qc(e[t])}}});var Kc=v(Nn=>{"use strict";Object.defineProperty(Nn,"__esModule",{value:!0});Nn.postChangeSet=Nn.parseChangeSetStatuses=Nn.renderChangeSet=void 0;var $s=te(),FR=be(),g0=pt(),v0=ae();function y0(e,t){let r=`batch_${(0,g0.newId)()}`,n=`changeset_${(0,g0.newId)()}`,i=t.map((s,l)=>String(l+1)),a=t.map((s,l)=>{let u=s.body===void 0?void 0:JSON.stringify(s.body);return(0,v0.assertNoControlChars)(s.path,"batch operation path"),s.etag&&(0,v0.assertNoControlChars)(s.etag,"batch operation etag"),[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${i[l]}`,"",`${s.method} ${e.apiUrl(s.path)} HTTP/1.1`,...u===void 0?[]:["Content-Type: application/json;type=entry"],...e.solutionName?[`MSCRM.SolutionUniqueName: ${e.solutionName}`]:[],...s.etag?[`If-Match: ${s.etag}`]:[],"",...u===void 0?[]:[u]].join(`\r+ &$filter=(applicationid eq '${e}')`;A.SPNPrincipalIdUrl=iL;function aL(){return"/api/data/v9.0/appmodules?$filter=(uniquename eq 'AppDeploymentConfiguration')"}A.retrieveDeploymentPipelineConfigAppUrl=aL;A.retrieveFeatureControlSettingsByNamespaceUrl="/api/data/v9.1/RetrieveFeatureControlSettingsByNamespace";function oL(e){return`/api/data/v9.0/settingdefinitions${e}`}A.getSettingDefinitionsUri=oL;A.OrgSettingOverrideName="organizationsettings";function sL(e,t=!1){let r=`/api/data/v9.0/${A.OrgSettingOverrideName}${e}`;return t?`${A.cdsServiceUrl}${r}`:r}A.getOrgSettingOverrideUri=sL;A.AppSettingOverrideName="appsettings";function lL(e,t=!1){let r=`/api/data/v9.0/${A.AppSettingOverrideName}${e}`;return t?`${A.cdsServiceUrl.replace("/$","")}${r}`:r}A.getAppSettingOverrideUri=lL;var bo;(function(e){e[e.All=0]="All",e[e.IsPlatformOnly=1]="IsPlatformOnly",e[e.NotPlatformOnly=2]="NotPlatformOnly"})(bo||(A.RetrievePlatform=bo={}));function uL(e,t,r,n=bo.All,i=!1){let a=[];e&&a.push(`AppUniqueName='${e}'`),t!=null&&a.push(`ReleaseLevel=${t}`),r&&a.push(`RetrieveHiddenSettings=${r}`),n!==bo.All&&a.push(`RetrievePlatformSettings=${n===bo.IsPlatformOnly?1:0}`);let o="/api/data/v9.0/RetrieveUnpublishedOverridableSettingsInfo";return a.length&&(o=`${o}(${a.join(",")})`),i?`${A.cdsServiceUrl}${o}`:o}A.getPowerSettingsUri=uL;function cL(e,t,r,n=!1){let i=[`SettingName='${e}'`];t!==void 0&&i.push(`SolutionName='${t}'`),r!==void 0&&i.push(`AppUniqueName='${r}'`);let a="/api/data/v9.0/RetrieveUnpublishedSettingInfo";return i.length&&(a=`${a}(${i.join(",")})`),n?`${A.cdsServiceUrl}${a}`:a}A.getPowerSettingUri=cL;function dL(e=!1){let t="/api/data/v9.0/SaveSettingValue()";return e?`${A.cdsServiceUrl}${t}`:t}A.getSavePowerSettingUri=dL;A.retrieveUnpublishedSuffix="Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()";function pL(e){return`tools/systemcustomization/businessrules/businessRulesDesigner.aspx?BRlaunchpoint=BRGrid&appSolutionId={${e}}`}A.getBusinessRuleDesignerUri=pL;function sv({environmentInstanceUrl:e,entityLogicalName:t}){return e&&t?`${e}main.aspx?cmdbar=true&forceUCI=1&navbar=off&newWindow=true&pageType=entityRecord&etn=${t}`:void 0}A.getUCIEntityRecordBaseUrl=sv;function fL({baseUrl:e,environmentInstanceUrl:t,entityLogicalName:r,recordId:n}){let i=e||sv({environmentInstanceUrl:t,entityLogicalName:r});return i&&n?`${i}&id=${n}`:void 0}A.getUCIEntityRecordEditUrl=fL;A.retrieveOrganizationResources=`${A.cdsServiceUrl}api/data/v9.0/RetrieveOrganizationResources`});var lv=y(sl=>{"use strict";Object.defineProperty(sl,"__esModule",{value:!0});sl.DataverseClient=void 0;var mL=_d(),ui=ee(),Pd=class{constructor(t,r,n){this.instanceUrl=t,this.httpClient=r,this.solutionUniqueName=n}withSolution(t){return this.solutionUniqueName?{...t,headers:{...t?.headers,"MSCRM.SolutionUniqueName":this.solutionUniqueName}}:t}apiUrl(t){let r=this.instanceUrl.replace(/\/+$/,""),n=t.startsWith("/")?t:`/${t}`;return`${r}/${mL.xrmApiUrl}${n}`}async send(t,r){try{return await r()}catch(n){throw n instanceof ui.SdkError?n:new ui.ConnectionError(t,0,n instanceof Error?n.message:String(n),n)}}get(t,r){let n=this.apiUrl(t);return this.send(n,()=>this.httpClient.get(n,r))}getAbsolute(t,r){return this.assertSameOrigin(t),this.send(t,()=>this.httpClient.get(t,r))}assertSameOrigin(t){let r,n;try{r=new URL(t),n=new URL(this.instanceUrl)}catch{throw new ui.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${t}'`)}if(r.protocol!==n.protocol||r.host!==n.host)throw new ui.InvalidArgumentError(`Refusing to follow a cross-origin link ('${r.origin}' is not the configured instance '${n.origin}'); server-driven pagination must stay on-instance.`)}post(t,r,n){let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.post(i,r,this.withSolution(n)))}get supportsAtomicBatch(){return typeof this.httpClient.postRaw=="function"}get solutionName(){return this.solutionUniqueName}postBatch(t,r,n){if(!this.httpClient.postRaw)throw new ui.InvalidArgumentError("The injected HttpClient does not implement postRaw(), required for atomic $batch change sets");let i=this.apiUrl("/$batch"),a={...n,headers:{...n?.headers,"Content-Type":`multipart/mixed;boundary=${r}`}};return this.send(i,()=>this.httpClient.postRaw(i,t,a))}patch(t,r,n){let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.patch(i,r,this.withSolution(n)))}get supportsBinaryPatch(){return typeof this.httpClient.patchRaw=="function"}patchRaw(t,r,n){if(!this.httpClient.patchRaw)throw new ui.InvalidArgumentError("The injected HttpClient does not implement patchRaw(), required to upload file content (a Dataverse File column cannot be written through a JSON body)");let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.patchRaw(i,r,this.withSolution(n)))}put(t,r,n){if(!this.httpClient.put)throw new ui.InvalidArgumentError("The injected HttpClient does not implement put(), required for metadata replace operations (e.g. updateColumn)");let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.put(i,r,this.withSolution(n)))}delete(t,r){let n=this.apiUrl(t);return this.send(n,()=>this.httpClient.delete(n,this.withSolution(r)))}};sl.DataverseClient=Pd});var uv=y(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});Ln.findColumns=Ln.findTables=Ln.fetchEntityMetadataFromApi=void 0;var Od=Ee(),Kt=le();function Rr(e){var t,r;return(r=(t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)!==null&&r!==void 0?r:""}function Hi(e){let t=e?.LocalizedLabels;if(!Array.isArray(t)||t.length<2)return;let r={};for(let n of t)typeof n?.LanguageCode=="number"&&typeof n.Label=="string"&&(r[n.LanguageCode]=n.Label);return Object.keys(r).length?r:void 0}async function Ao(e,t){return(await xd(e,t)).rows}async function xd(e,t){var r,n;let i=await e.get(t);return i.status<200||i.status>=300?{rows:[],ok:!1}:{rows:(n=(r=i.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[],ok:!0}}function Or(e){return`/EntityDefinitions(LogicalName='${(0,Kt.odataPathLiteral)(e)}')`}async function hL(e,t,r){let n=await Ao(e,`${Or(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata${(0,Kt.odataQuery)([["$select","LogicalName,MaxLength"]])}`);for(let i of n){let a=r.get(i.LogicalName);a&&typeof i.MaxLength=="number"&&(a.maxLength=i.MaxLength)}}async function gL(e,t,r){var n;let i=await Ao(e,`${Or(t)}/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata${(0,Kt.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`);for(let a of i){let o=r.get(a.LogicalName);o&&(!((n=a.OptionSet)===null||n===void 0)&&n.Options)&&(o.options=a.OptionSet.Options.map(s=>{var l;return{value:(l=s.Value)!==null&&l!==void 0?l:0,label:Rr(s.Label),...Hi(s.Label)?{localizedLabel:Hi(s.Label)}:{}}}))}}function Rd(e){var t;return{value:(t=e.Value)!==null&&t!==void 0?t:0,label:Rr(e.Label),...e.InvariantName?{invariantName:e.InvariantName}:{},...e.Color?{color:e.Color}:{}}}async function vL(e,t){var r;let n=l=>xd(e,l).catch(()=>({rows:[],ok:!1})),i=["PicklistAttributeMetadata","MultiSelectPicklistAttributeMetadata","StateAttributeMetadata","StatusAttributeMetadata"],a=await Promise.all(i.map(l=>n(`${Or(t)}/Attributes/Microsoft.Dynamics.CRM.${l}${(0,Kt.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`))),o=new Map;for(let{rows:l}of a)for(let u of l)!((r=u.OptionSet)===null||r===void 0)&&r.Options&&o.set(u.LogicalName,u.OptionSet.Options.map(Rd));let s=await n(`${Or(t)}/Attributes/Microsoft.Dynamics.CRM.BooleanAttributeMetadata${(0,Kt.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=TrueOption,FalseOption)"]])}`);for(let l of s.rows){let u=l.OptionSet;u?.TrueOption&&u.FalseOption&&o.set(l.LogicalName,[Rd(u.FalseOption),Rd(u.TrueOption)])}return{byColumn:o,complete:s.ok&&a.every(l=>l.ok)}}async function yL(e,t,r){let{rows:n,ok:i}=await xd(e,`${Or(t)}/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata${(0,Kt.odataQuery)([["$select","LogicalName,Targets"]])}`);for(let a of n){let o=r.get(a.LogicalName);o&&a.Targets&&(o.targets=a.Targets)}return i}async function bL(e,t){var r,n,i,a;let o=[],s=await Ao(e,`${Or(t)}/OneToManyRelationships${(0,Kt.odataQuery)([["$select","SchemaName,ReferencingEntity,ReferencingAttribute"]])}`);for(let c of s)o.push({schemaName:c.SchemaName,type:"OneToMany",relatedEntity:(r=c.ReferencingEntity)!==null&&r!==void 0?r:"",relatedAttribute:(n=c.ReferencingAttribute)!==null&&n!==void 0?n:""});let l=await Ao(e,`${Or(t)}/ManyToOneRelationships${(0,Kt.odataQuery)([["$select","SchemaName,ReferencedEntity,ReferencedAttribute"]])}`);for(let c of l)o.push({schemaName:c.SchemaName,type:"ManyToOne",relatedEntity:(i=c.ReferencedEntity)!==null&&i!==void 0?i:"",relatedAttribute:(a=c.ReferencedAttribute)!==null&&a!==void 0?a:""});let u=await Ao(e,`${Or(t)}/ManyToManyRelationships${(0,Kt.odataQuery)([["$select","SchemaName,Entity1LogicalName,Entity2LogicalName"]])}`);for(let c of u){let d=c.Entity1LogicalName===t?c.Entity2LogicalName:c.Entity1LogicalName;o.push({schemaName:c.SchemaName,type:"ManyToMany",relatedEntity:d??"",relatedAttribute:""})}return o}async function wL(e,t){var r,n,i,a,o;let s=`${Or(t)}`+(0,Kt.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,Description,EntitySetName,IsCustomEntity,PrimaryNameAttribute,PrimaryIdAttribute,PrimaryImageAttribute"],["$expand","Attributes($select=LogicalName,DisplayName,Description,AttributeType,AttributeTypeName,IsCustomAttribute,IsValidForUpdate,IsValidForRead,AttributeOf)"]]),u=(0,Od.ensureSuccess)(await e.get(s),e.apiUrl(s)).body,c=((r=u.Attributes)!==null&&r!==void 0?r:[]).map(h=>{var v,w,C;return{logicalName:h.LogicalName,displayName:Rr(h.DisplayName),...Hi(h.DisplayName)?{localizedDisplayName:Hi(h.DisplayName)}:{},attributeType:(v=h.AttributeType)!==null&&v!==void 0?v:"Unknown",isCustomAttribute:!!h.IsCustomAttribute,attributeTypeName:(C=(w=h.AttributeTypeName)===null||w===void 0?void 0:w.Value)!==null&&C!==void 0?C:"",...typeof h.IsValidForUpdate=="boolean"?{isValidForUpdate:h.IsValidForUpdate}:{},...typeof h.IsValidForRead=="boolean"?{isValidForRead:h.IsValidForRead}:{},...h.AttributeOf?{attributeOf:h.AttributeOf}:{},...Rr(h.Description)?{description:Rr(h.Description)}:{}}}),d=new Map(c.map(h=>[h.logicalName,h])),[,,p,f,m]=await Promise.all([hL(e,t,d),gL(e,t,d),vL(e,t),yL(e,t,d),bL(e,t)]);for(let h of c){let v=p.byColumn.get(h.logicalName);v&&(h.choices=v)}return{logicalName:u.LogicalName,schemaName:(n=u.SchemaName)!==null&&n!==void 0?n:u.LogicalName,displayName:Rr(u.DisplayName),...Hi(u.DisplayName)?{localizedDisplayName:Hi(u.DisplayName)}:{},entitySetName:(i=u.EntitySetName)!==null&&i!==void 0?i:"",primaryNameAttribute:(a=u.PrimaryNameAttribute)!==null&&a!==void 0?a:"",primaryIdAttribute:(o=u.PrimaryIdAttribute)!==null&&o!==void 0?o:"",...u.PrimaryImageAttribute?{primaryImageAttribute:u.PrimaryImageAttribute}:{},isCustomEntity:!!u.IsCustomEntity,...Rr(u.Description)?{description:Rr(u.Description)}:{},columnDetailComplete:p.complete&&f,attributes:c,relationships:m}}Ln.fetchEntityMetadataFromApi=wL;async function AL(e,t,r){var n,i;let a=`/EntityDefinitions${(0,Kt.odataQuery)([["$select","LogicalName,SchemaName,EntitySetName,DisplayName,IsCustomEntity"]])}`,s=(i=(n=(0,Od.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[],l=(t??"").toLowerCase(),u=s.filter(c=>!r?.customOnly||c.IsCustomEntity).map(c=>{var d,p;return{logicalName:c.LogicalName,schemaName:(d=c.SchemaName)!==null&&d!==void 0?d:c.LogicalName,displayName:Rr(c.DisplayName),entitySetName:(p=c.EntitySetName)!==null&&p!==void 0?p:"",isCustom:!!c.IsCustomEntity}}).filter(c=>c.logicalName.toLowerCase().includes(l)||c.schemaName.toLowerCase().includes(l)||c.displayName.toLowerCase().includes(l));return typeof r?.top=="number"?u.slice(0,r.top):u}Ln.findTables=AL;async function CL(e,t,r,n){var i,a;let o=`${Or(t)}/Attributes`+(0,Kt.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute"]]),l=(a=(i=(0,Od.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||i===void 0?void 0:i.value)!==null&&a!==void 0?a:[],u=(r??"").toLowerCase(),c=l.map(d=>{var p,f;return{logicalName:d.LogicalName,schemaName:(p=d.SchemaName)!==null&&p!==void 0?p:d.LogicalName,displayName:Rr(d.DisplayName),attributeType:(f=d.AttributeType)!==null&&f!==void 0?f:"Unknown",isCustom:!!d.IsCustomAttribute}}).filter(d=>d.logicalName.toLowerCase().includes(u)||d.schemaName.toLowerCase().includes(u)||d.displayName.toLowerCase().includes(u));return typeof n?.top=="number"?c.slice(0,n.top):c}Ln.findColumns=CL});var kd=y(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.renderTypeRegistrations=Dt.buildGenPageLegacyEnums=Dt.renderGenPageAuthoringTypes=Dt.buildGenPageRuntimeTypes=Dt.toDesignerEntity=Dt.TABLE_LOGICAL_NAME=void 0;Dt.TABLE_LOGICAL_NAME=/^[a-z_][a-z0-9_]*$/;function Ld(e){return e.replace(/[\r\n\u2028\u2029]+/g," ")}var EL=new Set(["createdby","createdon","createdonbehalfby","importsequencenumber","modifiedby","modifiedon","modifiedonbehalfby","overriddencreatedon","ownerid","owningbusinessunit","owningteam","owninguser","timezoneruleversionnumber","utcconversiontimezonecode","versionnumber"]);function ll(e){var t;return((t=e.attributeTypeName)!==null&&t!==void 0?t:"").replace(/Type$/,"").toLowerCase()}function pv(e){var t,r;let n=e.choices;if(!n||n.length===0)return;let i=ll(e)==="boolean",a={};for(let o of n)a[o.value]={text:(r=(t=o.invariantName)!==null&&t!==void 0?t:o.label)!==null&&r!==void 0?r:"",value:o.value,...!i&&o.color?{color:o.color}:{}};return a}function cv(e,t){return e.logicalName<t.logicalName?-1:e.logicalName>t.logicalName?1:0}function fv(e){return!EL.has(e.logicalName)&&(!e.attributeOf||ll(e)==="image")&&e.isValidForRead!==!1}var dv=new Set(["boolean","picklist","multiselectpicklist","state","status"]);function mv(e){let t=e.primaryImageAttribute,r=new Set([e.primaryIdAttribute,e.primaryNameAttribute,t,t?`${t}_url`:void 0,"processid","statecode","statuscode"].filter(a=>!!a)),n=e.attributes.filter(a=>r.has(a.logicalName)).sort(cv),i=e.attributes.filter(a=>!r.has(a.logicalName)).sort(cv);return[...n,...i]}function Fd(e){var t;let r=[],n=new Set,i=mv(e);for(let a of i){let o=ll(a),s=o==="image";fv(a)&&(s&&a.attributeOf&&n.add(a.attributeOf),r.push({AttributeTypeName:o,IsReadOnly:!a.isValidForUpdate,LogicalName:a.logicalName,OptionSet:pv(a),Targets:a.targets,Description:a.description,MaxLength:a.maxLength}))}return{Description:(t=e.description)!==null&&t!==void 0?t:"",LogicalName:e.logicalName,PrimaryIdAttribute:e.primaryIdAttribute,Attributes:r.filter(a=>!n.has(a.LogicalName))}}Dt.toDesignerEntity=Fd;function hv(e,t="None"){let r={};for(let n of e)r[n.logicalName]=Fd(n);return yv(r,t)}Dt.buildGenPageRuntimeTypes=hv;var gv=`export interface TableRegistrations extends BaseTableRegistrations {+`,vv=`export interface EnumRegistrations extends BaseEnumRegistrations {+`;function SL(e,t){return e.length>0?hv(e,t).text:wv(`${gv}}+`,`${vv}}+`,"","")}Dt.renderGenPageAuthoringTypes=SL;function NL(e){let t=new Set;for(let n of e)for(let i of Fd(n).Attributes)dv.has(i.AttributeTypeName)&&t.add(`${n.logicalName}_${i.LogicalName}`);let r=new Map;for(let n of e)for(let i of mv(n)){let a=`${n.logicalName}_${i.logicalName}`,o=pv(i);if(fv(i)||!dv.has(ll(i))||!o||t.has(a)||r.has(a))continue;let s={name:a,runtime:{},labels:new Map};r.set(a,{declaration:bv(a,o,!1,s),model:s})}return r}Dt.buildGenPageLegacyEnums=NL;function yv(e,t="None"){var r,n;let i=new Map,a=Object.values(e);if(a.length===0)return{text:"",enums:i};let o=t==="ColorsDefaultsConstraints"||t==="ColorsDefaultsConstraintsDescriptions",s=t==="ColorsDefaultsConstraintsDescriptions",l=gv,u=vv,c="",d="";for(let p of a){s&&p.Description&&(c+=`// ${Ld(p.Description)}+`),c+=`export type ${p.LogicalName} = TableRow<{+ // Primary Key Column+ readonly ${p.PrimaryIdAttribute}: string,+`,l+=` "${p.LogicalName}": ${p.LogicalName},+`;for(let f of p.Attributes){if(f.LogicalName===p.PrimaryIdAttribute)continue;let m=`${f.IsReadOnly?" readonly ":""}${f.LogicalName}`,h=!0;switch(f.AttributeTypeName){case"string":case"memo":case"uniqueidentifier":case"entityname":m+=`: string,+`;break;case"integer":case"double":case"decimal":case"money":case"bigint":m+=`: number,+`;break;case"datetime":m+=`: Date,+`;break;case"customer":case"lookup":{let v=(r=f.Targets)!==null&&r!==void 0?r:f.AttributeTypeName==="customer"?["account","contact"]:void 0;if(!v||v.length===0){h=!1;break}m=` // Foreign Key Column+ ${f.IsReadOnly||v.every(C=>!e[C])?" readonly ":""}_${f.LogicalName}_value: `;let w="";for(let C of v)w+=`${w.length===0?"":" | "}\`/${C}(\${string})\``;m+=`${w},+`;break}case"boolean":case"picklist":case"multiselectpicklist":case"state":case"status":{let v=`${p.LogicalName}_${f.LogicalName}`;m+=`: ${v},+`;let w=(n=i.get(v))!==null&&n!==void 0?n:{name:v,runtime:{},labels:new Map};i.set(v,w),d+=bv(v,f.OptionSet,o,w),u+=` "${p.LogicalName}-${f.LogicalName}": ${v},+`;break}case"image":c+=` // This is an image encoded as a base64 string+`,m+=`: string,+`;break;default:h=!1}h&&(s&&f.Description&&(c+=` // ${Ld(f.Description)}+`),o&&f.MaxLength&&(c+=" // Maximum length: "+f.MaxLength+`+`),c+=` ${m}`)}c+=`}>+`}return l+=`}+`,u+=`}+`,{text:wv(l,u,c,d),enums:i}}Dt.renderTypeRegistrations=yv;function bv(e,t,r,n){var i;let a=`const enum ${e} {+`;for(let o of Object.values(t??{}))if(o){r&&(a+=`${o.color?`// Option Color: ${Ld(o.color)}+`:""}`),a+=`${JSON.stringify(o.text)} = ${o.value},+`,n.runtime[o.text]=o.value,n.runtime[String(o.value)]=o.text;let s=(i=n.labels.get(o.text))!==null&&i!==void 0?i:[];s.includes(o.value)||s.push(o.value),n.labels.set(o.text,s)}return`${a}}+`}function wv(e,t,r,n){return`+// ---------------- Type Definitions which can be imported from ./RuntimeTypes -------------------------+${e}+${t}+${r}+${n}++/**+ * Possible scalar values of a data column in a data row.+ */+export type DataColumnValue = string | number | boolean | Date | null;++/**+ * Represents the type for the value of a primary key column, typically a string.+ */+export type RowKeyDataColumnValue = string;++/**+ * Represents the row of a table+ */+export interface DataRow {+ /**+ * A column can be a simple field value+ */+ [column: string]: DataColumnValue;+}++/**+ * Represents a table type with the given row typing+ */+export type TableRow<R extends DataRow = DataRow> = R;++/**+ * Represents a collection of rows for a table+ */+export interface DataTable<T> {+ rows: T[];+ hasMoreRows: boolean;+ loadMoreRows?: () => Promise<DataTable<T>>;+}++// Type equality check utility - leverages assignability of extends+// See https://stackoverflow.com/a/52473108 for detailed explanation+export type IfTypeEquals<X, Y, A, B> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2+ ? A+ : B;++export type ExcludeReadonly<T> =+ // For every property, we are checking if a type with just that property (whether readonly or writable) is assignable to a type which requires that property to be writable+ // If it does, then the property is inferred to be writable and is kept in the mapped keys+ // If not, it is removed from the mapped keys+ { [P in keyof T as IfTypeEquals<{ [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, P, never>]: T[P] };++/**+ * Extracts a sub-type with only the fields of the table (simple values, but not nav props)+ * @template T The original type representing a table row.+ * @template FieldType The base type for fields to extract (defaults to DataColumnValue).+ */+export type ExtractFields<T, FieldType = DataColumnValue> = {+ [K in keyof T as Required<T>[K] extends FieldType ? K : never]: T[K];+};++/**+ * Extracts the properties from type E that represent selectable scalar fields.+ * @template E The entity type.+ */+export type ExtractSelectable<E> = {+ // All simple value fields get included as the actual value+ [K in keyof ExtractFields<E, DataColumnValue>]: E[K];+};++/**+ * Extracts properties representing the OData formatted values for display purposes.+ * Creates properties like \`<fieldName>@OData.Community.Display.V1.FormattedValue\`.+ * @template E The entity type.+ */+export type ExtractReadonly<E> = {+ // For all field values, include a <prop-name>@OData.Community.Display.V1.FormattedValue string property that holds the formatted value of the field+ [K in keyof ExtractFields<E, DataColumnValue> as \`\${Extract<+ K,+ string+ >}@OData.Community.Display.V1.FormattedValue\`]?: string;+};++/**+ * Retrieved record definition is projected from the defined typing structure for the table+ */+export type ReadableTableRow<E> = ExtractSelectable<E> & ExtractReadonly<E>;++/**+ * Writable record definition is projected from the defined typing structure for the table+ */+export type WritableTableRow<E extends TableRow> = {+ // All non readonly fields get included as the actual value type+ [K in keyof ExcludeReadonly<ExtractFields<E, DataColumnValue>>]: E[K];+};++/**+ * Base options for fetching row data, allowing selection of specific fields.+ * @template E The entity type extending TableRow.+ */+export interface FetchRowOptions<E extends TableRow> {+ /**+ * List of fields to select (not allowed to select from related)+ */+ select?: Array<keyof ExtractSelectable<E>>;+}++/**+ * Options for table query operation+ */+export interface QueryTableOptions<E extends TableRow> extends FetchRowOptions<E> {+ /**+ * Optionally specifies the page size for fetching records+ */+ pageSize?: number;+ /**+ * ODATA filter expression for the table+ */+ filter?: string;++ /**+ * ODATA orderby expression for the table+ */+ orderBy?: string;+}++/**+ * Options for fetching a single record operation+ */+export interface RetrieveRowOptions<E extends TableRow> extends FetchRowOptions<E> {+ /**+ * ID of the row+ */+ id: string;+}++/**+ * Base interface for table registrations. Specific implementations should extend this.+ */+export interface BaseTableRegistrations {+ [tableName: string]: TableRow;+}++/**+ * Base interface for enum registrations. Specific implementations should extend this.+ */+export interface BaseEnumRegistrations {+ [enumName: string]: number;+}++/**+ * Extract all available table names from a given TableRegistrations type+ * @template TR The type extending BaseTableRegistrations.+ * @template E The base entity type constraint (defaults to TableRow).+ */+export type TableName<TR extends BaseTableRegistrations, E extends TableRow = TableRow> = keyof {+ [K in keyof TR as TR[K] extends E ? K : never]: TR[K];+};++/**+ * Extracts all available enum names from a given EnumRegistrations type+ * @template ER The type extending BaseEnumRegistrations.+ */+export type EnumName<ER extends BaseEnumRegistrations> = keyof {+ [K in keyof ER as ER[K] extends number ? K : never]: ER[K];+};++/**+ * Represents a single choice for an enum, containing a display label and its corresponding value.+ * @template E The specific enum name.+ * @template ER The type extending BaseEnumRegistrations.+ */+export interface EnumChoice<E extends EnumName<ER>, ER extends BaseEnumRegistrations> {+ label: string;+ value: ER[E];+}++/**+ * Gets the table row type of a table given its name and optional TableRegistrations type+ * @template T The name of the table.+ * @template TR The type extending BaseTableRegistrations.+ */+export type RowOf<T extends TableName<TR>, TR extends BaseTableRegistrations> = TR[T];++/**+ * The input for a page, which may include an optional record ID, entity name, and additional data.+ */+export interface PageInput {+ recordId?: string;+ entityName?: string;+ data?: object;+}++/**+ * Represents the base interface for a UX Agent Data API, providing CRUD operations for table data+ * and retrieval of enum choices. This generic interface is designed to be extended for specific+ * table and enum registrations.+ *+ * @template TR - The type representing table registrations, mapping table names to their row types.+ * @template ER - The type representing enum registrations, mapping enum names to their value types.+ *+ * @interface+ */+export interface BaseUxAgentDataApi<TR extends BaseTableRegistrations, ER extends BaseEnumRegistrations> {+ /**+ * Creates a new row in the specified table.+ * @template T - The name of the table.+ * @param tableName - The name of the table to create the row in.+ * @param row - The data for the new row.+ * @returns A promise that resolves with the ID of the newly created row.+ */+ createRow<T extends keyof TR>(tableName: T, row: WritableTableRow<TR[T]>): Promise<RowKeyDataColumnValue>;+ /**+ * Updates an existing row in the specified table.+ * @template T - The name of the table.+ * @param tableName - The name of the table containing the row to update.+ * @param rowId - The ID of the row to update.+ * @param row - The updated data for the row.+ * @returns A promise that resolves when the update is complete.+ */+ updateRow<T extends keyof TR>(+ tableName: T,+ rowId: RowKeyDataColumnValue,+ row: WritableTableRow<TR[T]>+ ): Promise<void>;+ /**+ * Deletes a row from the specified table.+ * @template T - The name of the table.+ * @param tableName - The name of the table to delete the row from.+ * @param rowId - The ID of the row to delete.+ * @returns A promise that resolves when the deletion is complete.+ */+ deleteRow<T extends keyof TR>(tableName: T, rowId: RowKeyDataColumnValue): Promise<void>;+ /**+ * Retrieves a single row from the specified table based on the provided options.+ * @template T - The name of the table.+ * @param tableName - The name of the table to retrieve the row from.+ * @param options - The options for retrieving the row, including the row ID and selected fields.+ * @returns A promise that resolves with the retrieved row data.+ */+ retrieveRow<T extends keyof TR>(+ tableName: T,+ options: RetrieveRowOptions<TR[T]>+ ): Promise<ReadableTableRow<TR[T]>>;+ /**+ * Queries a table based on the specified options.+ * @template T - The name of the table.+ * @param tableName - The name of the table to query.+ * @param query - The query options, including select, filter, sorting and pagination settings.+ * @returns A promise that resolves with a DataTable containing the query results.+ */+ queryTable<T extends keyof TR>(+ tableName: T,+ query: QueryTableOptions<TR[T]>+ ): Promise<DataTable<ReadableTableRow<TR[T]>>>;+ /**+ * Retrieves the available choices for a specified enum.+ * @template E - The name of the enum.+ * @param enumName - The name of the enum to retrieve choices for.+ * @returns A promise that resolves with an array of enum choices, each containing a label and value.+ */+ getChoices<E extends EnumName<ER>>(enumName: E): Promise<Array<EnumChoice<E, ER>>>;+}++export interface UxAgentDataApi extends BaseUxAgentDataApi<TableRegistrations, EnumRegistrations> {}++export interface GeneratedComponentProps {+ dataApi: UxAgentDataApi;+ pageInput?: PageInput;+}+`}});var Ev=y(ul=>{"use strict";Object.defineProperty(ul,"__esModule",{value:!0});ul.generateGenPageRuntimeTypes=void 0;var Cv=kd(),ci=ee(),Av=new Set(["None","ColorsDefaultsConstraints","ColorsDefaultsConstraintsDescriptions"]),di="generateGenPageRuntimeTypes";async function DL(e,t,r){let n=IL(t),i=_L(r),a=[];for(let o of n){let s=await e(o);if(s.columnDetailComplete!==!0)throw new ci.SdkError("GENPAGE_DATA_SOURCE_INCOMPLETE",`${di}: the column metadata of data source '${o}' could not be read completely (a choice or lookup request failed), so its RuntimeTypes would lack enums a page can use. Retry.`);a.push(s)}return(0,Cv.renderGenPageAuthoringTypes)(a,i)}ul.generateGenPageRuntimeTypes=DL;function IL(e){if(!Array.isArray(e))throw new ci.InvalidArgumentError(`${di}: dataSources must be an array of table logical names`);let t=new Set;for(let r of e){if(typeof r!="string"||!Cv.TABLE_LOGICAL_NAME.test(r))throw new ci.InvalidArgumentError(`${di}: a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(r)}'`);if(t.has(r))throw new ci.InvalidArgumentError(`${di}: data source '${r}' is listed twice; a page's dataSources hold each table once`);t.add(r)}return[...t]}function _L(e){if(e===void 0)return"None";if(e===null||typeof e!="object"||Array.isArray(e))throw new ci.InvalidArgumentError(`${di}: options must be an object`);let t=Object.keys(e).filter(n=>n!=="detail");if(t.length>0)throw new ci.InvalidArgumentError(`${di}: unknown option '${t[0]}' (the only option is 'detail')`);let r=e.detail===void 0?"None":e.detail;if(typeof r!="string"||!Av.has(r))throw new ci.InvalidArgumentError(`${di}: detail must be one of ${[...Av].map(n=>`'${n}'`).join(", ")}, got '${String(r)}'`);return r}});var Ji=y(cl=>{"use strict";Object.defineProperty(cl,"__esModule",{value:!0});cl.DEFAULT_LCID=void 0;cl.DEFAULT_LCID=1033});var st=y(Ki=>{"use strict";Object.defineProperty(Ki,"__esModule",{value:!0});Ki.assignMissingIds=Ki.newId=void 0;function Sv(){return globalThis.crypto.randomUUID().toLowerCase()}Ki.newId=Sv;function TL(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var PL=new Set(["parameters","bag","expression","rawExpression","lookupValue","stepLabels"]);function RL(e){return Md(e),e}Ki.assignMissingIds=RL;function Md(e){if(Array.isArray(e)){e.forEach(t=>Md(t));return}if(TL(e)){(typeof e.id!="string"||e.id.length===0)&&(e.id=Sv());for(let t of Object.keys(e))t==="id"||PL.has(t)||Md(e[t])}}});var dl=y(Fn=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});Fn.postChangeSet=Fn.parseChangeSetStatuses=Fn.renderChangeSet=void 0;var pi=ee(),OL=Ee(),Nv=st(),Co=le();function Dv(e,t){let r=`batch_${(0,Nv.newId)()}`,n=`changeset_${(0,Nv.newId)()}`,i=t.map((s,l)=>String(l+1)),a=t.map((s,l)=>{var u,c;if(s.rawBody!==void 0&&s.contentType===void 0)throw new pi.InvalidArgumentError(`batch operation ${s.method} ${s.path} has a raw body but no Content-Type`);let d=(u=s.rawBody)!==null&&u!==void 0?u:s.body===void 0?void 0:JSON.stringify(s.body);if(d!==void 0&&(d.includes(`--${n}`)||d.includes(`--${r}`)))throw new pi.InvalidArgumentError(`batch operation ${s.method} ${s.path} has a body containing the batch boundary`);(0,Co.assertNoControlChars)(s.path,"batch operation path"),s.etag&&(0,Co.assertNoControlChars)(s.etag,"batch operation etag");let p=Object.entries((c=s.headers)!==null&&c!==void 0?c:{});for(let[f,m]of p)if((0,Co.assertNoControlChars)(f,"batch operation header name"),(0,Co.assertNoControlChars)(m,"batch operation header value"),!/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/.test(f))throw new pi.InvalidArgumentError(`batch operation header name '${f}' is not a valid HTTP token`);return s.contentType!==void 0&&(0,Co.assertNoControlChars)(s.contentType,"batch operation content type"),[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${i[l]}`,"",`${s.method} ${e.apiUrl(s.path)} HTTP/1.1`,...d===void 0?[]:[`Content-Type: ${s.rawBody!==void 0?s.contentType:"application/json;type=entry"}`],...e.solutionName?[`MSCRM.SolutionUniqueName: ${e.solutionName}`]:[],...s.etag?[`If-Match: ${s.etag}`]:[],...p.map(([f,m])=>`${f}: ${m}`),"",...d===void 0?[]:[d]].join(`\r`)});return{body:[`--${r}`,`Content-Type: multipart/mixed;boundary=${n}`,"",...a,`--${n}--`,`--${r}--`,""].join(`\r-`),batchId:r,contentIds:i}}Nn.renderChangeSet=y0;function b0(e,t){var r,n,i,a;if(typeof e!="string"||e.length===0)return;let o=(r=/^--(\S+)\r?\n/.exec(e))===null||r===void 0?void 0:r[1];if(o===void 0||!e.trimEnd().endsWith(`--${o}--`))return;let s=(n=/Content-Type:\s*multipart\/mixed;\s*boundary=(\S+)/i.exec(e))===null||n===void 0?void 0:n[1];if(s===void 0||s===o)return;let l=e.split(`--${s}`);if(l.length<2||!/^--(\r?\n|$)/.test(l[l.length-1]))return;let u=new Set(t),c=[],d=new Set;for(let p of l.slice(1)){if(p.startsWith("--"))break;let f=p.indexOf(`\r+`),batchId:r,contentIds:i}}Fn.renderChangeSet=Dv;function Iv(e,t){var r,n,i,a;if(typeof e!="string"||e.length===0)return;let o=(r=/^--(\S+)\r?\n/.exec(e))===null||r===void 0?void 0:r[1];if(o===void 0||!e.trimEnd().endsWith(`--${o}--`))return;let s=(n=/Content-Type:\s*multipart\/mixed;\s*boundary=(\S+)/i.exec(e))===null||n===void 0?void 0:n[1];if(s===void 0||s===o)return;let l=e.split(`--${s}`);if(l.length<2||!/^--(\r?\n|$)/.test(l[l.length-1]))return;let u=new Set(t),c=[],d=new Set;for(let p of l.slice(1)){if(p.startsWith("--"))break;let f=p.indexOf(`\r\r-`);if(f===-1)return;let m=p.slice(0,f),g=p.slice(f+4);if(!/^Content-Type:\s*application\/http\b/im.test(m))return;let y=/^HTTP\/1\.[01] (\d{3})\b/.exec(g);if(!y||((i=g.match(/^HTTP\/1\.[01] \d{3}\b/gm))!==null&&i!==void 0?i:[]).length!==1)return;let A=(a=/^Content-ID:\s*(\S+)/im.exec(m))===null||a===void 0?void 0:a[1];if(A===void 0||d.has(A)||!u.has(A))return;d.add(A),c.push(Number(y[1]))}return c.length===0?void 0:c}Nn.parseChangeSetStatuses=b0;async function xR(e,t,r){if(t.length===0)return;let{body:n,batchId:i,contentIds:a}=y0(e,t),o=await e.postBatch(n,i),s=e.apiUrl("/$batch");if((0,FR.ensureSuccess)(o,s),typeof o.body!="string"||o.body.length===0)throw new $s.ConnectionError(s,o.status,`atomic write of ${r} cannot be confirmed: the $batch response had no readable body, so the change set's outcome is unknown`);let l=b0(o.body,a);if(l===void 0)throw new $s.ConnectionError(s,o.status,`atomic write of ${r} cannot be confirmed: the $batch response could not be parsed as a change set, so the outcome is unknown`);if(l.length!==t.length)throw new $s.ConnectionError(s,o.status,`atomic write of ${r} cannot be confirmed: the change set reported ${l.length} result(s) for ${t.length} operation(s)`);let u=l.find(c=>c<200||c>=300);if(u!==void 0)throw new $s.ConnectionError(s,u,`atomic write of ${r} was rolled back: the change set reported HTTP ${u}`)}Nn.postChangeSet=xR});var qs=v(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.updateTable=Q.deleteAlternateKey=Q.createAlternateKey=Q.deleteGlobalOptionSet=Q.createGlobalOptionSet=Q.deleteRelationship=Q.deleteColumn=Q.updateColumn=Q.deleteTable=Q.createRelationship=Q.insertStatusValue=Q.createCustomerColumn=Q.createColumns=Q.setColumnVisualization=Q.getColumnVisualization=Q.createColumn=Q.createTable=Q.resolveEntitySetName=Q.pluralFallback=void 0;var se=be(),J=ae(),Er=Ri(),pe=te(),LR=Kc(),kR={String:"Microsoft.Dynamics.CRM.StringAttributeMetadata",Memo:"Microsoft.Dynamics.CRM.MemoAttributeMetadata",Integer:"Microsoft.Dynamics.CRM.IntegerAttributeMetadata",Decimal:"Microsoft.Dynamics.CRM.DecimalAttributeMetadata",Money:"Microsoft.Dynamics.CRM.MoneyAttributeMetadata",Boolean:"Microsoft.Dynamics.CRM.BooleanAttributeMetadata",DateTime:"Microsoft.Dynamics.CRM.DateTimeAttributeMetadata",Picklist:"Microsoft.Dynamics.CRM.PicklistAttributeMetadata",Lookup:"Microsoft.Dynamics.CRM.LookupAttributeMetadata"};function Ie(e,t){return{"@odata.type":"Microsoft.Dynamics.CRM.Label",LocalizedLabels:MR(e,t)}}var w0=65535;function MR(e,t){let r=(a,o)=>({"@odata.type":"Microsoft.Dynamics.CRM.LocalizedLabel",Label:a,LanguageCode:o});if(typeof e=="string")return[r(e,t)];let n=Object.entries(e);if(!n.length)throw new pe.InvalidArgumentError("a localized label must contain at least one language");let i=new Set;return n.map(([a,o])=>{if(!/^[1-9]\d*$/.test(a))throw new pe.InvalidArgumentError(`localized label key '${a}' is not an LCID (expected a canonical positive integer, e.g. 1033)`);let s=Number(a);if(s>w0)throw new pe.InvalidArgumentError(`localized label LCID ${s} is out of range (1-${w0})`);if(i.has(s))throw new pe.InvalidArgumentError(`localized label LCID ${s} is specified more than once`);if(i.add(s),typeof o!="string")throw new pe.InvalidArgumentError(`localized label for LCID ${s} must be a string`);return r(o,s)})}function S0(e){return typeof e=="string"?`${e}s`:Object.fromEntries(Object.entries(e).map(([t,r])=>{if(typeof r!="string")throw new pe.InvalidArgumentError(`localized label for LCID ${t} must be a string`);return[t,`${r}s`]}))}Q.pluralFallback=S0;function ao(e){return{Value:e,CanBeChanged:!0,ManagedPropertyLogicalName:"canmodifyrequirementlevelsettings"}}function Zc(e){let t=e.indexOf("_");return t>0?e.slice(0,t):e}function A0(e,t,r){let n=e[t];n&&typeof n=="object"?n.Value=r:e[t]={Value:r}}function oo(e){let t=(0,se.readCreatedId)(e,"MetadataId");if(!t)throw new pe.InvalidArgumentError("Dataverse did not return a MetadataId for the created metadata component");return t}function UR(e,t,r){var n,i,a,o,s,l,u,c,d,p,f,m,g,y,A,D,F,_,q,B,L,k,M,G;if(t.defaultValue!==void 0&&e!=="boolean")throw new pe.InvalidArgumentError(`createColumn: 'defaultValue' applies to boolean columns, but '${t.schemaName}' is of type '${e}'.`);if(t.integerFormat!==void 0&&e!=="integer")throw new pe.InvalidArgumentError(`createColumn: 'integerFormat' applies to integer columns, but '${t.schemaName}' is of type '${e}'.`);switch(e){case"string":return{"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},MaxLength:(n=t.maxLength)!==null&&n!==void 0?n:100,FormatName:{Value:(i=t.stringFormat)!==null&&i!==void 0?i:"Text"}};case"memo":return{"@odata.type":"Microsoft.Dynamics.CRM.MemoAttributeMetadata",AttributeType:"Memo",AttributeTypeName:{Value:"MemoType"},MaxLength:(a=t.maxLength)!==null&&a!==void 0?a:2e3,Format:"TextArea"};case"integer":return{"@odata.type":"Microsoft.Dynamics.CRM.IntegerAttributeMetadata",AttributeType:"Integer",AttributeTypeName:{Value:"IntegerType"},Format:(o=t.integerFormat)!==null&&o!==void 0?o:"None",MinValue:(s=t.minValue)!==null&&s!==void 0?s:-2147483648,MaxValue:(l=t.maxValue)!==null&&l!==void 0?l:2147483647};case"bigint":return{"@odata.type":"Microsoft.Dynamics.CRM.BigIntAttributeMetadata",AttributeType:"BigInt",AttributeTypeName:{Value:"BigIntType"}};case"double":return{"@odata.type":"Microsoft.Dynamics.CRM.DoubleAttributeMetadata",AttributeType:"Double",AttributeTypeName:{Value:"DoubleType"},Precision:(u=t.precision)!==null&&u!==void 0?u:2,MinValue:(c=t.minValue)!==null&&c!==void 0?c:-1e11,MaxValue:(d=t.maxValue)!==null&&d!==void 0?d:1e11};case"decimal":return{"@odata.type":"Microsoft.Dynamics.CRM.DecimalAttributeMetadata",AttributeType:"Decimal",AttributeTypeName:{Value:"DecimalType"},Precision:(p=t.precision)!==null&&p!==void 0?p:2,MinValue:(f=t.minValue)!==null&&f!==void 0?f:-1e11,MaxValue:(m=t.maxValue)!==null&&m!==void 0?m:1e11};case"money":return{"@odata.type":"Microsoft.Dynamics.CRM.MoneyAttributeMetadata",AttributeType:"Money",AttributeTypeName:{Value:"MoneyType"},Precision:(g=t.precision)!==null&&g!==void 0?g:2,PrecisionSource:2,MinValue:(y=t.minValue)!==null&&y!==void 0?y:0,MaxValue:(A=t.maxValue)!==null&&A!==void 0?A:1e9};case"boolean":return{"@odata.type":"Microsoft.Dynamics.CRM.BooleanAttributeMetadata",AttributeType:"Boolean",AttributeTypeName:{Value:"BooleanType"},DefaultValue:(D=t.defaultValue)!==null&&D!==void 0?D:!1,OptionSet:{"@odata.type":"Microsoft.Dynamics.CRM.BooleanOptionSetMetadata",TrueOption:{Value:1,Label:Ie((F=t.trueLabel)!==null&&F!==void 0?F:"Yes",r)},FalseOption:{Value:0,Label:Ie((_=t.falseLabel)!==null&&_!==void 0?_:"No",r)}}};case"dateTime":return{"@odata.type":"Microsoft.Dynamics.CRM.DateTimeAttributeMetadata",AttributeType:"DateTime",AttributeTypeName:{Value:"DateTimeType"},Format:(q=t.dateFormat)!==null&&q!==void 0?q:"DateAndTime"};case"choice":return C0(t,r,!1);case"multiChoice":return C0(t,r,!0);case"file":return{"@odata.type":"Microsoft.Dynamics.CRM.FileAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"FileType"},MaxSizeInKB:(B=t.maxSizeKb)!==null&&B!==void 0?B:10240};case"image":return{"@odata.type":"Microsoft.Dynamics.CRM.ImageAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"ImageType"},IsPrimaryImage:(L=t.isPrimaryImage)!==null&&L!==void 0?L:!1,MaxSizeInKB:(k=t.maxSizeKb)!==null&&k!==void 0?k:10240};case"autonumber":return{"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},FormatName:{Value:"Text"},MaxLength:(M=t.maxLength)!==null&&M!==void 0?M:100,AutoNumberFormat:(G=t.autoNumberFormat)!==null&&G!==void 0?G:""};default:throw new pe.InvalidArgumentError(`unsupported column type '${String(e)}'`)}}function C0(e,t,r){let i={"@odata.type":r?"Microsoft.Dynamics.CRM.MultiSelectPicklistAttributeMetadata":"Microsoft.Dynamics.CRM.PicklistAttributeMetadata",AttributeType:r?"Virtual":"Picklist",AttributeTypeName:{Value:r?"MultiSelectPicklistType":"PicklistType"}};if(e.globalChoiceMetadataId)return i["[email protected]"]=`/GlobalOptionSetDefinitions(${(0,J.normalizeGuid)(e.globalChoiceMetadataId,"globalChoiceMetadataId")})`,i;if(!e.options||e.options.length===0)throw new pe.InvalidArgumentError(`choice column '${e.schemaName}' requires at least one option (or a globalChoiceMetadataId)`);return i.OptionSet={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",IsGlobal:!1,OptionSetType:"Picklist",Options:e.options.map(a=>({Value:a.value,Label:Ie(a.label,t)}))},i}var Xc=new WeakMap;async function BR(e,t){var r,n;let i=(r=Xc.get(e))===null||r===void 0?void 0:r.get(t);if(i)return i;let a=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')${(0,J.odataQuery)([["$select","EntitySetName"]])}`,s=(n=(0,se.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.EntitySetName;if(!s)throw new pe.InvalidArgumentError(`could not resolve EntitySetName for '${t}'`);(0,J.assertODataName)(s,`server-derived EntitySetName for '${t}'`);let l=Xc.get(e);return l||(l=new Map,Xc.set(e,l)),l.set(t,s),s}Q.resolveEntitySetName=BR;async function $R(e,t){var r,n,i,a,o,s,l,u,c,d,p,f,m,g,y;let A=(r=t.languageCode)!==null&&r!==void 0?r:Er.DEFAULT_LCID,D=Zc(t.schemaName),F=(n=t.primaryColumnSchemaName)!==null&&n!==void 0?n:`${D}_Name`,_={"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},SchemaName:F,RequiredLevel:ao("None"),MaxLength:(i=t.primaryColumnMaxLength)!==null&&i!==void 0?i:100,FormatName:{Value:"Text"},DisplayName:Ie((a=t.primaryColumnDisplayName)!==null&&a!==void 0?a:"Name",A),IsPrimaryName:!0};t.primaryColumnAutoNumberFormat&&(_.AutoNumberFormat=t.primaryColumnAutoNumberFormat),t.columns&&I0(t.columns,"createTable");let q={"@odata.type":"Microsoft.Dynamics.CRM.EntityMetadata",SchemaName:t.schemaName,DisplayName:Ie(t.displayName,A),DisplayCollectionName:Ie((o=t.pluralName)!==null&&o!==void 0?o:S0(t.displayName),A),OwnershipType:(s=t.ownership)!==null&&s!==void 0?s:"UserOwned",IsActivity:!1,HasActivities:(l=t.hasActivities)!==null&&l!==void 0?l:!1,HasNotes:(u=t.hasNotes)!==null&&u!==void 0?u:!1,Attributes:[_,...((c=t.columns)!==null&&c!==void 0?c:[]).map(et=>ed(et,A))]};t.description&&(q.Description=Ie(t.description,A));let B="/EntityDefinitions",L=(0,se.ensureSuccess)(await e.post(B,q),e.apiUrl(B)),k=oo(L),M=`/EntityDefinitions(${k})`+(0,J.odataQuery)([["$select","LogicalName,EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute"]]),G=Math.max(1,Math.trunc((d=t.readBackAttempts)!==null&&d!==void 0?d:6)),V=Math.max(0,(p=t.readBackDelayMs)!==null&&p!==void 0?p:1e3),Ze;for(let et=1;et<=G;et+=1){let dt=await e.get(M);if(dt.status>=200&&dt.status<300){Ze=dt;break}dt.status!==404&&(0,se.ensureSuccess)(dt,e.apiUrl(M)),et<G&&V>0&&await new Promise(ue=>setTimeout(ue,V))}if(!Ze)throw new pe.SdkError("TABLE_METADATA_NOT_VISIBLE",`Table '${t.schemaName}' WAS CREATED (MetadataId ${k}) but its metadata was still not readable after ${G} attempt(s). Do NOT re-run the create \u2014 it will collide on the schema name. Re-read /EntityDefinitions(${k}) once the environment catches up, or raise 'readBackAttempts'.`);let ir=Ze.body;return{logicalName:(f=ir.LogicalName)!==null&&f!==void 0?f:t.schemaName.toLowerCase(),metadataId:k,entitySetName:(m=ir.EntitySetName)!==null&&m!==void 0?m:"",primaryIdAttribute:(g=ir.PrimaryIdAttribute)!==null&&g!==void 0?g:`${t.schemaName.toLowerCase()}id`,primaryNameAttribute:(y=ir.PrimaryNameAttribute)!==null&&y!==void 0?y:F.toLowerCase()}}Q.createTable=$R;function ed(e,t){var r,n;let i=(r=e.languageCode)!==null&&r!==void 0?r:t,a={...UR(e.type,e,i),SchemaName:e.schemaName,RequiredLevel:ao((n=e.required)!==null&&n!==void 0?n:"None"),DisplayName:Ie(e.displayName,i)};return e.description&&(a.Description=Ie(e.description,i)),e.sourceType&&e.sourceType!=="Simple"&&(a.SourceType=e.sourceType==="Rollup"?2:1,e.formulaDefinition&&(a.FormulaDefinition=e.formulaDefinition)),N0(a,e),a}function N0(e,t){t.isValidForCreate!==void 0&&(e.IsValidForCreate=t.isValidForCreate),t.isValidForUpdate!==void 0&&(e.IsValidForUpdate=t.isValidForUpdate),t.isValidForRead!==void 0&&(e.IsValidForRead=t.isValidForRead)}async function qR(e,t,r){var n;let i=ed(r,(n=r.languageCode)!==null&&n!==void 0?n:Er.DEFAULT_LCID),a=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Attributes`,o=(0,se.ensureSuccess)(await e.post(a,i),e.apiUrl(a)),s={logicalName:r.schemaName.toLowerCase(),metadataId:oo(o)};if(r.visualization&&r.visualization!=="None")try{await P0(e,t,s.logicalName,s.metadataId,r.visualization)}catch(l){let u=new pe.SdkError("COLUMN_VISUALIZATION_BIND_FAILED",`Column '${s.logicalName}' on '${t}' was created, but binding its '${r.visualization}' grid visualization failed; the column exists WITHOUT a visualization. Retry with setColumnVisualization('${t}', '${s.logicalName}', '${r.visualization}'). Cause: ${l instanceof Error?l.message:String(l)}`);throw u.cause=l,u}return s}Q.createColumn=qR;var xi="/controlconfigurations",D0="CustomRenderersConfiguration",Yc={RadialDial:"c3d4e5f6-a7b8-9012-cdef-345678901234",LineChart:"a1b2c3d4-e5f6-7890-abcd-ef1234567890",HeatMap:"e7f8a9b0-c1d2-4e3f-5a6b-7c8d9e0f1a2b",StarRating:"b5e4c3d2-f1a0-4e2b-8a7c-9d3f5c1e6b04"};function I0(e,t){let r=e.find(n=>n.visualization&&n.visualization!=="None");if(r)throw new pe.InvalidArgumentError(`${t}: setting 'visualization' on an inline column ('${r.schemaName}') is not supported \u2014 the attribute metadata and its control-configuration row are separate writes. Create the column, then call setColumnVisualization; or use the single-column createColumn.`)}function _0(e){return JSON.stringify({type:Yc[e]})}function VR(e){if(!e)return"None";let t;try{t=JSON.parse(e)}catch{return"None"}let r=t?.type,n=Object.keys(Yc).find(i=>Yc[i]===r);return n??"None"}async function T0(e,t,r){var n,i;let a=`entitylogicalname eq '${(0,J.odataLiteral)(t)}' and Attribute/logicalname eq '${(0,J.odataLiteral)(r)}'`,o=`${xi}${(0,J.odataQuery)([["$select","name,uniquename,metadatajson"],["$expand","Attribute($select=name,logicalname)"],["$filter",a]])}`,l=(i=(n=(0,se.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[],u=r.toLowerCase();return l.filter(c=>{var d,p;return((p=(d=c.Attribute)===null||d===void 0?void 0:d.logicalname)===null||p===void 0?void 0:p.toLowerCase())===u})}async function GR(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Attributes(LogicalName='${(0,J.odataPathLiteral)(r)}')${(0,J.odataQuery)([["$select","MetadataId"]])}`,o=(n=(0,se.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||n===void 0?void 0:n.MetadataId;if(!o)throw new pe.InvalidArgumentError(`cannot resolve column '${r}' on '${t}' to set its visualization`);return(0,J.normalizeGuid)(o,"MetadataId")}async function P0(e,t,r,n,i){let a={name:D0,uniquename:`msdyn_${t}_${r}_customrenderers`,metadatajson:_0(i),"[email protected]":`/attributes(${(0,J.normalizeGuid)(n,"MetadataId")})`,entitylogicalname:t};(0,se.ensureSuccess)(await e.post(xi,a),e.apiUrl(xi))}async function zR(e,t,r){var n;let i=await T0(e,t,r);return VR((n=i[0])===null||n===void 0?void 0:n.metadatajson)}Q.getColumnVisualization=zR;async function WR(e,t,r,n){let a=(await T0(e,t,r)).map(u=>u.controlconfigurationid).filter(u=>!!u);if(n==="None"){for(let u of a){let c=`${xi}(${(0,J.normalizeGuid)(u,"controlconfigurationid")})`;(0,se.ensureSuccess)(await e.delete(c),e.apiUrl(c))}return}let[o,...s]=a,l=await GR(e,t,r);if(o){let u=`${xi}(${(0,J.normalizeGuid)(o,"controlconfigurationid")})`,c={name:D0,metadatajson:_0(n),"[email protected]":`/attributes(${l})`,entitylogicalname:t};(0,se.ensureSuccess)(await e.patch(u,c),e.apiUrl(u))}else await P0(e,t,r,l,n);for(let u of s){let c=`${xi}(${(0,J.normalizeGuid)(u,"controlconfigurationid")})`;(0,se.ensureSuccess)(await e.delete(c),e.apiUrl(c))}}Q.setColumnVisualization=WR;async function HR(e,t,r){if(r.length===0)return;if(I0(r,"createColumns"),!e.supportsAtomicBatch)throw new pe.InvalidArgumentError(`createColumns writes ${r.length} columns on '${t}' as ONE atomic change set, which needs a verbatim request body. Implement HttpClient.postRaw, or call createColumn per column and accept that a failure can leave the table partly extended.`);let n=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Attributes`;await(0,LR.postChangeSet)(e,r.map(i=>{var a;return{method:"POST",path:n,body:ed(i,(a=i.languageCode)!==null&&a!==void 0?a:Er.DEFAULT_LCID)}}),`${r.length} column(s) on '${t}'`)}Q.createColumns=HR;async function jR(e,t,r){var n,i,a,o;let s=(n=r.languageCode)!==null&&n!==void 0?n:Er.DEFAULT_LCID,l=Zc(r.schemaName),u=(i=r.accountRelationshipName)!==null&&i!==void 0?i:`${l}_${t}_account`,c=(a=r.contactRelationshipName)!==null&&a!==void 0?a:`${l}_${t}_contact`,d={Lookup:{"@odata.type":"Microsoft.Dynamics.CRM.ComplexLookupAttributeMetadata",SchemaName:r.schemaName,DisplayName:Ie(r.displayName,s),RequiredLevel:ao((o=r.required)!==null&&o!==void 0?o:"None"),Targets:["account","contact"]},OneToManyRelationships:[{"@odata.type":"Microsoft.Dynamics.CRM.ComplexOneToManyRelationshipMetadata",SchemaName:u,ReferencedEntity:"account",ReferencingEntity:t},{"@odata.type":"Microsoft.Dynamics.CRM.ComplexOneToManyRelationshipMetadata",SchemaName:c,ReferencedEntity:"contact",ReferencingEntity:t}]};return(0,se.ensureSuccess)(await e.post("/CreateCustomerRelationships",d),e.apiUrl("/CreateCustomerRelationships")),{logicalName:r.schemaName.toLowerCase(),metadataId:""}}Q.createCustomerColumn=jR;async function JR(e,t,r){var n,i,a,o,s;let l=(n=r.languageCode)!==null&&n!==void 0?n:Er.DEFAULT_LCID,u={EntityLogicalName:t,AttributeLogicalName:"statuscode",Label:Ie(r.label,l),StateCode:(i=r.stateCode)!==null&&i!==void 0?i:0};typeof r.value=="number"&&(u.Value=r.value),r.color&&(u.Color=r.color);let c=(0,se.ensureSuccess)(await e.post("/InsertStatusValue",u),e.apiUrl("/InsertStatusValue"));return Number((s=(o=(a=c.body)===null||a===void 0?void 0:a.NewOptionValue)!==null&&o!==void 0?o:r.value)!==null&&s!==void 0?s:0)}Q.insertStatusValue=JR;async function QR(e,t){var r,n,i,a,o;let s=(r=t.languageCode)!==null&&r!==void 0?r:Er.DEFAULT_LCID,l,u;if(t.type==="OneToMany"){if(!t.referencedEntity||!t.referencingEntity)throw new pe.InvalidArgumentError("OneToMany relationship requires referencedEntity and referencingEntity");let p=(n=t.lookupSchemaName)!==null&&n!==void 0?n:`${Zc(t.schemaName)}_${t.referencedEntity}Id`;u=p.toLowerCase(),l={"@odata.type":"Microsoft.Dynamics.CRM.OneToManyRelationshipMetadata",SchemaName:t.schemaName,ReferencedEntity:t.referencedEntity,ReferencingEntity:t.referencingEntity,Lookup:{"@odata.type":"Microsoft.Dynamics.CRM.LookupAttributeMetadata",AttributeType:"Lookup",AttributeTypeName:{Value:"LookupType"},SchemaName:p,RequiredLevel:ao((i=t.lookupRequired)!==null&&i!==void 0?i:"None"),DisplayName:Ie((a=t.lookupDisplayName)!==null&&a!==void 0?a:t.referencedEntity,s)}}}else{if(!t.entity1||!t.entity2)throw new pe.InvalidArgumentError("ManyToMany relationship requires entity1 and entity2");l={"@odata.type":"Microsoft.Dynamics.CRM.ManyToManyRelationshipMetadata",SchemaName:t.schemaName,IntersectEntityName:(o=t.intersectEntityName)!==null&&o!==void 0?o:t.schemaName.toLowerCase(),Entity1LogicalName:t.entity1,Entity2LogicalName:t.entity2}}let c="/RelationshipDefinitions",d=(0,se.ensureSuccess)(await e.post(c,l),e.apiUrl(c));return{schemaName:t.schemaName,metadataId:oo(d),lookupLogicalName:u}}Q.createRelationship=QR;async function KR(e,t){let r=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')`;(0,se.ensureSuccess)(await e.delete(r),e.apiUrl(r))}Q.deleteTable=KR;async function XR(e,t,r,n){var i,a;let o=(i=n.languageCode)!==null&&i!==void 0?i:Er.DEFAULT_LCID,s=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Attributes`,l=`${s}(LogicalName='${(0,J.odataPathLiteral)(r)}')${(0,J.odataQuery)([["$select","MetadataId,AttributeType"]])}`,c=(0,se.ensureSuccess)(await e.get(l),e.apiUrl(l)).body,d=kR[(a=c.AttributeType)!==null&&a!==void 0?a:""];if(!c.MetadataId||!d)throw new pe.InvalidArgumentError(`cannot update column '${r}' on '${t}' (type '${c.AttributeType}' not supported)`);let p=(0,J.normalizeGuid)(c.MetadataId,"MetadataId"),f=`${s}(${p})/${d}`,m=(0,se.ensureSuccess)(await e.get(f),e.apiUrl(f)).body;for(let y of Object.keys(m))y.startsWith("@odata.")&&delete m[y];if(m["@odata.type"]=d,n.displayName!==void 0&&(m.DisplayName=Ie(n.displayName,o)),n.description!==void 0&&(m.Description=Ie(n.description,o)),n.required!==void 0&&(m.RequiredLevel=ao(n.required)),n.maxLength!==void 0&&(m.MaxLength=n.maxLength),n.autoNumberFormat!==void 0&&(m.AutoNumberFormat=n.autoNumberFormat),n.defaultValue!==void 0&&c.AttributeType!=="Boolean")throw new pe.InvalidArgumentError(`updateColumn: 'defaultValue' applies to Boolean columns, but '${r}' on '${t}' is of type '${c.AttributeType}'.`);if(n.integerFormat!==void 0&&c.AttributeType!=="Integer")throw new pe.InvalidArgumentError(`updateColumn: 'integerFormat' applies to Integer columns, but '${r}' on '${t}' is of type '${c.AttributeType}'.`);n.defaultValue!==void 0&&(m.DefaultValue=n.defaultValue),n.integerFormat!==void 0&&(m.Format=n.integerFormat),N0(m,n);let g=`${s}(${p})`;(0,se.ensureSuccess)(await e.put(g,m,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(g))}Q.updateColumn=XR;async function YR(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Attributes`,a=`${i}(LogicalName='${(0,J.odataPathLiteral)(r)}')${(0,J.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,se.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new pe.InvalidArgumentError(`column '${r}' not found on '${t}'`);let l=`${i}(${(0,J.normalizeGuid)(s,"MetadataId")})`;(0,se.ensureSuccess)(await e.delete(l),e.apiUrl(l))}Q.deleteColumn=YR;async function ZR(e,t){var r,n,i;let a=`/RelationshipDefinitions${(0,J.odataQuery)([["$filter",`SchemaName eq '${(0,J.odataLiteral)(t)}'`],["$select","MetadataId"]])}`,s=(i=(n=(r=(0,se.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||r===void 0?void 0:r.value)===null||n===void 0?void 0:n[0])===null||i===void 0?void 0:i.MetadataId;if(!s)throw new pe.InvalidArgumentError(`relationship '${t}' not found`);let l=`/RelationshipDefinitions(${(0,J.normalizeGuid)(s,"MetadataId")})`;(0,se.ensureSuccess)(await e.delete(l),e.apiUrl(l))}Q.deleteRelationship=ZR;async function E0(e,t){var r;let n=`/GlobalOptionSetDefinitions(Name='${(0,J.odataPathLiteral)(t)}')${(0,J.odataQuery)([["$select","MetadataId"]])}`,i=await e.get(n);if(i.status===404)return;let o=(r=(0,se.ensureSuccess)(i,e.apiUrl(n)).body)===null||r===void 0?void 0:r.MetadataId;return o?(0,J.normalizeGuid)(o,"MetadataId"):void 0}async function eF(e,t){var r;let n=t.name.toLowerCase(),i=await E0(e,n);if(i)return{name:n,metadataId:i};let a=(r=t.languageCode)!==null&&r!==void 0?r:Er.DEFAULT_LCID,o={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",Name:n,DisplayName:Ie(t.displayName,a),IsGlobal:!0,OptionSetType:"Picklist",Options:t.options.map(l=>({Value:l.value,Label:Ie(l.label,a)}))};t.description&&(o.Description=Ie(t.description,a));let s="/GlobalOptionSetDefinitions";try{let l=(0,se.ensureSuccess)(await e.post(s,o),e.apiUrl(s));return{name:n,metadataId:oo(l)}}catch(l){let u;try{u=await E0(e,n)}catch{u=void 0}if(u)return{name:n,metadataId:u};throw l}}Q.createGlobalOptionSet=eF;async function tF(e,t){let r=`/GlobalOptionSetDefinitions(Name='${(0,J.odataPathLiteral)(t.toLowerCase())}')`;(0,se.ensureSuccess)(await e.delete(r),e.apiUrl(r))}Q.deleteGlobalOptionSet=tF;async function rF(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:Er.DEFAULT_LCID,a={"@odata.type":"Microsoft.Dynamics.CRM.EntityKeyMetadata",SchemaName:r.schemaName,DisplayName:Ie(r.displayName,i),KeyAttributes:r.keyAttributes},o=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Keys`,s=(0,se.ensureSuccess)(await e.post(o,a),e.apiUrl(o));return{logicalName:r.schemaName.toLowerCase(),metadataId:oo(s)}}Q.createAlternateKey=rF;async function nF(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Keys`,a=`${i}(LogicalName='${(0,J.odataPathLiteral)(r.toLowerCase())}')${(0,J.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,se.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new pe.InvalidArgumentError(`alternate key '${r}' not found on '${t}'`);let l=`${i}(${(0,J.normalizeGuid)(s,"MetadataId")})`;(0,se.ensureSuccess)(await e.delete(l),e.apiUrl(l))}Q.deleteAlternateKey=nF;async function iF(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:Er.DEFAULT_LCID,a=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')`,s=(0,se.ensureSuccess)(await e.get(a),e.apiUrl(a)).body,l=s.MetadataId;if(!l)throw new pe.InvalidArgumentError(`table '${t}' not found`);let u=(0,J.normalizeGuid)(l,"MetadataId");for(let d of Object.keys(s))d.startsWith("@odata.")&&delete s[d];s["@odata.type"]="Microsoft.Dynamics.CRM.EntityMetadata",r.displayName!==void 0&&(s.DisplayName=Ie(r.displayName,i)),r.pluralName!==void 0&&(s.DisplayCollectionName=Ie(r.pluralName,i)),r.description!==void 0&&(s.Description=Ie(r.description,i)),r.auditEnabled!==void 0&&A0(s,"IsAuditEnabled",r.auditEnabled),r.duplicateDetectionEnabled!==void 0&&A0(s,"IsDuplicateDetectionEnabled",r.duplicateDetectionEnabled),r.changeTrackingEnabled!==void 0&&(s.ChangeTrackingEnabled=r.changeTrackingEnabled),r.quickCreateEnabled!==void 0&&(s.IsQuickCreateEnabled=r.quickCreateEnabled),r.iconVectorName!==void 0&&(s.IconVectorName=r.iconVectorName),r.iconSmallName!==void 0&&(s.IconSmallName=r.iconSmallName),r.iconMediumName!==void 0&&(s.IconMediumName=r.iconMediumName),r.iconLargeName!==void 0&&(s.IconLargeName=r.iconLargeName);let c=`/EntityDefinitions(${u})`;(0,se.ensureSuccess)(await e.put(c,s,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(c))}Q.updateTable=iF});var In=v(wt=>{"use strict";Object.defineProperty(wt,"__esModule",{value:!0});wt.rebuildRaw=wt.assembleChildren=wt.spliceChildren=wt.mergeAttrs=wt.rawFromNode=wt.emptyBag=void 0;var Dn=te(),O0=1e6,Gs=512;function aF(){return{a:[],c:[]}}wt.emptyBag=aF;function R0(e,t=0){if(t>Gs)throw new Dn.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${Gs}`);return{n:e.getNodeName(),a:e.getAllProperties().map(r=>[r.key,r.value]),c:e.getAllChildren().map(r=>R0(r,t+1))}}wt.rawFromNode=R0;function oF(e,t,r=[]){let n=new Map;for(let[s,l]of t)n.set(s,l);let i=new Set(r.filter(s=>!n.has(s))),a=new Set,o=[];for(let[s,l]of e)i.has(s)||(n.has(s)?o.push([s,n.get(s)]):o.push([s,l]),a.add(s));for(let[s,l]of t)a.has(s)||(o.push([s,l]),a.add(s));return o}wt.mergeAttrs=oF;function Vs(e,t){let r=new Set;for(let s of e){let l=s.i;if(!Number.isInteger(l)||l<0||l>O0)throw new Dn.InvalidArgumentError(`Bag child index must be an integer in [0, ${O0}] (got ${String(l)})`);if(r.has(l))throw new Dn.InvalidArgumentError(`Duplicate bag child index ${l}`);r.add(l)}let n=[...e].sort((s,l)=>s.i-l.i),i=[],a=0,o=0;for(let s of n){for(;o<s.i&&a<t.length;)i.push(t[a]),a+=1,o+=1;o<s.i&&(o=s.i),i.push(s.node),o+=1}for(;a<t.length;)i.push(t[a]),a+=1;return i}wt.spliceChildren=Vs;function sF(e,t){if(e.w){let r={n:e.w.n,a:e.w.a.map(n=>[n[0],n[1]]),c:Vs(e.w.c,t)};return Vs(e.c,[r])}return Vs(e.c,t)}wt.assembleChildren=sF;function F0(e,t,r,n=0){if(n>Gs)throw new Dn.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${Gs}`);lF(e,n);let i=t.make(e.n,r);for(let[a,o]of e.a)t.setProp(i,a,o);for(let a of e.c)t.addChild(i,F0(a,t,i,n+1));return i}wt.rebuildRaw=F0;function lF(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Dn.InvalidArgumentError(`Malformed hybrid node at depth ${t}: expected a JSON object`);let r=e;if(typeof r.n!="string")throw new Dn.InvalidArgumentError(`Malformed hybrid node at depth ${t}: 'n' (tag name) must be a string`);if(!Array.isArray(r.a)||!Array.isArray(r.c))throw new Dn.InvalidArgumentError(`Malformed hybrid node '${r.n}': 'a' and 'c' must be arrays`);for(let n of r.a)if(!Array.isArray(n)||n.length!==2||typeof n[0]!="string"||typeof n[1]!="string")throw new Dn.InvalidArgumentError(`Malformed hybrid node '${r.n}': each attribute must be a [string, string] pair`)}});var Li=v(Jr=>{"use strict";function uF(e,t,r){if(r===void 0&&(r=Array.prototype),e&&typeof r.find=="function")return r.find.call(e,t);for(var n=0;n<e.length;n++)if(Object.prototype.hasOwnProperty.call(e,n)){var i=e[n];if(t.call(void 0,i,n,e))return i}}function rd(e,t){return t===void 0&&(t=Object),t&&typeof t.freeze=="function"?t.freeze(e):e}function cF(e,t){if(e===null||typeof e!="object")throw new TypeError("target is not an object");for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e}var x0=rd({HTML:"text/html",isHTML:function(e){return e===x0.HTML},XML_APPLICATION:"application/xml",XML_TEXT:"text/xml",XML_XHTML_APPLICATION:"application/xhtml+xml",XML_SVG_IMAGE:"image/svg+xml"}),L0=rd({HTML:"http://www.w3.org/1999/xhtml",isHTML:function(e){return e===L0.HTML},SVG:"http://www.w3.org/2000/svg",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"}),zs=/[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,td=new RegExp("[\\-\\.0-9"+zs.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),dF=new RegExp("^"+zs.source+td.source+"*(?::"+zs.source+td.source+"*)?$");Jr.assign=cF;Jr.find=uF;Jr.freeze=rd;Jr.MIME_TYPE=x0;Jr.NAMESPACE=L0;Jr.nameStartChar=zs;Jr.nameChar=td;Jr.tagNamePattern=dF});var md=v(Yr=>{var nd=Li(),Sr=nd.find,lo=nd.NAMESPACE,ki=nd.tagNamePattern;function pF(e){return e!==""}function fF(e){return e?e.split(/[\t\n\f\r ]+/).filter(pF):[]}function mF(e,t){return e.hasOwnProperty(t)||(e[t]=!0),e}function k0(e){if(!e)return[];var t=fF(e);return Object.keys(t.reduce(mF,{}))}function hF(e){return function(t){return e&&e.indexOf(t)!==-1}}function co(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function Ct(e,t){var r=e.prototype;if(!(r instanceof t)){let i=function(){};var n=i;i.prototype=t.prototype,i=new i,co(r,i),e.prototype=r=i}r.constructor!=e&&(typeof e!="function"&&console.error("unknown Class:"+e),r.constructor=e)}var Et={},Vt=Et.ELEMENT_NODE=1,Mi=Et.ATTRIBUTE_NODE=2,so=Et.TEXT_NODE=3,z0=Et.CDATA_SECTION_NODE=4,W0=Et.ENTITY_REFERENCE_NODE=5,gF=Et.ENTITY_NODE=6,id=Et.PROCESSING_INSTRUCTION_NODE=7,ad=Et.COMMENT_NODE=8,H0=Et.DOCUMENT_NODE=9,j0=Et.DOCUMENT_TYPE_NODE=10,Qr=Et.DOCUMENT_FRAGMENT_NODE=11,vF=Et.NOTATION_NODE=12,tt={},Ve={},oW=tt.INDEX_SIZE_ERR=(Ve[1]="Index size error",1),sW=tt.DOMSTRING_SIZE_ERR=(Ve[2]="DOMString size error",2),At=tt.HIERARCHY_REQUEST_ERR=(Ve[3]="Hierarchy request error",3),lW=tt.WRONG_DOCUMENT_ERR=(Ve[4]="Wrong document",4),M0=tt.INVALID_CHARACTER_ERR=(Ve[5]="Invalid character",5),uW=tt.NO_DATA_ALLOWED_ERR=(Ve[6]="No data allowed",6),cW=tt.NO_MODIFICATION_ALLOWED_ERR=(Ve[7]="No modification allowed",7),J0=tt.NOT_FOUND_ERR=(Ve[8]="Not found",8),dW=tt.NOT_SUPPORTED_ERR=(Ve[9]="Not supported",9),U0=tt.INUSE_ATTRIBUTE_ERR=(Ve[10]="Attribute in use",10),or=tt.INVALID_STATE_ERR=(Ve[11]="Invalid state",11),pW=tt.SYNTAX_ERR=(Ve[12]="Syntax error",12),fW=tt.INVALID_MODIFICATION_ERR=(Ve[13]="Invalid modification",13),mW=tt.NAMESPACE_ERR=(Ve[14]="Invalid namespace",14),hW=tt.INVALID_ACCESS_ERR=(Ve[15]="Invalid access",15);function Z(e,t){if(t instanceof Error)var r=t;else r=this,Error.call(this,Ve[e]),this.message=Ve[e],Error.captureStackTrace&&Error.captureStackTrace(this,Z);return r.code=e,t&&(this.message=this.message+": "+t),r}Z.prototype=Error.prototype;co(tt,Z);function Kr(){}Kr.prototype={length:0,item:function(e){return e>=0&&e<this.length?this[e]:null},toString:function(e,t,r){for(var n=!!r&&!!r.requireWellFormed,i=[],a=0;a<this.length;a++)fd(this[a],i,e,t,null,n);return i.join("")},filter:function(e){return Array.prototype.filter.call(this,e)},indexOf:function(e){return Array.prototype.indexOf.call(this,e)}};function Ui(e,t){this._node=e,this._refresh=t,od(this)}function od(e){var t=e._node._inc||e._node.ownerDocument._inc;if(e._inc!==t){var r=e._refresh(e._node);if(sv(e,"length",r.length),!e.$$length||r.length<e.$$length)for(var n=r.length;n in e;n++)Object.prototype.hasOwnProperty.call(e,n)&&delete e[n];co(r,e),e._inc=t}}Ui.prototype.item=function(e){return od(this),this[e]||null};Ct(Ui,Kr);function Hs(){this._nameIndex=Object.create(null)}function Q0(e,t){for(var r=e.length;r--;)if(e[r]===t)return r}function yF(e,t){e._nameIndex[t.nodeName]=t}function K0(e,t){e._nameIndex[t.nodeName]===t&&delete e._nameIndex[t.nodeName]}function B0(e,t,r,n){if(n?(t[Q0(t,n)]=r,K0(t,n)):t[t.length++]=r,yF(t,r),e){r.ownerElement=e;var i=e.ownerDocument;i&&(n&&Z0(i,e,n),bF(i,e,r))}}function $0(e,t,r){var n=Q0(t,r);if(n>=0){for(var i=t.length-1;n<i;)t[n]=t[++n];if(t.length=i,K0(t,r),e){var a=e.ownerDocument;a&&(Z0(a,e,r),r.ownerElement=null)}}else throw new Z(J0,new Error(e.tagName+"@"+r))}Hs.prototype={length:0,item:Kr.prototype.item,getNamedItem:function(e){for(var t=this.length;t--;){var r=this[t];if(r.nodeName==e)return r}},setNamedItem:function(e){var t=e.ownerElement;if(t&&t!=this._ownerElement)throw new Z(U0);var r=this._nameIndex[e.nodeName];return B0(this._ownerElement,this,e,r),r},setNamedItemNS:function(e){var t=e.ownerElement,r;if(t&&t!=this._ownerElement)throw new Z(U0);return r=this.getNamedItemNS(e.namespaceURI,e.localName),B0(this._ownerElement,this,e,r),r},removeNamedItem:function(e){var t=this.getNamedItem(e);return $0(this._ownerElement,this,t),t},removeNamedItemNS:function(e,t){var r=this.getNamedItemNS(e,t);return $0(this._ownerElement,this,r),r},getNamedItemNS:function(e,t){for(var r=this.length;r--;){var n=this[r];if(n.localName==t&&n.namespaceURI==e)return n}return null}};function X0(){}X0.prototype={hasFeature:function(e,t){return!0},createDocument:function(e,t,r){var n=new po;if(n.implementation=this,n.childNodes=new Kr,n.doctype=r||null,r&&n.appendChild(r),t){var i=n.createElementNS(e,t);n.appendChild(i)}return n},createDocumentType:function(e,t,r){var n=new Xs;return n.name=e,n.nodeName=e,n.publicId=t||"",n.systemId=r||"",n}};function ce(){}ce.prototype={firstChild:null,lastChild:null,previousSibling:null,nextSibling:null,attributes:null,parentNode:null,childNodes:null,ownerDocument:null,nodeValue:null,namespaceURI:null,prefix:null,localName:null,insertBefore:function(e,t){return Js(this,e,t)},replaceChild:function(e,t){Js(this,e,t,tv),t&&this.removeChild(t)},removeChild:function(e){return ev(this,e)},appendChild:function(e){return this.insertBefore(e,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(e){return ov(this.ownerDocument||this,this,e)},normalize:function(){qe(this,null,{enter:function(e){for(var t=e.firstChild;t;){var r=t.nextSibling;if(r!==null&&r.nodeType===so&&t.nodeType===so){for(var n=[],i=r;i!==null&&i.nodeType===so;)n.push(i.data),i=i.nextSibling;for(var a=t.nextSibling;a!==i;){var o=a.nextSibling;a.parentNode=null,a.previousSibling=null,a.nextSibling=null,a=o}t.nextSibling=i,i!==null?i.previousSibling=t:e.lastChild=t,t.appendData(n.join("")),Ks(e.ownerDocument,e),t=i}else t=r}return!0}})},isSupported:function(e,t){return this.ownerDocument.implementation.hasFeature(e,t)},hasAttributes:function(){return this.attributes.length>0},lookupPrefix:function(e){for(var t=this;t;){var r=t._nsMap;if(r){for(var n in r)if(Object.prototype.hasOwnProperty.call(r,n)&&r[n]===e)return n}t=t.nodeType==Mi?t.ownerDocument:t.parentNode}return null},lookupNamespaceURI:function(e){for(var t=this;t;){var r=t._nsMap;if(r&&Object.prototype.hasOwnProperty.call(r,e))return r[e];t=t.nodeType==Mi?t.ownerDocument:t.parentNode}return null},isDefaultNamespace:function(e){var t=this.lookupPrefix(e);return t==null}};function Y0(e){return e=="<"&&"<"||e==">"&&">"||e=="&"&&"&"||e=='"'&&"""||"&#"+e.charCodeAt()+";"}co(Et,ce);co(Et,ce.prototype);function js(e,t){return qe(e,null,{enter:function(r){return t(r)?qe.STOP:!0}})===qe.STOP}function qe(e,t,r){for(var n=[{node:e,context:t,phase:qe.ENTER}];n.length>0;){var i=n.pop();if(i.phase===qe.ENTER){var a=r.enter(i.node,i.context);if(a===qe.STOP)return qe.STOP;if(n.push({node:i.node,context:a,phase:qe.EXIT}),a==null)continue;for(var o=i.node.lastChild;o;)n.push({node:o,context:a,phase:qe.ENTER}),o=o.previousSibling}else r.exit&&r.exit(i.node,i.context)}}qe.STOP=Symbol("walkDOM.STOP");qe.ENTER=0;qe.EXIT=1;function po(){this.ownerDocument=this}function bF(e,t,r){e&&e._inc++;var n=r.namespaceURI;n===lo.XMLNS&&(t._nsMap[r.prefix?r.localName:""]=r.value)}function Z0(e,t,r,n){e&&e._inc++;var i=r.namespaceURI;i===lo.XMLNS&&delete t._nsMap[r.prefix?r.localName:""]}function Ks(e,t,r){if(e&&e._inc){e._inc++;var n=t.childNodes;if(r)n[n.length++]=r;else{for(var i=t.firstChild,a=0;i;)n[a++]=i,i=i.nextSibling;n.length=a,delete n[n.length]}}}function ev(e,t){var r=t.previousSibling,n=t.nextSibling;return r?r.nextSibling=n:e.firstChild=n,n?n.previousSibling=r:e.lastChild=r,t.parentNode=null,t.previousSibling=null,t.nextSibling=null,Ks(e.ownerDocument,e),t}function wF(e){return e&&(e.nodeType===ce.DOCUMENT_NODE||e.nodeType===ce.DOCUMENT_FRAGMENT_NODE||e.nodeType===ce.ELEMENT_NODE)}function AF(e){return e&&(Nr(e)||sd(e)||Xr(e)||e.nodeType===ce.DOCUMENT_FRAGMENT_NODE||e.nodeType===ce.COMMENT_NODE||e.nodeType===ce.PROCESSING_INSTRUCTION_NODE)}function Xr(e){return e&&e.nodeType===ce.DOCUMENT_TYPE_NODE}function Nr(e){return e&&e.nodeType===ce.ELEMENT_NODE}function sd(e){return e&&e.nodeType===ce.TEXT_NODE}function q0(e,t){var r=e.childNodes||[];if(Sr(r,Nr)||Xr(t))return!1;var n=Sr(r,Xr);return!(t&&n&&r.indexOf(n)>r.indexOf(t))}function V0(e,t){var r=e.childNodes||[];function n(a){return Nr(a)&&a!==t}if(Sr(r,n))return!1;var i=Sr(r,Xr);return!(t&&i&&r.indexOf(i)>r.indexOf(t))}function CF(e,t,r){if(!wF(e))throw new Z(At,"Unexpected parent node type "+e.nodeType);if(r&&r.parentNode!==e)throw new Z(J0,"child not in parent");if(!AF(t)||Xr(t)&&e.nodeType!==ce.DOCUMENT_NODE)throw new Z(At,"Unexpected node type "+t.nodeType+" for parent node type "+e.nodeType)}function EF(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===ce.DOCUMENT_FRAGMENT_NODE){var a=i.filter(Nr);if(a.length>1||Sr(i,sd))throw new Z(At,"More than one element or text in fragment");if(a.length===1&&!q0(e,r))throw new Z(At,"Element in fragment can not be inserted before doctype")}if(Nr(t)&&!q0(e,r))throw new Z(At,"Only one element can be added and only after doctype");if(Xr(t)){if(Sr(n,Xr))throw new Z(At,"Only one doctype is allowed");var o=Sr(n,Nr);if(r&&n.indexOf(o)<n.indexOf(r))throw new Z(At,"Doctype can only be inserted before an element");if(!r&&o)throw new Z(At,"Doctype can not be appended since element is present")}}function tv(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===ce.DOCUMENT_FRAGMENT_NODE){var a=i.filter(Nr);if(a.length>1||Sr(i,sd))throw new Z(At,"More than one element or text in fragment");if(a.length===1&&!V0(e,r))throw new Z(At,"Element in fragment can not be inserted before doctype")}if(Nr(t)&&!V0(e,r))throw new Z(At,"Only one element can be added and only after doctype");if(Xr(t)){let l=function(u){return Xr(u)&&u!==r};var s=l;if(Sr(n,l))throw new Z(At,"Only one doctype is allowed");var o=Sr(n,Nr);if(r&&n.indexOf(o)<n.indexOf(r))throw new Z(At,"Doctype can only be inserted before an element")}}function Js(e,t,r,n){CF(e,t,r),e.nodeType===ce.DOCUMENT_NODE&&(n||EF)(e,t,r);var i=t.parentNode;if(i&&i.removeChild(t),t.nodeType===Qr){var a=t.firstChild;if(a==null)return t;var o=t.lastChild}else a=o=t;var s=r?r.previousSibling:e.lastChild;a.previousSibling=s,o.nextSibling=r,s?s.nextSibling=a:e.firstChild=a,r==null?e.lastChild=o:r.previousSibling=o;do{a.parentNode=e;var l=e.ownerDocument||e;uo(a,l)}while(a!==o&&(a=a.nextSibling));return Ks(e.ownerDocument||e,e),t.nodeType==Qr&&(t.firstChild=t.lastChild=null),t}function uo(e,t){if(e.ownerDocument!==t){if(e.ownerDocument=t,e.nodeType===Vt&&e.attributes)for(var r=0;r<e.attributes.length;r++){var n=e.attributes.item(r);n&&(n.ownerDocument=t)}for(var i=e.firstChild;i;)uo(i,t),i=i.nextSibling}}function SF(e,t){t.parentNode&&t.parentNode.removeChild(t),t.parentNode=e,t.previousSibling=e.lastChild,t.nextSibling=null,t.previousSibling?t.previousSibling.nextSibling=t:e.firstChild=t,e.lastChild=t,Ks(e.ownerDocument,e,t);var r=e.ownerDocument||e;return uo(t,r),t}po.prototype={nodeName:"#document",nodeType:H0,doctype:null,documentElement:null,_inc:1,insertBefore:function(e,t){if(e.nodeType==Qr){for(var r=e.firstChild;r;){var n=r.nextSibling;this.insertBefore(r,t),r=n}return e}return Js(this,e,t),uo(e,this),this.documentElement===null&&e.nodeType===Vt&&(this.documentElement=e),e},removeChild:function(e){return this.documentElement==e&&(this.documentElement=null),ev(this,e)},replaceChild:function(e,t){Js(this,e,t,tv),uo(e,this),t&&this.removeChild(t),Nr(e)&&(this.documentElement=e)},importNode:function(e,t){return NF(this,e,t)},getElementById:function(e){var t=null;return js(this.documentElement,function(r){if(r.nodeType==Vt&&r.getAttribute("id")==e)return t=r,!0}),t},getElementsByClassName:function(e){var t=k0(e);return new Ui(this,function(r){var n=[];return t.length>0&&js(r.documentElement,function(i){if(i!==r&&i.nodeType===Vt){var a=i.getAttribute("class");if(a){var o=e===a;if(!o){var s=k0(a);o=t.every(hF(s))}o&&n.push(i)}}}),n})},createElement:function(e){var t=new ti;t.ownerDocument=this,t.nodeName=e,t.tagName=e,t.localName=e,t.childNodes=new Kr;var r=t.attributes=new Hs;return r._ownerElement=t,t},createDocumentFragment:function(){var e=new Ys;return e.ownerDocument=this,e.childNodes=new Kr,e},createTextNode:function(e){var t=new ld;return t.ownerDocument=this,t.appendData(e),t},createComment:function(e){var t=new ud;return t.ownerDocument=this,t.appendData(e),t},createCDATASection:function(e){if(e.indexOf("]]>")!==-1)throw new Z(M0,'data contains "]]>"');var t=new cd;return t.ownerDocument=this,t.appendData(e),t},createProcessingInstruction:function(e,t){var r=new pd;return r.ownerDocument=this,r.tagName=r.nodeName=r.target=e,r.nodeValue=r.data=t,r},createAttribute:function(e){var t=new Qs;return t.ownerDocument=this,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},createEntityReference:function(e){if(!ki.test(e))throw new Z(M0,'not a valid xml name "'+e+'"');var t=new dd;return t.ownerDocument=this,t.nodeName=e,t},createElementNS:function(e,t){var r=new ti,n=t.split(":"),i=r.attributes=new Hs;return r.childNodes=new Kr,r.ownerDocument=this,r.nodeName=t,r.tagName=t,r.namespaceURI=e,n.length==2?(r.prefix=n[0],r.localName=n[1]):r.localName=t,i._ownerElement=r,r},createAttributeNS:function(e,t){var r=new Qs,n=t.split(":");return r.ownerDocument=this,r.nodeName=t,r.name=t,r.namespaceURI=e,r.specified=!0,n.length==2?(r.prefix=n[0],r.localName=n[1]):r.localName=t,r}};Ct(po,ce);function ti(){this._nsMap={}}ti.prototype={nodeType:Vt,hasAttribute:function(e){return this.getAttributeNode(e)!=null},getAttribute:function(e){var t=this.getAttributeNode(e);return t&&t.value||""},getAttributeNode:function(e){return this.attributes.getNamedItem(e)},setAttribute:function(e,t){var r=this.ownerDocument.createAttribute(e);r.value=r.nodeValue=""+t,this.setAttributeNode(r)},removeAttribute:function(e){var t=this.getAttributeNode(e);t&&this.removeAttributeNode(t)},appendChild:function(e){return e.nodeType===Qr?this.insertBefore(e,null):SF(this,e)},setAttributeNode:function(e){return this.attributes.setNamedItem(e)},setAttributeNodeNS:function(e){return this.attributes.setNamedItemNS(e)},removeAttributeNode:function(e){return this.attributes.removeNamedItem(e.nodeName)},removeAttributeNS:function(e,t){var r=this.getAttributeNodeNS(e,t);r&&this.removeAttributeNode(r)},hasAttributeNS:function(e,t){return this.getAttributeNodeNS(e,t)!=null},getAttributeNS:function(e,t){var r=this.getAttributeNodeNS(e,t);return r&&r.value||""},setAttributeNS:function(e,t,r){var n=this.ownerDocument.createAttributeNS(e,t);n.value=n.nodeValue=""+r,this.setAttributeNode(n)},getAttributeNodeNS:function(e,t){return this.attributes.getNamedItemNS(e,t)},getElementsByTagName:function(e){return new Ui(this,function(t){var r=[];return js(t,function(n){n!==t&&n.nodeType==Vt&&(e==="*"||n.tagName==e)&&r.push(n)}),r})},getElementsByTagNameNS:function(e,t){return new Ui(this,function(r){var n=[];return js(r,function(i){i!==r&&i.nodeType===Vt&&(e==="*"||i.namespaceURI===e)&&(t==="*"||i.localName==t)&&n.push(i)}),n})}};po.prototype.getElementsByTagName=ti.prototype.getElementsByTagName;po.prototype.getElementsByTagNameNS=ti.prototype.getElementsByTagNameNS;Ct(ti,ce);function Qs(){}Qs.prototype.nodeType=Mi;Ct(Qs,ce);function fo(){}fo.prototype={data:"",substringData:function(e,t){return this.data.substring(e,e+t)},appendData:function(e){e=this.data+e,this.nodeValue=this.data=e,this.length=e.length},insertData:function(e,t){this.replaceData(e,0,t)},appendChild:function(e){throw new Error(Ve[At])},deleteData:function(e,t){this.replaceData(e,t,"")},replaceData:function(e,t,r){var n=this.data.substring(0,e),i=this.data.substring(e+t);r=n+r+i,this.nodeValue=this.data=r,this.length=r.length}};Ct(fo,ce);function ld(){}ld.prototype={nodeName:"#text",nodeType:so,splitText:function(e){var t=this.data,r=t.substring(e);t=t.substring(0,e),this.data=this.nodeValue=t,this.length=t.length;var n=this.ownerDocument.createTextNode(r);return this.parentNode&&this.parentNode.insertBefore(n,this.nextSibling),n}};Ct(ld,fo);function ud(){}ud.prototype={nodeName:"#comment",nodeType:ad};Ct(ud,fo);function cd(){}cd.prototype={nodeName:"#cdata-section",nodeType:z0};Ct(cd,fo);function Xs(){}Xs.prototype.nodeType=j0;Ct(Xs,ce);function rv(){}rv.prototype.nodeType=vF;Ct(rv,ce);function nv(){}nv.prototype.nodeType=gF;Ct(nv,ce);function dd(){}dd.prototype.nodeType=W0;Ct(dd,ce);function Ys(){}Ys.prototype.nodeName="#document-fragment";Ys.prototype.nodeType=Qr;Ct(Ys,ce);function pd(){}pd.prototype.nodeType=id;Ct(pd,ce);function iv(){}iv.prototype.serializeToString=function(e,t,r,n){return av.call(e,t,r,n)};ce.prototype.toString=av;function av(e,t,r){var n=!!r&&!!r.requireWellFormed,i=[],a=this.nodeType==9&&this.documentElement||this,o=a.prefix,s=a.namespaceURI;if(s&&o==null){var o=a.lookupPrefix(s);if(o==null)var l=[{namespace:s,prefix:null}]}return fd(this,i,e,t,l,n),i.join("")}function G0(e,t,r){var n=e.prefix||"",i=e.namespaceURI;if(!i||n==="xml"&&i===lo.XML||i===lo.XMLNS)return!1;for(var a=r.length;a--;){var o=r[a];if(o.prefix===n)return o.namespace!==i}return!0}function Ws(e,t,r,n){if(n&&!ki.test(t))throw new Z(or,'The attribute name "'+t+'" is not a valid XML QName');e.push(" ",t,'="',r.replace(/[<>&"\t\n\r]/g,Y0),'"')}function fd(e,t,r,n,i,a){i||(i=[]),qe(e,{ns:i,isHTML:r},{enter:function(o,s){var l=s.ns,u=s.isHTML;if(n)if(o=n(o),o){if(typeof o=="string")return t.push(o),null}else return null;switch(o.nodeType){case Vt:var c=o.attributes,d=c.length,p=o.tagName;u=lo.isHTML(o.namespaceURI)||u;var f=p;if(!u&&!o.prefix&&o.namespaceURI){for(var m,g=0;g<c.length;g++)if(c.item(g).name==="xmlns"){m=c.item(g).value;break}if(!m)for(var y=l.length-1;y>=0;y--){var A=l[y];if(A.prefix===""&&A.namespace===o.namespaceURI){m=A.namespace;break}}if(m!==o.namespaceURI)for(var y=l.length-1;y>=0;y--){var A=l[y];if(A.namespace===o.namespaceURI){A.prefix&&(f=A.prefix+":"+p);break}}}if(a&&!ki.test(f))throw new Z(or,'The element name "'+f+'" is not a valid XML QName');t.push("<",f);for(var D=l.slice(),F=0;F<d;F++){var _=c.item(F);_.prefix=="xmlns"?D.push({prefix:_.localName,namespace:_.value}):_.nodeName=="xmlns"&&D.push({prefix:"",namespace:_.value})}for(var F=0;F<d;F++){var _=c.item(F);if(G0(_,u,D)){var q=_.prefix||"",B=_.namespaceURI;Ws(t,q?"xmlns:"+q:"xmlns",B,a),D.push({prefix:q,namespace:B})}var L=n?n(_):_;L&&(typeof L=="string"?t.push(L):Ws(t,L.name,L.value,a))}if(p===f&&G0(o,u,D)){var k=o.prefix||"",B=o.namespaceURI;Ws(t,k?"xmlns:"+k:"xmlns",B,a),D.push({prefix:k,namespace:B})}var M=o.firstChild;if(M||u&&!/^(?:meta|link|img|br|hr|input)$/i.test(p)){if(t.push(">"),u&&/^script$/i.test(p)){for(;M;)M.data?t.push(M.data):fd(M,t,u,n,D.slice(),a),M=M.nextSibling;return t.push("</",p,">"),null}return{ns:D,isHTML:u,tag:f}}else return t.push("/>"),null;case H0:case Qr:return{ns:l.slice(),isHTML:u,tag:null};case Mi:return Ws(t,o.name,o.value,a),null;case so:return t.push(o.data.replace(/[<&>]/g,Y0)),null;case z0:if(a&&o.data.indexOf("]]>")!==-1)throw new Z(or,'The CDATASection data contains "]]>"');return t.push("<![CDATA[",o.data.replace(/]]>/g,"]]]]><![CDATA[>"),"]]>"),null;case ad:if(a&&o.data.indexOf("-->")!==-1)throw new Z(or,'The comment node data contains "-->"');return t.push("<!--",o.data,"-->"),null;case j0:if(a){if(!ki.test(o.name))throw new Z(or,'The doctype name "'+o.name+'" is not a valid XML Name');if(o.publicId&&!/^("[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%']*"|'[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%'"]*')$/.test(o.publicId))throw new Z(or,"DocumentType publicId is not a valid PubidLiteral");if(o.systemId&&!/^("[^"]*"|'[^']*')$/.test(o.systemId))throw new Z(or,"DocumentType systemId is not a valid SystemLiteral");if(o.internalSubset&&o.internalSubset.indexOf("]>")!==-1)throw new Z(or,'DocumentType internalSubset contains "]>"')}var G=o.publicId,V=o.systemId;if(t.push("<!DOCTYPE ",o.name),G)t.push(" PUBLIC ",G),V&&V!="."&&t.push(" ",V),t.push(">");else if(V&&V!=".")t.push(" SYSTEM ",V,">");else{var Ze=o.internalSubset;Ze&&t.push(" [",Ze,"]"),t.push(">")}return null;case id:if(a){if(!ki.test(o.target)||o.target.indexOf(":")!==-1||o.target.toLowerCase()==="xml")throw new Z(or,'The processing instruction target "'+o.target+'" is not a valid XML NCName or is reserved');if(o.data.indexOf("?>")!==-1)throw new Z(or,'The ProcessingInstruction data contains "?>"')}return t.push("<?",o.target," ",o.data,"?>"),null;case W0:if(a&&!ki.test(o.nodeName))throw new Z(or,'The entity reference name "'+o.nodeName+'" is not a valid XML Name');return t.push("&",o.nodeName,";"),null;default:return t.push("??",o.nodeName),null}},exit:function(o,s){s&&s.tag&&t.push("</",s.tag,">")}})}function NF(e,t,r){var n;return qe(t,null,{enter:function(i,a){var o=i.cloneNode(!1);o.ownerDocument=e,o.parentNode=null,a===null?n=o:a.appendChild(o);var s=i.nodeType===Mi||r;return s?o:null}}),n}function ov(e,t,r){var n;return qe(t,null,{enter:function(i,a){var o=new i.constructor;for(var s in i)if(Object.prototype.hasOwnProperty.call(i,s)){var l=i[s];typeof l!="object"&&l!=o[s]&&(o[s]=l)}i.childNodes&&(o.childNodes=new Kr),o.ownerDocument=e;var u=r;switch(o.nodeType){case Vt:var c=i.attributes,d=o.attributes=new Hs,p=c.length;d._ownerElement=o;for(var f=0;f<p;f++)o.setAttributeNode(ov(e,c.item(f),!0));break;case Mi:u=!0}return a!==null?a.appendChild(o):n=o,u?o:null}}),n}function sv(e,t,r){e[t]=r}try{Object.defineProperty&&(Object.defineProperty(Ui.prototype,"length",{get:function(){return od(this),this.$$length}}),Object.defineProperty(ce.prototype,"textContent",{get:function(){if(this.nodeType===Vt||this.nodeType===Qr){var e=[];return qe(this,null,{enter:function(t){if(t.nodeType===Vt||t.nodeType===Qr)return!0;if(t.nodeType===id||t.nodeType===ad)return null;e.push(t.nodeValue)}}),e.join("")}return this.nodeValue},set:function(e){switch(this.nodeType){case Vt:case Qr:for(;this.firstChild;)this.removeChild(this.firstChild);(e||String(e))&&this.appendChild(this.ownerDocument.createTextNode(e));break;default:this.data=e,this.value=e,this.nodeValue=e}}}),sv=function(e,t,r){e["$$"+t]=r})}catch{}Yr.DocumentType=Xs;Yr.DOMException=Z;Yr.DOMImplementation=X0;Yr.Element=ti;Yr.Node=ce;Yr.NodeList=Kr;Yr.walkDOM=qe;Yr.XMLSerializer=iv});var uv=v(mo=>{"use strict";var lv=Li().freeze;mo.XML_ENTITIES=lv({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'});mo.HTML_ENTITIES=lv({Aacute:"\xC1",aacute:"\xE1",Abreve:"\u0102",abreve:"\u0103",ac:"\u223E",acd:"\u223F",acE:"\u223E\u0333",Acirc:"\xC2",acirc:"\xE2",acute:"\xB4",Acy:"\u0410",acy:"\u0430",AElig:"\xC6",aelig:"\xE6",af:"\u2061",Afr:"\u{1D504}",afr:"\u{1D51E}",Agrave:"\xC0",agrave:"\xE0",alefsym:"\u2135",aleph:"\u2135",Alpha:"\u0391",alpha:"\u03B1",Amacr:"\u0100",amacr:"\u0101",amalg:"\u2A3F",AMP:"&",amp:"&",And:"\u2A53",and:"\u2227",andand:"\u2A55",andd:"\u2A5C",andslope:"\u2A58",andv:"\u2A5A",ang:"\u2220",ange:"\u29A4",angle:"\u2220",angmsd:"\u2221",angmsdaa:"\u29A8",angmsdab:"\u29A9",angmsdac:"\u29AA",angmsdad:"\u29AB",angmsdae:"\u29AC",angmsdaf:"\u29AD",angmsdag:"\u29AE",angmsdah:"\u29AF",angrt:"\u221F",angrtvb:"\u22BE",angrtvbd:"\u299D",angsph:"\u2222",angst:"\xC5",angzarr:"\u237C",Aogon:"\u0104",aogon:"\u0105",Aopf:"\u{1D538}",aopf:"\u{1D552}",ap:"\u2248",apacir:"\u2A6F",apE:"\u2A70",ape:"\u224A",apid:"\u224B",apos:"'",ApplyFunction:"\u2061",approx:"\u2248",approxeq:"\u224A",Aring:"\xC5",aring:"\xE5",Ascr:"\u{1D49C}",ascr:"\u{1D4B6}",Assign:"\u2254",ast:"*",asymp:"\u2248",asympeq:"\u224D",Atilde:"\xC3",atilde:"\xE3",Auml:"\xC4",auml:"\xE4",awconint:"\u2233",awint:"\u2A11",backcong:"\u224C",backepsilon:"\u03F6",backprime:"\u2035",backsim:"\u223D",backsimeq:"\u22CD",Backslash:"\u2216",Barv:"\u2AE7",barvee:"\u22BD",Barwed:"\u2306",barwed:"\u2305",barwedge:"\u2305",bbrk:"\u23B5",bbrktbrk:"\u23B6",bcong:"\u224C",Bcy:"\u0411",bcy:"\u0431",bdquo:"\u201E",becaus:"\u2235",Because:"\u2235",because:"\u2235",bemptyv:"\u29B0",bepsi:"\u03F6",bernou:"\u212C",Bernoullis:"\u212C",Beta:"\u0392",beta:"\u03B2",beth:"\u2136",between:"\u226C",Bfr:"\u{1D505}",bfr:"\u{1D51F}",bigcap:"\u22C2",bigcirc:"\u25EF",bigcup:"\u22C3",bigodot:"\u2A00",bigoplus:"\u2A01",bigotimes:"\u2A02",bigsqcup:"\u2A06",bigstar:"\u2605",bigtriangledown:"\u25BD",bigtriangleup:"\u25B3",biguplus:"\u2A04",bigvee:"\u22C1",bigwedge:"\u22C0",bkarow:"\u290D",blacklozenge:"\u29EB",blacksquare:"\u25AA",blacktriangle:"\u25B4",blacktriangledown:"\u25BE",blacktriangleleft:"\u25C2",blacktriangleright:"\u25B8",blank:"\u2423",blk12:"\u2592",blk14:"\u2591",blk34:"\u2593",block:"\u2588",bne:"=\u20E5",bnequiv:"\u2261\u20E5",bNot:"\u2AED",bnot:"\u2310",Bopf:"\u{1D539}",bopf:"\u{1D553}",bot:"\u22A5",bottom:"\u22A5",bowtie:"\u22C8",boxbox:"\u29C9",boxDL:"\u2557",boxDl:"\u2556",boxdL:"\u2555",boxdl:"\u2510",boxDR:"\u2554",boxDr:"\u2553",boxdR:"\u2552",boxdr:"\u250C",boxH:"\u2550",boxh:"\u2500",boxHD:"\u2566",boxHd:"\u2564",boxhD:"\u2565",boxhd:"\u252C",boxHU:"\u2569",boxHu:"\u2567",boxhU:"\u2568",boxhu:"\u2534",boxminus:"\u229F",boxplus:"\u229E",boxtimes:"\u22A0",boxUL:"\u255D",boxUl:"\u255C",boxuL:"\u255B",boxul:"\u2518",boxUR:"\u255A",boxUr:"\u2559",boxuR:"\u2558",boxur:"\u2514",boxV:"\u2551",boxv:"\u2502",boxVH:"\u256C",boxVh:"\u256B",boxvH:"\u256A",boxvh:"\u253C",boxVL:"\u2563",boxVl:"\u2562",boxvL:"\u2561",boxvl:"\u2524",boxVR:"\u2560",boxVr:"\u255F",boxvR:"\u255E",boxvr:"\u251C",bprime:"\u2035",Breve:"\u02D8",breve:"\u02D8",brvbar:"\xA6",Bscr:"\u212C",bscr:"\u{1D4B7}",bsemi:"\u204F",bsim:"\u223D",bsime:"\u22CD",bsol:"\\",bsolb:"\u29C5",bsolhsub:"\u27C8",bull:"\u2022",bullet:"\u2022",bump:"\u224E",bumpE:"\u2AAE",bumpe:"\u224F",Bumpeq:"\u224E",bumpeq:"\u224F",Cacute:"\u0106",cacute:"\u0107",Cap:"\u22D2",cap:"\u2229",capand:"\u2A44",capbrcup:"\u2A49",capcap:"\u2A4B",capcup:"\u2A47",capdot:"\u2A40",CapitalDifferentialD:"\u2145",caps:"\u2229\uFE00",caret:"\u2041",caron:"\u02C7",Cayleys:"\u212D",ccaps:"\u2A4D",Ccaron:"\u010C",ccaron:"\u010D",Ccedil:"\xC7",ccedil:"\xE7",Ccirc:"\u0108",ccirc:"\u0109",Cconint:"\u2230",ccups:"\u2A4C",ccupssm:"\u2A50",Cdot:"\u010A",cdot:"\u010B",cedil:"\xB8",Cedilla:"\xB8",cemptyv:"\u29B2",cent:"\xA2",CenterDot:"\xB7",centerdot:"\xB7",Cfr:"\u212D",cfr:"\u{1D520}",CHcy:"\u0427",chcy:"\u0447",check:"\u2713",checkmark:"\u2713",Chi:"\u03A7",chi:"\u03C7",cir:"\u25CB",circ:"\u02C6",circeq:"\u2257",circlearrowleft:"\u21BA",circlearrowright:"\u21BB",circledast:"\u229B",circledcirc:"\u229A",circleddash:"\u229D",CircleDot:"\u2299",circledR:"\xAE",circledS:"\u24C8",CircleMinus:"\u2296",CirclePlus:"\u2295",CircleTimes:"\u2297",cirE:"\u29C3",cire:"\u2257",cirfnint:"\u2A10",cirmid:"\u2AEF",cirscir:"\u29C2",ClockwiseContourIntegral:"\u2232",CloseCurlyDoubleQuote:"\u201D",CloseCurlyQuote:"\u2019",clubs:"\u2663",clubsuit:"\u2663",Colon:"\u2237",colon:":",Colone:"\u2A74",colone:"\u2254",coloneq:"\u2254",comma:",",commat:"@",comp:"\u2201",compfn:"\u2218",complement:"\u2201",complexes:"\u2102",cong:"\u2245",congdot:"\u2A6D",Congruent:"\u2261",Conint:"\u222F",conint:"\u222E",ContourIntegral:"\u222E",Copf:"\u2102",copf:"\u{1D554}",coprod:"\u2210",Coproduct:"\u2210",COPY:"\xA9",copy:"\xA9",copysr:"\u2117",CounterClockwiseContourIntegral:"\u2233",crarr:"\u21B5",Cross:"\u2A2F",cross:"\u2717",Cscr:"\u{1D49E}",cscr:"\u{1D4B8}",csub:"\u2ACF",csube:"\u2AD1",csup:"\u2AD0",csupe:"\u2AD2",ctdot:"\u22EF",cudarrl:"\u2938",cudarrr:"\u2935",cuepr:"\u22DE",cuesc:"\u22DF",cularr:"\u21B6",cularrp:"\u293D",Cup:"\u22D3",cup:"\u222A",cupbrcap:"\u2A48",CupCap:"\u224D",cupcap:"\u2A46",cupcup:"\u2A4A",cupdot:"\u228D",cupor:"\u2A45",cups:"\u222A\uFE00",curarr:"\u21B7",curarrm:"\u293C",curlyeqprec:"\u22DE",curlyeqsucc:"\u22DF",curlyvee:"\u22CE",curlywedge:"\u22CF",curren:"\xA4",curvearrowleft:"\u21B6",curvearrowright:"\u21B7",cuvee:"\u22CE",cuwed:"\u22CF",cwconint:"\u2232",cwint:"\u2231",cylcty:"\u232D",Dagger:"\u2021",dagger:"\u2020",daleth:"\u2138",Darr:"\u21A1",dArr:"\u21D3",darr:"\u2193",dash:"\u2010",Dashv:"\u2AE4",dashv:"\u22A3",dbkarow:"\u290F",dblac:"\u02DD",Dcaron:"\u010E",dcaron:"\u010F",Dcy:"\u0414",dcy:"\u0434",DD:"\u2145",dd:"\u2146",ddagger:"\u2021",ddarr:"\u21CA",DDotrahd:"\u2911",ddotseq:"\u2A77",deg:"\xB0",Del:"\u2207",Delta:"\u0394",delta:"\u03B4",demptyv:"\u29B1",dfisht:"\u297F",Dfr:"\u{1D507}",dfr:"\u{1D521}",dHar:"\u2965",dharl:"\u21C3",dharr:"\u21C2",DiacriticalAcute:"\xB4",DiacriticalDot:"\u02D9",DiacriticalDoubleAcute:"\u02DD",DiacriticalGrave:"`",DiacriticalTilde:"\u02DC",diam:"\u22C4",Diamond:"\u22C4",diamond:"\u22C4",diamondsuit:"\u2666",diams:"\u2666",die:"\xA8",DifferentialD:"\u2146",digamma:"\u03DD",disin:"\u22F2",div:"\xF7",divide:"\xF7",divideontimes:"\u22C7",divonx:"\u22C7",DJcy:"\u0402",djcy:"\u0452",dlcorn:"\u231E",dlcrop:"\u230D",dollar:"$",Dopf:"\u{1D53B}",dopf:"\u{1D555}",Dot:"\xA8",dot:"\u02D9",DotDot:"\u20DC",doteq:"\u2250",doteqdot:"\u2251",DotEqual:"\u2250",dotminus:"\u2238",dotplus:"\u2214",dotsquare:"\u22A1",doublebarwedge:"\u2306",DoubleContourIntegral:"\u222F",DoubleDot:"\xA8",DoubleDownArrow:"\u21D3",DoubleLeftArrow:"\u21D0",DoubleLeftRightArrow:"\u21D4",DoubleLeftTee:"\u2AE4",DoubleLongLeftArrow:"\u27F8",DoubleLongLeftRightArrow:"\u27FA",DoubleLongRightArrow:"\u27F9",DoubleRightArrow:"\u21D2",DoubleRightTee:"\u22A8",DoubleUpArrow:"\u21D1",DoubleUpDownArrow:"\u21D5",DoubleVerticalBar:"\u2225",DownArrow:"\u2193",Downarrow:"\u21D3",downarrow:"\u2193",DownArrowBar:"\u2913",DownArrowUpArrow:"\u21F5",DownBreve:"\u0311",downdownarrows:"\u21CA",downharpoonleft:"\u21C3",downharpoonright:"\u21C2",DownLeftRightVector:"\u2950",DownLeftTeeVector:"\u295E",DownLeftVector:"\u21BD",DownLeftVectorBar:"\u2956",DownRightTeeVector:"\u295F",DownRightVector:"\u21C1",DownRightVectorBar:"\u2957",DownTee:"\u22A4",DownTeeArrow:"\u21A7",drbkarow:"\u2910",drcorn:"\u231F",drcrop:"\u230C",Dscr:"\u{1D49F}",dscr:"\u{1D4B9}",DScy:"\u0405",dscy:"\u0455",dsol:"\u29F6",Dstrok:"\u0110",dstrok:"\u0111",dtdot:"\u22F1",dtri:"\u25BF",dtrif:"\u25BE",duarr:"\u21F5",duhar:"\u296F",dwangle:"\u29A6",DZcy:"\u040F",dzcy:"\u045F",dzigrarr:"\u27FF",Eacute:"\xC9",eacute:"\xE9",easter:"\u2A6E",Ecaron:"\u011A",ecaron:"\u011B",ecir:"\u2256",Ecirc:"\xCA",ecirc:"\xEA",ecolon:"\u2255",Ecy:"\u042D",ecy:"\u044D",eDDot:"\u2A77",Edot:"\u0116",eDot:"\u2251",edot:"\u0117",ee:"\u2147",efDot:"\u2252",Efr:"\u{1D508}",efr:"\u{1D522}",eg:"\u2A9A",Egrave:"\xC8",egrave:"\xE8",egs:"\u2A96",egsdot:"\u2A98",el:"\u2A99",Element:"\u2208",elinters:"\u23E7",ell:"\u2113",els:"\u2A95",elsdot:"\u2A97",Emacr:"\u0112",emacr:"\u0113",empty:"\u2205",emptyset:"\u2205",EmptySmallSquare:"\u25FB",emptyv:"\u2205",EmptyVerySmallSquare:"\u25AB",emsp:"\u2003",emsp13:"\u2004",emsp14:"\u2005",ENG:"\u014A",eng:"\u014B",ensp:"\u2002",Eogon:"\u0118",eogon:"\u0119",Eopf:"\u{1D53C}",eopf:"\u{1D556}",epar:"\u22D5",eparsl:"\u29E3",eplus:"\u2A71",epsi:"\u03B5",Epsilon:"\u0395",epsilon:"\u03B5",epsiv:"\u03F5",eqcirc:"\u2256",eqcolon:"\u2255",eqsim:"\u2242",eqslantgtr:"\u2A96",eqslantless:"\u2A95",Equal:"\u2A75",equals:"=",EqualTilde:"\u2242",equest:"\u225F",Equilibrium:"\u21CC",equiv:"\u2261",equivDD:"\u2A78",eqvparsl:"\u29E5",erarr:"\u2971",erDot:"\u2253",Escr:"\u2130",escr:"\u212F",esdot:"\u2250",Esim:"\u2A73",esim:"\u2242",Eta:"\u0397",eta:"\u03B7",ETH:"\xD0",eth:"\xF0",Euml:"\xCB",euml:"\xEB",euro:"\u20AC",excl:"!",exist:"\u2203",Exists:"\u2203",expectation:"\u2130",ExponentialE:"\u2147",exponentiale:"\u2147",fallingdotseq:"\u2252",Fcy:"\u0424",fcy:"\u0444",female:"\u2640",ffilig:"\uFB03",fflig:"\uFB00",ffllig:"\uFB04",Ffr:"\u{1D509}",ffr:"\u{1D523}",filig:"\uFB01",FilledSmallSquare:"\u25FC",FilledVerySmallSquare:"\u25AA",fjlig:"fj",flat:"\u266D",fllig:"\uFB02",fltns:"\u25B1",fnof:"\u0192",Fopf:"\u{1D53D}",fopf:"\u{1D557}",ForAll:"\u2200",forall:"\u2200",fork:"\u22D4",forkv:"\u2AD9",Fouriertrf:"\u2131",fpartint:"\u2A0D",frac12:"\xBD",frac13:"\u2153",frac14:"\xBC",frac15:"\u2155",frac16:"\u2159",frac18:"\u215B",frac23:"\u2154",frac25:"\u2156",frac34:"\xBE",frac35:"\u2157",frac38:"\u215C",frac45:"\u2158",frac56:"\u215A",frac58:"\u215D",frac78:"\u215E",frasl:"\u2044",frown:"\u2322",Fscr:"\u2131",fscr:"\u{1D4BB}",gacute:"\u01F5",Gamma:"\u0393",gamma:"\u03B3",Gammad:"\u03DC",gammad:"\u03DD",gap:"\u2A86",Gbreve:"\u011E",gbreve:"\u011F",Gcedil:"\u0122",Gcirc:"\u011C",gcirc:"\u011D",Gcy:"\u0413",gcy:"\u0433",Gdot:"\u0120",gdot:"\u0121",gE:"\u2267",ge:"\u2265",gEl:"\u2A8C",gel:"\u22DB",geq:"\u2265",geqq:"\u2267",geqslant:"\u2A7E",ges:"\u2A7E",gescc:"\u2AA9",gesdot:"\u2A80",gesdoto:"\u2A82",gesdotol:"\u2A84",gesl:"\u22DB\uFE00",gesles:"\u2A94",Gfr:"\u{1D50A}",gfr:"\u{1D524}",Gg:"\u22D9",gg:"\u226B",ggg:"\u22D9",gimel:"\u2137",GJcy:"\u0403",gjcy:"\u0453",gl:"\u2277",gla:"\u2AA5",glE:"\u2A92",glj:"\u2AA4",gnap:"\u2A8A",gnapprox:"\u2A8A",gnE:"\u2269",gne:"\u2A88",gneq:"\u2A88",gneqq:"\u2269",gnsim:"\u22E7",Gopf:"\u{1D53E}",gopf:"\u{1D558}",grave:"`",GreaterEqual:"\u2265",GreaterEqualLess:"\u22DB",GreaterFullEqual:"\u2267",GreaterGreater:"\u2AA2",GreaterLess:"\u2277",GreaterSlantEqual:"\u2A7E",GreaterTilde:"\u2273",Gscr:"\u{1D4A2}",gscr:"\u210A",gsim:"\u2273",gsime:"\u2A8E",gsiml:"\u2A90",Gt:"\u226B",GT:">",gt:">",gtcc:"\u2AA7",gtcir:"\u2A7A",gtdot:"\u22D7",gtlPar:"\u2995",gtquest:"\u2A7C",gtrapprox:"\u2A86",gtrarr:"\u2978",gtrdot:"\u22D7",gtreqless:"\u22DB",gtreqqless:"\u2A8C",gtrless:"\u2277",gtrsim:"\u2273",gvertneqq:"\u2269\uFE00",gvnE:"\u2269\uFE00",Hacek:"\u02C7",hairsp:"\u200A",half:"\xBD",hamilt:"\u210B",HARDcy:"\u042A",hardcy:"\u044A",hArr:"\u21D4",harr:"\u2194",harrcir:"\u2948",harrw:"\u21AD",Hat:"^",hbar:"\u210F",Hcirc:"\u0124",hcirc:"\u0125",hearts:"\u2665",heartsuit:"\u2665",hellip:"\u2026",hercon:"\u22B9",Hfr:"\u210C",hfr:"\u{1D525}",HilbertSpace:"\u210B",hksearow:"\u2925",hkswarow:"\u2926",hoarr:"\u21FF",homtht:"\u223B",hookleftarrow:"\u21A9",hookrightarrow:"\u21AA",Hopf:"\u210D",hopf:"\u{1D559}",horbar:"\u2015",HorizontalLine:"\u2500",Hscr:"\u210B",hscr:"\u{1D4BD}",hslash:"\u210F",Hstrok:"\u0126",hstrok:"\u0127",HumpDownHump:"\u224E",HumpEqual:"\u224F",hybull:"\u2043",hyphen:"\u2010",Iacute:"\xCD",iacute:"\xED",ic:"\u2063",Icirc:"\xCE",icirc:"\xEE",Icy:"\u0418",icy:"\u0438",Idot:"\u0130",IEcy:"\u0415",iecy:"\u0435",iexcl:"\xA1",iff:"\u21D4",Ifr:"\u2111",ifr:"\u{1D526}",Igrave:"\xCC",igrave:"\xEC",ii:"\u2148",iiiint:"\u2A0C",iiint:"\u222D",iinfin:"\u29DC",iiota:"\u2129",IJlig:"\u0132",ijlig:"\u0133",Im:"\u2111",Imacr:"\u012A",imacr:"\u012B",image:"\u2111",ImaginaryI:"\u2148",imagline:"\u2110",imagpart:"\u2111",imath:"\u0131",imof:"\u22B7",imped:"\u01B5",Implies:"\u21D2",in:"\u2208",incare:"\u2105",infin:"\u221E",infintie:"\u29DD",inodot:"\u0131",Int:"\u222C",int:"\u222B",intcal:"\u22BA",integers:"\u2124",Integral:"\u222B",intercal:"\u22BA",Intersection:"\u22C2",intlarhk:"\u2A17",intprod:"\u2A3C",InvisibleComma:"\u2063",InvisibleTimes:"\u2062",IOcy:"\u0401",iocy:"\u0451",Iogon:"\u012E",iogon:"\u012F",Iopf:"\u{1D540}",iopf:"\u{1D55A}",Iota:"\u0399",iota:"\u03B9",iprod:"\u2A3C",iquest:"\xBF",Iscr:"\u2110",iscr:"\u{1D4BE}",isin:"\u2208",isindot:"\u22F5",isinE:"\u22F9",isins:"\u22F4",isinsv:"\u22F3",isinv:"\u2208",it:"\u2062",Itilde:"\u0128",itilde:"\u0129",Iukcy:"\u0406",iukcy:"\u0456",Iuml:"\xCF",iuml:"\xEF",Jcirc:"\u0134",jcirc:"\u0135",Jcy:"\u0419",jcy:"\u0439",Jfr:"\u{1D50D}",jfr:"\u{1D527}",jmath:"\u0237",Jopf:"\u{1D541}",jopf:"\u{1D55B}",Jscr:"\u{1D4A5}",jscr:"\u{1D4BF}",Jsercy:"\u0408",jsercy:"\u0458",Jukcy:"\u0404",jukcy:"\u0454",Kappa:"\u039A",kappa:"\u03BA",kappav:"\u03F0",Kcedil:"\u0136",kcedil:"\u0137",Kcy:"\u041A",kcy:"\u043A",Kfr:"\u{1D50E}",kfr:"\u{1D528}",kgreen:"\u0138",KHcy:"\u0425",khcy:"\u0445",KJcy:"\u040C",kjcy:"\u045C",Kopf:"\u{1D542}",kopf:"\u{1D55C}",Kscr:"\u{1D4A6}",kscr:"\u{1D4C0}",lAarr:"\u21DA",Lacute:"\u0139",lacute:"\u013A",laemptyv:"\u29B4",lagran:"\u2112",Lambda:"\u039B",lambda:"\u03BB",Lang:"\u27EA",lang:"\u27E8",langd:"\u2991",langle:"\u27E8",lap:"\u2A85",Laplacetrf:"\u2112",laquo:"\xAB",Larr:"\u219E",lArr:"\u21D0",larr:"\u2190",larrb:"\u21E4",larrbfs:"\u291F",larrfs:"\u291D",larrhk:"\u21A9",larrlp:"\u21AB",larrpl:"\u2939",larrsim:"\u2973",larrtl:"\u21A2",lat:"\u2AAB",lAtail:"\u291B",latail:"\u2919",late:"\u2AAD",lates:"\u2AAD\uFE00",lBarr:"\u290E",lbarr:"\u290C",lbbrk:"\u2772",lbrace:"{",lbrack:"[",lbrke:"\u298B",lbrksld:"\u298F",lbrkslu:"\u298D",Lcaron:"\u013D",lcaron:"\u013E",Lcedil:"\u013B",lcedil:"\u013C",lceil:"\u2308",lcub:"{",Lcy:"\u041B",lcy:"\u043B",ldca:"\u2936",ldquo:"\u201C",ldquor:"\u201E",ldrdhar:"\u2967",ldrushar:"\u294B",ldsh:"\u21B2",lE:"\u2266",le:"\u2264",LeftAngleBracket:"\u27E8",LeftArrow:"\u2190",Leftarrow:"\u21D0",leftarrow:"\u2190",LeftArrowBar:"\u21E4",LeftArrowRightArrow:"\u21C6",leftarrowtail:"\u21A2",LeftCeiling:"\u2308",LeftDoubleBracket:"\u27E6",LeftDownTeeVector:"\u2961",LeftDownVector:"\u21C3",LeftDownVectorBar:"\u2959",LeftFloor:"\u230A",leftharpoondown:"\u21BD",leftharpoonup:"\u21BC",leftleftarrows:"\u21C7",LeftRightArrow:"\u2194",Leftrightarrow:"\u21D4",leftrightarrow:"\u2194",leftrightarrows:"\u21C6",leftrightharpoons:"\u21CB",leftrightsquigarrow:"\u21AD",LeftRightVector:"\u294E",LeftTee:"\u22A3",LeftTeeArrow:"\u21A4",LeftTeeVector:"\u295A",leftthreetimes:"\u22CB",LeftTriangle:"\u22B2",LeftTriangleBar:"\u29CF",LeftTriangleEqual:"\u22B4",LeftUpDownVector:"\u2951",LeftUpTeeVector:"\u2960",LeftUpVector:"\u21BF",LeftUpVectorBar:"\u2958",LeftVector:"\u21BC",LeftVectorBar:"\u2952",lEg:"\u2A8B",leg:"\u22DA",leq:"\u2264",leqq:"\u2266",leqslant:"\u2A7D",les:"\u2A7D",lescc:"\u2AA8",lesdot:"\u2A7F",lesdoto:"\u2A81",lesdotor:"\u2A83",lesg:"\u22DA\uFE00",lesges:"\u2A93",lessapprox:"\u2A85",lessdot:"\u22D6",lesseqgtr:"\u22DA",lesseqqgtr:"\u2A8B",LessEqualGreater:"\u22DA",LessFullEqual:"\u2266",LessGreater:"\u2276",lessgtr:"\u2276",LessLess:"\u2AA1",lesssim:"\u2272",LessSlantEqual:"\u2A7D",LessTilde:"\u2272",lfisht:"\u297C",lfloor:"\u230A",Lfr:"\u{1D50F}",lfr:"\u{1D529}",lg:"\u2276",lgE:"\u2A91",lHar:"\u2962",lhard:"\u21BD",lharu:"\u21BC",lharul:"\u296A",lhblk:"\u2584",LJcy:"\u0409",ljcy:"\u0459",Ll:"\u22D8",ll:"\u226A",llarr:"\u21C7",llcorner:"\u231E",Lleftarrow:"\u21DA",llhard:"\u296B",lltri:"\u25FA",Lmidot:"\u013F",lmidot:"\u0140",lmoust:"\u23B0",lmoustache:"\u23B0",lnap:"\u2A89",lnapprox:"\u2A89",lnE:"\u2268",lne:"\u2A87",lneq:"\u2A87",lneqq:"\u2268",lnsim:"\u22E6",loang:"\u27EC",loarr:"\u21FD",lobrk:"\u27E6",LongLeftArrow:"\u27F5",Longleftarrow:"\u27F8",longleftarrow:"\u27F5",LongLeftRightArrow:"\u27F7",Longleftrightarrow:"\u27FA",longleftrightarrow:"\u27F7",longmapsto:"\u27FC",LongRightArrow:"\u27F6",Longrightarrow:"\u27F9",longrightarrow:"\u27F6",looparrowleft:"\u21AB",looparrowright:"\u21AC",lopar:"\u2985",Lopf:"\u{1D543}",lopf:"\u{1D55D}",loplus:"\u2A2D",lotimes:"\u2A34",lowast:"\u2217",lowbar:"_",LowerLeftArrow:"\u2199",LowerRightArrow:"\u2198",loz:"\u25CA",lozenge:"\u25CA",lozf:"\u29EB",lpar:"(",lparlt:"\u2993",lrarr:"\u21C6",lrcorner:"\u231F",lrhar:"\u21CB",lrhard:"\u296D",lrm:"\u200E",lrtri:"\u22BF",lsaquo:"\u2039",Lscr:"\u2112",lscr:"\u{1D4C1}",Lsh:"\u21B0",lsh:"\u21B0",lsim:"\u2272",lsime:"\u2A8D",lsimg:"\u2A8F",lsqb:"[",lsquo:"\u2018",lsquor:"\u201A",Lstrok:"\u0141",lstrok:"\u0142",Lt:"\u226A",LT:"<",lt:"<",ltcc:"\u2AA6",ltcir:"\u2A79",ltdot:"\u22D6",lthree:"\u22CB",ltimes:"\u22C9",ltlarr:"\u2976",ltquest:"\u2A7B",ltri:"\u25C3",ltrie:"\u22B4",ltrif:"\u25C2",ltrPar:"\u2996",lurdshar:"\u294A",luruhar:"\u2966",lvertneqq:"\u2268\uFE00",lvnE:"\u2268\uFE00",macr:"\xAF",male:"\u2642",malt:"\u2720",maltese:"\u2720",Map:"\u2905",map:"\u21A6",mapsto:"\u21A6",mapstodown:"\u21A7",mapstoleft:"\u21A4",mapstoup:"\u21A5",marker:"\u25AE",mcomma:"\u2A29",Mcy:"\u041C",mcy:"\u043C",mdash:"\u2014",mDDot:"\u223A",measuredangle:"\u2221",MediumSpace:"\u205F",Mellintrf:"\u2133",Mfr:"\u{1D510}",mfr:"\u{1D52A}",mho:"\u2127",micro:"\xB5",mid:"\u2223",midast:"*",midcir:"\u2AF0",middot:"\xB7",minus:"\u2212",minusb:"\u229F",minusd:"\u2238",minusdu:"\u2A2A",MinusPlus:"\u2213",mlcp:"\u2ADB",mldr:"\u2026",mnplus:"\u2213",models:"\u22A7",Mopf:"\u{1D544}",mopf:"\u{1D55E}",mp:"\u2213",Mscr:"\u2133",mscr:"\u{1D4C2}",mstpos:"\u223E",Mu:"\u039C",mu:"\u03BC",multimap:"\u22B8",mumap:"\u22B8",nabla:"\u2207",Nacute:"\u0143",nacute:"\u0144",nang:"\u2220\u20D2",nap:"\u2249",napE:"\u2A70\u0338",napid:"\u224B\u0338",napos:"\u0149",napprox:"\u2249",natur:"\u266E",natural:"\u266E",naturals:"\u2115",nbsp:"\xA0",nbump:"\u224E\u0338",nbumpe:"\u224F\u0338",ncap:"\u2A43",Ncaron:"\u0147",ncaron:"\u0148",Ncedil:"\u0145",ncedil:"\u0146",ncong:"\u2247",ncongdot:"\u2A6D\u0338",ncup:"\u2A42",Ncy:"\u041D",ncy:"\u043D",ndash:"\u2013",ne:"\u2260",nearhk:"\u2924",neArr:"\u21D7",nearr:"\u2197",nearrow:"\u2197",nedot:"\u2250\u0338",NegativeMediumSpace:"\u200B",NegativeThickSpace:"\u200B",NegativeThinSpace:"\u200B",NegativeVeryThinSpace:"\u200B",nequiv:"\u2262",nesear:"\u2928",nesim:"\u2242\u0338",NestedGreaterGreater:"\u226B",NestedLessLess:"\u226A",NewLine:`-`,nexist:"\u2204",nexists:"\u2204",Nfr:"\u{1D511}",nfr:"\u{1D52B}",ngE:"\u2267\u0338",nge:"\u2271",ngeq:"\u2271",ngeqq:"\u2267\u0338",ngeqslant:"\u2A7E\u0338",nges:"\u2A7E\u0338",nGg:"\u22D9\u0338",ngsim:"\u2275",nGt:"\u226B\u20D2",ngt:"\u226F",ngtr:"\u226F",nGtv:"\u226B\u0338",nhArr:"\u21CE",nharr:"\u21AE",nhpar:"\u2AF2",ni:"\u220B",nis:"\u22FC",nisd:"\u22FA",niv:"\u220B",NJcy:"\u040A",njcy:"\u045A",nlArr:"\u21CD",nlarr:"\u219A",nldr:"\u2025",nlE:"\u2266\u0338",nle:"\u2270",nLeftarrow:"\u21CD",nleftarrow:"\u219A",nLeftrightarrow:"\u21CE",nleftrightarrow:"\u21AE",nleq:"\u2270",nleqq:"\u2266\u0338",nleqslant:"\u2A7D\u0338",nles:"\u2A7D\u0338",nless:"\u226E",nLl:"\u22D8\u0338",nlsim:"\u2274",nLt:"\u226A\u20D2",nlt:"\u226E",nltri:"\u22EA",nltrie:"\u22EC",nLtv:"\u226A\u0338",nmid:"\u2224",NoBreak:"\u2060",NonBreakingSpace:"\xA0",Nopf:"\u2115",nopf:"\u{1D55F}",Not:"\u2AEC",not:"\xAC",NotCongruent:"\u2262",NotCupCap:"\u226D",NotDoubleVerticalBar:"\u2226",NotElement:"\u2209",NotEqual:"\u2260",NotEqualTilde:"\u2242\u0338",NotExists:"\u2204",NotGreater:"\u226F",NotGreaterEqual:"\u2271",NotGreaterFullEqual:"\u2267\u0338",NotGreaterGreater:"\u226B\u0338",NotGreaterLess:"\u2279",NotGreaterSlantEqual:"\u2A7E\u0338",NotGreaterTilde:"\u2275",NotHumpDownHump:"\u224E\u0338",NotHumpEqual:"\u224F\u0338",notin:"\u2209",notindot:"\u22F5\u0338",notinE:"\u22F9\u0338",notinva:"\u2209",notinvb:"\u22F7",notinvc:"\u22F6",NotLeftTriangle:"\u22EA",NotLeftTriangleBar:"\u29CF\u0338",NotLeftTriangleEqual:"\u22EC",NotLess:"\u226E",NotLessEqual:"\u2270",NotLessGreater:"\u2278",NotLessLess:"\u226A\u0338",NotLessSlantEqual:"\u2A7D\u0338",NotLessTilde:"\u2274",NotNestedGreaterGreater:"\u2AA2\u0338",NotNestedLessLess:"\u2AA1\u0338",notni:"\u220C",notniva:"\u220C",notnivb:"\u22FE",notnivc:"\u22FD",NotPrecedes:"\u2280",NotPrecedesEqual:"\u2AAF\u0338",NotPrecedesSlantEqual:"\u22E0",NotReverseElement:"\u220C",NotRightTriangle:"\u22EB",NotRightTriangleBar:"\u29D0\u0338",NotRightTriangleEqual:"\u22ED",NotSquareSubset:"\u228F\u0338",NotSquareSubsetEqual:"\u22E2",NotSquareSuperset:"\u2290\u0338",NotSquareSupersetEqual:"\u22E3",NotSubset:"\u2282\u20D2",NotSubsetEqual:"\u2288",NotSucceeds:"\u2281",NotSucceedsEqual:"\u2AB0\u0338",NotSucceedsSlantEqual:"\u22E1",NotSucceedsTilde:"\u227F\u0338",NotSuperset:"\u2283\u20D2",NotSupersetEqual:"\u2289",NotTilde:"\u2241",NotTildeEqual:"\u2244",NotTildeFullEqual:"\u2247",NotTildeTilde:"\u2249",NotVerticalBar:"\u2224",npar:"\u2226",nparallel:"\u2226",nparsl:"\u2AFD\u20E5",npart:"\u2202\u0338",npolint:"\u2A14",npr:"\u2280",nprcue:"\u22E0",npre:"\u2AAF\u0338",nprec:"\u2280",npreceq:"\u2AAF\u0338",nrArr:"\u21CF",nrarr:"\u219B",nrarrc:"\u2933\u0338",nrarrw:"\u219D\u0338",nRightarrow:"\u21CF",nrightarrow:"\u219B",nrtri:"\u22EB",nrtrie:"\u22ED",nsc:"\u2281",nsccue:"\u22E1",nsce:"\u2AB0\u0338",Nscr:"\u{1D4A9}",nscr:"\u{1D4C3}",nshortmid:"\u2224",nshortparallel:"\u2226",nsim:"\u2241",nsime:"\u2244",nsimeq:"\u2244",nsmid:"\u2224",nspar:"\u2226",nsqsube:"\u22E2",nsqsupe:"\u22E3",nsub:"\u2284",nsubE:"\u2AC5\u0338",nsube:"\u2288",nsubset:"\u2282\u20D2",nsubseteq:"\u2288",nsubseteqq:"\u2AC5\u0338",nsucc:"\u2281",nsucceq:"\u2AB0\u0338",nsup:"\u2285",nsupE:"\u2AC6\u0338",nsupe:"\u2289",nsupset:"\u2283\u20D2",nsupseteq:"\u2289",nsupseteqq:"\u2AC6\u0338",ntgl:"\u2279",Ntilde:"\xD1",ntilde:"\xF1",ntlg:"\u2278",ntriangleleft:"\u22EA",ntrianglelefteq:"\u22EC",ntriangleright:"\u22EB",ntrianglerighteq:"\u22ED",Nu:"\u039D",nu:"\u03BD",num:"#",numero:"\u2116",numsp:"\u2007",nvap:"\u224D\u20D2",nVDash:"\u22AF",nVdash:"\u22AE",nvDash:"\u22AD",nvdash:"\u22AC",nvge:"\u2265\u20D2",nvgt:">\u20D2",nvHarr:"\u2904",nvinfin:"\u29DE",nvlArr:"\u2902",nvle:"\u2264\u20D2",nvlt:"<\u20D2",nvltrie:"\u22B4\u20D2",nvrArr:"\u2903",nvrtrie:"\u22B5\u20D2",nvsim:"\u223C\u20D2",nwarhk:"\u2923",nwArr:"\u21D6",nwarr:"\u2196",nwarrow:"\u2196",nwnear:"\u2927",Oacute:"\xD3",oacute:"\xF3",oast:"\u229B",ocir:"\u229A",Ocirc:"\xD4",ocirc:"\xF4",Ocy:"\u041E",ocy:"\u043E",odash:"\u229D",Odblac:"\u0150",odblac:"\u0151",odiv:"\u2A38",odot:"\u2299",odsold:"\u29BC",OElig:"\u0152",oelig:"\u0153",ofcir:"\u29BF",Ofr:"\u{1D512}",ofr:"\u{1D52C}",ogon:"\u02DB",Ograve:"\xD2",ograve:"\xF2",ogt:"\u29C1",ohbar:"\u29B5",ohm:"\u03A9",oint:"\u222E",olarr:"\u21BA",olcir:"\u29BE",olcross:"\u29BB",oline:"\u203E",olt:"\u29C0",Omacr:"\u014C",omacr:"\u014D",Omega:"\u03A9",omega:"\u03C9",Omicron:"\u039F",omicron:"\u03BF",omid:"\u29B6",ominus:"\u2296",Oopf:"\u{1D546}",oopf:"\u{1D560}",opar:"\u29B7",OpenCurlyDoubleQuote:"\u201C",OpenCurlyQuote:"\u2018",operp:"\u29B9",oplus:"\u2295",Or:"\u2A54",or:"\u2228",orarr:"\u21BB",ord:"\u2A5D",order:"\u2134",orderof:"\u2134",ordf:"\xAA",ordm:"\xBA",origof:"\u22B6",oror:"\u2A56",orslope:"\u2A57",orv:"\u2A5B",oS:"\u24C8",Oscr:"\u{1D4AA}",oscr:"\u2134",Oslash:"\xD8",oslash:"\xF8",osol:"\u2298",Otilde:"\xD5",otilde:"\xF5",Otimes:"\u2A37",otimes:"\u2297",otimesas:"\u2A36",Ouml:"\xD6",ouml:"\xF6",ovbar:"\u233D",OverBar:"\u203E",OverBrace:"\u23DE",OverBracket:"\u23B4",OverParenthesis:"\u23DC",par:"\u2225",para:"\xB6",parallel:"\u2225",parsim:"\u2AF3",parsl:"\u2AFD",part:"\u2202",PartialD:"\u2202",Pcy:"\u041F",pcy:"\u043F",percnt:"%",period:".",permil:"\u2030",perp:"\u22A5",pertenk:"\u2031",Pfr:"\u{1D513}",pfr:"\u{1D52D}",Phi:"\u03A6",phi:"\u03C6",phiv:"\u03D5",phmmat:"\u2133",phone:"\u260E",Pi:"\u03A0",pi:"\u03C0",pitchfork:"\u22D4",piv:"\u03D6",planck:"\u210F",planckh:"\u210E",plankv:"\u210F",plus:"+",plusacir:"\u2A23",plusb:"\u229E",pluscir:"\u2A22",plusdo:"\u2214",plusdu:"\u2A25",pluse:"\u2A72",PlusMinus:"\xB1",plusmn:"\xB1",plussim:"\u2A26",plustwo:"\u2A27",pm:"\xB1",Poincareplane:"\u210C",pointint:"\u2A15",Popf:"\u2119",popf:"\u{1D561}",pound:"\xA3",Pr:"\u2ABB",pr:"\u227A",prap:"\u2AB7",prcue:"\u227C",prE:"\u2AB3",pre:"\u2AAF",prec:"\u227A",precapprox:"\u2AB7",preccurlyeq:"\u227C",Precedes:"\u227A",PrecedesEqual:"\u2AAF",PrecedesSlantEqual:"\u227C",PrecedesTilde:"\u227E",preceq:"\u2AAF",precnapprox:"\u2AB9",precneqq:"\u2AB5",precnsim:"\u22E8",precsim:"\u227E",Prime:"\u2033",prime:"\u2032",primes:"\u2119",prnap:"\u2AB9",prnE:"\u2AB5",prnsim:"\u22E8",prod:"\u220F",Product:"\u220F",profalar:"\u232E",profline:"\u2312",profsurf:"\u2313",prop:"\u221D",Proportion:"\u2237",Proportional:"\u221D",propto:"\u221D",prsim:"\u227E",prurel:"\u22B0",Pscr:"\u{1D4AB}",pscr:"\u{1D4C5}",Psi:"\u03A8",psi:"\u03C8",puncsp:"\u2008",Qfr:"\u{1D514}",qfr:"\u{1D52E}",qint:"\u2A0C",Qopf:"\u211A",qopf:"\u{1D562}",qprime:"\u2057",Qscr:"\u{1D4AC}",qscr:"\u{1D4C6}",quaternions:"\u210D",quatint:"\u2A16",quest:"?",questeq:"\u225F",QUOT:'"',quot:'"',rAarr:"\u21DB",race:"\u223D\u0331",Racute:"\u0154",racute:"\u0155",radic:"\u221A",raemptyv:"\u29B3",Rang:"\u27EB",rang:"\u27E9",rangd:"\u2992",range:"\u29A5",rangle:"\u27E9",raquo:"\xBB",Rarr:"\u21A0",rArr:"\u21D2",rarr:"\u2192",rarrap:"\u2975",rarrb:"\u21E5",rarrbfs:"\u2920",rarrc:"\u2933",rarrfs:"\u291E",rarrhk:"\u21AA",rarrlp:"\u21AC",rarrpl:"\u2945",rarrsim:"\u2974",Rarrtl:"\u2916",rarrtl:"\u21A3",rarrw:"\u219D",rAtail:"\u291C",ratail:"\u291A",ratio:"\u2236",rationals:"\u211A",RBarr:"\u2910",rBarr:"\u290F",rbarr:"\u290D",rbbrk:"\u2773",rbrace:"}",rbrack:"]",rbrke:"\u298C",rbrksld:"\u298E",rbrkslu:"\u2990",Rcaron:"\u0158",rcaron:"\u0159",Rcedil:"\u0156",rcedil:"\u0157",rceil:"\u2309",rcub:"}",Rcy:"\u0420",rcy:"\u0440",rdca:"\u2937",rdldhar:"\u2969",rdquo:"\u201D",rdquor:"\u201D",rdsh:"\u21B3",Re:"\u211C",real:"\u211C",realine:"\u211B",realpart:"\u211C",reals:"\u211D",rect:"\u25AD",REG:"\xAE",reg:"\xAE",ReverseElement:"\u220B",ReverseEquilibrium:"\u21CB",ReverseUpEquilibrium:"\u296F",rfisht:"\u297D",rfloor:"\u230B",Rfr:"\u211C",rfr:"\u{1D52F}",rHar:"\u2964",rhard:"\u21C1",rharu:"\u21C0",rharul:"\u296C",Rho:"\u03A1",rho:"\u03C1",rhov:"\u03F1",RightAngleBracket:"\u27E9",RightArrow:"\u2192",Rightarrow:"\u21D2",rightarrow:"\u2192",RightArrowBar:"\u21E5",RightArrowLeftArrow:"\u21C4",rightarrowtail:"\u21A3",RightCeiling:"\u2309",RightDoubleBracket:"\u27E7",RightDownTeeVector:"\u295D",RightDownVector:"\u21C2",RightDownVectorBar:"\u2955",RightFloor:"\u230B",rightharpoondown:"\u21C1",rightharpoonup:"\u21C0",rightleftarrows:"\u21C4",rightleftharpoons:"\u21CC",rightrightarrows:"\u21C9",rightsquigarrow:"\u219D",RightTee:"\u22A2",RightTeeArrow:"\u21A6",RightTeeVector:"\u295B",rightthreetimes:"\u22CC",RightTriangle:"\u22B3",RightTriangleBar:"\u29D0",RightTriangleEqual:"\u22B5",RightUpDownVector:"\u294F",RightUpTeeVector:"\u295C",RightUpVector:"\u21BE",RightUpVectorBar:"\u2954",RightVector:"\u21C0",RightVectorBar:"\u2953",ring:"\u02DA",risingdotseq:"\u2253",rlarr:"\u21C4",rlhar:"\u21CC",rlm:"\u200F",rmoust:"\u23B1",rmoustache:"\u23B1",rnmid:"\u2AEE",roang:"\u27ED",roarr:"\u21FE",robrk:"\u27E7",ropar:"\u2986",Ropf:"\u211D",ropf:"\u{1D563}",roplus:"\u2A2E",rotimes:"\u2A35",RoundImplies:"\u2970",rpar:")",rpargt:"\u2994",rppolint:"\u2A12",rrarr:"\u21C9",Rrightarrow:"\u21DB",rsaquo:"\u203A",Rscr:"\u211B",rscr:"\u{1D4C7}",Rsh:"\u21B1",rsh:"\u21B1",rsqb:"]",rsquo:"\u2019",rsquor:"\u2019",rthree:"\u22CC",rtimes:"\u22CA",rtri:"\u25B9",rtrie:"\u22B5",rtrif:"\u25B8",rtriltri:"\u29CE",RuleDelayed:"\u29F4",ruluhar:"\u2968",rx:"\u211E",Sacute:"\u015A",sacute:"\u015B",sbquo:"\u201A",Sc:"\u2ABC",sc:"\u227B",scap:"\u2AB8",Scaron:"\u0160",scaron:"\u0161",sccue:"\u227D",scE:"\u2AB4",sce:"\u2AB0",Scedil:"\u015E",scedil:"\u015F",Scirc:"\u015C",scirc:"\u015D",scnap:"\u2ABA",scnE:"\u2AB6",scnsim:"\u22E9",scpolint:"\u2A13",scsim:"\u227F",Scy:"\u0421",scy:"\u0441",sdot:"\u22C5",sdotb:"\u22A1",sdote:"\u2A66",searhk:"\u2925",seArr:"\u21D8",searr:"\u2198",searrow:"\u2198",sect:"\xA7",semi:";",seswar:"\u2929",setminus:"\u2216",setmn:"\u2216",sext:"\u2736",Sfr:"\u{1D516}",sfr:"\u{1D530}",sfrown:"\u2322",sharp:"\u266F",SHCHcy:"\u0429",shchcy:"\u0449",SHcy:"\u0428",shcy:"\u0448",ShortDownArrow:"\u2193",ShortLeftArrow:"\u2190",shortmid:"\u2223",shortparallel:"\u2225",ShortRightArrow:"\u2192",ShortUpArrow:"\u2191",shy:"\xAD",Sigma:"\u03A3",sigma:"\u03C3",sigmaf:"\u03C2",sigmav:"\u03C2",sim:"\u223C",simdot:"\u2A6A",sime:"\u2243",simeq:"\u2243",simg:"\u2A9E",simgE:"\u2AA0",siml:"\u2A9D",simlE:"\u2A9F",simne:"\u2246",simplus:"\u2A24",simrarr:"\u2972",slarr:"\u2190",SmallCircle:"\u2218",smallsetminus:"\u2216",smashp:"\u2A33",smeparsl:"\u29E4",smid:"\u2223",smile:"\u2323",smt:"\u2AAA",smte:"\u2AAC",smtes:"\u2AAC\uFE00",SOFTcy:"\u042C",softcy:"\u044C",sol:"/",solb:"\u29C4",solbar:"\u233F",Sopf:"\u{1D54A}",sopf:"\u{1D564}",spades:"\u2660",spadesuit:"\u2660",spar:"\u2225",sqcap:"\u2293",sqcaps:"\u2293\uFE00",sqcup:"\u2294",sqcups:"\u2294\uFE00",Sqrt:"\u221A",sqsub:"\u228F",sqsube:"\u2291",sqsubset:"\u228F",sqsubseteq:"\u2291",sqsup:"\u2290",sqsupe:"\u2292",sqsupset:"\u2290",sqsupseteq:"\u2292",squ:"\u25A1",Square:"\u25A1",square:"\u25A1",SquareIntersection:"\u2293",SquareSubset:"\u228F",SquareSubsetEqual:"\u2291",SquareSuperset:"\u2290",SquareSupersetEqual:"\u2292",SquareUnion:"\u2294",squarf:"\u25AA",squf:"\u25AA",srarr:"\u2192",Sscr:"\u{1D4AE}",sscr:"\u{1D4C8}",ssetmn:"\u2216",ssmile:"\u2323",sstarf:"\u22C6",Star:"\u22C6",star:"\u2606",starf:"\u2605",straightepsilon:"\u03F5",straightphi:"\u03D5",strns:"\xAF",Sub:"\u22D0",sub:"\u2282",subdot:"\u2ABD",subE:"\u2AC5",sube:"\u2286",subedot:"\u2AC3",submult:"\u2AC1",subnE:"\u2ACB",subne:"\u228A",subplus:"\u2ABF",subrarr:"\u2979",Subset:"\u22D0",subset:"\u2282",subseteq:"\u2286",subseteqq:"\u2AC5",SubsetEqual:"\u2286",subsetneq:"\u228A",subsetneqq:"\u2ACB",subsim:"\u2AC7",subsub:"\u2AD5",subsup:"\u2AD3",succ:"\u227B",succapprox:"\u2AB8",succcurlyeq:"\u227D",Succeeds:"\u227B",SucceedsEqual:"\u2AB0",SucceedsSlantEqual:"\u227D",SucceedsTilde:"\u227F",succeq:"\u2AB0",succnapprox:"\u2ABA",succneqq:"\u2AB6",succnsim:"\u22E9",succsim:"\u227F",SuchThat:"\u220B",Sum:"\u2211",sum:"\u2211",sung:"\u266A",Sup:"\u22D1",sup:"\u2283",sup1:"\xB9",sup2:"\xB2",sup3:"\xB3",supdot:"\u2ABE",supdsub:"\u2AD8",supE:"\u2AC6",supe:"\u2287",supedot:"\u2AC4",Superset:"\u2283",SupersetEqual:"\u2287",suphsol:"\u27C9",suphsub:"\u2AD7",suplarr:"\u297B",supmult:"\u2AC2",supnE:"\u2ACC",supne:"\u228B",supplus:"\u2AC0",Supset:"\u22D1",supset:"\u2283",supseteq:"\u2287",supseteqq:"\u2AC6",supsetneq:"\u228B",supsetneqq:"\u2ACC",supsim:"\u2AC8",supsub:"\u2AD4",supsup:"\u2AD6",swarhk:"\u2926",swArr:"\u21D9",swarr:"\u2199",swarrow:"\u2199",swnwar:"\u292A",szlig:"\xDF",Tab:" ",target:"\u2316",Tau:"\u03A4",tau:"\u03C4",tbrk:"\u23B4",Tcaron:"\u0164",tcaron:"\u0165",Tcedil:"\u0162",tcedil:"\u0163",Tcy:"\u0422",tcy:"\u0442",tdot:"\u20DB",telrec:"\u2315",Tfr:"\u{1D517}",tfr:"\u{1D531}",there4:"\u2234",Therefore:"\u2234",therefore:"\u2234",Theta:"\u0398",theta:"\u03B8",thetasym:"\u03D1",thetav:"\u03D1",thickapprox:"\u2248",thicksim:"\u223C",ThickSpace:"\u205F\u200A",thinsp:"\u2009",ThinSpace:"\u2009",thkap:"\u2248",thksim:"\u223C",THORN:"\xDE",thorn:"\xFE",Tilde:"\u223C",tilde:"\u02DC",TildeEqual:"\u2243",TildeFullEqual:"\u2245",TildeTilde:"\u2248",times:"\xD7",timesb:"\u22A0",timesbar:"\u2A31",timesd:"\u2A30",tint:"\u222D",toea:"\u2928",top:"\u22A4",topbot:"\u2336",topcir:"\u2AF1",Topf:"\u{1D54B}",topf:"\u{1D565}",topfork:"\u2ADA",tosa:"\u2929",tprime:"\u2034",TRADE:"\u2122",trade:"\u2122",triangle:"\u25B5",triangledown:"\u25BF",triangleleft:"\u25C3",trianglelefteq:"\u22B4",triangleq:"\u225C",triangleright:"\u25B9",trianglerighteq:"\u22B5",tridot:"\u25EC",trie:"\u225C",triminus:"\u2A3A",TripleDot:"\u20DB",triplus:"\u2A39",trisb:"\u29CD",tritime:"\u2A3B",trpezium:"\u23E2",Tscr:"\u{1D4AF}",tscr:"\u{1D4C9}",TScy:"\u0426",tscy:"\u0446",TSHcy:"\u040B",tshcy:"\u045B",Tstrok:"\u0166",tstrok:"\u0167",twixt:"\u226C",twoheadleftarrow:"\u219E",twoheadrightarrow:"\u21A0",Uacute:"\xDA",uacute:"\xFA",Uarr:"\u219F",uArr:"\u21D1",uarr:"\u2191",Uarrocir:"\u2949",Ubrcy:"\u040E",ubrcy:"\u045E",Ubreve:"\u016C",ubreve:"\u016D",Ucirc:"\xDB",ucirc:"\xFB",Ucy:"\u0423",ucy:"\u0443",udarr:"\u21C5",Udblac:"\u0170",udblac:"\u0171",udhar:"\u296E",ufisht:"\u297E",Ufr:"\u{1D518}",ufr:"\u{1D532}",Ugrave:"\xD9",ugrave:"\xF9",uHar:"\u2963",uharl:"\u21BF",uharr:"\u21BE",uhblk:"\u2580",ulcorn:"\u231C",ulcorner:"\u231C",ulcrop:"\u230F",ultri:"\u25F8",Umacr:"\u016A",umacr:"\u016B",uml:"\xA8",UnderBar:"_",UnderBrace:"\u23DF",UnderBracket:"\u23B5",UnderParenthesis:"\u23DD",Union:"\u22C3",UnionPlus:"\u228E",Uogon:"\u0172",uogon:"\u0173",Uopf:"\u{1D54C}",uopf:"\u{1D566}",UpArrow:"\u2191",Uparrow:"\u21D1",uparrow:"\u2191",UpArrowBar:"\u2912",UpArrowDownArrow:"\u21C5",UpDownArrow:"\u2195",Updownarrow:"\u21D5",updownarrow:"\u2195",UpEquilibrium:"\u296E",upharpoonleft:"\u21BF",upharpoonright:"\u21BE",uplus:"\u228E",UpperLeftArrow:"\u2196",UpperRightArrow:"\u2197",Upsi:"\u03D2",upsi:"\u03C5",upsih:"\u03D2",Upsilon:"\u03A5",upsilon:"\u03C5",UpTee:"\u22A5",UpTeeArrow:"\u21A5",upuparrows:"\u21C8",urcorn:"\u231D",urcorner:"\u231D",urcrop:"\u230E",Uring:"\u016E",uring:"\u016F",urtri:"\u25F9",Uscr:"\u{1D4B0}",uscr:"\u{1D4CA}",utdot:"\u22F0",Utilde:"\u0168",utilde:"\u0169",utri:"\u25B5",utrif:"\u25B4",uuarr:"\u21C8",Uuml:"\xDC",uuml:"\xFC",uwangle:"\u29A7",vangrt:"\u299C",varepsilon:"\u03F5",varkappa:"\u03F0",varnothing:"\u2205",varphi:"\u03D5",varpi:"\u03D6",varpropto:"\u221D",vArr:"\u21D5",varr:"\u2195",varrho:"\u03F1",varsigma:"\u03C2",varsubsetneq:"\u228A\uFE00",varsubsetneqq:"\u2ACB\uFE00",varsupsetneq:"\u228B\uFE00",varsupsetneqq:"\u2ACC\uFE00",vartheta:"\u03D1",vartriangleleft:"\u22B2",vartriangleright:"\u22B3",Vbar:"\u2AEB",vBar:"\u2AE8",vBarv:"\u2AE9",Vcy:"\u0412",vcy:"\u0432",VDash:"\u22AB",Vdash:"\u22A9",vDash:"\u22A8",vdash:"\u22A2",Vdashl:"\u2AE6",Vee:"\u22C1",vee:"\u2228",veebar:"\u22BB",veeeq:"\u225A",vellip:"\u22EE",Verbar:"\u2016",verbar:"|",Vert:"\u2016",vert:"|",VerticalBar:"\u2223",VerticalLine:"|",VerticalSeparator:"\u2758",VerticalTilde:"\u2240",VeryThinSpace:"\u200A",Vfr:"\u{1D519}",vfr:"\u{1D533}",vltri:"\u22B2",vnsub:"\u2282\u20D2",vnsup:"\u2283\u20D2",Vopf:"\u{1D54D}",vopf:"\u{1D567}",vprop:"\u221D",vrtri:"\u22B3",Vscr:"\u{1D4B1}",vscr:"\u{1D4CB}",vsubnE:"\u2ACB\uFE00",vsubne:"\u228A\uFE00",vsupnE:"\u2ACC\uFE00",vsupne:"\u228B\uFE00",Vvdash:"\u22AA",vzigzag:"\u299A",Wcirc:"\u0174",wcirc:"\u0175",wedbar:"\u2A5F",Wedge:"\u22C0",wedge:"\u2227",wedgeq:"\u2259",weierp:"\u2118",Wfr:"\u{1D51A}",wfr:"\u{1D534}",Wopf:"\u{1D54E}",wopf:"\u{1D568}",wp:"\u2118",wr:"\u2240",wreath:"\u2240",Wscr:"\u{1D4B2}",wscr:"\u{1D4CC}",xcap:"\u22C2",xcirc:"\u25EF",xcup:"\u22C3",xdtri:"\u25BD",Xfr:"\u{1D51B}",xfr:"\u{1D535}",xhArr:"\u27FA",xharr:"\u27F7",Xi:"\u039E",xi:"\u03BE",xlArr:"\u27F8",xlarr:"\u27F5",xmap:"\u27FC",xnis:"\u22FB",xodot:"\u2A00",Xopf:"\u{1D54F}",xopf:"\u{1D569}",xoplus:"\u2A01",xotime:"\u2A02",xrArr:"\u27F9",xrarr:"\u27F6",Xscr:"\u{1D4B3}",xscr:"\u{1D4CD}",xsqcup:"\u2A06",xuplus:"\u2A04",xutri:"\u25B3",xvee:"\u22C1",xwedge:"\u22C0",Yacute:"\xDD",yacute:"\xFD",YAcy:"\u042F",yacy:"\u044F",Ycirc:"\u0176",ycirc:"\u0177",Ycy:"\u042B",ycy:"\u044B",yen:"\xA5",Yfr:"\u{1D51C}",yfr:"\u{1D536}",YIcy:"\u0407",yicy:"\u0457",Yopf:"\u{1D550}",yopf:"\u{1D56A}",Yscr:"\u{1D4B4}",yscr:"\u{1D4CE}",YUcy:"\u042E",yucy:"\u044E",Yuml:"\u0178",yuml:"\xFF",Zacute:"\u0179",zacute:"\u017A",Zcaron:"\u017D",zcaron:"\u017E",Zcy:"\u0417",zcy:"\u0437",Zdot:"\u017B",zdot:"\u017C",zeetrf:"\u2128",ZeroWidthSpace:"\u200B",Zeta:"\u0396",zeta:"\u03B6",Zfr:"\u2128",zfr:"\u{1D537}",ZHcy:"\u0416",zhcy:"\u0436",zigrarr:"\u21DD",Zopf:"\u2124",zopf:"\u{1D56B}",Zscr:"\u{1D4B5}",zscr:"\u{1D4CF}",zwj:"\u200D",zwnj:"\u200C"});mo.entityMap=mo.HTML_ENTITIES});var mv=v(gd=>{var vo=Li().NAMESPACE,hd=Li().tagNamePattern,Bi=0,_n=1,$i=2,ho=3,qi=4,Vi=5,go=6,Zs=7;function Gi(e,t){this.message=e,this.locator=t,Error.captureStackTrace&&Error.captureStackTrace(this,Gi)}Gi.prototype=new Error;Gi.prototype.name=Gi.name;function pv(){}pv.prototype={parse:function(e,t,r){var n=this.domBuilder;n.startDocument(),PF(t,t={}),DF(e,t,r,n,this.errorHandler),n.endDocument()}};function DF(e,t,r,n,i){function a(ue){if(ue>65535){ue-=65536;var $e=55296+(ue>>10),xe=56320+(ue&1023);return String.fromCharCode($e,xe)}else return String.fromCharCode(ue)}function o(ue){var $e=ue.slice(1,-1);return Object.hasOwnProperty.call(r,$e)?r[$e]:$e.charAt(0)==="#"?a(parseInt($e.substr(1).replace("x","0x"))):(i.error("entity not found:"+ue),ue)}function s(ue){if(ue>g){var $e=e.substring(g,ue).replace(/&#?\w+;/g,o);p&&l(g),n.characters($e,0,ue-g),g=ue}}function l(ue,$e){for(;ue>=c&&($e=d.exec(e));)u=$e.index,c=u+$e[0].length,p.lineNumber++;p.columnNumber=ue-u+1}for(var u=0,c=0,d=/.*(?:\r\n?|\n)|.*$/g,p=n.locator,f=[{currentNSMap:t}],m={},g=0;;){try{var y=e.indexOf("<",g);if(y<0){if(!e.substr(g).match(/^\s*$/)){var A=n.doc,D=A.createTextNode(e.substr(g));A.appendChild(D),n.currentElement=D}return}switch(y>g&&s(y),e.charAt(y+1)){case"/":var V=e.indexOf(">",y+3),F=e.substring(y+2,V).replace(/^([\s\S]*?[^ \t\n\r])?[ \t\n\r]*$/,"$1"),_=f.pop();V<0?(F=e.substring(y+2).replace(/[\s<].*/,""),i.error("end tag name: "+F+" is not complete:"+_.tagName),V=y+1+F.length):F.match(/\s</)?(F=F.replace(/[\s<].*/,""),i.error("end tag name: "+F+" maybe not complete"),V=y+1+F.length):/[ \t\n\r]/.test(F)&&hd.test(F.split(/[ \t\n\r]/)[0])&&i.error('end tag name is followed by whitespace and trailing content: "'+F+'"');var q=_.localNSMap,B=_.tagName==F,L=B||_.tagName&&_.tagName.toLowerCase()==F.toLowerCase();if(L){if(n.endElement(_.uri,_.localName,F),q)for(var k in q)Object.prototype.hasOwnProperty.call(q,k)&&n.endPrefixMapping(k);B||i.fatalError("end tag name: "+F+" is not match the current start tagName:"+_.tagName)}else f.push(_);V++;break;case"?":p&&l(y),V=RF(e,y,n);break;case"!":p&&l(y),V=OF(e,y,n,i);break;default:p&&l(y);var M=new fv,G=f[f.length-1].currentNSMap,V=IF(e,y,M,G,o,i),Ze=M.length;if(!M.closed&&TF(e,V,M.tagName,m)&&(M.closed=!0,r.nbsp||i.warning("unclosed xml attribute")),p&&Ze){for(var ir=cv(p,{}),et=0;et<Ze;et++){var dt=M[et];l(dt.offset),dt.locator=cv(p,{})}n.locator=ir,dv(M,n,G)&&f.push(M),n.locator=p}else dv(M,n,G)&&f.push(M);vo.isHTML(M.uri)&&!M.closed?V=_F(e,V,M.tagName,o,n):V++}}catch(ue){if(ue instanceof Gi)throw ue;i.error("element parse error: "+ue),V=-1}V>g?g=V:s(Math.max(y,g)+1)}}function cv(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}function IF(e,t,r,n,i,a){function o(f,m,g){r.attributeNames.hasOwnProperty(f)&&a.fatalError("Attribute "+f+" redefined"),r.addValue(f,m.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,i),g)}for(var s,l,u=++t,c=Bi;;){var d=e.charAt(u);if(c===Bi&&d==="<")throw new Error("unexpected < in tag name: "+e.slice(t,u));switch(d){case"=":if(c===_n)s=e.slice(t,u),c=ho;else if(c===$i)c=ho;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(c===ho||c===_n)if(c===_n&&(a.warning('attribute value must after "="'),s=e.slice(t,u)),t=u+1,u=e.indexOf(d,t),u>0)l=e.slice(t,u),o(s,l,t-1),c=Vi;else throw new Error("attribute value no end '"+d+"' match");else if(c==qi)l=e.slice(t,u),o(s,l,t),a.warning('attribute "'+s+'" missed start quot('+d+")!!"),t=u+1,c=Vi;else throw new Error('attribute value must after "="');break;case"/":switch(c){case Bi:r.setTagName(e.slice(t,u));case Vi:case go:case Zs:c=Zs,r.closed=!0;case qi:case _n:break;case $i:r.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return a.error("unexpected end of input"),c==Bi&&r.setTagName(e.slice(t,u)),u;case">":switch(c){case Bi:r.setTagName(e.slice(t,u));case Vi:case go:case Zs:break;case qi:case _n:l=e.slice(t,u),l.slice(-1)==="/"&&(r.closed=!0,l=l.slice(0,-1));case $i:c===$i&&(l=s),c==qi?(a.warning('attribute "'+l+'" missed quot(")!'),o(s,l,t)):((!vo.isHTML(n[""])||!l.match(/^(?:disabled|checked|selected)$/i))&&a.warning('attribute "'+l+'" missed value!! "'+l+'" instead!!'),o(l,l,t));break;case ho:throw new Error("attribute value missed!!")}return u;case"\x80":d=" ";default:if(d<=" ")switch(c){case Bi:r.setTagName(e.slice(t,u)),c=go;break;case _n:s=e.slice(t,u),c=$i;break;case qi:var l=e.slice(t,u);a.warning('attribute "'+l+'" missed quot(")!!'),o(s,l,t);case Vi:c=go;break}else switch(c){case $i:var p=r.tagName;(!vo.isHTML(n[""])||!s.match(/^(?:disabled|checked|selected)$/i))&&a.warning('attribute "'+s+'" missed value!! "'+s+'" instead2!!'),o(s,s,t),t=u,c=_n;break;case Vi:a.warning('attribute space is required"'+s+'"!!');case go:c=_n,t=u;break;case ho:c=qi,t=u;break;case Zs:throw new Error("elements closed character '/' and '>' must be connected to")}}u++}}function dv(e,t,r){for(var n=e.tagName,i=null,d=e.length;d--;){var a=e[d],o=a.qName,s=a.value,p=o.indexOf(":");if(p>0)var l=a.prefix=o.slice(0,p),u=o.slice(p+1),c=l==="xmlns"&&u;else u=o,l=null,c=o==="xmlns"&&"";a.localName=u,c!==!1&&(i==null&&(i={},r=Object.create(r)),r[c]=i[c]=s,a.uri=vo.XMLNS,t.startPrefixMapping(c,s))}for(var d=e.length;d--;){a=e[d];var l=a.prefix;l&&(l==="xml"&&(a.uri=vo.XML),l!=="xmlns"&&(a.uri=r[l||""]))}var p=n.indexOf(":");p>0?(l=e.prefix=n.slice(0,p),u=e.localName=n.slice(p+1)):(l=null,u=e.localName=n);var f=e.uri=r[l||""];if(t.startElement(f,u,n,e),e.closed){if(t.endElement(f,u,n),i)for(l in i)Object.prototype.hasOwnProperty.call(i,l)&&t.endPrefixMapping(l)}else return e.currentNSMap=r,e.localNSMap=i,!0}function _F(e,t,r,n,i){if(/^(?:script|textarea)$/i.test(r)){var a=e.indexOf("</"+r+">",t),o=e.substring(t+1,a);if(/[&<]/.test(o))return/^script$/i.test(r)?(i.characters(o,0,o.length),a):(o=o.replace(/&#?\w+;/g,n),i.characters(o,0,o.length),a)}return t+1}function TF(e,t,r,n){var i=n[r];return i==null&&(i=e.lastIndexOf("</"+r+">"),i<t&&(i=e.lastIndexOf("</"+r)),n[r]=i),i<t}function PF(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function OF(e,t,r,n){var i=e.charAt(t+2);switch(i){case"-":if(e.charAt(t+3)==="-"){var a=e.indexOf("-->",t+4);return a>t?(r.comment(e,t+4,a-t-4),a+3):(n.error("Unclosed comment"),-1)}else return-1;default:if(e.substr(t+3,6)=="CDATA["){var a=e.indexOf("]]>",t+9);return r.startCDATA(),r.characters(e,t+9,a-t-9),r.endCDATA(),a+3}var o=FF(e,t),s=o.length;if(s>1&&/!doctype/i.test(o[0][0])){var l=o[1][0],u=!1,c=!1;s>3&&(/^public$/i.test(o[2][0])?(u=o[3][0],c=s>4&&o[4][0]):/^system$/i.test(o[2][0])&&(c=o[3][0]));var d=o[s-1];return r.startDTD(l,u,c),r.endDTD(),d.index+d[0].length}}return-1}function RF(e,t,r){var n=e.indexOf("?>",t);if(n){var i=e.substring(t,n).match(/^<\?(\S*)\s*([\s\S]*?)$/);if(i){var a=i[0].length;return r.processingInstruction(i[1],i[2]),n+2}else return-1}return-1}function fv(){this.attributeNames={}}fv.prototype={setTagName:function(e){if(!hd.test(e))throw new Error("invalid tagName:"+e);this.tagName=e},addValue:function(e,t,r){if(!hd.test(e))throw new Error("invalid attribute:"+e);this.attributeNames[e]=this.length,this[this.length++]={qName:e,value:t,offset:r}},length:0,getLocalName:function(e){return this[e].localName},getLocator:function(e){return this[e].locator},getQName:function(e){return this[e].qName},getURI:function(e){return this[e].uri},getValue:function(e){return this[e].value}};function FF(e,t){var r,n=[],i=/'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;for(i.lastIndex=t,i.exec(e);r=i.exec(e);)if(n.push(r),r[1])return n}gd.XMLReader=pv;gd.ParseError=Gi});var Av=v(tl=>{var xF=Li(),LF=md(),hv=uv(),yv=mv(),kF=LF.DOMImplementation,gv=xF.NAMESPACE,MF=yv.ParseError,UF=yv.XMLReader;function bv(e){return e.replace(/\r[\n\u0085]/g,`+`);if(f===-1)return;let m=p.slice(0,f),h=p.slice(f+4);if(!/^Content-Type:\s*application\/http\b/im.test(m))return;let v=/^HTTP\/1\.[01] (\d{3})\b/.exec(h);if(!v||((i=h.match(/^HTTP\/1\.[01] \d{3}\b/gm))!==null&&i!==void 0?i:[]).length!==1)return;let w=(a=/^Content-ID:\s*(\S+)/im.exec(m))===null||a===void 0?void 0:a[1];if(w===void 0||d.has(w)||!u.has(w))return;d.add(w),c.push(Number(v[1]))}return c.length===0?void 0:c}Fn.parseChangeSetStatuses=Iv;async function xL(e,t,r){if(t.length===0)return;let{body:n,batchId:i,contentIds:a}=Dv(e,t),o=await e.postBatch(n,i),s=e.apiUrl("/$batch");if((0,OL.ensureSuccess)(o,s),typeof o.body!="string"||o.body.length===0)throw new pi.ConnectionError(s,o.status,`atomic write of ${r} cannot be confirmed: the $batch response had no readable body, so the change set's outcome is unknown`);let l=Iv(o.body,a);if(l===void 0)throw new pi.ConnectionError(s,o.status,`atomic write of ${r} cannot be confirmed: the $batch response could not be parsed as a change set, so the outcome is unknown`);if(l.length!==t.length)throw new pi.ConnectionError(s,o.status,`atomic write of ${r} cannot be confirmed: the change set reported ${l.length} result(s) for ${t.length} operation(s)`);let u=l.find(c=>c<200||c>=300);if(u!==void 0)throw new pi.ConnectionError(s,u,`atomic write of ${r} was rolled back: the change set reported HTTP ${u}`)}Fn.postChangeSet=xL});var pl=y(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.updateTable=K.deleteAlternateKey=K.createAlternateKey=K.deleteGlobalOptionSet=K.createGlobalOptionSet=K.deleteRelationship=K.deleteColumn=K.updateColumn=K.deleteTable=K.createRelationship=K.insertStatusValue=K.createCustomerColumn=K.createColumns=K.setColumnVisualization=K.getColumnVisualization=K.createColumn=K.createTable=K.resolveEntitySetName=K.pluralFallback=void 0;var ce=Ee(),J=le(),xr=Ji(),he=ee(),LL=dl(),FL={String:"Microsoft.Dynamics.CRM.StringAttributeMetadata",Memo:"Microsoft.Dynamics.CRM.MemoAttributeMetadata",Integer:"Microsoft.Dynamics.CRM.IntegerAttributeMetadata",Decimal:"Microsoft.Dynamics.CRM.DecimalAttributeMetadata",Money:"Microsoft.Dynamics.CRM.MoneyAttributeMetadata",Boolean:"Microsoft.Dynamics.CRM.BooleanAttributeMetadata",DateTime:"Microsoft.Dynamics.CRM.DateTimeAttributeMetadata",Picklist:"Microsoft.Dynamics.CRM.PicklistAttributeMetadata",Lookup:"Microsoft.Dynamics.CRM.LookupAttributeMetadata"};function Oe(e,t){return{"@odata.type":"Microsoft.Dynamics.CRM.Label",LocalizedLabels:kL(e,t)}}var _v=65535;function kL(e,t){let r=(a,o)=>({"@odata.type":"Microsoft.Dynamics.CRM.LocalizedLabel",Label:a,LanguageCode:o});if(typeof e=="string")return[r(e,t)];let n=Object.entries(e);if(!n.length)throw new he.InvalidArgumentError("a localized label must contain at least one language");let i=new Set;return n.map(([a,o])=>{if(!/^[1-9]\d*$/.test(a))throw new he.InvalidArgumentError(`localized label key '${a}' is not an LCID (expected a canonical positive integer, e.g. 1033)`);let s=Number(a);if(s>_v)throw new he.InvalidArgumentError(`localized label LCID ${s} is out of range (1-${_v})`);if(i.has(s))throw new he.InvalidArgumentError(`localized label LCID ${s} is specified more than once`);if(i.add(s),typeof o!="string")throw new he.InvalidArgumentError(`localized label for LCID ${s} must be a string`);return r(o,s)})}function Ov(e){return typeof e=="string"?`${e}s`:Object.fromEntries(Object.entries(e).map(([t,r])=>{if(typeof r!="string")throw new he.InvalidArgumentError(`localized label for LCID ${t} must be a string`);return[t,`${r}s`]}))}K.pluralFallback=Ov;function Eo(e){return{Value:e,CanBeChanged:!0,ManagedPropertyLogicalName:"canmodifyrequirementlevelsettings"}}function $d(e){let t=e.indexOf("_");return t>0?e.slice(0,t):e}function Tv(e,t,r){let n=e[t];n&&typeof n=="object"?n.Value=r:e[t]={Value:r}}function So(e){let t=(0,ce.readCreatedId)(e,"MetadataId");if(!t)throw new he.InvalidArgumentError("Dataverse did not return a MetadataId for the created metadata component");return t}function ML(e,t,r){var n,i,a,o,s,l,u,c,d,p,f,m,h,v,w,C,E,D,O,x,F,M,P,q;if(t.defaultValue!==void 0&&e!=="boolean")throw new he.InvalidArgumentError(`createColumn: 'defaultValue' applies to boolean columns, but '${t.schemaName}' is of type '${e}'.`);if(t.integerFormat!==void 0&&e!=="integer")throw new he.InvalidArgumentError(`createColumn: 'integerFormat' applies to integer columns, but '${t.schemaName}' is of type '${e}'.`);switch(e){case"string":return{"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},MaxLength:(n=t.maxLength)!==null&&n!==void 0?n:100,FormatName:{Value:(i=t.stringFormat)!==null&&i!==void 0?i:"Text"}};case"memo":return{"@odata.type":"Microsoft.Dynamics.CRM.MemoAttributeMetadata",AttributeType:"Memo",AttributeTypeName:{Value:"MemoType"},MaxLength:(a=t.maxLength)!==null&&a!==void 0?a:2e3,Format:"TextArea"};case"integer":return{"@odata.type":"Microsoft.Dynamics.CRM.IntegerAttributeMetadata",AttributeType:"Integer",AttributeTypeName:{Value:"IntegerType"},Format:(o=t.integerFormat)!==null&&o!==void 0?o:"None",MinValue:(s=t.minValue)!==null&&s!==void 0?s:-2147483648,MaxValue:(l=t.maxValue)!==null&&l!==void 0?l:2147483647};case"bigint":return{"@odata.type":"Microsoft.Dynamics.CRM.BigIntAttributeMetadata",AttributeType:"BigInt",AttributeTypeName:{Value:"BigIntType"}};case"double":return{"@odata.type":"Microsoft.Dynamics.CRM.DoubleAttributeMetadata",AttributeType:"Double",AttributeTypeName:{Value:"DoubleType"},Precision:(u=t.precision)!==null&&u!==void 0?u:2,MinValue:(c=t.minValue)!==null&&c!==void 0?c:-1e11,MaxValue:(d=t.maxValue)!==null&&d!==void 0?d:1e11};case"decimal":return{"@odata.type":"Microsoft.Dynamics.CRM.DecimalAttributeMetadata",AttributeType:"Decimal",AttributeTypeName:{Value:"DecimalType"},Precision:(p=t.precision)!==null&&p!==void 0?p:2,MinValue:(f=t.minValue)!==null&&f!==void 0?f:-1e11,MaxValue:(m=t.maxValue)!==null&&m!==void 0?m:1e11};case"money":return{"@odata.type":"Microsoft.Dynamics.CRM.MoneyAttributeMetadata",AttributeType:"Money",AttributeTypeName:{Value:"MoneyType"},Precision:(h=t.precision)!==null&&h!==void 0?h:2,PrecisionSource:2,MinValue:(v=t.minValue)!==null&&v!==void 0?v:0,MaxValue:(w=t.maxValue)!==null&&w!==void 0?w:1e9};case"boolean":return{"@odata.type":"Microsoft.Dynamics.CRM.BooleanAttributeMetadata",AttributeType:"Boolean",AttributeTypeName:{Value:"BooleanType"},DefaultValue:(C=t.defaultValue)!==null&&C!==void 0?C:!1,OptionSet:{"@odata.type":"Microsoft.Dynamics.CRM.BooleanOptionSetMetadata",TrueOption:{Value:1,Label:Oe((E=t.trueLabel)!==null&&E!==void 0?E:"Yes",r)},FalseOption:{Value:0,Label:Oe((D=t.falseLabel)!==null&&D!==void 0?D:"No",r)}}};case"dateTime":return{"@odata.type":"Microsoft.Dynamics.CRM.DateTimeAttributeMetadata",AttributeType:"DateTime",AttributeTypeName:{Value:"DateTimeType"},Format:(O=t.dateFormat)!==null&&O!==void 0?O:"DateAndTime"};case"choice":return Pv(t,r,!1);case"multiChoice":return Pv(t,r,!0);case"file":return{"@odata.type":"Microsoft.Dynamics.CRM.FileAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"FileType"},MaxSizeInKB:(x=t.maxSizeKb)!==null&&x!==void 0?x:10240};case"image":return{"@odata.type":"Microsoft.Dynamics.CRM.ImageAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"ImageType"},IsPrimaryImage:(F=t.isPrimaryImage)!==null&&F!==void 0?F:!1,MaxSizeInKB:(M=t.maxSizeKb)!==null&&M!==void 0?M:10240};case"autonumber":return{"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},FormatName:{Value:"Text"},MaxLength:(P=t.maxLength)!==null&&P!==void 0?P:100,AutoNumberFormat:(q=t.autoNumberFormat)!==null&&q!==void 0?q:""};default:throw new he.InvalidArgumentError(`unsupported column type '${String(e)}'`)}}function Pv(e,t,r){let i={"@odata.type":r?"Microsoft.Dynamics.CRM.MultiSelectPicklistAttributeMetadata":"Microsoft.Dynamics.CRM.PicklistAttributeMetadata",AttributeType:r?"Virtual":"Picklist",AttributeTypeName:{Value:r?"MultiSelectPicklistType":"PicklistType"}};if(e.globalChoiceMetadataId)return i["[email protected]"]=`/GlobalOptionSetDefinitions(${(0,J.normalizeGuid)(e.globalChoiceMetadataId,"globalChoiceMetadataId")})`,i;if(!e.options||e.options.length===0)throw new he.InvalidArgumentError(`choice column '${e.schemaName}' requires at least one option (or a globalChoiceMetadataId)`);return i.OptionSet={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",IsGlobal:!1,OptionSetType:"Picklist",Options:e.options.map(a=>({Value:a.value,Label:Oe(a.label,t)}))},i}var Bd=new WeakMap;async function BL(e,t){var r,n;let i=(r=Bd.get(e))===null||r===void 0?void 0:r.get(t);if(i)return i;let a=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')${(0,J.odataQuery)([["$select","EntitySetName"]])}`,s=(n=(0,ce.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.EntitySetName;if(!s)throw new he.InvalidArgumentError(`could not resolve EntitySetName for '${t}'`);(0,J.assertODataName)(s,`server-derived EntitySetName for '${t}'`);let l=Bd.get(e);return l||(l=new Map,Bd.set(e,l)),l.set(t,s),s}K.resolveEntitySetName=BL;async function UL(e,t){var r,n,i,a,o,s,l,u,c,d,p,f,m,h,v;let w=(r=t.languageCode)!==null&&r!==void 0?r:xr.DEFAULT_LCID,C=$d(t.schemaName),E=(n=t.primaryColumnSchemaName)!==null&&n!==void 0?n:`${C}_Name`,D={"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},SchemaName:E,RequiredLevel:Eo("None"),MaxLength:(i=t.primaryColumnMaxLength)!==null&&i!==void 0?i:100,FormatName:{Value:"Text"},DisplayName:Oe((a=t.primaryColumnDisplayName)!==null&&a!==void 0?a:"Name",w),IsPrimaryName:!0};t.primaryColumnAutoNumberFormat&&(D.AutoNumberFormat=t.primaryColumnAutoNumberFormat),t.columns&&Fv(t.columns,"createTable");let O={"@odata.type":"Microsoft.Dynamics.CRM.EntityMetadata",SchemaName:t.schemaName,DisplayName:Oe(t.displayName,w),DisplayCollectionName:Oe((o=t.pluralName)!==null&&o!==void 0?o:Ov(t.displayName),w),OwnershipType:(s=t.ownership)!==null&&s!==void 0?s:"UserOwned",IsActivity:!1,HasActivities:(l=t.hasActivities)!==null&&l!==void 0?l:!1,HasNotes:(u=t.hasNotes)!==null&&u!==void 0?u:!1,Attributes:[D,...((c=t.columns)!==null&&c!==void 0?c:[]).map(ke=>qd(ke,w))]};t.description&&(O.Description=Oe(t.description,w));let x="/EntityDefinitions",F=(0,ce.ensureSuccess)(await e.post(x,O),e.apiUrl(x)),M=So(F),P=`/EntityDefinitions(${M})`+(0,J.odataQuery)([["$select","LogicalName,EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute"]]),q=Math.max(1,Math.trunc((d=t.readBackAttempts)!==null&&d!==void 0?d:6)),$=Math.max(0,(p=t.readBackDelayMs)!==null&&p!==void 0?p:1e3),qe;for(let ke=1;ke<=q;ke+=1){let He=await e.get(P);if(He.status>=200&&He.status<300){qe=He;break}He.status!==404&&(0,ce.ensureSuccess)(He,e.apiUrl(P)),ke<q&&$>0&&await new Promise(X=>setTimeout(X,$))}if(!qe)throw new he.SdkError("TABLE_METADATA_NOT_VISIBLE",`Table '${t.schemaName}' WAS CREATED (MetadataId ${M}) but its metadata was still not readable after ${q} attempt(s). Do NOT re-run the create \u2014 it will collide on the schema name. Re-read /EntityDefinitions(${M}) once the environment catches up, or raise 'readBackAttempts'.`);let Nt=qe.body;return{logicalName:(f=Nt.LogicalName)!==null&&f!==void 0?f:t.schemaName.toLowerCase(),metadataId:M,entitySetName:(m=Nt.EntitySetName)!==null&&m!==void 0?m:"",primaryIdAttribute:(h=Nt.PrimaryIdAttribute)!==null&&h!==void 0?h:`${t.schemaName.toLowerCase()}id`,primaryNameAttribute:(v=Nt.PrimaryNameAttribute)!==null&&v!==void 0?v:E.toLowerCase()}}K.createTable=UL;function qd(e,t){var r,n;let i=(r=e.languageCode)!==null&&r!==void 0?r:t,a={...ML(e.type,e,i),SchemaName:e.schemaName,RequiredLevel:Eo((n=e.required)!==null&&n!==void 0?n:"None"),DisplayName:Oe(e.displayName,i)};return e.description&&(a.Description=Oe(e.description,i)),e.sourceType&&e.sourceType!=="Simple"&&(a.SourceType=e.sourceType==="Rollup"?2:1,e.formulaDefinition&&(a.FormulaDefinition=e.formulaDefinition)),xv(a,e),a}function xv(e,t){t.isValidForCreate!==void 0&&(e.IsValidForCreate=t.isValidForCreate),t.isValidForUpdate!==void 0&&(e.IsValidForUpdate=t.isValidForUpdate),t.isValidForRead!==void 0&&(e.IsValidForRead=t.isValidForRead)}async function $L(e,t,r){var n;let i=qd(r,(n=r.languageCode)!==null&&n!==void 0?n:xr.DEFAULT_LCID),a=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Attributes`,o=(0,ce.ensureSuccess)(await e.post(a,i),e.apiUrl(a)),s={logicalName:r.schemaName.toLowerCase(),metadataId:So(o)};if(r.visualization&&r.visualization!=="None")try{await Bv(e,t,s.logicalName,s.metadataId,r.visualization)}catch(l){let u=new he.SdkError("COLUMN_VISUALIZATION_BIND_FAILED",`Column '${s.logicalName}' on '${t}' was created, but binding its '${r.visualization}' grid visualization failed; the column exists WITHOUT a visualization. Retry with setColumnVisualization('${t}', '${s.logicalName}', '${r.visualization}'). Cause: ${l instanceof Error?l.message:String(l)}`);throw u.cause=l,u}return s}K.createColumn=$L;var Qi="/controlconfigurations",Lv="CustomRenderersConfiguration",Ud={RadialDial:"c3d4e5f6-a7b8-9012-cdef-345678901234",LineChart:"a1b2c3d4-e5f6-7890-abcd-ef1234567890",HeatMap:"e7f8a9b0-c1d2-4e3f-5a6b-7c8d9e0f1a2b",StarRating:"b5e4c3d2-f1a0-4e2b-8a7c-9d3f5c1e6b04"};function Fv(e,t){let r=e.find(n=>n.visualization&&n.visualization!=="None");if(r)throw new he.InvalidArgumentError(`${t}: setting 'visualization' on an inline column ('${r.schemaName}') is not supported \u2014 the attribute metadata and its control-configuration row are separate writes. Create the column, then call setColumnVisualization; or use the single-column createColumn.`)}function kv(e){return JSON.stringify({type:Ud[e]})}function qL(e){if(!e)return"None";let t;try{t=JSON.parse(e)}catch{return"None"}let r=t?.type,n=Object.keys(Ud).find(i=>Ud[i]===r);return n??"None"}async function Mv(e,t,r){var n,i;let a=`entitylogicalname eq '${(0,J.odataLiteral)(t)}' and Attribute/logicalname eq '${(0,J.odataLiteral)(r)}'`,o=`${Qi}${(0,J.odataQuery)([["$select","name,uniquename,metadatajson"],["$expand","Attribute($select=name,logicalname)"],["$filter",a]])}`,l=(i=(n=(0,ce.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[],u=r.toLowerCase();return l.filter(c=>{var d,p;return((p=(d=c.Attribute)===null||d===void 0?void 0:d.logicalname)===null||p===void 0?void 0:p.toLowerCase())===u})}async function VL(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Attributes(LogicalName='${(0,J.odataPathLiteral)(r)}')${(0,J.odataQuery)([["$select","MetadataId"]])}`,o=(n=(0,ce.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||n===void 0?void 0:n.MetadataId;if(!o)throw new he.InvalidArgumentError(`cannot resolve column '${r}' on '${t}' to set its visualization`);return(0,J.normalizeGuid)(o,"MetadataId")}async function Bv(e,t,r,n,i){let a={name:Lv,uniquename:`msdyn_${t}_${r}_customrenderers`,metadatajson:kv(i),"[email protected]":`/attributes(${(0,J.normalizeGuid)(n,"MetadataId")})`,entitylogicalname:t};(0,ce.ensureSuccess)(await e.post(Qi,a),e.apiUrl(Qi))}async function GL(e,t,r){var n;let i=await Mv(e,t,r);return qL((n=i[0])===null||n===void 0?void 0:n.metadatajson)}K.getColumnVisualization=GL;async function zL(e,t,r,n){let a=(await Mv(e,t,r)).map(u=>u.controlconfigurationid).filter(u=>!!u);if(n==="None"){for(let u of a){let c=`${Qi}(${(0,J.normalizeGuid)(u,"controlconfigurationid")})`;(0,ce.ensureSuccess)(await e.delete(c),e.apiUrl(c))}return}let[o,...s]=a,l=await VL(e,t,r);if(o){let u=`${Qi}(${(0,J.normalizeGuid)(o,"controlconfigurationid")})`,c={name:Lv,metadatajson:kv(n),"[email protected]":`/attributes(${l})`,entitylogicalname:t};(0,ce.ensureSuccess)(await e.patch(u,c),e.apiUrl(u))}else await Bv(e,t,r,l,n);for(let u of s){let c=`${Qi}(${(0,J.normalizeGuid)(u,"controlconfigurationid")})`;(0,ce.ensureSuccess)(await e.delete(c),e.apiUrl(c))}}K.setColumnVisualization=zL;async function WL(e,t,r){if(r.length===0)return;if(Fv(r,"createColumns"),!e.supportsAtomicBatch)throw new he.InvalidArgumentError(`createColumns writes ${r.length} columns on '${t}' as ONE atomic change set, which needs a verbatim request body. Implement HttpClient.postRaw, or call createColumn per column and accept that a failure can leave the table partly extended.`);let n=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Attributes`;await(0,LL.postChangeSet)(e,r.map(i=>{var a;return{method:"POST",path:n,body:qd(i,(a=i.languageCode)!==null&&a!==void 0?a:xr.DEFAULT_LCID)}}),`${r.length} column(s) on '${t}'`)}K.createColumns=WL;async function jL(e,t,r){var n,i,a,o;let s=(n=r.languageCode)!==null&&n!==void 0?n:xr.DEFAULT_LCID,l=$d(r.schemaName),u=(i=r.accountRelationshipName)!==null&&i!==void 0?i:`${l}_${t}_account`,c=(a=r.contactRelationshipName)!==null&&a!==void 0?a:`${l}_${t}_contact`,d={Lookup:{"@odata.type":"Microsoft.Dynamics.CRM.ComplexLookupAttributeMetadata",SchemaName:r.schemaName,DisplayName:Oe(r.displayName,s),RequiredLevel:Eo((o=r.required)!==null&&o!==void 0?o:"None"),Targets:["account","contact"]},OneToManyRelationships:[{"@odata.type":"Microsoft.Dynamics.CRM.ComplexOneToManyRelationshipMetadata",SchemaName:u,ReferencedEntity:"account",ReferencingEntity:t},{"@odata.type":"Microsoft.Dynamics.CRM.ComplexOneToManyRelationshipMetadata",SchemaName:c,ReferencedEntity:"contact",ReferencingEntity:t}]};return(0,ce.ensureSuccess)(await e.post("/CreateCustomerRelationships",d),e.apiUrl("/CreateCustomerRelationships")),{logicalName:r.schemaName.toLowerCase(),metadataId:""}}K.createCustomerColumn=jL;async function HL(e,t,r){var n,i,a,o,s;let l=(n=r.languageCode)!==null&&n!==void 0?n:xr.DEFAULT_LCID,u={EntityLogicalName:t,AttributeLogicalName:"statuscode",Label:Oe(r.label,l),StateCode:(i=r.stateCode)!==null&&i!==void 0?i:0};typeof r.value=="number"&&(u.Value=r.value),r.color&&(u.Color=r.color);let c=(0,ce.ensureSuccess)(await e.post("/InsertStatusValue",u),e.apiUrl("/InsertStatusValue"));return Number((s=(o=(a=c.body)===null||a===void 0?void 0:a.NewOptionValue)!==null&&o!==void 0?o:r.value)!==null&&s!==void 0?s:0)}K.insertStatusValue=HL;async function JL(e,t){var r,n,i,a,o;let s=(r=t.languageCode)!==null&&r!==void 0?r:xr.DEFAULT_LCID,l,u;if(t.type==="OneToMany"){if(!t.referencedEntity||!t.referencingEntity)throw new he.InvalidArgumentError("OneToMany relationship requires referencedEntity and referencingEntity");let p=(n=t.lookupSchemaName)!==null&&n!==void 0?n:`${$d(t.schemaName)}_${t.referencedEntity}Id`;u=p.toLowerCase(),l={"@odata.type":"Microsoft.Dynamics.CRM.OneToManyRelationshipMetadata",SchemaName:t.schemaName,ReferencedEntity:t.referencedEntity,ReferencingEntity:t.referencingEntity,Lookup:{"@odata.type":"Microsoft.Dynamics.CRM.LookupAttributeMetadata",AttributeType:"Lookup",AttributeTypeName:{Value:"LookupType"},SchemaName:p,RequiredLevel:Eo((i=t.lookupRequired)!==null&&i!==void 0?i:"None"),DisplayName:Oe((a=t.lookupDisplayName)!==null&&a!==void 0?a:t.referencedEntity,s)}}}else{if(!t.entity1||!t.entity2)throw new he.InvalidArgumentError("ManyToMany relationship requires entity1 and entity2");l={"@odata.type":"Microsoft.Dynamics.CRM.ManyToManyRelationshipMetadata",SchemaName:t.schemaName,IntersectEntityName:(o=t.intersectEntityName)!==null&&o!==void 0?o:t.schemaName.toLowerCase(),Entity1LogicalName:t.entity1,Entity2LogicalName:t.entity2}}let c="/RelationshipDefinitions",d=(0,ce.ensureSuccess)(await e.post(c,l),e.apiUrl(c));return{schemaName:t.schemaName,metadataId:So(d),lookupLogicalName:u}}K.createRelationship=JL;async function KL(e,t){let r=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')`;(0,ce.ensureSuccess)(await e.delete(r),e.apiUrl(r))}K.deleteTable=KL;async function QL(e,t,r,n){var i,a;let o=(i=n.languageCode)!==null&&i!==void 0?i:xr.DEFAULT_LCID,s=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Attributes`,l=`${s}(LogicalName='${(0,J.odataPathLiteral)(r)}')${(0,J.odataQuery)([["$select","MetadataId,AttributeType"]])}`,c=(0,ce.ensureSuccess)(await e.get(l),e.apiUrl(l)).body,d=FL[(a=c.AttributeType)!==null&&a!==void 0?a:""];if(!c.MetadataId||!d)throw new he.InvalidArgumentError(`cannot update column '${r}' on '${t}' (type '${c.AttributeType}' not supported)`);let p=(0,J.normalizeGuid)(c.MetadataId,"MetadataId"),f=`${s}(${p})/${d}`,m=(0,ce.ensureSuccess)(await e.get(f),e.apiUrl(f)).body;for(let v of Object.keys(m))v.startsWith("@odata.")&&delete m[v];if(m["@odata.type"]=d,n.displayName!==void 0&&(m.DisplayName=Oe(n.displayName,o)),n.description!==void 0&&(m.Description=Oe(n.description,o)),n.required!==void 0&&(m.RequiredLevel=Eo(n.required)),n.maxLength!==void 0&&(m.MaxLength=n.maxLength),n.autoNumberFormat!==void 0&&(m.AutoNumberFormat=n.autoNumberFormat),n.defaultValue!==void 0&&c.AttributeType!=="Boolean")throw new he.InvalidArgumentError(`updateColumn: 'defaultValue' applies to Boolean columns, but '${r}' on '${t}' is of type '${c.AttributeType}'.`);if(n.integerFormat!==void 0&&c.AttributeType!=="Integer")throw new he.InvalidArgumentError(`updateColumn: 'integerFormat' applies to Integer columns, but '${r}' on '${t}' is of type '${c.AttributeType}'.`);n.defaultValue!==void 0&&(m.DefaultValue=n.defaultValue),n.integerFormat!==void 0&&(m.Format=n.integerFormat),xv(m,n);let h=`${s}(${p})`;(0,ce.ensureSuccess)(await e.put(h,m,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(h))}K.updateColumn=QL;async function XL(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Attributes`,a=`${i}(LogicalName='${(0,J.odataPathLiteral)(r)}')${(0,J.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,ce.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new he.InvalidArgumentError(`column '${r}' not found on '${t}'`);let l=`${i}(${(0,J.normalizeGuid)(s,"MetadataId")})`;(0,ce.ensureSuccess)(await e.delete(l),e.apiUrl(l))}K.deleteColumn=XL;async function YL(e,t){var r,n,i;let a=`/RelationshipDefinitions${(0,J.odataQuery)([["$filter",`SchemaName eq '${(0,J.odataLiteral)(t)}'`],["$select","MetadataId"]])}`,s=(i=(n=(r=(0,ce.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||r===void 0?void 0:r.value)===null||n===void 0?void 0:n[0])===null||i===void 0?void 0:i.MetadataId;if(!s)throw new he.InvalidArgumentError(`relationship '${t}' not found`);let l=`/RelationshipDefinitions(${(0,J.normalizeGuid)(s,"MetadataId")})`;(0,ce.ensureSuccess)(await e.delete(l),e.apiUrl(l))}K.deleteRelationship=YL;async function Rv(e,t){var r;let n=`/GlobalOptionSetDefinitions(Name='${(0,J.odataPathLiteral)(t)}')${(0,J.odataQuery)([["$select","MetadataId"]])}`,i=await e.get(n);if(i.status===404)return;let o=(r=(0,ce.ensureSuccess)(i,e.apiUrl(n)).body)===null||r===void 0?void 0:r.MetadataId;return o?(0,J.normalizeGuid)(o,"MetadataId"):void 0}async function ZL(e,t){var r;let n=t.name.toLowerCase(),i=await Rv(e,n);if(i)return{name:n,metadataId:i};let a=(r=t.languageCode)!==null&&r!==void 0?r:xr.DEFAULT_LCID,o={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",Name:n,DisplayName:Oe(t.displayName,a),IsGlobal:!0,OptionSetType:"Picklist",Options:t.options.map(l=>({Value:l.value,Label:Oe(l.label,a)}))};t.description&&(o.Description=Oe(t.description,a));let s="/GlobalOptionSetDefinitions";try{let l=(0,ce.ensureSuccess)(await e.post(s,o),e.apiUrl(s));return{name:n,metadataId:So(l)}}catch(l){let u;try{u=await Rv(e,n)}catch{u=void 0}if(u)return{name:n,metadataId:u};throw l}}K.createGlobalOptionSet=ZL;async function eF(e,t){let r=`/GlobalOptionSetDefinitions(Name='${(0,J.odataPathLiteral)(t.toLowerCase())}')`;(0,ce.ensureSuccess)(await e.delete(r),e.apiUrl(r))}K.deleteGlobalOptionSet=eF;async function tF(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:xr.DEFAULT_LCID,a={"@odata.type":"Microsoft.Dynamics.CRM.EntityKeyMetadata",SchemaName:r.schemaName,DisplayName:Oe(r.displayName,i),KeyAttributes:r.keyAttributes},o=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Keys`,s=(0,ce.ensureSuccess)(await e.post(o,a),e.apiUrl(o));return{logicalName:r.schemaName.toLowerCase(),metadataId:So(s)}}K.createAlternateKey=tF;async function rF(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Keys`,a=`${i}(LogicalName='${(0,J.odataPathLiteral)(r.toLowerCase())}')${(0,J.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,ce.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new he.InvalidArgumentError(`alternate key '${r}' not found on '${t}'`);let l=`${i}(${(0,J.normalizeGuid)(s,"MetadataId")})`;(0,ce.ensureSuccess)(await e.delete(l),e.apiUrl(l))}K.deleteAlternateKey=rF;async function nF(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:xr.DEFAULT_LCID,a=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')`,s=(0,ce.ensureSuccess)(await e.get(a),e.apiUrl(a)).body,l=s.MetadataId;if(!l)throw new he.InvalidArgumentError(`table '${t}' not found`);let u=(0,J.normalizeGuid)(l,"MetadataId");for(let d of Object.keys(s))d.startsWith("@odata.")&&delete s[d];s["@odata.type"]="Microsoft.Dynamics.CRM.EntityMetadata",r.displayName!==void 0&&(s.DisplayName=Oe(r.displayName,i)),r.pluralName!==void 0&&(s.DisplayCollectionName=Oe(r.pluralName,i)),r.description!==void 0&&(s.Description=Oe(r.description,i)),r.auditEnabled!==void 0&&Tv(s,"IsAuditEnabled",r.auditEnabled),r.duplicateDetectionEnabled!==void 0&&Tv(s,"IsDuplicateDetectionEnabled",r.duplicateDetectionEnabled),r.changeTrackingEnabled!==void 0&&(s.ChangeTrackingEnabled=r.changeTrackingEnabled),r.quickCreateEnabled!==void 0&&(s.IsQuickCreateEnabled=r.quickCreateEnabled),r.iconVectorName!==void 0&&(s.IconVectorName=r.iconVectorName),r.iconSmallName!==void 0&&(s.IconSmallName=r.iconSmallName),r.iconMediumName!==void 0&&(s.IconMediumName=r.iconMediumName),r.iconLargeName!==void 0&&(s.IconLargeName=r.iconLargeName);let c=`/EntityDefinitions(${u})`;(0,ce.ensureSuccess)(await e.put(c,s,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(c))}K.updateTable=nF});var Mn=y(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.rebuildRaw=It.assembleChildren=It.spliceChildren=It.mergeAttrs=It.rawFromNode=It.emptyBag=void 0;var kn=ee(),Uv=1e6,ml=512;function iF(){return{a:[],c:[]}}It.emptyBag=iF;function $v(e,t=0){if(t>ml)throw new kn.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${ml}`);return{n:e.getNodeName(),a:e.getAllProperties().map(r=>[r.key,r.value]),c:e.getAllChildren().map(r=>$v(r,t+1))}}It.rawFromNode=$v;function aF(e,t,r=[]){let n=new Map;for(let[s,l]of t)n.set(s,l);let i=new Set(r.filter(s=>!n.has(s))),a=new Set,o=[];for(let[s,l]of e)i.has(s)||(n.has(s)?o.push([s,n.get(s)]):o.push([s,l]),a.add(s));for(let[s,l]of t)a.has(s)||(o.push([s,l]),a.add(s));return o}It.mergeAttrs=aF;function fl(e,t){let r=new Set;for(let s of e){let l=s.i;if(!Number.isInteger(l)||l<0||l>Uv)throw new kn.InvalidArgumentError(`Bag child index must be an integer in [0, ${Uv}] (got ${String(l)})`);if(r.has(l))throw new kn.InvalidArgumentError(`Duplicate bag child index ${l}`);r.add(l)}let n=[...e].sort((s,l)=>s.i-l.i),i=[],a=0,o=0;for(let s of n){for(;o<s.i&&a<t.length;)i.push(t[a]),a+=1,o+=1;o<s.i&&(o=s.i),i.push(s.node),o+=1}for(;a<t.length;)i.push(t[a]),a+=1;return i}It.spliceChildren=fl;function oF(e,t){if(e.w){let r={n:e.w.n,a:e.w.a.map(n=>[n[0],n[1]]),c:fl(e.w.c,t)};return fl(e.c,[r])}return fl(e.c,t)}It.assembleChildren=oF;function qv(e,t,r,n=0){if(n>ml)throw new kn.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${ml}`);sF(e,n);let i=t.make(e.n,r);for(let[a,o]of e.a)t.setProp(i,a,o);for(let a of e.c)t.addChild(i,qv(a,t,i,n+1));return i}It.rebuildRaw=qv;function sF(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new kn.InvalidArgumentError(`Malformed hybrid node at depth ${t}: expected a JSON object`);let r=e;if(typeof r.n!="string")throw new kn.InvalidArgumentError(`Malformed hybrid node at depth ${t}: 'n' (tag name) must be a string`);if(!Array.isArray(r.a)||!Array.isArray(r.c))throw new kn.InvalidArgumentError(`Malformed hybrid node '${r.n}': 'a' and 'c' must be arrays`);for(let n of r.a)if(!Array.isArray(n)||n.length!==2||typeof n[0]!="string"||typeof n[1]!="string")throw new kn.InvalidArgumentError(`Malformed hybrid node '${r.n}': each attribute must be a [string, string] pair`)}});var Xi=y(nn=>{"use strict";function lF(e,t,r){if(r===void 0&&(r=Array.prototype),e&&typeof r.find=="function")return r.find.call(e,t);for(var n=0;n<e.length;n++)if(Object.prototype.hasOwnProperty.call(e,n)){var i=e[n];if(t.call(void 0,i,n,e))return i}}function Gd(e,t){return t===void 0&&(t=Object),t&&typeof t.freeze=="function"?t.freeze(e):e}function uF(e,t){if(e===null||typeof e!="object")throw new TypeError("target is not an object");for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e}var Vv=Gd({HTML:"text/html",isHTML:function(e){return e===Vv.HTML},XML_APPLICATION:"application/xml",XML_TEXT:"text/xml",XML_XHTML_APPLICATION:"application/xhtml+xml",XML_SVG_IMAGE:"image/svg+xml"}),Gv=Gd({HTML:"http://www.w3.org/1999/xhtml",isHTML:function(e){return e===Gv.HTML},SVG:"http://www.w3.org/2000/svg",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"}),hl=/[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,Vd=new RegExp("[\\-\\.0-9"+hl.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),cF=new RegExp("^"+hl.source+Vd.source+"*(?::"+hl.source+Vd.source+"*)?$");nn.assign=uF;nn.find=lF;nn.freeze=Gd;nn.MIME_TYPE=Vv;nn.NAMESPACE=Gv;nn.nameStartChar=hl;nn.nameChar=Vd;nn.tagNamePattern=cF});var tp=y(ln=>{var zd=Xi(),Lr=zd.find,Do=zd.NAMESPACE,Yi=zd.tagNamePattern;function dF(e){return e!==""}function pF(e){return e?e.split(/[\t\n\f\r ]+/).filter(dF):[]}function fF(e,t){return e.hasOwnProperty(t)||(e[t]=!0),e}function zv(e){if(!e)return[];var t=pF(e);return Object.keys(t.reduce(fF,{}))}function mF(e){return function(t){return e&&e.indexOf(t)!==-1}}function _o(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function Tt(e,t){var r=e.prototype;if(!(r instanceof t)){let i=function(){};var n=i;i.prototype=t.prototype,i=new i,_o(r,i),e.prototype=r=i}r.constructor!=e&&(typeof e!="function"&&console.error("unknown Class:"+e),r.constructor=e)}var Pt={},Qt=Pt.ELEMENT_NODE=1,Zi=Pt.ATTRIBUTE_NODE=2,No=Pt.TEXT_NODE=3,Yv=Pt.CDATA_SECTION_NODE=4,Zv=Pt.ENTITY_REFERENCE_NODE=5,hF=Pt.ENTITY_NODE=6,Wd=Pt.PROCESSING_INSTRUCTION_NODE=7,jd=Pt.COMMENT_NODE=8,ey=Pt.DOCUMENT_NODE=9,ty=Pt.DOCUMENT_TYPE_NODE=10,an=Pt.DOCUMENT_FRAGMENT_NODE=11,gF=Pt.NOTATION_NODE=12,lt={},Ke={},VH=lt.INDEX_SIZE_ERR=(Ke[1]="Index size error",1),GH=lt.DOMSTRING_SIZE_ERR=(Ke[2]="DOMString size error",2),_t=lt.HIERARCHY_REQUEST_ERR=(Ke[3]="Hierarchy request error",3),zH=lt.WRONG_DOCUMENT_ERR=(Ke[4]="Wrong document",4),Wv=lt.INVALID_CHARACTER_ERR=(Ke[5]="Invalid character",5),WH=lt.NO_DATA_ALLOWED_ERR=(Ke[6]="No data allowed",6),jH=lt.NO_MODIFICATION_ALLOWED_ERR=(Ke[7]="No modification allowed",7),ry=lt.NOT_FOUND_ERR=(Ke[8]="Not found",8),HH=lt.NOT_SUPPORTED_ERR=(Ke[9]="Not supported",9),jv=lt.INUSE_ATTRIBUTE_ERR=(Ke[10]="Attribute in use",10),fr=lt.INVALID_STATE_ERR=(Ke[11]="Invalid state",11),JH=lt.SYNTAX_ERR=(Ke[12]="Syntax error",12),KH=lt.INVALID_MODIFICATION_ERR=(Ke[13]="Invalid modification",13),QH=lt.NAMESPACE_ERR=(Ke[14]="Invalid namespace",14),XH=lt.INVALID_ACCESS_ERR=(Ke[15]="Invalid access",15);function te(e,t){if(t instanceof Error)var r=t;else r=this,Error.call(this,Ke[e]),this.message=Ke[e],Error.captureStackTrace&&Error.captureStackTrace(this,te);return r.code=e,t&&(this.message=this.message+": "+t),r}te.prototype=Error.prototype;_o(lt,te);function on(){}on.prototype={length:0,item:function(e){return e>=0&&e<this.length?this[e]:null},toString:function(e,t,r){for(var n=!!r&&!!r.requireWellFormed,i=[],a=0;a<this.length;a++)ep(this[a],i,e,t,null,n);return i.join("")},filter:function(e){return Array.prototype.filter.call(this,e)},indexOf:function(e){return Array.prototype.indexOf.call(this,e)}};function ea(e,t){this._node=e,this._refresh=t,Hd(this)}function Hd(e){var t=e._node._inc||e._node.ownerDocument._inc;if(e._inc!==t){var r=e._refresh(e._node);if(hy(e,"length",r.length),!e.$$length||r.length<e.$$length)for(var n=r.length;n in e;n++)Object.prototype.hasOwnProperty.call(e,n)&&delete e[n];_o(r,e),e._inc=t}}ea.prototype.item=function(e){return Hd(this),this[e]||null};Tt(ea,on);function vl(){this._nameIndex=Object.create(null)}function ny(e,t){for(var r=e.length;r--;)if(e[r]===t)return r}function vF(e,t){e._nameIndex[t.nodeName]=t}function iy(e,t){e._nameIndex[t.nodeName]===t&&delete e._nameIndex[t.nodeName]}function Hv(e,t,r,n){if(n?(t[ny(t,n)]=r,iy(t,n)):t[t.length++]=r,vF(t,r),e){r.ownerElement=e;var i=e.ownerDocument;i&&(n&&sy(i,e,n),yF(i,e,r))}}function Jv(e,t,r){var n=ny(t,r);if(n>=0){for(var i=t.length-1;n<i;)t[n]=t[++n];if(t.length=i,iy(t,r),e){var a=e.ownerDocument;a&&(sy(a,e,r),r.ownerElement=null)}}else throw new te(ry,new Error(e.tagName+"@"+r))}vl.prototype={length:0,item:on.prototype.item,getNamedItem:function(e){for(var t=this.length;t--;){var r=this[t];if(r.nodeName==e)return r}},setNamedItem:function(e){var t=e.ownerElement;if(t&&t!=this._ownerElement)throw new te(jv);var r=this._nameIndex[e.nodeName];return Hv(this._ownerElement,this,e,r),r},setNamedItemNS:function(e){var t=e.ownerElement,r;if(t&&t!=this._ownerElement)throw new te(jv);return r=this.getNamedItemNS(e.namespaceURI,e.localName),Hv(this._ownerElement,this,e,r),r},removeNamedItem:function(e){var t=this.getNamedItem(e);return Jv(this._ownerElement,this,t),t},removeNamedItemNS:function(e,t){var r=this.getNamedItemNS(e,t);return Jv(this._ownerElement,this,r),r},getNamedItemNS:function(e,t){for(var r=this.length;r--;){var n=this[r];if(n.localName==t&&n.namespaceURI==e)return n}return null}};function ay(){}ay.prototype={hasFeature:function(e,t){return!0},createDocument:function(e,t,r){var n=new To;if(n.implementation=this,n.childNodes=new on,n.doctype=r||null,r&&n.appendChild(r),t){var i=n.createElementNS(e,t);n.appendChild(i)}return n},createDocumentType:function(e,t,r){var n=new Cl;return n.name=e,n.nodeName=e,n.publicId=t||"",n.systemId=r||"",n}};function de(){}de.prototype={firstChild:null,lastChild:null,previousSibling:null,nextSibling:null,attributes:null,parentNode:null,childNodes:null,ownerDocument:null,nodeValue:null,namespaceURI:null,prefix:null,localName:null,insertBefore:function(e,t){return bl(this,e,t)},replaceChild:function(e,t){bl(this,e,t,uy),t&&this.removeChild(t)},removeChild:function(e){return ly(this,e)},appendChild:function(e){return this.insertBefore(e,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(e){return my(this.ownerDocument||this,this,e)},normalize:function(){Je(this,null,{enter:function(e){for(var t=e.firstChild;t;){var r=t.nextSibling;if(r!==null&&r.nodeType===No&&t.nodeType===No){for(var n=[],i=r;i!==null&&i.nodeType===No;)n.push(i.data),i=i.nextSibling;for(var a=t.nextSibling;a!==i;){var o=a.nextSibling;a.parentNode=null,a.previousSibling=null,a.nextSibling=null,a=o}t.nextSibling=i,i!==null?i.previousSibling=t:e.lastChild=t,t.appendData(n.join("")),Al(e.ownerDocument,e),t=i}else t=r}return!0}})},isSupported:function(e,t){return this.ownerDocument.implementation.hasFeature(e,t)},hasAttributes:function(){return this.attributes.length>0},lookupPrefix:function(e){for(var t=this;t;){var r=t._nsMap;if(r){for(var n in r)if(Object.prototype.hasOwnProperty.call(r,n)&&r[n]===e)return n}t=t.nodeType==Zi?t.ownerDocument:t.parentNode}return null},lookupNamespaceURI:function(e){for(var t=this;t;){var r=t._nsMap;if(r&&Object.prototype.hasOwnProperty.call(r,e))return r[e];t=t.nodeType==Zi?t.ownerDocument:t.parentNode}return null},isDefaultNamespace:function(e){var t=this.lookupPrefix(e);return t==null}};function oy(e){return e=="<"&&"<"||e==">"&&">"||e=="&"&&"&"||e=='"'&&"""||"&#"+e.charCodeAt()+";"}_o(Pt,de);_o(Pt,de.prototype);function yl(e,t){return Je(e,null,{enter:function(r){return t(r)?Je.STOP:!0}})===Je.STOP}function Je(e,t,r){for(var n=[{node:e,context:t,phase:Je.ENTER}];n.length>0;){var i=n.pop();if(i.phase===Je.ENTER){var a=r.enter(i.node,i.context);if(a===Je.STOP)return Je.STOP;if(n.push({node:i.node,context:a,phase:Je.EXIT}),a==null)continue;for(var o=i.node.lastChild;o;)n.push({node:o,context:a,phase:Je.ENTER}),o=o.previousSibling}else r.exit&&r.exit(i.node,i.context)}}Je.STOP=Symbol("walkDOM.STOP");Je.ENTER=0;Je.EXIT=1;function To(){this.ownerDocument=this}function yF(e,t,r){e&&e._inc++;var n=r.namespaceURI;n===Do.XMLNS&&(t._nsMap[r.prefix?r.localName:""]=r.value)}function sy(e,t,r,n){e&&e._inc++;var i=r.namespaceURI;i===Do.XMLNS&&delete t._nsMap[r.prefix?r.localName:""]}function Al(e,t,r){if(e&&e._inc){e._inc++;var n=t.childNodes;if(r)n[n.length++]=r;else{for(var i=t.firstChild,a=0;i;)n[a++]=i,i=i.nextSibling;n.length=a,delete n[n.length]}}}function ly(e,t){var r=t.previousSibling,n=t.nextSibling;return r?r.nextSibling=n:e.firstChild=n,n?n.previousSibling=r:e.lastChild=r,t.parentNode=null,t.previousSibling=null,t.nextSibling=null,Al(e.ownerDocument,e),t}function bF(e){return e&&(e.nodeType===de.DOCUMENT_NODE||e.nodeType===de.DOCUMENT_FRAGMENT_NODE||e.nodeType===de.ELEMENT_NODE)}function wF(e){return e&&(Fr(e)||Jd(e)||sn(e)||e.nodeType===de.DOCUMENT_FRAGMENT_NODE||e.nodeType===de.COMMENT_NODE||e.nodeType===de.PROCESSING_INSTRUCTION_NODE)}function sn(e){return e&&e.nodeType===de.DOCUMENT_TYPE_NODE}function Fr(e){return e&&e.nodeType===de.ELEMENT_NODE}function Jd(e){return e&&e.nodeType===de.TEXT_NODE}function Kv(e,t){var r=e.childNodes||[];if(Lr(r,Fr)||sn(t))return!1;var n=Lr(r,sn);return!(t&&n&&r.indexOf(n)>r.indexOf(t))}function Qv(e,t){var r=e.childNodes||[];function n(a){return Fr(a)&&a!==t}if(Lr(r,n))return!1;var i=Lr(r,sn);return!(t&&i&&r.indexOf(i)>r.indexOf(t))}function AF(e,t,r){if(!bF(e))throw new te(_t,"Unexpected parent node type "+e.nodeType);if(r&&r.parentNode!==e)throw new te(ry,"child not in parent");if(!wF(t)||sn(t)&&e.nodeType!==de.DOCUMENT_NODE)throw new te(_t,"Unexpected node type "+t.nodeType+" for parent node type "+e.nodeType)}function CF(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===de.DOCUMENT_FRAGMENT_NODE){var a=i.filter(Fr);if(a.length>1||Lr(i,Jd))throw new te(_t,"More than one element or text in fragment");if(a.length===1&&!Kv(e,r))throw new te(_t,"Element in fragment can not be inserted before doctype")}if(Fr(t)&&!Kv(e,r))throw new te(_t,"Only one element can be added and only after doctype");if(sn(t)){if(Lr(n,sn))throw new te(_t,"Only one doctype is allowed");var o=Lr(n,Fr);if(r&&n.indexOf(o)<n.indexOf(r))throw new te(_t,"Doctype can only be inserted before an element");if(!r&&o)throw new te(_t,"Doctype can not be appended since element is present")}}function uy(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===de.DOCUMENT_FRAGMENT_NODE){var a=i.filter(Fr);if(a.length>1||Lr(i,Jd))throw new te(_t,"More than one element or text in fragment");if(a.length===1&&!Qv(e,r))throw new te(_t,"Element in fragment can not be inserted before doctype")}if(Fr(t)&&!Qv(e,r))throw new te(_t,"Only one element can be added and only after doctype");if(sn(t)){let l=function(u){return sn(u)&&u!==r};var s=l;if(Lr(n,l))throw new te(_t,"Only one doctype is allowed");var o=Lr(n,Fr);if(r&&n.indexOf(o)<n.indexOf(r))throw new te(_t,"Doctype can only be inserted before an element")}}function bl(e,t,r,n){AF(e,t,r),e.nodeType===de.DOCUMENT_NODE&&(n||CF)(e,t,r);var i=t.parentNode;if(i&&i.removeChild(t),t.nodeType===an){var a=t.firstChild;if(a==null)return t;var o=t.lastChild}else a=o=t;var s=r?r.previousSibling:e.lastChild;a.previousSibling=s,o.nextSibling=r,s?s.nextSibling=a:e.firstChild=a,r==null?e.lastChild=o:r.previousSibling=o;do{a.parentNode=e;var l=e.ownerDocument||e;Io(a,l)}while(a!==o&&(a=a.nextSibling));return Al(e.ownerDocument||e,e),t.nodeType==an&&(t.firstChild=t.lastChild=null),t}function Io(e,t){if(e.ownerDocument!==t){if(e.ownerDocument=t,e.nodeType===Qt&&e.attributes)for(var r=0;r<e.attributes.length;r++){var n=e.attributes.item(r);n&&(n.ownerDocument=t)}for(var i=e.firstChild;i;)Io(i,t),i=i.nextSibling}}function EF(e,t){t.parentNode&&t.parentNode.removeChild(t),t.parentNode=e,t.previousSibling=e.lastChild,t.nextSibling=null,t.previousSibling?t.previousSibling.nextSibling=t:e.firstChild=t,e.lastChild=t,Al(e.ownerDocument,e,t);var r=e.ownerDocument||e;return Io(t,r),t}To.prototype={nodeName:"#document",nodeType:ey,doctype:null,documentElement:null,_inc:1,insertBefore:function(e,t){if(e.nodeType==an){for(var r=e.firstChild;r;){var n=r.nextSibling;this.insertBefore(r,t),r=n}return e}return bl(this,e,t),Io(e,this),this.documentElement===null&&e.nodeType===Qt&&(this.documentElement=e),e},removeChild:function(e){return this.documentElement==e&&(this.documentElement=null),ly(this,e)},replaceChild:function(e,t){bl(this,e,t,uy),Io(e,this),t&&this.removeChild(t),Fr(e)&&(this.documentElement=e)},importNode:function(e,t){return SF(this,e,t)},getElementById:function(e){var t=null;return yl(this.documentElement,function(r){if(r.nodeType==Qt&&r.getAttribute("id")==e)return t=r,!0}),t},getElementsByClassName:function(e){var t=zv(e);return new ea(this,function(r){var n=[];return t.length>0&&yl(r.documentElement,function(i){if(i!==r&&i.nodeType===Qt){var a=i.getAttribute("class");if(a){var o=e===a;if(!o){var s=zv(a);o=t.every(mF(s))}o&&n.push(i)}}}),n})},createElement:function(e){var t=new fi;t.ownerDocument=this,t.nodeName=e,t.tagName=e,t.localName=e,t.childNodes=new on;var r=t.attributes=new vl;return r._ownerElement=t,t},createDocumentFragment:function(){var e=new El;return e.ownerDocument=this,e.childNodes=new on,e},createTextNode:function(e){var t=new Kd;return t.ownerDocument=this,t.appendData(e),t},createComment:function(e){var t=new Qd;return t.ownerDocument=this,t.appendData(e),t},createCDATASection:function(e){if(e.indexOf("]]>")!==-1)throw new te(Wv,'data contains "]]>"');var t=new Xd;return t.ownerDocument=this,t.appendData(e),t},createProcessingInstruction:function(e,t){var r=new Zd;return r.ownerDocument=this,r.tagName=r.nodeName=r.target=e,r.nodeValue=r.data=t,r},createAttribute:function(e){var t=new wl;return t.ownerDocument=this,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},createEntityReference:function(e){if(!Yi.test(e))throw new te(Wv,'not a valid xml name "'+e+'"');var t=new Yd;return t.ownerDocument=this,t.nodeName=e,t},createElementNS:function(e,t){var r=new fi,n=t.split(":"),i=r.attributes=new vl;return r.childNodes=new on,r.ownerDocument=this,r.nodeName=t,r.tagName=t,r.namespaceURI=e,n.length==2?(r.prefix=n[0],r.localName=n[1]):r.localName=t,i._ownerElement=r,r},createAttributeNS:function(e,t){var r=new wl,n=t.split(":");return r.ownerDocument=this,r.nodeName=t,r.name=t,r.namespaceURI=e,r.specified=!0,n.length==2?(r.prefix=n[0],r.localName=n[1]):r.localName=t,r}};Tt(To,de);function fi(){this._nsMap={}}fi.prototype={nodeType:Qt,hasAttribute:function(e){return this.getAttributeNode(e)!=null},getAttribute:function(e){var t=this.getAttributeNode(e);return t&&t.value||""},getAttributeNode:function(e){return this.attributes.getNamedItem(e)},setAttribute:function(e,t){var r=this.ownerDocument.createAttribute(e);r.value=r.nodeValue=""+t,this.setAttributeNode(r)},removeAttribute:function(e){var t=this.getAttributeNode(e);t&&this.removeAttributeNode(t)},appendChild:function(e){return e.nodeType===an?this.insertBefore(e,null):EF(this,e)},setAttributeNode:function(e){return this.attributes.setNamedItem(e)},setAttributeNodeNS:function(e){return this.attributes.setNamedItemNS(e)},removeAttributeNode:function(e){return this.attributes.removeNamedItem(e.nodeName)},removeAttributeNS:function(e,t){var r=this.getAttributeNodeNS(e,t);r&&this.removeAttributeNode(r)},hasAttributeNS:function(e,t){return this.getAttributeNodeNS(e,t)!=null},getAttributeNS:function(e,t){var r=this.getAttributeNodeNS(e,t);return r&&r.value||""},setAttributeNS:function(e,t,r){var n=this.ownerDocument.createAttributeNS(e,t);n.value=n.nodeValue=""+r,this.setAttributeNode(n)},getAttributeNodeNS:function(e,t){return this.attributes.getNamedItemNS(e,t)},getElementsByTagName:function(e){return new ea(this,function(t){var r=[];return yl(t,function(n){n!==t&&n.nodeType==Qt&&(e==="*"||n.tagName==e)&&r.push(n)}),r})},getElementsByTagNameNS:function(e,t){return new ea(this,function(r){var n=[];return yl(r,function(i){i!==r&&i.nodeType===Qt&&(e==="*"||i.namespaceURI===e)&&(t==="*"||i.localName==t)&&n.push(i)}),n})}};To.prototype.getElementsByTagName=fi.prototype.getElementsByTagName;To.prototype.getElementsByTagNameNS=fi.prototype.getElementsByTagNameNS;Tt(fi,de);function wl(){}wl.prototype.nodeType=Zi;Tt(wl,de);function Po(){}Po.prototype={data:"",substringData:function(e,t){return this.data.substring(e,e+t)},appendData:function(e){e=this.data+e,this.nodeValue=this.data=e,this.length=e.length},insertData:function(e,t){this.replaceData(e,0,t)},appendChild:function(e){throw new Error(Ke[_t])},deleteData:function(e,t){this.replaceData(e,t,"")},replaceData:function(e,t,r){var n=this.data.substring(0,e),i=this.data.substring(e+t);r=n+r+i,this.nodeValue=this.data=r,this.length=r.length}};Tt(Po,de);function Kd(){}Kd.prototype={nodeName:"#text",nodeType:No,splitText:function(e){var t=this.data,r=t.substring(e);t=t.substring(0,e),this.data=this.nodeValue=t,this.length=t.length;var n=this.ownerDocument.createTextNode(r);return this.parentNode&&this.parentNode.insertBefore(n,this.nextSibling),n}};Tt(Kd,Po);function Qd(){}Qd.prototype={nodeName:"#comment",nodeType:jd};Tt(Qd,Po);function Xd(){}Xd.prototype={nodeName:"#cdata-section",nodeType:Yv};Tt(Xd,Po);function Cl(){}Cl.prototype.nodeType=ty;Tt(Cl,de);function cy(){}cy.prototype.nodeType=gF;Tt(cy,de);function dy(){}dy.prototype.nodeType=hF;Tt(dy,de);function Yd(){}Yd.prototype.nodeType=Zv;Tt(Yd,de);function El(){}El.prototype.nodeName="#document-fragment";El.prototype.nodeType=an;Tt(El,de);function Zd(){}Zd.prototype.nodeType=Wd;Tt(Zd,de);function py(){}py.prototype.serializeToString=function(e,t,r,n){return fy.call(e,t,r,n)};de.prototype.toString=fy;function fy(e,t,r){var n=!!r&&!!r.requireWellFormed,i=[],a=this.nodeType==9&&this.documentElement||this,o=a.prefix,s=a.namespaceURI;if(s&&o==null){var o=a.lookupPrefix(s);if(o==null)var l=[{namespace:s,prefix:null}]}return ep(this,i,e,t,l,n),i.join("")}function Xv(e,t,r){var n=e.prefix||"",i=e.namespaceURI;if(!i||n==="xml"&&i===Do.XML||i===Do.XMLNS)return!1;for(var a=r.length;a--;){var o=r[a];if(o.prefix===n)return o.namespace!==i}return!0}function gl(e,t,r,n){if(n&&!Yi.test(t))throw new te(fr,'The attribute name "'+t+'" is not a valid XML QName');e.push(" ",t,'="',r.replace(/[<>&"\t\n\r]/g,oy),'"')}function ep(e,t,r,n,i,a){i||(i=[]),Je(e,{ns:i,isHTML:r},{enter:function(o,s){var l=s.ns,u=s.isHTML;if(n)if(o=n(o),o){if(typeof o=="string")return t.push(o),null}else return null;switch(o.nodeType){case Qt:var c=o.attributes,d=c.length,p=o.tagName;u=Do.isHTML(o.namespaceURI)||u;var f=p;if(!u&&!o.prefix&&o.namespaceURI){for(var m,h=0;h<c.length;h++)if(c.item(h).name==="xmlns"){m=c.item(h).value;break}if(!m)for(var v=l.length-1;v>=0;v--){var w=l[v];if(w.prefix===""&&w.namespace===o.namespaceURI){m=w.namespace;break}}if(m!==o.namespaceURI)for(var v=l.length-1;v>=0;v--){var w=l[v];if(w.namespace===o.namespaceURI){w.prefix&&(f=w.prefix+":"+p);break}}}if(a&&!Yi.test(f))throw new te(fr,'The element name "'+f+'" is not a valid XML QName');t.push("<",f);for(var C=l.slice(),E=0;E<d;E++){var D=c.item(E);D.prefix=="xmlns"?C.push({prefix:D.localName,namespace:D.value}):D.nodeName=="xmlns"&&C.push({prefix:"",namespace:D.value})}for(var E=0;E<d;E++){var D=c.item(E);if(Xv(D,u,C)){var O=D.prefix||"",x=D.namespaceURI;gl(t,O?"xmlns:"+O:"xmlns",x,a),C.push({prefix:O,namespace:x})}var F=n?n(D):D;F&&(typeof F=="string"?t.push(F):gl(t,F.name,F.value,a))}if(p===f&&Xv(o,u,C)){var M=o.prefix||"",x=o.namespaceURI;gl(t,M?"xmlns:"+M:"xmlns",x,a),C.push({prefix:M,namespace:x})}var P=o.firstChild;if(P||u&&!/^(?:meta|link|img|br|hr|input)$/i.test(p)){if(t.push(">"),u&&/^script$/i.test(p)){for(;P;)P.data?t.push(P.data):ep(P,t,u,n,C.slice(),a),P=P.nextSibling;return t.push("</",p,">"),null}return{ns:C,isHTML:u,tag:f}}else return t.push("/>"),null;case ey:case an:return{ns:l.slice(),isHTML:u,tag:null};case Zi:return gl(t,o.name,o.value,a),null;case No:return t.push(o.data.replace(/[<&>]/g,oy)),null;case Yv:if(a&&o.data.indexOf("]]>")!==-1)throw new te(fr,'The CDATASection data contains "]]>"');return t.push("<![CDATA[",o.data.replace(/]]>/g,"]]]]><![CDATA[>"),"]]>"),null;case jd:if(a&&o.data.indexOf("-->")!==-1)throw new te(fr,'The comment node data contains "-->"');return t.push("<!--",o.data,"-->"),null;case ty:if(a){if(!Yi.test(o.name))throw new te(fr,'The doctype name "'+o.name+'" is not a valid XML Name');if(o.publicId&&!/^("[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%']*"|'[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%'"]*')$/.test(o.publicId))throw new te(fr,"DocumentType publicId is not a valid PubidLiteral");if(o.systemId&&!/^("[^"]*"|'[^']*')$/.test(o.systemId))throw new te(fr,"DocumentType systemId is not a valid SystemLiteral");if(o.internalSubset&&o.internalSubset.indexOf("]>")!==-1)throw new te(fr,'DocumentType internalSubset contains "]>"')}var q=o.publicId,$=o.systemId;if(t.push("<!DOCTYPE ",o.name),q)t.push(" PUBLIC ",q),$&&$!="."&&t.push(" ",$),t.push(">");else if($&&$!=".")t.push(" SYSTEM ",$,">");else{var qe=o.internalSubset;qe&&t.push(" [",qe,"]"),t.push(">")}return null;case Wd:if(a){if(!Yi.test(o.target)||o.target.indexOf(":")!==-1||o.target.toLowerCase()==="xml")throw new te(fr,'The processing instruction target "'+o.target+'" is not a valid XML NCName or is reserved');if(o.data.indexOf("?>")!==-1)throw new te(fr,'The ProcessingInstruction data contains "?>"')}return t.push("<?",o.target," ",o.data,"?>"),null;case Zv:if(a&&!Yi.test(o.nodeName))throw new te(fr,'The entity reference name "'+o.nodeName+'" is not a valid XML Name');return t.push("&",o.nodeName,";"),null;default:return t.push("??",o.nodeName),null}},exit:function(o,s){s&&s.tag&&t.push("</",s.tag,">")}})}function SF(e,t,r){var n;return Je(t,null,{enter:function(i,a){var o=i.cloneNode(!1);o.ownerDocument=e,o.parentNode=null,a===null?n=o:a.appendChild(o);var s=i.nodeType===Zi||r;return s?o:null}}),n}function my(e,t,r){var n;return Je(t,null,{enter:function(i,a){var o=new i.constructor;for(var s in i)if(Object.prototype.hasOwnProperty.call(i,s)){var l=i[s];typeof l!="object"&&l!=o[s]&&(o[s]=l)}i.childNodes&&(o.childNodes=new on),o.ownerDocument=e;var u=r;switch(o.nodeType){case Qt:var c=i.attributes,d=o.attributes=new vl,p=c.length;d._ownerElement=o;for(var f=0;f<p;f++)o.setAttributeNode(my(e,c.item(f),!0));break;case Zi:u=!0}return a!==null?a.appendChild(o):n=o,u?o:null}}),n}function hy(e,t,r){e[t]=r}try{Object.defineProperty&&(Object.defineProperty(ea.prototype,"length",{get:function(){return Hd(this),this.$$length}}),Object.defineProperty(de.prototype,"textContent",{get:function(){if(this.nodeType===Qt||this.nodeType===an){var e=[];return Je(this,null,{enter:function(t){if(t.nodeType===Qt||t.nodeType===an)return!0;if(t.nodeType===Wd||t.nodeType===jd)return null;e.push(t.nodeValue)}}),e.join("")}return this.nodeValue},set:function(e){switch(this.nodeType){case Qt:case an:for(;this.firstChild;)this.removeChild(this.firstChild);(e||String(e))&&this.appendChild(this.ownerDocument.createTextNode(e));break;default:this.data=e,this.value=e,this.nodeValue=e}}}),hy=function(e,t,r){e["$$"+t]=r})}catch{}ln.DocumentType=Cl;ln.DOMException=te;ln.DOMImplementation=ay;ln.Element=fi;ln.Node=de;ln.NodeList=on;ln.walkDOM=Je;ln.XMLSerializer=py});var vy=y(Ro=>{"use strict";var gy=Xi().freeze;Ro.XML_ENTITIES=gy({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'});Ro.HTML_ENTITIES=gy({Aacute:"\xC1",aacute:"\xE1",Abreve:"\u0102",abreve:"\u0103",ac:"\u223E",acd:"\u223F",acE:"\u223E\u0333",Acirc:"\xC2",acirc:"\xE2",acute:"\xB4",Acy:"\u0410",acy:"\u0430",AElig:"\xC6",aelig:"\xE6",af:"\u2061",Afr:"\u{1D504}",afr:"\u{1D51E}",Agrave:"\xC0",agrave:"\xE0",alefsym:"\u2135",aleph:"\u2135",Alpha:"\u0391",alpha:"\u03B1",Amacr:"\u0100",amacr:"\u0101",amalg:"\u2A3F",AMP:"&",amp:"&",And:"\u2A53",and:"\u2227",andand:"\u2A55",andd:"\u2A5C",andslope:"\u2A58",andv:"\u2A5A",ang:"\u2220",ange:"\u29A4",angle:"\u2220",angmsd:"\u2221",angmsdaa:"\u29A8",angmsdab:"\u29A9",angmsdac:"\u29AA",angmsdad:"\u29AB",angmsdae:"\u29AC",angmsdaf:"\u29AD",angmsdag:"\u29AE",angmsdah:"\u29AF",angrt:"\u221F",angrtvb:"\u22BE",angrtvbd:"\u299D",angsph:"\u2222",angst:"\xC5",angzarr:"\u237C",Aogon:"\u0104",aogon:"\u0105",Aopf:"\u{1D538}",aopf:"\u{1D552}",ap:"\u2248",apacir:"\u2A6F",apE:"\u2A70",ape:"\u224A",apid:"\u224B",apos:"'",ApplyFunction:"\u2061",approx:"\u2248",approxeq:"\u224A",Aring:"\xC5",aring:"\xE5",Ascr:"\u{1D49C}",ascr:"\u{1D4B6}",Assign:"\u2254",ast:"*",asymp:"\u2248",asympeq:"\u224D",Atilde:"\xC3",atilde:"\xE3",Auml:"\xC4",auml:"\xE4",awconint:"\u2233",awint:"\u2A11",backcong:"\u224C",backepsilon:"\u03F6",backprime:"\u2035",backsim:"\u223D",backsimeq:"\u22CD",Backslash:"\u2216",Barv:"\u2AE7",barvee:"\u22BD",Barwed:"\u2306",barwed:"\u2305",barwedge:"\u2305",bbrk:"\u23B5",bbrktbrk:"\u23B6",bcong:"\u224C",Bcy:"\u0411",bcy:"\u0431",bdquo:"\u201E",becaus:"\u2235",Because:"\u2235",because:"\u2235",bemptyv:"\u29B0",bepsi:"\u03F6",bernou:"\u212C",Bernoullis:"\u212C",Beta:"\u0392",beta:"\u03B2",beth:"\u2136",between:"\u226C",Bfr:"\u{1D505}",bfr:"\u{1D51F}",bigcap:"\u22C2",bigcirc:"\u25EF",bigcup:"\u22C3",bigodot:"\u2A00",bigoplus:"\u2A01",bigotimes:"\u2A02",bigsqcup:"\u2A06",bigstar:"\u2605",bigtriangledown:"\u25BD",bigtriangleup:"\u25B3",biguplus:"\u2A04",bigvee:"\u22C1",bigwedge:"\u22C0",bkarow:"\u290D",blacklozenge:"\u29EB",blacksquare:"\u25AA",blacktriangle:"\u25B4",blacktriangledown:"\u25BE",blacktriangleleft:"\u25C2",blacktriangleright:"\u25B8",blank:"\u2423",blk12:"\u2592",blk14:"\u2591",blk34:"\u2593",block:"\u2588",bne:"=\u20E5",bnequiv:"\u2261\u20E5",bNot:"\u2AED",bnot:"\u2310",Bopf:"\u{1D539}",bopf:"\u{1D553}",bot:"\u22A5",bottom:"\u22A5",bowtie:"\u22C8",boxbox:"\u29C9",boxDL:"\u2557",boxDl:"\u2556",boxdL:"\u2555",boxdl:"\u2510",boxDR:"\u2554",boxDr:"\u2553",boxdR:"\u2552",boxdr:"\u250C",boxH:"\u2550",boxh:"\u2500",boxHD:"\u2566",boxHd:"\u2564",boxhD:"\u2565",boxhd:"\u252C",boxHU:"\u2569",boxHu:"\u2567",boxhU:"\u2568",boxhu:"\u2534",boxminus:"\u229F",boxplus:"\u229E",boxtimes:"\u22A0",boxUL:"\u255D",boxUl:"\u255C",boxuL:"\u255B",boxul:"\u2518",boxUR:"\u255A",boxUr:"\u2559",boxuR:"\u2558",boxur:"\u2514",boxV:"\u2551",boxv:"\u2502",boxVH:"\u256C",boxVh:"\u256B",boxvH:"\u256A",boxvh:"\u253C",boxVL:"\u2563",boxVl:"\u2562",boxvL:"\u2561",boxvl:"\u2524",boxVR:"\u2560",boxVr:"\u255F",boxvR:"\u255E",boxvr:"\u251C",bprime:"\u2035",Breve:"\u02D8",breve:"\u02D8",brvbar:"\xA6",Bscr:"\u212C",bscr:"\u{1D4B7}",bsemi:"\u204F",bsim:"\u223D",bsime:"\u22CD",bsol:"\\",bsolb:"\u29C5",bsolhsub:"\u27C8",bull:"\u2022",bullet:"\u2022",bump:"\u224E",bumpE:"\u2AAE",bumpe:"\u224F",Bumpeq:"\u224E",bumpeq:"\u224F",Cacute:"\u0106",cacute:"\u0107",Cap:"\u22D2",cap:"\u2229",capand:"\u2A44",capbrcup:"\u2A49",capcap:"\u2A4B",capcup:"\u2A47",capdot:"\u2A40",CapitalDifferentialD:"\u2145",caps:"\u2229\uFE00",caret:"\u2041",caron:"\u02C7",Cayleys:"\u212D",ccaps:"\u2A4D",Ccaron:"\u010C",ccaron:"\u010D",Ccedil:"\xC7",ccedil:"\xE7",Ccirc:"\u0108",ccirc:"\u0109",Cconint:"\u2230",ccups:"\u2A4C",ccupssm:"\u2A50",Cdot:"\u010A",cdot:"\u010B",cedil:"\xB8",Cedilla:"\xB8",cemptyv:"\u29B2",cent:"\xA2",CenterDot:"\xB7",centerdot:"\xB7",Cfr:"\u212D",cfr:"\u{1D520}",CHcy:"\u0427",chcy:"\u0447",check:"\u2713",checkmark:"\u2713",Chi:"\u03A7",chi:"\u03C7",cir:"\u25CB",circ:"\u02C6",circeq:"\u2257",circlearrowleft:"\u21BA",circlearrowright:"\u21BB",circledast:"\u229B",circledcirc:"\u229A",circleddash:"\u229D",CircleDot:"\u2299",circledR:"\xAE",circledS:"\u24C8",CircleMinus:"\u2296",CirclePlus:"\u2295",CircleTimes:"\u2297",cirE:"\u29C3",cire:"\u2257",cirfnint:"\u2A10",cirmid:"\u2AEF",cirscir:"\u29C2",ClockwiseContourIntegral:"\u2232",CloseCurlyDoubleQuote:"\u201D",CloseCurlyQuote:"\u2019",clubs:"\u2663",clubsuit:"\u2663",Colon:"\u2237",colon:":",Colone:"\u2A74",colone:"\u2254",coloneq:"\u2254",comma:",",commat:"@",comp:"\u2201",compfn:"\u2218",complement:"\u2201",complexes:"\u2102",cong:"\u2245",congdot:"\u2A6D",Congruent:"\u2261",Conint:"\u222F",conint:"\u222E",ContourIntegral:"\u222E",Copf:"\u2102",copf:"\u{1D554}",coprod:"\u2210",Coproduct:"\u2210",COPY:"\xA9",copy:"\xA9",copysr:"\u2117",CounterClockwiseContourIntegral:"\u2233",crarr:"\u21B5",Cross:"\u2A2F",cross:"\u2717",Cscr:"\u{1D49E}",cscr:"\u{1D4B8}",csub:"\u2ACF",csube:"\u2AD1",csup:"\u2AD0",csupe:"\u2AD2",ctdot:"\u22EF",cudarrl:"\u2938",cudarrr:"\u2935",cuepr:"\u22DE",cuesc:"\u22DF",cularr:"\u21B6",cularrp:"\u293D",Cup:"\u22D3",cup:"\u222A",cupbrcap:"\u2A48",CupCap:"\u224D",cupcap:"\u2A46",cupcup:"\u2A4A",cupdot:"\u228D",cupor:"\u2A45",cups:"\u222A\uFE00",curarr:"\u21B7",curarrm:"\u293C",curlyeqprec:"\u22DE",curlyeqsucc:"\u22DF",curlyvee:"\u22CE",curlywedge:"\u22CF",curren:"\xA4",curvearrowleft:"\u21B6",curvearrowright:"\u21B7",cuvee:"\u22CE",cuwed:"\u22CF",cwconint:"\u2232",cwint:"\u2231",cylcty:"\u232D",Dagger:"\u2021",dagger:"\u2020",daleth:"\u2138",Darr:"\u21A1",dArr:"\u21D3",darr:"\u2193",dash:"\u2010",Dashv:"\u2AE4",dashv:"\u22A3",dbkarow:"\u290F",dblac:"\u02DD",Dcaron:"\u010E",dcaron:"\u010F",Dcy:"\u0414",dcy:"\u0434",DD:"\u2145",dd:"\u2146",ddagger:"\u2021",ddarr:"\u21CA",DDotrahd:"\u2911",ddotseq:"\u2A77",deg:"\xB0",Del:"\u2207",Delta:"\u0394",delta:"\u03B4",demptyv:"\u29B1",dfisht:"\u297F",Dfr:"\u{1D507}",dfr:"\u{1D521}",dHar:"\u2965",dharl:"\u21C3",dharr:"\u21C2",DiacriticalAcute:"\xB4",DiacriticalDot:"\u02D9",DiacriticalDoubleAcute:"\u02DD",DiacriticalGrave:"`",DiacriticalTilde:"\u02DC",diam:"\u22C4",Diamond:"\u22C4",diamond:"\u22C4",diamondsuit:"\u2666",diams:"\u2666",die:"\xA8",DifferentialD:"\u2146",digamma:"\u03DD",disin:"\u22F2",div:"\xF7",divide:"\xF7",divideontimes:"\u22C7",divonx:"\u22C7",DJcy:"\u0402",djcy:"\u0452",dlcorn:"\u231E",dlcrop:"\u230D",dollar:"$",Dopf:"\u{1D53B}",dopf:"\u{1D555}",Dot:"\xA8",dot:"\u02D9",DotDot:"\u20DC",doteq:"\u2250",doteqdot:"\u2251",DotEqual:"\u2250",dotminus:"\u2238",dotplus:"\u2214",dotsquare:"\u22A1",doublebarwedge:"\u2306",DoubleContourIntegral:"\u222F",DoubleDot:"\xA8",DoubleDownArrow:"\u21D3",DoubleLeftArrow:"\u21D0",DoubleLeftRightArrow:"\u21D4",DoubleLeftTee:"\u2AE4",DoubleLongLeftArrow:"\u27F8",DoubleLongLeftRightArrow:"\u27FA",DoubleLongRightArrow:"\u27F9",DoubleRightArrow:"\u21D2",DoubleRightTee:"\u22A8",DoubleUpArrow:"\u21D1",DoubleUpDownArrow:"\u21D5",DoubleVerticalBar:"\u2225",DownArrow:"\u2193",Downarrow:"\u21D3",downarrow:"\u2193",DownArrowBar:"\u2913",DownArrowUpArrow:"\u21F5",DownBreve:"\u0311",downdownarrows:"\u21CA",downharpoonleft:"\u21C3",downharpoonright:"\u21C2",DownLeftRightVector:"\u2950",DownLeftTeeVector:"\u295E",DownLeftVector:"\u21BD",DownLeftVectorBar:"\u2956",DownRightTeeVector:"\u295F",DownRightVector:"\u21C1",DownRightVectorBar:"\u2957",DownTee:"\u22A4",DownTeeArrow:"\u21A7",drbkarow:"\u2910",drcorn:"\u231F",drcrop:"\u230C",Dscr:"\u{1D49F}",dscr:"\u{1D4B9}",DScy:"\u0405",dscy:"\u0455",dsol:"\u29F6",Dstrok:"\u0110",dstrok:"\u0111",dtdot:"\u22F1",dtri:"\u25BF",dtrif:"\u25BE",duarr:"\u21F5",duhar:"\u296F",dwangle:"\u29A6",DZcy:"\u040F",dzcy:"\u045F",dzigrarr:"\u27FF",Eacute:"\xC9",eacute:"\xE9",easter:"\u2A6E",Ecaron:"\u011A",ecaron:"\u011B",ecir:"\u2256",Ecirc:"\xCA",ecirc:"\xEA",ecolon:"\u2255",Ecy:"\u042D",ecy:"\u044D",eDDot:"\u2A77",Edot:"\u0116",eDot:"\u2251",edot:"\u0117",ee:"\u2147",efDot:"\u2252",Efr:"\u{1D508}",efr:"\u{1D522}",eg:"\u2A9A",Egrave:"\xC8",egrave:"\xE8",egs:"\u2A96",egsdot:"\u2A98",el:"\u2A99",Element:"\u2208",elinters:"\u23E7",ell:"\u2113",els:"\u2A95",elsdot:"\u2A97",Emacr:"\u0112",emacr:"\u0113",empty:"\u2205",emptyset:"\u2205",EmptySmallSquare:"\u25FB",emptyv:"\u2205",EmptyVerySmallSquare:"\u25AB",emsp:"\u2003",emsp13:"\u2004",emsp14:"\u2005",ENG:"\u014A",eng:"\u014B",ensp:"\u2002",Eogon:"\u0118",eogon:"\u0119",Eopf:"\u{1D53C}",eopf:"\u{1D556}",epar:"\u22D5",eparsl:"\u29E3",eplus:"\u2A71",epsi:"\u03B5",Epsilon:"\u0395",epsilon:"\u03B5",epsiv:"\u03F5",eqcirc:"\u2256",eqcolon:"\u2255",eqsim:"\u2242",eqslantgtr:"\u2A96",eqslantless:"\u2A95",Equal:"\u2A75",equals:"=",EqualTilde:"\u2242",equest:"\u225F",Equilibrium:"\u21CC",equiv:"\u2261",equivDD:"\u2A78",eqvparsl:"\u29E5",erarr:"\u2971",erDot:"\u2253",Escr:"\u2130",escr:"\u212F",esdot:"\u2250",Esim:"\u2A73",esim:"\u2242",Eta:"\u0397",eta:"\u03B7",ETH:"\xD0",eth:"\xF0",Euml:"\xCB",euml:"\xEB",euro:"\u20AC",excl:"!",exist:"\u2203",Exists:"\u2203",expectation:"\u2130",ExponentialE:"\u2147",exponentiale:"\u2147",fallingdotseq:"\u2252",Fcy:"\u0424",fcy:"\u0444",female:"\u2640",ffilig:"\uFB03",fflig:"\uFB00",ffllig:"\uFB04",Ffr:"\u{1D509}",ffr:"\u{1D523}",filig:"\uFB01",FilledSmallSquare:"\u25FC",FilledVerySmallSquare:"\u25AA",fjlig:"fj",flat:"\u266D",fllig:"\uFB02",fltns:"\u25B1",fnof:"\u0192",Fopf:"\u{1D53D}",fopf:"\u{1D557}",ForAll:"\u2200",forall:"\u2200",fork:"\u22D4",forkv:"\u2AD9",Fouriertrf:"\u2131",fpartint:"\u2A0D",frac12:"\xBD",frac13:"\u2153",frac14:"\xBC",frac15:"\u2155",frac16:"\u2159",frac18:"\u215B",frac23:"\u2154",frac25:"\u2156",frac34:"\xBE",frac35:"\u2157",frac38:"\u215C",frac45:"\u2158",frac56:"\u215A",frac58:"\u215D",frac78:"\u215E",frasl:"\u2044",frown:"\u2322",Fscr:"\u2131",fscr:"\u{1D4BB}",gacute:"\u01F5",Gamma:"\u0393",gamma:"\u03B3",Gammad:"\u03DC",gammad:"\u03DD",gap:"\u2A86",Gbreve:"\u011E",gbreve:"\u011F",Gcedil:"\u0122",Gcirc:"\u011C",gcirc:"\u011D",Gcy:"\u0413",gcy:"\u0433",Gdot:"\u0120",gdot:"\u0121",gE:"\u2267",ge:"\u2265",gEl:"\u2A8C",gel:"\u22DB",geq:"\u2265",geqq:"\u2267",geqslant:"\u2A7E",ges:"\u2A7E",gescc:"\u2AA9",gesdot:"\u2A80",gesdoto:"\u2A82",gesdotol:"\u2A84",gesl:"\u22DB\uFE00",gesles:"\u2A94",Gfr:"\u{1D50A}",gfr:"\u{1D524}",Gg:"\u22D9",gg:"\u226B",ggg:"\u22D9",gimel:"\u2137",GJcy:"\u0403",gjcy:"\u0453",gl:"\u2277",gla:"\u2AA5",glE:"\u2A92",glj:"\u2AA4",gnap:"\u2A8A",gnapprox:"\u2A8A",gnE:"\u2269",gne:"\u2A88",gneq:"\u2A88",gneqq:"\u2269",gnsim:"\u22E7",Gopf:"\u{1D53E}",gopf:"\u{1D558}",grave:"`",GreaterEqual:"\u2265",GreaterEqualLess:"\u22DB",GreaterFullEqual:"\u2267",GreaterGreater:"\u2AA2",GreaterLess:"\u2277",GreaterSlantEqual:"\u2A7E",GreaterTilde:"\u2273",Gscr:"\u{1D4A2}",gscr:"\u210A",gsim:"\u2273",gsime:"\u2A8E",gsiml:"\u2A90",Gt:"\u226B",GT:">",gt:">",gtcc:"\u2AA7",gtcir:"\u2A7A",gtdot:"\u22D7",gtlPar:"\u2995",gtquest:"\u2A7C",gtrapprox:"\u2A86",gtrarr:"\u2978",gtrdot:"\u22D7",gtreqless:"\u22DB",gtreqqless:"\u2A8C",gtrless:"\u2277",gtrsim:"\u2273",gvertneqq:"\u2269\uFE00",gvnE:"\u2269\uFE00",Hacek:"\u02C7",hairsp:"\u200A",half:"\xBD",hamilt:"\u210B",HARDcy:"\u042A",hardcy:"\u044A",hArr:"\u21D4",harr:"\u2194",harrcir:"\u2948",harrw:"\u21AD",Hat:"^",hbar:"\u210F",Hcirc:"\u0124",hcirc:"\u0125",hearts:"\u2665",heartsuit:"\u2665",hellip:"\u2026",hercon:"\u22B9",Hfr:"\u210C",hfr:"\u{1D525}",HilbertSpace:"\u210B",hksearow:"\u2925",hkswarow:"\u2926",hoarr:"\u21FF",homtht:"\u223B",hookleftarrow:"\u21A9",hookrightarrow:"\u21AA",Hopf:"\u210D",hopf:"\u{1D559}",horbar:"\u2015",HorizontalLine:"\u2500",Hscr:"\u210B",hscr:"\u{1D4BD}",hslash:"\u210F",Hstrok:"\u0126",hstrok:"\u0127",HumpDownHump:"\u224E",HumpEqual:"\u224F",hybull:"\u2043",hyphen:"\u2010",Iacute:"\xCD",iacute:"\xED",ic:"\u2063",Icirc:"\xCE",icirc:"\xEE",Icy:"\u0418",icy:"\u0438",Idot:"\u0130",IEcy:"\u0415",iecy:"\u0435",iexcl:"\xA1",iff:"\u21D4",Ifr:"\u2111",ifr:"\u{1D526}",Igrave:"\xCC",igrave:"\xEC",ii:"\u2148",iiiint:"\u2A0C",iiint:"\u222D",iinfin:"\u29DC",iiota:"\u2129",IJlig:"\u0132",ijlig:"\u0133",Im:"\u2111",Imacr:"\u012A",imacr:"\u012B",image:"\u2111",ImaginaryI:"\u2148",imagline:"\u2110",imagpart:"\u2111",imath:"\u0131",imof:"\u22B7",imped:"\u01B5",Implies:"\u21D2",in:"\u2208",incare:"\u2105",infin:"\u221E",infintie:"\u29DD",inodot:"\u0131",Int:"\u222C",int:"\u222B",intcal:"\u22BA",integers:"\u2124",Integral:"\u222B",intercal:"\u22BA",Intersection:"\u22C2",intlarhk:"\u2A17",intprod:"\u2A3C",InvisibleComma:"\u2063",InvisibleTimes:"\u2062",IOcy:"\u0401",iocy:"\u0451",Iogon:"\u012E",iogon:"\u012F",Iopf:"\u{1D540}",iopf:"\u{1D55A}",Iota:"\u0399",iota:"\u03B9",iprod:"\u2A3C",iquest:"\xBF",Iscr:"\u2110",iscr:"\u{1D4BE}",isin:"\u2208",isindot:"\u22F5",isinE:"\u22F9",isins:"\u22F4",isinsv:"\u22F3",isinv:"\u2208",it:"\u2062",Itilde:"\u0128",itilde:"\u0129",Iukcy:"\u0406",iukcy:"\u0456",Iuml:"\xCF",iuml:"\xEF",Jcirc:"\u0134",jcirc:"\u0135",Jcy:"\u0419",jcy:"\u0439",Jfr:"\u{1D50D}",jfr:"\u{1D527}",jmath:"\u0237",Jopf:"\u{1D541}",jopf:"\u{1D55B}",Jscr:"\u{1D4A5}",jscr:"\u{1D4BF}",Jsercy:"\u0408",jsercy:"\u0458",Jukcy:"\u0404",jukcy:"\u0454",Kappa:"\u039A",kappa:"\u03BA",kappav:"\u03F0",Kcedil:"\u0136",kcedil:"\u0137",Kcy:"\u041A",kcy:"\u043A",Kfr:"\u{1D50E}",kfr:"\u{1D528}",kgreen:"\u0138",KHcy:"\u0425",khcy:"\u0445",KJcy:"\u040C",kjcy:"\u045C",Kopf:"\u{1D542}",kopf:"\u{1D55C}",Kscr:"\u{1D4A6}",kscr:"\u{1D4C0}",lAarr:"\u21DA",Lacute:"\u0139",lacute:"\u013A",laemptyv:"\u29B4",lagran:"\u2112",Lambda:"\u039B",lambda:"\u03BB",Lang:"\u27EA",lang:"\u27E8",langd:"\u2991",langle:"\u27E8",lap:"\u2A85",Laplacetrf:"\u2112",laquo:"\xAB",Larr:"\u219E",lArr:"\u21D0",larr:"\u2190",larrb:"\u21E4",larrbfs:"\u291F",larrfs:"\u291D",larrhk:"\u21A9",larrlp:"\u21AB",larrpl:"\u2939",larrsim:"\u2973",larrtl:"\u21A2",lat:"\u2AAB",lAtail:"\u291B",latail:"\u2919",late:"\u2AAD",lates:"\u2AAD\uFE00",lBarr:"\u290E",lbarr:"\u290C",lbbrk:"\u2772",lbrace:"{",lbrack:"[",lbrke:"\u298B",lbrksld:"\u298F",lbrkslu:"\u298D",Lcaron:"\u013D",lcaron:"\u013E",Lcedil:"\u013B",lcedil:"\u013C",lceil:"\u2308",lcub:"{",Lcy:"\u041B",lcy:"\u043B",ldca:"\u2936",ldquo:"\u201C",ldquor:"\u201E",ldrdhar:"\u2967",ldrushar:"\u294B",ldsh:"\u21B2",lE:"\u2266",le:"\u2264",LeftAngleBracket:"\u27E8",LeftArrow:"\u2190",Leftarrow:"\u21D0",leftarrow:"\u2190",LeftArrowBar:"\u21E4",LeftArrowRightArrow:"\u21C6",leftarrowtail:"\u21A2",LeftCeiling:"\u2308",LeftDoubleBracket:"\u27E6",LeftDownTeeVector:"\u2961",LeftDownVector:"\u21C3",LeftDownVectorBar:"\u2959",LeftFloor:"\u230A",leftharpoondown:"\u21BD",leftharpoonup:"\u21BC",leftleftarrows:"\u21C7",LeftRightArrow:"\u2194",Leftrightarrow:"\u21D4",leftrightarrow:"\u2194",leftrightarrows:"\u21C6",leftrightharpoons:"\u21CB",leftrightsquigarrow:"\u21AD",LeftRightVector:"\u294E",LeftTee:"\u22A3",LeftTeeArrow:"\u21A4",LeftTeeVector:"\u295A",leftthreetimes:"\u22CB",LeftTriangle:"\u22B2",LeftTriangleBar:"\u29CF",LeftTriangleEqual:"\u22B4",LeftUpDownVector:"\u2951",LeftUpTeeVector:"\u2960",LeftUpVector:"\u21BF",LeftUpVectorBar:"\u2958",LeftVector:"\u21BC",LeftVectorBar:"\u2952",lEg:"\u2A8B",leg:"\u22DA",leq:"\u2264",leqq:"\u2266",leqslant:"\u2A7D",les:"\u2A7D",lescc:"\u2AA8",lesdot:"\u2A7F",lesdoto:"\u2A81",lesdotor:"\u2A83",lesg:"\u22DA\uFE00",lesges:"\u2A93",lessapprox:"\u2A85",lessdot:"\u22D6",lesseqgtr:"\u22DA",lesseqqgtr:"\u2A8B",LessEqualGreater:"\u22DA",LessFullEqual:"\u2266",LessGreater:"\u2276",lessgtr:"\u2276",LessLess:"\u2AA1",lesssim:"\u2272",LessSlantEqual:"\u2A7D",LessTilde:"\u2272",lfisht:"\u297C",lfloor:"\u230A",Lfr:"\u{1D50F}",lfr:"\u{1D529}",lg:"\u2276",lgE:"\u2A91",lHar:"\u2962",lhard:"\u21BD",lharu:"\u21BC",lharul:"\u296A",lhblk:"\u2584",LJcy:"\u0409",ljcy:"\u0459",Ll:"\u22D8",ll:"\u226A",llarr:"\u21C7",llcorner:"\u231E",Lleftarrow:"\u21DA",llhard:"\u296B",lltri:"\u25FA",Lmidot:"\u013F",lmidot:"\u0140",lmoust:"\u23B0",lmoustache:"\u23B0",lnap:"\u2A89",lnapprox:"\u2A89",lnE:"\u2268",lne:"\u2A87",lneq:"\u2A87",lneqq:"\u2268",lnsim:"\u22E6",loang:"\u27EC",loarr:"\u21FD",lobrk:"\u27E6",LongLeftArrow:"\u27F5",Longleftarrow:"\u27F8",longleftarrow:"\u27F5",LongLeftRightArrow:"\u27F7",Longleftrightarrow:"\u27FA",longleftrightarrow:"\u27F7",longmapsto:"\u27FC",LongRightArrow:"\u27F6",Longrightarrow:"\u27F9",longrightarrow:"\u27F6",looparrowleft:"\u21AB",looparrowright:"\u21AC",lopar:"\u2985",Lopf:"\u{1D543}",lopf:"\u{1D55D}",loplus:"\u2A2D",lotimes:"\u2A34",lowast:"\u2217",lowbar:"_",LowerLeftArrow:"\u2199",LowerRightArrow:"\u2198",loz:"\u25CA",lozenge:"\u25CA",lozf:"\u29EB",lpar:"(",lparlt:"\u2993",lrarr:"\u21C6",lrcorner:"\u231F",lrhar:"\u21CB",lrhard:"\u296D",lrm:"\u200E",lrtri:"\u22BF",lsaquo:"\u2039",Lscr:"\u2112",lscr:"\u{1D4C1}",Lsh:"\u21B0",lsh:"\u21B0",lsim:"\u2272",lsime:"\u2A8D",lsimg:"\u2A8F",lsqb:"[",lsquo:"\u2018",lsquor:"\u201A",Lstrok:"\u0141",lstrok:"\u0142",Lt:"\u226A",LT:"<",lt:"<",ltcc:"\u2AA6",ltcir:"\u2A79",ltdot:"\u22D6",lthree:"\u22CB",ltimes:"\u22C9",ltlarr:"\u2976",ltquest:"\u2A7B",ltri:"\u25C3",ltrie:"\u22B4",ltrif:"\u25C2",ltrPar:"\u2996",lurdshar:"\u294A",luruhar:"\u2966",lvertneqq:"\u2268\uFE00",lvnE:"\u2268\uFE00",macr:"\xAF",male:"\u2642",malt:"\u2720",maltese:"\u2720",Map:"\u2905",map:"\u21A6",mapsto:"\u21A6",mapstodown:"\u21A7",mapstoleft:"\u21A4",mapstoup:"\u21A5",marker:"\u25AE",mcomma:"\u2A29",Mcy:"\u041C",mcy:"\u043C",mdash:"\u2014",mDDot:"\u223A",measuredangle:"\u2221",MediumSpace:"\u205F",Mellintrf:"\u2133",Mfr:"\u{1D510}",mfr:"\u{1D52A}",mho:"\u2127",micro:"\xB5",mid:"\u2223",midast:"*",midcir:"\u2AF0",middot:"\xB7",minus:"\u2212",minusb:"\u229F",minusd:"\u2238",minusdu:"\u2A2A",MinusPlus:"\u2213",mlcp:"\u2ADB",mldr:"\u2026",mnplus:"\u2213",models:"\u22A7",Mopf:"\u{1D544}",mopf:"\u{1D55E}",mp:"\u2213",Mscr:"\u2133",mscr:"\u{1D4C2}",mstpos:"\u223E",Mu:"\u039C",mu:"\u03BC",multimap:"\u22B8",mumap:"\u22B8",nabla:"\u2207",Nacute:"\u0143",nacute:"\u0144",nang:"\u2220\u20D2",nap:"\u2249",napE:"\u2A70\u0338",napid:"\u224B\u0338",napos:"\u0149",napprox:"\u2249",natur:"\u266E",natural:"\u266E",naturals:"\u2115",nbsp:"\xA0",nbump:"\u224E\u0338",nbumpe:"\u224F\u0338",ncap:"\u2A43",Ncaron:"\u0147",ncaron:"\u0148",Ncedil:"\u0145",ncedil:"\u0146",ncong:"\u2247",ncongdot:"\u2A6D\u0338",ncup:"\u2A42",Ncy:"\u041D",ncy:"\u043D",ndash:"\u2013",ne:"\u2260",nearhk:"\u2924",neArr:"\u21D7",nearr:"\u2197",nearrow:"\u2197",nedot:"\u2250\u0338",NegativeMediumSpace:"\u200B",NegativeThickSpace:"\u200B",NegativeThinSpace:"\u200B",NegativeVeryThinSpace:"\u200B",nequiv:"\u2262",nesear:"\u2928",nesim:"\u2242\u0338",NestedGreaterGreater:"\u226B",NestedLessLess:"\u226A",NewLine:`+`,nexist:"\u2204",nexists:"\u2204",Nfr:"\u{1D511}",nfr:"\u{1D52B}",ngE:"\u2267\u0338",nge:"\u2271",ngeq:"\u2271",ngeqq:"\u2267\u0338",ngeqslant:"\u2A7E\u0338",nges:"\u2A7E\u0338",nGg:"\u22D9\u0338",ngsim:"\u2275",nGt:"\u226B\u20D2",ngt:"\u226F",ngtr:"\u226F",nGtv:"\u226B\u0338",nhArr:"\u21CE",nharr:"\u21AE",nhpar:"\u2AF2",ni:"\u220B",nis:"\u22FC",nisd:"\u22FA",niv:"\u220B",NJcy:"\u040A",njcy:"\u045A",nlArr:"\u21CD",nlarr:"\u219A",nldr:"\u2025",nlE:"\u2266\u0338",nle:"\u2270",nLeftarrow:"\u21CD",nleftarrow:"\u219A",nLeftrightarrow:"\u21CE",nleftrightarrow:"\u21AE",nleq:"\u2270",nleqq:"\u2266\u0338",nleqslant:"\u2A7D\u0338",nles:"\u2A7D\u0338",nless:"\u226E",nLl:"\u22D8\u0338",nlsim:"\u2274",nLt:"\u226A\u20D2",nlt:"\u226E",nltri:"\u22EA",nltrie:"\u22EC",nLtv:"\u226A\u0338",nmid:"\u2224",NoBreak:"\u2060",NonBreakingSpace:"\xA0",Nopf:"\u2115",nopf:"\u{1D55F}",Not:"\u2AEC",not:"\xAC",NotCongruent:"\u2262",NotCupCap:"\u226D",NotDoubleVerticalBar:"\u2226",NotElement:"\u2209",NotEqual:"\u2260",NotEqualTilde:"\u2242\u0338",NotExists:"\u2204",NotGreater:"\u226F",NotGreaterEqual:"\u2271",NotGreaterFullEqual:"\u2267\u0338",NotGreaterGreater:"\u226B\u0338",NotGreaterLess:"\u2279",NotGreaterSlantEqual:"\u2A7E\u0338",NotGreaterTilde:"\u2275",NotHumpDownHump:"\u224E\u0338",NotHumpEqual:"\u224F\u0338",notin:"\u2209",notindot:"\u22F5\u0338",notinE:"\u22F9\u0338",notinva:"\u2209",notinvb:"\u22F7",notinvc:"\u22F6",NotLeftTriangle:"\u22EA",NotLeftTriangleBar:"\u29CF\u0338",NotLeftTriangleEqual:"\u22EC",NotLess:"\u226E",NotLessEqual:"\u2270",NotLessGreater:"\u2278",NotLessLess:"\u226A\u0338",NotLessSlantEqual:"\u2A7D\u0338",NotLessTilde:"\u2274",NotNestedGreaterGreater:"\u2AA2\u0338",NotNestedLessLess:"\u2AA1\u0338",notni:"\u220C",notniva:"\u220C",notnivb:"\u22FE",notnivc:"\u22FD",NotPrecedes:"\u2280",NotPrecedesEqual:"\u2AAF\u0338",NotPrecedesSlantEqual:"\u22E0",NotReverseElement:"\u220C",NotRightTriangle:"\u22EB",NotRightTriangleBar:"\u29D0\u0338",NotRightTriangleEqual:"\u22ED",NotSquareSubset:"\u228F\u0338",NotSquareSubsetEqual:"\u22E2",NotSquareSuperset:"\u2290\u0338",NotSquareSupersetEqual:"\u22E3",NotSubset:"\u2282\u20D2",NotSubsetEqual:"\u2288",NotSucceeds:"\u2281",NotSucceedsEqual:"\u2AB0\u0338",NotSucceedsSlantEqual:"\u22E1",NotSucceedsTilde:"\u227F\u0338",NotSuperset:"\u2283\u20D2",NotSupersetEqual:"\u2289",NotTilde:"\u2241",NotTildeEqual:"\u2244",NotTildeFullEqual:"\u2247",NotTildeTilde:"\u2249",NotVerticalBar:"\u2224",npar:"\u2226",nparallel:"\u2226",nparsl:"\u2AFD\u20E5",npart:"\u2202\u0338",npolint:"\u2A14",npr:"\u2280",nprcue:"\u22E0",npre:"\u2AAF\u0338",nprec:"\u2280",npreceq:"\u2AAF\u0338",nrArr:"\u21CF",nrarr:"\u219B",nrarrc:"\u2933\u0338",nrarrw:"\u219D\u0338",nRightarrow:"\u21CF",nrightarrow:"\u219B",nrtri:"\u22EB",nrtrie:"\u22ED",nsc:"\u2281",nsccue:"\u22E1",nsce:"\u2AB0\u0338",Nscr:"\u{1D4A9}",nscr:"\u{1D4C3}",nshortmid:"\u2224",nshortparallel:"\u2226",nsim:"\u2241",nsime:"\u2244",nsimeq:"\u2244",nsmid:"\u2224",nspar:"\u2226",nsqsube:"\u22E2",nsqsupe:"\u22E3",nsub:"\u2284",nsubE:"\u2AC5\u0338",nsube:"\u2288",nsubset:"\u2282\u20D2",nsubseteq:"\u2288",nsubseteqq:"\u2AC5\u0338",nsucc:"\u2281",nsucceq:"\u2AB0\u0338",nsup:"\u2285",nsupE:"\u2AC6\u0338",nsupe:"\u2289",nsupset:"\u2283\u20D2",nsupseteq:"\u2289",nsupseteqq:"\u2AC6\u0338",ntgl:"\u2279",Ntilde:"\xD1",ntilde:"\xF1",ntlg:"\u2278",ntriangleleft:"\u22EA",ntrianglelefteq:"\u22EC",ntriangleright:"\u22EB",ntrianglerighteq:"\u22ED",Nu:"\u039D",nu:"\u03BD",num:"#",numero:"\u2116",numsp:"\u2007",nvap:"\u224D\u20D2",nVDash:"\u22AF",nVdash:"\u22AE",nvDash:"\u22AD",nvdash:"\u22AC",nvge:"\u2265\u20D2",nvgt:">\u20D2",nvHarr:"\u2904",nvinfin:"\u29DE",nvlArr:"\u2902",nvle:"\u2264\u20D2",nvlt:"<\u20D2",nvltrie:"\u22B4\u20D2",nvrArr:"\u2903",nvrtrie:"\u22B5\u20D2",nvsim:"\u223C\u20D2",nwarhk:"\u2923",nwArr:"\u21D6",nwarr:"\u2196",nwarrow:"\u2196",nwnear:"\u2927",Oacute:"\xD3",oacute:"\xF3",oast:"\u229B",ocir:"\u229A",Ocirc:"\xD4",ocirc:"\xF4",Ocy:"\u041E",ocy:"\u043E",odash:"\u229D",Odblac:"\u0150",odblac:"\u0151",odiv:"\u2A38",odot:"\u2299",odsold:"\u29BC",OElig:"\u0152",oelig:"\u0153",ofcir:"\u29BF",Ofr:"\u{1D512}",ofr:"\u{1D52C}",ogon:"\u02DB",Ograve:"\xD2",ograve:"\xF2",ogt:"\u29C1",ohbar:"\u29B5",ohm:"\u03A9",oint:"\u222E",olarr:"\u21BA",olcir:"\u29BE",olcross:"\u29BB",oline:"\u203E",olt:"\u29C0",Omacr:"\u014C",omacr:"\u014D",Omega:"\u03A9",omega:"\u03C9",Omicron:"\u039F",omicron:"\u03BF",omid:"\u29B6",ominus:"\u2296",Oopf:"\u{1D546}",oopf:"\u{1D560}",opar:"\u29B7",OpenCurlyDoubleQuote:"\u201C",OpenCurlyQuote:"\u2018",operp:"\u29B9",oplus:"\u2295",Or:"\u2A54",or:"\u2228",orarr:"\u21BB",ord:"\u2A5D",order:"\u2134",orderof:"\u2134",ordf:"\xAA",ordm:"\xBA",origof:"\u22B6",oror:"\u2A56",orslope:"\u2A57",orv:"\u2A5B",oS:"\u24C8",Oscr:"\u{1D4AA}",oscr:"\u2134",Oslash:"\xD8",oslash:"\xF8",osol:"\u2298",Otilde:"\xD5",otilde:"\xF5",Otimes:"\u2A37",otimes:"\u2297",otimesas:"\u2A36",Ouml:"\xD6",ouml:"\xF6",ovbar:"\u233D",OverBar:"\u203E",OverBrace:"\u23DE",OverBracket:"\u23B4",OverParenthesis:"\u23DC",par:"\u2225",para:"\xB6",parallel:"\u2225",parsim:"\u2AF3",parsl:"\u2AFD",part:"\u2202",PartialD:"\u2202",Pcy:"\u041F",pcy:"\u043F",percnt:"%",period:".",permil:"\u2030",perp:"\u22A5",pertenk:"\u2031",Pfr:"\u{1D513}",pfr:"\u{1D52D}",Phi:"\u03A6",phi:"\u03C6",phiv:"\u03D5",phmmat:"\u2133",phone:"\u260E",Pi:"\u03A0",pi:"\u03C0",pitchfork:"\u22D4",piv:"\u03D6",planck:"\u210F",planckh:"\u210E",plankv:"\u210F",plus:"+",plusacir:"\u2A23",plusb:"\u229E",pluscir:"\u2A22",plusdo:"\u2214",plusdu:"\u2A25",pluse:"\u2A72",PlusMinus:"\xB1",plusmn:"\xB1",plussim:"\u2A26",plustwo:"\u2A27",pm:"\xB1",Poincareplane:"\u210C",pointint:"\u2A15",Popf:"\u2119",popf:"\u{1D561}",pound:"\xA3",Pr:"\u2ABB",pr:"\u227A",prap:"\u2AB7",prcue:"\u227C",prE:"\u2AB3",pre:"\u2AAF",prec:"\u227A",precapprox:"\u2AB7",preccurlyeq:"\u227C",Precedes:"\u227A",PrecedesEqual:"\u2AAF",PrecedesSlantEqual:"\u227C",PrecedesTilde:"\u227E",preceq:"\u2AAF",precnapprox:"\u2AB9",precneqq:"\u2AB5",precnsim:"\u22E8",precsim:"\u227E",Prime:"\u2033",prime:"\u2032",primes:"\u2119",prnap:"\u2AB9",prnE:"\u2AB5",prnsim:"\u22E8",prod:"\u220F",Product:"\u220F",profalar:"\u232E",profline:"\u2312",profsurf:"\u2313",prop:"\u221D",Proportion:"\u2237",Proportional:"\u221D",propto:"\u221D",prsim:"\u227E",prurel:"\u22B0",Pscr:"\u{1D4AB}",pscr:"\u{1D4C5}",Psi:"\u03A8",psi:"\u03C8",puncsp:"\u2008",Qfr:"\u{1D514}",qfr:"\u{1D52E}",qint:"\u2A0C",Qopf:"\u211A",qopf:"\u{1D562}",qprime:"\u2057",Qscr:"\u{1D4AC}",qscr:"\u{1D4C6}",quaternions:"\u210D",quatint:"\u2A16",quest:"?",questeq:"\u225F",QUOT:'"',quot:'"',rAarr:"\u21DB",race:"\u223D\u0331",Racute:"\u0154",racute:"\u0155",radic:"\u221A",raemptyv:"\u29B3",Rang:"\u27EB",rang:"\u27E9",rangd:"\u2992",range:"\u29A5",rangle:"\u27E9",raquo:"\xBB",Rarr:"\u21A0",rArr:"\u21D2",rarr:"\u2192",rarrap:"\u2975",rarrb:"\u21E5",rarrbfs:"\u2920",rarrc:"\u2933",rarrfs:"\u291E",rarrhk:"\u21AA",rarrlp:"\u21AC",rarrpl:"\u2945",rarrsim:"\u2974",Rarrtl:"\u2916",rarrtl:"\u21A3",rarrw:"\u219D",rAtail:"\u291C",ratail:"\u291A",ratio:"\u2236",rationals:"\u211A",RBarr:"\u2910",rBarr:"\u290F",rbarr:"\u290D",rbbrk:"\u2773",rbrace:"}",rbrack:"]",rbrke:"\u298C",rbrksld:"\u298E",rbrkslu:"\u2990",Rcaron:"\u0158",rcaron:"\u0159",Rcedil:"\u0156",rcedil:"\u0157",rceil:"\u2309",rcub:"}",Rcy:"\u0420",rcy:"\u0440",rdca:"\u2937",rdldhar:"\u2969",rdquo:"\u201D",rdquor:"\u201D",rdsh:"\u21B3",Re:"\u211C",real:"\u211C",realine:"\u211B",realpart:"\u211C",reals:"\u211D",rect:"\u25AD",REG:"\xAE",reg:"\xAE",ReverseElement:"\u220B",ReverseEquilibrium:"\u21CB",ReverseUpEquilibrium:"\u296F",rfisht:"\u297D",rfloor:"\u230B",Rfr:"\u211C",rfr:"\u{1D52F}",rHar:"\u2964",rhard:"\u21C1",rharu:"\u21C0",rharul:"\u296C",Rho:"\u03A1",rho:"\u03C1",rhov:"\u03F1",RightAngleBracket:"\u27E9",RightArrow:"\u2192",Rightarrow:"\u21D2",rightarrow:"\u2192",RightArrowBar:"\u21E5",RightArrowLeftArrow:"\u21C4",rightarrowtail:"\u21A3",RightCeiling:"\u2309",RightDoubleBracket:"\u27E7",RightDownTeeVector:"\u295D",RightDownVector:"\u21C2",RightDownVectorBar:"\u2955",RightFloor:"\u230B",rightharpoondown:"\u21C1",rightharpoonup:"\u21C0",rightleftarrows:"\u21C4",rightleftharpoons:"\u21CC",rightrightarrows:"\u21C9",rightsquigarrow:"\u219D",RightTee:"\u22A2",RightTeeArrow:"\u21A6",RightTeeVector:"\u295B",rightthreetimes:"\u22CC",RightTriangle:"\u22B3",RightTriangleBar:"\u29D0",RightTriangleEqual:"\u22B5",RightUpDownVector:"\u294F",RightUpTeeVector:"\u295C",RightUpVector:"\u21BE",RightUpVectorBar:"\u2954",RightVector:"\u21C0",RightVectorBar:"\u2953",ring:"\u02DA",risingdotseq:"\u2253",rlarr:"\u21C4",rlhar:"\u21CC",rlm:"\u200F",rmoust:"\u23B1",rmoustache:"\u23B1",rnmid:"\u2AEE",roang:"\u27ED",roarr:"\u21FE",robrk:"\u27E7",ropar:"\u2986",Ropf:"\u211D",ropf:"\u{1D563}",roplus:"\u2A2E",rotimes:"\u2A35",RoundImplies:"\u2970",rpar:")",rpargt:"\u2994",rppolint:"\u2A12",rrarr:"\u21C9",Rrightarrow:"\u21DB",rsaquo:"\u203A",Rscr:"\u211B",rscr:"\u{1D4C7}",Rsh:"\u21B1",rsh:"\u21B1",rsqb:"]",rsquo:"\u2019",rsquor:"\u2019",rthree:"\u22CC",rtimes:"\u22CA",rtri:"\u25B9",rtrie:"\u22B5",rtrif:"\u25B8",rtriltri:"\u29CE",RuleDelayed:"\u29F4",ruluhar:"\u2968",rx:"\u211E",Sacute:"\u015A",sacute:"\u015B",sbquo:"\u201A",Sc:"\u2ABC",sc:"\u227B",scap:"\u2AB8",Scaron:"\u0160",scaron:"\u0161",sccue:"\u227D",scE:"\u2AB4",sce:"\u2AB0",Scedil:"\u015E",scedil:"\u015F",Scirc:"\u015C",scirc:"\u015D",scnap:"\u2ABA",scnE:"\u2AB6",scnsim:"\u22E9",scpolint:"\u2A13",scsim:"\u227F",Scy:"\u0421",scy:"\u0441",sdot:"\u22C5",sdotb:"\u22A1",sdote:"\u2A66",searhk:"\u2925",seArr:"\u21D8",searr:"\u2198",searrow:"\u2198",sect:"\xA7",semi:";",seswar:"\u2929",setminus:"\u2216",setmn:"\u2216",sext:"\u2736",Sfr:"\u{1D516}",sfr:"\u{1D530}",sfrown:"\u2322",sharp:"\u266F",SHCHcy:"\u0429",shchcy:"\u0449",SHcy:"\u0428",shcy:"\u0448",ShortDownArrow:"\u2193",ShortLeftArrow:"\u2190",shortmid:"\u2223",shortparallel:"\u2225",ShortRightArrow:"\u2192",ShortUpArrow:"\u2191",shy:"\xAD",Sigma:"\u03A3",sigma:"\u03C3",sigmaf:"\u03C2",sigmav:"\u03C2",sim:"\u223C",simdot:"\u2A6A",sime:"\u2243",simeq:"\u2243",simg:"\u2A9E",simgE:"\u2AA0",siml:"\u2A9D",simlE:"\u2A9F",simne:"\u2246",simplus:"\u2A24",simrarr:"\u2972",slarr:"\u2190",SmallCircle:"\u2218",smallsetminus:"\u2216",smashp:"\u2A33",smeparsl:"\u29E4",smid:"\u2223",smile:"\u2323",smt:"\u2AAA",smte:"\u2AAC",smtes:"\u2AAC\uFE00",SOFTcy:"\u042C",softcy:"\u044C",sol:"/",solb:"\u29C4",solbar:"\u233F",Sopf:"\u{1D54A}",sopf:"\u{1D564}",spades:"\u2660",spadesuit:"\u2660",spar:"\u2225",sqcap:"\u2293",sqcaps:"\u2293\uFE00",sqcup:"\u2294",sqcups:"\u2294\uFE00",Sqrt:"\u221A",sqsub:"\u228F",sqsube:"\u2291",sqsubset:"\u228F",sqsubseteq:"\u2291",sqsup:"\u2290",sqsupe:"\u2292",sqsupset:"\u2290",sqsupseteq:"\u2292",squ:"\u25A1",Square:"\u25A1",square:"\u25A1",SquareIntersection:"\u2293",SquareSubset:"\u228F",SquareSubsetEqual:"\u2291",SquareSuperset:"\u2290",SquareSupersetEqual:"\u2292",SquareUnion:"\u2294",squarf:"\u25AA",squf:"\u25AA",srarr:"\u2192",Sscr:"\u{1D4AE}",sscr:"\u{1D4C8}",ssetmn:"\u2216",ssmile:"\u2323",sstarf:"\u22C6",Star:"\u22C6",star:"\u2606",starf:"\u2605",straightepsilon:"\u03F5",straightphi:"\u03D5",strns:"\xAF",Sub:"\u22D0",sub:"\u2282",subdot:"\u2ABD",subE:"\u2AC5",sube:"\u2286",subedot:"\u2AC3",submult:"\u2AC1",subnE:"\u2ACB",subne:"\u228A",subplus:"\u2ABF",subrarr:"\u2979",Subset:"\u22D0",subset:"\u2282",subseteq:"\u2286",subseteqq:"\u2AC5",SubsetEqual:"\u2286",subsetneq:"\u228A",subsetneqq:"\u2ACB",subsim:"\u2AC7",subsub:"\u2AD5",subsup:"\u2AD3",succ:"\u227B",succapprox:"\u2AB8",succcurlyeq:"\u227D",Succeeds:"\u227B",SucceedsEqual:"\u2AB0",SucceedsSlantEqual:"\u227D",SucceedsTilde:"\u227F",succeq:"\u2AB0",succnapprox:"\u2ABA",succneqq:"\u2AB6",succnsim:"\u22E9",succsim:"\u227F",SuchThat:"\u220B",Sum:"\u2211",sum:"\u2211",sung:"\u266A",Sup:"\u22D1",sup:"\u2283",sup1:"\xB9",sup2:"\xB2",sup3:"\xB3",supdot:"\u2ABE",supdsub:"\u2AD8",supE:"\u2AC6",supe:"\u2287",supedot:"\u2AC4",Superset:"\u2283",SupersetEqual:"\u2287",suphsol:"\u27C9",suphsub:"\u2AD7",suplarr:"\u297B",supmult:"\u2AC2",supnE:"\u2ACC",supne:"\u228B",supplus:"\u2AC0",Supset:"\u22D1",supset:"\u2283",supseteq:"\u2287",supseteqq:"\u2AC6",supsetneq:"\u228B",supsetneqq:"\u2ACC",supsim:"\u2AC8",supsub:"\u2AD4",supsup:"\u2AD6",swarhk:"\u2926",swArr:"\u21D9",swarr:"\u2199",swarrow:"\u2199",swnwar:"\u292A",szlig:"\xDF",Tab:" ",target:"\u2316",Tau:"\u03A4",tau:"\u03C4",tbrk:"\u23B4",Tcaron:"\u0164",tcaron:"\u0165",Tcedil:"\u0162",tcedil:"\u0163",Tcy:"\u0422",tcy:"\u0442",tdot:"\u20DB",telrec:"\u2315",Tfr:"\u{1D517}",tfr:"\u{1D531}",there4:"\u2234",Therefore:"\u2234",therefore:"\u2234",Theta:"\u0398",theta:"\u03B8",thetasym:"\u03D1",thetav:"\u03D1",thickapprox:"\u2248",thicksim:"\u223C",ThickSpace:"\u205F\u200A",thinsp:"\u2009",ThinSpace:"\u2009",thkap:"\u2248",thksim:"\u223C",THORN:"\xDE",thorn:"\xFE",Tilde:"\u223C",tilde:"\u02DC",TildeEqual:"\u2243",TildeFullEqual:"\u2245",TildeTilde:"\u2248",times:"\xD7",timesb:"\u22A0",timesbar:"\u2A31",timesd:"\u2A30",tint:"\u222D",toea:"\u2928",top:"\u22A4",topbot:"\u2336",topcir:"\u2AF1",Topf:"\u{1D54B}",topf:"\u{1D565}",topfork:"\u2ADA",tosa:"\u2929",tprime:"\u2034",TRADE:"\u2122",trade:"\u2122",triangle:"\u25B5",triangledown:"\u25BF",triangleleft:"\u25C3",trianglelefteq:"\u22B4",triangleq:"\u225C",triangleright:"\u25B9",trianglerighteq:"\u22B5",tridot:"\u25EC",trie:"\u225C",triminus:"\u2A3A",TripleDot:"\u20DB",triplus:"\u2A39",trisb:"\u29CD",tritime:"\u2A3B",trpezium:"\u23E2",Tscr:"\u{1D4AF}",tscr:"\u{1D4C9}",TScy:"\u0426",tscy:"\u0446",TSHcy:"\u040B",tshcy:"\u045B",Tstrok:"\u0166",tstrok:"\u0167",twixt:"\u226C",twoheadleftarrow:"\u219E",twoheadrightarrow:"\u21A0",Uacute:"\xDA",uacute:"\xFA",Uarr:"\u219F",uArr:"\u21D1",uarr:"\u2191",Uarrocir:"\u2949",Ubrcy:"\u040E",ubrcy:"\u045E",Ubreve:"\u016C",ubreve:"\u016D",Ucirc:"\xDB",ucirc:"\xFB",Ucy:"\u0423",ucy:"\u0443",udarr:"\u21C5",Udblac:"\u0170",udblac:"\u0171",udhar:"\u296E",ufisht:"\u297E",Ufr:"\u{1D518}",ufr:"\u{1D532}",Ugrave:"\xD9",ugrave:"\xF9",uHar:"\u2963",uharl:"\u21BF",uharr:"\u21BE",uhblk:"\u2580",ulcorn:"\u231C",ulcorner:"\u231C",ulcrop:"\u230F",ultri:"\u25F8",Umacr:"\u016A",umacr:"\u016B",uml:"\xA8",UnderBar:"_",UnderBrace:"\u23DF",UnderBracket:"\u23B5",UnderParenthesis:"\u23DD",Union:"\u22C3",UnionPlus:"\u228E",Uogon:"\u0172",uogon:"\u0173",Uopf:"\u{1D54C}",uopf:"\u{1D566}",UpArrow:"\u2191",Uparrow:"\u21D1",uparrow:"\u2191",UpArrowBar:"\u2912",UpArrowDownArrow:"\u21C5",UpDownArrow:"\u2195",Updownarrow:"\u21D5",updownarrow:"\u2195",UpEquilibrium:"\u296E",upharpoonleft:"\u21BF",upharpoonright:"\u21BE",uplus:"\u228E",UpperLeftArrow:"\u2196",UpperRightArrow:"\u2197",Upsi:"\u03D2",upsi:"\u03C5",upsih:"\u03D2",Upsilon:"\u03A5",upsilon:"\u03C5",UpTee:"\u22A5",UpTeeArrow:"\u21A5",upuparrows:"\u21C8",urcorn:"\u231D",urcorner:"\u231D",urcrop:"\u230E",Uring:"\u016E",uring:"\u016F",urtri:"\u25F9",Uscr:"\u{1D4B0}",uscr:"\u{1D4CA}",utdot:"\u22F0",Utilde:"\u0168",utilde:"\u0169",utri:"\u25B5",utrif:"\u25B4",uuarr:"\u21C8",Uuml:"\xDC",uuml:"\xFC",uwangle:"\u29A7",vangrt:"\u299C",varepsilon:"\u03F5",varkappa:"\u03F0",varnothing:"\u2205",varphi:"\u03D5",varpi:"\u03D6",varpropto:"\u221D",vArr:"\u21D5",varr:"\u2195",varrho:"\u03F1",varsigma:"\u03C2",varsubsetneq:"\u228A\uFE00",varsubsetneqq:"\u2ACB\uFE00",varsupsetneq:"\u228B\uFE00",varsupsetneqq:"\u2ACC\uFE00",vartheta:"\u03D1",vartriangleleft:"\u22B2",vartriangleright:"\u22B3",Vbar:"\u2AEB",vBar:"\u2AE8",vBarv:"\u2AE9",Vcy:"\u0412",vcy:"\u0432",VDash:"\u22AB",Vdash:"\u22A9",vDash:"\u22A8",vdash:"\u22A2",Vdashl:"\u2AE6",Vee:"\u22C1",vee:"\u2228",veebar:"\u22BB",veeeq:"\u225A",vellip:"\u22EE",Verbar:"\u2016",verbar:"|",Vert:"\u2016",vert:"|",VerticalBar:"\u2223",VerticalLine:"|",VerticalSeparator:"\u2758",VerticalTilde:"\u2240",VeryThinSpace:"\u200A",Vfr:"\u{1D519}",vfr:"\u{1D533}",vltri:"\u22B2",vnsub:"\u2282\u20D2",vnsup:"\u2283\u20D2",Vopf:"\u{1D54D}",vopf:"\u{1D567}",vprop:"\u221D",vrtri:"\u22B3",Vscr:"\u{1D4B1}",vscr:"\u{1D4CB}",vsubnE:"\u2ACB\uFE00",vsubne:"\u228A\uFE00",vsupnE:"\u2ACC\uFE00",vsupne:"\u228B\uFE00",Vvdash:"\u22AA",vzigzag:"\u299A",Wcirc:"\u0174",wcirc:"\u0175",wedbar:"\u2A5F",Wedge:"\u22C0",wedge:"\u2227",wedgeq:"\u2259",weierp:"\u2118",Wfr:"\u{1D51A}",wfr:"\u{1D534}",Wopf:"\u{1D54E}",wopf:"\u{1D568}",wp:"\u2118",wr:"\u2240",wreath:"\u2240",Wscr:"\u{1D4B2}",wscr:"\u{1D4CC}",xcap:"\u22C2",xcirc:"\u25EF",xcup:"\u22C3",xdtri:"\u25BD",Xfr:"\u{1D51B}",xfr:"\u{1D535}",xhArr:"\u27FA",xharr:"\u27F7",Xi:"\u039E",xi:"\u03BE",xlArr:"\u27F8",xlarr:"\u27F5",xmap:"\u27FC",xnis:"\u22FB",xodot:"\u2A00",Xopf:"\u{1D54F}",xopf:"\u{1D569}",xoplus:"\u2A01",xotime:"\u2A02",xrArr:"\u27F9",xrarr:"\u27F6",Xscr:"\u{1D4B3}",xscr:"\u{1D4CD}",xsqcup:"\u2A06",xuplus:"\u2A04",xutri:"\u25B3",xvee:"\u22C1",xwedge:"\u22C0",Yacute:"\xDD",yacute:"\xFD",YAcy:"\u042F",yacy:"\u044F",Ycirc:"\u0176",ycirc:"\u0177",Ycy:"\u042B",ycy:"\u044B",yen:"\xA5",Yfr:"\u{1D51C}",yfr:"\u{1D536}",YIcy:"\u0407",yicy:"\u0457",Yopf:"\u{1D550}",yopf:"\u{1D56A}",Yscr:"\u{1D4B4}",yscr:"\u{1D4CE}",YUcy:"\u042E",yucy:"\u044E",Yuml:"\u0178",yuml:"\xFF",Zacute:"\u0179",zacute:"\u017A",Zcaron:"\u017D",zcaron:"\u017E",Zcy:"\u0417",zcy:"\u0437",Zdot:"\u017B",zdot:"\u017C",zeetrf:"\u2128",ZeroWidthSpace:"\u200B",Zeta:"\u0396",zeta:"\u03B6",Zfr:"\u2128",zfr:"\u{1D537}",ZHcy:"\u0416",zhcy:"\u0436",zigrarr:"\u21DD",Zopf:"\u2124",zopf:"\u{1D56B}",Zscr:"\u{1D4B5}",zscr:"\u{1D4CF}",zwj:"\u200D",zwnj:"\u200C"});Ro.entityMap=Ro.HTML_ENTITIES});var Cy=y(np=>{var Lo=Xi().NAMESPACE,rp=Xi().tagNamePattern,ta=0,Bn=1,ra=2,Oo=3,na=4,ia=5,xo=6,Sl=7;function aa(e,t){this.message=e,this.locator=t,Error.captureStackTrace&&Error.captureStackTrace(this,aa)}aa.prototype=new Error;aa.prototype.name=aa.name;function wy(){}wy.prototype={parse:function(e,t,r){var n=this.domBuilder;n.startDocument(),TF(t,t={}),NF(e,t,r,n,this.errorHandler),n.endDocument()}};function NF(e,t,r,n,i){function a(X){if(X>65535){X-=65536;var me=55296+(X>>10),Re=56320+(X&1023);return String.fromCharCode(me,Re)}else return String.fromCharCode(X)}function o(X){var me=X.slice(1,-1);return Object.hasOwnProperty.call(r,me)?r[me]:me.charAt(0)==="#"?a(parseInt(me.substr(1).replace("x","0x"))):(i.error("entity not found:"+X),X)}function s(X){if(X>h){var me=e.substring(h,X).replace(/&#?\w+;/g,o);p&&l(h),n.characters(me,0,X-h),h=X}}function l(X,me){for(;X>=c&&(me=d.exec(e));)u=me.index,c=u+me[0].length,p.lineNumber++;p.columnNumber=X-u+1}for(var u=0,c=0,d=/.*(?:\r\n?|\n)|.*$/g,p=n.locator,f=[{currentNSMap:t}],m={},h=0;;){try{var v=e.indexOf("<",h);if(v<0){if(!e.substr(h).match(/^\s*$/)){var w=n.doc,C=w.createTextNode(e.substr(h));w.appendChild(C),n.currentElement=C}return}switch(v>h&&s(v),e.charAt(v+1)){case"/":var $=e.indexOf(">",v+3),E=e.substring(v+2,$).replace(/^([\s\S]*?[^ \t\n\r])?[ \t\n\r]*$/,"$1"),D=f.pop();$<0?(E=e.substring(v+2).replace(/[\s<].*/,""),i.error("end tag name: "+E+" is not complete:"+D.tagName),$=v+1+E.length):E.match(/\s</)?(E=E.replace(/[\s<].*/,""),i.error("end tag name: "+E+" maybe not complete"),$=v+1+E.length):/[ \t\n\r]/.test(E)&&rp.test(E.split(/[ \t\n\r]/)[0])&&i.error('end tag name is followed by whitespace and trailing content: "'+E+'"');var O=D.localNSMap,x=D.tagName==E,F=x||D.tagName&&D.tagName.toLowerCase()==E.toLowerCase();if(F){if(n.endElement(D.uri,D.localName,E),O)for(var M in O)Object.prototype.hasOwnProperty.call(O,M)&&n.endPrefixMapping(M);x||i.fatalError("end tag name: "+E+" is not match the current start tagName:"+D.tagName)}else f.push(D);$++;break;case"?":p&&l(v),$=RF(e,v,n);break;case"!":p&&l(v),$=PF(e,v,n,i);break;default:p&&l(v);var P=new Ay,q=f[f.length-1].currentNSMap,$=DF(e,v,P,q,o,i),qe=P.length;if(!P.closed&&_F(e,$,P.tagName,m)&&(P.closed=!0,r.nbsp||i.warning("unclosed xml attribute")),p&&qe){for(var Nt=yy(p,{}),ke=0;ke<qe;ke++){var He=P[ke];l(He.offset),He.locator=yy(p,{})}n.locator=Nt,by(P,n,q)&&f.push(P),n.locator=p}else by(P,n,q)&&f.push(P);Lo.isHTML(P.uri)&&!P.closed?$=IF(e,$,P.tagName,o,n):$++}}catch(X){if(X instanceof aa)throw X;i.error("element parse error: "+X),$=-1}$>h?h=$:s(Math.max(v,h)+1)}}function yy(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}function DF(e,t,r,n,i,a){function o(f,m,h){r.attributeNames.hasOwnProperty(f)&&a.fatalError("Attribute "+f+" redefined"),r.addValue(f,m.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,i),h)}for(var s,l,u=++t,c=ta;;){var d=e.charAt(u);if(c===ta&&d==="<")throw new Error("unexpected < in tag name: "+e.slice(t,u));switch(d){case"=":if(c===Bn)s=e.slice(t,u),c=Oo;else if(c===ra)c=Oo;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(c===Oo||c===Bn)if(c===Bn&&(a.warning('attribute value must after "="'),s=e.slice(t,u)),t=u+1,u=e.indexOf(d,t),u>0)l=e.slice(t,u),o(s,l,t-1),c=ia;else throw new Error("attribute value no end '"+d+"' match");else if(c==na)l=e.slice(t,u),o(s,l,t),a.warning('attribute "'+s+'" missed start quot('+d+")!!"),t=u+1,c=ia;else throw new Error('attribute value must after "="');break;case"/":switch(c){case ta:r.setTagName(e.slice(t,u));case ia:case xo:case Sl:c=Sl,r.closed=!0;case na:case Bn:break;case ra:r.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return a.error("unexpected end of input"),c==ta&&r.setTagName(e.slice(t,u)),u;case">":switch(c){case ta:r.setTagName(e.slice(t,u));case ia:case xo:case Sl:break;case na:case Bn:l=e.slice(t,u),l.slice(-1)==="/"&&(r.closed=!0,l=l.slice(0,-1));case ra:c===ra&&(l=s),c==na?(a.warning('attribute "'+l+'" missed quot(")!'),o(s,l,t)):((!Lo.isHTML(n[""])||!l.match(/^(?:disabled|checked|selected)$/i))&&a.warning('attribute "'+l+'" missed value!! "'+l+'" instead!!'),o(l,l,t));break;case Oo:throw new Error("attribute value missed!!")}return u;case"\x80":d=" ";default:if(d<=" ")switch(c){case ta:r.setTagName(e.slice(t,u)),c=xo;break;case Bn:s=e.slice(t,u),c=ra;break;case na:var l=e.slice(t,u);a.warning('attribute "'+l+'" missed quot(")!!'),o(s,l,t);case ia:c=xo;break}else switch(c){case ra:var p=r.tagName;(!Lo.isHTML(n[""])||!s.match(/^(?:disabled|checked|selected)$/i))&&a.warning('attribute "'+s+'" missed value!! "'+s+'" instead2!!'),o(s,s,t),t=u,c=Bn;break;case ia:a.warning('attribute space is required"'+s+'"!!');case xo:c=Bn,t=u;break;case Oo:c=na,t=u;break;case Sl:throw new Error("elements closed character '/' and '>' must be connected to")}}u++}}function by(e,t,r){for(var n=e.tagName,i=null,d=e.length;d--;){var a=e[d],o=a.qName,s=a.value,p=o.indexOf(":");if(p>0)var l=a.prefix=o.slice(0,p),u=o.slice(p+1),c=l==="xmlns"&&u;else u=o,l=null,c=o==="xmlns"&&"";a.localName=u,c!==!1&&(i==null&&(i={},r=Object.create(r)),r[c]=i[c]=s,a.uri=Lo.XMLNS,t.startPrefixMapping(c,s))}for(var d=e.length;d--;){a=e[d];var l=a.prefix;l&&(l==="xml"&&(a.uri=Lo.XML),l!=="xmlns"&&(a.uri=r[l||""]))}var p=n.indexOf(":");p>0?(l=e.prefix=n.slice(0,p),u=e.localName=n.slice(p+1)):(l=null,u=e.localName=n);var f=e.uri=r[l||""];if(t.startElement(f,u,n,e),e.closed){if(t.endElement(f,u,n),i)for(l in i)Object.prototype.hasOwnProperty.call(i,l)&&t.endPrefixMapping(l)}else return e.currentNSMap=r,e.localNSMap=i,!0}function IF(e,t,r,n,i){if(/^(?:script|textarea)$/i.test(r)){var a=e.indexOf("</"+r+">",t),o=e.substring(t+1,a);if(/[&<]/.test(o))return/^script$/i.test(r)?(i.characters(o,0,o.length),a):(o=o.replace(/&#?\w+;/g,n),i.characters(o,0,o.length),a)}return t+1}function _F(e,t,r,n){var i=n[r];return i==null&&(i=e.lastIndexOf("</"+r+">"),i<t&&(i=e.lastIndexOf("</"+r)),n[r]=i),i<t}function TF(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function PF(e,t,r,n){var i=e.charAt(t+2);switch(i){case"-":if(e.charAt(t+3)==="-"){var a=e.indexOf("-->",t+4);return a>t?(r.comment(e,t+4,a-t-4),a+3):(n.error("Unclosed comment"),-1)}else return-1;default:if(e.substr(t+3,6)=="CDATA["){var a=e.indexOf("]]>",t+9);return r.startCDATA(),r.characters(e,t+9,a-t-9),r.endCDATA(),a+3}var o=OF(e,t),s=o.length;if(s>1&&/!doctype/i.test(o[0][0])){var l=o[1][0],u=!1,c=!1;s>3&&(/^public$/i.test(o[2][0])?(u=o[3][0],c=s>4&&o[4][0]):/^system$/i.test(o[2][0])&&(c=o[3][0]));var d=o[s-1];return r.startDTD(l,u,c),r.endDTD(),d.index+d[0].length}}return-1}function RF(e,t,r){var n=e.indexOf("?>",t);if(n){var i=e.substring(t,n).match(/^<\?(\S*)\s*([\s\S]*?)$/);if(i){var a=i[0].length;return r.processingInstruction(i[1],i[2]),n+2}else return-1}return-1}function Ay(){this.attributeNames={}}Ay.prototype={setTagName:function(e){if(!rp.test(e))throw new Error("invalid tagName:"+e);this.tagName=e},addValue:function(e,t,r){if(!rp.test(e))throw new Error("invalid attribute:"+e);this.attributeNames[e]=this.length,this[this.length++]={qName:e,value:t,offset:r}},length:0,getLocalName:function(e){return this[e].localName},getLocator:function(e){return this[e].locator},getQName:function(e){return this[e].qName},getURI:function(e){return this[e].uri},getValue:function(e){return this[e].value}};function OF(e,t){var r,n=[],i=/'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;for(i.lastIndex=t,i.exec(e);r=i.exec(e);)if(n.push(r),r[1])return n}np.XMLReader=wy;np.ParseError=aa});var Ty=y(Dl=>{var xF=Xi(),LF=tp(),Ey=vy(),Dy=Cy(),FF=LF.DOMImplementation,Sy=xF.NAMESPACE,kF=Dy.ParseError,MF=Dy.XMLReader;function Iy(e){return e.replace(/\r[\n\u0085]/g,``).replace(/[\r\u0085\u2028]/g,`-`)}function wv(e){this.options=e||{locator:{}}}wv.prototype.parseFromString=function(e,t){var r=this.options,n=new UF,i=r.domBuilder||new yo,a=r.errorHandler,o=r.locator,s=r.xmlns||{},l=/\/x?html?$/.test(t),u=l?hv.HTML_ENTITIES:hv.XML_ENTITIES;o&&i.setDocumentLocator(o),n.errorHandler=BF(a,i,o),n.domBuilder=r.domBuilder||i,l&&(s[""]=gv.HTML),s.xml=s.xml||gv.XML;var c=r.normalizeLineEndings||bv;return e&&typeof e=="string"?n.parse(c(e),s,u):n.errorHandler.error("invalid doc source"),i.doc};function BF(e,t,r){if(!e){if(t instanceof yo)return t;e=t}var n={},i=e instanceof Function;r=r||{};function a(o){var s=e[o];!s&&i&&(s=e.length==2?function(l){e(o,l)}:e),n[o]=s&&function(l){s("[xmldom "+o+"] "+l+vd(r))}||function(){}}return a("warning"),a("error"),a("fatalError"),n}function yo(){this.cdata=!1}function zi(e,t){t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber}yo.prototype={startDocument:function(){this.doc=new kF().createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(e,t,r,n){var i=this.doc,a=i.createElementNS(e,r||t),o=n.length;el(this,a),this.currentElement=a,this.locator&&zi(this.locator,a);for(var s=0;s<o;s++){var e=n.getURI(s),l=n.getValue(s),r=n.getQName(s),u=i.createAttributeNS(e,r);this.locator&&zi(n.getLocator(s),u),u.value=u.nodeValue=l,a.setAttributeNode(u)}},endElement:function(e,t,r){var n=this.currentElement,i=n.tagName;this.currentElement=n.parentNode},startPrefixMapping:function(e,t){},endPrefixMapping:function(e){},processingInstruction:function(e,t){var r=this.doc.createProcessingInstruction(e,t);this.locator&&zi(this.locator,r),el(this,r)},ignorableWhitespace:function(e,t,r){},characters:function(e,t,r){if(e=vv.apply(this,arguments),e){if(this.cdata)var n=this.doc.createCDATASection(e);else var n=this.doc.createTextNode(e);this.currentElement?this.currentElement.appendChild(n):/^\s*$/.test(e)&&this.doc.appendChild(n),this.locator&&zi(this.locator,n)}},skippedEntity:function(e){},endDocument:function(){this.doc.normalize()},setDocumentLocator:function(e){(this.locator=e)&&(e.lineNumber=0)},comment:function(e,t,r){e=vv.apply(this,arguments);var n=this.doc.createComment(e);this.locator&&zi(this.locator,n),el(this,n)},startCDATA:function(){this.cdata=!0},endCDATA:function(){this.cdata=!1},startDTD:function(e,t,r){var n=this.doc.implementation;if(n&&n.createDocumentType){var i=n.createDocumentType(e,t,r);this.locator&&zi(this.locator,i),el(this,i),this.doc.doctype=i}},warning:function(e){console.warn("[xmldom warning] "+e,vd(this.locator))},error:function(e){console.error("[xmldom error] "+e,vd(this.locator))},fatalError:function(e){throw new MF(e,this.locator)}};function vd(e){if(e)return`-@`+(e.systemId||"")+"#[line:"+e.lineNumber+",col:"+e.columnNumber+"]"}function vv(e,t,r){return typeof e=="string"?e.substr(t,r):e.length>=t+r||t?new java.lang.String(e,t,r)+"":e}"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(e){yo.prototype[e]=function(){return null}});function el(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}tl.__DOMHandler=yo;tl.normalizeLineEndings=bv;tl.DOMParser=wv});var yd=v(rl=>{var Cv=md();rl.DOMImplementation=Cv.DOMImplementation;rl.XMLSerializer=Cv.XMLSerializer;rl.DOMParser=Av().DOMParser});var Tn=v(nl=>{"use strict";Object.defineProperty(nl,"__esModule",{value:!0});nl.installDomShim=void 0;var Ev=yd(),Sv=!1,$F={ELEMENT_NODE:1,ATTRIBUTE_NODE:2,TEXT_NODE:3,CDATA_SECTION_NODE:4,ENTITY_REFERENCE_NODE:5,ENTITY_NODE:6,PROCESSING_INSTRUCTION_NODE:7,COMMENT_NODE:8,DOCUMENT_NODE:9,DOCUMENT_TYPE_NODE:10,DOCUMENT_FRAGMENT_NODE:11,NOTATION_NODE:12};function qF(){if(Sv)return;let e=globalThis;typeof e.DOMParser>"u"&&(e.DOMParser=Ev.DOMParser),typeof e.XMLSerializer>"u"&&(e.XMLSerializer=Ev.XMLSerializer),typeof e.Node>"u"&&(e.Node=$F),Sv=!0}nl.installDomShim=qF});var ri=v(_e=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});_e.projectElementBag=_e.serializeNode=_e.domEngine=_e.nodeLikeFromDom=_e.parseXmlRoot=_e.EMPTY_FORM_SENTINEL=_e.TEXT_SENTINEL=void 0;var VF=In(),bo=te(),GF=Tn();_e.TEXT_SENTINEL="#text";_e.EMPTY_FORM_SENTINEL="#empty";var al=new WeakSet;function zF(e,t){(0,GF.installDomShim)();let r=e&&e.trim()!==""?e:t,i=new DOMParser().parseFromString(r,"text/xml").documentElement;if(!i)throw new bo.InvalidArgumentError("XML source has no root element (empty or malformed input)");return HF(i),jF(i),KF(i,r),i}_e.parseXmlRoot=zF;var WF=new Set([1,3]);function HF(e){let t=[e];for(;t.length>0;){let n=t.pop().childNodes;for(let i=0;i<n.length;i+=1){let a=n[i];if(!WF.has(a.nodeType))throw new bo.InvalidArgumentError(`Unsupported XML node type ${a.nodeType} (CDATA / comment / processing-instruction) is outside the hybrid projection's lossless grammar and cannot be round-tripped`);a.nodeType===1&&t.push(a)}}}function jF(e){var t,r;let n=(t=e.ownerDocument)!==null&&t!==void 0?t:e.parentNode;if(!n)return;let i=n.childNodes;for(let a=0;a<i.length;a+=1){let o=i[a];if(o!==e&&!(o.nodeType===3&&((r=o.nodeValue)!==null&&r!==void 0?r:"").trim()===""))throw new bo.InvalidArgumentError(`Unsupported document-level XML node (type ${o.nodeType}: declaration / comment / processing-instruction outside the root element) cannot be round-tripped`)}}function JF(e){let t=[],r=/<([^>]*)>/g;for(let n=r.exec(e);n!==null;n=r.exec(e)){let i=n[1];i.startsWith("/")||i.startsWith("?")||i.startsWith("!")||t.push(i.endsWith("/"))}return t}function QF(e){let t=[],r=[e];for(;r.length>0;){let n=r.pop();t.push(n);let i=n.childNodes;for(let a=i.length-1;a>=0;a-=1){let o=i[a];o.nodeType===1&&r.push(o)}}return t}function Dv(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1){let n=t[r].nodeType;if(n===1||n===3)return!0}return!1}function KF(e,t){let r=JF(t),n=QF(e),i=Math.min(r.length,n.length);for(let a=0;a<i;a+=1){if(r[a])continue;let o=n[a];Dv(o)||al.add(o)}}function bd(e){let t=e.nodeType===3;return{getNodeName:()=>t?_e.TEXT_SENTINEL:e.tagName,getAllProperties:()=>{var r;if(t)return[{key:_e.TEXT_SENTINEL,value:(r=e.nodeValue)!==null&&r!==void 0?r:""}];let n=e.attributes,i=[];for(let a=0;a<n.length;a+=1)i.push({key:n[a].name,value:n[a].value});return al.has(e)&&!Dv(e)&&i.push({key:_e.EMPTY_FORM_SENTINEL,value:"1"}),i},getAllChildren:()=>{if(t)return[];let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let a=n[i];(a.nodeType===1||a.nodeType===3)&&r.push(bd(a))}return r}}}_e.nodeLikeFromDom=bd;function XF(e){return{make:t=>t===_e.TEXT_SENTINEL?e.createTextNode(""):e.createElement(t),setProp:(t,r,n)=>{t.nodeType===3?t.nodeValue=n:r===_e.EMPTY_FORM_SENTINEL?al.add(t):t.setAttribute(r,n)},addChild:(t,r)=>{t.appendChild(r)}}}_e.domEngine=XF;function Iv(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r<=31&&r!==9&&r!==10&&r!==13||r===65534||r===65535)throw il(r);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))throw il(r);t+=1;continue}if(r>=56320&&r<=57343)throw il(r)}}function il(e){let t=e.toString(16).toUpperCase().padStart(4,"0");return new bo.InvalidArgumentError(`Value contains U+${t}, a character not permitted in XML 1.0 (control char / lone surrogate / non-character); it cannot be serialized losslessly`)}function YF(e){return Iv(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/\r/g,"
").replace(/\n/g,"
").replace(/\t/g,"	")}function ZF(e){return Iv(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function ex(e){return _v(e,0)}_e.serializeNode=ex;var Nv=512;function _v(e,t){var r;if(t>Nv)throw new bo.InvalidArgumentError(`XML nesting exceeds the maximum supported depth of ${Nv}`);if(e.nodeType===3)return ZF((r=e.nodeValue)!==null&&r!==void 0?r:"");let n=e,i="<"+n.tagName,a=n.attributes;for(let l=0;l<a.length;l+=1)i+=" "+a[l].name+'="'+YF(a[l].value)+'"';let o=[],s=n.childNodes;for(let l=0;l<s.length;l+=1){let u=s[l];(u.nodeType===1||u.nodeType===3)&&o.push(u)}if(o.length===0)return al.has(n)?i+"></"+n.tagName+">":i+" />";i+=">";for(let l of o)i+=_v(l,t+1);return i+"</"+n.tagName+">"}function tx(e){let t=bd(e);return{a:t.getAllProperties().map(r=>[r.key,r.value]),c:t.getAllChildren().map((r,n)=>({i:n,node:(0,VF.rawFromNode)(r)}))}}_e.projectElementBag=tx});var Cd=v(Pn=>{"use strict";Object.defineProperty(Pn,"__esModule",{value:!0});Pn.getFormSecurityRoles=Pn.setFormSecurityRoles=Pn.formApi=void 0;var rx=qt(),he=be(),Gt=ae(),Wi=te(),wd=ri(),nx="formid,formxml,name,type,objecttypecode,formpresentation,formactivationstate,uniquename,description,versionnumber",ix="formid,name,type,objecttypecode",ax=2,ox={Main:ax,QuickView:6,QuickCreate:7,Card:11};Pn.formApi={async get(e,t){let n=`/systemforms(${(0,Gt.normalizeGuid)(t,"id")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Gt.odataQuery)([["$select",nx]]),i=(0,he.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,he.readEtag)(i)}},async list(e,t){var r;let n=!((r=t?.formTypes)===null||r===void 0)&&r.length?t.formTypes:["Main"],i=[...new Set(n.map(u=>ox[u]))],o=[i.length===1?`type eq ${i[0]}`:`(${i.map(u=>`type eq ${u}`).join(" or ")})`];t?.entityLogicalName&&o.push(`objecttypecode eq '${(0,Gt.odataLiteral)(t.entityLogicalName)}'`);let s=`/systemforms${(0,Gt.odataQuery)([["$select",ix],["$filter",o.join(" and ")]])}`;return(await(0,rx.collectPages)(e,s,"listArtifacts('form')")).map(u=>{var c,d;return{type:"form",id:(c=u.formid)!==null&&c!==void 0?c:"",name:(d=u.name)!==null&&d!==void 0?d:"",entityLogicalName:u.objecttypecode,isDirty:!1}})},async create(e,t,r){let n=(0,he.echoWrite)("formid"),i=`/systemforms${n.query}`,a=(0,he.ensureSuccess)(await e.post(i,(0,he.withClientMintedId)(t,"formid",r),n.options),e.apiUrl(i));return{id:(0,he.resolveCreatedId)(a,"formid","form",r),etag:(0,he.readEtag)(a)}},async update(e,t,r,n){let i=(0,Gt.normalizeGuid)(t,"id");await Ov(e,i,Pv(i),n);let a=await Tv(e,i),o=(0,he.echoWrite)("formid",{"If-Match":(0,he.requireEtag)(a,"form",i)}),s=`/systemforms(${i})${o.query}`;return(0,he.ensureSuccess)(await e.patch(s,r,o.options),e.apiUrl(s)),{id:i,etag:await lx(e,i)}},delete(e,t){return(0,he.deleteRecord)(e,"systemforms",t)}};var Ad="DisplayConditions";async function sx(e,t,r){var n,i,a,o;if(r.everyone&&r.roleIds&&r.roleIds.length>0)throw new Wi.InvalidArgumentError("setFormSecurityRoles: `everyone` and `roleIds` are mutually exclusive \u2014 the platform models <Everyone /> as a replacement for the <Role> list, not an addition to it.");let s=(0,Gt.normalizeGuid)(t,"formId"),l=`/systemforms(${s})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Gt.odataQuery)([["$select","formid,formxml"]]),u=(0,he.ensureSuccess)(await e.get(l),e.apiUrl(l)),c=(0,he.readEtag)(u),d=u.body,p=d?.formxml;if(!p)throw new Wi.InvalidArgumentError(`form '${s}' returned no formxml, so its roles cannot be set`);let f=(0,wd.parseXmlRoot)(p,"<form/>"),m=f.ownerDocument;if(!m)throw new Wi.InvalidArgumentError(`form '${s}' produced no owner document`);let g=Rv(f,Ad),y=g?.hasAttribute("Order")&&(n=g.getAttribute("Order"))!==null&&n!==void 0?n:void 0,A=g?.getAttribute("FallbackForm")||void 0;g&&f.removeChild(g);let D=!!r.everyone||((a=(i=r.roleIds)===null||i===void 0?void 0:i.length)!==null&&a!==void 0?a:0)>0;if(!D&&(r.order!==void 0||r.fallbackForm!==void 0)){if(!g)throw new Wi.InvalidArgumentError("setFormSecurityRoles: `order`/`fallbackForm` were supplied without `roleIds` or `everyone`, but this form has no <DisplayConditions> to attach them to. Pass the roles as well.");r.order!==void 0&&g.setAttribute("Order",String(r.order)),r.fallbackForm!==void 0&&g.setAttribute("FallbackForm",String(r.fallbackForm)),f.appendChild(g)}else if(D){let L=m.createElement(Ad),k=r.order!==void 0?String(r.order):y;k!==void 0&&L.setAttribute("Order",k);let M=r.fallbackForm!==void 0?String(r.fallbackForm):A??"false";if(L.setAttribute("FallbackForm",M),r.everyone)L.appendChild(m.createElement("Everyone"));else for(let G of(o=r.roleIds)!==null&&o!==void 0?o:[]){let V=m.createElement("Role");V.setAttribute("Id",`{${(0,Gt.normalizeGuid)(G,"roleId")}}`),L.appendChild(V)}f.appendChild(L)}let _=(0,wd.serializeNode)(f);await Ov(e,s,l,c);let q=await Tv(e,s),B=`/systemforms(${s})`;(0,he.ensureSuccess)(await e.patch(B,{formxml:_},{headers:{"Content-Type":"application/json","If-Match":(0,he.requireEtag)(q,"form",s)}}),e.apiUrl(B))}Pn.setFormSecurityRoles=sx;async function Tv(e,t){let r=`/systemforms(${t})${(0,Gt.odataQuery)([["$select","formid"]])}`;return(0,he.readEtag)((0,he.ensureSuccess)(await e.get(r),e.apiUrl(r)))}function Pv(e){return`/systemforms(${e})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Gt.odataQuery)([["$select","formid"]])}async function lx(e,t){let r=Pv(t);return(0,he.readEtag)((0,he.ensureSuccess)(await e.get(r),e.apiUrl(r)))}async function Ov(e,t,r,n){(0,he.requireEtag)(n,"form",t);let i=(0,he.readEtag)((0,he.ensureSuccess)(await e.get(r),e.apiUrl(r)));if(i===null)throw new Wi.SdkError(he.VERSION_CONFLICT_CODE,`Refusing to write form '${t}': its current version could not be read, so the write could not be verified as conditional and would risk silently overwriting a concurrent edit.`);if(i!==n)throw new Wi.SdkError(he.VERSION_CONFLICT_CODE,`Version conflict writing form '${t}': its formxml changed on the server since it was read (held ${n}, server ${i}). Re-fetch the form and re-apply the change.`)}function Rv(e,t){let r=e.childNodes;for(let n=0;n<r.length;n+=1){let i=r[n];if(i.nodeType===1&&i.tagName===t)return i}}async function ux(e,t){var r,n;let a=`/systemforms(${(0,Gt.normalizeGuid)(t,"formId")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Gt.odataQuery)([["$select","formid,formxml"]]),s=(r=(0,he.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||r===void 0?void 0:r.formxml;if(!s)return;let l=(0,wd.parseXmlRoot)(s,"<form/>"),u=Rv(l,Ad);if(!u)return;let c=[],d=!1,p=u.childNodes;for(let m=0;m<p.length;m+=1){let g=p[m];if(g.nodeType!==1)continue;let y=g;if(y.tagName==="Everyone")d=!0;else if(y.tagName==="Role"){let A=(n=y.getAttribute("Id"))!==null&&n!==void 0?n:"";A&&c.push(A.replace(/[{}]/g,"").toLowerCase())}}let f=u.getAttribute("Order");return{...d?{everyone:!0}:{},...c.length>0?{roleIds:c}:{},fallbackForm:u.getAttribute("FallbackForm")==="true",...f!==null&&f!==""?{order:Number(f)}:{}}}Pn.getFormSecurityRoles=ux});var ll=v(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.disassociateRecords=Se.associateRecords=Se.createRecordsBulk=Se.upsertRecord=Se.queryAllRecords=Se.queryRecords=Se.getRecord=Se.deleteRecord=Se.updateRecord=Se.createRecord=void 0;var cx=qt(),sr=be(),rt=ae(),ol=te(),Dr=qs();function sl(e){let t=e,r=!1,n={};for(let i of Object.keys(t)){let a=t[i];Array.isArray(a)&&a.every(o=>typeof o=="number")?(n[i]=a.join(","),r=!0):n[i]=a}return r?n:e}async function dx(e,t,r){let i=`/${await(0,Dr.resolveEntitySetName)(e,t)}`,a=(0,sr.ensureSuccess)(await e.post(i,sl(r)),e.apiUrl(i)),o=(0,sr.readCreatedId)(a,`${t}id`);if(!o)throw new ol.InvalidArgumentError(`Dataverse did not return an id for the created '${t}' row`);return{id:o,entityType:t}}Se.createRecord=dx;async function px(e,t,r,n){let i=(0,rt.normalizeGuid)(r,"id"),o=`/${await(0,Dr.resolveEntitySetName)(e,t)}(${i})`;(0,sr.ensureSuccess)(await e.patch(o,sl(n)),e.apiUrl(o))}Se.updateRecord=px;async function fx(e,t,r){let n=(0,rt.normalizeGuid)(r,"id"),a=`/${await(0,Dr.resolveEntitySetName)(e,t)}(${n})`;(0,sr.ensureSuccess)(await e.delete(a),e.apiUrl(a))}Se.deleteRecord=fx;async function mx(e,t,r,n){var i;let a=(0,rt.normalizeGuid)(r,"id"),o=await(0,Dr.resolveEntitySetName)(e,t),s=(0,rt.odataQuery)([["$select",n&&n.length>0?n.join(","):void 0]]),l=`/${o}(${a})${s}`;return(i=(0,sr.ensureSuccess)(await e.get(l),e.apiUrl(l)).body)!==null&&i!==void 0?i:{}}Se.getRecord=mx;function hx(e){return e?.fetchXml?(0,rt.odataQuery)([["fetchXml",e.fetchXml]]):(0,rt.odataQuery)([["$select",e?.select&&e.select.length>0?e.select.join(","):void 0],["$filter",e?.filter],["$orderby",e?.orderBy],["$expand",e?.expand],["$top",e?.top]])}async function Fv(e,t,r){var n,i;if(r?.paginate){if(r.top!==void 0)throw new ol.InvalidArgumentError("queryRecords: `paginate` cannot be combined with `top` \u2014 Dataverse honors $top as a hard cap and omits @odata.nextLink, so the result would be silently capped at one page.");if(r.fetchXml)throw new ol.InvalidArgumentError("queryRecords: `paginate` is not supported with `fetchXml` \u2014 FetchXML paging uses a paging cookie (page / fetchxmlpagingcookie), not @odata.nextLink. Page the FetchXML manually, or use an OData query.")}let o=`/${await(0,Dr.resolveEntitySetName)(e,t)}${hx(r)}`;return r?.paginate?(0,cx.collectPages)(e,o,"queryRecords"):(i=(n=(0,sr.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]}Se.queryRecords=Fv;async function gx(e,t,r){return Fv(e,t,{...r,paginate:!0})}Se.queryAllRecords=gx;function vx(e){if("id"in e)return`(${(0,rt.normalizeGuid)(e.id,"id")})`;let t=typeof e.value=="string"?`'${(0,rt.odataPathLiteral)(e.value)}'`:e.value;return`(${(0,rt.assertODataName)(e.key,"alternate key name")}=${t})`}async function yx(e,t,r,n){let i=vx(r),o=`/${await(0,Dr.resolveEntitySetName)(e,t)}${i}`,s=(0,sr.ensureSuccess)(await e.patch(o,sl(n)),e.apiUrl(o)),l=s.status===201,u=(0,sr.readCreatedId)(s,`${t}id`);return{id:u??("id"in r?(0,rt.normalizeGuid)(r.id,"id"):""),created:l}}Se.upsertRecord=yx;async function bx(e,t,r){var n,i;if(r.length===0)return[];let a=await(0,Dr.resolveEntitySetName)(e,t),o=r.map(c=>({"@odata.type":`Microsoft.Dynamics.CRM.${t}`,...sl(c)})),s=`/${a}/Microsoft.Dynamics.CRM.CreateMultiple`,u=(i=(n=(0,sr.ensureSuccess)(await e.post(s,{Targets:o}),e.apiUrl(s)).body)===null||n===void 0?void 0:n.Ids)!==null&&i!==void 0?i:[];if(u.length!==r.length)throw new ol.InvalidArgumentError(`CreateMultiple on '${t}' returned ${u.length} id(s) for ${r.length} row(s)`);return u}Se.createRecordsBulk=bx;async function wx(e,t,r,n){let i=(0,rt.normalizeGuid)(r,"id"),a=(0,rt.normalizeGuid)(n.targetId,"targetId"),o=await(0,Dr.resolveEntitySetName)(e,t),s=await(0,Dr.resolveEntitySetName)(e,n.targetEntity),l=(0,rt.assertODataName)(n.relationshipName,"relationshipName"),u=`/${o}(${i})/${l}/$ref`,c={"@odata.id":e.apiUrl(`/${s}(${a})`)};(0,sr.ensureSuccess)(await e.post(u,c),e.apiUrl(u))}Se.associateRecords=wx;async function Ax(e,t,r,n,i){let a=(0,rt.normalizeGuid)(r,"id"),o=(0,rt.normalizeGuid)(i,"targetId"),s=await(0,Dr.resolveEntitySetName)(e,t),l=(0,rt.assertODataName)(n,"relationshipName"),u=`/${s}(${a})/${l}(${o})/$ref`;(0,sr.ensureSuccess)(await e.delete(u),e.apiUrl(u))}Se.disassociateRecords=Ax});var lr=v(Ge=>{"use strict";Object.defineProperty(Ge,"__esModule",{value:!0});Ge.publishBoundEntity=Ge.boundEntityPublishScope=Ge.publishGenPageById=Ge.publishDashboardById=Ge.publishWebResourceById=Ge.publishEntity=Ge.publishAppModule=Ge.publishXml=void 0;var Cx=be(),wo=ae(),xv="/PublishXml";async function Hi(e,t){(0,Cx.ensureSuccess)(await e.post(xv,{ParameterXml:t}),e.apiUrl(xv))}Ge.publishXml=Hi;function Ex(e,t){return Hi(e,`<importexportxml><appmodules><appmodule>${(0,wo.xmlText)(t)}</appmodule></appmodules></importexportxml>`)}Ge.publishAppModule=Ex;function Lv(e,t){return Hi(e,`<importexportxml><entities><entity>${(0,wo.xmlText)(t)}</entity></entities></importexportxml>`)}Ge.publishEntity=Lv;function Sx(e,t){return Hi(e,`<importexportxml><webresources><webresource>${(0,wo.xmlText)(t)}</webresource></webresources></importexportxml>`)}Ge.publishWebResourceById=Sx;function Nx(e,t){return Hi(e,`<importexportxml><dashboards><dashboard>${(0,wo.xmlText)(t)}</dashboard></dashboards></importexportxml>`)}Ge.publishDashboardById=Nx;function Dx(e,t){return Hi(e,`<importexportxml><uxagentprojects><uxagentproject>${(0,wo.xmlText)(t)}</uxagentproject></uxagentprojects></importexportxml>`)}Ge.publishGenPageById=Dx;function Ix(e){let t=e?.entityLogicalName;return t?{envelope:"entity",entityLogicalName:t,blastRadiusWarning:"ENTITY_ENVELOPE_ALSO_SHIPS_UNRELATED_UNPUBLISHED_CHANGES"}:{envelope:"entity"}}Ge.boundEntityPublishScope=Ix;function _x(e,t){let r=t?.entityLogicalName;return r?Lv(e,r):Promise.resolve()}Ge.publishBoundEntity=_x});var Sd=v(On=>{"use strict";Object.defineProperty(On,"__esModule",{value:!0});On.base64ToBytes=On.bytesToBase64=On.utf8ToBase64=void 0;var kv=32768,St="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Ed(){return globalThis}function Tx(e){let t=[];for(let r=0;r<e.length;r+=1){let n=e.charCodeAt(r);if(n>=55296&&n<=56319){let i=r+1<e.length?e.charCodeAt(r+1):0;i>=56320&&i<=57343?(n=(n-55296<<10)+(i-56320)+65536,r+=1):n=65533}else n>=56320&&n<=57343&&(n=65533);n<128?t.push(n):n<2048?t.push(192|n>>6,128|n&63):n<65536?t.push(224|n>>12,128|n>>6&63,128|n&63):t.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|n&63)}return Uint8Array.from(t)}function Px(e){let t="";for(let r=0;r<e.length;r+=kv)t+=String.fromCharCode(...e.subarray(r,r+kv));return t}function Ox(e){let t="";for(let r=0;r<e.length;r+=1){let n=String.fromCharCode(e.charCodeAt(r)&255);if(n==="=")break;n==="-"?t+="+":n==="_"?t+="/":St.indexOf(n)>=0&&(t+=n)}for(t.length%4===1&&(t=t.slice(0,-1));t.length%4!==0;)t+="=";return t}function Rx(e){let t="",r=0;for(;r+2<e.length;r+=3){let i=e[r]<<16|e[r+1]<<8|e[r+2];t+=St[i>>18&63]+St[i>>12&63]+St[i>>6&63]+St[i&63]}let n=e.length-r;if(n===1){let i=e[r]<<16;t+=`${St[i>>18&63]}${St[i>>12&63]}==`}else if(n===2){let i=e[r]<<16|e[r+1]<<8,a=St[i>>18&63],o=St[i>>12&63],s=St[i>>6&63];t+=`${a}${o}${s}=`}return t}function Fx(e){let t=e.endsWith("==")?2:e.endsWith("=")?1:0,r=e.length/4*3-t,n=new Uint8Array(r>0?r:0),i=0;for(let a=0;a<e.length;a+=4){let o=St.indexOf(e[a])<<18|St.indexOf(e[a+1])<<12|(e[a+2]==="="?0:St.indexOf(e[a+2]))<<6|(e[a+3]==="="?0:St.indexOf(e[a+3]));i<r&&(n[i++]=o>>16&255),i<r&&(n[i++]=o>>8&255),i<r&&(n[i++]=o&255)}return n}function xx(e){let t=Ed();if(t.Buffer)return t.Buffer.from(e,"utf8").toString("base64");let r=t.TextEncoder;return Mv(r?new r().encode(e):Tx(e))}On.utf8ToBase64=xx;function Mv(e){let t=Ed();return t.Buffer?t.Buffer.from(e).toString("base64"):t.btoa?t.btoa(Px(e)):Rx(e)}On.bytesToBase64=Mv;function Lx(e){let t=Ed();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"base64"));let r=Ox(e);if(t.atob){let n=t.atob(r);return Uint8Array.from(n,i=>i.charCodeAt(0))}return Fx(r)}On.base64ToBytes=Lx});var qv=v(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.deleteWebResource=Ir.getWebResource=Ir.updateWebResource=Ir.createWebResource=void 0;var kx=lr(),Ao=be(),ul=ae(),Mx=Sd(),Uv=te(),Ux={html:1,css:2,js:3,xml:4,png:5,jpg:6,gif:7,xsl:9,ico:10,svg:11,resx:12};function Bv(e){if(e.contentBase64!==void 0)return e.contentBase64;if(e.content!==void 0)return(0,Mx.utf8ToBase64)(e.content)}async function $v(e,t){return(0,kx.publishWebResourceById)(e,t)}async function Bx(e,t){var r;let n=Bv(t);if(n===void 0)throw new Uv.InvalidArgumentError(`web resource '${t.name}' requires content or contentBase64`);let i={name:t.name,displayname:(r=t.displayName)!==null&&r!==void 0?r:t.name,webresourcetype:Ux[t.type],content:n};t.description&&(i.description=t.description);let a=(0,Ao.ensureSuccess)(await e.post("/webresourceset",i),e.apiUrl("/webresourceset")),o=(0,Ao.readCreatedId)(a,"webresourceid");if(!o)throw new Uv.InvalidArgumentError(`Dataverse did not return an id for web resource '${t.name}'`);return t.publish!==!1&&await $v(e,o),{id:o,name:t.name}}Ir.createWebResource=Bx;async function $x(e,t,r){let n=(0,ul.normalizeGuid)(t,"id"),i={},a=Bv(r);a!==void 0&&(i.content=a),r.displayName!==void 0&&(i.displayname=r.displayName),r.description!==void 0&&(i.description=r.description);let o=`/webresourceset(${n})`;(0,Ao.ensureSuccess)(await e.patch(o,i),e.apiUrl(o)),r.publish!==!1&&await $v(e,n)}Ir.updateWebResource=$x;async function qx(e,t){var r;let i=`/webresourceset(${(0,ul.normalizeGuid)(t,"id")})${(0,ul.odataQuery)([["$select","name,displayname,webresourcetype,content,description"]])}`;return(r=(0,Ao.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)!==null&&r!==void 0?r:{}}Ir.getWebResource=qx;async function Vx(e,t){let n=`/webresourceset(${(0,ul.normalizeGuid)(t,"id")})`;(0,Ao.ensureSuccess)(await e.delete(n),e.apiUrl(n))}Ir.deleteWebResource=Vx});var cl=v(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.applyAppSettings=ze.setAppSetting=ze.readAppSettings=ze.resolveSettingDefinitions=ze.APP_SETTING_UNSET=ze.APP_SETTING_OFF=ze.APP_SETTING_ON=ze.HEADER_AND_NAVIGATION_REFRESH=void 0;var ji=be(),Zr=ae();ze.HEADER_AND_NAVIGATION_REFRESH="HeaderAndNavigationRefresh";ze.APP_SETTING_ON="2";ze.APP_SETTING_OFF="1";ze.APP_SETTING_UNSET="0";function zv(e,t){return"/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Zr.odataQuery)([["$select",e],["$filter",t]])}async function Wv(e,t){var r,n;let i=[...new Set(t.filter(Boolean))],a=new Map;if(i.length===0)return a;let o=i.map(c=>`uniquename eq '${(0,Zr.odataLiteral)(c)}'`).join(" or "),s=`/settingdefinitions${(0,Zr.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",o]])}`,u=((n=(r=(0,ji.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[]).filter(Boolean);for(let c of u)c.uniquename&&a.set(c.uniquename,c);return a}ze.resolveSettingDefinitions=Wv;async function Gx(e,t){var r,n,i,a;let o=(0,Zr.normalizeGuid)(t,"App id"),s=zv("appsettingid,value,_settingdefinitionid_value",`_parentappmoduleid_value eq ${o}`),u=((n=(r=(0,ji.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[]).filter(Boolean);if(u.length===0)return[];let c=[...new Set(u.map(p=>p._settingdefinitionid_value).filter(Boolean))],d=new Map;if(c.length>0){let p=c.map(g=>`settingdefinitionid eq ${(0,Zr.normalizeGuid)(g,"Setting definition id")}`).join(" or "),f=`/settingdefinitions${(0,Zr.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",p]])}`,m=(0,ji.ensureSuccess)(await e.get(f),e.apiUrl(f));for(let g of((a=(i=m.body)===null||i===void 0?void 0:i.value)!==null&&a!==void 0?a:[]).filter(Boolean))g.settingdefinitionid&&d.set(g.settingdefinitionid.toLowerCase(),g)}return u.map(p=>{var f,m,g,y,A;let D=d.get(((f=p._settingdefinitionid_value)!==null&&f!==void 0?f:"").toLowerCase());return{id:(m=p.appsettingid)!==null&&m!==void 0?m:"",name:(y=(g=D?.uniquename)!==null&&g!==void 0?g:p._settingdefinitionid_value)!==null&&y!==void 0?y:"",value:(A=p.value)!==null&&A!==void 0?A:"",...D?.displayname?{displayName:D.displayname}:{}}})}ze.readAppSettings=Gx;async function Vv(e,t,r){var n,i,a;let o=zv("appsettingid,value",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${r}`),l=((i=(n=(0,ji.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]).filter(Boolean)[0];return l?.appsettingid?{id:l.appsettingid,value:(a=l.value)!==null&&a!==void 0?a:""}:void 0}async function Hv(e,t,r,n){let i=(0,Zr.normalizeGuid)(t,"App id"),o=(await Wv(e,[r])).get(r),s=o?.settingdefinitionid;if(!s)throw new Error(`App setting '${r}' is not available in this environment: no settingdefinition row has that uniquename. The feature may be version-gated or its solution may not be installed.`);let l=(0,Zr.normalizeGuid)(s,"Setting definition id"),u=await Vv(e,i,l);if(u)return Gv(e,u,n);let c="/appsettings",d={"[email protected]":`/appmodules(${i})`,"[email protected]":`/settingdefinitions(${l})`,value:n},p,f;try{if(p=await e.post(c,d),p.status>=200&&p.status<300)return"created"}catch(g){f=g}let m;try{m=await Vv(e,i,l)}catch{m=void 0}if(m)return Gv(e,m,n);throw p&&(0,ji.ensureSuccess)(p,e.apiUrl(c)),f}ze.setAppSetting=Hv;async function Gv(e,t,r){if(t.value===r)return"unchanged";let n=`/appsettings(${(0,Zr.normalizeGuid)(t.id,"App setting id")})`;return(0,ji.ensureSuccess)(await e.patch(n,{value:r}),e.apiUrl(n)),"updated"}async function zx(e,t,r){var n;let i=[];for(let[a,o]of Object.entries(r??{}))try{await Hv(e,t,a,o)}catch(s){i.push(`App setting '${a}' was not applied: ${(n=s?.message)!==null&&n!==void 0?n:String(s)} The app was created; set it later with setAppSetting().`)}return i}ze.applyAppSettings=zx});var pl=v(dl=>{"use strict";Object.defineProperty(dl,"__esModule",{value:!0});dl.HEADER_NAV_BOOLEAN_RULE=void 0;dl.HEADER_NAV_BOOLEAN_RULE="headerAndNavigationRefresh-must-be-boolean"});var Jv=v(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.deleteSolution=re.importSolution=re.exportSolution=re.removeSolutionComponent=re.addSolutionComponent=re.setSolutionVersion=re.createSolution=re.createPublisher=re.getSolution=re.fetchSolutionComponents=re.SolutionComponentType=void 0;var jv=qt(),ur=be(),Nt=ae(),ni=te();re.SolutionComponentType={SavedQuery:26,Workflow:29,SavedQueryVisualization:59,SystemForm:60,AppModule:80,UxAgentProject:10372};var Wx=[re.SolutionComponentType.SavedQuery,re.SolutionComponentType.Workflow,re.SolutionComponentType.SavedQueryVisualization,re.SolutionComponentType.SystemForm,re.SolutionComponentType.AppModule,re.SolutionComponentType.UxAgentProject];async function Hx(e,t){let r=(0,Nt.normalizeGuid)(t,"solutionId"),n=Wx.map(s=>`msdyn_componenttype eq ${s}`).join(" or "),i=`/msdyn_solutioncomponentsummaries${(0,Nt.odataQuery)([["$select","msdyn_objectid,msdyn_componenttype,msdyn_workflowcategory,msdyn_displayname,msdyn_name"],["$filter",`msdyn_solutionid eq ${r} and (${n})`]])}`,o=(await(0,jv.collectPages)(e,i,"fetchSolutionComponents")).filter(s=>typeof s.msdyn_objectid=="string").map(s=>({objectId:s.msdyn_objectid,componentType:Number(s.msdyn_componenttype),workflowCategory:s.msdyn_workflowcategory==null?void 0:Number(s.msdyn_workflowcategory),displayName:s.msdyn_displayname,name:s.msdyn_name}));return[...o,...await jx(e,r,o)]}re.fetchSolutionComponents=Hx;async function jx(e,t,r){let n=new Set(r.map(s=>s.objectId.toLowerCase())),i=`/solutioncomponents${(0,Nt.odataQuery)([["$select","objectid,componenttype"],["$filter",`_solutionid_value eq ${t} and componenttype eq ${re.SolutionComponentType.UxAgentProject}`]])}`,a=await(0,jv.collectPages)(e,i,"fetchSolutionComponents(draft pages)"),o=[];for(let s of a){let l=typeof s.objectid=="string"?s.objectid:void 0;l&&!n.has(l.toLowerCase())&&(n.add(l.toLowerCase()),o.push({objectId:l,componentType:re.SolutionComponentType.UxAgentProject}))}return o}function Jx(e){let t=e.length===38&&e.startsWith("{")&&e.endsWith("}")?e.slice(1,-1):e;return/^[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}$/.test(t)}async function Qx(e,t){var r,n,i,a,o,s,l,u,c,d;let p=String(t??"").trim();if(!p)throw new ni.InvalidArgumentError("getSolution: a solution unique name or id is required.");let f=Jx(p)?`solutionid eq ${(0,Nt.normalizeGuid)(p,"solutionId")}`:`uniquename eq '${(0,Nt.odataLiteral)(p)}'`,m=`/solutions${(0,Nt.odataQuery)([["$select","solutionid,uniquename,friendlyname,version,ismanaged"],["$expand","publisherid($select=publisherid,uniquename,customizationprefix,customizationoptionvalueprefix)"],["$filter",f]])}`,A=((n=(r=(0,ur.ensureSuccess)(await e.get(m),e.apiUrl(m)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0];if(!A?.solutionid)throw new ni.InvalidArgumentError(`No solution found for '${t}'.`);let D=A.publisherid;if(!D?.publisherid)throw new ni.InvalidArgumentError(`Solution '${(i=A.uniquename)!==null&&i!==void 0?i:t}' returned no owning publisher, so its customization prefix cannot be determined; refusing to report an empty prefix that could be mistaken for "no prefix".`);if(!("customizationprefix"in D))throw new ni.InvalidArgumentError(`Solution '${(a=A.uniquename)!==null&&a!==void 0?a:t}' returned a publisher without a customizationprefix property (partial expansion), so its prefix cannot be determined.`);return{solutionId:(0,Nt.normalizeGuid)(A.solutionid,"solutionId"),uniqueName:(o=A.uniquename)!==null&&o!==void 0?o:"",friendlyName:(s=A.friendlyname)!==null&&s!==void 0?s:"",version:(l=A.version)!==null&&l!==void 0?l:"",isManaged:!!A.ismanaged,publisherId:(0,Nt.normalizeGuid)(D.publisherid,"publisherId"),publisherUniqueName:(u=D.uniquename)!==null&&u!==void 0?u:"",publisherPrefix:(c=D.customizationprefix)!==null&&c!==void 0?c:"",publisherOptionValuePrefix:(d=D.customizationoptionvalueprefix)!==null&&d!==void 0?d:0}}re.getSolution=Qx;async function Kx(e,t){var r;let n={uniquename:t.uniqueName,friendlyname:t.friendlyName,customizationprefix:t.prefix,customizationoptionvalueprefix:(r=t.optionValuePrefix)!==null&&r!==void 0?r:1e4};t.description&&(n.description=t.description);let i=(0,ur.ensureSuccess)(await e.post("/publishers",n),e.apiUrl("/publishers")),a=(0,ur.readCreatedId)(i,"publisherid");if(!a)throw new ni.InvalidArgumentError(`Dataverse did not return an id for publisher '${t.uniqueName}'`);return{id:a,uniqueName:t.uniqueName}}re.createPublisher=Kx;async function Xx(e,t){var r;let n=(0,Nt.normalizeGuid)(t.publisherId,"publisherId"),i={uniquename:t.uniqueName,friendlyname:t.friendlyName,version:(r=t.version)!==null&&r!==void 0?r:"1.0.0.0","[email protected]":`/publishers(${n})`};t.description&&(i.description=t.description);let a=(0,ur.ensureSuccess)(await e.post("/solutions",i),e.apiUrl("/solutions")),o=(0,ur.readCreatedId)(a,"solutionid");if(!o)throw new ni.InvalidArgumentError(`Dataverse did not return an id for solution '${t.uniqueName}'`);return{id:o,uniqueName:t.uniqueName}}re.createSolution=Xx;async function Yx(e,t,r){let i=`/solutions(${(0,Nt.normalizeGuid)(t,"solutionId")})`;(0,ur.ensureSuccess)(await e.patch(i,{version:r}),e.apiUrl(i))}re.setSolutionVersion=Yx;async function Zx(e,t){var r;let i={ComponentId:(0,Nt.normalizeGuid)(t.componentId,"componentId"),ComponentType:t.componentType,SolutionUniqueName:t.solutionUniqueName,AddRequiredComponents:(r=t.addRequiredComponents)!==null&&r!==void 0?r:!1};t.doNotIncludeSubcomponents!==void 0&&(i.DoNotIncludeSubcomponents=t.doNotIncludeSubcomponents),(0,ur.ensureSuccess)(await e.post("/AddSolutionComponent",i),e.apiUrl("/AddSolutionComponent"))}re.addSolutionComponent=Zx;async function eL(e,t,r,n){let a={SolutionComponent:{"@odata.type":"Microsoft.Dynamics.CRM.solutioncomponent",solutioncomponentid:(0,Nt.normalizeGuid)(t,"componentId")},ComponentType:r,SolutionUniqueName:n};(0,ur.ensureSuccess)(await e.post("/RemoveSolutionComponent",a),e.apiUrl("/RemoveSolutionComponent"))}re.removeSolutionComponent=eL;async function tL(e,t){var r,n;let i={SolutionName:t.solutionName,Managed:(r=t.managed)!==null&&r!==void 0?r:!1},o=(n=(0,ur.ensureSuccess)(await e.post("/ExportSolution",i),e.apiUrl("/ExportSolution")).body)===null||n===void 0?void 0:n.ExportSolutionFile;if(!o)throw new ni.InvalidArgumentError(`ExportSolution returned no file for '${t.solutionName}'`);return{base64:o}}re.exportSolution=tL;async function rL(e,t){var r,n;let i={OverwriteUnmanagedCustomizations:(r=t.overwriteUnmanagedCustomizations)!==null&&r!==void 0?r:!0,PublishWorkflows:(n=t.publishWorkflows)!==null&&n!==void 0?n:!0,CustomizationFile:t.base64};t.importJobId&&(i.ImportJobId=(0,Nt.normalizeGuid)(t.importJobId,"importJobId")),(0,ur.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution"))}re.importSolution=rL;async function nL(e,t){let n=`/solutions(${(0,Nt.normalizeGuid)(t,"solutionId")})`;(0,ur.ensureSuccess)(await e.delete(n),e.apiUrl(n))}re.deleteSolution=nL});var ml=v(Rn=>{"use strict";Object.defineProperty(Rn,"__esModule",{value:!0});Rn.appApi=Rn.deleteAppResolvingOnce=Rn.unpublishedAppModulesQuery=void 0;var Pd=qt(),iL=xd(),Qv=lr(),aL=cl(),fe=be(),ne=ae(),Td=pt(),oL=Kc(),me=te(),sL=(0,ne.odataQuery)([["$select","appmoduleid,name,uniquename,description,aiappdescription"]]),Nd="appmoduleid,name,uniquename,description,aiappdescription";function ry(e,t,r){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,ne.odataQuery)([["$select",e],["$filter",t],["$top",r]])}Rn.unpublishedAppModulesQuery=ry;function Dd(e,t){return ry(e,t?`appmoduleid eq ${t}`:void 0,t?1:void 0)}function fl(e,t){return"/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,ne.odataQuery)([["$select",t],["$filter",`sitemapid eq ${e}`],["$top",1]])}function Ji(e){var t;let r=(t=e.body)===null||t===void 0?void 0:t.value;if(Array.isArray(r))return r[0]}function lL(e){let t=e?.["@odata.etag"];return typeof t=="string"?t:null}function Od(e,t){if(typeof e!="string")return!1;try{return(0,ne.normalizeGuid)(e,"sitemapid")===t}catch{return!1}}function Co(e){let t=new Set,r=[];for(let n of e??[])n&&!t.has(n)&&(t.add(n),r.push(n));return r}function uL(e){return`cdsapp_${(e||"").replace(/[^a-zA-Z0-9]/g,"")||"app"}`}async function ny(e,t){var r,n;let i=u=>{throw new me.SdkError("APP_SITEMAP_UNRESOLVED",`The sitemap lookup for app uniquename '${t??""}' ${u}, so it cannot be determined whether this app has a sitemap. Retry; if the app is newly created, publish it first (an unpublished app is not readable).`)};if(!t)return i("cannot run because the app record carried no uniquename");let a=`/sitemaps${(0,ne.odataQuery)([["$select","sitemapid"],["$filter",`sitemapnameunique eq '${(0,ne.odataLiteral)(t)}'`],["$top",1]])}`,o;try{o=await e.get(a)}catch(u){return i(`failed (${u.message})`)}if(o.status<200||o.status>=300)return i(`returned HTTP ${o.status}`);let s=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(s))return i("returned a malformed body");let l=(n=s[0])===null||n===void 0?void 0:n.sitemapid;return s.length>0&&!l?i("returned a row with no sitemapid"):l}async function cL(e){let t=s=>{var l,u,c;return(c=(u=(l=s.body)===null||l===void 0?void 0:l.value)===null||u===void 0?void 0:u[0])===null||c===void 0?void 0:c.webresourceid},r=s=>`/webresourceset${(0,ne.odataQuery)([["$select","webresourceid"],["$top",1],["$filter",s]])}`,n="(webresourcetype eq 5 or webresourcetype eq 6 or webresourcetype eq 7 or webresourcetype eq 10 or webresourcetype eq 11)",i=t(await e.get(r("webresourcetype eq 5 and ismanaged eq false and contains(name,'icon')")));if(i)return{id:i,managed:!1};let a=t(await e.get(r(`${n} and ismanaged eq false`)));if(a)return{id:a,managed:!1};let o=t(await e.get(r(n)));return o?{id:o,managed:!0}:void 0}function Rd(e){return e instanceof Error?e.message:String(e)}async function dL(e,t){var r,n,i;try{let a=`/roles${(0,ne.odataQuery)([["$select","roleid"],["$filter","name eq 'System Administrator'"],["$top",1]])}`,s=(i=(n=(r=(0,fe.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||r===void 0?void 0:r.value)===null||n===void 0?void 0:n[0])===null||i===void 0?void 0:i.roleid;if(!s)return"App roles: no 'System Administrator' role was found in this environment, so the app was created with NO security role associated \u2014 it will not be visible or playable until a role is granted access to it.";let l=`/appmodules(${t})/appmoduleroles_association/$ref`;return(0,fe.ensureSuccess)(await e.post(l,{"@odata.id":e.apiUrl(`/roles(${s})`)}),e.apiUrl(l)),null}catch(a){return`App roles: could not associate the 'System Administrator' role with the app (${Rd(a)}); it will not be visible or playable until a role is granted access to it.`}}async function pL(e,t){let r=[];async function n(s,l,u){try{return(await(0,Pd.collectPages)(e,s,`app assets (${u} for '${t}')`)).map(d=>String(d[l])).filter(d=>d&&d!=="undefined")}catch(c){return r.push(`App components: could not enumerate ${u} for table '${t}' (${Rd(c)}); they were NOT added to the app.`),[]}}let[i,a,o]=await Promise.all([n(`/systemforms${(0,ne.odataQuery)([["$select","formid"],["$filter",`objecttypecode eq '${(0,ne.odataLiteral)(t)}' and type eq 2 and formactivationstate eq 1`]])}`,"formid","forms"),n(`/savedqueries${(0,ne.odataQuery)([["$select","savedqueryid"],["$filter",`returnedtypecode eq '${(0,ne.odataLiteral)(t)}' and querytype eq 0 and statecode eq 0`]])}`,"savedqueryid","views"),n(`/savedqueryvisualizations${(0,ne.odataQuery)([["$select","savedqueryvisualizationid"],["$filter",`primaryentitytypecode eq '${(0,ne.odataLiteral)(t)}'`]])}`,"savedqueryvisualizationid","charts")]);return{forms:i,views:a,charts:o,warnings:r}}var Kv=new WeakMap;async function fL(e,t){let r=Kv.get(e);r||(r=new Map,Kv.set(e,r));let n=r.get(t);if(n!==void 0)return n;let i=await mL(e,t);return i&&r.set(t,i),i}async function Xv(e,t,r){let n=new Array(e.length),i=0;async function a(){for(let o=i;o<e.length;o=i)i=o+1,n[o]=await r(e[o])}return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>a())),n}async function mL(e,t){let r=`/EntityDefinitions(LogicalName='${(0,ne.odataPathLiteral)(t)}')${(0,ne.odataQuery)([["$select","MetadataId,EntitySetName"]])}`,n=await e.get(r);if(n.status>=200&&n.status<300){let i=n.body;if(i?.MetadataId&&i.EntitySetName)return{logicalName:t,metadataId:i.MetadataId,entitySetName:i.EntitySetName}}}async function Yv(e,t){let r=[],n=Co(t.entities),i=4,a=await Xv(n,i,f=>fL(e,f)),o=n.filter((f,m)=>!a[m]);if(o.length>0)throw new me.SdkError("APP_ENTITY_COMPONENT_UNRESOLVED",`Refusing to build app components: table(s) ${o.map(f=>`'${f}'`).join(", ")} could not be resolved to an EntityDefinitions MetadataId + EntitySetName. Pinning the rest would produce an app whose navigation references a table the app does not contain. Verify the table name(s) exist in this environment and retry.`);let s=a.filter(f=>!!f);for(let f of s)r.push({"@odata.id":`${f.entitySetName}(${f.metadataId})`});for(let f of Co(t.components.forms))r.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:f});for(let f of Co(t.components.views))r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:f});for(let f of Co(t.components.charts))r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:f});for(let f of Co(t.components.dashboards))r.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:f});let l=new Set(t.components.forms),u=new Set(t.components.views),c=new Set(t.components.charts),d=await Xv(n,i,f=>pL(e,f)),p=d.flatMap(f=>f.warnings);for(let f of d){for(let m of f.forms)l.has(m)||(l.add(m),r.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:m}));for(let m of f.views)u.has(m)||(u.add(m),r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:m}));for(let m of f.charts)c.has(m)||(c.add(m),r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:m}))}return{components:r,tables:s,warnings:p}}async function Zv(e,t,r){if(r.length===0)return;let n="/AddAppComponents";(0,fe.ensureSuccess)(await e.post(n,{AppId:t,Components:r}),e.apiUrl(n))}function hL(e){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,ne.odataQuery)([["$select","appmoduleid,appmoduleidunique"],["$filter",`appmoduleid eq ${e}`],["$top",1]])}async function ey(e,t,r){var n;if(r.length===0)return;let i=hL(t),a=await e.get(i);if(a.status<200||a.status>=300)throw new me.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its components were written but could not be verified \u2014 the unpublished-aware read returned HTTP ${a.status}. Re-push to retry.`);let o=Ji(a),s=o?.appmoduleidunique;if(typeof s!="string"||!s)throw new me.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its components were written but could not be verified \u2014 the app did not return an 'appmoduleidunique' to file components under. Re-push to retry.`);let l=`/appmodulecomponents${(0,ne.odataQuery)([["$select","objectid,componenttype"],["$filter",`_appmoduleidunique_value eq ${(0,ne.normalizeGuid)(s,`App '${t}' appmoduleidunique`)} and componenttype eq 1`]])}`,u=await e.get(l);if(u.status<200||u.status>=300)throw new me.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its table components were written but could not be verified \u2014 reading them back returned HTTP ${u.status}. Re-push to retry.`);let c=(n=u.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(c))throw new me.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its table components were written but could not be verified \u2014 the read-back returned no readable result set. Re-push to retry.`);let d=new Set(c.map(f=>f.objectid).filter(f=>typeof f=="string").map(f=>f.toLowerCase())),p=r.filter(f=>!d.has(f.metadataId.toLowerCase()));if(p.length>0)throw new me.SdkError("APP_COMPONENTS_NOT_PERSISTED",`App '${t}': ${p.length} declared table(s) are NOT components of the app after AddAppComponents reported success \u2014 ${p.map(f=>`'${f.logicalName}' (expected objectid ${f.metadataId})`).join(", ")}. The app's navigation would reference content the app does not contain.`)}async function gL(e,t,r){let n=`/appmodules(${t})`,i=`/sitemaps(${r.sitemapId})`;try{let a=await vL(e,r.sitemapId,r.sitemapNameUnique);if(a==="absent"){r.serverRefusedSitemap&&(0,fe.ensureSuccess)(await e.delete(n),e.apiUrl(n));return}if(a==="foreign"){r.serverRefusedSitemap&&(0,fe.ensureSuccess)(await e.delete(n),e.apiUrl(n));return}if(e.supportsAtomicBatch){if(!r.sitemapWriteToken)return;await ay(e,[{path:n},{path:i,etag:r.sitemapWriteToken}])}}catch{}}async function vL(e,t,r){var n,i,a;let o=fl(t,"sitemapid,sitemapnameunique"),s=await e.get(o);if(s.status<200||s.status>=300)throw new me.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned HTTP ${s.status}, so it cannot be determined whether the row exists.`);let l=(n=s.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(l))throw new me.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned no readable result set, so it cannot be determined whether the row exists.`);return l.length===0?"absent":String((a=(i=l[0])===null||i===void 0?void 0:i.sitemapnameunique)!==null&&a!==void 0?a:"")===r?"ours":"foreign"}async function iy(e,t){var r;let n=(0,ne.normalizeGuid)(t,"id"),i=g=>{throw new me.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to delete app '${n}': ${g} Deleting the app would destroy the only pointer to its sitemap, stranding that row and reserving its unique name forever. Retry; if the app is newly created, publish it first (an unpublished app is not readable).`)},a=`/appmodules(${n})${sL}`,o;try{o=await e.get(a)}catch(g){return i(`reading the app failed (${g.message}).`)}if(o.status<200||o.status>=300)return i(o.status===404?"reading the app returned HTTP 404, which does NOT prove it is absent \u2014 Dataverse also reports an unpublished app that way, and such an app still owns a sitemap.":`reading the app returned HTTP ${o.status}.`);let s=(r=o.body)===null||r===void 0?void 0:r.uniquename;if(!s)return i("the app record carried no uniquename, so its sitemap cannot be located.");let l=await ny(e,s);if(!l)return{uniquename:s,appEtag:(0,fe.readEtag)(o)};let u=(0,ne.normalizeGuid)(l,"sitemapId"),c=await Fd(e,u),d=fl(u,"sitemapid,sitemapnameunique,sitemapxml"),p;try{p=await e.get(d)}catch(g){return i(`reading sitemap '${u}' failed (${g.message}).`)}if(p.status<200||p.status>=300)return i(`reading sitemap '${u}' returned HTTP ${p.status}.`);let f=Ji(p);if(!f)return i(`sitemap '${u}' was not returned by the unpublished-aware read.`);if(f.sitemapnameunique!==s)return i(`sitemap '${u}' now carries sitemapnameunique '${String(f.sitemapnameunique)}', not '${s}', so it is no longer this app's sitemap.`);if(!Od(f.sitemapid,u))return i(`sitemap '${u}' was read back as a row carrying sitemapid '${String(f.sitemapid)}'.`);let m=f.sitemapxml;return typeof m!="string"?i(`sitemap '${u}' returned no sitemapxml.`):{sitemapId:u,uniquename:s,sitemapXml:m,appEtag:(0,fe.readEtag)(o),sitemapEtag:c}}async function yL(e,t,r){let n=(0,ne.normalizeGuid)(t,"id"),i=await iy(e,n);await r?.(i.sitemapXml),await oy(e,n,i)}Rn.deleteAppResolvingOnce=yL;async function ay(e,t){let r=`batch_${(0,Td.newId)()}`,n=`changeset_${(0,Td.newId)()}`,i=t.map((d,p)=>[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${p+1}`,"",`DELETE ${e.apiUrl(d.path)} HTTP/1.1`,...d.etag?[`If-Match: ${d.etag}`]:[],""].join(`\r+`)}function _y(e){this.options=e||{locator:{}}}_y.prototype.parseFromString=function(e,t){var r=this.options,n=new MF,i=r.domBuilder||new Fo,a=r.errorHandler,o=r.locator,s=r.xmlns||{},l=/\/x?html?$/.test(t),u=l?Ey.HTML_ENTITIES:Ey.XML_ENTITIES;o&&i.setDocumentLocator(o),n.errorHandler=BF(a,i,o),n.domBuilder=r.domBuilder||i,l&&(s[""]=Sy.HTML),s.xml=s.xml||Sy.XML;var c=r.normalizeLineEndings||Iy;return e&&typeof e=="string"?n.parse(c(e),s,u):n.errorHandler.error("invalid doc source"),i.doc};function BF(e,t,r){if(!e){if(t instanceof Fo)return t;e=t}var n={},i=e instanceof Function;r=r||{};function a(o){var s=e[o];!s&&i&&(s=e.length==2?function(l){e(o,l)}:e),n[o]=s&&function(l){s("[xmldom "+o+"] "+l+ip(r))}||function(){}}return a("warning"),a("error"),a("fatalError"),n}function Fo(){this.cdata=!1}function oa(e,t){t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber}Fo.prototype={startDocument:function(){this.doc=new FF().createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(e,t,r,n){var i=this.doc,a=i.createElementNS(e,r||t),o=n.length;Nl(this,a),this.currentElement=a,this.locator&&oa(this.locator,a);for(var s=0;s<o;s++){var e=n.getURI(s),l=n.getValue(s),r=n.getQName(s),u=i.createAttributeNS(e,r);this.locator&&oa(n.getLocator(s),u),u.value=u.nodeValue=l,a.setAttributeNode(u)}},endElement:function(e,t,r){var n=this.currentElement,i=n.tagName;this.currentElement=n.parentNode},startPrefixMapping:function(e,t){},endPrefixMapping:function(e){},processingInstruction:function(e,t){var r=this.doc.createProcessingInstruction(e,t);this.locator&&oa(this.locator,r),Nl(this,r)},ignorableWhitespace:function(e,t,r){},characters:function(e,t,r){if(e=Ny.apply(this,arguments),e){if(this.cdata)var n=this.doc.createCDATASection(e);else var n=this.doc.createTextNode(e);this.currentElement?this.currentElement.appendChild(n):/^\s*$/.test(e)&&this.doc.appendChild(n),this.locator&&oa(this.locator,n)}},skippedEntity:function(e){},endDocument:function(){this.doc.normalize()},setDocumentLocator:function(e){(this.locator=e)&&(e.lineNumber=0)},comment:function(e,t,r){e=Ny.apply(this,arguments);var n=this.doc.createComment(e);this.locator&&oa(this.locator,n),Nl(this,n)},startCDATA:function(){this.cdata=!0},endCDATA:function(){this.cdata=!1},startDTD:function(e,t,r){var n=this.doc.implementation;if(n&&n.createDocumentType){var i=n.createDocumentType(e,t,r);this.locator&&oa(this.locator,i),Nl(this,i),this.doc.doctype=i}},warning:function(e){console.warn("[xmldom warning] "+e,ip(this.locator))},error:function(e){console.error("[xmldom error] "+e,ip(this.locator))},fatalError:function(e){throw new kF(e,this.locator)}};function ip(e){if(e)return`+@`+(e.systemId||"")+"#[line:"+e.lineNumber+",col:"+e.columnNumber+"]"}function Ny(e,t,r){return typeof e=="string"?e.substr(t,r):e.length>=t+r||t?new java.lang.String(e,t,r)+"":e}"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(e){Fo.prototype[e]=function(){return null}});function Nl(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}Dl.__DOMHandler=Fo;Dl.normalizeLineEndings=Iy;Dl.DOMParser=_y});var ap=y(Il=>{var Py=tp();Il.DOMImplementation=Py.DOMImplementation;Il.XMLSerializer=Py.XMLSerializer;Il.DOMParser=Ty().DOMParser});var Un=y(_l=>{"use strict";Object.defineProperty(_l,"__esModule",{value:!0});_l.installDomShim=void 0;var Ry=ap(),Oy=!1,UF={ELEMENT_NODE:1,ATTRIBUTE_NODE:2,TEXT_NODE:3,CDATA_SECTION_NODE:4,ENTITY_REFERENCE_NODE:5,ENTITY_NODE:6,PROCESSING_INSTRUCTION_NODE:7,COMMENT_NODE:8,DOCUMENT_NODE:9,DOCUMENT_TYPE_NODE:10,DOCUMENT_FRAGMENT_NODE:11,NOTATION_NODE:12};function $F(){if(Oy)return;let e=globalThis;typeof e.DOMParser>"u"&&(e.DOMParser=Ry.DOMParser),typeof e.XMLSerializer>"u"&&(e.XMLSerializer=Ry.XMLSerializer),typeof e.Node>"u"&&(e.Node=UF),Oy=!0}_l.installDomShim=$F});var mi=y(xe=>{"use strict";Object.defineProperty(xe,"__esModule",{value:!0});xe.projectElementBag=xe.serializeNode=xe.domEngine=xe.nodeLikeFromDom=xe.parseXmlRoot=xe.EMPTY_FORM_SENTINEL=xe.TEXT_SENTINEL=void 0;var qF=Mn(),ko=ee(),VF=Un();xe.TEXT_SENTINEL="#text";xe.EMPTY_FORM_SENTINEL="#empty";var Pl=new WeakSet;function GF(e,t){(0,VF.installDomShim)();let r=e&&e.trim()!==""?e:t,i=new DOMParser().parseFromString(r,"text/xml").documentElement;if(!i)throw new ko.InvalidArgumentError("XML source has no root element (empty or malformed input)");return WF(i),jF(i),KF(i,r),i}xe.parseXmlRoot=GF;var zF=new Set([1,3]);function WF(e){let t=[e];for(;t.length>0;){let n=t.pop().childNodes;for(let i=0;i<n.length;i+=1){let a=n[i];if(!zF.has(a.nodeType))throw new ko.InvalidArgumentError(`Unsupported XML node type ${a.nodeType} (CDATA / comment / processing-instruction) is outside the hybrid projection's lossless grammar and cannot be round-tripped`);a.nodeType===1&&t.push(a)}}}function jF(e){var t,r;let n=(t=e.ownerDocument)!==null&&t!==void 0?t:e.parentNode;if(!n)return;let i=n.childNodes;for(let a=0;a<i.length;a+=1){let o=i[a];if(o!==e&&!(o.nodeType===3&&((r=o.nodeValue)!==null&&r!==void 0?r:"").trim()===""))throw new ko.InvalidArgumentError(`Unsupported document-level XML node (type ${o.nodeType}: declaration / comment / processing-instruction outside the root element) cannot be round-tripped`)}}function HF(e){let t=[],r=/<([^>]*)>/g;for(let n=r.exec(e);n!==null;n=r.exec(e)){let i=n[1];i.startsWith("/")||i.startsWith("?")||i.startsWith("!")||t.push(i.endsWith("/"))}return t}function JF(e){let t=[],r=[e];for(;r.length>0;){let n=r.pop();t.push(n);let i=n.childNodes;for(let a=i.length-1;a>=0;a-=1){let o=i[a];o.nodeType===1&&r.push(o)}}return t}function Ly(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1){let n=t[r].nodeType;if(n===1||n===3)return!0}return!1}function KF(e,t){let r=HF(t),n=JF(e),i=Math.min(r.length,n.length);for(let a=0;a<i;a+=1){if(r[a])continue;let o=n[a];Ly(o)||Pl.add(o)}}function op(e){let t=e.nodeType===3;return{getNodeName:()=>t?xe.TEXT_SENTINEL:e.tagName,getAllProperties:()=>{var r;if(t)return[{key:xe.TEXT_SENTINEL,value:(r=e.nodeValue)!==null&&r!==void 0?r:""}];let n=e.attributes,i=[];for(let a=0;a<n.length;a+=1)i.push({key:n[a].name,value:n[a].value});return Pl.has(e)&&!Ly(e)&&i.push({key:xe.EMPTY_FORM_SENTINEL,value:"1"}),i},getAllChildren:()=>{if(t)return[];let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let a=n[i];(a.nodeType===1||a.nodeType===3)&&r.push(op(a))}return r}}}xe.nodeLikeFromDom=op;function QF(e){return{make:t=>t===xe.TEXT_SENTINEL?e.createTextNode(""):e.createElement(t),setProp:(t,r,n)=>{t.nodeType===3?t.nodeValue=n:r===xe.EMPTY_FORM_SENTINEL?Pl.add(t):t.setAttribute(r,n)},addChild:(t,r)=>{t.appendChild(r)}}}xe.domEngine=QF;function Fy(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r<=31&&r!==9&&r!==10&&r!==13||r===65534||r===65535)throw Tl(r);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))throw Tl(r);t+=1;continue}if(r>=56320&&r<=57343)throw Tl(r)}}function Tl(e){let t=e.toString(16).toUpperCase().padStart(4,"0");return new ko.InvalidArgumentError(`Value contains U+${t}, a character not permitted in XML 1.0 (control char / lone surrogate / non-character); it cannot be serialized losslessly`)}function XF(e){return Fy(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/\r/g,"
").replace(/\n/g,"
").replace(/\t/g,"	")}function YF(e){return Fy(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function ZF(e){return ky(e,0)}xe.serializeNode=ZF;var xy=512;function ky(e,t){var r;if(t>xy)throw new ko.InvalidArgumentError(`XML nesting exceeds the maximum supported depth of ${xy}`);if(e.nodeType===3)return YF((r=e.nodeValue)!==null&&r!==void 0?r:"");let n=e,i="<"+n.tagName,a=n.attributes;for(let l=0;l<a.length;l+=1)i+=" "+a[l].name+'="'+XF(a[l].value)+'"';let o=[],s=n.childNodes;for(let l=0;l<s.length;l+=1){let u=s[l];(u.nodeType===1||u.nodeType===3)&&o.push(u)}if(o.length===0)return Pl.has(n)?i+"></"+n.tagName+">":i+" />";i+=">";for(let l of o)i+=ky(l,t+1);return i+"</"+n.tagName+">"}function ek(e){let t=op(e);return{a:t.getAllProperties().map(r=>[r.key,r.value]),c:t.getAllChildren().map((r,n)=>({i:n,node:(0,qF.rawFromNode)(r)}))}}xe.projectElementBag=ek});var up=y($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.getFormSecurityRoles=$n.setFormSecurityRoles=$n.formApi=void 0;var tk=$t(),ye=Ee(),Xt=le(),sa=ee(),sp=mi(),rk="formid,formxml,name,type,objecttypecode,formpresentation,formactivationstate,uniquename,description,versionnumber",nk="formid,name,type,objecttypecode",ik=2,ak={Main:ik,QuickView:6,QuickCreate:7,Card:11};$n.formApi={async get(e,t){let n=`/systemforms(${(0,Xt.normalizeGuid)(t,"id")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Xt.odataQuery)([["$select",rk]]),i=(0,ye.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,ye.readEtag)(i)}},async list(e,t){var r;let n=!((r=t?.formTypes)===null||r===void 0)&&r.length?t.formTypes:["Main"],i=[...new Set(n.map(u=>ak[u]))],o=[i.length===1?`type eq ${i[0]}`:`(${i.map(u=>`type eq ${u}`).join(" or ")})`];t?.entityLogicalName&&o.push(`objecttypecode eq '${(0,Xt.odataLiteral)(t.entityLogicalName)}'`);let s=`/systemforms${(0,Xt.odataQuery)([["$select",nk],["$filter",o.join(" and ")]])}`;return(await(0,tk.collectPages)(e,s,"listArtifacts('form')")).map(u=>{var c,d;return{type:"form",id:(c=u.formid)!==null&&c!==void 0?c:"",name:(d=u.name)!==null&&d!==void 0?d:"",entityLogicalName:u.objecttypecode,isDirty:!1}})},async create(e,t,r){let n=(0,ye.echoWrite)("formid"),i=`/systemforms${n.query}`,a=(0,ye.ensureSuccess)(await e.post(i,(0,ye.withClientMintedId)(t,"formid",r),n.options),e.apiUrl(i));return{id:(0,ye.resolveCreatedId)(a,"formid","form",r),etag:(0,ye.readEtag)(a)}},async update(e,t,r,n){let i=(0,Xt.normalizeGuid)(t,"id");await Uy(e,i,By(i),n);let a=await My(e,i),o=(0,ye.echoWrite)("formid",{"If-Match":(0,ye.requireEtag)(a,"form",i)}),s=`/systemforms(${i})${o.query}`;return(0,ye.ensureSuccess)(await e.patch(s,r,o.options),e.apiUrl(s)),{id:i,etag:await sk(e,i)}},delete(e,t){return(0,ye.deleteRecord)(e,"systemforms",t)}};var lp="DisplayConditions";async function ok(e,t,r){var n,i,a,o;if(r.everyone&&r.roleIds&&r.roleIds.length>0)throw new sa.InvalidArgumentError("setFormSecurityRoles: `everyone` and `roleIds` are mutually exclusive \u2014 the platform models <Everyone /> as a replacement for the <Role> list, not an addition to it.");let s=(0,Xt.normalizeGuid)(t,"formId"),l=`/systemforms(${s})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Xt.odataQuery)([["$select","formid,formxml"]]),u=(0,ye.ensureSuccess)(await e.get(l),e.apiUrl(l)),c=(0,ye.readEtag)(u),d=u.body,p=d?.formxml;if(!p)throw new sa.InvalidArgumentError(`form '${s}' returned no formxml, so its roles cannot be set`);let f=(0,sp.parseXmlRoot)(p,"<form/>"),m=f.ownerDocument;if(!m)throw new sa.InvalidArgumentError(`form '${s}' produced no owner document`);let h=$y(f,lp),v=h?.hasAttribute("Order")&&(n=h.getAttribute("Order"))!==null&&n!==void 0?n:void 0,w=h?.getAttribute("FallbackForm")||void 0;h&&f.removeChild(h);let C=!!r.everyone||((a=(i=r.roleIds)===null||i===void 0?void 0:i.length)!==null&&a!==void 0?a:0)>0;if(!C&&(r.order!==void 0||r.fallbackForm!==void 0)){if(!h)throw new sa.InvalidArgumentError("setFormSecurityRoles: `order`/`fallbackForm` were supplied without `roleIds` or `everyone`, but this form has no <DisplayConditions> to attach them to. Pass the roles as well.");r.order!==void 0&&h.setAttribute("Order",String(r.order)),r.fallbackForm!==void 0&&h.setAttribute("FallbackForm",String(r.fallbackForm)),f.appendChild(h)}else if(C){let F=m.createElement(lp),M=r.order!==void 0?String(r.order):v;M!==void 0&&F.setAttribute("Order",M);let P=r.fallbackForm!==void 0?String(r.fallbackForm):w??"false";if(F.setAttribute("FallbackForm",P),r.everyone)F.appendChild(m.createElement("Everyone"));else for(let q of(o=r.roleIds)!==null&&o!==void 0?o:[]){let $=m.createElement("Role");$.setAttribute("Id",`{${(0,Xt.normalizeGuid)(q,"roleId")}}`),F.appendChild($)}f.appendChild(F)}let D=(0,sp.serializeNode)(f);await Uy(e,s,l,c);let O=await My(e,s),x=`/systemforms(${s})`;(0,ye.ensureSuccess)(await e.patch(x,{formxml:D},{headers:{"Content-Type":"application/json","If-Match":(0,ye.requireEtag)(O,"form",s)}}),e.apiUrl(x))}$n.setFormSecurityRoles=ok;async function My(e,t){let r=`/systemforms(${t})${(0,Xt.odataQuery)([["$select","formid"]])}`;return(0,ye.readEtag)((0,ye.ensureSuccess)(await e.get(r),e.apiUrl(r)))}function By(e){return`/systemforms(${e})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Xt.odataQuery)([["$select","formid"]])}async function sk(e,t){let r=By(t);return(0,ye.readEtag)((0,ye.ensureSuccess)(await e.get(r),e.apiUrl(r)))}async function Uy(e,t,r,n){(0,ye.requireEtag)(n,"form",t);let i=(0,ye.readEtag)((0,ye.ensureSuccess)(await e.get(r),e.apiUrl(r)));if(i===null)throw new sa.SdkError(ye.VERSION_CONFLICT_CODE,`Refusing to write form '${t}': its current version could not be read, so the write could not be verified as conditional and would risk silently overwriting a concurrent edit.`);if(i!==n)throw new sa.SdkError(ye.VERSION_CONFLICT_CODE,`Version conflict writing form '${t}': its formxml changed on the server since it was read (held ${n}, server ${i}). Re-fetch the form and re-apply the change.`)}function $y(e,t){let r=e.childNodes;for(let n=0;n<r.length;n+=1){let i=r[n];if(i.nodeType===1&&i.tagName===t)return i}}async function lk(e,t){var r,n;let a=`/systemforms(${(0,Xt.normalizeGuid)(t,"formId")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Xt.odataQuery)([["$select","formid,formxml"]]),s=(r=(0,ye.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||r===void 0?void 0:r.formxml;if(!s)return;let l=(0,sp.parseXmlRoot)(s,"<form/>"),u=$y(l,lp);if(!u)return;let c=[],d=!1,p=u.childNodes;for(let m=0;m<p.length;m+=1){let h=p[m];if(h.nodeType!==1)continue;let v=h;if(v.tagName==="Everyone")d=!0;else if(v.tagName==="Role"){let w=(n=v.getAttribute("Id"))!==null&&n!==void 0?n:"";w&&c.push(w.replace(/[{}]/g,"").toLowerCase())}}let f=u.getAttribute("Order");return{...d?{everyone:!0}:{},...c.length>0?{roleIds:c}:{},fallbackForm:u.getAttribute("FallbackForm")==="true",...f!==null&&f!==""?{order:Number(f)}:{}}}$n.getFormSecurityRoles=lk});var xl=y(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.disassociateRecords=Pe.associateRecords=Pe.createRecordsBulk=Pe.upsertRecord=Pe.queryAllRecords=Pe.queryRecords=Pe.getRecord=Pe.deleteRecord=Pe.updateRecord=Pe.createRecord=void 0;var uk=$t(),mr=Ee(),ut=le(),Rl=ee(),kr=pl();function Ol(e){let t=e,r=!1,n={};for(let i of Object.keys(t)){let a=t[i];Array.isArray(a)&&a.every(o=>typeof o=="number")?(n[i]=a.join(","),r=!0):n[i]=a}return r?n:e}async function ck(e,t,r){let i=`/${await(0,kr.resolveEntitySetName)(e,t)}`,a=(0,mr.ensureSuccess)(await e.post(i,Ol(r)),e.apiUrl(i)),o=(0,mr.readCreatedId)(a,`${t}id`);if(!o)throw new Rl.InvalidArgumentError(`Dataverse did not return an id for the created '${t}' row`);return{id:o,entityType:t}}Pe.createRecord=ck;async function dk(e,t,r,n){let i=(0,ut.normalizeGuid)(r,"id"),o=`/${await(0,kr.resolveEntitySetName)(e,t)}(${i})`;(0,mr.ensureSuccess)(await e.patch(o,Ol(n)),e.apiUrl(o))}Pe.updateRecord=dk;async function pk(e,t,r){let n=(0,ut.normalizeGuid)(r,"id"),a=`/${await(0,kr.resolveEntitySetName)(e,t)}(${n})`;(0,mr.ensureSuccess)(await e.delete(a),e.apiUrl(a))}Pe.deleteRecord=pk;async function fk(e,t,r,n){var i;let a=(0,ut.normalizeGuid)(r,"id"),o=await(0,kr.resolveEntitySetName)(e,t),s=(0,ut.odataQuery)([["$select",n&&n.length>0?n.join(","):void 0]]),l=`/${o}(${a})${s}`;return(i=(0,mr.ensureSuccess)(await e.get(l),e.apiUrl(l)).body)!==null&&i!==void 0?i:{}}Pe.getRecord=fk;function mk(e){return e?.fetchXml?(0,ut.odataQuery)([["fetchXml",e.fetchXml]]):(0,ut.odataQuery)([["$select",e?.select&&e.select.length>0?e.select.join(","):void 0],["$filter",e?.filter],["$orderby",e?.orderBy],["$expand",e?.expand],["$top",e?.top]])}async function qy(e,t,r){var n,i;if(r?.paginate){if(r.top!==void 0)throw new Rl.InvalidArgumentError("queryRecords: `paginate` cannot be combined with `top` \u2014 Dataverse honors $top as a hard cap and omits @odata.nextLink, so the result would be silently capped at one page.");if(r.fetchXml)throw new Rl.InvalidArgumentError("queryRecords: `paginate` is not supported with `fetchXml` \u2014 FetchXML paging uses a paging cookie (page / fetchxmlpagingcookie), not @odata.nextLink. Page the FetchXML manually, or use an OData query.")}let o=`/${await(0,kr.resolveEntitySetName)(e,t)}${mk(r)}`;return r?.paginate?(0,uk.collectPages)(e,o,"queryRecords"):(i=(n=(0,mr.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]}Pe.queryRecords=qy;async function hk(e,t,r){return qy(e,t,{...r,paginate:!0})}Pe.queryAllRecords=hk;function gk(e){if("id"in e)return`(${(0,ut.normalizeGuid)(e.id,"id")})`;let t=typeof e.value=="string"?`'${(0,ut.odataPathLiteral)(e.value)}'`:e.value;return`(${(0,ut.assertODataName)(e.key,"alternate key name")}=${t})`}async function vk(e,t,r,n){let i=gk(r),o=`/${await(0,kr.resolveEntitySetName)(e,t)}${i}`,s=(0,mr.ensureSuccess)(await e.patch(o,Ol(n)),e.apiUrl(o)),l=s.status===201,u=(0,mr.readCreatedId)(s,`${t}id`);return{id:u??("id"in r?(0,ut.normalizeGuid)(r.id,"id"):""),created:l}}Pe.upsertRecord=vk;async function yk(e,t,r){var n,i;if(r.length===0)return[];let a=await(0,kr.resolveEntitySetName)(e,t),o=r.map(c=>({"@odata.type":`Microsoft.Dynamics.CRM.${t}`,...Ol(c)})),s=`/${a}/Microsoft.Dynamics.CRM.CreateMultiple`,u=(i=(n=(0,mr.ensureSuccess)(await e.post(s,{Targets:o}),e.apiUrl(s)).body)===null||n===void 0?void 0:n.Ids)!==null&&i!==void 0?i:[];if(u.length!==r.length)throw new Rl.InvalidArgumentError(`CreateMultiple on '${t}' returned ${u.length} id(s) for ${r.length} row(s)`);return u}Pe.createRecordsBulk=yk;async function bk(e,t,r,n){let i=(0,ut.normalizeGuid)(r,"id"),a=(0,ut.normalizeGuid)(n.targetId,"targetId"),o=await(0,kr.resolveEntitySetName)(e,t),s=await(0,kr.resolveEntitySetName)(e,n.targetEntity),l=(0,ut.assertODataName)(n.relationshipName,"relationshipName"),u=`/${o}(${i})/${l}/$ref`,c={"@odata.id":e.apiUrl(`/${s}(${a})`)};(0,mr.ensureSuccess)(await e.post(u,c),e.apiUrl(u))}Pe.associateRecords=bk;async function wk(e,t,r,n,i){let a=(0,ut.normalizeGuid)(r,"id"),o=(0,ut.normalizeGuid)(i,"targetId"),s=await(0,kr.resolveEntitySetName)(e,t),l=(0,ut.assertODataName)(n,"relationshipName"),u=`/${s}(${a})/${l}(${o})/$ref`;(0,mr.ensureSuccess)(await e.delete(u),e.apiUrl(u))}Pe.disassociateRecords=wk});var hr=y(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.publishBoundEntity=Qe.boundEntityPublishScope=Qe.publishGenPageById=Qe.publishDashboardById=Qe.publishWebResourceById=Qe.publishEntity=Qe.publishAppModule=Qe.publishXml=void 0;var Ak=Ee(),Mo=le(),Vy="/PublishXml";async function la(e,t){(0,Ak.ensureSuccess)(await e.post(Vy,{ParameterXml:t}),e.apiUrl(Vy))}Qe.publishXml=la;function Ck(e,t){return la(e,`<importexportxml><appmodules><appmodule>${(0,Mo.xmlText)(t)}</appmodule></appmodules></importexportxml>`)}Qe.publishAppModule=Ck;function Gy(e,t){return la(e,`<importexportxml><entities><entity>${(0,Mo.xmlText)(t)}</entity></entities></importexportxml>`)}Qe.publishEntity=Gy;function Ek(e,t){return la(e,`<importexportxml><webresources><webresource>${(0,Mo.xmlText)(t)}</webresource></webresources></importexportxml>`)}Qe.publishWebResourceById=Ek;function Sk(e,t){return la(e,`<importexportxml><dashboards><dashboard>${(0,Mo.xmlText)(t)}</dashboard></dashboards></importexportxml>`)}Qe.publishDashboardById=Sk;function Nk(e,t){return la(e,`<importexportxml><uxagentprojects><uxagentproject>${(0,Mo.xmlText)(t)}</uxagentproject></uxagentprojects></importexportxml>`)}Qe.publishGenPageById=Nk;function Dk(e){let t=e?.entityLogicalName;return t?{envelope:"entity",entityLogicalName:t,blastRadiusWarning:"ENTITY_ENVELOPE_ALSO_SHIPS_UNRELATED_UNPUBLISHED_CHANGES"}:{envelope:"entity"}}Qe.boundEntityPublishScope=Dk;function Ik(e,t){let r=t?.entityLogicalName;return r?Gy(e,r):Promise.resolve()}Qe.publishBoundEntity=Ik});var Fl=y(Mr=>{"use strict";Object.defineProperty(Mr,"__esModule",{value:!0});Mr.base64ToUtf8=Mr.base64ToBytes=Mr.bytesToBase64=Mr.utf8ToBase64=void 0;var cp=32768,Rt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Ll(){return globalThis}function _k(e){let t=[];for(let r=0;r<e.length;r+=1){let n=e.charCodeAt(r);if(n>=55296&&n<=56319){let i=r+1<e.length?e.charCodeAt(r+1):0;i>=56320&&i<=57343?(n=(n-55296<<10)+(i-56320)+65536,r+=1):n=65533}else n>=56320&&n<=57343&&(n=65533);n<128?t.push(n):n<2048?t.push(192|n>>6,128|n&63):n<65536?t.push(224|n>>12,128|n>>6&63,128|n&63):t.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|n&63)}return Uint8Array.from(t)}function Tk(e){let t="";for(let r=0;r<e.length;r+=cp)t+=String.fromCharCode(...e.subarray(r,r+cp));return t}function Pk(e){let t="";for(let r=0;r<e.length;r+=1){let n=String.fromCharCode(e.charCodeAt(r)&255);if(n==="=")break;n==="-"?t+="+":n==="_"?t+="/":Rt.indexOf(n)>=0&&(t+=n)}for(t.length%4===1&&(t=t.slice(0,-1));t.length%4!==0;)t+="=";return t}function Rk(e){let t="",r=0;for(;r+2<e.length;r+=3){let i=e[r]<<16|e[r+1]<<8|e[r+2];t+=Rt[i>>18&63]+Rt[i>>12&63]+Rt[i>>6&63]+Rt[i&63]}let n=e.length-r;if(n===1){let i=e[r]<<16;t+=`${Rt[i>>18&63]}${Rt[i>>12&63]}==`}else if(n===2){let i=e[r]<<16|e[r+1]<<8,a=Rt[i>>18&63],o=Rt[i>>12&63],s=Rt[i>>6&63];t+=`${a}${o}${s}=`}return t}function Ok(e){let t=e.endsWith("==")?2:e.endsWith("=")?1:0,r=e.length/4*3-t,n=new Uint8Array(r>0?r:0),i=0;for(let a=0;a<e.length;a+=4){let o=Rt.indexOf(e[a])<<18|Rt.indexOf(e[a+1])<<12|(e[a+2]==="="?0:Rt.indexOf(e[a+2]))<<6|(e[a+3]==="="?0:Rt.indexOf(e[a+3]));i<r&&(n[i++]=o>>16&255),i<r&&(n[i++]=o>>8&255),i<r&&(n[i++]=o&255)}return n}function xk(e){let t=Ll();if(t.Buffer)return t.Buffer.from(e,"utf8").toString("base64");let r=t.TextEncoder;return zy(r?new r().encode(e):_k(e))}Mr.utf8ToBase64=xk;function zy(e){let t=Ll();return t.Buffer?t.Buffer.from(e).toString("base64"):t.btoa?t.btoa(Tk(e)):Rk(e)}Mr.bytesToBase64=zy;function Wy(e){let t=Ll();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"base64"));let r=Pk(e);if(t.atob){let n=t.atob(r);return Uint8Array.from(n,i=>i.charCodeAt(0))}return Ok(r)}Mr.base64ToBytes=Wy;function Lk(e){let t=[],r="",n=()=>{r+=String.fromCharCode(...t),t.length=0},i=o=>{if(o>65535){let s=o-65536;t.push(55296+(s>>10),56320+(s&1023))}else t.push(o);t.length>=cp&&n()},a=0;for(;a<e.length;){let o=e[a],s=0,l=0,u=128,c=191;if(o<128){i(o),a+=1;continue}else if(o>=194&&o<=223)s=1,l=o&31;else if(o>=224&&o<=239)s=2,l=o&15,u=o===224?160:128,c=o===237?159:191;else if(o>=240&&o<=244)s=3,l=o&7,u=o===240?144:128,c=o===244?143:191;else{i(65533),a+=1;continue}let d=a+1,p=!0;for(let f=0;f<s;f+=1,d+=1){let m=d<e.length?e[d]:-1;if(m<u||m>c){p=!1;break}u=128,c=191,l=l<<6|m&63}p?(i(l),a=d):(i(65533),a=d)}return n(),r}function Fk(e){let t=Ll();return t.Buffer?t.Buffer.from(e,"base64").toString("utf8"):Lk(Wy(e))}Mr.base64ToUtf8=Fk});var Ky=y(Br=>{"use strict";Object.defineProperty(Br,"__esModule",{value:!0});Br.deleteWebResource=Br.getWebResource=Br.updateWebResource=Br.createWebResource=void 0;var kk=hr(),Bo=Ee(),kl=le(),Mk=Fl(),jy=ee(),Bk={html:1,css:2,js:3,xml:4,png:5,jpg:6,gif:7,xsl:9,ico:10,svg:11,resx:12};function Hy(e){if(e.contentBase64!==void 0)return e.contentBase64;if(e.content!==void 0)return(0,Mk.utf8ToBase64)(e.content)}async function Jy(e,t){return(0,kk.publishWebResourceById)(e,t)}async function Uk(e,t){var r;let n=Hy(t);if(n===void 0)throw new jy.InvalidArgumentError(`web resource '${t.name}' requires content or contentBase64`);let i={name:t.name,displayname:(r=t.displayName)!==null&&r!==void 0?r:t.name,webresourcetype:Bk[t.type],content:n};t.description&&(i.description=t.description);let a=(0,Bo.ensureSuccess)(await e.post("/webresourceset",i),e.apiUrl("/webresourceset")),o=(0,Bo.readCreatedId)(a,"webresourceid");if(!o)throw new jy.InvalidArgumentError(`Dataverse did not return an id for web resource '${t.name}'`);return t.publish!==!1&&await Jy(e,o),{id:o,name:t.name}}Br.createWebResource=Uk;async function $k(e,t,r){let n=(0,kl.normalizeGuid)(t,"id"),i={},a=Hy(r);a!==void 0&&(i.content=a),r.displayName!==void 0&&(i.displayname=r.displayName),r.description!==void 0&&(i.description=r.description);let o=`/webresourceset(${n})`;(0,Bo.ensureSuccess)(await e.patch(o,i),e.apiUrl(o)),r.publish!==!1&&await Jy(e,n)}Br.updateWebResource=$k;async function qk(e,t){var r;let i=`/webresourceset(${(0,kl.normalizeGuid)(t,"id")})${(0,kl.odataQuery)([["$select","name,displayname,webresourcetype,content,description"]])}`;return(r=(0,Bo.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)!==null&&r!==void 0?r:{}}Br.getWebResource=qk;async function Vk(e,t){let n=`/webresourceset(${(0,kl.normalizeGuid)(t,"id")})`;(0,Bo.ensureSuccess)(await e.delete(n),e.apiUrl(n))}Br.deleteWebResource=Vk});var Ml=y(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.applyAppSettings=Xe.setAppSetting=Xe.readAppSettings=Xe.resolveSettingDefinitions=Xe.APP_SETTING_UNSET=Xe.APP_SETTING_OFF=Xe.APP_SETTING_ON=Xe.HEADER_AND_NAVIGATION_REFRESH=void 0;var ua=Ee(),un=le();Xe.HEADER_AND_NAVIGATION_REFRESH="HeaderAndNavigationRefresh";Xe.APP_SETTING_ON="2";Xe.APP_SETTING_OFF="1";Xe.APP_SETTING_UNSET="0";function Yy(e,t){return"/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,un.odataQuery)([["$select",e],["$filter",t]])}async function Zy(e,t){var r,n;let i=[...new Set(t.filter(Boolean))],a=new Map;if(i.length===0)return a;let o=i.map(c=>`uniquename eq '${(0,un.odataLiteral)(c)}'`).join(" or "),s=`/settingdefinitions${(0,un.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",o]])}`,u=((n=(r=(0,ua.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[]).filter(Boolean);for(let c of u)c.uniquename&&a.set(c.uniquename,c);return a}Xe.resolveSettingDefinitions=Zy;async function Gk(e,t){var r,n,i,a;let o=(0,un.normalizeGuid)(t,"App id"),s=Yy("appsettingid,value,_settingdefinitionid_value",`_parentappmoduleid_value eq ${o}`),u=((n=(r=(0,ua.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[]).filter(Boolean);if(u.length===0)return[];let c=[...new Set(u.map(p=>p._settingdefinitionid_value).filter(Boolean))],d=new Map;if(c.length>0){let p=c.map(h=>`settingdefinitionid eq ${(0,un.normalizeGuid)(h,"Setting definition id")}`).join(" or "),f=`/settingdefinitions${(0,un.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",p]])}`,m=(0,ua.ensureSuccess)(await e.get(f),e.apiUrl(f));for(let h of((a=(i=m.body)===null||i===void 0?void 0:i.value)!==null&&a!==void 0?a:[]).filter(Boolean))h.settingdefinitionid&&d.set(h.settingdefinitionid.toLowerCase(),h)}return u.map(p=>{var f,m,h,v,w;let C=d.get(((f=p._settingdefinitionid_value)!==null&&f!==void 0?f:"").toLowerCase());return{id:(m=p.appsettingid)!==null&&m!==void 0?m:"",name:(v=(h=C?.uniquename)!==null&&h!==void 0?h:p._settingdefinitionid_value)!==null&&v!==void 0?v:"",value:(w=p.value)!==null&&w!==void 0?w:"",...C?.displayname?{displayName:C.displayname}:{}}})}Xe.readAppSettings=Gk;async function Qy(e,t,r){var n,i,a;let o=Yy("appsettingid,value",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${r}`),l=((i=(n=(0,ua.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]).filter(Boolean)[0];return l?.appsettingid?{id:l.appsettingid,value:(a=l.value)!==null&&a!==void 0?a:""}:void 0}async function eb(e,t,r,n){let i=(0,un.normalizeGuid)(t,"App id"),o=(await Zy(e,[r])).get(r),s=o?.settingdefinitionid;if(!s)throw new Error(`App setting '${r}' is not available in this environment: no settingdefinition row has that uniquename. The feature may be version-gated or its solution may not be installed.`);let l=(0,un.normalizeGuid)(s,"Setting definition id"),u=await Qy(e,i,l);if(u)return Xy(e,u,n);let c="/appsettings",d={"[email protected]":`/appmodules(${i})`,"[email protected]":`/settingdefinitions(${l})`,value:n},p,f;try{if(p=await e.post(c,d),p.status>=200&&p.status<300)return"created"}catch(h){f=h}let m;try{m=await Qy(e,i,l)}catch{m=void 0}if(m)return Xy(e,m,n);throw p&&(0,ua.ensureSuccess)(p,e.apiUrl(c)),f}Xe.setAppSetting=eb;async function Xy(e,t,r){if(t.value===r)return"unchanged";let n=`/appsettings(${(0,un.normalizeGuid)(t.id,"App setting id")})`;return(0,ua.ensureSuccess)(await e.patch(n,{value:r}),e.apiUrl(n)),"updated"}async function zk(e,t,r){var n;let i=[];for(let[a,o]of Object.entries(r??{}))try{await eb(e,t,a,o)}catch(s){i.push(`App setting '${a}' was not applied: ${(n=s?.message)!==null&&n!==void 0?n:String(s)} The app was created; set it later with setAppSetting().`)}return i}Xe.applyAppSettings=zk});var Ul=y(Bl=>{"use strict";Object.defineProperty(Bl,"__esModule",{value:!0});Bl.HEADER_NAV_BOOLEAN_RULE=void 0;Bl.HEADER_NAV_BOOLEAN_RULE="headerAndNavigationRefresh-must-be-boolean"});var rb=y(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.deleteSolution=ne.importSolution=ne.exportSolution=ne.removeSolutionComponent=ne.addSolutionComponent=ne.setSolutionVersion=ne.createSolution=ne.createPublisher=ne.getSolution=ne.fetchSolutionComponents=ne.SolutionComponentType=void 0;var tb=$t(),gr=Ee(),Ot=le(),hi=ee();ne.SolutionComponentType={SavedQuery:26,Workflow:29,SavedQueryVisualization:59,SystemForm:60,AppModule:80,UxAgentProject:10372};var Wk=[ne.SolutionComponentType.SavedQuery,ne.SolutionComponentType.Workflow,ne.SolutionComponentType.SavedQueryVisualization,ne.SolutionComponentType.SystemForm,ne.SolutionComponentType.AppModule,ne.SolutionComponentType.UxAgentProject];async function jk(e,t){let r=(0,Ot.normalizeGuid)(t,"solutionId"),n=Wk.map(s=>`msdyn_componenttype eq ${s}`).join(" or "),i=`/msdyn_solutioncomponentsummaries${(0,Ot.odataQuery)([["$select","msdyn_objectid,msdyn_componenttype,msdyn_workflowcategory,msdyn_displayname,msdyn_name"],["$filter",`msdyn_solutionid eq ${r} and (${n})`]])}`,o=(await(0,tb.collectPages)(e,i,"fetchSolutionComponents")).filter(s=>typeof s.msdyn_objectid=="string").map(s=>({objectId:s.msdyn_objectid,componentType:Number(s.msdyn_componenttype),workflowCategory:s.msdyn_workflowcategory==null?void 0:Number(s.msdyn_workflowcategory),displayName:s.msdyn_displayname,name:s.msdyn_name}));return[...o,...await Hk(e,r,o)]}ne.fetchSolutionComponents=jk;async function Hk(e,t,r){let n=new Set(r.map(s=>s.objectId.toLowerCase())),i=`/solutioncomponents${(0,Ot.odataQuery)([["$select","objectid,componenttype"],["$filter",`_solutionid_value eq ${t} and componenttype eq ${ne.SolutionComponentType.UxAgentProject}`]])}`,a=await(0,tb.collectPages)(e,i,"fetchSolutionComponents(draft pages)"),o=[];for(let s of a){let l=typeof s.objectid=="string"?s.objectid:void 0;l&&!n.has(l.toLowerCase())&&(n.add(l.toLowerCase()),o.push({objectId:l,componentType:ne.SolutionComponentType.UxAgentProject}))}return o}function Jk(e){let t=e.length===38&&e.startsWith("{")&&e.endsWith("}")?e.slice(1,-1):e;return/^[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}$/.test(t)}async function Kk(e,t){var r,n,i,a,o,s,l,u,c,d;let p=String(t??"").trim();if(!p)throw new hi.InvalidArgumentError("getSolution: a solution unique name or id is required.");let f=Jk(p)?`solutionid eq ${(0,Ot.normalizeGuid)(p,"solutionId")}`:`uniquename eq '${(0,Ot.odataLiteral)(p)}'`,m=`/solutions${(0,Ot.odataQuery)([["$select","solutionid,uniquename,friendlyname,version,ismanaged"],["$expand","publisherid($select=publisherid,uniquename,customizationprefix,customizationoptionvalueprefix)"],["$filter",f]])}`,w=((n=(r=(0,gr.ensureSuccess)(await e.get(m),e.apiUrl(m)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0];if(!w?.solutionid)throw new hi.InvalidArgumentError(`No solution found for '${t}'.`);let C=w.publisherid;if(!C?.publisherid)throw new hi.InvalidArgumentError(`Solution '${(i=w.uniquename)!==null&&i!==void 0?i:t}' returned no owning publisher, so its customization prefix cannot be determined; refusing to report an empty prefix that could be mistaken for "no prefix".`);if(!("customizationprefix"in C))throw new hi.InvalidArgumentError(`Solution '${(a=w.uniquename)!==null&&a!==void 0?a:t}' returned a publisher without a customizationprefix property (partial expansion), so its prefix cannot be determined.`);return{solutionId:(0,Ot.normalizeGuid)(w.solutionid,"solutionId"),uniqueName:(o=w.uniquename)!==null&&o!==void 0?o:"",friendlyName:(s=w.friendlyname)!==null&&s!==void 0?s:"",version:(l=w.version)!==null&&l!==void 0?l:"",isManaged:!!w.ismanaged,publisherId:(0,Ot.normalizeGuid)(C.publisherid,"publisherId"),publisherUniqueName:(u=C.uniquename)!==null&&u!==void 0?u:"",publisherPrefix:(c=C.customizationprefix)!==null&&c!==void 0?c:"",publisherOptionValuePrefix:(d=C.customizationoptionvalueprefix)!==null&&d!==void 0?d:0}}ne.getSolution=Kk;async function Qk(e,t){var r;let n={uniquename:t.uniqueName,friendlyname:t.friendlyName,customizationprefix:t.prefix,customizationoptionvalueprefix:(r=t.optionValuePrefix)!==null&&r!==void 0?r:1e4};t.description&&(n.description=t.description);let i=(0,gr.ensureSuccess)(await e.post("/publishers",n),e.apiUrl("/publishers")),a=(0,gr.readCreatedId)(i,"publisherid");if(!a)throw new hi.InvalidArgumentError(`Dataverse did not return an id for publisher '${t.uniqueName}'`);return{id:a,uniqueName:t.uniqueName}}ne.createPublisher=Qk;async function Xk(e,t){var r;let n=(0,Ot.normalizeGuid)(t.publisherId,"publisherId"),i={uniquename:t.uniqueName,friendlyname:t.friendlyName,version:(r=t.version)!==null&&r!==void 0?r:"1.0.0.0","[email protected]":`/publishers(${n})`};t.description&&(i.description=t.description);let a=(0,gr.ensureSuccess)(await e.post("/solutions",i),e.apiUrl("/solutions")),o=(0,gr.readCreatedId)(a,"solutionid");if(!o)throw new hi.InvalidArgumentError(`Dataverse did not return an id for solution '${t.uniqueName}'`);return{id:o,uniqueName:t.uniqueName}}ne.createSolution=Xk;async function Yk(e,t,r){let i=`/solutions(${(0,Ot.normalizeGuid)(t,"solutionId")})`;(0,gr.ensureSuccess)(await e.patch(i,{version:r}),e.apiUrl(i))}ne.setSolutionVersion=Yk;async function Zk(e,t){var r;let i={ComponentId:(0,Ot.normalizeGuid)(t.componentId,"componentId"),ComponentType:t.componentType,SolutionUniqueName:t.solutionUniqueName,AddRequiredComponents:(r=t.addRequiredComponents)!==null&&r!==void 0?r:!1};t.doNotIncludeSubcomponents!==void 0&&(i.DoNotIncludeSubcomponents=t.doNotIncludeSubcomponents),(0,gr.ensureSuccess)(await e.post("/AddSolutionComponent",i),e.apiUrl("/AddSolutionComponent"))}ne.addSolutionComponent=Zk;async function eM(e,t,r,n){let a={SolutionComponent:{"@odata.type":"Microsoft.Dynamics.CRM.solutioncomponent",solutioncomponentid:(0,Ot.normalizeGuid)(t,"componentId")},ComponentType:r,SolutionUniqueName:n};(0,gr.ensureSuccess)(await e.post("/RemoveSolutionComponent",a),e.apiUrl("/RemoveSolutionComponent"))}ne.removeSolutionComponent=eM;async function tM(e,t){var r,n;let i={SolutionName:t.solutionName,Managed:(r=t.managed)!==null&&r!==void 0?r:!1},o=(n=(0,gr.ensureSuccess)(await e.post("/ExportSolution",i),e.apiUrl("/ExportSolution")).body)===null||n===void 0?void 0:n.ExportSolutionFile;if(!o)throw new hi.InvalidArgumentError(`ExportSolution returned no file for '${t.solutionName}'`);return{base64:o}}ne.exportSolution=tM;async function rM(e,t){var r,n;let i={OverwriteUnmanagedCustomizations:(r=t.overwriteUnmanagedCustomizations)!==null&&r!==void 0?r:!0,PublishWorkflows:(n=t.publishWorkflows)!==null&&n!==void 0?n:!0,CustomizationFile:t.base64};t.importJobId&&(i.ImportJobId=(0,Ot.normalizeGuid)(t.importJobId,"importJobId")),(0,gr.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution"))}ne.importSolution=rM;async function nM(e,t){let n=`/solutions(${(0,Ot.normalizeGuid)(t,"solutionId")})`;(0,gr.ensureSuccess)(await e.delete(n),e.apiUrl(n))}ne.deleteSolution=nM});var mp=y(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.compileGenPage=be.legacyEnumsNeeded=be.createGenPageTypeScriptLoader=be.acceptGenPageTypeScript=be.isLoadableGenPageOutput=be.GENPAGE_RUNTIME_TYPES_END=be.GENPAGE_RUNTIME_TYPES_BEGIN=be.GENPAGE_TYPESCRIPT_VERSION=void 0;var ca=ee();be.GENPAGE_TYPESCRIPT_VERSION="5.8.3";be.GENPAGE_RUNTIME_TYPES_BEGIN="// --- BEGIN GENERATED RUNTIME TYPES ---";be.GENPAGE_RUNTIME_TYPES_END="// --- END GENERATED RUNTIME TYPES ---";var iM=/(import\s+[^'"]+)(['"`])(\.\/RuntimeTypes)\2;?\s*/g,qn="./RuntimeTypes",aM=/\b(import\s.+from\s+['"]|import\s*['"]|export\s)/;function oM(e){return e!==void 0&&e!==""&&aM.test(e)}be.isLoadableGenPageOutput=oM;var nb=["transpileModule","createSourceFile","createProgram","getParseTreeNode","flattenDiagnosticMessageText","forEachChild","getModifiers","canHaveModifiers","isImportDeclaration","isExportDeclaration","isExportAssignment","isStringLiteral"];function ob(e){var t;let r=s=>s!==null&&(typeof s=="object"||typeof s=="function")?s:void 0,n=r(e);n&&typeof n.transpileModule!="function"&&(n=(t=r(n.default))!==null&&t!==void 0?t:n);let i=n?nb.filter(s=>typeof n?.[s]!="function"):[...nb];if(!n||i.length>0)throw new ca.SdkError("GENPAGE_COMPILER_INVALID",`The TypeScript compiler supplied as MakerSdkOptions.typescript is not the typescript module (missing ${i.join(", ")}). Pass the 'typescript' package's module object, loadNodeTypeScript from '@maker-studio/cds-maker-sdk/node', or \u2014 in a bare engine \u2014 globalThis.ts after evaluating typescript@${be.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js.`);let a=typeof n.version=="string"?n.version:"",o=be.GENPAGE_TYPESCRIPT_VERSION.split(".").slice(0,2).join(".");if(a.split(".").slice(0,2).join(".")!==o)throw new ca.SdkError("GENPAGE_COMPILER_VERSION",`The TypeScript compiler supplied as MakerSdkOptions.typescript is version '${a||"unknown"}', but generative pages are compiled with ${o}.x \u2014 the version the maker portal itself uses (${be.GENPAGE_TYPESCRIPT_VERSION}). Another version can emit different JavaScript for the same page. Supply typescript@${be.GENPAGE_TYPESCRIPT_VERSION}.`);return n}be.acceptGenPageTypeScript=ob;function sM(e){let t;return()=>{if(!t){if(e===void 0)return Promise.reject(new ca.SdkError("GENPAGE_COMPILER_UNAVAILABLE",`This push must compile a generative page, but no TypeScript compiler was supplied. Pass MakerSdkOptions.typescript \u2014 in Node, loadNodeTypeScript from '@maker-studio/cds-maker-sdk/node'; in a bare engine, globalThis.ts after evaluating typescript@${be.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js. Nothing was written.`));t=Promise.resolve().then(()=>typeof e=="function"?e():e).then(ob).catch(r=>{throw t=void 0,r instanceof ca.SdkError?r:new ca.SdkError("GENPAGE_COMPILER_UNAVAILABLE",`The TypeScript compiler could not be loaded, so a generative page cannot be compiled (${r instanceof Error?r.message:String(r)}). Nothing was written.`)})}return t}}be.createGenPageTypeScriptLoader=sM;var sb=e=>`${e.kind}:${e.pos}:${e.end}`;function lM(e,t){return()=>r=>{let n=i=>{let a=e.getParseTreeNode(i);a&&t.add(sb(a)),e.forEachChild(i,n)};return n(r),r}}function fp(e){return{target:e.ScriptTarget.ES5,module:e.ModuleKind.ES2020,jsx:e.JsxEmit.React}}function ib(e,t,r){var n;let i=e.transpileModule(t,{compilerOptions:fp(e),reportDiagnostics:!0,...r?{transformers:{after:[lM(e,r)]}}:{}}),a=((n=i.diagnostics)!==null&&n!==void 0?n:[]).filter(o=>o.category===e.DiagnosticCategory.Error).map(o=>{let s=o.file&&typeof o.start=="number"?o.file.getLineAndCharacterOfPosition(o.start):{line:0,character:0};return{line:s.line+1,column:s.character+1,rule:"genpage-source-syntax",code:o.code,message:e.flattenDiagnosticMessageText(o.messageText,`+`)}});return{code:i.outputText,diagnostics:a}}var ab=e=>e.startsWith(".")||e.startsWith("/"),dp={line:1,column:1};function pp(e,t){let r=a=>{let o=t.getLineAndCharacterOfPosition(a.getStart(t));return{line:o.line+1,column:o.character+1}},n=a=>(e.isImportDeclaration(a)||e.isExportDeclaration(a))&&a.moduleSpecifier&&e.isStringLiteral(a.moduleSpecifier)?a.moduleSpecifier.text:void 0,i=a=>t.statements.filter(o=>e.isImportDeclaration(o)&&n(o)===a);return{statement(a,o){let s=t.statements.find(l=>n(l)===a&&(o==="import"?e.isImportDeclaration(l):e.isExportDeclaration(l)));return s?r(s):dp},element(a,o){var s;for(let l of i(a)){let u=(s=l.importClause)===null||s===void 0?void 0:s.namedBindings,c=u&&e.isNamedImports(u)?u.elements.find(d=>d.name.text===o):void 0;if(c)return r(c)}return this.statement(a,"import")},binding(a){var o,s;for(let l of t.statements)if(e.isImportDeclaration(l)&&l.importClause){let u=l.importClause,c=u.namedBindings,d=((o=u.name)===null||o===void 0?void 0:o.text)===a?u.name:c&&e.isNamespaceImport(c)&&c.name.text===a?c.name:c&&e.isNamedImports(c)?c.elements.find(p=>p.name.text===a):void 0;if(d)return r(d)}else{if((e.isFunctionDeclaration(l)||e.isClassDeclaration(l))&&((s=l.name)===null||s===void 0?void 0:s.text)===a)return r(l.name);if(e.isVariableStatement(l)){let u=l.declarationList.declarations.find(c=>e.isIdentifier(c.name)&&c.name.text===a);if(u)return r(u.name)}}return dp}}}function uM(e,t,r,n){var i,a;let o=[],s=pp(e,r),l=(m,h,v)=>{o.push({...m,rule:h,code:0,message:v})},u=(m,h)=>{var v;return(e.canHaveModifiers(m)?(v=e.getModifiers(m))!==null&&v!==void 0?v:[]:[]).some(w=>w.kind===h)},c=(m,h)=>l(m,"genpage-relative-import",`'${h}' cannot resolve at runtime: the page is loaded as a single module from a blob URL, so the only relative import it may have is './RuntimeTypes'`),d="genpage-runtime-types-import-form",p=!1,f=new Set;for(let m of t.statements){if(e.isExportAssignment(m)){p=p||!m.isExportEquals;continue}if(e.isFunctionDeclaration(m)||e.isClassDeclaration(m)){u(m,e.SyntaxKind.ExportKeyword)&&u(m,e.SyntaxKind.DefaultKeyword)&&(p=!0),m.name&&f.add(m.name.text);continue}if(e.isExportDeclaration(m)){let C=m.exportClause;C&&e.isNamedExports(C)&&C.elements.some(D=>D.name.text==="default")&&(p=!0);let E=m.moduleSpecifier&&e.isStringLiteral(m.moduleSpecifier)?m.moduleSpecifier.text:void 0;E===qn?l(s.statement(E,"export"),d,"a page cannot re-export from './RuntimeTypes': that module does not exist at runtime"):E!==void 0&&ab(E)&&c(s.statement(E,"export"),E);continue}if(!e.isImportDeclaration(m)||!e.isStringLiteral(m.moduleSpecifier))continue;let h=m.moduleSpecifier.text,v=m.importClause;if(h!==qn){ab(h)&&c(s.statement(h,"import"),h),v?.name&&f.add(v.name.text);let C=v?.namedBindings;C&&e.isNamespaceImport(C)?f.add(C.name.text):C&&e.isNamedImports(C)&&C.elements.forEach(E=>f.add(E.name.text));continue}if(!v){l(s.statement(h,"import"),d,"a side-effect import of './RuntimeTypes' cannot resolve at runtime; import the names it declares");continue}v.name&&l(s.binding(v.name.text),d,"'./RuntimeTypes' has no default export at runtime; import its names");let w=v.namedBindings;if(w&&e.isNamespaceImport(w))l(s.binding(w.name.text),d,"a namespace import of './RuntimeTypes' is undefined at runtime \u2014 its enums are inlined under their own names; import the names instead");else if(w&&e.isNamedImports(w))for(let C of w.elements){let E=C.name.text,D=(a=(i=C.propertyName)===null||i===void 0?void 0:i.text)!==null&&a!==void 0?a:E,O=s.element(h,E);D!==E?l(O,d,`'${D} as ${E}' would be undefined at runtime: the enum is inlined as '${D}', so import it under its own name`):n?.text?n.enums.has(E)||l(O,"genpage-runtime-types-unresolved",`'${E}' is imported from './RuntimeTypes' as a VALUE, but the runtime types define no value of that name \u2014 only the choice enums of the page's data sources are values. Import a type with 'import type'.`):l(O,"genpage-runtime-types-unresolved",`'${E}' is imported from './RuntimeTypes' as a VALUE, but the page has no data sources, so no runtime types are inlined and the import reaches the runtime, which cannot load it. Import it with 'import type', or add the table it belongs to to dataSources.`)}}if(p||l(dp,"genpage-no-default-export","the page has no default export \u2014 the runtime renders the module's default export as the page component"),n?.text)for(let m of f)n.enums.has(m)&&l(s.binding(m),"genpage-runtime-types-collision",`'${m}' is declared at the page's module scope and is also one of its inlined choice enums, so the compiled page would declare it twice and fail to load. Rename the page's binding, or import the enum from './RuntimeTypes'.`);return o}function lb(e,t,r){let n,i=()=>{if(!n){let c={getSourceFile:p=>p===t.fileName?t:void 0,getDefaultLibFileName:()=>"lib.d.ts",writeFile:()=>{},getCurrentDirectory:()=>"",getCanonicalFileName:p=>p,useCaseSensitiveFileNames:()=>!0,getNewLine:()=>`+`,fileExists:p=>p===t.fileName,readFile:()=>{},directoryExists:()=>!0,getDirectories:()=>[]},d={...r,noLib:!0,noResolve:!0,allowJs:!0,types:[],alwaysStrict:!0,moduleDetection:e.ModuleDetectionKind.Force};n=e.createProgram({rootNames:[t.fileName],options:d,host:c}).getTypeChecker()}return n},a=c=>e.isImportSpecifier(c)?c.parent.parent.parent:e.isImportClause(c)?c.parent:e.isNamespaceImport(c)?c.parent.parent:void 0,o=c=>{let d=a(c);return d!==void 0&&e.isImportDeclaration(d)&&e.isStringLiteral(d.moduleSpecifier)&&d.moduleSpecifier.text===qn},s=c=>{var d;for(let p=c;p;p=p.parent)if(e.canHaveModifiers(p)&&((d=e.getModifiers(p))!==null&&d!==void 0?d:[]).some(f=>f.kind===e.SyntaxKind.DeclareKeyword))return!0;return!1},l=c=>s(c)||e.isImportEqualsDeclaration(c)&&(c.isTypeOnly||e.isExternalModuleReference(c.moduleReference))||e.isImportClause(c)&&c.isTypeOnly||e.isNamespaceImport(c)&&c.parent.isTypeOnly||e.isImportSpecifier(c)&&(c.isTypeOnly||c.parent.parent.isTypeOnly),u=c=>{var d;return((d=c?.declarations)!==null&&d!==void 0?d:[]).some(p=>!o(p)&&!l(p))};return{pageOwns:c=>{let d=c.parent;return u(e.isShorthandPropertyAssignment(d)&&d.name===c?i().getShorthandAssignmentValueSymbol(d):i().getSymbolAtLocation(c))},pageOwnsLocalExport:c=>u(i().getExportSpecifierLocalTargetSymbol(c))}}function cM(e,t,r,n){let i=[],a=r?.enums;if(!a||a.size===0)return i;let o=(u,c,d)=>{let p=t.getLineAndCharacterOfPosition(u.getStart(t));i.push({line:p.line+1,column:p.character+1,rule:c,code:0,message:d})},s=lb(e,t,fp(e)),l=u=>{let c,d;if(e.isPropertyAccessExpression(u)&&e.isIdentifier(u.expression))c=u.expression,d=u.name.text;else if(e.isElementAccessExpression(u)&&e.isIdentifier(u.expression)){let f=u.argumentExpression;e.isStringLiteral(f)||e.isNoSubstitutionTemplateLiteral(f)?(c=u.expression,d=f.text):e.isNumericLiteral(f)&&(c=u.expression,d=String(Number(f.text)))}let p=c&&a.has(c.text)&&n.has(sb(u))&&!s.pageOwns(c)?a.get(c.text):void 0;if(c&&p&&d!==void 0){let f=e.isPropertyAccessExpression(u)?`${p.name}.${d}`:`${p.name}[${JSON.stringify(d)}]`,m=Object.prototype.hasOwnProperty.call(p.runtime,d)?p.runtime[d]:void 0,h=p.labels.get(d);m===void 0?o(u,"genpage-enum-member-unknown",`${f} is undefined at runtime: '${p.name}' has no member '${d}' in this environment's metadata \u2014 members are the column's choice labels, so a renamed or differently localized label no longer matches. Known: ${[...p.labels.keys()].map(v=>`'${v}'`).join(", ")}`):h&&typeof m!="number"?o(u,"genpage-enum-member-clobbered",`${f} is the string '${String(m)}' at runtime, not a choice value: the label '${d}' looks like a number, and another option's reverse mapping overwrites it. Use the choice's numeric value instead.`):h&&h.length>1&&o(u,"genpage-enum-member-ambiguous",`${f} labels more than one choice (${h.join(", ")}); the compiled value is whichever option comes last. Use the choice's numeric value instead.`)}e.forEachChild(u,l)};return l(t),i}function dM(e,t){return e.createSourceFile("page.js",t,e.ScriptTarget.ES2020,!1,e.ScriptKind.JS).statements.some(n=>(e.isImportDeclaration(n)||e.isExportDeclaration(n))&&n.moduleSpecifier!==void 0&&e.isStringLiteral(n.moduleSpecifier)&&n.moduleSpecifier.text===qn)}function pM(e,t){let r=e.createSourceFile("page.js",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),n=new Set(r.statements.filter(o=>e.isImportDeclaration(o)&&e.isStringLiteral(o.moduleSpecifier)&&o.moduleSpecifier.text===qn).map(o=>o.getStart(r))),i=!0;return{code:t.replace(iM,(...o)=>(n.has(o[o.length-2])||(i=!1),"")),exact:i}}function ub(e,t,r){if(!r||r.size===0)return[];let n=lb(e,t,{...fp(e),target:e.ScriptTarget.ESNext}),i=new Set,a=s=>{var l,u;let c=s.parent;if(e.isImportSpecifier(c)){let d=c.parent.parent.parent;e.isImportDeclaration(d)&&e.isStringLiteral(d.moduleSpecifier)&&d.moduleSpecifier.text===qn&&((l=c.propertyName)!==null&&l!==void 0?l:c.name)===s&&i.add(s.text);return}if(e.isExportSpecifier(c)){!(c.parent.parent.moduleSpecifier!==void 0)&&((u=c.propertyName)!==null&&u!==void 0?u:c.name)===s&&!n.pageOwnsLocalExport(c)&&i.add(s.text);return}e.isPropertyAccessExpression(c)&&c.name===s||e.isBindingElement(c)&&c.propertyName===s||e.isLabeledStatement(c)||e.isBreakOrContinueStatement(c)||n.pageOwns(s)||i.add(s.text)},o=s=>{e.isIdentifier(s)&&r.has(s.text)&&a(s),e.forEachChild(s,o)};return o(t),[...r.keys()].filter(s=>i.has(s))}be.legacyEnumsNeeded=ub;function fM(e,t,r){if(!e?.text||!t||r.length===0)return e;let n=new Map(e.enums),i=e.text;for(let a of r){let o=t.get(a);o&&(i+=o.declaration,n.set(a,o.model))}return{text:i,enums:n}}function mM(e,t,r,n){let i=new Set,a=ib(e,t,i);if(a.diagnostics.length>0)return a;let o=e.createSourceFile("page.tsx",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.TSX),s=e.createSourceFile("page.js",a.code,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),l=fM(r,n,ub(e,s,n)),u=[...uM(e,s,o,l),...cM(e,o,l,i)];if(!l?.text)return{code:a.code,diagnostics:u};let c=ib(e,l.text);if(c.diagnostics.length>0)throw new ca.SdkError("GENPAGE_RUNTIME_TYPES_INVALID",`The generated runtime types do not compile (${c.diagnostics.map(m=>`${m.line}:${m.column} ${m.message}`).join("; ")}). This is an SDK defect: the page was not written.`);let d=pM(e,a.code),p=d.code;return u.length===0&&!d.exact?u.push({...pp(e,o).statement(qn,"import"),rule:"genpage-runtime-types-import-form",code:0,message:"the maker portal's patch would remove more than this './RuntimeTypes' import: a comment or other text before it contains the word 'import', and the pattern would delete from there \u2014 taking the code in between with it. Reword or move that text."}):u.length===0&&dM(e,p)&&u.push({...pp(e,o).statement(qn,"import"),rule:"genpage-runtime-types-import-form",code:0,message:"this './RuntimeTypes' import is not one the maker portal's patch can remove (a comment holding a quote inside it stops the pattern), so it would reach the runtime, which cannot load it. Write it on one line, as 'import { name } from './RuntimeTypes';'."}),{code:[be.GENPAGE_RUNTIME_TYPES_BEGIN,c.code,be.GENPAGE_RUNTIME_TYPES_END,p].join(`++`),diagnostics:u}}be.compileGenPage=mM});var ql=y(Vn=>{"use strict";Object.defineProperty(Vn,"__esModule",{value:!0});Vn.appApi=Vn.deleteAppResolvingOnce=Vn.unpublishedAppModulesQuery=void 0;var wp=$t(),hM=Sp(),cb=hr(),gM=Ml(),ge=Ee(),ae=le(),bp=st(),vM=dl(),ve=ee(),yM=(0,ae.odataQuery)([["$select","appmoduleid,name,uniquename,description,aiappdescription"]]),hp="appmoduleid,name,uniquename,description,aiappdescription";function vb(e,t,r){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,ae.odataQuery)([["$select",e],["$filter",t],["$top",r]])}Vn.unpublishedAppModulesQuery=vb;function gp(e,t){return vb(e,t?`appmoduleid eq ${t}`:void 0,t?1:void 0)}function $l(e,t){return"/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,ae.odataQuery)([["$select",t],["$filter",`sitemapid eq ${e}`],["$top",1]])}function da(e){var t;let r=(t=e.body)===null||t===void 0?void 0:t.value;if(Array.isArray(r))return r[0]}function bM(e){let t=e?.["@odata.etag"];return typeof t=="string"?t:null}function Ap(e,t){if(typeof e!="string")return!1;try{return(0,ae.normalizeGuid)(e,"sitemapid")===t}catch{return!1}}function Uo(e){let t=new Set,r=[];for(let n of e??[])n&&!t.has(n)&&(t.add(n),r.push(n));return r}function wM(e){return`cdsapp_${(e||"").replace(/[^a-zA-Z0-9]/g,"")||"app"}`}async function yb(e,t){var r,n;let i=u=>{throw new ve.SdkError("APP_SITEMAP_UNRESOLVED",`The sitemap lookup for app uniquename '${t??""}' ${u}, so it cannot be determined whether this app has a sitemap. Retry; if the app is newly created, publish it first (an unpublished app is not readable).`)};if(!t)return i("cannot run because the app record carried no uniquename");let a=`/sitemaps${(0,ae.odataQuery)([["$select","sitemapid"],["$filter",`sitemapnameunique eq '${(0,ae.odataLiteral)(t)}'`],["$top",1]])}`,o;try{o=await e.get(a)}catch(u){return i(`failed (${u.message})`)}if(o.status<200||o.status>=300)return i(`returned HTTP ${o.status}`);let s=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(s))return i("returned a malformed body");let l=(n=s[0])===null||n===void 0?void 0:n.sitemapid;return s.length>0&&!l?i("returned a row with no sitemapid"):l}async function AM(e){let t=s=>{var l,u,c;return(c=(u=(l=s.body)===null||l===void 0?void 0:l.value)===null||u===void 0?void 0:u[0])===null||c===void 0?void 0:c.webresourceid},r=s=>`/webresourceset${(0,ae.odataQuery)([["$select","webresourceid"],["$top",1],["$filter",s]])}`,n="(webresourcetype eq 5 or webresourcetype eq 6 or webresourcetype eq 7 or webresourcetype eq 10 or webresourcetype eq 11)",i=t(await e.get(r("webresourcetype eq 5 and ismanaged eq false and contains(name,'icon')")));if(i)return{id:i,managed:!1};let a=t(await e.get(r(`${n} and ismanaged eq false`)));if(a)return{id:a,managed:!1};let o=t(await e.get(r(n)));return o?{id:o,managed:!0}:void 0}function Cp(e){return e instanceof Error?e.message:String(e)}async function CM(e,t){var r,n,i;try{let a=`/roles${(0,ae.odataQuery)([["$select","roleid"],["$filter","name eq 'System Administrator'"],["$top",1]])}`,s=(i=(n=(r=(0,ge.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||r===void 0?void 0:r.value)===null||n===void 0?void 0:n[0])===null||i===void 0?void 0:i.roleid;if(!s)return"App roles: no 'System Administrator' role was found in this environment, so the app was created with NO security role associated \u2014 it will not be visible or playable until a role is granted access to it.";let l=`/appmodules(${t})/appmoduleroles_association/$ref`;return(0,ge.ensureSuccess)(await e.post(l,{"@odata.id":e.apiUrl(`/roles(${s})`)}),e.apiUrl(l)),null}catch(a){return`App roles: could not associate the 'System Administrator' role with the app (${Cp(a)}); it will not be visible or playable until a role is granted access to it.`}}async function EM(e,t){let r=[];async function n(s,l,u){try{return(await(0,wp.collectPages)(e,s,`app assets (${u} for '${t}')`)).map(d=>String(d[l])).filter(d=>d&&d!=="undefined")}catch(c){return r.push(`App components: could not enumerate ${u} for table '${t}' (${Cp(c)}); they were NOT added to the app.`),[]}}let[i,a,o]=await Promise.all([n(`/systemforms${(0,ae.odataQuery)([["$select","formid"],["$filter",`objecttypecode eq '${(0,ae.odataLiteral)(t)}' and type eq 2 and formactivationstate eq 1`]])}`,"formid","forms"),n(`/savedqueries${(0,ae.odataQuery)([["$select","savedqueryid"],["$filter",`returnedtypecode eq '${(0,ae.odataLiteral)(t)}' and querytype eq 0 and statecode eq 0`]])}`,"savedqueryid","views"),n(`/savedqueryvisualizations${(0,ae.odataQuery)([["$select","savedqueryvisualizationid"],["$filter",`primaryentitytypecode eq '${(0,ae.odataLiteral)(t)}'`]])}`,"savedqueryvisualizationid","charts")]);return{forms:i,views:a,charts:o,warnings:r}}var db=new WeakMap;async function SM(e,t){let r=db.get(e);r||(r=new Map,db.set(e,r));let n=r.get(t);if(n!==void 0)return n;let i=await NM(e,t);return i&&r.set(t,i),i}async function pb(e,t,r){let n=new Array(e.length),i=0;async function a(){for(let o=i;o<e.length;o=i)i=o+1,n[o]=await r(e[o])}return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>a())),n}async function NM(e,t){let r=`/EntityDefinitions(LogicalName='${(0,ae.odataPathLiteral)(t)}')${(0,ae.odataQuery)([["$select","MetadataId,EntitySetName"]])}`,n=await e.get(r);if(n.status>=200&&n.status<300){let i=n.body;if(i?.MetadataId&&i.EntitySetName)return{logicalName:t,metadataId:i.MetadataId,entitySetName:i.EntitySetName}}}async function fb(e,t){let r=[],n=Uo(t.entities),i=4,a=await pb(n,i,f=>SM(e,f)),o=n.filter((f,m)=>!a[m]);if(o.length>0)throw new ve.SdkError("APP_ENTITY_COMPONENT_UNRESOLVED",`Refusing to build app components: table(s) ${o.map(f=>`'${f}'`).join(", ")} could not be resolved to an EntityDefinitions MetadataId + EntitySetName. Pinning the rest would produce an app whose navigation references a table the app does not contain. Verify the table name(s) exist in this environment and retry.`);let s=a.filter(f=>!!f);for(let f of s)r.push({"@odata.id":`${f.entitySetName}(${f.metadataId})`});for(let f of Uo(t.components.forms))r.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:f});for(let f of Uo(t.components.views))r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:f});for(let f of Uo(t.components.charts))r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:f});for(let f of Uo(t.components.dashboards))r.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:f});let l=new Set(t.components.forms),u=new Set(t.components.views),c=new Set(t.components.charts),d=await pb(n,i,f=>EM(e,f)),p=d.flatMap(f=>f.warnings);for(let f of d){for(let m of f.forms)l.has(m)||(l.add(m),r.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:m}));for(let m of f.views)u.has(m)||(u.add(m),r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:m}));for(let m of f.charts)c.has(m)||(c.add(m),r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:m}))}return{components:r,tables:s,warnings:p}}async function mb(e,t,r){if(r.length===0)return;let n="/AddAppComponents";(0,ge.ensureSuccess)(await e.post(n,{AppId:t,Components:r}),e.apiUrl(n))}function DM(e){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,ae.odataQuery)([["$select","appmoduleid,appmoduleidunique"],["$filter",`appmoduleid eq ${e}`],["$top",1]])}async function hb(e,t,r){var n;if(r.length===0)return;let i=DM(t),a=await e.get(i);if(a.status<200||a.status>=300)throw new ve.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its components were written but could not be verified \u2014 the unpublished-aware read returned HTTP ${a.status}. Re-push to retry.`);let o=da(a),s=o?.appmoduleidunique;if(typeof s!="string"||!s)throw new ve.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its components were written but could not be verified \u2014 the app did not return an 'appmoduleidunique' to file components under. Re-push to retry.`);let l=`/appmodulecomponents${(0,ae.odataQuery)([["$select","objectid,componenttype"],["$filter",`_appmoduleidunique_value eq ${(0,ae.normalizeGuid)(s,`App '${t}' appmoduleidunique`)} and componenttype eq 1`]])}`,u=await e.get(l);if(u.status<200||u.status>=300)throw new ve.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its table components were written but could not be verified \u2014 reading them back returned HTTP ${u.status}. Re-push to retry.`);let c=(n=u.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(c))throw new ve.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its table components were written but could not be verified \u2014 the read-back returned no readable result set. Re-push to retry.`);let d=new Set(c.map(f=>f.objectid).filter(f=>typeof f=="string").map(f=>f.toLowerCase())),p=r.filter(f=>!d.has(f.metadataId.toLowerCase()));if(p.length>0)throw new ve.SdkError("APP_COMPONENTS_NOT_PERSISTED",`App '${t}': ${p.length} declared table(s) are NOT components of the app after AddAppComponents reported success \u2014 ${p.map(f=>`'${f.logicalName}' (expected objectid ${f.metadataId})`).join(", ")}. The app's navigation would reference content the app does not contain.`)}async function IM(e,t,r){let n=`/appmodules(${t})`,i=`/sitemaps(${r.sitemapId})`;try{let a=await _M(e,r.sitemapId,r.sitemapNameUnique);if(a==="absent"){r.serverRefusedSitemap&&(0,ge.ensureSuccess)(await e.delete(n),e.apiUrl(n));return}if(a==="foreign"){r.serverRefusedSitemap&&(0,ge.ensureSuccess)(await e.delete(n),e.apiUrl(n));return}if(e.supportsAtomicBatch){if(!r.sitemapWriteToken)return;await wb(e,[{path:n},{path:i,etag:r.sitemapWriteToken}])}}catch{}}async function _M(e,t,r){var n,i,a;let o=$l(t,"sitemapid,sitemapnameunique"),s=await e.get(o);if(s.status<200||s.status>=300)throw new ve.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned HTTP ${s.status}, so it cannot be determined whether the row exists.`);let l=(n=s.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(l))throw new ve.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned no readable result set, so it cannot be determined whether the row exists.`);return l.length===0?"absent":String((a=(i=l[0])===null||i===void 0?void 0:i.sitemapnameunique)!==null&&a!==void 0?a:"")===r?"ours":"foreign"}async function bb(e,t){var r;let n=(0,ae.normalizeGuid)(t,"id"),i=h=>{throw new ve.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to delete app '${n}': ${h} Deleting the app would destroy the only pointer to its sitemap, stranding that row and reserving its unique name forever. Retry; if the app is newly created, publish it first (an unpublished app is not readable).`)},a=`/appmodules(${n})${yM}`,o;try{o=await e.get(a)}catch(h){return i(`reading the app failed (${h.message}).`)}if(o.status<200||o.status>=300)return i(o.status===404?"reading the app returned HTTP 404, which does NOT prove it is absent \u2014 Dataverse also reports an unpublished app that way, and such an app still owns a sitemap.":`reading the app returned HTTP ${o.status}.`);let s=(r=o.body)===null||r===void 0?void 0:r.uniquename;if(!s)return i("the app record carried no uniquename, so its sitemap cannot be located.");let l=await yb(e,s);if(!l)return{uniquename:s,appEtag:(0,ge.readEtag)(o)};let u=(0,ae.normalizeGuid)(l,"sitemapId"),c=await Ep(e,u),d=$l(u,"sitemapid,sitemapnameunique,sitemapxml"),p;try{p=await e.get(d)}catch(h){return i(`reading sitemap '${u}' failed (${h.message}).`)}if(p.status<200||p.status>=300)return i(`reading sitemap '${u}' returned HTTP ${p.status}.`);let f=da(p);if(!f)return i(`sitemap '${u}' was not returned by the unpublished-aware read.`);if(f.sitemapnameunique!==s)return i(`sitemap '${u}' now carries sitemapnameunique '${String(f.sitemapnameunique)}', not '${s}', so it is no longer this app's sitemap.`);if(!Ap(f.sitemapid,u))return i(`sitemap '${u}' was read back as a row carrying sitemapid '${String(f.sitemapid)}'.`);let m=f.sitemapxml;return typeof m!="string"?i(`sitemap '${u}' returned no sitemapxml.`):{sitemapId:u,uniquename:s,sitemapXml:m,appEtag:(0,ge.readEtag)(o),sitemapEtag:c}}async function TM(e,t,r){let n=(0,ae.normalizeGuid)(t,"id"),i=await bb(e,n);await r?.(i.sitemapXml),await Ab(e,n,i)}Vn.deleteAppResolvingOnce=TM;async function wb(e,t){let r=`batch_${(0,bp.newId)()}`,n=`changeset_${(0,bp.newId)()}`,i=t.map((d,p)=>[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${p+1}`,"",`DELETE ${e.apiUrl(d.path)} HTTP/1.1`,...d.etag?[`If-Match: ${d.etag}`]:[],""].join(`\r`)),a=[`--${r}`,`Content-Type: multipart/mixed;boundary=${n}`,"",...i,`--${n}--`,`--${r}--`,""].join(`\r-`),o=await e.postBatch(a,r),s=e.apiUrl("/$batch");(0,fe.ensureSuccess)(o,s);let l=`app '${t[0].path}'`;if(typeof o.body!="string"||o.body.length===0)throw new me.ConnectionError(s,o.status,`atomic delete of ${l} cannot be confirmed: the $batch response had no readable body, so the change set's outcome is unknown`);let u=(0,oL.parseChangeSetStatuses)(o.body,i.map((d,p)=>String(p+1)));if(u===void 0)throw new me.ConnectionError(s,o.status,`atomic delete of ${l} cannot be confirmed: the $batch response could not be parsed as a change set, so the outcome is unknown`);let c=u.find(d=>d<200||d>=300);if(c!==void 0)throw new me.ConnectionError(s,c,`atomic delete of ${l} was rolled back: the change set reported HTTP ${c}`);if(u.length!==i.length)throw new me.ConnectionError(s,o.status,`atomic delete of ${l} cannot be confirmed: the $batch response reported ${u.length} operation result(s), expected exactly ${i.length}`)}async function Fd(e,t){try{let r=await e.get(`/sitemaps(${t})?$select=sitemapid`);return r.status<200||r.status>=300?null:(0,fe.readEtag)(r)}catch{return null}}async function Id(e,t,r,n){if(!n)return null;let i=await Fd(e,t);if(!i)return null;try{let a=await e.get(fl(t,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"));if(a.status<200||a.status>=300)return null;let o=Ji(a);return!o||!Od(o.sitemapid,t)||o.sitemapnameunique!==n||o.sitemapxml!==r.sitemapxml||o.sitemapname!==r.sitemapname?null:i}catch{return null}}function bL(e){return e>=400&&e<500&&e!==408&&e!==429}function _d(e,t,r){if(!e)throw new me.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to delete app '${t}': the ${r} read returned no ETag, so the delete cannot be made conditional on the row that was actually inspected. Without that condition a row renamed or re-pointed between the read and the delete would be destroyed. Retry.`);return e}async function oy(e,t,r){let n=`/appmodules(${t})`;if(!r.sitemapId){await wL(e,n,_d(r.appEtag,t,"app"));return}if(!e.supportsAtomicBatch)throw new me.SdkError("APP_DELETE_NOT_ATOMIC",`Refusing to delete app '${t}': it owns a sitemap, and the injected HttpClient cannot send a raw body, so the two rows would have to be deleted as separate requests. A failure between them strands the sitemap and permanently reserves the app's unique name. Implement HttpClient.postRaw so the SDK can delete them atomically.`);await ay(e,[{path:n,etag:_d(r.appEtag,t,"app")},{path:`/sitemaps(${r.sitemapId})`,etag:_d(r.sitemapEtag,t,"sitemap")}])}async function wL(e,t,r){(0,fe.ensureSuccess)(await e.delete(t,{headers:{"If-Match":r}}),e.apiUrl(t))}async function ty(e,t){if(!/GenPageId/i.test(t))return;let r;try{r=[...new Set((0,iL.collectGenPageIds)(t))]}catch(o){throw new me.SdkError("SITEMAP_TARGET_UNVERIFIABLE",`Refusing to push the app: its sitemap xml could not be parsed, so the generative pages it navigates to cannot be verified (${Rd(o)}).`)}if(r.length===0)return;let n=new Set,i=50;for(let o=0;o<r.length;o+=i){let s=r.slice(o,o+i),l="/uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,ne.odataQuery)([["$select","uxagentprojectid"],["$filter",s.map(c=>`uxagentprojectid eq ${c}`).join(" or ")]]),u=await(0,Pd.collectPages)(e,l,"sitemap generative-page preflight");for(let c of u){let d=c.uxagentprojectid;typeof d=="string"&&d.trim()!==""&&n.add((0,ne.normalizeGuid)(d,"uxagentprojectid"))}}let a=r.filter(o=>!n.has(o));if(a.length>0)throw new me.SdkError("SITEMAP_TARGET_NOT_FOUND",`Refusing to push the app: its sitemap navigates to generative page(s) ${a.map(o=>`'${o}'`).join(", ")} that do not exist in this environment. Push the page before the app that links to it.`)}function AL(e){var t,r;if(e.status!==400)return!1;let n=e.body;return String((r=(t=n?.error)===null||t===void 0?void 0:t.message)!==null&&r!==void 0?r:"").includes("retrieval of version numbers failed")}Rn.appApi={async get(e,t){var r;let n=(0,ne.normalizeGuid)(t,"id"),i=Dd(Nd,n),a=(0,fe.ensureSuccess)(await e.get(i),e.apiUrl(i)),o=(r=Ji(a))!==null&&r!==void 0?r:{};if(!o.appmoduleid)throw new me.SdkError("APP_NOT_FOUND",`App '${n}' was not found (checked the unpublished-aware projection, which includes drafts).`);let s=await ny(e,o.uniquename),l=s?(0,ne.normalizeGuid)(s,"sitemapId"):void 0,u=null;if(l){u=await Fd(e,l);let d=fl(l,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"),p=(0,fe.ensureSuccess)(await e.get(d),e.apiUrl(d)),f=Ji(p),m=g=>{throw new me.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${n}': its sitemap '${l}' was located by unique name, but ${g}, so the sitemap cannot be read. Persisting the app without it would misreport it as having no sitemap, or write an empty one over its navigation. Retry.`)};if(!f)return m("the by-id read returned no row");if(f.sitemapnameunique!==o.uniquename)throw new me.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${n}': sitemap '${l}' now carries sitemapnameunique '${String(f.sitemapnameunique)}', not '${String(o.uniquename)}', so it is no longer this app's sitemap. Retry.`);if(!Od(f.sitemapid,l))return m(`the by-id read returned a row carrying sitemapid '${String(f.sitemapid)}'`);if(typeof f.sitemapxml!="string")return m("the by-id read returned no sitemapxml");o.$sitemap=f}let c=lL(o);return{raw:o,etag:u,...o.appmoduleid?{siblingEtags:{[(0,ne.normalizeGuid)(o.appmoduleid,"appmoduleid")]:c}}:{}}},async list(e,t){let r=Dd(Nd);return(await(0,Pd.collectPages)(e,r,"listArtifacts('app')")).map(i=>{var a,o;return{type:"app",id:(a=i.appmoduleid)!==null&&a!==void 0?a:"",name:(o=i.name)!==null&&o!==void 0?o:"",isDirty:!1}})},async create(e,t,r){let n=t;await ty(e,n.sitemapxml);let i=n.iconWebResourceId?void 0:await cL(e),a=n.iconWebResourceId||i?.id;if(!a)throw new me.SdkError("APP_ICON_UNRESOLVED",`Cannot create app '${n.appModuleName}': its icon (\`appmodule.webresourceid\`) is a REQUIRED attribute and this environment has no image web resource to use. Pass \`iconWebResourceId\` explicitly, or add an image (PNG/JPG/GIF/ICO/SVG) web resource to the environment.`);let o=null;i?.managed&&(o=`No unmanaged image web resource was available, so the app icon resolved to a MANAGED one (${i.id}). That creates a cross-solution dependency which can fail to import into an environment without the owning managed solution. Pass \`iconWebResourceId\` with an in-solution image to avoid it.`);let s=n.appModuleUniqueName||uL(n.appModuleId),l={name:n.appModuleName,uniquename:s,clienttype:4,formfactor:1,navigationtype:0};n.appModuleDescription&&(l.description=n.appModuleDescription),n.appModuleAiDescription&&(l.aiappdescription=n.appModuleAiDescription),a&&(l.webresourceid=a);let u="/appmodules",c=(0,fe.ensureSuccess)(await e.post(u,(0,fe.withClientMintedId)(l,"appmoduleid",r)),e.apiUrl(u)),d=(0,fe.resolveCreatedId)(c,"appmoduleid","app module",r),p=null,f=null,m=[];o&&m.push(o);let g={kind:"notRequested"},y=n.sitemapId?(0,ne.normalizeGuid)(n.sitemapId,"sitemapId"):(0,Td.newId)(),A=!1,D={sitemapxml:n.sitemapxml,sitemapname:n.sitemapname};try{let _="/sitemaps",q=(0,fe.echoWrite)("sitemapid"),B=await e.post(`${_}${q.query}`,{sitemapid:y,sitemapnameunique:s,...D},q.options);A=bL(B.status);let L=(0,fe.ensureSuccess)(B,e.apiUrl(_));f=(0,fe.readEtag)(L),p=f??await Id(e,y,D,s);let k=await Yv(e,n);m.push(...k.warnings);let M=k.components;M.unshift({"@odata.type":"Microsoft.Dynamics.CRM.sitemap",sitemapid:y}),await Zv(e,d,M),await ey(e,d,k.tables);let G=await dL(e,d);G&&m.push(G),n.appSettings&&Object.keys(n.appSettings).length>0&&m.push(...await(0,aL.applyAppSettings)(e,d,n.appSettings)),n.published!==!1&&(await(0,Qv.publishAppModule)(e,d),g={kind:"submitted"})}catch(_){throw await gL(e,d,{sitemapId:y,sitemapNameUnique:s,serverRefusedSitemap:A,sitemapWriteToken:f}),_}let F=null;if(g.kind==="submitted")try{let _=await e.get(`/appmodules(${d})?$select=appmoduleid`);_.status>=200&&_.status<300&&(F=(0,fe.readEtag)(_))}catch{}return{id:d,etag:p,serverIdentity:{sitemapId:y},siblingEtags:{[d]:F},publish:g,...m.length>0?{warnings:m}:{}}},async update(e,t,r,n,i,a){var o,s,l,u,c,d,p,f,m;let g=r,y=(0,ne.normalizeGuid)(t,"id");if(await ty(e,g.sitemapxml),!g.sitemapId)throw new me.ValidationError("app",y,[{pointer:"/sitemapId",rule:"app-sitemap-identity-missing",message:`missing sitemap identity \u2014 re-fetch the app before pushing edits: fetchArtifact('app', '${y}', { overwrite: true }) (it REPLACES the local copy \u2014 keep outstanding changes aside), push that refreshed copy UNTOUCHED, then re-apply your changes and push again. If the untouched push is refused with this same rule, the app has NO sitemap on the server \u2014 an earlier create committed its appmodule but not its sitemap \u2014 and it can be neither updated, published nor removed with deleteRemoteArtifact (an unpublished app reads back 404). Only for an app you have confirmed is your own abandoned partial create, with nothing else provisioning it: remove its appmodule row with deleteRecord('appmodule', '${y}'), clear the local copy with deleteArtifact('app', '${y}'), then author the app again and push.`}]);let A=(0,ne.normalizeGuid)(g.sitemapId,"sitemapId");if(!n)throw new me.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${y}': no concurrency token is held for its sitemap row, so the write could not be made conditional and would silently overwrite a concurrent edit. Re-fetch the app and re-apply the change.`);let D=await Yv(e,g),F=`/appmodules(${y})`,_=(o=a?.[y])!==null&&o!==void 0?o:null,q=!0,B=!1,L;try{let xe=Dd(Nd,y),yn=await e.get(xe);if(yn.status>=200&&yn.status<300){let $t=(s=Ji(yn))!==null&&s!==void 0?s:{};B=!0,L=typeof $t.uniquename=="string"&&$t.uniquename?$t.uniquename:void 0,q=String((l=$t.name)!==null&&l!==void 0?l:"")!==String((u=g.appModuleName)!==null&&u!==void 0?u:"")||String((c=$t.description)!==null&&c!==void 0?c:"")!==String((d=g.appModuleDescription)!==null&&d!==void 0?d:"")||g.appModuleAiDescription!==void 0&&String((p=$t.aiappdescription)!==null&&p!==void 0?p:"")!==String(g.appModuleAiDescription)}}catch{}let k=_;if(q){let xe=B?_:null,yn=xe?(0,fe.echoWrite)("appmoduleid",{"If-Match":xe}):{query:"",options:void 0},$t=await e.patch(`${F}${yn.query}`,{name:g.appModuleName,description:g.appModuleDescription,...g.appModuleAiDescription!==void 0?{aiappdescription:g.appModuleAiDescription}:{}},yn.options);if(AL($t))throw new me.SdkError("APP_DRAFT_HEADER_NOT_WRITABLE",`Refusing to update app '${y}': its appmodule row is UNPUBLISHED, and Dataverse cannot resolve version numbers for a draft appmodule (HTTP 400). A draft header cannot be PATCHed at all \u2014 a plain retry fails too, as an upsert-create ("webresourceid cannot be NULL"). Publish the app first, then push the header edit. Nothing was modified by this call.`);(0,fe.ensureSuccess)($t,e.apiUrl(F)),k=(0,fe.readEtag)($t)}let M={sitemapxml:g.sitemapxml,sitemapname:g.sitemapname},G=L||g.appModuleUniqueName||void 0,V=(0,fe.echoWrite)("sitemapid",{"If-Match":n}),Ze=`/sitemaps(${A})`,ir;try{ir=(0,fe.ensureSuccess)(await e.patch(`${Ze}${V.query}`,{...M},V.options),e.apiUrl(Ze))}catch(xe){throw(0,me.withPartialTokens)(xe,{siblingEtags:{[y]:k}})}let et=[...D.warnings];try{await Zv(e,y,D.components),await ey(e,y,D.tables)}catch(xe){et.push(`App '${y}': one or more components were not pinned (${xe.message}). Navigation may reference content not included in the app; re-push to retry.`)}let dt={kind:"notRequested"},ue=k,$e=(f=(0,fe.readEtag)(ir))!==null&&f!==void 0?f:await Id(e,A,M,G);if(g.published===!0){try{await(0,Qv.publishAppModule)(e,y),dt={kind:"submitted"}}catch(xe){dt={kind:"failed",error:xe},et.push(`App '${y}': saved, but publishing failed (${xe.message}). The app remains unpublished; re-push to retry.`)}if(dt.kind==="submitted"){ue=null;try{let xe=await e.get(`/appmodules(${y})?$select=appmoduleid`);xe.status>=200&&xe.status<300&&(ue=(0,fe.readEtag)(xe)),$e=(m=await Id(e,A,M,G))!==null&&m!==void 0?m:$e}catch{}}}return{id:y,etag:$e,siblingEtags:{[y]:ue},publish:dt,...et.length>0?{warnings:et}:{}}},async delete(e,t){let r=(0,ne.normalizeGuid)(t,"id");await oy(e,r,await iy(e,r))}}});var xd=v(Qi=>{"use strict";Object.defineProperty(Qi,"__esModule",{value:!0});Qi.deleteAppCascade=Qi.collectGenPageIds=void 0;var CL=ml(),EL=te(),Ld=ae(),SL=yd();function sy(e){let t=[],r=s=>l=>t.push(`${s}: ${l}`),i=new SL.DOMParser({errorHandler:{warning:r("warning"),error:r("error"),fatalError:r("fatalError")}}).parseFromString(e,"text/xml").documentElement;if(!i||t.length>0)throw new EL.InvalidArgumentError(`The app sitemap xml could not be parsed cleanly, so its generative-page children cannot be determined${t.length>0?` (${t[0]})`:""}`);let a=[],o=s=>{if(s.nodeName==="SubArea"){let u=s.getAttribute("GenPageId");u&&a.push((0,Ld.normalizeGuid)(u,"GenPageId"))}let l=s.childNodes;for(let u=0;u<l.length;u+=1){let c=l[u];c.nodeType===1&&o(c)}};return o(i),a}Qi.collectGenPageIds=sy;async function NL(e,t,r){let n=(0,Ld.normalizeGuid)(t,"appModuleId");(0,Ld.normalizeGuid)(r,"appModuleIdUnique");let i=[],a=[],o=[];await(0,CL.deleteAppResolvingOnce)(e,n,l=>{l!==void 0&&o.push(...sy(l))}),i.push({type:"app",id:n});let s=[...new Set(o)].map(l=>({type:"genPage",id:l}));return{success:a.length===0,deleted:i,failures:a,retained:s}}Qi.deleteAppCascade=NL});var ly={};zr(ly,{Guid:()=>P});var P,Le=I(()=>{"use strict";P=class e{guidString;guid;static get EmptyGuid(){return new e("00000000-0000-0000-0000-000000000000")}static NewGuid(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var r=Math.random()*16|0,n=t=="x"?r:r&3|8;return n.toString(16)})}constructor(t,r=!1){this.guidString=t;let n=new RegExp("[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}$");(r||n.test(t))&&(this.guid=t)}ToString(){return this.guid}}});var O,nt=I(()=>{"use strict";Oe();O=class e{static get EmptyString(){return""}static IsTrue(t){let r=!1;return r=t&&(this.IsStrictTrue(t)||this.IsYes(t)),r}static IsStrictTrue(t){let r=!1;return t&&(r=t.toLowerCase()==="true"),r}static IsYes(t){return t.toLowerCase()==="yes"||t.toLowerCase()==="y"}static get WhiteSpace(){return/ /g}static get EnglishAndNumericCharacters(){return/([a-z0-9A-Z]+)/g}static get ValidIdExpression(){return/([a-z0-9A-Z_]+)/g}static IsNullOrEmpty(t){return t==null||t==null||t==""}static Format(t,r){return e.IsNullOrEmpty(t)?t:t.replace(/\{\{|\}\}|\{(\d+)\}/g,function(n,i){return n=="{{"?"{":n=="}}"?"}":r[i]})}static EndsWithString(t,r){return t.indexOf(r,t.length-r.length)!==-1}static IsBlankString(t){return t.replace(/\s/g,"").length==0}static EscapeXml(t,r){let n=t;return this.IsNullOrEmpty(n)||(n=n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),r&&(n=n.replace(/"/g,""").replace(/'/g,"'"))),n}static EscapeDomId(t){return t.replace(".","\\.")}static ToSnakeCase(t){let r=e.EmptyString;for(let n=0;n<t.length;n++)n!==0&&t[n]==t[n].toUpperCase()&&(r+="-"),r+=t[n].toLowerCase();return r}static GetSnakeCaseMarkup(t,r){let n="<"+this.ToSnakeCase(t);if(!N.IsNullOrUndefined(r))for(let i of r.getKeys())n+=" "+this.ToSnakeCase(i)+'="'+r.getValue(i)+'"';return n+">"}static StripBraces(t){return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?t.substr(1,t.length-2):t}static AddBraces(t){return N.IsNullOrUndefined(t)||t.charAt(0)==="{"||t.charAt(t.length-1)==="}"?t:`{${t}}`}static GuidStringEquals(t,r){return t===r?!0:!t||!r?!1:e.StripBraces(t).toUpperCase()===e.StripBraces(r).toUpperCase()}static AddBracesToArrayValues(t){return t.length>0?t.map(n=>(n.charAt(0)!=="{"&&(n="{"+n),n.charAt(n.length-1)!=="}"&&(n=n+"}"),n)):t}static StripBracesOnArrayValues(t){return t.length>0?t.map(n=>{let i;return n.charAt(0)==="{"&&(i=n.substr(1,n.length-1)),n.charAt(n.length-1)==="}"&&(i=i.substr(0,n.length-2)),i}):t}}});var uy={};zr(uy,{ScriptUtilities:()=>N});var N,Oe=I(()=>{"use strict";Le();nt();N=class e{static IsNullOrUndefined(t){return t==null||t===void 0}static IsMacMachine(){return navigator.platform.indexOf("Mac")!==-1}static IsNullOrEmptyGuid(t){return O.IsNullOrEmpty(t.ToString())?!0:P.EmptyGuid.ToString()===t.ToString()}static IsNullOrUndefinedNested(t,r){return r.split(".").every(i=>typeof t!="object"||t==null||!(i in t)||t[i]==null?!1:(t=t[i],!0))}static ParseXml(t){return new DOMParser().parseFromString(t,"text/xml")}static IsWellFormedXml(t){return!e.ParseXml(t).querySelector("parsererror")}static getNamedItemValue(t,r){let n=t.getNamedItem(r);return e.IsNullOrUndefined(n)?null:n.value}static getBooleanValue(t,r){let n=e.getNamedItemValue(t,r);return e.IsNullOrUndefined(n)?null:O.IsTrue(n)}static getNumericValue(t){return e.IsNullOrUndefined(t)?null:parseInt(t)}static getAllUniqueTagNames(t){let r=new Set;return e.getAllUniqueTagNamesHelper(t,r),r}static getAllUniqueTagNamesHelper(t,r){if(t.nodeType===Node.ELEMENT_NODE&&(r.add(t.tagName),t.hasChildNodes()))for(let n=0;n<t.children.length;n++)this.getAllUniqueTagNamesHelper(t.children.item(n),r)}}});var hl,gl,ii,vl,kd,yl,Md=I(()=>{"use strict";(function(e){e[e.FormElementNodeChange=0]="FormElementNodeChange",e[e.FormElementAttributeChange=1]="FormElementAttributeChange"})(hl||(hl={}));gl=class{type;targetNode;constructor(t,r){this.type=t,this.targetNode=r}},ii=class extends gl{key;oldValue;newValue;constructor(t,r,n,i){super(hl.FormElementNodeChange,t),this.key=r,this.oldValue=n,this.newValue=i}apply(){this.targetNode.replaceObjectPropertyValue(this.key,this.newValue)}revert(){this.targetNode.replaceObjectPropertyValue(this.key,this.oldValue)}},vl=class extends gl{property;oldValue;newValue;constructor(t,r,n,i){super(hl.FormElementAttributeChange,t),this.property=r,this.oldValue=n,this.newValue=i}apply(){this.targetNode.replaceAttributeValue(this.property,this.newValue)}revert(){this.targetNode.replaceAttributeValue(this.property,this.oldValue)}},kd=class{changeSet;reversedChangeSet;constructor(t){this.changeSet=t,this.changeSet&&(this.reversedChangeSet=this.changeSet.slice().reverse())}length(){return this.changeSet?this.changeSet.length:0}apply(){this.changeSet&&this.changeSet.length>0&&this.changeSet.forEach(t=>{t.apply()})}revert(){this.reversedChangeSet&&this.reversedChangeSet.length>0&&this.reversedChangeSet.forEach(t=>{t.revert()})}},yl=class{isTracking;_trackedChanges;_trackedChangeSets;constructor(t=!1){this.isTracking=t,this._trackedChanges=[],this._trackedChangeSets=[]}addChange(t){this.isTracking&&this._trackedChanges.push(t)}collectChanges(){let t=new kd(this._trackedChanges.slice());return this._trackedChanges=[],t}pushChangeSet(t){this._trackedChangeSets.push(t)}popChangeSet(){if(this._trackedChangeSets?.length>0)return this._trackedChangeSets.pop()}getChangeSets(){return this._trackedChangeSets}}});var cy={};zr(cy,{ChartGridMode:()=>zt,ColumnLayoutWidths:()=>PL,ComponentCategory:()=>wl,ComponentType:()=>Ud,ControlLayoutTypes:()=>Wd,DisplayConditionsInfo:()=>_L,ElementNames:()=>b,ElementProperties:()=>h,ElementType:()=>$d,EntityAttributeProperty:()=>qd,EventType:()=>Eo,FormActivationState:()=>zd,FormCanvasServiceScope:()=>VL,FormDesignerSideBarTab:()=>Bd,FormPresentation:()=>Vd,FormState:()=>bl,FormType:()=>ke,HeaderDensityType:()=>Fn,LookUpTable:()=>_r,MORE_TAB_PREFIX:()=>RL,NavBarChildElementType:()=>Gd,PREVIEW_ID_HEADER_FLYOUT:()=>kL,PREVIEW_ID_HEADER_OVERFLOW_BUTTON:()=>UL,PREVIEW_ID_NAVIGATION_AREA:()=>xL,PREVIEW_ID_QUICKCREATE_ROOT:()=>$L,PREVIEW_ID_TAB:()=>BL,PREVIEW_ID_TAB_LIST:()=>ML,PREVIEW_ID_TAB_PANEL:()=>LL,PropertyModelKeys:()=>Jd,PropertyModelSectionKeys:()=>OL,RELATED_TAB_ID:()=>Qd,RELATED_TAB_PREFIX:()=>FL,SectionDefaultProperties:()=>TL,SectionLayoutTypes:()=>Ce,TabContentType:()=>Hd,TabDefaultProperties:()=>xn,TabLayoutTypes:()=>Ae,TelemetryPropertyNames:()=>qL,UnboundControlPropertyKeys:()=>jd,compositeAddressFields:()=>IL,compositeFieldNames:()=>Lt,compositeFields:()=>DL});var ke,Ud,Bd,b,h,$d,Lt,DL,IL,qd,_r,bl,Fn,Vd,_L,Gd,zd,Ae,TL,xn,Ce,Wd,Hd,PL,jd,Jd,OL,Eo,zt,Qd,RL,FL,xL,LL,kL,ML,UL,BL,$L,qL,wl,VL,X=I(()=>{"use strict";(function(e){e[e.Dashboard=0]="Dashboard",e[e.AppointmentBook=1]="AppointmentBook",e[e.Main=2]="Main",e[e.MiniCampaignBO=3]="MiniCampaignBO",e[e.Preview=4]="Preview",e[e.MobileExpress=5]="MobileExpress",e[e.QuickViewForm=6]="QuickViewForm",e[e.QuickCreate=7]="QuickCreate",e[e.Dialog=8]="Dialog",e[e.TaskFlowForm=9]="TaskFlowForm",e[e.InteractionCentricDashboard=10]="InteractionCentricDashboard",e[e.Card=11]="Card",e[e.MainInteractiveExperience=12]="MainInteractiveExperience",e[e.Other=100]="Other",e[e.MainBackup=101]="MainBackup",e[e.AppointmentBookBackup=102]="AppointmentBookBackup",e[e.PowerBIDashboard=103]="PowerBIDashboard"})(ke||(ke={}));(function(e){e[e.Form=0]="Form",e[e.Dialog=1]="Dialog"})(Ud||(Ud={}));(function(e){e[e.Components=0]="Components",e[e.Properties=1]="Properties",e[e.Relationship=2]="Relationship",e[e.BusinessRules=3]="BusinessRules"})(Bd||(Bd={}));(function(e){e.form="form",e.formTab="tab",e.formColumn="column",e.formSection="section",e.formRow="row",e.formCell="cell",e.formLabel="label",e.formControl="control",e.formEvent="event",e.dependency="dependency",e.queryStringParameter="querystringparameter",e.controlDescriptions="controlDescriptions",e.controlDescription="controlDescription",e.customControl="customControl",e.dataset="data-set",e.formFooter="footer",e.formHeader="header",e.formNavigation="Navigation",e.formTabs="tabs",e.formColumns="columns",e.formSections="sections",e.formRows="rows",e.formEvents="events",e.quickFormDependencies="externaldependencies",e.controlParameters="parameters",e.formDependencies="dependencies",e.formNavBarAreas="NavBarAreas",e.formNavBarArea="NavBarArea",e.formNavBar="NavBar",e.spacerControl="SpacerControl",e.formField="Field",e.formNavBarByRelationshipItem="NavBarByRelationshipItem",e.formNavBarItem="NavBarItem",e.Title="Title",e.Titles="Titles",e.NavigationLink="Navigation Link",e.Relationship="Relationship",e.NavigationLinkIconClass="mscrm-glyph-NavLinkIcon",e.formDisplayConditions="DisplayConditions",e.formLibraries="formLibraries",e.internalLibraries="internaljscriptfile",e.eventHandlers="Handlers",e.handler="Handler",e.library="Library",e.formRoles="Role",e.formEveryOne="Everyone",e.Handler="Handler",e.EventHandlers="Handlers",e.InternalEventHandlers="InternalHandlers",e.HiddenControl="hiddencontrols",e.EventDependencies="dependencies",e.EventDependency="dependency",e.isvisibleinmocaonly="msinternal.isvisibleinmocaonly"})(b||(b={}));h={ShowImage:"showImage",ShowNavigationbar:"shownavigationbar",MaxWidth:"maxWidth",HeaderDensityType:"headerdensity",OnLoadEvent:"onload",EventActive:"active",EventAttribute:"attribute",Relationship:"relationship",Control:"control",HandlerUniqueId:"handlerUniqueId",functionName:"functionName",libraryNameEventHandler:"libraryName",enabledForField:"enabled",passExecutionContext:"passExecutionContext",parameters:"parameters",eventFunctionName:"eventFunctionName",eventEnabled:"eventEnabled",indicationOfSubgrid:"indicationOfSubgrid",Name:"name",Type:"type",TitleResourceId:"TitleResourceId",Show:"Show",RelationshipName:"RelationshipName",Sequence:"Sequence",Area:"Area",headerPrefix:"header_",application:"application",labelId:"labelid",showbar:"showbar",layout:"layout",classid:"classid",uniqueid:"uniqueid",isUnbound:"isunbound",isRequired:"isrequired",rowspan:"rowspan",rowheight:"rowheight",colspan:"colspan",width:"width",IsUserDefined:"IsUserDefined",expanded:"expanded",related:"related",showlabel:"showlabel",locklevel:"locklevel",datafieldname:"datafieldname",formFactor:"formFactor",static:"static",disabled:"disabled",description:"description",languagecode:"languagecode",LCID:"LCID",groupName:"group",contentType:"contenttype",showCommandBar:"showcommandbar",showBody:"showbody",showTabNavigator:"showtabnavigator",userspacer:"userspacer",columnName:"columns",LabelWidth:"labelwidth",Fieldlabelalignment:"celllabelalignment",Fieldlabelposition:"celllabelposition",availableforphone:"availableforphone",Locked:"bLocked",ReadOnly:"bDisabled",visible:"visible",ForControl:"forControl",text:"Text",url:"Url",passParameters:"PassParameters",autoExpand:"AutoExpand",auto:"auto",Auto:"Auto",Fixed:"Fixed",icon:"Icon",id:"id",Id:"Id",showOnMobileClient:"ShowOnMobileClient",webResourceId:"WebResourceId",viewName:"ViewName",failureTimeField:"FailureTimeField",successCondition:"SuccessConditionName",successConditionValue:"SuccessConditionValue",failureCondition:"FailureConditionName",failureConditionValue:"FailureConditionValue",warningCondition:"WarningConditionName",warningConditionValue:"WarningConditionValue",cancelCondition:"CancelConditionName",cancelConditionValue:"CancelConditionValue",pauseCondition:"PauseConditionName",pauseConditionValue:"PauseConditionValue",filterResults:"FilterResults",autoSuggestionSource:"AutoSuggestionSource",numberOfResults:"NumberOfResults",addressField:"AddressField",displayAsCustomer360Tile:"DisplayAsCustomer360Tile",hideQuickFormBorder:"HideQuickFormBorder",quickForms:"QuickForms",entityName:"EntityName",controlMode:"ControlMode",headerColorCode:"HeaderColorCode",targetEntityType:"TargetEntityType",enableQuickFind:"EnableQuickFind",enableViewPicker:"EnableViewPicker",enableChartPicker:"EnableChartPicker",recordsPerPage:"RecordsPerPage",chartGridMode:"ChartGridMode",referencePanelSubgridIconUrl:"ReferencePanelSubgridIconUrl",referencePanelQuickFormCollectionIconUrl:"ReferencePanelQuickFormCollectionIconUrl",referencePanelSearchWidgetIconUrl:"ReferencePanelSearchWidgetIconUrl",viewId:"ViewId",isUserView:"IsUserView",enableJumpBar:"EnableJumpBar",isUserChart:"IsUserChart",viewIds:"ViewIds",filteredViewIds:"FilteredViewIds",visualizationId:"VisualizationId",teamTemplateId:"TeamTemplateId",selectDefaultLanguage:"SelectDefaultLanguage",allowChangingFiltersOnUI:"AllowChangingFiltersOnUI",enableAutoSuggestions:"EnableAutoSuggestions",enableRating:"EnableRating",searchForAutoSuggestionsUsing:"SearchForAutoSuggestionsUsing",showContextualActions:"ShowContextualActions",showDepartmentFilter:"ShowDepartmentFilter",showLanguageFilter:"ShowLanguageFilter",showRatingUsing:"ShowRatingUsing",actionList:"ActionList",Order:"Order",FallbackForm:"FallbackForm",allowSearchFilter:"allowSearchFilter",socialInstanceParameters:"<Parameters>k__BackingField",signalUrl:"SignalUrl",border:"Border",scrolling:"Scrolling",security:"Security",BingMapsAddress1Composite:"address1_composite",BingMapsAddress2Composite:"address2_composite",UrlHttpsProtocolPrefix:"https://",UrlHttpProtocolPrefix:"http://",showAll:"ShowAll",ShowFilterPane:"UClientShowFilterPane",ExpandFilterPane:"UClientExpandFilterPane",SortOption:"UClientOrderBy",DefaultModuleCreateExperience:"UClientDefaultModuleForCreateExperience",RecordPerPages:"UClientRecordPerPage",moduleList:"UClientModules",showAllModule:"Show All",showSelectedModule:"Show Selected",Ascending:"Ascending",Descending:"Descending",Activities:"Activities",Posts:"Posts",Notes:"Notes",CardForm:"CardForm",SelectActivity:"SelectActivity",DisplayActivity:"UClientDisplayActivityUsing",CreateActivity:"UClientCreateActivityUsing",DisplayActivityHeader:"UClientDisplayActivityHeaderUsing",SortTimeLine:"UClientSortActivitiesByValue",activityList:"UClientActivities",CardActivityMap:"UClientActivityCardMap",DefaultTabId:"DefaultTabId",EmailConversationView:"EmailConversationView",OrderByActivityWall:"OrderByActivityWall",ShowArticleTab:"ShowArticleTab",SortActivityWall:"SortActivityWall",TimelineUniqueName:"UClientUniqueName",SortTimeLineBy:"modifiedon",SelectActivityListDefault:"appointment",SelectCardDefault:"Select Card Form",AscendingValue:"ascending",DescendingValue:"descending",DefaultTabIdValue:"ActivitiesTab",EmailConversationViewDefault:"true",ShowArticleTabDefault:"false",SelectDefaultLanguage:"SelectDefaultLanguage",SelectDefaultLanguageValue:"00000000-0000-0000-0000-000000000000",SortActivityWallDefault:"modifiedon",RecordPerPagesDefault:"10",TimelineNameLabel:"Timeline",showSelectedActions:"Show Selected",defaultFormat:"defaultformat",fieldLabels:"fieldlabels",QuickCreateForm:"quickcreateform",QuickFormNameToIdXMLTempate:"<QuickFormId e,yname={0}>{1}</QuickFormId>",QuickFormIdListXMLTempate:"<QuickFormId,}</QuickFormIds>",AllowFilterOff:"AllowFilterOff",AutoResolve:"AutoResolve",DefaultViewId:"DefaultViewId",DependentAttributeName:"DependentAttributeName",DependentAttributeType:"DependentAttributeType",DisableMru:"DisableMru",UseMFDForCreate:"useMainFormDialogForCreate",UseMFDForEdit:"useMainFormDialogForEdit",DisableQuickFind:"DisableQuickFind",DisableViewPicker:"DisableViewPicker",FilterRelationshipName:"FilterRelationshipName",AvailableViewIds:"AvailableViewIds",MainForm:"mainform",DefaultsFields:"defaultfields",TimeLineCardForm:"cardform",libraryUniqueId:"libraryUniqueId",libraryName:"name",displayName:"displayName",OnChangeEvent:"onchange",ViewIdRAControlDefault:"{92AFD454-0F2E-4397-A1C8-05E37C6AD699}",TargetEntityTypeRAControlDefault:"actioncard",ChartGridModeRAControlDefault:"All",RecordsPerPageRAControlDefault:"4",RAControlDefaultValue:"false",RAcontrolDefaultHeaderColorCode:"#000000",DropdownSelectedDefaultValue:"1",selectPrimaryCustomer:"SelectPrimaryCustomer",bindAttribute:"BindAttribute"};(function(e){e[e.TAB=0]="TAB",e[e.SECTION=1]="SECTION",e[e.BASIC_CONTROL=2]="BASIC_CONTROL",e[e.HEADER=3]="HEADER",e[e.FOOTER=4]="FOOTER",e[e.UB_CONTROL=5]="UB_CONTROL",e[e.RELATIONSHIPITEM=6]="RELATIONSHIPITEM",e[e.RELATIONSHIPGROUP=7]="RELATIONSHIPGROUP",e[e.NAVIGATIONLINK=8]="NAVIGATIONLINK",e[e.FORMMODEL=9]="FORMMODEL",e[e.UNDEFINED=10]="UNDEFINED"})($d||($d={}));Lt={fullname:"fullname",yomifullname:"yomifullname",address1_composite:"address1_composite",address2_composite:"address2_composite",address3_composite:"address3_composite",billto:"billto_composite",shipto:"shipto_composite"},DL=[Lt.fullname,Lt.yomifullname,Lt.address1_composite,Lt.address2_composite,Lt.address3_composite,Lt.billto,Lt.shipto],IL=[Lt.address1_composite,Lt.address2_composite,Lt.address3_composite,Lt.billto,Lt.shipto];(function(e){e[e.IsValidForForm=0]="IsValidForForm",e[e.IsValidForCreate=1]="IsValidForCreate"})(qd||(qd={}));(function(e){e[e.DependencyFieldTable=0]="DependencyFieldTable",e[e.LockedFieldTable=1]="LockedFieldTable"})(_r||(_r={}));(function(e){e[e.Published=0]="Published",e[e.Draft=1]="Draft",e[e.New=2]="New",e[e.SaveAs=3]="SaveAs"})(bl||(bl={}));(function(e){e.Low="Low",e.HighReadOnlyValues="HighReadOnlyValues",e.HighWithControls="HighWithControls"})(Fn||(Fn={}));(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(Vd||(Vd={}));_L={TopOrderFormId:"topOrderFormId",NextDisplayOrder:"nextDisplayOrder"};(function(e){e[e.NavBarRelationShipItem=0]="NavBarRelationShipItem",e[e.NavBarItem=1]="NavBarItem"})(Gd||(Gd={}));(function(e){e[e.InActive=0]="InActive",e[e.Active=1]="Active"})(zd||(zd={}));(function(e){e[e.ONE_COLUMN=0]="ONE_COLUMN",e[e.TWO_COLUMN_EQUAL=1]="TWO_COLUMN_EQUAL",e[e.TWO_COLUMN_WIDER_LEFT=2]="TWO_COLUMN_WIDER_LEFT",e[e.TWO_COLUMN_WIDER_RIGHT=3]="TWO_COLUMN_WIDER_RIGHT",e[e.TWO_COLUMN_CUSTOM_LAYOUT=4]="TWO_COLUMN_CUSTOM_LAYOUT",e[e.THREE_COLUMN_EQUAL=5]="THREE_COLUMN_EQUAL",e[e.THREE_COLUMN_WIDER_MID=6]="THREE_COLUMN_WIDER_MID",e[e.THREE_COLUMN_CUSTOM_LAYOUT=7]="THREE_COLUMN_CUSTOM_LAYOUT"})(Ae||(Ae={}));TL={ShowLabel:"false",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_"},xn={namePrefix:"tab_",ShowLabel:"true",LockLevel:"0",IsUserDefined:"0"};(function(e){e[e.ONE_COLUMN=0]="ONE_COLUMN",e[e.TWO_COLUMN=1]="TWO_COLUMN",e[e.THREE_COLUMN=2]="THREE_COLUMN",e[e.FOUR_COLUMN=3]="FOUR_COLUMN",e[e.REFERENCE_PANEL=4]="REFERENCE_PANEL"})(Ce||(Ce={}));(function(e){e[e.SUBGRID=0]="SUBGRID",e[e.SPACER=1]="SPACER",e[e.QUICK_VIEW=2]="QUICK_VIEW",e[e.WEB_RESOURCE=3]="WEB_RESOURCE",e[e.IFRAME=4]="IFRAME",e[e.BING_MAPS=5]="BING_MAPS",e[e.TIMER=6]="TIMER",e[e.TIMELINE=7]="TIMELINE",e[e.NOTES=8]="NOTES",e[e.SOCIAL_INSIGHTS=9]="SOCIAL_INSIGHTS",e[e.KB_SEARCH=10]="KB_SEARCH",e[e.INTERACTION_WALL=11]="INTERACTION_WALL",e[e.ACI_CONTROL=12]="ACI_CONTROL",e[e.RELATIONSHIP_ASSISTANT=13]="RELATIONSHIP_ASSISTANT",e[e.REFERENCE_PANEL=14]="REFERENCE_PANEL",e[e.REF_PANEL_QUICKVIEW=15]="REF_PANEL_QUICKVIEW",e[e.REF_PANEL_SUBGRID=16]="REF_PANEL_SUBGRID",e[e.REF_PANEL_KBSEARCH=17]="REF_PANEL_KBSEARCH",e[e.WEB_RESOURCE_HTML=18]="WEB_RESOURCE_HTML",e[e.PRED_LEAD_SCORING=19]="PRED_LEAD_SCORING"})(Wd||(Wd={}));(function(e){e.cardSections="cardSections",e.singleComponent="singleComponent",e.default="default",e.expandAvailableSpace="expandAvailableSpace"})(Hd||(Hd={}));PL={ONE_COLUMN:"100",TWO_COLUMN:"50",THREE_COLUMN:"33.33",FOUR_COLUMN:"25"};(function(e){e.minValue="MinValue",e.maxValue="MaxValue",e.precision="Precision",e.maxLength="MaxLength",e.entityLogicalName="EntityLogicalName",e.defaultViewId="DefaultViewId",e.optionSetDefaultValue="DefaultValue",e.optionSetId="OptionSetId"})(jd||(jd={}));(function(e){e.entityName="entityName",e.formName="formName",e.formDisplayName="formDisplayName",e.description="description",e.maxWidth="maxWidth",e.showNavigation="showNavigation",e.showImageCheck="showImageCheck",e.downloadFormXml="downloadFormXml",e.downloadRawFormXml="downloadRawFormXml",e.expandTab="expandTab",e.singleComponent="singleComponent",e.label="label",e.name="name",e.hiddenByDefault="hiddenByDefault",e.hideForPhone="hideForPhone",e.tabLayout="tabLayout",e.column1Width="column1Width",e.column2Width="column2Width",e.column3Width="column3Width",e.hideLabel="hideLabel",e.lockElement="lockElement",e.sectionLayout="sectionLayout",e.labelWidth="labelWidth",e.fieldLabelAlignment="fieldLabelAlignment",e.fieldLabelPosition="fieldLabelPosition",e.cellWidth="cellWidth",e.fieldHeight="fieldHeight",e.cellHeight="cellHeight",e.showLine="showLine",e.readonly="readonly",e.required="required",e.maxLength="maxLength",e.isTitle="isTitle",e.minValue="minValue",e.maxValue="maxValue",e.precision="precision",e.autoExpand="autoExpand",e.highDensityEnabled="highDensityEnabled",e.hideExtendedHeader="hideExtendedHeader",e.defaultViewProperty="defaultViewProperty",e.defaultChartProperty="defaultChartProperty",e.teamTemplateProperty="teamTemplateProperty",e.datasourceProperty="datasourceProperty",e.eventType="eventType",e.addEvent="addEvent",e.cellOnChange="cellOnChange",e.cellOnChangeEventDependencies="cellOnChangeEventDependencies",e.cellOnChangeHandlers="cellOnChangeHandlers",e.gridOnChange="gridOnChange",e.gridOnChangeEventDependencies="gridOnChangeEventDependencies",e.gridOnChangeHandlers="gridOnChangeHandlers",e.gridOnChangeTargetField="gridOnChangeTargetField",e.gridOnRecordSelect="gridOnRecordSelect",e.gridOnRecordSelectEventDependencies="gridOnRecordSelectEventDependencies",e.gridOnRecordSelectHandlers="gridOnRecordSelectHandlers",e.cellOnReadyStateEventDependencies="cellOnReadyStateEventDependencies",e.cellOnReadyStateHandlers="cellOnReadyStateEventHandlers",e.tabOnChange="tabOnChange",e.tabOnChangeEventDependencies="tabOnChangeEventDependencies",e.tabOnChangeHandlers="tabOnChangeHandlers",e.formOnLoad="formOnLoad",e.formOnLoadEventDependencies="formOnLoadEventDependencies",e.formOnLoadHandlers="formOnLoadHandlers",e.formOnSave="formOnSave",e.formOnSaveDependencies="formOnSaveDependencies",e.formOnSaveHandlers="formOnSaveHandlers",e.gridOnSave="gridOnSave",e.gridOnSaveDependencies="gridOnSaveDependencies",e.gridOnSaveHandlers="gridOnSaveHandlers",e.formHasNoLibraries="formHasNoLibraries",e.hideHeaderCommandBar="hideHeaderCommandBar",e.hideHeaderBody="hideHeaderBody",e.hideHeaderTabNavigator="hideHeaderTabNavigator",e.hideFooter="hideFooter",e.scrollingDropdown="scrollingDropdown",e.displayBorder="displayBorder",e.crossScripting="crossScripting",e.passParams="passParams",e.webResourceCustomParamData="webResourceCustomParameterData",e.webResourceAltText="webResourceAltText",e.verticalAlignment="verticalAlignment",e.horizontalAlignment="horizontalAlignment",e.specificSize="specificSize",e.urlProperty="urlProperty",e.enableViewPicker="enableViewPicker",e.enableChartPicker="enableChartPicker",e.chartGridMode="chartGridMode",e.relatedRecords="relatedRecords",e.hideSearchBox="hideSearchBox",e.showAllViews="showAllViews",e.availableViewsProperty="availableViewsProperty",e.recordsPerPage="recordsPerPage",e.businessRulePill="business-rule-pill-",e.addBusinessRule="addBusinessRule",e.rowHeight="rowHeight",e.refPanelSectionTabs="refPanelSectionTabs",e.editCanvasAppProperty="editCanvasAppProperty"})(Jd||(Jd={}));OL={display:"DisplayOptions",format:"Formatting",control:"Controls",data:"DataOptions",form:"FormProperties",events:"EventProperties",activeBusinessRules:"activeBusinessRules",addBusinessRule:"addBusinessRule",inactiveBusinessRules:"inactiveBusinessRules"};(function(e){e.onChange="onchange",e.onTabStateChange="tabstatechange",e.onLoad="onload",e.onSave="onsave",e.onReadyStateComplete="onreadystatecomplete",e.onRecordSelect="onrecordselect"})(Eo||(Eo={}));(function(e){e.All="All",e.Chart="Chart",e.Grid="Grid"})(zt||(zt={}));Qd="tab_related3b554255-7717-4d17-bb7f-9936fb1e75ca",RL="more_tab_",FL="related_tab_",xL="preview_id_navigation_area",LL="tab-section",kL="headerFieldsFlyout",ML="tablist",UL="header_overflowButton",BL="tab",$L="quickCreateRoot",qL={defaultVisibility:"Default visibility"};(function(e){e.input="input",e.layout="layout",e.grid="grid",e.relatedData="relatedData",e.display="display",e.powerbi="powerbi",e.artificialIntelligence="artificialIntelligence",e.media="media",e.collaboration="collaboration",e.more="more",e.test="test",e.popular="popular"})(wl||(wl={}));VL="CellCanvasServiceScope"});var dy={};zr(dy,{Attribute:()=>Al,FormElementNode:()=>H});var Al,H,We=I(()=>{"use strict";Oe();nt();Md();X();Le();Al=class{key;value;constructor(t,r){this.key=t,this.value=r}},H=class e{nodeName;properties;childrenNodes;parentNode;nodeId;isTransient;constructor(t,r){this.nodeName=t,this.properties=[],this.childrenNodes=[],this.parentNode=r,this.isTransient=!1,this.nodeId=`nodeId-${P.NewGuid()}`}getProperty(t){for(let r of this.properties)if(r.key===t)return r.value;return null}getNodeId(){return this.nodeId}getNodeName(){return this.nodeName}setNodeName(t){this.trackObjectPropertyChange("nodeName",t)}get NodeName(){return this.getNodeName()}getAllProperties(){return this.properties}replaceAttributeValue(t,r){this.properties.find(n=>n===t)&&(t.value=r)}replaceObjectPropertyValue(t,r){this[t]=r}getAllChildren(){return this.childrenNodes}getParentNode(){return this.parentNode}visit(t){let r=!1;if(t){r=!!t(this);let n=this.childrenNodes;if(!r&&n)for(let i=0;!r&&i<n.length;i++)r=n[i].visit(t)}return r}findAll(t){let r=[];return t&&this.visit(n=>{t(n)&&r.push(n)}),r}findFirst(t){let r=null;return t&&this.visit(n=>{if(t(n))return r=n,!0}),r}raiseMetadataChange(t){let r=this.getAncestor(b.form);r&&r.raiseMetadataChange(t)}trackPropertyAddition(t,r){this.trackPropertyCollectionChange(()=>{this.properties.push(new Al(t,r))})}trackPropertyDeletion(t){this.trackPropertyCollectionChange(()=>{let r=this.properties.findIndex(n=>n.key===t);r>-1&&this.properties.splice(r,1)})}trackPropertyCollectionChange(t){let r=this.changeTracker();if(r&&r.isTracking){let n=this.properties.slice();t(),r.addChange(new ii(this,"properties",n,this.properties.slice()))}else t()}trackChildrenCollectionChange(t){let r=this.changeTracker();if(r&&r.isTracking){let n=this.childrenNodes.slice();t(),r.addChange(new ii(this,"childrenNodes",n,this.childrenNodes.slice()))}else t()}trackParentNodeChange(t){let r=this.changeTracker();if(r&&r.isTracking){let n=this.parentNode;if(t(),n===this.parentNode)return;r.addChange(new ii(this,"parentNode",n,this.parentNode))}else t()}trackAttributeValueChange(t,r){let n=this.changeTracker();if(n&&n.isTracking){let i=t.value;if(i===r)return;t.value=r,n.addChange(new vl(this,t,i,r))}else t.value=r}trackObjectPropertyChange(t,r){let n=this.changeTracker();if(n&&n.isTracking){let i=this[t];if(i===r)return;this[t]=r,n.addChange(new ii(this,t,i,r))}else this[t]=r}setProperty(t,r){if(!t)throw new Error("Invalid property key");let n=this.properties.find(i=>i.key===t);n?this.trackAttributeValueChange(n,r):this.addProperty(t,r)}addProperty(t,r){if(!t)throw new Error("Invalid property key");this.trackPropertyAddition(t,r)}removeProperty(t){this.trackPropertyDeletion(t)}addChild(t){t.trackParentNodeChange(()=>{t.parentNode=this}),this.trackChildrenCollectionChange(()=>{this.childrenNodes.push(t)})}insertChildAtIndex(t,r){N.IsNullOrUndefined(t)||(t.trackParentNodeChange(()=>{t.parentNode=this}),this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(r,0,t)}))}moveChild(t,r){let n=this.childrenNodes.indexOf(t);if(n<0)return!1;let i=Math.min(Math.max(0,n+r),this.childrenNodes.length-1);return n!==i&&this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(i,0,this.childrenNodes.splice(n,1)[0])}),!0}getChildren(t){let r=[];for(let n of this.childrenNodes)n.nodeName===t&&r.push(n);return r}getFirstChild(t){for(let r of this.childrenNodes)if(r.nodeName===t)return r;return null}getAllGrandChildren(t){let r=this.getChildren(t),n=null;return r.length===0?new Array:(n=r[0],n.childrenNodes)}deleteChild(t){if(N.IsNullOrUndefined(t))return-1;for(let r=0;r<this.childrenNodes.length;r++)if(this.childrenNodes[r]===t)return this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(r,1)}),r;return-1}deleteAllChildren(){this.trackChildrenCollectionChange(()=>{this.childrenNodes=[]})}getParent(){return this.parentNode}getParentType(){return this.parentNode?this.parentNode.nodeName:O.EmptyString}updateChild(t,r){let n=this.childrenNodes.indexOf(t);return n>-1?(r.trackParentNodeChange(()=>{r.parentNode=this}),this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(n,1,r)}),!0):!1}getAncestor(t){let r=this.getParent(),n=this.getParentType();for(;r;){if(n===t)return r;n=r.getParentType(),r=r.getParent()}return null}deleteFirstGrandChildOfName(t,r){return this.getChildren(t)[0].deleteChild(r)}deleteChildren(t,r){r=N.IsNullOrUndefined(r)?this.childrenNodes.length:r,this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(t,r)})}deleteGrandChildren(t,r,n){this.getChildren(t)[0].deleteChildren(r,n)}addGrandChild(t,r){let n=this.getChildren(t),i=null;n.length===0?(i=new e(t,this),this.addChild(i)):i=n[0],i.addChild(r)}addGrandChildAtIndex(t,r,n){let i=this.getChildren(t),a=null;i.length===0?(a=new e(t,this),this.addChild(a)):a=i[0],a.insertChildAtIndex(r,n)}GetPropertyByParameter(t){return this.getProperty(t)}getSemanticParent(){switch(this.getNodeName()){case b.formCell:let t=this.getAncestor(b.formSection);return t||(t=this.getAncestor(b.formHeader),t)||(t=this.getAncestor(b.formFooter),t)?t:null;case b.formSection:return this.getAncestor(b.formTab);case b.formTab:return this.getAncestor(b.form);default:return null}}isDirty(){return this.visit(t=>t.isInChangeSet())}isInChangeSet(){return this.changeTracker().getChangeSets().some(r=>r.changeSet.some(n=>n.targetNode.getNodeId()===this.getNodeId()))}changeTracker(){let t=this.getAncestor(b.form);return t?t.changeTracker():null}}});var py={};zr(py,{ControlClassId:()=>S,ControlNamePrefixes:()=>Cl,getControlDisplayNames:()=>GL});function GL(e){return{[S.AccessPrivilegeControl]:e("controls.controlNames.accessPrivilege"),[S.AccessTeamTablePickerControl]:e("controls.controlNames.accessTeamTablePicker"),[S.ACIControl]:e("controls.controlNames.aci"),[S.ActivitiesContainerControl]:e("controls.controlNames.activitiesContainer"),[S.ActivitiesWallControl]:e("controls.controlNames.activitiesWall"),[S.AppliedFiltersControl]:e("controls.controlNames.appliedFilters"),[S.ArticleContentControl]:e("controls.controlNames.articleContent"),[S.BooleanControl]:e("controls.controlNames.twoOption"),[S.ButtonControl]:e("controls.controlNames.button"),[S.CheckboxControl]:e("controls.controlNames.checkbox"),[S.CompositionLinkControl]:e("controls.controlNames.compositionLink"),[S.ConnectionControl]:e("controls.controlNames.connection"),[S.ConnectionRoleObjectTypeListControl]:e("controls.controlNames.connectionRoleObjectTypeList"),[S.CoverageChoiceControl]:e("controls.controlNames.coverageChoice"),[S.DashboardControl]:e("controls.controlNames.dashboard"),[S.DynamicPropertyListControl]:e("controls.controlNames.dynamicPropertyList"),[S.EditFilterControl]:e("controls.controlNames.editFilter"),[S.ErrorStatusControl]:e("controls.controlNames.errorStatus"),[S.GlobalFilterControl]:e("controls.controlNames.globalFilter"),[S.HiddenInputControl]:e("controls.controlNames.hiddenInput"),[S.KBViewerControl]:e("controls.controlNames.kbViewer"),[S.LabelControl]:e("controls.controlNames.label"),[S.MailMergeLanguagePickerControl]:e("controls.controlNames.mailMergeLanguagePicker"),[S.MapLinkControl]:e("controls.controlNames.mapLink"),[S.OrgInsightsControl]:e("controls.controlNames.orgInsights"),[S.ChoiceLookupControl]:e("controls.controlNames.choiceLookup"),[S.PowerBIControl]:e("controls.controlNames.powerBI"),[S.ProcessControl]:e("controls.controlNames.process"),[S.RelatedInformationControl]:e("controls.controlNames.relatedInformation"),[S.RelationshipRoleChoiceControl]:e("controls.controlNames.relationshipRoleChoice"),[S.ReportControl]:e("controls.controlNames.report"),[S.StreamsControl]:e("controls.controlNames.streams"),[S.WebResourceSilverlightControl]:e("controls.controlNames.webResourceSilverlight"),[S.CurrencyControl]:e("controls.controlNames.currency"),[S.DateTimeControl]:e("controls.controlNames.dateAndTime"),[S.DecimalControl]:e("controls.controlNames.decimal"),[S.DurationControl]:e("controls.controlNames.duration"),[S.EmailAddressControl]:e("controls.controlNames.email"),[S.FileControl]:e("controls.controlNames.file"),[S.FloatingNumberControl]:e("controls.controlNames.floatingNumber"),[S.IframeControl]:e("controls.controlNames.iframe"),[S.ImageControl]:e("controls.controlNames.image"),[S.LookupControl]:e("controls.controlNames.lookup"),[S.MapsControl]:e("controls.controlNames.maps"),[S.PhoneNumberControl]:e("controls.controlNames.phoneNumber"),[S.ChoiceControl]:e("controls.controlNames.choice"),[S.QuickViewControl]:e("controls.controlNames.quickView"),[S.QuickFormControl]:e("controls.controlNames.quickForm"),[S.CustomControl]:e("controls.controlNames.customControl"),[S.SearchWidgetControl]:e("controls.controlNames.searchWidget"),[S.SocialInsightsControl]:e("controls.controlNames.socialInsights"),[S.SubgridControl]:e("controls.controlNames.subgrid"),[S.TextAreaControl]:e("controls.controlNames.textArea"),[S.TextboxControl]:e("controls.controlNames.textBox"),[S.TickerControl]:e("controls.controlNames.ticker"),[S.UrlControl]:e("controls.controlNames.url"),[S.WebResourceHTMLControl]:e("controls.controlNames.webResourceHTML"),[S.WebResourceImageControl]:e("controls.controlNames.webResourceImage"),[S.IntegerControl]:e("controls.controlNames.integer"),[S.TimerControl]:e("controls.controlNames.timer"),[S.TimelineControl]:e("controls.controlNames.timeline"),[S.EmailBodyControl]:e("controls.controlNames.emailBody"),[S.PartyListControl]:e("controls.controlNames.partyList"),[S.TimezoneControl]:e("controls.controlNames.timezone"),[S.LanguageControl]:e("controls.controlNames.language"),[S.ChoiceStatusControl]:e("controls.controlNames.choiceStatus"),[S.ChoicesControl]:e("controls.controlNames.choices"),[S.RegardingControl]:e("controls.controlNames.regarding"),[S.EmailEngagementActionsControl]:e("controls.controlNames.emailEngagementActions"),[S.EmailRecipientActivityControl]:e("controls.controlNames.emailRecipientActivity"),[S.ReferencePanelSearchWidgetControl]:e("controls.controlNames.referencePanelSearchWidget"),[S.ReferencePanelQuickViewControl]:e("controls.controlNames.referencePanelQuickView"),[S.ReferencePanelSubgridControl]:e("controls.controlNames.referencePanelSubgrid"),[S.KBEditorControl]:e("controls.controlNames.KBEditor"),[S.LinkControl]:e("controls.controlNames.link")}}var S,Cl,ai=I(()=>{"use strict";(function(e){e.AccessPrivilegeControl="F93A31B2-99AC-4084-8EC2-D4027C31369A",e.AccessTeamTablePickerControl="3f4e2a56-f102-4b4d-ab9c-f1574ca5bfda",e.ACIControl="C8BFBBEF-6851-4401-A0CC-7450062FE085",e.ActivitiesContainerControl="C72511AB-84E5-4FB7-A543-25B4FC01E83E",e.ActivitiesWallControl="6636847D-B74D-4994-B55A-A6FAF97ECEA2",e.AppliedFiltersControl="9C310A73-A360-42C5-8943-47A06F1B51EA",e.ArticleContentControl="F02EF977-2564-4B9A-B2F0-DF083D8A019B",e.BooleanControl="67FAC785-CD58-4F9F-ABB3-4B7DDC6ED5ED",e.ButtonControl="00AD73DA-BD4D-49C6-88A8-2F4F4CAD4A20",e.CheckboxControl="B0C6723A-8503-4FD7-BB28-C8A06AC933C2",e.CompositionLinkControl="DB1284EF-9FFC-4E99-B382-0CC082FE2364",e.ConnectionControl="3246F906-1F71-45F7-B11F-D7BE0F9D04C9",e.ConnectionRoleObjectTypeListControl="821ACF1A-7E46-4A0C-965D-FE14A57D78C7",e.CoverageChoiceControl="4168A05C-D857-46AF-8457-5BB47EB04EA1",e.DashboardControl="D2561F53-B292-42D9-B222-478E40FFE29F",e.DynamicPropertyListControl="6896F004-B17A-4202-861E-8B7EA2080E0B",e.EditFilterControl="1479835F-F852-4679-B864-C6892A2844C9",e.ErrorStatusControl="F4C16ECA-CA81-4E39-9448-834B8378721E",e.GlobalFilterControl="FFF0E632-9D7B-4F21-BBC1-05D1567AD144",e.HiddenInputControl="5546E6CD-394C-4BEE-94A8-4425E17EF6C6",e.KBViewerControl="A62B6FA9-169E-406C-B1AA-EAB828CB6026",e.LabelControl="39354E4A-5015-4D74-8031-EA9EB73A1322",e.MailMergeLanguagePickerControl="B634828E-C390-444A-AFE6-E07315D9D970",e.MapLinkControl="91DC0675-C8B9-4421-B1E0-261CEBF02BAC",e.OrgInsightsControl="76b9e25e-695e-4fef-ac69-f05cfa96739c",e.ChoiceLookupControl="2305e33a-bad3-4022-9e15-1856cf218333",e.PowerBIControl="8C54228C-1B25-4909-A12A-F2B968BB0D62",e.ProcessControl="06E9F7AF-1F54-4681-8EEC-1E21A1CEB465",e.RelatedInformationControl="163B90A6-EB64-49D2-9DF8-3C84A4F0A0F8",e.RelationshipRoleChoiceControl="5F986642-5961-4D9F-AB5E-643D71E231E9",e.ReportControl="A28F441B-916C-4865-87FD-0C5D53BD59C9",e.StreamsControl="EE9078C8-6946-4E2C-B8F8-35E65F4BE6A8",e.WebResourceSilverlightControl="080677DB-86EC-4544-AC42-F927E74B491F",e.CurrencyControl="533B9E00-756B-4312-95A0-DC888637AC78",e.CustomControl="F9A8A302-114E-466A-B582-6771B2AE0D92",e.DateTimeControl="5B773807-9FB2-42DB-97C3-7A91EFF8ADFF",e.DecimalControl="C3EFE0C3-0EC6-42BE-8349-CBD9079DFD8E",e.DurationControl="AA987274-CE4E-4271-A803-66164311A958",e.EmailAddressControl="ADA2203E-B4CD-49BE-9DDF-234642B43B52",e.EmailBodyControl="6F3FB987-393B-4D2D-859F-9D0F0349B6AD",e.EmailEngagementActionsControl="F454228D-1D25-4319-E12F-D27968BC0234",e.EmailRecipientActivityControl="26E9760F-7454-40DE-BB07-F6DCCCB82040",e.FileControl="0A7FF475-B016-4687-9CE5-042BFDBD6519",e.FloatingNumberControl="0D2C745A-E5A8-4C8F-BA63-C6D3BB604660",e.IframeControl="FD2A7985-3187-444E-908D-6624B21F69C0",e.ImageControl="7E548B0D-209C-477B-9DCD-F0F44472381D",e.LanguageControl="671A9387-CA5A-4D1E-8AB7-06E39DDCF6B5",e.LookupControl="270BD3DB-D9AF-4782-9025-509E298DEC0A",e.MapsControl="62B0DF79-0464-470F-8AF7-4483CFEA0C7D",e.ChoicesControl="4AA28AB7-9C13-4F57-A73D-AD894D048B5F",e.IntegerControl="C6D124CA-7EDA-4A60-AEA9-7FB8D318B68F",e.PartyListControl="CBFB742C-14E7-4A17-96BB-1A13F7F64AA2",e.PhoneNumberControl="8C10015A-B339-4982-9474-A95FE05631A5",e.ChoiceControl="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE",e.ChoiceStatusControl="5D68B988-0661-4DB2-BC3E-17598AD3BE6C",e.QuickViewControl="5C5600E0-1D6E-4205-A272-BE80DA87FD42",e.QuickFormControl="69AF7DCA-2E3B-4EE7-9201-0DA731DD2413",e.RegardingControl="F3015350-44A2-4AA0-97B5-00166532B5E9",e.SearchWidgetControl="E616A57F-20E0-4534-8662-A101B5DDF4E0",e.SocialInsightsControl="86B9E25E-695E-4FEF-AC69-F05CFA96739C",e.SubgridControl="E7A81278-8635-4D9E-8D4D-59480B391C5B",e.TextAreaControl="E0DECE4B-6FC8-4A8F-A065-082708572369",e.TextboxControl="4273EDBD-AC1D-40D3-9FB2-095C621B552D",e.TickerControl="1E1FC551-F7A8-43AF-AC34-A8DC35C7B6D4",e.TimerControl="9C5CA0A1-AB4D-4781-BE7E-8DFBE867B87E",e.TimelineControl="06375649-C143-495E-A496-C962E5B4488E",e.TimezoneControl="7C624A0B-F59E-493D-9583-638D34759266",e.UrlControl="71716B6C-711E-476C-8AB8-5D11542BFB47",e.WebResourceHTMLControl="9FDF5F91-88B1-47F4-AD53-C11EFC01A01D",e.WebResourceImageControl="587CDF98-C1D5-4BDE-8473-14A0BC7644A7",e.ReferencePanelSearchWidgetControl="7CCD1494-1F7A-4E3A-8BDE-F32069DAEB9F",e.ReferencePanelSubgridControl="02D4264B-47E2-4B4C-AA95-F439F3F4D458",e.ReferencePanelQuickViewControl="B68B05F0-A46D-43F8-843B-917920AF806A",e.KBEditorControl="F94DB24F-263D-44A7-B38E-A35E9854812B",e.LinkControl="DFDF1CDE-837B-4AC9-98CF-AC74361FD89D"})(S||(S={}));Cl={[S.WebResourceHTMLControl]:"WebResource",[S.WebResourceImageControl]:"WebResource",[S.IframeControl]:"IFRAME",[S.SearchWidgetControl]:"Search widget",[S.SubgridControl]:"Subgrid",[S.TimelineControl]:"Timeline",[S.QuickViewControl]:"QuickviewControl"}});var oi=v((GW,my)=>{var So=new Proxy(function(){return So},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:So},apply:function(){return So},construct:function(){return{}}}),fy=function(){return So};Object.setPrototypeOf(fy,So);my.exports=fy});var ft,en,hy,gy,Ki=I(()=>{"use strict";ft="cds-designer-models",en="FormCustomControl",hy="FormCell",gy="Form"});var Xi,mt,No=I(()=>{"use strict";Xi=class{keys;values;constructor(){this.keys=[],this.values=[]}add(t,r){return this.containsKey(t)?!1:(this.keys.push(t),this.values.push(r),!0)}upsert(t,r){this.update(t,r)||this.add(t,r)}sortedUpsert(t,r){if(!this.update(t,r)){let n=0;for(;n<this.keys.length&&this.keys[n]<t;)n++;this.keys.splice(n,0,t),this.values.splice(n,0,r)}}clear(){this.keys=[],this.values=[]}containsKey(t){return this.keys.indexOf(t)!==-1}containsValue(t){return this.values.indexOf(t)!==-1}count(){return this.keys.length}getValue(t){let r=this.keys.indexOf(t);return r!==-1?this.values[r]:!1}getKeys(){return this.keys.slice()}getValues(){return this.values.slice()}remove(t){let r=this.keys.indexOf(t);return r!==-1?(this.keys.splice(r,1),this.values.splice(r,1),!0):!1}update(t,r){let n=this.keys.indexOf(t);return n!==-1?(this.values[n]=r,!0):!1}},mt=class{data={};add(t,r){return this.containsKey(t)?!1:(this.data[t]=r,!0)}upsert(t,r){this.data[t]=r}clear(){this.data={}}containsKey(t){return this.data.hasOwnProperty(t)}containsValue(t){for(let r in this.data)if(this.data[r]===t)return!0;return!1}count(){return Object.keys(this.data).length}getValue(t){return this.containsKey(t)?this.data[t]:!1}getKeys(){return Object.keys(this.data)}getValues(){let t=[];for(let r in this.data)t.push(this.data[r]);return t}remove(t){return this.containsKey(t)?delete this.data[t]:!1}update(t,r){return this.containsKey(t)?(this.data[t]=r,!0):!1}getInternalObject(){return this.data}}});var si,Kd=I(()=>{"use strict";No();X();si=class e{static lockedFieldCount=new mt;static dependencyFieldCount=new mt;static getNecessaryLookUpTable(t){switch(t){case _r.DependencyFieldTable:return e.dependencyFieldCount;case _r.LockedFieldTable:return e.lockedFieldCount}}static initCanvasLockedFieldLookUp(t){switch(t){case _r.DependencyFieldTable:e.dependencyFieldCount=new mt;case _r.LockedFieldTable:e.lockedFieldCount=new mt}}}});var El,vy=I(()=>{"use strict";Le();Oe();X();We();El=class extends H{constructor(t){super(b.controlDescription,t)}get forControl(){let t=this.getProperty(h.ForControl);return N.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new P(t))}set forControl(t){this.setProperty(h.ForControl,`{${t.ToString()}}`)}get customControls(){return this.getChildren(b.customControl)}set customControls(t){this.deleteAllChildren();for(let r of t)this.addChild(r)}get DefaultControlClassId(){for(let t of this.customControls)if(!N.IsNullOrUndefined(t.id))return t.id;return null}get DefaultCustomControl(){for(let t of this.customControls)if(!N.IsNullOrUndefined(t.id))return t;return null}get DefaultCustomControls(){let t=[];for(let r of this.customControls)N.IsNullOrUndefined(r.id)||t.push(r);return t}async toJSON(t){let r=await this.getCustomControlsJSON(t);return r?{UniqueId:this.forControl.guidString,CustomControls:r,VersionNumber:0,OverallVersionNumber:0}:null}async getCustomControlsJSON(t){if(this.customControls){let r=[];for(let n of this.customControls){let i=await n.toJSON(t);i&&r.push(i)}return r}return null}}});var by,wy,ht,T,yy,Ln,li,Yi,Xd,Yd,Zi=I(()=>{"use strict";by={Name:"Name",Value:"Value",Type:"Type",TypeGroup:"TypeGroup",Usage:"Usage",Static:"Static",Primary:"Primary",Columns:"Columns",EnableViewPicker:"EnableViewPicker",EntityName:"EntityName",FilteredViewIds:"FilteredViewIds",ReferencingName:"ReferencingName",RelationshipName:"RelationshipName",RelationshipType:"RelationshipType",TargetEntityType:"TargetEntityType",ViewId:"ViewId",DependentAttributeName:"DependentAttributeName",DependentAttributeType:"DependentAttributeType",DefaultViewId:"DefaultViewId",BindAttribute:"BindAttribute",FilterRelationshipName:"FilterRelationshipName",AvailableViewIds:"AvailableViewIds",QuickForms:"QuickForms",EntityNameKey:"EntityNameKey",CardFormType:"Form.Card",CardFormId:"CardFormId",Hidden:"Hidden",Required:"Required",DefaultValue:"DefaultValue"},wy={GroupDefinition:"GroupDefinition"},ht={Control:"control",Resources:"resources",DisplayNameKey:"display-name-key",descriptionKey:"description-key",value:"value",name:"name",defaultKey:"default",groups:"groups",group:"group",property:"property",hidden:"hidden",required:"required",typeGroup:"type-group",type:"type",usage:"usage",ofType:"of-type",ofTypeGroup:"of-type-group",ImageURL:"preview-image",DefaultValue:"default-value",static:"static",dataset:"data-set",propertySet:"property-set",initialDatasetFetch:"initial-data-set-fetch",editable:"editable",cdsDatasetOptions:"cds-data-set-options",allowDefaultSelectedItems:"allow-default-selected-items",resettable:"resettable",isGroup:"isGroup",entityName:"entityname"};(function(e){e.Boolean="Boolean",e.Currency="Currency",e.DateAndTimeDateAndTime="DateAndTime.DateAndTime",e.DateAndTimeDateOnly="DateAndTime.DateOnly",e.Decimal="Decimal",e.Enum="Enum",e.FP="FP",e.File="File",e.Guid="Guid",e.Image="Image",e.LookupCustomer="Lookup.Customer",e.LookupOwner="Lookup.Owner",e.LookupPartyList="Lookup.PartyList",e.LookupRegarding="Lookup.Regarding",e.LookupSimple="Lookup.Simple",e.Multiple="Multiple",e.MultiSelectOptionSet="MultiSelectOptionSet",e.OptionSet="OptionSet",e.SingleLineEmail="SingleLine.Email",e.SingleLinePhone="SingleLine.Phone",e.SingleLineText="SingleLine.Text",e.SingleLineTextArea="SingleLine.TextArea",e.SingleLineTickerSymbol="SingleLine.Ticker",e.SingleLineURL="SingleLine.URL",e.TwoOptions="TwoOptions",e.WholeDuration="Whole.Duration",e.WholeLanguage="Whole.Language",e.WholeNone="Whole.None",e.WholeTimeZone="Whole.TimeZone",e.BusinessProcessFlow="BusinessProcessFlow",e.CardForm="Form.Card",e.Dashboard="Dashboard",e.FormMain="Form.Main",e.Grid="Grid",e.PowerBIReport="PowerBI.Report",e.QuickForm="Form.QuickForm",e.Search="Search",e.SearchWidget="SearchWidget",e.TimelineWall="TimelineWall",e.UnboundCustomControl="Unbound",e.WebResourceHtmlControl="WebResource.HTML"})(T||(T={}));(function(e){e.BooleanType="CC_FlipLabel_Name",e.DateTimeType="CC_TextBox_Name",e.DecimalType="CC_TextBox_Name",e.DoubleType="CC_TextBox_Name",e.IntegerType="CC_TextBox_Name",e.LookupType="CC_TextBox_Name",e.MemoType="CC_TextArea_Name",e.MoneyType="CC_TextBox_Name",e.OptionSetType="CC_OptionSet_Name",e.StringType="CC_TextBox_Name",e.GridType="CC_ReadOnlyGrid_Name",e.UnboundCustomControlType="CC_UnboundCustomControl_Name"})(yy||(yy={}));(function(e){e.ArcKnobControl="MscrmControls.Knob.ArcKnobControl",e.CardFeedNameControl="MscrmControls.CardFeedContainer.CardFeedContainer",e.CheckboxControl="MscrmControls.FieldControls.CheckboxControl",e.DateTimeControl="MscrmControls.FieldControls.DateTimeControl",e.DurationControl="MscrmControls.FieldControls.DurationControl",e.EditableGridControl="MscrmControls.Grid.GridControl",e.EmailEngagementActionsControl="MscrmControls.EmailEngagement.EmailEngagementActionsControl",e.FormComponent="MscrmControls.ModelForm.ModelFormControl",e.LanguageCodeControl="MscrmControls.FieldControls.LanguagePickerControl",e.LinearSliderControl="MscrmControls.Slider.LinearSliderControl",e.MultiSelectOptionSetControl="MscrmControls.MultiSelectPicklist.UpdMSPicklistControl",e.OptionSetControl="MscrmControls.OptionSet.OptionSetControl",e.PowerBIPCFControl="MscrmControls.PowerBIPCFControl",e.PredictiveScoringWidget="MscrmControls.Sales.PredictiveScoringWidget.PredictiveScoringWidget",e.ReadonlyGrid="MscrmControls.Grid.ReadOnlyGrid",e.SimilarCasesGrid="MscrmControls.Containers.SimilarCasesGridControl",e.StarRatingControl="MscrmControls.Rating.StarRatingControl",e.TimeZoneControl="MscrmControls.FieldControls.TimeZonePickListControl",e.ModelFormControl="MscrmControls.ModelForm.ModelFormControl",e.AutoCompleteControl="MscrmControls.AutoComplete.AutoCompleteControl",e.CanvasAppControl="MscrmControls.Canvas.CanvasControl",e.PowerAppsOneGrid="Microsoft.PowerApps.PowerAppsOneGrid"})(Ln||(Ln={}));(function(e){e[e.Read=0]="Read",e[e.Edit=1]="Edit",e[e.Both=2]="Both",e[e.Container=3]="Container",e[e.Unknown=4]="Unknown"})(li||(li={}));(function(e){e[e.Bound=0]="Bound",e[e.Input=1]="Input",e[e.Output=2]="Output"})(Yi||(Yi={}));Xd=[T.LookupCustomer,T.LookupOwner,T.LookupPartyList,T.LookupRegarding,T.LookupSimple],Yd=[T.WholeNone,T.WholeDuration,T.WholeLanguage,T.WholeTimeZone,T.FP,T.Decimal]});function tn(){return Tr||(Tr=window._makerConfig,Tr&&window?.location?.search?.indexOf("useProductionConfig")>-1&&(Tr={...Tr,region:"prod",graphQLEndpoint:"https://graph.make.powerapps.com/"}),Tr?.region==="prod"&&(Tr={endpoints:{eu:{ch:{graphql:"https://graph-make.ch-cm001.gateway.prod.cm.powerapps.com/"},de:{graphql:"https://graph-make.de-cm001.gateway.prod.cm.powerapps.com/"},fr:{graphql:"https://graph-make.fr-cm001.gateway.prod.cm.powerapps.com/"},no:{graphql:"https://graph-make.no-cm001.gateway.prod.cm.powerapps.com/"},default:{graphql:"https://graph-make.eu-cm001.gateway.prod.cm.powerapps.com/"}}},...Tr}),Tr||{aadClientId:"a8f7a65c-f5ba-4859-b2d6-df772c264e9d",location:"cus",region:"test",publicPath:"/",graphQLEndpoint:"https://graph.make.test.powerapps.com/"})}var Tr,Sl=I(()=>{"use strict";});function Ay(e,t,r){if(!e)return Nl.has(e)||(window._ppux?.log?.("PPUX/Geo/NonExistent",{eventType:"Trace",team:"Shell",severity:"Error",errorCode:"GeoIsEmpty"}),Nl.add("")),!1;if(e){if(e=e.toLowerCase(),Nl.has(e))return!1;if(!(e in t))return window._ppux?.log?.("PPUX/Geo/NonExistent",{eventType:"Trace",team:"Shell",severity:"Error",errorCode:"GeoNonExistent",eventInfo:{missinggeo:e,parent:r}}),Nl.add(e),!1}return!0}function zL(e){return Ay(e,Zd,"Location dictionary")?Zd[e.toLowerCase()]:"us"}function WL(){let e=tn().location.toLowerCase();return Ay(e,Zd,"Current location dictionary")?e:"us"}var Nl,Zd,iH,Cy=I(()=>{"use strict";Sl();Nl=new Set,Zd={cae:"ae",nae:"ae",eas:"as",seas:"as",eau:"au",seau:"au",sbr:"br",cca:"ca",eca:"ca",nch:"ch",wch:"ch",nde:"de",wcde:"de",neu:"eu",weu:"eu",cfr:"fr",sfr:"fr",cin:"in",sin:"in",ejp:"jp",wjp:"jp",suk:"uk",wuk:"uk",eus:"us",wus:"us",cus:"us",ude:"us",udc:"us",ugtx:"us",ugva:"us",eus2:"us",wus2:"us",nza:"za",wza:"za",cne2:"cn",cnn2:"cn",skr:"kr",ckr:"kr",eno:"no",wno:"no",wrx:"us",erx:"us",wex:"us",eex:"us",unitedstates:"us",europe:"eu",asia:"as",australia:"au",japan:"jp",canada:"ca",india:"in",italy:"it",unitedstatesfirstrelease:"us",unitedkingdom:"uk",southamerica:"br",france:"fr",unitedarabemirates:"ae",germany:"de",sweden:"se",switzerland:"ch",korea:"kr",norway:"no",usgov:"us",usgovhigh:"us",usdod:"us",china:"cn",usnat:"us",ussec:"us",southafrica:"za",singapore:"sg",newzealand:"nz",poland:"pl",qatar:"qa",as:"as",au:"au",ca:"ca",in:"in",jp:"jp",kr:"kr",nz:"nz",ae:"ae",qa:"qa",us:"us",uk:"uk",eu:"eu",de:"de",ch:"ch",no:"no",fr:"fr",se:"se",it:"it",pl:"pl",be:"eu",bel:"eu",gr:"eu",grc:"eu",lt:"eu",ltu:"eu",pt:"eu",prt:"eu",bg:"eu",bgr:"eu",es:"eu",esp:"eu",lu:"eu",lux:"eu",ro:"eu",rou:"eu",cz:"eu",cze:"eu",hu:"eu",hun:"eu",si:"eu",svn:"eu",dk:"eu",dnk:"eu",hr:"eu",hrv:"eu",mt:"eu",mlt:"eu",sk:"eu",svk:"eu",nit:"it",nl:"eu",nld:"eu",fi:"eu",fin:"eu",ee:"eu",est:"eu",cy:"eu",cyp:"eu",at:"eu",aut:"eu",swe:"se",cse:"se",ie:"eu",irl:"eu",lv:"eu",lva:"eu",cpl:"pl",nnz:"nz",cqa:"qa",sg:"sg",br:"br",za:"za",sa:"za"};iH=zL(WL())});var U,oH,Ey=I(()=>{"use strict";U={USWest:"westus",USWest2:"westus2",USCentral:"centralus",USEast:"eastus",USEast2:"eastus2",USNorthCentral:"northcentralus",USSouthCentral:"southcentralus",USWestCentral:"westcentralus",CanadaCentral:"canadacentral",CanadaEast:"canadaeast",BrazilSouth:"brazilsouth",EuropeNorth:"northeurope",EuropeWest:"westeurope",UKSouth:"uksouth",UKWest:"ukwest",FranceCentral:"francecentral",FranceSouth:"francesouth",SwitzerlandNorth:"switzerlandnorth",SwitzerlandWest:"switzerlandwest",GermanyNorth:"germanynorth",GermanyWestCentral:"germanywestcentral",NorwayWest:"norwaywest",NorwayEast:"norwayeast",SwedenCentral:"swedencentral",ItalyNorth:"italynorth",PolandCentral:"polandcentral",AsiaEast:"eastasia",AsiaSouthEast:"southeastasia",JapanEast:"japaneast",JapanWest:"japanwest",AustraliaEast:"australiaeast",AustraliaSouthEast:"australiasoutheast",AustraliaCentral:"australiacentral",AustraliaCentral2:"australiacentral2",IndiaCentral:"centralindia",IndiaSouth:"southindia",IndiaWest:"westindia",KoreaSouth:"koreasouth",KoreaCentral:"koreacentral",NewZealandNorth:"newzealandnorth",UAECentral:"uaecentral",UAENorth:"uaenorth",SouthAfricaNorth:"southafricanorth",SouthAfricaWest:"southafricawest",QatarCentral:"qatarcentral",GermanyCentral:"germanycentral",GermanyNorthEast:"germanynortheast",SingaporeSouthEast:"southeastasia",GovernmentUSVirginia:"usgovvirginia",GovernmentUSIowa:"usgoviowa",GovernmentUSArizona:"usgovarizona",GovernmentUSTexas:"usgovtexas",GovernmentUSDodEast:"usdodeast",GovernmentUSDodCentral:"usdodcentral",ChinaNorth:"chinanorth",ChinaNorth2:"chinanorth2",ChinaNorth3:"chinanorth3",ChinaEast:"chinaeast",ChinaEast2:"chinaeast2",ChinaEast3:"chinaeast3",UssecEast:"usseceast",UssecWest:"ussecwest",UsnatEast:"usnateast",UsnatWest:"usnatwest"},oH={[U.USWest]:{geoName:"us",regionShortName:"wus"},[U.USCentral]:{geoName:"us",regionShortName:"cus"},[U.USEast]:{geoName:"us",regionShortName:"eus"},[U.USEast2]:{geoName:"us",regionShortName:"eus2"},[U.USWestCentral]:{geoName:"us",regionShortName:"wcus"},[U.USWest2]:{geoName:"us",regionShortName:"wus2"},[U.USSouthCentral]:{geoName:"br",regionShortName:"scus"},[U.BrazilSouth]:{geoName:"br",regionShortName:"sbr"},[U.UKSouth]:{geoName:"uk",regionShortName:"suk"},[U.UKWest]:{geoName:"uk",regionShortName:"wuk"},[U.JapanEast]:{geoName:"jp",regionShortName:"ejp"},[U.JapanWest]:{geoName:"jp",regionShortName:"wjp"},[U.IndiaCentral]:{geoName:"in",regionShortName:"cin"},[U.IndiaSouth]:{geoName:"in",regionShortName:"sin"},[U.ItalyNorth]:{geoName:"it",regionShortName:"nit"},[U.GermanyWestCentral]:{geoName:"de",regionShortName:"wcde"},[U.GermanyNorth]:{geoName:"de",regionShortName:"nde"},[U.EuropeNorth]:{geoName:"eu",regionShortName:"neu"},[U.EuropeWest]:{geoName:"eu",regionShortName:"weu"},[U.AustraliaEast]:{geoName:"au",regionShortName:"eau"},[U.AustraliaSouthEast]:{geoName:"au",regionShortName:"seau"},[U.AsiaSouthEast]:{geoName:"as",regionShortName:"seas"},[U.AsiaEast]:{geoName:"as",regionShortName:"eas"},[U.CanadaCentral]:{geoName:"ca",regionShortName:"cca"},[U.CanadaEast]:{geoName:"ca",regionShortName:"eca"},[U.SouthAfricaNorth]:{geoName:"za",regionShortName:"nza"},[U.SouthAfricaWest]:{geoName:"za",regionShortName:"wza"},[U.FranceCentral]:{geoName:"fr",regionShortName:"cfr"},[U.FranceSouth]:{geoName:"fr",regionShortName:"sfr"},[U.UAENorth]:{geoName:"ae",regionShortName:"nae"},[U.UAECentral]:{geoName:"ae",regionShortName:"cae"},[U.SwedenCentral]:{geoName:"se",regionShortName:"cse"},[U.SwitzerlandNorth]:{geoName:"ch",regionShortName:"nch"},[U.SwitzerlandWest]:{geoName:"ch",regionShortName:"wch"},[U.NorwayEast]:{geoName:"no",regionShortName:"eno"},[U.NorwayWest]:{geoName:"no",regionShortName:"wno"},[U.KoreaCentral]:{geoName:"kr",regionShortName:"ckr"},[U.KoreaSouth]:{geoName:"kr",regionShortName:"skr"},[U.SingaporeSouthEast]:{geoName:"sg",regionShortName:"seas"},[U.PolandCentral]:{geoName:"pl",regionShortName:"cpl"},[U.QatarCentral]:{geoName:"qa",regionShortName:"cqa"},[U.NewZealandNorth]:{geoName:"nz",regionShortName:"nnz"},[U.GovernmentUSTexas]:{geoName:"us",regionShortName:"ugtx"},[U.GovernmentUSVirginia]:{geoName:"us",regionShortName:"ugva"},[U.GovernmentUSDodCentral]:{regionShortName:"udc"},[U.GovernmentUSDodEast]:{regionShortName:"ude"},[U.ChinaEast]:{regionShortName:"cne"},[U.ChinaEast2]:{regionShortName:"cne2"},[U.ChinaEast3]:{regionShortName:"cne3"},[U.ChinaNorth]:{regionShortName:"cnn"},[U.ChinaNorth2]:{regionShortName:"cnn2"},[U.ChinaNorth3]:{regionShortName:"cnn3"},[U.UssecEast]:{geoName:"us",regionShortName:"erx"},[U.UssecWest]:{geoName:"us",regionShortName:"wrx"},[U.UsnatEast]:{geoName:"us",regionShortName:"eex"},[U.UsnatWest]:{geoName:"us",regionShortName:"wex"}}});var Sy=I(()=>{"use strict";Sl();});var Do=I(()=>{"use strict";Sl();Cy();Ey();Sy();});function Io(e,t){return Ny?Ny.isOverridden(e,t):{overridden:!1}}var Ny,_o=I(()=>{"use strict";});var ep=I(()=>{"use strict";Do();_o();});function HL(e,t){let{region:r}=tn();return()=>{let n=e.settings[t];if(n.allowOverrides){let s=Io(e.packageName,t);if(s.overridden)return typeof s.value=="string"?jL(s.value):s.value}let a=n.values,o=process.env.SETTINGS_FALLBACK_REGION?.[r];return a[r]!==void 0?a[r]:o&&a[o]!==void 0?a[o]:a.default}}function jL(e){return isNaN(Number(e))?e==="true"?!0:e==="false"?!1:e:Number(e)}function JL(e){let t=e.packageName;if(Dl.has(t)){let r=`settings has already been created for this package ${t}`;throw console.error(r),new Error(r)}if(Object.keys(e.settings).some(r=>rp(t,r))){let r=`error parsing settings config for package ${t}, a feature gate with the same name exists`;throw console.error(r),new Error(r)}Object.keys(e.settings).forEach(r=>{if(Object.keys(e.settings[r].values).filter(i=>i!=="default").some(i=>!_l(i))){let i=`error parsing settings config for package ${t}, setting ${r} has invalid region`;throw console.error(i),new Error(i)}})}function To(e){JL(e);let t={};return Object.keys(e.settings).forEach(r=>{t[r]={enumerable:!0,get:HL(e,r)}}),Dl.set(e.packageName,e),Object.defineProperties({},t)}function tp(e,t){return Dl.has(e)?!!Dl.get(e).settings[t]:!1}var Dl,Il=I(()=>{"use strict";Do();_o();np();Po();Dl=new Map});function Dy(e,t){let{region:r}=tn();return()=>{let n=Io(e.packageName,t);if(n.overridden)return n.value.toString()==="true";let i=e.features[t].enabledFor,a=process.env.SETTINGS_FALLBACK_REGION?.[r];return i[r]!==void 0?!!i[r]:a&&i[a]!==void 0?!!i[a]:!1}}function QL(e){let t=e.packageName;if(Tl.has(t)){let r="feature gates has already been created for this package";throw console.error(r),new Error(r)}if(Object.keys(e.features).some(r=>tp(t,r))){let r=`error parsing feature gates config for package ${t}, a setting with the same name exists`;throw console.error(r),new Error(r)}Object.keys(e.features).forEach(r=>{if(Object.keys(e.features[r].enabledFor).some(i=>!_l(i))){let i=`error parsing feature gates config for package ${t}, feature ${r} has invalid region`;throw console.error(i),new Error(i)}})}function ip(e){QL(e);let t={};Object.keys(e.features).forEach(i=>{t[i]={enumerable:!0,configurable:!0,get:Dy(e,i)}});let r={},n=new Set;return t.dangerouslySet={enumerable:!1,value:(i,a)=>{n.add(i),Object.defineProperty(r,i,{enumerable:!0,configurable:!0,value:a})}},t.dangerouslyReset={enumerable:!1,value:()=>{let i={};n.forEach(a=>{i[a.toString()]={enumerable:!0,configurable:!0,get:Dy(e,a.toString())}}),Object.defineProperties(r,i),n.clear()}},Tl.set(e.packageName,e),Object.defineProperties(r,t)}function rp(e,t){return Tl.has(e)?!!Tl.get(e).features[t]:!1}var Tl,np=I(()=>{"use strict";Do();Po();_o();Il();Tl=new Map});var _y=v((OH,Iy)=>{"use strict";Iy.exports=function(t,r){if(r=r.split(":")[0],t=+t,!t)return!1;switch(r){case"http":case"ws":return t!==80;case"https":case"wss":return t!==443;case"ftp":return t!==21;case"gopher":return t!==70;case"file":return!1}return t!==0}});var Oy=v(ap=>{"use strict";var KL=Object.prototype.hasOwnProperty,XL;function Ty(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch{return null}}function Py(e){try{return encodeURIComponent(e)}catch{return null}}function YL(e){for(var t=/([^=?#&]+)=?([^&]*)/g,r={},n;n=t.exec(e);){var i=Ty(n[1]),a=Ty(n[2]);i===null||a===null||i in r||(r[i]=a)}return r}function ZL(e,t){t=t||"";var r=[],n,i;typeof t!="string"&&(t="?");for(i in e)if(KL.call(e,i)){if(n=e[i],!n&&(n===null||n===XL||isNaN(n))&&(n=""),i=Py(i),n=Py(n),i===null||n===null)continue;r.push(i+"="+n)}return r.length?t+r.join("&"):""}ap.stringify=ZL;ap.parse=YL});var lp=v((FH,My)=>{"use strict";var Fy=_y(),Pl=Oy(),xy=/[\n\r\t]/g,ek=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,tk=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,rk=/^[a-zA-Z]:/,nk=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;function sp(e){return(e||"").toString().replace(nk,"")}var op=[["#","hash"],["?","query"],function(t,r){return Pr(r.protocol)?t.replace(/\\/g,"/"):t},["/","pathname"],["@","auth",1],[NaN,"host",void 0,1,1],[/:(\d*)$/,"port",void 0,1],[NaN,"hostname",void 0,1,1]],Ry={hash:1,query:1};function Ly(e){var t;typeof window<"u"?t=window:typeof global<"u"?t=global:typeof self<"u"?t=self:t={};var r=t.location||{};e=e||r;var n={},i=typeof e,a;if(e.protocol==="blob:")n=new Or(unescape(e.pathname),{});else if(i==="string"){n=new Or(e,{});for(a in Ry)delete n[a]}else if(i==="object"){for(a in e)a in Ry||(n[a]=e[a]);n.slashes===void 0&&(n.slashes=ek.test(e.href))}return n}function Pr(e){return e==="file:"||e==="ftp:"||e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function ky(e,t){e=sp(e),e=e.replace(xy,""),t=t||{};var r=tk.exec(e),n=r[1]?r[1].toLowerCase():"",i=!!r[2],a=!!r[3],o=0,s;return i?a?(s=r[2]+r[3]+r[4],o=r[2].length+r[3].length):(s=r[2]+r[4],o=r[2].length):a?(s=r[3]+r[4],o=r[3].length):s=r[4],n==="file:"?o>=2&&(s=s.slice(2)):Pr(n)?s=r[4]:n?i&&(s=s.slice(2)):o>=2&&Pr(t.protocol)&&(s=r[4]),{protocol:n,slashes:i||Pr(n),slashesCount:o,rest:s}}function ik(e,t){if(e==="")return t;for(var r=(t||"/").split("/").slice(0,-1).concat(e.split("/")),n=r.length,i=r[n-1],a=!1,o=0;n--;)r[n]==="."?r.splice(n,1):r[n]===".."?(r.splice(n,1),o++):o&&(n===0&&(a=!0),r.splice(n,1),o--);return a&&r.unshift(""),(i==="."||i==="..")&&r.push(""),r.join("/")}function Or(e,t,r){if(e=sp(e),e=e.replace(xy,""),!(this instanceof Or))return new Or(e,t,r);var n,i,a,o,s,l,u=op.slice(),c=typeof t,d=this,p=0;for(c!=="object"&&c!=="string"&&(r=t,t=null),r&&typeof r!="function"&&(r=Pl.parse),t=Ly(t),i=ky(e||"",t),n=!i.protocol&&!i.slashes,d.slashes=i.slashes||n&&t.slashes,d.protocol=i.protocol||t.protocol||"",e=i.rest,(i.protocol==="file:"&&(i.slashesCount!==2||rk.test(e))||!i.slashes&&(i.protocol||i.slashesCount<2||!Pr(d.protocol)))&&(u[3]=[/(.*)/,"pathname"]);p<u.length;p++){if(o=u[p],typeof o=="function"){e=o(e,d);continue}a=o[0],l=o[1],a!==a?d[l]=e:typeof a=="string"?(s=a==="@"?e.lastIndexOf(a):e.indexOf(a),~s&&(typeof o[2]=="number"?(d[l]=e.slice(0,s),e=e.slice(s+o[2])):(d[l]=e.slice(s),e=e.slice(0,s)))):(s=a.exec(e))&&(d[l]=s[1],e=e.slice(0,s.index)),d[l]=d[l]||n&&o[3]&&t[l]||"",o[4]&&(d[l]=d[l].toLowerCase())}r&&(d.query=r(d.query)),n&&t.slashes&&d.pathname.charAt(0)!=="/"&&(d.pathname!==""||t.pathname!=="")&&(d.pathname=ik(d.pathname,t.pathname)),d.pathname.charAt(0)!=="/"&&Pr(d.protocol)&&(d.pathname="/"+d.pathname),Fy(d.port,d.protocol)||(d.host=d.hostname,d.port=""),d.username=d.password="",d.auth&&(s=d.auth.indexOf(":"),~s?(d.username=d.auth.slice(0,s),d.username=encodeURIComponent(decodeURIComponent(d.username)),d.password=d.auth.slice(s+1),d.password=encodeURIComponent(decodeURIComponent(d.password))):d.username=encodeURIComponent(decodeURIComponent(d.auth)),d.auth=d.password?d.username+":"+d.password:d.username),d.origin=d.protocol!=="file:"&&Pr(d.protocol)&&d.host?d.protocol+"//"+d.host:"null",d.href=d.toString()}function ak(e,t,r){var n=this;switch(e){case"query":typeof t=="string"&&t.length&&(t=(r||Pl.parse)(t)),n[e]=t;break;case"port":n[e]=t,Fy(t,n.protocol)?t&&(n.host=n.hostname+":"+t):(n.host=n.hostname,n[e]="");break;case"hostname":n[e]=t,n.port&&(t+=":"+n.port),n.host=t;break;case"host":n[e]=t,/:\d+$/.test(t)?(t=t.split(":"),n.port=t.pop(),n.hostname=t.join(":")):(n.hostname=t,n.port="");break;case"protocol":n.protocol=t.toLowerCase(),n.slashes=!r;break;case"pathname":case"hash":if(t){var i=e==="pathname"?"/":"#";n[e]=t.charAt(0)!==i?i+t:t}else n[e]=t;break;case"username":case"password":n[e]=encodeURIComponent(t);break;case"auth":var a=t.indexOf(":");~a?(n.username=t.slice(0,a),n.username=encodeURIComponent(decodeURIComponent(n.username)),n.password=t.slice(a+1),n.password=encodeURIComponent(decodeURIComponent(n.password))):n.username=encodeURIComponent(decodeURIComponent(t))}for(var o=0;o<op.length;o++){var s=op[o];s[4]&&(n[s[1]]=n[s[1]].toLowerCase())}return n.auth=n.password?n.username+":"+n.password:n.username,n.origin=n.protocol!=="file:"&&Pr(n.protocol)&&n.host?n.protocol+"//"+n.host:"null",n.href=n.toString(),n}function ok(e){(!e||typeof e!="function")&&(e=Pl.stringify);var t,r=this,n=r.host,i=r.protocol;i&&i.charAt(i.length-1)!==":"&&(i+=":");var a=i+(r.protocol&&r.slashes||Pr(r.protocol)?"//":"");return r.username?(a+=r.username,r.password&&(a+=":"+r.password),a+="@"):r.password?(a+=":"+r.password,a+="@"):r.protocol!=="file:"&&Pr(r.protocol)&&!n&&r.pathname!=="/"&&(a+="@"),n[n.length-1]===":"&&(n+=":"),a+=n+r.pathname,t=typeof r.query=="object"?e(r.query):r.query,t&&(a+=t.charAt(0)!=="?"?"?"+t:t),r.hash&&(a+=r.hash),a}Or.prototype={set:ak,toString:ok};Or.extractProtocol=ky;Or.location=Ly;Or.trimLeft=sp;Or.qs=Pl;My.exports=Or});var sk,Uy=I(()=>{"use strict";sk=ie(lp());});function up(e,t,r){let n=Object.keys(r).sort();if(n.length===0)throw new Error(`ECS feature has no properties: ${e}.${t}`);let i=`ecs.${e}.${t}`;return n.length===1?`${i}.${n[0]}`:`${i}.{${n.join(";")}}`}var Ol=I(()=>{"use strict";});var cp,dp,pp=I(()=>{"use strict";Ol();cp=class{features=new Map;register(t,r){let n=up(r,t.teamName,t.fallback),i={clientName:r,teamName:t.teamName,fullName:n,description:t.description,owners:t.owners,ecsURL:t.ecsURL,createdOn:t.createdOn,fallbackConfig:t.fallback,feature:t,displayTeam:t.displayTeam,tags:t.tags,category:t.category};this.features.set(n,i)}getAll(){return Array.from(this.features.values())}get(t){return this.features.get(t)}has(t){return this.features.has(t)}getByClient(t){return this.getAll().filter(r=>r.clientName===t)}getByTeam(t){return this.getAll().filter(r=>r.teamName===t)}search(t){let r=t.toLowerCase();return this.getAll().filter(n=>n.fullName.toLowerCase().includes(r)||n.description?.toLowerCase().includes(r)||n.teamName.toLowerCase().includes(r)||n.clientName.toLowerCase().includes(r))}getClientNames(){let t=new Set;return this.features.forEach(r=>t.add(r.clientName)),Array.from(t)}getTeamNames(){let t=new Set;return this.features.forEach(r=>t.add(r.teamName)),Array.from(t)}clear(){this.features.clear()}},dp=new cp});var fp=I(()=>{"use strict";});function _l(e){return lk.has(e)}var lk,Po=I(()=>{"use strict";ep();np();Il();_o();ep();Uy();pp();Ol();fp();lk=new Set(["tie","test","prod","preview","preprod","gov","high","dod","mooncake","ex","rx"])});var uk,By=I(()=>{"use strict";Po();uk=To({packageName:"cds-designer-models",settings:{testCustomControls:{description:"Test Custom Controls to show up in the component picker.",allowOverrides:!0,values:{default:"",test:"",preprod:"",preview:"",gov:""}}}})});var Rl,R,$,ui,ea,Fl,$y,qy,mp,Oo=I(()=>{"use strict";No();Rl=class{name;constructor(t){this.name=t}toString(){return this.name}getName(){return this.name}getDisplayNameResourceKey(){return mp.getDisplayNameResourceKey(this.name)}};(function(e){e.BigInt="BigIntType",e.CalendarRulesType="CalendarRulesType",e.Currency="MoneyType",e.Customer="Customer",e.CustomerType="CustomerType",e.DateTime="DateTimeType",e.DecimalNumber="DecimalType",e.EntityNameType="EntityNameType",e.FloatingPointNumber="DoubleType",e.Image="ImageType",e.File="FileType",e.Lookup="Lookup",e.LookupType="LookupType",e.ManagedPropertyType="ManagedPropertyType",e.MultipleLineofText="MemoType",e.MultiSelectOptionSet="MultiSelectPicklistType",e.OptionSet="PicklistType",e.Owner="Owner",e.OwnerType="OwnerType",e.PartyList="PartyList",e.PartyListType="PartyListType",e.PrimaryNameAttributeType="String",e.SingleLineofText="StringType",e.State="StateType",e.Status="StatusType",e.Subject="Subject",e.TimeStamp="TimeStampType",e.TwoOptions="BooleanType",e.UniqueIdentifier="Uniqueidentifier",e.UniqueIdentifierType="UniqueidentifierType",e.VirtualType="VirtualType",e.WholeNumber="IntegerType"})(R||(R={}));(function(e){e.Email="Email",e.Text="Text",e.TextArea="TextArea",e.Url="Url",e.TickerSymbol="TickerSymbol",e.PhoneticGuide="PhoneticGuide",e.VersionNumber="VersionNumber",e.Phone="Phone",e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale",e.DateOnly="DateOnly",e.DateAndTime="DateAndTime",e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean",e.Regarding="Regarding"})($||($={}));ui=class extends Rl{constructor(t){super(t)}static get None(){return"None"}static get SystemRequired(){return"SystemRequired"}static get ApplicationRequired(){return"ApplicationRequired"}static get Recommended(){return"Recommended"}},ea=class e extends Rl{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get Persistent(){return"Persistent"}static get Calculated(){return"Calculated"}static get Rollup(){return"Rollup"}GetValue(){return this.name===e.None?Fl.Persistent:parseInt(Fl[this.name])}};(function(e){e[e.Persistent=0]="Persistent",e[e.Calculated=1]="Calculated",e[e.Rollup=2]="Rollup"})(Fl||(Fl={}));(function(e){e[e.Undefined=0]="Undefined",e[e.Simple=1]="Simple",e[e.Related=2]="Related",e[e.Logical=4]="Logical",e[e.Calculated=8]="Calculated",e[e.Rollup=16]="Rollup",e[e.Invalid=32]="Invalid"})($y||($y={}));(function(e){e[e.Attribute=0]="Attribute",e[e.Organization=1]="Organization",e[e.Currency=2]="Currency"})(qy||(qy={}));mp=class e{static resourceKeyMap=e.initResourceKeyMap();static initResourceKeyMap(){let t=new Xi;return t.add(R.TwoOptions,"SystemCustomization.type.bit.label"),t.add(R.Customer,"SystemCustomization.type.customer.label"),t.add(R.CustomerType,"SystemCustomization.type.customer.label"),t.add(R.DateTime,"SystemCustomization.type.datetime.label"),t.add(R.DecimalNumber,"SystemCustomization.type.decimal.label"),t.add(R.FloatingPointNumber,"SystemCustomization.type.float.label"),t.add(R.WholeNumber,"SystemCustomization.type.int.label"),t.add(R.LookupType,"SystemCustomization.type.lookup.label"),t.add(R.Lookup,"SystemCustomization.type.lookup.label"),t.add(R.MultipleLineofText,"SystemCustomization.type.ntext.label"),t.add(R.Currency,"SystemCustomization.type.money.label"),t.add(R.Owner,"SystemCustomization.type.owner.label"),t.add(R.OwnerType,"SystemCustomization.type.owner.label"),t.add(R.PartyList,"SystemCustomization.type.partylist.label"),t.add(R.PartyListType,"SystemCustomization.type.partylist.label"),t.add(R.OptionSet,"SystemCustomization.type.picklist.label"),t.add(R.State,"SystemCustomization.type.state.label"),t.add(R.Status,"SystemCustomization.type.status.label"),t.add(R.SingleLineofText,"SystemCustomization.type.nvarchar.label"),t.add(R.UniqueIdentifier,"SystemCustomization.type.uniqueidentifier.label"),t.add(R.UniqueIdentifierType,"SystemCustomization.type.uniqueidentifiertype.label"),t.add(R.CalendarRulesType,"SystemCustomization.type.calendarrules.label"),t.add(R.VirtualType,"SystemCustomization.type.virtual.label"),t.add(R.BigInt,"SystemCustomization.type.bigint.label"),t.add(R.ManagedPropertyType,"SystemCustomization.type.managedproperty.label"),t.add(R.EntityNameType,"SystemCustomization.type.entityname.label"),t.add(R.Image,"SystemCustomization.type.image.label"),t.add(R.MultiSelectOptionSet,"SystemCustomization.type.multiselectpicklist.label"),t.add(R.PrimaryNameAttributeType,"SystemCustomization.type.primaryname.label"),t.add(R.LookupType,"SystemCustomization.type.lookuptype.label"),t.add(R.Subject,"SystemCustomization.type.subject.label"),t.add($.Email,"SystemCustomization.String.Format.email"),t.add($.Text,"SystemCustomization.String.Format.text"),t.add($.TextArea,"SystemCustomization.String.Format.textarea"),t.add($.Url,"SystemCustomization.String.Format.url"),t.add($.TickerSymbol,"SystemCustomization.String.Format.tickersymbol"),t.add($.PhoneticGuide,"SystemCustomization.String.Format.phoneticguide"),t.add($.VersionNumber,"SystemCustomization.String.Format.versionnumber"),t.add($.Phone,"SystemCustomization.String.Format.phone"),t.add($.None,"SystemCustomization.Integer.Format."),t.add($.Duration,"SystemCustomization.Integer.Format.duration"),t.add($.TimeZone,"SystemCustomization.Integer.Format.timezone"),t.add($.Language,"SystemCustomization.Integer.Format.language"),t.add($.Locale,"SystemCustomization.Integer.Format.language"),t.add($.DateOnly,"SystemCustomization.DateTime.Format.date"),t.add($.DateAndTime,"SystemCustomization.DateTime.Format.datetime"),t.add($.Regarding,"SystemCustomization.Lookup.Format.regarding"),t.add(ea.Persistent,"SystemCustomization.String.Source.persistent"),t.add(ea.Calculated,"SystemCustomization.String.Source.calculated"),t.add(ea.Rollup,"SystemCustomization.String.Source.rollup"),t.add(ea.None,"SystemCustomization.String.Source.none"),t}static getDisplayNameResourceKey(t){return e.resourceKeyMap.getValue(t)}}});var Wy,gp,ta,ci,hp,xl,ra,rn,we,Vy,Gy,zy,cr=I(()=>{"use strict";Wy={ThreeEqColumn_FirstColumn:34,ThreeEqColumn_SecondColumn:33,ThreeEqColumn_ThirdColumn:33,FiveEqColumn:20},gp={ONE_COLUMN:"1",TWO_COLUMN:"2",THREE_COLUMN:"3",FOUR_COLUMN:"4"};(function(e){e[e.SUBGRID=0]="SUBGRID",e[e.SPACER=1]="SPACER",e[e.QUICK_VIEW=2]="QUICK_VIEW",e[e.WEB_RESOURCE=3]="WEB_RESOURCE",e[e.IFRAME=4]="IFRAME",e[e.BING_MAPS=5]="BING_MAPS",e[e.TIMER=6]="TIMER",e[e.TIMELINE=7]="TIMELINE",e[e.SOCIAL_INSIGHTS=8]="SOCIAL_INSIGHTS",e[e.KB_SEARCH=9]="KB_SEARCH",e[e.ACI_CONTROL=10]="ACI_CONTROL",e[e.RELATIONSHIP_ASSISTANT=11]="RELATIONSHIP_ASSISTANT",e[e.REFERENCE_PANEL=12]="REFERENCE_PANEL",e[e.REF_PANEL_QUICKVIEW=13]="REF_PANEL_QUICKVIEW",e[e.REF_PANEL_SUBGRID=14]="REF_PANEL_SUBGRID",e[e.REF_PANEL_KBSEARCH=15]="REF_PANEL_KBSEARCH",e[e.WEB_RESOURCE_HTML=16]="WEB_RESOURCE_HTML",e[e.PRED_LEAD_SCORING=17]="PRED_LEAD_SCORING"})(ta||(ta={}));(function(e){e.Left="Left",e.Right="Right",e.Center="Center"})(ci||(ci={}));(function(e){e[e.Mobile=0]="Mobile",e[e.Tablet=1]="Tablet",e[e.Web=2]="Web"})(hp||(hp={}));xl=class{static ONE_COLUMN=1;static TWO_COLUMN=2;static THREE_COLUMN=3;static FIVE_COLUMN=5};(function(e){e.Left="Left",e.Top="Top"})(ra||(ra={}));rn=class{static StartTag="<"},we={ShowLabel:"true",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_",labelAlignment:ci.Left,labelPosition:ra.Left,MarginalControlColumns:"111",referencePanelNamePrefix:"ref_pan_"};(function(e){e.AddFormBodyFieldToReadOnlyHeader="AddFormBodyFieldToReadOnlyHeader",e.AddFieldPaneFieldToReadOnlyHeader="AddFieldPaneFieldToReadOnlyHeader",e.AddFieldExceedsReadOnlyHeaderLimit="AddFieldExceedsReadOnlyHeaderLimit",e.AddCustomComponentToReadOnlyHeader="AddCustomComponentToReadOnlyHeader",e.AddNonDisplayableComponentToReadOnlyHeader="AddNonDisplayableComponentToReadOnlyHeader",e.AddFieldToFlyoutOnly="AddFieldToFlyoutOnly",e.DisplayedFieldToFlyout="DisplayedFieldToFlyout",e.FlyoutFieldToDisplayed="FlyoutFieldToDisplayed",e.AddControlBeforeDefaultLabel="AddControlBeforeDefaultLabel"})(Vy||(Vy={}));(function(e){e.TabWithLockedFieldRemoval="TabWithLockedFieldRemoval",e.SectionWithLockedFieldRemoval="SectionWithLockedFieldRemoval",e.LockedSectionRemoval="LockedSectionRemoval",e.LockedFieldRemoval="LockedFieldRemoval",e.RequiredFieldRemoval="RequiredFieldRemoval",e.LastRemainingTab="LastRemainingTab",e.UnknownRemoval="UnknownRemoval"})(Gy||(Gy={}));(function(e){e.IsHeader="IsHeader",e.IsFooter="IsFooter",e.ContainedInHeader="ContainedInHeader",e.ContainedInFooter="ContainedInFooter",e.NoElementFound="NoElementFound",e.NoTarget="NoTarget",e.CannotAddControlToHeader="CannotAddControlToHeader",e.CannotAddControlToFooter="CannotAddControlToFooter"})(zy||(zy={}))});var vp,Hy=I(()=>{"use strict";(function(e){e.DefaultValue="defaultValue",e.Loaded="loaded"})(vp||(vp={}))});var Qy,ck,jy,Oj,Rj,Ro,Jy,Fj,xj,Ky=I(()=>{"use strict";Qy=ie(oi());Oe();Ki();By();Oo();cr();Zi();X();ck=ie(Yn());Hy();(function(e){e.Model="Model",e.Canvas="Canvas",e.CustomPages="CustomPages"})(jy||(jy={}));Oj={Read:li.Read,Edit:li.Edit,Both:li.Both,Container:li.Container},Rj={input:Yi.Input,bound:Yi.Bound,output:Yi.Output};(function(e){e[e.dataset=0]="dataset",e[e.property=1]="property",e[e.groups=2]="groups",e[e.group=3]="group"})(Ro||(Ro={}));(function(e){e[e.None=0]="None",e[e.HiddenControl=1]="HiddenControl",e[e.CompatibleDataTypesIsMissing=2]="CompatibleDataTypesIsMissing",e[e.TagNameIsUnsupported=3]="TagNameIsUnsupported",e[e.PropertyTypeIsUnsupported=4]="PropertyTypeIsUnsupported",e[e.PropertyTypeGroupIsUnsupported=5]="PropertyTypeGroupIsUnsupported"})(Jy||(Jy={}));Fj=new Set([T.Currency,T.Decimal,T.FP,T.Multiple,T.SingleLineEmail,T.SingleLinePhone,T.SingleLineText,T.SingleLineTextArea,T.SingleLineURL,T.SingleLineTickerSymbol,T.WholeNone,T.WholeDuration,T.WholeLanguage,T.WholeTimeZone,T.Enum,T.LookupSimple,T.LookupCustomer,T.LookupOwner,T.LookupPartyList,T.LookupRegarding,T.TwoOptions,T.Boolean,T.PowerBIReport,T.DateAndTimeDateAndTime,T.DateAndTimeDateOnly,T.OptionSet,T.MultiSelectOptionSet,T.CardForm]),xj={numbers:[T.WholeNone,T.FP,T.Decimal,T.Currency],text:[T.SingleLineText,T.SingleLineTextArea,T.Multiple],lookup:[T.LookupSimple,T.LookupCustomer,T.LookupOwner,T.LookupPartyList,T.LookupRegarding],dates:[T.DateAndTimeDateOnly,T.DateAndTimeDateAndTime],allFields:[T.TwoOptions,T.DateAndTimeDateOnly,T.DateAndTimeDateAndTime,T.FP,T.Decimal,T.WholeNone,T.WholeDuration,T.WholeTimeZone,T.WholeLanguage,T.LookupSimple,T.LookupCustomer,T.LookupOwner,T.LookupPartyList,T.LookupRegarding,T.Multiple,T.OptionSet,T.SingleLineText,T.SingleLineTextArea,T.SingleLineEmail,T.SingleLineURL,T.SingleLineTickerSymbol,T.SingleLinePhone]}});var dr,Ll,Xy=I(()=>{"use strict";dr=ie(oi());Le();Oe();nt();Ki();Zi();Ky();Oo();X();We();cr();Ll=class extends H{constructor(t){super(b.customControl,t)}customControlId;get id(){let t=this.getProperty(h.id);return N.IsNullOrUndefined(t)?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new P(t.substr(1,t.length-2)):new P(t)}getParameters(){let t=new Map,r=this.getAllChildren();if(r&&r.length!==0&&r[0]){let n=r[0].getAllChildren();if(n!=null){for(let i of n)if(i&&i.getAllChildren().length>0){let a=i.getNodeName();t.get(a)?t.get(a).push(i):t.set(a,[i])}}}return t}getFormComponentValueByParameterName(t){let r=this.getParameters()?.get(ht.value);if(r?.length>0){let n=r[0],i=n?.getAllChildren()?.length>0?n.getAllChildren().find(o=>o.getNodeName()===t):null,a=i?.getAllChildren()?.length>0?i.getAllChildren()[0].getNodeName():"";return this.normalizePropertyValue(a)}}getParameterValue(t){let r=this.getParameterNodeChild(t);return r&&this.normalizePropertyValue(r.getNodeName())}getParameterNodeChild(t){let r=this.getParameters().get(t);return r?.length>0&&r[0].getAllChildren()?.length>0?r[0].getAllChildren()[0]:null}getDatasetName(t){return t.getAllProperties().find(r=>r.key===ht.name)?.value}getParameterChildrenValues(t,r,n){if(this.isDataSet(t)){let i=r.find(u=>u.key===ht.name)?.value,a={Name:i,Type:T.Grid,Columns:[]},l=this.getParameters().get(ht.dataset).find(u=>this.getDatasetName(u)===i).getAllChildren();for(let u of l){let c=u.getNodeName();if(u&&u.getAllChildren().length>0){let d=this.normalizePropertyValue(u.getAllChildren()[0].getNodeName());a[c]=d}}return a}}getParameterIsStatic(t){let r=!1,n=this.getParameters().get(t)[0],i=n&&n.getAllProperties();if(i){for(let a of i)if(a.key===h.static&&a.value==="true"){r=!0;break}}return r}get name(){return this.getProperty(h.Name)}get formFactor(){return this.getProperty(h.formFactor)}set formFactor(t){this.setProperty(h.formFactor,t)}async toJSON(t){if(this.id)return null;let r=await this.parametersToJSON(t),n=parseInt(this.formFactor,10);return{CustomControlId:this.customControlId,FormFactor:isNaN(n)?-1:n,Name:this.name,Version:null,Parameters:r,ShouldOverrideControlVisible:!1}}normalizePropertyValue(t){return t.startsWith(rn.StartTag)&&(t=t.substring(1)),t}async parametersToJSON(t){let r=[];if(!this.name)return r;try{let n=await t.formModelService.customControlDiscoveryService.getCustomControlMetadata(this.name);if(n)if(n.configurations){let i=n.configurations,a=this.getParameters();for(let[o,s]of a)if(this.isDataSet(o))for(let l of a.get(o)){let u=l.getAllProperties(),c=this.getDatasetName(l),d=i.get(c),p=await this.parameterJSON(o,u,d,t);r.push({Name:c,Value:p})}else if(this.isGroups(s))r.push({Name:o,Value:{Type:wy.GroupDefinition,Value:this.normalizePropertyValue(this.getParameterNodeChild(s[0].NodeName).NodeName)}}),i.get(o).groupSet?.forEach(u=>{u.groupConfigurableProperties.forEach(async c=>{let d=c.name;c.propertyType===Ro.dataset?a.get(ht.dataset)?.some(f=>this.getDatasetName(f)===d)||r.push({Name:d,Value:{Name:d,Columns:[],Type:T.Grid}}):c.propertyType===Ro.property&&(a.has(d)||r.push({Name:d,Value:{Usage:c.usage}}))})});else{let l=s[0].getAllProperties(),u=i.get(o),c=await this.parameterJSON(o,l,u,t);if(c)r.push({Name:o,Value:c});else{(0,dr.trackInfoTrace)(ft,{eventName:`${en}/parametersToJSON`,eventData:{message:`Configuration metadata for custom control parameter ${o} is not available for custom control : ${this.name}.`}}),r=[];break}}}else(0,dr.trackErrorTrace)(ft,{eventName:`${en}/parametersToJSON`,eventData:{message:"Custom Control Manifest Property Info not available"}},new Error(`Custom Control Manifest Property Info not available for custom control : ${this.name}.`));else(0,dr.trackErrorTrace)(ft,{eventName:`${en}/parametersToJSON`,eventData:{message:"Custom Control Manifest not found"}},new Error(`No custom control manifest found for ${this.name}`))}catch(n){(0,dr.trackErrorTrace)(ft,{eventName:`${en}/parametersToJSON`,eventData:{message:"parameters to json failed"}},n)}return r}async parameterJSON(t,r,n,i){if(this.isDataSet(t)){let a=n,o=r.find(s=>s.key===ht.name)?.value;if(a)return this.getParameterChildrenValues(t,r);{let s=new Error(`No dataset manifest info for ${o}`);(0,dr.trackErrorTrace)(ft,{eventName:`${en}/parameterJSON`,eventData:{message:"Missing custom control manifest dataset info"}},s)}}else{let a=n,o=r&&r.find(l=>l.key===h.Type),s=a&&!a.ofTypeGroup.every(l=>!Xd.includes(l));if(this.isLookupType(o?.value)||this.isLookupType(a?.ofType)||s)if(a){let l=a.usage,u=this.getParameterIsStatic(t),c=a.isPrimary;if(this.name===Ln.FormComponent){let d=this.getFormComponentValueByParameterName(h.bindAttribute),p=await i.formModelService.loadLookupModel(d),f=p.lookupColumn,m=this.getLookupDataTypeFromAttributeMetadata(f);return{Name:t,Type:m,Usage:l,Static:u,Primary:c,EntityName:p.primaryTableName,Value:d,ViewId:this.getFormComponentValueByParameterName(by.DefaultViewId),TargetEntityType:f.targets[0],FilterRelationshipName:this.getFormComponentValueByParameterName(h.FilterRelationshipName),AvailableViewIds:this.getFormComponentValueByParameterName(h.AvailableViewIds),DependentAttributeName:this.getFormComponentValueByParameterName(h.DependentAttributeName),DependentAttributeType:this.getFormComponentValueByParameterName(h.DependentAttributeType),AllowFilterOff:O.IsStrictTrue(this.getFormComponentValueByParameterName(h.AllowFilterOff)),DisableQuickFind:O.IsStrictTrue(this.getFormComponentValueByParameterName(h.DisableQuickFind)),EnableViewPicker:!O.IsStrictTrue(this.getFormComponentValueByParameterName(h.DisableViewPicker))}}return{Name:t,Usage:l,Static:u,Primary:c,Value:this.getParameterValue(t)}}else{let l=new Error(`No lookup manifest info for ${t}`);(0,dr.trackErrorTrace)(ft,{eventName:`${en}/parameterJSON`,eventData:{message:"Missing custom control manifest lookup property info"}},l)}if(a){let l=a.usage,u=this.getParameterIsStatic(t),c=this.getParameterValue(t),d=a.isPrimary;if(o){let f=o.value;return{Type:f,Static:u,Usage:l,Value:this.isNumberTypeProperty(a,f)&&Number(c)?Number(c):c,Primary:d}}if(a.ofType)return{Type:a.ofType,Static:u,Usage:l,Value:c,Primary:!0};if(a.ofTypeGroup)return{Static:u,Usage:l,Value:c,Primary:!0};let p=new Error(`No property type info for ${t}`);(0,dr.trackErrorTrace)(ft,{eventName:`${en}/parameterJSON`,eventData:{message:"Missing property type info"}},p)}else{let l=new Error(`No property manifest info for ${t}`);(0,dr.trackWarningTrace)(ft,{eventName:`${en}/parameterJSON`,eventData:{message:"Missing custom control manifest property info"}},l)}}return null}getLookupDataTypeFromAttributeMetadata(t){let{attributeType:r,format:n}=t;switch(r){case R.Customer:return T.LookupCustomer;case R.Owner:return T.LookupOwner;case R.PartyList:return T.LookupPartyList;default:return n===$.Regarding?T.LookupRegarding:T.LookupSimple}}isLookupType(t){return Xd.includes(t)}isNumberTypeProperty(t,r){return Yd.includes(r)||t.ofTypeGroup.some(n=>Yd.includes(n))}isDataSet(t){return ht.dataset===t}isGroups(t){return!!t[0].getAllProperties().find(n=>n.key==="isGroup"&&n.value==="true")}}});var z,yp=I(()=>{"use strict";z=class{static get CustomControl(){return"CustomControl"}static get ACIControl(){return"ACIControl"}static get ReferencePanelSearchWidget(){return"ReferencePanelSearchWidget"}static get SearchWidgetControl(){return"SearchWidgetControl"}static get SocialInsightControl(){return"SocialInsightControl"}static get NotesControl(){return"notescontrol"}static get TimerControl(){return"TimerControl"}static get MapsControl(){return"MapsControl"}static get IframeControl(){return"IframeControl"}static get WebResourceHtmlControl(){return"WebResourceHtmlControl"}static get QuickFormCollectionControl(){return"QuickFormCollectionControl"}static get QuickFormControl(){return"QuickFormControl"}static get GridControl(){return"GridControl"}static get SubGridControl(){return"SubGridControl"}static get WebResourceImageControl(){return"WebResourceImageControl"}static get TimeLineControl(){return"TimeLineControl"}static get LeadScoringControl(){return"LeadScoringControl"}}});var x,na,Me,kl=I(()=>{"use strict";Le();No();Oe();nt();Oo();ai();yp();cr();x=class{static get TextBoxControl(){return"4273EDBD-AC1D-40d3-9FB2-095C621B552D"}static get TickerControl(){return"1E1FC551-F7A8-43af-AC34-A8DC35C7B6D4"}static get UrlControl(){return"71716B6C-711E-476c-8AB8-5D11542BFB47"}static get PhoneNumberControl(){return"8C10015A-B339-4982-9474-A95FE05631A5"}static get EmailAddressControl(){return"ADA2203E-B4CD-49be-9DDF-234642B43B52"}static get RadioControl(){return"67FAC785-CD58-4f9f-ABB3-4B7DDC6ED5ED"}static get LookupControl(){return"270BD3DB-D9AF-4782-9025-509E298DEC0A"}static get DateTimeControl(){return"5B773807-9FB2-42db-97C3-7A91EFF8ADFF"}static get IntegerControl(){return"C6D124CA-7EDA-4a60-AEA9-7FB8D318B68F"}static get MoneyControl(){return"533B9E00-756B-4312-95A0-DC888637AC78"}static get FloatControl(){return"0D2C745A-E5A8-4c8f-BA63-C6D3BB604660"}static get DecimalControl(){return"C3EFE0C3-0EC6-42be-8349-CBD9079DFD8E"}static get TextAreaControl(){return"E0DECE4B-6FC8-4a8f-A065-082708572369"}static get PicklistControl(){return"3EF39988-22BB-4f0b-BBBE-64B5A3748AEE"}static get HiddenInputControl(){return"5546E6CD-394C-4BEE-94A8-4425E17EF6C6"}static get GridControl(){return"E7A81278-8635-4D9E-8D4D-59480B391C5B"}static get CheckBoxControl(){return"B0C6723A-8503-4fd7-BB28-C8A06AC933C2"}static get IframeControl(){return"FD2A7985-3187-444e-908D-6624B21F69C0"}static get SocialInsightControl(){return"86B9E25E-695E-4FEF-AC69-F05CFA96739C"}static get OrgInsightsControl(){return"76B9E25E-695E-4FEF-AC69-F05CFA96739C"}static get DurationControl(){return"AA987274-CE4E-4271-A803-66164311A958"}static get RegardingControl(){return"F3015350-44A2-4aa0-97B5-00166532B5E9"}static get PartyListControl(){return"CBFB742C-14E7-4a17-96BB-1A13F7F64AA2"}static get TimeLineControl(){return"06375649-c143-495e-a496-c962e5b4488e"}static get TimeLineControlUC(){return"06375649-C143-495E-A496-C962E5B4488E"}static get TimeZonePicklistControl(){return"7C624A0B-F59E-493d-9583-638D34759266"}static get LanguagePickerControl(){return"671A9387-CA5A-4d1e-8AB7-06E39DDCF6B5"}static get AccessTeamTablePickerControl(){return"3F4E2A56-F102-4B4D-AB9C-F1574CA5BFDA"}static get KBViewerControl(){return"A62B6FA9-169E-406C-B1AA-EAB828CB6026"}static get PicklistStatusControl(){return"5D68B988-0661-4db2-BC3E-17598AD3BE6C"}static get EmailBodyControl(){return"6F3FB987-393B-4d2d-859F-9D0F0349B6AD"}static get PicklistLookupControl(){return"2305E33A-BAD3-4022-9E15-1856CF218333"}static get RelationshipRolePicklistControl(){return"5F986642-5961-4D9F-AB5E-643D71E231E9"}static get RelatedInformationControl(){return"163B90A6-EB64-49D2-9DF8-3C84A4F0A0F8"}static get CoverPagePicklistControl(){return"4168A05C-D857-46AF-8457-5BB47EB04EA1"}static get MailMergeLanguagePickerControl(){return"B634828E-C390-444A-AFE6-E07315D9D970"}static get ConnectionControl(){return"3246F906-1F71-45F7-B11F-D7BE0F9D04C9"}static get ConnectionRoleObjectTypeListControl(){return"821ACF1A-7E46-4A0C-965D-FE14A57D78C7"}static get MapsControl(){return"62B0DF79-0464-470F-8AF7-4483CFEA0C7D"}static get MapLinkControl(){return"91DC0675-C8B9-4421-B1E0-261CEBF02BAC"}static get WebResourceHtmlControl(){return"9FDF5F91-88B1-47F4-AD53-C11EFC01A01D"}static get WebResourceImageControl(){return"587CDF98-C1D5-4BDE-8473-14A0BC7644A7"}static get WebResourceSilverlightControl(){return"080677DB-86EC-4544-AC42-F927E74B491F"}static get ReportControl(){return"A28F441B-916C-4865-87FD-0C5D53BD59C9"}static get ArticleContentControl(){return"F02EF977-2564-4B9A-B2F0-DF083D8A019B"}static get ProcessControl(){return"06E9F7AF-1F54-4681-8EEC-1E21A1CEB465"}static get ActivitiesWallControl(){return"6636847D-B74D-4994-B55A-A6FAF97ECEA2"}static get QuickFormControl(){return"69AF7DCA-2E3B-4EE7-9201-0DA731DD2413"}static get QuickFormCollectionControl(){return"5C5600E0-1D6E-4205-A272-BE80DA87FD42"}static get LinkControl(){return"DFDF1CDE-837B-4AC9-98CF-AC74361FD89D"}static get CompositionLinkControl(){return"DB1284EF-9FFC-4E99-B382-0CC082FE2364"}static get ErrorStatusControl(){return"F4C16ECA-CA81-4E39-9448-834B8378721E"}static get ActivitiesContainerControl(){return"C72511AB-84E5-4FB7-A543-25B4FC01E83E"}static get AccessPrivilegeControl(){return"F93A31B2-99AC-4084-8EC2-D4027C31369A"}static get TimerControl(){return"9C5CA0A1-AB4D-4781-BE7E-8DFBE867B87E"}static get DynamicPropertyListControl(){return"6896F004-B17A-4202-861E-8B7EA2080E0B"}static get ButtonControl(){return"00AD73DA-BD4D-49C6-88A8-2F4F4CAD4A20"}static get SearchWidgetControl(){return"E616A57F-20E0-4534-8662-A101B5DDF4E0"}static get EmailRecipientActivityControl(){return"26E9760F-7454-40DE-BB07-F6DCCCB82040"}static get LabelControl(){return"39354E4A-5015-4D74-8031-EA9EB73A1322"}static get CustomControl(){return"F9A8A302-114E-466A-B582-6771B2AE0D92"}static get EditFilterControl(){return"1479835F-F852-4679-B864-C6892A2844C9"}static get RichEditorControl(){return"F94DB24F-263D-44A7-B38E-A35E9854812B"}static get PowerBIControl(){return"8C54228C-1B25-4909-A12A-F2B968BB0D62"}static get EmailEngagementActionsControl(){return"F454228D-1D25-4319-E12F-D27968BC0234"}static get ACIControl(){return"C8BFBBEF-6851-4401-A0CC-7450062FE085"}static get ChoicesControl(){return"4AA28AB7-9C13-4F57-A73D-AD894D048B5F"}static get ReferencePanelSubgridControl(){return"02D4264B-47E2-4B4C-AA95-F439F3F4D458"}static get ReferencePanelSearchWidget(){return"7CCD1494-1F7A-4E3A-8BDE-F32069DAEB9F"}static get ReferencePanelQuickFormCollectionControl(){return"B68B05F0-A46D-43F8-843B-917920AF806A"}static get SpacerControl(){return"E4BAB03A-A9A5-4C23-CC3B-54AA680150E2"}},na=class{static get RelationshipAssistant(){return"3ff9a528-dd50-4aca-8f10-2e5ed73513ad"}static get PredictiveLeadScoring(){return"6f503f2a-d033-4106-b62c-f8f2e5f01a57"}},Me=class e{static FieldControlIds=e.initializeFieldControls();static UnboundControlIds=e.initializeUnboundControls();static ControlsAllowedForReferencePanel=e.initializeReferencePanelControls();static ControlsAllowedForFooter=e.initializeFooterControls();static CustomControlIdMap=new mt;static initializeFieldControls(){let t=new mt,r=e.getControlName(R.SingleLineofText,$.Phone);t.add(r,new P(x.PhoneNumberControl));let n=e.getControlName(R.SingleLineofText,$.TextArea);t.add(n,new P(x.TextAreaControl));let i=e.getControlName(R.SingleLineofText,$.Text);t.add(i,new P(x.TextBoxControl));let a=e.getControlName(R.SingleLineofText,$.Email);t.add(a,new P(x.EmailAddressControl));let o=e.getControlName(R.SingleLineofText,$.Url);t.add(o,new P(x.UrlControl));let s=e.getControlName(R.SingleLineofText,$.TickerSymbol);t.add(s,new P(x.TickerControl));let l=e.getControlName(R.SingleLineofText,$.PhoneticGuide);t.add(l,new P(x.TextBoxControl));let u=e.getControlName(R.WholeNumber,$.Duration);t.add(u,new P(x.DurationControl));let c=e.getControlName(R.WholeNumber,$.Language);t.add(c,new P(x.LanguagePickerControl));let d=e.getControlName(R.WholeNumber,$.TimeZone);t.add(d,new P(x.TimeZonePicklistControl));let p=e.getControlName(R.WholeNumber,$.None);t.add(p,new P(x.IntegerControl));let f=e.getControlName(R.DateTime,$.DateOnly);t.add(f,new P(x.DateTimeControl));let m=e.getControlName(R.DateTime,$.DateAndTime);t.add(m,new P(x.DateTimeControl));let g=e.getControlName(R.LookupType,$.None);t.add(g,new P(x.LookupControl));let y=e.getControlName(R.CustomerType,$.None);t.add(y,new P(x.LookupControl));let A=e.getControlName(R.FloatingPointNumber,$.None);t.add(A,new P(x.FloatControl));let D=e.getControlName(R.DecimalNumber,$.None);t.add(D,new P(x.DecimalControl));let F=e.getControlName(R.Currency,$.None);t.add(F,new P(x.MoneyControl));let _=e.getControlName(R.MultipleLineofText,$.None);t.add(_,new P(x.TextAreaControl));let q=e.getControlName(R.MultipleLineofText,$.Text);t.add(q,new P(x.TextAreaControl));let B=e.getControlName(R.MultipleLineofText,$.TextArea);t.add(B,new P(x.TextAreaControl));let L=e.getControlName(R.MultipleLineofText,$.Email);t.add(L,new P(x.EmailBodyControl));let k=e.getControlName(R.OptionSet,$.None);t.add(k,new P(x.PicklistControl));let M=e.getControlName(R.TwoOptions,$.None);t.add(M,new P(x.RadioControl));let G=e.getControlName(R.Image,$.None);t.add(G,new P(x.WebResourceImageControl));let V=e.getControlName(R.Image,$.None);t.add(V,new P(x.WebResourceHtmlControl));let Ze=e.getControlName(R.TwoOptions,"Radio");t.add(Ze,new P(x.RadioControl));let ir=e.getControlName(R.TwoOptions,"CheckBox");t.add(ir,new P(x.CheckBoxControl));let et=e.getControlName(R.TwoOptions,"List");t.add(et,new P(x.PicklistControl));let dt=e.getControlName(R.State,$.None);t.add(dt,new P(x.PicklistControl));let ue=e.getControlName(R.Status,$.None);t.add(ue,new P(x.PicklistStatusControl));let $e=e.getControlName(R.OwnerType,$.None);t.add($e,new P(x.LookupControl));let xe=e.getControlName(R.PartyListType,$.None);t.add(xe,new P(x.PartyListControl));let yn=e.getControlName(R.LookupType,$.Regarding);t.add(yn,new P(x.RegardingControl));let $t=e.getControlName(R.MultiSelectOptionSet,$.None);return t.add($t,new P(x.ChoicesControl)),t}static getControlName(t,r){return t+"_"+r}static getControlIdByTypeAndFormat(t,r){let n=e.getControlName(t.toString(),r.toString());return e.FieldControlIds.containsKey(n)?e.FieldControlIds.getValue(n):null}static getTypeAndFormatByControlOrUniqueId(t){for(let r in e.FieldControlIds.getKeys())if(e.FieldControlIds.getValue(e.FieldControlIds.getKeys()[r]).guidString.toLowerCase()===t)return e.FieldControlIds.getKeys()[r]}static getControlDataTypeByControlOrUniqueId(t){if(!N.IsNullOrEmptyGuid(t)){let r=e.getTypeAndFormatByControlOrUniqueId(t.guidString.toLowerCase());return r=N.IsNullOrUndefined(r)?e.getUnboundControlNameFromIdentifier(t):r.substring(0,r.indexOf("_")),r}return null}static isCustomControl(t){return N.IsNullOrUndefined(t.control)||N.IsNullOrUndefined(t.control.ClassId)||t.control.ClassId.guidString===x.CustomControl}static initializeUnboundControls(){let t=new mt;return t.add(x.ACIControl,z.ACIControl),t.add(x.IframeControl,z.IframeControl),t.add(x.SearchWidgetControl,z.SearchWidgetControl),t.add(x.MapsControl,z.MapsControl),t.add(x.QuickFormCollectionControl,z.QuickFormCollectionControl),t.add(x.GridControl,z.SubGridControl),t.add(x.WebResourceImageControl,z.WebResourceImageControl),t.add(x.WebResourceHtmlControl,z.WebResourceHtmlControl),t.add(x.ReferencePanelSearchWidget,z.SearchWidgetControl),t.add(x.ReferencePanelQuickFormCollectionControl,z.QuickFormCollectionControl),t.add(x.ReferencePanelSubgridControl,z.SubGridControl),t.add(x.TimerControl,z.TimerControl),t.add(x.TimeLineControl,z.NotesControl),t.add(x.TimeLineControlUC,z.NotesControl),t.add(x.SocialInsightControl,z.SocialInsightControl),t.add(na.RelationshipAssistant,z.CustomControl),t}static initializeReferencePanelControls(){let t=new mt;return t.add(x.IframeControl,z.IframeControl),t.add(x.ReferencePanelSearchWidget,z.SearchWidgetControl),t.add(x.ReferencePanelQuickFormCollectionControl,z.QuickFormCollectionControl),t.add(x.ReferencePanelSubgridControl,z.SubGridControl),t.add(x.WebResourceHtmlControl,z.WebResourceHtmlControl),t.add(x.WebResourceImageControl,z.WebResourceHtmlControl),t}static initializeFooterControls(){let t=new Xi;return t.add(ta.IFRAME,!0),t.add(ta.SPACER,!0),t.add(ta.WEB_RESOURCE_HTML,!0),t}static isUnboundFormControl(t){if(N.IsNullOrUndefined(t)||N.IsNullOrUndefined(t.control)||N.IsNullOrUndefined(t.control.ClassId))return!1;let r=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.containsKey(r.guidString)}static isReferencePanelSection(t){return!N.IsNullOrUndefined(t)&&!N.IsNullOrUndefined(t.Name)&&t.Name.indexOf(we.referencePanelNamePrefix)===0}static isUnboundFormControlByIdentifier(t){return N.IsNullOrUndefined(t)||N.IsNullOrUndefined(t.guidString)?!1:e.UnboundControlIds.containsKey(t.guidString)}static getUnboundFormControlName(t){let r=O.EmptyString;if(N.IsNullOrUndefined(t)||N.IsNullOrUndefined(t.control)||N.IsNullOrUndefined(t.control.ClassId))return r;let n=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.getValue(n.guidString).toString()}static getUnboundControlNameFromIdentifier(t){return N.IsNullOrUndefined(t)||N.IsNullOrUndefined(t.guidString)?O.EmptyString:e.UnboundControlIds.getValue(t.guidString).toString()}static isSpacerControl(t){return t===x.SpacerControl}static GetRowSpan(t){let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===x.CustomControl&&!N.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}switch(e.UnboundControlIds.getValue(r.guidString)){case z.IframeControl:case z.ACIControl:case z.SocialInsightControl:return 6;case z.SubGridControl:case z.CustomControl:return 4;case z.WebResourceImageControl:return 15;case z.WebResourceHtmlControl:return 15;case z.MapsControl:return 8;case z.SearchWidgetControl:return 10;case z.NotesControl:case z.TimeLineControl:return 15;case z.TimerControl:return 2;default:}}static isLookUpControl(t){return!N.IsNullOrUndefined(t)&&t.ClassId.guidString===x.LookupControl}static isRelationshipAssistantOrLeadScoringControl(t){return!N.IsNullOrUndefined(t)&&e.isRelationshipAssistantOrLeadScoring(t.UniqueId)}static isRelationshipAssistantOrLeadScoring(t){return!N.IsNullOrUndefined(t)&&(t.guidString===na.RelationshipAssistant||t.guidString===na.PredictiveLeadScoring)}static isRelationshipAssistantControl(t){return!N.IsNullOrUndefined(t)&&e.isRelationshipAssistant(t.UniqueId)}static isRelationshipAssistant(t){return!N.IsNullOrUndefined(t)&&t.guidString===na.RelationshipAssistant}static getUniqueIdentifierForControl(t){if(N.IsNullOrUndefined(t))return null;let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===x.CustomControl&&!N.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}return r}}});var Ml,Yy=I(()=>{"use strict";Ml=class{listeners=[];listenersOncer=[];on(t){return this.listeners.push(t),{dispose:()=>this.off(t)}}once(t){this.listenersOncer.push(t)}off(t){let r=this.listeners.indexOf(t);r>-1&&this.listeners.splice(r,1)}emit(t){this.listeners.forEach(r=>r(t)),this.listenersOncer.forEach(r=>r(t)),this.listenersOncer=[]}pipe(t){return this.on(r=>t.emit(r))}}});var di,ia,Zy,eb,kn,tb,rb,bp=I(()=>{"use strict";(function(e){e[e.Center=0]="Center",e[e.Left=1]="Left",e[e.Right=2]="Right"})(di||(di={}));(function(e){e[e.Left=0]="Left",e[e.Top=1]="Top"})(ia||(ia={}));(function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle"})(Zy||(Zy={}));(function(e){e[e.None=0]="None",e[e.Create=1]="Create",e[e.Existing=2]="Existing",e[e.ReadOnly=3]="ReadOnly",e[e.Disabled=4]="Disabled",e[e.BulkEdit=6]="BulkEdit",e[e.Merge=7]="Merge",e[e.Print=8]="Print",e[e.FollowUp=9]="FollowUp"})(eb||(eb={}));(function(e){e[e.None=-1]="None",e[e.AppointmentBook=0]="AppointmentBook",e[e.Hardcoded=1]="Hardcoded",e[e.Main=2]="Main",e[e.MiniCampaignBO=3]="MiniCampaignBO",e[e.Preview=4]="Preview",e[e.Dashboard=5]="Dashboard",e[e.Quick=6]="Quick",e[e.Mobile=7]="Mobile",e[e.Read=8]="Read",e[e.QuickCreate=9]="QuickCreate",e[e.Dialog=10]="Dialog",e[e.Card=11]="Card",e[e.TaskBasedForm=12]="TaskBasedForm",e[e.InteractionCentricDashboard=13]="InteractionCentricDashboard"})(kn||(kn={}));(function(e){e[e.None=0]="None",e[e.SystemRequired=1]="SystemRequired",e[e.ApplicationRequired=2]="ApplicationRequired",e[e.Recommended=3]="Recommended"})(tb||(tb={}));(function(e){e[e.Boolean=0]="Boolean",e[e.Customer=1]="Customer",e[e.DateTime=2]="DateTime",e[e.Decimal=3]="Decimal",e[e.Double=4]="Double",e[e.Integer=5]="Integer",e[e.Lookup=6]="Lookup",e[e.Memo=7]="Memo",e[e.Money=8]="Money",e[e.Owner=9]="Owner",e[e.PartyList=10]="PartyList",e[e.Picklist=11]="Picklist",e[e.State=12]="State",e[e.Status=13]="Status",e[e.String=14]="String",e[e.Uniqueidentifier=15]="Uniqueidentifier",e[e.CalendarRules=16]="CalendarRules",e[e.Virtual=17]="Virtual",e[e.BigInt=18]="BigInt",e[e.ManagedProperty=19]="ManagedProperty",e[e.EntityName=20]="EntityName"})(rb||(rb={}))});var aa,nb=I(()=>{"use strict";Po();aa=ip({packageName:"cds-designer-models",features:{showAllPCFControls:{owner:"anchoudh",description:"Do not only show the controls that exist on the whitelist",enabledFor:{test:!1,preprod:!1,preview:!1,prod:!1,gov:!1,high:!1,dod:!1,mooncake:!1}},showTestControls:{owner:"lucorre",description:"Show advanced custom controls for testing (designated in Authoring Manifest with isTestOnly=true)",enabledFor:{test:!0,preprod:!1,preview:!1,prod:!1,gov:!1,high:!1,dod:!1,mooncake:!1}},enablePrefetchGetMoreComponentsLocalization:{owner:"vajagarl",description:"Enables prefetching the localization files for controls displayed in custom control picker",enabledFor:{test:!0,preprod:!0,preview:!0,prod:!0,gov:!0,high:!0,dod:!0,mooncake:!0}},showMapControl:{owner:"vayilavarapu",createdDate:"07/19/2022",description:"Show map control",enabledFor:{test:!0,preprod:!0,preview:!0,prod:!0,gov:!0,high:!0,dod:!0,mooncake:!0,ex:!0,rx:!0}},enableFallbackFormTemplate:{owner:"vajagarl",createdDate:"01/03/2023",description:"Enable default form template as fallback if unable to retrieve a form template from Dataverse",enabledFor:{test:!0,preprod:!0,preview:!0,prod:!0,gov:!0,high:!0,dod:!0,mooncake:!0,ex:!0,rx:!0}},enableAutoInsertionOfCellInRow:{owner:"debeshd",createdDate:"09/01/2023",description:"Enable the auto insertion of cell in a row when a section is initialized",enabledFor:{test:!1,preprod:!1,preview:!1,prod:!1,gov:!1,high:!1,dod:!1,mooncake:!1,ex:!1,rx:!1}},enableOneGridEvents:{owner:"aansu",createdDate:"08/21/2024",description:"Enable OneGrid events in form designer",enabledFor:{test:!0,preprod:!0,prod:!0,preview:!0,gov:!0,high:!0,dod:!0,mooncake:!0,ex:!0,rx:!0}},disablePBIComponents:{owner:"adekulkarni",createdDate:"02/13/2025",description:"Disables PBI components and cleans them up from the form",enabledFor:{test:!0,preprod:!1,preview:!1,prod:!1,gov:!1,high:!1,dod:!1,mooncake:!1,ex:!1,rx:!1}},enableAgentResponse:{owner:"jennietu",createdDate:"04/24/2025",description:"Enables agent response in form designer",enabledFor:{test:!0,preprod:!0,preview:!1,prod:!1,gov:!1,high:!1,dod:!1,mooncake:!1,ex:!1,rx:!1}},enableDelayedLocalizationForCustomControls:{owner:"aansu",createdDate:"06/08/2025",description:"Enables delayed localization of custom control",enabledFor:{test:!0,preprod:!0,preview:!0,prod:!0,gov:!0,high:!0,dod:!0,mooncake:!0,ex:!0,rx:!0}}}})});function ib(e){return{...e,extractConfig:t=>dk(t,Object.keys(e.fallback))}}function dk(e,t){let r={};for(let n of t)typeof e[n]<"u"&&(r[n]=e[n]);return r}var wp=I(()=>{"use strict";});var Ap=v((lJ,ob)=>{var Fo=new Proxy(function(){return Fo},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Fo},apply:function(){return Fo},construct:function(){return{}}}),ab=function(){return Fo};Object.setPrototypeOf(ab,Fo);ob.exports=ab});var ub=v((uJ,lb)=>{var xo=new Proxy(function(){return xo},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:xo},apply:function(){return xo},construct:function(){return{}}}),sb=function(){return xo};Object.setPrototypeOf(sb,xo);lb.exports=sb});var Cp=v((cJ,db)=>{var Lo=new Proxy(function(){return Lo},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Lo},apply:function(){return Lo},construct:function(){return{}}}),cb=function(){return Lo};Object.setPrototypeOf(cb,Lo);db.exports=cb});var fb=v((dJ,pb)=>{function pk(){this.__data__=[],this.size=0}pb.exports=pk});var oa=v((pJ,mb)=>{function fk(e,t){return e===t||e!==e&&t!==t}mb.exports=fk});var ko=v((fJ,hb)=>{var mk=oa();function hk(e,t){for(var r=e.length;r--;)if(mk(e[r][0],t))return r;return-1}hb.exports=hk});var vb=v((mJ,gb)=>{var gk=ko(),vk=Array.prototype,yk=vk.splice;function bk(e){var t=this.__data__,r=gk(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():yk.call(t,r,1),--this.size,!0}gb.exports=bk});var bb=v((hJ,yb)=>{var wk=ko();function Ak(e){var t=this.__data__,r=wk(t,e);return r<0?void 0:t[r][1]}yb.exports=Ak});var Ab=v((gJ,wb)=>{var Ck=ko();function Ek(e){return Ck(this.__data__,e)>-1}wb.exports=Ek});var Eb=v((vJ,Cb)=>{var Sk=ko();function Nk(e,t){var r=this.__data__,n=Sk(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}Cb.exports=Nk});var Mo=v((yJ,Sb)=>{var Dk=fb(),Ik=vb(),_k=bb(),Tk=Ab(),Pk=Eb();function sa(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}sa.prototype.clear=Dk;sa.prototype.delete=Ik;sa.prototype.get=_k;sa.prototype.has=Tk;sa.prototype.set=Pk;Sb.exports=sa});var Db=v((bJ,Nb)=>{var Ok=Mo();function Rk(){this.__data__=new Ok,this.size=0}Nb.exports=Rk});var _b=v((wJ,Ib)=>{function Fk(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}Ib.exports=Fk});var Pb=v((AJ,Tb)=>{function xk(e){return this.__data__.get(e)}Tb.exports=xk});var Rb=v((CJ,Ob)=>{function Lk(e){return this.__data__.has(e)}Ob.exports=Lk});var Ep=v((EJ,Fb)=>{var kk=typeof global=="object"&&global&&global.Object===Object&&global;Fb.exports=kk});var pr=v((SJ,xb)=>{var Mk=Ep(),Uk=typeof self=="object"&&self&&self.Object===Object&&self,Bk=Mk||Uk||Function("return this")();xb.exports=Bk});var Uo=v((NJ,Lb)=>{var $k=pr(),qk=$k.Symbol;Lb.exports=qk});var Bb=v((DJ,Ub)=>{var kb=Uo(),Mb=Object.prototype,Vk=Mb.hasOwnProperty,Gk=Mb.toString,Bo=kb?kb.toStringTag:void 0;function zk(e){var t=Vk.call(e,Bo),r=e[Bo];try{e[Bo]=void 0;var n=!0}catch{}var i=Gk.call(e);return n&&(t?e[Bo]=r:delete e[Bo]),i}Ub.exports=zk});var qb=v((IJ,$b)=>{var Wk=Object.prototype,Hk=Wk.toString;function jk(e){return Hk.call(e)}$b.exports=jk});var pi=v((_J,zb)=>{var Vb=Uo(),Jk=Bb(),Qk=qb(),Kk="[object Null]",Xk="[object Undefined]",Gb=Vb?Vb.toStringTag:void 0;function Yk(e){return e==null?e===void 0?Xk:Kk:Gb&&Gb in Object(e)?Jk(e):Qk(e)}zb.exports=Yk});var nn=v((TJ,Wb)=>{function Zk(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}Wb.exports=Zk});var Ul=v((PJ,Hb)=>{var eM=pi(),tM=nn(),rM="[object AsyncFunction]",nM="[object Function]",iM="[object GeneratorFunction]",aM="[object Proxy]";function oM(e){if(!tM(e))return!1;var t=eM(e);return t==nM||t==iM||t==rM||t==aM}Hb.exports=oM});var Jb=v((OJ,jb)=>{var sM=pr(),lM=sM["__core-js_shared__"];jb.exports=lM});var Xb=v((RJ,Kb)=>{var Sp=Jb(),Qb=(function(){var e=/[^.]+$/.exec(Sp&&Sp.keys&&Sp.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function uM(e){return!!Qb&&Qb in e}Kb.exports=uM});var Np=v((FJ,Yb)=>{var cM=Function.prototype,dM=cM.toString;function pM(e){if(e!=null){try{return dM.call(e)}catch{}try{return e+""}catch{}}return""}Yb.exports=pM});var ew=v((xJ,Zb)=>{var fM=Ul(),mM=Xb(),hM=nn(),gM=Np(),vM=/[\\^$.*+?()[\]{}|]/g,yM=/^\[object .+?Constructor\]$/,bM=Function.prototype,wM=Object.prototype,AM=bM.toString,CM=wM.hasOwnProperty,EM=RegExp("^"+AM.call(CM).replace(vM,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function SM(e){if(!hM(e)||mM(e))return!1;var t=fM(e)?EM:yM;return t.test(gM(e))}Zb.exports=SM});var rw=v((LJ,tw)=>{function NM(e,t){return e?.[t]}tw.exports=NM});var Mn=v((kJ,nw)=>{var DM=ew(),IM=rw();function _M(e,t){var r=IM(e,t);return DM(r)?r:void 0}nw.exports=_M});var Bl=v((MJ,iw)=>{var TM=Mn(),PM=pr(),OM=TM(PM,"Map");iw.exports=OM});var $o=v((UJ,aw)=>{var RM=Mn(),FM=RM(Object,"create");aw.exports=FM});var lw=v((BJ,sw)=>{var ow=$o();function xM(){this.__data__=ow?ow(null):{},this.size=0}sw.exports=xM});var cw=v(($J,uw)=>{function LM(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}uw.exports=LM});var pw=v((qJ,dw)=>{var kM=$o(),MM="__lodash_hash_undefined__",UM=Object.prototype,BM=UM.hasOwnProperty;function $M(e){var t=this.__data__;if(kM){var r=t[e];return r===MM?void 0:r}return BM.call(t,e)?t[e]:void 0}dw.exports=$M});var mw=v((VJ,fw)=>{var qM=$o(),VM=Object.prototype,GM=VM.hasOwnProperty;function zM(e){var t=this.__data__;return qM?t[e]!==void 0:GM.call(t,e)}fw.exports=zM});var gw=v((GJ,hw)=>{var WM=$o(),HM="__lodash_hash_undefined__";function jM(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=WM&&t===void 0?HM:t,this}hw.exports=jM});var yw=v((zJ,vw)=>{var JM=lw(),QM=cw(),KM=pw(),XM=mw(),YM=gw();function la(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}la.prototype.clear=JM;la.prototype.delete=QM;la.prototype.get=KM;la.prototype.has=XM;la.prototype.set=YM;vw.exports=la});var Aw=v((WJ,ww)=>{var bw=yw(),ZM=Mo(),eU=Bl();function tU(){this.size=0,this.__data__={hash:new bw,map:new(eU||ZM),string:new bw}}ww.exports=tU});var Ew=v((HJ,Cw)=>{function rU(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}Cw.exports=rU});var qo=v((jJ,Sw)=>{var nU=Ew();function iU(e,t){var r=e.__data__;return nU(t)?r[typeof t=="string"?"string":"hash"]:r.map}Sw.exports=iU});var Dw=v((JJ,Nw)=>{var aU=qo();function oU(e){var t=aU(this,e).delete(e);return this.size-=t?1:0,t}Nw.exports=oU});var _w=v((QJ,Iw)=>{var sU=qo();function lU(e){return sU(this,e).get(e)}Iw.exports=lU});var Pw=v((KJ,Tw)=>{var uU=qo();function cU(e){return uU(this,e).has(e)}Tw.exports=cU});var Rw=v((XJ,Ow)=>{var dU=qo();function pU(e,t){var r=dU(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}Ow.exports=pU});var $l=v((YJ,Fw)=>{var fU=Aw(),mU=Dw(),hU=_w(),gU=Pw(),vU=Rw();function ua(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}ua.prototype.clear=fU;ua.prototype.delete=mU;ua.prototype.get=hU;ua.prototype.has=gU;ua.prototype.set=vU;Fw.exports=ua});var Lw=v((ZJ,xw)=>{var yU=Mo(),bU=Bl(),wU=$l(),AU=200;function CU(e,t){var r=this.__data__;if(r instanceof yU){var n=r.__data__;if(!bU||n.length<AU-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new wU(n)}return r.set(e,t),this.size=r.size,this}xw.exports=CU});var Dp=v((eQ,kw)=>{var EU=Mo(),SU=Db(),NU=_b(),DU=Pb(),IU=Rb(),_U=Lw();function ca(e){var t=this.__data__=new EU(e);this.size=t.size}ca.prototype.clear=SU;ca.prototype.delete=NU;ca.prototype.get=DU;ca.prototype.has=IU;ca.prototype.set=_U;kw.exports=ca});var Uw=v((tQ,Mw)=>{var TU="__lodash_hash_undefined__";function PU(e){return this.__data__.set(e,TU),this}Mw.exports=PU});var $w=v((rQ,Bw)=>{function OU(e){return this.__data__.has(e)}Bw.exports=OU});var Vw=v((nQ,qw)=>{var RU=$l(),FU=Uw(),xU=$w();function ql(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new RU;++t<r;)this.add(e[t])}ql.prototype.add=ql.prototype.push=FU;ql.prototype.has=xU;qw.exports=ql});var zw=v((iQ,Gw)=>{function LU(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}Gw.exports=LU});var Hw=v((aQ,Ww)=>{function kU(e,t){return e.has(t)}Ww.exports=kU});var Ip=v((oQ,jw)=>{var MU=Vw(),UU=zw(),BU=Hw(),$U=1,qU=2;function VU(e,t,r,n,i,a){var o=r&$U,s=e.length,l=t.length;if(s!=l&&!(o&&l>s))return!1;var u=a.get(e),c=a.get(t);if(u&&c)return u==t&&c==e;var d=-1,p=!0,f=r&qU?new MU:void 0;for(a.set(e,t),a.set(t,e);++d<s;){var m=e[d],g=t[d];if(n)var y=o?n(g,m,d,t,e,a):n(m,g,d,e,t,a);if(y!==void 0){if(y)continue;p=!1;break}if(f){if(!UU(t,function(A,D){if(!BU(f,D)&&(m===A||i(m,A,r,n,a)))return f.push(D)})){p=!1;break}}else if(!(m===g||i(m,g,r,n,a))){p=!1;break}}return a.delete(e),a.delete(t),p}jw.exports=VU});var _p=v((sQ,Jw)=>{var GU=pr(),zU=GU.Uint8Array;Jw.exports=zU});var Kw=v((lQ,Qw)=>{function WU(e){var t=-1,r=Array(e.size);return e.forEach(function(n,i){r[++t]=[i,n]}),r}Qw.exports=WU});var Yw=v((uQ,Xw)=>{function HU(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n}),r}Xw.exports=HU});var nA=v((cQ,rA)=>{var Zw=Uo(),eA=_p(),jU=oa(),JU=Ip(),QU=Kw(),KU=Yw(),XU=1,YU=2,ZU="[object Boolean]",eB="[object Date]",tB="[object Error]",rB="[object Map]",nB="[object Number]",iB="[object RegExp]",aB="[object Set]",oB="[object String]",sB="[object Symbol]",lB="[object ArrayBuffer]",uB="[object DataView]",tA=Zw?Zw.prototype:void 0,Tp=tA?tA.valueOf:void 0;function cB(e,t,r,n,i,a,o){switch(r){case uB:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case lB:return!(e.byteLength!=t.byteLength||!a(new eA(e),new eA(t)));case ZU:case eB:case nB:return jU(+e,+t);case tB:return e.name==t.name&&e.message==t.message;case iB:case oB:return e==t+"";case rB:var s=QU;case aB:var l=n&XU;if(s||(s=KU),e.size!=t.size&&!l)return!1;var u=o.get(e);if(u)return u==t;n|=YU,o.set(e,t);var c=JU(s(e),s(t),n,i,a,o);return o.delete(e),c;case sB:if(Tp)return Tp.call(e)==Tp.call(t)}return!1}rA.exports=cB});var aA=v((dQ,iA)=>{function dB(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}iA.exports=dB});var Un=v((pQ,oA)=>{var pB=Array.isArray;oA.exports=pB});var lA=v((fQ,sA)=>{var fB=aA(),mB=Un();function hB(e,t,r){var n=t(e);return mB(e)?n:fB(n,r(e))}sA.exports=hB});var cA=v((mQ,uA)=>{function gB(e,t){for(var r=-1,n=e==null?0:e.length,i=0,a=[];++r<n;){var o=e[r];t(o,r,e)&&(a[i++]=o)}return a}uA.exports=gB});var pA=v((hQ,dA)=>{function vB(){return[]}dA.exports=vB});var hA=v((gQ,mA)=>{var yB=cA(),bB=pA(),wB=Object.prototype,AB=wB.propertyIsEnumerable,fA=Object.getOwnPropertySymbols,CB=fA?function(e){return e==null?[]:(e=Object(e),yB(fA(e),function(t){return AB.call(e,t)}))}:bB;mA.exports=CB});var vA=v((vQ,gA)=>{function EB(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}gA.exports=EB});var Bn=v((yQ,yA)=>{function SB(e){return e!=null&&typeof e=="object"}yA.exports=SB});var wA=v((bQ,bA)=>{var NB=pi(),DB=Bn(),IB="[object Arguments]";function _B(e){return DB(e)&&NB(e)==IB}bA.exports=_B});var Pp=v((wQ,EA)=>{var AA=wA(),TB=Bn(),CA=Object.prototype,PB=CA.hasOwnProperty,OB=CA.propertyIsEnumerable,RB=AA((function(){return arguments})())?AA:function(e){return TB(e)&&PB.call(e,"callee")&&!OB.call(e,"callee")};EA.exports=RB});var NA=v((AQ,SA)=>{function FB(){return!1}SA.exports=FB});var Vl=v((Vo,da)=>{var xB=pr(),LB=NA(),_A=typeof Vo=="object"&&Vo&&!Vo.nodeType&&Vo,DA=_A&&typeof da=="object"&&da&&!da.nodeType&&da,kB=DA&&DA.exports===_A,IA=kB?xB.Buffer:void 0,MB=IA?IA.isBuffer:void 0,UB=MB||LB;da.exports=UB});var Gl=v((CQ,TA)=>{var BB=9007199254740991,$B=/^(?:0|[1-9]\d*)$/;function qB(e,t){var r=typeof e;return t=t??BB,!!t&&(r=="number"||r!="symbol"&&$B.test(e))&&e>-1&&e%1==0&&e<t}TA.exports=qB});var Op=v((EQ,PA)=>{var VB=9007199254740991;function GB(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=VB}PA.exports=GB});var RA=v((SQ,OA)=>{var zB=pi(),WB=Op(),HB=Bn(),jB="[object Arguments]",JB="[object Array]",QB="[object Boolean]",KB="[object Date]",XB="[object Error]",YB="[object Function]",ZB="[object Map]",e$="[object Number]",t$="[object Object]",r$="[object RegExp]",n$="[object Set]",i$="[object String]",a$="[object WeakMap]",o$="[object ArrayBuffer]",s$="[object DataView]",l$="[object Float32Array]",u$="[object Float64Array]",c$="[object Int8Array]",d$="[object Int16Array]",p$="[object Int32Array]",f$="[object Uint8Array]",m$="[object Uint8ClampedArray]",h$="[object Uint16Array]",g$="[object Uint32Array]",ge={};ge[l$]=ge[u$]=ge[c$]=ge[d$]=ge[p$]=ge[f$]=ge[m$]=ge[h$]=ge[g$]=!0;ge[jB]=ge[JB]=ge[o$]=ge[QB]=ge[s$]=ge[KB]=ge[XB]=ge[YB]=ge[ZB]=ge[e$]=ge[t$]=ge[r$]=ge[n$]=ge[i$]=ge[a$]=!1;function v$(e){return HB(e)&&WB(e.length)&&!!ge[zB(e)]}OA.exports=v$});var xA=v((NQ,FA)=>{function y$(e){return function(t){return e(t)}}FA.exports=y$});var kA=v((Go,pa)=>{var b$=Ep(),LA=typeof Go=="object"&&Go&&!Go.nodeType&&Go,zo=LA&&typeof pa=="object"&&pa&&!pa.nodeType&&pa,w$=zo&&zo.exports===LA,Rp=w$&&b$.process,A$=(function(){try{var e=zo&&zo.require&&zo.require("util").types;return e||Rp&&Rp.binding&&Rp.binding("util")}catch{}})();pa.exports=A$});var zl=v((DQ,BA)=>{var C$=RA(),E$=xA(),MA=kA(),UA=MA&&MA.isTypedArray,S$=UA?E$(UA):C$;BA.exports=S$});var Fp=v((IQ,$A)=>{var N$=vA(),D$=Pp(),I$=Un(),_$=Vl(),T$=Gl(),P$=zl(),O$=Object.prototype,R$=O$.hasOwnProperty;function F$(e,t){var r=I$(e),n=!r&&D$(e),i=!r&&!n&&_$(e),a=!r&&!n&&!i&&P$(e),o=r||n||i||a,s=o?N$(e.length,String):[],l=s.length;for(var u in e)(t||R$.call(e,u))&&!(o&&(u=="length"||i&&(u=="offset"||u=="parent")||a&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||T$(u,l)))&&s.push(u);return s}$A.exports=F$});var Wl=v((_Q,qA)=>{var x$=Object.prototype;function L$(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||x$;return e===r}qA.exports=L$});var xp=v((TQ,VA)=>{function k$(e,t){return function(r){return e(t(r))}}VA.exports=k$});var zA=v((PQ,GA)=>{var M$=xp(),U$=M$(Object.keys,Object);GA.exports=U$});var HA=v((OQ,WA)=>{var B$=Wl(),$$=zA(),q$=Object.prototype,V$=q$.hasOwnProperty;function G$(e){if(!B$(e))return $$(e);var t=[];for(var r in Object(e))V$.call(e,r)&&r!="constructor"&&t.push(r);return t}WA.exports=G$});var Wo=v((RQ,jA)=>{var z$=Ul(),W$=Op();function H$(e){return e!=null&&W$(e.length)&&!z$(e)}jA.exports=H$});var QA=v((FQ,JA)=>{var j$=Fp(),J$=HA(),Q$=Wo();function K$(e){return Q$(e)?j$(e):J$(e)}JA.exports=K$});var XA=v((xQ,KA)=>{var X$=lA(),Y$=hA(),Z$=QA();function eq(e){return X$(e,Z$,Y$)}KA.exports=eq});var eC=v((LQ,ZA)=>{var YA=XA(),tq=1,rq=Object.prototype,nq=rq.hasOwnProperty;function iq(e,t,r,n,i,a){var o=r&tq,s=YA(e),l=s.length,u=YA(t),c=u.length;if(l!=c&&!o)return!1;for(var d=l;d--;){var p=s[d];if(!(o?p in t:nq.call(t,p)))return!1}var f=a.get(e),m=a.get(t);if(f&&m)return f==t&&m==e;var g=!0;a.set(e,t),a.set(t,e);for(var y=o;++d<l;){p=s[d];var A=e[p],D=t[p];if(n)var F=o?n(D,A,p,t,e,a):n(A,D,p,e,t,a);if(!(F===void 0?A===D||i(A,D,r,n,a):F)){g=!1;break}y||(y=p=="constructor")}if(g&&!y){var _=e.constructor,q=t.constructor;_!=q&&"constructor"in e&&"constructor"in t&&!(typeof _=="function"&&_ instanceof _&&typeof q=="function"&&q instanceof q)&&(g=!1)}return a.delete(e),a.delete(t),g}ZA.exports=iq});var rC=v((kQ,tC)=>{var aq=Mn(),oq=pr(),sq=aq(oq,"DataView");tC.exports=sq});var iC=v((MQ,nC)=>{var lq=Mn(),uq=pr(),cq=lq(uq,"Promise");nC.exports=cq});var oC=v((UQ,aC)=>{var dq=Mn(),pq=pr(),fq=dq(pq,"Set");aC.exports=fq});var lC=v((BQ,sC)=>{var mq=Mn(),hq=pr(),gq=mq(hq,"WeakMap");sC.exports=gq});var gC=v(($Q,hC)=>{var Lp=rC(),kp=Bl(),Mp=iC(),Up=oC(),Bp=lC(),mC=pi(),fa=Np(),uC="[object Map]",vq="[object Object]",cC="[object Promise]",dC="[object Set]",pC="[object WeakMap]",fC="[object DataView]",yq=fa(Lp),bq=fa(kp),wq=fa(Mp),Aq=fa(Up),Cq=fa(Bp),fi=mC;(Lp&&fi(new Lp(new ArrayBuffer(1)))!=fC||kp&&fi(new kp)!=uC||Mp&&fi(Mp.resolve())!=cC||Up&&fi(new Up)!=dC||Bp&&fi(new Bp)!=pC)&&(fi=function(e){var t=mC(e),r=t==vq?e.constructor:void 0,n=r?fa(r):"";if(n)switch(n){case yq:return fC;case bq:return uC;case wq:return cC;case Aq:return dC;case Cq:return pC}return t});hC.exports=fi});var SC=v((qQ,EC)=>{var $p=Dp(),Eq=Ip(),Sq=nA(),Nq=eC(),vC=gC(),yC=Un(),bC=Vl(),Dq=zl(),Iq=1,wC="[object Arguments]",AC="[object Array]",Hl="[object Object]",_q=Object.prototype,CC=_q.hasOwnProperty;function Tq(e,t,r,n,i,a){var o=yC(e),s=yC(t),l=o?AC:vC(e),u=s?AC:vC(t);l=l==wC?Hl:l,u=u==wC?Hl:u;var c=l==Hl,d=u==Hl,p=l==u;if(p&&bC(e)){if(!bC(t))return!1;o=!0,c=!1}if(p&&!c)return a||(a=new $p),o||Dq(e)?Eq(e,t,r,n,i,a):Sq(e,t,l,r,n,i,a);if(!(r&Iq)){var f=c&&CC.call(e,"__wrapped__"),m=d&&CC.call(t,"__wrapped__");if(f||m){var g=f?e.value():e,y=m?t.value():t;return a||(a=new $p),i(g,y,r,n,a)}}return p?(a||(a=new $p),Nq(e,t,r,n,i,a)):!1}EC.exports=Tq});var _C=v((VQ,IC)=>{var Pq=SC(),NC=Bn();function DC(e,t,r,n,i){return e===t?!0:e==null||t==null||!NC(e)&&!NC(t)?e!==e&&t!==t:Pq(e,t,r,n,DC,i)}IC.exports=DC});var PC=v((GQ,TC)=>{var Oq=_C();function Rq(e,t){return Oq(e,t)}TC.exports=Rq});var qp=v((zQ,OC)=>{var Fq=Mn(),xq=(function(){try{var e=Fq(Object,"defineProperty");return e({},"",{}),e}catch{}})();OC.exports=xq});var jl=v((WQ,FC)=>{var RC=qp();function Lq(e,t,r){t=="__proto__"&&RC?RC(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}FC.exports=Lq});var Vp=v((HQ,xC)=>{var kq=jl(),Mq=oa();function Uq(e,t,r){(r!==void 0&&!Mq(e[t],r)||r===void 0&&!(t in e))&&kq(e,t,r)}xC.exports=Uq});var kC=v((jQ,LC)=>{function Bq(e){return function(t,r,n){for(var i=-1,a=Object(t),o=n(t),s=o.length;s--;){var l=o[e?s:++i];if(r(a[l],l,a)===!1)break}return t}}LC.exports=Bq});var UC=v((JQ,MC)=>{var $q=kC(),qq=$q();MC.exports=qq});var GC=v((Ho,ma)=>{var Vq=pr(),VC=typeof Ho=="object"&&Ho&&!Ho.nodeType&&Ho,BC=VC&&typeof ma=="object"&&ma&&!ma.nodeType&&ma,Gq=BC&&BC.exports===VC,$C=Gq?Vq.Buffer:void 0,qC=$C?$C.allocUnsafe:void 0;function zq(e,t){if(t)return e.slice();var r=e.length,n=qC?qC(r):new e.constructor(r);return e.copy(n),n}ma.exports=zq});var HC=v((QQ,WC)=>{var zC=_p();function Wq(e){var t=new e.constructor(e.byteLength);return new zC(t).set(new zC(e)),t}WC.exports=Wq});var JC=v((KQ,jC)=>{var Hq=HC();function jq(e,t){var r=t?Hq(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}jC.exports=jq});var KC=v((XQ,QC)=>{function Jq(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}QC.exports=Jq});var ZC=v((YQ,YC)=>{var Qq=nn(),XC=Object.create,Kq=(function(){function e(){}return function(t){if(!Qq(t))return{};if(XC)return XC(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}})();YC.exports=Kq});var Gp=v((ZQ,eE)=>{var Xq=xp(),Yq=Xq(Object.getPrototypeOf,Object);eE.exports=Yq});var rE=v((eK,tE)=>{var Zq=ZC(),e3=Gp(),t3=Wl();function r3(e){return typeof e.constructor=="function"&&!t3(e)?Zq(e3(e)):{}}tE.exports=r3});var iE=v((tK,nE)=>{var n3=Wo(),i3=Bn();function a3(e){return i3(e)&&n3(e)}nE.exports=a3});var sE=v((rK,oE)=>{var o3=pi(),s3=Gp(),l3=Bn(),u3="[object Object]",c3=Function.prototype,d3=Object.prototype,aE=c3.toString,p3=d3.hasOwnProperty,f3=aE.call(Object);function m3(e){if(!l3(e)||o3(e)!=u3)return!1;var t=s3(e);if(t===null)return!0;var r=p3.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&aE.call(r)==f3}oE.exports=m3});var zp=v((nK,lE)=>{function h3(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}lE.exports=h3});var Wp=v((iK,uE)=>{var g3=jl(),v3=oa(),y3=Object.prototype,b3=y3.hasOwnProperty;function w3(e,t,r){var n=e[t];(!(b3.call(e,t)&&v3(n,r))||r===void 0&&!(t in e))&&g3(e,t,r)}uE.exports=w3});var dE=v((aK,cE)=>{var A3=Wp(),C3=jl();function E3(e,t,r,n){var i=!r;r||(r={});for(var a=-1,o=t.length;++a<o;){var s=t[a],l=n?n(r[s],e[s],s,r,e):void 0;l===void 0&&(l=e[s]),i?C3(r,s,l):A3(r,s,l)}return r}cE.exports=E3});var fE=v((oK,pE)=>{function S3(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}pE.exports=S3});var hE=v((sK,mE)=>{var N3=nn(),D3=Wl(),I3=fE(),_3=Object.prototype,T3=_3.hasOwnProperty;function P3(e){if(!N3(e))return I3(e);var t=D3(e),r=[];for(var n in e)n=="constructor"&&(t||!T3.call(e,n))||r.push(n);return r}mE.exports=P3});var Hp=v((lK,gE)=>{var O3=Fp(),R3=hE(),F3=Wo();function x3(e){return F3(e)?O3(e,!0):R3(e)}gE.exports=x3});var yE=v((uK,vE)=>{var L3=dE(),k3=Hp();function M3(e){return L3(e,k3(e))}vE.exports=M3});var SE=v((cK,EE)=>{var bE=Vp(),U3=GC(),B3=JC(),$3=KC(),q3=rE(),wE=Pp(),AE=Un(),V3=iE(),G3=Vl(),z3=Ul(),W3=nn(),H3=sE(),j3=zl(),CE=zp(),J3=yE();function Q3(e,t,r,n,i,a,o){var s=CE(e,r),l=CE(t,r),u=o.get(l);if(u){bE(e,r,u);return}var c=a?a(s,l,r+"",e,t,o):void 0,d=c===void 0;if(d){var p=AE(l),f=!p&&G3(l),m=!p&&!f&&j3(l);c=l,p||f||m?AE(s)?c=s:V3(s)?c=$3(s):f?(d=!1,c=U3(l,!0)):m?(d=!1,c=B3(l,!0)):c=[]:H3(l)||wE(l)?(c=s,wE(s)?c=J3(s):(!W3(s)||z3(s))&&(c=q3(l))):d=!1}d&&(o.set(l,c),i(c,l,n,a,o),o.delete(l)),bE(e,r,c)}EE.exports=Q3});var jp=v((dK,DE)=>{var K3=Dp(),X3=Vp(),Y3=UC(),Z3=SE(),e4=nn(),t4=Hp(),r4=zp();function NE(e,t,r,n,i){e!==t&&Y3(t,function(a,o){if(i||(i=new K3),e4(a))Z3(e,t,o,r,NE,n,i);else{var s=n?n(r4(e,o),a,o+"",e,t,i):void 0;s===void 0&&(s=a),X3(e,o,s)}},t4)}DE.exports=NE});var Jp=v((pK,IE)=>{function n4(e){return e}IE.exports=n4});var TE=v((fK,_E)=>{function i4(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}_E.exports=i4});var RE=v((mK,OE)=>{var a4=TE(),PE=Math.max;function o4(e,t,r){return t=PE(t===void 0?e.length-1:t,0),function(){for(var n=arguments,i=-1,a=PE(n.length-t,0),o=Array(a);++i<a;)o[i]=n[t+i];i=-1;for(var s=Array(t+1);++i<t;)s[i]=n[i];return s[t]=r(o),a4(e,this,s)}}OE.exports=o4});var xE=v((hK,FE)=>{function s4(e){return function(){return e}}FE.exports=s4});var ME=v((gK,kE)=>{var l4=xE(),LE=qp(),u4=Jp(),c4=LE?function(e,t){return LE(e,"toString",{configurable:!0,enumerable:!1,value:l4(t),writable:!0})}:u4;kE.exports=c4});var BE=v((vK,UE)=>{var d4=800,p4=16,f4=Date.now;function m4(e){var t=0,r=0;return function(){var n=f4(),i=p4-(n-r);if(r=n,i>0){if(++t>=d4)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}UE.exports=m4});var qE=v((yK,$E)=>{var h4=ME(),g4=BE(),v4=g4(h4);$E.exports=v4});var GE=v((bK,VE)=>{var y4=Jp(),b4=RE(),w4=qE();function A4(e,t){return w4(b4(e,t,y4),e+"")}VE.exports=A4});var WE=v((wK,zE)=>{var C4=oa(),E4=Wo(),S4=Gl(),N4=nn();function D4(e,t,r){if(!N4(r))return!1;var n=typeof t;return(n=="number"?E4(r)&&S4(t,r.length):n=="string"&&t in r)?C4(r[t],e):!1}zE.exports=D4});var Qp=v((AK,HE)=>{var I4=GE(),_4=WE();function T4(e){return I4(function(t,r){var n=-1,i=r.length,a=i>1?r[i-1]:void 0,o=i>2?r[2]:void 0;for(a=e.length>3&&typeof a=="function"?(i--,a):void 0,o&&_4(r[0],r[1],o)&&(a=i<3?void 0:a,i=1),t=Object(t);++n<i;){var s=r[n];s&&e(t,s,n,a)}return t})}HE.exports=T4});var JE=v((CK,jE)=>{var P4=jp(),O4=Qp(),R4=O4(function(e,t,r,n){P4(e,t,r,n)});jE.exports=R4});var Wt,jo=I(()=>{"use strict";(function(e){e[e.NotLoaded=0]="NotLoaded",e[e.Initialized=1]="Initialized",e[e.ConfigsLoaded=2]="ConfigsLoaded",e[e.Error=3]="Error"})(Wt||(Wt={}))});function KE(e,t,r="PROD"){let n=i=>`ShellSettings_ECS_ClientCache_${e}_${QE.EcsConfigType[i]}_${r}`;return{getData:i=>{let a=t.getItem(n(i));return Promise.resolve(a?JSON.parse(a):void 0)},putData:(i,a)=>(t.setItem(n(i),JSON.stringify(a)),Promise.resolve())}}var QE,F4,XE=I(()=>{"use strict";QE=ie(Cp()),F4=ie(Ap());});var Kp,YE=I(()=>{"use strict";Il();Kp=To({packageName:"shell-settings",settings:{prodEcsEndpoint:{description:"The url for the PROD ECS endpoint",values:{default:"https://ecs.office.com",dod:"https://config.ecs.dod.teams.microsoft.us",high:"https://config.ecs.gov.teams.microsoft.us",ex:"https://config.ecs.teams.eaglex.ic.gov",rx:"https://config.ecs.teams.microsoft.scloud"}},integrationEcsEndpoint:{description:"The url for the INT ECS endpoint",values:{default:"https://config.edge.skype.net"}}}})});var eS,tS,rS,nS,Xp,x4,Jl,ZE,Yp=I(()=>{"use strict";eS=ie(Ap()),tS=ie(ub()),rS=ie(Cp()),nS=ie(PC()),Xp=ie(JE());jo();XE();YE();x4=60*1e3,Jl=class{clientName;logger;ecsEndpoint;resolveLoadingPromise;loadingPromise=new Promise(t=>this.resolveLoadingPromise=t);_status=Wt.NotLoaded;endpointType;clientConfigOverride;get status(){return this._status}constructor(t,r,n="PROD"){this.clientName=t,this.logger=r,this.endpointType=n,this.ecsEndpoint=n==="PROD"?Kp.prodEcsEndpoint:Kp.integrationEcsEndpoint}client=new tS.default;init=async({clientVersion:t,getFilters:r,cacheStorage:n=eS.StorageHelper.transientWithGlobalFallback,updateIntervalInMinutes:i,overrideEcsInitParams:a})=>{this.client.telemetryEventAdded.subscribe(this.logger.logEvent),this.client.configUpdated.subscribe(this.handleConfigUpdated);let o=(async()=>{let s=await r();return this.logEvent("FeaturesClient/configRequested",{ecsClientName:this.clientName,filters:s}),s});try{await this.client.initialize({clientName:this.clientName,clientVersion:t??"1.0.0.0",configsToFetch:[rS.EcsConfigType.Default],hosts:[this.ecsEndpoint],initialAppActiveState:!0,getEcsParameters:o,databaseInterface:KE(this.clientName,n,this.endpointType),...a}),this.client.requestUpdate(),this._status===Wt.NotLoaded&&(this._status=Wt.Initialized)}catch(s){this._status=Wt.Error,this.resolveLoadingPromise(),this.logEvent("FeaturesClient/initializationFailed",{ecsClientName:this.clientName,error:s},"Error")}i&&window.setInterval(()=>this.client.requestUpdate(),i*x4)};getConfig=t=>{let r=this.getMergedClientConfigByTeamName(t.teamName),n=r?t.extractConfig(r):{};return(0,Xp.default)({},t.fallback,n,t.override,ZE)};getAllConfigs=()=>this.getMergedClientConfig();getAllConfigsByTeamName=t=>this.getMergedClientConfigByTeamName(t);requestConfigUpdate=()=>{this.client.requestUpdate()};subscribe=(t,r)=>{let n=this.getConfig(t),i=this.client.configUpdated.subscribe(()=>{let a=this.getConfig(t);(0,nS.default)(a,n)||(n={...a},r(a))});return{unsubscribe:()=>i.unsubscribe()}};waitUntilLoaded=async t=>{if(t!==void 0){let r,n=new Promise((i,a)=>{r=window.setTimeout(()=>{a(new Error("Timed out waiting for configuration to load"))},t)});await Promise.race([this.loadingPromise,n]),clearTimeout(r)}else await this.loadingPromise};overrideClientConfig(t){this.logger.logEvent("FeaturesClient/overrideClientConfig",{clientConfigOverride:t}),this.clientConfigOverride=t}undoClientConfigOverride(){this.clientConfigOverride=void 0,this.logger.logEvent("FeaturesClient/undoClientConfigOverride")}getMergedClientConfig=()=>(0,Xp.default)({},this.client.getConfig()?.config,this.clientConfigOverride,ZE);getMergedClientConfigByTeamName=t=>this.getMergedClientConfig()?.[t];handleConfigUpdated=()=>{let t=this.client.getConfig();if(t===void 0)return;this.resolveLoadingPromise(),this._status=Wt.ConfigsLoaded;let{ConfigIDs:r,Headers:n}=t.config;this.logEvent("FeaturesClient/configUpdated",{ecsClientName:this.clientName,configIDs:r,ETag:n?.ETag})};logEvent=(t,r)=>{this.logger.logEvent(t,{ecsClientName:this.clientName,ecsEndpointType:this.endpointType,...r})}},ZE=(e,t)=>{if(Array.isArray(t))return t}});var aS=v((OK,iS)=>{"use strict";var L4=()=>{let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e};iS.exports=L4});var Zp=v((RK,sS)=>{var Jo=new Proxy(function(){return Jo},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Jo},apply:function(){return Jo},construct:function(){return{}}}),oS=function(){return Jo};Object.setPrototypeOf(oS,Jo);sS.exports=oS});var cS=v((FK,uS)=>{var Qo=new Proxy(function(){return Qo},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Qo},apply:function(){return Qo},construct:function(){return{}}}),lS=function(){return Qo};Object.setPrototypeOf(lS,Qo);uS.exports=lS});var vS=v((xK,gS)=>{"use strict";var ef=cS(),k4={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},M4={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},U4={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},mS={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},tf={};tf[ef.ForwardRef]=U4;tf[ef.Memo]=mS;function dS(e){return ef.isMemo(e)?mS:tf[e.$$typeof]||k4}var B4=Object.defineProperty,$4=Object.getOwnPropertyNames,pS=Object.getOwnPropertySymbols,q4=Object.getOwnPropertyDescriptor,V4=Object.getPrototypeOf,fS=Object.prototype;function hS(e,t,r){if(typeof t!="string"){if(fS){var n=V4(t);n&&n!==fS&&hS(e,n,r)}var i=$4(t);pS&&(i=i.concat(pS(t)));for(var a=dS(e),o=dS(t),s=0;s<i.length;++s){var l=i[s];if(!M4[l]&&!(r&&r[l])&&!(o&&o[l])&&!(a&&a[l])){var u=q4(t,l);try{B4(e,l,u)}catch{}}}}return e}gS.exports=hS});function bS(e,t,r){let[n,i]=(0,ha.useState)(e.getConfig(t));return(0,ha.useEffect)(()=>{if(!r?.subscribe&&e.status===Wt.ConfigsLoaded)return;let a=e.subscribe(t,o=>{i(o),r?.subscribe||a.unsubscribe()});return a?.unsubscribe},[]),n}function wS(e){return function(t,r){return bS(e,t,r)}}function AS(e,t,r,n){let i=a=>{let o=bS(e,t,n),s={...a,...o};return ha.default.createElement(r,{...s})};return(0,yS.default)(i,r),i.displayName=`WithFeature(${r.name})`,i}function CS(e,t,r,n){return t.reduce((i,a)=>AS(e,a,i,n),r)}function ES(e){return function(t,r,n){return AS(e,t,r,n)}}var yS,ha,rf=I(()=>{"use strict";yS=ie(vS()),ha=ie(Zp());jo();});var NS=v((MK,SS)=>{var G4=jp(),z4=Qp(),W4=z4(function(e,t,r){G4(e,t,r)});SS.exports=W4});var Ql=v((UK,DS)=>{var H4=pi(),j4=Bn(),J4="[object Symbol]";function Q4(e){return typeof e=="symbol"||j4(e)&&H4(e)==J4}DS.exports=Q4});var _S=v((BK,IS)=>{var K4=Un(),X4=Ql(),Y4=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Z4=/^\w*$/;function eV(e,t){if(K4(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||X4(e)?!0:Z4.test(e)||!Y4.test(e)||t!=null&&e in Object(t)}IS.exports=eV});var OS=v(($K,PS)=>{var TS=$l(),tV="Expected a function";function nf(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(tV);var r=function(){var n=arguments,i=t?t.apply(this,n):n[0],a=r.cache;if(a.has(i))return a.get(i);var o=e.apply(this,n);return r.cache=a.set(i,o)||a,o};return r.cache=new(nf.Cache||TS),r}nf.Cache=TS;PS.exports=nf});var FS=v((qK,RS)=>{var rV=OS(),nV=500;function iV(e){var t=rV(e,function(n){return r.size===nV&&r.clear(),n}),r=t.cache;return t}RS.exports=iV});var LS=v((VK,xS)=>{var aV=FS(),oV=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,sV=/\\(\\)?/g,lV=aV(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(oV,function(r,n,i,a){t.push(i?a.replace(sV,"$1"):n||r)}),t});xS.exports=lV});var MS=v((GK,kS)=>{function uV(e,t){for(var r=-1,n=e==null?0:e.length,i=Array(n);++r<n;)i[r]=t(e[r],r,e);return i}kS.exports=uV});var GS=v((zK,VS)=>{var US=Uo(),cV=MS(),dV=Un(),pV=Ql(),fV=1/0,BS=US?US.prototype:void 0,$S=BS?BS.toString:void 0;function qS(e){if(typeof e=="string")return e;if(dV(e))return cV(e,qS)+"";if(pV(e))return $S?$S.call(e):"";var t=e+"";return t=="0"&&1/e==-fV?"-0":t}VS.exports=qS});var WS=v((WK,zS)=>{var mV=GS();function hV(e){return e==null?"":mV(e)}zS.exports=hV});var jS=v((HK,HS)=>{var gV=Un(),vV=_S(),yV=LS(),bV=WS();function wV(e,t){return gV(e)?e:vV(e,t)?[e]:yV(bV(e))}HS.exports=wV});var QS=v((jK,JS)=>{var AV=Ql(),CV=1/0;function EV(e){if(typeof e=="string"||AV(e))return e;var t=e+"";return t=="0"&&1/e==-CV?"-0":t}JS.exports=EV});var YS=v((JK,XS)=>{var SV=Wp(),NV=jS(),DV=Gl(),KS=nn(),IV=QS();function _V(e,t,r,n){if(!KS(e))return e;t=NV(t,e);for(var i=-1,a=t.length,o=a-1,s=e;s!=null&&++i<a;){var l=IV(t[i]),u=r;if(l==="__proto__"||l==="constructor"||l==="prototype")return e;if(i!=o){var c=s[l];u=n?n(c,l,s):void 0,u===void 0&&(u=KS(c)?c:DV(t[i+1])?[]:{})}SV(s,l,u),s=s[l]}return e}XS.exports=_V});var eN=v((QK,ZS)=>{var TV=YS();function PV(e,t,r){return e==null?e:TV(e,t,r)}ZS.exports=PV});function iN(e){let{query:t}=(0,nN.default)(window.location.href,!0);return RV(e,t),e}function RV(e,t){let r=OV+e.clientName,n=Object.keys(t).filter(a=>a.startsWith(r));if(!n)return;let i={};n.forEach(a=>{let o=t[a];if(o)try{let s=JSON.parse(o),l=r+aN,u={};if(a===r)u=s;else if(a.startsWith(l)){let c=a.substring(l.length);(0,rN.default)(u,c,s)}(0,tN.default)(i,u)}catch{}}),Object.keys(i).length>0&&e.overrideClientConfig(i)}var tN,rN,nN,aN,OV,oN=I(()=>{"use strict";tN=ie(NS()),rN=ie(eN()),nN=ie(lp());aN=".",OV="ecs"+aN});function Xl(e,t,r){let n=iN(new Jl(e,t,r));function i(a){(0,Kl.useEffect)(()=>{n.init(a)},[])}return{featuresClient:n,createFeature:xV(n),useFeaturesClientInitParams:i,withFeatures:(a,o,s)=>CS(n,a,o,s)}}function xV(e){let t=wS(e),r=ES(e);return function(i){let a=ib(i);return a.getConfig=()=>e.getConfig(a),a.isLoaded=()=>e.status===Wt.ConfigsLoaded,dp.register(a,e.clientName),{useFeature:o=>t(a,o),withFeature:(o,s)=>r(a,o,s),feature:a}}}var FV,Kl,af=I(()=>{"use strict";FV=ie(aS()),Kl=ie(Zp());wp();Yp();jo();rf();oN();pp();});var sN=I(()=>{"use strict";wp();Yp();af();jo();rf();Ol();fp();});function Yl(e){return{logEvent:(t,r,n)=>{switch(n){case"Error":(0,ga.trackErrorTrace)(e,{eventName:t,eventData:r});break;case"Warning":(0,ga.trackWarningTrace)(e,{eventName:t,eventData:r});break;default:(0,ga.trackInfoTrace)(e,{eventName:t,eventData:r});break}}}}var ga,of=I(()=>{"use strict";ga=ie(oi());});var hX,gX,vX,lN=I(()=>{"use strict";sN();of();({featuresClient:hX,createFeature:gX,useFeaturesClientInitParams:vX}=Xl("PowerApps-Shell-Test",Yl("shell-features")))});var dN=v((bX,cN)=>{var Ko=new Proxy(function(){return Ko},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Ko},apply:function(){return Ko},construct:function(){return{}}}),uN=function(){return Ko};Object.setPrototypeOf(uN,Ko);cN.exports=uN});var LV,kV,pN=I(()=>{"use strict";Do();LV=ie(dN()),kV=ie(oi());});var fN=I(()=>{"use strict";lN();of();pN();});var _X,va,TX,mN=I(()=>{"use strict";fN();af();({featuresClient:_X,createFeature:va,useFeaturesClientInitParams:TX}=Xl("PowerApps-MakerPortal",Yl("powerapps-features")))});var hN,gN,FX,xX,LX,kX,sf=I(()=>{"use strict";nb();mN();({feature:hN}=va({teamName:"MakerPortal",owners:["debeshd"],description:"Enable the auto insertion of cell in a row when a section is initialized",createdOn:"09/01/2023",fallback:{enableAutoInsertionOfCellInRow:aa.enableAutoInsertionOfCellInRow}})),{feature:gN}=va({teamName:"MakerPortal",owners:["aansu"],description:"Enable the one grid events for form designer",createdOn:"08/21/2024",fallback:{enableOneGridEventsForFormDesigner:aa.enableOneGridEvents}}),{feature:FX}=va({teamName:"MakerPortal",owners:["adekulkarni"],description:"Disables PBI components and cleans them up from the form",createdOn:"01/03/2023",fallback:{enableFallbackFormTemplate:aa.disablePBIComponents}}),{feature:xX}=va({teamName:"MakerPortal",owners:["jennietu"],description:"Enables agent response in form designer. This feature is used to enable the agent response in form designer",createdOn:"04/24/2025",fallback:{enableAgentResponse:aa.enableAgentResponse}}),{feature:LX,useFeature:kX}=va({teamName:"MakerPortal",owners:["aansu"],description:"Enables delayed localization of custom control",createdOn:"06/08/2025",fallback:{enableDelayedLocalizationForCustomControls:aa.enableDelayedLocalizationForCustomControls}})});var bN=v((UX,yN)=>{var Xo=new Proxy(function(){return Xo},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Xo},apply:function(){return Xo},construct:function(){return{}}}),vN=function(){return Xo};Object.setPrototypeOf(vN,Xo);yN.exports=vN});var it,$n=I(()=>{"use strict";Le();Oe();nt();kl();X();We();it=class extends H{static HighestUsedIndexByClass=new Map;get colspan(){let t=this.getProperty(h.colspan);return N.IsNullOrUndefined(t)?null:parseInt(t,10)}set colspan(t){N.IsNullOrUndefined(t)||this.setProperty(h.colspan,String(t))}constructor(t,r){super(t,r)}get id(){let t=this.getProperty(h.id);return t==null?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new P(t.substr(1,t.length-2)):new P(t)}set id(t){this.setProperty(h.id,`{${t.ToString()}}`)}set labelId(t){this.setProperty(h.labelId,`{${t.ToString()}}`)}get labelId(){let t=this.getProperty(h.labelId);return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new P(t.substr(1,t.length-2)):new P(t)}get Name(){return this.getProperty(h.Name)}set Name(t){this.setProperty(h.Name,t)}setDisplayName(t,r){for(let i of this.getAllLabels())if(+i.getProperty(h.languagecode)===r){i.setProperty(h.description,t);return}let n=new H(b.formLabel,null);n.setProperty(h.description,t),n.setProperty(h.languagecode,String(r)),this.addGrandChild("labels",n)}getDisplayName(t){for(let r of this.getAllLabels())if(+r.getProperty(h.languagecode)===t)return r.getProperty(h.description)}getAllLabels(){let t=this.getChildren("labels");return t.length!==1?[]:t[0].getChildren("label")}get isLocked(){return+this.getProperty(h.locklevel)==1}set isLocked(t){!this.IsUnboundControl&&this.setProperty(h.locklevel,t?"1":"0")}get availableforphone(){return this.getProcessedValue(h.availableforphone)}set availableforphone(t){N.IsNullOrUndefined(t)||!this.IsAllowedUBCForAvailableOnPhone()||this.setProperty(h.availableforphone,String(t))}get visible(){return this.getProcessedValue(h.visible)}set visible(t){N.IsNullOrUndefined(t)||!this.IsAllowedUBCForVisibleByDefault()||this.setProperty(h.visible,String(t))}isLockLevelSettable(){return!this.IsUnboundControl}get showlabel(){return this.getProcessedValue(h.showlabel)}set showlabel(t){N.IsNullOrUndefined(t)||this.setProperty(h.showlabel,String(t))}isAvailableForPhoneSettable(){return this.IsAllowedUBCForAvailableOnPhone()}isVisibleSettable(){return this.IsAllowedUBCForVisibleByDefault()}getProcessedValue(t){let r=this.getProperty(t);return N.IsNullOrUndefined(r)||this.getProperty(t)==="true"}get readonly(){let t=this.getFirstChild(b.formControl);return t?t.disabled:!1}set readonly(t){let r=this.getFirstChild(b.formControl);r&&(r.disabled=t)}get allowfilteroff(){let t=this.getFirstChild(b.formControl);if(t)return t.getParam(h.AllowFilterOff)==="true"}set allowfilteroff(t){let r=this.getFirstChild(b.formControl);r&&!this.IsUnboundControl&&r.setParameter(h.AllowFilterOff,t)}get autoresolve(){let t=this.getFirstChild(b.formControl);if(t)return t.getParam(h.AutoResolve)==="true"}set autoresolve(t){let r=this.getFirstChild(b.formControl);r&&!this.IsUnboundControl&&r.setParameter(h.AutoResolve,t)}get defaultviewid(){let t=this.getFirstChild(b.formControl);return t?t.getParam(h.DefaultViewId):O.EmptyString}set defaultviewid(t){let r=this.getFirstChild(b.formControl);r&&!this.IsUnboundControl&&r.setParameter(h.DefaultViewId,t)}get dependentattributename(){let t=this.getFirstChild(b.formControl);return t?t.getParam(h.DependentAttributeName):O.EmptyString}set dependentattributename(t){let r=this.getFirstChild(b.formControl);r&&!this.IsUnboundControl&&r.setParameter(h.DependentAttributeName,t)}get dependentattributetype(){let t=this.getFirstChild(b.formControl);return t?t.getParam(h.DependentAttributeType):O.EmptyString}set dependentattributetype(t){let r=this.getFirstChild(b.formControl);r&&!this.IsUnboundControl&&r.setParameter(h.DependentAttributeType,t)}get disablequickfind(){let t=this.getFirstChild(b.formControl);if(t)return t.getParam(h.DisableQuickFind)==="true"}set disablequickfind(t){let r=this.getFirstChild(b.formControl);r&&!this.IsUnboundControl&&r.setParameter(h.DisableQuickFind,t)}get disableviewpicker(){let t=this.getFirstChild(b.formControl);if(t)return t.getParam(h.DisableViewPicker)==="true"}set disableviewpicker(t){let r=this.getFirstChild(b.formControl);r&&!this.IsUnboundControl&&r.setParameter(h.DisableViewPicker,t)}get filterrelationshipname(){let t=this.getFirstChild(b.formControl);return t?t.getParam(h.FilterRelationshipName):O.EmptyString}set filterrelationshipname(t){let r=this.getFirstChild(b.formControl);r&&!this.IsUnboundControl&&r.setParameter(h.FilterRelationshipName,t)}get availableviewids(){let t=this.getFirstChild(b.formControl);return t?t.getParam(h.AvailableViewIds):O.EmptyString}set availableviewids(t){let r=this.getFirstChild(b.formControl);r&&!this.IsUnboundControl&&r.setParameter(h.AvailableViewIds,t)}get IsUnboundControl(){let t=this.getFirstChild(b.formControl);if(t&&t.ClassId){let r=Me.getUniqueIdentifierForControl(t);return!N.IsNullOrUndefined(r)&&Me.isUnboundFormControlByIdentifier(r)}else return!1}IsAllowedUBCForAvailableOnPhone(){let t=this.getFirstChild(b.formControl);if(t){let n=Me.getUniqueIdentifierForControl(t).guidString,i=n===x.GridControl||n===x.TimeLineControl||n===x.TimeLineControlUC;return this.IsUnboundControl?i:!0}return this.NodeName===b.formSection||this.NodeName===b.formTab}IsAllowedUBCForVisibleByDefault(){let t=this.getFirstChild(b.formControl);if(t){let n=Me.getUniqueIdentifierForControl(t).guidString,i=n===x.MapsControl||n===x.WebResourceHtmlControl||n===x.WebResourceImageControl||n===x.IframeControl||n===x.SocialInsightControl;return this.IsUnboundControl?i:!0}else return!0}get events(){let t=this.getChildren(b.formEvents);return t.length===1?t[0].getAllChildren():[]}addEvent(t){this.addGrandChild(b.formEvents,t)}getUsedNodeNameSet(t){return null}getHighestIndexById(t,r){return null}}});var ya,lf=I(()=>{"use strict";nt();X();We();ya=class extends H{constructor(t,r){super(b.dependency,t),O.IsNullOrEmpty(r)||this.setDefaultProperties(r)}set id(t){this.setProperty(h.id,t)}get id(){return this.getProperty(h.id)}setDefaultProperties(t){this.id=t}}});var wN,ba,uf=I(()=>{"use strict";Oe();lf();X();We();$n();(function(e){e[e.Form=0]="Form",e[e.Cell=1]="Cell",e[e.Tab=2]="Tab",e[e.Control=3]="Control"})(wN||(wN={}));ba=class extends it{constructor(t,r){super(b.formEvent,t),r&&(this.eventName=r,this.application="false",this.active="false")}set eventName(t){this.setProperty(h.Name,t)}get eventName(){return this.getProperty(h.Name)}set application(t){this.setProperty(h.application,t)}get application(){return this.getProperty(h.application)}set attribute(t){this.setProperty(h.EventAttribute,t)}get attribute(){return this.getProperty(h.EventAttribute)}set relationship(t){this.setProperty(h.Relationship,t)}get relationship(){return this.getProperty(h.Relationship)}set control(t){this.setProperty(h.Control,t)}get control(){return this.getProperty(h.Control)}set active(t){this.setProperty(h.EventActive,t)}get active(){return this.getProperty(h.EventActive)}getAllHandlers(){let t=this.getChildren(b.EventHandlers);return t&&t.length?t[0].getChildren(b.handler):[]}getAllDependencies(){let t=this.getChildren(b.formDependencies);return t.length===0?[]:t[0].getAllChildren()}setDependencies(t){let r=this.getFirstChild(b.formDependencies);if(N.IsNullOrUndefined(r)){if(t.length===0)return;this.addChild(new H(b.formDependencies,this)),r=this.getFirstChild(b.formDependencies)}if(t.length===0)r.getParentNode().deleteChild(r);else{r.deleteAllChildren();for(let n of t)r.addChild(new ya(r,n.toString()))}}}});var fr,Yo=I(()=>{"use strict";Le();No();Oe();ai();X();We();cr();fr=class extends H{previewVersion;constructor(t){super(b.formControl,t)}updatePreview(){this.previewVersion=Date.now()}get ClassId(){let t=this.getProperty(h.classid);return t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new P(t)}set ClassId(t){this.setProperty(h.classid,`{${t.ToString()}}`)}get dataFieldName(){return this.getProperty(h.datafieldname)}set dataFieldName(t){this.setProperty(h.datafieldname,t)}set id(t){this.setProperty(h.id,t)}get id(){return this.getProperty(h.id)}get UniqueId(){let t=this.getProperty(h.uniqueid);return N.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new P(t))}set UniqueId(t){this.setProperty(h.uniqueid,`{${t.ToString()}}`)}get isRequired(){return this.getProperty(h.isRequired)==="true"}set isRequired(t){N.IsNullOrUndefined(t)||this.setProperty(h.isRequired,String(t))}get disableMru(){return this.getParam(h.DisableMru)==="true"}set disableMru(t){N.IsNullOrUndefined(t)||this.setParameter(h.DisableMru,t)}get useMFDForCreate(){return this.getParam(h.UseMFDForCreate)==="true"}set useMFDForCreate(t){N.IsNullOrUndefined(t)||this.setParameter(h.UseMFDForCreate,t)}get useMFDForEdit(){return this.getParam(h.UseMFDForEdit)==="true"}set useMFDForEdit(t){N.IsNullOrUndefined(t)||this.setParameter(h.UseMFDForEdit,t)}get disabled(){return this.getProperty(h.disabled)==="true"}set disabled(t){N.IsNullOrUndefined(t)||this.setProperty(h.disabled,String(t))}get indicationOfSubgrid(){return this.getProperty(h.indicationOfSubgrid)==="true"}set indicationOfSubgrid(t){this.setProperty(h.indicationOfSubgrid,String(t))}getAllParameters(){let t=new mt,r=this.getFirstChild(h.parameters);return r&&r.getAllChildren().forEach(n=>{if(n){let i=n.getAllChildren(),a=i&&i.length>0&&i[0];a&&t.add(n.getNodeName(),a.getNodeName())}}),t}setParameter(t,r){let n=!1;r===null&&(n=!0);let i=(rn.StartTag+r).toString(),a=this.parametersNode;if(a){let o=a.findFirst(s=>s&&s.getNodeName()===t);if(o)if(n){this.deleteFirstGrandChildOfName(b.controlParameters,o);return}else{let s=o.getAllChildren();s&&s.length>0&&s[0]?s[0].setNodeName(i):o.addChild(new H(i,o))}else n||(o=new H(t,a),o.addChild(new H(i,o)),a.addChild(o))}else if(!n){a=new H("parameters",this);let o=new H(t,a);o.addChild(new H(i,o)),a.addChild(o),this.addChild(a)}}getParam(t){if(this.parametersNode){let r=this.parametersNode.findFirst(n=>n&&n.getNodeName()===t);if(r){let n=r.getAllChildren(),i=n&&n.length>0&&n[0];if(i){let a=i.getNodeName();return a.charAt(0)===rn.StartTag?a.substring(1):a}}}return null}get parametersNode(){let t=this.getChildren(h.parameters);return t.length===0?null:t[0]}async serializeParameters(t,r){let n=new mt;switch(this.ClassId.guidString.toUpperCase()){case S.LookupControl:if(t&&t.getKeys())if(t.getKeys().forEach(o=>{n.add(o,this.getParam(o))}),t&&t.containsKey("DefaultViewId")){let o=this.getParam("DefaultViewId").replace("{","").replace("}","");n.upsert("DefaultViewId",o)}else{let o=this.getParent(),s=await r.formModelService.lookupControlService.populateDefaultView(this,o.getParentForm().entityName);s&&s.id&&n.upsert("DefaultViewId",s.id.replace("{","").replace("}",""))}break;default:t&&t.getKeys()&&t.getKeys().forEach(o=>{n.add(o,this.getParam(o))});break}let i=n.getInternalObject(),a=[];for(let o in i)i.hasOwnProperty(o)&&a.push({Name:o,Value:i[o]});return a}getIsUnbound(){return this.getProperty(h.isUnbound)==="true"}getAttributeTypeFromClassId(t){if(t)switch(t.toUpperCase()){case S.BooleanControl:case S.CheckboxControl:return 0;case S.DateTimeControl:return 2;case S.DecimalControl:return 3;case S.FloatingNumberControl:return 4;case S.IntegerControl:case S.DurationControl:case S.LanguageControl:case S.TimezoneControl:return 5;case S.LookupControl:return 6;case S.CurrencyControl:return 8;case S.PartyListControl:return 10;case S.ChoiceControl:case S.RelationshipRoleChoiceControl:return 11;case S.ChoiceStatusControl:return 13;case S.TextAreaControl:case S.TextboxControl:case S.LabelControl:case S.EmailAddressControl:case S.UrlControl:case S.TickerControl:case S.ButtonControl:case S.PhoneNumberControl:return 14;case S.ChoicesControl:return 24;default:return}return 14}async toJSON(t){let r=this.getParent(),n=t&&t.formModelService&&t.formModelService.getFormType()===ke.QuickViewForm?!0:this.disabled,i=await this.serializeParameters(this.getAllParameters(),t);return{ClassId:this.ClassId&&this.ClassId.guidString,Parameters:i,Disabled:n,ControlLayout:0,RequiredLevel:0,Type:this.getAttributeTypeFromClassId(this.ClassId.guidString),IsUnbound:this.getIsUnbound(),IsRequired:this.isRequired,DataFieldName:this.dataFieldName,UniqueId:this.UniqueId&&this.UniqueId.guidString,Id:this.previewVersion?this.id+this.previewVersion:this.id,Label:r.getDisplayName(t.langCode),LabelId:r.labelId&&r.labelId.guidString,Name:null,ShowLabel:r.showlabel,PreviewId:r&&r.id.guidString,Visible:r.visible||t.formModelService.showHiddenElements}}}});var wa,cf=I(()=>{"use strict";nt();Zi();Yo();X();We();wa=class extends fr{constructor(t){super(t)}get targetEntityType(){return this.getParam(h.targetEntityType)||O.EmptyString}set targetEntityType(t){this.setParameter(h.targetEntityType,t)}get viewId(){return O.StripBraces(this.getParam(h.viewId))||O.EmptyString}set viewId(t){this.setParameter(h.viewId,O.AddBraces(t))}get viewIds(){return this.getParam(h.viewIds)||O.EmptyString}set viewIds(t){this.setParameter(h.viewIds,t)}get relationshipName(){return this.getParam(h.RelationshipName)||O.EmptyString}set relationshipName(t){this.setParameter(h.RelationshipName,t)}get isUserView(){return O.IsStrictTrue(this.getParam(h.isUserView))}set isUserView(t){this.setParameter(h.isUserView,t.toString())}get enableViewPicker(){return O.IsStrictTrue(this.getParam(h.enableViewPicker))}set enableViewPicker(t){this.setParameter(h.enableViewPicker,t)}get autoExpand(){return this.getParent().autoexpand&&this.getParam(h.autoExpand)===h.Auto}set autoExpand(t){let r=this.getParent();this.setParameter(h.autoExpand,t?h.Auto:h.Fixed),r.autoexpand=t}get recordsPerPage(){return this.getParam(h.recordsPerPage)?Number(this.getParam(h.recordsPerPage)):Number(h.RecordsPerPageRAControlDefault)}set recordsPerPage(t){this.setParameter(h.recordsPerPage,String(t))}get enableQuickFind(){return O.IsStrictTrue(this.getParam(h.enableQuickFind))}set enableQuickFind(t){this.setParameter(h.enableQuickFind,t)}get teamTemplateId(){return O.StripBraces(this.getParam(h.teamTemplateId))||O.EmptyString}set teamTemplateId(t){this.setParameter(h.teamTemplateId,O.AddBraces(t))}get chartId(){return this.getParam(h.visualizationId)||O.EmptyString}set chartId(t){this.setParameter(h.visualizationId,t)}get enableChartPicker(){return O.IsStrictTrue(this.getParam(h.enableChartPicker))}set enableChartPicker(t){this.setParameter(h.enableChartPicker,t)}get chartGridMode(){switch(this.getParam(h.chartGridMode)){case zt.Chart:return zt.Chart;case zt.Grid:return zt.Grid;default:return zt.All}}set chartGridMode(t){this.setParameter(h.chartGridMode,t)}updateChartGridMode(t){t?this.chartGridMode=zt.Chart:this.chartGridMode=this.enableChartPicker?zt.All:zt.Grid}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case h.targetEntityType:n.getAllChildren()[0].setNodeName("<"+r.targetEntityType);break;case h.viewId:n.getAllChildren()[0].setNodeName("<"+O.AddBraces(r.viewId));break;case h.isUserView:n.getAllChildren()[0].setNodeName("<"+r.isUserView);break;case h.enableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.enableViewPicker);break;case h.RelationshipName:let i=n.getAllChildren(),a="<"+r.relationshipName;i.length?n.getAllChildren()[0].setNodeName(a):n.addChild(new H(a,n));break;default:break}}updateControlDescription(t){let r=t.getControlDescriptionByForControl(this.UniqueId);if(r){let n=r.customControls;for(let i=0;i<n.length;i++){let a=n[i].getParameters().get(ht.dataset)?n[i].getParameters().get(ht.dataset)[0]:null;if(a){let o=a.getAllChildren();this.updateDefaultProperties(o,this)}else{let o=n[i].getAllChildren()[0].getAllChildren();this.updateDefaultProperties(o,this)}}}}}});var Aa,df=I(()=>{"use strict";nt();Zi();Yo();X();Aa=class extends fr{constructor(t){super(t)}get defaultViewId(){return O.StripBraces(this.getParam(h.DefaultViewId))||O.EmptyString}set defaultViewId(t){this.setParameter(h.DefaultViewId,O.AddBraces(t))}get autoResolve(){return O.IsStrictTrue(this.getParam(h.AutoResolve))}set autoResolve(t){this.setParameter(h.AutoResolve,t)}get disableQuickFind(){return O.IsStrictTrue(this.getParam(h.DisableQuickFind))}set disableQuickFind(t){this.setParameter(h.DisableQuickFind,t)}get disableViewPicker(){return O.IsStrictTrue(this.getParam(h.DisableViewPicker))}set disableViewPicker(t){this.setParameter(h.DisableViewPicker,t)}get allowFilterOff(){return O.IsStrictTrue(this.getParam(h.AllowFilterOff))}set allowFilterOff(t){this.setParameter(h.AllowFilterOff,t)}get disableMru(){return O.IsStrictTrue(this.getParam(h.DisableMru))}set disableMru(t){this.setParameter(h.DisableMru,t)}get dependentAttributeName(){return this.getParam(h.DependentAttributeName)||O.EmptyString}set dependentAttributeName(t){this.setParameter(h.DependentAttributeName,t)}get dependentAttributeType(){return this.getParam(h.DependentAttributeType)||O.EmptyString}set dependentAttributeType(t){this.setParameter(h.DependentAttributeType,t)}get filterRelationshipName(){return this.getParam(h.FilterRelationshipName)||O.EmptyString}set filterRelationshipName(t){this.setParameter(h.FilterRelationshipName,t)}get availableViewIds(){return this.getParam(h.AvailableViewIds)||O.EmptyString}set availableViewIds(t){this.setParameter(h.AvailableViewIds,t)}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case h.datafieldname:case h.bindAttribute:n.getAllChildren()[0].setNodeName("<"+r.dataFieldName);break;case h.DefaultViewId:n.getAllChildren()[0].setNodeName("<"+O.AddBraces(r.defaultViewId));break;case h.AllowFilterOff:n.getAllChildren()[0].setNodeName("<"+r.allowFilterOff);break;case h.DisableQuickFind:n.getAllChildren()[0].setNodeName("<"+r.disableQuickFind);break;case h.DisableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.disableViewPicker);break;case h.FilterRelationshipName:n.getAllChildren()[0].setNodeName("<"+r.filterRelationshipName);break;case h.DependentAttributeName:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeName);break;case h.DependentAttributeType:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeType);break;case h.AvailableViewIds:n.getAllChildren()[0].setNodeName("<"+r.availableViewIds);break;case h.DisableMru:n.getAllChildren()[0].setNodeName("<"+r.disableMru);break;case h.AutoResolve:n.getAllChildren()[0].setNodeName("<"+r.autoResolve);break;default:break}}updateControlDescription(t){let r=t.getControlDescriptionByForControl(this.UniqueId);if(r){let n=r.customControls;for(let i=0;i<n.length;i++){let a=n[i].getParameters().get(ht.value)?n[i].getParameters().get(ht.value)[0]:null;if(a){let o=a.getAllChildren();this.updateDefaultProperties(o,this)}else{let o=n[i].getAllChildren()[0].getAllChildren();this.updateDefaultProperties(o,this)}}}}}});var AN,pf,Dt,Zo=I(()=>{"use strict";AN=ie(bN());$n();X();Oe();Le();uf();Yo();kl();yp();Kd();cr();ai();Ki();cf();df();ff();Oo();pf="_",Dt=class e extends it{fieldPlaceholder;fieldRequiredLevel;isNewField;cellColType;dependentFields=[];constructor(t){super(b.formCell,t),this.isNewField=!1}get cellType(){return this.cellColType}set cellType(t){this.cellColType=t}setDefaultProperties(t){this.showlabel=t,this.isLocked=!1,N.IsNullOrUndefined(this.getProperty(h.id))&&(this.id=new P(P.NewGuid()))}addControl(t,r,n,i,a,o,s){n instanceof fr?this.addChild(n):n instanceof P&&this.addChild(this.getControlWithControlSpecificProperties(t,r,n,i,a,o,s))}removeControl(){return this.deleteChild(this.control)>=0}get isIndependent(){if(!N.IsNullOrUndefined(this.control))return N.IsNullOrUndefined(this.control.dataFieldName)?N.IsNullOrUndefined(this.control.id)?!0:!si.dependencyFieldCount.containsKey(this.control.id):!si.dependencyFieldCount.containsKey(this.control.dataFieldName)}createOnLoadEvent(){this.addEvent(new ba(this,Eo.onLoad))}get dependencies(){let t=this.getChildren(b.formEvents);for(let r of t){let n=r.getChildren(b.formEvent);for(let i of n)this.buildDependencyList(i,this.dependentFields)}return this.dependentFields}getNextAvailableControlName(t,r,n,i){let a;if(i&&Cl[i])a=Cl[i].replace(/ /g,pf)+pf;else{a="Control_";let u=new Error("Control class id does not exist or is undefined");(0,AN.trackErrorTrace)(ft,{eventName:`${hy}/getNextAvailableControlName`},u)}let o="new_",s=this.getHighestIndexById(t,i)+1,l=`${a}${o}${s}`;for(;n.has(l);)s++,l=`${a}${o}${s}`;return l}getUnboundControlProperties(t){e.prototype.setProperty.call(t,h.isUnbound,"true"),e.prototype.setProperty.call(t,h.isRequired,"false")}getControlWithControlSpecificProperties(t,r,n,i,a,o,s){let l;a===Ht.Grid?(l=new wa(this),l.indicationOfSubgrid=!0):a===Ht.Lookup?l=new Aa(this):l=new fr(this);let u=n.guidString,c=o||this.getNextAvailableControlName(t,i,this.getUsedNodeNameSet(t),u);if(e.prototype.setProperty.call(l,h.id,c),l.ClassId=n,!N.IsNullOrUndefined(s)&&(l.UniqueId=s),!o&&r)this.getUnboundControlProperties(l);else{let d=Me.getUniqueIdentifierForControl(l);N.IsNullOrUndefined(d)||(Me.getControlDataTypeByControlOrUniqueId(d)===z.QuickFormCollectionControl||!Me.isUnboundFormControlByIdentifier(d)?a!==Ht.Grid&&o&&u!==S.IframeControl&&u!==S.SubgridControl&&u!==S.ReferencePanelSubgridControl&&(l.dataFieldName=o,e.prototype.setProperty.call(l,h.disabled,"false")):(this.rowspan=Me.GetRowSpan(l),(Me.getControlDataTypeByControlOrUniqueId(d)===z.NotesControl||Me.getControlDataTypeByControlOrUniqueId(d)===z.TimeLineControl)&&(e.prototype.setProperty.call(l,h.disabled,"false"),l.id=z.NotesControl)),(Me.getUnboundControlNameFromIdentifier(n)===z.SubGridControl||Me.getUnboundControlNameFromIdentifier(n)===z.NotesControl||Me.getUnboundControlNameFromIdentifier(n)===z.TimeLineControl)&&(this.availableforphone=!0))}return l}buildDependencyList(t,r){if(N.IsNullOrUndefined(t))return;let n=t.getAllChildren();for(let i of n){let a=i.getAllChildren();for(let o of a){let s=o.GetPropertyByParameter(h.id);o.getNodeName()===b.dependency&&s?r.push(s):this.buildDependencyList(o,r)}}}get control(){return this.getFirstChild(b.formControl)}set rowspan(t){this.setProperty(h.rowspan,String(t))}get rowspan(){let t=this.getProperty(h.rowspan);return N.IsNullOrUndefined(t)?1:parseInt(t,10)}set autoexpand(t){this.setProperty(h.auto,String(t))}get autoexpand(){return this.getProperty(h.auto)==="true"}set colspan(t){let r=Number(gp.ONE_COLUMN),n=Number(gp.FOUR_COLUMN);N.IsNullOrUndefined(t)||t>n||t<r||this.setProperty(h.colspan,String(t))}get colspan(){let t=this.getProperty(h.colspan);return N.IsNullOrUndefined(t)?1:parseInt(t,10)}getParentRow(){return this.getAncestor(b.formRow)}getParentSection(){return this.getAncestor(b.formSection)}getParentTab(){return this.getAncestor(b.formTab)}getParentForm(){return this.getAncestor(b.form)}isInHeader(){let t=this.getAncestor(b.formHeader);return!N.IsNullOrUndefined(t)}isInFooter(){let t=this.getAncestor(b.formFooter);return!N.IsNullOrUndefined(t)}isEmpty(){return N.IsNullOrUndefined(this.control)&&!this.IsUserSpacer}getHeaderFooter(){return this.isInHeader()?this.getAncestor(b.formHeader):this.isInFooter()?this.getAncestor(b.formFooter):null}get FieldRequiredLevel(){return this.fieldRequiredLevel}set FieldRequiredLevel(t){this.fieldRequiredLevel=t}get FieldPlaceholder(){return this.fieldPlaceholder}set FieldPlaceholder(t){this.fieldPlaceholder=t}get IsNewField(){return this.isNewField}set IsNewField(t){this.isNewField=t}get IsUserSpacer(){let t=this.getProperty(h.userspacer);return N.IsNullOrUndefined(t)?!1:t==="true"}SetUserSpacer(){this.setProperty(h.userspacer,"true")}ClearUserSpacer(){this.setProperty(h.userspacer,"false")}get columns(){let t=this.getProperty(h.columnName);return N.IsNullOrUndefined(t)?null:parseInt(t,10)}getColumnLayoutValue(t){let r;switch(t){case Ce.TWO_COLUMN:r="11";break;case Ce.THREE_COLUMN:r="111";break;case Ce.FOUR_COLUMN:r="1111";break;default:r="1"}return r}findRowIndexByCellId(t){let r=this.getParentRow().cells.indexOf(this);for(let n=0;n<t.rows.length;n++)if(!N.IsNullOrUndefined(t.rows[n].cells[r])&&this.id.ToString()===t.rows[n].cells[r].id.ToString())return n;return-1}setAutoExpandDetailsForTab(){let t=this.getParentTab();N.IsNullOrUndefined(t)||(t.autoExpandCell=this,t.tabContainsAutoExpandControl=!0)}isCellRequiredOrLocked(t,r,n){let i=this.getParentForm();if(this?.control){if(this.IsUserSpacer)return!1;{if(this.isLocked||r().has(this.control.dataFieldName))return!0;let a=i.isDuplicateCell(this,n),o=this.getRequiredLevel(t);if((o===ui.ApplicationRequired||o===ui.SystemRequired)&&!a||this.isCellLockedByExternal(t)&&!a)return!0}}return!1}getRequiredLevel(t){return!this.control?.dataFieldName||!this.control?.id||this.IsNewField||!this.control?.ClassId?ui.None:t.getEntityAttributeByName(this.control.dataFieldName)?.requiredLevel?.toString()??ui.None}isCellLockedByExternal(t){return this.control||this.IsUnboundControl?!1:t.getEntityAttributeByName(this.control.dataFieldName).isRequiredForForm||!this.isIndependent}async toJSON(t){return{Id:this.id&&this.id.guidString,Name:this.Name,Label:this.getDisplayName(t.langCode),ShowLabel:this.showlabel,Visible:this.visible||t.formModelService.showHiddenElements,LabelId:this.labelId.guidString,PreviewId:this.id&&this.id.guidString,ColSpan:this.colspan,RowSpan:this.rowspan,AutoExpand:this.autoexpand,IsInFirstColumnOfSection:!1,IsInLastColumnOfSection:!1,AvailableForPhone:this.availableforphone,UserSpacer:this.IsUserSpacer,IsPreviewCell:!1,IsStreamCell:!1,IsChartCell:!1,IsTileCell:!1,Control:this.control&&await this.control.toJSON(t)}}getUsedNodeNameSet(t){let r=new Set;return t&&t.visit(n=>{if(n.getNodeName()===b.formCell){let i=n;i.control&&i!==this&&r.add(n.control.id)}return!1}),r}getHighestIndexById(t,r){let n=t.findAll(a=>a.getNodeName()===b.formCell&&a.control&&a.control.ClassId.guidString===r),i=0;return n.forEach(a=>{i=Math.max(this.parseControlNameIndex(a.control.id),i)}),i}parseControlNameIndex(t){let r=t.length-1,n=0;for(;r>0&&parseInt(t.charAt(r),10);)r--;return r>0&&r!==t.length-1&&t.charAt(r)===pf&&(r++,n=parseInt(t.substr(r,t.length-r),10)),n}}});var Ca,mf=I(()=>{"use strict";nt();X();We();Ca=class extends H{isInternal;constructor(t,r,n,i){super(b.library,t),this.isInternal=!!i,O.IsNullOrEmpty(n)||(this.name=r,this.libraryUniqueId=n)}get libraryUniqueId(){let t=this.getProperty(h.libraryUniqueId);return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),t?.toUpperCase()}set libraryUniqueId(t){this.setProperty(h.libraryUniqueId,t)}get name(){return this.getProperty(h.libraryName)}set name(t){this.setProperty(h.libraryName,t)}get displayName(){return this.getProperty(h.displayName)}set displayName(t){this.setProperty(h.displayName,t)}get description(){return this.getProperty(h.description)}set description(t){this.setProperty(h.description,t)}}});var mi,hf=I(()=>{"use strict";Oe();Zo();X();We();mi=class extends H{isRowAddedOnDragOver;constructor(t){super(b.formRow,t)}addCell(t){this.addChild(t)}appendCells(t){for(let r of t)this.addChild(r)}updateCell(t,r){return this.updateChild(t,r)}removeCell(t){return N.IsNullOrUndefined(t)?!1:this.deleteChild(t)>=0}insertCellAtIndex(t,r){return N.IsNullOrUndefined(t)?!1:(this.insertChildAtIndex(t,r),!0)}isEmpty(){return!this.cells||this.cells.every(t=>t.isEmpty())}getParentSection(){return this.getAncestor(b.formSection)}insertPaddingCellAtIndex(t){let r=new Dt(this);r.setDefaultProperties(),this.insertCellAtIndex(r,t)}get firstCell(){let t=this.cells;return t.length>0?t[0]:null}get cells(){return this.getChildren(b.formCell)}get rowColspan(){return this.cells.reduce((t,r)=>t+r.colspan,0)}set IsRowAddedOnDragOver(t){this.isRowAddedOnDragOver=t}get IsRowAddedOnDragOver(){return this.isRowAddedOnDragOver}async getCellsJSON(t){let r=[],n=[];if(this.cells){for(let i of this.cells)n.push(i.toJSON(t));for(let i of n)r.push(await i)}return r}async toJSON(t){return{Cells:await this.getCellsJSON(t),Visible:!0,Height:"0"}}}});function MV(e){switch(e){case ci.Left:return di.Left;case ci.Right:return di.Right;case ci.Center:return di.Center;default:return di.Left}}function UV(e){switch(e){case ra.Left:return ia.Left;case ra.Top:return ia.Top;default:return ia.Left}}function CN(e){switch(e){case 1:return 1;case 2:return 11;case 3:return 111;case 4:return 1111;default:return 1}}var BV,Rr,es=I(()=>{"use strict";bp();Le();Oe();nt();sf();Zo();X();cr();$n();hf();BV=115,Rr=class e extends it{colSpan=1;constructor(t,r){super(t,r)}getSectionType(){let t;switch(this.columns){case 1:t=Ce.ONE_COLUMN;break;case 11:t=Ce.TWO_COLUMN;break;case 111:t=Ce.THREE_COLUMN;break;case 1111:t=Ce.FOUR_COLUMN;break;default:t=this.colSpan-1}return t}setUniqueName(){let t=this.getParentTab(),r=we.namePrefix;if(t){let n=t.Name,i=t.TotalSectionsCount+1;r=n+we.namePrefix+i.toString()}else r+=Math.floor(Math.random()*1e3);this.setProperty(h.Name,r)}initializeDefaultProperties(t,r,n){if(n===Ce.REFERENCE_PANEL){this.addProperty(h.rowheight,"25");let i=`${we.referencePanelNamePrefix}${P.NewGuid()}${we.namePrefix}`;this.addProperty(h.Name,i)}else this.setUniqueName();if(this.addProperty(h.id,new P(P.NewGuid()).guidString),this.addProperty(h.IsUserDefined,we.IsUserDefined),this.addProperty(h.locklevel,we.LockLevel),this.addProperty(h.showlabel,we.ShowLabel),this.addProperty(h.showbar,we.ShowBar),this.addProperty(h.layout,we.Layout),this.addProperty(h.Fieldlabelalignment,we.labelAlignment),this.addProperty(h.Fieldlabelposition,we.labelPosition),N.IsNullOrUndefined(n))this.addProperty(h.columnName,we.columns);else{let i=this.getColumnLayoutValue(n);this.addProperty(h.columnName,i)}this.addProperty(h.LabelWidth,we.LabelWidth),this.setDisplayName(r,t)}getColumnLayoutValue(t){let r;switch(t){case Ce.TWO_COLUMN:r="11";break;case Ce.THREE_COLUMN:r="111";break;case Ce.FOUR_COLUMN:r="1111";break;default:r="1"}return r}getNumberOfColumns(){return e.getNumericColumnLayoutValue(this.columns)}static getNumericColumnLayoutValue(t){switch(t){case 1:return 1;case 11:return 2;case 111:return 3;case 1111:return 4;default:throw new Error("Unexpected Section Layout Value.")}}getColumnCountValue(){let t=0;return N.IsNullOrUndefined(this.columns)?t=this.ColSpan:this.columns.toString().split(O.EmptyString).forEach(r=>{t+=parseInt(r,10)}),t}get ColSpan(){return this.colSpan}initializeRow(t){if(t>0&&t<5){let r=new mi(null);if(this.addGrandChild(b.formRows,r),hN.getConfig().enableAutoInsertionOfCellInRow)for(let n=0;n<t;n++){let i=new Dt(r);i.setDefaultProperties(!1),r.addCell(i)}}}initialize(t,r,n){this.initializeDefaultProperties(t,r,n),n===Ce.REFERENCE_PANEL&&(n=Ce.ONE_COLUMN),this.initializeRow(n+1)}setColSpan(t){this.colSpan=t}appendRow(t){this.addGrandChild(b.formRows,t)}insertRowAtIndex(t,r){this.addGrandChildAtIndex(b.formRows,t,r)}insertRowsAtIndex(t,r){if(t&&t.length>0)for(let n=0;n<t.length;n++)this.addGrandChildAtIndex(b.formRows,t[n],r+n)}indexOfRow(t){return this.rows.indexOf(t)}deleteRow(t){return this.deleteFirstGrandChildOfName(b.formRows,t)}deleteRows(t,r){this.deleteGrandChildren(b.formRows,t,r)}get rows(){return this.getRows()}getRows(){let t=this.getChildren(b.formRows);return t.length===0?[]:t[0].getChildren(b.formRow)}get columns(){let t=this.getProperty(h.columnName),r=N.IsNullOrUndefined(t)?NaN:parseInt(t,10);if(isNaN(r)){let n=1;for(let i of this.rows)n=Math.max(n,i.cells.length);return CN(n)}return r}set columns(t){N.IsNullOrUndefined(t)||this.setProperty(h.columnName,String(t))}get rowHeight(){let t=this.getProperty(h.rowheight);return N.IsNullOrUndefined(t)?null:parseInt(t,10)}set rowHeight(t){this.setProperty(h.rowheight,String(t))}set autoexpand(t){this.setProperty(h.autoExpand.toLowerCase(),String(t))}get autoexpand(){return this.getProperty(h.autoExpand.toLowerCase())==="true"}get isUserDefined(){return+this.getProperty(h.IsUserDefined)!=0}set isUserDefined(t){t?this.setProperty(h.IsUserDefined,"1"):this.setProperty(h.IsUserDefined,"0")}getParentColumn(){return this.getAncestor(b.formColumn)}getParentTab(){return this.getAncestor(b.formTab)}get hasMultiColumnRow(){return this.getColumnCountValue()>1}get showlabel(){return this.getProperty(h.showlabel)==="true"}set showlabel(t){N.IsNullOrUndefined(t)||this.setProperty(h.showlabel,String(t))}get fieldLabelAlignment(){let t=we.labelAlignment,r=this.getProperty(h.Fieldlabelalignment);return N.IsNullOrUndefined(r)?t:r}set fieldLabelAlignment(t){N.IsNullOrUndefined(t)||this.setProperty(h.Fieldlabelalignment,t)}get fieldLabelPosition(){let t=this.getProperty(h.Fieldlabelposition);return N.IsNullOrUndefined(t)?we.labelPosition:t}set fieldLabelPosition(t){N.IsNullOrUndefined(t)||this.setProperty(h.Fieldlabelposition,String(t))}get showbar(){return this.getProperty(h.showbar)==="true"}set showbar(t){N.IsNullOrUndefined(t)||this.setProperty(h.showbar,String(t))}get labelwidth(){let t=+this.getProperty(h.LabelWidth);return t===0?BV:t}set labelwidth(t){N.IsNullOrUndefined(t)||t>283&&t<57||this.setProperty(h.LabelWidth,t.toString())}async getRowsJSON(t){let r=[],n=[];if(this.rows){for(let i of this.rows)n.push(i.toJSON(t));for(let i of n)r.push(await i)}return r}async toJSON(t){return{Name:this.Name,Id:this.id&&this.id.guidString,Label:this.getDisplayName(t.langCode),ShowLabel:this.showlabel,Visible:this.visible||t.formModelService.showHiddenElements,LabelId:this.labelId&&this.labelId.guidString,PreviewId:this.id&&this.id.guidString,Rows:await this.getRowsJSON(t),CellLabel:{Width:this.labelwidth,Alignment:MV(this.fieldLabelAlignment),Position:UV(this.fieldLabelPosition)},Columns:CN(this.getColumnCountValue()),AvailableForPhone:this.availableforphone,Height:this.rowHeight&&this.rowHeight.toString()}}getUsedNodeNameSet(t){let r=new Set;return t&&t.visit(n=>{if(n.getNodeName()===b.formSection){let i=n;i.Name&&!O.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}isReferencePanelSection(){return!N.IsNullOrUndefined(this)&&!N.IsNullOrUndefined(this.Name)&&this.Name.indexOf(we.referencePanelNamePrefix)===0}getAllMultiRowCells(){return this.findAll(t=>{if(t.getNodeName()===b.formCell){let r=t;return!r.isEmpty()&&r.rowspan>1}return!1})}isHeaderOrFooterSection(){return this.NodeName===b.formFooter||this.NodeName===b.formHeader}}});var qn,Zl=I(()=>{"use strict";X();We();es();qn=class e extends H{constructor(t){super(b.formColumn,t)}initializeDefaultProperties(t){this.addProperty(h.width,t.toString()+"%")}insertSectionAtIndex(t,r){this.addGrandChildAtIndex(b.formSections,t,r)}static createAndInitNewSection(t,r,n){let i=new Rr(b.formSection,null);return i.initialize(t,r,n),i}addSectionAtIndex(t,r){this.addGrandChildAtIndex(b.formSections,t,r)}initialize(t,r,n,i=Ce.ONE_COLUMN){this.initializeDefaultProperties(t);let a=e.createAndInitNewSection(r,n,i);this.addSectionAtIndex(a,this.sections.length),a.setUniqueName()}get parentTab(){return this.getAncestor(b.formTab)}get sections(){let t=this.getChildren("sections");return t.length!==1?[]:t[0].getChildren(b.formSection)}get width(){return this.getProperty(h.width)}set width(t){this.setProperty(h.width,t)}deleteSection(t){return this.deleteFirstGrandChildOfName(b.formSections,t)}async getSectionsJSON(t){let r=[];if(this.sections)for(let n of this.sections)r.push(await n.toJSON(t));return r}async toJSON(t){return{Name:this.getProperty(h.Name),Id:this.getProperty(h.id),Label:null,ShowLabel:!1,Visible:!0,LabelId:null,PreviewId:this.getProperty(h.id),Sections:await this.getSectionsJSON(t),Width:this.width}}}});var eu,EN=I(()=>{"use strict";Le();X();cr();es();eu=class extends Rr{initializeNavArea(t,r,n){this.initializeNavAreaProps(t,r,n)}get AreaName(){return this.Name}initializeNavAreaProps(t,r,n){this.addProperty(h.Name,n),this.addProperty(h.id,new P(P.NewGuid()).guidString),this.addProperty(h.columnName,we.columns),this.setDisplayName(r,t)}}});var tu,SN=I(()=>{"use strict";Zl();X();EN();tu=class extends qn{addAndIntializeNavBarSection(t,r,n,i){let a=new eu(b.formSection,null);return a.initializeNavArea(t,r,i),this.addGrandChildAtIndex(b.formSections,a,n),a}}});var an,ru=I(()=>{"use strict";Le();Oe();nt();Zl();X();We();$n();an=class extends it{tabContainsAutoExpandControl;autoExpandCell;constructor(t,r){super(b.formTab,t),this.tabContainsAutoExpandControl=!1}getParentForm(){return this.getAncestor(b.form)}getTabLayoutType(){let t;switch(this.columns.length){case 1:t=Ae.ONE_COLUMN;break;case 2:if(parseInt(this.columns[0].width,10)===50&&parseInt(this.columns[1].width,10)===50){t=Ae.TWO_COLUMN_EQUAL;break}if(parseInt(this.columns[0].width,10)===67&&parseInt(this.columns[1].width,10)===33){t=Ae.TWO_COLUMN_WIDER_LEFT;break}if(parseInt(this.columns[0].width,10)===34&&parseInt(this.columns[1].width,10)===66){t=Ae.TWO_COLUMN_WIDER_RIGHT;break}t=Ae.TWO_COLUMN_CUSTOM_LAYOUT;break;case 3:if(parseInt(this.columns[0].width,10)===34&&parseInt(this.columns[1].width,10)===33&&parseInt(this.columns[2].width,10)===33){t=Ae.THREE_COLUMN_EQUAL;break}if(parseInt(this.columns[0].width,10)===28&&parseInt(this.columns[1].width,10)===44&&parseInt(this.columns[2].width,10)===28){t=Ae.THREE_COLUMN_WIDER_MID;break}t=Ae.THREE_COLUMN_CUSTOM_LAYOUT;break;default:}return t}initializeProperties(t,r,n){this.addProperty(h.Name,xn.namePrefix+t.toString()),this.addProperty(h.id,new P(P.NewGuid()).guidString),this.addProperty(h.IsUserDefined,xn.IsUserDefined),this.addProperty(h.locklevel,xn.LockLevel),this.addProperty(h.showlabel,xn.ShowLabel),this.setDisplayName(n,r)}get TotalSectionsCount(){let t=0;for(let r of this.columns)t+=r.sections.length;return t}initializeColumns(t,r,n,i=Ce.ONE_COLUMN,a=!0,o){let s=this.getChildren(b.formColumns)[0],l=[];switch(t){case Ae.ONE_COLUMN:l.push(100);break;case Ae.TWO_COLUMN_EQUAL:l.push(50),l.push(50);break;case Ae.TWO_COLUMN_WIDER_LEFT:l.push(67),l.push(33);break;case Ae.TWO_COLUMN_WIDER_RIGHT:l.push(34),l.push(66);break;case Ae.THREE_COLUMN_EQUAL:l.push(34),l.push(33),l.push(33);break;case Ae.THREE_COLUMN_WIDER_MID:l.push(28),l.push(44),l.push(28);break;default:}for(let u of l){let c=new qn(s);c.initialize(u,r,n,i),this.addGrandChild(b.formColumns,c)}}initialize(t,r,n,i,a,o=Ce.ONE_COLUMN,s=!0,l){this.addChild(new H(b.formColumns,this)),this.initializeProperties(r,n,i),this.initializeColumns(t,n,a,o,s,l)}get columns(){let t=this.getChildren(b.formColumns);return t.length!==1?[]:t[0].getChildren(b.formColumn)}get expanded(){return this.getProcessedValue(h.expanded)}set expanded(t){N.IsNullOrUndefined(t)||this.setProperty(h.expanded,String(t))}get groupName(){return this.getProperty(h.groupName)}get contentType(){return this.getProperty(h.contentType)}set contentType(t){this.setProperty(h.contentType,t)}insertNewColumnAtIndex(t,r,n,i,a){t.initialize(n,i,a),this.addGrandChildAtIndex(b.formColumns,t,r)}insertColumnAtIndex(t,r){this.addGrandChildAtIndex(b.formColumns,t,r)}deleteColumn(t){return this.deleteFirstGrandChildOfName(b.formColumns,t)}async getColumnsJSON(t){let r=[],n=[];if(this.columns){for(let i of this.columns)n.push(i.toJSON(t));for(let i of n)r.push(await i)}return r}async toJSON(t){return{Name:this.Name,Id:this.id&&this.id.guidString,Label:this.getDisplayName(t.langCode)+(!this.visible&&t.formModelService.showHiddenElements?"\u3000\u3000":""),ShowLabel:this.showlabel,Visible:this.visible||t.formModelService.showHiddenElements,LabelId:this.labelId&&this.labelId.guidString,UniqueId:this.id&&this.id.guidString,PreviewId:this.id&&this.id.guidString,Columns:await this.getColumnsJSON(t),EventHandlers:[],Expanded:this.expanded,ContentType:this.contentType,AvailableForPhone:this.availableforphone,Header:void 0,Footer:void 0}}getUsedNodeNameSet(t){let r=new Set;return t&&t.visit(n=>{if(n.getNodeName()===b.formTab){let i=n;i.Name&&!O.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}}});var hi,gf=I(()=>{"use strict";Le();X();We();cr();SN();ru();hi=class extends an{constructor(t,r,n){super(t,Ae.THREE_COLUMN_EQUAL),this.setDisplayName(r,n),this.id=new P(P.NewGuid())}initializeDefaultProps(){this.addChild(new H(b.formColumns,this)),this.initializeFiveColumns()}get columns(){let t=this.getChildren("columns");return t.length!==1?[]:t[0].getChildren(b.formColumn)}getNavSectionForArea(t){for(let r of this.columns)for(let n of r.sections)if(n.AreaName===t)return n;return null}getNavCellFromNavId(t){for(let r of this.columns)for(let n of r.sections)for(let i of n.rows)for(let a of i.cells)if(a.NavId===t)return a;return null}initializeFiveColumns(){for(let t=0;t<xl.FIVE_COLUMN;t++){let r=new tu(this.getChildren(b.formColumns)[0]);r.initializeDefaultProperties(Wy.FiveEqColumn),this.addGrandChild(b.formColumns,r)}}}});function qV(e){switch(e){case ke.Main:return kn.Main;case ke.QuickCreate:return kn.QuickCreate;case ke.QuickViewForm:return kn.Quick;case ke.Dialog:return kn.Dialog;default:return kn.None}}function VV(e,t){if(t===ke.Main){if(e)switch(e.toLowerCase()){case"low":return Fn.Low;case"highreadonlyvalues":return Fn.HighReadOnlyValues;default:return Fn.HighWithControls}return Fn.Low}}var iu,$V,nu,NN=I(()=>{"use strict";Yy();iu=ie(oi());bp();Oe();nt();Ki();sf();X();Zi();Md();ai();Zo();X();$n();mf();gf();ru();$V="1920";nu=class e extends it{_formUniqueName;isHeaderDefaulted;consistencyStrong=!1;_formId;_rawFormXml;_entityName;_entityDisplayName;_status;_formName;_langCode;_description;_formType;_formPresentation;parameters=[];_formactivationstate;_changeTracker;_metadataChangeEvent;_etag;constructor(t,r,n,i,a,o,s,l,u){super(b.form,null),this._formUniqueName=a,this._formId=t,this._entityName=r,this._status=n,this._formName=i,this._description=l,this._formType=o,this._formPresentation=s,this._formactivationstate=u,this._changeTracker=new yl,this._metadataChangeEvent=new Ml}get FormLibraries(){let t=this.getFirstChild(b.formLibraries),r=t?t.getAllChildren():[],n=this._getInternalLibraries();return r.concat(n)}getAllEvents(){let t=[],r=this.events;r&&(t=t.concat(r));for(let n of this.tabs){let i=n.events;i&&(t=t.concat(i)),n.findAll(a=>a instanceof Dt).forEach(a=>{let o=a.events;o&&(t=t.concat(o))})}return t}getEventsForNode(t){if(t instanceof e){let r=t.events;return r?r.filter(n=>!n.control&&!n.attribute):null}else if(t instanceof Dt){if(t.control?.dataFieldName){let r=this.events;return r?r.filter(n=>n.attribute&&t.control.dataFieldName===n.attribute):null}else if(this.isCellEditableGridControl(t)){let r=this.events;return r?r.filter(n=>n.control&&t.control.id===n.control):null}}return t?.events}_getInternalLibraries(){let t=this.findAll(i=>i.getNodeName()===b.internalLibraries),r=[],n="src";return t.length>0&&(r=t.map(i=>{let a=i.GetPropertyByParameter(n).replace("$webresource:",""),o=new Ca(void 0,void 0,"",!0);return o.name=a,o.displayName=a,o})),r}getDependentFields(){let t=this.getAllEvents(),r=new Set;return t.forEach(n=>{try{n.getAllDependencies().forEach(a=>{r.add(a.id)})}catch(i){throw(0,iu.trackErrorTrace)(gy,{eventName:"GetDependentFields_MissingDependencies",eventData:{Message:`Failed get dependencies for form event in form ${this.formId.guidString}.`,Attribute:n.attribute,EventName:n.eventName}}),i}}),r}get Parameters(){return this.parameters}set Parameters(t){this.parameters=t}get ShowImagecheck(){return O.IsNullOrEmpty(this.getProperty(h.ShowImage))?!0:this.getProperty(h.ShowImage)!=="false"}set ShowImagecheck(t){t?this.setProperty(h.ShowImage,String(t)):this.setProperty(h.ShowImage,"false")}get ShowNavigation(){return O.IsNullOrEmpty(this.getProperty(h.ShowNavigationbar))?!0:this.getProperty(h.ShowNavigationbar)!=="false"}set ShowNavigation(t){t?this.setProperty(h.ShowNavigationbar,String(t)):this.setProperty(h.ShowNavigationbar,"false")}get MaxWidth(){return O.IsNullOrEmpty(this.getProperty(h.MaxWidth))?$V:this.getProperty(h.MaxWidth)}set MaxWidth(t){this.setProperty(h.MaxWidth,t)}get headerDensityType(){return this.getProperty(h.HeaderDensityType)}set headerDensityType(t){t&&this.formType===ke.Main?this.setProperty(h.HeaderDensityType,t):this.formType!==ke.Main&&this.headerDensityType&&this.removeProperty(h.HeaderDensityType)}IsMainOrQuickCreateForm(){return this.formType===ke.Main||this.formType===ke.QuickCreate}get FormPresentation(){return this._formPresentation}get LanguageCode(){return this._langCode}set LanguageCode(t){this._langCode=t}get header(){let t=this.getChildren(b.formHeader);return t.length!==1?null:t[0]}set header(t){N.IsNullOrUndefined(t)||(this.deleteChild(this.header),this.addChild(t))}getAllDependencies(){return this.getChildren(b.quickFormDependencies).length===0?[]:this.ConvertModelToArray(this.getChildren(b.quickFormDependencies)[0].getAllChildren())}ConvertModelToArray(t){let r=[];return N.IsNullOrUndefined(t)||t.forEach(n=>{r.push(n.id)}),r}get footer(){let t=this.getChildren(b.formFooter);return t.length!==1?null:t[0]}set footer(t){N.IsNullOrUndefined(t)||(this.deleteChild(this.footer),this.addChild(t))}createAndInitNewTab(t,r,n){let i=new an(null,t),a=this.getNextTabCounter(this.tabs.length+1);return i.initialize(t,a,this.LanguageCode,r,n),i}addTabAtIndex(t,r){this.addGrandChildAtIndex(b.formTabs,t,r)}createAndInitNewTabWithMarginalControl(t,r,n,i,a){let o=new an(null,Ae.ONE_COLUMN),s=this.getNextTabCounter(this.tabs.length+1);o.initialize(Ae.ONE_COLUMN,s,this.LanguageCode,r,n,a,!1),this.addGrandChildAtIndex(b.formTabs,o,i);let l=o.columns[0].sections[0];for(let u=0;u<t.rows.length;u++)l.appendRow(t.rows[u])}getNextTabCounter(t){for(let r=0;r<this.tabs.length;r++)if(this.tabs[r].Name===xn.namePrefix+t.toString())return this.getNextTabCounter(t+1);return t}get allTabs(){let t=this.getChildren(b.formTabs);return t.length!==1?[]:t[0].getChildren(b.formTab)}get CanvasNavigationTab(){if(this.tabs.length>0){let t=this.tabs[this.tabs.length-1];if(t instanceof hi)return t}return null}get NavigationNode(){let t=this.getChildren(b.formNavigation);return t.length!==1?null:t[0]}set NavigationNode(t){let n=this.getAllChildren().indexOf(this.NavigationNode);n>=0&&(this.deleteChild(this.NavigationNode),this.insertChildAtIndex(t,n))}addNavigatioNode(t){this.addChild(t)}get tabs(){return this.allTabs}deleteTab(t){return this.deleteFirstGrandChildOfName(b.formTabs,t)}insertTabAtIndex(t,r){this.addGrandChildAtIndex(b.formTabs,t,r)}insertRelatedTab(t){let r=this.getAllGrandChildren(b.formTabs);if(!N.IsNullOrUndefined(r)){let n=r.length;this.insertTabAtIndex(t,n)}}get isfooterPresent(){return this.getChildren(b.formFooter).length>0}get displayCondition(){let t=this.getChildren(b.formDisplayConditions);return t.length>0?t[0]:null}set displayCondition(t){this.deleteChild(this.displayCondition),this.addChild(t)}get entityName(){return this._entityName}get formId(){return this._formId}set formId(t){this._formId=t}get rawFormXml(){return this._rawFormXml}set rawFormXml(t){this._rawFormXml=t}get status(){return this._status}set status(t){this._status=t}get formName(){return this._formName}set formName(t){this.trackObjectPropertyChange("_formName",t)}get formUniqueName(){return this._formUniqueName}set formUniqueName(t){this.trackObjectPropertyChange("_formUniqueName",t)}get formType(){return this._formType}get tabCount(){return this.allTabs.length}get description(){return this._description}set description(t){this.trackObjectPropertyChange("_description",t)}get formactivationstate(){return this._formactivationstate}set formactivationstate(t){this.trackObjectPropertyChange("_formactivationstate",t)}get entityDisplayName(){return this._entityDisplayName}set entityDisplayName(t){this._entityDisplayName=t}get etag(){return this._etag}set etag(t){this._etag=t}indexOfTab(t){return this.getAllGrandChildren(b.formTabs).indexOf(t)}get ControlDescriptions(){return this.getAllGrandChildren(b.controlDescriptions)}addControlDescriptionNode(t){this.addGrandChild(b.controlDescriptions,t)}deleteControlDescByForControlId(t){let r=this.getControlDescriptionByForControl(t);N.IsNullOrUndefined(r)||this.deleteFirstGrandChildOfName(b.controlDescriptions,r)}getControlDescriptionByForControl(t){if(!t)return null;for(let r of this.ControlDescriptions)if(r.forControl.guidString===t.guidString)return r;return null}cellHasCustomControlWithName(t,r){if(!t?.control||!r)return!1;let n=this.getControlDescriptionByForControl(t.control.UniqueId);return n?!!n.customControls.find(i=>i.name===r):!1}isDuplicateCell(t,r){return!!this.findFirst(i=>{if(!(i instanceof Dt))return!1;let a=!0;return r==="Tab"?a=i.getParentTab()!==t.getParentTab():r==="Section"?a=i.getParentSection()!==t.getParentSection():a=i!==t,i instanceof Dt&&i.control&&t.control&&a&&i.control.dataFieldName===t.control.dataFieldName})}isCellEditableGridControl(t){return!t?.control?.indicationOfSubgrid||t.control.ClassId.guidString.toUpperCase()!==S.CustomControl?!1:this.cellHasCustomControlWithName(t,Ln.EditableGridControl)||gN.getConfig()?.enableOneGridEventsForFormDesigner&&this.cellHasCustomControlWithName(t,Ln.PowerAppsOneGrid)}isCellCanvasAppControl(t){return t?.control?.ClassId.guidString.toUpperCase()===S.CustomControl&&this.cellHasCustomControlWithName(t,Ln.CanvasAppControl)}findFormNodeById(t,r=this){return r===null?null:r.findFirst(n=>{if(n===this&&t===this.formId.ToString()||n.id?.ToString?.()===t)return!0})}findFormCellByClassId(t,r=this){return r?r.findFirst(n=>{if(n.getNodeName()===b.formCell){let i=n;return i&&i.control&&i.control.ClassId.guidString===t}return!1}):null}async getTabsJSON(t){let r=this.tabs,n=[],i=[];if(r){for(let a of r)if(!(a instanceof hi)){let o=a.toJSON(t);n.push(o)}for(let a of n)i.push(await a)}return i}async getControlDescriptionsToJSON(t){let r=[];for(let n of this.ControlDescriptions){let i=await n.toJSON(t);i&&r.push(i)}return r}async toJSON(t){let r=[];r=await this.getControlDescriptionsToJSON(t);let n=this.NavigationNode&&await this.NavigationNode.toJSON(t);return{Id:this._formId.guidString,Name:this.formName,Label:this.getDisplayName(t.langCode),ShowLabel:this.showlabel,Visible:this.visible,LabelId:this.labelId&&this.labelId.guidString,PreviewId:this._formId.guidString,PreviewSessionId:(0,iu.getSessionId)(),EntityLogicalName:this._entityName,FormId:this._formId.guidString,TabAttributes:{},Tabs:await this.getTabsJSON(t),HiddenFields:[],Header:this.header&&await this.header.toJSON(t),Footer:this.footer&&await this.footer.toJSON(t),...this.formType===ke.Main?{HeaderDensity:VV(this.headerDensityType,this.formType)}:{},InlineEditGridRow:[],InlineQuickForms:[],QuickFormEntities:[],EventHandlers:[],LinkControlSections:[],FormType:qV(this.formType),SubGrids:[],Views:void 0,Charts:void 0,CustomControlConfigurations:r,BusinessLogic:void 0,FormLibraries:[],Navigation:n,ShowNavigationBar:this.ShowNavigation||t.formModelService.showHiddenElements,ClientResources:[]}}changeTracker(){return this._changeTracker}onMetadataChange=t=>this._metadataChangeEvent.on(t);raiseMetadataChange(t){this._metadataChangeEvent.emit(t)}}});var au,vf,DN=I(()=>{"use strict";Le();Oe();X();We();$n();au=class extends it{constructor(t){super(b.formDisplayConditions,t)}get Order(){let t=this.getProperty(h.Order);return N.IsNullOrUndefined(t)?null:parseInt(t,10)}set Order(t){this.setProperty(h.Order,t.toString())}get FallbackForm(){return this.getProperty(h.FallbackForm)==="true"}set FallbackForm(t){this.setProperty(h.FallbackForm,t.toString())}addRoles(t){this.deleteAllChildren();for(let r=0;r<t.length;r++)this.addChild(t[r])}isRoleEveryone(){return!!(this.getChildren(b.formEveryOne)&&this.getChildren(b.formEveryOne)[0])}setRoleEveryone(){this.deleteAllChildren(),this.addChild(new vf(this))}},vf=class extends H{constructor(t){super(b.formEveryOne,t)}}});var ou,IN=I(()=>{"use strict";X();We();ou=class extends H{constructor(t,r){super(b.Handler,r),t.length>0&&this.setDefaultProperties(t)}setDefaultProperties(t){this.FunctionName=t[0],this.LibraryName=t[1],this.HandlerUniqueID=t[2],this.Enabled=t[3],this.Parameters=t[4],this.PassExecutionContext=t[5]}get HandlerUniqueID(){return this.getProperty(h.HandlerUniqueId)}set HandlerUniqueID(t){this.setProperty(h.HandlerUniqueId,t)}get FunctionName(){return this.getProperty(h.functionName)}set FunctionName(t){this.setProperty(h.functionName,t)}get LibraryName(){return this.getProperty(h.libraryNameEventHandler)}set LibraryName(t){this.setProperty(h.libraryNameEventHandler,t)}get Enabled(){return this.getProperty(h.enabledForField)}set Enabled(t){this.setProperty(h.enabledForField,t)}get PassExecutionContext(){return this.getProperty(h.passExecutionContext)}set PassExecutionContext(t){this.setProperty(h.passExecutionContext,t)}get Parameters(){return this.getProperty(h.parameters)}set Parameters(t){this.setProperty(h.parameters,t)}}});var Ea,yf=I(()=>{"use strict";X();es();Ea=class extends Rr{constructor(t,r){super(t,r)}get cells(){let t=this.getRows(),r=[];if(this.rows&&t.length){for(let n of this.rows)if(n.cells){let i=n.getChildren(b.formCell);for(let a of i)r.push(a)}}return r}get occupiedCells(){return this.cells.filter(t=>!t.isEmpty())}get maxColumns(){return super.getColumnCountValue()}}});var ts,_N=I(()=>{"use strict";X();yf();ts=class extends Ea{_customFooter;constructor(t,r){super(b.formFooter,t),this._customFooter=r}get customFooter(){return this._customFooter}set customFooter(t){this._customFooter=t}async getControls(t){let r=[];if(this.rows){for(let n of this.rows)if(n.cells)for(let i of n.cells)i.control&&r.push(await i.control.toJSON(t))}return r}async toJSON(t){return{AvailableForPhone:this.availableforphone,Controls:await this.getControls(t),UniqueId:this.id&&this.id.guidString,PreviewId:this.id&&this.id.guidString}}isEmpty(){return!this.cells.find(t=>!!t.control)}}});var rs,TN=I(()=>{"use strict";X();yf();rs=class extends Ea{_customHeader;constructor(t,r){super(b.formHeader,t),this._customHeader=r}get customHeader(){return this._customHeader}set customHeader(t){this._customHeader=t}get showCommandBar(){return this.getProcessedValue(h.showCommandBar)}set showCommandBar(t){t!=null&&this.setProperty(h.showCommandBar,String(t))}get showBody(){return this.getProcessedValue(h.showBody)}set showBody(t){t!=null&&this.setProperty(h.showBody,String(t))}get showTabNavigator(){return this.getProcessedValue(h.showTabNavigator)}set showTabNavigator(t){t!=null&&this.setProperty(h.showTabNavigator,String(t))}async getControls(t){let r=[];if(this.rows){for(let n of this.rows)if(n.cells)for(let i of n.cells)i.control&&r.push(await i.control.toJSON(t))}return r}async toJSON(t){return{AvailableForPhone:this.availableforphone,Controls:await this.getControls(t),UniqueId:this.id&&this.id.guidString,PreviewId:this.id&&this.id.guidString}}}});var It,gi=I(()=>{"use strict";Le();nt();X();$n();It=class e extends it{constructor(t,r){super(t,r)}getTitle(t){for(let r of this.getAllTitles())if(+r.getProperty(h.LCID)===t)return r.getProperty(h.text);return null}getAllTitles(){let t=this.getChildren(b.Titles);return t.length===0?[]:t[0].getChildren(b.Title)}setTitle(t,r){for(let i of this.getAllTitles())if(+i.getProperty(h.LCID)===r){i.setProperty(h.text,t);return}let n=new e(b.Title,null);n.setProperty(h.text,t),n.setProperty(h.LCID,String(r)),this.addGrandChild(b.Titles,n)}get Sequence(){return+this.getProperty(h.Sequence)}set Sequence(t){this.setProperty(h.Sequence,t.toString())}get Area(){return this.getProperty(h.Area)}set Area(t){this.setProperty(h.Area,t)}set Id(t){this.setProperty(h.Id,t)}get Id(){return this.getProperty(h.Id)}get id(){return new P(this.Id??"",!0)}set id(t){this.Id=t.guidString}get Show(){return!0}get Icon(){return this.getProperty(h.icon)}set Icon(t){t=t||O.EmptyString,this.setProperty(h.icon,t)}updateCommonProperties(t,r){this.Area=t.Area,this.Sequence=t.Sequence,this.setTitle(t.getDisplayName(r),r)}}});var ns,PN=I(()=>{"use strict";(function(e){e[e.NavLinkNotAvailable=-1]="NavLinkNotAvailable",e[e.NavLinkIdConflict=-2]="NavLinkIdConflict",e[e.NavBarNotAvailable=-3]="NavBarNotAvailable"})(ns||(ns={}))});var su,ON=I(()=>{"use strict";Oe();X();gi();PN();su=class extends It{constructor(t){super(b.formNavBar,t)}addChildElement(t){this.addChild(t)}getAllActiveNavBarChildren(){return this.getAllChildren().filter(n=>n.Show)}getAllInActiveActiveNavBarChildren(){return this.getAllChildren().filter(n=>!n.Show)}get AllRelationShipItems(){return this.getChildren("NavBarByRelationshipItem")}get AllNavLinkItems(){return this.getChildren("NavBarItem")}removeNavLink(t){let r=this.getNavBarLinkItemById(t);return N.IsNullOrUndefined(r)?ns.NavLinkNotAvailable:r.length===1?this.deleteChild(r[0]):ns.NavLinkIdConflict}getRelationShipItemsByArea(t){let r=this.AllRelationShipItems,n=[];for(let i of r)i.Area===t&&i.Show===!0&&n.push(i);return n}getNavBarRelationShipItemsByNavId(t){return this.AllRelationShipItems.filter(n=>n.Id===t)}getNavBarLinkItemById(t){let r=this.AllNavLinkItems.filter(n=>n.Id===t);return r.length>0?r:null}getAllActiveChildrenForGivenArea(t){let r=this.getAllChildren(),n=[];for(let i of r)i.Area===t&&i.Show&&n.push(i);return n}}});var ve,GV,RN,Iee,Sa,bf=I(()=>{"use strict";Le();X();gi();(function(e){e.Info="_NA_Info",e.Sales="_NA_SFA",e.Service="_NA_CS",e.Marketing="_NA_MA",e.InternetMarketing="_NA_IMA",e.ProcessCenter="_NA_PROC",e.Async="_NA_AO"})(ve||(ve={}));GV=new Map([[ve.Info,"Info"],[ve.Sales,"Sales"],[ve.Service,"Service"],[ve.Marketing,"Marketing"],[ve.ProcessCenter,"ProcessCenter"]]),RN=new Map([["Info",ve.Info],["Sales",ve.Sales],["Service",ve.Service],["Marketing",ve.Marketing],["ProcessCenter",ve.ProcessCenter]]),Iee=new Map([[ve.Info,9e3],[ve.Sales,9200],[ve.Service,9400],[ve.Marketing,9600],[ve.ProcessCenter,9800],[ve.InternetMarketing,1e4],[ve.Async,10200]]),Sa=class extends It{constructor(t,r){super(b.formNavBarArea,r)}setDefaultPropertiesByType(t,r,n){this.AreaId=GV.get(t);let i=n?.(`navBarArea.title.${this.AreaId}`)??this.AreaId;this.setTitle(i,r)}get ParentNavigation(){return this.getAncestor(b.formNavigation)}get AreaId(){return this.getProperty(h.Id)}set AreaId(t){this.setProperty(h.Id,t)}get id(){return new P(this.AreaId??"",!0)}set id(t){this.AreaId=t.guidString}async toJSON(t){return{Id:this.AreaId,Titles:[{LCID:t.langCode,Text:this.getTitle(t.langCode)}],PreviewId:this.AreaId}}}});var Na,wf=I(()=>{"use strict";X();gi();Na=class extends It{constructor(t,r){super(b.formNavBarAreas,r)}get AllNavBarAreaItems(){return this.getChildren(b.formNavBarArea)}get ParentNavigation(){return this.getAncestor(b.formNavigation)}addNavBarArea(t){this.addChild(t)}}});var lu,FN=I(()=>{"use strict";Oe();X();gi();lu=class extends It{RelationshipNameUCIRuntime;constructor(t){super(b.formNavBarByRelationshipItem,t)}get RelationshipName(){return this.getProperty(h.RelationshipName)}set RelationshipName(t){this.setProperty(h.RelationshipName,t)}set Show(t){this.setProperty(h.Show,String(t))}get Show(){let t=this.getProperty(h.Show);return N.IsNullOrUndefined(t)||t==="true"}get TitleResourceId(){return this.getProperty(h.TitleResourceId)}async toJSON(t){return{Area:this.Area,Show:this.Show||t.formModelService.showHiddenElements,Id:this.Id,Titles:[{Name:t.langCode.toString(),Value:this.getTitle(t.langCode)}],Sequence:this.Sequence.toString(),Privileges:[],TooltipTitles:[],AvailableOffline:!0,PreviewId:this.Id,RelationshipName:this.RelationshipNameUCIRuntime??this.RelationshipName,Icon:null,ViewId:null,Client:null,TitleResourceId:null}}}});var uu,xN=I(()=>{"use strict";X();gi();uu=class extends It{constructor(t){super(b.formNavBarItem,t)}get Url(){return this.getProperty(h.url)}set Url(t){this.setProperty(h.url,t)}}});var cu,LN=I(()=>{"use strict";Le();X();bf();wf();gi();cu=class extends It{constructor(t,r){super(t,r)}getNavBarAreaByAreaName(t){let r=this.navBarAreas.AllNavBarAreaItems.filter(n=>n.AreaId===t);return r.length===0?null:r[0]}get navBarAreas(){return this.getFirstChild(b.formNavBarAreas)}setDefaultNavBarAreas(t,r){let n=[ve.Info,ve.Sales,ve.Service,ve.Marketing,ve.ProcessCenter];if(this.navBarAreas){let i=this.navBarAreas?.AllNavBarAreaItems;if(i&&i.length>0){let a=new Set(i.map(o=>RN.get(o.AreaId)));n=n.filter(o=>!a.has(o))}}else{let i=new Na(b.formNavBarAreas,this);i.isTransient=!0,this.addChild(i)}return n.length>0?(n.forEach(i=>{let a=new Sa(b.formNavBarArea,this.navBarAreas);a.setDefaultPropertiesByType(i,t,r),this.navBarAreas.addNavBarArea(a)}),!0):!1}get navBar(){return this.getFirstChild(b.formNavBar)}get id(){return new P(Qd,!0)}replaceNavAreaToGivenIndex(t,r){this.navBarAreas?.AllNavBarAreaItems.indexOf(r)!==-1&&(this.deleteFirstGrandChildOfName(b.formNavBarAreas,r),this.addGrandChildAtIndex(b.formNavBarAreas,r,t))}async getNavBarAreasJSON(t){let r=[],n=[];if(this.navBarAreas?.AllNavBarAreaItems){for(let a of this.navBarAreas.AllNavBarAreaItems)n.push(a.toJSON(t));r=await Promise.all(n)}return r}async getNavBarRelationshipItemsJSON(t){let r=[],n=[];if(this.navBar?.AllRelationShipItems){for(let i of this.navBar.AllRelationShipItems)n.push(i.toJSON(t));r=await Promise.all(n)}return r}async toJSON(t){let r=await this.getNavBarAreasJSON(t),n=await this.getNavBarRelationshipItemsJSON(t);return{NavBarAreas:{NavBarAreas:r},NavBarByRelationshipItems:n,NavBarItems:[],NavPaneIsvItems:{NavBarIsvItems:[]},ShowEmptyNavBarAreas:t.formModelService.showHiddenElements}}}});var kN={};zr(kN,{ControlType:()=>Ht,DeserializationService:()=>Ef,DeserializationServiceScope:()=>Cf,DeserializedFormElementNode:()=>_t});var Af,_t,Cf,Ht,Ef,ff=I(()=>{"use strict";Af=ie(oi());Le();Oe();nt();Ki();Kd();ai();vy();Xy();kl();NN();Zo();Zl();Yo();lf();X();X();DN();We();cr();uf();IN();_N();cf();df();TN();mf();hf();es();ru();ON();bf();wf();FN();xN();LN();_t=class extends H{constructor(t,r){super(t,r)}insertProperty(t,r){this.addProperty(t,r)}insertChild(t){this.addChild(t)}},Cf="DeserializationService";(function(e){e.Grid="Grid",e.Lookup="Lookup",e.Base="Base"})(Ht||(Ht={}));Ef=class{lcid;constructor(t){this.lcid=t}deSerializeFormXml(t,r,n,i,a,o,s,l,u,c){if(!t)throw new Error("Formxml could not be parsed.");let d=t.getElementsByTagName("form");if(d.length!==1){let f="";throw d.length===0?f="FormXml has no form node.":f="FormXml has multiple form nodes.",(0,Af.trackErrorTrace)(ft,{eventName:Cf,eventData:{error:f}}),new Error(f)}let p=this.createFormModel(d.item(0),r,n,i,a,o,s,l,u,c);return N.IsNullOrUndefined(p.displayCondition)&&s!==ke.Dialog&&this.appendDefaultDisplayCondition(p),p}upsertFieldCount(t,r){let n=si.getNecessaryLookUpTable(r),i=1;n.containsKey(t)&&(i+=n.getValue(t)),n.upsert(t,i)}appendDefaultDisplayCondition(t){let r='<DisplayConditions Order="0" FallbackForm="true"><Everyone/></DisplayConditions>';if(!N.IsNullOrUndefined(t)){let n=N.ParseXml(r);n!==null&&this.populateElementChildren(t,n.childNodes)}}createFormModel(t,r,n,i,a,o,s,l,u,c){let d=new nu(r,n,i,a,o,s,l,u,c);return this.populateElementProperties(d,t.attributes),this.populateElementChildren(d,t.childNodes),s===ke.Main&&(this.insertHeaderFooterElementProperties(b.formHeader,d,d.header),this.insertHeaderFooterElementProperties(b.formFooter,d,d.footer)),d}insertHeaderFooterElementProperties(t,r,n){if(N.IsNullOrUndefined(n)){let i=t===b.formHeader?new rs(r,!0):new ts(r,!0);_t.prototype.insertProperty.call(i,h.id,"{"+P.NewGuid()+"}"),_t.prototype.insertProperty.call(i,h.Fieldlabelposition,"Top"),_t.prototype.insertProperty.call(i,h.columnName,we.MarginalControlColumns),_t.prototype.insertProperty.call(i,h.LabelWidth,we.LabelWidth),_t.prototype.insertProperty.call(i,h.Fieldlabelalignment,"Left");let a=null,o=new mi(a);for(let s=0;s<i.maxColumns;s++){let l=new Dt(o);_t.prototype.insertProperty.call(l,h.id,"{"+P.NewGuid()+"}"),l.setDisplayName(O.EmptyString,this.lcid),_t.prototype.insertProperty.call(l,h.showlabel,"false"),o.addCell(l)}i.appendRow(o),t===b.formHeader?r.header=i:r.footer=i}}deSerializeFormXmlNode(t,r){if(t&&t.nodeValue&&(t.nodeType===Node.TEXT_NODE||t.nodeType===Node.CDATA_SECTION_NODE))return new _t(`<${t.nodeValue}`,r);if(t.nodeType===Node.COMMENT_NODE)return;let n=this.createModelNode(t,r);return this.populateElementProperties(n,t.attributes),this.populateElementChildren(n,t.childNodes),n}populateElementProperties(t,r){if(!r){let n="attributes is undefined for element: "+t.getNodeName();throw(0,Af.trackErrorTrace)(ft,{eventName:Cf,eventData:{error:n}}),new Error(n)}for(let n=0;n<r.length;n++){let i=r.item(n);i&&(_t.prototype.insertProperty.call(t,i.name,i.value),t.getNodeName()===b.formCell&&i.name===h.auto&&i.value==="true"&&t.setAutoExpandDetailsForTab())}}populateElementChildren(t,r){for(let n=0;n<r.length;n++){let i=r.item(n),a=this.deSerializeFormXmlNode(i,t);a&&_t.prototype.insertChild.call(t,a)}}createModelNode(t,r){switch(t.nodeName){case b.form:throw new Error("Form node shouldn't be created using this method");case b.formTab:return new an(r);case b.formColumn:return new qn(r);case b.formHeader:return new rs(r,!1);case b.formFooter:return new ts(r,!1);case b.formSection:return new Rr(b.formSection,r);case b.formRow:return new mi(r);case b.formCell:return new Dt(r);case b.formControl:let n=t.attributes,i=t.childNodes.length>0?t.childNodes[0].childNodes:null,a;for(let s=0;s<n.length;s++){let l=n.item(s);if(l.name===h.indicationOfSubgrid&&l.value==="true"||l.name===h.classid&&(l.value?.toLocaleUpperCase()===`{${S.SubgridControl}}`||l.value?.toLocaleUpperCase()===`{${S.ReferencePanelSubgridControl}}`))a=Ht.Grid;else if(l.name===h.classid&&l.value?.toLocaleUpperCase()===`{${S.LookupControl}}`)a=Ht.Lookup;else if(l.name===h.classid&&l.value?.toLocaleUpperCase()===`{${S.CustomControl}}`)for(let u=0;u<i?.length;u++)i[u].nodeName===h.DefaultViewId&&(a=Ht.Lookup)}return a===Ht.Grid?new wa(r):a===Ht.Lookup?new Aa(r):new fr(r);case b.formEvent:return new ba(r,O.EmptyString);case b.dependency:return this.populateDependencyTable(t),new ya(r,O.EmptyString);case b.Handler:let o=[];return new ou(o,r);case b.formNavigation:return new cu(t.nodeName,r);case b.formNavBarArea:return new Sa(t.nodeName,r);case b.formNavBarAreas:return new Na(t.nodeName,r);case b.formNavBar:return new su(r);case b.formNavBarByRelationshipItem:return new lu(r);case b.formNavBarItem:return new uu(r);case b.formDisplayConditions:return new au(r);case b.library:return new Ca(r,O.EmptyString,O.EmptyString);case b.controlDescription:return new El(r);case b.customControl:return this.populateCustomControlConfigurationId(t),new Ll(r);default:return new _t(t.nodeName,r)}}populateDependencyTable(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);i.name===h.id&&this.upsertFieldCount(i.value,_r.DependencyFieldTable)}}populateCustomControlConfigurationId(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);if(i.name===h.id){let a=new P(i.value.substr(1,i.value.length-2));for(let o=0;o<t.parentNode.attributes.length;o++){let s=t.parentNode.attributes.item(o);if(s.name===h.ForControl){let l=s.value.substr(1,i.value.length-2);Me.CustomControlIdMap.upsert(l,a);break}}break}}}}});var MN={};zr(MN,{SerializationService:()=>Sf,SerializationServiceScope:()=>zV,SerializedFormElementNode:()=>Da});var zV,Da,Sf,UN=I(()=>{"use strict";nt();We();cr();gf();zV="SerializationService",Da=class extends H{fetchNodeName(){return this.getNodeName()}enumerateProperties(){return this.getAllProperties()}enumerateChildren(){return this.getAllChildren()}},Sf=class{langCode;constructor(t){this.langCode=t}serializeFormXmlNode(t){let r=Da.prototype.fetchNodeName.call(t);if(r.charAt(0)===rn.StartTag)return O.EscapeXml(r.substr(1),!1);if(t.isTransient&&!t.isDirty())return O.EmptyString;let n=Da.prototype.enumerateProperties.call(t),i=Da.prototype.enumerateChildren.call(t);if(!(t instanceof hi)){let a=`<${r}`;if(n.length!==0&&(a+=` ${this.getPropertiesString(n)}`),i.length===0)a+=" />";else{let o=O.EmptyString;for(let s of i)o+=this.serializeFormXmlNode(s);a+=`>${o}</${r}>`}return a}return O.EmptyString}getPropertiesString(t){let r=O.EmptyString;return t.forEach((n,i)=>{i!==0&&(r+=" "),r+=`${n.key}="${O.EscapeXml(n.value,!0)}"`}),r}}});var Fr=v(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.rejectUnknownKeys=at.childObjects=at.optionalGuidId=at.optionalEnum=at.eachObject=at.issue=at.isJsonObject=void 0;function BN(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}at.isJsonObject=BN;function Ia(e,t,r,n){return n?{pointer:e,rule:t,message:r,fatal:n}:{pointer:e,rule:t,message:r}}at.issue=Ia;function $N(e,t,r,n){if(!Array.isArray(e))return[];let i=[];return e.forEach((a,o)=>{BN(a)?i.push({node:a,index:o}):n.push(Ia(`${t}/${o}`,`${r}-must-be-object`,`a ${r} must be a JSON object, got ${a===null?"null":typeof a}`))}),i}at.eachObject=$N;function WV(e,t,r,n,i,a){let o=e[t];o!==void 0&&(typeof o!="string"||!r.includes(o))&&a.push(Ia(`${n}/${t}`,i,`${t} must be one of ${r.map(s=>`'${s}'`).join(", ")}, got ${JSON.stringify(o)}`))}at.optionalEnum=WV;var HV=/^(?:\{[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}\}|[0-9a-fA-F]{8}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{12})$/;function jV(e,t,r,n,i){let a=e[t];typeof a=="string"&&a!==""&&!HV.test(a)&&i.push(Ia(`${r}/${t}`,n,`${t} must be a GUID or empty, got '${a}'`))}at.optionalGuidId=jV;function JV(e,t,r,n,i){let a=e[t],o=`${r}/${t}`;return a===void 0?[]:Array.isArray(a)?$N(a,o,n,i):(i.push(Ia(o,`${n}-list-must-be-array`,`${t} must be an array when present, got ${typeof a}`)),[])}at.childObjects=JV;function QV(e,t,r,n,i,a={}){var o,s;for(let l of Object.keys(e)){if(t.has(l))continue;let u=(o=a.elsewhere)===null||o===void 0?void 0:o[l],c=(s=a.unsupported)===null||s===void 0?void 0:s[l],d=u?` '${l}' is a ${u} key \u2014 set it on the ${u} instead.`:c?` ${c}`:` Put values the typed layer does not model in '${n}.bag', which round-trips them verbatim.`;i.push(Ia(`${r}/${l}`,`${n}-unknown-key`,`'${l}' is not a ${n} property, and would be SILENTLY DROPPED at serialization.${d}`))}}at.rejectUnknownKeys=QV});var tD=v(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.classIdForAttributeType=Pt.QUICK_VIEW_CLASS_ID=Pt.NOTES_CLASS_ID=Pt.SUBGRID_CLASS_ID=Pt.formRegistration=Pt.FormAdapter=void 0;var on=(Le(),br(ly)),KV=(Oe(),br(uy)),XV=(We(),br(dy)),ot=(X(),br(cy)),Re=(ai(),br(py)),YV=(ff(),br(kN)),ZV=(UN(),br(MN)),Ue=In(),qN=lr(),Tt=Fr(),e5=Cd(),is=pt(),Tf=ae(),jN=Tn(),JN=Ri(),t5={[ot.FormType.Main]:"Main",[ot.FormType.QuickCreate]:"QuickCreate",[ot.FormType.QuickViewForm]:"QuickView",[ot.FormType.Card]:"Card"},Nf={Main:ot.FormType.Main,QuickCreate:ot.FormType.QuickCreate,QuickView:ot.FormType.QuickViewForm,Card:ot.FormType.Card},r5=new Map(Object.entries(Re.ControlClassId).map(([e,t])=>[String(t).toUpperCase(),e]));function QN(e){var t;return e&&(t=r5.get(e.toUpperCase()))!==null&&t!==void 0?t:"Unknown"}function as(e){return e.getAllProperties().map(t=>[t.key,t.value])}function vi(e){let t=new Map;for(let r of e.getAllProperties())t.has(r.key)||t.set(r.key,r.value);return t}function KN(e,t){return e.getAllChildren().find(r=>r.getNodeName()===t)}function Pf(e,t){var r,n;let i=KN(e,"labels");if(!i)return"";let a=i.getAllChildren().filter(s=>s.getNodeName()==="label"),o=(r=a.find(s=>vi(s).get("languagecode")===String(t)))!==null&&r!==void 0?r:a[0];return o&&(n=vi(o).get("description"))!==null&&n!==void 0?n:""}function n5(e){let t=KN(e,"parameters"),r={};if(!t)return r;for(let n of t.getAllChildren()){let i=n.getNodeName();if(i.charAt(0)==="<"||i.charAt(0)==="#")continue;let a=n.getAllChildren()[0],o=a?a.getNodeName():"";o.charAt(0)==="<"&&(o=o.substring(1)),r[i]=o}return r}function XN(e){return/^1+$/.test(e)&&e.length>=1&&e.length<=4?e.length:1}function Df(e){let t=Math.min(Math.max(Math.trunc(e),1),4);return"1".repeat(t)}function os(e){return String(e??"").replace(/[{}]/g,"")}function If(e){return`{${os(e)}}`}function VN(e,t){if(e===void 0||e==="")return t;let r=Number(e);return Number.isNaN(r)?t:r}function pu(e,t,r){let n=e.getAllChildren(),i=n.findIndex(u=>u.getNodeName()===t),a=[];if(n.forEach((u,c)=>{c!==i&&a.push({i:c,node:(0,Ue.rawFromNode)(u)})}),i<0)return{modeled:[],bag:{a:as(e),c:a}};let o=n[i],s=[],l=[];return o.getAllChildren().forEach((u,c)=>{u.getNodeName()===r?s.push(u):l.push({i:c,node:(0,Ue.rawFromNode)(u)})}),{modeled:s,bag:{a:as(e),c:a,w:{n:o.getNodeName(),a:as(o),c:l}}}}function YN(e,t,r){let n=[],i=[];return e.getAllChildren().forEach((a,o)=>{a.getNodeName()===t&&(!r||n.length===0)?n.push(a):i.push({i:o,node:(0,Ue.rawFromNode)(a)})}),{modeled:n,bag:{a:as(e),c:i}}}function i5(e,t){let{modeled:r,bag:n}=pu(e,"tabs","tab");return{tabs:r.map(i=>a5(i,t)),bag:n}}function a5(e,t){var r,n;let i=vi(e),{modeled:a,bag:o}=pu(e,"columns","column");return{id:(r=i.get("id"))!==null&&r!==void 0?r:"",name:(n=i.get("name"))!==null&&n!==void 0?n:"",label:Pf(e,t),expanded:i.get("expanded")==="true",visible:i.has("visible")?i.get("visible")==="true":!0,columns:a.map(s=>o5(s,t)),bag:o}}function o5(e,t){let r=vi(e),{modeled:n,bag:i}=pu(e,"sections","section");return{width:r.get("width"),sections:n.map(a=>s5(a,t)),bag:i}}function s5(e,t){var r,n,i;let a=vi(e),{modeled:o,bag:s}=pu(e,"rows","row");return{id:(r=a.get("id"))!==null&&r!==void 0?r:"",name:(n=a.get("name"))!==null&&n!==void 0?n:"",label:Pf(e,t),visible:a.has("visible")?a.get("visible")==="true":!0,showLabel:a.get("showlabel")==="true",columns:XN((i=a.get("columns"))!==null&&i!==void 0?i:"1"),rows:o.map(l=>l5(l,t)),bag:s}}function l5(e,t){let{modeled:r,bag:n}=YN(e,"cell",!1);return{cells:r.map(i=>u5(i,t)),bag:n}}function u5(e,t){var r;let n=vi(e),{modeled:i,bag:a}=YN(e,"control",!0),o=Pf(e,t),s=n.get("showlabel")==="true",l=i[0]?c5(i[0],o,s):null;return{id:(r=n.get("id"))!==null&&r!==void 0?r:"",visible:n.has("visible")?n.get("visible")==="true":!0,colspan:VN(n.get("colspan"),1),rowspan:VN(n.get("rowspan"),1),control:l,bag:a}}function c5(e,t,r){var n,i;let a=vi(e),o=os((n=a.get("classid"))!==null&&n!==void 0?n:""),s=a.get("datafieldname");return{id:(i=a.get("id"))!==null&&i!==void 0?i:"",classId:o,fieldName:s||null,type:QN(o),isRequired:a.get("isrequired")==="true",isReadOnly:a.get("disabled")==="true",label:t,showLabel:r,parameters:n5(e),bag:{a:as(e),c:e.getAllChildren().map((l,u)=>({i:u,node:(0,Ue.rawFromNode)(l)}))}}}function zn(e){return e.a.length===0&&e.c.length===0&&!e.w}function ZN(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function yi(e,t){var r;let n=new Set(e.a.map(o=>o[0])),i=zn(e),a=[];for(let o of t)if(n.has(o.key)){let s=(r=ZN(e,o.key))!==null&&r!==void 0?r:"";o.matches(s)||a.push([o.key,o.render()])}else i?a.push([o.key,o.render()]):o.matches(o.absentDefault)||a.push([o.key,o.render()]);return(0,Ue.mergeAttrs)(e.a,a)}var Vn=(e,t)=>({key:e,matches:r=>r===t,render:()=>t,absentDefault:""}),Gn=(e,t,r=!1)=>({key:e,matches:n=>n==="true"===t,render:()=>String(t),absentDefault:String(r)}),GN=(e,t,r=1)=>({key:e,matches:n=>Number(n)===t,render:()=>String(t),absentDefault:String(r)});function fu(e,t){return{n:"labels",a:[],c:[{n:"label",a:[["description",e],["languagecode",String(t)]],c:[]}]}}function _f(e){return{n:"parameters",a:[],c:Object.keys(e).map(t=>({n:(0,Tf.assertXmlName)(t,"Form control parameter name"),a:[],c:[{n:`<${e[t]}`,a:[],c:[]}]}))}}function d5(e,t){var r,n;let i=e.c.find(o=>o.n==="label"&&o.a.some(s=>s[0]==="languagecode"&&s[1]===String(t))),a=i??e.c.find(o=>o.n==="label");return(n=(r=a?.a.find(o=>o[0]==="description"))===null||r===void 0?void 0:r[1])!==null&&n!==void 0?n:""}function p5(e,t,r){let n=!1,i=e.c.map(a=>a.n!=="label"||!a.a.some(s=>s[0]==="languagecode"&&s[1]===String(r))?a:(n=!0,{...a,a:a.a.map(s=>s[0]==="description"?["description",t]:s)}));return n||i.push({n:"label",a:[["description",t],["languagecode",String(r)]],c:[]}),{...e,c:i}}function Of(e,t,r){let n=e.c.findIndex(a=>a.node.n==="labels");if(n<0){if(!t||zn(e))return e;let o=e.c.some(s=>s.i===0)?e.c.map(s=>({...s,i:s.i+1})):e.c;return{...e,c:[{i:0,node:fu(t,r)},...o]}}if(d5(e.c[n].node,r)===t)return e;let i=p5(e.c[n].node,t,r);return{...e,c:e.c.map((a,o)=>o===n?{...a,node:i}:a)}}function f5(e){let t={};for(let r of e.c){let n=r.n;if(n.charAt(0)==="<"||n.charAt(0)==="#")continue;let i=r.c[0],a=i?i.n:"";a.charAt(0)==="<"&&(a=a.substring(1)),t[n]=a}return t}function m5(e,t){let r=Object.keys(e),n=Object.keys(t);return r.length===n.length&&r.every(i=>e[i]===t[i])}function h5(e,t){return e.a.some(r=>r[0]===t)?{...e,a:e.a.filter(r=>r[0]!==t)}:e}function g5(e,t){let r=e.c.findIndex(i=>i.node.n==="parameters");if(r<0){if(Object.keys(t).length===0||zn(e))return e;let i=e.c.reduce((a,o)=>o.i>a?o.i:a,-1);return{...e,c:[...e.c,{i:i+1,node:_f(t)}]}}if(m5(f5(e.c[r].node),t))return e;let n=_f(t);return{...e,c:e.c.map((i,a)=>a===r?{...i,node:n}:i)}}function mu(e,t,r,n){if(e.w){let o={n:e.w.n,a:e.w.a.map(s=>[s[0],s[1]]),c:(0,Ue.spliceChildren)(e.w.c,r)};return(0,Ue.spliceChildren)(e.c,[o])}let i=n(),a={n:t,a:[],c:r};return e.c.length===0?[...i,a]:(0,Ue.spliceChildren)(e.c,[...i,a])}function v5(e,t){let r=e.tabs.map(n=>y5(n,t));return{n:"form",a:yi(e.bag,[]),c:e.tabs.length===0&&zn(e.bag)?[]:mu(e.bag,"tabs",r,()=>[])}}function y5(e,t){let r=[Vn("id",e.id),Vn("name",e.name),Gn("expanded",e.expanded),Gn("visible",e.visible,!0)],n=e.columns.map(a=>b5(a,t)),i=Of(e.bag,e.label,t);return{n:"tab",a:yi(i,r),c:mu(i,"columns",n,()=>e.label?[fu(e.label,t)]:[])}}function b5(e,t){let r=e.width!==void 0?[Vn("width",e.width)]:[],n=e.sections.map(i=>w5(i,t));return{n:"column",a:yi(e.bag,r),c:mu(e.bag,"sections",n,()=>[])}}function w5(e,t){let r=[Vn("id",e.id),Vn("name",e.name),Gn("showlabel",e.showLabel),Gn("visible",e.visible,!0),{key:"columns",matches:a=>XN(a)===e.columns,render:()=>Df(e.columns),absentDefault:Df(1)}],n=e.rows.map(a=>A5(a,t)),i=Of(e.bag,e.label,t);return{n:"section",a:yi(i,r),c:mu(i,"rows",n,()=>e.label?[fu(e.label,t)]:[])}}function A5(e,t){let r=e.cells.map(n=>C5(n,t));return{n:"row",a:yi(e.bag,[]),c:zn(e.bag)?r:(0,Ue.assembleChildren)(e.bag,r)}}function C5(e,t){let r=e.control?e.control.showLabel:ZN(e.bag,"showlabel")==="true",n=[Vn("id",e.id),Gn("showlabel",r),Gn("visible",e.visible,!0),GN("colspan",e.colspan),GN("rowspan",e.rowspan)],i=e.control?[E5(e.control)]:[],a;if(zn(e.bag))a=[...e.control&&e.control.label?[fu(e.control.label,t)]:[],...i];else{let o=e.control?Of(e.bag,e.control.label,t):e.bag;a=(0,Ue.assembleChildren)(o,i)}return{n:"cell",a:yi(e.bag,n),c:a}}function E5(e){let t=[Vn("id",e.id),{key:"classid",matches:i=>os(i)===e.classId,render:()=>If(e.classId),absentDefault:""}];e.fieldName!==null&&t.push(Vn("datafieldname",e.fieldName)),t.push(Gn("disabled",e.isReadOnly)),t.push(Gn("isrequired",e.isRequired));let r=e.fieldName===null?h5(e.bag,"datafieldname"):e.bag,n;return zn(r)?n=Object.keys(e.parameters).length>0?[_f(e.parameters)]:[]:n=(0,Ue.assembleChildren)(g5(r,e.parameters),[]),{n:"control",a:yi(r,t),c:n}}var S5={make:(e,t)=>new XV.FormElementNode(e,t),setProp:(e,t,r)=>e.setProperty(t,r),addChild:(e,t)=>e.addChild(t)};function zN(e,t,r){(0,jN.installDomShim)();let n=D5(e,r),i=(0,Ue.rebuildRaw)(v5(n,t),S5,null);return new ZV.SerializationService(t).serializeFormXmlNode(i)}function N5(e){return JSON.parse(JSON.stringify(e))}function D5(e,t){var r;let n=N5(e);n.bag||(n.bag=(0,Ue.emptyBag)()),x5(n.bag),t&&I5(n,t);for(let i of(r=n.tabs)!==null&&r!==void 0?r:[])_5(i);return n}function I5(e,t){var r;let n=(r=e.entityLogicalName)!==null&&r!==void 0?r:"";Rf(e,i=>{let a=i.fieldName,o=i;if(!a||o.label!==void 0&&o.classId!==void 0)return;let s=t.resolveField(n,a);s&&(o.label===void 0&&s.displayName&&(o.label=s.displayName),o.classId===void 0&&s.attributeType&&(o.classId=eD(s.attributeType)))})}function WN(e){let t=[];return Rf(e,r=>t.push(r)),t}function Rf(e,t){var r,n,i,a,o;for(let s of(r=e.tabs)!==null&&r!==void 0?r:[])for(let l of(n=s.columns)!==null&&n!==void 0?n:[])for(let u of(i=l.sections)!==null&&i!==void 0?i:[])for(let c of(a=u.rows)!==null&&a!==void 0?a:[])for(let d of(o=c.cells)!==null&&o!==void 0?o:[])d.control&&t(d.control)}function _5(e){e.id||(e.id=on.Guid.NewGuid()),e.name===void 0&&(e.name=""),e.label===void 0&&(e.label=""),e.expanded===void 0&&(e.expanded=!0),e.visible===void 0&&(e.visible=!0),e.columns||(e.columns=[]);for(let t of e.columns)T5(t);e.bag||(e.bag=(0,Ue.emptyBag)())}function T5(e){e.sections||(e.sections=[]);for(let t of e.sections)P5(t);e.bag||(e.bag=(0,Ue.emptyBag)()),e.width===void 0&&zn(e.bag)&&(e.width="100%")}function P5(e){e.id||(e.id=on.Guid.NewGuid()),e.name===void 0&&(e.name=""),e.label===void 0&&(e.label=""),e.showLabel===void 0&&(e.showLabel=!1),e.visible===void 0&&(e.visible=!0),e.columns===void 0&&(e.columns=1),e.rows||(e.rows=[]);for(let t of e.rows)O5(t);e.bag||(e.bag=(0,Ue.emptyBag)())}function O5(e){e.cells||(e.cells=[]);for(let t of e.cells)R5(t);e.bag||(e.bag=(0,Ue.emptyBag)())}function R5(e){e.id||(e.id=on.Guid.NewGuid()),e.visible===void 0&&(e.visible=!0),e.colspan===void 0&&(e.colspan=1),e.rowspan===void 0&&(e.rowspan=1),e.control===void 0&&(e.control=null),e.control&&F5(e.control),e.bag||(e.bag=(0,Ue.emptyBag)())}function F5(e){var t;e.id||(e.id=on.Guid.NewGuid()),e.classId===void 0&&(e.classId=String(Re.ControlClassId.TextboxControl)),e.fieldName===void 0&&(e.fieldName=null),e.type===void 0&&(e.type=e.fieldName?"Field":QN(String(e.classId))),e.isRequired===void 0&&(e.isRequired=!1),e.isReadOnly===void 0&&(e.isReadOnly=!1),e.label===void 0&&(e.label=(t=e.fieldName)!==null&&t!==void 0?t:""),e.showLabel===void 0&&(e.showLabel=!0),(e.parameters===void 0||e.parameters===null)&&(e.parameters={});for(let r of Object.keys(e.parameters))(0,Tf.assertXmlName)(r,"Form control parameter name");e.bag||(e.bag=(0,Ue.emptyBag)())}function x5(e){for(let t of e.c){let r=t.node;if(r.n==="events"){for(let n of r.c)if(n.n==="event"){for(let i of n.c)if(i.n==="Handlers")for(let a of i.c)a.n==="Handler"&&!HN(a,"handlerUniqueId")&&a.a.push(["handlerUniqueId",If(on.Guid.NewGuid())])}}else if(r.n==="formLibraries")for(let n of r.c)n.n==="Library"&&!HN(n,"libraryUniqueId")&&n.a.push(["libraryUniqueId",If(on.Guid.NewGuid())])}}var du=class{constructor(t=JN.DEFAULT_LCID){this.lcid=t}toArtifact(t,r){var n,i,a;let{tabs:o,bag:s}=i5(t,this.lcid);return{id:t.formId?t.formId.guidString:"",name:(n=t.formName)!==null&&n!==void 0?n:"",entityLogicalName:(i=t.entityName)!==null&&i!==void 0?i:"",formType:(a=t5[t.formType])!==null&&a!==void 0?a:"Main",status:this.readActivationStatus(t),...r!==void 0&&r!==""?{description:r}:{},tabs:o,bag:s}}fromArtifact(t){var r;return this.deserialize({formxml:zN(t,this.lcid),formid:t.id||(0,is.newId)(),objecttypecode:t.entityLogicalName,type:Nf[t.formType],name:t.name,uniquename:t.name,description:(r=t.description)!==null&&r!==void 0?r:"",formpresentation:ot.FormPresentation.AirForm,formactivationstate:t.status==="Active"?ot.FormActivationState.Active:ot.FormActivationState.InActive})}fromApiResponse(t){var r,n,i,a,o,s,l;let u=t,c=this.deserialize({formxml:(r=u.formxml)!==null&&r!==void 0?r:"",formid:(n=u.formid)!==null&&n!==void 0?n:(0,is.newId)(),objecttypecode:(i=u.objecttypecode)!==null&&i!==void 0?i:"",type:u.type,name:(a=u.name)!==null&&a!==void 0?a:"",uniquename:(o=u.uniquename)!==null&&o!==void 0?o:"",description:(s=u.description)!==null&&s!==void 0?s:"",formpresentation:u.formpresentation,formactivationstate:u.formactivationstate});return this.toArtifact(c,(l=u.description)!==null&&l!==void 0?l:void 0)}toApiPayload(t,r,n){return{formxml:zN(t,this.lcid,n),name:t.name,type:Nf[t.formType],objecttypecode:t.entityLogicalName,...t.description!==void 0?{description:t.description}:{}}}metadataNeeds(t){let r=t.entityLogicalName;if(!r)return[];let n=new Set,i=[];return Rf(t,a=>{let o=a.fieldName,s=a;!o||s.label!==void 0&&s.classId!==void 0||n.has(o)||(n.add(o),i.push({entityLogicalName:r,fieldName:o}))}),i}createDefault(t){var r,n,i,a,o,s,l,u,c,d,p;let f=t.tabs&&t.tabs.length>0?void 0:G5(this.lcid),m=f!==void 0?f:t.tabs.map(A=>L5(A,this.lcid)).join(""),g=this.deserialize({formxml:`<form><tabs>${m}</tabs></form>`,formid:t.id||(0,is.newId)(),objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",type:Nf[(n=t.formType)!==null&&n!==void 0?n:"Main"],name:(i=t.name)!==null&&i!==void 0?i:"New Form",uniquename:(a=t.name)!==null&&a!==void 0?a:"New Form",description:(o=t.description)!==null&&o!==void 0?o:"",formpresentation:ot.FormPresentation.AirForm,formactivationstate:((s=t.status)!==null&&s!==void 0?s:"Active")==="Active"?ot.FormActivationState.Active:ot.FormActivationState.InActive}),y=this.toArtifact(g,t.description);if(t.tabs&&t.tabs.length>0){let A=WN(t);WN(y).forEach((D,F)=>{A[F]&&A[F].label===void 0&&delete D.label})}return{id:(l=t.id)!==null&&l!==void 0?l:y.id,name:(u=t.name)!==null&&u!==void 0?u:"New Form",entityLogicalName:(c=t.entityLogicalName)!==null&&c!==void 0?c:"",formType:(d=t.formType)!==null&&d!==void 0?d:"Main",status:(p=t.status)!==null&&p!==void 0?p:"Active",...t.description!==void 0?{description:t.description}:{},tabs:y.tabs,bag:y.bag}}assignMissingIds(t){return(0,is.assignMissingIds)(t)}validate(t){return Y5(t)}deserialize(t){(0,jN.installDomShim)();let r=KV.ScriptUtilities.ParseXml(t.formxml),n=new YV.DeserializationService(this.lcid).deSerializeFormXml(r,new on.Guid(t.formid),t.objecttypecode,ot.FormState.Draft,t.name,t.uniquename,t.type,t.formpresentation,t.description,t.formactivationstate);if(!n)throw new Error("FormXml could not be deserialized into a Form model.");return n}readActivationStatus(t){return t.formactivationstate===ot.FormActivationState.InActive?"Inactive":"Active"}};Pt.FormAdapter=du;function mr(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Ff(e,t){return e?`<labels><label description="${mr(e)}" languagecode="${t}" /></labels>`:""}function xf(e){return e&&e.length>0?os(e):(0,is.newId)()}function L5(e,t){var r,n,i,a;let o=(r=e.columns)!==null&&r!==void 0?r:[],s=(o.length>0?o:[V5()]).map(l=>k5(l,t)).join("");return`<tab id="{${mr(xf(e.id))}}" name="${mr((n=e.name)!==null&&n!==void 0?n:"")}" expanded="${(i=e.expanded)!==null&&i!==void 0?i:!0}" visible="${(a=e.visible)!==null&&a!==void 0?a:!0}">${Ff(e.label,t)}<columns>${s}</columns></tab>`}function k5(e,t){var r,n;let i=((r=e.sections)!==null&&r!==void 0?r:[]).map(a=>M5(a,t)).join("");return`<column width="${mr((n=e.width)!==null&&n!==void 0?n:"100%")}"><sections>${i}</sections></column>`}function M5(e,t){var r,n,i,a,o;let s=((r=e.rows)!==null&&r!==void 0?r:[]).map(l=>U5(l,t)).join("");return`<section id="{${mr(xf(e.id))}}" name="${mr((n=e.name)!==null&&n!==void 0?n:"")}" showlabel="${(i=e.showLabel)!==null&&i!==void 0?i:!1}" visible="${(a=e.visible)!==null&&a!==void 0?a:!0}" columns="${Df((o=e.columns)!==null&&o!==void 0?o:1)}">${Ff(e.label,t)}<rows>${s}</rows></section>`}function U5(e,t){var r;return`<row>${((r=e.cells)!==null&&r!==void 0?r:[]).map(n=>B5(n,t)).join("")}</row>`}function B5(e,t){var r,n,i,a,o;let s=e.control,l=s?Ff((r=s.label)!==null&&r!==void 0?r:"",t):"",u=s?$5(s):"";return`<cell id="{${mr(xf(e.id))}}" showlabel="${s?(n=s.showLabel)!==null&&n!==void 0?n:!0:!1}" visible="${(i=e.visible)!==null&&i!==void 0?i:!0}" colspan="${(a=e.colspan)!==null&&a!==void 0?a:1}" rowspan="${(o=e.rowspan)!==null&&o!==void 0?o:1}">${l}${u}</cell>`}function $5(e){var t,r,n;let i=e.fieldName?` datafieldname="${mr(e.fieldName)}"`:"",a=q5(e.parameters),o=e.classId?os(e.classId):String(Re.ControlClassId.TextboxControl);return`<control id="${mr((t=e.id)!==null&&t!==void 0?t:"")}" classid="{${mr(o)}}"${i} disabled="${(r=e.isReadOnly)!==null&&r!==void 0?r:!1}" isrequired="${(n=e.isRequired)!==null&&n!==void 0?n:!1}">${a}</control>`}function q5(e){let t=Object.keys(e??{});return t.length===0?"":(t.forEach(n=>(0,Tf.assertXmlName)(n,"Form control parameter name")),`<parameters>${t.map(n=>`<${n}>${mr(e[n])}</${n}>`).join("")}</parameters>`)}function V5(){return{width:"100%",sections:[],bag:{a:[],c:[]}}}function G5(e){return`<tab id="{${on.Guid.NewGuid()}}" name="tab_general" expanded="true" visible="true"><labels><label description="General" languagecode="${e}" /></labels><columns><column width="100%"><sections><section id="{${on.Guid.NewGuid()}}" name="section_general" showlabel="false" visible="true" columns="1"><labels><label description="General" languagecode="${e}" /></labels><rows></rows></section></sections></column></columns></tab>`}function z5(e=JN.DEFAULT_LCID){return{adapter:new du(e),api:e5.formApi,languageSensitive:!0,publish:(t,r,n)=>(0,qN.publishBoundEntity)(t,n),publishScope:(t,r)=>(0,qN.boundEntityPublishScope)(r)}}Pt.formRegistration=z5;var W5=new Set(["id","name","label","expanded","visible","columns","bag"]),H5=new Set(["id","width","sections","bag"]),j5=new Set(["id","name","label","visible","showLabel","columns","rows","bag"]),J5=new Set(["id","cells","bag"]),Q5=new Set(["id","visible","colspan","rowspan","control","bag"]),K5=new Set(["id","classId","fieldName","type","isRequired","isReadOnly","label","showLabel","parameters","bag"]),X5={elsewhere:{isReadOnly:"control",isRequired:"control",fieldName:"control",classId:"control",label:"control",showLabel:"control",parameters:"control"},unsupported:{createOnly:"FormXml has no create-only concept; gate the field with a business rule instead. Raise it with the SDK owners if you need it modeled.",updateOnly:"FormXml has no update-only concept; gate the field with a business rule instead. Raise it with the SDK owners if you need it modeled."}};function Y5(e){let t=[];return(0,Tt.childObjects)(e,"tabs","","tab",t).forEach(({node:n,index:i})=>{let a=`/tabs/${i}`;(0,Tt.rejectUnknownKeys)(n,W5,a,"tab",t),(0,Tt.childObjects)(n,"columns",a,"column",t).forEach(({node:s,index:l})=>{let u=`${a}/columns/${l}`;(0,Tt.rejectUnknownKeys)(s,H5,u,"column",t),(0,Tt.childObjects)(s,"sections",u,"section",t).forEach(({node:d,index:p})=>{let f=`${u}/sections/${p}`;(0,Tt.rejectUnknownKeys)(d,j5,f,"section",t),(0,Tt.childObjects)(d,"rows",f,"row",t).forEach(({node:g,index:y})=>{let A=`${f}/rows/${y}`;(0,Tt.rejectUnknownKeys)(g,J5,A,"row",t),(0,Tt.childObjects)(g,"cells",A,"cell",t).forEach(({node:F,index:_})=>{let q=`${A}/cells/${_}`;(0,Tt.rejectUnknownKeys)(F,Q5,q,"cell",t,X5);let B=F.control;B!=null&&!(0,Tt.isJsonObject)(B)?t.push((0,Tt.issue)(`${q}/control`,"control-must-be-object-or-null",`a cell control must be a JSON object or null, got ${typeof B}`)):(0,Tt.isJsonObject)(B)&&(0,Tt.rejectUnknownKeys)(B,K5,`${q}/control`,"control",t)})})})})}),t}Pt.SUBGRID_CLASS_ID=Re.ControlClassId.SubgridControl;Pt.NOTES_CLASS_ID=Re.ControlClassId.TimelineControl;Pt.QUICK_VIEW_CLASS_ID=Re.ControlClassId.QuickViewControl;var Z5={Lookup:String(Re.ControlClassId.LookupControl),Customer:String(Re.ControlClassId.LookupControl),Owner:String(Re.ControlClassId.LookupControl),PartyList:String(Re.ControlClassId.PartyListControl),Boolean:String(Re.ControlClassId.BooleanControl),DateTime:String(Re.ControlClassId.DateTimeControl),Decimal:String(Re.ControlClassId.DecimalControl),Double:String(Re.ControlClassId.FloatingNumberControl),Money:String(Re.ControlClassId.CurrencyControl),Integer:String(Re.ControlClassId.IntegerControl),BigInt:String(Re.ControlClassId.IntegerControl),Memo:String(Re.ControlClassId.TextAreaControl),String:String(Re.ControlClassId.TextboxControl)},e9="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE";function eD(e){return e==="Picklist"||e==="State"||e==="Status"?e9:e&&Z5[e]||String(Re.ControlClassId.TextboxControl)}Pt.classIdForAttributeType=eD;function HN(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}});var Lf=v(_a=>{"use strict";Object.defineProperty(_a,"__esModule",{value:!0});_a.viewApi=_a.findDefaultViews=void 0;var nD=qt(),jt=be(),sn=ae(),t9="savedqueryid,name,description,fetchxml,layoutxml,querytype,returnedtypecode,isdefault",r9="savedqueryid,name,returnedtypecode,querytype,isdefault";async function n9(e,t,r={}){var n;let i=new Set(((n=r.excludeViewIds)!==null&&n!==void 0?n:[]).filter(Boolean)),a=`returnedtypecode eq '${(0,sn.odataLiteral)(t)}' and querytype eq 0`,o=`/savedqueries${(0,sn.odataQuery)([["$select","savedqueryid,name,isdefault"],["$filter",a]])}`;return(await(0,nD.collectPages)(e,o,`findDefaultViews('${t}')`)).filter(l=>{var u;return l.savedqueryid&&!i.has(l.savedqueryid)&&(l.isdefault||/^(Active|Inactive)\b/i.test((u=l.name)!==null&&u!==void 0?u:""))}).map(l=>{var u;return{id:String(l.savedqueryid),name:String((u=l.name)!==null&&u!==void 0?u:"")}})}_a.findDefaultViews=n9;async function i9(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,sn.odataPathLiteral)(t)}')${(0,sn.odataQuery)([["$select","ObjectTypeCode"]])}`,i=await e.get(n);if(i.status>=200&&i.status<300){let a=(r=i.body)===null||r===void 0?void 0:r.ObjectTypeCode;return typeof a=="number"?a:void 0}}async function rD(e,t,r){if(!r||!/<grid\b/.test(t)||/<grid[^>]*\bobject=/.test(t))return t;let n=await i9(e,r);return n===void 0?t:t.replace(/<grid\b/,`<grid object="${n}"`)}_a.viewApi={async get(e,t){let n=`/savedqueries(${(0,sn.normalizeGuid)(t,"id")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,sn.odataQuery)([["$select",t9]]),i=(0,jt.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,jt.readEtag)(i)}},async list(e,t){let r=`/savedqueries${(0,sn.odataQuery)([["$select",r9],["$filter",t?.entityLogicalName?`returnedtypecode eq '${(0,sn.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,nD.collectPages)(e,r,"listArtifacts('view')")).map(i=>{var a,o;return{type:"view",id:(a=i.savedqueryid)!==null&&a!==void 0?a:"",name:(o=i.name)!==null&&o!==void 0?o:"",entityLogicalName:i.returnedtypecode,isDirty:!1}})},async create(e,t,r){let n=t,i=(0,jt.echoWrite)("savedqueryid"),a=`/savedqueries${i.query}`,o=await rD(e,n.layoutxml,n.returnedtypecode),s=(0,jt.ensureSuccess)(await e.post(a,(0,jt.withClientMintedId)({name:n.name,description:n.description,fetchxml:n.fetchxml,layoutxml:o,returnedtypecode:n.returnedtypecode,querytype:n.querytype,isdefault:n.isdefault},"savedqueryid",r),i.options),e.apiUrl(a));return{id:(0,jt.resolveCreatedId)(s,"savedqueryid","view",r),etag:(0,jt.readEtag)(s)}},async update(e,t,r,n){let i=r,a=(0,sn.normalizeGuid)(t,"id"),o=(0,jt.echoWrite)("savedqueryid",{"If-Match":(0,jt.requireEtag)(n,"view",a)}),s=`/savedqueries(${a})${o.query}`,l=await rD(e,i.layoutxml,i.returnedtypecode),u=(0,jt.ensureSuccess)(await e.patch(s,{name:i.name,description:i.description,fetchxml:i.fetchxml,layoutxml:l},o.options),e.apiUrl(s));return{id:a,etag:(0,jt.readEtag)(u)}},delete(e,t){return(0,jt.deleteRecord)(e,"savedqueries",t)}}});var yD=v(Ta=>{"use strict";Object.defineProperty(Ta,"__esModule",{value:!0});Ta.viewRegistration=Ta.ViewAdapter=void 0;var cD=te(),kt=Fr(),kf=In(),bi=ri(),iD=lr(),a9=Lf(),Mf=Tn(),o9=pt(),dD=100,gu=class{toArtifact(t){var r,n,i,a,o,s,l,u;(0,Mf.installDomShim)();let c=(r=t.fetchxml)!==null&&r!==void 0?r:"",d=(n=t.layoutxml)!==null&&n!==void 0?n:"",p=(0,bi.parseXmlRoot)(c,"<fetch/>"),f=(0,bi.parseXmlRoot)(d,"<grid/>"),m=fD(p);return{id:(i=t.savedqueryid)!==null&&i!==void 0?i:"",name:(a=t.name)!==null&&a!==void 0?a:"",description:(o=t.description)!==null&&o!==void 0?o:"",entityLogicalName:(s=t.returnedtypecode)!==null&&s!==void 0?s:l9(p),queryType:(l=t.querytype)!==null&&l!==void 0?l:0,isDefault:(u=t.isdefault)!==null&&u!==void 0?u:!1,columns:pD(f,p),filters:hD(p),sort:mD(p),...m.length>0?{linkEntities:m}:{},fetchBag:c?(0,bi.projectElementBag)(p):void 0,layoutBag:d?(0,bi.projectElementBag)(f):void 0}}fromArtifact(t){(0,Mf.installDomShim)();let{fetchxml:r,layoutxml:n}=aD(t);return{savedqueryid:t.id,name:t.name,description:t.description,returnedtypecode:t.entityLogicalName,querytype:t.queryType,isdefault:t.isDefault,fetchxml:r,layoutxml:n}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t){var r,n,i,a,o;(0,Mf.installDomShim)();let{fetchxml:s,layoutxml:l}=aD(t);return{name:(r=t.name)!==null&&r!==void 0?r:"",description:(n=t.description)!==null&&n!==void 0?n:"",fetchxml:s,layoutxml:l,returnedtypecode:(i=t.entityLogicalName)!==null&&i!==void 0?i:"",querytype:(a=t.queryType)!==null&&a!==void 0?a:0,isdefault:(o=t.isDefault)!==null&&o!==void 0?o:!1}}createDefault(t){var r,n,i,a,o,s,l,u;let c=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,o9.newId)(),name:(i=t.name)!==null&&i!==void 0?i:"New View",description:(a=t.description)!==null&&a!==void 0?a:"",entityLogicalName:c,queryType:(o=t.queryType)!==null&&o!==void 0?o:0,isDefault:(s=t.isDefault)!==null&&s!==void 0?s:!1,columns:t.columns&&t.columns.length>0?t.columns:[{name:`${c}id`,width:300,order:0}],filters:(l=t.filters)!==null&&l!==void 0?l:{type:"and",conditions:[],groups:[]},sort:(u=t.sort)!==null&&u!==void 0?u:[],...t.linkEntities&&t.linkEntities.length>0?{linkEntities:t.linkEntities}:{}}}assignMissingIds(t){return t}validate(t){let r=[],n=t;(0,kt.childObjects)(n,"columns","","column",r),(0,kt.childObjects)(n,"sort","","sort",r),(0,kt.childObjects)(n,"linkEntities","","linkEntity",r),s9(n.linkEntities,r);let i=n.filters;return i!=null&&((0,kt.isJsonObject)(i)?Uf(i,"/filters",r):r.push((0,kt.issue)("/filters","filters-must-be-object",`filters must be a JSON object, got ${typeof i}`))),r}};Ta.ViewAdapter=gu;function s9(e,t){Array.isArray(e)&&e.forEach((r,n)=>{if(!(0,kt.isJsonObject)(r))return;for(let a of["name","from","to"]){let o=r[a];(typeof o!="string"||o.trim()==="")&&t.push((0,kt.issue)(`/linkEntities/${n}/${a}`,"linkentity-needs-keys",`a join needs a non-empty '${a}' \u2014 'from'/'to' are what DEFINE the relationship, and a link without them is unresolvable. Got ${JSON.stringify(o)}.`))}let i=r.filters;i!=null&&((0,kt.isJsonObject)(i)?Uf(i,`/linkEntities/${n}/filters`,t):t.push((0,kt.issue)(`/linkEntities/${n}/filters`,"filters-must-be-object",`filters must be a JSON object, got ${typeof i}`)))})}function Uf(e,t,r){(0,kt.childObjects)(e,"conditions",t,"condition",r),(0,kt.childObjects)(e,"groups",t,"filterGroup",r).forEach(({node:i,index:a})=>Uf(i,`${t}/groups/${a}`,r))}function l9(e){var t;let r=e.getElementsByTagName("entity")[0];return(t=r?.getAttribute("name"))!==null&&t!==void 0?t:""}function pD(e,t){var r;let n=Bf(t),i=e.getElementsByTagName("cell"),a=[],o=0;for(let s=0;s<i.length;s+=1){let l=i[s];if(l.getAttribute("ishidden")==="1")continue;let u=l.getAttribute("name");if(!u)continue;let c=parseInt((r=l.getAttribute("width"))!==null&&r!==void 0?r:"",10),d={name:u,width:Number.isNaN(c)?dD:c,order:o},p=n.get(u);p&&(d.relatedEntity=p.linkKey,p.attributeName&&p.attributeName!==u&&(d.sourceAttribute=p.attributeName)),o+=1,a.push(d)}return a}function Bf(e){let t=new Map,r=e.getElementsByTagName("link-entity");for(let n=0;n<r.length;n+=1){let i=r[n],a=i.getAttribute("name");if(!a)continue;let o=i.getElementsByTagName("attribute");for(let s=0;s<o.length;s+=1){let l=o[s],u=l.getAttribute("name")||"",c=l.getAttribute("alias")||u;c&&t.set(c,{linkKey:i.getAttribute("alias")||a,linkName:a,attributeName:u,link:i})}}return t}function fD(e){let t=e.getElementsByTagName("entity")[0];if(!t)return[];let r=[];for(let n of st(t,"link-entity")){let i=n.getAttribute("name"),a=n.getAttribute("from"),o=n.getAttribute("to");if(!i||!a||!o)continue;let s=n.getAttribute("alias"),l=n.getAttribute("link-type"),u=st(n,"filter").find(c=>!vu(c));r.push({name:i,from:a,to:o,...s?{alias:s}:{},...l==="inner"||l==="outer"?{linkType:l}:{},...u?{filters:$f(u)}:{}})}return r}function mD(e){var t;let r=e.getElementsByTagName("entity")[0];if(!r)return[];let n=[],i=r.childNodes;for(let a=0;a<i.length;a+=1){let o=i[a];if(o.nodeType===1&&o.tagName==="order"){let s=o.getAttribute("attribute");s&&n.push({attribute:s,descending:((t=o.getAttribute("descending"))!==null&&t!==void 0?t:"").toLowerCase()==="true",entityname:o.getAttribute("entityname")||""})}}return n}function hD(e){let t=e.getElementsByTagName("entity")[0],r={type:"and",conditions:[],groups:[]};if(!t)return r;let n=st(t,"filter").filter(i=>!vu(i)).map($f);return n.length===0?r:n.length===1?n[0]:{type:"and",conditions:[],groups:n}}function vu(e){if(e.getAttribute("isquickfindfields")==="1")return!0;if(st(e,"filter").length>0)return!1;let t=st(e,"condition");return t.length===0?!1:t.some(r=>r.getAttribute("isquickfindfields")==="1"||st(r,"value").length>0||c9(r))}var u9=new Set(["attribute","operator","value","entityname","uiname","uitype"]);function c9(e){var t;let r=e.attributes;for(let n=0;n<r.length;n+=1){let i=(t=r[n])===null||t===void 0?void 0:t.name;if(i&&!u9.has(i))return!0}return!1}function $f(e){var t,r;let n=((t=e.getAttribute("type"))!==null&&t!==void 0?t:"and").toLowerCase()==="or"?"or":"and",i=[],a=[],o=e.childNodes;for(let s=0;s<o.length;s+=1){let l=o[s];if(l.nodeType===1)if(l.tagName==="condition"){if(l.getAttribute("isquickfindfields")==="1")continue;let u=l.getAttribute("attribute");if(!u)continue;let c={attribute:u,operator:(r=l.getAttribute("operator"))!==null&&r!==void 0?r:""},d=l.getAttribute("value");d!==null&&(c.value=d);let p=l.getAttribute("entityname")||"";p&&(c.entityname=p),i.push(c)}else l.tagName==="filter"&&a.push($f(l))}return{type:n,conditions:i,groups:a}}function st(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let a=n[i];a.nodeType===1&&a.tagName===t&&r.push(a)}return r}var qf=e=>{var t,r;return`${(t=e.relatedEntity)!==null&&t!==void 0?t:""}::${(r=e.sourceAttribute)!==null&&r!==void 0?r:e.name}`};function d9(e,t){let r=Bf(e),n=new Map;for(let i of t){if(!i.relatedEntity)continue;let a=r.get(i.name);if(a){let o=qf(i),s=n.get(o);s?s.push(a.link):n.set(o,[a.link])}}return n}function p9(e,t,r,n){if(!n||n.size===0)return;let i=new Set,a=t.getElementsByTagName("link-entity");for(let s=0;s<a.length;s+=1)i.add(a[s]);let o=r.filter(s=>{if(!s.relatedEntity)return!1;let l=n.get(qf(s));return!!l&&l.some(u=>!i.has(u))});if(o.length!==0)throw new cD.ValidationError("view",e.id,o.map(s=>(0,kt.issue)(`/columns/${r.indexOf(s)}`,"view-column-orphaned-by-join-removal",`column '${s.name}' came from a join this push REMOVED. Another join matching '${s.relatedEntity}' still exists, but nothing can say whether it is the one the column belonged to \u2014 re-attaching it there would silently change the data the column shows. Remove the column too, keep the join it came from, or point the column at the join you want by setting relatedEntity to that join's alias.`)))}function aD(e){let t=f9(e.columns);if(!oD(e.fetchBag)||!oD(e.layoutBag))return{fetchxml:N9({...e,columns:t}),layoutxml:D9({...e,columns:t},`${e.entityLogicalName}id`)};let r=new DOMParser().parseFromString("<root/>","text/xml"),n=sD(e.fetchBag,"fetch",r),i=sD(e.layoutBag,"grid",r),a=pD(i,n),o=!hu(t,a),s=!hu(e.sort,mD(n)),l=!hu(e.filters,hD(n)),u=e.linkEntities,c=u!==void 0&&!hu(u,fD(n)),d=c?d9(n,a):void 0;return c&&C9(r,n,u),c&&(S9(e,n,t,d),p9(e,n,t,d)),o?(lD(r,n,t,a),v9(r,i,t)):c&&lD(r,n,t,a),s&&w9(r,n,e.sort),l&&A9(r,n,e.filters),{fetchxml:(0,bi.serializeNode)(n),layoutxml:(0,bi.serializeNode)(i)}}function f9(e){return(e??[]).map((t,r)=>{var n,i;return{name:String(t.name).toLowerCase(),width:(n=t.width)!==null&&n!==void 0?n:dD,order:(i=t.order)!==null&&i!==void 0?i:r,...t.relatedEntity?{relatedEntity:t.relatedEntity}:{},...t.sourceAttribute?{sourceAttribute:String(t.sourceAttribute).toLowerCase()}:{}}})}function oD(e){return!!e&&(e.c.length>0||e.a.length>0)}function sD(e,t,r){let n={n:t,a:(0,kf.mergeAttrs)(e.a,[]),c:(0,kf.spliceChildren)(e.c,[])};return(0,kf.rebuildRaw)(n,(0,bi.domEngine)(r),null)}function lD(e,t,r,n){var i,a;let o=t.getElementsByTagName("entity")[0];if(!o)return;let s=d=>{var p,f;return`${(p=d.relatedEntity)!==null&&p!==void 0?p:""}:${d.name}:${(f=d.sourceAttribute)!==null&&f!==void 0?f:d.name}`},l=new Set(r.map(s));for(let d of n)l.has(s(d))||m9(o,d);let u=Bf(t),c=new Set(st(o,"attribute").map(d=>d.getAttribute("name")).filter(d=>!!d));for(let d of[...r].sort((p,f)=>p.order-f.order))if(d.relatedEntity){let p=u.get(d.name);if(p&&p.attributeName===((i=d.sourceAttribute)!==null&&i!==void 0?i:d.name)&&(p.linkKey===d.relatedEntity||p.linkName===d.relatedEntity||!vD(o,d.relatedEntity)))continue;let f=h9(e,o,d.relatedEntity),m=e.createElement("attribute");gD(m,d),f.appendChild(m),u.set(d.name,{linkKey:d.relatedEntity,linkName:f.getAttribute("name")||d.relatedEntity,attributeName:(a=d.sourceAttribute)!==null&&a!==void 0?a:d.name,link:f})}else{if(c.has(d.name))continue;let p=e.createElement("attribute");p.setAttribute("name",d.name),g9(o,p),c.add(d.name)}}function gD(e,t){if(t.sourceAttribute&&t.sourceAttribute!==t.name){e.setAttribute("name",t.sourceAttribute),e.setAttribute("alias",t.name);return}e.setAttribute("name",t.name)}function m9(e,t){if(t.relatedEntity){for(let r of st(e,"link-entity"))if(!(r.getAttribute("alias")!==t.relatedEntity&&r.getAttribute("name")!==t.relatedEntity)){for(let n of st(r,"attribute"))if((n.getAttribute("alias")||n.getAttribute("name"))===t.name){r.removeChild(n);return}}return}for(let r of st(e,"attribute"))if(r.getAttribute("name")===t.name){e.removeChild(r);return}}function vD(e,t,r=!1){let n=a=>a.getAttribute("alias")===t||a.getAttribute("name")===t;for(let a of st(e,"link-entity"))if(n(a))return a;if(r)return;let i=e.getElementsByTagName("link-entity");for(let a=0;a<i.length;a+=1)if(n(i[a]))return i[a]}function h9(e,t,r){let n=vD(t,r);if(n)return n;let i=e.createElement("link-entity");return i.setAttribute("name",r),t.appendChild(i),i}function g9(e,t){let r=e.childNodes;for(let n=0;n<r.length;n+=1){let i=r[n];if(i.nodeType===1&&i.tagName!=="attribute"){e.insertBefore(t,i);return}}e.appendChild(t)}function v9(e,t,r){let n=t.getElementsByTagName("row")[0];if(!n)return;let i=[...r].sort((s,l)=>s.order-l.order),a=y9(n);if(b9(a,i)){for(let s=0;s<i.length;s+=1){let l=String(i[s].width);a[s].getAttribute("width")!==l&&a[s].setAttribute("width",l)}return}let o=new Map;for(let s of a){let l=s.getAttribute("name");l&&o.set(l,s),n.removeChild(s)}for(let s of i){let l=o.get(s.name);l||(l=e.createElement("cell"),l.setAttribute("name",s.name)),l.setAttribute("width",String(s.width)),n.appendChild(l)}}function y9(e){return st(e,"cell").filter(t=>!!t.getAttribute("name")&&t.getAttribute("ishidden")!=="1")}function b9(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r].getAttribute("name")!==t[r].name)return!1;return!0}function w9(e,t,r){let n=t.getElementsByTagName("entity")[0];if(!n)return;let i=(p,f)=>`${p.toLowerCase()}\0${f.toLowerCase()}`,a=new Map,o=new Map,s=(p,f,m)=>{let g=p.get(f);g?g.push(m):p.set(f,[m])};for(let p of st(n,"order")){let f=p.getAttribute("attribute")||"";f&&(s(a,i(p.getAttribute("entityname")||"",f),p),s(o,f.toLowerCase(),p)),n.removeChild(p)}let l=new Set,u=(p,f)=>{let m=p.get(f);for(;m&&m.length>0;){let g=m.shift();if(!l.has(g))return l.add(g),g}},c=p=>{var f;let m=o.get(p.toLowerCase());if(!m)return;let g=m.filter(A=>!l.has(A)),y=(f=g.find(A=>!A.getAttribute("entityname")))!==null&&f!==void 0?f:g[0];return y&&l.add(y),y},d=r.map(p=>{let f=String(p.attribute);return p.entityname===void 0?{expression:p,element:void 0}:{expression:p,element:u(a,i(p.entityname,f))}});for(let p of d)p.expression.entityname===void 0&&(p.element=c(String(p.expression.attribute)));for(let{expression:p,element:f}of d){let m=f??e.createElement("order");m.setAttribute("attribute",p.attribute),m.setAttribute("descending",String(p.descending)),p.entityname?m.setAttribute("entityname",p.entityname):p.entityname===""&&m.removeAttribute("entityname"),n.appendChild(m)}}function A9(e,t,r){let n=t.getElementsByTagName("entity")[0];if(n){for(let i of st(n,"filter"))vu(i)||n.removeChild(i);(r.conditions.length>0||r.groups.length>0)&&n.appendChild(ss(e,r))}}function hu(e,t){return JSON.stringify(e)===JSON.stringify(t)}function C9(e,t,r){var n;let i=t.getElementsByTagName("entity")[0];if(!i)return;let a=st(i,"link-entity").filter(m=>m.getAttribute("name")&&m.getAttribute("from")&&m.getAttribute("to")),o=(m,g)=>m.getAttribute(g)||"",s=new Array(r.length),l=new Set,u=m=>{r.forEach((g,y)=>{if(s[y])return;let A=a.filter(_=>!l.has(_)&&m(_,g));if(A.length!==1)return;let D=A[0];r.some((_,q)=>q!==y&&!s[q]&&m(D,_))||(s[y]=D,l.add(D))})};u((m,g)=>!!g.alias&&o(m,"name")===g.name&&o(m,"alias")===g.alias),u((m,g)=>o(m,"name")===g.name&&o(m,"from")===g.from&&o(m,"to")===g.to),u((m,g)=>o(m,"name")===g.name&&o(m,"from")===g.from),u((m,g)=>o(m,"name")===g.name&&o(m,"to")===g.to),u((m,g)=>o(m,"name")===g.name);let c=r.map((m,g)=>g).filter(m=>!s[m]),d=a.filter(m=>!l.has(m)),p=new Map;for(let m of d){let g=p.get(o(m,"name"));g?g.push(m):p.set(o(m,"name"),[m])}let f=new Map;for(let m of c){let g=f.get(r[m].name);g?g.push(m):f.set(r[m].name,[m])}for(let[m,g]of f){let y=(n=p.get(m))!==null&&n!==void 0?n:[];y.length===g.length&&g.forEach((A,D)=>{s[A]=y[D],l.add(y[D])})}r.forEach((m,g)=>{let y=s[g];if(y){uD(e,y,m);return}let A=e.createElement("link-entity");uD(e,A,m),i.appendChild(A)});for(let m of a)l.has(m)||i.removeChild(m)}var E9=new Set(["inner","outer"]);function S9(e,t,r,n){if(!t.getElementsByTagName("entity")[0])return;let a=new Set,o=t.getElementsByTagName("link-entity");for(let c=0;c<o.length;c+=1){let d=o[c],p=d.getAttribute("name"),f=d.getAttribute("alias");p&&a.add(p),f&&a.add(f)}let s=new Set;for(let c=0;c<o.length;c+=1)s.add(o[c]);let l=c=>{let d=n?.get(qf(c));return!!d&&d.every(p=>s.has(p))},u=r.filter(c=>c.relatedEntity&&!a.has(c.relatedEntity)&&!l(c));if(u.length!==0)throw new cD.ValidationError("view",e.id,u.map(c=>{var d;let p=((d=e.linkEntities)!==null&&d!==void 0?d:[]).some(f=>f.name===c.relatedEntity||f.alias===c.relatedEntity);return(0,kt.issue)(`/columns/${r.indexOf(c)}`,"view-column-dangling-link",`column '${c.name}' has relatedEntity '${c.relatedEntity}', but no matching join remains in linkEntities. `+(p?"Remove the column too, or keep the join.":"That join is NESTED (a join off a join), which the typed layer does not model, so it cannot be re-declared in linkEntities \u2014 it only survives while the join above it does. Remove the column, or restore the parent join this push replaced."))}))}function uD(e,t,r){t.setAttribute("name",r.name),t.setAttribute("from",r.from),t.setAttribute("to",r.to),r.alias?t.setAttribute("alias",r.alias):t.removeAttribute("alias"),r.linkType?t.setAttribute("link-type",r.linkType):E9.has(t.getAttribute("link-type")||"")&&t.removeAttribute("link-type");let n=st(t,"filter").find(a=>!vu(a)),i=r.filters&&(r.filters.conditions.length>0||r.filters.groups.length>0)?ss(e,r.filters):null;n&&i?t.replaceChild(i,n):n?t.removeChild(n):i&&t.appendChild(i)}function N9(e){var t;let r=new DOMParser().parseFromString("<fetch/>","text/xml"),n=r.documentElement;n.setAttribute("version","1.0"),n.setAttribute("mapping","logical");let i=r.createElement("entity");i.setAttribute("name",e.entityLogicalName),n.appendChild(i);let a=new Map;for(let o of(t=e.linkEntities)!==null&&t!==void 0?t:[]){let s=r.createElement("link-entity");s.setAttribute("name",o.name),s.setAttribute("from",o.from),s.setAttribute("to",o.to),o.alias&&s.setAttribute("alias",o.alias),o.linkType&&s.setAttribute("link-type",o.linkType),o.filters&&(o.filters.conditions.length>0||o.filters.groups.length>0)&&s.appendChild(ss(r,o.filters)),i.appendChild(s);for(let l of[o.alias||o.name,o.name])a.has(l)||a.set(l,s)}for(let o of[...e.columns].sort((s,l)=>s.order-l.order)){let s=r.createElement("attribute");if(o.relatedEntity){gD(s,o);let l=a.get(o.relatedEntity);l||(l=r.createElement("link-entity"),l.setAttribute("name",o.relatedEntity),i.appendChild(l),a.set(o.relatedEntity,l)),l.appendChild(s)}else s.setAttribute("name",o.name),i.appendChild(s)}for(let o of e.sort){let s=r.createElement("order");s.setAttribute("attribute",o.attribute),s.setAttribute("descending",String(o.descending)),o.entityname&&s.setAttribute("entityname",o.entityname),i.appendChild(s)}return(e.filters.conditions.length>0||e.filters.groups.length>0)&&i.appendChild(ss(r,e.filters)),new XMLSerializer().serializeToString(r)}function ss(e,t){let r=e.createElement("filter");r.setAttribute("type",t.type);for(let n of t.conditions){let i=e.createElement("condition");i.setAttribute("attribute",n.attribute),i.setAttribute("operator",n.operator),n.entityname&&i.setAttribute("entityname",n.entityname),n.value!==void 0&&i.setAttribute("value",n.value),r.appendChild(i)}for(let n of t.groups)r.appendChild(ss(e,n));return r}function D9(e,t){var r;let n=new DOMParser().parseFromString("<grid/>","text/xml"),i=n.documentElement,a=[...e.columns].sort((s,l)=>s.order-l.order);i.setAttribute("name","resultset"),i.setAttribute("jump",((r=a[0])===null||r===void 0?void 0:r.name)||t||`${e.entityLogicalName}id`),i.setAttribute("select","1"),i.setAttribute("icon","1"),i.setAttribute("preview","1");let o=n.createElement("row");o.setAttribute("name","result"),o.setAttribute("id",t||`${e.entityLogicalName}id`),i.appendChild(o);for(let s of a){let l=n.createElement("cell");l.setAttribute("name",s.name),l.setAttribute("width",String(s.width)),o.appendChild(l)}return new XMLSerializer().serializeToString(n)}function I9(){return{adapter:new gu,api:a9.viewApi,publish:(e,t,r)=>(0,iD.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,iD.boundEntityPublishScope)(t)}}Ta.viewRegistration=I9});function yu(e,t){return e==="SetFieldValue"&&t!==void 0&&_9.has(t.attributeType)&&(t.requiredLevel==="None"||t.requiredLevel==="Recommended")}var _9,Vf=I(()=>{"use strict";_9=new Set(["Integer","Double","Decimal","Money","String","Memo","DateTime","Picklist","Lookup"])});function bD(e){return e!=="Entity"&&e!=="AllForms"&&typeof e=="string"&&e.trim()!==""}function Gf(e){return bD(e)?1:2}function zf(e){return bD(e)?e:void 0}function wD(e,t){let r=zf(e.scope);return{"@odata.type":"#Microsoft.Dynamics.CRM.workflow",name:e.name,description:e.description,workflowid:t,ondemand:!1,subprocess:!1,triggeroncreate:!1,triggerondelete:!1,category:Pa.WorkflowCategory.BusinessRule,type:Pa.WorkflowTypeCode.Definition,mode:1,scope:Pa.WorkflowScope.Organization,primaryentity:e.entityLogicalName,iscrmuiworkflow:!0,processtriggerscope:Gf(e.scope),...r!==void 0?{processtriggerformid:r}:{}}}var Pa,AD=I(()=>{"use strict";Pa=ie(Yn());});function CD(e,t=0){return(Ye[e[t+0]]+Ye[e[t+1]]+Ye[e[t+2]]+Ye[e[t+3]]+"-"+Ye[e[t+4]]+Ye[e[t+5]]+"-"+Ye[e[t+6]]+Ye[e[t+7]]+"-"+Ye[e[t+8]]+Ye[e[t+9]]+"-"+Ye[e[t+10]]+Ye[e[t+11]]+Ye[e[t+12]]+Ye[e[t+13]]+Ye[e[t+14]]+Ye[e[t+15]]).toLowerCase()}var Ye,ED=I(()=>{Ye=[];for(let e=0;e<256;++e)Ye.push((e+256).toString(16).slice(1))});function Wf(){return bu>wu.length-16&&((0,SD.randomFillSync)(wu),bu=0),wu.slice(bu,bu+=16)}var SD,wu,bu,ND=I(()=>{SD=require("crypto"),wu=new Uint8Array(256),bu=wu.length});var DD,Hf,ID=I(()=>{DD=require("crypto"),Hf={randomUUID:DD.randomUUID}});function T9(e,t,r){if(Hf.randomUUID&&!t&&!e)return Hf.randomUUID();e=e||{};let n=e.random??e.rng?.()??Wf();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){if(r=r||0,r<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let i=0;i<16;++i)t[r+i]=n[i];return t}return CD(n)}var gt,_D=I(()=>{ID();ND();ED();gt=T9});var jf=I(()=>{_D()});var TD=I(()=>{"use strict";});var Jf=v(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.WorkflowConditionOperator=Jt.WorkflowAttributeType=Jt.SystemStep=Jt.FieldRequiredLevelTypes=Jt.AttributeDateTimeBehavior=void 0;Jt.AttributeDateTimeBehavior={None:0,Dynamic:1,DateOnly:2,StaticTimeZoneInvariant:3,UserLocal:4};Jt.FieldRequiredLevelTypes={None:"0",Required:"1",Recommended:"2"};Jt.SystemStep={IdentifyContact:"IdentifyContact",IdentifyAccount:"IdentifyAccount",IdentifyCustomer:"IdentifyCustomer",IdentifyCase:"IdentifyCase",Solution:"Solution",Resolve:"Resolve"};Jt.WorkflowAttributeType={Boolean:"0",Customer:"1",DateTime:"2",Decimal:"3",Float:"4",Integer:"5",Lookup:"6",Money:"7",Owner:"8",PartyList:"9",Picklist:"10",Key:"11",State:"12",Status:"13",String:"14",UniqueIdentifier:"15",EntityNameReference:"16",Entity:"17",EntityCollection:"18",BpfProcess:"19",BpfStageCategory:"20",BpfStage:"21",EntityReferenceCollection:"22",MultiSelectPicklist:"23",BigType:"24"};Jt.WorkflowConditionOperator={IsNull:"0",NotNull:"1",LogicalAnd:"2",LogicalOr:"3",IN:"4",NotIn:"5",NotInNull:"51",Equal:"6",NotEqual:"7",Contains:"8",DoesNotContain:"9",BeginsWith:"10",DoesNotBeginWith:"11",EndsWith:"12",DoesNotEndWith:"13",GreaterThan:"14",GreaterThanOrEqual:"15",LessThan:"16",LessThanOrEqual:"17",EqualUserId:"18",NotEqualUserId:"19",On:"20",NotOn:"21",OnOrAfter:"22",OnOrBefore:"23",Yesterday:"24",Today:"25",Tomorrow:"26",NextSevenDays:"27",LastSevenDays:"28",NextWeek:"29",LastWeek:"30",ThisWeek:"31",NextMonth:"32",LastMonth:"33",ThisMonth:"34",NextYear:"35",LastYear:"36",ThisYear:"37",Anytime:"38",LastXHours:"39",NextXHours:"40",LastXDays:"41",NextXDays:"42",LastXWeeks:"43",NextXWeeks:"44",LastXMonths:"45",NextXMonths:"46",LastXYears:"47",NextXYears:"48",Under:"49",NotUnder:"50"}});function FD(e){switch(e){case"Boolean":return ye.WorkflowAttributeType.Boolean;case"Customer":return ye.WorkflowAttributeType.Customer;case"DateTime":return ye.WorkflowAttributeType.DateTime;case"Decimal":return ye.WorkflowAttributeType.Decimal;case"Double":return ye.WorkflowAttributeType.Float;case"Integer":return ye.WorkflowAttributeType.Integer;case"Lookup":return ye.WorkflowAttributeType.Lookup;case"Money":return ye.WorkflowAttributeType.Money;case"Owner":return ye.WorkflowAttributeType.Owner;case"Picklist":return ye.WorkflowAttributeType.Picklist;case"State":return ye.WorkflowAttributeType.State;case"Status":return ye.WorkflowAttributeType.Status;case"Uniqueidentifier":case"UniqueIdentifier":return ye.WorkflowAttributeType.UniqueIdentifier;case"BigInt":return ye.WorkflowAttributeType.BigType;default:return ye.WorkflowAttributeType.String}}function $D(e){return e&&e!==ye.WorkflowAttributeType.String?e:void 0}function R9(e){return{__class:BD,parameterName:"primaryEntity",entityName:e}}function PD(e){return{__class:Kf,type:Qf,typeSet:!1,behavior:ye.AttributeDateTimeBehavior.None,method:xD,parameters:[e]}}function OD(e,t,r=ye.WorkflowAttributeType.String){return{__class:kD,type:r,behavior:ye.AttributeDateTimeBehavior.None,typeSet:!1,entity:R9(t),attributeName:e}}function F9(e,t=ye.WorkflowAttributeType.String){return{__class:MD,type:t,behavior:ye.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function x9(e){return{__class:UD,type:Qf,typeSet:!1,behavior:ye.AttributeDateTimeBehavior.None,days:e,hours:"0",minutes:"0",months:"0",years:"0"}}function qD(e,t){let r=P9[e.operator],n=PD(OD(e.leftField,t,e.leftWorkflowType)),i;e.dateArithmetic?i=x9(e.right.value??"0"):e.right.kind==="field"?i=OD(e.right.field??"",t,e.right.workflowType):i=F9(e.right.value??"",e.right.workflowType??e.leftWorkflowType);let a=PD(i);return{__class:Kf,type:Qf,typeSet:!1,behavior:ye.AttributeDateTimeBehavior.None,method:LD,parameters:[r,n,a]}}function VD(e){return typeof e=="object"&&e.__class===Kf}function L9(e){return typeof e=="object"&&e.__class===UD}function Au(e){return VD(e)&&e.method===xD&&e.parameters.length>0?Au(e.parameters[0]):e}function RD(e){if(typeof e!="object"||e.__class!==kD)return null;let t=e.entity;if(t&&t.__class&&t.__class!==BD)return null;let r=e.attributeName;return r?{field:r,workflowType:$D(e.type)}:null}function GD(e){if(!e)return null;let t=Au(e);if(!VD(t)||t.method!==LD||t.parameters.length!==3)return null;let r=t.parameters[0],n=O9[String(r)];if(!n)return null;let i=RD(Au(t.parameters[1]));if(!i)return null;let a=Au(t.parameters[2]);if(L9(a))return n!=="+"&&n!=="-"?null:{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:String(a.days??"")},dateArithmetic:!0};let o=RD(a);if(o)return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"field",field:o.field,workflowType:o.workflowType}};if(typeof a=="object"&&a.__class===MD){let s=a.primitiveValue;return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:s!=null?String(s):"",workflowType:$D(a.type)}}}return null}function Yf(e){let t=(e??"").trim();if(!/^\d+$/.test(t))return!1;let r=Number(t);return Number.isSafeInteger(r)&&r>=Xf&&r<=Oa}function wi(e){if(!e||!e.leftField)return"incomplete";if(e.right.kind==="field")return e.right.field&&e.right.field.trim()?null:"incomplete";let t=e.right.value;return!t||!t.trim()?"incomplete":e.dateArithmetic&&!Yf(t)?"invalidDayCount":null}function Ra(e){return wi(e)===null}var ye,xD,LD,Qf,kD,MD,Kf,UD,BD,P9,O9,Xf,Oa,ls=I(()=>{"use strict";ye=ie(Jf());xD="0",LD="3",Qf="0",kD="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",MD="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",Kf="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",UD="TimeSpanExpression:#Microsoft.Crm.Workflow.Expressions",BD="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions";P9={"+":0,"-":1,"*":2,"/":3},O9={0:"+",1:"-",2:"*",3:"/"};Xf=0,Oa=2147483647});function M9(e){return e.startsWith("__")&&!k9.has(e)}function U9(e){let t=Object.create(null);return Object.keys(e).forEach(r=>{M9(r)&&(t[r]=e[r])}),Object.keys(t).length>0?t:void 0}function zD(e){return e.__class==="BinaryExpression:#Microsoft.Crm.Workflow.Expressions"}function B9(e){return e.__class==="ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel"}function us(){return{list:[]}}function WD(e,t,r){return e&&e.list.length>0?{list:[{...e.list[0],description:t},...e.list.slice(1)]}:{list:[{labelId:gt(),languageCode:r,description:t}]}}function rm(e){return{__class:"PrimaryEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:"primaryEntity",entityName:e}}function nm(e,t,r){return{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:W.AttributeDateTimeBehavior.None,typeSet:!1,entity:rm(t),attributeName:e}}function cs(e,t){return{__class:"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",type:t,behavior:W.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function YD(e){return{__class:"LookupExpression:#Microsoft.Crm.Workflow.Expressions",type:e.workflowType??W.WorkflowAttributeType.Lookup,behavior:W.AttributeDateTimeBehavior.None,typeSet:!1,entityType:e.entityType,label:e.label??"",staticValue:cs(e.id.replace(/[{}]/g,""),W.WorkflowAttributeType.UniqueIdentifier)}}function HD(e,t){let r=e.valueType==="Lookup"?e.lookupValue?.workflowType??W.WorkflowAttributeType.Lookup:e.valueWorkflowType??W.WorkflowAttributeType.String,n=tm[e.operator]??W.WorkflowConditionOperator.Equal,i=nm(e.field,t,r),a;if(e.operator==="ContainsData"||e.operator==="DoesNotContainData")a=[];else if(e.valueType==="Field"&&e.valueField)a=[nm(e.valueField,t,r)];else if(e.valueType==="Lookup"){if(!e.lookupValue)throw new Error("Lookup condition is missing its record value.");a=[YD(e.lookupValue)]}else e.valueType==="Clear"?a=[cs(null,r)]:e.valueType==="Expression"?a=[Eu(e.valueType,e.value,e.valueField,t,e.expression,e.rawExpression)]:a=[cs(e.value??"",r)];return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:W.WorkflowAttributeType.Boolean,behavior:W.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:i,right:a}}function $9(e,t,r){if(e.length===0)return null;if(e.length===1)return HD(e[0],r);let n=t==="AND"?W.WorkflowConditionOperator.LogicalAnd:W.WorkflowConditionOperator.LogicalOr,[i,...a]=e.map(o=>HD(o,r));return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:W.WorkflowAttributeType.Boolean,behavior:W.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:i,right:a}}function Cu(e){if(!e)return{valueType:"Value",value:""};if(e.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions")return{valueType:"Field",valueField:e.attributeName};if(e.__class==="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions")return e.primitiveValue==null?{valueType:"Clear",valueWorkflowType:e.type}:{valueType:"Value",value:e.primitiveValue!=null?String(e.primitiveValue):""};if(e.__class==="LookupExpression:#Microsoft.Crm.Workflow.Expressions"){let t=e.staticValue,r=typeof t=="object"&&t?.__class==="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"?t.primitiveValue:t;return{valueType:"Lookup",lookupValue:{entityType:e.entityType,id:String(r??""),label:e.label,...e.type!==W.WorkflowAttributeType.Lookup?{workflowType:e.type}:{}}}}if(e.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"){let t=GD(e);return t?{valueType:"Expression",expression:t}:{valueType:"Expression",rawExpression:e}}return{valueType:"Value",value:""}}function Zf(e){let t=XD[e.conditionOperatoroperator]??"Equals",r=e.left,n=r.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",i=n?r.attributeName:"",a=n?r.type:void 0,s=t==="ContainsData"||t==="DoesNotContainData"?{valueType:"Value"}:Cu(e.right[0]),l=s.valueWorkflowType??a;return{id:gt(),field:i,fieldDisplayName:i,operator:t,...s,...l?{valueWorkflowType:l}:{}}}function jD(e){if(!e||e.__class!=="BinaryExpression:#Microsoft.Crm.Workflow.Expressions")return{clauses:[],logic:"AND"};let t=e.conditionOperatoroperator;if(t===W.WorkflowConditionOperator.LogicalAnd||t===W.WorkflowConditionOperator.LogicalOr){let r=t===W.WorkflowConditionOperator.LogicalAnd?"AND":"OR";return{clauses:[...zD(e.left)?[Zf(e.left)]:[],...e.right.filter(zD).map(Zf)],logic:r}}return{clauses:[Zf(e)],logic:"AND"}}function Eu(e,t,r,n,i,a,o,s){if(e==="Field"&&r)return nm(r,n,W.WorkflowAttributeType.String);if(e==="Expression"){if(i)return qD(i,n);if(a!=null)return a}return e==="Lookup"&&o?YD(o):e==="Clear"?cs(null,s??W.WorkflowAttributeType.String):cs(t??"",W.WorkflowAttributeType.String)}function em(e,t){return{propertyName:e,propertyValueExpr:t}}function Fa(e){return`Step_${e.value++}`}function Qt(e,t){let r=(t.counts[e]??0)+1,n=`${e}${r}`;for(;t.used.has(n);)r+=1,n=`${e}${r}`;return t.counts[e]=r,t.used.add(n),n}function JD(e,t,r){return e&&!r.used.has(e)?(r.used.add(e),e):Qt(t,r)}function q9(e){return e===KD.StateCode.Activated?"Active":"Draft"}function V9(e,t){let r=e.processtriggerscope,n=e.processtriggerformid;return r===1&&n?n:r===2?"Entity":t??"Entity"}function ZD(e,t=1033){return new xa({languageCode:t}).serialize(e)}function eI(e){return new xa().deserialize(e)}var KD,W,k9,tm,XD,im,xa,am=I(()=>{"use strict";jf();KD=ie(Yn());TD();ls();W=ie(Jf());k9=new Set(["__class"]);tm={Equals:W.WorkflowConditionOperator.Equal,DoesNotEqual:W.WorkflowConditionOperator.NotEqual,IsGreaterThan:W.WorkflowConditionOperator.GreaterThan,IsLessThan:W.WorkflowConditionOperator.LessThan,IsGreaterThanEqualTo:W.WorkflowConditionOperator.GreaterThanOrEqual,IsLessThanEqualTo:W.WorkflowConditionOperator.LessThanOrEqual,Contains:W.WorkflowConditionOperator.Contains,DoesNotContain:W.WorkflowConditionOperator.DoesNotContain,BeginsWith:W.WorkflowConditionOperator.BeginsWith,DoesNotBeginWith:W.WorkflowConditionOperator.DoesNotBeginWith,EndsWith:W.WorkflowConditionOperator.EndsWith,DoesNotEndWith:W.WorkflowConditionOperator.DoesNotEndWith,On:W.WorkflowConditionOperator.On,NotOn:W.WorkflowConditionOperator.NotOn,ContainsData:W.WorkflowConditionOperator.NotNull,DoesNotContainData:W.WorkflowConditionOperator.IsNull},XD={};for(let e of Object.keys(tm))XD[tm[e]]=e;im={setFieldValue:"Set Field Value",setDefaultValue:"Set Default Value",lockUnlock:"Lock/Unlock",setBusinessRequired:"Set Business Required",setVisibility:"Set Visibility",recommendation:"Recommendation",showErrorMessage:"Show Error Message",condition:"Condition"};xa=class{resolveLabel;languageCode;entityName="";stepCounter={value:0};idCounter={counts:{},used:new Set};constructor(t={}){this.resolveLabel=t.resolveLabel??(r=>im[r]),this.languageCode=t.languageCode??1033}label(t){return this.resolveLabel(t)}serialize(t){let r=t.wfomRoot;this.entityName=t.entityLogicalName,this.stepCounter={value:r?Number(r.nextStepIndex):1},this.idCounter={counts:{},used:new Set};let n=t.scope!=="Entity"&&t.scope!=="AllForms"?t.scope:null,i=t.rootCondition?[this.serializeConditionNode(t.rootCondition)]:[],a={...r?.reservedProperties??{},__class:"WorkflowStep:#Microsoft.Crm.Workflow.ObjectModel",id:r?.id??t.ruleId??gt(),name:r?.name??"Step_0",description:r!==void 0?r.description:t.description||null,stepLabels:us(),argumentsArray:[],primaryEntityName:r?.primaryEntityName??this.entityName,nextStepIndex:String(this.stepCounter.value),isCrmUIWorkflow:!0,category:r?.category??"2",businessProcessType:r?.businessProcessType??"0",mode:r?.mode??"0",title:r?.title??t.name,formId:n,workflowEntityId:r?.workflowEntityId??t.ruleId??"",variables:r?.variables??[],inputs:r?.inputs??[],steps:{list:i}};return JSON.stringify(a)}makeApplyActionStep(t){return{__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",id:Qt("SetAttributeValueStep",this.idCounter),description:t.displayName||"New Action",name:t.stepName??Fa(this.stepCounter),stepLabels:{list:[]},specification:em(t.field,Eu(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType)),entity:rm(this.entityName)}}makeRecommendationActionStep(t,r,n){let i=r.map(l=>this.makeApplyActionStep(l)),a=t??"",o=n?.stepLabels,s=WD(o,a,this.languageCode);return{__class:"ActionStep:#Microsoft.Crm.Workflow.ObjectModel",id:JD(n?.id,"ActionStep",this.idCounter),name:n?.name??Fa(this.stepCounter),description:n?.description??"Action step",stepLabels:s,steps:{list:i},actionId:null,actionType:n?.actionType??"4",processId:n?.processId??gt(),uniqueName:n?.uniqueName??`id_${gt().replace(/-/g,"")}ActionStep`}}serializeAction(t){let r=rm(this.entityName),n=t.stepName??Fa(this.stepCounter),i=t.stepLabels??us(),a={name:n,stepLabels:i,description:t.displayName},o=t.type;switch(o){case"SetFieldValue":return{...a,id:Qt("SetAttributeValueStep",this.idCounter),__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:em(t.field,Eu(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"SetDefaultValue":return{...a,id:Qt("SetDefaultValueStep",this.idCounter),__class:"SetDefaultValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:em(t.field,Eu(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"LockUnlock":return{...a,id:Qt("SetDisplayModeStep",this.idCounter),__class:"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isReadOnly:t.lock,entity:r};case"SetBusinessRequired":return{...a,id:Qt("SetFieldRequiredLevelStep",this.idCounter),__class:"SetFieldRequiredLevelStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",requiredLevel:t.required?W.FieldRequiredLevelTypes.Required:W.FieldRequiredLevelTypes.None,entity:r};case"SetVisibility":return{...a,id:Qt("SetVisibilityStep",this.idCounter),__class:"SetVisibilityStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isVisible:t.visible,entity:r};case"ShowErrorMessage":{let s=t.errorMessage||t.displayName,l=t.stepLabels&&t.stepLabels.list.length>0?t.stepLabels:{list:[{labelId:gt(),languageCode:this.languageCode,description:s}]};return{...a,id:Qt("SetMessageStep",this.idCounter),__class:"SetMessageStep:#Microsoft.Crm.Workflow.ObjectModel",stepLabels:l,name:s,controlId:t.field,entity:r,level:t.messageLevel??"error",actionSteps:t.messageActionSteps??{list:[]}}}case"Recommendation":{let s=t.messageText??t.recommendationTitle??t.displayName,l=WD(t.stepLabels,s,this.languageCode),u={list:[this.makeRecommendationActionStep(t.acceptanceText,t.applyActions??[],t.recommendationActionStepMeta)]};return{...a,id:Qt("SetMessageStep",this.idCounter),__class:"SetMessageStep:#Microsoft.Crm.Workflow.ObjectModel",stepLabels:l,description:t.recommendationTitle||t.displayName,controlId:t.field,entity:r,level:"RECOMMENDATION",actionSteps:u}}default:throw new Error(`Unsupported action type: ${o}`)}}serializeConditionNode(t){let r=t.stepName??Fa(this.stepCounter),n=Qt("ConditionStep",this.idCounter),i=[],a=t,o=!0;for(;a;){let s=$9(a.clauses,a.logic,this.entityName),l=o?a.branchName??Fa(this.stepCounter):Fa(this.stepCounter),c={__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:o?JD(a.branchId,"ConditionBranchStep",this.idCounter):Qt("ConditionBranchStep",this.idCounter),name:l,description:a.displayName,stepLabels:us(),conditionExpression:s??void 0,steps:{list:a.trueBranch.map(p=>this.serializeBranchItem(p))}};i.push(c);let d=a.falseBranch;if(d.length===1&&d[0].kind==="condition"){a=d[0],o=!1;continue}d.length>0&&i.push(this.makeTerminalElseBranch(d)),a=void 0}return{__class:"ConditionStep:#Microsoft.Crm.Workflow.ObjectModel",id:n,name:r,description:"",stepLabels:us(),containsElsebranch:i.length>1,steps:{list:i}}}makeTerminalElseBranch(t){return{__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:Qt("ConditionBranchStep",this.idCounter),name:"Else",description:null,stepLabels:us(),conditionExpression:void 0,steps:{list:t.map(r=>this.serializeBranchItem(r))}}}serializeBranchItem(t){return t.kind==="condition"?this.serializeConditionNode(t):this.serializeAction(t)}deserialize(t){let r=t,n=null,i;if(t.wfomJson)try{let a=JSON.parse(t.wfomJson);i={id:a.id==="WorkflowStep0"||!a.id?t.workflowid??gt():a.id,name:a.name,description:a.description,nextStepIndex:a.nextStepIndex,category:a.category==="0"||a.category===0?"2":a.category,businessProcessType:a.businessProcessType,mode:a.mode,title:a.title||t.name||"",primaryEntityName:a.primaryEntityName==="1"||!a.primaryEntityName?t.primaryentity??"":a.primaryEntityName,workflowEntityId:a.workflowEntityId==="00000000-0000-0000-0000-000000000000"||!a.workflowEntityId?t.workflowid??"":a.workflowEntityId,formId:a.formId,variables:a.variables,inputs:a.inputs,reservedProperties:U9(a)};let s=(a.steps?.list??[]).find(l=>l.__class==="ConditionStep:#Microsoft.Crm.Workflow.ObjectModel");s&&(n=this.deserializeConditionStep(s))}catch{}return{ruleId:t.workflowid??null,name:t.name??"",description:t.description??"",entityLogicalName:t.primaryentity??"",scope:V9(r,i?.formId),status:q9(t.statecode),rootCondition:n,wfomRoot:i}}deserializeConditionStep(t){let r=(t.steps?.list??[]).filter(B9);return this.buildConditionNodeFromBranches(r,t,!0)}buildConditionNodeFromBranches(t,r,n){let[i,...a]=t,{clauses:o,logic:s}=jD(i?.conditionExpression),l=this.deserializeBranch(i?.steps?.list??[]),u=this.deserializeElseChain(a,r),c=i?.description||i?.name||r.description||r.name||this.label("condition");return{kind:"condition",id:(n?r.id:i?.id)??gt(),displayName:c,clauses:o,logic:s,trueBranch:l,falseBranch:u,isCollapsed:!1,stepName:n?r.name:void 0,branchId:n?i?.id:void 0,branchName:n?i?.name:void 0}}deserializeElseChain(t,r){if(t.length===0)return[];let[n]=t,{clauses:i}=jD(n.conditionExpression);return i.length===0?this.deserializeBranch(n.steps?.list??[]):[this.buildConditionNodeFromBranches(t,r,!1)]}deserializeBranch(t){return t.map(r=>r.__class==="ConditionStep:#Microsoft.Crm.Workflow.ObjectModel"?this.deserializeConditionStep(r):this.deserializeAction(r)).filter(r=>r!==null)}parseRecommendationApplyActions(t){let n=(t?.list??[])[0];if(!n)return{applyActions:[]};let i={id:n.id,name:n.name,description:n.description??void 0,stepLabels:n.stepLabels,processId:n.processId,uniqueName:n.uniqueName,actionType:n.actionType},a=n.stepLabels?.list,o=a&&a.length>0?a[0].description??"":"";return{applyActions:(n.steps?.list??[]).filter(l=>l.__class==="SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel").map(l=>{let u=l.specification;return{id:l.id||gt(),field:u?.propertyName??"",stepName:l.name??void 0,displayName:l.description??void 0,...Cu(u?.propertyValueExpr)}}),meta:i,acceptanceText:o}}deserializeAction(t){switch(t.__class){case"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=Cu(t.specification.propertyValueExpr);return{kind:"action",id:t.id,type:"SetFieldValue",displayName:t.description||t.name||this.label("setFieldValue"),stepName:t.name,stepLabels:t.stepLabels,field:t.specification.propertyName,...r}}case"SetDefaultValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=Cu(t.specification.propertyValueExpr);return{kind:"action",id:t.id,type:"SetDefaultValue",displayName:t.description||t.name||this.label("setDefaultValue"),stepName:t.name,stepLabels:t.stepLabels,field:t.specification.propertyName,...r}}case"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel":return{kind:"action",id:t.id,type:"LockUnlock",displayName:t.description||t.name||this.label("lockUnlock"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,lock:t.isReadOnly};case"SetFieldRequiredLevelStep:#Microsoft.Crm.Workflow.ObjectModel":return{kind:"action",id:t.id,type:"SetBusinessRequired",displayName:t.description||t.name||this.label("setBusinessRequired"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,required:t.requiredLevel!==W.FieldRequiredLevelTypes.None};case"SetVisibilityStep:#Microsoft.Crm.Workflow.ObjectModel":return{kind:"action",id:t.id,type:"SetVisibility",displayName:t.description||t.name||this.label("setVisibility"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,visible:t.isVisible};case"SetMessageStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=t.stepLabels?.list,n=r&&r.length>0?r[0].description??"":"";if((t.level??"").toUpperCase()==="RECOMMENDATION"){let{applyActions:i,meta:a,acceptanceText:o}=this.parseRecommendationApplyActions(t.actionSteps);return{kind:"action",id:t.id,type:"Recommendation",displayName:t.description||this.label("recommendation"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,recommendationTitle:t.description||"",messageText:n,acceptanceText:o,applyActions:i,recommendationActionStepMeta:a}}return{kind:"action",id:t.id,type:"ShowErrorMessage",displayName:t.description||this.label("showErrorMessage"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,errorMessage:n||t.name||"",messageLevel:t.level??void 0,messageActionSteps:t.actionSteps}}case"ActionStep:#Microsoft.Crm.Workflow.ObjectModel":{let{applyActions:r,meta:n,acceptanceText:i}=this.parseRecommendationApplyActions({list:[t]});return{kind:"action",id:t.id,type:"Recommendation",displayName:t.name||this.label("recommendation"),stepName:t.name,stepLabels:t.stepLabels,field:t.actionControl?.controlId??"",recommendationTitle:t.name||"",messageText:t.description||"",acceptanceText:i,applyActions:r,recommendationActionStepMeta:n}}default:return null}}}});var tI=I(()=>{"use strict";});function Wn(e){return!G9.has(e)}function aI(e){return K9.has(e)}function Su(e){return nI.has(e)?z9:J9.has(e)?W9:iI.has(e)?H9:j9}function oI(e){return Su(e)[0]}function sI(e,t){return Su(t).includes(e)}function rI(e){return nI.has(e)?"string":e==="Money"?"money":e==="Integer"||e==="BigInt"?"integer":e==="Decimal"||e==="Double"?"decimal":iI.has(e)?"date":Q9.has(e)?"boolean":"other"}function Nu(e,t){let r=rI(e),n=rI(t);return r==="other"||n==="other"?e===t:r===n}var G9,z9,W9,H9,j9,nI,J9,iI,Q9,K9,om=I(()=>{"use strict";tI();G9=new Set(["ContainsData","DoesNotContainData"]);z9=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],W9=["Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],H9=["On","NotOn","Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],j9=["Equals","DoesNotEqual","ContainsData","DoesNotContainData"],nI=new Set(["String","Memo","EntityName"]),J9=new Set(["Integer","BigInt","Money","Decimal","Double"]),iI=new Set(["DateTime"]),Q9=new Set(["Boolean"]),K9=new Set(["Equals","DoesNotEqual"])});function cm(e){return X9.has(e.type)}function sm(e,t,r,n,i,a,o){let s=i.get(r);!s||!Y9.has(s.attributeType)||n!=="Value"||o?.operator&&!aI(o.operator)||a.push({nodeId:e,kind:"INVALID_VALUE_TYPE_FOR_FIELD",message:`${t}: please select a record for this lookup field; a typed text value cannot be saved.`,target:o?.target,itemId:o?.itemId,messageKey:"Validation.InvalidValueTypeForField",messageParams:{label:t}})}function lm(e){return!!(e?.entityType?.trim()&&e.id?.trim())}function um(e,t,r){return{nodeId:e,kind:"INVALID_DAY_COUNT",message:`Please enter a whole number of days between 0 and ${Oa}.`,target:t,itemId:r,messageKey:"Validation.InvalidDayCount",messageParams:{max:Oa}}}function lI(e,t,r,n,i,a,o,s){if(i!=="Clear")return;let l=a.get(n);yu(r,l)||o.push({nodeId:e,kind:"INVALID_CLEAR_FOR_FIELD",message:`${t}: Clear is only supported for optional fields with a legacy-compatible type.`,target:s?.target,itemId:s?.itemId,messageKey:"Validation.InvalidClearForField",messageParams:{label:t}})}function Iu(e){if(!e)return!1;for(let t of[...e.trueBranch,...e.falseBranch])if(t.kind==="action"){if(cm(t))return!0}else if(Iu(t))return!0;return!1}function dm(e,t){if(e.id===t)return e;for(let r of[...e.trueBranch,...e.falseBranch]){if(r.id===t)return r;if(r.kind==="condition"){let n=dm(r,t);if(n)return n}}return null}function La(e,t){for(let r=0;r<e.trueBranch.length;r++){let n=e.trueBranch[r];if(n.id===t)return{node:e,branch:"true",index:r};if(n.kind==="condition"){let i=La(n,t);if(i)return i}}for(let r=0;r<e.falseBranch.length;r++){let n=e.falseBranch[r];if(n.id===t)return{node:e,branch:"false",index:r};if(n.kind==="condition"){let i=La(n,t);if(i)return i}}return null}function pm(e,t){return{...e,trueBranch:uI(e.trueBranch,t),falseBranch:uI(e.falseBranch,t)}}function uI(e,t){return e.filter(r=>r.id!==t).map(r=>r.kind==="condition"?pm(r,t):r)}function Hn(e,t,r){return e.id===t?r(e):{...e,trueBranch:e.trueBranch.map(n=>n.kind==="condition"?Hn(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="condition"?Hn(n,t,r):n)}}function Du(e,t,r){return{...e,trueBranch:e.trueBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?Du(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?Du(n,t,r):n)}}function cI(e,t,r,n){return Hn(e,t,i=>({...i,trueBranch:r==="true"?[...i.trueBranch,n]:i.trueBranch,falseBranch:r==="false"?[...i.falseBranch,n]:i.falseBranch}))}function fm(e){return e.length===1&&e[0].kind==="condition"}function e8(e){let t=0,r=e??void 0;for(;r;){t+=1;let{falseBranch:n}=r;if(fm(n)){r=n[0];continue}n.length>0&&(t+=1),r=void 0}return t}function t8(e){return!!e&&e8(e)<Z9}function r8(e,t){if(!e)return;let r=(n,i)=>{if(n.id===t)return i;let a=[];if(fm(n.falseBranch)){let o=r(n.falseBranch[0],i);if(o)return o}else a.push(...n.falseBranch.filter(o=>o.kind==="condition"));a.push(...n.trueBranch.filter(o=>o.kind==="condition"));for(let o of a){let s=r(o,o);if(s)return s}};return r(e,e)}function dI(e,t,r){let n=r8(e,t);return!n||!t8(n)?e:Hn(e,t,i=>pI(i,r))}function pI(e,t){if(fm(e.falseBranch))return{...e,falseBranch:[pI(e.falseBranch[0],t)]};let r=mm(t);return r.falseBranch=e.falseBranch,{...e,falseBranch:[r]}}function fI(e,t){let r=La(e,t);if(!r||r.branch!=="false")return e;let n=r.node.falseBranch[r.index];if(!n||n.kind!=="condition")return e;let i=n.falseBranch;return Hn(e,r.node.id,a=>({...a,falseBranch:i}))}function mI(e,t,r){let n=La(e,t);if(!n)return e;let i=a=>{let o=[...a],s=o[n.index+r];return s?(o[n.index+r]=o[n.index],o[n.index]=s,o):a};return Hn(e,n.node.id,a=>({...a,trueBranch:n.branch==="true"?i(a.trueBranch):a.trueBranch,falseBranch:n.branch==="false"?i(a.falseBranch):a.falseBranch}))}function mm(e){return{kind:"condition",id:gt(),displayName:e??"New Condition",clauses:[],logic:"AND",trueBranch:[],falseBranch:[],isCollapsed:!1}}function hI(e,t){let r={kind:"action",id:gt(),type:e,displayName:t??`New ${e}`};switch(e){case"Recommendation":return{...r,type:"Recommendation",field:"",recommendationTitle:"",messageText:"",applyActions:[{id:gt(),field:"",valueType:"Value",value:""}]};case"LockUnlock":return{...r,type:"LockUnlock",field:"",lock:!0};case"ShowErrorMessage":return{...r,type:"ShowErrorMessage",field:"",errorMessage:""};case"SetFieldValue":return{...r,type:"SetFieldValue",field:"",valueType:"Value",value:""};case"SetDefaultValue":return{...r,type:"SetDefaultValue",field:"",valueType:"Value",value:""};case"SetBusinessRequired":return{...r,type:"SetBusinessRequired",field:"",required:!0};case"SetVisibility":return{...r,type:"SetVisibility",field:"",visible:!0};default:return{...r,type:"SetFieldValue",field:"",valueType:"Value",value:""}}}function gI(e){if(!e)return[];let t=[];return vI(e,t),[...new Set(t)]}function vI(e,t){e.clauses.forEach(r=>{r.field&&t.push(r.field)}),[...e.trueBranch,...e.falseBranch].forEach(r=>{r.kind==="condition"?vI(r,t):"field"in r&&r.field&&t.push(r.field)})}function yI(e,t=[]){if(!e)return[{nodeId:"root",kind:"NO_CONDITION",message:"A business rule must include at least one condition.",target:"node"}];let r=[],n=new Map(t.map(i=>[i.logicalName,i]));return bI(e,r,n),Iu(e)||r.push({nodeId:"root",kind:"NO_ACTION",message:"A business rule must include at least one action step.",target:"node"}),r}function bI(e,t,r){e.clauses.length===0&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Add at least one clause to this condition.",target:"node",messageKey:"Validation.AddClause"}),e.clauses.forEach(n=>{let i=n.valueType==="Expression"&&!n.rawExpression?wi(n.expression):null;if(!n.field)t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Please select a field for this clause.",target:"clauseField",itemId:n.id});else if(Wn(n.operator)&&n.valueType==="Value"&&!n.value)t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause.",target:"clauseValue",itemId:n.id});else if(Wn(n.operator)&&n.valueType==="Value"&&n.value){let a=r.get(n.field);a?.maxLength&&n.value.length>a.maxLength&&t.push({nodeId:e.id,kind:"CLAUSE_VALUE_TOO_LONG",message:`Value exceeds the field's maximum length of ${a.maxLength} characters.`,target:"clauseValue",itemId:n.id,messageParams:{maxLength:a.maxLength}})}else Wn(n.operator)&&n.valueType==="Expression"&&!n.rawExpression&&!Ra(n.expression)&&t.push(i==="invalidDayCount"?um(e.id,"clauseValue",n.id):{nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please complete the formula for this clause.",target:"clauseValue",itemId:n.id,messageKey:"Validation.CompleteClauseFormula"});Wn(n.operator)&&n.valueType==="Lookup"&&(lm(n.lookupValue)||t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please select a lookup record for this clause.",target:"clauseValue",itemId:n.id,messageKey:"Validation.EmptyClauseLookupValue"})),Wn(n.operator)&&sm(e.id,"Condition",n.field,n.valueType,r,t,{operator:n.operator,target:"clauseValue",itemId:n.id})}),[...e.trueBranch,...e.falseBranch].forEach(n=>{if(n.kind==="condition")bI(n,t,r);else{if(!("field"in n)||!n.field)t.push({nodeId:n.id,kind:"EMPTY_ACTION_FIELD",message:`${n.type}: a target field is required.`,target:"actionField",messageParams:{actionType:n.type}});else if((n.type==="SetFieldValue"||n.type==="SetDefaultValue")&&(n.valueType??"Value")==="Value"&&!n.value?.trim())t.push({nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:`${n.type}: please provide a value.`,target:"actionValue",messageParams:{actionType:n.type}});else if((n.type==="SetFieldValue"||n.type==="SetDefaultValue")&&n.valueType==="Value"&&n.value){let i=r.get(n.field);i?.maxLength&&n.value.length>i.maxLength&&t.push({nodeId:n.id,kind:"ACTION_VALUE_TOO_LONG",message:`${n.type}: value exceeds the field's maximum length of ${i.maxLength} characters.`,target:"actionValue",messageParams:{actionType:n.type,maxLength:i.maxLength}})}else if((n.type==="SetFieldValue"||n.type==="SetDefaultValue")&&n.valueType==="Field"){if(!n.valueField)t.push({nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:`${n.type}: please select a field to copy from.`,target:"actionValue",messageKey:"Validation.SelectActionSourceField",messageParams:{actionType:n.type}});else if(r.size>0){let i=r.get(n.field),a=r.get(n.valueField);i&&a&&!Nu(i.attributeType,a.attributeType)&&t.push({nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:`${n.type}: the source field's type is not compatible with the target field.`,target:"actionValue",messageKey:"Validation.IncompatibleActionSourceField",messageParams:{actionType:n.type}})}}else if((n.type==="SetFieldValue"||n.type==="SetDefaultValue")&&n.valueType==="Expression"){let i=n.rawExpression?null:wi(n.expression);!n.rawExpression&&!Ra(n.expression)&&t.push(i==="invalidDayCount"?um(n.id,"actionValue"):{nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:`${n.type}: please complete the formula.`,target:"actionValue",messageKey:"Validation.CompleteActionFormula",messageParams:{actionType:n.type}})}else(n.type==="SetFieldValue"||n.type==="SetDefaultValue")&&n.valueType==="Lookup"&&!lm(n.lookupValue)&&t.push({nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:`${n.type}: please complete the lookup record.`,target:"actionValue",messageKey:"Validation.EmptyActionLookupValue",messageParams:{actionType:n.type}});if((n.type==="SetFieldValue"||n.type==="SetDefaultValue")&&n.field&&(sm(n.id,n.type,n.field,n.valueType,r,t,{target:"actionValue"}),lI(n.id,n.type,n.type,n.field,n.valueType,r,t,{target:"actionValue"})),n.type==="ShowErrorMessage"&&!n.errorMessage?.trim()&&t.push({nodeId:n.id,kind:"EMPTY_ACTION_MESSAGE",message:"Show error message: please enter an error message.",target:"actionMessage"}),n.type==="Recommendation"){let i=n.applyActions??[];n.recommendationTitle?.trim()||t.push({nodeId:n.id,kind:"EMPTY_RECOMMENDATION_TITLE",message:"Recommendation: please enter a recommendation title.",target:"recommendationTitle"}),n.messageText?.trim()||t.push({nodeId:n.id,kind:"EMPTY_RECOMMENDATION_MESSAGE",message:"Recommendation: please enter a recommendation message.",target:"recommendationMessage"}),i.length===0&&t.push({nodeId:n.id,kind:"RECOMMENDATION_NO_APPLY_ACTION",message:"Recommendation: add at least one action to apply.",target:"node"}),i.forEach(a=>{if(!a.field)t.push({nodeId:n.id,kind:"EMPTY_ACTION_FIELD",message:"Recommendation: a target field is required for each action to apply.",target:"applyActionField",itemId:a.id,messageKey:"Validation.RecommendationApplyField"});else if(a.valueType==="Field")a.valueField||t.push({nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please select a field to copy from.",target:"applyActionValue",itemId:a.id,messageKey:"Validation.RecommendationApplySourceField"});else if(a.valueType==="Expression"){let o=a.rawExpression?null:wi(a.expression);!a.rawExpression&&!Ra(a.expression)&&t.push(o==="invalidDayCount"?um(n.id,"applyActionValue",a.id):{nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the formula.",target:"applyActionValue",itemId:a.id,messageKey:"Validation.RecommendationApplyFormula"})}else a.valueType==="Lookup"?lm(a.lookupValue)||t.push({nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the lookup record.",target:"applyActionValue",itemId:a.id,messageKey:"Validation.RecommendationApplyLookupValue"}):a.valueType==="Clear"||a.value?.trim()||t.push({nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please enter a value for each action to apply.",target:"applyActionValue",itemId:a.id,messageKey:"Validation.RecommendationApplyValue"});a.field&&(sm(n.id,"Recommendation",a.field,a.valueType,r,t,{target:"applyActionValue",itemId:a.id}),lI(n.id,"Recommendation","SetFieldValue",a.field,a.valueType,r,t,{target:"applyActionValue",itemId:a.id}))})}}})}var X9,Y9,Z9,hm=I(()=>{"use strict";jf();Vf();om();ls();X9=new Set(["LockUnlock","ShowErrorMessage","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]);Y9=new Set(["Lookup","Customer","Owner"]);Z9=10});var wI={};zr(wI,{DAY_COUNT_MAX:()=>Oa,DAY_COUNT_MIN:()=>Xf,DEFAULT_DESERIALIZE_LABELS:()=>im,WorkflowJsonMapper:()=>xa,addElseIfInTree:()=>dI,appendToBranch:()=>cI,areFieldKindsCompatible:()=>Nu,attributeTypeToWorkflowType:()=>FD,buildWorkflowEntity:()=>wD,collectUsedFields:()=>gI,createEmptyAction:()=>hI,createEmptyCondition:()=>mm,deserializeWorkflowJson:()=>eI,findNode:()=>dm,findParent:()=>La,getDefaultOperatorForFieldType:()=>oI,getExpressionModelIssue:()=>wi,getOperatorsForFieldType:()=>Su,hasAnyTriggerGeneratingAction:()=>Iu,isDayCountValid:()=>Yf,isExpressionModelComplete:()=>Ra,isOperatorCompatible:()=>sI,isTriggerGeneratingAction:()=>cm,moveBranchItemInTree:()=>mI,operatorNeedsValue:()=>Wn,processTriggerFormIdFromScope:()=>zf,processTriggerScopeFromScope:()=>Gf,removeElseIfInTree:()=>fI,removeNodeFromTree:()=>pm,serializeToWorkflowJson:()=>ZD,supportsClearForActionType:()=>yu,updateActionInTree:()=>Du,updateConditionInTree:()=>Hn,validateBusinessRule:()=>yI});var AI=I(()=>{"use strict";Vf();AD();am();am();hm();hm();om();ls();ls();});var gm=v(_u=>{"use strict";Object.defineProperty(_u,"__esModule",{value:!0});_u.cloneJson=void 0;function n8(e){return JSON.parse(JSON.stringify(e))}_u.cloneJson=n8});var RI=v(jn=>{"use strict";Object.defineProperty(jn,"__esModule",{value:!0});jn.BUSINESS_RULE_NULL_GUID=jn.businessRuleRegistration=jn.BusinessRuleAdapter=void 0;var CI=pt(),ds=(AI(),br(wI)),EI=lr(),SI=te(),i8=gm(),xr=Fr(),a8=kc(),o8=pt();function s8(e){return _I((0,i8.cloneJson)(e))}function _I(e){var t,r;let n=i=>(i??[]).map(a=>l8(a)?_I(a):a);return{...e,logic:(t=e.logic)!==null&&t!==void 0?t:"AND",clauses:(r=e.clauses)!==null&&r!==void 0?r:[],trueBranch:n(e.trueBranch),falseBranch:n(e.falseBranch)}}function l8(e){return Object.prototype.hasOwnProperty.call(e,"type")?!1:Object.prototype.hasOwnProperty.call(e,"clauses")||Object.prototype.hasOwnProperty.call(e,"trueBranch")||Object.prototype.hasOwnProperty.call(e,"falseBranch")||Object.prototype.hasOwnProperty.call(e,"logic")}function u8(e){var t;if(e===null||typeof e!="object"||Array.isArray(e))throw new SI.ValidationError("businessRule","(new)","/rootCondition",`rootCondition must be a condition object or null, got ${Array.isArray(e)?"array":typeof e}`);if(Object.prototype.hasOwnProperty.call(e,"type"))throw new SI.ValidationError("businessRule",(t=e.id)!==null&&t!==void 0?t:"(new)","/rootCondition","rootCondition looks like an ACTION (it carries 'type'), but it must be a condition. Wrap the action in a condition's trueBranch instead \u2014 a bare action would compile to an empty rule that saves successfully and does nothing.");return e}var c8="00000000-0000-0000-0000-000000000000";jn.BUSINESS_RULE_NULL_GUID=c8;var d8=new Set(["Recommendation","LockUnlock","ShowErrorMessage","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]),p8=["ruleId","name","description","entityLogicalName","scope","status","rootCondition"],f8=["kind","id","displayName","logic","clauses","trueBranch","falseBranch"],m8=["id","field","fieldDisplayName","operator","valueType","value","valueField","lookupValue","expression","rawExpression","valueWorkflowType"];function hr(e,t){return e===void 0?t:{...e,...t}}var Ai=["kind","id","type","displayName","field","stepName","stepLabels"],NI=["valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression"],h8={Recommendation:[...Ai,"recommendationTitle","messageText","acceptanceText","applyActions","recommendationActionStepMeta"],LockUnlock:[...Ai,"lock"],ShowErrorMessage:[...Ai,"errorMessage","messageLevel","messageActionSteps"],SetFieldValue:[...Ai,...NI],SetDefaultValue:[...Ai,...NI],SetBusinessRequired:[...Ai,"required"],SetVisibility:[...Ai,"visible"]};function j(e,t){return t===void 0?{}:{[e]:t}}function TI(e){var t;return e===void 0?void 0:{...e,label:(t=e.label)!==null&&t!==void 0?t:""}}function vm(e){return{valueType:e.valueType,...j("valueWorkflowType",e.valueWorkflowType),...j("value",e.value),...j("valueField",e.valueField),...j("lookupValue",TI(e.lookupValue)),...j("expression",e.expression),...j("rawExpression",e.rawExpression)}}function PI(e,t){let r=new Set(t),n={};for(let[i,a]of Object.entries(e))r.has(i)||a!==void 0&&(n[i]=a);return Object.keys(n).length>0?n:void 0}var g8=["id","field","valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression","stepName","displayName"];function v8(e){return hr(e.bag,{id:e.id,field:e.field,...vm(e),...j("stepName",e.stepName),...j("displayName",e.displayName)})}function y8(e){let t=PI(e,g8);return{id:e.id,field:e.field,valueType:e.valueType,...j("valueWorkflowType",e.valueWorkflowType),...j("value",e.value),...j("valueField",e.valueField),...j("lookupValue",e.lookupValue),...j("expression",e.expression),...j("rawExpression",e.rawExpression),...j("stepName",e.stepName),...j("displayName",e.displayName),...j("bag",t)}}function DI(e){return{valueType:e.valueType,...j("valueWorkflowType",e.valueWorkflowType),...j("value",e.value),...j("valueField",e.valueField),...j("lookupValue",e.lookupValue),...j("expression",e.expression),...j("rawExpression",e.rawExpression)}}function II(e){throw new Error(`Unsupported business-rule action type: ${e.type}`)}var b8=new Set(["INVALID_CLEAR_FOR_FIELD","INVALID_VALUE_TYPE_FOR_FIELD","CLAUSE_VALUE_TOO_LONG","ACTION_VALUE_TOO_LONG"]),w8=new Set,A8="INVALID_CLEAR_FOR_FIELD";function C8(e){let t=n=>{var i;return(0,xr.isJsonObject)(n)&&(n.label===""||n.label===void 0)?{...n,label:String((i=n.id)!==null&&i!==void 0?i:"")}:n},r=n=>{if(!(0,xr.isJsonObject)(n))return n;let i={...n};"lookupValue"in i&&(i.lookupValue=t(i.lookupValue)),Array.isArray(i.applyActions)&&(i.applyActions=i.applyActions.map(r));for(let a of["clauses","trueBranch","falseBranch"])Array.isArray(i[a])&&(i[a]=i[a].map(r));return i};return r(e)}var Tu=class{toArtifact(t){let r=this.residualBag(t,p8),n={id:t.ruleId,name:t.name,description:t.description,entityLogicalName:t.entityLogicalName,scope:t.scope,status:t.status,rootCondition:t.rootCondition?this.conditionToJson(t.rootCondition):null};return r&&(n.bag=r),n}fromArtifact(t){let r=t.rootCondition?this.conditionFromJson(t.rootCondition):null;return hr(t.bag,{ruleId:t.id,name:t.name,description:t.description,entityLogicalName:t.entityLogicalName,scope:t.scope,status:t.status,rootCondition:r})}fromApiResponse(t){var r;let n=t??{},i={...(r=n.Entity)!==null&&r!==void 0?r:{},wfomJson:n.WfomJson},a=(0,ds.deserializeWorkflowJson)(i);return this.toArtifact(a)}toApiPayload(t){var r;let n=this.fromArtifact(t);n.wfomRoot&&(n.wfomRoot={...n.wfomRoot,name:t.name,title:t.name,primaryEntityName:t.entityLogicalName||n.wfomRoot.primaryEntityName});let i=(0,ds.serializeToWorkflowJson)(n),a=(r=n.ruleId)!==null&&r!==void 0?r:(0,CI.newId)();return{Entity:this.buildWorkflowEntity(n,a),WfomJson:i,status:t.status}}createDefault(t){var r,n,i,a,o,s;let l={ruleId:(r=t.id)!==null&&r!==void 0?r:null,name:(n=t.name)!==null&&n!==void 0?n:"New business rule",description:(i=t.description)!==null&&i!==void 0?i:"",entityLogicalName:(a=t.entityLogicalName)!==null&&a!==void 0?a:"",scope:(o=t.scope)!==null&&o!==void 0?o:"Entity",status:(s=t.status)!==null&&s!==void 0?s:"Draft",rootCondition:t.rootCondition===void 0?(0,ds.createEmptyCondition)():t.rootCondition===null?null:this.conditionFromJson(s8(u8(t.rootCondition)))},u=this.toArtifact(l);return u.id||(u.id=(0,CI.newId)()),u}assignMissingIds(t){return(0,o8.assignMissingIds)(t)}validate(t){let r=[],n=t.rootCondition;return n==null?r:(0,xr.isJsonObject)(n)?(OI(n,"/rootCondition",r),r):(r.push((0,xr.issue)("/rootCondition","condition-must-be-object",`rootCondition must be a JSON object or null, got ${typeof n}`)),r)}semanticIssues(t,r=[]){let n;try{n=this.fromArtifact(t)}catch(o){return[(0,xr.issue)("/rootCondition","rule-not-representable",o instanceof Error?o.message:String(o))]}let i=n.rootCondition===null?null:C8(n.rootCondition),a;return r.length===0?a=b8:r.some(o=>o.requiredLevel!==void 0)?a=w8:a=new Set([A8]),(0,ds.validateBusinessRule)(i,r).filter(o=>!a.has(o.kind)).map(o=>(0,xr.issue)(`/rootCondition (${o.nodeId})`,`business-rule-${o.kind}`,o.message))}issuesBlockingPush(t,r=[],n){return this.semanticIssues(t,r)}residualBag(t,r){return PI(t,r)}buildWorkflowEntity(t,r){return(0,ds.buildWorkflowEntity)(t,r)}conditionToJson(t){let r=this.residualBag(t,f8),n={id:t.id,displayName:t.displayName,logic:t.logic,clauses:t.clauses.map(i=>this.clauseToJson(i)),trueBranch:t.trueBranch.map(i=>this.branchItemToJson(i)),falseBranch:t.falseBranch.map(i=>this.branchItemToJson(i))};return r&&(n.bag=r),n}clauseToJson(t){let r=this.residualBag(t,m8),n={id:t.id,field:t.field,fieldDisplayName:t.fieldDisplayName,operator:t.operator,valueType:t.valueType,...t.value!==void 0?{value:t.value}:{},...t.valueField!==void 0?{valueField:t.valueField}:{},...t.lookupValue!==void 0?{lookupValue:t.lookupValue}:{},...t.expression!==void 0?{expression:t.expression}:{},...t.rawExpression!==void 0?{rawExpression:t.rawExpression}:{},...t.valueWorkflowType!==void 0?{valueWorkflowType:t.valueWorkflowType}:{}};return r&&(n.bag=r),n}branchItemToJson(t){return t.kind==="condition"?this.conditionToJson(t):this.actionToJson(t)}actionToJson(t){let r=this.residualBag(t,h8[t.type]),n={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...j("stepName",t.stepName),...j("stepLabels",t.stepLabels),...j("bag",r)};switch(t.type){case"Recommendation":return{...n,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...j("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(y8),...j("recommendationActionStepMeta",t.recommendationActionStepMeta)};case"LockUnlock":return{...n,type:"LockUnlock",lock:t.lock};case"ShowErrorMessage":return{...n,type:"ShowErrorMessage",errorMessage:t.errorMessage,...j("messageLevel",t.messageLevel),...j("messageActionSteps",t.messageActionSteps)};case"SetFieldValue":return{...n,type:"SetFieldValue",...DI(t)};case"SetDefaultValue":return{...n,type:"SetDefaultValue",...DI(t)};case"SetBusinessRequired":return{...n,type:"SetBusinessRequired",required:t.required};case"SetVisibility":return{...n,type:"SetVisibility",visible:t.visible};default:return II(t)}}conditionFromJson(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:{};return hr(n,{kind:"condition",isCollapsed:typeof n.isCollapsed=="boolean"?n.isCollapsed:!1,id:t.id,displayName:t.displayName,logic:t.logic,clauses:t.clauses.map(i=>this.clauseFromJson(i)),trueBranch:t.trueBranch.map(i=>this.branchItemFromJson(i)),falseBranch:t.falseBranch.map(i=>this.branchItemFromJson(i))})}clauseFromJson(t){var r;return hr(t.bag,{id:t.id,field:t.field,fieldDisplayName:(r=t.fieldDisplayName)!==null&&r!==void 0?r:t.field,operator:t.operator,valueType:t.valueType,...j("value",t.value),...j("valueField",t.valueField),...j("lookupValue",TI(t.lookupValue)),...j("expression",t.expression),...j("rawExpression",t.rawExpression),...j("valueWorkflowType",t.valueWorkflowType)})}branchItemFromJson(t){return this.isConditionJson(t)?this.conditionFromJson(t):this.actionFromJson(t)}actionFromJson(t){if(!d8.has(t.type))throw new Error(`Unsupported business-rule action type: ${t.type}`);S8(t);let r={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...j("stepName",t.stepName),...j("stepLabels",t.stepLabels)};switch(t.type){case"Recommendation":return hr(t.bag,{...r,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...j("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(v8),...j("recommendationActionStepMeta",t.recommendationActionStepMeta)});case"LockUnlock":return hr(t.bag,{...r,type:"LockUnlock",lock:t.lock});case"ShowErrorMessage":return hr(t.bag,{...r,type:"ShowErrorMessage",errorMessage:t.errorMessage,...j("messageLevel",t.messageLevel),...j("messageActionSteps",t.messageActionSteps)});case"SetFieldValue":return hr(t.bag,{...r,type:"SetFieldValue",...vm(t)});case"SetDefaultValue":return hr(t.bag,{...r,type:"SetDefaultValue",...vm(t)});case"SetBusinessRequired":return hr(t.bag,{...r,type:"SetBusinessRequired",required:t.required});case"SetVisibility":return hr(t.bag,{...r,type:"SetVisibility",visible:t.visible});default:return II(t)}}isConditionJson(t){return Object.prototype.hasOwnProperty.call(t,"clauses")&&Object.prototype.hasOwnProperty.call(t,"logic")&&!Object.prototype.hasOwnProperty.call(t,"type")}};jn.BusinessRuleAdapter=Tu;function OI(e,t,r){(0,xr.optionalEnum)(e,"logic",["AND","OR"],t,"condition-logic-invalid",r),(0,xr.childObjects)(e,"clauses",t,"clause",r);for(let n of["trueBranch","falseBranch"])(0,xr.childObjects)(e,n,t,"branchItem",r).forEach(({node:a,index:o})=>{"clauses"in a||"trueBranch"in a||"falseBranch"in a?OI(a,`${t}/${n}/${o}`,r):E8(a,`${t}/${n}/${o}`,r)})}function E8(e,t,r){e.type==="SetDefaultValue"&&e.valueType==="Clear"&&r.push((0,xr.issue)(`${t}/valueType`,"clear-only-set-field-value","Clear is only supported for SetFieldValue actions."))}function S8(e){if(e.type==="SetDefaultValue"&&e.valueType==="Clear")throw new Error("Clear is only supported for SetFieldValue actions.")}function N8(){return{adapter:new Tu,api:a8.businessRuleApi,publish:(e,t,r)=>(0,EI.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,EI.boundEntityPublishScope)(t)}}jn.businessRuleRegistration=N8});var JI=v(Jn=>{"use strict";Object.defineProperty(Jn,"__esModule",{value:!0});Jn.appRegistration=Jn.AppAdapter=Jn.HEADER_NAV_BOOLEAN_RULE=void 0;var ln=Fr(),He=In(),fs=ri(),D8=lr(),I8=ml(),ym=cl(),bm=Tn(),_8=pt(),T8=ae(),VI=Ri(),GI=te(),zI=pl();Object.defineProperty(Jn,"HEADER_NAV_BOOLEAN_RULE",{enumerable:!0,get:function(){return zI.HEADER_NAV_BOOLEAN_RULE}});var Fu="7.0.0.0",FI=`<SiteMap IntroducedVersion="${Fu}"></SiteMap>`,xI="/_imgs/imagestrips/transparent_spacer.gif",LI="/_imgs/TableIconsFluentV9/document_one_page_sparkle.svg",P8=["Entity","Url","DefaultDashboard","Page","GenPageId"],ps="sitemapId",kI="sitemapName",O8="sitemapNameUnique",MI="aiDescription",UI="[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}",R8=new RegExp(`^(?:\\{${UI}\\}|${UI})$`);function BI(e,t){if(!R8.test(e.trim()))throw new GI.ValidationError("app",t,[{pointer:"/sitemapId",rule:"app-sitemapid-guid",message:`sitemapId must be a GUID; received '${e}'.`}]);return e.trim()}function $I(e,t,r){if(e===void 0)return r;if(typeof e!="boolean")throw new GI.ValidationError("app",t,[WI(e)]);return e}function WI(e){return(0,ln.issue)("/headerAndNavigationRefresh",zI.HEADER_NAV_BOOLEAN_RULE,`headerAndNavigationRefresh must be a boolean, got ${typeof e}`)}function F8(e){let t=n=>{let i=e[n];return typeof i=="string"&&i.trim()!==""?i.trim():void 0},r=n=>{let i=t(n);if(i!==void 0)try{return(0,T8.normalizeGuid)(i,n)}catch{return}};switch(e.type){case"Entity":return t("entity")&&`Entity:${t("entity").toLowerCase()}`;case"URL":return t("url")&&`URL:${t("url").toLowerCase()}`;case"DashBoard":return r("dashboardId")&&`DashBoard:${r("dashboardId")}`;case"CustomPage":return t("page")&&`CustomPage:${t("page").toLowerCase()}`;case"GenPage":return r("genPageId")&&`GenPage:${r("genPageId")}`;default:return}}var xu=class{constructor(t=VI.DEFAULT_LCID){this.lcid=t}toArtifact(t){let{bag:r,modeledEls:n}=Pu(t,"Area");return{id:"",name:"",uniqueName:"",description:"",siteMap:{areas:n.map(i=>this.areaToJson(i)),bag:r},bag:(0,He.emptyBag)()}}fromArtifact(t){(0,bm.installDomShim)();let r=this.assignMissingIds(JSON.parse(JSON.stringify(t))),n=new DOMParser().parseFromString("<root/>","text/xml"),i=this.rootToRaw(r);return(0,He.rebuildRaw)(i,(0,fs.domEngine)(n),null)}fromApiResponse(t){var r,n,i,a,o,s,l,u,c,d,p;(0,bm.installDomShim)();let f=t??{},m=(r=f.$sitemap)!==null&&r!==void 0?r:f,g=(0,fs.parseXmlRoot)((n=m.sitemapxml)!==null&&n!==void 0?n:FI,FI),y=this.toArtifact(g);return y.id=(i=f.appmoduleid)!==null&&i!==void 0?i:"",y.name=(a=f.name)!==null&&a!==void 0?a:"",y.uniqueName=(o=f.uniquename)!==null&&o!==void 0?o:"",y.description=(s=f.description)!==null&&s!==void 0?s:"",f.aiappdescription&&(y.aiDescription=f.aiappdescription),y.bag={a:[[ps,(u=(l=m.sitemapid)!==null&&l!==void 0?l:f._sitemapid_value)!==null&&u!==void 0?u:""],[kI,(c=m.sitemapname)!==null&&c!==void 0?c:""],[O8,(d=m.sitemapnameunique)!==null&&d!==void 0?d:""],[MI,(p=f.aiappdescription)!==null&&p!==void 0?p:""]],c:[]},y}toApiPayload(t,r){var n,i,a,o,s,l,u,c,d,p,f,m,g,y;(0,bm.installDomShim)();let A=(0,fs.serializeNode)(this.fromArtifact(t)),D=[],F=[];for(let q of(i=(n=t.siteMap)===null||n===void 0?void 0:n.areas)!==null&&i!==void 0?i:[])for(let B of(a=q.groups)!==null&&a!==void 0?a:[])for(let L of(o=B.subAreas)!==null&&o!==void 0?o:[])L.type==="Entity"&&L.entity?D.push(L.entity):L.type==="DashBoard"&&L.dashboardId&&F.push(L.dashboardId);let _=(s=t.bag)!==null&&s!==void 0?s:(0,He.emptyBag)();return{sitemapId:Am(_,ps)||(t.sitemapId?BI(t.sitemapId,t.id):""),sitemapxml:A,sitemapname:Am(_,kI)||t.name,appModuleId:t.id,appModuleName:t.name,appModuleDescription:t.description,...t.aiDescription!==void 0&&t.aiDescription!==(r?r.aiDescription:Am(_,MI))?{appModuleAiDescription:t.aiDescription}:{},appModuleUniqueName:t.uniqueName,...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},...t.headerAndNavigationRefresh===void 0?{}:{appSettings:{[ym.HEADER_AND_NAVIGATION_REFRESH]:$I(t.headerAndNavigationRefresh,(l=t.id)!==null&&l!==void 0?l:"(unknown)",!0)?ym.APP_SETTING_ON:ym.APP_SETTING_OFF}},...typeof t.published=="boolean"?{published:t.published}:{},entities:D,components:{forms:(c=(u=t.components)===null||u===void 0?void 0:u.forms)!==null&&c!==void 0?c:[],views:(p=(d=t.components)===null||d===void 0?void 0:d.views)!==null&&p!==void 0?p:[],charts:(m=(f=t.components)===null||f===void 0?void 0:f.charts)!==null&&m!==void 0?m:[],dashboards:[...(y=(g=t.components)===null||g===void 0?void 0:g.dashboards)!==null&&y!==void 0?y:[],...F]}}}createDefault(t){var r,n,i,a,o,s;let l=!((r=t.siteMap)===null||r===void 0)&&r.areas&&t.siteMap.areas.length>0?t.siteMap.areas:[{id:"",title:"Area",groups:[{id:"",title:"Group",subAreas:[]}]}],u=(n=t.id)!==null&&n!==void 0?n:(0,_8.newId)();return{id:u,name:(i=t.name)!==null&&i!==void 0?i:"New App",uniqueName:(a=t.uniqueName)!==null&&a!==void 0?a:"",description:(o=t.description)!==null&&o!==void 0?o:"",...t.aiDescription?{aiDescription:t.aiDescription}:{},siteMap:{areas:l},...t.sitemapId?{sitemapId:BI(t.sitemapId,u)}:{},...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},headerAndNavigationRefresh:$I(t.headerAndNavigationRefresh,(s=t.id)!==null&&s!==void 0?s:"(new)",!0),...typeof t.published=="boolean"?{published:t.published}:{},...t.components?{components:t.components}:{}}}assignMissingIds(t){let r=t;if(!r||typeof r!="object")return t;let n=r.siteMap;return n&&Array.isArray(n.areas)?n.areas.forEach(Em):Array.isArray(r.areas)?r.areas.forEach(Em):Array.isArray(r.groups)?Em(r):Array.isArray(r.subAreas)?jI(r):"type"in r&&Lu(r,"subarea"),t}validate(t){let r=[],n=t.published;n!==void 0&&typeof n!="boolean"&&r.push((0,ln.issue)("/published","published-must-be-boolean",`published must be a boolean, got ${typeof n}`));let i=t.siteMap,a=t.headerAndNavigationRefresh;if(a!==void 0&&typeof a!="boolean"&&r.push(WI(a)),i==null)return r;if(!(0,ln.isJsonObject)(i))return r.push((0,ln.issue)("/siteMap","sitemap-must-be-object",`siteMap must be a JSON object, got ${typeof i}`)),r;let o=(0,ln.childObjects)(i,"areas","/siteMap","area",r),s=new Map;return o.forEach(({node:l,index:u})=>{let c=`/siteMap/areas/${u}`;(0,ln.childObjects)(l,"groups",c,"group",r).forEach(({node:p,index:f})=>{let m=`${c}/groups/${f}`;(0,ln.childObjects)(p,"subAreas",m,"subArea",r).forEach(({node:y,index:A})=>{let D=`${m}/subAreas/${A}`;(0,ln.optionalEnum)(y,"type",["Entity","URL","DashBoard","CustomPage","GenPage"],D,"subarea-type-invalid",r);let F=F8(y);if(!F)return;let _=s.get(F);if(_===void 0){s.set(F,D);return}r.push((0,ln.issue)(D,"subarea-duplicate-target",`the sitemap already navigates to this target at ${_}; a duplicate SubArea would pin it twice and a single removeElement would leave one behind`))})})}),r}applyServerIdentity(t,r){let n=r[ps];if(!n)return;t.bag||(t.bag=(0,He.emptyBag)());let i=t.bag.a.find(a=>a[0]===ps);i?i[1]=n:t.bag.a.push([ps,n])}areaToJson(t){var r;let{bag:n,modeledEls:i}=Pu(t,"Group"),a={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:wm(t,this.lcid),groups:i.map(l=>this.groupToJson(l)),bag:n},o=t.getAttribute("Icon");o&&(a.icon=o);let s=t.getAttribute("VectorIcon");return s&&(a.vectorIcon=s),a}groupToJson(t){var r;let{bag:n,modeledEls:i}=Pu(t,"SubArea");return{id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:wm(t,this.lcid),subAreas:i.map(a=>this.subAreaToJson(a)),bag:n}}subAreaToJson(t){var r;let{bag:n}=Pu(t,null),i=x8(t),a={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",type:i,title:wm(t,this.lcid),bag:n};if(i==="Entity"){let l=t.getAttribute("Entity");l&&(a.entity=l)}else if(i==="DashBoard"){let l=t.getAttribute("DefaultDashboard");l&&(a.dashboardId=l);let u=t.getAttribute("Url");u&&(a.dashboardUrl=u)}else if(i==="CustomPage"){let l=t.getAttribute("Page");l&&(a.page=l)}else if(i==="GenPage"){let l=t.getAttribute("GenPageId");l&&(a.genPageId=l)}else{let l=t.getAttribute("Url");l&&(a.url=l)}let o=t.getAttribute("Icon");o&&o!==xI&&(a.icon=o);let s=t.getAttribute("VectorIcon");return s&&(a.vectorIcon=s),a}rootToRaw(t){var r,n,i,a;let o=(n=(r=t.siteMap)===null||r===void 0?void 0:r.bag)!==null&&n!==void 0?n:(0,He.emptyBag)(),l=Ou(o)?[["IntroducedVersion",Fu]]:[],u=((a=(i=t.siteMap)===null||i===void 0?void 0:i.areas)!==null&&a!==void 0?a:[]).map(c=>this.areaToRaw(c));return{n:"SiteMap",a:(0,He.mergeAttrs)(o.a,l),c:(0,He.spliceChildren)(o.c,u)}}areaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,He.emptyBag)(),i=Ou(n),a=[],o=[];t.id&&a.push(["Id",t.id]),i&&a.push(["ShowGroups","true"],["ResourceId","SitemapDesigner.NewTitle"],["DescriptionResourceId","SitemapDesigner.NewTitle"],["IntroducedVersion",Fu]),t.icon!==void 0?a.push(["Icon",t.icon]):Ru(n.a,"Icon")&&o.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):Ru(n.a,"VectorIcon")&&o.push("VectorIcon");let s=t.groups.map(u=>this.groupToRaw(u)),l=Cm((0,He.spliceChildren)(n.c,s),t.title,i,this.lcid);return{n:"Area",a:(0,He.mergeAttrs)(n.a,a,o),c:l}}groupToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,He.emptyBag)(),i=Ou(n),a=[];t.id&&a.push(["Id",t.id]),i&&a.push(["ResourceId","SitemapDesigner.NewGroup"],["DescriptionResourceId","SitemapDesigner.NewGroup"],["ToolTipResourseId","SitemapDesigner.Unknown"],["IntroducedVersion",Fu],["IsProfile","false"]);let o=t.subAreas.map(l=>this.subAreaToRaw(l)),s=Cm((0,He.spliceChildren)(n.c,o),t.title,i,this.lcid);return{n:"Group",a:(0,He.mergeAttrs)(n.a,a),c:s}}subAreaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,He.emptyBag)(),i=Ou(n),a=k8(n.a,t.type),o=[],s=[];t.id&&o.push(["Id",t.id]),U8(o,t),i?(o.push(["ResourceId","SitemapDesigner.NewSubArea"],["Client","All,Outlook,OutlookLaptopClient,OutlookWorkstationClient,Web"],["Sku","All,OnPremise,Live,SPLA"],["AvailableOffline","true"],["PassParams","false"]),t.icon&&o.push(["Icon",t.icon])):t.icon!==void 0?o.push(["Icon",t.icon]):Ru(a,"Icon",xI)&&s.push("Icon"),t.vectorIcon!==void 0?o.push(["VectorIcon",t.vectorIcon]):Ru(a,"VectorIcon")?t.type==="GenPage"?o.push(["VectorIcon",LI]):s.push("VectorIcon"):t.type==="GenPage"&&!L8(a,"VectorIcon")&&o.push(["VectorIcon",LI]);let l=Cm((0,He.spliceChildren)(n.c,[]),t.title,i,this.lcid);return{n:"SubArea",a:(0,He.mergeAttrs)(a,o,s),c:l}}};Jn.AppAdapter=xu;function Pu(e,t){let r=(0,fs.nodeLikeFromDom)(e).getAllProperties().map(s=>[s.key,s.value]),n=[],i=[],a=e.childNodes,o=0;for(let s=0;s<a.length;s+=1){let l=a[s];l.nodeType!==1&&l.nodeType!==3||(l.nodeType===1&&t!==null&&l.tagName===t?i.push(l):n.push({i:o,node:(0,He.rawFromNode)((0,fs.nodeLikeFromDom)(l))}),o+=1)}return{bag:{a:r,c:n},modeledEls:i}}function qI(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let a=n[i];a.nodeType===1&&a.tagName===t&&r.push(a)}return r}function wm(e,t){var r;let n=qI(e,"Titles")[0];if(!n)return"";let a=qI(n,"Title").find(o=>o.getAttribute("LCID")===String(t));return a&&(r=a.getAttribute("Title"))!==null&&r!==void 0?r:""}function x8(e){return e.getAttribute("GenPageId")?"GenPage":e.getAttribute("Entity")?"Entity":e.getAttribute("Page")?"CustomPage":e.getAttribute("DefaultDashboard")?"DashBoard":"URL"}function Ou(e){return e.a.length===0&&e.c.length===0}function L8(e,t){return e.some(([r])=>r===t)}function Ru(e,t,r){let n=e.find(([a])=>a===t),i=n?.[1];return!!i&&i!==r}function Am(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function k8(e,t){let r=M8(t);return e.filter(([n])=>!P8.includes(n)||r.has(n)).map(n=>[n[0],n[1]])}function M8(e){switch(e){case"Entity":return new Set(["Entity"]);case"URL":return new Set(["Url"]);case"DashBoard":return new Set(["DefaultDashboard","Url"]);case"CustomPage":return new Set(["Page"]);case"GenPage":return new Set(["GenPageId"]);default:return new Set}}function U8(e,t){var r,n,i,a,o;switch(t.type){case"Entity":e.push(["Entity",(r=t.entity)!==null&&r!==void 0?r:""]);break;case"URL":e.push(["Url",(n=t.url)!==null&&n!==void 0?n:""]);break;case"DashBoard":e.push(["DefaultDashboard",(i=t.dashboardId)!==null&&i!==void 0?i:""]),t.dashboardUrl!==void 0&&e.push(["Url",t.dashboardUrl]);break;case"CustomPage":e.push(["Page",(a=t.page)!==null&&a!==void 0?a:""]);break;case"GenPage":e.push(["GenPageId",(o=t.genPageId)!==null&&o!==void 0?o:""]);break;default:break}}function Cm(e,t,r,n){if(!t)return e;let i=e.findIndex(a=>a.n==="Titles");if(i>=0){let a=e.slice();return a[i]=B8(e[i],t,n),a}return r?[$8(t,n),...e]:e}function B8(e,t,r){let n=!1,i=e.c.map(a=>!n&&a.n==="Title"&&q8(a,"LCID")===String(r)?(n=!0,{n:a.n,a:(0,He.mergeAttrs)(a.a,[["Title",t]]),c:a.c}):a);return n||i.unshift(HI(t,r)),{n:e.n,a:e.a.map(a=>[a[0],a[1]]),c:i}}function $8(e,t){return{n:"Titles",a:[],c:[HI(e,t)]}}function HI(e,t){return{n:"Title",a:[["LCID",String(t)],["Title",e]],c:[]}}function q8(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function V8(e){let t="0123456789abcdef",r="";for(let n=0;n<e;n+=1)r+=t[Math.floor(Math.random()*t.length)];return r}function Lu(e,t){e&&(typeof e.id!="string"||e.id.length===0)&&(e.id=`${t}_${V8(8)}`)}function Em(e){var t;Lu(e,"area");for(let r of(t=e.groups)!==null&&t!==void 0?t:[])jI(r)}function jI(e){var t;Lu(e,"group");for(let r of(t=e.subAreas)!==null&&t!==void 0?t:[])Lu(r,"subarea")}function G8(e=VI.DEFAULT_LCID){return{adapter:new xu(e),api:I8.appApi,languageSensitive:!0,publish:(t,r)=>(0,D8.publishAppModule)(t,r),publishScope:t=>({envelope:"appmodule",targetIds:[t]})}}Jn.appRegistration=G8});var QI={};zr(QI,{ActionType:()=>Nm,AppActionOrigin:()=>Fm,AppActionVisibilityType:()=>Rm,ButtonType:()=>Im,CannotUpdateAppActionColumns:()=>z8,Context:()=>Tm,IconType:()=>Dm,Location:()=>_m,OnClickEventType:()=>Om,Scope:()=>Pm,VisibilityType:()=>Sm});var Sm,Nm,Dm,Im,_m,Tm,Pm,Om,Rm,Fm,z8,KI=I(()=>{"use strict";(function(e){e[e.NotSupported=0]="NotSupported",e[e.Show=1]="Show",e[e.ClassicRules=2]="ClassicRules",e[e.Expression=3]="Expression"})(Sm||(Sm={}));(function(e){e[e.NotSupported=0]="NotSupported",e[e.None=1]="None",e[e.JavaScript=2]="JavaScript",e[e.Expression=3]="Expression"})(Nm||(Nm={}));(function(e){e[e.NoIcon=0]="NoIcon",e[e.UseIcon=1]="UseIcon",e[e.UseWebResource=2]="UseWebResource"})(Dm||(Dm={}));(function(e){e[e.Standard=0]="Standard",e[e.Dropdown=1]="Dropdown",e[e.Split=2]="Split",e[e.Group=3]="Group"})(Im||(Im={}));(function(e){e[e.Form=0]="Form",e[e.HomePageGrid=1]="HomePageGrid",e[e.SubGridStandard=2]="SubGridStandard",e[e.SubGridAssociated=3]="SubGridAssociated",e[e.QuickForm=4]="QuickForm",e[e.Global=5]="Global",e[e.Dashboard=6]="Dashboard"})(_m||(_m={}));(function(e){e[e.All=0]="All",e[e.Entity=1]="Entity"})(Tm||(Tm={}));(function(e){e[e.App=0]="App",e[e.Entity=1]="Entity",e[e.Global=2]="Global"})(Pm||(Pm={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.JavaScript=2]="JavaScript"})(Om||(Om={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.ClassicRules=2]="ClassicRules"})(Rm||(Rm={}));(function(e){e[e.Default=0]="Default",e[e.Migrated=1]="Migrated",e[e.MigratedClone=2]="MigratedClone"})(Fm||(Fm={}));z8=["appactionid","appmoduleid","context","contextvalue","location","name","type","uniquename","isdisabled","origin"]});var e2=v(Mu=>{"use strict";Object.defineProperty(Mu,"__esModule",{value:!0});Mu.commandApi=void 0;var XI=qt(),gr=be(),ZI=te(),Kt=ae(),W8="OnClickEventJavaScriptWebResourceId($select=name,webresourceid),IconWebResourceId($select=name,webresourceid)";async function ku(e,t){let r=`/EntityDefinitions(LogicalName='${(0,Kt.odataPathLiteral)(t)}')${(0,Kt.odataQuery)([["$select","MetadataId"]])}`,i=(0,gr.ensureSuccess)(await e.get(r),e.apiUrl(r)).body,a=i?.MetadataId;return a?(0,Kt.normalizeGuid)(a,"entityMetadataId"):""}Mu.commandApi={async get(e,t){let r=t,n=await ku(e,r),i=n?`_contextentity_value eq ${n}`:`contextvalue eq '${(0,Kt.odataLiteral)(r)}'`,a=`/appactions${(0,Kt.odataQuery)([["$expand",W8],["$filter",i]])}`,o,s=await(0,XI.collectPages)(e,a,"fetchArtifact('command')",c=>{o=c}),l={entityLogicalName:r,entityMetadataId:n,appActions:s},u={};for(let c of s){let d=typeof c.appactionid=="string"?c.appactionid:void 0;if(d){let p=c["@odata.etag"];u[(0,Kt.normalizeGuid)(d,"appactionid")]=typeof p=="string"?p:null}}return{raw:l,etag:o?(0,gr.readEtag)(o):null,memberEtags:u}},async list(e,t){let r=t?.entityLogicalName;return r?[{type:"command",id:r,name:`${r} commands`,entityLogicalName:r,isDirty:!1}]:[]},async create(e,t){let r=t,n=r.entityMetadataId||await ku(e,r.entityLogicalName);return YI(e,{...r,entityMetadataId:n},!1)},async update(e,t,r,n,i){let a=r,o=a.entityMetadataId||await ku(e,a.entityLogicalName);return YI(e,{...a,entityMetadataId:o},!0,i)},async delete(e,t){let r=await ku(e,t),n=r?`_contextentity_value eq ${r}`:`contextvalue eq '${(0,Kt.odataLiteral)(t)}'`,i=`/appactions${(0,Kt.odataQuery)([["$select","appactionid"],["$filter",n]])}`,a=await(0,XI.collectPages)(e,i,"deleteArtifact('command')");for(let o of a)o.appactionid&&await(0,gr.deleteRecord)(e,"appactions",o.appactionid)}};async function YI(e,t,r,n){let i=t.entityMetadataId?(0,Kt.normalizeGuid)(t.entityMetadataId,"entityMetadataId"):"",a=j8(t.rows),o={};try{await H8(e,t,a,i,r,n,o)}catch(s){throw(0,ZI.withPartialTokens)(s,{memberEtags:o})}return{id:t.entityLogicalName,etag:null,memberEtags:o}}async function H8(e,t,r,n,i,a,o){var s,l,u;for(let c of r)if(i&&c.exists){let d=(0,Kt.normalizeGuid)(c.appactionid,"id"),p=(s=a?.[d])!==null&&s!==void 0?s:c.etag,f=(0,gr.echoWrite)("appactionid",p?{"If-Match":p}:void 0),m=`/appactions(${d})${f.query}`,g=(0,gr.ensureSuccess)(await e.patch(m,c.body,f.options),e.apiUrl(m));o[d]=(0,gr.readEtag)(g)}else{let d=(0,gr.echoWrite)("appactionid"),p=`/appactions${d.query}`,f={...c.body};if(f["[email protected]"]===void 0){if(!n)throw new ZI.SdkError("COMMAND_CONTEXT_ENTITY_UNRESOLVED",`Cannot create app action '${c.appactionid}' for entity '${t.entityLogicalName}': the entity MetadataId could not be resolved, so the required ContextEntity bind cannot be set. A row written without it is created but is permanently unreadable \u2014 commandApi.get filters on _contextentity_value. Verify the entity logical name exists and is readable, then retry.`);f["[email protected]"]=`/entities(${n})`}let m=(0,gr.ensureSuccess)(await e.post(p,f,d.options),e.apiUrl(p)),g=(0,gr.readCreatedId)(m,"appactionid");g&&(o[(0,Kt.normalizeGuid)(g,"appactionid")]=(0,gr.readEtag)(m))}for(let c of[...(l=t.deletedRowIds)!==null&&l!==void 0?l:[]].reverse()){let d=(0,Kt.normalizeGuid)(c,"id");await(0,gr.deleteRecord)(e,"appactions",d,(u=a?.[d])!==null&&u!==void 0?u:void 0),delete o[d]}}function j8(e){let t=new Map(e.map(a=>[a.appactionid,a])),r=new Set,n=[],i=a=>{if(r.has(a.appactionid))return;let o=a.body["[email protected]"];if(typeof o=="string"){let s=/\(([^)]+)\)/.exec(o),l=s?t.get(s[1]):void 0;l&&i(l)}r.add(a.appactionid),n.push(a)};return e.forEach(i),n}});var f2=v(ka=>{"use strict";Object.defineProperty(ka,"__esModule",{value:!0});ka.commandRegistration=ka.CommandAdapter=void 0;var Fe=(KI(),br(QI)),t2=lr(),Xt=Fr(),J8=e2(),Q8=pt(),Ma=ae(),km="$ClientSvg:",Mm=".svg",K8=2,X8=1,Y8=1,i2="entityMetadataId",Z8=new Set(["@odata.etag","IconWebResourceId","OnClickEventJavaScriptWebResourceId","VisibilityFormulaComponentLibraryId","OnClickEventFormulaComponentLibraryId","ContextEntity","_appmoduleid_value","_contextentity_value","_createdby_value","_createdonbehalfby_value","_iconwebresourceid_value","_modifiedby_value","_modifiedonbehalfby_value","_onclickeventformulacomponentlibraryid_value","_onclickeventjavascriptwebresourceid_value","_organizationid_value","_parentappactionid_value","_visibilityformulacomponentlibraryid_value","createdon","modifiedon","overriddencreatedon","overwritetime","componentstate","componentidunique","solutionid","ismanaged","iscustomizable","versionnumber","importsequencenumber","timezoneruleversionnumber","utcconversiontimezonecode","statecode","statuscode","scope"]),Uu=class{toArtifact(t){var r,n,i,a,o,s;let l=(r=t.appActions)!==null&&r!==void 0?r:[],u=(n=t.entityLogicalName)!==null&&n!==void 0?n:"",c=new Map;for(let f of l){let m=typeof f._parentappactionid_value=="string"&&f._parentappactionid_value?f._parentappactionid_value:"",g=(i=c.get(m))!==null&&i!==void 0?i:[];g.push(f),c.set(m,g)}let d=new Map;for(let f of(a=c.get(""))!==null&&a!==void 0?a:[]){let m=iG(f.location),g=(o=d.get(m))!==null&&o!==void 0?o:[];g.push(f),d.set(m,g)}let p=[];for(let[f,m]of d)p.push({location:f,groups:tG(m,c,u2(f),u)});return{id:u,entityLogicalName:u,commandBars:nG(p),bag:{a:[[i2,(s=t.entityMetadataId)!==null&&s!==void 0?s:""]]}}}fromArtifact(t){return{entityLogicalName:t.entityLogicalName,entityMetadataId:Bm(t),appActions:xm(t).map(r=>r.row)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t,r){let n=new Set(r?xm(r).map(l=>l.appactionid):[]),i=xm(t,new Set([...n].map(l=>l.toLowerCase()))),a=new Set(i.map(l=>l.appactionid)),o=i.map(l=>{let u=l.exists||n.has(l.appactionid);return{appactionid:l.appactionid,exists:u,etag:l.etag,body:u?gG(l.row):p2(l.row)}}),s=[...n].filter(l=>!a.has(l));return{entityLogicalName:t.entityLogicalName,entityMetadataId:Bm(t),rows:o,...s.length>0?{deletedRowIds:s}:{}}}createDefault(t){var r,n,i,a;let o=(n=(r=t.entityLogicalName)!==null&&r!==void 0?r:t.id)!==null&&n!==void 0?n:"";return{id:(i=t.id)!==null&&i!==void 0?i:o,entityLogicalName:o,commandBars:(a=t.commandBars)!==null&&a!==void 0?a:[]}}assignMissingIds(t){return(0,Q8.assignMissingIds)(t)}validate(t){let r=[];return(0,Xt.childObjects)(t,"commandBars","","commandBar",r).forEach(({node:i,index:a})=>{let o=`/commandBars/${a}`;(0,Xt.optionalEnum)(i,"location",["MainTab","ContextualTab","HomeTab"],o,"bar-location-invalid",r),(0,Xt.childObjects)(i,"groups",o,"group",r).forEach(({node:l,index:u})=>{let c=`${o}/groups/${u}`;a2(l.bag)||((0,Xt.optionalGuidId)(l,"id",c,"group-id-invalid",r),typeof l.title=="string"&&l.title.length>0&&r.push({pointer:`${c}/title`,rule:"group-toplevel-title-unsupported",message:"a new top-level command group cannot have a title: Dataverse rejects a Group row with no parent (0x80040265). Leave the title empty to hold the commands without creating a group row, or nest them under a FlyoutAnchor control, which supplies the parent a group needs."})),o2((0,Xt.childObjects)(l,"controls",c,"control",r),`${c}/controls`,r)})}),r}};ka.CommandAdapter=Uu;function a2(e){let t=e?.a;return Array.isArray(t)&&t.length>0}function o2(e,t,r){e.forEach(({node:n,index:i})=>{let a=`${t}/${i}`;a2(n.bag)||(0,Xt.optionalGuidId)(n,"id",a,"control-id-invalid",r),(0,Xt.optionalEnum)(n,"type",["Button","FlyoutAnchor","SplitButton"],a,"control-type-invalid",r);let o=n.location;o!==void 0&&(typeof o!="number"||!Number.isInteger(o)||o<0||o>6)&&r.push((0,Xt.issue)(`${a}/location`,"control-location-invalid",`location must be an integer 0-6 when present, got ${JSON.stringify(o)}`)),n.action!==void 0&&n.action!==null&&((0,Xt.isJsonObject)(n.action)?(0,Xt.optionalEnum)(n.action,"type",["javascript"],`${a}/action`,"action-type-invalid",r):r.push((0,Xt.issue)(`${a}/action`,"control-action-must-be-object",`a control action must be a JSON object when present, got ${typeof n.action}`)));let s=(0,Xt.childObjects)(n,"children",a,"control",r);s.length>0&&o2(s,`${a}/children`,r)})}function Um(e){return{a:Object.entries(e)}}function eG(e){return Object.fromEntries(e.a)}function Bu(e,t){if(e){for(let[r,n]of e.a)if(r===t)return n}}function Bm(e){let t=Bu(e.bag,i2);return typeof t=="string"?t:""}function tG(e,t,r,n){var i,a;let o=[],s=[];for(let l of qu(e))l.type===Fe.ButtonType.Group?o.push({id:l2(l.name,n),title:typeof l.grouptitle=="string"?l.grouptitle:"",controls:qu((a=t.get((i=l.appactionid)!==null&&i!==void 0?i:""))!==null&&a!==void 0?a:[]).map(u=>$u(u,t,r,n)),bag:Um(l)}):s.push($u(l,t,r,n));return s.length>0&&o.unshift({id:hG(n,r),title:"",controls:s}),o}function $m(e){let t=e.bag?Bu(e.bag,"appactionid"):void 0;return typeof t=="string"&&t.trim()!==""?t:e.id}function $u(e,t,r,n){var i,a,o,s,l;let u=l2(e.name,n),c={id:u,type:aG(e.type),label:typeof e.buttonlabeltext=="string"?e.buttonlabeltext:"",command:typeof e.appactionid=="string"?e.appactionid:u,bag:Um(e)},d=s2(e);d&&(c.icon=d);let p=rG(e);p&&(c.action=p),typeof e.hidden=="boolean"&&(c.hidden=e.hidden),typeof e.isdisabled=="boolean"&&(c.disabled=e.isdisabled),typeof e.location=="number"&&e.location!==r&&(c.location=e.location);let f=t.get((i=e.appactionid)!==null&&i!==void 0?i:"");if(f&&f.length>0){let m=[],g=[];for(let y of qu(f))if(y.type===Fe.ButtonType.Group){let A=(a=y.appactionid)!==null&&a!==void 0?a:"",D=Um(y);c.flyoutGroupId===void 0&&(c.flyoutGroupId=(o=y.appactionid)!==null&&o!==void 0?o:void 0,c.flyoutGroupBag=D);let F=[];for(let _ of qu((l=t.get((s=y.appactionid)!==null&&s!==void 0?s:""))!==null&&l!==void 0?l:[])){let q=$u(_,t,r,n);m.push(q),F.push($m(q))}g.push({id:A,bag:D,childIds:F})}else m.push($u(y,t,r,n));c.children=m,g.length>1&&(c.flyoutGroups=g)}return c}function s2(e){var t;if(!((t=e.IconWebResourceId)===null||t===void 0)&&t.name)return e.IconWebResourceId.name;if(e.fonticon)return e.fonticon.startsWith(km)?e.fonticon.slice(km.length)+Mm:e.fonticon}function rG(e){var t;let r=e.onclickeventjavascriptfunctionname;if(typeof r!="string"||!r)return;let n=e.OnClickEventJavaScriptWebResourceId,i=e._onclickeventjavascriptwebresourceid_value,a={type:"javascript",webResourceId:(t=typeof i=="string"?i:n?.webresourceid)!==null&&t!==void 0?t:"",functionName:r};n?.name&&(a.libraryName=n.name);let o=e.onclickeventjavascriptparameters;return typeof o=="string"&&o&&(a.parameters=o),a}function r2(e){return typeof e.sequence=="number"?e.sequence:typeof e.buttonsequencepriority=="number"?e.buttonsequencepriority:0}function qu(e){return[...e].sort((t,r)=>r2(t)-r2(r))}function nG(e){let t={MainTab:0,ContextualTab:1,HomeTab:2};return[...e].sort((r,n)=>{var i,a;return((i=t[r.location])!==null&&i!==void 0?i:9)-((a=t[n.location])!==null&&a!==void 0?a:9)})}function l2(e,t){if(!e)return"";if(e.indexOf("{!EntityLogicalName}")>=0)return e.replace("{!EntityLogicalName}",t);let r=e.split("!");return r.length===2?r[1]:e}function iG(e){switch(e){case Fe.Location.Form:case Fe.Location.QuickForm:return"MainTab";case Fe.Location.HomePageGrid:case Fe.Location.Dashboard:return"HomeTab";default:return"ContextualTab"}}function u2(e){switch(e){case"MainTab":return Fe.Location.Form;case"HomeTab":return Fe.Location.HomePageGrid;default:return Fe.Location.SubGridStandard}}function aG(e){switch(e){case Fe.ButtonType.Dropdown:return"FlyoutAnchor";case Fe.ButtonType.Split:return"SplitButton";default:return"Button"}}function oG(e){switch(e){case"FlyoutAnchor":return Fe.ButtonType.Dropdown;case"SplitButton":return Fe.ButtonType.Split;default:return Fe.ButtonType.Standard}}function sG(e){var t;return e.bag&&e.bag.a.length>0?!0:((t=e.title)!==null&&t!==void 0?t:"").length>0}function c2(e,t){var r,n,i;return((n=(r=e.bag)===null||r===void 0?void 0:r.a.length)!==null&&n!==void 0?n:0)>0?!0:t.has(((i=e.id)!==null&&i!==void 0?i:"").toLowerCase())}function xm(e,t=new Set){var r,n,i,a;let o=[],s=Bm(e);for(let l of(r=e.commandBars)!==null&&r!==void 0?r:[]){let u=u2(l.location),c=((n=l.groups)!==null&&n!==void 0?n:[]).flatMap(f=>{var m;return(m=f.controls)!==null&&m!==void 0?m:[]}),d=c.length>0&&c.every(f=>!c2(f,t)),p=0;for(let f of(i=l.groups)!==null&&i!==void 0?i:[]){let m;if(sG(f)){let g=uG(f,u,void 0,e,s);o.push(g),m=g.appactionid}for(let g of(a=f.controls)!==null&&a!==void 0?a:[])d2(g,u,m,e,s,o,d?p:void 0,t),p+=1}}return o}function d2(e,t,r,n,i,a,o,s=new Set){var l;let u=lG(e,t,r,n,i,o);a.push(u);let c=(l=e.children)!==null&&l!==void 0?l:[];if(c.length===0&&!(e.flyoutGroups&&e.flyoutGroups.length>0))return;let d=c.every(g=>!c2(g,s)),p=(g,y,A)=>{d2(g,t,y,n,i,a,d?A:void 0,s)},f=e.flyoutGroups;if(f&&f.length>0){let g=new Map(c.map(_=>[$m(_),_])),y=new Set,A=0,D;for(let[_,q]of f.entries()){let B=q.id||(_===0?Lm(u.appactionid):Vm("flyout-group",`${u.appactionid}#${_}`)),L=n2(B,t,u.appactionid,n,i,q.bag);a.push(L);let k=L.appactionid;D===void 0&&(D=k);for(let M of q.childIds){let G=g.get(M);!G||y.has(M)||(y.add(M),p(G,k,A),A+=1)}}let F=D??Lm(u.appactionid);for(let _ of c){let q=$m(_);y.has(q)||(y.add(q),p(_,F,A),A+=1)}return}let m=e.flyoutGroupId||Lm(u.appactionid);a.push(n2(m,t,u.appactionid,n,i,e.flyoutGroupBag));for(let[g,y]of c.entries())p(y,m,g)}function lG(e,t,r,n,i,a){let o=qm(e,t,r,n,i),s=o.row;a!==void 0&&typeof s.sequence!="number"&&(s.sequence=a);let l=s2(s);return e.location!==void 0&&(s.location=e.location),s.type=oG(e.type),s.buttonlabeltext=e.label,dG(s,e.icon,l),fG(s,e.action),pG(s),e.hidden!==void 0&&(s.hidden=e.hidden),e.disabled!==void 0&&(s.isdisabled=e.disabled),{...o,row:s}}function uG(e,t,r,n,i){let a=qm(e,t,r,n,i);return a.row.type=Fe.ButtonType.Group,a.row.grouptitle=e.title,a}function n2(e,t,r,n,i,a){let o=qm({id:e,bag:a},t,r,n,i),s=o.row;return s["[email protected]"]=`/appactions(${(0,Ma.normalizeGuid)(r,"Command flyout group id")})`,s.type=Fe.ButtonType.Group,s.grouptitle===void 0&&(s.grouptitle=""),s.isgrouptitlehidden===void 0&&(s.isgrouptitlehidden=!0),o}function qm(e,t,r,n,i){let a,o,s,l;if(e.bag&&e.bag.a.length>0){a=eG(e.bag),o=!0;let u=Bu(e.bag,"@odata.etag");s=typeof u=="string"?u:null;let c=Bu(e.bag,"appactionid");l=typeof c=="string"&&c?c:e.id}else l=e.id,a=cG(l,t,n,i),o=!1,s=null;return r?a["[email protected]"]=`/appactions(${(0,Ma.normalizeGuid)(r,"Command parent appaction id")})`:o&&typeof a._parentappactionid_value=="string"&&a._parentappactionid_value&&a.type!==Fe.ButtonType.Group&&(a["[email protected]"]=null),delete a._parentappactionid_value,{appactionid:l,exists:o,etag:s,row:a}}function cG(e,t,r,n){let i={appactionid:e,name:`${e}!${e.replace(/-/g,"").slice(0,32)}`,uniquename:"",location:t,context:Fe.Context.Entity,contextvalue:r.entityLogicalName,scope:Fe.Scope.Entity};return n&&(i["[email protected]"]=`/entities(${(0,Ma.normalizeGuid)(n,"Command context entity metadata id")})`),i}function dG(e,t,r){if(t===r){let n=e._iconwebresourceid_value;typeof n=="string"&&n&&!e.fonticon&&(e["[email protected]"]=`/webresourceset(${(0,Ma.normalizeGuid)(n,"Command icon web resource id")})`);return}if(t===void 0){e.fonticon="",e.IconWebResourceId=null;return}e.fonticon=t.toLowerCase().endsWith(Mm)?km+t.slice(0,t.length-Mm.length):t,e.IconWebResourceId=null}function pG(e){let t=(n,i)=>{let a=e[n];if(typeof a!="string"||a.length===0||e[`${i}@odata.bind`]!==void 0)return;let o=(0,Ma.normalizeGuid)(a,`Command ${i}`);e[`${i}@odata.bind`]=`/canvasapps(${o})`};e.onclickeventtype===X8&&t("_onclickeventformulacomponentlibraryid_value","OnClickEventFormulaComponentLibraryId");let r=e.visibilitytype;(!r||r===Y8)&&t("_visibilityformulacomponentlibraryid_value","VisibilityFormulaComponentLibraryId")}function fG(e,t){if(!(!t||t.type!=="javascript")){if(e.onclickeventtype=K8,t.webResourceId){let r=(0,Ma.normalizeGuid)(t.webResourceId,"Command action web resource id");e["[email protected]"]=`/webresourceset(${r})`}e.onclickeventjavascriptfunctionname=t.functionName,t.parameters!==void 0&&(e.onclickeventjavascriptparameters=t.parameters)}}function mG(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return t>>>0}function Vm(e,t){let r="";for(let n=0;n<4;n+=1)r+=mG(`${n}:${e}:${t}`).toString(16).padStart(8,"0");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`}function Lm(e){return Vm("flyout-group",e)}function hG(e,t){return Vm("loose-group",`${e}|${t}`)}function p2(e){let t={...e};for(let r of Z8)delete t[r];return t}function gG(e){let t=p2(e);for(let r of Fe.CannotUpdateAppActionColumns)delete t[r];return t}function vG(){return{adapter:new Uu,api:J8.commandApi,publish:(e,t,r)=>(0,t2.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,t2.boundEntityPublishScope)(t)}}ka.commandRegistration=vG});var m2=v(Vu=>{"use strict";Object.defineProperty(Vu,"__esModule",{value:!0});Vu.chartApi=void 0;var yG=qt(),Yt=be(),ms=ae(),bG="savedqueryvisualizationid,name,description,primaryentitytypecode,datadescription,presentationdescription,charttype,type,isdefault",wG="savedqueryvisualizationid,name,primaryentitytypecode,charttype,isdefault";Vu.chartApi={async get(e,t){let n=`/savedqueryvisualizations(${(0,ms.normalizeGuid)(t,"id")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,ms.odataQuery)([["$select",bG]]),i=(0,Yt.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,Yt.readEtag)(i)}},async list(e,t){let r=`/savedqueryvisualizations${(0,ms.odataQuery)([["$select",wG],["$filter",t?.entityLogicalName?`primaryentitytypecode eq '${(0,ms.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,yG.collectPages)(e,r,"listArtifacts('chart')")).map(i=>{var a,o;return{type:"chart",id:(a=i.savedqueryvisualizationid)!==null&&a!==void 0?a:"",name:(o=i.name)!==null&&o!==void 0?o:"",entityLogicalName:i.primaryentitytypecode,isDirty:!1}})},async create(e,t,r){let n=t,i=(0,Yt.echoWrite)("savedqueryvisualizationid"),a=`/savedqueryvisualizations${i.query}`,o=(0,Yt.ensureSuccess)(await e.post(a,(0,Yt.withClientMintedId)({name:n.name,description:n.description,datadescription:n.datadescription,presentationdescription:n.presentationdescription,primaryentitytypecode:n.primaryentitytypecode,charttype:n.charttype,isdefault:n.isdefault},"savedqueryvisualizationid",r),i.options),e.apiUrl(a));return{id:(0,Yt.resolveCreatedId)(o,"savedqueryvisualizationid","chart",r),etag:(0,Yt.readEtag)(o)}},async update(e,t,r,n){let i=r,a=(0,ms.normalizeGuid)(t,"id"),o=(0,Yt.echoWrite)("savedqueryvisualizationid",{"If-Match":(0,Yt.requireEtag)(n,"chart",a)}),s=`/savedqueryvisualizations(${a})${o.query}`,l=(0,Yt.ensureSuccess)(await e.patch(s,{name:i.name,description:i.description,datadescription:i.datadescription,presentationdescription:i.presentationdescription},o.options),e.apiUrl(s));return{id:a,etag:(0,Yt.readEtag)(l)}},delete(e,t){return(0,Yt.deleteRecord)(e,"savedqueryvisualizations",t)}}});var R2=v(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});Ba.chartRegistration=Ba.ChartAdapter=void 0;var Gm=In(),h2=Fr(),Lr=ri(),g2=lr(),AG=m2(),zm=Tn(),CG=pt(),EG=["Column","StackedColumn","StackedColumn100","Bar","StackedBar","StackedBar100","Area","StackedArea","StackedArea100","Line","Pie","Doughnut","Funnel","Tag"],SG=new Map(EG.map(e=>[e.toLowerCase(),e]));function A2(e){var t;return e&&(t=SG.get(e.toLowerCase()))!==null&&t!==void 0?t:"Column"}function NG(){return'<Chart Palette="BrightPastel"><Series><Series ChartType="Column" ChartArea="Default" /></Series><ChartAreas><ChartArea Name="Default" /></ChartAreas><Legends><Legend Name="Default" /></Legends></Chart>'}function DG(e){var t,r;let n=e.entityLogicalName,i=e.series.map((g,y)=>({alias:`agg_${y}`,series:g})),a=e.categories.map((g,y)=>({alias:`grp_${y}`,category:g})),o=g=>`<attribute alias="${g.alias}" name="${Ua(g.series.attribute)}" aggregate="${Ua(g.series.aggregate)}" />`,s=g=>`<attribute alias="${g.alias}" name="${Ua(g.category.attribute)}" groupby="true"${g.category.dateGrouping?` dategrouping="${Ua(g.category.dateGrouping)}"`:""} />`,l=[],u=new Map,c=(g,y)=>{if(!g){l.push(y);return}let A=u.get(g);A?A.push(y):u.set(g,[y])};i.forEach(g=>c(g.series.relatedEntity,o(g))),a.forEach(g=>c(g.category.relatedEntity,s(g)));let d=[...u.entries()].map(([g,y])=>`<link-entity name="${Ua(g)}">${y.join("")}</link-entity>`).join(""),p=l.join("")+d,f=i.map(g=>`<measurecollection><measure alias="${g.alias}" /></measurecollection>`).join(""),m=(r=(t=a[0])===null||t===void 0?void 0:t.alias)!==null&&r!==void 0?r:"";return`<datadefinition><fetchcollection><fetch mapping="logical" aggregate="true"><entity name="${Ua(n)}">${p}</entity></fetch></fetchcollection><categorycollection><category alias="${m}">${f}</category></categorycollection></datadefinition>`}var Gu=class{toArtifact(t){var r,n,i,a,o,s,l;(0,zm.installDomShim)();let u=(r=t.datadescription)!==null&&r!==void 0?r:"",c=(n=t.presentationdescription)!==null&&n!==void 0?n:"",d=(0,Lr.parseXmlRoot)(u,"<datadefinition/>"),p=(0,Lr.parseXmlRoot)(c,"<Chart/>");return{id:(i=t.savedqueryvisualizationid)!==null&&i!==void 0?i:"",name:(a=t.name)!==null&&a!==void 0?a:"",description:(o=t.description)!==null&&o!==void 0?o:"",entityLogicalName:(s=t.primaryentitytypecode)!==null&&s!==void 0?s:"",chartType:C2(p),isDefault:(l=t.isdefault)!==null&&l!==void 0?l:!1,series:N2(d),categories:D2(d),presentation:E2(p),dataBag:u?(0,Lr.projectElementBag)(d):void 0,presentationBag:c?(0,Lr.projectElementBag)(p):void 0,rowBag:IG(t.charttype,t.type)}}fromArtifact(t){(0,zm.installDomShim)();let{datadescription:r,presentationdescription:n}=_G(t);return{savedqueryvisualizationid:t.id,name:t.name,description:t.description,primaryentitytypecode:t.entityLogicalName,datadescription:r,presentationdescription:n,charttype:v2(t.rowBag,"charttype"),type:v2(t.rowBag,"type"),isdefault:t.isDefault}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t){var r,n,i,a,o,s,l;let u=this.fromArtifact(t);return{name:(r=u.name)!==null&&r!==void 0?r:"",description:(n=u.description)!==null&&n!==void 0?n:"",datadescription:(i=u.datadescription)!==null&&i!==void 0?i:"",presentationdescription:(a=u.presentationdescription)!==null&&a!==void 0?a:"",primaryentitytypecode:(o=u.primaryentitytypecode)!==null&&o!==void 0?o:"",charttype:(s=u.charttype)!==null&&s!==void 0?s:0,isdefault:(l=u.isdefault)!==null&&l!==void 0?l:!1}}createDefault(t){var r,n,i,a,o,s,l;(0,zm.installDomShim)();let u=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,CG.newId)(),name:(i=t.name)!==null&&i!==void 0?i:"New Chart",description:(a=t.description)!==null&&a!==void 0?a:"",entityLogicalName:u,chartType:(o=t.chartType)!==null&&o!==void 0?o:"Column",isDefault:(s=t.isDefault)!==null&&s!==void 0?s:!1,series:t.series&&t.series.length>0?t.series:[{attribute:"createdon",aggregate:"count"}],categories:t.categories&&t.categories.length>0?t.categories:[{attribute:"createdon",dateGrouping:"month"}],presentation:(l=t.presentation)!==null&&l!==void 0?l:{palette:"BrightPastel",showLegend:!0}}}assignMissingIds(t){return t}validate(t){let r=[],n=t;return(0,h2.childObjects)(n,"series","","series",r),(0,h2.childObjects)(n,"categories","","category",r),r}};Ba.ChartAdapter=Gu;function IG(e,t){let r=[];return e!==void 0&&r.push(["charttype",String(e)]),t!==void 0&&r.push(["type",String(t)]),r.length>0?{a:r,c:[]}:void 0}function v2(e,t){if(!e)return;let r=e.a.find(([i])=>i===t);if(!r)return;let n=parseInt(r[1],10);return Number.isNaN(n)?void 0:n}function C2(e){let t=e.getElementsByTagName("Series");for(let r=0;r<t.length;r+=1)if(t[r].getAttribute("ChartType"))return A2(t[r].getAttribute("ChartType"));return"Column"}function E2(e){var t;let r={showLegend:e.getElementsByTagName("Legend").length>0},n=e.getAttribute("Palette");n&&(r.palette=n);let i=e.getElementsByTagName("Title")[0],a=((t=i?.textContent)!==null&&t!==void 0?t:"").trim();return a&&(r.title=a),r}function zu(e){return e.getElementsByTagName("fetch")[0]}function S2(e){let t=new Map;if(!e)return t;let r=e.getElementsByTagName("link-entity");for(let n=0;n<r.length;n+=1){let i=r[n],a=i.getAttribute("name");if(!a)continue;let o=i.getElementsByTagName("attribute");for(let s=0;s<o.length;s+=1){let l=o[s],u=l.getAttribute("alias")||l.getAttribute("name");u&&t.set(u,a)}}return t}function N2(e){let t=zu(e);if(!t)return[];let r=S2(t),n=t.getElementsByTagName("attribute"),i=[];for(let a=0;a<n.length;a+=1){let o=n[a],s=o.getAttribute("aggregate");if(!s)continue;let l=o.getAttribute("name");if(!l)continue;let u={attribute:l,aggregate:s},c=o.getAttribute("charttype");c&&(u.seriesType=A2(c));let d=o.getAttribute("alias");d&&(u.alias=d);let p=d??l,f=r.get(p);f&&(u.relatedEntity=f),i.push(u)}return i}function D2(e){var t;let r=zu(e);if(!r)return[];let n=S2(r),i=r.getElementsByTagName("attribute"),a=[];for(let o=0;o<i.length;o+=1){let s=i[o];if(((t=s.getAttribute("groupby"))!==null&&t!==void 0?t:"").toLowerCase()!=="true")continue;let l=s.getAttribute("name");if(!l)continue;let u={attribute:l},c=s.getAttribute("dategrouping");c&&(u.dateGrouping=c);let d=s.getAttribute("alias");d&&(u.alias=d);let p=d??l,f=n.get(p);f&&(u.relatedEntity=f),a.push(u)}return a}function _G(e){if(!y2(e.dataBag)||!y2(e.presentationBag)){let a=DG(e);return{datadescription:a,presentationdescription:jG(e,a)}}let t=new DOMParser().parseFromString("<root/>","text/xml"),r=b2(e.dataBag,"datadefinition",t),n=b2(e.presentationBag,"Chart",t),i=N2(r);if(!Wm(e.series,i)){let a=Hm(r);TG(t,r,e.series);let o=Hm(r),s=o.length>0?o:e.series.map(()=>"");I2(t,n,s,a,e.chartType)}return Wm(e.categories,D2(r))||PG(t,r,e.categories),e.chartType!==C2(n)&&P2(n,e.chartType),Wm(e.presentation,E2(n))||O2(n,e.presentation),{datadescription:(0,Lr.serializeNode)(r),presentationdescription:(0,Lr.serializeNode)(n)}}function y2(e){return!!e&&(e.c.length>0||e.a.length>0)}function I2(e,t,r,n,i){let a,o=t.childNodes;for(let d=0;d<o.length;d+=1)if(o[d].nodeType===1&&o[d].tagName==="Series"){a=o[d];break}a||(a=e.createElement("Series"),t.insertBefore(a,t.firstChild));let s=[],l=a.childNodes;for(let d=0;d<l.length;d+=1)l[d].nodeType===1&&l[d].tagName==="Series"&&s.push(l[d]);let u=new Map;n.forEach((d,p)=>{let f=s[p];if(!f)return;let m=u.get(d);m?m.push(f):u.set(d,[f])});let c=r.map(d=>{let p=u.get(d),f=p&&p.length>0?p.shift():void 0;if(f)return f;let m=e.createElement("Series");m.setAttribute("ChartType",i);let g=s.length>0?s[0].getAttribute("ChartArea"):null;return g&&m.setAttribute("ChartArea",g),m});for(let d of s)a.removeChild(d);for(let d of c)a.appendChild(d)}function Hm(e){let t=[],r=e.getElementsByTagName("measure");for(let n=0;n<r.length;n+=1)t.push(r[n].getAttribute("alias")||"");return t}function b2(e,t,r){let n={n:t,a:(0,Gm.mergeAttrs)(e.a,[]),c:(0,Gm.spliceChildren)(e.c,[])};return(0,Gm.rebuildRaw)(n,(0,Lr.domEngine)(r),null)}function TG(e,t,r){let n=zu(t),i=n?.getElementsByTagName("entity")[0];!n||!i||_2(e,t,i,MG(n),r,BG,{aliasPrefix:"aggregate_column",addRef:FG,removeRef:kG})}function PG(e,t,r){let n=zu(t),i=n?.getElementsByTagName("entity")[0];!n||!i||_2(e,t,i,UG(n),r,$G,{aliasPrefix:"groupby_column",addRef:xG,removeRef:LG})}function _2(e,t,r,n,i,a,o){let s=new Map;for(let f of n){let m=f.getAttribute("alias");m&&s.set(m,f)}let l=new Set,u=[],c=(f,m)=>{var g;let y=qG(r,f),A=m.relatedEntity;(y??void 0)!==(A??void 0)&&((g=f.parentNode)===null||g===void 0||g.removeChild(f),w2(e,r,f,A))};for(let f of i){let m=f.alias?s.get(f.alias):void 0;m&&!l.has(m)?(a(m,f),c(m,f),l.add(m)):u.push(f)}let d=n.filter(f=>!l.has(f)),p=0;for(let f of u)if(p<d.length){let m=d[p];a(m,f),c(m,f),l.add(m),p+=1}else{let m=e.createElement("attribute"),g=f.alias||RG(t,o.aliasPrefix);m.setAttribute("alias",g),a(m,f),w2(e,r,m,f.relatedEntity),o.addRef(e,t,g)}for(let f of n)if(!l.has(f)){let m=f.getAttribute("alias");m&&o.removeRef(t,m),GG(f)}}function OG(e){let t=new Set;for(let r of["attribute","measure","category"]){let n=e.getElementsByTagName(r);for(let i=0;i<n.length;i+=1){let a=n[i].getAttribute("alias");a&&t.add(a)}}return t}function RG(e,t){let r=OG(e);if(!r.has(t))return t;for(let n=2;;n+=1){let i=`${t}_${n}`;if(!r.has(i))return i}}function T2(e,t){let r=t.getElementsByTagName("categorycollection")[0];if(r)return r;let n=e.createElement("categorycollection");return t.appendChild(n),n}function FG(e,t,r){let n=T2(e,t),i=n.getElementsByTagName("category")[0];i||(i=e.createElement("category"),n.appendChild(i));let a=e.createElement("measurecollection"),o=e.createElement("measure");o.setAttribute("alias",r),a.appendChild(o),i.appendChild(a)}function xG(e,t,r){let n=T2(e,t),i=e.createElement("category");i.setAttribute("alias",r),n.appendChild(i)}function LG(e,t){let r=e.getElementsByTagName("category");for(let n=0;n<r.length;n+=1)r[n].getAttribute("alias")===t&&r[n].removeAttribute("alias")}function kG(e,t){var r;let n=e.getElementsByTagName("measure"),i=[];for(let a=0;a<n.length;a+=1)n[a].getAttribute("alias")===t&&i.push(n[a]);for(let a of i){let o=a.parentNode;o?.removeChild(a),o&&o.tagName==="measurecollection"&&!WG(o)&&((r=o.parentNode)===null||r===void 0||r.removeChild(o))}}function MG(e){let t=[],r=e.getElementsByTagName("attribute");for(let n=0;n<r.length;n+=1)r[n].getAttribute("aggregate")&&t.push(r[n]);return t}function UG(e){var t;let r=[],n=e.getElementsByTagName("attribute");for(let i=0;i<n.length;i+=1)((t=n[i].getAttribute("groupby"))!==null&&t!==void 0?t:"").toLowerCase()==="true"&&r.push(n[i]);return r}function BG(e,t){e.setAttribute("name",t.attribute),e.setAttribute("aggregate",t.aggregate),t.seriesType&&e.setAttribute("charttype",t.seriesType)}function $G(e,t){e.setAttribute("name",t.attribute),e.setAttribute("groupby","true"),t.dateGrouping?e.setAttribute("dategrouping",t.dateGrouping):e.getAttribute("dategrouping")!==null&&e.removeAttribute("dategrouping")}function qG(e,t){let r=t.parentNode;for(;r&&r!==e;){let n=r;if(n.nodeType===1&&n.tagName==="link-entity")return n.getAttribute("name")||void 0;r=n.parentNode}}function w2(e,t,r,n){n?VG(e,t,n).appendChild(r):t.appendChild(r)}function VG(e,t,r){let n=t.getElementsByTagName("link-entity");for(let a=0;a<n.length;a+=1)if(n[a].getAttribute("name")===r)return n[a];let i=e.createElement("link-entity");return i.setAttribute("name",r),t.appendChild(i),i}function GG(e){let t=e.parentNode;if(t&&(t.removeChild(e),t.tagName==="link-entity"&&!zG(t))){let r=t.parentNode;r&&r.removeChild(t)}}function zG(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1){let n=t[r];if(n.nodeType===1){let i=n.tagName;if(i==="attribute"||i==="link-entity")return!0}}return!1}function WG(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1)if(t[r].nodeType===1)return!0;return!1}function P2(e,t){let r=e.getElementsByTagName("Series"),n=!1;for(let i=0;i<r.length;i+=1)r[i].getAttribute("ChartType")&&(r[i].setAttribute("ChartType",t),n=!0);if(!n){for(let i=0;i<r.length;i+=1)if(!HG(r[i])){r[i].setAttribute("ChartType",t);return}}}function HG(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1){let n=t[r];if(n.nodeType===1&&n.tagName==="Series")return!0}return!1}function O2(e,t){var r;let n=e.ownerDocument;if(t.palette!==void 0&&e.setAttribute("Palette",t.palette),t.showLegend!==void 0){let i=[],a=e.getElementsByTagName("Legends");for(let o=0;o<a.length;o+=1)i.push(a[o]);if(t.showLegend&&i.length===0){let o=n.createElement("Legends"),s=n.createElement("Legend");s.setAttribute("Name","Default"),o.appendChild(s),e.appendChild(o)}else if(!t.showLegend)for(let o of i)(r=o.parentNode)===null||r===void 0||r.removeChild(o)}if(t.title!==void 0){let i=e.getElementsByTagName("Title")[0];i&&(i.textContent=t.title)}}function jG(e,t){let r=(0,Lr.parseXmlRoot)(NG(),"<Chart/>");P2(r,e.chartType),O2(r,e.presentation);let n=Hm((0,Lr.parseXmlRoot)(t,"<datadefinition/>"));return n.length>0&&I2(r.ownerDocument,r,n,n.slice(0,1),e.chartType),(0,Lr.serializeNode)(r)}function Wm(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Ua(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function JG(){return{adapter:new Gu,api:AG.chartApi,publish:(e,t,r)=>(0,g2.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,g2.boundEntityPublishScope)(t)}}Ba.chartRegistration=JG});var F2=v(Wu=>{"use strict";Object.defineProperty(Wu,"__esModule",{value:!0});Wu.dashboardApi=void 0;var QG=qt(),Zt=be(),hs=ae(),KG="formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber",XG="formid,name,type,objecttypecode",YG=0,ZG=10;Wu.dashboardApi={async get(e,t){let n=`/systemforms(${(0,hs.normalizeGuid)(t,"id")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,hs.odataQuery)([["$select",KG]]),i=(0,Zt.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,Zt.readEtag)(i)}},async list(e,t){let r=[`(type eq ${YG} or type eq ${ZG})`];t?.entityLogicalName&&r.push(`objecttypecode eq '${(0,hs.odataLiteral)(t.entityLogicalName)}'`);let n=`/systemforms${(0,hs.odataQuery)([["$select",XG],["$filter",r.join(" and ")]])}`;return(await(0,QG.collectPages)(e,n,"listArtifacts('dashboard')")).map(a=>{var o,s;return{type:"dashboard",id:(o=a.formid)!==null&&o!==void 0?o:"",name:(s=a.name)!==null&&s!==void 0?s:"",entityLogicalName:a.objecttypecode,isDirty:!1}})},async create(e,t,r){let n=t,i=(0,Zt.echoWrite)("formid"),a=`/systemforms${i.query}`,o={name:n.name,description:n.description,formxml:n.formxml,istabletenabled:n.istabletenabled,type:n.type};n.objecttypecode&&(o.objecttypecode=n.objecttypecode);let s=(0,Zt.ensureSuccess)(await e.post(a,(0,Zt.withClientMintedId)(o,"formid",r),i.options),e.apiUrl(a));return{id:(0,Zt.resolveCreatedId)(s,"formid","dashboard",r),etag:(0,Zt.readEtag)(s)}},async update(e,t,r,n){let i=r,a=(0,hs.normalizeGuid)(t,"id"),o=(0,Zt.echoWrite)("formid",{"If-Match":(0,Zt.requireEtag)(n,"dashboard",a)}),s=`/systemforms(${a})${o.query}`,l=(0,Zt.ensureSuccess)(await e.patch(s,{name:i.name,description:i.description,formxml:i.formxml,istabletenabled:i.istabletenabled},o.options),e.apiUrl(s));return{id:a,etag:(0,Zt.readEtag)(l)}},delete(e,t){return(0,Zt.deleteRecord)(e,"systemforms",t)}}});var W2=v(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});kr.dashboardRegistration=kr.TILE_CLASS_ID=kr.DashboardAdapter=void 0;var vs=In(),er=ri(),jm=lr(),gs=Fr(),e6=F2(),Jm=Tn(),Ci=pt(),B2=ae(),$2=Ri(),x2="0",Qm="10",t6=new Map([["{E7A81278-8635-4D9E-8D4D-59480B391C5B}","chart"],["{FD2A7985-3187-444E-908D-6624B21F69C0}","iframe"],["{9FDF5F91-88B1-47F4-AD53-C11EFC01A01D}","webresource"],["{EE9078C8-6946-4E2C-B8F8-35E65F4BE6A8}","stream"],["{06375649-C143-495E-A496-C962E5B4488E}","timeline"],["{8C54228C-1B25-4909-A12A-F2B968BB0D62}","powerbi"],["{F9A8A302-114E-466A-B582-6771B2AE0D92}","assistant"]]),r6="{3FF9A528-DD50-4ACA-8F10-2E5ED73513AD}",ju=class{constructor(t=$2.DEFAULT_LCID){this.lcid=t}toArtifact(t){var r,n,i,a;(0,Jm.installDomShim)();let o=(r=t.formxml)!==null&&r!==void 0?r:"",s=(0,er.parseXmlRoot)(o,"<form/>");return{id:(n=t.formid)!==null&&n!==void 0?n:"",name:(i=t.name)!==null&&i!==void 0?i:"",description:(a=t.description)!==null&&a!==void 0?a:"",dashboardType:n6(t.type),entityLogicalName:t.objecttypecode?t.objecttypecode:null,enabledForMobile:!!t.istabletenabled,layoutType:i6(s),components:L2(s,this.lcid),bag:(0,er.projectElementBag)(s)}}fromArtifact(t){var r;return(0,Jm.installDomShim)(),{formid:t.id,name:t.name,description:t.description,type:t.dashboardType==="Interactive"?Qm:x2,objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",istabletenabled:t.enabledForMobile,formxml:k2(t,this.lcid)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t){return{name:t.name,description:t.description,formxml:k2(t,this.lcid),istabletenabled:t.enabledForMobile,type:t.dashboardType==="Interactive"?Qm:x2,objecttypecode:t.entityLogicalName}}createDefault(t){var r,n,i,a,o,s,l,u;(0,Jm.installDomShim)();let c=(0,er.parseXmlRoot)(v6(),"<form/>");return{id:(r=t.id)!==null&&r!==void 0?r:(0,Ci.newId)(),name:(n=t.name)!==null&&n!==void 0?n:"New Dashboard",description:(i=t.description)!==null&&i!==void 0?i:"",dashboardType:(a=t.dashboardType)!==null&&a!==void 0?a:"Standard",entityLogicalName:(o=t.entityLogicalName)!==null&&o!==void 0?o:null,enabledForMobile:(s=t.enabledForMobile)!==null&&s!==void 0?s:!1,layoutType:(l=t.layoutType)!==null&&l!==void 0?l:0,components:(u=t.components)!==null&&u!==void 0?u:L2(c,this.lcid),bag:(0,er.projectElementBag)(c)}}assignMissingIds(t){if(t&&typeof t=="object"&&!Array.isArray(t)&&"position"in t&&!("components"in t)){let r=t;(typeof r.id!="string"||r.id.length===0)&&(r.id=(0,Ci.newId)())}return t}validate(t){let r=[],n=(0,gs.childObjects)(t,"components","","component",r),i=new Set;return n.forEach(({node:a,index:o})=>{let s=`/components/${o}`;for(let l of["position","parameters"]){let u=a[l];u!==void 0&&!(0,gs.isJsonObject)(u)&&r.push((0,gs.issue)(`${s}/${l}`,`component-${l}-must-be-object`,`a component ${l} must be a JSON object when present, got ${u===null?"null":typeof u}`))}if((0,gs.isJsonObject)(a.position)){let l=ys(a.position);i.has(l)?r.push((0,gs.issue)(`${s}/position`,"component-position-collision",`two components occupy the same dashboard position (${l}); move one to a free cell`)):i.add(l)}}),r}};kr.DashboardAdapter=ju;function n6(e){return String(e??"")===Qm?"Interactive":"Standard"}function i6(e){let t=e?.getAttribute("formLayout")||e?.getAttribute("layoutType"),r=parseInt(t??"",10);return Number.isNaN(r)?0:r}function K(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let a=n[i];a.nodeType===1&&a.tagName.toLowerCase()===t&&r.push(a)}return r}function L2(e,t){let r=[];return K(e,"tabs").flatMap(i=>K(i,"tab")).forEach((i,a)=>{K(i,"columns").flatMap(s=>K(s,"column")).forEach((s,l)=>{K(s,"sections").flatMap(c=>K(c,"section")).forEach((c,d)=>{a6(c,{tabIndex:a,columnIndex:l,sectionIndex:d},r,t)})})}),r}function a6(e,t,r,n){K(e,"rows").flatMap(a=>K(a,"row")).forEach((a,o)=>{K(a,"cell").forEach((s,l)=>{let u=o6(s,{...t,rowIndex:o,cellIndex:l},n);u&&r.push(u)})})}function o6(e,t,r){var n,i;let a=G2((n=e.getAttribute("id"))!==null&&n!==void 0?n:"");if(a.toLowerCase().startsWith("spacer"))return null;let o=K(e,"control")[0];if(!o)return null;let s=(i=o.getAttribute("classid"))!==null&&i!==void 0?i:"",l=u6(o),u=c6(s,l,o),c=s6(o);return{id:o.getAttribute("id")||a,type:u,name:V2(e,r),classId:s,position:t,colspan:Km(e,"colspan",1),rowspan:Km(e,"rowspan",1),parameters:l,bag:(0,er.projectElementBag)(e),...c?{icProperties:c}:{}}}function q2(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1){let n=t[r];if(n.nodeType===1&&n.tagName.toLowerCase()==="icproperties")return n}}function s6(e){let t=q2(e);return t?(0,er.serializeNode)(t):void 0}function l6(e,t,r){let n=q2(t);if(!r){n&&t.removeChild(n);return}let i=new DOMParser().parseFromString(r,"text/xml").documentElement,a=(0,vs.rebuildRaw)((0,vs.rawFromNode)((0,er.nodeLikeFromDom)(i)),(0,er.domEngine)(e),null);n&&(0,er.serializeNode)(n)===(0,er.serializeNode)(a)||(n?t.replaceChild(a,n):t.appendChild(a))}function V2(e,t){var r,n;let i=K(e,"labels")[0];if(!i)return"";let a=K(i,"label"),o=(r=a.find(s=>s.getAttribute("languagecode")===String(t)))!==null&&r!==void 0?r:a[0];return(n=o?.getAttribute("description"))!==null&&n!==void 0?n:""}function u6(e){var t;let r={},n=K(e,"parameters")[0];if(!n)return r;let i=n.childNodes;for(let a=0;a<i.length;a+=1){let o=i[a];o.nodeType===1&&(r[o.tagName]=((t=o.textContent)!==null&&t!==void 0?t:"").trim())}return r}function c6(e,t,r){var n;let i=t6.get(e.toUpperCase());return i?i==="chart"?t.ChartGridMode==="Chart"?"chart":"list":i==="assistant"&&((n=r.getAttribute("uniqueid"))!==null&&n!==void 0?n:"").toUpperCase()===r6?"assistant":i:"unknown"}function Km(e,t,r){var n;let i=parseInt((n=e.getAttribute(t))!==null&&n!==void 0?n:"",10);return Number.isNaN(i)?r:i}function G2(e){return e.replace(/^\{/,"").replace(/\}$/,"")}function d6(e,t){let r={n:"form",a:(0,vs.mergeAttrs)(e.bag.a,[]),c:(0,vs.spliceChildren)(e.bag.c,[])};return(0,vs.rebuildRaw)(r,(0,er.domEngine)(t),null)}function k2(e,t){let r=new DOMParser().parseFromString("<root/>","text/xml"),n=d6(e,r);return m6(r,n,e.components,t),p6(r,n,e.components,t),(0,er.serializeNode)(n)}function p6(e,t,r,n){let i=z2(t);for(let a of r)i.has(ys(a.position))||f6(e,t,a,n)}function f6(e,t,r,n){var i,a,o,s;let l=(a=(i=r.position)===null||i===void 0?void 0:i.sectionIndex)!==null&&a!==void 0?a:0,u=y6(t,e,l);for(let G of K(u,"row"))K(G,"cell").some(V=>K(V,"control").length>0)||u.removeChild(G);let c=r.classId||kr.TILE_CLASS_ID[r.type]||kr.TILE_CLASS_ID.iframe,d=r.rowspan&&r.rowspan>0?r.rowspan:4,p=r.bag&&M2(r.bag,"id")?String(M2(r.bag,"id")):Hu((0,Ci.newId)()),f=r.id?Hu(r.id):Hu((0,Ci.newId)()),m=u.parentNode,g=Math.max(1,parseInt(m&&m.getAttribute&&m.getAttribute("columns")||"1",10)||1),y=Math.min(Math.max(1,r.colspan&&r.colspan>0?r.colspan:1),g),A=K(u,"row"),D=A[A.length-1],F=D?K(D,"cell").reduce((G,V)=>G+Km(V,"colspan",1),0):0;(!D||F+y>g)&&(D=e.createElement("row"),u.appendChild(D));let _=e.createElement("cell");_.setAttribute("id",p),_.setAttribute("colspan",String(y)),_.setAttribute("rowspan",String(d)),_.setAttribute("showlabel","true");let q=e.createElement("labels"),B=e.createElement("label");B.setAttribute("description",(o=r.name)!==null&&o!==void 0?o:""),B.setAttribute("languagecode",String(n)),q.appendChild(B),_.appendChild(q);let L=e.createElement("control");L.setAttribute("id",f),L.setAttribute("classid",Hu(c));let k=e.createElement("parameters"),M=(s=r.parameters)!==null&&s!==void 0?s:{};for(let G of Object.keys(M)){let V=(0,B2.createSafeXmlElement)(e,G,"dashboard tile parameter");V.textContent=M[G],k.appendChild(V)}L.appendChild(k),_.appendChild(L),D.appendChild(_)}function M2(e,t){if(!e)return;let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function m6(e,t,r,n){var i;let a=z2(t),o=new Set(r.map(s=>ys(s.position)));for(let s of r){let l=a.get(ys(s.position));if(!l)continue;let u=K(l,"control")[0];u&&(h6(e,l,s.name,n),g6(e,u,s.parameters),U2(l,"colspan",s.colspan),U2(l,"rowspan",s.rowspan),s.icProperties!==void 0&&l6(e,u,s.icProperties))}for(let[s,l]of a)o.has(s)||(i=l.parentNode)===null||i===void 0||i.removeChild(l)}function z2(e){let t=new Map;return K(e,"tabs").flatMap(n=>K(n,"tab")).forEach((n,i)=>{K(n,"columns").flatMap(o=>K(o,"column")).forEach((o,s)=>{K(o,"sections").flatMap(u=>K(u,"section")).forEach((u,c)=>{K(u,"rows").flatMap(p=>K(p,"row")).forEach((p,f)=>{K(p,"cell").forEach((m,g)=>{var y;G2((y=m.getAttribute("id"))!==null&&y!==void 0?y:"").toLowerCase().startsWith("spacer")||K(m,"control")[0]&&t.set(ys({tabIndex:i,columnIndex:s,sectionIndex:c,rowIndex:f,cellIndex:g}),m)})})})})}),t}function ys(e){let t=e??{};return`${t.tabIndex}.${t.columnIndex}.${t.sectionIndex}.${t.rowIndex}.${t.cellIndex}`}function h6(e,t,r,n){if(r===V2(t,n))return;let i=K(t,"labels")[0];i||(i=e.createElement("labels"),t.appendChild(i));let a=K(i,"label").find(o=>o.getAttribute("languagecode")===String(n));a||(a=e.createElement("label"),a.setAttribute("languagecode",String(n)),i.appendChild(a)),a.setAttribute("description",r)}function g6(e,t,r){var n;if(!r)return;let i=Object.keys(r);if(i.length===0)return;let a=K(t,"parameters")[0];a||(a=e.createElement("parameters"),t.appendChild(a));let o=new Map,s=a.childNodes;for(let l=0;l<s.length;l+=1){let u=s[l];u.nodeType===1&&o.set(u.tagName,u)}for(let l of i){let u=r[l],c=o.get(l);if(c)((n=c.textContent)!==null&&n!==void 0?n:"")!==u&&(c.textContent=u);else{let d=(0,B2.createSafeXmlElement)(e,l,"dashboard component parameter");d.textContent=u,a.appendChild(d)}}}function U2(e,t,r){var n;((n=e.getAttribute(t))!==null&&n!==void 0?n:"")!==String(r)&&e.setAttribute(t,String(r))}function v6(e=2){let t=`{${(0,Ci.newId)()}}`,r=`{${(0,Ci.newId)()}}`,n=`{${(0,Ci.newId)()}}`,i=Math.max(1,Math.floor(e));return`<form><tabs><tab id="${t}" name="General" showlabel="true" expanded="true" verticallayout="true"><columns><column width="100%"><sections><section id="${r}" name="Section 1" showlabel="false" columns="${i}"><rows><row><cell id="${n}" rowspan="12" colspan="${i}" showlabel="true" /></row></rows></section></sections></column></columns></tab></tabs></form>`}kr.TILE_CLASS_ID={chart:"E7A81278-8635-4D9E-8D4D-59480B391C5B",list:"E7A81278-8635-4D9E-8D4D-59480B391C5B",iframe:"FD2A7985-3187-444E-908D-6624B21F69C0",webresource:"9FDF5F91-88B1-47F4-AD53-C11EFC01A01D"};function Hu(e){return`{${e.replace(/[{}]/g,"")}}`}function y6(e,t,r){var n;let i=K(e,"tabs").flatMap(u=>K(u,"tab"))[0];if(!i)throw new Error("addDashboardTile: dashboard formxml has no <tab>");let a=K(i,"columns").flatMap(u=>K(u,"column"))[0];if(!a)throw new Error("addDashboardTile: dashboard formxml has no <column>");let o=K(a,"sections").flatMap(u=>K(u,"section")),s=(n=o[r])!==null&&n!==void 0?n:o[0];if(!s)throw new Error("addDashboardTile: dashboard formxml has no <section>");let l=K(s,"rows")[0];return l||(l=t.createElement("rows"),s.appendChild(l)),l}function b6(e=$2.DEFAULT_LCID){return{adapter:new ju(e),api:e6.dashboardApi,languageSensitive:!0,publish:(t,r,n)=>n?.entityLogicalName?(0,jm.publishBoundEntity)(t,n):(0,jm.publishDashboardById)(t,r),publishScope:(t,r)=>r?.entityLogicalName?(0,jm.boundEntityPublishScope)(r):{envelope:"dashboard",targetIds:[t]}}}kr.dashboardRegistration=b6});var X2=v(Qu=>{"use strict";Object.defineProperty(Qu,"__esModule",{value:!0});Qu.genPageApi=void 0;var K2=qt(),Ne=be(),Ot=ae(),Xm=Sd(),Mr=te();function w6(e){if(ArrayBuffer.isView(e)){let r=e;return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}if(Object.prototype.toString.call(e)==="[object ArrayBuffer]")return new Uint8Array(e);let t=globalThis;if(t.Buffer&&t.Buffer.isBuffer(e)){let r=e;return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}}var Qn="uxagentprojects",qa="uxagentprojectfiles",$a="uxagentprojectid",Ur="uxagentprojectfileid",Ju=`${$a},name`,A6=`${Ur},filename,filetype`;async function Ym(e,t,r,n){var i;let a=`/${t}(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Ot.odataQuery)([["$select",n]]),o=(0,Ne.ensureSuccess)(await e.get(a),e.apiUrl(a));return{row:(i=o.body)!==null&&i!==void 0?i:{},etag:(0,Ne.readEtag)(o)}}async function C6(e,t){let r=`/${qa}(${t})/filecontent/$value`,n=await e.get(r);if(n.status===404)return{status:"unavailable",reason:"unpublished"};(0,Ne.ensureSuccess)(n,e.apiUrl(r));let i=n.body,a=w6(i);if(a)return{status:"available",data:(0,Xm.bytesToBase64)(a)};if(typeof i=="string")return{status:"available",data:(0,Xm.utf8ToBase64)(i)};throw new Mr.SdkError("GENPAGE_CONTENT_UNREADABLE",`Read the content of file '${t}' but the injected HttpClient returned a body this SDK cannot encode (${typeof i}). Return the response as a string, Uint8Array, Buffer, or ArrayBuffer; a byte-returning transport is required to round-trip non-UTF8 assets.`)}async function E6(e,t,r,n){if(!e.supportsBinaryPatch)throw new Mr.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED",`Refusing to push generative-page file '${t}': its content cannot be written because the injected HttpClient does not implement patchRaw(). A Dataverse File column is not writable through a JSON body, so saving the row without its bytes would report success for a page whose source never uploaded.`);let i=`/${qa}(${t})/filecontent`,a=(0,Xm.base64ToBytes)(n);(0,Ot.assertNoControlChars)(r,"generative-page file name"),(0,Ne.ensureSuccess)(await e.patchRaw(i,a,{headers:{"Content-Type":"application/octet-stream","Content-Length":String(a.byteLength),"x-ms-file-name":r}}),e.apiUrl(i))}async function Zm(e,t){let r=`/${qa}/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()`+(0,Ot.odataQuery)([["$select",A6],["$filter",`_${$a}_value eq ${t}`]]);return(await(0,K2.collectPages)(e,r,"fetchArtifact('genPage')")).map(i=>({row:i,etag:typeof i["@odata.etag"]=="string"?i["@odata.etag"]:null}))}async function H2(e,t,r){var n;let{etag:i}=await Ym(e,Qn,t,Ju),a={};for(let{row:l,etag:u}of await Zm(e,t))a[(0,Ot.normalizeGuid)(String((n=l[Ur])!==null&&n!==void 0?n:""),Ur)]=u;let o=Object.keys(a),s=!i||o.length!==r.size||o.some(l=>!r.has(l))||Object.values(a).some(l=>!l);return{etag:i,memberEtags:a,mismatch:s}}function j2(e,t){return t.mismatch?{etag:null,memberEtags:{},warnings:[`Generative page '${e}' was written, but its files changed on the server while the write was in progress, so the new concurrency tokens cannot be trusted. The local baseline is now unusable: re-fetch the page before editing it again \u2014 the next push will refuse rather than overwrite blind.`]}:{etag:t.etag,memberEtags:t.memberEtags}}Qu.genPageApi={async get(e,t){var r;let n=(0,Ot.normalizeGuid)(t,"id"),{row:i,etag:a}=await Ym(e,Qn,n,Ju),o=await Zm(e,n),s={},l=[];for(let{row:u,etag:c}of o){let d=(0,Ot.normalizeGuid)(String((r=u[Ur])!==null&&r!==void 0?r:""),Ur);s[d]=c;let p=await C6(e,d);l.push({...u,content:p})}return{raw:{project:i,files:l},etag:a,memberEtags:s}},async list(e,t){let r=`/${Qn}/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()`+(0,Ot.odataQuery)([["$select",Ju]]);return(await(0,K2.collectPages)(e,r,"listArtifacts('genPage')")).map(i=>{var a,o;return{type:"genPage",id:String((a=i[$a])!==null&&a!==void 0?a:""),name:String((o=i.name)!==null&&o!==void 0?o:""),isDirty:!1}})},async create(e,t,r){let n=t;J2(e,n);let i=`/${Qn}`,a=(0,Ne.ensureSuccess)(await e.post(i,(0,Ne.withClientMintedId)({name:n.name},$a,r)),e.apiUrl(i)),o=(0,Ne.resolveCreatedId)(a,$a,"generative page",r),s=new Set;for(let l of n.files){let u=await Q2(e,o,l,!0);s.add((0,Ot.normalizeGuid)(u.id,"file id"))}try{return{id:o,...j2(o,await H2(e,o,s))}}catch(l){return{id:o,etag:null,memberEtags:{},warnings:[`The generative page was created, but re-reading its concurrency tokens failed (${l instanceof Error?l.message:String(l)}). The local baseline is unusable: re-fetch the page before editing it \u2014 the next push will refuse rather than overwrite blind.`]}}},async update(e,t,r,n,i){let a=r,o=(0,Ot.normalizeGuid)(t,"id");J2(e,a);let s=await Zm(e,o),{etag:l}=await Ym(e,Qn,o,Ju);if(n&&l&&n!==l)throw new Mr.SdkError(Ne.VERSION_CONFLICT_CODE,`Generative page '${o}' changed on the server after it was fetched (baseline ${n}, server ${l}) \u2014 another writer edited it. A page row accepts no If-Match validator, so this push would silently overwrite them. Re-fetch the page and re-apply the edit.`);if(!n||!l)throw new Mr.SdkError(Ne.VERSION_CONFLICT_CODE,`Cannot verify generative page '${o}' before writing: ${n?"the server did not return the page's current token":"no baseline token was recorded"}. This entity accepts no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);let u=new Set(s.map(({row:f})=>{var m;return(0,Ot.normalizeGuid)(String((m=f[Ur])!==null&&m!==void 0?m:""),Ur)})),c=new Set(a.files.map(f=>(0,Ot.normalizeGuid)(f.id,"file id")));if(!i)throw new Mr.SdkError(Ne.VERSION_CONFLICT_CODE,`Cannot verify the files of generative page '${o}' before writing: no child baseline was recorded. These rows accept no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);let d=new Set(Object.keys(i).map(f=>f.toLowerCase()));{for(let m of c)if(!u.has(m)&&d.has(m))throw new Mr.SdkError(Ne.VERSION_CONFLICT_CODE,`Generative-page file '${m}' existed when this page was fetched but is gone from the server now \u2014 another writer deleted it. Refusing to recreate it, because a blind re-create would undo that delete and, for an unpublished page, restore the row WITHOUT its content. Re-fetch the page and re-apply the edit.`);for(let m of u)if(!d.has(m))throw new Mr.SdkError(Ne.VERSION_CONFLICT_CODE,`Generative-page file '${m}' is on the server but absent from this page's baseline \u2014 another writer added it after the page was fetched, so its contents cannot be verified. Refusing to write over or delete it. Re-fetch the page so the addition is part of your baseline.`);let f=new Map(s.map(({row:m,etag:g})=>{var y;return[(0,Ot.normalizeGuid)(String((y=m[Ur])!==null&&y!==void 0?y:""),Ur),g]}));for(let[m,g]of Object.entries(i??{})){let y=m.toLowerCase();if(!u.has(y))continue;let A=f.get(y);if(!g||!A)throw new Mr.SdkError(Ne.VERSION_CONFLICT_CODE,`Cannot verify generative-page file '${y}' before writing: ${g?"the server did not return its current token":"no baseline token was recorded"}. A file row accepts no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);if(g!==A)throw new Mr.SdkError(Ne.VERSION_CONFLICT_CODE,`Generative-page file '${y}' changed on the server after this page was fetched (baseline ${g}, server ${A}) \u2014 another writer edited it. A file row accepts no If-Match validator, so this push would silently overwrite that change. Re-fetch the page and re-apply the edit.`)}}let p=`/${Qn}(${o})`;(0,Ne.ensureSuccess)(await e.patch(p,{name:a.name},{headers:{"If-Match":"*"}}),e.apiUrl(p));for(let f of a.files){let m=(0,Ot.normalizeGuid)(f.id,"file id");await Q2(e,o,f,!u.has(m))}for(let f of u)c.has(f)||await(0,Ne.deleteRecord)(e,qa,f);try{return{id:o,...j2(o,await H2(e,o,c))}}catch(f){return{id:o,etag:null,memberEtags:{},warnings:[`The generative page was written, but re-reading its concurrency tokens failed (${f instanceof Error?f.message:String(f)}). The local baseline is now unusable: re-fetch the page before editing it again \u2014 the next push will refuse rather than overwrite blind.`]}}},delete(e,t){return(0,Ne.deleteRecord)(e,Qn,t)}};function J2(e,t){var r;if(((r=t.files)!==null&&r!==void 0?r:[]).some(i=>i.content.status==="available")&&!e.supportsBinaryPatch)throw new Mr.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED","Refusing to write this generative page: it has file content to upload, but the injected HttpClient does not implement patchRaw(). A Dataverse File column is not writable through a JSON body, so proceeding would create the page and its rows and then fail, leaving a page whose source never uploaded.")}async function Q2(e,t,r,n){let i=(0,Ot.normalizeGuid)(r.id,"file id"),a;if(n){let o=`/${qa}`,s=(0,Ne.ensureSuccess)(await e.post(o,(0,Ne.withClientMintedId)({filename:r.name,filetype:r.fileType,[`${$a}@odata.bind`]:`/${Qn}(${t})`},Ur,i)),e.apiUrl(o));a=(0,Ne.readEtag)(s)}else{let o=`/${qa}(${i})`,s=(0,Ne.ensureSuccess)(await e.patch(o,{filename:r.name,filetype:r.fileType},{headers:{"If-Match":"*"}}),e.apiUrl(o));a=(0,Ne.readEtag)(s)}return r.content.status==="available"&&await E6(e,i,r.name,r.content.data),{id:i,etag:a}}});var t_=v(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});Ga.genPageRegistration=Ga.GenPageAdapter=void 0;var S6=X2(),N6=lr(),Kn=Fr(),e_=pt(),Y2=2e8;function Z2(e){return typeof e=="string"&&e.trim()!==""?e:(0,e_.newId)()}function Va(e){return(0,Kn.isJsonObject)(e)?e:{}}function D6(e){let t=Va(e);return t.status==="available"&&typeof t.data=="string"?{status:"available",data:t.data}:{status:"unavailable",reason:"unpublished"}}var Ku=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var r,n;let i=t,a=Va(i?.project),o=Array.isArray(i?.files)?i.files:[];return{id:String((r=a.uxagentprojectid)!==null&&r!==void 0?r:""),name:String((n=a.name)!==null&&n!==void 0?n:""),files:o.map(s=>{var l,u,c;let d=Va(s);return{id:String((l=d.uxagentprojectfileid)!==null&&l!==void 0?l:""),name:String((u=d.filename)!==null&&u!==void 0?u:""),fileType:Number((c=d.filetype)!==null&&c!==void 0?c:Y2),content:D6(d.content)}})}}toApiPayload(t){var r;return{name:t.name,files:((r=t.files)!==null&&r!==void 0?r:[]).map(n=>({id:n.id,name:n.name,fileType:n.fileType,content:n.content}))}}createDefault(t){var r,n;return{id:Z2(t.id),name:(r=t.name)!==null&&r!==void 0?r:"New page",files:((n=t.files)!==null&&n!==void 0?n:[]).map(i=>{var a,o,s;return{id:Z2(i.id),name:(a=i.name)!==null&&a!==void 0?a:"index.tsx",fileType:(o=i.fileType)!==null&&o!==void 0?o:Y2,content:(s=i.content)!==null&&s!==void 0?s:{status:"available",data:""}}})}}assignMissingIds(t){let r=Va(t);return(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,e_.newId)()),r}validate(t){let r=[],n=t.files;if(n!==void 0&&!Array.isArray(n))return r.push((0,Kn.issue)("/files","files-must-be-array",`files must be an array, got ${typeof n}`)),r;let i=new Map;return(Array.isArray(n)?n:[]).forEach((a,o)=>{let s=`/files/${o}`,l=Va(a),u=typeof l.id=="string"?l.id.trim().toLowerCase():"";if(u==="")r.push((0,Kn.issue)(s,"file-id-required","a generative-page file needs an id"));else{let f=i.get(u);f!==void 0?r.push((0,Kn.issue)(s,"file-id-duplicate",`two files share the id '${l.id}' (also at /files/${f}); a file's id is its identity, so a duplicate makes an edit ambiguous`)):i.set(u,o)}let c=typeof l.name=="string"?l.name:"";(c===""||/[\u0000-\u001F\u007F]/.test(c)||/[\\/]/.test(c))&&r.push((0,Kn.issue)(s+"/name","file-name-invalid",`a file name must be a non-empty single path segment with no control characters or path separators (it is sent as an HTTP header on upload); got '${c}'`));let d=l.content;if(d===void 0){r.push((0,Kn.issue)(s+"/content","file-content-required","content is required: omitting it is indistinguishable from an empty file, and the two have opposite effects on the next push"));return}let p=Va(d);p.status==="available"?typeof p.data!="string"&&r.push((0,Kn.issue)(s+"/content/data","file-content-data-invalid","available content needs base64 `data`")):p.status!=="unavailable"&&r.push((0,Kn.issue)(s+"/content/status","file-content-status-invalid",`content.status must be 'available' or 'unavailable', got ${String(p.status)}`))}),r}};Ga.GenPageAdapter=Ku;function I6(){return{adapter:new Ku,api:S6.genPageApi,publish:(e,t)=>(0,N6.publishGenPageById)(e,t),publishScope:e=>({envelope:"uxagentproject",targetIds:[e]})}}Ga.genPageRegistration=I6});var n_=v(Zu=>{"use strict";Object.defineProperty(Zu,"__esModule",{value:!0});Zu.reconcileBpfSecurityRoles=void 0;var Yu=be(),Xu=ae(),_6="Global",r_={create:"Create",read:"Read",write:"Write",delete:"Delete"};async function T6(e,t){var r,n;let i=`/EntityDefinitions(LogicalName='${(0,Xu.odataPathLiteral)(t)}')?$select=LogicalName,Privileges`,o=(n=(r=(0,Yu.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||r===void 0?void 0:r.Privileges)!==null&&n!==void 0?n:[],s={},l=new Set;return Object.keys(r_).forEach(u=>{let c=o.find(d=>d.PrivilegeType===r_[u]);if(c){let d=(0,Xu.normalizeGuid)(c.PrivilegeId,"PrivilegeId");s[u]=d,l.add(d)}}),{byAccess:s,all:l}}async function P6(e,t){var r,n;let i=`/RetrieveRolePrivilegesRole(RoleId=${t})`,o=(n=(r=(0,Yu.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||r===void 0?void 0:r.RolePrivileges)!==null&&n!==void 0?n:[];return new Set(o.map(s=>(0,Xu.normalizeGuid)(s.PrivilegeId,"PrivilegeId")))}async function O6(e,t,r){if(r.length===0)return;let n={Privileges:r.map(a=>({Depth:_6,PrivilegeId:a}))},i=`/roles(${t})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;(0,Yu.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function R6(e,t,r){let n={Privilege:{"@odata.type":"Microsoft.Dynamics.CRM.privilege",privilegeid:r}},i=`/roles(${t})/Microsoft.Dynamics.CRM.RemovePrivilegeRole`;(0,Yu.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function F6(e,t,r){var n;if(!r||r.length===0)return;let i=await T6(e,t.toLowerCase());for(let a of r){let o=(0,Xu.normalizeGuid)(a.roleId,"roleId"),s=new Set(((n=a.access)!==null&&n!==void 0?n:[]).map(p=>i.byAccess[p]).filter(p=>!!p)),l=await P6(e,o),u=new Set([...l].filter(p=>i.all.has(p))),c=[...s].filter(p=>!u.has(p)),d=[...u].filter(p=>!s.has(p));await O6(e,o,c);for(let p of d)await R6(e,o,p)}}Zu.reconcileBpfSecurityRoles=F6});var p_=v(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});nc.bpfApi=void 0;var tr=Yn(),x6=qt(),rr=te(),vt=be(),un=ae(),L6=n_(),k6={"Content-Type":"application/json",Accept:"application/json"},ec={...k6,Prefer:"return=representation"},M6=new Set([408,502,503,504]),U6=`category eq ${tr.WorkflowCategory.BusinessProcessFlow} and type eq ${tr.WorkflowTypeCode.Definition} and businessprocesstype eq ${tr.BusinessProcessType.BusinessFlow}`,B6="workflowid,name,description,primaryentity,statecode,category,type,businessprocesstype,processorder",$6="workflowid,name,uniquename,description,primaryentity,statecode,statuscode,category,type,businessprocesstype,processorder,xaml,clientdata",q6=["xaml","name","description","processorder"];async function i_(e,t){var r;if(t.status!=="Active"||!t.securityRoles||t.securityRoles.length===0)return;let n=String((r=t.record.uniquename)!==null&&r!==void 0?r:"");n!==""&&await(0,L6.reconcileBpfSecurityRoles)(e,n,t.securityRoles)}async function d_(e,t,r){let n={statecode:tr.StateCode.Activated,statuscode:tr.StatusCode.Activated},i=`/workflows(${t})`,a={...ec};return r&&(a["If-Match"]=r),(0,vt.ensureSuccess)(await e.patch(i,n,{headers:a}),e.apiUrl(i))}async function a_(e,t,r){return(0,vt.readEtag)(await d_(e,t,r))}function o_(e,t){return new rr.SdkError("BPF_WRITE_NOT_ECHOED",`The ${t} of business process flow '${e}' was applied, but the server returned no concurrency token for it (this environment did not honour 'Prefer: return=representation'), so the next step could not be conditioned on a token this push produced and was NOT sent. `+rc(e))}async function tc(e,t){var r;let n=`/workflows(${t})${(0,un.odataQuery)([["$select","statecode"]])}`,i=(0,vt.ensureSuccess)(await e.get(n),e.apiUrl(n)),a=(r=i.body)===null||r===void 0?void 0:r.statecode,o=Number(a);if(a==null||a===""||!Number.isFinite(o))throw new rr.SdkError("BPF_STATE_UNREADABLE",`Reading the state of business process flow '${t}' answered HTTP ${i.status} without a usable statecode, so whether it is Active cannot be decided.`);return o}async function eh(e,t,r){if(await tc(e,t)!==tr.StateCode.Activated)return{deactivated:!1,etag:null};let n={statecode:tr.StateCode.Draft,statuscode:tr.StatusCode.Draft},i=`/workflows(${t})`,a={...ec};r&&(a["If-Match"]=r);let o;try{o=await e.patch(i,n,{headers:a})}catch(l){return await s_(e,t,l)}if(M6.has(o.status))return await s_(e,t,new rr.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",`Deactivating business process flow '${t}' answered HTTP ${o.status} from an intermediary, so whether it committed is unknown.`));let s=(0,vt.ensureSuccess)(o,e.apiUrl(i));return{deactivated:!0,etag:(0,vt.readEtag)(s)}}async function s_(e,t,r){let n;try{n=await tc(e,t)}catch{n=void 0}if(n===tr.StateCode.Draft)return{deactivated:!0,etag:null,uncertainCause:r};if(n===tr.StateCode.Activated)throw r;let i=new rr.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",`Deactivating business process flow '${t}' did not complete, and its state could not be re-read \u2014 it MAY be left DISABLED and needs reconciling. Original failure: ${r instanceof Error?r.message:String(r)}`);throw i.cause=r,i}async function l_(e,t){let r=(0,un.normalizeGuid)(t,"workflowid");try{return await d_(e,r,null),"restored"}catch{try{let n=await tc(e,r);return n===tr.StateCode.Activated?"restored":n===tr.StateCode.Draft?"disabled":"unknown"}catch{return"unknown"}}}function u_(e,t,r,n){let i=`Original failure: ${n instanceof Error?n.message:String(n)}`,a=r==="disabled"?new rr.SdkError("BPF_LEFT_DEACTIVATED",`Business process flow '${e}' was deactivated ${t}, and it could NOT be reactivated \u2014 it is left DISABLED. ${i}`):new rr.SdkError("BPF_REACTIVATE_OUTCOME_UNKNOWN",`Business process flow '${e}' was deactivated ${t}, and whether it was reactivated could not be confirmed \u2014 it MAY be left DISABLED and needs checking. ${i}`);return a.cause=n,a}async function V6(e,t){try{return await tc(e,t),"survived"}catch(r){return r instanceof rr.ConnectionError&&r.statusCode===404?"removed":"unknown"}}async function G6(e,t,r){if(r)try{let{deactivated:n,etag:i}=await eh(e,t,r),a=n?i:r;if(a)return await(0,vt.deleteRecord)(e,"workflows",t,a),"removed"}catch{}return V6(e,t)}function rc(e){return`Adopt the server's copy with fetchArtifact('bpf', '${e}', { overwrite: true }) \u2014 it REPLACES the local copy, so keep any outstanding local changes aside first \u2014 then re-apply them and push.`}function c_(e,t){return new rr.SdkError("BPF_CREATE_NO_TOKEN",`Created business process flow '${e}' but the server returned no concurrency token for it (this environment did not honour 'Prefer: return=representation'), so the next push would have nothing to condition on. ${t} It was NOT rolled back: deleting it without a token could remove an edit made since. ${rc(e)}`)}function z6(e,t){let r=new rr.SdkError("BPF_CREATE_NOT_ROLLED_BACK",`Creating business process flow '${e}' failed part-way, and the rollback could NOT remove it \u2014 it still EXISTS, possibly Active and half-configured. (The rollback deletes only on a token this create produced, so a row somebody has since edited is left in place on purpose; a delete the platform refused or failed leaves it too.) ${rc(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return r.cause=t,r}function W6(e,t){let r=new rr.SdkError("BPF_CREATE_ROLLBACK_OUTCOME_UNKNOWN",`Creating business process flow '${e}' failed part-way, and whether its rollback removed the process could not be confirmed \u2014 it MAY still exist, possibly Active and half-configured. ${rc(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return r.cause=t,r}function H6(e,t){let r=new rr.SdkError("BPF_CREATE_REMOVED_AFTER_CONFLICT",`Creating business process flow '${e}' was interrupted: another writer changed it right after it was created, so this push's next step was refused rather than overwrite or activate their edit \u2014 and the process has since been removed. Nothing is left behind and there is nothing to fetch. If the removal was deliberate, stop here; otherwise push again to re-create it at the same id. Original failure: ${t instanceof Error?t.message:String(t)}`);return r.cause=t,r}function j6(e){let t={};for(let r of q6)e[r]!==void 0&&(t[r]=e[r]);return t}nc.bpfApi={async get(e,t){let n=`/workflows(${(0,un.normalizeGuid)(t,"id")})${(0,un.odataQuery)([["$select",$6]])}`,i=(0,vt.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,vt.readEtag)(i)}},async list(e,t){let r=[U6];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,un.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,un.odataQuery)([["$select",B6],["$filter",r.join(" and ")]])}`;return(await(0,x6.collectPages)(e,n,"listArtifacts('bpf')")).map(a=>{var o,s;return{type:"bpf",id:(o=a.workflowid)!==null&&o!==void 0?o:"",name:(s=a.name)!==null&&s!==void 0?s:"",entityLogicalName:a.primaryentity,isDirty:!1}})},async create(e,t){let r=t,n=(0,un.normalizeGuid)(r.record.workflowid,"workflowid"),i="/workflows",a=(0,vt.ensureSuccess)(await e.post(i,r.record,{headers:ec}),e.apiUrl(i)),o=(0,vt.readEtag)(a);if(!o)throw c_(n,r.status==="Active"?"The process EXISTS as Draft and was NOT activated \u2014 an activation that cannot be conditioned on our own write could activate somebody else's edit.":"The process EXISTS as Draft.");let s=o;try{r.status==="Active"&&(s=await a_(e,n,o)),await i_(e,r)}catch(l){let u=await G6(e,n,s);throw u==="survived"?z6(n,l):u==="unknown"?W6(n,l):l instanceof rr.SdkError&&l.code===vt.VERSION_CONFLICT_CODE?H6(n,l):l}if(!s)throw c_(n,"The process EXISTS and IS Active, but its activation returned no token.");return{id:n,etag:s}},async update(e,t,r,n){let i=r,a=(0,un.normalizeGuid)(t,"id"),o=(0,vt.requireEtag)(n,"bpf",a),{deactivated:s,etag:l,uncertainCause:u}=await eh(e,a,o);try{if(u!==void 0)throw u;let c=o;if(s){if(!l)throw o_(a,"deactivation");c=l}let d=`/workflows(${a})`,p=(0,vt.ensureSuccess)(await e.patch(d,j6(i.record),{headers:{...ec,"If-Match":c}}),e.apiUrl(d)),f=(0,vt.readEtag)(p);if(i.status==="Active"){if(!f)throw o_(a,"definition write");f=await a_(e,a,f)}return await i_(e,i),{id:a,etag:f}}catch(c){if(s){let d=await l_(e,a);if(d!=="restored")throw u_(a,"to apply an edit, the edit failed",d,c)}throw c}},async delete(e,t){let r=(0,un.normalizeGuid)(t,"id"),{deactivated:n}=await eh(e,r,null);try{await(0,vt.deleteRecord)(e,"workflows",r)}catch(i){if(n){let a=await l_(e,r);if(a!=="restored")throw u_(r,"so it could be deleted, the delete failed",a,i)}throw i}}}});var Q_=v(Wa=>{"use strict";Object.defineProperty(Wa,"__esModule",{value:!0});Wa.bpfRegistration=Wa.BpfAdapter=void 0;var ic=Yn(),J6=p_(),th=In(),Ei=ri(),N_=Tn(),Mt=Fr(),Rt=pt(),Br=te(),Q6=100,nh='<?xml version="1.0" encoding="utf-16"?>',f_=1033,D_="mxswa:Workflow",K6="mxswa:ActivityReference.Properties",X6="mcwo:StepLabel",Y6="mcwb:Control",m_="mcwb:Control.ControlDisplayName",I_="mcwb:Control.DataFieldName",__="DataFieldName",h_="ControlDisplayName",T_="Literal",ac="x:Null",g_="x:String",ih="x:Key",ah="DisplayName",sc="Activities",Z6="StepLabels",P_="StageId",O_="StageCategory",R_="NextStageId",F_="ProcessStepId",oh="IsProcessRequired",x_="EntityComposite",L_="StageComposite",k_="StepComposite";function rh(e){return(0,Mt.isJsonObject)(e)?e:{}}function $r(e){if(!e)return[];let t=[],r=e.childNodes;for(let n=0;n<r.length;n+=1){let i=r[n];i.nodeType===1&&t.push(i)}return t}function Si(e,t){var r;return(r=$r(e).find(n=>n.tagName===t))!==null&&r!==void 0?r:null}function qr(e){return Si(e,K6)}function yt(e,t){var r;return(r=$r(e).find(n=>n.getAttribute(ih)===t))!==null&&r!==void 0?r:null}function za(e,t){var r;return((r=e.getAttribute("AssemblyQualifiedName"))!==null&&r!==void 0?r:"").includes(t)}function dn(e){var t;return!e||!e.firstChild?"":(t=e.firstChild.nodeValue)!==null&&t!==void 0?t:""}function M_(e,t,r){e.firstChild?e.firstChild.nodeValue=r:e.appendChild(t.createTextNode(r))}function bs(e){var t;let r=(t=e.getAttribute(ah))!==null&&t!==void 0?t:"",n=r.indexOf(": ");return n>=0?r.slice(n+2):r}function U_(e,t){var r;let n=(r=e.getAttribute(ah))!==null&&r!==void 0?r:"",i=n.indexOf(": ");e.setAttribute(ah,i>=0?n.slice(0,i+2)+t:t)}function B_(e,t){let r=yt(e,Z6),n=Si(r,X6);n&&n.setAttribute("Description",t)}function e7(e){let t=yt(e,O_);if(!t||t.tagName===ac)return;let r=dn(t).trim();return r===""?void 0:Number(r)}function t7(e){let t=yt(e,R_);if(!t||t.tagName===ac)return;let r=dn(t).trim();return r===""?void 0:r}function $_(e){let t=q_(e);if(!t)return;let r=G_(t,__,I_);return r===""?void 0:r}function sh(e,t){let r=$r(e);for(;r.length>0;){let n=r.pop();if(n.tagName===t)return n;for(let i of $r(n))r.push(i)}return null}function q_(e){let t=yt(qr(e),sc);return t?sh(t,Y6):null}function V_(e,t){let r=e.attributes;for(let n=0;n<r.length;n+=1)if(r[n].name===t)return!0;return!1}function G_(e,t,r){var n;return V_(e,t)?(n=e.getAttribute(t))!==null&&n!==void 0?n:"":o7(e,r)}function v_(e,t,r,n){if(V_(e,t)){e.setAttribute(t,n);return}if(Si(e,r)){r7(e,r,n);return}throw new Br.InvalidArgumentError(`BPF step control exposes neither a '${t}' attribute nor a <${r}> wrapper to bind a column`)}function r7(e,t,r){let n=Si(e,t),i=n?sh(n,T_):null;i&&i.setAttribute("Value",r)}function z_(e){return bs(e)}function lc(e){let t=Si(e,D_),r=[];for(let n of $r(t).filter(i=>za(i,x_))){let i=yt(qr(n),sc);for(let a of $r(i).filter(o=>za(o,L_)))r.push({el:a,entity:z_(n)})}return r}function lh(e){let t=yt(qr(e),sc);return $r(t).filter(r=>za(r,k_))}function n7(e){let t=qr(e),r=dn(yt(t,oh)).trim().toLowerCase(),n=$_(e),i={id:dn(yt(t,F_)),name:bs(e)};return n!==void 0&&(i.fieldName=n),r==="true"&&(i.required=!0),i}function i7(e,t){let r=qr(e),n=e7(r),i=t7(r),a={id:dn(yt(r,P_)),name:bs(e),entityLogicalName:t,steps:lh(e).map(n7)};return n!==void 0&&(a.category=n),i!==void 0&&(a.nextStageId=i),a}function a7(e){return lc(e).map(({el:t,entity:r})=>i7(t,r))}function cn(e){return new Br.NotImplementedError("bpf-structural-authoring",`${e} is not supported yet (this phase authors identity, stage/step names, step required, step field binding, stage categories, and adding/removing/reordering stages & steps on a single-table process; branching, actions, security-role wiring and multi-table processes land in later phases). The rest of the process round-trips losslessly.`)}function o7(e,t){var r;let n=Si(e,t),i=n?sh(n,T_):null;return(r=i?.getAttribute("Value"))!==null&&r!==void 0?r:""}function uh(e,t){var r;let n=e.createElement(t.tagName),i=t.attributes;for(let o=0;o<i.length;o+=1)n.setAttribute(i[o].name,i[o].value);let a=t.childNodes;for(let o=0;o<a.length;o+=1){let s=a[o];s.nodeType===1?n.appendChild(uh(e,s)):s.nodeType===3&&n.appendChild(e.createTextNode((r=s.nodeValue)!==null&&r!==void 0?r:""))}return n}function W_(e){return yt(qr(e),sc)}function s7(e,t,r){var n;let i=t.entityLogicalName&&t.entityLogicalName.trim()!==""?t.entityLogicalName:r,a=!((n=t.steps[0])===null||n===void 0)&&n.id&&t.steps[0].id.trim()!==""?t.steps[0].id:(0,Rt.newId)(),{body:o}=uc(ch(i,(0,Rt.newId)(),t.id,a));return uh(e,lc((0,Ei.parseXmlRoot)(o,"<Activity/>"))[0].el)}function l7(e,t){let{body:r}=uc(ch("account",(0,Rt.newId)(),(0,Rt.newId)(),t.id));return uh(e,lh(lc((0,Ei.parseXmlRoot)(r,"<Activity/>"))[0].el)[0])}function H_(e,t){for(;e.firstChild;)e.removeChild(e.firstChild);for(let r of t)e.appendChild(r)}function j_(e,t,r,n){let i=yt(e,r);if(!i||!i.parentNode){if(n!==void 0&&n!=="")throw cn(`setting '${r}' on a stage whose xaml does not expose that slot`);return}let a=i.parentNode;if(n===void 0||n===""){if(i.tagName!==ac){let s=t.createElement(ac);s.setAttribute(ih,r),a.replaceChild(s,i)}return}if(i.tagName===g_){dn(i)!==n&&M_(i,t,n);return}let o=t.createElement(g_);o.setAttribute(ih,r),o.appendChild(t.createTextNode(n)),a.replaceChild(o,i)}function u7(e,t,r){j_(e,t,O_,r===void 0?void 0:String(r))}function c7(e,t,r){j_(e,t,R_,r)}function J_(e,t,r){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(r(e[n])!==t[n])return!1;return!0}function y_(e){return dn(yt(qr(e),P_))}function b_(e){return dn(yt(qr(e),F_))}function w_(e,t,r){var n,i,a,o;let s=qr(e);r.name!==bs(e)&&(U_(e,r.name),B_(s,r.name));let l=dn(yt(s,oh)).trim().toLowerCase()==="true";if(((n=r.required)!==null&&n!==void 0?n:!1)!==l){let u=yt(s,oh);u&&M_(u,t,r.required?"True":"False")}if(((i=r.fieldName)!==null&&i!==void 0?i:"")!==((a=$_(e))!==null&&a!==void 0?a:"")){let u=q_(e);if(!u)throw new Br.InvalidArgumentError("BPF step has no <mcwb:Control> element to bind a column to");let c=(o=r.fieldName)!==null&&o!==void 0?o:"";v_(u,__,I_,c),c!==""&&G_(u,h_,m_)===""&&v_(u,h_,m_,c)}}function A_(e,t,r,n){var i;let a=qr(e);if(!a)throw new Br.InvalidArgumentError("BPF stage composite has no <\u2026ActivityReference.Properties>");if(r.name!==bs(e)&&(U_(e,r.name),B_(a,r.name)),u7(a,t,r.category),c7(a,t,n),r.relationshipName&&r.relationshipName.trim()!=="")throw cn("a stage relationship / table change (multi-table authoring)");if(r.actions&&r.actions.length>0||r.branch)throw cn("stage actions or conditional branching");let o=W_(e);if(!o)throw new Br.InvalidArgumentError("BPF stage has no [Activities] collection");let s=(i=r.steps)!==null&&i!==void 0?i:[];if(s.length===0)throw new Br.InvalidArgumentError(`BPF stage '${r.name}' must have at least one step`);let l=lh(e);if(J_(l,s.map(d=>d.id),b_)){l.forEach((d,p)=>w_(d,t,s[p]));return}let u=new Map(l.map(d=>[b_(d),d]));if($r(o).some(d=>!za(d,k_)))throw cn("adding, removing or reordering steps on a stage that also contains branching or actions");let c=s.map(d=>{var p;return(p=u.get(d.id))!==null&&p!==void 0?p:l7(t,d)});H_(o,c),c.forEach((d,p)=>w_(d,t,s[p]))}function d7(e,t,r){let n=Si(e,D_);if(!n)throw new Br.InvalidArgumentError("BPF xaml has no <mxswa:Workflow> root activity");if(r.globalActions&&r.globalActions.length>0)throw cn("global (process-completed/abandoned) actions");if(!r.stages||r.stages.length===0)throw new Br.InvalidArgumentError("a BPF must have at least one stage");let i=lc(e),a=i.map(p=>p.el);if(J_(a,r.stages.map(p=>p.id),y_)){i.forEach(({el:p,entity:f},m)=>{let g=r.stages[m];if(g.entityLogicalName&&g.entityLogicalName.trim()!==""&&g.entityLogicalName!==f)throw cn(`changing a stage's table ('${g.entityLogicalName}' vs the process's '${f}')`);A_(p,t,g,g.nextStageId)});return}let o=$r(n).filter(p=>za(p,x_));if(o.length!==1)throw cn("adding, removing or reordering stages on a multi-table process");let s=o[0],l=z_(s),u=W_(s);if(!u)throw new Br.InvalidArgumentError("BPF primary entity composite has no [Activities] collection");if($r(u).some(p=>!za(p,L_)))throw cn("adding, removing or reordering stages on a process whose primary composite holds non-stage activities (multi-table nesting or advanced constructs)");for(let p of r.stages)if(p.entityLogicalName&&p.entityLogicalName.trim()!==""&&p.entityLogicalName!==l)throw cn(`a stage on a different table ('${p.entityLogicalName}') than the process primary ('${l}')`);let c=new Map(a.map(p=>[y_(p),p])),d=r.stages.map(p=>{var f;return(f=c.get(p.id))!==null&&f!==void 0?f:s7(t,p,l)});H_(u,d),d.forEach((p,f)=>{let m=f<d.length-1?r.stages[f+1].id:void 0;A_(p,t,r.stages[f],m)})}function uc(e){let t=e.match(/^<\?xml[^>]*\?>\s*/),r=t?t[0]:"";return{prolog:r,body:e.slice(r.length)}}function p7(e){var t,r,n,i,a,o;(0,N_.installDomShim)();let s=(t=e.bag)===null||t===void 0?void 0:t.xaml;if(s){let p=new DOMParser().parseFromString("<root/>","text/xml"),f={n:"Activity",a:(0,th.mergeAttrs)(s.a,[]),c:(0,th.spliceChildren)(s.c,[])};return{root:(0,th.rebuildRaw)(f,(0,Ei.domEngine)(p),null),prolog:(n=(r=e.bag)===null||r===void 0?void 0:r.xamlProlog)!==null&&n!==void 0?n:nh,eol:(a=(i=e.bag)===null||i===void 0?void 0:i.xamlEol)!==null&&a!==void 0?a:"lf"}}let l=e.stages[0],u=(o=l?.steps)===null||o===void 0?void 0:o[0],c=ch(e.entityLogicalName,(0,Rt.newId)(),l?.id&&l.id.trim()!==""?l.id:(0,Rt.newId)(),u?.id&&u.id.trim()!==""?u.id:(0,Rt.newId)()),{body:d}=uc(c);return{root:(0,Ei.parseXmlRoot)(d,"<Activity/>"),prolog:nh,eol:"lf"}}function f7(e){let{root:t,prolog:r,eol:n}=p7(e);d7(t,t.ownerDocument,e);let i=(0,Ei.serializeNode)(t);return n==="crlf"&&(i=i.replace(/\n/g,`\r-`)),r+i}function m7(e){return e.uniqueName&&e.uniqueName.trim()!==""?e.uniqueName:`new_${(e.name||"businessprocessflow").toLowerCase().replace(/[^a-z0-9]/g,"")||"businessprocessflow"}`}var oc=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var r,n;(0,N_.installDomShim)();let i=t,a=typeof i.xaml=="string"?i.xaml:"",o={id:i.workflowid?String(i.workflowid):null,name:String((r=i.name)!==null&&r!==void 0?r:""),entityLogicalName:String((n=i.primaryentity)!==null&&n!==void 0?n:""),status:Number(i.statecode)===1?"Active":"Draft",stages:[]};if(i.uniquename&&(o.uniqueName=String(i.uniquename)),i.description!=null&&i.description!==""&&(o.description=String(i.description)),i.processorder!=null&&i.processorder!==""&&(o.order=Number(i.processorder)),a.trim()!==""){let{prolog:s,body:l}=uc(a),u=(0,Ei.parseXmlRoot)(l,"<Activity/>");o.stages=a7(u),o.bag={xaml:(0,Ei.projectElementBag)(u),xamlProlog:s,xamlEol:/\r\n/.test(a)?"crlf":"lf"}}return o}toApiPayload(t){var r;let n={workflowid:t.id&&t.id.trim()!==""?t.id:(0,Rt.newId)(),name:t.name,uniquename:m7(t),primaryentity:t.entityLogicalName,xaml:f7(t),category:ic.WorkflowCategory.BusinessProcessFlow,type:ic.WorkflowTypeCode.Definition,businessprocesstype:ic.BusinessProcessType.BusinessFlow,scope:ic.WorkflowScope.Organization,processorder:(r=t.order)!==null&&r!==void 0?r:Q6};t.description!==void 0&&(n.description=t.description);let i={record:n,status:t.status};if(t.securityRoles&&t.securityRoles.length>0){if(t.status!=="Active")throw new Br.InvalidArgumentError('securityRoles require the BPF to be Active \u2014 the backing table they grant access to is created on activation; set status to "Active" to wire security roles');i.securityRoles=t.securityRoles}return i}createDefault(t){var r,n,i;let a=t.stages&&t.stages.length>0?t.stages.map(E_):[E_({id:(0,Rt.newId)(),name:"New Stage",steps:[]})],o={id:t.id&&t.id.trim()!==""?t.id:(0,Rt.newId)(),name:(r=t.name)!==null&&r!==void 0?r:"New business process flow",entityLogicalName:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",status:(i=t.status)!==null&&i!==void 0?i:"Draft",stages:a};return t.uniqueName&&(o.uniqueName=t.uniqueName),t.description!==void 0&&(o.description=t.description),t.order!==void 0&&(o.order=t.order),t.globalActions!==void 0&&(o.globalActions=t.globalActions),t.securityRoles!==void 0&&(o.securityRoles=t.securityRoles),o}assignMissingIds(t){let r=rh(t);(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,Rt.newId)());for(let n of["stages","steps","actions","globalActions"]){let i=r[n];Array.isArray(i)&&i.forEach(a=>this.assignMissingIds(a))}return r}validate(t){let r=[],n=t.stages;if(n!==void 0&&!Array.isArray(n))return r.push((0,Mt.issue)("/stages","stages-must-be-array",`stages must be an array, got ${typeof n}`)),r;let i=Array.isArray(n)?n:[];i.length>30&&r.push((0,Mt.issue)("/stages","too-many-stages",`a BPF allows at most 30 stages, got ${i.length}`));let a=new Set,o=new Map;i.forEach((l,u)=>{let c=`/stages/${u}`,d=rh(l),p=typeof d.id=="string"?d.id.trim():"";p===""?r.push((0,Mt.issue)(`${c}/id`,"stage-id-required","a stage needs an id")):o.has(p.toLowerCase())?r.push((0,Mt.issue)(`${c}/id`,"stage-id-duplicate",`two stages share the id '${l.id}' (also at /stages/${o.get(p.toLowerCase())})`)):o.set(p.toLowerCase(),u),typeof l.entityLogicalName=="string"&&l.entityLogicalName!==""&&a.add(l.entityLogicalName);let f=Array.isArray(l.steps)?l.steps:[];f.length===0&&r.push((0,Mt.issue)(`${c}/steps`,"stage-needs-step","a BPF stage must have at least one step")),f.length>30&&r.push((0,Mt.issue)(`${c}/steps`,"too-many-steps",`a stage allows at most 30 steps, got ${f.length}`));let m=new Map;f.forEach((g,y)=>{let A=`${c}/steps/${y}`,D=typeof rh(g).id=="string"?g.id.trim():"";D===""?r.push((0,Mt.issue)(`${A}/id`,"step-id-required","a step needs an id")):m.has(D.toLowerCase())?r.push((0,Mt.issue)(`${A}/id`,"step-id-duplicate",`two steps in this stage share the id '${g.id}'`)):m.set(D.toLowerCase(),y)}),l.branch&&!C_(i,l.branch.nextStageId)&&r.push((0,Mt.issue)(`${c}/branch/nextStageId`,"branch-target-unknown",`branch nextStageId '${l.branch.nextStageId}' does not match any stage id`)),typeof l.nextStageId=="string"&&l.nextStageId!==""&&!C_(i,l.nextStageId)&&r.push((0,Mt.issue)(`${c}/nextStageId`,"next-stage-unknown",`nextStageId '${l.nextStageId}' does not match any stage id`))}),a.size>5&&r.push((0,Mt.issue)("/stages","too-many-tables",`a BPF spans at most 5 tables, got ${a.size}`));let s=h7(i);return s>=0&&r.push((0,Mt.issue)(`/stages/${s}/nextStageId`,"next-stage-cycle","the stage nextStageId links form a cycle; the flow must be acyclic")),r}};Wa.BpfAdapter=oc;function h7(e){let t=new Map(e.map(r=>[r.id,r]));for(let r=0;r<e.length;r+=1){let n=new Set,i=e[r];for(;i&&typeof i.nextStageId=="string"&&i.nextStageId!=="";){if(n.has(i.id))return r;n.add(i.id),i=t.get(i.nextStageId)}}return-1}function C_(e,t){return e.some(r=>r.id===t)}function E_(e){var t,r;let n=e.steps&&e.steps.length>0?e.steps.map(S_):[S_({id:(0,Rt.newId)(),name:"New Step"})],i={id:e.id&&e.id.trim()!==""?e.id:(0,Rt.newId)(),name:(t=e.name)!==null&&t!==void 0?t:"New Stage",entityLogicalName:(r=e.entityLogicalName)!==null&&r!==void 0?r:"",steps:n};return e.category!==void 0&&(i.category=e.category),e.nextStageId!==void 0&&(i.nextStageId=e.nextStageId),e.relationshipName!==void 0&&(i.relationshipName=e.relationshipName),e.actions!==void 0&&(i.actions=e.actions),e.branch!==void 0&&(i.branch=e.branch),i}function S_(e){var t;let r={id:e.id&&e.id.trim()!==""?e.id:(0,Rt.newId)(),name:(t=e.name)!==null&&t!==void 0?t:"New Step"};return e.fieldName!==void 0&&(r.fieldName=e.fieldName),e.required!==void 0&&(r.required=e.required),r}function ch(e,t,r,n){return`${nh}<Activity x:Class="XrmWorkflow00000000000000000000000000000000" xmlns="http://schemas.microsoft.com/netfx/2009/xaml/activities" xmlns:mcwb="clr-namespace:Microsoft.Crm.Workflow.BusinessProcessFlowActivities;assembly=Microsoft.Crm.Workflow, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" xmlns:mcwo="clr-namespace:Microsoft.Crm.Workflow.ObjectModel;assembly=Microsoft.Crm, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" xmlns:mva="clr-namespace:Microsoft.VisualBasic.Activities;assembly=System.Activities, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" xmlns:mxs="clr-namespace:Microsoft.Xrm.Sdk;assembly=Microsoft.Xrm.Sdk, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" xmlns:mxswa="clr-namespace:Microsoft.Xrm.Sdk.Workflow.Activities;assembly=Microsoft.Xrm.Sdk.Workflow, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" xmlns:scg="clr-namespace:System.Collections.Generic;assembly=mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" xmlns:sco="clr-namespace:System.Collections.ObjectModel;assembly=mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" xmlns:srs="clr-namespace:System.Runtime.Serialization;assembly=System.Runtime.Serialization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" xmlns:this="clr-namespace:" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"><x:Members><x:Property Name="InputEntities" Type="InArgument(scg:IDictionary(x:String, mxs:Entity))" /><x:Property Name="CreatedEntities" Type="InArgument(scg:IDictionary(x:String, mxs:Entity))" /></x:Members><this:XrmWorkflow00000000000000000000000000000000.InputEntities><InArgument x:TypeArguments="scg:IDictionary(x:String, mxs:Entity)" /></this:XrmWorkflow00000000000000000000000000000000.InputEntities><this:XrmWorkflow00000000000000000000000000000000.CreatedEntities><InArgument x:TypeArguments="scg:IDictionary(x:String, mxs:Entity)" /></this:XrmWorkflow00000000000000000000000000000000.CreatedEntities><mva:VisualBasic.Settings>Assembly references and imported namespaces for internal implementation</mva:VisualBasic.Settings><mxswa:Workflow><mxswa:ActivityReference AssemblyQualifiedName="Microsoft.Crm.Workflow.Activities.EntityComposite, Microsoft.Crm.Workflow, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" DisplayName="EntityStep1: ${e}"><mxswa:ActivityReference.Properties><sco:Collection x:TypeArguments="Variable" x:Key="Variables" /><sco:Collection x:TypeArguments="Activity" x:Key="Activities"><mxswa:ActivityReference AssemblyQualifiedName="Microsoft.Crm.Workflow.Activities.StageComposite, Microsoft.Crm.Workflow, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" DisplayName="StageStep2: New Stage"><mxswa:ActivityReference.Properties><sco:Collection x:TypeArguments="Variable" x:Key="Variables" /><sco:Collection x:TypeArguments="Activity" x:Key="Activities"><mxswa:ActivityReference AssemblyQualifiedName="Microsoft.Crm.Workflow.Activities.StepComposite, Microsoft.Crm.Workflow, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" DisplayName="StepStep3: New Step"><mxswa:ActivityReference.Properties><sco:Collection x:TypeArguments="Variable" x:Key="Variables" /><sco:Collection x:TypeArguments="Activity" x:Key="Activities"><Sequence DisplayName="ControlStep4"><mcwb:Control ControlId="${t}" IsSystemControl="False" IsUnbound="False" SystemStepType="0"><mcwb:Control.ClassId><InArgument x:TypeArguments="x:String"><Literal x:TypeArguments="x:String" Value="" /></InArgument></mcwb:Control.ClassId><mcwb:Control.ControlDisplayName><InArgument x:TypeArguments="x:String"><Literal x:TypeArguments="x:String" Value="" /></InArgument></mcwb:Control.ControlDisplayName><mcwb:Control.DataFieldName><InArgument x:TypeArguments="x:String"><Literal x:TypeArguments="x:String" Value="" /></InArgument></mcwb:Control.DataFieldName><mcwb:Control.Parameters><InArgument x:TypeArguments="x:String"><Literal x:TypeArguments="x:String" Value="" /></InArgument></mcwb:Control.Parameters></mcwb:Control></Sequence></sco:Collection><sco:Collection x:TypeArguments="mcwo:StepLabel" x:Key="StepLabels"><mcwo:StepLabel Description="New Step" LabelId="${n}" LanguageCode="${f_}" /></sco:Collection><x:String x:Key="ProcessStepId">${n}</x:String><x:Boolean x:Key="IsProcessRequired">False</x:Boolean></mxswa:ActivityReference.Properties></mxswa:ActivityReference></sco:Collection><sco:Collection x:TypeArguments="mcwo:StepLabel" x:Key="StepLabels"><mcwo:StepLabel Description="New Stage" LabelId="${r}" LanguageCode="${f_}" /></sco:Collection><x:String x:Key="StageId">${r}</x:String><x:Null x:Key="StageCategory" /><x:Null x:Key="NextStageId" /></mxswa:ActivityReference.Properties></mxswa:ActivityReference></sco:Collection><x:Null x:Key="RelationshipName" /><x:Null x:Key="AttributeName" /><x:Boolean x:Key="IsClosedLoop">False</x:Boolean></mxswa:ActivityReference.Properties></mxswa:ActivityReference></mxswa:Workflow></Activity>`}function g7(){return{adapter:new oc,api:J6.bpfApi,languageSensitive:!0}}Wa.bpfRegistration=g7});var K_=v(cc=>{"use strict";Object.defineProperty(cc,"__esModule",{value:!0});cc.buildRegistrations=void 0;var v7=tD(),y7=yD(),b7=RI(),w7=JI(),A7=f2(),C7=R2(),E7=W2(),S7=t_(),N7=Q_();function D7(e){let t=new Map;return t.set("form",(0,v7.formRegistration)(e)),t.set("view",(0,y7.viewRegistration)()),t.set("businessRule",(0,b7.businessRuleRegistration)()),t.set("app",(0,w7.appRegistration)(e)),t.set("command",(0,A7.commandRegistration)()),t.set("chart",(0,C7.chartRegistration)()),t.set("dashboard",(0,E7.dashboardRegistration)(e)),t.set("genPage",(0,S7.genPageRegistration)()),t.set("bpf",(0,N7.bpfRegistration)()),t}cc.buildRegistrations=D7});var aT=v(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.removeRowSummary=Te.configureRowSummary=Te.buildGptDynamicPrompt=Te.setAppAiFeatures=Te.getAiReadiness=Te.saveSettingValue=Te.retrieveSetting=Te.AI_GATE=void 0;var vr=be(),je=ae(),X_=pt(),pn=te();Te.AI_GATE={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabled",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"EnableNLGridSearch",nlChart:"NLChartVisualizationSetting",summaries:"EnableFormInsights",m365:"m365copilotmodelappenabled"};var tT={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabledOnByDefault",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"NLGridSearchSetting",nlChart:"NLChartDataVisualizationSetting",m365:"m365copilotmodelappenabled"},I7=new Set(Object.entries(Te.AI_GATE).filter(([e,t])=>tT[e]===t).map(([e])=>e)),_7={formFill:{enabled:"2",disabled:"1"},formFillSuggestions:{enabled:"2",disabled:"1"},formFillSmartPaste:{enabled:"2",disabled:"1"},formFillFiles:{enabled:"2",disabled:"1"}};function dh(e){return _7[e]}var dc=1e6;function T7(e,t){let r=dh(t),n=()=>{throw new pn.InvalidArgumentError(`setAppAiFeatures: '${t}' must be a boolean or an integer between 0 and ${dc} (e.g. 0, 1, 2); got '${String(e)}'.`)},i=a=>r?a?r.enabled:r.disabled:a?"1":"0";if(typeof e=="boolean")return i(e);if(typeof e=="number")return!Number.isSafeInteger(e)||e<0||e>dc?n():String(e);if(typeof e=="string"){let a=e.trim(),o=a.toLowerCase();if(o==="true")return i(!0);if(o==="false")return i(!1);if(/^[0-9]+$/.test(a)){let s=a.replace(/^0+(?=[0-9])/,"");return s.length>String(dc).length||Number(s)>dc?n():s}}return n()}function P7(e,t){let r=dh(t);return r?e===r.enabled:e!=="0"}async function O7(e,t){var r,n,i;let a=`/appmodules${(0,je.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,je.odataLiteral)(t)}'`]])}`,o=await e.get(a);return o.status>=200&&o.status<300?(i=((n=(r=o.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0])===null||i===void 0?void 0:i.appmoduleid:void 0}async function R7(e,t){var r,n;let i=`/appmodules${(0,je.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,je.odataLiteral)(t)}'`]])}`,a;try{a=await e.get(i)}catch(l){throw new pn.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup failed (${l.message}). Retry, or omit appModuleId to verify by name.`)}if(a.status<200||a.status>=300)throw new pn.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned HTTP ${a.status}. Retry, or omit appModuleId to verify by name.`);let o=(r=a.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(o))throw new pn.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a malformed body.`);if(o.length===0)return;let s=(n=o[0])===null||n===void 0?void 0:n.appmoduleid;if(!s)throw new pn.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a row with no appmoduleid.`);return s}var Y_=new WeakMap;async function F7(e,t){var r,n,i;let a=Y_.get(e);if(a||(a=new Map,Y_.set(e,a)),a.has(t))return a.get(t);let o=`/settingdefinitions${(0,je.odataQuery)([["$select","settingdefinitionid"],["$filter",`uniquename eq '${(0,je.odataLiteral)(t)}'`]])}`,s=await e.get(o),l=s.status>=200&&s.status<300?(i=((n=(r=s.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0])===null||i===void 0?void 0:i.settingdefinitionid:void 0;return l&&a.set(t,l),l}async function x7(e,t,r){var n,i;let a=await F7(e,r);if(!t||!a)return;let o=`/appsettings${(0,je.odataQuery)([["$select","value"],["$filter",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${a}`]])}`,s=await e.get(o);if(s.status<200||s.status>=300)return;let l=(i=(n=s.body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[];return l.length>0?{exists:!0,value:l[0].value}:{exists:!1}}var L7=4,k7=500,Z_=20,eT=3e4;function M7(e){if(e===void 0)return L7;if(!Number.isFinite(e))throw new pn.InvalidArgumentError(`setAppAiFeatures: verifyAttempts must be a finite integer between 1 and ${Z_}; got ${e}.`);return Math.min(Z_,Math.max(1,Math.floor(e)))}function U7(e){if(e===void 0)return k7;if(!Number.isFinite(e))throw new pn.InvalidArgumentError(`setAppAiFeatures: verifyDelayMs must be a finite number between 0 and ${eT}; got ${e}.`);return Math.min(eT,Math.max(0,Math.floor(e)))}async function B7(e,t,r,n,i,a,o){let s,l,u,c=!1;for(let d=0;d<a;d+=1){d>0&&await new Promise(f=>setTimeout(f,o*d));let p;try{let f=await t();f?(p=await x7(e,f,n),p===void 0&&(u="the app-scope override row could not be read (insufficient access or unresolvable ids)")):u=`the app '${r}' could not be resolved to an appmoduleid \u2014 a newly created app is not readable until it is published, so either publish it first or pass \`appModuleId\` in the options to verify without the lookup`}catch(f){p=void 0,u=f.message}c=p!==void 0,l=p?.exists;try{s=(await pc(e,n,{appUniqueName:r})).value}catch{}if(p?.exists&&p.value===i)return{result:"proven",effectiveValue:p.value,appOverrideExists:!0}}return c?{result:"absent",effectiveValue:s,appOverrideExists:l}:{result:"unverifiable",effectiveValue:s,appOverrideExists:void 0,reason:u}}function rT(e,t,r){if(t===2)return String(e).toLowerCase()==="true";let n=r?dh(r):void 0;return n?e===n.enabled:e!=null&&e!=="0"&&e!==""}async function pc(e,t,r={}){var n,i;let a=[`SettingName='${(0,je.odataPathLiteral)(t)}'`];r.appUniqueName&&a.push(`AppUniqueName='${(0,je.odataPathLiteral)(r.appUniqueName)}'`);let o=`/RetrieveSetting(${a.join(",")})`,l=(i=(n=(0,vr.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.SettingDetail)!==null&&i!==void 0?i:{};return{value:l.Value,dataType:l.DataType}}Te.retrieveSetting=pc;async function nT(e,t,r,n={}){let i={SettingName:t,Value:r};n.appUniqueName&&(i.AppUniqueName=n.appUniqueName),n.solutionUniqueName&&(i.SolutionUniqueName=n.solutionUniqueName),(0,vr.ensureSuccess)(await e.post("/SaveSettingValue",i),e.apiUrl("/SaveSettingValue"))}Te.saveSettingValue=nT;async function $7(e,t={}){let r={};for(let[n,i]of Object.entries(Te.AI_GATE)){let{value:a,dataType:o}=await pc(e,i,t);r[n]={enabled:rT(a,o,n),setting:i,value:a}}return r}Te.getAiReadiness=$7;async function q7(e,t,r,n={}){var i,a;if(!t||!t.trim())throw new pn.InvalidArgumentError("setAppAiFeatures: a non-empty appUniqueName is required (an empty value would write the setting at organization scope, affecting every app).");let o=M7(n.verifyAttempts),s=U7(n.verifyDelayMs),l=[];for(let[g,y]of Object.entries(r)){if(y===void 0)continue;let A=tT[g];A&&l.push({feature:g,setting:A,requestedValue:T7(y,g)})}let u=[],c=n.appModuleId?(0,je.normalizeGuid)(n.appModuleId,"appModuleId"):void 0;if(c){let g=await R7(e,t);if(g&&(0,je.normalizeGuid)(g,"appModuleId")!==c)throw new pn.InvalidArgumentError(`setAppAiFeatures: appModuleId '${c}' does not belong to app '${t}' (which resolves to '${g}'). Settings are written by unique name, so verifying against a different app would report success for a write that never landed.`)}let d,p=async()=>c||(d||(d=await O7(e,t)),d),f=new Map,m=async g=>{if(I7.has(g))return;let y=Te.AI_GATE[g];if(y){if(!f.has(y))try{let{value:A,dataType:D}=await pc(e,y);f.set(y,{enabled:rT(A,D,g),setting:y,value:A})}catch{f.set(y,void 0)}return f.get(y)}};for(let{feature:g,setting:y,requestedValue:A}of l)try{await nT(e,y,A,{appUniqueName:t,solutionUniqueName:n.solutionUniqueName});let D=await B7(e,p,t,y,A,o,s),F={feature:g,setting:y,requestedValue:A,effectiveValue:D.effectiveValue,appOverrideExists:D.appOverrideExists};if(D.result==="proven")u.push({...F,status:"applied"});else if(D.result==="absent"){let _=P7(A,g)?await m(g):void 0;_&&!_.enabled?u.push({...F,status:"skipped",reason:`the write was issued and no app-scope override holding '${A}' was observed for '${y}' after ${o} attempt(s); the org readiness gate '${_.setting}' reads '${_.value}', so an environment admin must enable it before this app can turn the feature on`}):u.push({...F,status:"notPersisted",reason:`the write reported success but no app-scope override holding '${A}' was observed for '${y}' after ${o} attempt(s) \u2014 it reads '${(i=D.effectiveValue)!==null&&i!==void 0?i:""}' for this app (Dataverse can accept an app-scope write without storing it)`})}else u.push({...F,status:"unverified",reason:`the write was issued but could not be confirmed: ${(a=D.reason)!==null&&a!==void 0?a:"the app-scope override row could not be read"}. The value may or may not be in force \u2014 verify manually before relying on it.`})}catch(D){u.push({feature:g,setting:y,requestedValue:A,status:"failed",reason:D.message})}return{applied:u.filter(g=>g.status==="applied").map(g=>g.feature),skipped:u.filter(g=>g.status==="skipped").map(g=>g.feature),notPersisted:u.filter(g=>g.status==="notPersisted").map(g=>g.feature),unverified:u.filter(g=>g.status==="unverified").map(g=>g.feature),failed:u.filter(g=>g.status==="failed").map(g=>g.feature),outcomes:u}}Te.setAppAiFeatures=q7;var V7="GptPowerPrompt",G7='{ "consumptionSource": "Api", "partnerSource": "AIBuilder", "consumptionSourceVersion": "GptApiClient"}';function iT(e){var t,r,n,i;let a=e.entityLogicalName,o=[{type:"literal",text:e.instruction.replace(/\s*$/,"")+" "}];return e.columns.forEach((s,l)=>{o.push({type:"data",id:`${a}.${s.logical}`,text:s.display}),l<e.columns.length-1&&o.push({type:"literal",text:", "})}),{version:"GptDynamicPrompt-2",prompt:o,definitions:{inputs:[{id:"RecordId",text:"RecordId",type:"text"},{id:"LanguageCode",text:"LanguageCode",type:"text"}],formulas:[],data:[{id:a,displayName:a,type:"dataverseTable",filters:[{filterType:"equal",attribute:e.primaryKey,valueType:"inputVariable",value:"RecordId"}]}],output:{formats:[(t=e.outputFormat)!==null&&t!==void 0?t:"text"]}},modelParameters:{modelType:"default",gptParameters:{temperature:(r=e.temperature)!==null&&r!==void 0?r:0}},settings:{recordRetrievalLimit:(n=e.recordRetrievalLimit)!==null&&n!==void 0?n:30,shouldPreserveRecordLinks:null,runtime:null,enableReasoning:(i=e.enableReasoning)!==null&&i!==void 0?i:!0},code:"",signature:""}}Te.buildGptDynamicPrompt=iT;async function z7(e,t){var r,n;let i=`/EntityDefinitions(LogicalName='${(0,je.odataPathLiteral)(t)}')${(0,je.odataQuery)([["$select","MetadataId"]])}`;return(n=(r=(0,vr.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||r===void 0?void 0:r.MetadataId)!==null&&n!==void 0?n:""}async function W7(e,t,r={}){var n,i,a,o,s;let l=`ais_RowSummary_${t.entityLogicalName}`,u=`/aiskillconfigs${(0,je.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,je.odataLiteral)(l)}'`],["$top",1]])}`,c=((i=(n=(0,vr.ensureSuccess)(await e.get(u),e.apiUrl(u)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[])[0];if(c)return{modelId:c._aimodel_value,aiSkillConfigId:c.aiskillconfigid};let d=`/msdyn_aitemplates${(0,je.odataQuery)([["$select","msdyn_aitemplateid"],["$filter",`msdyn_uniquename eq '${V7}'`],["$top",1]])}`,p=((s=(o=(a=(0,vr.ensureSuccess)(await e.get(d),e.apiUrl(d)).body)===null||a===void 0?void 0:a.value)===null||o===void 0?void 0:o[0])!==null&&s!==void 0?s:{}).msdyn_aitemplateid,f=(0,X_.newId)(),m=(0,X_.newId)(),g=JSON.stringify(iT(t)),y={ModelId:f,RunConfigurationId:m,ModelName:`${t.entityLogicalName} row summary`,TemplateId:p,CustomConfiguration:g,Source:G7,RunConfiguration:""};(0,vr.ensureSuccess)(await e.post("/AIModelPublish",y),e.apiUrl("/AIModelPublish"));try{let A=await z7(e,t.entityLogicalName),D={uniquename:l,description:`${t.entityLogicalName} row summary`,"[email protected]":`/entities(${A})`,"[email protected]":`/msdyn_aimodels(${f})`,aiskill:"RowSummary"},F=(0,vr.ensureSuccess)(await e.post("/aiskillconfigs",D),e.apiUrl("/aiskillconfigs")),_=(0,vr.requireCreatedId)(F,"aiskillconfigid","row-summary skill");return{modelId:f,aiSkillConfigId:_}}catch(A){try{await e.delete(`/msdyn_aimodels(${f})`)}catch{}throw A}}Te.configureRowSummary=W7;async function H7(e,t){var r,n;let i=`ais_RowSummary_${t.entityLogicalName}`,a=`/aiskillconfigs${(0,je.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,je.odataLiteral)(i)}'`],["$top",1]])}`,o=((n=(r=(0,vr.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0];if(!o)return;let s=`/aiskillconfigs(${o.aiskillconfigid})`;if((0,vr.ensureSuccess)(await e.delete(s),e.apiUrl(s)),o._aimodel_value){let l=`/msdyn_aimodels(${o._aimodel_value})`;(0,vr.ensureSuccess)(await e.delete(l),e.apiUrl(l))}}Te.removeRowSummary=H7});var oT=v(Ha=>{"use strict";Object.defineProperty(Ha,"__esModule",{value:!0});Ha.findArtifact=Ha.resolveArtifact=void 0;var bt=ae(),fn=ll(),j7=ml(),J7=be(),Q7=te();async function K7(e,t,r){var n,i,a,o,s,l,u,c,d,p,f,m;switch(t){case"app":{let g=(0,j7.unpublishedAppModulesQuery)("appmoduleid,name,appmoduleidunique",`uniquename eq '${(0,bt.odataLiteral)((n=r.uniqueName)!==null&&n!==void 0?n:"")}'`,1),A=(i=(0,J7.ensureSuccess)(await e.get(g),e.apiUrl(g)).body)===null||i===void 0?void 0:i.value,D=A&&A[0];return D?[{id:String(D.appmoduleid),name:String(D.name),appModuleIdUnique:String(D.appmoduleidunique)}]:[]}case"dashboard":return(await(0,fn.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,bt.odataLiteral)((a=r.name)!==null&&a!==void 0?a:"")}' and type eq 0`,top:10})||[]).map(y=>({id:String(y.formid),name:String(y.name)}));case"command":{let g=await(0,fn.queryRecords)(e,"appaction",{select:["appactionid","buttonlabeltext"],filter:`contextvalue eq '${(0,bt.odataLiteral)((o=r.entity)!==null&&o!==void 0?o:"")}'`,top:1});return g&&g.length?[{id:String(r.entity),entity:String(r.entity)}]:[]}case"form":return(await(0,fn.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,bt.odataLiteral)((s=r.name)!==null&&s!==void 0?s:"")}' and objecttypecode eq '${(0,bt.odataLiteral)((l=r.entity)!==null&&l!==void 0?l:"")}'`,top:10})||[]).map(y=>({id:String(y.formid),name:String(y.name)}));case"chart":return(await(0,fn.queryRecords)(e,"savedqueryvisualization",{select:["savedqueryvisualizationid","name"],filter:`name eq '${(0,bt.odataLiteral)((u=r.name)!==null&&u!==void 0?u:"")}' and primaryentitytypecode eq '${(0,bt.odataLiteral)((c=r.entity)!==null&&c!==void 0?c:"")}'`,top:10})||[]).map(y=>({id:String(y.savedqueryvisualizationid),name:String(y.name)}));case"view":return(await(0,fn.queryRecords)(e,"savedquery",{select:["savedqueryid","name"],filter:`name eq '${(0,bt.odataLiteral)((d=r.name)!==null&&d!==void 0?d:"")}' and returnedtypecode eq '${(0,bt.odataLiteral)((p=r.entity)!==null&&p!==void 0?p:"")}'`,top:10})||[]).map(y=>({id:String(y.savedqueryid),name:String(y.name)}));case"webResource":return(await(0,fn.queryRecords)(e,"webresource",{select:["webresourceid","name"],filter:`name eq '${(0,bt.odataLiteral)((f=r.name)!==null&&f!==void 0?f:"")}'`,top:1})||[]).map(y=>({id:String(y.webresourceid),name:String(y.name)}));case"solution":return(await(0,fn.queryRecords)(e,"solution",{select:["solutionid","uniquename"],filter:`uniquename eq '${(0,bt.odataLiteral)((m=r.uniqueName)!==null&&m!==void 0?m:"")}'`,top:1})||[]).map(y=>({id:String(y.solutionid),name:String(y.uniquename)}));default:return[]}}Ha.resolveArtifact=K7;async function X7(e,t,r){var n,i,a,o,s;let l=(0,bt.odataLiteral)((n=r.name)!==null&&n!==void 0?n:""),u=(0,bt.odataLiteral)((i=r.entity)!==null&&i!==void 0?i:"");if(t==="command"){let m=await(0,fn.queryRecords)(e,"appaction",{select:["appactionid"],filter:`contextvalue eq '${(0,bt.odataLiteral)((a=r.entity)!==null&&a!==void 0?a:"")}'`,top:1});return m&&m.length?String(r.entity):null}let c=Y7(t,l,u,r),d=t!=="app",p=await(0,fn.queryRecords)(e,c.set,{select:[c.idField],filter:c.filter,top:d?2:1});if(d&&p&&p.length>1)throw new Q7.AmbiguousArtifactError(t,(s=(o=r.name)!==null&&o!==void 0?o:r.uniqueName)!==null&&s!==void 0?s:"",p.length);let f=p&&p[0]&&p[0][c.idField];return f!=null?String(f):null}Ha.findArtifact=X7;function Y7(e,t,r,n){var i;switch(e){case"view":return{set:"savedquery",idField:"savedqueryid",filter:`returnedtypecode eq '${r}' and name eq '${t}'`};case"chart":return{set:"savedqueryvisualization",idField:"savedqueryvisualizationid",filter:`primaryentitytypecode eq '${r}' and name eq '${t}'`};case"form":return{set:"systemform",idField:"formid",filter:`objecttypecode eq '${r}' and name eq '${t}'`};case"app":return{set:"appmodule",idField:"appmoduleid",filter:`uniquename eq '${(0,bt.odataLiteral)((i=n.uniqueName)!==null&&i!==void 0?i:"")}'`};case"dashboard":return{set:"systemform",idField:"formid",filter:`name eq '${t}' and type eq 0`};default:throw new Error(`Unsupported findable kind: ${e}`)}}});var lT=v(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});mc.seedRecordGraph=void 0;var sT=ll(),Z7=qs(),fc=ae(),ez=te();async function tz(e,t,r={}){var n,i,a,o,s;let l=(n=r.createdIds)!==null&&n!==void 0?n:{},u=(i=r.entitySetFor)!==null&&i!==void 0?i:(p=>(0,Z7.resolveEntitySetName)(e,p)),c={},d=p=>{var f;return(f=c[p])!==null&&f!==void 0?f:l[p]};for(let p of t){let f=p.entityLogical.toLowerCase(),m=(a=p.matchOn)===null||a===void 0?void 0:a.toLowerCase(),g=[];for(let B of p.records){let L={...B.body};for(let k of(o=B.binds)!==null&&o!==void 0?o:[]){let M=k.parentEntity.toLowerCase(),G=(s=d(M))===null||s===void 0?void 0:s[k.parentIndex];if(!G)throw new ez.InvalidArgumentError(`Cannot resolve bind '${k.navProperty}' on a '${f}' record: parent '${k.parentEntity}'[${k.parentIndex}] has no created id. Seed the parent group before the child, or supply it via options.createdIds.`);let V=(0,fc.assertODataName)(await u(M),`entity set for parent '${k.parentEntity}'`),Ze=(0,fc.normalizeGuid)(G,`parent id for bind '${k.navProperty}'`);L[`${k.navProperty}@odata.bind`]=`/${V}(${Ze})`}g.push(L)}let y=m?g.map(B=>{let L=B[m];return L!=null&&L!==""?String(L):null}):g.map(()=>null),A=new Map;if(m){let B=(0,fc.assertODataName)(m,"RecordGraph matchOn key"),L=[...new Set(y.filter(k=>k!==null))];if(L.length){let k=L.map(G=>`${B} eq '${(0,fc.odataLiteral)(G)}'`).join(" or "),M=await(0,sT.queryRecords)(e,f,{select:[B,`${f}id`],filter:k,top:5e3});for(let G of M??[]){let V=G[B];V!=null&&A.set(String(V).toLowerCase(),String(G[`${f}id`]))}}}let D=[],F=new Map,_=g.map((B,L)=>{let k=y[L];if(k&&A.has(k.toLowerCase()))return null;if(k){let M=k.toLowerCase(),G=F.get(M);if(G!==void 0)return G;let V=D.push(B)-1;return F.set(M,V),V}return D.push(B)-1}),q=D.length?await(0,sT.createRecordsBulk)(e,f,D):[];c[f]=g.map((B,L)=>{let k=y[L];return k&&A.has(k.toLowerCase())?A.get(k.toLowerCase()):q[_[L]]})}return{createdIds:c}}mc.seedRecordGraph=tz});var yT=v(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.getEntityPrivileges=lt.addEntityPrivilegesToRole=lt.deleteSecurityRole=lt.createPersonaRole=lt.createSecurityRole=lt.SDK_ROLE_MARKER=void 0;var yr=be(),Je=ae(),Ut=te(),hc={read:"Read",create:"Create",write:"Write",delete:"Delete",append:"Append",appendTo:"AppendTo",assign:"Assign",share:"Share"},fh={user:"Basic",businessUnit:"Local",parentChild:"Deep",organization:"Global"},uT={user:1,businessUnit:2,parentChild:3,organization:4},ph={user:"CanBeBasic",businessUnit:"CanBeLocal",parentChild:"CanBeDeep",organization:"CanBeGlobal"};lt.SDK_ROLE_MARKER="Authored by @maker-studio/cds-maker-sdk (persona/security role).";function rz(e){return Object.prototype.hasOwnProperty.call(hc,e)?hc[e]:void 0}function nz(e){return Object.prototype.hasOwnProperty.call(fh,e)}var cT=new WeakMap,dT=new WeakMap;async function mT(e,t){var r,n;(0,Je.assertODataName)(t,"entity logical name");let i=cT.get(e);i||(i=new Map,cT.set(e,i));let a=i.get(t);if(a)return a;let o=`/EntityDefinitions(LogicalName='${(0,Je.odataPathLiteral)(t)}')${(0,Je.odataQuery)([["$select","LogicalName,Privileges"]])}`,l=(n=(r=(0,yr.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||r===void 0?void 0:r.Privileges)!==null&&n!==void 0?n:[];if(l.length===0)throw new Ut.InvalidArgumentError(`Entity '${t}' exposes no privileges (unknown or non-securable entity).`);return i.set(t,l),l}async function iz(e){var t,r,n;let i=dT.get(e);if(i)return i;let a=`/businessunits${(0,Je.odataQuery)([["$select","businessunitid"],["$filter","_parentbusinessunitid_value eq null"],["$top",1]])}`,l=(n=((r=(t=(0,yr.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||t===void 0?void 0:t.value)!==null&&r!==void 0?r:[])[0])===null||n===void 0?void 0:n.businessunitid;if(!l)throw new Ut.InvalidArgumentError("Could not resolve the root business unit.");let u=(0,Je.normalizeGuid)(l,"businessUnitId");return dT.set(e,u),u}async function hT(e,t){var r;let n=new Map;for(let i of t){if(!i.access||i.access.length===0)throw new Ut.InvalidArgumentError(`Entity '${i.entity}' privilege request has no access levels.`);let a=(r=i.scope)!==null&&r!==void 0?r:"user";if(!nz(a))throw new Ut.InvalidArgumentError(`Unknown privilege scope '${a}' for entity '${i.entity}'.`);let o=await mT(e,i.entity);for(let s of i.access){let l=rz(s);if(!l)throw new Ut.InvalidArgumentError(`Unknown access level '${s}' for entity '${i.entity}'.`);let u=o.find(m=>m.PrivilegeType===l);if(!u)throw new Ut.InvalidArgumentError(`Entity '${i.entity}' does not support '${s}' access.`);let c=ph[a];if(u[c]===!1)throw new Ut.InvalidArgumentError(`Privilege '${u.Name}' on '${i.entity}' does not support the '${a}' scope.`);let d=(0,Je.normalizeGuid)(u.PrivilegeId,"PrivilegeId"),p=n.get(d);if(!p){n.set(d,{privilegeName:u.Name,privilegeType:l,scope:a,entities:new Set([i.entity])});continue}if(p.scope===a){p.entities.add(i.entity);continue}if(!(p.entities.size===1&&p.entities.has(i.entity))){let m=[...p.entities].sort().join(", ");throw new Ut.InvalidArgumentError(`Entities '${m}' and '${i.entity}' share the Dataverse privilege '${u.Name}' but request different scopes; a role holds one depth per privilege. Use the same scope for all entities that share this privilege, or split them.`)}p.scope=uT[a]>uT[p.scope]?a:p.scope}}return[...n.entries()].map(([i,a])=>({entity:[...a.entities].sort().join(", "),privilegeId:i,privilegeName:a.privilegeName,privilegeType:a.privilegeType,scope:a.scope}))}async function az(e,t,r,n){if(r.length===0&&!n)return;let i={Privileges:r.map(o=>({Depth:fh[o.scope],PrivilegeId:o.privilegeId}))},a=`/roles(${t})/Microsoft.Dynamics.CRM.ReplacePrivilegesRole`;(0,yr.ensureSuccess)(await e.post(a,i),e.apiUrl(a))}async function pT(e,t,r,n,i){var a,o;let s=`/${t}(${r})/${n}${(0,Je.odataQuery)([["$select","roleid"],["$filter",`roleid eq ${i}`]])}`;return((o=(a=(0,yr.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||a===void 0?void 0:a.value)!==null&&o!==void 0?o:[]).length>0}async function oz(e,t,r){var n,i;let a=[],o=[],s={"@odata.id":e.apiUrl(`/roles(${t})`)};for(let l of(n=r?.teams)!==null&&n!==void 0?n:[]){let u=(0,Je.normalizeGuid)(l,"teamId");if(!await pT(e,"teams",u,"teamroles_association",t)){let c=`/teams(${u})/teamroles_association/$ref`;(0,yr.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}a.push(u)}for(let l of(i=r?.users)!==null&&i!==void 0?i:[]){let u=(0,Je.normalizeGuid)(l,"userId");if(!await pT(e,"systemusers",u,"systemuserroles_association",t)){let c=`/systemusers(${u})/systemuserroles_association/$ref`;(0,yr.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}o.push(u)}return{teams:a,users:o}}async function fT(e,t,r){var n,i;let a=`/roles${(0,Je.odataQuery)([["$select","roleid,description,ismanaged"],["$filter",`name eq '${(0,Je.odataLiteral)(t)}' and _businessunitid_value eq ${r}`]])}`,l=((i=(n=(0,yr.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]).filter(d=>!!d.roleid);if(l.length===0)return;let u=d=>{var p;return d.ismanaged!==!0&&((p=d.description)!==null&&p!==void 0?p:"")===lt.SDK_ROLE_MARKER};if(l.some(d=>!u(d)))throw new Ut.InvalidArgumentError(`A role named '${t}' already exists in this business unit and was not created by the SDK; refusing to modify or assign it. Choose a different persona/role name.`);if(l.length>1)throw new Ut.InvalidArgumentError(`Multiple (${l.length}) SDK-owned roles named '${t}' exist in this business unit; refusing to reuse one arbitrarily. Remove the duplicate role(s) and retry.`);let c=l[0].roleid;return c?(0,Je.normalizeGuid)(c,"roleId"):void 0}function sz(e){var t,r;return{teams:((t=e?.teams)!==null&&t!==void 0?t:[]).map(n=>(0,Je.normalizeGuid)(n,"teamId")),users:((r=e?.users)!==null&&r!==void 0?r:[]).map(n=>(0,Je.normalizeGuid)(n,"userId"))}}function gT(e){return e.map(t=>({entity:t.entity,privilegeName:t.privilegeName,privilegeType:t.privilegeType,scope:t.scope}))}async function vT(e,t){var r,n;let i=(r=t.name)===null||r===void 0?void 0:r.trim();if(!i)throw new Ut.InvalidArgumentError("createSecurityRole: a non-empty role name is required.");let a=t.businessUnitId?(0,Je.normalizeGuid)(t.businessUnitId,"businessUnitId"):await iz(e),o=await hT(e,(n=t.privileges)!==null&&n!==void 0?n:[]),s=sz(t.assignTo),l=await fT(e,i,a),u=l!==void 0;if(!l){let d="/roles",p={name:i,description:lt.SDK_ROLE_MARKER,"[email protected]":`/businessunits(${a})`};try{let f=(0,yr.ensureSuccess)(await e.post(d,p),e.apiUrl(d));l=(0,Je.normalizeGuid)((0,yr.requireCreatedId)(f,"roleid","role"),"roleId")}catch(f){let m;try{m=await fT(e,i,a)}catch{m=void 0}if(!m)throw f;l=m}}await az(e,l,o,u);let c=await oz(e,l,s);return{roleId:l,name:i,reused:u,appliedPrivileges:gT(o),assignedTeams:c.teams,assignedUsers:c.users}}lt.createSecurityRole=vT;async function lz(e,t){var r,n;let i=(r=t.persona)===null||r===void 0?void 0:r.trim();if(!i)throw new Ut.InvalidArgumentError("createPersonaRole: a non-empty persona name is required.");let a=[...t.jobs.flatMap(o=>{var s;return(s=o.privileges)!==null&&s!==void 0?s:[]}),...(n=t.additionalPrivileges)!==null&&n!==void 0?n:[]];return vT(e,{name:i,businessUnitId:t.businessUnitId,privileges:a,assignTo:t.assignTo})}lt.createPersonaRole=lz;async function uz(e,t){let n=`/roles(${(0,Je.normalizeGuid)(t,"roleId")})`;(0,yr.ensureSuccess)(await e.delete(n),e.apiUrl(n))}lt.deleteSecurityRole=uz;async function cz(e,t,r){let n=(0,Je.normalizeGuid)(t,"roleId");if(r.length===0)throw new Ut.InvalidArgumentError("addEntityPrivilegesToRole requires at least one entity privilege (an empty grant would be a silent no-op).");let i=await hT(e,r),a={Privileges:i.map(s=>({Depth:fh[s.scope],PrivilegeId:s.privilegeId}))},o=`/roles(${n})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;return(0,yr.ensureSuccess)(await e.post(o,a),e.apiUrl(o)),gT(i)}lt.addEntityPrivilegesToRole=cz;var dz=new Map(Object.keys(hc).map(e=>[hc[e],e]));async function pz(e,t){return(await mT(e,t)).map(n=>{let i=Object.keys(ph).filter(o=>n[ph[o]]!==!1),a=dz.get(n.PrivilegeType);return{name:n.Name,privilegeId:n.PrivilegeId,privilegeType:n.PrivilegeType,...a?{access:a}:{},scopes:i}})}lt.getEntityPrivileges=pz});var DT=v(Bt=>{"use strict";Object.defineProperty(Bt,"__esModule",{value:!0});Bt.createMakerSdk=Bt.MakerSdk=Bt.PUSH_NOT_ATTEMPTED_CODE=Bt.ALREADY_EXISTS_CODE=void 0;var bT=kc(),ee=te(),nr=Rs(),fz=kg(),NT=Vg(),ws=Jg(),mz=Uc(),hz=f0(),mh=m0(),Qe=qs(),wT=Cd(),mn=ll(),gc=qv(),ja=cl(),gz=pl(),ut=Jv(),vz=xd(),yz=K_(),bz=pt(),wz=Ri(),hn=gm(),AT=qc(),Az=3e5,Vr=be(),Xn=ae(),Ja=aT(),CT=oT(),Cz=lT(),Ez=Lf(),As=yT();function Sz(e){let t=e.workspaceStorage;if(t==null)throw new Error("createMakerSdk requires a workspaceStorage. Node callers can build one with `createNodeWorkspaceStorage(path)` from '@maker-studio/cds-maker-sdk/node'; a host with no filesystem implements WorkspaceStorage directly.");return new NT.WorkspaceManager(Nz,e.instanceUrl,(0,mz.assertStorageContract)(t))}Bt.ALREADY_EXISTS_CODE="ARTIFACT_ALREADY_EXISTS";Bt.PUSH_NOT_ATTEMPTED_CODE="PUSH_NOT_ATTEMPTED";var Nz="<injected workspaceStorage>",vc=class{constructor(t){var r,n;this.artifactLocks=new Map,this.languageCode=(r=t.languageCode)!==null&&r!==void 0?r:wz.DEFAULT_LCID,this.cacheStalenessMs=(n=t.cacheStalenessMs)!==null&&n!==void 0?n:Az,this.workspace=Sz(t),this.versions=new ws.VersionManager(this.workspace),this.dataverse=new hz.DataverseClient(t.instanceUrl,t.httpClient,t.solutionUniqueName),this.registrations=(0,yz.buildRegistrations)(this.languageCode)}async initWorkspace(){await this.workspace.init()}async getManifest(){return this.workspace.getManifest()}async cleanWorkspace(){await this.workspace.clean()}withArtifactLock(t,r,n){var i;let a=`${t}\0${(0,NT.canonicalArtifactId)(r)}`,s=((i=this.artifactLocks.get(a))!==null&&i!==void 0?i:Promise.resolve()).then(n,n),l=s.then(()=>{},()=>{});return this.artifactLocks.set(a,l),l.then(()=>{this.artifactLocks.get(a)===l&&this.artifactLocks.delete(a)}),s}async fetchArtifact(t,r,n){return this.withArtifactLock(t,r,()=>this.fetchArtifactUnlocked(t,r,n))}async fetchArtifactUnlocked(t,r,n){var i,a;let o=this.requireRegistration(t,"fetchArtifact"),{raw:s,etag:l,memberEtags:u,siblingEtags:c}=await o.api.get(this.dataverse,r),d=o.adapter.fromApiResponse(s);if(!n?.overwrite&&await this.versions.isDirty(t,r)){let p=(a=(i=await this.versions.getMeta(t,r))===null||i===void 0?void 0:i.etag)!==null&&a!==void 0?a:null;if(p&&l&&p!==l)throw new ee.LocalEditsWouldBeLostError(t,r,p,l);let f=await this.workspace.readArtifact(t,r);if(f){let m=await this.versions.getMeta(t,r);if(m&&!m.etag&&l){if(!(0,AT.deepEqual)(m.snapshot,d))throw new ee.LocalEditsWouldBeLostError(t,r,p,l);await this.versions.storeMeta(t,r,{...m,etag:l,fetchedAt:(0,Vr.nowIso)()})}return(0,hn.cloneJson)(f)}}return await this.workspace.writeArtifact(t,r,d),await this.versions.storeMeta(t,r,{etag:l,languageCode:this.languageCode,projectionVersion:ws.PROJECTION_VERSION,fetchedAt:(0,Vr.nowIso)(),snapshot:(0,hn.cloneJson)(d),...u?{memberEtags:u}:{},...c?{siblingEtags:c}:{}}),(0,hn.cloneJson)(d)}async fetchArtifactList(t,r){return this.requireRegistration(t,"fetchArtifactList").api.list(this.dataverse,r)}async fetchSolution(t){var r;let n=await(0,ut.fetchSolutionComponents)(this.dataverse,t),i=[],a=[];for(let o of n)try{let s=await this.resolveComponentType(o);if(!s){a.push({componentId:o.objectId,componentType:o.componentType,workflowCategory:o.workflowCategory,reason:"unsupported"});continue}let l=await this.fetchArtifact(s,o.objectId);i.push({type:s,id:o.objectId,name:typeof l.name=="string"?l.name:(r=o.displayName)!==null&&r!==void 0?r:o.objectId,entityLogicalName:typeof l.entityLogicalName=="string"?l.entityLogicalName:void 0,lastFetched:(0,Vr.nowIso)(),isDirty:!1})}catch(s){a.push({componentId:o.objectId,componentType:o.componentType,workflowCategory:o.workflowCategory,reason:"failed",error:Cs(s)})}return await this.workspace.updateManifest({lastSyncAt:(0,Vr.nowIso)()}),{summaries:i,skipped:a}}async fetchEntityMetadata(t){let r=await(0,mh.fetchEntityMetadataFromApi)(this.dataverse,t);return await this.workspace.writeEntityMetadata(t,r),r}findTables(t,r){return(0,mh.findTables)(this.dataverse,t,r)}findColumns(t,r,n){return(0,mh.findColumns)(this.dataverse,t,r,n)}createTable(t){return(0,Qe.createTable)(this.dataverse,t)}createColumn(t,r){return(0,Qe.createColumn)(this.dataverse,t,r)}createColumns(t,r){return(0,Qe.createColumns)(this.dataverse,t,r)}updateColumn(t,r,n){return(0,Qe.updateColumn)(this.dataverse,t,r,n)}deleteColumn(t,r){return(0,Qe.deleteColumn)(this.dataverse,t,r)}setFormSecurityRoles(t,r){return(0,wT.setFormSecurityRoles)(this.dataverse,t,r)}getFormSecurityRoles(t){return(0,wT.getFormSecurityRoles)(this.dataverse,t)}setColumnVisualization(t,r,n){return(0,Qe.setColumnVisualization)(this.dataverse,t,r,n)}getColumnVisualization(t,r){return(0,Qe.getColumnVisualization)(this.dataverse,t,r)}createCustomerColumn(t,r){return(0,Qe.createCustomerColumn)(this.dataverse,t,r)}insertStatusValue(t,r){return(0,Qe.insertStatusValue)(this.dataverse,t,r)}updateTable(t,r){return(0,Qe.updateTable)(this.dataverse,t,r)}async setEntityIcon(t,r){if(await(0,Qe.updateTable)(this.dataverse,t,{iconVectorName:r.vector,iconSmallName:r.small,iconMediumName:r.medium,iconLargeName:r.large}),r.publish!==!1){let n=`<importexportxml><entities><entity>${(0,Xn.xmlText)(t)}</entity></entities></importexportxml>`;(0,Vr.ensureSuccess)(await this.dataverse.post("/PublishXml",{ParameterXml:n}),this.dataverse.apiUrl("/PublishXml"))}}createAlternateKey(t,r){return(0,Qe.createAlternateKey)(this.dataverse,t,r)}deleteAlternateKey(t,r){return(0,Qe.deleteAlternateKey)(this.dataverse,t,r)}createRelationship(t){return(0,Qe.createRelationship)(this.dataverse,t)}deleteRelationship(t){return(0,Qe.deleteRelationship)(this.dataverse,t)}createGlobalOptionSet(t){return(0,Qe.createGlobalOptionSet)(this.dataverse,t)}deleteGlobalOptionSet(t){return(0,Qe.deleteGlobalOptionSet)(this.dataverse,t)}deleteTable(t){return(0,Qe.deleteTable)(this.dataverse,t)}createSecurityRole(t){return(0,As.createSecurityRole)(this.dataverse,t)}createPersonaRole(t){return(0,As.createPersonaRole)(this.dataverse,t)}deleteSecurityRole(t){return(0,As.deleteSecurityRole)(this.dataverse,t)}addEntityPrivilegesToRole(t,r){return(0,As.addEntityPrivilegesToRole)(this.dataverse,t,r)}getEntityPrivileges(t){return(0,As.getEntityPrivileges)(this.dataverse,t)}createRecord(t,r){return(0,mn.createRecord)(this.dataverse,t,r)}createRecordsBulk(t,r){return(0,mn.createRecordsBulk)(this.dataverse,t,r)}updateRecord(t,r,n){return(0,mn.updateRecord)(this.dataverse,t,r,n)}upsertRecord(t,r,n){return(0,mn.upsertRecord)(this.dataverse,t,r,n)}deleteRecord(t,r){return(0,mn.deleteRecord)(this.dataverse,t,r)}getRecord(t,r,n){return(0,mn.getRecord)(this.dataverse,t,r,n)}queryRecords(t,r){return(0,mn.queryRecords)(this.dataverse,t,r)}seedRecordGraph(t,r){return(0,Cz.seedRecordGraph)(this.dataverse,t,r)}resolveArtifact(t,r){return(0,CT.resolveArtifact)(this.dataverse,t,r)}findArtifact(t,r){return(0,CT.findArtifact)(this.dataverse,t,r)}async deleteAppCascade(t,r){let n=await(0,vz.deleteAppCascade)(this.dataverse,t,r),i=(0,Xn.normalizeGuid)(t,"appModuleId");return await this.workspace.readArtifact("app",i)&&await this.workspace.deleteArtifact("app",i),n}associateRecords(t,r,n){return(0,mn.associateRecords)(this.dataverse,t,r,n)}disassociateRecords(t,r,n,i){return(0,mn.disassociateRecords)(this.dataverse,t,r,n,i)}createWebResource(t){return(0,gc.createWebResource)(this.dataverse,t)}updateWebResource(t,r){return(0,gc.updateWebResource)(this.dataverse,t,r)}getWebResource(t){return(0,gc.getWebResource)(this.dataverse,t)}deleteWebResource(t){return(0,gc.deleteWebResource)(this.dataverse,t)}getAppSettings(t){return(0,ja.readAppSettings)(this.dataverse,t)}setAppSetting(t,r,n){return(0,ja.setAppSetting)(this.dataverse,t,r,n)}setHeaderAndNavigationRefresh(t,r){if(typeof r!="boolean")throw new ee.ValidationError("app",t,[{pointer:"/headerAndNavigationRefresh",rule:gz.HEADER_NAV_BOOLEAN_RULE,message:`enabled must be a boolean, got ${typeof r}`}]);return(0,ja.setAppSetting)(this.dataverse,t,ja.HEADER_AND_NAVIGATION_REFRESH,r?ja.APP_SETTING_ON:ja.APP_SETTING_OFF)}getSolution(t){return(0,ut.getSolution)(this.dataverse,t)}createPublisher(t){return(0,ut.createPublisher)(this.dataverse,t)}createSolution(t){return(0,ut.createSolution)(this.dataverse,t)}setSolutionVersion(t,r){return(0,ut.setSolutionVersion)(this.dataverse,t,r)}addSolutionComponent(t){return(0,ut.addSolutionComponent)(this.dataverse,t)}removeSolutionComponent(t,r,n){return(0,ut.removeSolutionComponent)(this.dataverse,t,r,n)}exportSolution(t){return(0,ut.exportSolution)(this.dataverse,t)}importSolution(t){return(0,ut.importSolution)(this.dataverse,t)}deleteSolution(t){return(0,ut.deleteSolution)(this.dataverse,t)}async getArtifact(t,r){return this.withArtifactLock(t,r,()=>this.getArtifactUnlocked(t,r))}async getArtifactUnlocked(t,r){return(0,hn.cloneJson)(await this.readRaw(t,r))}async readRaw(t,r){return await this.revalidateIfStale(t,r),this.readLocal(t,r)}async readForMutation(t,r,n){if(await this.revalidateIfStale(t,r)==="refreshed-changed")throw new ee.StaleArtifactError(t,r,n);return this.readLocal(t,r)}async readLocal(t,r){let n=await this.workspace.readArtifact(t,r);if(!n)throw new ee.ArtifactNotFoundError(t,r);return n}async revalidateIfStale(t,r){let n=await this.versions.getMeta(t,r);if(!n)return"skipped";let i=n.fetchedAt?Date.parse(n.fetchedAt):NaN,a=Date.now()-i;if(!Number.isNaN(i)&&this.cacheStalenessMs>0&&a<=this.cacheStalenessMs)return"fresh";if(await this.versions.isDirty(t,r))return"skipped";let o=await this.workspace.readArtifact(t,r);await this.fetchArtifactUnlocked(t,r);let s=await this.workspace.readArtifact(t,r);return(0,AT.deepEqual)(o,s)?"refreshed-unchanged":"refreshed-changed"}async queryTree(t,r,n){return this.withArtifactLock(t,r,async()=>{let i=await this.getArtifactUnlocked(t,r),a=nr.JsonPointer.resolve(i,n);if(a===void 0)throw new ee.PathNotFoundError(t,r,n);return a})}async findElements(t,r,n){return this.withArtifactLock(t,r,async()=>(0,fz.findElements)(await this.getArtifactUnlocked(t,r),n))}async withDirtyFlags(t){let r=[];for(let n of t)r.push({...n,isDirty:await this.versions.isDirty(n.type,n.id)});return r}async listArtifacts(t,r){return this.withDirtyFlags(await this.workspace.listArtifacts(t,r))}async getEntityMetadata(t){let r=await this.workspace.readEntityMetadata(t);if(!r)throw new ee.ArtifactNotFoundError("entityMetadata",t);return r}async getFieldMetadata(t,r){let i=(await this.getEntityMetadata(t)).attributes.find(a=>a.logicalName===r);if(!i)throw new ee.PathNotFoundError("entityMetadata",t,r);return i}async updateElement(t,r,n,i){return this.withArtifactLock(t,r,async()=>{let a=await this.readForMutation(t,r,n),o=nr.JsonPointer.resolve(a,n);if(o===void 0)throw new ee.PathNotFoundError(t,r,n);let s=gn(o)&&gn(i)?{...o,...i}:i;return nr.JsonPointer.set(a,n,(0,hn.cloneJson)(s)),this.assertStructurallyValid(t,r,a,n),await this.workspace.writeArtifact(t,r,a),this.getArtifactUnlocked(t,r)})}async addElement(t,r,n,i,a){return this.withArtifactLock(t,r,async()=>{let o=await this.readForMutation(t,r,n),s=nr.JsonPointer.resolve(o,n);if(s===void 0)throw new ee.PathNotFoundError(t,r,n);if(!Array.isArray(s)){if(!gn(s)||!gn(i))throw new ee.ValidationError(t,r,n,"parent must be an array, or an object with an object of properties to add");if(a?.position!==void 0)throw new ee.ValidationError(t,r,n,"position is not supported for an object parent");let c={};for(let d of Object.keys(i)){if(d==="id")throw new ee.ValidationError(t,r,n,"refusing to write 'id' \u2014 that re-keys the node rather than adding a property");let p=(0,hn.cloneJson)(i[d]);c[d]=Array.isArray(p)?p.map(f=>gn(f)?this.assignMissingIds(t,f):f):gn(p)?this.assignMissingIds(t,p):p}for(let d of Object.keys(c))nr.JsonPointer.set(o,nr.JsonPointer.append(n,d),c[d]);return this.assertStructurallyValid(t,r,o,n),await this.workspace.writeArtifact(t,r,o),this.getArtifactUnlocked(t,r)}let l=this.assignMissingIds(t,(0,hn.cloneJson)(i)),u=Iz(s,a?.position);return s.splice(u,0,l),this.assertStructurallyValid(t,r,o,n),await this.workspace.writeArtifact(t,r,o),this.getArtifactUnlocked(t,r)})}async moveElement(t,r,n,i,a){return this.withArtifactLock(t,r,async()=>{var o;let s=await this.readForMutation(t,r,n),l=nr.JsonPointer.resolve(s,n);if(l===void 0)throw new ee.PathNotFoundError(t,r,n);let u=nr.JsonPointer.resolve(s,i);if(u===void 0)throw new ee.PathNotFoundError(t,r,i);if(!Array.isArray(u))throw new ee.ValidationError(t,r,i,"move target must be an array");if(i===n||i.startsWith(`${n}/`))throw new ee.ValidationError(t,r,i,"cannot move an element into its own subtree");nr.JsonPointer.remove(s,n);let c=(o=a?.index)!==null&&o!==void 0?o:u.length;u.splice(Math.max(0,Math.min(c,u.length)),0,l),ST(u);let d=nr.JsonPointer.resolve(s,ET(n));return Array.isArray(d)&&d!==u&&ST(d),this.assertStructurallyValid(t,r,s,i),await this.workspace.writeArtifact(t,r,s),this.getArtifactUnlocked(t,r)})}async removeElement(t,r,n){return this.withArtifactLock(t,r,async()=>{let i=await this.readForMutation(t,r,n);if(nr.JsonPointer.resolve(i,n)===void 0)throw new ee.PathNotFoundError(t,r,n);return nr.JsonPointer.remove(i,n),this.assertStructurallyValid(t,r,i,ET(n)),await this.workspace.writeArtifact(t,r,i),this.getArtifactUnlocked(t,r)})}assertStructurallyValid(t,r,n,i){var a,o,s;let l=this.registrations.get(t),u=(s=(o=l==null?void 0:(a=l.adapter).validate)===null||o===void 0?void 0:o.call(a,n,i))!==null&&s!==void 0?s:[];if(u.length>0)throw new ee.ValidationError(t,r,u)}retrieveSetting(t,r){return(0,Ja.retrieveSetting)(this.dataverse,t,r)}saveSettingValue(t,r,n){return(0,Ja.saveSettingValue)(this.dataverse,t,r,n)}getAiReadiness(t){return(0,Ja.getAiReadiness)(this.dataverse,t)}setAppAiFeatures(t,r,n){return(0,Ja.setAppAiFeatures)(this.dataverse,t,r,n)}configureRowSummary(t,r){return(0,Ja.configureRowSummary)(this.dataverse,t,r)}removeRowSummary(t){return(0,Ja.removeRowSummary)(this.dataverse,t)}async enrichDefaultViews(t,r,n={}){let i=await(0,Ez.findDefaultViews)(this.dataverse,t,n),a=[];for(let o of i)await this.fetchArtifact("view",o.id),await this.updateElement("view",o.id,"/columns",r),(await this.pushArtifact("view",o.id)).saved&&a.push(o.id);if(a.length){let o=await this.publishArtifact("view",a[0]);if(o.publish.kind==="failed")throw new ee.SdkError("ENRICH_DEFAULT_VIEWS_PUBLISH_FAILED",`enrichDefaultViews: ${a.length} view(s) on '${t}' were saved but the publish FAILED, so none of them is live (${o.publish.error.message}). Re-publish the entity to make them visible; the saves themselves are unaffected.`)}return{updated:a}}async createArtifact(t,r){let n=this.requireRegistration(t,"createArtifact"),i=n.adapter.assignMissingIds(n.adapter.createDefault(r)),a=i.id;if(!a)throw new ee.ValidationError(t,"(new)","/id","created artifact must have an id");return this.withArtifactLock(t,a,async()=>(await this.workspace.writeArtifact(t,a,i),(0,hn.cloneJson)(i)))}async deleteArtifact(t,r){return this.withArtifactLock(t,r,async()=>{await this.workspace.deleteArtifact(t,r)})}async deleteRemoteArtifact(t,r){return this.withArtifactLock(t,r,async()=>{await this.requireRegistration(t,"deleteRemoteArtifact").api.delete(this.dataverse,r),await this.workspace.readArtifact(t,r)&&await this.workspace.deleteArtifact(t,r)})}async publishArtifact(t,r,n){return this.withArtifactLock(t,r,()=>this.publishArtifactUnlocked(t,r,n))}async publishArtifactUnlocked(t,r,n){var i;let a=await this.readRaw(t,r),o=this.registrations.get(t);if(!o?.publish)return{type:t,id:r,shipped:!1,publish:{kind:"notApplicable"}};let s=(i=o.publishScope)===null||i===void 0?void 0:i.call(o,r,a);try{await o.publish(this.dataverse,r,a)}catch(u){return{type:t,id:r,shipped:!1,publish:{kind:"failed",error:Cs(u)},...s?{publishScope:s}:{}}}if(!n?.verify)return{type:t,id:r,shipped:!1,publish:{kind:"submitted"},...s?{publishScope:s}:{}};let l=await this.verifyPublished(t,r);return{type:t,id:r,shipped:l.kind==="verified",publish:l,...s?{publishScope:s}:{}}}async verifyPublished(t,r){var n,i,a,o,s;if(t!=="app")return{kind:"unverifiable",reason:`published-projection verification is not characterised for '${t}'; the publish was submitted`};try{let l=`/appmodules(${(0,Xn.normalizeGuid)(r,"id")})${(0,Xn.odataQuery)([["$select","appmoduleid,name,description"]])}`,u=await this.dataverse.get(l);if(u.status>=200&&u.status<300){let c=(n=u.body)!==null&&n!==void 0?n:{},d=await this.workspace.readArtifact("app",r);if(!d)return{kind:"verified"};let p=[];return((i=d.name)!==null&&i!==void 0?i:"")!==((a=c.name)!==null&&a!==void 0?a:"")&&p.push("name"),((o=d.description)!==null&&o!==void 0?o:"")!==((s=c.description)!==null&&s!==void 0?s:"")&&p.push("description"),p.length>0?{kind:"unverifiable",reason:`the published projection does not yet match the saved app (${p.join(", ")} still differ). PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists`}:{kind:"verified"}}return{kind:"unverifiable",reason:`the published projection answered HTTP ${u.status}`}}catch(l){return{kind:"unverifiable",reason:Cs(l).message}}}async pushArtifact(t,r){return this.withArtifactLock(t,r,()=>this.pushArtifactUnlocked(t,r))}async prepareArtifactUnlocked(t,r){let n=this.requireRegistration(t,"pushArtifact"),i=await this.readLocal(t,r),a=await this.versions.getMeta(t,r);this.assertLanguageMatches(t,r,a,n),this.assertProjectionMatches(t,r,a);let o=await this.buildMetadataContext(n.adapter,i),s=await n.adapter.toApiPayload(i,a?.snapshot,o);return await this.assertSemanticallyComplete(n,t,r,i,a===null,a?.everActivated),{type:t,id:r,reg:n,json:i,meta:a,payload:s}}async assertSemanticallyComplete(t,r,n,i,a,o){var s;let l=t.adapter.issuesBlockingPush;if(!l)return;let u=i.entityLogicalName,c=u?await this.workspace.readEntityMetadata(u):null,d=((s=c?.attributes)!==null&&s!==void 0?s:[]).map(f=>({logicalName:f.logicalName,displayName:f.displayName,attributeType:f.attributeType,isCustomAttribute:f.isCustomAttribute,...f.maxLength!==void 0?{maxLength:f.maxLength}:{},...f.options?{options:f.options.map(m=>({value:m.value,label:m.label}))}:{},...f.targets?{targets:f.targets}:{}})),p=l.call(t.adapter,i,d,{isCreate:a,everActivated:o});if(p.length>0)throw new ee.ValidationError(r,n,p)}async pushArtifactUnlocked(t,r){return this.executePrepared(await this.prepareArtifactUnlocked(t,r))}async executePrepared(t){var r,n,i,a,o,s;let{type:l,id:u,reg:c,json:d,meta:p,payload:f}=t;try{let m=p?await c.api.update(this.dataverse,u,f,p.etag,p.memberEtags,p.siblingEtags):await this.createWithMintedId(c,l,u,f),g=u;return p||(m.serverIdentity&&c.adapter.applyServerIdentity&&c.adapter.applyServerIdentity(d,m.serverIdentity),m.id&&m.id!==u&&(d.id=m.id,await this.workspace.deleteArtifact(l,u),g=m.id),await this.workspace.writeArtifact(l,g,d)),await this.versions.storeMeta(l,g,{etag:m.etag,languageCode:this.languageCode,projectionVersion:ws.PROJECTION_VERSION,fetchedAt:(0,Vr.nowIso)(),snapshot:(0,hn.cloneJson)(d),...m.memberEtags?{memberEtags:m.memberEtags}:{},...m.siblingEtags?{siblingEtags:m.siblingEtags}:{}}),{type:l,id:g,saved:!0,shipped:!1,publish:(r=m.publish)!==null&&r!==void 0?r:{kind:"notRequested"},...m.publish&&m.publish.kind!=="notRequested"?(()=>{var y;let A=(y=c.publishScope)===null||y===void 0?void 0:y.call(c,g,d);return A?{publishScope:A}:{}})():{},...m.warnings&&m.warnings.length>0?{warnings:m.warnings}:{}}}catch(m){let g=(0,ee.readPartialTokens)(m);if(g&&p){let y={...(n=p.memberEtags)!==null&&n!==void 0?n:{},...(i=g.memberEtags)!==null&&i!==void 0?i:{}},A={...(a=p.siblingEtags)!==null&&a!==void 0?a:{},...(o=g.siblingEtags)!==null&&o!==void 0?o:{}};await this.versions.storeMeta(l,u,{...p,...Object.keys(y).length>0?{memberEtags:y}:{},...Object.keys(A).length>0?{siblingEtags:A}:{}})}if(m instanceof ee.SdkError&&m.code===Bt.ALREADY_EXISTS_CODE)return{type:l,id:u,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:m};if(m instanceof ee.SdkError&&m.code===bT.WFOM_API_UNAVAILABLE_CODE)return{type:l,id:u,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:m};if(m instanceof ee.SdkError&&m.code===bT.BUSINESS_RULE_LEFT_DEACTIVATED_CODE)return{type:l,id:u,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:m};if(m instanceof ee.SdkError&&m.code===Vr.VERSION_CONFLICT_CODE)return{type:l,id:u,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:new ee.VersionConflictError(l,u,(s=p?.etag)!==null&&s!==void 0?s:null,null,m.message)};throw m}}assertLanguageMatches(t,r,n,i){if(i?.languageSensitive&&!(n?.languageCode===void 0||n.languageCode===this.languageCode))throw new ee.SdkError("ARTIFACT_LANGUAGE_MISMATCH",`Refusing to push ${t} '${r}': it was fetched with languageCode ${n.languageCode} but this SDK is configured with ${this.languageCode}. Pushing would rewrite labels read in one language as labels in another. Re-fetch with languageCode ${this.languageCode}, or create the SDK with languageCode ${n.languageCode}.`)}assertProjectionMatches(t,r,n){var i;if(n&&n.projectionVersion!==ws.PROJECTION_VERSION)throw new ee.SdkError("ARTIFACT_PROJECTION_STALE",`Refusing to push ${t} '${r}': its workspace copy was produced by projection version ${(i=n.projectionVersion)!==null&&i!==void 0?i:"unknown (pre-versioning)"}, but this SDK produces version ${ws.PROJECTION_VERSION}. The parsers changed in between, so an unedited part of this artifact can no longer be told apart from an edited one and pushing could overwrite server content the caller never touched. Re-fetch it with fetchArtifact('${t}', '${r}') and re-apply any local edits.`)}async createWithMintedId(t,r,n,i){try{return await t.api.create(this.dataverse,i,n)}catch(a){throw!(a instanceof ee.SdkError)||a.code!==Vr.VERSION_CONFLICT_CODE?a:new ee.SdkError(Bt.ALREADY_EXISTS_CODE,`Cannot create ${r} '${n}': a record already exists at that id, so an earlier push of this artifact committed before its local version metadata was saved. No duplicate was created. Run fetchArtifact('${r}', '${n}', { overwrite: true }) to adopt the existing record's identity, etag and snapshot \u2014 the overwrite is required, because this local copy has never been pushed, so a plain fetch keeps it and adopts nothing; it REPLACES the local copy, so keep any outstanding local changes aside first \u2014 then re-apply them and push again: a conditional update, provided the adopted record is complete. If the earlier push committed only PART of a multi-row artifact (e.g. an app's appmodule without its sitemap), that update refuses, naming what is missing and how to remove the partial record. This is not done automatically because the only recovery available here would be an UNCONDITIONAL overwrite, which would destroy any edit made to the record in the meantime.`)}}async buildMetadataContext(t,r){var n,i;let a=(i=(n=t.metadataNeeds)===null||n===void 0?void 0:n.call(t,r))!==null&&i!==void 0?i:[];if(a.length===0)return;let o=new Set(a.map(l=>l.entityLogicalName).filter(l=>!!l)),s=new Map;for(let l of o){let u=await this.workspace.readEntityMetadata(l);if(!u)try{await this.fetchEntityMetadata(l),u=await this.workspace.readEntityMetadata(l)}catch{}u&&s.set(l,u)}return{resolveField:(l,u)=>{let c=s.get(l),d=c?.attributes.find(p=>p.logicalName===u);return d?{displayName:d.displayName,attributeType:d.attributeType}:void 0}}}async pushAll(){let t=await this.getDirtyArtifacts();await this.warmBatchMetadata(t);let r=new Map;for(let i=0;i<t.length;i+=1){let a=t[i];try{await this.withArtifactLock(a.type,a.id,()=>this.prepareArtifactUnlocked(a.type,a.id))}catch(o){r.set(i,{type:a.type,id:a.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:Cs(o)})}}if(r.size>0)return t.map((i,a)=>{var o;return(o=r.get(a))!==null&&o!==void 0?o:{type:i.type,id:i.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:new ee.SdkError(Bt.PUSH_NOT_ATTEMPTED_CODE,`Not attempted: ${r.size} artifact(s) in this batch could not be prepared, so no writes were issued. Fix the reported failures and push again.`)}});let n=[];for(let i of t)try{n.push(await this.pushArtifact(i.type,i.id))}catch(a){n.push({type:i.type,id:i.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:Cs(a)})}return n}async warmBatchMetadata(t){var r,n,i;let a=new Set;for(let o of t){let s=this.registrations.get(o.type);if(!s)continue;let l;try{l=await this.readLocal(o.type,o.id)}catch{continue}let u=l.entityLogicalName;u&&a.add(u);for(let c of(i=(n=(r=s.adapter).metadataNeeds)===null||n===void 0?void 0:n.call(r,l))!==null&&i!==void 0?i:[])c.entityLogicalName&&a.add(c.entityLogicalName)}for(let o of a)if(!await this.workspace.readEntityMetadata(o))try{await this.fetchEntityMetadata(o)}catch{}}async getDirtyArtifacts(){return(await this.withDirtyFlags(await this.workspace.listArtifacts())).filter(r=>r.isDirty)}async diffArtifact(t,r){return this.versions.diff(t,r)}assignMissingIds(t,r){let n=this.registrations.get(t);return n?n.adapter.assignMissingIds(r):(0,bz.assignMissingIds)(r)}async resolveComponentType(t){switch(t.componentType){case ut.SolutionComponentType.SavedQuery:return"view";case ut.SolutionComponentType.SavedQueryVisualization:return"chart";case ut.SolutionComponentType.AppModule:return"app";case ut.SolutionComponentType.UxAgentProject:return"genPage";case ut.SolutionComponentType.Workflow:return t.workflowCategory===2?"businessRule":t.workflowCategory===4&&await this.isBusinessFlowWorkflow(t.objectId)?"bpf":void 0;case ut.SolutionComponentType.SystemForm:return await this.isDashboardForm(t.objectId)?"dashboard":"form";default:return}}async isDashboardForm(t){let n=`/systemforms(${(0,Xn.normalizeGuid)(t,"formId")})${(0,Xn.odataQuery)([["$select","type"]])}`,i=(0,Vr.ensureSuccess)(await this.dataverse.get(n),this.dataverse.apiUrl(n)),a=Number(i.body.type);return a===0||a===10}async isBusinessFlowWorkflow(t){let n=`/workflows(${(0,Xn.normalizeGuid)(t,"workflowId")})${(0,Xn.odataQuery)([["$select","businessprocesstype"]])}`,i=(0,Vr.ensureSuccess)(await this.dataverse.get(n),this.dataverse.apiUrl(n));return Number(i.body.businessprocesstype)===0}requireRegistration(t,r){let n=this.registrations.get(t);if(!n)throw new ee.NotImplementedError(r,`no adapter registered for artifact type '${t}'`);return n}};Bt.MakerSdk=vc;function Dz(e){return new vc(e)}Bt.createMakerSdk=Dz;function Cs(e){return e instanceof Error?e:new Error(String(e))}function gn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ET(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function ST(e){e.length===0||!e.every(t=>gn(t)&&typeof t.order=="number")||e.forEach((t,r)=>{t.order=r})}function Iz(e,t){if(t===void 0||t==="end")return e.length;if(t==="start")return 0;if("index"in t)return Math.max(0,Math.min(t.index,e.length));if("before"in t){let n=e.findIndex(i=>gn(i)&&i.id===t.before);return n<0?e.length:n}let r=e.findIndex(n=>gn(n)&&n.id===t.after);return r<0?e.length:r+1}});var IT=v(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});yc.ARTIFACT_TYPES=void 0;yc.ARTIFACT_TYPES=["form","view","businessRule","app","command","chart","dashboard","genPage","bpf"]});var TT=v(_T=>{"use strict";Object.defineProperty(_T,"__esModule",{value:!0})});var OT=v(PT=>{"use strict";Object.defineProperty(PT,"__esModule",{value:!0})});var FT=v(RT=>{"use strict";Object.defineProperty(RT,"__esModule",{value:!0})});var LT=v(xT=>{"use strict";Object.defineProperty(xT,"__esModule",{value:!0})});var MT=v(kT=>{"use strict";Object.defineProperty(kT,"__esModule",{value:!0})});var BT=v(UT=>{"use strict";Object.defineProperty(UT,"__esModule",{value:!0})});var qT=v($T=>{"use strict";Object.defineProperty($T,"__esModule",{value:!0})});var GT=v(VT=>{"use strict";Object.defineProperty(VT,"__esModule",{value:!0})});var WT=v(zT=>{"use strict";Object.defineProperty(zT,"__esModule",{value:!0})});var jT=v(HT=>{"use strict";Object.defineProperty(HT,"__esModule",{value:!0})});var QT=v(JT=>{"use strict";Object.defineProperty(JT,"__esModule",{value:!0})});var XT=v(KT=>{"use strict";Object.defineProperty(KT,"__esModule",{value:!0})});var ZT=v(YT=>{"use strict";Object.defineProperty(YT,"__esModule",{value:!0})});var tP=v(eP=>{"use strict";Object.defineProperty(eP,"__esModule",{value:!0})});var nP=v(rP=>{"use strict";Object.defineProperty(rP,"__esModule",{value:!0})});var aP=v(iP=>{"use strict";Object.defineProperty(iP,"__esModule",{value:!0})});var sP=v(oP=>{"use strict";Object.defineProperty(oP,"__esModule",{value:!0})});var uP=v(lP=>{"use strict";Object.defineProperty(lP,"__esModule",{value:!0})});var dP=v(cP=>{"use strict";Object.defineProperty(cP,"__esModule",{value:!0})});var pP=v(le=>{"use strict";var _z=le&&le.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),De=le&&le.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&_z(t,e,r)};Object.defineProperty(le,"__esModule",{value:!0});le.createMakerSdk=void 0;var Tz=DT();Object.defineProperty(le,"createMakerSdk",{enumerable:!0,get:function(){return Tz.createMakerSdk}});De(IT(),le);De(TT(),le);De(OT(),le);De(FT(),le);De(LT(),le);De(MT(),le);De(BT(),le);De(qT(),le);De(GT(),le);De(WT(),le);De(jT(),le);De(QT(),le);De(XT(),le);De(pl(),le);De(ZT(),le);De(tP(),le);De(nP(),le);De(aP(),le);De(sP(),le);De(uP(),le);De(dP(),le);De(te(),le)});var gh=v(Gr=>{"use strict";var Pz=Gr&&Gr.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),Oz=Gr&&Gr.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),hP=Gr&&Gr.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&Pz(t,e,r);return Oz(t,e),t};Object.defineProperty(Gr,"__esModule",{value:!0});Gr.NodeFileSystemStorage=void 0;var Be=hP(require("fs")),ct=hP(require("path")),fP=te(),mP=Bc();async function gP(e){let t;try{t=await Be.promises.lstat(e)}catch{return}if(t.isSymbolicLink()){try{await Be.promises.unlink(e)}catch{await Be.promises.rmdir(e)}return}if(!t.isDirectory()){await Be.promises.unlink(e);return}for(let r of await Be.promises.readdir(e))await gP(ct.join(e,r));await Be.promises.rmdir(e)}var hh=class{constructor(t){this.root=t}getRoot(){return this.root}pathFor(t,r=!0){return this.assertWithinRoot(ct.join(this.root,...t),r)}realPathThroughNearestAncestor(t){let r=t,n=[];for(;!Be.existsSync(r);){n.unshift(ct.basename(r));let i=ct.dirname(r);if(i===r)return ct.resolve(t);r=i}return ct.resolve(Be.realpathSync(r),...n)}assertWithinRoot(t,r){let n=ct.resolve(this.root),i=ct.resolve(t);if(i!==n&&!i.startsWith(n+ct.sep))throw new fP.PathTraversalError(t,this.root);let a=this.realPathThroughNearestAncestor(n),o=r?this.realPathThroughNearestAncestor(i):ct.resolve(this.realPathThroughNearestAncestor(ct.dirname(i)),ct.basename(i));if(o!==a&&!o.startsWith(a+ct.sep))throw new fP.PathTraversalError(t,this.root);return i}async readText(t){let r=this.pathFor(t);if(!Be.existsSync(r))return null;try{return await(0,mP.retryTransientIoAsync)(()=>Be.promises.readFile(r,"utf8"))}catch(n){if(n.code==="ENOENT")return null;throw n}}async writeTextAtomic(t,r){let n=this.pathFor(t),i=ct.dirname(n);await Be.promises.mkdir(i,{recursive:!0});let a=ct.join(i,`.${ct.basename(n)}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);try{await Be.promises.writeFile(a,r,"utf8"),await(0,mP.retryTransientIoAsync)(()=>Be.promises.rename(a,n))}catch(o){try{Be.existsSync(a)&&await Be.promises.unlink(a)}catch{}throw o}}async deleteFile(t){let r=this.pathFor(t);Be.existsSync(r)&&await Be.promises.unlink(r)}async deleteByPrefix(t){await gP(this.pathFor(t,!1))}async ensureContainer(t){await Be.promises.mkdir(this.pathFor(t),{recursive:!0})}async exists(t){return Be.existsSync(this.pathFor(t))}};Gr.NodeFileSystemStorage=hh});var vP=v(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});Qa.createNodeWorkspaceStorage=Qa.NodeFileSystemStorage=void 0;var Rz=gh(),Fz=gh();Object.defineProperty(Qa,"NodeFileSystemStorage",{enumerable:!0,get:function(){return Fz.NodeFileSystemStorage}});function xz(e){return new Rz.NodeFileSystemStorage(e)}Qa.createNodeWorkspaceStorage=xz});var vn={};module.exports=br(vn);bn(vn,ie(pP()),module.exports);bn(vn,ie(vP()),module.exports);+`),o=await e.postBatch(a,r),s=e.apiUrl("/$batch");(0,ge.ensureSuccess)(o,s);let l=`app '${t[0].path}'`;if(typeof o.body!="string"||o.body.length===0)throw new ve.ConnectionError(s,o.status,`atomic delete of ${l} cannot be confirmed: the $batch response had no readable body, so the change set's outcome is unknown`);let u=(0,vM.parseChangeSetStatuses)(o.body,i.map((d,p)=>String(p+1)));if(u===void 0)throw new ve.ConnectionError(s,o.status,`atomic delete of ${l} cannot be confirmed: the $batch response could not be parsed as a change set, so the outcome is unknown`);let c=u.find(d=>d<200||d>=300);if(c!==void 0)throw new ve.ConnectionError(s,c,`atomic delete of ${l} was rolled back: the change set reported HTTP ${c}`);if(u.length!==i.length)throw new ve.ConnectionError(s,o.status,`atomic delete of ${l} cannot be confirmed: the $batch response reported ${u.length} operation result(s), expected exactly ${i.length}`)}async function Ep(e,t){try{let r=await e.get(`/sitemaps(${t})?$select=sitemapid`);return r.status<200||r.status>=300?null:(0,ge.readEtag)(r)}catch{return null}}async function vp(e,t,r,n){if(!n)return null;let i=await Ep(e,t);if(!i)return null;try{let a=await e.get($l(t,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"));if(a.status<200||a.status>=300)return null;let o=da(a);return!o||!Ap(o.sitemapid,t)||o.sitemapnameunique!==n||o.sitemapxml!==r.sitemapxml||o.sitemapname!==r.sitemapname?null:i}catch{return null}}function PM(e){return e>=400&&e<500&&e!==408&&e!==429}function yp(e,t,r){if(!e)throw new ve.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to delete app '${t}': the ${r} read returned no ETag, so the delete cannot be made conditional on the row that was actually inspected. Without that condition a row renamed or re-pointed between the read and the delete would be destroyed. Retry.`);return e}async function Ab(e,t,r){let n=`/appmodules(${t})`;if(!r.sitemapId){await RM(e,n,yp(r.appEtag,t,"app"));return}if(!e.supportsAtomicBatch)throw new ve.SdkError("APP_DELETE_NOT_ATOMIC",`Refusing to delete app '${t}': it owns a sitemap, and the injected HttpClient cannot send a raw body, so the two rows would have to be deleted as separate requests. A failure between them strands the sitemap and permanently reserves the app's unique name. Implement HttpClient.postRaw so the SDK can delete them atomically.`);await wb(e,[{path:n,etag:yp(r.appEtag,t,"app")},{path:`/sitemaps(${r.sitemapId})`,etag:yp(r.sitemapEtag,t,"sitemap")}])}async function RM(e,t,r){(0,ge.ensureSuccess)(await e.delete(t,{headers:{"If-Match":r}}),e.apiUrl(t))}async function gb(e,t){if(!/GenPageId/i.test(t))return;let r;try{r=[...new Set((0,hM.collectGenPageIds)(t))]}catch(o){throw new ve.SdkError("SITEMAP_TARGET_UNVERIFIABLE",`Refusing to push the app: its sitemap xml could not be parsed, so the generative pages it navigates to cannot be verified (${Cp(o)}).`)}if(r.length===0)return;let n=new Set,i=50;for(let o=0;o<r.length;o+=i){let s=r.slice(o,o+i),l="/uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,ae.odataQuery)([["$select","uxagentprojectid"],["$filter",s.map(c=>`uxagentprojectid eq ${c}`).join(" or ")]]),u=await(0,wp.collectPages)(e,l,"sitemap generative-page preflight");for(let c of u){let d=c.uxagentprojectid;typeof d=="string"&&d.trim()!==""&&n.add((0,ae.normalizeGuid)(d,"uxagentprojectid"))}}let a=r.filter(o=>!n.has(o));if(a.length>0)throw new ve.SdkError("SITEMAP_TARGET_NOT_FOUND",`Refusing to push the app: its sitemap navigates to generative page(s) ${a.map(o=>`'${o}'`).join(", ")} that do not exist in this environment. Push the page before the app that links to it.`)}function OM(e){var t,r;if(e.status!==400)return!1;let n=e.body;return String((r=(t=n?.error)===null||t===void 0?void 0:t.message)!==null&&r!==void 0?r:"").includes("retrieval of version numbers failed")}Vn.appApi={async get(e,t){var r;let n=(0,ae.normalizeGuid)(t,"id"),i=gp(hp,n),a=(0,ge.ensureSuccess)(await e.get(i),e.apiUrl(i)),o=(r=da(a))!==null&&r!==void 0?r:{};if(!o.appmoduleid)throw new ve.SdkError("APP_NOT_FOUND",`App '${n}' was not found (checked the unpublished-aware projection, which includes drafts).`);let s=await yb(e,o.uniquename),l=s?(0,ae.normalizeGuid)(s,"sitemapId"):void 0,u=null;if(l){u=await Ep(e,l);let d=$l(l,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"),p=(0,ge.ensureSuccess)(await e.get(d),e.apiUrl(d)),f=da(p),m=h=>{throw new ve.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${n}': its sitemap '${l}' was located by unique name, but ${h}, so the sitemap cannot be read. Persisting the app without it would misreport it as having no sitemap, or write an empty one over its navigation. Retry.`)};if(!f)return m("the by-id read returned no row");if(f.sitemapnameunique!==o.uniquename)throw new ve.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${n}': sitemap '${l}' now carries sitemapnameunique '${String(f.sitemapnameunique)}', not '${String(o.uniquename)}', so it is no longer this app's sitemap. Retry.`);if(!Ap(f.sitemapid,l))return m(`the by-id read returned a row carrying sitemapid '${String(f.sitemapid)}'`);if(typeof f.sitemapxml!="string")return m("the by-id read returned no sitemapxml");o.$sitemap=f}let c=bM(o);return{raw:o,etag:u,...o.appmoduleid?{siblingEtags:{[(0,ae.normalizeGuid)(o.appmoduleid,"appmoduleid")]:c}}:{}}},async list(e,t){let r=gp(hp);return(await(0,wp.collectPages)(e,r,"listArtifacts('app')")).map(i=>{var a,o;return{type:"app",id:(a=i.appmoduleid)!==null&&a!==void 0?a:"",name:(o=i.name)!==null&&o!==void 0?o:"",isDirty:!1}})},async create(e,t,r){let n=t;await gb(e,n.sitemapxml);let i=n.iconWebResourceId?void 0:await AM(e),a=n.iconWebResourceId||i?.id;if(!a)throw new ve.SdkError("APP_ICON_UNRESOLVED",`Cannot create app '${n.appModuleName}': its icon (\`appmodule.webresourceid\`) is a REQUIRED attribute and this environment has no image web resource to use. Pass \`iconWebResourceId\` explicitly, or add an image (PNG/JPG/GIF/ICO/SVG) web resource to the environment.`);let o=null;i?.managed&&(o=`No unmanaged image web resource was available, so the app icon resolved to a MANAGED one (${i.id}). That creates a cross-solution dependency which can fail to import into an environment without the owning managed solution. Pass \`iconWebResourceId\` with an in-solution image to avoid it.`);let s=n.appModuleUniqueName||wM(n.appModuleId),l={name:n.appModuleName,uniquename:s,clienttype:4,formfactor:1,navigationtype:0};n.appModuleDescription&&(l.description=n.appModuleDescription),n.appModuleAiDescription&&(l.aiappdescription=n.appModuleAiDescription),a&&(l.webresourceid=a);let u="/appmodules",c=(0,ge.ensureSuccess)(await e.post(u,(0,ge.withClientMintedId)(l,"appmoduleid",r)),e.apiUrl(u)),d=(0,ge.resolveCreatedId)(c,"appmoduleid","app module",r),p=null,f=null,m=[];o&&m.push(o);let h={kind:"notRequested"},v=n.sitemapId?(0,ae.normalizeGuid)(n.sitemapId,"sitemapId"):(0,bp.newId)(),w=!1,C={sitemapxml:n.sitemapxml,sitemapname:n.sitemapname};try{let D="/sitemaps",O=(0,ge.echoWrite)("sitemapid"),x=await e.post(`${D}${O.query}`,{sitemapid:v,sitemapnameunique:s,...C},O.options);w=PM(x.status);let F=(0,ge.ensureSuccess)(x,e.apiUrl(D));f=(0,ge.readEtag)(F),p=f??await vp(e,v,C,s);let M=await fb(e,n);m.push(...M.warnings);let P=M.components;P.unshift({"@odata.type":"Microsoft.Dynamics.CRM.sitemap",sitemapid:v}),await mb(e,d,P),await hb(e,d,M.tables);let q=await CM(e,d);q&&m.push(q),n.appSettings&&Object.keys(n.appSettings).length>0&&m.push(...await(0,gM.applyAppSettings)(e,d,n.appSettings)),n.published!==!1&&(await(0,cb.publishAppModule)(e,d),h={kind:"submitted"})}catch(D){throw await IM(e,d,{sitemapId:v,sitemapNameUnique:s,serverRefusedSitemap:w,sitemapWriteToken:f}),D}let E=null;if(h.kind==="submitted")try{let D=await e.get(`/appmodules(${d})?$select=appmoduleid`);D.status>=200&&D.status<300&&(E=(0,ge.readEtag)(D))}catch{}return{id:d,etag:p,serverIdentity:{sitemapId:v},siblingEtags:{[d]:E},publish:h,...m.length>0?{warnings:m}:{}}},async update(e,t,r,n,i,a){var o,s,l,u,c,d,p,f,m;let h=r,v=(0,ae.normalizeGuid)(t,"id");if(await gb(e,h.sitemapxml),!h.sitemapId)throw new ve.ValidationError("app",v,[{pointer:"/sitemapId",rule:"app-sitemap-identity-missing",message:`missing sitemap identity \u2014 re-fetch the app before pushing edits: fetchArtifact('app', '${v}', { overwrite: true }) (it REPLACES the local copy \u2014 keep outstanding changes aside), push that refreshed copy UNTOUCHED, then re-apply your changes and push again. If the untouched push is refused with this same rule, the app has NO sitemap on the server \u2014 an earlier create committed its appmodule but not its sitemap \u2014 and it can be neither updated, published nor removed with deleteRemoteArtifact (an unpublished app reads back 404). Only for an app you have confirmed is your own abandoned partial create, with nothing else provisioning it: remove its appmodule row with deleteRecord('appmodule', '${v}'), clear the local copy with deleteArtifact('app', '${v}'), then author the app again and push.`}]);let w=(0,ae.normalizeGuid)(h.sitemapId,"sitemapId");if(!n)throw new ve.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${v}': no concurrency token is held for its sitemap row, so the write could not be made conditional and would silently overwrite a concurrent edit. Re-fetch the app and re-apply the change.`);let C=await fb(e,h),E=`/appmodules(${v})`,D=(o=a?.[v])!==null&&o!==void 0?o:null,O=!0,x=!1,F;try{let Re=gp(hp,v),Tn=await e.get(Re);if(Tn.status>=200&&Tn.status<300){let Jt=(s=da(Tn))!==null&&s!==void 0?s:{};x=!0,F=typeof Jt.uniquename=="string"&&Jt.uniquename?Jt.uniquename:void 0,O=String((l=Jt.name)!==null&&l!==void 0?l:"")!==String((u=h.appModuleName)!==null&&u!==void 0?u:"")||String((c=Jt.description)!==null&&c!==void 0?c:"")!==String((d=h.appModuleDescription)!==null&&d!==void 0?d:"")||h.appModuleAiDescription!==void 0&&String((p=Jt.aiappdescription)!==null&&p!==void 0?p:"")!==String(h.appModuleAiDescription)}}catch{}let M=D;if(O){let Re=x?D:null,Tn=Re?(0,ge.echoWrite)("appmoduleid",{"If-Match":Re}):{query:"",options:void 0},Jt=await e.patch(`${E}${Tn.query}`,{name:h.appModuleName,description:h.appModuleDescription,...h.appModuleAiDescription!==void 0?{aiappdescription:h.appModuleAiDescription}:{}},Tn.options);if(OM(Jt))throw new ve.SdkError("APP_DRAFT_HEADER_NOT_WRITABLE",`Refusing to update app '${v}': its appmodule row is UNPUBLISHED, and Dataverse cannot resolve version numbers for a draft appmodule (HTTP 400). A draft header cannot be PATCHed at all \u2014 a plain retry fails too, as an upsert-create ("webresourceid cannot be NULL"). Publish the app first, then push the header edit. Nothing was modified by this call.`);(0,ge.ensureSuccess)(Jt,e.apiUrl(E)),M=(0,ge.readEtag)(Jt)}let P={sitemapxml:h.sitemapxml,sitemapname:h.sitemapname},q=F||h.appModuleUniqueName||void 0,$=(0,ge.echoWrite)("sitemapid",{"If-Match":n}),qe=`/sitemaps(${w})`,Nt;try{Nt=(0,ge.ensureSuccess)(await e.patch(`${qe}${$.query}`,{...P},$.options),e.apiUrl(qe))}catch(Re){throw(0,ve.withPartialTokens)(Re,{siblingEtags:{[v]:M}})}let ke=[...C.warnings];try{await mb(e,v,C.components),await hb(e,v,C.tables)}catch(Re){ke.push(`App '${v}': one or more components were not pinned (${Re.message}). Navigation may reference content not included in the app; re-push to retry.`)}let He={kind:"notRequested"},X=M,me=(f=(0,ge.readEtag)(Nt))!==null&&f!==void 0?f:await vp(e,w,P,q);if(h.published===!0){try{await(0,cb.publishAppModule)(e,v),He={kind:"submitted"}}catch(Re){He={kind:"failed",error:Re},ke.push(`App '${v}': saved, but publishing failed (${Re.message}). The app remains unpublished; re-push to retry.`)}if(He.kind==="submitted"){X=null;try{let Re=await e.get(`/appmodules(${v})?$select=appmoduleid`);Re.status>=200&&Re.status<300&&(X=(0,ge.readEtag)(Re)),me=(m=await vp(e,w,P,q))!==null&&m!==void 0?m:me}catch{}}}return{id:v,etag:me,siblingEtags:{[v]:X},publish:He,...ke.length>0?{warnings:ke}:{}}},async delete(e,t){let r=(0,ae.normalizeGuid)(t,"id");await Ab(e,r,await bb(e,r))}}});var Sp=y(pa=>{"use strict";Object.defineProperty(pa,"__esModule",{value:!0});pa.deleteAppCascade=pa.collectGenPageIds=void 0;var xM=ql(),LM=ee(),Np=le(),FM=ap();function Cb(e){let t=[],r=s=>l=>t.push(`${s}: ${l}`),i=new FM.DOMParser({errorHandler:{warning:r("warning"),error:r("error"),fatalError:r("fatalError")}}).parseFromString(e,"text/xml").documentElement;if(!i||t.length>0)throw new LM.InvalidArgumentError(`The app sitemap xml could not be parsed cleanly, so its generative-page children cannot be determined${t.length>0?` (${t[0]})`:""}`);let a=[],o=s=>{if(s.nodeName==="SubArea"){let u=s.getAttribute("GenPageId");u&&a.push((0,Np.normalizeGuid)(u,"GenPageId"))}let l=s.childNodes;for(let u=0;u<l.length;u+=1){let c=l[u];c.nodeType===1&&o(c)}};return o(i),a}pa.collectGenPageIds=Cb;async function kM(e,t,r){let n=(0,Np.normalizeGuid)(t,"appModuleId");(0,Np.normalizeGuid)(r,"appModuleIdUnique");let i=[],a=[],o=[];await(0,xM.deleteAppResolvingOnce)(e,n,l=>{l!==void 0&&o.push(...Cb(l))}),i.push({type:"app",id:n});let s=[...new Set(o)].map(l=>({type:"genPage",id:l}));return{success:a.length===0,deleted:i,failures:a,retained:s}}pa.deleteAppCascade=kM});var Eb={};Zr(Eb,{Guid:()=>L});var L,Ve=T(()=>{"use strict";L=class e{guidString;guid;static get EmptyGuid(){return new e("00000000-0000-0000-0000-000000000000")}static NewGuid(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var r=Math.random()*16|0,n=t=="x"?r:r&3|8;return n.toString(16)})}constructor(t,r=!1){this.guidString=t;let n=new RegExp("[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}$");(r||n.test(t))&&(this.guid=t)}ToString(){return this.guid}}});var k,ct=T(()=>{"use strict";Be();k=class e{static get EmptyString(){return""}static IsTrue(t){let r=!1;return r=t&&(this.IsStrictTrue(t)||this.IsYes(t)),r}static IsStrictTrue(t){let r=!1;return t&&(r=t.toLowerCase()==="true"),r}static IsYes(t){return t.toLowerCase()==="yes"||t.toLowerCase()==="y"}static get WhiteSpace(){return/ /g}static get EnglishAndNumericCharacters(){return/([a-z0-9A-Z]+)/g}static get ValidIdExpression(){return/([a-z0-9A-Z_]+)/g}static IsNullOrEmpty(t){return t==null||t==null||t==""}static Format(t,r){return e.IsNullOrEmpty(t)?t:t.replace(/\{\{|\}\}|\{(\d+)\}/g,function(n,i){return n=="{{"?"{":n=="}}"?"}":r[i]})}static EndsWithString(t,r){return t.indexOf(r,t.length-r.length)!==-1}static IsBlankString(t){return t.replace(/\s/g,"").length==0}static EscapeXml(t,r){let n=t;return this.IsNullOrEmpty(n)||(n=n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),r&&(n=n.replace(/"/g,""").replace(/'/g,"'"))),n}static EscapeDomId(t){return t.replace(".","\\.")}static ToSnakeCase(t){let r=e.EmptyString;for(let n=0;n<t.length;n++)n!==0&&t[n]==t[n].toUpperCase()&&(r+="-"),r+=t[n].toLowerCase();return r}static GetSnakeCaseMarkup(t,r){let n="<"+this.ToSnakeCase(t);if(!_.IsNullOrUndefined(r))for(let i of r.getKeys())n+=" "+this.ToSnakeCase(i)+'="'+r.getValue(i)+'"';return n+">"}static StripBraces(t){return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?t.substr(1,t.length-2):t}static AddBraces(t){return _.IsNullOrUndefined(t)||t.charAt(0)==="{"||t.charAt(t.length-1)==="}"?t:`{${t}}`}static GuidStringEquals(t,r){return t===r?!0:!t||!r?!1:e.StripBraces(t).toUpperCase()===e.StripBraces(r).toUpperCase()}static AddBracesToArrayValues(t){return t.length>0?t.map(n=>(n.charAt(0)!=="{"&&(n="{"+n),n.charAt(n.length-1)!=="}"&&(n=n+"}"),n)):t}static StripBracesOnArrayValues(t){return t.length>0?t.map(n=>{let i;return n.charAt(0)==="{"&&(i=n.substr(1,n.length-1)),n.charAt(n.length-1)==="}"&&(i=i.substr(0,n.length-2)),i}):t}}});var Sb={};Zr(Sb,{ScriptUtilities:()=>_});var _,Be=T(()=>{"use strict";Ve();ct();_=class e{static IsNullOrUndefined(t){return t==null||t===void 0}static IsMacMachine(){return navigator.platform.indexOf("Mac")!==-1}static IsNullOrEmptyGuid(t){return k.IsNullOrEmpty(t.ToString())?!0:L.EmptyGuid.ToString()===t.ToString()}static IsNullOrUndefinedNested(t,r){return r.split(".").every(i=>typeof t!="object"||t==null||!(i in t)||t[i]==null?!1:(t=t[i],!0))}static ParseXml(t){return new DOMParser().parseFromString(t,"text/xml")}static IsWellFormedXml(t){return!e.ParseXml(t).querySelector("parsererror")}static getNamedItemValue(t,r){let n=t.getNamedItem(r);return e.IsNullOrUndefined(n)?null:n.value}static getBooleanValue(t,r){let n=e.getNamedItemValue(t,r);return e.IsNullOrUndefined(n)?null:k.IsTrue(n)}static getNumericValue(t){return e.IsNullOrUndefined(t)?null:parseInt(t)}static getAllUniqueTagNames(t){let r=new Set;return e.getAllUniqueTagNamesHelper(t,r),r}static getAllUniqueTagNamesHelper(t,r){if(t.nodeType===Node.ELEMENT_NODE&&(r.add(t.tagName),t.hasChildNodes()))for(let n=0;n<t.children.length;n++)this.getAllUniqueTagNamesHelper(t.children.item(n),r)}}});var Vl,Gl,gi,zl,Dp,Wl,Ip=T(()=>{"use strict";(function(e){e[e.FormElementNodeChange=0]="FormElementNodeChange",e[e.FormElementAttributeChange=1]="FormElementAttributeChange"})(Vl||(Vl={}));Gl=class{type;targetNode;constructor(t,r){this.type=t,this.targetNode=r}},gi=class extends Gl{key;oldValue;newValue;constructor(t,r,n,i){super(Vl.FormElementNodeChange,t),this.key=r,this.oldValue=n,this.newValue=i}apply(){this.targetNode.replaceObjectPropertyValue(this.key,this.newValue)}revert(){this.targetNode.replaceObjectPropertyValue(this.key,this.oldValue)}},zl=class extends Gl{property;oldValue;newValue;constructor(t,r,n,i){super(Vl.FormElementAttributeChange,t),this.property=r,this.oldValue=n,this.newValue=i}apply(){this.targetNode.replaceAttributeValue(this.property,this.newValue)}revert(){this.targetNode.replaceAttributeValue(this.property,this.oldValue)}},Dp=class{changeSet;reversedChangeSet;constructor(t){this.changeSet=t,this.changeSet&&(this.reversedChangeSet=this.changeSet.slice().reverse())}length(){return this.changeSet?this.changeSet.length:0}apply(){this.changeSet&&this.changeSet.length>0&&this.changeSet.forEach(t=>{t.apply()})}revert(){this.reversedChangeSet&&this.reversedChangeSet.length>0&&this.reversedChangeSet.forEach(t=>{t.revert()})}},Wl=class{isTracking;_trackedChanges;_trackedChangeSets;constructor(t=!1){this.isTracking=t,this._trackedChanges=[],this._trackedChangeSets=[]}addChange(t){this.isTracking&&this._trackedChanges.push(t)}collectChanges(){let t=new Dp(this._trackedChanges.slice());return this._trackedChanges=[],t}pushChangeSet(t){this._trackedChangeSets.push(t)}popChangeSet(){if(this._trackedChangeSets?.length>0)return this._trackedChangeSets.pop()}getChangeSets(){return this._trackedChangeSets}}});var Nb={};Zr(Nb,{ChartGridMode:()=>Yt,ColumnLayoutWidths:()=>qM,ComponentCategory:()=>Hl,ComponentType:()=>_p,ControlLayoutTypes:()=>Fp,DisplayConditionsInfo:()=>UM,ElementNames:()=>b,ElementProperties:()=>g,ElementType:()=>Pp,EntityAttributeProperty:()=>Rp,EventType:()=>$o,FormActivationState:()=>Lp,FormCanvasServiceScope:()=>ZM,FormDesignerSideBarTab:()=>Tp,FormPresentation:()=>Op,FormState:()=>jl,FormType:()=>Ge,HeaderDensityType:()=>Gn,LookUpTable:()=>Ur,MORE_TAB_PREFIX:()=>GM,NavBarChildElementType:()=>xp,PREVIEW_ID_HEADER_FLYOUT:()=>HM,PREVIEW_ID_HEADER_OVERFLOW_BUTTON:()=>KM,PREVIEW_ID_NAVIGATION_AREA:()=>WM,PREVIEW_ID_QUICKCREATE_ROOT:()=>XM,PREVIEW_ID_TAB:()=>QM,PREVIEW_ID_TAB_LIST:()=>JM,PREVIEW_ID_TAB_PANEL:()=>jM,PropertyModelKeys:()=>Bp,PropertyModelSectionKeys:()=>VM,RELATED_TAB_ID:()=>Up,RELATED_TAB_PREFIX:()=>zM,SectionDefaultProperties:()=>$M,SectionLayoutTypes:()=>Ie,TabContentType:()=>kp,TabDefaultProperties:()=>zn,TabLayoutTypes:()=>De,TelemetryPropertyNames:()=>YM,UnboundControlPropertyKeys:()=>Mp,compositeAddressFields:()=>BM,compositeFieldNames:()=>Gt,compositeFields:()=>MM});var Ge,_p,Tp,b,g,Pp,Gt,MM,BM,Rp,Ur,jl,Gn,Op,UM,xp,Lp,De,$M,zn,Ie,Fp,kp,qM,Mp,Bp,VM,$o,Yt,Up,GM,zM,WM,jM,HM,JM,KM,QM,XM,YM,Hl,ZM,Y=T(()=>{"use strict";(function(e){e[e.Dashboard=0]="Dashboard",e[e.AppointmentBook=1]="AppointmentBook",e[e.Main=2]="Main",e[e.MiniCampaignBO=3]="MiniCampaignBO",e[e.Preview=4]="Preview",e[e.MobileExpress=5]="MobileExpress",e[e.QuickViewForm=6]="QuickViewForm",e[e.QuickCreate=7]="QuickCreate",e[e.Dialog=8]="Dialog",e[e.TaskFlowForm=9]="TaskFlowForm",e[e.InteractionCentricDashboard=10]="InteractionCentricDashboard",e[e.Card=11]="Card",e[e.MainInteractiveExperience=12]="MainInteractiveExperience",e[e.Other=100]="Other",e[e.MainBackup=101]="MainBackup",e[e.AppointmentBookBackup=102]="AppointmentBookBackup",e[e.PowerBIDashboard=103]="PowerBIDashboard"})(Ge||(Ge={}));(function(e){e[e.Form=0]="Form",e[e.Dialog=1]="Dialog"})(_p||(_p={}));(function(e){e[e.Components=0]="Components",e[e.Properties=1]="Properties",e[e.Relationship=2]="Relationship",e[e.BusinessRules=3]="BusinessRules"})(Tp||(Tp={}));(function(e){e.form="form",e.formTab="tab",e.formColumn="column",e.formSection="section",e.formRow="row",e.formCell="cell",e.formLabel="label",e.formControl="control",e.formEvent="event",e.dependency="dependency",e.queryStringParameter="querystringparameter",e.controlDescriptions="controlDescriptions",e.controlDescription="controlDescription",e.customControl="customControl",e.dataset="data-set",e.formFooter="footer",e.formHeader="header",e.formNavigation="Navigation",e.formTabs="tabs",e.formColumns="columns",e.formSections="sections",e.formRows="rows",e.formEvents="events",e.quickFormDependencies="externaldependencies",e.controlParameters="parameters",e.formDependencies="dependencies",e.formNavBarAreas="NavBarAreas",e.formNavBarArea="NavBarArea",e.formNavBar="NavBar",e.spacerControl="SpacerControl",e.formField="Field",e.formNavBarByRelationshipItem="NavBarByRelationshipItem",e.formNavBarItem="NavBarItem",e.Title="Title",e.Titles="Titles",e.NavigationLink="Navigation Link",e.Relationship="Relationship",e.NavigationLinkIconClass="mscrm-glyph-NavLinkIcon",e.formDisplayConditions="DisplayConditions",e.formLibraries="formLibraries",e.internalLibraries="internaljscriptfile",e.eventHandlers="Handlers",e.handler="Handler",e.library="Library",e.formRoles="Role",e.formEveryOne="Everyone",e.Handler="Handler",e.EventHandlers="Handlers",e.InternalEventHandlers="InternalHandlers",e.HiddenControl="hiddencontrols",e.EventDependencies="dependencies",e.EventDependency="dependency",e.isvisibleinmocaonly="msinternal.isvisibleinmocaonly"})(b||(b={}));g={ShowImage:"showImage",ShowNavigationbar:"shownavigationbar",MaxWidth:"maxWidth",HeaderDensityType:"headerdensity",OnLoadEvent:"onload",EventActive:"active",EventAttribute:"attribute",Relationship:"relationship",Control:"control",HandlerUniqueId:"handlerUniqueId",functionName:"functionName",libraryNameEventHandler:"libraryName",enabledForField:"enabled",passExecutionContext:"passExecutionContext",parameters:"parameters",eventFunctionName:"eventFunctionName",eventEnabled:"eventEnabled",indicationOfSubgrid:"indicationOfSubgrid",Name:"name",Type:"type",TitleResourceId:"TitleResourceId",Show:"Show",RelationshipName:"RelationshipName",Sequence:"Sequence",Area:"Area",headerPrefix:"header_",application:"application",labelId:"labelid",showbar:"showbar",layout:"layout",classid:"classid",uniqueid:"uniqueid",isUnbound:"isunbound",isRequired:"isrequired",rowspan:"rowspan",rowheight:"rowheight",colspan:"colspan",width:"width",IsUserDefined:"IsUserDefined",expanded:"expanded",related:"related",showlabel:"showlabel",locklevel:"locklevel",datafieldname:"datafieldname",formFactor:"formFactor",static:"static",disabled:"disabled",description:"description",languagecode:"languagecode",LCID:"LCID",groupName:"group",contentType:"contenttype",showCommandBar:"showcommandbar",showBody:"showbody",showTabNavigator:"showtabnavigator",userspacer:"userspacer",columnName:"columns",LabelWidth:"labelwidth",Fieldlabelalignment:"celllabelalignment",Fieldlabelposition:"celllabelposition",availableforphone:"availableforphone",Locked:"bLocked",ReadOnly:"bDisabled",visible:"visible",ForControl:"forControl",text:"Text",url:"Url",passParameters:"PassParameters",autoExpand:"AutoExpand",auto:"auto",Auto:"Auto",Fixed:"Fixed",icon:"Icon",id:"id",Id:"Id",showOnMobileClient:"ShowOnMobileClient",webResourceId:"WebResourceId",viewName:"ViewName",failureTimeField:"FailureTimeField",successCondition:"SuccessConditionName",successConditionValue:"SuccessConditionValue",failureCondition:"FailureConditionName",failureConditionValue:"FailureConditionValue",warningCondition:"WarningConditionName",warningConditionValue:"WarningConditionValue",cancelCondition:"CancelConditionName",cancelConditionValue:"CancelConditionValue",pauseCondition:"PauseConditionName",pauseConditionValue:"PauseConditionValue",filterResults:"FilterResults",autoSuggestionSource:"AutoSuggestionSource",numberOfResults:"NumberOfResults",addressField:"AddressField",displayAsCustomer360Tile:"DisplayAsCustomer360Tile",hideQuickFormBorder:"HideQuickFormBorder",quickForms:"QuickForms",entityName:"EntityName",controlMode:"ControlMode",headerColorCode:"HeaderColorCode",targetEntityType:"TargetEntityType",enableQuickFind:"EnableQuickFind",enableViewPicker:"EnableViewPicker",enableChartPicker:"EnableChartPicker",recordsPerPage:"RecordsPerPage",chartGridMode:"ChartGridMode",referencePanelSubgridIconUrl:"ReferencePanelSubgridIconUrl",referencePanelQuickFormCollectionIconUrl:"ReferencePanelQuickFormCollectionIconUrl",referencePanelSearchWidgetIconUrl:"ReferencePanelSearchWidgetIconUrl",viewId:"ViewId",isUserView:"IsUserView",enableJumpBar:"EnableJumpBar",isUserChart:"IsUserChart",viewIds:"ViewIds",filteredViewIds:"FilteredViewIds",visualizationId:"VisualizationId",teamTemplateId:"TeamTemplateId",selectDefaultLanguage:"SelectDefaultLanguage",allowChangingFiltersOnUI:"AllowChangingFiltersOnUI",enableAutoSuggestions:"EnableAutoSuggestions",enableRating:"EnableRating",searchForAutoSuggestionsUsing:"SearchForAutoSuggestionsUsing",showContextualActions:"ShowContextualActions",showDepartmentFilter:"ShowDepartmentFilter",showLanguageFilter:"ShowLanguageFilter",showRatingUsing:"ShowRatingUsing",actionList:"ActionList",Order:"Order",FallbackForm:"FallbackForm",allowSearchFilter:"allowSearchFilter",socialInstanceParameters:"<Parameters>k__BackingField",signalUrl:"SignalUrl",border:"Border",scrolling:"Scrolling",security:"Security",BingMapsAddress1Composite:"address1_composite",BingMapsAddress2Composite:"address2_composite",UrlHttpsProtocolPrefix:"https://",UrlHttpProtocolPrefix:"http://",showAll:"ShowAll",ShowFilterPane:"UClientShowFilterPane",ExpandFilterPane:"UClientExpandFilterPane",SortOption:"UClientOrderBy",DefaultModuleCreateExperience:"UClientDefaultModuleForCreateExperience",RecordPerPages:"UClientRecordPerPage",moduleList:"UClientModules",showAllModule:"Show All",showSelectedModule:"Show Selected",Ascending:"Ascending",Descending:"Descending",Activities:"Activities",Posts:"Posts",Notes:"Notes",CardForm:"CardForm",SelectActivity:"SelectActivity",DisplayActivity:"UClientDisplayActivityUsing",CreateActivity:"UClientCreateActivityUsing",DisplayActivityHeader:"UClientDisplayActivityHeaderUsing",SortTimeLine:"UClientSortActivitiesByValue",activityList:"UClientActivities",CardActivityMap:"UClientActivityCardMap",DefaultTabId:"DefaultTabId",EmailConversationView:"EmailConversationView",OrderByActivityWall:"OrderByActivityWall",ShowArticleTab:"ShowArticleTab",SortActivityWall:"SortActivityWall",TimelineUniqueName:"UClientUniqueName",SortTimeLineBy:"modifiedon",SelectActivityListDefault:"appointment",SelectCardDefault:"Select Card Form",AscendingValue:"ascending",DescendingValue:"descending",DefaultTabIdValue:"ActivitiesTab",EmailConversationViewDefault:"true",ShowArticleTabDefault:"false",SelectDefaultLanguage:"SelectDefaultLanguage",SelectDefaultLanguageValue:"00000000-0000-0000-0000-000000000000",SortActivityWallDefault:"modifiedon",RecordPerPagesDefault:"10",TimelineNameLabel:"Timeline",showSelectedActions:"Show Selected",defaultFormat:"defaultformat",fieldLabels:"fieldlabels",QuickCreateForm:"quickcreateform",QuickFormNameToIdXMLTempate:"<QuickFormId e,yname={0}>{1}</QuickFormId>",QuickFormIdListXMLTempate:"<QuickFormId,}</QuickFormIds>",AllowFilterOff:"AllowFilterOff",AutoResolve:"AutoResolve",DefaultViewId:"DefaultViewId",DependentAttributeName:"DependentAttributeName",DependentAttributeType:"DependentAttributeType",DisableMru:"DisableMru",UseMFDForCreate:"useMainFormDialogForCreate",UseMFDForEdit:"useMainFormDialogForEdit",DisableQuickFind:"DisableQuickFind",DisableViewPicker:"DisableViewPicker",FilterRelationshipName:"FilterRelationshipName",AvailableViewIds:"AvailableViewIds",MainForm:"mainform",DefaultsFields:"defaultfields",TimeLineCardForm:"cardform",libraryUniqueId:"libraryUniqueId",libraryName:"name",displayName:"displayName",OnChangeEvent:"onchange",ViewIdRAControlDefault:"{92AFD454-0F2E-4397-A1C8-05E37C6AD699}",TargetEntityTypeRAControlDefault:"actioncard",ChartGridModeRAControlDefault:"All",RecordsPerPageRAControlDefault:"4",RAControlDefaultValue:"false",RAcontrolDefaultHeaderColorCode:"#000000",DropdownSelectedDefaultValue:"1",selectPrimaryCustomer:"SelectPrimaryCustomer",bindAttribute:"BindAttribute"};(function(e){e[e.TAB=0]="TAB",e[e.SECTION=1]="SECTION",e[e.BASIC_CONTROL=2]="BASIC_CONTROL",e[e.HEADER=3]="HEADER",e[e.FOOTER=4]="FOOTER",e[e.UB_CONTROL=5]="UB_CONTROL",e[e.RELATIONSHIPITEM=6]="RELATIONSHIPITEM",e[e.RELATIONSHIPGROUP=7]="RELATIONSHIPGROUP",e[e.NAVIGATIONLINK=8]="NAVIGATIONLINK",e[e.FORMMODEL=9]="FORMMODEL",e[e.UNDEFINED=10]="UNDEFINED"})(Pp||(Pp={}));Gt={fullname:"fullname",yomifullname:"yomifullname",address1_composite:"address1_composite",address2_composite:"address2_composite",address3_composite:"address3_composite",billto:"billto_composite",shipto:"shipto_composite"},MM=[Gt.fullname,Gt.yomifullname,Gt.address1_composite,Gt.address2_composite,Gt.address3_composite,Gt.billto,Gt.shipto],BM=[Gt.address1_composite,Gt.address2_composite,Gt.address3_composite,Gt.billto,Gt.shipto];(function(e){e[e.IsValidForForm=0]="IsValidForForm",e[e.IsValidForCreate=1]="IsValidForCreate"})(Rp||(Rp={}));(function(e){e[e.DependencyFieldTable=0]="DependencyFieldTable",e[e.LockedFieldTable=1]="LockedFieldTable"})(Ur||(Ur={}));(function(e){e[e.Published=0]="Published",e[e.Draft=1]="Draft",e[e.New=2]="New",e[e.SaveAs=3]="SaveAs"})(jl||(jl={}));(function(e){e.Low="Low",e.HighReadOnlyValues="HighReadOnlyValues",e.HighWithControls="HighWithControls"})(Gn||(Gn={}));(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(Op||(Op={}));UM={TopOrderFormId:"topOrderFormId",NextDisplayOrder:"nextDisplayOrder"};(function(e){e[e.NavBarRelationShipItem=0]="NavBarRelationShipItem",e[e.NavBarItem=1]="NavBarItem"})(xp||(xp={}));(function(e){e[e.InActive=0]="InActive",e[e.Active=1]="Active"})(Lp||(Lp={}));(function(e){e[e.ONE_COLUMN=0]="ONE_COLUMN",e[e.TWO_COLUMN_EQUAL=1]="TWO_COLUMN_EQUAL",e[e.TWO_COLUMN_WIDER_LEFT=2]="TWO_COLUMN_WIDER_LEFT",e[e.TWO_COLUMN_WIDER_RIGHT=3]="TWO_COLUMN_WIDER_RIGHT",e[e.TWO_COLUMN_CUSTOM_LAYOUT=4]="TWO_COLUMN_CUSTOM_LAYOUT",e[e.THREE_COLUMN_EQUAL=5]="THREE_COLUMN_EQUAL",e[e.THREE_COLUMN_WIDER_MID=6]="THREE_COLUMN_WIDER_MID",e[e.THREE_COLUMN_CUSTOM_LAYOUT=7]="THREE_COLUMN_CUSTOM_LAYOUT"})(De||(De={}));$M={ShowLabel:"false",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_"},zn={namePrefix:"tab_",ShowLabel:"true",LockLevel:"0",IsUserDefined:"0"};(function(e){e[e.ONE_COLUMN=0]="ONE_COLUMN",e[e.TWO_COLUMN=1]="TWO_COLUMN",e[e.THREE_COLUMN=2]="THREE_COLUMN",e[e.FOUR_COLUMN=3]="FOUR_COLUMN",e[e.REFERENCE_PANEL=4]="REFERENCE_PANEL"})(Ie||(Ie={}));(function(e){e[e.SUBGRID=0]="SUBGRID",e[e.SPACER=1]="SPACER",e[e.QUICK_VIEW=2]="QUICK_VIEW",e[e.WEB_RESOURCE=3]="WEB_RESOURCE",e[e.IFRAME=4]="IFRAME",e[e.BING_MAPS=5]="BING_MAPS",e[e.TIMER=6]="TIMER",e[e.TIMELINE=7]="TIMELINE",e[e.NOTES=8]="NOTES",e[e.SOCIAL_INSIGHTS=9]="SOCIAL_INSIGHTS",e[e.KB_SEARCH=10]="KB_SEARCH",e[e.INTERACTION_WALL=11]="INTERACTION_WALL",e[e.ACI_CONTROL=12]="ACI_CONTROL",e[e.RELATIONSHIP_ASSISTANT=13]="RELATIONSHIP_ASSISTANT",e[e.REFERENCE_PANEL=14]="REFERENCE_PANEL",e[e.REF_PANEL_QUICKVIEW=15]="REF_PANEL_QUICKVIEW",e[e.REF_PANEL_SUBGRID=16]="REF_PANEL_SUBGRID",e[e.REF_PANEL_KBSEARCH=17]="REF_PANEL_KBSEARCH",e[e.WEB_RESOURCE_HTML=18]="WEB_RESOURCE_HTML",e[e.PRED_LEAD_SCORING=19]="PRED_LEAD_SCORING"})(Fp||(Fp={}));(function(e){e.cardSections="cardSections",e.singleComponent="singleComponent",e.default="default",e.expandAvailableSpace="expandAvailableSpace"})(kp||(kp={}));qM={ONE_COLUMN:"100",TWO_COLUMN:"50",THREE_COLUMN:"33.33",FOUR_COLUMN:"25"};(function(e){e.minValue="MinValue",e.maxValue="MaxValue",e.precision="Precision",e.maxLength="MaxLength",e.entityLogicalName="EntityLogicalName",e.defaultViewId="DefaultViewId",e.optionSetDefaultValue="DefaultValue",e.optionSetId="OptionSetId"})(Mp||(Mp={}));(function(e){e.entityName="entityName",e.formName="formName",e.formDisplayName="formDisplayName",e.description="description",e.maxWidth="maxWidth",e.showNavigation="showNavigation",e.showImageCheck="showImageCheck",e.downloadFormXml="downloadFormXml",e.downloadRawFormXml="downloadRawFormXml",e.expandTab="expandTab",e.singleComponent="singleComponent",e.label="label",e.name="name",e.hiddenByDefault="hiddenByDefault",e.hideForPhone="hideForPhone",e.tabLayout="tabLayout",e.column1Width="column1Width",e.column2Width="column2Width",e.column3Width="column3Width",e.hideLabel="hideLabel",e.lockElement="lockElement",e.sectionLayout="sectionLayout",e.labelWidth="labelWidth",e.fieldLabelAlignment="fieldLabelAlignment",e.fieldLabelPosition="fieldLabelPosition",e.cellWidth="cellWidth",e.fieldHeight="fieldHeight",e.cellHeight="cellHeight",e.showLine="showLine",e.readonly="readonly",e.required="required",e.maxLength="maxLength",e.isTitle="isTitle",e.minValue="minValue",e.maxValue="maxValue",e.precision="precision",e.autoExpand="autoExpand",e.highDensityEnabled="highDensityEnabled",e.hideExtendedHeader="hideExtendedHeader",e.defaultViewProperty="defaultViewProperty",e.defaultChartProperty="defaultChartProperty",e.teamTemplateProperty="teamTemplateProperty",e.datasourceProperty="datasourceProperty",e.eventType="eventType",e.addEvent="addEvent",e.cellOnChange="cellOnChange",e.cellOnChangeEventDependencies="cellOnChangeEventDependencies",e.cellOnChangeHandlers="cellOnChangeHandlers",e.gridOnChange="gridOnChange",e.gridOnChangeEventDependencies="gridOnChangeEventDependencies",e.gridOnChangeHandlers="gridOnChangeHandlers",e.gridOnChangeTargetField="gridOnChangeTargetField",e.gridOnRecordSelect="gridOnRecordSelect",e.gridOnRecordSelectEventDependencies="gridOnRecordSelectEventDependencies",e.gridOnRecordSelectHandlers="gridOnRecordSelectHandlers",e.cellOnReadyStateEventDependencies="cellOnReadyStateEventDependencies",e.cellOnReadyStateHandlers="cellOnReadyStateEventHandlers",e.tabOnChange="tabOnChange",e.tabOnChangeEventDependencies="tabOnChangeEventDependencies",e.tabOnChangeHandlers="tabOnChangeHandlers",e.formOnLoad="formOnLoad",e.formOnLoadEventDependencies="formOnLoadEventDependencies",e.formOnLoadHandlers="formOnLoadHandlers",e.formOnSave="formOnSave",e.formOnSaveDependencies="formOnSaveDependencies",e.formOnSaveHandlers="formOnSaveHandlers",e.gridOnSave="gridOnSave",e.gridOnSaveDependencies="gridOnSaveDependencies",e.gridOnSaveHandlers="gridOnSaveHandlers",e.formHasNoLibraries="formHasNoLibraries",e.hideHeaderCommandBar="hideHeaderCommandBar",e.hideHeaderBody="hideHeaderBody",e.hideHeaderTabNavigator="hideHeaderTabNavigator",e.hideFooter="hideFooter",e.scrollingDropdown="scrollingDropdown",e.displayBorder="displayBorder",e.crossScripting="crossScripting",e.passParams="passParams",e.webResourceCustomParamData="webResourceCustomParameterData",e.webResourceAltText="webResourceAltText",e.verticalAlignment="verticalAlignment",e.horizontalAlignment="horizontalAlignment",e.specificSize="specificSize",e.urlProperty="urlProperty",e.enableViewPicker="enableViewPicker",e.enableChartPicker="enableChartPicker",e.chartGridMode="chartGridMode",e.relatedRecords="relatedRecords",e.hideSearchBox="hideSearchBox",e.showAllViews="showAllViews",e.availableViewsProperty="availableViewsProperty",e.recordsPerPage="recordsPerPage",e.businessRulePill="business-rule-pill-",e.addBusinessRule="addBusinessRule",e.rowHeight="rowHeight",e.refPanelSectionTabs="refPanelSectionTabs",e.editCanvasAppProperty="editCanvasAppProperty"})(Bp||(Bp={}));VM={display:"DisplayOptions",format:"Formatting",control:"Controls",data:"DataOptions",form:"FormProperties",events:"EventProperties",activeBusinessRules:"activeBusinessRules",addBusinessRule:"addBusinessRule",inactiveBusinessRules:"inactiveBusinessRules"};(function(e){e.onChange="onchange",e.onTabStateChange="tabstatechange",e.onLoad="onload",e.onSave="onsave",e.onReadyStateComplete="onreadystatecomplete",e.onRecordSelect="onrecordselect"})($o||($o={}));(function(e){e.All="All",e.Chart="Chart",e.Grid="Grid"})(Yt||(Yt={}));Up="tab_related3b554255-7717-4d17-bb7f-9936fb1e75ca",GM="more_tab_",zM="related_tab_",WM="preview_id_navigation_area",jM="tab-section",HM="headerFieldsFlyout",JM="tablist",KM="header_overflowButton",QM="tab",XM="quickCreateRoot",YM={defaultVisibility:"Default visibility"};(function(e){e.input="input",e.layout="layout",e.grid="grid",e.relatedData="relatedData",e.display="display",e.powerbi="powerbi",e.artificialIntelligence="artificialIntelligence",e.media="media",e.collaboration="collaboration",e.more="more",e.test="test",e.popular="popular"})(Hl||(Hl={}));ZM="CellCanvasServiceScope"});var Db={};Zr(Db,{Attribute:()=>Jl,FormElementNode:()=>j});var Jl,j,Ye=T(()=>{"use strict";Be();ct();Ip();Y();Ve();Jl=class{key;value;constructor(t,r){this.key=t,this.value=r}},j=class e{nodeName;properties;childrenNodes;parentNode;nodeId;isTransient;constructor(t,r){this.nodeName=t,this.properties=[],this.childrenNodes=[],this.parentNode=r,this.isTransient=!1,this.nodeId=`nodeId-${L.NewGuid()}`}getProperty(t){for(let r of this.properties)if(r.key===t)return r.value;return null}getNodeId(){return this.nodeId}getNodeName(){return this.nodeName}setNodeName(t){this.trackObjectPropertyChange("nodeName",t)}get NodeName(){return this.getNodeName()}getAllProperties(){return this.properties}replaceAttributeValue(t,r){this.properties.find(n=>n===t)&&(t.value=r)}replaceObjectPropertyValue(t,r){this[t]=r}getAllChildren(){return this.childrenNodes}getParentNode(){return this.parentNode}visit(t){let r=!1;if(t){r=!!t(this);let n=this.childrenNodes;if(!r&&n)for(let i=0;!r&&i<n.length;i++)r=n[i].visit(t)}return r}findAll(t){let r=[];return t&&this.visit(n=>{t(n)&&r.push(n)}),r}findFirst(t){let r=null;return t&&this.visit(n=>{if(t(n))return r=n,!0}),r}raiseMetadataChange(t){let r=this.getAncestor(b.form);r&&r.raiseMetadataChange(t)}trackPropertyAddition(t,r){this.trackPropertyCollectionChange(()=>{this.properties.push(new Jl(t,r))})}trackPropertyDeletion(t){this.trackPropertyCollectionChange(()=>{let r=this.properties.findIndex(n=>n.key===t);r>-1&&this.properties.splice(r,1)})}trackPropertyCollectionChange(t){let r=this.changeTracker();if(r&&r.isTracking){let n=this.properties.slice();t(),r.addChange(new gi(this,"properties",n,this.properties.slice()))}else t()}trackChildrenCollectionChange(t){let r=this.changeTracker();if(r&&r.isTracking){let n=this.childrenNodes.slice();t(),r.addChange(new gi(this,"childrenNodes",n,this.childrenNodes.slice()))}else t()}trackParentNodeChange(t){let r=this.changeTracker();if(r&&r.isTracking){let n=this.parentNode;if(t(),n===this.parentNode)return;r.addChange(new gi(this,"parentNode",n,this.parentNode))}else t()}trackAttributeValueChange(t,r){let n=this.changeTracker();if(n&&n.isTracking){let i=t.value;if(i===r)return;t.value=r,n.addChange(new zl(this,t,i,r))}else t.value=r}trackObjectPropertyChange(t,r){let n=this.changeTracker();if(n&&n.isTracking){let i=this[t];if(i===r)return;this[t]=r,n.addChange(new gi(this,t,i,r))}else this[t]=r}setProperty(t,r){if(!t)throw new Error("Invalid property key");let n=this.properties.find(i=>i.key===t);n?this.trackAttributeValueChange(n,r):this.addProperty(t,r)}addProperty(t,r){if(!t)throw new Error("Invalid property key");this.trackPropertyAddition(t,r)}removeProperty(t){this.trackPropertyDeletion(t)}addChild(t){t.trackParentNodeChange(()=>{t.parentNode=this}),this.trackChildrenCollectionChange(()=>{this.childrenNodes.push(t)})}insertChildAtIndex(t,r){_.IsNullOrUndefined(t)||(t.trackParentNodeChange(()=>{t.parentNode=this}),this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(r,0,t)}))}moveChild(t,r){let n=this.childrenNodes.indexOf(t);if(n<0)return!1;let i=Math.min(Math.max(0,n+r),this.childrenNodes.length-1);return n!==i&&this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(i,0,this.childrenNodes.splice(n,1)[0])}),!0}getChildren(t){let r=[];for(let n of this.childrenNodes)n.nodeName===t&&r.push(n);return r}getFirstChild(t){for(let r of this.childrenNodes)if(r.nodeName===t)return r;return null}getAllGrandChildren(t){let r=this.getChildren(t),n=null;return r.length===0?new Array:(n=r[0],n.childrenNodes)}deleteChild(t){if(_.IsNullOrUndefined(t))return-1;for(let r=0;r<this.childrenNodes.length;r++)if(this.childrenNodes[r]===t)return this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(r,1)}),r;return-1}deleteAllChildren(){this.trackChildrenCollectionChange(()=>{this.childrenNodes=[]})}getParent(){return this.parentNode}getParentType(){return this.parentNode?this.parentNode.nodeName:k.EmptyString}updateChild(t,r){let n=this.childrenNodes.indexOf(t);return n>-1?(r.trackParentNodeChange(()=>{r.parentNode=this}),this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(n,1,r)}),!0):!1}getAncestor(t){let r=this.getParent(),n=this.getParentType();for(;r;){if(n===t)return r;n=r.getParentType(),r=r.getParent()}return null}deleteFirstGrandChildOfName(t,r){return this.getChildren(t)[0].deleteChild(r)}deleteChildren(t,r){r=_.IsNullOrUndefined(r)?this.childrenNodes.length:r,this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(t,r)})}deleteGrandChildren(t,r,n){this.getChildren(t)[0].deleteChildren(r,n)}addGrandChild(t,r){let n=this.getChildren(t),i=null;n.length===0?(i=new e(t,this),this.addChild(i)):i=n[0],i.addChild(r)}addGrandChildAtIndex(t,r,n){let i=this.getChildren(t),a=null;i.length===0?(a=new e(t,this),this.addChild(a)):a=i[0],a.insertChildAtIndex(r,n)}GetPropertyByParameter(t){return this.getProperty(t)}getSemanticParent(){switch(this.getNodeName()){case b.formCell:let t=this.getAncestor(b.formSection);return t||(t=this.getAncestor(b.formHeader),t)||(t=this.getAncestor(b.formFooter),t)?t:null;case b.formSection:return this.getAncestor(b.formTab);case b.formTab:return this.getAncestor(b.form);default:return null}}isDirty(){return this.visit(t=>t.isInChangeSet())}isInChangeSet(){return this.changeTracker().getChangeSets().some(r=>r.changeSet.some(n=>n.targetNode.getNodeId()===this.getNodeId()))}changeTracker(){let t=this.getAncestor(b.form);return t?t.changeTracker():null}}});var Ib={};Zr(Ib,{ControlClassId:()=>I,ControlNamePrefixes:()=>Kl,getControlDisplayNames:()=>eB});function eB(e){return{[I.AccessPrivilegeControl]:e("controls.controlNames.accessPrivilege"),[I.AccessTeamTablePickerControl]:e("controls.controlNames.accessTeamTablePicker"),[I.ACIControl]:e("controls.controlNames.aci"),[I.ActivitiesContainerControl]:e("controls.controlNames.activitiesContainer"),[I.ActivitiesWallControl]:e("controls.controlNames.activitiesWall"),[I.AppliedFiltersControl]:e("controls.controlNames.appliedFilters"),[I.ArticleContentControl]:e("controls.controlNames.articleContent"),[I.BooleanControl]:e("controls.controlNames.twoOption"),[I.ButtonControl]:e("controls.controlNames.button"),[I.CheckboxControl]:e("controls.controlNames.checkbox"),[I.CompositionLinkControl]:e("controls.controlNames.compositionLink"),[I.ConnectionControl]:e("controls.controlNames.connection"),[I.ConnectionRoleObjectTypeListControl]:e("controls.controlNames.connectionRoleObjectTypeList"),[I.CoverageChoiceControl]:e("controls.controlNames.coverageChoice"),[I.DashboardControl]:e("controls.controlNames.dashboard"),[I.DynamicPropertyListControl]:e("controls.controlNames.dynamicPropertyList"),[I.EditFilterControl]:e("controls.controlNames.editFilter"),[I.ErrorStatusControl]:e("controls.controlNames.errorStatus"),[I.GlobalFilterControl]:e("controls.controlNames.globalFilter"),[I.HiddenInputControl]:e("controls.controlNames.hiddenInput"),[I.KBViewerControl]:e("controls.controlNames.kbViewer"),[I.LabelControl]:e("controls.controlNames.label"),[I.MailMergeLanguagePickerControl]:e("controls.controlNames.mailMergeLanguagePicker"),[I.MapLinkControl]:e("controls.controlNames.mapLink"),[I.OrgInsightsControl]:e("controls.controlNames.orgInsights"),[I.ChoiceLookupControl]:e("controls.controlNames.choiceLookup"),[I.PowerBIControl]:e("controls.controlNames.powerBI"),[I.ProcessControl]:e("controls.controlNames.process"),[I.RelatedInformationControl]:e("controls.controlNames.relatedInformation"),[I.RelationshipRoleChoiceControl]:e("controls.controlNames.relationshipRoleChoice"),[I.ReportControl]:e("controls.controlNames.report"),[I.StreamsControl]:e("controls.controlNames.streams"),[I.WebResourceSilverlightControl]:e("controls.controlNames.webResourceSilverlight"),[I.CurrencyControl]:e("controls.controlNames.currency"),[I.DateTimeControl]:e("controls.controlNames.dateAndTime"),[I.DecimalControl]:e("controls.controlNames.decimal"),[I.DurationControl]:e("controls.controlNames.duration"),[I.EmailAddressControl]:e("controls.controlNames.email"),[I.FileControl]:e("controls.controlNames.file"),[I.FloatingNumberControl]:e("controls.controlNames.floatingNumber"),[I.IframeControl]:e("controls.controlNames.iframe"),[I.ImageControl]:e("controls.controlNames.image"),[I.LookupControl]:e("controls.controlNames.lookup"),[I.MapsControl]:e("controls.controlNames.maps"),[I.PhoneNumberControl]:e("controls.controlNames.phoneNumber"),[I.ChoiceControl]:e("controls.controlNames.choice"),[I.QuickViewControl]:e("controls.controlNames.quickView"),[I.QuickFormControl]:e("controls.controlNames.quickForm"),[I.CustomControl]:e("controls.controlNames.customControl"),[I.SearchWidgetControl]:e("controls.controlNames.searchWidget"),[I.SocialInsightsControl]:e("controls.controlNames.socialInsights"),[I.SubgridControl]:e("controls.controlNames.subgrid"),[I.TextAreaControl]:e("controls.controlNames.textArea"),[I.TextboxControl]:e("controls.controlNames.textBox"),[I.TickerControl]:e("controls.controlNames.ticker"),[I.UrlControl]:e("controls.controlNames.url"),[I.WebResourceHTMLControl]:e("controls.controlNames.webResourceHTML"),[I.WebResourceImageControl]:e("controls.controlNames.webResourceImage"),[I.IntegerControl]:e("controls.controlNames.integer"),[I.TimerControl]:e("controls.controlNames.timer"),[I.TimelineControl]:e("controls.controlNames.timeline"),[I.EmailBodyControl]:e("controls.controlNames.emailBody"),[I.PartyListControl]:e("controls.controlNames.partyList"),[I.TimezoneControl]:e("controls.controlNames.timezone"),[I.LanguageControl]:e("controls.controlNames.language"),[I.ChoiceStatusControl]:e("controls.controlNames.choiceStatus"),[I.ChoicesControl]:e("controls.controlNames.choices"),[I.RegardingControl]:e("controls.controlNames.regarding"),[I.EmailEngagementActionsControl]:e("controls.controlNames.emailEngagementActions"),[I.EmailRecipientActivityControl]:e("controls.controlNames.emailRecipientActivity"),[I.ReferencePanelSearchWidgetControl]:e("controls.controlNames.referencePanelSearchWidget"),[I.ReferencePanelQuickViewControl]:e("controls.controlNames.referencePanelQuickView"),[I.ReferencePanelSubgridControl]:e("controls.controlNames.referencePanelSubgrid"),[I.KBEditorControl]:e("controls.controlNames.KBEditor"),[I.LinkControl]:e("controls.controlNames.link")}}var I,Kl,vi=T(()=>{"use strict";(function(e){e.AccessPrivilegeControl="F93A31B2-99AC-4084-8EC2-D4027C31369A",e.AccessTeamTablePickerControl="3f4e2a56-f102-4b4d-ab9c-f1574ca5bfda",e.ACIControl="C8BFBBEF-6851-4401-A0CC-7450062FE085",e.ActivitiesContainerControl="C72511AB-84E5-4FB7-A543-25B4FC01E83E",e.ActivitiesWallControl="6636847D-B74D-4994-B55A-A6FAF97ECEA2",e.AppliedFiltersControl="9C310A73-A360-42C5-8943-47A06F1B51EA",e.ArticleContentControl="F02EF977-2564-4B9A-B2F0-DF083D8A019B",e.BooleanControl="67FAC785-CD58-4F9F-ABB3-4B7DDC6ED5ED",e.ButtonControl="00AD73DA-BD4D-49C6-88A8-2F4F4CAD4A20",e.CheckboxControl="B0C6723A-8503-4FD7-BB28-C8A06AC933C2",e.CompositionLinkControl="DB1284EF-9FFC-4E99-B382-0CC082FE2364",e.ConnectionControl="3246F906-1F71-45F7-B11F-D7BE0F9D04C9",e.ConnectionRoleObjectTypeListControl="821ACF1A-7E46-4A0C-965D-FE14A57D78C7",e.CoverageChoiceControl="4168A05C-D857-46AF-8457-5BB47EB04EA1",e.DashboardControl="D2561F53-B292-42D9-B222-478E40FFE29F",e.DynamicPropertyListControl="6896F004-B17A-4202-861E-8B7EA2080E0B",e.EditFilterControl="1479835F-F852-4679-B864-C6892A2844C9",e.ErrorStatusControl="F4C16ECA-CA81-4E39-9448-834B8378721E",e.GlobalFilterControl="FFF0E632-9D7B-4F21-BBC1-05D1567AD144",e.HiddenInputControl="5546E6CD-394C-4BEE-94A8-4425E17EF6C6",e.KBViewerControl="A62B6FA9-169E-406C-B1AA-EAB828CB6026",e.LabelControl="39354E4A-5015-4D74-8031-EA9EB73A1322",e.MailMergeLanguagePickerControl="B634828E-C390-444A-AFE6-E07315D9D970",e.MapLinkControl="91DC0675-C8B9-4421-B1E0-261CEBF02BAC",e.OrgInsightsControl="76b9e25e-695e-4fef-ac69-f05cfa96739c",e.ChoiceLookupControl="2305e33a-bad3-4022-9e15-1856cf218333",e.PowerBIControl="8C54228C-1B25-4909-A12A-F2B968BB0D62",e.ProcessControl="06E9F7AF-1F54-4681-8EEC-1E21A1CEB465",e.RelatedInformationControl="163B90A6-EB64-49D2-9DF8-3C84A4F0A0F8",e.RelationshipRoleChoiceControl="5F986642-5961-4D9F-AB5E-643D71E231E9",e.ReportControl="A28F441B-916C-4865-87FD-0C5D53BD59C9",e.StreamsControl="EE9078C8-6946-4E2C-B8F8-35E65F4BE6A8",e.WebResourceSilverlightControl="080677DB-86EC-4544-AC42-F927E74B491F",e.CurrencyControl="533B9E00-756B-4312-95A0-DC888637AC78",e.CustomControl="F9A8A302-114E-466A-B582-6771B2AE0D92",e.DateTimeControl="5B773807-9FB2-42DB-97C3-7A91EFF8ADFF",e.DecimalControl="C3EFE0C3-0EC6-42BE-8349-CBD9079DFD8E",e.DurationControl="AA987274-CE4E-4271-A803-66164311A958",e.EmailAddressControl="ADA2203E-B4CD-49BE-9DDF-234642B43B52",e.EmailBodyControl="6F3FB987-393B-4D2D-859F-9D0F0349B6AD",e.EmailEngagementActionsControl="F454228D-1D25-4319-E12F-D27968BC0234",e.EmailRecipientActivityControl="26E9760F-7454-40DE-BB07-F6DCCCB82040",e.FileControl="0A7FF475-B016-4687-9CE5-042BFDBD6519",e.FloatingNumberControl="0D2C745A-E5A8-4C8F-BA63-C6D3BB604660",e.IframeControl="FD2A7985-3187-444E-908D-6624B21F69C0",e.ImageControl="7E548B0D-209C-477B-9DCD-F0F44472381D",e.LanguageControl="671A9387-CA5A-4D1E-8AB7-06E39DDCF6B5",e.LookupControl="270BD3DB-D9AF-4782-9025-509E298DEC0A",e.MapsControl="62B0DF79-0464-470F-8AF7-4483CFEA0C7D",e.ChoicesControl="4AA28AB7-9C13-4F57-A73D-AD894D048B5F",e.IntegerControl="C6D124CA-7EDA-4A60-AEA9-7FB8D318B68F",e.PartyListControl="CBFB742C-14E7-4A17-96BB-1A13F7F64AA2",e.PhoneNumberControl="8C10015A-B339-4982-9474-A95FE05631A5",e.ChoiceControl="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE",e.ChoiceStatusControl="5D68B988-0661-4DB2-BC3E-17598AD3BE6C",e.QuickViewControl="5C5600E0-1D6E-4205-A272-BE80DA87FD42",e.QuickFormControl="69AF7DCA-2E3B-4EE7-9201-0DA731DD2413",e.RegardingControl="F3015350-44A2-4AA0-97B5-00166532B5E9",e.SearchWidgetControl="E616A57F-20E0-4534-8662-A101B5DDF4E0",e.SocialInsightsControl="86B9E25E-695E-4FEF-AC69-F05CFA96739C",e.SubgridControl="E7A81278-8635-4D9E-8D4D-59480B391C5B",e.TextAreaControl="E0DECE4B-6FC8-4A8F-A065-082708572369",e.TextboxControl="4273EDBD-AC1D-40D3-9FB2-095C621B552D",e.TickerControl="1E1FC551-F7A8-43AF-AC34-A8DC35C7B6D4",e.TimerControl="9C5CA0A1-AB4D-4781-BE7E-8DFBE867B87E",e.TimelineControl="06375649-C143-495E-A496-C962E5B4488E",e.TimezoneControl="7C624A0B-F59E-493D-9583-638D34759266",e.UrlControl="71716B6C-711E-476C-8AB8-5D11542BFB47",e.WebResourceHTMLControl="9FDF5F91-88B1-47F4-AD53-C11EFC01A01D",e.WebResourceImageControl="587CDF98-C1D5-4BDE-8473-14A0BC7644A7",e.ReferencePanelSearchWidgetControl="7CCD1494-1F7A-4E3A-8BDE-F32069DAEB9F",e.ReferencePanelSubgridControl="02D4264B-47E2-4B4C-AA95-F439F3F4D458",e.ReferencePanelQuickViewControl="B68B05F0-A46D-43F8-843B-917920AF806A",e.KBEditorControl="F94DB24F-263D-44A7-B38E-A35E9854812B",e.LinkControl="DFDF1CDE-837B-4AC9-98CF-AC74361FD89D"})(I||(I={}));Kl={[I.WebResourceHTMLControl]:"WebResource",[I.WebResourceImageControl]:"WebResource",[I.IframeControl]:"IFRAME",[I.SearchWidgetControl]:"Search widget",[I.SubgridControl]:"Subgrid",[I.TimelineControl]:"Timeline",[I.QuickViewControl]:"QuickviewControl"}});var yi=y((DJ,Tb)=>{var qo=new Proxy(function(){return qo},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:qo},apply:function(){return qo},construct:function(){return{}}}),_b=function(){return qo};Object.setPrototypeOf(_b,qo);Tb.exports=_b});var yt,cn,Pb,Rb,fa=T(()=>{"use strict";yt="cds-designer-models",cn="FormCustomControl",Pb="FormCell",Rb="Form"});var ma,bt,Vo=T(()=>{"use strict";ma=class{keys;values;constructor(){this.keys=[],this.values=[]}add(t,r){return this.containsKey(t)?!1:(this.keys.push(t),this.values.push(r),!0)}upsert(t,r){this.update(t,r)||this.add(t,r)}sortedUpsert(t,r){if(!this.update(t,r)){let n=0;for(;n<this.keys.length&&this.keys[n]<t;)n++;this.keys.splice(n,0,t),this.values.splice(n,0,r)}}clear(){this.keys=[],this.values=[]}containsKey(t){return this.keys.indexOf(t)!==-1}containsValue(t){return this.values.indexOf(t)!==-1}count(){return this.keys.length}getValue(t){let r=this.keys.indexOf(t);return r!==-1?this.values[r]:!1}getKeys(){return this.keys.slice()}getValues(){return this.values.slice()}remove(t){let r=this.keys.indexOf(t);return r!==-1?(this.keys.splice(r,1),this.values.splice(r,1),!0):!1}update(t,r){let n=this.keys.indexOf(t);return n!==-1?(this.values[n]=r,!0):!1}},bt=class{data={};add(t,r){return this.containsKey(t)?!1:(this.data[t]=r,!0)}upsert(t,r){this.data[t]=r}clear(){this.data={}}containsKey(t){return this.data.hasOwnProperty(t)}containsValue(t){for(let r in this.data)if(this.data[r]===t)return!0;return!1}count(){return Object.keys(this.data).length}getValue(t){return this.containsKey(t)?this.data[t]:!1}getKeys(){return Object.keys(this.data)}getValues(){let t=[];for(let r in this.data)t.push(this.data[r]);return t}remove(t){return this.containsKey(t)?delete this.data[t]:!1}update(t,r){return this.containsKey(t)?(this.data[t]=r,!0):!1}getInternalObject(){return this.data}}});var bi,$p=T(()=>{"use strict";Vo();Y();bi=class e{static lockedFieldCount=new bt;static dependencyFieldCount=new bt;static getNecessaryLookUpTable(t){switch(t){case Ur.DependencyFieldTable:return e.dependencyFieldCount;case Ur.LockedFieldTable:return e.lockedFieldCount}}static initCanvasLockedFieldLookUp(t){switch(t){case Ur.DependencyFieldTable:e.dependencyFieldCount=new bt;case Ur.LockedFieldTable:e.lockedFieldCount=new bt}}}});var Ql,Ob=T(()=>{"use strict";Ve();Be();Y();Ye();Ql=class extends j{constructor(t){super(b.controlDescription,t)}get forControl(){let t=this.getProperty(g.ForControl);return _.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new L(t))}set forControl(t){this.setProperty(g.ForControl,`{${t.ToString()}}`)}get customControls(){return this.getChildren(b.customControl)}set customControls(t){this.deleteAllChildren();for(let r of t)this.addChild(r)}get DefaultControlClassId(){for(let t of this.customControls)if(!_.IsNullOrUndefined(t.id))return t.id;return null}get DefaultCustomControl(){for(let t of this.customControls)if(!_.IsNullOrUndefined(t.id))return t;return null}get DefaultCustomControls(){let t=[];for(let r of this.customControls)_.IsNullOrUndefined(r.id)||t.push(r);return t}async toJSON(t){let r=await this.getCustomControlsJSON(t);return r?{UniqueId:this.forControl.guidString,CustomControls:r,VersionNumber:0,OverallVersionNumber:0}:null}async getCustomControlsJSON(t){if(this.customControls){let r=[];for(let n of this.customControls){let i=await n.toJSON(t);i&&r.push(i)}return r}return null}}});var Lb,Fb,wt,R,xb,Wn,wi,ha,qp,Vp,ga=T(()=>{"use strict";Lb={Name:"Name",Value:"Value",Type:"Type",TypeGroup:"TypeGroup",Usage:"Usage",Static:"Static",Primary:"Primary",Columns:"Columns",EnableViewPicker:"EnableViewPicker",EntityName:"EntityName",FilteredViewIds:"FilteredViewIds",ReferencingName:"ReferencingName",RelationshipName:"RelationshipName",RelationshipType:"RelationshipType",TargetEntityType:"TargetEntityType",ViewId:"ViewId",DependentAttributeName:"DependentAttributeName",DependentAttributeType:"DependentAttributeType",DefaultViewId:"DefaultViewId",BindAttribute:"BindAttribute",FilterRelationshipName:"FilterRelationshipName",AvailableViewIds:"AvailableViewIds",QuickForms:"QuickForms",EntityNameKey:"EntityNameKey",CardFormType:"Form.Card",CardFormId:"CardFormId",Hidden:"Hidden",Required:"Required",DefaultValue:"DefaultValue"},Fb={GroupDefinition:"GroupDefinition"},wt={Control:"control",Resources:"resources",DisplayNameKey:"display-name-key",descriptionKey:"description-key",value:"value",name:"name",defaultKey:"default",groups:"groups",group:"group",property:"property",hidden:"hidden",required:"required",typeGroup:"type-group",type:"type",usage:"usage",ofType:"of-type",ofTypeGroup:"of-type-group",ImageURL:"preview-image",DefaultValue:"default-value",static:"static",dataset:"data-set",propertySet:"property-set",initialDatasetFetch:"initial-data-set-fetch",editable:"editable",cdsDatasetOptions:"cds-data-set-options",allowDefaultSelectedItems:"allow-default-selected-items",resettable:"resettable",isGroup:"isGroup",entityName:"entityname"};(function(e){e.Boolean="Boolean",e.Currency="Currency",e.DateAndTimeDateAndTime="DateAndTime.DateAndTime",e.DateAndTimeDateOnly="DateAndTime.DateOnly",e.Decimal="Decimal",e.Enum="Enum",e.FP="FP",e.File="File",e.Guid="Guid",e.Image="Image",e.LookupCustomer="Lookup.Customer",e.LookupOwner="Lookup.Owner",e.LookupPartyList="Lookup.PartyList",e.LookupRegarding="Lookup.Regarding",e.LookupSimple="Lookup.Simple",e.Multiple="Multiple",e.MultiSelectOptionSet="MultiSelectOptionSet",e.OptionSet="OptionSet",e.SingleLineEmail="SingleLine.Email",e.SingleLinePhone="SingleLine.Phone",e.SingleLineText="SingleLine.Text",e.SingleLineTextArea="SingleLine.TextArea",e.SingleLineTickerSymbol="SingleLine.Ticker",e.SingleLineURL="SingleLine.URL",e.TwoOptions="TwoOptions",e.WholeDuration="Whole.Duration",e.WholeLanguage="Whole.Language",e.WholeNone="Whole.None",e.WholeTimeZone="Whole.TimeZone",e.BusinessProcessFlow="BusinessProcessFlow",e.CardForm="Form.Card",e.Dashboard="Dashboard",e.FormMain="Form.Main",e.Grid="Grid",e.PowerBIReport="PowerBI.Report",e.QuickForm="Form.QuickForm",e.Search="Search",e.SearchWidget="SearchWidget",e.TimelineWall="TimelineWall",e.UnboundCustomControl="Unbound",e.WebResourceHtmlControl="WebResource.HTML"})(R||(R={}));(function(e){e.BooleanType="CC_FlipLabel_Name",e.DateTimeType="CC_TextBox_Name",e.DecimalType="CC_TextBox_Name",e.DoubleType="CC_TextBox_Name",e.IntegerType="CC_TextBox_Name",e.LookupType="CC_TextBox_Name",e.MemoType="CC_TextArea_Name",e.MoneyType="CC_TextBox_Name",e.OptionSetType="CC_OptionSet_Name",e.StringType="CC_TextBox_Name",e.GridType="CC_ReadOnlyGrid_Name",e.UnboundCustomControlType="CC_UnboundCustomControl_Name"})(xb||(xb={}));(function(e){e.ArcKnobControl="MscrmControls.Knob.ArcKnobControl",e.CardFeedNameControl="MscrmControls.CardFeedContainer.CardFeedContainer",e.CheckboxControl="MscrmControls.FieldControls.CheckboxControl",e.DateTimeControl="MscrmControls.FieldControls.DateTimeControl",e.DurationControl="MscrmControls.FieldControls.DurationControl",e.EditableGridControl="MscrmControls.Grid.GridControl",e.EmailEngagementActionsControl="MscrmControls.EmailEngagement.EmailEngagementActionsControl",e.FormComponent="MscrmControls.ModelForm.ModelFormControl",e.LanguageCodeControl="MscrmControls.FieldControls.LanguagePickerControl",e.LinearSliderControl="MscrmControls.Slider.LinearSliderControl",e.MultiSelectOptionSetControl="MscrmControls.MultiSelectPicklist.UpdMSPicklistControl",e.OptionSetControl="MscrmControls.OptionSet.OptionSetControl",e.PowerBIPCFControl="MscrmControls.PowerBIPCFControl",e.PredictiveScoringWidget="MscrmControls.Sales.PredictiveScoringWidget.PredictiveScoringWidget",e.ReadonlyGrid="MscrmControls.Grid.ReadOnlyGrid",e.SimilarCasesGrid="MscrmControls.Containers.SimilarCasesGridControl",e.StarRatingControl="MscrmControls.Rating.StarRatingControl",e.TimeZoneControl="MscrmControls.FieldControls.TimeZonePickListControl",e.ModelFormControl="MscrmControls.ModelForm.ModelFormControl",e.AutoCompleteControl="MscrmControls.AutoComplete.AutoCompleteControl",e.CanvasAppControl="MscrmControls.Canvas.CanvasControl",e.PowerAppsOneGrid="Microsoft.PowerApps.PowerAppsOneGrid"})(Wn||(Wn={}));(function(e){e[e.Read=0]="Read",e[e.Edit=1]="Edit",e[e.Both=2]="Both",e[e.Container=3]="Container",e[e.Unknown=4]="Unknown"})(wi||(wi={}));(function(e){e[e.Bound=0]="Bound",e[e.Input=1]="Input",e[e.Output=2]="Output"})(ha||(ha={}));qp=[R.LookupCustomer,R.LookupOwner,R.LookupPartyList,R.LookupRegarding,R.LookupSimple],Vp=[R.WholeNone,R.WholeDuration,R.WholeLanguage,R.WholeTimeZone,R.FP,R.Decimal]});function dn(){return $r||($r=window._makerConfig,$r&&window?.location?.search?.indexOf("useProductionConfig")>-1&&($r={...$r,region:"prod",graphQLEndpoint:"https://graph.make.powerapps.com/"}),$r?.region==="prod"&&($r={endpoints:{eu:{ch:{graphql:"https://graph-make.ch-cm001.gateway.prod.cm.powerapps.com/"},de:{graphql:"https://graph-make.de-cm001.gateway.prod.cm.powerapps.com/"},fr:{graphql:"https://graph-make.fr-cm001.gateway.prod.cm.powerapps.com/"},no:{graphql:"https://graph-make.no-cm001.gateway.prod.cm.powerapps.com/"},default:{graphql:"https://graph-make.eu-cm001.gateway.prod.cm.powerapps.com/"}}},...$r}),$r||{aadClientId:"a8f7a65c-f5ba-4859-b2d6-df772c264e9d",location:"cus",region:"test",publicPath:"/",graphQLEndpoint:"https://graph.make.test.powerapps.com/"})}var $r,Xl=T(()=>{"use strict";});function kb(e,t,r){if(!e)return Yl.has(e)||(window._ppux?.log?.("PPUX/Geo/NonExistent",{eventType:"Trace",team:"Shell",severity:"Error",errorCode:"GeoIsEmpty"}),Yl.add("")),!1;if(e){if(e=e.toLowerCase(),Yl.has(e))return!1;if(!(e in t))return window._ppux?.log?.("PPUX/Geo/NonExistent",{eventType:"Trace",team:"Shell",severity:"Error",errorCode:"GeoNonExistent",eventInfo:{missinggeo:e,parent:r}}),Yl.add(e),!1}return!0}function tB(e){return kb(e,Gp,"Location dictionary")?Gp[e.toLowerCase()]:"us"}function rB(){let e=dn().location.toLowerCase();return kb(e,Gp,"Current location dictionary")?e:"us"}var Yl,Gp,qJ,Mb=T(()=>{"use strict";Xl();Yl=new Set,Gp={cae:"ae",nae:"ae",eas:"as",seas:"as",eau:"au",seau:"au",sbr:"br",cca:"ca",eca:"ca",nch:"ch",wch:"ch",nde:"de",wcde:"de",neu:"eu",weu:"eu",cfr:"fr",sfr:"fr",cin:"in",sin:"in",ejp:"jp",wjp:"jp",suk:"uk",wuk:"uk",eus:"us",wus:"us",cus:"us",ude:"us",udc:"us",ugtx:"us",ugva:"us",eus2:"us",wus2:"us",nza:"za",wza:"za",cne2:"cn",cnn2:"cn",skr:"kr",ckr:"kr",eno:"no",wno:"no",wrx:"us",erx:"us",wex:"us",eex:"us",unitedstates:"us",europe:"eu",asia:"as",australia:"au",japan:"jp",canada:"ca",india:"in",italy:"it",unitedstatesfirstrelease:"us",unitedkingdom:"uk",southamerica:"br",france:"fr",unitedarabemirates:"ae",germany:"de",sweden:"se",switzerland:"ch",korea:"kr",norway:"no",usgov:"us",usgovhigh:"us",usdod:"us",china:"cn",usnat:"us",ussec:"us",southafrica:"za",singapore:"sg",newzealand:"nz",poland:"pl",qatar:"qa",as:"as",au:"au",ca:"ca",in:"in",jp:"jp",kr:"kr",nz:"nz",ae:"ae",qa:"qa",us:"us",uk:"uk",eu:"eu",de:"de",ch:"ch",no:"no",fr:"fr",se:"se",it:"it",pl:"pl",be:"eu",bel:"eu",gr:"eu",grc:"eu",lt:"eu",ltu:"eu",pt:"eu",prt:"eu",bg:"eu",bgr:"eu",es:"eu",esp:"eu",lu:"eu",lux:"eu",ro:"eu",rou:"eu",cz:"eu",cze:"eu",hu:"eu",hun:"eu",si:"eu",svn:"eu",dk:"eu",dnk:"eu",hr:"eu",hrv:"eu",mt:"eu",mlt:"eu",sk:"eu",svk:"eu",nit:"it",nl:"eu",nld:"eu",fi:"eu",fin:"eu",ee:"eu",est:"eu",cy:"eu",cyp:"eu",at:"eu",aut:"eu",swe:"se",cse:"se",ie:"eu",irl:"eu",lv:"eu",lva:"eu",cpl:"pl",nnz:"nz",cqa:"qa",sg:"sg",br:"br",za:"za",sa:"za"};qJ=tB(rB())});var V,GJ,Bb=T(()=>{"use strict";V={USWest:"westus",USWest2:"westus2",USCentral:"centralus",USEast:"eastus",USEast2:"eastus2",USNorthCentral:"northcentralus",USSouthCentral:"southcentralus",USWestCentral:"westcentralus",CanadaCentral:"canadacentral",CanadaEast:"canadaeast",BrazilSouth:"brazilsouth",EuropeNorth:"northeurope",EuropeWest:"westeurope",UKSouth:"uksouth",UKWest:"ukwest",FranceCentral:"francecentral",FranceSouth:"francesouth",SwitzerlandNorth:"switzerlandnorth",SwitzerlandWest:"switzerlandwest",GermanyNorth:"germanynorth",GermanyWestCentral:"germanywestcentral",NorwayWest:"norwaywest",NorwayEast:"norwayeast",SwedenCentral:"swedencentral",ItalyNorth:"italynorth",PolandCentral:"polandcentral",AsiaEast:"eastasia",AsiaSouthEast:"southeastasia",JapanEast:"japaneast",JapanWest:"japanwest",AustraliaEast:"australiaeast",AustraliaSouthEast:"australiasoutheast",AustraliaCentral:"australiacentral",AustraliaCentral2:"australiacentral2",IndiaCentral:"centralindia",IndiaSouth:"southindia",IndiaWest:"westindia",KoreaSouth:"koreasouth",KoreaCentral:"koreacentral",NewZealandNorth:"newzealandnorth",UAECentral:"uaecentral",UAENorth:"uaenorth",SouthAfricaNorth:"southafricanorth",SouthAfricaWest:"southafricawest",QatarCentral:"qatarcentral",GermanyCentral:"germanycentral",GermanyNorthEast:"germanynortheast",SingaporeSouthEast:"southeastasia",GovernmentUSVirginia:"usgovvirginia",GovernmentUSIowa:"usgoviowa",GovernmentUSArizona:"usgovarizona",GovernmentUSTexas:"usgovtexas",GovernmentUSDodEast:"usdodeast",GovernmentUSDodCentral:"usdodcentral",ChinaNorth:"chinanorth",ChinaNorth2:"chinanorth2",ChinaNorth3:"chinanorth3",ChinaEast:"chinaeast",ChinaEast2:"chinaeast2",ChinaEast3:"chinaeast3",UssecEast:"usseceast",UssecWest:"ussecwest",UsnatEast:"usnateast",UsnatWest:"usnatwest"},GJ={[V.USWest]:{geoName:"us",regionShortName:"wus"},[V.USCentral]:{geoName:"us",regionShortName:"cus"},[V.USEast]:{geoName:"us",regionShortName:"eus"},[V.USEast2]:{geoName:"us",regionShortName:"eus2"},[V.USWestCentral]:{geoName:"us",regionShortName:"wcus"},[V.USWest2]:{geoName:"us",regionShortName:"wus2"},[V.USSouthCentral]:{geoName:"br",regionShortName:"scus"},[V.BrazilSouth]:{geoName:"br",regionShortName:"sbr"},[V.UKSouth]:{geoName:"uk",regionShortName:"suk"},[V.UKWest]:{geoName:"uk",regionShortName:"wuk"},[V.JapanEast]:{geoName:"jp",regionShortName:"ejp"},[V.JapanWest]:{geoName:"jp",regionShortName:"wjp"},[V.IndiaCentral]:{geoName:"in",regionShortName:"cin"},[V.IndiaSouth]:{geoName:"in",regionShortName:"sin"},[V.ItalyNorth]:{geoName:"it",regionShortName:"nit"},[V.GermanyWestCentral]:{geoName:"de",regionShortName:"wcde"},[V.GermanyNorth]:{geoName:"de",regionShortName:"nde"},[V.EuropeNorth]:{geoName:"eu",regionShortName:"neu"},[V.EuropeWest]:{geoName:"eu",regionShortName:"weu"},[V.AustraliaEast]:{geoName:"au",regionShortName:"eau"},[V.AustraliaSouthEast]:{geoName:"au",regionShortName:"seau"},[V.AsiaSouthEast]:{geoName:"as",regionShortName:"seas"},[V.AsiaEast]:{geoName:"as",regionShortName:"eas"},[V.CanadaCentral]:{geoName:"ca",regionShortName:"cca"},[V.CanadaEast]:{geoName:"ca",regionShortName:"eca"},[V.SouthAfricaNorth]:{geoName:"za",regionShortName:"nza"},[V.SouthAfricaWest]:{geoName:"za",regionShortName:"wza"},[V.FranceCentral]:{geoName:"fr",regionShortName:"cfr"},[V.FranceSouth]:{geoName:"fr",regionShortName:"sfr"},[V.UAENorth]:{geoName:"ae",regionShortName:"nae"},[V.UAECentral]:{geoName:"ae",regionShortName:"cae"},[V.SwedenCentral]:{geoName:"se",regionShortName:"cse"},[V.SwitzerlandNorth]:{geoName:"ch",regionShortName:"nch"},[V.SwitzerlandWest]:{geoName:"ch",regionShortName:"wch"},[V.NorwayEast]:{geoName:"no",regionShortName:"eno"},[V.NorwayWest]:{geoName:"no",regionShortName:"wno"},[V.KoreaCentral]:{geoName:"kr",regionShortName:"ckr"},[V.KoreaSouth]:{geoName:"kr",regionShortName:"skr"},[V.SingaporeSouthEast]:{geoName:"sg",regionShortName:"seas"},[V.PolandCentral]:{geoName:"pl",regionShortName:"cpl"},[V.QatarCentral]:{geoName:"qa",regionShortName:"cqa"},[V.NewZealandNorth]:{geoName:"nz",regionShortName:"nnz"},[V.GovernmentUSTexas]:{geoName:"us",regionShortName:"ugtx"},[V.GovernmentUSVirginia]:{geoName:"us",regionShortName:"ugva"},[V.GovernmentUSDodCentral]:{regionShortName:"udc"},[V.GovernmentUSDodEast]:{regionShortName:"ude"},[V.ChinaEast]:{regionShortName:"cne"},[V.ChinaEast2]:{regionShortName:"cne2"},[V.ChinaEast3]:{regionShortName:"cne3"},[V.ChinaNorth]:{regionShortName:"cnn"},[V.ChinaNorth2]:{regionShortName:"cnn2"},[V.ChinaNorth3]:{regionShortName:"cnn3"},[V.UssecEast]:{geoName:"us",regionShortName:"erx"},[V.UssecWest]:{geoName:"us",regionShortName:"wrx"},[V.UsnatEast]:{geoName:"us",regionShortName:"eex"},[V.UsnatWest]:{geoName:"us",regionShortName:"wex"}}});var Ub=T(()=>{"use strict";Xl();});var Go=T(()=>{"use strict";Xl();Mb();Bb();Ub();});function zo(e,t){return $b?$b.isOverridden(e,t):{overridden:!1}}var $b,Wo=T(()=>{"use strict";});var zp=T(()=>{"use strict";Go();Wo();});function nB(e,t){let{region:r}=dn();return()=>{let n=e.settings[t];if(n.allowOverrides){let s=zo(e.packageName,t);if(s.overridden)return typeof s.value=="string"?iB(s.value):s.value}let a=n.values,o=process.env.SETTINGS_FALLBACK_REGION?.[r];return a[r]!==void 0?a[r]:o&&a[o]!==void 0?a[o]:a.default}}function iB(e){return isNaN(Number(e))?e==="true"?!0:e==="false"?!1:e:Number(e)}function aB(e){let t=e.packageName;if(Zl.has(t)){let r=`settings has already been created for this package ${t}`;throw console.error(r),new Error(r)}if(Object.keys(e.settings).some(r=>jp(t,r))){let r=`error parsing settings config for package ${t}, a feature gate with the same name exists`;throw console.error(r),new Error(r)}Object.keys(e.settings).forEach(r=>{if(Object.keys(e.settings[r].values).filter(i=>i!=="default").some(i=>!tu(i))){let i=`error parsing settings config for package ${t}, setting ${r} has invalid region`;throw console.error(i),new Error(i)}})}function jo(e){aB(e);let t={};return Object.keys(e.settings).forEach(r=>{t[r]={enumerable:!0,get:nB(e,r)}}),Zl.set(e.packageName,e),Object.defineProperties({},t)}function Wp(e,t){return Zl.has(e)?!!Zl.get(e).settings[t]:!1}var Zl,eu=T(()=>{"use strict";Go();Wo();Hp();Ho();Zl=new Map});function qb(e,t){let{region:r}=dn();return()=>{let n=zo(e.packageName,t);if(n.overridden)return n.value.toString()==="true";let i=e.features[t].enabledFor,a=process.env.SETTINGS_FALLBACK_REGION?.[r];return i[r]!==void 0?!!i[r]:a&&i[a]!==void 0?!!i[a]:!1}}function oB(e){let t=e.packageName;if(ru.has(t)){let r="feature gates has already been created for this package";throw console.error(r),new Error(r)}if(Object.keys(e.features).some(r=>Wp(t,r))){let r=`error parsing feature gates config for package ${t}, a setting with the same name exists`;throw console.error(r),new Error(r)}Object.keys(e.features).forEach(r=>{if(Object.keys(e.features[r].enabledFor).some(i=>!tu(i))){let i=`error parsing feature gates config for package ${t}, feature ${r} has invalid region`;throw console.error(i),new Error(i)}})}function Jp(e){oB(e);let t={};Object.keys(e.features).forEach(i=>{t[i]={enumerable:!0,configurable:!0,get:qb(e,i)}});let r={},n=new Set;return t.dangerouslySet={enumerable:!1,value:(i,a)=>{n.add(i),Object.defineProperty(r,i,{enumerable:!0,configurable:!0,value:a})}},t.dangerouslyReset={enumerable:!1,value:()=>{let i={};n.forEach(a=>{i[a.toString()]={enumerable:!0,configurable:!0,get:qb(e,a.toString())}}),Object.defineProperties(r,i),n.clear()}},ru.set(e.packageName,e),Object.defineProperties(r,t)}function jp(e,t){return ru.has(e)?!!ru.get(e).features[t]:!1}var ru,Hp=T(()=>{"use strict";Go();Ho();Wo();eu();ru=new Map});var Gb=y((mK,Vb)=>{"use strict";Vb.exports=function(t,r){if(r=r.split(":")[0],t=+t,!t)return!1;switch(r){case"http":case"ws":return t!==80;case"https":case"wss":return t!==443;case"ftp":return t!==21;case"gopher":return t!==70;case"file":return!1}return t!==0}});var jb=y(Kp=>{"use strict";var sB=Object.prototype.hasOwnProperty,lB;function zb(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch{return null}}function Wb(e){try{return encodeURIComponent(e)}catch{return null}}function uB(e){for(var t=/([^=?#&]+)=?([^&]*)/g,r={},n;n=t.exec(e);){var i=zb(n[1]),a=zb(n[2]);i===null||a===null||i in r||(r[i]=a)}return r}function cB(e,t){t=t||"";var r=[],n,i;typeof t!="string"&&(t="?");for(i in e)if(sB.call(e,i)){if(n=e[i],!n&&(n===null||n===lB||isNaN(n))&&(n=""),i=Wb(i),n=Wb(n),i===null||n===null)continue;r.push(i+"="+n)}return r.length?t+r.join("&"):""}Kp.stringify=cB;Kp.parse=uB});var Yp=y((gK,Yb)=>{"use strict";var Jb=Gb(),nu=jb(),Kb=/[\n\r\t]/g,dB=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,pB=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,fB=/^[a-zA-Z]:/,mB=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;function Xp(e){return(e||"").toString().replace(mB,"")}var Qp=[["#","hash"],["?","query"],function(t,r){return qr(r.protocol)?t.replace(/\\/g,"/"):t},["/","pathname"],["@","auth",1],[NaN,"host",void 0,1,1],[/:(\d*)$/,"port",void 0,1],[NaN,"hostname",void 0,1,1]],Hb={hash:1,query:1};function Qb(e){var t;typeof window<"u"?t=window:typeof global<"u"?t=global:typeof self<"u"?t=self:t={};var r=t.location||{};e=e||r;var n={},i=typeof e,a;if(e.protocol==="blob:")n=new Vr(unescape(e.pathname),{});else if(i==="string"){n=new Vr(e,{});for(a in Hb)delete n[a]}else if(i==="object"){for(a in e)a in Hb||(n[a]=e[a]);n.slashes===void 0&&(n.slashes=dB.test(e.href))}return n}function qr(e){return e==="file:"||e==="ftp:"||e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function Xb(e,t){e=Xp(e),e=e.replace(Kb,""),t=t||{};var r=pB.exec(e),n=r[1]?r[1].toLowerCase():"",i=!!r[2],a=!!r[3],o=0,s;return i?a?(s=r[2]+r[3]+r[4],o=r[2].length+r[3].length):(s=r[2]+r[4],o=r[2].length):a?(s=r[3]+r[4],o=r[3].length):s=r[4],n==="file:"?o>=2&&(s=s.slice(2)):qr(n)?s=r[4]:n?i&&(s=s.slice(2)):o>=2&&qr(t.protocol)&&(s=r[4]),{protocol:n,slashes:i||qr(n),slashesCount:o,rest:s}}function hB(e,t){if(e==="")return t;for(var r=(t||"/").split("/").slice(0,-1).concat(e.split("/")),n=r.length,i=r[n-1],a=!1,o=0;n--;)r[n]==="."?r.splice(n,1):r[n]===".."?(r.splice(n,1),o++):o&&(n===0&&(a=!0),r.splice(n,1),o--);return a&&r.unshift(""),(i==="."||i==="..")&&r.push(""),r.join("/")}function Vr(e,t,r){if(e=Xp(e),e=e.replace(Kb,""),!(this instanceof Vr))return new Vr(e,t,r);var n,i,a,o,s,l,u=Qp.slice(),c=typeof t,d=this,p=0;for(c!=="object"&&c!=="string"&&(r=t,t=null),r&&typeof r!="function"&&(r=nu.parse),t=Qb(t),i=Xb(e||"",t),n=!i.protocol&&!i.slashes,d.slashes=i.slashes||n&&t.slashes,d.protocol=i.protocol||t.protocol||"",e=i.rest,(i.protocol==="file:"&&(i.slashesCount!==2||fB.test(e))||!i.slashes&&(i.protocol||i.slashesCount<2||!qr(d.protocol)))&&(u[3]=[/(.*)/,"pathname"]);p<u.length;p++){if(o=u[p],typeof o=="function"){e=o(e,d);continue}a=o[0],l=o[1],a!==a?d[l]=e:typeof a=="string"?(s=a==="@"?e.lastIndexOf(a):e.indexOf(a),~s&&(typeof o[2]=="number"?(d[l]=e.slice(0,s),e=e.slice(s+o[2])):(d[l]=e.slice(s),e=e.slice(0,s)))):(s=a.exec(e))&&(d[l]=s[1],e=e.slice(0,s.index)),d[l]=d[l]||n&&o[3]&&t[l]||"",o[4]&&(d[l]=d[l].toLowerCase())}r&&(d.query=r(d.query)),n&&t.slashes&&d.pathname.charAt(0)!=="/"&&(d.pathname!==""||t.pathname!=="")&&(d.pathname=hB(d.pathname,t.pathname)),d.pathname.charAt(0)!=="/"&&qr(d.protocol)&&(d.pathname="/"+d.pathname),Jb(d.port,d.protocol)||(d.host=d.hostname,d.port=""),d.username=d.password="",d.auth&&(s=d.auth.indexOf(":"),~s?(d.username=d.auth.slice(0,s),d.username=encodeURIComponent(decodeURIComponent(d.username)),d.password=d.auth.slice(s+1),d.password=encodeURIComponent(decodeURIComponent(d.password))):d.username=encodeURIComponent(decodeURIComponent(d.auth)),d.auth=d.password?d.username+":"+d.password:d.username),d.origin=d.protocol!=="file:"&&qr(d.protocol)&&d.host?d.protocol+"//"+d.host:"null",d.href=d.toString()}function gB(e,t,r){var n=this;switch(e){case"query":typeof t=="string"&&t.length&&(t=(r||nu.parse)(t)),n[e]=t;break;case"port":n[e]=t,Jb(t,n.protocol)?t&&(n.host=n.hostname+":"+t):(n.host=n.hostname,n[e]="");break;case"hostname":n[e]=t,n.port&&(t+=":"+n.port),n.host=t;break;case"host":n[e]=t,/:\d+$/.test(t)?(t=t.split(":"),n.port=t.pop(),n.hostname=t.join(":")):(n.hostname=t,n.port="");break;case"protocol":n.protocol=t.toLowerCase(),n.slashes=!r;break;case"pathname":case"hash":if(t){var i=e==="pathname"?"/":"#";n[e]=t.charAt(0)!==i?i+t:t}else n[e]=t;break;case"username":case"password":n[e]=encodeURIComponent(t);break;case"auth":var a=t.indexOf(":");~a?(n.username=t.slice(0,a),n.username=encodeURIComponent(decodeURIComponent(n.username)),n.password=t.slice(a+1),n.password=encodeURIComponent(decodeURIComponent(n.password))):n.username=encodeURIComponent(decodeURIComponent(t))}for(var o=0;o<Qp.length;o++){var s=Qp[o];s[4]&&(n[s[1]]=n[s[1]].toLowerCase())}return n.auth=n.password?n.username+":"+n.password:n.username,n.origin=n.protocol!=="file:"&&qr(n.protocol)&&n.host?n.protocol+"//"+n.host:"null",n.href=n.toString(),n}function vB(e){(!e||typeof e!="function")&&(e=nu.stringify);var t,r=this,n=r.host,i=r.protocol;i&&i.charAt(i.length-1)!==":"&&(i+=":");var a=i+(r.protocol&&r.slashes||qr(r.protocol)?"//":"");return r.username?(a+=r.username,r.password&&(a+=":"+r.password),a+="@"):r.password?(a+=":"+r.password,a+="@"):r.protocol!=="file:"&&qr(r.protocol)&&!n&&r.pathname!=="/"&&(a+="@"),n[n.length-1]===":"&&(n+=":"),a+=n+r.pathname,t=typeof r.query=="object"?e(r.query):r.query,t&&(a+=t.charAt(0)!=="?"?"?"+t:t),r.hash&&(a+=r.hash),a}Vr.prototype={set:gB,toString:vB};Vr.extractProtocol=Xb;Vr.location=Qb;Vr.trimLeft=Xp;Vr.qs=nu;Yb.exports=Vr});var yB,Zb=T(()=>{"use strict";yB=se(Yp());});function Zp(e,t,r){let n=Object.keys(r).sort();if(n.length===0)throw new Error(`ECS feature has no properties: ${e}.${t}`);let i=`ecs.${e}.${t}`;return n.length===1?`${i}.${n[0]}`:`${i}.{${n.join(";")}}`}var iu=T(()=>{"use strict";});var ef,tf,rf=T(()=>{"use strict";iu();ef=class{features=new Map;register(t,r){let n=Zp(r,t.teamName,t.fallback),i={clientName:r,teamName:t.teamName,fullName:n,description:t.description,owners:t.owners,ecsURL:t.ecsURL,createdOn:t.createdOn,fallbackConfig:t.fallback,feature:t,displayTeam:t.displayTeam,tags:t.tags,category:t.category};this.features.set(n,i)}getAll(){return Array.from(this.features.values())}get(t){return this.features.get(t)}has(t){return this.features.has(t)}getByClient(t){return this.getAll().filter(r=>r.clientName===t)}getByTeam(t){return this.getAll().filter(r=>r.teamName===t)}search(t){let r=t.toLowerCase();return this.getAll().filter(n=>n.fullName.toLowerCase().includes(r)||n.description?.toLowerCase().includes(r)||n.teamName.toLowerCase().includes(r)||n.clientName.toLowerCase().includes(r))}getClientNames(){let t=new Set;return this.features.forEach(r=>t.add(r.clientName)),Array.from(t)}getTeamNames(){let t=new Set;return this.features.forEach(r=>t.add(r.teamName)),Array.from(t)}clear(){this.features.clear()}},tf=new ef});var nf=T(()=>{"use strict";});function tu(e){return bB.has(e)}var bB,Ho=T(()=>{"use strict";zp();Hp();eu();Wo();zp();Zb();rf();iu();nf();bB=new Set(["tie","test","prod","preview","preprod","gov","high","dod","mooncake","ex","rx"])});var wB,ew=T(()=>{"use strict";Ho();wB=jo({packageName:"cds-designer-models",settings:{testCustomControls:{description:"Test Custom Controls to show up in the component picker.",allowOverrides:!0,values:{default:"",test:"",preprod:"",preview:"",gov:""}}}})});var au,B,G,Ai,va,ou,tw,rw,af,Jo=T(()=>{"use strict";Vo();au=class{name;constructor(t){this.name=t}toString(){return this.name}getName(){return this.name}getDisplayNameResourceKey(){return af.getDisplayNameResourceKey(this.name)}};(function(e){e.BigInt="BigIntType",e.CalendarRulesType="CalendarRulesType",e.Currency="MoneyType",e.Customer="Customer",e.CustomerType="CustomerType",e.DateTime="DateTimeType",e.DecimalNumber="DecimalType",e.EntityNameType="EntityNameType",e.FloatingPointNumber="DoubleType",e.Image="ImageType",e.File="FileType",e.Lookup="Lookup",e.LookupType="LookupType",e.ManagedPropertyType="ManagedPropertyType",e.MultipleLineofText="MemoType",e.MultiSelectOptionSet="MultiSelectPicklistType",e.OptionSet="PicklistType",e.Owner="Owner",e.OwnerType="OwnerType",e.PartyList="PartyList",e.PartyListType="PartyListType",e.PrimaryNameAttributeType="String",e.SingleLineofText="StringType",e.State="StateType",e.Status="StatusType",e.Subject="Subject",e.TimeStamp="TimeStampType",e.TwoOptions="BooleanType",e.UniqueIdentifier="Uniqueidentifier",e.UniqueIdentifierType="UniqueidentifierType",e.VirtualType="VirtualType",e.WholeNumber="IntegerType"})(B||(B={}));(function(e){e.Email="Email",e.Text="Text",e.TextArea="TextArea",e.Url="Url",e.TickerSymbol="TickerSymbol",e.PhoneticGuide="PhoneticGuide",e.VersionNumber="VersionNumber",e.Phone="Phone",e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale",e.DateOnly="DateOnly",e.DateAndTime="DateAndTime",e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean",e.Regarding="Regarding"})(G||(G={}));Ai=class extends au{constructor(t){super(t)}static get None(){return"None"}static get SystemRequired(){return"SystemRequired"}static get ApplicationRequired(){return"ApplicationRequired"}static get Recommended(){return"Recommended"}},va=class e extends au{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get Persistent(){return"Persistent"}static get Calculated(){return"Calculated"}static get Rollup(){return"Rollup"}GetValue(){return this.name===e.None?ou.Persistent:parseInt(ou[this.name])}};(function(e){e[e.Persistent=0]="Persistent",e[e.Calculated=1]="Calculated",e[e.Rollup=2]="Rollup"})(ou||(ou={}));(function(e){e[e.Undefined=0]="Undefined",e[e.Simple=1]="Simple",e[e.Related=2]="Related",e[e.Logical=4]="Logical",e[e.Calculated=8]="Calculated",e[e.Rollup=16]="Rollup",e[e.Invalid=32]="Invalid"})(tw||(tw={}));(function(e){e[e.Attribute=0]="Attribute",e[e.Organization=1]="Organization",e[e.Currency=2]="Currency"})(rw||(rw={}));af=class e{static resourceKeyMap=e.initResourceKeyMap();static initResourceKeyMap(){let t=new ma;return t.add(B.TwoOptions,"SystemCustomization.type.bit.label"),t.add(B.Customer,"SystemCustomization.type.customer.label"),t.add(B.CustomerType,"SystemCustomization.type.customer.label"),t.add(B.DateTime,"SystemCustomization.type.datetime.label"),t.add(B.DecimalNumber,"SystemCustomization.type.decimal.label"),t.add(B.FloatingPointNumber,"SystemCustomization.type.float.label"),t.add(B.WholeNumber,"SystemCustomization.type.int.label"),t.add(B.LookupType,"SystemCustomization.type.lookup.label"),t.add(B.Lookup,"SystemCustomization.type.lookup.label"),t.add(B.MultipleLineofText,"SystemCustomization.type.ntext.label"),t.add(B.Currency,"SystemCustomization.type.money.label"),t.add(B.Owner,"SystemCustomization.type.owner.label"),t.add(B.OwnerType,"SystemCustomization.type.owner.label"),t.add(B.PartyList,"SystemCustomization.type.partylist.label"),t.add(B.PartyListType,"SystemCustomization.type.partylist.label"),t.add(B.OptionSet,"SystemCustomization.type.picklist.label"),t.add(B.State,"SystemCustomization.type.state.label"),t.add(B.Status,"SystemCustomization.type.status.label"),t.add(B.SingleLineofText,"SystemCustomization.type.nvarchar.label"),t.add(B.UniqueIdentifier,"SystemCustomization.type.uniqueidentifier.label"),t.add(B.UniqueIdentifierType,"SystemCustomization.type.uniqueidentifiertype.label"),t.add(B.CalendarRulesType,"SystemCustomization.type.calendarrules.label"),t.add(B.VirtualType,"SystemCustomization.type.virtual.label"),t.add(B.BigInt,"SystemCustomization.type.bigint.label"),t.add(B.ManagedPropertyType,"SystemCustomization.type.managedproperty.label"),t.add(B.EntityNameType,"SystemCustomization.type.entityname.label"),t.add(B.Image,"SystemCustomization.type.image.label"),t.add(B.MultiSelectOptionSet,"SystemCustomization.type.multiselectpicklist.label"),t.add(B.PrimaryNameAttributeType,"SystemCustomization.type.primaryname.label"),t.add(B.LookupType,"SystemCustomization.type.lookuptype.label"),t.add(B.Subject,"SystemCustomization.type.subject.label"),t.add(G.Email,"SystemCustomization.String.Format.email"),t.add(G.Text,"SystemCustomization.String.Format.text"),t.add(G.TextArea,"SystemCustomization.String.Format.textarea"),t.add(G.Url,"SystemCustomization.String.Format.url"),t.add(G.TickerSymbol,"SystemCustomization.String.Format.tickersymbol"),t.add(G.PhoneticGuide,"SystemCustomization.String.Format.phoneticguide"),t.add(G.VersionNumber,"SystemCustomization.String.Format.versionnumber"),t.add(G.Phone,"SystemCustomization.String.Format.phone"),t.add(G.None,"SystemCustomization.Integer.Format."),t.add(G.Duration,"SystemCustomization.Integer.Format.duration"),t.add(G.TimeZone,"SystemCustomization.Integer.Format.timezone"),t.add(G.Language,"SystemCustomization.Integer.Format.language"),t.add(G.Locale,"SystemCustomization.Integer.Format.language"),t.add(G.DateOnly,"SystemCustomization.DateTime.Format.date"),t.add(G.DateAndTime,"SystemCustomization.DateTime.Format.datetime"),t.add(G.Regarding,"SystemCustomization.Lookup.Format.regarding"),t.add(va.Persistent,"SystemCustomization.String.Source.persistent"),t.add(va.Calculated,"SystemCustomization.String.Source.calculated"),t.add(va.Rollup,"SystemCustomization.String.Source.rollup"),t.add(va.None,"SystemCustomization.String.Source.none"),t}static getDisplayNameResourceKey(t){return e.resourceKeyMap.getValue(t)}}});var ow,sf,ya,Ci,of,su,ba,pn,Se,nw,iw,aw,vr=T(()=>{"use strict";ow={ThreeEqColumn_FirstColumn:34,ThreeEqColumn_SecondColumn:33,ThreeEqColumn_ThirdColumn:33,FiveEqColumn:20},sf={ONE_COLUMN:"1",TWO_COLUMN:"2",THREE_COLUMN:"3",FOUR_COLUMN:"4"};(function(e){e[e.SUBGRID=0]="SUBGRID",e[e.SPACER=1]="SPACER",e[e.QUICK_VIEW=2]="QUICK_VIEW",e[e.WEB_RESOURCE=3]="WEB_RESOURCE",e[e.IFRAME=4]="IFRAME",e[e.BING_MAPS=5]="BING_MAPS",e[e.TIMER=6]="TIMER",e[e.TIMELINE=7]="TIMELINE",e[e.SOCIAL_INSIGHTS=8]="SOCIAL_INSIGHTS",e[e.KB_SEARCH=9]="KB_SEARCH",e[e.ACI_CONTROL=10]="ACI_CONTROL",e[e.RELATIONSHIP_ASSISTANT=11]="RELATIONSHIP_ASSISTANT",e[e.REFERENCE_PANEL=12]="REFERENCE_PANEL",e[e.REF_PANEL_QUICKVIEW=13]="REF_PANEL_QUICKVIEW",e[e.REF_PANEL_SUBGRID=14]="REF_PANEL_SUBGRID",e[e.REF_PANEL_KBSEARCH=15]="REF_PANEL_KBSEARCH",e[e.WEB_RESOURCE_HTML=16]="WEB_RESOURCE_HTML",e[e.PRED_LEAD_SCORING=17]="PRED_LEAD_SCORING"})(ya||(ya={}));(function(e){e.Left="Left",e.Right="Right",e.Center="Center"})(Ci||(Ci={}));(function(e){e[e.Mobile=0]="Mobile",e[e.Tablet=1]="Tablet",e[e.Web=2]="Web"})(of||(of={}));su=class{static ONE_COLUMN=1;static TWO_COLUMN=2;static THREE_COLUMN=3;static FIVE_COLUMN=5};(function(e){e.Left="Left",e.Top="Top"})(ba||(ba={}));pn=class{static StartTag="<"},Se={ShowLabel:"true",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_",labelAlignment:Ci.Left,labelPosition:ba.Left,MarginalControlColumns:"111",referencePanelNamePrefix:"ref_pan_"};(function(e){e.AddFormBodyFieldToReadOnlyHeader="AddFormBodyFieldToReadOnlyHeader",e.AddFieldPaneFieldToReadOnlyHeader="AddFieldPaneFieldToReadOnlyHeader",e.AddFieldExceedsReadOnlyHeaderLimit="AddFieldExceedsReadOnlyHeaderLimit",e.AddCustomComponentToReadOnlyHeader="AddCustomComponentToReadOnlyHeader",e.AddNonDisplayableComponentToReadOnlyHeader="AddNonDisplayableComponentToReadOnlyHeader",e.AddFieldToFlyoutOnly="AddFieldToFlyoutOnly",e.DisplayedFieldToFlyout="DisplayedFieldToFlyout",e.FlyoutFieldToDisplayed="FlyoutFieldToDisplayed",e.AddControlBeforeDefaultLabel="AddControlBeforeDefaultLabel"})(nw||(nw={}));(function(e){e.TabWithLockedFieldRemoval="TabWithLockedFieldRemoval",e.SectionWithLockedFieldRemoval="SectionWithLockedFieldRemoval",e.LockedSectionRemoval="LockedSectionRemoval",e.LockedFieldRemoval="LockedFieldRemoval",e.RequiredFieldRemoval="RequiredFieldRemoval",e.LastRemainingTab="LastRemainingTab",e.UnknownRemoval="UnknownRemoval"})(iw||(iw={}));(function(e){e.IsHeader="IsHeader",e.IsFooter="IsFooter",e.ContainedInHeader="ContainedInHeader",e.ContainedInFooter="ContainedInFooter",e.NoElementFound="NoElementFound",e.NoTarget="NoTarget",e.CannotAddControlToHeader="CannotAddControlToHeader",e.CannotAddControlToFooter="CannotAddControlToFooter"})(aw||(aw={}))});var lf,sw=T(()=>{"use strict";(function(e){e.DefaultValue="defaultValue",e.Loaded="loaded"})(lf||(lf={}))});var cw,AB,lw,mQ,hQ,Ko,uw,gQ,vQ,dw=T(()=>{"use strict";cw=se(yi());Be();fa();ew();Jo();vr();ga();Y();AB=se(si());sw();(function(e){e.Model="Model",e.Canvas="Canvas",e.CustomPages="CustomPages"})(lw||(lw={}));mQ={Read:wi.Read,Edit:wi.Edit,Both:wi.Both,Container:wi.Container},hQ={input:ha.Input,bound:ha.Bound,output:ha.Output};(function(e){e[e.dataset=0]="dataset",e[e.property=1]="property",e[e.groups=2]="groups",e[e.group=3]="group"})(Ko||(Ko={}));(function(e){e[e.None=0]="None",e[e.HiddenControl=1]="HiddenControl",e[e.CompatibleDataTypesIsMissing=2]="CompatibleDataTypesIsMissing",e[e.TagNameIsUnsupported=3]="TagNameIsUnsupported",e[e.PropertyTypeIsUnsupported=4]="PropertyTypeIsUnsupported",e[e.PropertyTypeGroupIsUnsupported=5]="PropertyTypeGroupIsUnsupported"})(uw||(uw={}));gQ=new Set([R.Currency,R.Decimal,R.FP,R.Multiple,R.SingleLineEmail,R.SingleLinePhone,R.SingleLineText,R.SingleLineTextArea,R.SingleLineURL,R.SingleLineTickerSymbol,R.WholeNone,R.WholeDuration,R.WholeLanguage,R.WholeTimeZone,R.Enum,R.LookupSimple,R.LookupCustomer,R.LookupOwner,R.LookupPartyList,R.LookupRegarding,R.TwoOptions,R.Boolean,R.PowerBIReport,R.DateAndTimeDateAndTime,R.DateAndTimeDateOnly,R.OptionSet,R.MultiSelectOptionSet,R.CardForm]),vQ={numbers:[R.WholeNone,R.FP,R.Decimal,R.Currency],text:[R.SingleLineText,R.SingleLineTextArea,R.Multiple],lookup:[R.LookupSimple,R.LookupCustomer,R.LookupOwner,R.LookupPartyList,R.LookupRegarding],dates:[R.DateAndTimeDateOnly,R.DateAndTimeDateAndTime],allFields:[R.TwoOptions,R.DateAndTimeDateOnly,R.DateAndTimeDateAndTime,R.FP,R.Decimal,R.WholeNone,R.WholeDuration,R.WholeTimeZone,R.WholeLanguage,R.LookupSimple,R.LookupCustomer,R.LookupOwner,R.LookupPartyList,R.LookupRegarding,R.Multiple,R.OptionSet,R.SingleLineText,R.SingleLineTextArea,R.SingleLineEmail,R.SingleLineURL,R.SingleLineTickerSymbol,R.SingleLinePhone]}});var yr,lu,pw=T(()=>{"use strict";yr=se(yi());Ve();Be();ct();fa();ga();dw();Jo();Y();Ye();vr();lu=class extends j{constructor(t){super(b.customControl,t)}customControlId;get id(){let t=this.getProperty(g.id);return _.IsNullOrUndefined(t)?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new L(t.substr(1,t.length-2)):new L(t)}getParameters(){let t=new Map,r=this.getAllChildren();if(r&&r.length!==0&&r[0]){let n=r[0].getAllChildren();if(n!=null){for(let i of n)if(i&&i.getAllChildren().length>0){let a=i.getNodeName();t.get(a)?t.get(a).push(i):t.set(a,[i])}}}return t}getFormComponentValueByParameterName(t){let r=this.getParameters()?.get(wt.value);if(r?.length>0){let n=r[0],i=n?.getAllChildren()?.length>0?n.getAllChildren().find(o=>o.getNodeName()===t):null,a=i?.getAllChildren()?.length>0?i.getAllChildren()[0].getNodeName():"";return this.normalizePropertyValue(a)}}getParameterValue(t){let r=this.getParameterNodeChild(t);return r&&this.normalizePropertyValue(r.getNodeName())}getParameterNodeChild(t){let r=this.getParameters().get(t);return r?.length>0&&r[0].getAllChildren()?.length>0?r[0].getAllChildren()[0]:null}getDatasetName(t){return t.getAllProperties().find(r=>r.key===wt.name)?.value}getParameterChildrenValues(t,r,n){if(this.isDataSet(t)){let i=r.find(u=>u.key===wt.name)?.value,a={Name:i,Type:R.Grid,Columns:[]},l=this.getParameters().get(wt.dataset).find(u=>this.getDatasetName(u)===i).getAllChildren();for(let u of l){let c=u.getNodeName();if(u&&u.getAllChildren().length>0){let d=this.normalizePropertyValue(u.getAllChildren()[0].getNodeName());a[c]=d}}return a}}getParameterIsStatic(t){let r=!1,n=this.getParameters().get(t)[0],i=n&&n.getAllProperties();if(i){for(let a of i)if(a.key===g.static&&a.value==="true"){r=!0;break}}return r}get name(){return this.getProperty(g.Name)}get formFactor(){return this.getProperty(g.formFactor)}set formFactor(t){this.setProperty(g.formFactor,t)}async toJSON(t){if(this.id)return null;let r=await this.parametersToJSON(t),n=parseInt(this.formFactor,10);return{CustomControlId:this.customControlId,FormFactor:isNaN(n)?-1:n,Name:this.name,Version:null,Parameters:r,ShouldOverrideControlVisible:!1}}normalizePropertyValue(t){return t.startsWith(pn.StartTag)&&(t=t.substring(1)),t}async parametersToJSON(t){let r=[];if(!this.name)return r;try{let n=await t.formModelService.customControlDiscoveryService.getCustomControlMetadata(this.name);if(n)if(n.configurations){let i=n.configurations,a=this.getParameters();for(let[o,s]of a)if(this.isDataSet(o))for(let l of a.get(o)){let u=l.getAllProperties(),c=this.getDatasetName(l),d=i.get(c),p=await this.parameterJSON(o,u,d,t);r.push({Name:c,Value:p})}else if(this.isGroups(s))r.push({Name:o,Value:{Type:Fb.GroupDefinition,Value:this.normalizePropertyValue(this.getParameterNodeChild(s[0].NodeName).NodeName)}}),i.get(o).groupSet?.forEach(u=>{u.groupConfigurableProperties.forEach(async c=>{let d=c.name;c.propertyType===Ko.dataset?a.get(wt.dataset)?.some(f=>this.getDatasetName(f)===d)||r.push({Name:d,Value:{Name:d,Columns:[],Type:R.Grid}}):c.propertyType===Ko.property&&(a.has(d)||r.push({Name:d,Value:{Usage:c.usage}}))})});else{let l=s[0].getAllProperties(),u=i.get(o),c=await this.parameterJSON(o,l,u,t);if(c)r.push({Name:o,Value:c});else{(0,yr.trackInfoTrace)(yt,{eventName:`${cn}/parametersToJSON`,eventData:{message:`Configuration metadata for custom control parameter ${o} is not available for custom control : ${this.name}.`}}),r=[];break}}}else(0,yr.trackErrorTrace)(yt,{eventName:`${cn}/parametersToJSON`,eventData:{message:"Custom Control Manifest Property Info not available"}},new Error(`Custom Control Manifest Property Info not available for custom control : ${this.name}.`));else(0,yr.trackErrorTrace)(yt,{eventName:`${cn}/parametersToJSON`,eventData:{message:"Custom Control Manifest not found"}},new Error(`No custom control manifest found for ${this.name}`))}catch(n){(0,yr.trackErrorTrace)(yt,{eventName:`${cn}/parametersToJSON`,eventData:{message:"parameters to json failed"}},n)}return r}async parameterJSON(t,r,n,i){if(this.isDataSet(t)){let a=n,o=r.find(s=>s.key===wt.name)?.value;if(a)return this.getParameterChildrenValues(t,r);{let s=new Error(`No dataset manifest info for ${o}`);(0,yr.trackErrorTrace)(yt,{eventName:`${cn}/parameterJSON`,eventData:{message:"Missing custom control manifest dataset info"}},s)}}else{let a=n,o=r&&r.find(l=>l.key===g.Type),s=a&&!a.ofTypeGroup.every(l=>!qp.includes(l));if(this.isLookupType(o?.value)||this.isLookupType(a?.ofType)||s)if(a){let l=a.usage,u=this.getParameterIsStatic(t),c=a.isPrimary;if(this.name===Wn.FormComponent){let d=this.getFormComponentValueByParameterName(g.bindAttribute),p=await i.formModelService.loadLookupModel(d),f=p.lookupColumn,m=this.getLookupDataTypeFromAttributeMetadata(f);return{Name:t,Type:m,Usage:l,Static:u,Primary:c,EntityName:p.primaryTableName,Value:d,ViewId:this.getFormComponentValueByParameterName(Lb.DefaultViewId),TargetEntityType:f.targets[0],FilterRelationshipName:this.getFormComponentValueByParameterName(g.FilterRelationshipName),AvailableViewIds:this.getFormComponentValueByParameterName(g.AvailableViewIds),DependentAttributeName:this.getFormComponentValueByParameterName(g.DependentAttributeName),DependentAttributeType:this.getFormComponentValueByParameterName(g.DependentAttributeType),AllowFilterOff:k.IsStrictTrue(this.getFormComponentValueByParameterName(g.AllowFilterOff)),DisableQuickFind:k.IsStrictTrue(this.getFormComponentValueByParameterName(g.DisableQuickFind)),EnableViewPicker:!k.IsStrictTrue(this.getFormComponentValueByParameterName(g.DisableViewPicker))}}return{Name:t,Usage:l,Static:u,Primary:c,Value:this.getParameterValue(t)}}else{let l=new Error(`No lookup manifest info for ${t}`);(0,yr.trackErrorTrace)(yt,{eventName:`${cn}/parameterJSON`,eventData:{message:"Missing custom control manifest lookup property info"}},l)}if(a){let l=a.usage,u=this.getParameterIsStatic(t),c=this.getParameterValue(t),d=a.isPrimary;if(o){let f=o.value;return{Type:f,Static:u,Usage:l,Value:this.isNumberTypeProperty(a,f)&&Number(c)?Number(c):c,Primary:d}}if(a.ofType)return{Type:a.ofType,Static:u,Usage:l,Value:c,Primary:!0};if(a.ofTypeGroup)return{Static:u,Usage:l,Value:c,Primary:!0};let p=new Error(`No property type info for ${t}`);(0,yr.trackErrorTrace)(yt,{eventName:`${cn}/parameterJSON`,eventData:{message:"Missing property type info"}},p)}else{let l=new Error(`No property manifest info for ${t}`);(0,yr.trackWarningTrace)(yt,{eventName:`${cn}/parameterJSON`,eventData:{message:"Missing custom control manifest property info"}},l)}}return null}getLookupDataTypeFromAttributeMetadata(t){let{attributeType:r,format:n}=t;switch(r){case B.Customer:return R.LookupCustomer;case B.Owner:return R.LookupOwner;case B.PartyList:return R.LookupPartyList;default:return n===G.Regarding?R.LookupRegarding:R.LookupSimple}}isLookupType(t){return qp.includes(t)}isNumberTypeProperty(t,r){return Vp.includes(r)||t.ofTypeGroup.some(n=>Vp.includes(n))}isDataSet(t){return wt.dataset===t}isGroups(t){return!!t[0].getAllProperties().find(n=>n.key==="isGroup"&&n.value==="true")}}});var W,uf=T(()=>{"use strict";W=class{static get CustomControl(){return"CustomControl"}static get ACIControl(){return"ACIControl"}static get ReferencePanelSearchWidget(){return"ReferencePanelSearchWidget"}static get SearchWidgetControl(){return"SearchWidgetControl"}static get SocialInsightControl(){return"SocialInsightControl"}static get NotesControl(){return"notescontrol"}static get TimerControl(){return"TimerControl"}static get MapsControl(){return"MapsControl"}static get IframeControl(){return"IframeControl"}static get WebResourceHtmlControl(){return"WebResourceHtmlControl"}static get QuickFormCollectionControl(){return"QuickFormCollectionControl"}static get QuickFormControl(){return"QuickFormControl"}static get GridControl(){return"GridControl"}static get SubGridControl(){return"SubGridControl"}static get WebResourceImageControl(){return"WebResourceImageControl"}static get TimeLineControl(){return"TimeLineControl"}static get LeadScoringControl(){return"LeadScoringControl"}}});var U,wa,ze,uu=T(()=>{"use strict";Ve();Vo();Be();ct();Jo();vi();uf();vr();U=class{static get TextBoxControl(){return"4273EDBD-AC1D-40d3-9FB2-095C621B552D"}static get TickerControl(){return"1E1FC551-F7A8-43af-AC34-A8DC35C7B6D4"}static get UrlControl(){return"71716B6C-711E-476c-8AB8-5D11542BFB47"}static get PhoneNumberControl(){return"8C10015A-B339-4982-9474-A95FE05631A5"}static get EmailAddressControl(){return"ADA2203E-B4CD-49be-9DDF-234642B43B52"}static get RadioControl(){return"67FAC785-CD58-4f9f-ABB3-4B7DDC6ED5ED"}static get LookupControl(){return"270BD3DB-D9AF-4782-9025-509E298DEC0A"}static get DateTimeControl(){return"5B773807-9FB2-42db-97C3-7A91EFF8ADFF"}static get IntegerControl(){return"C6D124CA-7EDA-4a60-AEA9-7FB8D318B68F"}static get MoneyControl(){return"533B9E00-756B-4312-95A0-DC888637AC78"}static get FloatControl(){return"0D2C745A-E5A8-4c8f-BA63-C6D3BB604660"}static get DecimalControl(){return"C3EFE0C3-0EC6-42be-8349-CBD9079DFD8E"}static get TextAreaControl(){return"E0DECE4B-6FC8-4a8f-A065-082708572369"}static get PicklistControl(){return"3EF39988-22BB-4f0b-BBBE-64B5A3748AEE"}static get HiddenInputControl(){return"5546E6CD-394C-4BEE-94A8-4425E17EF6C6"}static get GridControl(){return"E7A81278-8635-4D9E-8D4D-59480B391C5B"}static get CheckBoxControl(){return"B0C6723A-8503-4fd7-BB28-C8A06AC933C2"}static get IframeControl(){return"FD2A7985-3187-444e-908D-6624B21F69C0"}static get SocialInsightControl(){return"86B9E25E-695E-4FEF-AC69-F05CFA96739C"}static get OrgInsightsControl(){return"76B9E25E-695E-4FEF-AC69-F05CFA96739C"}static get DurationControl(){return"AA987274-CE4E-4271-A803-66164311A958"}static get RegardingControl(){return"F3015350-44A2-4aa0-97B5-00166532B5E9"}static get PartyListControl(){return"CBFB742C-14E7-4a17-96BB-1A13F7F64AA2"}static get TimeLineControl(){return"06375649-c143-495e-a496-c962e5b4488e"}static get TimeLineControlUC(){return"06375649-C143-495E-A496-C962E5B4488E"}static get TimeZonePicklistControl(){return"7C624A0B-F59E-493d-9583-638D34759266"}static get LanguagePickerControl(){return"671A9387-CA5A-4d1e-8AB7-06E39DDCF6B5"}static get AccessTeamTablePickerControl(){return"3F4E2A56-F102-4B4D-AB9C-F1574CA5BFDA"}static get KBViewerControl(){return"A62B6FA9-169E-406C-B1AA-EAB828CB6026"}static get PicklistStatusControl(){return"5D68B988-0661-4db2-BC3E-17598AD3BE6C"}static get EmailBodyControl(){return"6F3FB987-393B-4d2d-859F-9D0F0349B6AD"}static get PicklistLookupControl(){return"2305E33A-BAD3-4022-9E15-1856CF218333"}static get RelationshipRolePicklistControl(){return"5F986642-5961-4D9F-AB5E-643D71E231E9"}static get RelatedInformationControl(){return"163B90A6-EB64-49D2-9DF8-3C84A4F0A0F8"}static get CoverPagePicklistControl(){return"4168A05C-D857-46AF-8457-5BB47EB04EA1"}static get MailMergeLanguagePickerControl(){return"B634828E-C390-444A-AFE6-E07315D9D970"}static get ConnectionControl(){return"3246F906-1F71-45F7-B11F-D7BE0F9D04C9"}static get ConnectionRoleObjectTypeListControl(){return"821ACF1A-7E46-4A0C-965D-FE14A57D78C7"}static get MapsControl(){return"62B0DF79-0464-470F-8AF7-4483CFEA0C7D"}static get MapLinkControl(){return"91DC0675-C8B9-4421-B1E0-261CEBF02BAC"}static get WebResourceHtmlControl(){return"9FDF5F91-88B1-47F4-AD53-C11EFC01A01D"}static get WebResourceImageControl(){return"587CDF98-C1D5-4BDE-8473-14A0BC7644A7"}static get WebResourceSilverlightControl(){return"080677DB-86EC-4544-AC42-F927E74B491F"}static get ReportControl(){return"A28F441B-916C-4865-87FD-0C5D53BD59C9"}static get ArticleContentControl(){return"F02EF977-2564-4B9A-B2F0-DF083D8A019B"}static get ProcessControl(){return"06E9F7AF-1F54-4681-8EEC-1E21A1CEB465"}static get ActivitiesWallControl(){return"6636847D-B74D-4994-B55A-A6FAF97ECEA2"}static get QuickFormControl(){return"69AF7DCA-2E3B-4EE7-9201-0DA731DD2413"}static get QuickFormCollectionControl(){return"5C5600E0-1D6E-4205-A272-BE80DA87FD42"}static get LinkControl(){return"DFDF1CDE-837B-4AC9-98CF-AC74361FD89D"}static get CompositionLinkControl(){return"DB1284EF-9FFC-4E99-B382-0CC082FE2364"}static get ErrorStatusControl(){return"F4C16ECA-CA81-4E39-9448-834B8378721E"}static get ActivitiesContainerControl(){return"C72511AB-84E5-4FB7-A543-25B4FC01E83E"}static get AccessPrivilegeControl(){return"F93A31B2-99AC-4084-8EC2-D4027C31369A"}static get TimerControl(){return"9C5CA0A1-AB4D-4781-BE7E-8DFBE867B87E"}static get DynamicPropertyListControl(){return"6896F004-B17A-4202-861E-8B7EA2080E0B"}static get ButtonControl(){return"00AD73DA-BD4D-49C6-88A8-2F4F4CAD4A20"}static get SearchWidgetControl(){return"E616A57F-20E0-4534-8662-A101B5DDF4E0"}static get EmailRecipientActivityControl(){return"26E9760F-7454-40DE-BB07-F6DCCCB82040"}static get LabelControl(){return"39354E4A-5015-4D74-8031-EA9EB73A1322"}static get CustomControl(){return"F9A8A302-114E-466A-B582-6771B2AE0D92"}static get EditFilterControl(){return"1479835F-F852-4679-B864-C6892A2844C9"}static get RichEditorControl(){return"F94DB24F-263D-44A7-B38E-A35E9854812B"}static get PowerBIControl(){return"8C54228C-1B25-4909-A12A-F2B968BB0D62"}static get EmailEngagementActionsControl(){return"F454228D-1D25-4319-E12F-D27968BC0234"}static get ACIControl(){return"C8BFBBEF-6851-4401-A0CC-7450062FE085"}static get ChoicesControl(){return"4AA28AB7-9C13-4F57-A73D-AD894D048B5F"}static get ReferencePanelSubgridControl(){return"02D4264B-47E2-4B4C-AA95-F439F3F4D458"}static get ReferencePanelSearchWidget(){return"7CCD1494-1F7A-4E3A-8BDE-F32069DAEB9F"}static get ReferencePanelQuickFormCollectionControl(){return"B68B05F0-A46D-43F8-843B-917920AF806A"}static get SpacerControl(){return"E4BAB03A-A9A5-4C23-CC3B-54AA680150E2"}},wa=class{static get RelationshipAssistant(){return"3ff9a528-dd50-4aca-8f10-2e5ed73513ad"}static get PredictiveLeadScoring(){return"6f503f2a-d033-4106-b62c-f8f2e5f01a57"}},ze=class e{static FieldControlIds=e.initializeFieldControls();static UnboundControlIds=e.initializeUnboundControls();static ControlsAllowedForReferencePanel=e.initializeReferencePanelControls();static ControlsAllowedForFooter=e.initializeFooterControls();static CustomControlIdMap=new bt;static initializeFieldControls(){let t=new bt,r=e.getControlName(B.SingleLineofText,G.Phone);t.add(r,new L(U.PhoneNumberControl));let n=e.getControlName(B.SingleLineofText,G.TextArea);t.add(n,new L(U.TextAreaControl));let i=e.getControlName(B.SingleLineofText,G.Text);t.add(i,new L(U.TextBoxControl));let a=e.getControlName(B.SingleLineofText,G.Email);t.add(a,new L(U.EmailAddressControl));let o=e.getControlName(B.SingleLineofText,G.Url);t.add(o,new L(U.UrlControl));let s=e.getControlName(B.SingleLineofText,G.TickerSymbol);t.add(s,new L(U.TickerControl));let l=e.getControlName(B.SingleLineofText,G.PhoneticGuide);t.add(l,new L(U.TextBoxControl));let u=e.getControlName(B.WholeNumber,G.Duration);t.add(u,new L(U.DurationControl));let c=e.getControlName(B.WholeNumber,G.Language);t.add(c,new L(U.LanguagePickerControl));let d=e.getControlName(B.WholeNumber,G.TimeZone);t.add(d,new L(U.TimeZonePicklistControl));let p=e.getControlName(B.WholeNumber,G.None);t.add(p,new L(U.IntegerControl));let f=e.getControlName(B.DateTime,G.DateOnly);t.add(f,new L(U.DateTimeControl));let m=e.getControlName(B.DateTime,G.DateAndTime);t.add(m,new L(U.DateTimeControl));let h=e.getControlName(B.LookupType,G.None);t.add(h,new L(U.LookupControl));let v=e.getControlName(B.CustomerType,G.None);t.add(v,new L(U.LookupControl));let w=e.getControlName(B.FloatingPointNumber,G.None);t.add(w,new L(U.FloatControl));let C=e.getControlName(B.DecimalNumber,G.None);t.add(C,new L(U.DecimalControl));let E=e.getControlName(B.Currency,G.None);t.add(E,new L(U.MoneyControl));let D=e.getControlName(B.MultipleLineofText,G.None);t.add(D,new L(U.TextAreaControl));let O=e.getControlName(B.MultipleLineofText,G.Text);t.add(O,new L(U.TextAreaControl));let x=e.getControlName(B.MultipleLineofText,G.TextArea);t.add(x,new L(U.TextAreaControl));let F=e.getControlName(B.MultipleLineofText,G.Email);t.add(F,new L(U.EmailBodyControl));let M=e.getControlName(B.OptionSet,G.None);t.add(M,new L(U.PicklistControl));let P=e.getControlName(B.TwoOptions,G.None);t.add(P,new L(U.RadioControl));let q=e.getControlName(B.Image,G.None);t.add(q,new L(U.WebResourceImageControl));let $=e.getControlName(B.Image,G.None);t.add($,new L(U.WebResourceHtmlControl));let qe=e.getControlName(B.TwoOptions,"Radio");t.add(qe,new L(U.RadioControl));let Nt=e.getControlName(B.TwoOptions,"CheckBox");t.add(Nt,new L(U.CheckBoxControl));let ke=e.getControlName(B.TwoOptions,"List");t.add(ke,new L(U.PicklistControl));let He=e.getControlName(B.State,G.None);t.add(He,new L(U.PicklistControl));let X=e.getControlName(B.Status,G.None);t.add(X,new L(U.PicklistStatusControl));let me=e.getControlName(B.OwnerType,G.None);t.add(me,new L(U.LookupControl));let Re=e.getControlName(B.PartyListType,G.None);t.add(Re,new L(U.PartyListControl));let Tn=e.getControlName(B.LookupType,G.Regarding);t.add(Tn,new L(U.RegardingControl));let Jt=e.getControlName(B.MultiSelectOptionSet,G.None);return t.add(Jt,new L(U.ChoicesControl)),t}static getControlName(t,r){return t+"_"+r}static getControlIdByTypeAndFormat(t,r){let n=e.getControlName(t.toString(),r.toString());return e.FieldControlIds.containsKey(n)?e.FieldControlIds.getValue(n):null}static getTypeAndFormatByControlOrUniqueId(t){for(let r in e.FieldControlIds.getKeys())if(e.FieldControlIds.getValue(e.FieldControlIds.getKeys()[r]).guidString.toLowerCase()===t)return e.FieldControlIds.getKeys()[r]}static getControlDataTypeByControlOrUniqueId(t){if(!_.IsNullOrEmptyGuid(t)){let r=e.getTypeAndFormatByControlOrUniqueId(t.guidString.toLowerCase());return r=_.IsNullOrUndefined(r)?e.getUnboundControlNameFromIdentifier(t):r.substring(0,r.indexOf("_")),r}return null}static isCustomControl(t){return _.IsNullOrUndefined(t.control)||_.IsNullOrUndefined(t.control.ClassId)||t.control.ClassId.guidString===U.CustomControl}static initializeUnboundControls(){let t=new bt;return t.add(U.ACIControl,W.ACIControl),t.add(U.IframeControl,W.IframeControl),t.add(U.SearchWidgetControl,W.SearchWidgetControl),t.add(U.MapsControl,W.MapsControl),t.add(U.QuickFormCollectionControl,W.QuickFormCollectionControl),t.add(U.GridControl,W.SubGridControl),t.add(U.WebResourceImageControl,W.WebResourceImageControl),t.add(U.WebResourceHtmlControl,W.WebResourceHtmlControl),t.add(U.ReferencePanelSearchWidget,W.SearchWidgetControl),t.add(U.ReferencePanelQuickFormCollectionControl,W.QuickFormCollectionControl),t.add(U.ReferencePanelSubgridControl,W.SubGridControl),t.add(U.TimerControl,W.TimerControl),t.add(U.TimeLineControl,W.NotesControl),t.add(U.TimeLineControlUC,W.NotesControl),t.add(U.SocialInsightControl,W.SocialInsightControl),t.add(wa.RelationshipAssistant,W.CustomControl),t}static initializeReferencePanelControls(){let t=new bt;return t.add(U.IframeControl,W.IframeControl),t.add(U.ReferencePanelSearchWidget,W.SearchWidgetControl),t.add(U.ReferencePanelQuickFormCollectionControl,W.QuickFormCollectionControl),t.add(U.ReferencePanelSubgridControl,W.SubGridControl),t.add(U.WebResourceHtmlControl,W.WebResourceHtmlControl),t.add(U.WebResourceImageControl,W.WebResourceHtmlControl),t}static initializeFooterControls(){let t=new ma;return t.add(ya.IFRAME,!0),t.add(ya.SPACER,!0),t.add(ya.WEB_RESOURCE_HTML,!0),t}static isUnboundFormControl(t){if(_.IsNullOrUndefined(t)||_.IsNullOrUndefined(t.control)||_.IsNullOrUndefined(t.control.ClassId))return!1;let r=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.containsKey(r.guidString)}static isReferencePanelSection(t){return!_.IsNullOrUndefined(t)&&!_.IsNullOrUndefined(t.Name)&&t.Name.indexOf(Se.referencePanelNamePrefix)===0}static isUnboundFormControlByIdentifier(t){return _.IsNullOrUndefined(t)||_.IsNullOrUndefined(t.guidString)?!1:e.UnboundControlIds.containsKey(t.guidString)}static getUnboundFormControlName(t){let r=k.EmptyString;if(_.IsNullOrUndefined(t)||_.IsNullOrUndefined(t.control)||_.IsNullOrUndefined(t.control.ClassId))return r;let n=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.getValue(n.guidString).toString()}static getUnboundControlNameFromIdentifier(t){return _.IsNullOrUndefined(t)||_.IsNullOrUndefined(t.guidString)?k.EmptyString:e.UnboundControlIds.getValue(t.guidString).toString()}static isSpacerControl(t){return t===U.SpacerControl}static GetRowSpan(t){let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===U.CustomControl&&!_.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}switch(e.UnboundControlIds.getValue(r.guidString)){case W.IframeControl:case W.ACIControl:case W.SocialInsightControl:return 6;case W.SubGridControl:case W.CustomControl:return 4;case W.WebResourceImageControl:return 15;case W.WebResourceHtmlControl:return 15;case W.MapsControl:return 8;case W.SearchWidgetControl:return 10;case W.NotesControl:case W.TimeLineControl:return 15;case W.TimerControl:return 2;default:}}static isLookUpControl(t){return!_.IsNullOrUndefined(t)&&t.ClassId.guidString===U.LookupControl}static isRelationshipAssistantOrLeadScoringControl(t){return!_.IsNullOrUndefined(t)&&e.isRelationshipAssistantOrLeadScoring(t.UniqueId)}static isRelationshipAssistantOrLeadScoring(t){return!_.IsNullOrUndefined(t)&&(t.guidString===wa.RelationshipAssistant||t.guidString===wa.PredictiveLeadScoring)}static isRelationshipAssistantControl(t){return!_.IsNullOrUndefined(t)&&e.isRelationshipAssistant(t.UniqueId)}static isRelationshipAssistant(t){return!_.IsNullOrUndefined(t)&&t.guidString===wa.RelationshipAssistant}static getUniqueIdentifierForControl(t){if(_.IsNullOrUndefined(t))return null;let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===U.CustomControl&&!_.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}return r}}});var cu,fw=T(()=>{"use strict";cu=class{listeners=[];listenersOncer=[];on(t){return this.listeners.push(t),{dispose:()=>this.off(t)}}once(t){this.listenersOncer.push(t)}off(t){let r=this.listeners.indexOf(t);r>-1&&this.listeners.splice(r,1)}emit(t){this.listeners.forEach(r=>r(t)),this.listenersOncer.forEach(r=>r(t)),this.listenersOncer=[]}pipe(t){return this.on(r=>t.emit(r))}}});var Ei,Aa,mw,hw,jn,gw,vw,cf=T(()=>{"use strict";(function(e){e[e.Center=0]="Center",e[e.Left=1]="Left",e[e.Right=2]="Right"})(Ei||(Ei={}));(function(e){e[e.Left=0]="Left",e[e.Top=1]="Top"})(Aa||(Aa={}));(function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle"})(mw||(mw={}));(function(e){e[e.None=0]="None",e[e.Create=1]="Create",e[e.Existing=2]="Existing",e[e.ReadOnly=3]="ReadOnly",e[e.Disabled=4]="Disabled",e[e.BulkEdit=6]="BulkEdit",e[e.Merge=7]="Merge",e[e.Print=8]="Print",e[e.FollowUp=9]="FollowUp"})(hw||(hw={}));(function(e){e[e.None=-1]="None",e[e.AppointmentBook=0]="AppointmentBook",e[e.Hardcoded=1]="Hardcoded",e[e.Main=2]="Main",e[e.MiniCampaignBO=3]="MiniCampaignBO",e[e.Preview=4]="Preview",e[e.Dashboard=5]="Dashboard",e[e.Quick=6]="Quick",e[e.Mobile=7]="Mobile",e[e.Read=8]="Read",e[e.QuickCreate=9]="QuickCreate",e[e.Dialog=10]="Dialog",e[e.Card=11]="Card",e[e.TaskBasedForm=12]="TaskBasedForm",e[e.InteractionCentricDashboard=13]="InteractionCentricDashboard"})(jn||(jn={}));(function(e){e[e.None=0]="None",e[e.SystemRequired=1]="SystemRequired",e[e.ApplicationRequired=2]="ApplicationRequired",e[e.Recommended=3]="Recommended"})(gw||(gw={}));(function(e){e[e.Boolean=0]="Boolean",e[e.Customer=1]="Customer",e[e.DateTime=2]="DateTime",e[e.Decimal=3]="Decimal",e[e.Double=4]="Double",e[e.Integer=5]="Integer",e[e.Lookup=6]="Lookup",e[e.Memo=7]="Memo",e[e.Money=8]="Money",e[e.Owner=9]="Owner",e[e.PartyList=10]="PartyList",e[e.Picklist=11]="Picklist",e[e.State=12]="State",e[e.Status=13]="Status",e[e.String=14]="String",e[e.Uniqueidentifier=15]="Uniqueidentifier",e[e.CalendarRules=16]="CalendarRules",e[e.Virtual=17]="Virtual",e[e.BigInt=18]="BigInt",e[e.ManagedProperty=19]="ManagedProperty",e[e.EntityName=20]="EntityName"})(vw||(vw={}))});var Ca,yw=T(()=>{"use strict";Ho();Ca=Jp({packageName:"cds-designer-models",features:{showAllPCFControls:{owner:"anchoudh",description:"Do not only show the controls that exist on the whitelist",enabledFor:{test:!1,preprod:!1,preview:!1,prod:!1,gov:!1,high:!1,dod:!1,mooncake:!1}},showTestControls:{owner:"lucorre",description:"Show advanced custom controls for testing (designated in Authoring Manifest with isTestOnly=true)",enabledFor:{test:!0,preprod:!1,preview:!1,prod:!1,gov:!1,high:!1,dod:!1,mooncake:!1}},enablePrefetchGetMoreComponentsLocalization:{owner:"vajagarl",description:"Enables prefetching the localization files for controls displayed in custom control picker",enabledFor:{test:!0,preprod:!0,preview:!0,prod:!0,gov:!0,high:!0,dod:!0,mooncake:!0}},showMapControl:{owner:"vayilavarapu",createdDate:"07/19/2022",description:"Show map control",enabledFor:{test:!0,preprod:!0,preview:!0,prod:!0,gov:!0,high:!0,dod:!0,mooncake:!0,ex:!0,rx:!0}},enableFallbackFormTemplate:{owner:"vajagarl",createdDate:"01/03/2023",description:"Enable default form template as fallback if unable to retrieve a form template from Dataverse",enabledFor:{test:!0,preprod:!0,preview:!0,prod:!0,gov:!0,high:!0,dod:!0,mooncake:!0,ex:!0,rx:!0}},enableAutoInsertionOfCellInRow:{owner:"debeshd",createdDate:"09/01/2023",description:"Enable the auto insertion of cell in a row when a section is initialized",enabledFor:{test:!1,preprod:!1,preview:!1,prod:!1,gov:!1,high:!1,dod:!1,mooncake:!1,ex:!1,rx:!1}},enableOneGridEvents:{owner:"aansu",createdDate:"08/21/2024",description:"Enable OneGrid events in form designer",enabledFor:{test:!0,preprod:!0,prod:!0,preview:!0,gov:!0,high:!0,dod:!0,mooncake:!0,ex:!0,rx:!0}},disablePBIComponents:{owner:"adekulkarni",createdDate:"02/13/2025",description:"Disables PBI components and cleans them up from the form",enabledFor:{test:!0,preprod:!1,preview:!1,prod:!1,gov:!1,high:!1,dod:!1,mooncake:!1,ex:!1,rx:!1}},enableAgentResponse:{owner:"jennietu",createdDate:"04/24/2025",description:"Enables agent response in form designer",enabledFor:{test:!0,preprod:!0,preview:!1,prod:!1,gov:!1,high:!1,dod:!1,mooncake:!1,ex:!1,rx:!1}},enableDelayedLocalizationForCustomControls:{owner:"aansu",createdDate:"06/08/2025",description:"Enables delayed localization of custom control",enabledFor:{test:!0,preprod:!0,preview:!0,prod:!0,gov:!0,high:!0,dod:!0,mooncake:!0,ex:!0,rx:!0}}}})});function bw(e){return{...e,extractConfig:t=>CB(t,Object.keys(e.fallback))}}function CB(e,t){let r={};for(let n of t)typeof e[n]<"u"&&(r[n]=e[n]);return r}var df=T(()=>{"use strict";});var pf=y((WQ,Aw)=>{var Qo=new Proxy(function(){return Qo},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Qo},apply:function(){return Qo},construct:function(){return{}}}),ww=function(){return Qo};Object.setPrototypeOf(ww,Qo);Aw.exports=ww});var Sw=y((jQ,Ew)=>{var Xo=new Proxy(function(){return Xo},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Xo},apply:function(){return Xo},construct:function(){return{}}}),Cw=function(){return Xo};Object.setPrototypeOf(Cw,Xo);Ew.exports=Cw});var ff=y((HQ,Dw)=>{var Yo=new Proxy(function(){return Yo},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Yo},apply:function(){return Yo},construct:function(){return{}}}),Nw=function(){return Yo};Object.setPrototypeOf(Nw,Yo);Dw.exports=Nw});var _w=y((JQ,Iw)=>{function EB(){this.__data__=[],this.size=0}Iw.exports=EB});var Ea=y((KQ,Tw)=>{function SB(e,t){return e===t||e!==e&&t!==t}Tw.exports=SB});var Zo=y((QQ,Pw)=>{var NB=Ea();function DB(e,t){for(var r=e.length;r--;)if(NB(e[r][0],t))return r;return-1}Pw.exports=DB});var Ow=y((XQ,Rw)=>{var IB=Zo(),_B=Array.prototype,TB=_B.splice;function PB(e){var t=this.__data__,r=IB(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():TB.call(t,r,1),--this.size,!0}Rw.exports=PB});var Lw=y((YQ,xw)=>{var RB=Zo();function OB(e){var t=this.__data__,r=RB(t,e);return r<0?void 0:t[r][1]}xw.exports=OB});var kw=y((ZQ,Fw)=>{var xB=Zo();function LB(e){return xB(this.__data__,e)>-1}Fw.exports=LB});var Bw=y((eX,Mw)=>{var FB=Zo();function kB(e,t){var r=this.__data__,n=FB(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}Mw.exports=kB});var es=y((tX,Uw)=>{var MB=_w(),BB=Ow(),UB=Lw(),$B=kw(),qB=Bw();function Sa(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}Sa.prototype.clear=MB;Sa.prototype.delete=BB;Sa.prototype.get=UB;Sa.prototype.has=$B;Sa.prototype.set=qB;Uw.exports=Sa});var qw=y((rX,$w)=>{var VB=es();function GB(){this.__data__=new VB,this.size=0}$w.exports=GB});var Gw=y((nX,Vw)=>{function zB(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}Vw.exports=zB});var Ww=y((iX,zw)=>{function WB(e){return this.__data__.get(e)}zw.exports=WB});var Hw=y((aX,jw)=>{function jB(e){return this.__data__.has(e)}jw.exports=jB});var mf=y((oX,Jw)=>{var HB=typeof global=="object"&&global&&global.Object===Object&&global;Jw.exports=HB});var br=y((sX,Kw)=>{var JB=mf(),KB=typeof self=="object"&&self&&self.Object===Object&&self,QB=JB||KB||Function("return this")();Kw.exports=QB});var ts=y((lX,Qw)=>{var XB=br(),YB=XB.Symbol;Qw.exports=YB});var eA=y((uX,Zw)=>{var Xw=ts(),Yw=Object.prototype,ZB=Yw.hasOwnProperty,eU=Yw.toString,rs=Xw?Xw.toStringTag:void 0;function tU(e){var t=ZB.call(e,rs),r=e[rs];try{e[rs]=void 0;var n=!0}catch{}var i=eU.call(e);return n&&(t?e[rs]=r:delete e[rs]),i}Zw.exports=tU});var rA=y((cX,tA)=>{var rU=Object.prototype,nU=rU.toString;function iU(e){return nU.call(e)}tA.exports=iU});var Si=y((dX,aA)=>{var nA=ts(),aU=eA(),oU=rA(),sU="[object Null]",lU="[object Undefined]",iA=nA?nA.toStringTag:void 0;function uU(e){return e==null?e===void 0?lU:sU:iA&&iA in Object(e)?aU(e):oU(e)}aA.exports=uU});var fn=y((pX,oA)=>{function cU(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}oA.exports=cU});var du=y((fX,sA)=>{var dU=Si(),pU=fn(),fU="[object AsyncFunction]",mU="[object Function]",hU="[object GeneratorFunction]",gU="[object Proxy]";function vU(e){if(!pU(e))return!1;var t=dU(e);return t==mU||t==hU||t==fU||t==gU}sA.exports=vU});var uA=y((mX,lA)=>{var yU=br(),bU=yU["__core-js_shared__"];lA.exports=bU});var pA=y((hX,dA)=>{var hf=uA(),cA=(function(){var e=/[^.]+$/.exec(hf&&hf.keys&&hf.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function wU(e){return!!cA&&cA in e}dA.exports=wU});var gf=y((gX,fA)=>{var AU=Function.prototype,CU=AU.toString;function EU(e){if(e!=null){try{return CU.call(e)}catch{}try{return e+""}catch{}}return""}fA.exports=EU});var hA=y((vX,mA)=>{var SU=du(),NU=pA(),DU=fn(),IU=gf(),_U=/[\\^$.*+?()[\]{}|]/g,TU=/^\[object .+?Constructor\]$/,PU=Function.prototype,RU=Object.prototype,OU=PU.toString,xU=RU.hasOwnProperty,LU=RegExp("^"+OU.call(xU).replace(_U,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function FU(e){if(!DU(e)||NU(e))return!1;var t=SU(e)?LU:TU;return t.test(IU(e))}mA.exports=FU});var vA=y((yX,gA)=>{function kU(e,t){return e?.[t]}gA.exports=kU});var Hn=y((bX,yA)=>{var MU=hA(),BU=vA();function UU(e,t){var r=BU(e,t);return MU(r)?r:void 0}yA.exports=UU});var pu=y((wX,bA)=>{var $U=Hn(),qU=br(),VU=$U(qU,"Map");bA.exports=VU});var ns=y((AX,wA)=>{var GU=Hn(),zU=GU(Object,"create");wA.exports=zU});var EA=y((CX,CA)=>{var AA=ns();function WU(){this.__data__=AA?AA(null):{},this.size=0}CA.exports=WU});var NA=y((EX,SA)=>{function jU(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}SA.exports=jU});var IA=y((SX,DA)=>{var HU=ns(),JU="__lodash_hash_undefined__",KU=Object.prototype,QU=KU.hasOwnProperty;function XU(e){var t=this.__data__;if(HU){var r=t[e];return r===JU?void 0:r}return QU.call(t,e)?t[e]:void 0}DA.exports=XU});var TA=y((NX,_A)=>{var YU=ns(),ZU=Object.prototype,e$=ZU.hasOwnProperty;function t$(e){var t=this.__data__;return YU?t[e]!==void 0:e$.call(t,e)}_A.exports=t$});var RA=y((DX,PA)=>{var r$=ns(),n$="__lodash_hash_undefined__";function i$(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=r$&&t===void 0?n$:t,this}PA.exports=i$});var xA=y((IX,OA)=>{var a$=EA(),o$=NA(),s$=IA(),l$=TA(),u$=RA();function Na(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}Na.prototype.clear=a$;Na.prototype.delete=o$;Na.prototype.get=s$;Na.prototype.has=l$;Na.prototype.set=u$;OA.exports=Na});var kA=y((_X,FA)=>{var LA=xA(),c$=es(),d$=pu();function p$(){this.size=0,this.__data__={hash:new LA,map:new(d$||c$),string:new LA}}FA.exports=p$});var BA=y((TX,MA)=>{function f$(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}MA.exports=f$});var is=y((PX,UA)=>{var m$=BA();function h$(e,t){var r=e.__data__;return m$(t)?r[typeof t=="string"?"string":"hash"]:r.map}UA.exports=h$});var qA=y((RX,$A)=>{var g$=is();function v$(e){var t=g$(this,e).delete(e);return this.size-=t?1:0,t}$A.exports=v$});var GA=y((OX,VA)=>{var y$=is();function b$(e){return y$(this,e).get(e)}VA.exports=b$});var WA=y((xX,zA)=>{var w$=is();function A$(e){return w$(this,e).has(e)}zA.exports=A$});var HA=y((LX,jA)=>{var C$=is();function E$(e,t){var r=C$(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}jA.exports=E$});var fu=y((FX,JA)=>{var S$=kA(),N$=qA(),D$=GA(),I$=WA(),_$=HA();function Da(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}Da.prototype.clear=S$;Da.prototype.delete=N$;Da.prototype.get=D$;Da.prototype.has=I$;Da.prototype.set=_$;JA.exports=Da});var QA=y((kX,KA)=>{var T$=es(),P$=pu(),R$=fu(),O$=200;function x$(e,t){var r=this.__data__;if(r instanceof T$){var n=r.__data__;if(!P$||n.length<O$-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new R$(n)}return r.set(e,t),this.size=r.size,this}KA.exports=x$});var vf=y((MX,XA)=>{var L$=es(),F$=qw(),k$=Gw(),M$=Ww(),B$=Hw(),U$=QA();function Ia(e){var t=this.__data__=new L$(e);this.size=t.size}Ia.prototype.clear=F$;Ia.prototype.delete=k$;Ia.prototype.get=M$;Ia.prototype.has=B$;Ia.prototype.set=U$;XA.exports=Ia});var ZA=y((BX,YA)=>{var $$="__lodash_hash_undefined__";function q$(e){return this.__data__.set(e,$$),this}YA.exports=q$});var tC=y((UX,eC)=>{function V$(e){return this.__data__.has(e)}eC.exports=V$});var nC=y(($X,rC)=>{var G$=fu(),z$=ZA(),W$=tC();function mu(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new G$;++t<r;)this.add(e[t])}mu.prototype.add=mu.prototype.push=z$;mu.prototype.has=W$;rC.exports=mu});var aC=y((qX,iC)=>{function j$(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}iC.exports=j$});var sC=y((VX,oC)=>{function H$(e,t){return e.has(t)}oC.exports=H$});var yf=y((GX,lC)=>{var J$=nC(),K$=aC(),Q$=sC(),X$=1,Y$=2;function Z$(e,t,r,n,i,a){var o=r&X$,s=e.length,l=t.length;if(s!=l&&!(o&&l>s))return!1;var u=a.get(e),c=a.get(t);if(u&&c)return u==t&&c==e;var d=-1,p=!0,f=r&Y$?new J$:void 0;for(a.set(e,t),a.set(t,e);++d<s;){var m=e[d],h=t[d];if(n)var v=o?n(h,m,d,t,e,a):n(m,h,d,e,t,a);if(v!==void 0){if(v)continue;p=!1;break}if(f){if(!K$(t,function(w,C){if(!Q$(f,C)&&(m===w||i(m,w,r,n,a)))return f.push(C)})){p=!1;break}}else if(!(m===h||i(m,h,r,n,a))){p=!1;break}}return a.delete(e),a.delete(t),p}lC.exports=Z$});var bf=y((zX,uC)=>{var eq=br(),tq=eq.Uint8Array;uC.exports=tq});var dC=y((WX,cC)=>{function rq(e){var t=-1,r=Array(e.size);return e.forEach(function(n,i){r[++t]=[i,n]}),r}cC.exports=rq});var fC=y((jX,pC)=>{function nq(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n}),r}pC.exports=nq});var yC=y((HX,vC)=>{var mC=ts(),hC=bf(),iq=Ea(),aq=yf(),oq=dC(),sq=fC(),lq=1,uq=2,cq="[object Boolean]",dq="[object Date]",pq="[object Error]",fq="[object Map]",mq="[object Number]",hq="[object RegExp]",gq="[object Set]",vq="[object String]",yq="[object Symbol]",bq="[object ArrayBuffer]",wq="[object DataView]",gC=mC?mC.prototype:void 0,wf=gC?gC.valueOf:void 0;function Aq(e,t,r,n,i,a,o){switch(r){case wq:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case bq:return!(e.byteLength!=t.byteLength||!a(new hC(e),new hC(t)));case cq:case dq:case mq:return iq(+e,+t);case pq:return e.name==t.name&&e.message==t.message;case hq:case vq:return e==t+"";case fq:var s=oq;case gq:var l=n&lq;if(s||(s=sq),e.size!=t.size&&!l)return!1;var u=o.get(e);if(u)return u==t;n|=uq,o.set(e,t);var c=aq(s(e),s(t),n,i,a,o);return o.delete(e),c;case yq:if(wf)return wf.call(e)==wf.call(t)}return!1}vC.exports=Aq});var wC=y((JX,bC)=>{function Cq(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}bC.exports=Cq});var Jn=y((KX,AC)=>{var Eq=Array.isArray;AC.exports=Eq});var EC=y((QX,CC)=>{var Sq=wC(),Nq=Jn();function Dq(e,t,r){var n=t(e);return Nq(e)?n:Sq(n,r(e))}CC.exports=Dq});var NC=y((XX,SC)=>{function Iq(e,t){for(var r=-1,n=e==null?0:e.length,i=0,a=[];++r<n;){var o=e[r];t(o,r,e)&&(a[i++]=o)}return a}SC.exports=Iq});var IC=y((YX,DC)=>{function _q(){return[]}DC.exports=_q});var PC=y((ZX,TC)=>{var Tq=NC(),Pq=IC(),Rq=Object.prototype,Oq=Rq.propertyIsEnumerable,_C=Object.getOwnPropertySymbols,xq=_C?function(e){return e==null?[]:(e=Object(e),Tq(_C(e),function(t){return Oq.call(e,t)}))}:Pq;TC.exports=xq});var OC=y((eY,RC)=>{function Lq(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}RC.exports=Lq});var Kn=y((tY,xC)=>{function Fq(e){return e!=null&&typeof e=="object"}xC.exports=Fq});var FC=y((rY,LC)=>{var kq=Si(),Mq=Kn(),Bq="[object Arguments]";function Uq(e){return Mq(e)&&kq(e)==Bq}LC.exports=Uq});var Af=y((nY,BC)=>{var kC=FC(),$q=Kn(),MC=Object.prototype,qq=MC.hasOwnProperty,Vq=MC.propertyIsEnumerable,Gq=kC((function(){return arguments})())?kC:function(e){return $q(e)&&qq.call(e,"callee")&&!Vq.call(e,"callee")};BC.exports=Gq});var $C=y((iY,UC)=>{function zq(){return!1}UC.exports=zq});var hu=y((as,_a)=>{var Wq=br(),jq=$C(),GC=typeof as=="object"&&as&&!as.nodeType&&as,qC=GC&&typeof _a=="object"&&_a&&!_a.nodeType&&_a,Hq=qC&&qC.exports===GC,VC=Hq?Wq.Buffer:void 0,Jq=VC?VC.isBuffer:void 0,Kq=Jq||jq;_a.exports=Kq});var gu=y((aY,zC)=>{var Qq=9007199254740991,Xq=/^(?:0|[1-9]\d*)$/;function Yq(e,t){var r=typeof e;return t=t??Qq,!!t&&(r=="number"||r!="symbol"&&Xq.test(e))&&e>-1&&e%1==0&&e<t}zC.exports=Yq});var Cf=y((oY,WC)=>{var Zq=9007199254740991;function e3(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=Zq}WC.exports=e3});var HC=y((sY,jC)=>{var t3=Si(),r3=Cf(),n3=Kn(),i3="[object Arguments]",a3="[object Array]",o3="[object Boolean]",s3="[object Date]",l3="[object Error]",u3="[object Function]",c3="[object Map]",d3="[object Number]",p3="[object Object]",f3="[object RegExp]",m3="[object Set]",h3="[object String]",g3="[object WeakMap]",v3="[object ArrayBuffer]",y3="[object DataView]",b3="[object Float32Array]",w3="[object Float64Array]",A3="[object Int8Array]",C3="[object Int16Array]",E3="[object Int32Array]",S3="[object Uint8Array]",N3="[object Uint8ClampedArray]",D3="[object Uint16Array]",I3="[object Uint32Array]",we={};we[b3]=we[w3]=we[A3]=we[C3]=we[E3]=we[S3]=we[N3]=we[D3]=we[I3]=!0;we[i3]=we[a3]=we[v3]=we[o3]=we[y3]=we[s3]=we[l3]=we[u3]=we[c3]=we[d3]=we[p3]=we[f3]=we[m3]=we[h3]=we[g3]=!1;function _3(e){return n3(e)&&r3(e.length)&&!!we[t3(e)]}jC.exports=_3});var KC=y((lY,JC)=>{function T3(e){return function(t){return e(t)}}JC.exports=T3});var XC=y((os,Ta)=>{var P3=mf(),QC=typeof os=="object"&&os&&!os.nodeType&&os,ss=QC&&typeof Ta=="object"&&Ta&&!Ta.nodeType&&Ta,R3=ss&&ss.exports===QC,Ef=R3&&P3.process,O3=(function(){try{var e=ss&&ss.require&&ss.require("util").types;return e||Ef&&Ef.binding&&Ef.binding("util")}catch{}})();Ta.exports=O3});var vu=y((uY,eE)=>{var x3=HC(),L3=KC(),YC=XC(),ZC=YC&&YC.isTypedArray,F3=ZC?L3(ZC):x3;eE.exports=F3});var Sf=y((cY,tE)=>{var k3=OC(),M3=Af(),B3=Jn(),U3=hu(),$3=gu(),q3=vu(),V3=Object.prototype,G3=V3.hasOwnProperty;function z3(e,t){var r=B3(e),n=!r&&M3(e),i=!r&&!n&&U3(e),a=!r&&!n&&!i&&q3(e),o=r||n||i||a,s=o?k3(e.length,String):[],l=s.length;for(var u in e)(t||G3.call(e,u))&&!(o&&(u=="length"||i&&(u=="offset"||u=="parent")||a&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||$3(u,l)))&&s.push(u);return s}tE.exports=z3});var yu=y((dY,rE)=>{var W3=Object.prototype;function j3(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||W3;return e===r}rE.exports=j3});var Nf=y((pY,nE)=>{function H3(e,t){return function(r){return e(t(r))}}nE.exports=H3});var aE=y((fY,iE)=>{var J3=Nf(),K3=J3(Object.keys,Object);iE.exports=K3});var sE=y((mY,oE)=>{var Q3=yu(),X3=aE(),Y3=Object.prototype,Z3=Y3.hasOwnProperty;function e4(e){if(!Q3(e))return X3(e);var t=[];for(var r in Object(e))Z3.call(e,r)&&r!="constructor"&&t.push(r);return t}oE.exports=e4});var ls=y((hY,lE)=>{var t4=du(),r4=Cf();function n4(e){return e!=null&&r4(e.length)&&!t4(e)}lE.exports=n4});var cE=y((gY,uE)=>{var i4=Sf(),a4=sE(),o4=ls();function s4(e){return o4(e)?i4(e):a4(e)}uE.exports=s4});var pE=y((vY,dE)=>{var l4=EC(),u4=PC(),c4=cE();function d4(e){return l4(e,c4,u4)}dE.exports=d4});var hE=y((yY,mE)=>{var fE=pE(),p4=1,f4=Object.prototype,m4=f4.hasOwnProperty;function h4(e,t,r,n,i,a){var o=r&p4,s=fE(e),l=s.length,u=fE(t),c=u.length;if(l!=c&&!o)return!1;for(var d=l;d--;){var p=s[d];if(!(o?p in t:m4.call(t,p)))return!1}var f=a.get(e),m=a.get(t);if(f&&m)return f==t&&m==e;var h=!0;a.set(e,t),a.set(t,e);for(var v=o;++d<l;){p=s[d];var w=e[p],C=t[p];if(n)var E=o?n(C,w,p,t,e,a):n(w,C,p,e,t,a);if(!(E===void 0?w===C||i(w,C,r,n,a):E)){h=!1;break}v||(v=p=="constructor")}if(h&&!v){var D=e.constructor,O=t.constructor;D!=O&&"constructor"in e&&"constructor"in t&&!(typeof D=="function"&&D instanceof D&&typeof O=="function"&&O instanceof O)&&(h=!1)}return a.delete(e),a.delete(t),h}mE.exports=h4});var vE=y((bY,gE)=>{var g4=Hn(),v4=br(),y4=g4(v4,"DataView");gE.exports=y4});var bE=y((wY,yE)=>{var b4=Hn(),w4=br(),A4=b4(w4,"Promise");yE.exports=A4});var AE=y((AY,wE)=>{var C4=Hn(),E4=br(),S4=C4(E4,"Set");wE.exports=S4});var EE=y((CY,CE)=>{var N4=Hn(),D4=br(),I4=N4(D4,"WeakMap");CE.exports=I4});var RE=y((EY,PE)=>{var Df=vE(),If=pu(),_f=bE(),Tf=AE(),Pf=EE(),TE=Si(),Pa=gf(),SE="[object Map]",_4="[object Object]",NE="[object Promise]",DE="[object Set]",IE="[object WeakMap]",_E="[object DataView]",T4=Pa(Df),P4=Pa(If),R4=Pa(_f),O4=Pa(Tf),x4=Pa(Pf),Ni=TE;(Df&&Ni(new Df(new ArrayBuffer(1)))!=_E||If&&Ni(new If)!=SE||_f&&Ni(_f.resolve())!=NE||Tf&&Ni(new Tf)!=DE||Pf&&Ni(new Pf)!=IE)&&(Ni=function(e){var t=TE(e),r=t==_4?e.constructor:void 0,n=r?Pa(r):"";if(n)switch(n){case T4:return _E;case P4:return SE;case R4:return NE;case O4:return DE;case x4:return IE}return t});PE.exports=Ni});var UE=y((SY,BE)=>{var Rf=vf(),L4=yf(),F4=yC(),k4=hE(),OE=RE(),xE=Jn(),LE=hu(),M4=vu(),B4=1,FE="[object Arguments]",kE="[object Array]",bu="[object Object]",U4=Object.prototype,ME=U4.hasOwnProperty;function $4(e,t,r,n,i,a){var o=xE(e),s=xE(t),l=o?kE:OE(e),u=s?kE:OE(t);l=l==FE?bu:l,u=u==FE?bu:u;var c=l==bu,d=u==bu,p=l==u;if(p&&LE(e)){if(!LE(t))return!1;o=!0,c=!1}if(p&&!c)return a||(a=new Rf),o||M4(e)?L4(e,t,r,n,i,a):F4(e,t,l,r,n,i,a);if(!(r&B4)){var f=c&&ME.call(e,"__wrapped__"),m=d&&ME.call(t,"__wrapped__");if(f||m){var h=f?e.value():e,v=m?t.value():t;return a||(a=new Rf),i(h,v,r,n,a)}}return p?(a||(a=new Rf),k4(e,t,r,n,i,a)):!1}BE.exports=$4});var GE=y((NY,VE)=>{var q4=UE(),$E=Kn();function qE(e,t,r,n,i){return e===t?!0:e==null||t==null||!$E(e)&&!$E(t)?e!==e&&t!==t:q4(e,t,r,n,qE,i)}VE.exports=qE});var WE=y((DY,zE)=>{var V4=GE();function G4(e,t){return V4(e,t)}zE.exports=G4});var Of=y((IY,jE)=>{var z4=Hn(),W4=(function(){try{var e=z4(Object,"defineProperty");return e({},"",{}),e}catch{}})();jE.exports=W4});var wu=y((_Y,JE)=>{var HE=Of();function j4(e,t,r){t=="__proto__"&&HE?HE(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}JE.exports=j4});var xf=y((TY,KE)=>{var H4=wu(),J4=Ea();function K4(e,t,r){(r!==void 0&&!J4(e[t],r)||r===void 0&&!(t in e))&&H4(e,t,r)}KE.exports=K4});var XE=y((PY,QE)=>{function Q4(e){return function(t,r,n){for(var i=-1,a=Object(t),o=n(t),s=o.length;s--;){var l=o[e?s:++i];if(r(a[l],l,a)===!1)break}return t}}QE.exports=Q4});var ZE=y((RY,YE)=>{var X4=XE(),Y4=X4();YE.exports=Y4});var iS=y((us,Ra)=>{var Z4=br(),nS=typeof us=="object"&&us&&!us.nodeType&&us,eS=nS&&typeof Ra=="object"&&Ra&&!Ra.nodeType&&Ra,eV=eS&&eS.exports===nS,tS=eV?Z4.Buffer:void 0,rS=tS?tS.allocUnsafe:void 0;function tV(e,t){if(t)return e.slice();var r=e.length,n=rS?rS(r):new e.constructor(r);return e.copy(n),n}Ra.exports=tV});var sS=y((OY,oS)=>{var aS=bf();function rV(e){var t=new e.constructor(e.byteLength);return new aS(t).set(new aS(e)),t}oS.exports=rV});var uS=y((xY,lS)=>{var nV=sS();function iV(e,t){var r=t?nV(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}lS.exports=iV});var dS=y((LY,cS)=>{function aV(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}cS.exports=aV});var mS=y((FY,fS)=>{var oV=fn(),pS=Object.create,sV=(function(){function e(){}return function(t){if(!oV(t))return{};if(pS)return pS(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}})();fS.exports=sV});var Lf=y((kY,hS)=>{var lV=Nf(),uV=lV(Object.getPrototypeOf,Object);hS.exports=uV});var vS=y((MY,gS)=>{var cV=mS(),dV=Lf(),pV=yu();function fV(e){return typeof e.constructor=="function"&&!pV(e)?cV(dV(e)):{}}gS.exports=fV});var bS=y((BY,yS)=>{var mV=ls(),hV=Kn();function gV(e){return hV(e)&&mV(e)}yS.exports=gV});var CS=y((UY,AS)=>{var vV=Si(),yV=Lf(),bV=Kn(),wV="[object Object]",AV=Function.prototype,CV=Object.prototype,wS=AV.toString,EV=CV.hasOwnProperty,SV=wS.call(Object);function NV(e){if(!bV(e)||vV(e)!=wV)return!1;var t=yV(e);if(t===null)return!0;var r=EV.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&wS.call(r)==SV}AS.exports=NV});var Ff=y(($Y,ES)=>{function DV(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}ES.exports=DV});var kf=y((qY,SS)=>{var IV=wu(),_V=Ea(),TV=Object.prototype,PV=TV.hasOwnProperty;function RV(e,t,r){var n=e[t];(!(PV.call(e,t)&&_V(n,r))||r===void 0&&!(t in e))&&IV(e,t,r)}SS.exports=RV});var DS=y((VY,NS)=>{var OV=kf(),xV=wu();function LV(e,t,r,n){var i=!r;r||(r={});for(var a=-1,o=t.length;++a<o;){var s=t[a],l=n?n(r[s],e[s],s,r,e):void 0;l===void 0&&(l=e[s]),i?xV(r,s,l):OV(r,s,l)}return r}NS.exports=LV});var _S=y((GY,IS)=>{function FV(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}IS.exports=FV});var PS=y((zY,TS)=>{var kV=fn(),MV=yu(),BV=_S(),UV=Object.prototype,$V=UV.hasOwnProperty;function qV(e){if(!kV(e))return BV(e);var t=MV(e),r=[];for(var n in e)n=="constructor"&&(t||!$V.call(e,n))||r.push(n);return r}TS.exports=qV});var Mf=y((WY,RS)=>{var VV=Sf(),GV=PS(),zV=ls();function WV(e){return zV(e)?VV(e,!0):GV(e)}RS.exports=WV});var xS=y((jY,OS)=>{var jV=DS(),HV=Mf();function JV(e){return jV(e,HV(e))}OS.exports=JV});var US=y((HY,BS)=>{var LS=xf(),KV=iS(),QV=uS(),XV=dS(),YV=vS(),FS=Af(),kS=Jn(),ZV=bS(),e9=hu(),t9=du(),r9=fn(),n9=CS(),i9=vu(),MS=Ff(),a9=xS();function o9(e,t,r,n,i,a,o){var s=MS(e,r),l=MS(t,r),u=o.get(l);if(u){LS(e,r,u);return}var c=a?a(s,l,r+"",e,t,o):void 0,d=c===void 0;if(d){var p=kS(l),f=!p&&e9(l),m=!p&&!f&&i9(l);c=l,p||f||m?kS(s)?c=s:ZV(s)?c=XV(s):f?(d=!1,c=KV(l,!0)):m?(d=!1,c=QV(l,!0)):c=[]:n9(l)||FS(l)?(c=s,FS(s)?c=a9(s):(!r9(s)||t9(s))&&(c=YV(l))):d=!1}d&&(o.set(l,c),i(c,l,n,a,o),o.delete(l)),LS(e,r,c)}BS.exports=o9});var Bf=y((JY,qS)=>{var s9=vf(),l9=xf(),u9=ZE(),c9=US(),d9=fn(),p9=Mf(),f9=Ff();function $S(e,t,r,n,i){e!==t&&u9(t,function(a,o){if(i||(i=new s9),d9(a))c9(e,t,o,r,$S,n,i);else{var s=n?n(f9(e,o),a,o+"",e,t,i):void 0;s===void 0&&(s=a),l9(e,o,s)}},p9)}qS.exports=$S});var Uf=y((KY,VS)=>{function m9(e){return e}VS.exports=m9});var zS=y((QY,GS)=>{function h9(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}GS.exports=h9});var HS=y((XY,jS)=>{var g9=zS(),WS=Math.max;function v9(e,t,r){return t=WS(t===void 0?e.length-1:t,0),function(){for(var n=arguments,i=-1,a=WS(n.length-t,0),o=Array(a);++i<a;)o[i]=n[t+i];i=-1;for(var s=Array(t+1);++i<t;)s[i]=n[i];return s[t]=r(o),g9(e,this,s)}}jS.exports=v9});var KS=y((YY,JS)=>{function y9(e){return function(){return e}}JS.exports=y9});var YS=y((ZY,XS)=>{var b9=KS(),QS=Of(),w9=Uf(),A9=QS?function(e,t){return QS(e,"toString",{configurable:!0,enumerable:!1,value:b9(t),writable:!0})}:w9;XS.exports=A9});var eN=y((eZ,ZS)=>{var C9=800,E9=16,S9=Date.now;function N9(e){var t=0,r=0;return function(){var n=S9(),i=E9-(n-r);if(r=n,i>0){if(++t>=C9)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}ZS.exports=N9});var rN=y((tZ,tN)=>{var D9=YS(),I9=eN(),_9=I9(D9);tN.exports=_9});var iN=y((rZ,nN)=>{var T9=Uf(),P9=HS(),R9=rN();function O9(e,t){return R9(P9(e,t,T9),e+"")}nN.exports=O9});var oN=y((nZ,aN)=>{var x9=Ea(),L9=ls(),F9=gu(),k9=fn();function M9(e,t,r){if(!k9(r))return!1;var n=typeof t;return(n=="number"?L9(r)&&F9(t,r.length):n=="string"&&t in r)?x9(r[t],e):!1}aN.exports=M9});var $f=y((iZ,sN)=>{var B9=iN(),U9=oN();function $9(e){return B9(function(t,r){var n=-1,i=r.length,a=i>1?r[i-1]:void 0,o=i>2?r[2]:void 0;for(a=e.length>3&&typeof a=="function"?(i--,a):void 0,o&&U9(r[0],r[1],o)&&(a=i<3?void 0:a,i=1),t=Object(t);++n<i;){var s=r[n];s&&e(t,s,n,a)}return t})}sN.exports=$9});var uN=y((aZ,lN)=>{var q9=Bf(),V9=$f(),G9=V9(function(e,t,r,n){q9(e,t,r,n)});lN.exports=G9});var Zt,cs=T(()=>{"use strict";(function(e){e[e.NotLoaded=0]="NotLoaded",e[e.Initialized=1]="Initialized",e[e.ConfigsLoaded=2]="ConfigsLoaded",e[e.Error=3]="Error"})(Zt||(Zt={}))});function dN(e,t,r="PROD"){let n=i=>`ShellSettings_ECS_ClientCache_${e}_${cN.EcsConfigType[i]}_${r}`;return{getData:i=>{let a=t.getItem(n(i));return Promise.resolve(a?JSON.parse(a):void 0)},putData:(i,a)=>(t.setItem(n(i),JSON.stringify(a)),Promise.resolve())}}var cN,z9,pN=T(()=>{"use strict";cN=se(ff()),z9=se(pf());});var qf,fN=T(()=>{"use strict";eu();qf=jo({packageName:"shell-settings",settings:{prodEcsEndpoint:{description:"The url for the PROD ECS endpoint",values:{default:"https://ecs.office.com",dod:"https://config.ecs.dod.teams.microsoft.us",high:"https://config.ecs.gov.teams.microsoft.us",ex:"https://config.ecs.teams.eaglex.ic.gov",rx:"https://config.ecs.teams.microsoft.scloud"}},integrationEcsEndpoint:{description:"The url for the INT ECS endpoint",values:{default:"https://config.edge.skype.net"}}}})});var hN,gN,vN,yN,Vf,W9,Au,mN,Gf=T(()=>{"use strict";hN=se(pf()),gN=se(Sw()),vN=se(ff()),yN=se(WE()),Vf=se(uN());cs();pN();fN();W9=60*1e3,Au=class{clientName;logger;ecsEndpoint;resolveLoadingPromise;loadingPromise=new Promise(t=>this.resolveLoadingPromise=t);_status=Zt.NotLoaded;endpointType;clientConfigOverride;get status(){return this._status}constructor(t,r,n="PROD"){this.clientName=t,this.logger=r,this.endpointType=n,this.ecsEndpoint=n==="PROD"?qf.prodEcsEndpoint:qf.integrationEcsEndpoint}client=new gN.default;init=async({clientVersion:t,getFilters:r,cacheStorage:n=hN.StorageHelper.transientWithGlobalFallback,updateIntervalInMinutes:i,overrideEcsInitParams:a})=>{this.client.telemetryEventAdded.subscribe(this.logger.logEvent),this.client.configUpdated.subscribe(this.handleConfigUpdated);let o=(async()=>{let s=await r();return this.logEvent("FeaturesClient/configRequested",{ecsClientName:this.clientName,filters:s}),s});try{await this.client.initialize({clientName:this.clientName,clientVersion:t??"1.0.0.0",configsToFetch:[vN.EcsConfigType.Default],hosts:[this.ecsEndpoint],initialAppActiveState:!0,getEcsParameters:o,databaseInterface:dN(this.clientName,n,this.endpointType),...a}),this.client.requestUpdate(),this._status===Zt.NotLoaded&&(this._status=Zt.Initialized)}catch(s){this._status=Zt.Error,this.resolveLoadingPromise(),this.logEvent("FeaturesClient/initializationFailed",{ecsClientName:this.clientName,error:s},"Error")}i&&window.setInterval(()=>this.client.requestUpdate(),i*W9)};getConfig=t=>{let r=this.getMergedClientConfigByTeamName(t.teamName),n=r?t.extractConfig(r):{};return(0,Vf.default)({},t.fallback,n,t.override,mN)};getAllConfigs=()=>this.getMergedClientConfig();getAllConfigsByTeamName=t=>this.getMergedClientConfigByTeamName(t);requestConfigUpdate=()=>{this.client.requestUpdate()};subscribe=(t,r)=>{let n=this.getConfig(t),i=this.client.configUpdated.subscribe(()=>{let a=this.getConfig(t);(0,yN.default)(a,n)||(n={...a},r(a))});return{unsubscribe:()=>i.unsubscribe()}};waitUntilLoaded=async t=>{if(t!==void 0){let r,n=new Promise((i,a)=>{r=window.setTimeout(()=>{a(new Error("Timed out waiting for configuration to load"))},t)});await Promise.race([this.loadingPromise,n]),clearTimeout(r)}else await this.loadingPromise};overrideClientConfig(t){this.logger.logEvent("FeaturesClient/overrideClientConfig",{clientConfigOverride:t}),this.clientConfigOverride=t}undoClientConfigOverride(){this.clientConfigOverride=void 0,this.logger.logEvent("FeaturesClient/undoClientConfigOverride")}getMergedClientConfig=()=>(0,Vf.default)({},this.client.getConfig()?.config,this.clientConfigOverride,mN);getMergedClientConfigByTeamName=t=>this.getMergedClientConfig()?.[t];handleConfigUpdated=()=>{let t=this.client.getConfig();if(t===void 0)return;this.resolveLoadingPromise(),this._status=Zt.ConfigsLoaded;let{ConfigIDs:r,Headers:n}=t.config;this.logEvent("FeaturesClient/configUpdated",{ecsClientName:this.clientName,configIDs:r,ETag:n?.ETag})};logEvent=(t,r)=>{this.logger.logEvent(t,{ecsClientName:this.clientName,ecsEndpointType:this.endpointType,...r})}},mN=(e,t)=>{if(Array.isArray(t))return t}});var wN=y((mZ,bN)=>{"use strict";var j9=()=>{let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e};bN.exports=j9});var zf=y((hZ,CN)=>{var ds=new Proxy(function(){return ds},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:ds},apply:function(){return ds},construct:function(){return{}}}),AN=function(){return ds};Object.setPrototypeOf(AN,ds);CN.exports=AN});var NN=y((gZ,SN)=>{var ps=new Proxy(function(){return ps},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:ps},apply:function(){return ps},construct:function(){return{}}}),EN=function(){return ps};Object.setPrototypeOf(EN,ps);SN.exports=EN});var ON=y((vZ,RN)=>{"use strict";var Wf=NN(),H9={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},J9={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},K9={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},TN={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},jf={};jf[Wf.ForwardRef]=K9;jf[Wf.Memo]=TN;function DN(e){return Wf.isMemo(e)?TN:jf[e.$$typeof]||H9}var Q9=Object.defineProperty,X9=Object.getOwnPropertyNames,IN=Object.getOwnPropertySymbols,Y9=Object.getOwnPropertyDescriptor,Z9=Object.getPrototypeOf,_N=Object.prototype;function PN(e,t,r){if(typeof t!="string"){if(_N){var n=Z9(t);n&&n!==_N&&PN(e,n,r)}var i=X9(t);IN&&(i=i.concat(IN(t)));for(var a=DN(e),o=DN(t),s=0;s<i.length;++s){var l=i[s];if(!J9[l]&&!(r&&r[l])&&!(o&&o[l])&&!(a&&a[l])){var u=Y9(t,l);try{Q9(e,l,u)}catch{}}}}return e}RN.exports=PN});function LN(e,t,r){let[n,i]=(0,Oa.useState)(e.getConfig(t));return(0,Oa.useEffect)(()=>{if(!r?.subscribe&&e.status===Zt.ConfigsLoaded)return;let a=e.subscribe(t,o=>{i(o),r?.subscribe||a.unsubscribe()});return a?.unsubscribe},[]),n}function FN(e){return function(t,r){return LN(e,t,r)}}function kN(e,t,r,n){let i=a=>{let o=LN(e,t,n),s={...a,...o};return Oa.default.createElement(r,{...s})};return(0,xN.default)(i,r),i.displayName=`WithFeature(${r.name})`,i}function MN(e,t,r,n){return t.reduce((i,a)=>kN(e,a,i,n),r)}function BN(e){return function(t,r,n){return kN(e,t,r,n)}}var xN,Oa,Hf=T(()=>{"use strict";xN=se(ON()),Oa=se(zf());cs();});var $N=y((wZ,UN)=>{var e5=Bf(),t5=$f(),r5=t5(function(e,t,r){e5(e,t,r)});UN.exports=r5});var Cu=y((AZ,qN)=>{var n5=Si(),i5=Kn(),a5="[object Symbol]";function o5(e){return typeof e=="symbol"||i5(e)&&n5(e)==a5}qN.exports=o5});var GN=y((CZ,VN)=>{var s5=Jn(),l5=Cu(),u5=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,c5=/^\w*$/;function d5(e,t){if(s5(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||l5(e)?!0:c5.test(e)||!u5.test(e)||t!=null&&e in Object(t)}VN.exports=d5});var jN=y((EZ,WN)=>{var zN=fu(),p5="Expected a function";function Jf(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(p5);var r=function(){var n=arguments,i=t?t.apply(this,n):n[0],a=r.cache;if(a.has(i))return a.get(i);var o=e.apply(this,n);return r.cache=a.set(i,o)||a,o};return r.cache=new(Jf.Cache||zN),r}Jf.Cache=zN;WN.exports=Jf});var JN=y((SZ,HN)=>{var f5=jN(),m5=500;function h5(e){var t=f5(e,function(n){return r.size===m5&&r.clear(),n}),r=t.cache;return t}HN.exports=h5});var QN=y((NZ,KN)=>{var g5=JN(),v5=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,y5=/\\(\\)?/g,b5=g5(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(v5,function(r,n,i,a){t.push(i?a.replace(y5,"$1"):n||r)}),t});KN.exports=b5});var YN=y((DZ,XN)=>{function w5(e,t){for(var r=-1,n=e==null?0:e.length,i=Array(n);++r<n;)i[r]=t(e[r],r,e);return i}XN.exports=w5});var iD=y((IZ,nD)=>{var ZN=ts(),A5=YN(),C5=Jn(),E5=Cu(),S5=1/0,eD=ZN?ZN.prototype:void 0,tD=eD?eD.toString:void 0;function rD(e){if(typeof e=="string")return e;if(C5(e))return A5(e,rD)+"";if(E5(e))return tD?tD.call(e):"";var t=e+"";return t=="0"&&1/e==-S5?"-0":t}nD.exports=rD});var oD=y((_Z,aD)=>{var N5=iD();function D5(e){return e==null?"":N5(e)}aD.exports=D5});var lD=y((TZ,sD)=>{var I5=Jn(),_5=GN(),T5=QN(),P5=oD();function R5(e,t){return I5(e)?e:_5(e,t)?[e]:T5(P5(e))}sD.exports=R5});var cD=y((PZ,uD)=>{var O5=Cu(),x5=1/0;function L5(e){if(typeof e=="string"||O5(e))return e;var t=e+"";return t=="0"&&1/e==-x5?"-0":t}uD.exports=L5});var fD=y((RZ,pD)=>{var F5=kf(),k5=lD(),M5=gu(),dD=fn(),B5=cD();function U5(e,t,r,n){if(!dD(e))return e;t=k5(t,e);for(var i=-1,a=t.length,o=a-1,s=e;s!=null&&++i<a;){var l=B5(t[i]),u=r;if(l==="__proto__"||l==="constructor"||l==="prototype")return e;if(i!=o){var c=s[l];u=n?n(c,l,s):void 0,u===void 0&&(u=dD(c)?c:M5(t[i+1])?[]:{})}F5(s,l,u),s=s[l]}return e}pD.exports=U5});var hD=y((OZ,mD)=>{var $5=fD();function q5(e,t,r){return e==null?e:$5(e,t,r)}mD.exports=q5});function bD(e){let{query:t}=(0,yD.default)(window.location.href,!0);return G5(e,t),e}function G5(e,t){let r=V5+e.clientName,n=Object.keys(t).filter(a=>a.startsWith(r));if(!n)return;let i={};n.forEach(a=>{let o=t[a];if(o)try{let s=JSON.parse(o),l=r+wD,u={};if(a===r)u=s;else if(a.startsWith(l)){let c=a.substring(l.length);(0,vD.default)(u,c,s)}(0,gD.default)(i,u)}catch{}}),Object.keys(i).length>0&&e.overrideClientConfig(i)}var gD,vD,yD,wD,V5,AD=T(()=>{"use strict";gD=se($N()),vD=se(hD()),yD=se(Yp());wD=".",V5="ecs"+wD});function Su(e,t,r){let n=bD(new Au(e,t,r));function i(a){(0,Eu.useEffect)(()=>{n.init(a)},[])}return{featuresClient:n,createFeature:W5(n),useFeaturesClientInitParams:i,withFeatures:(a,o,s)=>MN(n,a,o,s)}}function W5(e){let t=FN(e),r=BN(e);return function(i){let a=bw(i);return a.getConfig=()=>e.getConfig(a),a.isLoaded=()=>e.status===Zt.ConfigsLoaded,tf.register(a,e.clientName),{useFeature:o=>t(a,o),withFeature:(o,s)=>r(a,o,s),feature:a}}}var z5,Eu,Kf=T(()=>{"use strict";z5=se(wN()),Eu=se(zf());df();Gf();cs();Hf();AD();rf();});var CD=T(()=>{"use strict";df();Gf();Kf();cs();Hf();iu();nf();});function Nu(e){return{logEvent:(t,r,n)=>{switch(n){case"Error":(0,xa.trackErrorTrace)(e,{eventName:t,eventData:r});break;case"Warning":(0,xa.trackWarningTrace)(e,{eventName:t,eventData:r});break;default:(0,xa.trackInfoTrace)(e,{eventName:t,eventData:r});break}}}}var xa,Qf=T(()=>{"use strict";xa=se(yi());});var YZ,ZZ,eee,ED=T(()=>{"use strict";CD();Qf();({featuresClient:YZ,createFeature:ZZ,useFeaturesClientInitParams:eee}=Su("PowerApps-Shell-Test",Nu("shell-features")))});var DD=y((ree,ND)=>{var fs=new Proxy(function(){return fs},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:fs},apply:function(){return fs},construct:function(){return{}}}),SD=function(){return fs};Object.setPrototypeOf(SD,fs);ND.exports=SD});var j5,H5,ID=T(()=>{"use strict";Go();j5=se(DD()),H5=se(yi());});var _D=T(()=>{"use strict";ED();Qf();ID();});var dee,La,pee,TD=T(()=>{"use strict";_D();Kf();({featuresClient:dee,createFeature:La,useFeaturesClientInitParams:pee}=Su("PowerApps-MakerPortal",Nu("powerapps-features")))});var PD,RD,gee,vee,yee,bee,Xf=T(()=>{"use strict";yw();TD();({feature:PD}=La({teamName:"MakerPortal",owners:["debeshd"],description:"Enable the auto insertion of cell in a row when a section is initialized",createdOn:"09/01/2023",fallback:{enableAutoInsertionOfCellInRow:Ca.enableAutoInsertionOfCellInRow}})),{feature:RD}=La({teamName:"MakerPortal",owners:["aansu"],description:"Enable the one grid events for form designer",createdOn:"08/21/2024",fallback:{enableOneGridEventsForFormDesigner:Ca.enableOneGridEvents}}),{feature:gee}=La({teamName:"MakerPortal",owners:["adekulkarni"],description:"Disables PBI components and cleans them up from the form",createdOn:"01/03/2023",fallback:{enableFallbackFormTemplate:Ca.disablePBIComponents}}),{feature:vee}=La({teamName:"MakerPortal",owners:["jennietu"],description:"Enables agent response in form designer. This feature is used to enable the agent response in form designer",createdOn:"04/24/2025",fallback:{enableAgentResponse:Ca.enableAgentResponse}}),{feature:yee,useFeature:bee}=La({teamName:"MakerPortal",owners:["aansu"],description:"Enables delayed localization of custom control",createdOn:"06/08/2025",fallback:{enableDelayedLocalizationForCustomControls:Ca.enableDelayedLocalizationForCustomControls}})});var LD=y((Aee,xD)=>{var ms=new Proxy(function(){return ms},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:ms},apply:function(){return ms},construct:function(){return{}}}),OD=function(){return ms};Object.setPrototypeOf(OD,ms);xD.exports=OD});var dt,Qn=T(()=>{"use strict";Ve();Be();ct();uu();Y();Ye();dt=class extends j{static HighestUsedIndexByClass=new Map;get colspan(){let t=this.getProperty(g.colspan);return _.IsNullOrUndefined(t)?null:parseInt(t,10)}set colspan(t){_.IsNullOrUndefined(t)||this.setProperty(g.colspan,String(t))}constructor(t,r){super(t,r)}get id(){let t=this.getProperty(g.id);return t==null?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new L(t.substr(1,t.length-2)):new L(t)}set id(t){this.setProperty(g.id,`{${t.ToString()}}`)}set labelId(t){this.setProperty(g.labelId,`{${t.ToString()}}`)}get labelId(){let t=this.getProperty(g.labelId);return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new L(t.substr(1,t.length-2)):new L(t)}get Name(){return this.getProperty(g.Name)}set Name(t){this.setProperty(g.Name,t)}setDisplayName(t,r){for(let i of this.getAllLabels())if(+i.getProperty(g.languagecode)===r){i.setProperty(g.description,t);return}let n=new j(b.formLabel,null);n.setProperty(g.description,t),n.setProperty(g.languagecode,String(r)),this.addGrandChild("labels",n)}getDisplayName(t){for(let r of this.getAllLabels())if(+r.getProperty(g.languagecode)===t)return r.getProperty(g.description)}getAllLabels(){let t=this.getChildren("labels");return t.length!==1?[]:t[0].getChildren("label")}get isLocked(){return+this.getProperty(g.locklevel)==1}set isLocked(t){!this.IsUnboundControl&&this.setProperty(g.locklevel,t?"1":"0")}get availableforphone(){return this.getProcessedValue(g.availableforphone)}set availableforphone(t){_.IsNullOrUndefined(t)||!this.IsAllowedUBCForAvailableOnPhone()||this.setProperty(g.availableforphone,String(t))}get visible(){return this.getProcessedValue(g.visible)}set visible(t){_.IsNullOrUndefined(t)||!this.IsAllowedUBCForVisibleByDefault()||this.setProperty(g.visible,String(t))}isLockLevelSettable(){return!this.IsUnboundControl}get showlabel(){return this.getProcessedValue(g.showlabel)}set showlabel(t){_.IsNullOrUndefined(t)||this.setProperty(g.showlabel,String(t))}isAvailableForPhoneSettable(){return this.IsAllowedUBCForAvailableOnPhone()}isVisibleSettable(){return this.IsAllowedUBCForVisibleByDefault()}getProcessedValue(t){let r=this.getProperty(t);return _.IsNullOrUndefined(r)||this.getProperty(t)==="true"}get readonly(){let t=this.getFirstChild(b.formControl);return t?t.disabled:!1}set readonly(t){let r=this.getFirstChild(b.formControl);r&&(r.disabled=t)}get allowfilteroff(){let t=this.getFirstChild(b.formControl);if(t)return t.getParam(g.AllowFilterOff)==="true"}set allowfilteroff(t){let r=this.getFirstChild(b.formControl);r&&!this.IsUnboundControl&&r.setParameter(g.AllowFilterOff,t)}get autoresolve(){let t=this.getFirstChild(b.formControl);if(t)return t.getParam(g.AutoResolve)==="true"}set autoresolve(t){let r=this.getFirstChild(b.formControl);r&&!this.IsUnboundControl&&r.setParameter(g.AutoResolve,t)}get defaultviewid(){let t=this.getFirstChild(b.formControl);return t?t.getParam(g.DefaultViewId):k.EmptyString}set defaultviewid(t){let r=this.getFirstChild(b.formControl);r&&!this.IsUnboundControl&&r.setParameter(g.DefaultViewId,t)}get dependentattributename(){let t=this.getFirstChild(b.formControl);return t?t.getParam(g.DependentAttributeName):k.EmptyString}set dependentattributename(t){let r=this.getFirstChild(b.formControl);r&&!this.IsUnboundControl&&r.setParameter(g.DependentAttributeName,t)}get dependentattributetype(){let t=this.getFirstChild(b.formControl);return t?t.getParam(g.DependentAttributeType):k.EmptyString}set dependentattributetype(t){let r=this.getFirstChild(b.formControl);r&&!this.IsUnboundControl&&r.setParameter(g.DependentAttributeType,t)}get disablequickfind(){let t=this.getFirstChild(b.formControl);if(t)return t.getParam(g.DisableQuickFind)==="true"}set disablequickfind(t){let r=this.getFirstChild(b.formControl);r&&!this.IsUnboundControl&&r.setParameter(g.DisableQuickFind,t)}get disableviewpicker(){let t=this.getFirstChild(b.formControl);if(t)return t.getParam(g.DisableViewPicker)==="true"}set disableviewpicker(t){let r=this.getFirstChild(b.formControl);r&&!this.IsUnboundControl&&r.setParameter(g.DisableViewPicker,t)}get filterrelationshipname(){let t=this.getFirstChild(b.formControl);return t?t.getParam(g.FilterRelationshipName):k.EmptyString}set filterrelationshipname(t){let r=this.getFirstChild(b.formControl);r&&!this.IsUnboundControl&&r.setParameter(g.FilterRelationshipName,t)}get availableviewids(){let t=this.getFirstChild(b.formControl);return t?t.getParam(g.AvailableViewIds):k.EmptyString}set availableviewids(t){let r=this.getFirstChild(b.formControl);r&&!this.IsUnboundControl&&r.setParameter(g.AvailableViewIds,t)}get IsUnboundControl(){let t=this.getFirstChild(b.formControl);if(t&&t.ClassId){let r=ze.getUniqueIdentifierForControl(t);return!_.IsNullOrUndefined(r)&&ze.isUnboundFormControlByIdentifier(r)}else return!1}IsAllowedUBCForAvailableOnPhone(){let t=this.getFirstChild(b.formControl);if(t){let n=ze.getUniqueIdentifierForControl(t).guidString,i=n===U.GridControl||n===U.TimeLineControl||n===U.TimeLineControlUC;return this.IsUnboundControl?i:!0}return this.NodeName===b.formSection||this.NodeName===b.formTab}IsAllowedUBCForVisibleByDefault(){let t=this.getFirstChild(b.formControl);if(t){let n=ze.getUniqueIdentifierForControl(t).guidString,i=n===U.MapsControl||n===U.WebResourceHtmlControl||n===U.WebResourceImageControl||n===U.IframeControl||n===U.SocialInsightControl;return this.IsUnboundControl?i:!0}else return!0}get events(){let t=this.getChildren(b.formEvents);return t.length===1?t[0].getAllChildren():[]}addEvent(t){this.addGrandChild(b.formEvents,t)}getUsedNodeNameSet(t){return null}getHighestIndexById(t,r){return null}}});var Fa,Yf=T(()=>{"use strict";ct();Y();Ye();Fa=class extends j{constructor(t,r){super(b.dependency,t),k.IsNullOrEmpty(r)||this.setDefaultProperties(r)}set id(t){this.setProperty(g.id,t)}get id(){return this.getProperty(g.id)}setDefaultProperties(t){this.id=t}}});var FD,ka,Zf=T(()=>{"use strict";Be();Yf();Y();Ye();Qn();(function(e){e[e.Form=0]="Form",e[e.Cell=1]="Cell",e[e.Tab=2]="Tab",e[e.Control=3]="Control"})(FD||(FD={}));ka=class extends dt{constructor(t,r){super(b.formEvent,t),r&&(this.eventName=r,this.application="false",this.active="false")}set eventName(t){this.setProperty(g.Name,t)}get eventName(){return this.getProperty(g.Name)}set application(t){this.setProperty(g.application,t)}get application(){return this.getProperty(g.application)}set attribute(t){this.setProperty(g.EventAttribute,t)}get attribute(){return this.getProperty(g.EventAttribute)}set relationship(t){this.setProperty(g.Relationship,t)}get relationship(){return this.getProperty(g.Relationship)}set control(t){this.setProperty(g.Control,t)}get control(){return this.getProperty(g.Control)}set active(t){this.setProperty(g.EventActive,t)}get active(){return this.getProperty(g.EventActive)}getAllHandlers(){let t=this.getChildren(b.EventHandlers);return t&&t.length?t[0].getChildren(b.handler):[]}getAllDependencies(){let t=this.getChildren(b.formDependencies);return t.length===0?[]:t[0].getAllChildren()}setDependencies(t){let r=this.getFirstChild(b.formDependencies);if(_.IsNullOrUndefined(r)){if(t.length===0)return;this.addChild(new j(b.formDependencies,this)),r=this.getFirstChild(b.formDependencies)}if(t.length===0)r.getParentNode().deleteChild(r);else{r.deleteAllChildren();for(let n of t)r.addChild(new Fa(r,n.toString()))}}}});var wr,hs=T(()=>{"use strict";Ve();Vo();Be();vi();Y();Ye();vr();wr=class extends j{previewVersion;constructor(t){super(b.formControl,t)}updatePreview(){this.previewVersion=Date.now()}get ClassId(){let t=this.getProperty(g.classid);return t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new L(t)}set ClassId(t){this.setProperty(g.classid,`{${t.ToString()}}`)}get dataFieldName(){return this.getProperty(g.datafieldname)}set dataFieldName(t){this.setProperty(g.datafieldname,t)}set id(t){this.setProperty(g.id,t)}get id(){return this.getProperty(g.id)}get UniqueId(){let t=this.getProperty(g.uniqueid);return _.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new L(t))}set UniqueId(t){this.setProperty(g.uniqueid,`{${t.ToString()}}`)}get isRequired(){return this.getProperty(g.isRequired)==="true"}set isRequired(t){_.IsNullOrUndefined(t)||this.setProperty(g.isRequired,String(t))}get disableMru(){return this.getParam(g.DisableMru)==="true"}set disableMru(t){_.IsNullOrUndefined(t)||this.setParameter(g.DisableMru,t)}get useMFDForCreate(){return this.getParam(g.UseMFDForCreate)==="true"}set useMFDForCreate(t){_.IsNullOrUndefined(t)||this.setParameter(g.UseMFDForCreate,t)}get useMFDForEdit(){return this.getParam(g.UseMFDForEdit)==="true"}set useMFDForEdit(t){_.IsNullOrUndefined(t)||this.setParameter(g.UseMFDForEdit,t)}get disabled(){return this.getProperty(g.disabled)==="true"}set disabled(t){_.IsNullOrUndefined(t)||this.setProperty(g.disabled,String(t))}get indicationOfSubgrid(){return this.getProperty(g.indicationOfSubgrid)==="true"}set indicationOfSubgrid(t){this.setProperty(g.indicationOfSubgrid,String(t))}getAllParameters(){let t=new bt,r=this.getFirstChild(g.parameters);return r&&r.getAllChildren().forEach(n=>{if(n){let i=n.getAllChildren(),a=i&&i.length>0&&i[0];a&&t.add(n.getNodeName(),a.getNodeName())}}),t}setParameter(t,r){let n=!1;r===null&&(n=!0);let i=(pn.StartTag+r).toString(),a=this.parametersNode;if(a){let o=a.findFirst(s=>s&&s.getNodeName()===t);if(o)if(n){this.deleteFirstGrandChildOfName(b.controlParameters,o);return}else{let s=o.getAllChildren();s&&s.length>0&&s[0]?s[0].setNodeName(i):o.addChild(new j(i,o))}else n||(o=new j(t,a),o.addChild(new j(i,o)),a.addChild(o))}else if(!n){a=new j("parameters",this);let o=new j(t,a);o.addChild(new j(i,o)),a.addChild(o),this.addChild(a)}}getParam(t){if(this.parametersNode){let r=this.parametersNode.findFirst(n=>n&&n.getNodeName()===t);if(r){let n=r.getAllChildren(),i=n&&n.length>0&&n[0];if(i){let a=i.getNodeName();return a.charAt(0)===pn.StartTag?a.substring(1):a}}}return null}get parametersNode(){let t=this.getChildren(g.parameters);return t.length===0?null:t[0]}async serializeParameters(t,r){let n=new bt;switch(this.ClassId.guidString.toUpperCase()){case I.LookupControl:if(t&&t.getKeys())if(t.getKeys().forEach(o=>{n.add(o,this.getParam(o))}),t&&t.containsKey("DefaultViewId")){let o=this.getParam("DefaultViewId").replace("{","").replace("}","");n.upsert("DefaultViewId",o)}else{let o=this.getParent(),s=await r.formModelService.lookupControlService.populateDefaultView(this,o.getParentForm().entityName);s&&s.id&&n.upsert("DefaultViewId",s.id.replace("{","").replace("}",""))}break;default:t&&t.getKeys()&&t.getKeys().forEach(o=>{n.add(o,this.getParam(o))});break}let i=n.getInternalObject(),a=[];for(let o in i)i.hasOwnProperty(o)&&a.push({Name:o,Value:i[o]});return a}getIsUnbound(){return this.getProperty(g.isUnbound)==="true"}getAttributeTypeFromClassId(t){if(t)switch(t.toUpperCase()){case I.BooleanControl:case I.CheckboxControl:return 0;case I.DateTimeControl:return 2;case I.DecimalControl:return 3;case I.FloatingNumberControl:return 4;case I.IntegerControl:case I.DurationControl:case I.LanguageControl:case I.TimezoneControl:return 5;case I.LookupControl:return 6;case I.CurrencyControl:return 8;case I.PartyListControl:return 10;case I.ChoiceControl:case I.RelationshipRoleChoiceControl:return 11;case I.ChoiceStatusControl:return 13;case I.TextAreaControl:case I.TextboxControl:case I.LabelControl:case I.EmailAddressControl:case I.UrlControl:case I.TickerControl:case I.ButtonControl:case I.PhoneNumberControl:return 14;case I.ChoicesControl:return 24;default:return}return 14}async toJSON(t){let r=this.getParent(),n=t&&t.formModelService&&t.formModelService.getFormType()===Ge.QuickViewForm?!0:this.disabled,i=await this.serializeParameters(this.getAllParameters(),t);return{ClassId:this.ClassId&&this.ClassId.guidString,Parameters:i,Disabled:n,ControlLayout:0,RequiredLevel:0,Type:this.getAttributeTypeFromClassId(this.ClassId.guidString),IsUnbound:this.getIsUnbound(),IsRequired:this.isRequired,DataFieldName:this.dataFieldName,UniqueId:this.UniqueId&&this.UniqueId.guidString,Id:this.previewVersion?this.id+this.previewVersion:this.id,Label:r.getDisplayName(t.langCode),LabelId:r.labelId&&r.labelId.guidString,Name:null,ShowLabel:r.showlabel,PreviewId:r&&r.id.guidString,Visible:r.visible||t.formModelService.showHiddenElements}}}});var Ma,em=T(()=>{"use strict";ct();ga();hs();Y();Ye();Ma=class extends wr{constructor(t){super(t)}get targetEntityType(){return this.getParam(g.targetEntityType)||k.EmptyString}set targetEntityType(t){this.setParameter(g.targetEntityType,t)}get viewId(){return k.StripBraces(this.getParam(g.viewId))||k.EmptyString}set viewId(t){this.setParameter(g.viewId,k.AddBraces(t))}get viewIds(){return this.getParam(g.viewIds)||k.EmptyString}set viewIds(t){this.setParameter(g.viewIds,t)}get relationshipName(){return this.getParam(g.RelationshipName)||k.EmptyString}set relationshipName(t){this.setParameter(g.RelationshipName,t)}get isUserView(){return k.IsStrictTrue(this.getParam(g.isUserView))}set isUserView(t){this.setParameter(g.isUserView,t.toString())}get enableViewPicker(){return k.IsStrictTrue(this.getParam(g.enableViewPicker))}set enableViewPicker(t){this.setParameter(g.enableViewPicker,t)}get autoExpand(){return this.getParent().autoexpand&&this.getParam(g.autoExpand)===g.Auto}set autoExpand(t){let r=this.getParent();this.setParameter(g.autoExpand,t?g.Auto:g.Fixed),r.autoexpand=t}get recordsPerPage(){return this.getParam(g.recordsPerPage)?Number(this.getParam(g.recordsPerPage)):Number(g.RecordsPerPageRAControlDefault)}set recordsPerPage(t){this.setParameter(g.recordsPerPage,String(t))}get enableQuickFind(){return k.IsStrictTrue(this.getParam(g.enableQuickFind))}set enableQuickFind(t){this.setParameter(g.enableQuickFind,t)}get teamTemplateId(){return k.StripBraces(this.getParam(g.teamTemplateId))||k.EmptyString}set teamTemplateId(t){this.setParameter(g.teamTemplateId,k.AddBraces(t))}get chartId(){return this.getParam(g.visualizationId)||k.EmptyString}set chartId(t){this.setParameter(g.visualizationId,t)}get enableChartPicker(){return k.IsStrictTrue(this.getParam(g.enableChartPicker))}set enableChartPicker(t){this.setParameter(g.enableChartPicker,t)}get chartGridMode(){switch(this.getParam(g.chartGridMode)){case Yt.Chart:return Yt.Chart;case Yt.Grid:return Yt.Grid;default:return Yt.All}}set chartGridMode(t){this.setParameter(g.chartGridMode,t)}updateChartGridMode(t){t?this.chartGridMode=Yt.Chart:this.chartGridMode=this.enableChartPicker?Yt.All:Yt.Grid}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case g.targetEntityType:n.getAllChildren()[0].setNodeName("<"+r.targetEntityType);break;case g.viewId:n.getAllChildren()[0].setNodeName("<"+k.AddBraces(r.viewId));break;case g.isUserView:n.getAllChildren()[0].setNodeName("<"+r.isUserView);break;case g.enableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.enableViewPicker);break;case g.RelationshipName:let i=n.getAllChildren(),a="<"+r.relationshipName;i.length?n.getAllChildren()[0].setNodeName(a):n.addChild(new j(a,n));break;default:break}}updateControlDescription(t){let r=t.getControlDescriptionByForControl(this.UniqueId);if(r){let n=r.customControls;for(let i=0;i<n.length;i++){let a=n[i].getParameters().get(wt.dataset)?n[i].getParameters().get(wt.dataset)[0]:null;if(a){let o=a.getAllChildren();this.updateDefaultProperties(o,this)}else{let o=n[i].getAllChildren()[0].getAllChildren();this.updateDefaultProperties(o,this)}}}}}});var Ba,tm=T(()=>{"use strict";ct();ga();hs();Y();Ba=class extends wr{constructor(t){super(t)}get defaultViewId(){return k.StripBraces(this.getParam(g.DefaultViewId))||k.EmptyString}set defaultViewId(t){this.setParameter(g.DefaultViewId,k.AddBraces(t))}get autoResolve(){return k.IsStrictTrue(this.getParam(g.AutoResolve))}set autoResolve(t){this.setParameter(g.AutoResolve,t)}get disableQuickFind(){return k.IsStrictTrue(this.getParam(g.DisableQuickFind))}set disableQuickFind(t){this.setParameter(g.DisableQuickFind,t)}get disableViewPicker(){return k.IsStrictTrue(this.getParam(g.DisableViewPicker))}set disableViewPicker(t){this.setParameter(g.DisableViewPicker,t)}get allowFilterOff(){return k.IsStrictTrue(this.getParam(g.AllowFilterOff))}set allowFilterOff(t){this.setParameter(g.AllowFilterOff,t)}get disableMru(){return k.IsStrictTrue(this.getParam(g.DisableMru))}set disableMru(t){this.setParameter(g.DisableMru,t)}get dependentAttributeName(){return this.getParam(g.DependentAttributeName)||k.EmptyString}set dependentAttributeName(t){this.setParameter(g.DependentAttributeName,t)}get dependentAttributeType(){return this.getParam(g.DependentAttributeType)||k.EmptyString}set dependentAttributeType(t){this.setParameter(g.DependentAttributeType,t)}get filterRelationshipName(){return this.getParam(g.FilterRelationshipName)||k.EmptyString}set filterRelationshipName(t){this.setParameter(g.FilterRelationshipName,t)}get availableViewIds(){return this.getParam(g.AvailableViewIds)||k.EmptyString}set availableViewIds(t){this.setParameter(g.AvailableViewIds,t)}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case g.datafieldname:case g.bindAttribute:n.getAllChildren()[0].setNodeName("<"+r.dataFieldName);break;case g.DefaultViewId:n.getAllChildren()[0].setNodeName("<"+k.AddBraces(r.defaultViewId));break;case g.AllowFilterOff:n.getAllChildren()[0].setNodeName("<"+r.allowFilterOff);break;case g.DisableQuickFind:n.getAllChildren()[0].setNodeName("<"+r.disableQuickFind);break;case g.DisableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.disableViewPicker);break;case g.FilterRelationshipName:n.getAllChildren()[0].setNodeName("<"+r.filterRelationshipName);break;case g.DependentAttributeName:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeName);break;case g.DependentAttributeType:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeType);break;case g.AvailableViewIds:n.getAllChildren()[0].setNodeName("<"+r.availableViewIds);break;case g.DisableMru:n.getAllChildren()[0].setNodeName("<"+r.disableMru);break;case g.AutoResolve:n.getAllChildren()[0].setNodeName("<"+r.autoResolve);break;default:break}}updateControlDescription(t){let r=t.getControlDescriptionByForControl(this.UniqueId);if(r){let n=r.customControls;for(let i=0;i<n.length;i++){let a=n[i].getParameters().get(wt.value)?n[i].getParameters().get(wt.value)[0]:null;if(a){let o=a.getAllChildren();this.updateDefaultProperties(o,this)}else{let o=n[i].getAllChildren()[0].getAllChildren();this.updateDefaultProperties(o,this)}}}}}});var kD,rm,xt,gs=T(()=>{"use strict";kD=se(LD());Qn();Y();Be();Ve();Zf();hs();uu();uf();$p();vr();vi();fa();em();tm();nm();Jo();rm="_",xt=class e extends dt{fieldPlaceholder;fieldRequiredLevel;isNewField;cellColType;dependentFields=[];constructor(t){super(b.formCell,t),this.isNewField=!1}get cellType(){return this.cellColType}set cellType(t){this.cellColType=t}setDefaultProperties(t){this.showlabel=t,this.isLocked=!1,_.IsNullOrUndefined(this.getProperty(g.id))&&(this.id=new L(L.NewGuid()))}addControl(t,r,n,i,a,o,s){n instanceof wr?this.addChild(n):n instanceof L&&this.addChild(this.getControlWithControlSpecificProperties(t,r,n,i,a,o,s))}removeControl(){return this.deleteChild(this.control)>=0}get isIndependent(){if(!_.IsNullOrUndefined(this.control))return _.IsNullOrUndefined(this.control.dataFieldName)?_.IsNullOrUndefined(this.control.id)?!0:!bi.dependencyFieldCount.containsKey(this.control.id):!bi.dependencyFieldCount.containsKey(this.control.dataFieldName)}createOnLoadEvent(){this.addEvent(new ka(this,$o.onLoad))}get dependencies(){let t=this.getChildren(b.formEvents);for(let r of t){let n=r.getChildren(b.formEvent);for(let i of n)this.buildDependencyList(i,this.dependentFields)}return this.dependentFields}getNextAvailableControlName(t,r,n,i){let a;if(i&&Kl[i])a=Kl[i].replace(/ /g,rm)+rm;else{a="Control_";let u=new Error("Control class id does not exist or is undefined");(0,kD.trackErrorTrace)(yt,{eventName:`${Pb}/getNextAvailableControlName`},u)}let o="new_",s=this.getHighestIndexById(t,i)+1,l=`${a}${o}${s}`;for(;n.has(l);)s++,l=`${a}${o}${s}`;return l}getUnboundControlProperties(t){e.prototype.setProperty.call(t,g.isUnbound,"true"),e.prototype.setProperty.call(t,g.isRequired,"false")}getControlWithControlSpecificProperties(t,r,n,i,a,o,s){let l;a===er.Grid?(l=new Ma(this),l.indicationOfSubgrid=!0):a===er.Lookup?l=new Ba(this):l=new wr(this);let u=n.guidString,c=o||this.getNextAvailableControlName(t,i,this.getUsedNodeNameSet(t),u);if(e.prototype.setProperty.call(l,g.id,c),l.ClassId=n,!_.IsNullOrUndefined(s)&&(l.UniqueId=s),!o&&r)this.getUnboundControlProperties(l);else{let d=ze.getUniqueIdentifierForControl(l);_.IsNullOrUndefined(d)||(ze.getControlDataTypeByControlOrUniqueId(d)===W.QuickFormCollectionControl||!ze.isUnboundFormControlByIdentifier(d)?a!==er.Grid&&o&&u!==I.IframeControl&&u!==I.SubgridControl&&u!==I.ReferencePanelSubgridControl&&(l.dataFieldName=o,e.prototype.setProperty.call(l,g.disabled,"false")):(this.rowspan=ze.GetRowSpan(l),(ze.getControlDataTypeByControlOrUniqueId(d)===W.NotesControl||ze.getControlDataTypeByControlOrUniqueId(d)===W.TimeLineControl)&&(e.prototype.setProperty.call(l,g.disabled,"false"),l.id=W.NotesControl)),(ze.getUnboundControlNameFromIdentifier(n)===W.SubGridControl||ze.getUnboundControlNameFromIdentifier(n)===W.NotesControl||ze.getUnboundControlNameFromIdentifier(n)===W.TimeLineControl)&&(this.availableforphone=!0))}return l}buildDependencyList(t,r){if(_.IsNullOrUndefined(t))return;let n=t.getAllChildren();for(let i of n){let a=i.getAllChildren();for(let o of a){let s=o.GetPropertyByParameter(g.id);o.getNodeName()===b.dependency&&s?r.push(s):this.buildDependencyList(o,r)}}}get control(){return this.getFirstChild(b.formControl)}set rowspan(t){this.setProperty(g.rowspan,String(t))}get rowspan(){let t=this.getProperty(g.rowspan);return _.IsNullOrUndefined(t)?1:parseInt(t,10)}set autoexpand(t){this.setProperty(g.auto,String(t))}get autoexpand(){return this.getProperty(g.auto)==="true"}set colspan(t){let r=Number(sf.ONE_COLUMN),n=Number(sf.FOUR_COLUMN);_.IsNullOrUndefined(t)||t>n||t<r||this.setProperty(g.colspan,String(t))}get colspan(){let t=this.getProperty(g.colspan);return _.IsNullOrUndefined(t)?1:parseInt(t,10)}getParentRow(){return this.getAncestor(b.formRow)}getParentSection(){return this.getAncestor(b.formSection)}getParentTab(){return this.getAncestor(b.formTab)}getParentForm(){return this.getAncestor(b.form)}isInHeader(){let t=this.getAncestor(b.formHeader);return!_.IsNullOrUndefined(t)}isInFooter(){let t=this.getAncestor(b.formFooter);return!_.IsNullOrUndefined(t)}isEmpty(){return _.IsNullOrUndefined(this.control)&&!this.IsUserSpacer}getHeaderFooter(){return this.isInHeader()?this.getAncestor(b.formHeader):this.isInFooter()?this.getAncestor(b.formFooter):null}get FieldRequiredLevel(){return this.fieldRequiredLevel}set FieldRequiredLevel(t){this.fieldRequiredLevel=t}get FieldPlaceholder(){return this.fieldPlaceholder}set FieldPlaceholder(t){this.fieldPlaceholder=t}get IsNewField(){return this.isNewField}set IsNewField(t){this.isNewField=t}get IsUserSpacer(){let t=this.getProperty(g.userspacer);return _.IsNullOrUndefined(t)?!1:t==="true"}SetUserSpacer(){this.setProperty(g.userspacer,"true")}ClearUserSpacer(){this.setProperty(g.userspacer,"false")}get columns(){let t=this.getProperty(g.columnName);return _.IsNullOrUndefined(t)?null:parseInt(t,10)}getColumnLayoutValue(t){let r;switch(t){case Ie.TWO_COLUMN:r="11";break;case Ie.THREE_COLUMN:r="111";break;case Ie.FOUR_COLUMN:r="1111";break;default:r="1"}return r}findRowIndexByCellId(t){let r=this.getParentRow().cells.indexOf(this);for(let n=0;n<t.rows.length;n++)if(!_.IsNullOrUndefined(t.rows[n].cells[r])&&this.id.ToString()===t.rows[n].cells[r].id.ToString())return n;return-1}setAutoExpandDetailsForTab(){let t=this.getParentTab();_.IsNullOrUndefined(t)||(t.autoExpandCell=this,t.tabContainsAutoExpandControl=!0)}isCellRequiredOrLocked(t,r,n){let i=this.getParentForm();if(this?.control){if(this.IsUserSpacer)return!1;{if(this.isLocked||r().has(this.control.dataFieldName))return!0;let a=i.isDuplicateCell(this,n),o=this.getRequiredLevel(t);if((o===Ai.ApplicationRequired||o===Ai.SystemRequired)&&!a||this.isCellLockedByExternal(t)&&!a)return!0}}return!1}getRequiredLevel(t){return!this.control?.dataFieldName||!this.control?.id||this.IsNewField||!this.control?.ClassId?Ai.None:t.getEntityAttributeByName(this.control.dataFieldName)?.requiredLevel?.toString()??Ai.None}isCellLockedByExternal(t){return this.control||this.IsUnboundControl?!1:t.getEntityAttributeByName(this.control.dataFieldName).isRequiredForForm||!this.isIndependent}async toJSON(t){return{Id:this.id&&this.id.guidString,Name:this.Name,Label:this.getDisplayName(t.langCode),ShowLabel:this.showlabel,Visible:this.visible||t.formModelService.showHiddenElements,LabelId:this.labelId.guidString,PreviewId:this.id&&this.id.guidString,ColSpan:this.colspan,RowSpan:this.rowspan,AutoExpand:this.autoexpand,IsInFirstColumnOfSection:!1,IsInLastColumnOfSection:!1,AvailableForPhone:this.availableforphone,UserSpacer:this.IsUserSpacer,IsPreviewCell:!1,IsStreamCell:!1,IsChartCell:!1,IsTileCell:!1,Control:this.control&&await this.control.toJSON(t)}}getUsedNodeNameSet(t){let r=new Set;return t&&t.visit(n=>{if(n.getNodeName()===b.formCell){let i=n;i.control&&i!==this&&r.add(n.control.id)}return!1}),r}getHighestIndexById(t,r){let n=t.findAll(a=>a.getNodeName()===b.formCell&&a.control&&a.control.ClassId.guidString===r),i=0;return n.forEach(a=>{i=Math.max(this.parseControlNameIndex(a.control.id),i)}),i}parseControlNameIndex(t){let r=t.length-1,n=0;for(;r>0&&parseInt(t.charAt(r),10);)r--;return r>0&&r!==t.length-1&&t.charAt(r)===rm&&(r++,n=parseInt(t.substr(r,t.length-r),10)),n}}});var Ua,im=T(()=>{"use strict";ct();Y();Ye();Ua=class extends j{isInternal;constructor(t,r,n,i){super(b.library,t),this.isInternal=!!i,k.IsNullOrEmpty(n)||(this.name=r,this.libraryUniqueId=n)}get libraryUniqueId(){let t=this.getProperty(g.libraryUniqueId);return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),t?.toUpperCase()}set libraryUniqueId(t){this.setProperty(g.libraryUniqueId,t)}get name(){return this.getProperty(g.libraryName)}set name(t){this.setProperty(g.libraryName,t)}get displayName(){return this.getProperty(g.displayName)}set displayName(t){this.setProperty(g.displayName,t)}get description(){return this.getProperty(g.description)}set description(t){this.setProperty(g.description,t)}}});var Di,am=T(()=>{"use strict";Be();gs();Y();Ye();Di=class extends j{isRowAddedOnDragOver;constructor(t){super(b.formRow,t)}addCell(t){this.addChild(t)}appendCells(t){for(let r of t)this.addChild(r)}updateCell(t,r){return this.updateChild(t,r)}removeCell(t){return _.IsNullOrUndefined(t)?!1:this.deleteChild(t)>=0}insertCellAtIndex(t,r){return _.IsNullOrUndefined(t)?!1:(this.insertChildAtIndex(t,r),!0)}isEmpty(){return!this.cells||this.cells.every(t=>t.isEmpty())}getParentSection(){return this.getAncestor(b.formSection)}insertPaddingCellAtIndex(t){let r=new xt(this);r.setDefaultProperties(),this.insertCellAtIndex(r,t)}get firstCell(){let t=this.cells;return t.length>0?t[0]:null}get cells(){return this.getChildren(b.formCell)}get rowColspan(){return this.cells.reduce((t,r)=>t+r.colspan,0)}set IsRowAddedOnDragOver(t){this.isRowAddedOnDragOver=t}get IsRowAddedOnDragOver(){return this.isRowAddedOnDragOver}async getCellsJSON(t){let r=[],n=[];if(this.cells){for(let i of this.cells)n.push(i.toJSON(t));for(let i of n)r.push(await i)}return r}async toJSON(t){return{Cells:await this.getCellsJSON(t),Visible:!0,Height:"0"}}}});function J5(e){switch(e){case Ci.Left:return Ei.Left;case Ci.Right:return Ei.Right;case Ci.Center:return Ei.Center;default:return Ei.Left}}function K5(e){switch(e){case ba.Left:return Aa.Left;case ba.Top:return Aa.Top;default:return Aa.Left}}function MD(e){switch(e){case 1:return 1;case 2:return 11;case 3:return 111;case 4:return 1111;default:return 1}}var Q5,Gr,vs=T(()=>{"use strict";cf();Ve();Be();ct();Xf();gs();Y();vr();Qn();am();Q5=115,Gr=class e extends dt{colSpan=1;constructor(t,r){super(t,r)}getSectionType(){let t;switch(this.columns){case 1:t=Ie.ONE_COLUMN;break;case 11:t=Ie.TWO_COLUMN;break;case 111:t=Ie.THREE_COLUMN;break;case 1111:t=Ie.FOUR_COLUMN;break;default:t=this.colSpan-1}return t}setUniqueName(){let t=this.getParentTab(),r=Se.namePrefix;if(t){let n=t.Name,i=t.TotalSectionsCount+1;r=n+Se.namePrefix+i.toString()}else r+=Math.floor(Math.random()*1e3);this.setProperty(g.Name,r)}initializeDefaultProperties(t,r,n){if(n===Ie.REFERENCE_PANEL){this.addProperty(g.rowheight,"25");let i=`${Se.referencePanelNamePrefix}${L.NewGuid()}${Se.namePrefix}`;this.addProperty(g.Name,i)}else this.setUniqueName();if(this.addProperty(g.id,new L(L.NewGuid()).guidString),this.addProperty(g.IsUserDefined,Se.IsUserDefined),this.addProperty(g.locklevel,Se.LockLevel),this.addProperty(g.showlabel,Se.ShowLabel),this.addProperty(g.showbar,Se.ShowBar),this.addProperty(g.layout,Se.Layout),this.addProperty(g.Fieldlabelalignment,Se.labelAlignment),this.addProperty(g.Fieldlabelposition,Se.labelPosition),_.IsNullOrUndefined(n))this.addProperty(g.columnName,Se.columns);else{let i=this.getColumnLayoutValue(n);this.addProperty(g.columnName,i)}this.addProperty(g.LabelWidth,Se.LabelWidth),this.setDisplayName(r,t)}getColumnLayoutValue(t){let r;switch(t){case Ie.TWO_COLUMN:r="11";break;case Ie.THREE_COLUMN:r="111";break;case Ie.FOUR_COLUMN:r="1111";break;default:r="1"}return r}getNumberOfColumns(){return e.getNumericColumnLayoutValue(this.columns)}static getNumericColumnLayoutValue(t){switch(t){case 1:return 1;case 11:return 2;case 111:return 3;case 1111:return 4;default:throw new Error("Unexpected Section Layout Value.")}}getColumnCountValue(){let t=0;return _.IsNullOrUndefined(this.columns)?t=this.ColSpan:this.columns.toString().split(k.EmptyString).forEach(r=>{t+=parseInt(r,10)}),t}get ColSpan(){return this.colSpan}initializeRow(t){if(t>0&&t<5){let r=new Di(null);if(this.addGrandChild(b.formRows,r),PD.getConfig().enableAutoInsertionOfCellInRow)for(let n=0;n<t;n++){let i=new xt(r);i.setDefaultProperties(!1),r.addCell(i)}}}initialize(t,r,n){this.initializeDefaultProperties(t,r,n),n===Ie.REFERENCE_PANEL&&(n=Ie.ONE_COLUMN),this.initializeRow(n+1)}setColSpan(t){this.colSpan=t}appendRow(t){this.addGrandChild(b.formRows,t)}insertRowAtIndex(t,r){this.addGrandChildAtIndex(b.formRows,t,r)}insertRowsAtIndex(t,r){if(t&&t.length>0)for(let n=0;n<t.length;n++)this.addGrandChildAtIndex(b.formRows,t[n],r+n)}indexOfRow(t){return this.rows.indexOf(t)}deleteRow(t){return this.deleteFirstGrandChildOfName(b.formRows,t)}deleteRows(t,r){this.deleteGrandChildren(b.formRows,t,r)}get rows(){return this.getRows()}getRows(){let t=this.getChildren(b.formRows);return t.length===0?[]:t[0].getChildren(b.formRow)}get columns(){let t=this.getProperty(g.columnName),r=_.IsNullOrUndefined(t)?NaN:parseInt(t,10);if(isNaN(r)){let n=1;for(let i of this.rows)n=Math.max(n,i.cells.length);return MD(n)}return r}set columns(t){_.IsNullOrUndefined(t)||this.setProperty(g.columnName,String(t))}get rowHeight(){let t=this.getProperty(g.rowheight);return _.IsNullOrUndefined(t)?null:parseInt(t,10)}set rowHeight(t){this.setProperty(g.rowheight,String(t))}set autoexpand(t){this.setProperty(g.autoExpand.toLowerCase(),String(t))}get autoexpand(){return this.getProperty(g.autoExpand.toLowerCase())==="true"}get isUserDefined(){return+this.getProperty(g.IsUserDefined)!=0}set isUserDefined(t){t?this.setProperty(g.IsUserDefined,"1"):this.setProperty(g.IsUserDefined,"0")}getParentColumn(){return this.getAncestor(b.formColumn)}getParentTab(){return this.getAncestor(b.formTab)}get hasMultiColumnRow(){return this.getColumnCountValue()>1}get showlabel(){return this.getProperty(g.showlabel)==="true"}set showlabel(t){_.IsNullOrUndefined(t)||this.setProperty(g.showlabel,String(t))}get fieldLabelAlignment(){let t=Se.labelAlignment,r=this.getProperty(g.Fieldlabelalignment);return _.IsNullOrUndefined(r)?t:r}set fieldLabelAlignment(t){_.IsNullOrUndefined(t)||this.setProperty(g.Fieldlabelalignment,t)}get fieldLabelPosition(){let t=this.getProperty(g.Fieldlabelposition);return _.IsNullOrUndefined(t)?Se.labelPosition:t}set fieldLabelPosition(t){_.IsNullOrUndefined(t)||this.setProperty(g.Fieldlabelposition,String(t))}get showbar(){return this.getProperty(g.showbar)==="true"}set showbar(t){_.IsNullOrUndefined(t)||this.setProperty(g.showbar,String(t))}get labelwidth(){let t=+this.getProperty(g.LabelWidth);return t===0?Q5:t}set labelwidth(t){_.IsNullOrUndefined(t)||t>283&&t<57||this.setProperty(g.LabelWidth,t.toString())}async getRowsJSON(t){let r=[],n=[];if(this.rows){for(let i of this.rows)n.push(i.toJSON(t));for(let i of n)r.push(await i)}return r}async toJSON(t){return{Name:this.Name,Id:this.id&&this.id.guidString,Label:this.getDisplayName(t.langCode),ShowLabel:this.showlabel,Visible:this.visible||t.formModelService.showHiddenElements,LabelId:this.labelId&&this.labelId.guidString,PreviewId:this.id&&this.id.guidString,Rows:await this.getRowsJSON(t),CellLabel:{Width:this.labelwidth,Alignment:J5(this.fieldLabelAlignment),Position:K5(this.fieldLabelPosition)},Columns:MD(this.getColumnCountValue()),AvailableForPhone:this.availableforphone,Height:this.rowHeight&&this.rowHeight.toString()}}getUsedNodeNameSet(t){let r=new Set;return t&&t.visit(n=>{if(n.getNodeName()===b.formSection){let i=n;i.Name&&!k.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}isReferencePanelSection(){return!_.IsNullOrUndefined(this)&&!_.IsNullOrUndefined(this.Name)&&this.Name.indexOf(Se.referencePanelNamePrefix)===0}getAllMultiRowCells(){return this.findAll(t=>{if(t.getNodeName()===b.formCell){let r=t;return!r.isEmpty()&&r.rowspan>1}return!1})}isHeaderOrFooterSection(){return this.NodeName===b.formFooter||this.NodeName===b.formHeader}}});var Xn,Du=T(()=>{"use strict";Y();Ye();vs();Xn=class e extends j{constructor(t){super(b.formColumn,t)}initializeDefaultProperties(t){this.addProperty(g.width,t.toString()+"%")}insertSectionAtIndex(t,r){this.addGrandChildAtIndex(b.formSections,t,r)}static createAndInitNewSection(t,r,n){let i=new Gr(b.formSection,null);return i.initialize(t,r,n),i}addSectionAtIndex(t,r){this.addGrandChildAtIndex(b.formSections,t,r)}initialize(t,r,n,i=Ie.ONE_COLUMN){this.initializeDefaultProperties(t);let a=e.createAndInitNewSection(r,n,i);this.addSectionAtIndex(a,this.sections.length),a.setUniqueName()}get parentTab(){return this.getAncestor(b.formTab)}get sections(){let t=this.getChildren("sections");return t.length!==1?[]:t[0].getChildren(b.formSection)}get width(){return this.getProperty(g.width)}set width(t){this.setProperty(g.width,t)}deleteSection(t){return this.deleteFirstGrandChildOfName(b.formSections,t)}async getSectionsJSON(t){let r=[];if(this.sections)for(let n of this.sections)r.push(await n.toJSON(t));return r}async toJSON(t){return{Name:this.getProperty(g.Name),Id:this.getProperty(g.id),Label:null,ShowLabel:!1,Visible:!0,LabelId:null,PreviewId:this.getProperty(g.id),Sections:await this.getSectionsJSON(t),Width:this.width}}}});var Iu,BD=T(()=>{"use strict";Ve();Y();vr();vs();Iu=class extends Gr{initializeNavArea(t,r,n){this.initializeNavAreaProps(t,r,n)}get AreaName(){return this.Name}initializeNavAreaProps(t,r,n){this.addProperty(g.Name,n),this.addProperty(g.id,new L(L.NewGuid()).guidString),this.addProperty(g.columnName,Se.columns),this.setDisplayName(r,t)}}});var _u,UD=T(()=>{"use strict";Du();Y();BD();_u=class extends Xn{addAndIntializeNavBarSection(t,r,n,i){let a=new Iu(b.formSection,null);return a.initializeNavArea(t,r,i),this.addGrandChildAtIndex(b.formSections,a,n),a}}});var mn,Tu=T(()=>{"use strict";Ve();Be();ct();Du();Y();Ye();Qn();mn=class extends dt{tabContainsAutoExpandControl;autoExpandCell;constructor(t,r){super(b.formTab,t),this.tabContainsAutoExpandControl=!1}getParentForm(){return this.getAncestor(b.form)}getTabLayoutType(){let t;switch(this.columns.length){case 1:t=De.ONE_COLUMN;break;case 2:if(parseInt(this.columns[0].width,10)===50&&parseInt(this.columns[1].width,10)===50){t=De.TWO_COLUMN_EQUAL;break}if(parseInt(this.columns[0].width,10)===67&&parseInt(this.columns[1].width,10)===33){t=De.TWO_COLUMN_WIDER_LEFT;break}if(parseInt(this.columns[0].width,10)===34&&parseInt(this.columns[1].width,10)===66){t=De.TWO_COLUMN_WIDER_RIGHT;break}t=De.TWO_COLUMN_CUSTOM_LAYOUT;break;case 3:if(parseInt(this.columns[0].width,10)===34&&parseInt(this.columns[1].width,10)===33&&parseInt(this.columns[2].width,10)===33){t=De.THREE_COLUMN_EQUAL;break}if(parseInt(this.columns[0].width,10)===28&&parseInt(this.columns[1].width,10)===44&&parseInt(this.columns[2].width,10)===28){t=De.THREE_COLUMN_WIDER_MID;break}t=De.THREE_COLUMN_CUSTOM_LAYOUT;break;default:}return t}initializeProperties(t,r,n){this.addProperty(g.Name,zn.namePrefix+t.toString()),this.addProperty(g.id,new L(L.NewGuid()).guidString),this.addProperty(g.IsUserDefined,zn.IsUserDefined),this.addProperty(g.locklevel,zn.LockLevel),this.addProperty(g.showlabel,zn.ShowLabel),this.setDisplayName(n,r)}get TotalSectionsCount(){let t=0;for(let r of this.columns)t+=r.sections.length;return t}initializeColumns(t,r,n,i=Ie.ONE_COLUMN,a=!0,o){let s=this.getChildren(b.formColumns)[0],l=[];switch(t){case De.ONE_COLUMN:l.push(100);break;case De.TWO_COLUMN_EQUAL:l.push(50),l.push(50);break;case De.TWO_COLUMN_WIDER_LEFT:l.push(67),l.push(33);break;case De.TWO_COLUMN_WIDER_RIGHT:l.push(34),l.push(66);break;case De.THREE_COLUMN_EQUAL:l.push(34),l.push(33),l.push(33);break;case De.THREE_COLUMN_WIDER_MID:l.push(28),l.push(44),l.push(28);break;default:}for(let u of l){let c=new Xn(s);c.initialize(u,r,n,i),this.addGrandChild(b.formColumns,c)}}initialize(t,r,n,i,a,o=Ie.ONE_COLUMN,s=!0,l){this.addChild(new j(b.formColumns,this)),this.initializeProperties(r,n,i),this.initializeColumns(t,n,a,o,s,l)}get columns(){let t=this.getChildren(b.formColumns);return t.length!==1?[]:t[0].getChildren(b.formColumn)}get expanded(){return this.getProcessedValue(g.expanded)}set expanded(t){_.IsNullOrUndefined(t)||this.setProperty(g.expanded,String(t))}get groupName(){return this.getProperty(g.groupName)}get contentType(){return this.getProperty(g.contentType)}set contentType(t){this.setProperty(g.contentType,t)}insertNewColumnAtIndex(t,r,n,i,a){t.initialize(n,i,a),this.addGrandChildAtIndex(b.formColumns,t,r)}insertColumnAtIndex(t,r){this.addGrandChildAtIndex(b.formColumns,t,r)}deleteColumn(t){return this.deleteFirstGrandChildOfName(b.formColumns,t)}async getColumnsJSON(t){let r=[],n=[];if(this.columns){for(let i of this.columns)n.push(i.toJSON(t));for(let i of n)r.push(await i)}return r}async toJSON(t){return{Name:this.Name,Id:this.id&&this.id.guidString,Label:this.getDisplayName(t.langCode)+(!this.visible&&t.formModelService.showHiddenElements?"\u3000\u3000":""),ShowLabel:this.showlabel,Visible:this.visible||t.formModelService.showHiddenElements,LabelId:this.labelId&&this.labelId.guidString,UniqueId:this.id&&this.id.guidString,PreviewId:this.id&&this.id.guidString,Columns:await this.getColumnsJSON(t),EventHandlers:[],Expanded:this.expanded,ContentType:this.contentType,AvailableForPhone:this.availableforphone,Header:void 0,Footer:void 0}}getUsedNodeNameSet(t){let r=new Set;return t&&t.visit(n=>{if(n.getNodeName()===b.formTab){let i=n;i.Name&&!k.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}}});var Ii,om=T(()=>{"use strict";Ve();Y();Ye();vr();UD();Tu();Ii=class extends mn{constructor(t,r,n){super(t,De.THREE_COLUMN_EQUAL),this.setDisplayName(r,n),this.id=new L(L.NewGuid())}initializeDefaultProps(){this.addChild(new j(b.formColumns,this)),this.initializeFiveColumns()}get columns(){let t=this.getChildren("columns");return t.length!==1?[]:t[0].getChildren(b.formColumn)}getNavSectionForArea(t){for(let r of this.columns)for(let n of r.sections)if(n.AreaName===t)return n;return null}getNavCellFromNavId(t){for(let r of this.columns)for(let n of r.sections)for(let i of n.rows)for(let a of i.cells)if(a.NavId===t)return a;return null}initializeFiveColumns(){for(let t=0;t<su.FIVE_COLUMN;t++){let r=new _u(this.getChildren(b.formColumns)[0]);r.initializeDefaultProperties(ow.FiveEqColumn),this.addGrandChild(b.formColumns,r)}}}});function Y5(e){switch(e){case Ge.Main:return jn.Main;case Ge.QuickCreate:return jn.QuickCreate;case Ge.QuickViewForm:return jn.Quick;case Ge.Dialog:return jn.Dialog;default:return jn.None}}function Z5(e,t){if(t===Ge.Main){if(e)switch(e.toLowerCase()){case"low":return Gn.Low;case"highreadonlyvalues":return Gn.HighReadOnlyValues;default:return Gn.HighWithControls}return Gn.Low}}var Ru,X5,Pu,$D=T(()=>{"use strict";fw();Ru=se(yi());cf();Be();ct();fa();Xf();Y();ga();Ip();vi();gs();Y();Qn();im();om();Tu();X5="1920";Pu=class e extends dt{_formUniqueName;isHeaderDefaulted;consistencyStrong=!1;_formId;_rawFormXml;_entityName;_entityDisplayName;_status;_formName;_langCode;_description;_formType;_formPresentation;parameters=[];_formactivationstate;_changeTracker;_metadataChangeEvent;_etag;constructor(t,r,n,i,a,o,s,l,u){super(b.form,null),this._formUniqueName=a,this._formId=t,this._entityName=r,this._status=n,this._formName=i,this._description=l,this._formType=o,this._formPresentation=s,this._formactivationstate=u,this._changeTracker=new Wl,this._metadataChangeEvent=new cu}get FormLibraries(){let t=this.getFirstChild(b.formLibraries),r=t?t.getAllChildren():[],n=this._getInternalLibraries();return r.concat(n)}getAllEvents(){let t=[],r=this.events;r&&(t=t.concat(r));for(let n of this.tabs){let i=n.events;i&&(t=t.concat(i)),n.findAll(a=>a instanceof xt).forEach(a=>{let o=a.events;o&&(t=t.concat(o))})}return t}getEventsForNode(t){if(t instanceof e){let r=t.events;return r?r.filter(n=>!n.control&&!n.attribute):null}else if(t instanceof xt){if(t.control?.dataFieldName){let r=this.events;return r?r.filter(n=>n.attribute&&t.control.dataFieldName===n.attribute):null}else if(this.isCellEditableGridControl(t)){let r=this.events;return r?r.filter(n=>n.control&&t.control.id===n.control):null}}return t?.events}_getInternalLibraries(){let t=this.findAll(i=>i.getNodeName()===b.internalLibraries),r=[],n="src";return t.length>0&&(r=t.map(i=>{let a=i.GetPropertyByParameter(n).replace("$webresource:",""),o=new Ua(void 0,void 0,"",!0);return o.name=a,o.displayName=a,o})),r}getDependentFields(){let t=this.getAllEvents(),r=new Set;return t.forEach(n=>{try{n.getAllDependencies().forEach(a=>{r.add(a.id)})}catch(i){throw(0,Ru.trackErrorTrace)(Rb,{eventName:"GetDependentFields_MissingDependencies",eventData:{Message:`Failed get dependencies for form event in form ${this.formId.guidString}.`,Attribute:n.attribute,EventName:n.eventName}}),i}}),r}get Parameters(){return this.parameters}set Parameters(t){this.parameters=t}get ShowImagecheck(){return k.IsNullOrEmpty(this.getProperty(g.ShowImage))?!0:this.getProperty(g.ShowImage)!=="false"}set ShowImagecheck(t){t?this.setProperty(g.ShowImage,String(t)):this.setProperty(g.ShowImage,"false")}get ShowNavigation(){return k.IsNullOrEmpty(this.getProperty(g.ShowNavigationbar))?!0:this.getProperty(g.ShowNavigationbar)!=="false"}set ShowNavigation(t){t?this.setProperty(g.ShowNavigationbar,String(t)):this.setProperty(g.ShowNavigationbar,"false")}get MaxWidth(){return k.IsNullOrEmpty(this.getProperty(g.MaxWidth))?X5:this.getProperty(g.MaxWidth)}set MaxWidth(t){this.setProperty(g.MaxWidth,t)}get headerDensityType(){return this.getProperty(g.HeaderDensityType)}set headerDensityType(t){t&&this.formType===Ge.Main?this.setProperty(g.HeaderDensityType,t):this.formType!==Ge.Main&&this.headerDensityType&&this.removeProperty(g.HeaderDensityType)}IsMainOrQuickCreateForm(){return this.formType===Ge.Main||this.formType===Ge.QuickCreate}get FormPresentation(){return this._formPresentation}get LanguageCode(){return this._langCode}set LanguageCode(t){this._langCode=t}get header(){let t=this.getChildren(b.formHeader);return t.length!==1?null:t[0]}set header(t){_.IsNullOrUndefined(t)||(this.deleteChild(this.header),this.addChild(t))}getAllDependencies(){return this.getChildren(b.quickFormDependencies).length===0?[]:this.ConvertModelToArray(this.getChildren(b.quickFormDependencies)[0].getAllChildren())}ConvertModelToArray(t){let r=[];return _.IsNullOrUndefined(t)||t.forEach(n=>{r.push(n.id)}),r}get footer(){let t=this.getChildren(b.formFooter);return t.length!==1?null:t[0]}set footer(t){_.IsNullOrUndefined(t)||(this.deleteChild(this.footer),this.addChild(t))}createAndInitNewTab(t,r,n){let i=new mn(null,t),a=this.getNextTabCounter(this.tabs.length+1);return i.initialize(t,a,this.LanguageCode,r,n),i}addTabAtIndex(t,r){this.addGrandChildAtIndex(b.formTabs,t,r)}createAndInitNewTabWithMarginalControl(t,r,n,i,a){let o=new mn(null,De.ONE_COLUMN),s=this.getNextTabCounter(this.tabs.length+1);o.initialize(De.ONE_COLUMN,s,this.LanguageCode,r,n,a,!1),this.addGrandChildAtIndex(b.formTabs,o,i);let l=o.columns[0].sections[0];for(let u=0;u<t.rows.length;u++)l.appendRow(t.rows[u])}getNextTabCounter(t){for(let r=0;r<this.tabs.length;r++)if(this.tabs[r].Name===zn.namePrefix+t.toString())return this.getNextTabCounter(t+1);return t}get allTabs(){let t=this.getChildren(b.formTabs);return t.length!==1?[]:t[0].getChildren(b.formTab)}get CanvasNavigationTab(){if(this.tabs.length>0){let t=this.tabs[this.tabs.length-1];if(t instanceof Ii)return t}return null}get NavigationNode(){let t=this.getChildren(b.formNavigation);return t.length!==1?null:t[0]}set NavigationNode(t){let n=this.getAllChildren().indexOf(this.NavigationNode);n>=0&&(this.deleteChild(this.NavigationNode),this.insertChildAtIndex(t,n))}addNavigatioNode(t){this.addChild(t)}get tabs(){return this.allTabs}deleteTab(t){return this.deleteFirstGrandChildOfName(b.formTabs,t)}insertTabAtIndex(t,r){this.addGrandChildAtIndex(b.formTabs,t,r)}insertRelatedTab(t){let r=this.getAllGrandChildren(b.formTabs);if(!_.IsNullOrUndefined(r)){let n=r.length;this.insertTabAtIndex(t,n)}}get isfooterPresent(){return this.getChildren(b.formFooter).length>0}get displayCondition(){let t=this.getChildren(b.formDisplayConditions);return t.length>0?t[0]:null}set displayCondition(t){this.deleteChild(this.displayCondition),this.addChild(t)}get entityName(){return this._entityName}get formId(){return this._formId}set formId(t){this._formId=t}get rawFormXml(){return this._rawFormXml}set rawFormXml(t){this._rawFormXml=t}get status(){return this._status}set status(t){this._status=t}get formName(){return this._formName}set formName(t){this.trackObjectPropertyChange("_formName",t)}get formUniqueName(){return this._formUniqueName}set formUniqueName(t){this.trackObjectPropertyChange("_formUniqueName",t)}get formType(){return this._formType}get tabCount(){return this.allTabs.length}get description(){return this._description}set description(t){this.trackObjectPropertyChange("_description",t)}get formactivationstate(){return this._formactivationstate}set formactivationstate(t){this.trackObjectPropertyChange("_formactivationstate",t)}get entityDisplayName(){return this._entityDisplayName}set entityDisplayName(t){this._entityDisplayName=t}get etag(){return this._etag}set etag(t){this._etag=t}indexOfTab(t){return this.getAllGrandChildren(b.formTabs).indexOf(t)}get ControlDescriptions(){return this.getAllGrandChildren(b.controlDescriptions)}addControlDescriptionNode(t){this.addGrandChild(b.controlDescriptions,t)}deleteControlDescByForControlId(t){let r=this.getControlDescriptionByForControl(t);_.IsNullOrUndefined(r)||this.deleteFirstGrandChildOfName(b.controlDescriptions,r)}getControlDescriptionByForControl(t){if(!t)return null;for(let r of this.ControlDescriptions)if(r.forControl.guidString===t.guidString)return r;return null}cellHasCustomControlWithName(t,r){if(!t?.control||!r)return!1;let n=this.getControlDescriptionByForControl(t.control.UniqueId);return n?!!n.customControls.find(i=>i.name===r):!1}isDuplicateCell(t,r){return!!this.findFirst(i=>{if(!(i instanceof xt))return!1;let a=!0;return r==="Tab"?a=i.getParentTab()!==t.getParentTab():r==="Section"?a=i.getParentSection()!==t.getParentSection():a=i!==t,i instanceof xt&&i.control&&t.control&&a&&i.control.dataFieldName===t.control.dataFieldName})}isCellEditableGridControl(t){return!t?.control?.indicationOfSubgrid||t.control.ClassId.guidString.toUpperCase()!==I.CustomControl?!1:this.cellHasCustomControlWithName(t,Wn.EditableGridControl)||RD.getConfig()?.enableOneGridEventsForFormDesigner&&this.cellHasCustomControlWithName(t,Wn.PowerAppsOneGrid)}isCellCanvasAppControl(t){return t?.control?.ClassId.guidString.toUpperCase()===I.CustomControl&&this.cellHasCustomControlWithName(t,Wn.CanvasAppControl)}findFormNodeById(t,r=this){return r===null?null:r.findFirst(n=>{if(n===this&&t===this.formId.ToString()||n.id?.ToString?.()===t)return!0})}findFormCellByClassId(t,r=this){return r?r.findFirst(n=>{if(n.getNodeName()===b.formCell){let i=n;return i&&i.control&&i.control.ClassId.guidString===t}return!1}):null}async getTabsJSON(t){let r=this.tabs,n=[],i=[];if(r){for(let a of r)if(!(a instanceof Ii)){let o=a.toJSON(t);n.push(o)}for(let a of n)i.push(await a)}return i}async getControlDescriptionsToJSON(t){let r=[];for(let n of this.ControlDescriptions){let i=await n.toJSON(t);i&&r.push(i)}return r}async toJSON(t){let r=[];r=await this.getControlDescriptionsToJSON(t);let n=this.NavigationNode&&await this.NavigationNode.toJSON(t);return{Id:this._formId.guidString,Name:this.formName,Label:this.getDisplayName(t.langCode),ShowLabel:this.showlabel,Visible:this.visible,LabelId:this.labelId&&this.labelId.guidString,PreviewId:this._formId.guidString,PreviewSessionId:(0,Ru.getSessionId)(),EntityLogicalName:this._entityName,FormId:this._formId.guidString,TabAttributes:{},Tabs:await this.getTabsJSON(t),HiddenFields:[],Header:this.header&&await this.header.toJSON(t),Footer:this.footer&&await this.footer.toJSON(t),...this.formType===Ge.Main?{HeaderDensity:Z5(this.headerDensityType,this.formType)}:{},InlineEditGridRow:[],InlineQuickForms:[],QuickFormEntities:[],EventHandlers:[],LinkControlSections:[],FormType:Y5(this.formType),SubGrids:[],Views:void 0,Charts:void 0,CustomControlConfigurations:r,BusinessLogic:void 0,FormLibraries:[],Navigation:n,ShowNavigationBar:this.ShowNavigation||t.formModelService.showHiddenElements,ClientResources:[]}}changeTracker(){return this._changeTracker}onMetadataChange=t=>this._metadataChangeEvent.on(t);raiseMetadataChange(t){this._metadataChangeEvent.emit(t)}}});var Ou,sm,qD=T(()=>{"use strict";Ve();Be();Y();Ye();Qn();Ou=class extends dt{constructor(t){super(b.formDisplayConditions,t)}get Order(){let t=this.getProperty(g.Order);return _.IsNullOrUndefined(t)?null:parseInt(t,10)}set Order(t){this.setProperty(g.Order,t.toString())}get FallbackForm(){return this.getProperty(g.FallbackForm)==="true"}set FallbackForm(t){this.setProperty(g.FallbackForm,t.toString())}addRoles(t){this.deleteAllChildren();for(let r=0;r<t.length;r++)this.addChild(t[r])}isRoleEveryone(){return!!(this.getChildren(b.formEveryOne)&&this.getChildren(b.formEveryOne)[0])}setRoleEveryone(){this.deleteAllChildren(),this.addChild(new sm(this))}},sm=class extends j{constructor(t){super(b.formEveryOne,t)}}});var xu,VD=T(()=>{"use strict";Y();Ye();xu=class extends j{constructor(t,r){super(b.Handler,r),t.length>0&&this.setDefaultProperties(t)}setDefaultProperties(t){this.FunctionName=t[0],this.LibraryName=t[1],this.HandlerUniqueID=t[2],this.Enabled=t[3],this.Parameters=t[4],this.PassExecutionContext=t[5]}get HandlerUniqueID(){return this.getProperty(g.HandlerUniqueId)}set HandlerUniqueID(t){this.setProperty(g.HandlerUniqueId,t)}get FunctionName(){return this.getProperty(g.functionName)}set FunctionName(t){this.setProperty(g.functionName,t)}get LibraryName(){return this.getProperty(g.libraryNameEventHandler)}set LibraryName(t){this.setProperty(g.libraryNameEventHandler,t)}get Enabled(){return this.getProperty(g.enabledForField)}set Enabled(t){this.setProperty(g.enabledForField,t)}get PassExecutionContext(){return this.getProperty(g.passExecutionContext)}set PassExecutionContext(t){this.setProperty(g.passExecutionContext,t)}get Parameters(){return this.getProperty(g.parameters)}set Parameters(t){this.setProperty(g.parameters,t)}}});var $a,lm=T(()=>{"use strict";Y();vs();$a=class extends Gr{constructor(t,r){super(t,r)}get cells(){let t=this.getRows(),r=[];if(this.rows&&t.length){for(let n of this.rows)if(n.cells){let i=n.getChildren(b.formCell);for(let a of i)r.push(a)}}return r}get occupiedCells(){return this.cells.filter(t=>!t.isEmpty())}get maxColumns(){return super.getColumnCountValue()}}});var ys,GD=T(()=>{"use strict";Y();lm();ys=class extends $a{_customFooter;constructor(t,r){super(b.formFooter,t),this._customFooter=r}get customFooter(){return this._customFooter}set customFooter(t){this._customFooter=t}async getControls(t){let r=[];if(this.rows){for(let n of this.rows)if(n.cells)for(let i of n.cells)i.control&&r.push(await i.control.toJSON(t))}return r}async toJSON(t){return{AvailableForPhone:this.availableforphone,Controls:await this.getControls(t),UniqueId:this.id&&this.id.guidString,PreviewId:this.id&&this.id.guidString}}isEmpty(){return!this.cells.find(t=>!!t.control)}}});var bs,zD=T(()=>{"use strict";Y();lm();bs=class extends $a{_customHeader;constructor(t,r){super(b.formHeader,t),this._customHeader=r}get customHeader(){return this._customHeader}set customHeader(t){this._customHeader=t}get showCommandBar(){return this.getProcessedValue(g.showCommandBar)}set showCommandBar(t){t!=null&&this.setProperty(g.showCommandBar,String(t))}get showBody(){return this.getProcessedValue(g.showBody)}set showBody(t){t!=null&&this.setProperty(g.showBody,String(t))}get showTabNavigator(){return this.getProcessedValue(g.showTabNavigator)}set showTabNavigator(t){t!=null&&this.setProperty(g.showTabNavigator,String(t))}async getControls(t){let r=[];if(this.rows){for(let n of this.rows)if(n.cells)for(let i of n.cells)i.control&&r.push(await i.control.toJSON(t))}return r}async toJSON(t){return{AvailableForPhone:this.availableforphone,Controls:await this.getControls(t),UniqueId:this.id&&this.id.guidString,PreviewId:this.id&&this.id.guidString}}}});var Lt,_i=T(()=>{"use strict";Ve();ct();Y();Qn();Lt=class e extends dt{constructor(t,r){super(t,r)}getTitle(t){for(let r of this.getAllTitles())if(+r.getProperty(g.LCID)===t)return r.getProperty(g.text);return null}getAllTitles(){let t=this.getChildren(b.Titles);return t.length===0?[]:t[0].getChildren(b.Title)}setTitle(t,r){for(let i of this.getAllTitles())if(+i.getProperty(g.LCID)===r){i.setProperty(g.text,t);return}let n=new e(b.Title,null);n.setProperty(g.text,t),n.setProperty(g.LCID,String(r)),this.addGrandChild(b.Titles,n)}get Sequence(){return+this.getProperty(g.Sequence)}set Sequence(t){this.setProperty(g.Sequence,t.toString())}get Area(){return this.getProperty(g.Area)}set Area(t){this.setProperty(g.Area,t)}set Id(t){this.setProperty(g.Id,t)}get Id(){return this.getProperty(g.Id)}get id(){return new L(this.Id??"",!0)}set id(t){this.Id=t.guidString}get Show(){return!0}get Icon(){return this.getProperty(g.icon)}set Icon(t){t=t||k.EmptyString,this.setProperty(g.icon,t)}updateCommonProperties(t,r){this.Area=t.Area,this.Sequence=t.Sequence,this.setTitle(t.getDisplayName(r),r)}}});var ws,WD=T(()=>{"use strict";(function(e){e[e.NavLinkNotAvailable=-1]="NavLinkNotAvailable",e[e.NavLinkIdConflict=-2]="NavLinkIdConflict",e[e.NavBarNotAvailable=-3]="NavBarNotAvailable"})(ws||(ws={}))});var Lu,jD=T(()=>{"use strict";Be();Y();_i();WD();Lu=class extends Lt{constructor(t){super(b.formNavBar,t)}addChildElement(t){this.addChild(t)}getAllActiveNavBarChildren(){return this.getAllChildren().filter(n=>n.Show)}getAllInActiveActiveNavBarChildren(){return this.getAllChildren().filter(n=>!n.Show)}get AllRelationShipItems(){return this.getChildren("NavBarByRelationshipItem")}get AllNavLinkItems(){return this.getChildren("NavBarItem")}removeNavLink(t){let r=this.getNavBarLinkItemById(t);return _.IsNullOrUndefined(r)?ws.NavLinkNotAvailable:r.length===1?this.deleteChild(r[0]):ws.NavLinkIdConflict}getRelationShipItemsByArea(t){let r=this.AllRelationShipItems,n=[];for(let i of r)i.Area===t&&i.Show===!0&&n.push(i);return n}getNavBarRelationShipItemsByNavId(t){return this.AllRelationShipItems.filter(n=>n.Id===t)}getNavBarLinkItemById(t){let r=this.AllNavLinkItems.filter(n=>n.Id===t);return r.length>0?r:null}getAllActiveChildrenForGivenArea(t){let r=this.getAllChildren(),n=[];for(let i of r)i.Area===t&&i.Show&&n.push(i);return n}}});var Ae,eG,HD,cne,qa,um=T(()=>{"use strict";Ve();Y();_i();(function(e){e.Info="_NA_Info",e.Sales="_NA_SFA",e.Service="_NA_CS",e.Marketing="_NA_MA",e.InternetMarketing="_NA_IMA",e.ProcessCenter="_NA_PROC",e.Async="_NA_AO"})(Ae||(Ae={}));eG=new Map([[Ae.Info,"Info"],[Ae.Sales,"Sales"],[Ae.Service,"Service"],[Ae.Marketing,"Marketing"],[Ae.ProcessCenter,"ProcessCenter"]]),HD=new Map([["Info",Ae.Info],["Sales",Ae.Sales],["Service",Ae.Service],["Marketing",Ae.Marketing],["ProcessCenter",Ae.ProcessCenter]]),cne=new Map([[Ae.Info,9e3],[Ae.Sales,9200],[Ae.Service,9400],[Ae.Marketing,9600],[Ae.ProcessCenter,9800],[Ae.InternetMarketing,1e4],[Ae.Async,10200]]),qa=class extends Lt{constructor(t,r){super(b.formNavBarArea,r)}setDefaultPropertiesByType(t,r,n){this.AreaId=eG.get(t);let i=n?.(`navBarArea.title.${this.AreaId}`)??this.AreaId;this.setTitle(i,r)}get ParentNavigation(){return this.getAncestor(b.formNavigation)}get AreaId(){return this.getProperty(g.Id)}set AreaId(t){this.setProperty(g.Id,t)}get id(){return new L(this.AreaId??"",!0)}set id(t){this.AreaId=t.guidString}async toJSON(t){return{Id:this.AreaId,Titles:[{LCID:t.langCode,Text:this.getTitle(t.langCode)}],PreviewId:this.AreaId}}}});var Va,cm=T(()=>{"use strict";Y();_i();Va=class extends Lt{constructor(t,r){super(b.formNavBarAreas,r)}get AllNavBarAreaItems(){return this.getChildren(b.formNavBarArea)}get ParentNavigation(){return this.getAncestor(b.formNavigation)}addNavBarArea(t){this.addChild(t)}}});var Fu,JD=T(()=>{"use strict";Be();Y();_i();Fu=class extends Lt{RelationshipNameUCIRuntime;constructor(t){super(b.formNavBarByRelationshipItem,t)}get RelationshipName(){return this.getProperty(g.RelationshipName)}set RelationshipName(t){this.setProperty(g.RelationshipName,t)}set Show(t){this.setProperty(g.Show,String(t))}get Show(){let t=this.getProperty(g.Show);return _.IsNullOrUndefined(t)||t==="true"}get TitleResourceId(){return this.getProperty(g.TitleResourceId)}async toJSON(t){return{Area:this.Area,Show:this.Show||t.formModelService.showHiddenElements,Id:this.Id,Titles:[{Name:t.langCode.toString(),Value:this.getTitle(t.langCode)}],Sequence:this.Sequence.toString(),Privileges:[],TooltipTitles:[],AvailableOffline:!0,PreviewId:this.Id,RelationshipName:this.RelationshipNameUCIRuntime??this.RelationshipName,Icon:null,ViewId:null,Client:null,TitleResourceId:null}}}});var ku,KD=T(()=>{"use strict";Y();_i();ku=class extends Lt{constructor(t){super(b.formNavBarItem,t)}get Url(){return this.getProperty(g.url)}set Url(t){this.setProperty(g.url,t)}}});var Mu,QD=T(()=>{"use strict";Ve();Y();um();cm();_i();Mu=class extends Lt{constructor(t,r){super(t,r)}getNavBarAreaByAreaName(t){let r=this.navBarAreas.AllNavBarAreaItems.filter(n=>n.AreaId===t);return r.length===0?null:r[0]}get navBarAreas(){return this.getFirstChild(b.formNavBarAreas)}setDefaultNavBarAreas(t,r){let n=[Ae.Info,Ae.Sales,Ae.Service,Ae.Marketing,Ae.ProcessCenter];if(this.navBarAreas){let i=this.navBarAreas?.AllNavBarAreaItems;if(i&&i.length>0){let a=new Set(i.map(o=>HD.get(o.AreaId)));n=n.filter(o=>!a.has(o))}}else{let i=new Va(b.formNavBarAreas,this);i.isTransient=!0,this.addChild(i)}return n.length>0?(n.forEach(i=>{let a=new qa(b.formNavBarArea,this.navBarAreas);a.setDefaultPropertiesByType(i,t,r),this.navBarAreas.addNavBarArea(a)}),!0):!1}get navBar(){return this.getFirstChild(b.formNavBar)}get id(){return new L(Up,!0)}replaceNavAreaToGivenIndex(t,r){this.navBarAreas?.AllNavBarAreaItems.indexOf(r)!==-1&&(this.deleteFirstGrandChildOfName(b.formNavBarAreas,r),this.addGrandChildAtIndex(b.formNavBarAreas,r,t))}async getNavBarAreasJSON(t){let r=[],n=[];if(this.navBarAreas?.AllNavBarAreaItems){for(let a of this.navBarAreas.AllNavBarAreaItems)n.push(a.toJSON(t));r=await Promise.all(n)}return r}async getNavBarRelationshipItemsJSON(t){let r=[],n=[];if(this.navBar?.AllRelationShipItems){for(let i of this.navBar.AllRelationShipItems)n.push(i.toJSON(t));r=await Promise.all(n)}return r}async toJSON(t){let r=await this.getNavBarAreasJSON(t),n=await this.getNavBarRelationshipItemsJSON(t);return{NavBarAreas:{NavBarAreas:r},NavBarByRelationshipItems:n,NavBarItems:[],NavPaneIsvItems:{NavBarIsvItems:[]},ShowEmptyNavBarAreas:t.formModelService.showHiddenElements}}}});var XD={};Zr(XD,{ControlType:()=>er,DeserializationService:()=>fm,DeserializationServiceScope:()=>pm,DeserializedFormElementNode:()=>Ft});var dm,Ft,pm,er,fm,nm=T(()=>{"use strict";dm=se(yi());Ve();Be();ct();fa();$p();vi();Ob();pw();uu();$D();gs();Du();hs();Yf();Y();Y();qD();Ye();vr();Zf();VD();GD();em();tm();zD();im();am();vs();Tu();jD();um();cm();JD();KD();QD();Ft=class extends j{constructor(t,r){super(t,r)}insertProperty(t,r){this.addProperty(t,r)}insertChild(t){this.addChild(t)}},pm="DeserializationService";(function(e){e.Grid="Grid",e.Lookup="Lookup",e.Base="Base"})(er||(er={}));fm=class{lcid;constructor(t){this.lcid=t}deSerializeFormXml(t,r,n,i,a,o,s,l,u,c){if(!t)throw new Error("Formxml could not be parsed.");let d=t.getElementsByTagName("form");if(d.length!==1){let f="";throw d.length===0?f="FormXml has no form node.":f="FormXml has multiple form nodes.",(0,dm.trackErrorTrace)(yt,{eventName:pm,eventData:{error:f}}),new Error(f)}let p=this.createFormModel(d.item(0),r,n,i,a,o,s,l,u,c);return _.IsNullOrUndefined(p.displayCondition)&&s!==Ge.Dialog&&this.appendDefaultDisplayCondition(p),p}upsertFieldCount(t,r){let n=bi.getNecessaryLookUpTable(r),i=1;n.containsKey(t)&&(i+=n.getValue(t)),n.upsert(t,i)}appendDefaultDisplayCondition(t){let r='<DisplayConditions Order="0" FallbackForm="true"><Everyone/></DisplayConditions>';if(!_.IsNullOrUndefined(t)){let n=_.ParseXml(r);n!==null&&this.populateElementChildren(t,n.childNodes)}}createFormModel(t,r,n,i,a,o,s,l,u,c){let d=new Pu(r,n,i,a,o,s,l,u,c);return this.populateElementProperties(d,t.attributes),this.populateElementChildren(d,t.childNodes),s===Ge.Main&&(this.insertHeaderFooterElementProperties(b.formHeader,d,d.header),this.insertHeaderFooterElementProperties(b.formFooter,d,d.footer)),d}insertHeaderFooterElementProperties(t,r,n){if(_.IsNullOrUndefined(n)){let i=t===b.formHeader?new bs(r,!0):new ys(r,!0);Ft.prototype.insertProperty.call(i,g.id,"{"+L.NewGuid()+"}"),Ft.prototype.insertProperty.call(i,g.Fieldlabelposition,"Top"),Ft.prototype.insertProperty.call(i,g.columnName,Se.MarginalControlColumns),Ft.prototype.insertProperty.call(i,g.LabelWidth,Se.LabelWidth),Ft.prototype.insertProperty.call(i,g.Fieldlabelalignment,"Left");let a=null,o=new Di(a);for(let s=0;s<i.maxColumns;s++){let l=new xt(o);Ft.prototype.insertProperty.call(l,g.id,"{"+L.NewGuid()+"}"),l.setDisplayName(k.EmptyString,this.lcid),Ft.prototype.insertProperty.call(l,g.showlabel,"false"),o.addCell(l)}i.appendRow(o),t===b.formHeader?r.header=i:r.footer=i}}deSerializeFormXmlNode(t,r){if(t&&t.nodeValue&&(t.nodeType===Node.TEXT_NODE||t.nodeType===Node.CDATA_SECTION_NODE))return new Ft(`<${t.nodeValue}`,r);if(t.nodeType===Node.COMMENT_NODE)return;let n=this.createModelNode(t,r);return this.populateElementProperties(n,t.attributes),this.populateElementChildren(n,t.childNodes),n}populateElementProperties(t,r){if(!r){let n="attributes is undefined for element: "+t.getNodeName();throw(0,dm.trackErrorTrace)(yt,{eventName:pm,eventData:{error:n}}),new Error(n)}for(let n=0;n<r.length;n++){let i=r.item(n);i&&(Ft.prototype.insertProperty.call(t,i.name,i.value),t.getNodeName()===b.formCell&&i.name===g.auto&&i.value==="true"&&t.setAutoExpandDetailsForTab())}}populateElementChildren(t,r){for(let n=0;n<r.length;n++){let i=r.item(n),a=this.deSerializeFormXmlNode(i,t);a&&Ft.prototype.insertChild.call(t,a)}}createModelNode(t,r){switch(t.nodeName){case b.form:throw new Error("Form node shouldn't be created using this method");case b.formTab:return new mn(r);case b.formColumn:return new Xn(r);case b.formHeader:return new bs(r,!1);case b.formFooter:return new ys(r,!1);case b.formSection:return new Gr(b.formSection,r);case b.formRow:return new Di(r);case b.formCell:return new xt(r);case b.formControl:let n=t.attributes,i=t.childNodes.length>0?t.childNodes[0].childNodes:null,a;for(let s=0;s<n.length;s++){let l=n.item(s);if(l.name===g.indicationOfSubgrid&&l.value==="true"||l.name===g.classid&&(l.value?.toLocaleUpperCase()===`{${I.SubgridControl}}`||l.value?.toLocaleUpperCase()===`{${I.ReferencePanelSubgridControl}}`))a=er.Grid;else if(l.name===g.classid&&l.value?.toLocaleUpperCase()===`{${I.LookupControl}}`)a=er.Lookup;else if(l.name===g.classid&&l.value?.toLocaleUpperCase()===`{${I.CustomControl}}`)for(let u=0;u<i?.length;u++)i[u].nodeName===g.DefaultViewId&&(a=er.Lookup)}return a===er.Grid?new Ma(r):a===er.Lookup?new Ba(r):new wr(r);case b.formEvent:return new ka(r,k.EmptyString);case b.dependency:return this.populateDependencyTable(t),new Fa(r,k.EmptyString);case b.Handler:let o=[];return new xu(o,r);case b.formNavigation:return new Mu(t.nodeName,r);case b.formNavBarArea:return new qa(t.nodeName,r);case b.formNavBarAreas:return new Va(t.nodeName,r);case b.formNavBar:return new Lu(r);case b.formNavBarByRelationshipItem:return new Fu(r);case b.formNavBarItem:return new ku(r);case b.formDisplayConditions:return new Ou(r);case b.library:return new Ua(r,k.EmptyString,k.EmptyString);case b.controlDescription:return new Ql(r);case b.customControl:return this.populateCustomControlConfigurationId(t),new lu(r);default:return new Ft(t.nodeName,r)}}populateDependencyTable(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);i.name===g.id&&this.upsertFieldCount(i.value,Ur.DependencyFieldTable)}}populateCustomControlConfigurationId(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);if(i.name===g.id){let a=new L(i.value.substr(1,i.value.length-2));for(let o=0;o<t.parentNode.attributes.length;o++){let s=t.parentNode.attributes.item(o);if(s.name===g.ForControl){let l=s.value.substr(1,i.value.length-2);ze.CustomControlIdMap.upsert(l,a);break}}break}}}}});var YD={};Zr(YD,{SerializationService:()=>mm,SerializationServiceScope:()=>tG,SerializedFormElementNode:()=>Ga});var tG,Ga,mm,ZD=T(()=>{"use strict";ct();Ye();vr();om();tG="SerializationService",Ga=class extends j{fetchNodeName(){return this.getNodeName()}enumerateProperties(){return this.getAllProperties()}enumerateChildren(){return this.getAllChildren()}},mm=class{langCode;constructor(t){this.langCode=t}serializeFormXmlNode(t){let r=Ga.prototype.fetchNodeName.call(t);if(r.charAt(0)===pn.StartTag)return k.EscapeXml(r.substr(1),!1);if(t.isTransient&&!t.isDirty())return k.EmptyString;let n=Ga.prototype.enumerateProperties.call(t),i=Ga.prototype.enumerateChildren.call(t);if(!(t instanceof Ii)){let a=`<${r}`;if(n.length!==0&&(a+=` ${this.getPropertiesString(n)}`),i.length===0)a+=" />";else{let o=k.EmptyString;for(let s of i)o+=this.serializeFormXmlNode(s);a+=`>${o}</${r}>`}return a}return k.EmptyString}getPropertiesString(t){let r=k.EmptyString;return t.forEach((n,i)=>{i!==0&&(r+=" "),r+=`${n.key}="${k.EscapeXml(n.value,!0)}"`}),r}}});var zr=y(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.rejectUnknownKeys=pt.childObjects=pt.optionalGuidId=pt.optionalEnum=pt.eachObject=pt.issue=pt.isJsonObject=void 0;function eI(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}pt.isJsonObject=eI;function za(e,t,r,n){return n?{pointer:e,rule:t,message:r,fatal:n}:{pointer:e,rule:t,message:r}}pt.issue=za;function tI(e,t,r,n){if(!Array.isArray(e))return[];let i=[];return e.forEach((a,o)=>{eI(a)?i.push({node:a,index:o}):n.push(za(`${t}/${o}`,`${r}-must-be-object`,`a ${r} must be a JSON object, got ${a===null?"null":typeof a}`))}),i}pt.eachObject=tI;function rG(e,t,r,n,i,a){let o=e[t];o!==void 0&&(typeof o!="string"||!r.includes(o))&&a.push(za(`${n}/${t}`,i,`${t} must be one of ${r.map(s=>`'${s}'`).join(", ")}, got ${JSON.stringify(o)}`))}pt.optionalEnum=rG;var nG=/^(?:\{[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}\}|[0-9a-fA-F]{8}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{12})$/;function iG(e,t,r,n,i){let a=e[t];typeof a=="string"&&a!==""&&!nG.test(a)&&i.push(za(`${r}/${t}`,n,`${t} must be a GUID or empty, got '${a}'`))}pt.optionalGuidId=iG;function aG(e,t,r,n,i){let a=e[t],o=`${r}/${t}`;return a===void 0?[]:Array.isArray(a)?tI(a,o,n,i):(i.push(za(o,`${n}-list-must-be-array`,`${t} must be an array when present, got ${typeof a}`)),[])}pt.childObjects=aG;function oG(e,t,r,n,i,a={}){var o,s;for(let l of Object.keys(e)){if(t.has(l))continue;let u=(o=a.elsewhere)===null||o===void 0?void 0:o[l],c=(s=a.unsupported)===null||s===void 0?void 0:s[l],d=u?` '${l}' is a ${u} key \u2014 set it on the ${u} instead.`:c?` ${c}`:` Put values the typed layer does not model in '${n}.bag', which round-trips them verbatim.`;i.push(za(`${r}/${l}`,`${n}-unknown-key`,`'${l}' is not a ${n} property, and would be SILENTLY DROPPED at serialization.${d}`))}}pt.rejectUnknownKeys=oG});var gI=y(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.classIdForAttributeType=Mt.QUICK_VIEW_CLASS_ID=Mt.NOTES_CLASS_ID=Mt.SUBGRID_CLASS_ID=Mt.formRegistration=Mt.FormAdapter=void 0;var hn=(Ve(),_r(Eb)),sG=(Be(),_r(Sb)),lG=(Ye(),_r(Db)),ft=(Y(),_r(Nb)),Ue=(vi(),_r(Ib)),uG=(nm(),_r(XD)),cG=(ZD(),_r(YD)),We=Mn(),rI=hr(),kt=zr(),dG=up(),As=st(),bm=le(),lI=Un(),uI=Ji(),pG={[ft.FormType.Main]:"Main",[ft.FormType.QuickCreate]:"QuickCreate",[ft.FormType.QuickViewForm]:"QuickView",[ft.FormType.Card]:"Card"},hm={Main:ft.FormType.Main,QuickCreate:ft.FormType.QuickCreate,QuickView:ft.FormType.QuickViewForm,Card:ft.FormType.Card},fG=new Map(Object.entries(Ue.ControlClassId).map(([e,t])=>[String(t).toUpperCase(),e]));function cI(e){var t;return e&&(t=fG.get(e.toUpperCase()))!==null&&t!==void 0?t:"Unknown"}function Cs(e){return e.getAllProperties().map(t=>[t.key,t.value])}function Ti(e){let t=new Map;for(let r of e.getAllProperties())t.has(r.key)||t.set(r.key,r.value);return t}function dI(e,t){return e.getAllChildren().find(r=>r.getNodeName()===t)}function wm(e,t){var r,n;let i=dI(e,"labels");if(!i)return"";let a=i.getAllChildren().filter(s=>s.getNodeName()==="label"),o=(r=a.find(s=>Ti(s).get("languagecode")===String(t)))!==null&&r!==void 0?r:a[0];return o&&(n=Ti(o).get("description"))!==null&&n!==void 0?n:""}function mG(e){let t=dI(e,"parameters"),r={};if(!t)return r;for(let n of t.getAllChildren()){let i=n.getNodeName();if(i.charAt(0)==="<"||i.charAt(0)==="#")continue;let a=n.getAllChildren()[0],o=a?a.getNodeName():"";o.charAt(0)==="<"&&(o=o.substring(1)),r[i]=o}return r}function pI(e){return/^1+$/.test(e)&&e.length>=1&&e.length<=4?e.length:1}function gm(e){let t=Math.min(Math.max(Math.trunc(e),1),4);return"1".repeat(t)}function Es(e){return String(e??"").replace(/[{}]/g,"")}function vm(e){return`{${Es(e)}}`}function nI(e,t){if(e===void 0||e==="")return t;let r=Number(e);return Number.isNaN(r)?t:r}function Uu(e,t,r){let n=e.getAllChildren(),i=n.findIndex(u=>u.getNodeName()===t),a=[];if(n.forEach((u,c)=>{c!==i&&a.push({i:c,node:(0,We.rawFromNode)(u)})}),i<0)return{modeled:[],bag:{a:Cs(e),c:a}};let o=n[i],s=[],l=[];return o.getAllChildren().forEach((u,c)=>{u.getNodeName()===r?s.push(u):l.push({i:c,node:(0,We.rawFromNode)(u)})}),{modeled:s,bag:{a:Cs(e),c:a,w:{n:o.getNodeName(),a:Cs(o),c:l}}}}function fI(e,t,r){let n=[],i=[];return e.getAllChildren().forEach((a,o)=>{a.getNodeName()===t&&(!r||n.length===0)?n.push(a):i.push({i:o,node:(0,We.rawFromNode)(a)})}),{modeled:n,bag:{a:Cs(e),c:i}}}function hG(e,t){let{modeled:r,bag:n}=Uu(e,"tabs","tab");return{tabs:r.map(i=>gG(i,t)),bag:n}}function gG(e,t){var r,n;let i=Ti(e),{modeled:a,bag:o}=Uu(e,"columns","column");return{id:(r=i.get("id"))!==null&&r!==void 0?r:"",name:(n=i.get("name"))!==null&&n!==void 0?n:"",label:wm(e,t),expanded:i.get("expanded")==="true",visible:i.has("visible")?i.get("visible")==="true":!0,columns:a.map(s=>vG(s,t)),bag:o}}function vG(e,t){let r=Ti(e),{modeled:n,bag:i}=Uu(e,"sections","section");return{width:r.get("width"),sections:n.map(a=>yG(a,t)),bag:i}}function yG(e,t){var r,n,i;let a=Ti(e),{modeled:o,bag:s}=Uu(e,"rows","row");return{id:(r=a.get("id"))!==null&&r!==void 0?r:"",name:(n=a.get("name"))!==null&&n!==void 0?n:"",label:wm(e,t),visible:a.has("visible")?a.get("visible")==="true":!0,showLabel:a.get("showlabel")==="true",columns:pI((i=a.get("columns"))!==null&&i!==void 0?i:"1"),rows:o.map(l=>bG(l,t)),bag:s}}function bG(e,t){let{modeled:r,bag:n}=fI(e,"cell",!1);return{cells:r.map(i=>wG(i,t)),bag:n}}function wG(e,t){var r;let n=Ti(e),{modeled:i,bag:a}=fI(e,"control",!0),o=wm(e,t),s=n.get("showlabel")==="true",l=i[0]?AG(i[0],o,s):null;return{id:(r=n.get("id"))!==null&&r!==void 0?r:"",visible:n.has("visible")?n.get("visible")==="true":!0,colspan:nI(n.get("colspan"),1),rowspan:nI(n.get("rowspan"),1),control:l,bag:a}}function AG(e,t,r){var n,i;let a=Ti(e),o=Es((n=a.get("classid"))!==null&&n!==void 0?n:""),s=a.get("datafieldname");return{id:(i=a.get("id"))!==null&&i!==void 0?i:"",classId:o,fieldName:s||null,type:cI(o),isRequired:a.get("isrequired")==="true",isReadOnly:a.get("disabled")==="true",label:t,showLabel:r,parameters:mG(e),bag:{a:Cs(e),c:e.getAllChildren().map((l,u)=>({i:u,node:(0,We.rawFromNode)(l)}))}}}function ei(e){return e.a.length===0&&e.c.length===0&&!e.w}function mI(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function Pi(e,t){var r;let n=new Set(e.a.map(o=>o[0])),i=ei(e),a=[];for(let o of t)if(n.has(o.key)){let s=(r=mI(e,o.key))!==null&&r!==void 0?r:"";o.matches(s)||a.push([o.key,o.render()])}else i?a.push([o.key,o.render()]):o.matches(o.absentDefault)||a.push([o.key,o.render()]);return(0,We.mergeAttrs)(e.a,a)}var Yn=(e,t)=>({key:e,matches:r=>r===t,render:()=>t,absentDefault:""}),Zn=(e,t,r=!1)=>({key:e,matches:n=>n==="true"===t,render:()=>String(t),absentDefault:String(r)}),iI=(e,t,r=1)=>({key:e,matches:n=>Number(n)===t,render:()=>String(t),absentDefault:String(r)});function $u(e,t){return{n:"labels",a:[],c:[{n:"label",a:[["description",e],["languagecode",String(t)]],c:[]}]}}function ym(e){return{n:"parameters",a:[],c:Object.keys(e).map(t=>({n:(0,bm.assertXmlName)(t,"Form control parameter name"),a:[],c:[{n:`<${e[t]}`,a:[],c:[]}]}))}}function CG(e,t){var r,n;let i=e.c.find(o=>o.n==="label"&&o.a.some(s=>s[0]==="languagecode"&&s[1]===String(t))),a=i??e.c.find(o=>o.n==="label");return(n=(r=a?.a.find(o=>o[0]==="description"))===null||r===void 0?void 0:r[1])!==null&&n!==void 0?n:""}function EG(e,t,r){let n=!1,i=e.c.map(a=>a.n!=="label"||!a.a.some(s=>s[0]==="languagecode"&&s[1]===String(r))?a:(n=!0,{...a,a:a.a.map(s=>s[0]==="description"?["description",t]:s)}));return n||i.push({n:"label",a:[["description",t],["languagecode",String(r)]],c:[]}),{...e,c:i}}function Am(e,t,r){let n=e.c.findIndex(a=>a.node.n==="labels");if(n<0){if(!t||ei(e))return e;let o=e.c.some(s=>s.i===0)?e.c.map(s=>({...s,i:s.i+1})):e.c;return{...e,c:[{i:0,node:$u(t,r)},...o]}}if(CG(e.c[n].node,r)===t)return e;let i=EG(e.c[n].node,t,r);return{...e,c:e.c.map((a,o)=>o===n?{...a,node:i}:a)}}function SG(e){let t={};for(let r of e.c){let n=r.n;if(n.charAt(0)==="<"||n.charAt(0)==="#")continue;let i=r.c[0],a=i?i.n:"";a.charAt(0)==="<"&&(a=a.substring(1)),t[n]=a}return t}function NG(e,t){let r=Object.keys(e),n=Object.keys(t);return r.length===n.length&&r.every(i=>e[i]===t[i])}function DG(e,t){return e.a.some(r=>r[0]===t)?{...e,a:e.a.filter(r=>r[0]!==t)}:e}function IG(e,t){let r=e.c.findIndex(i=>i.node.n==="parameters");if(r<0){if(Object.keys(t).length===0||ei(e))return e;let i=e.c.reduce((a,o)=>o.i>a?o.i:a,-1);return{...e,c:[...e.c,{i:i+1,node:ym(t)}]}}if(NG(SG(e.c[r].node),t))return e;let n=ym(t);return{...e,c:e.c.map((i,a)=>a===r?{...i,node:n}:i)}}function qu(e,t,r,n){if(e.w){let o={n:e.w.n,a:e.w.a.map(s=>[s[0],s[1]]),c:(0,We.spliceChildren)(e.w.c,r)};return(0,We.spliceChildren)(e.c,[o])}let i=n(),a={n:t,a:[],c:r};return e.c.length===0?[...i,a]:(0,We.spliceChildren)(e.c,[...i,a])}function _G(e,t){let r=e.tabs.map(n=>TG(n,t));return{n:"form",a:Pi(e.bag,[]),c:e.tabs.length===0&&ei(e.bag)?[]:qu(e.bag,"tabs",r,()=>[])}}function TG(e,t){let r=[Yn("id",e.id),Yn("name",e.name),Zn("expanded",e.expanded),Zn("visible",e.visible,!0)],n=e.columns.map(a=>PG(a,t)),i=Am(e.bag,e.label,t);return{n:"tab",a:Pi(i,r),c:qu(i,"columns",n,()=>e.label?[$u(e.label,t)]:[])}}function PG(e,t){let r=e.width!==void 0?[Yn("width",e.width)]:[],n=e.sections.map(i=>RG(i,t));return{n:"column",a:Pi(e.bag,r),c:qu(e.bag,"sections",n,()=>[])}}function RG(e,t){let r=[Yn("id",e.id),Yn("name",e.name),Zn("showlabel",e.showLabel),Zn("visible",e.visible,!0),{key:"columns",matches:a=>pI(a)===e.columns,render:()=>gm(e.columns),absentDefault:gm(1)}],n=e.rows.map(a=>OG(a,t)),i=Am(e.bag,e.label,t);return{n:"section",a:Pi(i,r),c:qu(i,"rows",n,()=>e.label?[$u(e.label,t)]:[])}}function OG(e,t){let r=e.cells.map(n=>xG(n,t));return{n:"row",a:Pi(e.bag,[]),c:ei(e.bag)?r:(0,We.assembleChildren)(e.bag,r)}}function xG(e,t){let r=e.control?e.control.showLabel:mI(e.bag,"showlabel")==="true",n=[Yn("id",e.id),Zn("showlabel",r),Zn("visible",e.visible,!0),iI("colspan",e.colspan),iI("rowspan",e.rowspan)],i=e.control?[LG(e.control)]:[],a;if(ei(e.bag))a=[...e.control&&e.control.label?[$u(e.control.label,t)]:[],...i];else{let o=e.control?Am(e.bag,e.control.label,t):e.bag;a=(0,We.assembleChildren)(o,i)}return{n:"cell",a:Pi(e.bag,n),c:a}}function LG(e){let t=[Yn("id",e.id),{key:"classid",matches:i=>Es(i)===e.classId,render:()=>vm(e.classId),absentDefault:""}];e.fieldName!==null&&t.push(Yn("datafieldname",e.fieldName)),t.push(Zn("disabled",e.isReadOnly)),t.push(Zn("isrequired",e.isRequired));let r=e.fieldName===null?DG(e.bag,"datafieldname"):e.bag,n;return ei(r)?n=Object.keys(e.parameters).length>0?[ym(e.parameters)]:[]:n=(0,We.assembleChildren)(IG(r,e.parameters),[]),{n:"control",a:Pi(r,t),c:n}}var FG={make:(e,t)=>new lG.FormElementNode(e,t),setProp:(e,t,r)=>e.setProperty(t,r),addChild:(e,t)=>e.addChild(t)};function aI(e,t,r){(0,lI.installDomShim)();let n=MG(e,r),i=(0,We.rebuildRaw)(_G(n,t),FG,null);return new cG.SerializationService(t).serializeFormXmlNode(i)}function kG(e){return JSON.parse(JSON.stringify(e))}function MG(e,t){var r;let n=kG(e);n.bag||(n.bag=(0,We.emptyBag)()),WG(n.bag),t&&BG(n,t);for(let i of(r=n.tabs)!==null&&r!==void 0?r:[])UG(i);return n}function BG(e,t){var r;let n=(r=e.entityLogicalName)!==null&&r!==void 0?r:"";Cm(e,i=>{let a=i.fieldName,o=i;if(!a||o.label!==void 0&&o.classId!==void 0)return;let s=t.resolveField(n,a);s&&(o.label===void 0&&s.displayName&&(o.label=s.displayName),o.classId===void 0&&s.attributeType&&(o.classId=hI(s.attributeType)))})}function oI(e){let t=[];return Cm(e,r=>t.push(r)),t}function Cm(e,t){var r,n,i,a,o;for(let s of(r=e.tabs)!==null&&r!==void 0?r:[])for(let l of(n=s.columns)!==null&&n!==void 0?n:[])for(let u of(i=l.sections)!==null&&i!==void 0?i:[])for(let c of(a=u.rows)!==null&&a!==void 0?a:[])for(let d of(o=c.cells)!==null&&o!==void 0?o:[])d.control&&t(d.control)}function UG(e){e.id||(e.id=hn.Guid.NewGuid()),e.name===void 0&&(e.name=""),e.label===void 0&&(e.label=""),e.expanded===void 0&&(e.expanded=!0),e.visible===void 0&&(e.visible=!0),e.columns||(e.columns=[]);for(let t of e.columns)$G(t);e.bag||(e.bag=(0,We.emptyBag)())}function $G(e){e.sections||(e.sections=[]);for(let t of e.sections)qG(t);e.bag||(e.bag=(0,We.emptyBag)()),e.width===void 0&&ei(e.bag)&&(e.width="100%")}function qG(e){e.id||(e.id=hn.Guid.NewGuid()),e.name===void 0&&(e.name=""),e.label===void 0&&(e.label=""),e.showLabel===void 0&&(e.showLabel=!1),e.visible===void 0&&(e.visible=!0),e.columns===void 0&&(e.columns=1),e.rows||(e.rows=[]);for(let t of e.rows)VG(t);e.bag||(e.bag=(0,We.emptyBag)())}function VG(e){e.cells||(e.cells=[]);for(let t of e.cells)GG(t);e.bag||(e.bag=(0,We.emptyBag)())}function GG(e){e.id||(e.id=hn.Guid.NewGuid()),e.visible===void 0&&(e.visible=!0),e.colspan===void 0&&(e.colspan=1),e.rowspan===void 0&&(e.rowspan=1),e.control===void 0&&(e.control=null),e.control&&zG(e.control),e.bag||(e.bag=(0,We.emptyBag)())}function zG(e){var t;e.id||(e.id=hn.Guid.NewGuid()),e.classId===void 0&&(e.classId=String(Ue.ControlClassId.TextboxControl)),e.fieldName===void 0&&(e.fieldName=null),e.type===void 0&&(e.type=e.fieldName?"Field":cI(String(e.classId))),e.isRequired===void 0&&(e.isRequired=!1),e.isReadOnly===void 0&&(e.isReadOnly=!1),e.label===void 0&&(e.label=(t=e.fieldName)!==null&&t!==void 0?t:""),e.showLabel===void 0&&(e.showLabel=!0),(e.parameters===void 0||e.parameters===null)&&(e.parameters={});for(let r of Object.keys(e.parameters))(0,bm.assertXmlName)(r,"Form control parameter name");e.bag||(e.bag=(0,We.emptyBag)())}function WG(e){for(let t of e.c){let r=t.node;if(r.n==="events"){for(let n of r.c)if(n.n==="event"){for(let i of n.c)if(i.n==="Handlers")for(let a of i.c)a.n==="Handler"&&!sI(a,"handlerUniqueId")&&a.a.push(["handlerUniqueId",vm(hn.Guid.NewGuid())])}}else if(r.n==="formLibraries")for(let n of r.c)n.n==="Library"&&!sI(n,"libraryUniqueId")&&n.a.push(["libraryUniqueId",vm(hn.Guid.NewGuid())])}}var Bu=class{constructor(t=uI.DEFAULT_LCID){this.lcid=t}toArtifact(t,r){var n,i,a;let{tabs:o,bag:s}=hG(t,this.lcid);return{id:t.formId?t.formId.guidString:"",name:(n=t.formName)!==null&&n!==void 0?n:"",entityLogicalName:(i=t.entityName)!==null&&i!==void 0?i:"",formType:(a=pG[t.formType])!==null&&a!==void 0?a:"Main",status:this.readActivationStatus(t),...r!==void 0&&r!==""?{description:r}:{},tabs:o,bag:s}}fromArtifact(t){var r;return this.deserialize({formxml:aI(t,this.lcid),formid:t.id||(0,As.newId)(),objecttypecode:t.entityLogicalName,type:hm[t.formType],name:t.name,uniquename:t.name,description:(r=t.description)!==null&&r!==void 0?r:"",formpresentation:ft.FormPresentation.AirForm,formactivationstate:t.status==="Active"?ft.FormActivationState.Active:ft.FormActivationState.InActive})}fromApiResponse(t){var r,n,i,a,o,s,l;let u=t,c=this.deserialize({formxml:(r=u.formxml)!==null&&r!==void 0?r:"",formid:(n=u.formid)!==null&&n!==void 0?n:(0,As.newId)(),objecttypecode:(i=u.objecttypecode)!==null&&i!==void 0?i:"",type:u.type,name:(a=u.name)!==null&&a!==void 0?a:"",uniquename:(o=u.uniquename)!==null&&o!==void 0?o:"",description:(s=u.description)!==null&&s!==void 0?s:"",formpresentation:u.formpresentation,formactivationstate:u.formactivationstate});return this.toArtifact(c,(l=u.description)!==null&&l!==void 0?l:void 0)}toApiPayload(t,r,n){return{formxml:aI(t,this.lcid,n),name:t.name,type:hm[t.formType],objecttypecode:t.entityLogicalName,...t.description!==void 0?{description:t.description}:{}}}metadataNeeds(t){let r=t.entityLogicalName;if(!r)return[];let n=new Set,i=[];return Cm(t,a=>{let o=a.fieldName,s=a;!o||s.label!==void 0&&s.classId!==void 0||n.has(o)||(n.add(o),i.push({entityLogicalName:r,fieldName:o}))}),i}createDefault(t){var r,n,i,a,o,s,l,u,c,d,p;let f=t.tabs&&t.tabs.length>0?void 0:e8(this.lcid),m=f!==void 0?f:t.tabs.map(w=>jG(w,this.lcid)).join(""),h=this.deserialize({formxml:`<form><tabs>${m}</tabs></form>`,formid:t.id||(0,As.newId)(),objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",type:hm[(n=t.formType)!==null&&n!==void 0?n:"Main"],name:(i=t.name)!==null&&i!==void 0?i:"New Form",uniquename:(a=t.name)!==null&&a!==void 0?a:"New Form",description:(o=t.description)!==null&&o!==void 0?o:"",formpresentation:ft.FormPresentation.AirForm,formactivationstate:((s=t.status)!==null&&s!==void 0?s:"Active")==="Active"?ft.FormActivationState.Active:ft.FormActivationState.InActive}),v=this.toArtifact(h,t.description);if(t.tabs&&t.tabs.length>0){let w=oI(t);oI(v).forEach((C,E)=>{w[E]&&w[E].label===void 0&&delete C.label})}return{id:(l=t.id)!==null&&l!==void 0?l:v.id,name:(u=t.name)!==null&&u!==void 0?u:"New Form",entityLogicalName:(c=t.entityLogicalName)!==null&&c!==void 0?c:"",formType:(d=t.formType)!==null&&d!==void 0?d:"Main",status:(p=t.status)!==null&&p!==void 0?p:"Active",...t.description!==void 0?{description:t.description}:{},tabs:v.tabs,bag:v.bag}}assignMissingIds(t){return(0,As.assignMissingIds)(t)}validate(t){return u8(t)}deserialize(t){(0,lI.installDomShim)();let r=sG.ScriptUtilities.ParseXml(t.formxml),n=new uG.DeserializationService(this.lcid).deSerializeFormXml(r,new hn.Guid(t.formid),t.objecttypecode,ft.FormState.Draft,t.name,t.uniquename,t.type,t.formpresentation,t.description,t.formactivationstate);if(!n)throw new Error("FormXml could not be deserialized into a Form model.");return n}readActivationStatus(t){return t.formactivationstate===ft.FormActivationState.InActive?"Inactive":"Active"}};Mt.FormAdapter=Bu;function Ar(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Em(e,t){return e?`<labels><label description="${Ar(e)}" languagecode="${t}" /></labels>`:""}function Sm(e){return e&&e.length>0?Es(e):(0,As.newId)()}function jG(e,t){var r,n,i,a;let o=(r=e.columns)!==null&&r!==void 0?r:[],s=(o.length>0?o:[ZG()]).map(l=>HG(l,t)).join("");return`<tab id="{${Ar(Sm(e.id))}}" name="${Ar((n=e.name)!==null&&n!==void 0?n:"")}" expanded="${(i=e.expanded)!==null&&i!==void 0?i:!0}" visible="${(a=e.visible)!==null&&a!==void 0?a:!0}">${Em(e.label,t)}<columns>${s}</columns></tab>`}function HG(e,t){var r,n;let i=((r=e.sections)!==null&&r!==void 0?r:[]).map(a=>JG(a,t)).join("");return`<column width="${Ar((n=e.width)!==null&&n!==void 0?n:"100%")}"><sections>${i}</sections></column>`}function JG(e,t){var r,n,i,a,o;let s=((r=e.rows)!==null&&r!==void 0?r:[]).map(l=>KG(l,t)).join("");return`<section id="{${Ar(Sm(e.id))}}" name="${Ar((n=e.name)!==null&&n!==void 0?n:"")}" showlabel="${(i=e.showLabel)!==null&&i!==void 0?i:!1}" visible="${(a=e.visible)!==null&&a!==void 0?a:!0}" columns="${gm((o=e.columns)!==null&&o!==void 0?o:1)}">${Em(e.label,t)}<rows>${s}</rows></section>`}function KG(e,t){var r;return`<row>${((r=e.cells)!==null&&r!==void 0?r:[]).map(n=>QG(n,t)).join("")}</row>`}function QG(e,t){var r,n,i,a,o;let s=e.control,l=s?Em((r=s.label)!==null&&r!==void 0?r:"",t):"",u=s?XG(s):"";return`<cell id="{${Ar(Sm(e.id))}}" showlabel="${s?(n=s.showLabel)!==null&&n!==void 0?n:!0:!1}" visible="${(i=e.visible)!==null&&i!==void 0?i:!0}" colspan="${(a=e.colspan)!==null&&a!==void 0?a:1}" rowspan="${(o=e.rowspan)!==null&&o!==void 0?o:1}">${l}${u}</cell>`}function XG(e){var t,r,n;let i=e.fieldName?` datafieldname="${Ar(e.fieldName)}"`:"",a=YG(e.parameters),o=e.classId?Es(e.classId):String(Ue.ControlClassId.TextboxControl);return`<control id="${Ar((t=e.id)!==null&&t!==void 0?t:"")}" classid="{${Ar(o)}}"${i} disabled="${(r=e.isReadOnly)!==null&&r!==void 0?r:!1}" isrequired="${(n=e.isRequired)!==null&&n!==void 0?n:!1}">${a}</control>`}function YG(e){let t=Object.keys(e??{});return t.length===0?"":(t.forEach(n=>(0,bm.assertXmlName)(n,"Form control parameter name")),`<parameters>${t.map(n=>`<${n}>${Ar(e[n])}</${n}>`).join("")}</parameters>`)}function ZG(){return{width:"100%",sections:[],bag:{a:[],c:[]}}}function e8(e){return`<tab id="{${hn.Guid.NewGuid()}}" name="tab_general" expanded="true" visible="true"><labels><label description="General" languagecode="${e}" /></labels><columns><column width="100%"><sections><section id="{${hn.Guid.NewGuid()}}" name="section_general" showlabel="false" visible="true" columns="1"><labels><label description="General" languagecode="${e}" /></labels><rows></rows></section></sections></column></columns></tab>`}function t8(e=uI.DEFAULT_LCID){return{adapter:new Bu(e),api:dG.formApi,languageSensitive:!0,publish:(t,r,n)=>(0,rI.publishBoundEntity)(t,n),publishScope:(t,r)=>(0,rI.boundEntityPublishScope)(r)}}Mt.formRegistration=t8;var r8=new Set(["id","name","label","expanded","visible","columns","bag"]),n8=new Set(["id","width","sections","bag"]),i8=new Set(["id","name","label","visible","showLabel","columns","rows","bag"]),a8=new Set(["id","cells","bag"]),o8=new Set(["id","visible","colspan","rowspan","control","bag"]),s8=new Set(["id","classId","fieldName","type","isRequired","isReadOnly","label","showLabel","parameters","bag"]),l8={elsewhere:{isReadOnly:"control",isRequired:"control",fieldName:"control",classId:"control",label:"control",showLabel:"control",parameters:"control"},unsupported:{createOnly:"FormXml has no create-only concept; gate the field with a business rule instead. Raise it with the SDK owners if you need it modeled.",updateOnly:"FormXml has no update-only concept; gate the field with a business rule instead. Raise it with the SDK owners if you need it modeled."}};function u8(e){let t=[];return(0,kt.childObjects)(e,"tabs","","tab",t).forEach(({node:n,index:i})=>{let a=`/tabs/${i}`;(0,kt.rejectUnknownKeys)(n,r8,a,"tab",t),(0,kt.childObjects)(n,"columns",a,"column",t).forEach(({node:s,index:l})=>{let u=`${a}/columns/${l}`;(0,kt.rejectUnknownKeys)(s,n8,u,"column",t),(0,kt.childObjects)(s,"sections",u,"section",t).forEach(({node:d,index:p})=>{let f=`${u}/sections/${p}`;(0,kt.rejectUnknownKeys)(d,i8,f,"section",t),(0,kt.childObjects)(d,"rows",f,"row",t).forEach(({node:h,index:v})=>{let w=`${f}/rows/${v}`;(0,kt.rejectUnknownKeys)(h,a8,w,"row",t),(0,kt.childObjects)(h,"cells",w,"cell",t).forEach(({node:E,index:D})=>{let O=`${w}/cells/${D}`;(0,kt.rejectUnknownKeys)(E,o8,O,"cell",t,l8);let x=E.control;x!=null&&!(0,kt.isJsonObject)(x)?t.push((0,kt.issue)(`${O}/control`,"control-must-be-object-or-null",`a cell control must be a JSON object or null, got ${typeof x}`)):(0,kt.isJsonObject)(x)&&(0,kt.rejectUnknownKeys)(x,s8,`${O}/control`,"control",t)})})})})}),t}Mt.SUBGRID_CLASS_ID=Ue.ControlClassId.SubgridControl;Mt.NOTES_CLASS_ID=Ue.ControlClassId.TimelineControl;Mt.QUICK_VIEW_CLASS_ID=Ue.ControlClassId.QuickViewControl;var c8={Lookup:String(Ue.ControlClassId.LookupControl),Customer:String(Ue.ControlClassId.LookupControl),Owner:String(Ue.ControlClassId.LookupControl),PartyList:String(Ue.ControlClassId.PartyListControl),Boolean:String(Ue.ControlClassId.BooleanControl),DateTime:String(Ue.ControlClassId.DateTimeControl),Decimal:String(Ue.ControlClassId.DecimalControl),Double:String(Ue.ControlClassId.FloatingNumberControl),Money:String(Ue.ControlClassId.CurrencyControl),Integer:String(Ue.ControlClassId.IntegerControl),BigInt:String(Ue.ControlClassId.IntegerControl),Memo:String(Ue.ControlClassId.TextAreaControl),String:String(Ue.ControlClassId.TextboxControl)},d8="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE";function hI(e){return e==="Picklist"||e==="State"||e==="Status"?d8:e&&c8[e]||String(Ue.ControlClassId.TextboxControl)}Mt.classIdForAttributeType=hI;function sI(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}});var Nm=y(Wa=>{"use strict";Object.defineProperty(Wa,"__esModule",{value:!0});Wa.viewApi=Wa.findDefaultViews=void 0;var yI=$t(),tr=Ee(),gn=le(),p8="savedqueryid,name,description,fetchxml,layoutxml,querytype,returnedtypecode,isdefault",f8="savedqueryid,name,returnedtypecode,querytype,isdefault";async function m8(e,t,r={}){var n;let i=new Set(((n=r.excludeViewIds)!==null&&n!==void 0?n:[]).filter(Boolean)),a=`returnedtypecode eq '${(0,gn.odataLiteral)(t)}' and querytype eq 0`,o=`/savedqueries${(0,gn.odataQuery)([["$select","savedqueryid,name,isdefault"],["$filter",a]])}`;return(await(0,yI.collectPages)(e,o,`findDefaultViews('${t}')`)).filter(l=>{var u;return l.savedqueryid&&!i.has(l.savedqueryid)&&(l.isdefault||/^(Active|Inactive)\b/i.test((u=l.name)!==null&&u!==void 0?u:""))}).map(l=>{var u;return{id:String(l.savedqueryid),name:String((u=l.name)!==null&&u!==void 0?u:"")}})}Wa.findDefaultViews=m8;async function h8(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,gn.odataPathLiteral)(t)}')${(0,gn.odataQuery)([["$select","ObjectTypeCode"]])}`,i=await e.get(n);if(i.status>=200&&i.status<300){let a=(r=i.body)===null||r===void 0?void 0:r.ObjectTypeCode;return typeof a=="number"?a:void 0}}async function vI(e,t,r){if(!r||!/<grid\b/.test(t)||/<grid[^>]*\bobject=/.test(t))return t;let n=await h8(e,r);return n===void 0?t:t.replace(/<grid\b/,`<grid object="${n}"`)}Wa.viewApi={async get(e,t){let n=`/savedqueries(${(0,gn.normalizeGuid)(t,"id")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,gn.odataQuery)([["$select",p8]]),i=(0,tr.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,tr.readEtag)(i)}},async list(e,t){let r=`/savedqueries${(0,gn.odataQuery)([["$select",f8],["$filter",t?.entityLogicalName?`returnedtypecode eq '${(0,gn.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,yI.collectPages)(e,r,"listArtifacts('view')")).map(i=>{var a,o;return{type:"view",id:(a=i.savedqueryid)!==null&&a!==void 0?a:"",name:(o=i.name)!==null&&o!==void 0?o:"",entityLogicalName:i.returnedtypecode,isDirty:!1}})},async create(e,t,r){let n=t,i=(0,tr.echoWrite)("savedqueryid"),a=`/savedqueries${i.query}`,o=await vI(e,n.layoutxml,n.returnedtypecode),s=(0,tr.ensureSuccess)(await e.post(a,(0,tr.withClientMintedId)({name:n.name,description:n.description,fetchxml:n.fetchxml,layoutxml:o,returnedtypecode:n.returnedtypecode,querytype:n.querytype,isdefault:n.isdefault},"savedqueryid",r),i.options),e.apiUrl(a));return{id:(0,tr.resolveCreatedId)(s,"savedqueryid","view",r),etag:(0,tr.readEtag)(s)}},async update(e,t,r,n){let i=r,a=(0,gn.normalizeGuid)(t,"id"),o=(0,tr.echoWrite)("savedqueryid",{"If-Match":(0,tr.requireEtag)(n,"view",a)}),s=`/savedqueries(${a})${o.query}`,l=await vI(e,i.layoutxml,i.returnedtypecode),u=(0,tr.ensureSuccess)(await e.patch(s,{name:i.name,description:i.description,fetchxml:i.fetchxml,layoutxml:l},o.options),e.apiUrl(s));return{id:a,etag:(0,tr.readEtag)(u)}},delete(e,t){return(0,tr.deleteRecord)(e,"savedqueries",t)}}});var xI=y(ja=>{"use strict";Object.defineProperty(ja,"__esModule",{value:!0});ja.viewRegistration=ja.ViewAdapter=void 0;var NI=ee(),zt=zr(),Dm=Mn(),Ri=mi(),bI=hr(),g8=Nm(),Im=Un(),v8=st(),DI=100,Gu=class{toArtifact(t){var r,n,i,a,o,s,l,u;(0,Im.installDomShim)();let c=(r=t.fetchxml)!==null&&r!==void 0?r:"",d=(n=t.layoutxml)!==null&&n!==void 0?n:"",p=(0,Ri.parseXmlRoot)(c,"<fetch/>"),f=(0,Ri.parseXmlRoot)(d,"<grid/>"),m=_I(p);return{id:(i=t.savedqueryid)!==null&&i!==void 0?i:"",name:(a=t.name)!==null&&a!==void 0?a:"",description:(o=t.description)!==null&&o!==void 0?o:"",entityLogicalName:(s=t.returnedtypecode)!==null&&s!==void 0?s:b8(p),queryType:(l=t.querytype)!==null&&l!==void 0?l:0,isDefault:(u=t.isdefault)!==null&&u!==void 0?u:!1,columns:II(f,p),filters:PI(p),sort:TI(p),...m.length>0?{linkEntities:m}:{},fetchBag:c?(0,Ri.projectElementBag)(p):void 0,layoutBag:d?(0,Ri.projectElementBag)(f):void 0}}fromArtifact(t){(0,Im.installDomShim)();let{fetchxml:r,layoutxml:n}=wI(t);return{savedqueryid:t.id,name:t.name,description:t.description,returnedtypecode:t.entityLogicalName,querytype:t.queryType,isdefault:t.isDefault,fetchxml:r,layoutxml:n}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t){var r,n,i,a,o;(0,Im.installDomShim)();let{fetchxml:s,layoutxml:l}=wI(t);return{name:(r=t.name)!==null&&r!==void 0?r:"",description:(n=t.description)!==null&&n!==void 0?n:"",fetchxml:s,layoutxml:l,returnedtypecode:(i=t.entityLogicalName)!==null&&i!==void 0?i:"",querytype:(a=t.queryType)!==null&&a!==void 0?a:0,isdefault:(o=t.isDefault)!==null&&o!==void 0?o:!1}}createDefault(t){var r,n,i,a,o,s,l,u;let c=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,v8.newId)(),name:(i=t.name)!==null&&i!==void 0?i:"New View",description:(a=t.description)!==null&&a!==void 0?a:"",entityLogicalName:c,queryType:(o=t.queryType)!==null&&o!==void 0?o:0,isDefault:(s=t.isDefault)!==null&&s!==void 0?s:!1,columns:t.columns&&t.columns.length>0?t.columns:[{name:`${c}id`,width:300,order:0}],filters:(l=t.filters)!==null&&l!==void 0?l:{type:"and",conditions:[],groups:[]},sort:(u=t.sort)!==null&&u!==void 0?u:[],...t.linkEntities&&t.linkEntities.length>0?{linkEntities:t.linkEntities}:{}}}assignMissingIds(t){return t}validate(t){let r=[],n=t;(0,zt.childObjects)(n,"columns","","column",r),(0,zt.childObjects)(n,"sort","","sort",r),(0,zt.childObjects)(n,"linkEntities","","linkEntity",r),y8(n.linkEntities,r);let i=n.filters;return i!=null&&((0,zt.isJsonObject)(i)?_m(i,"/filters",r):r.push((0,zt.issue)("/filters","filters-must-be-object",`filters must be a JSON object, got ${typeof i}`))),r}};ja.ViewAdapter=Gu;function y8(e,t){Array.isArray(e)&&e.forEach((r,n)=>{if(!(0,zt.isJsonObject)(r))return;for(let a of["name","from","to"]){let o=r[a];(typeof o!="string"||o.trim()==="")&&t.push((0,zt.issue)(`/linkEntities/${n}/${a}`,"linkentity-needs-keys",`a join needs a non-empty '${a}' \u2014 'from'/'to' are what DEFINE the relationship, and a link without them is unresolvable. Got ${JSON.stringify(o)}.`))}let i=r.filters;i!=null&&((0,zt.isJsonObject)(i)?_m(i,`/linkEntities/${n}/filters`,t):t.push((0,zt.issue)(`/linkEntities/${n}/filters`,"filters-must-be-object",`filters must be a JSON object, got ${typeof i}`)))})}function _m(e,t,r){(0,zt.childObjects)(e,"conditions",t,"condition",r),(0,zt.childObjects)(e,"groups",t,"filterGroup",r).forEach(({node:i,index:a})=>_m(i,`${t}/groups/${a}`,r))}function b8(e){var t;let r=e.getElementsByTagName("entity")[0];return(t=r?.getAttribute("name"))!==null&&t!==void 0?t:""}function II(e,t){var r;let n=Tm(t),i=e.getElementsByTagName("cell"),a=[],o=0;for(let s=0;s<i.length;s+=1){let l=i[s];if(l.getAttribute("ishidden")==="1")continue;let u=l.getAttribute("name");if(!u)continue;let c=parseInt((r=l.getAttribute("width"))!==null&&r!==void 0?r:"",10),d={name:u,width:Number.isNaN(c)?DI:c,order:o},p=n.get(u);p&&(d.relatedEntity=p.linkKey,p.attributeName&&p.attributeName!==u&&(d.sourceAttribute=p.attributeName)),o+=1,a.push(d)}return a}function Tm(e){let t=new Map,r=e.getElementsByTagName("link-entity");for(let n=0;n<r.length;n+=1){let i=r[n],a=i.getAttribute("name");if(!a)continue;let o=i.getElementsByTagName("attribute");for(let s=0;s<o.length;s+=1){let l=o[s],u=l.getAttribute("name")||"",c=l.getAttribute("alias")||u;c&&t.set(c,{linkKey:i.getAttribute("alias")||a,linkName:a,attributeName:u,link:i})}}return t}function _I(e){let t=e.getElementsByTagName("entity")[0];if(!t)return[];let r=[];for(let n of mt(t,"link-entity")){let i=n.getAttribute("name"),a=n.getAttribute("from"),o=n.getAttribute("to");if(!i||!a||!o)continue;let s=n.getAttribute("alias"),l=n.getAttribute("link-type"),u=mt(n,"filter").find(c=>!zu(c));r.push({name:i,from:a,to:o,...s?{alias:s}:{},...l==="inner"||l==="outer"?{linkType:l}:{},...u?{filters:Pm(u)}:{}})}return r}function TI(e){var t;let r=e.getElementsByTagName("entity")[0];if(!r)return[];let n=[],i=r.childNodes;for(let a=0;a<i.length;a+=1){let o=i[a];if(o.nodeType===1&&o.tagName==="order"){let s=o.getAttribute("attribute");s&&n.push({attribute:s,descending:((t=o.getAttribute("descending"))!==null&&t!==void 0?t:"").toLowerCase()==="true",entityname:o.getAttribute("entityname")||""})}}return n}function PI(e){let t=e.getElementsByTagName("entity")[0],r={type:"and",conditions:[],groups:[]};if(!t)return r;let n=mt(t,"filter").filter(i=>!zu(i)).map(Pm);return n.length===0?r:n.length===1?n[0]:{type:"and",conditions:[],groups:n}}function zu(e){if(e.getAttribute("isquickfindfields")==="1")return!0;if(mt(e,"filter").length>0)return!1;let t=mt(e,"condition");return t.length===0?!1:t.some(r=>r.getAttribute("isquickfindfields")==="1"||mt(r,"value").length>0||A8(r))}var w8=new Set(["attribute","operator","value","entityname","uiname","uitype"]);function A8(e){var t;let r=e.attributes;for(let n=0;n<r.length;n+=1){let i=(t=r[n])===null||t===void 0?void 0:t.name;if(i&&!w8.has(i))return!0}return!1}function Pm(e){var t,r;let n=((t=e.getAttribute("type"))!==null&&t!==void 0?t:"and").toLowerCase()==="or"?"or":"and",i=[],a=[],o=e.childNodes;for(let s=0;s<o.length;s+=1){let l=o[s];if(l.nodeType===1)if(l.tagName==="condition"){if(l.getAttribute("isquickfindfields")==="1")continue;let u=l.getAttribute("attribute");if(!u)continue;let c={attribute:u,operator:(r=l.getAttribute("operator"))!==null&&r!==void 0?r:""},d=l.getAttribute("value");d!==null&&(c.value=d);let p=l.getAttribute("entityname")||"";p&&(c.entityname=p),i.push(c)}else l.tagName==="filter"&&a.push(Pm(l))}return{type:n,conditions:i,groups:a}}function mt(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let a=n[i];a.nodeType===1&&a.tagName===t&&r.push(a)}return r}var Rm=e=>{var t,r;return`${(t=e.relatedEntity)!==null&&t!==void 0?t:""}::${(r=e.sourceAttribute)!==null&&r!==void 0?r:e.name}`};function C8(e,t){let r=Tm(e),n=new Map;for(let i of t){if(!i.relatedEntity)continue;let a=r.get(i.name);if(a){let o=Rm(i),s=n.get(o);s?s.push(a.link):n.set(o,[a.link])}}return n}function E8(e,t,r,n){if(!n||n.size===0)return;let i=new Set,a=t.getElementsByTagName("link-entity");for(let s=0;s<a.length;s+=1)i.add(a[s]);let o=r.filter(s=>{if(!s.relatedEntity)return!1;let l=n.get(Rm(s));return!!l&&l.some(u=>!i.has(u))});if(o.length!==0)throw new NI.ValidationError("view",e.id,o.map(s=>(0,zt.issue)(`/columns/${r.indexOf(s)}`,"view-column-orphaned-by-join-removal",`column '${s.name}' came from a join this push REMOVED. Another join matching '${s.relatedEntity}' still exists, but nothing can say whether it is the one the column belonged to \u2014 re-attaching it there would silently change the data the column shows. Remove the column too, keep the join it came from, or point the column at the join you want by setting relatedEntity to that join's alias.`)))}function wI(e){let t=S8(e.columns);if(!AI(e.fetchBag)||!AI(e.layoutBag))return{fetchxml:k8({...e,columns:t}),layoutxml:M8({...e,columns:t},`${e.entityLogicalName}id`)};let r=new DOMParser().parseFromString("<root/>","text/xml"),n=CI(e.fetchBag,"fetch",r),i=CI(e.layoutBag,"grid",r),a=II(i,n),o=!Vu(t,a),s=!Vu(e.sort,TI(n)),l=!Vu(e.filters,PI(n)),u=e.linkEntities,c=u!==void 0&&!Vu(u,_I(n)),d=c?C8(n,a):void 0;return c&&x8(r,n,u),c&&(F8(e,n,t,d),E8(e,n,t,d)),o?(EI(r,n,t,a),_8(r,i,t)):c&&EI(r,n,t,a),s&&R8(r,n,e.sort),l&&O8(r,n,e.filters),{fetchxml:(0,Ri.serializeNode)(n),layoutxml:(0,Ri.serializeNode)(i)}}function S8(e){return(e??[]).map((t,r)=>{var n,i;return{name:String(t.name).toLowerCase(),width:(n=t.width)!==null&&n!==void 0?n:DI,order:(i=t.order)!==null&&i!==void 0?i:r,...t.relatedEntity?{relatedEntity:t.relatedEntity}:{},...t.sourceAttribute?{sourceAttribute:String(t.sourceAttribute).toLowerCase()}:{}}})}function AI(e){return!!e&&(e.c.length>0||e.a.length>0)}function CI(e,t,r){let n={n:t,a:(0,Dm.mergeAttrs)(e.a,[]),c:(0,Dm.spliceChildren)(e.c,[])};return(0,Dm.rebuildRaw)(n,(0,Ri.domEngine)(r),null)}function EI(e,t,r,n){var i,a;let o=t.getElementsByTagName("entity")[0];if(!o)return;let s=d=>{var p,f;return`${(p=d.relatedEntity)!==null&&p!==void 0?p:""}:${d.name}:${(f=d.sourceAttribute)!==null&&f!==void 0?f:d.name}`},l=new Set(r.map(s));for(let d of n)l.has(s(d))||N8(o,d);let u=Tm(t),c=new Set(mt(o,"attribute").map(d=>d.getAttribute("name")).filter(d=>!!d));for(let d of[...r].sort((p,f)=>p.order-f.order))if(d.relatedEntity){let p=u.get(d.name);if(p&&p.attributeName===((i=d.sourceAttribute)!==null&&i!==void 0?i:d.name)&&(p.linkKey===d.relatedEntity||p.linkName===d.relatedEntity||!OI(o,d.relatedEntity)))continue;let f=D8(e,o,d.relatedEntity),m=e.createElement("attribute");RI(m,d),f.appendChild(m),u.set(d.name,{linkKey:d.relatedEntity,linkName:f.getAttribute("name")||d.relatedEntity,attributeName:(a=d.sourceAttribute)!==null&&a!==void 0?a:d.name,link:f})}else{if(c.has(d.name))continue;let p=e.createElement("attribute");p.setAttribute("name",d.name),I8(o,p),c.add(d.name)}}function RI(e,t){if(t.sourceAttribute&&t.sourceAttribute!==t.name){e.setAttribute("name",t.sourceAttribute),e.setAttribute("alias",t.name);return}e.setAttribute("name",t.name)}function N8(e,t){if(t.relatedEntity){for(let r of mt(e,"link-entity"))if(!(r.getAttribute("alias")!==t.relatedEntity&&r.getAttribute("name")!==t.relatedEntity)){for(let n of mt(r,"attribute"))if((n.getAttribute("alias")||n.getAttribute("name"))===t.name){r.removeChild(n);return}}return}for(let r of mt(e,"attribute"))if(r.getAttribute("name")===t.name){e.removeChild(r);return}}function OI(e,t,r=!1){let n=a=>a.getAttribute("alias")===t||a.getAttribute("name")===t;for(let a of mt(e,"link-entity"))if(n(a))return a;if(r)return;let i=e.getElementsByTagName("link-entity");for(let a=0;a<i.length;a+=1)if(n(i[a]))return i[a]}function D8(e,t,r){let n=OI(t,r);if(n)return n;let i=e.createElement("link-entity");return i.setAttribute("name",r),t.appendChild(i),i}function I8(e,t){let r=e.childNodes;for(let n=0;n<r.length;n+=1){let i=r[n];if(i.nodeType===1&&i.tagName!=="attribute"){e.insertBefore(t,i);return}}e.appendChild(t)}function _8(e,t,r){let n=t.getElementsByTagName("row")[0];if(!n)return;let i=[...r].sort((s,l)=>s.order-l.order),a=T8(n);if(P8(a,i)){for(let s=0;s<i.length;s+=1){let l=String(i[s].width);a[s].getAttribute("width")!==l&&a[s].setAttribute("width",l)}return}let o=new Map;for(let s of a){let l=s.getAttribute("name");l&&o.set(l,s),n.removeChild(s)}for(let s of i){let l=o.get(s.name);l||(l=e.createElement("cell"),l.setAttribute("name",s.name)),l.setAttribute("width",String(s.width)),n.appendChild(l)}}function T8(e){return mt(e,"cell").filter(t=>!!t.getAttribute("name")&&t.getAttribute("ishidden")!=="1")}function P8(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r].getAttribute("name")!==t[r].name)return!1;return!0}function R8(e,t,r){let n=t.getElementsByTagName("entity")[0];if(!n)return;let i=(p,f)=>`${p.toLowerCase()}\0${f.toLowerCase()}`,a=new Map,o=new Map,s=(p,f,m)=>{let h=p.get(f);h?h.push(m):p.set(f,[m])};for(let p of mt(n,"order")){let f=p.getAttribute("attribute")||"";f&&(s(a,i(p.getAttribute("entityname")||"",f),p),s(o,f.toLowerCase(),p)),n.removeChild(p)}let l=new Set,u=(p,f)=>{let m=p.get(f);for(;m&&m.length>0;){let h=m.shift();if(!l.has(h))return l.add(h),h}},c=p=>{var f;let m=o.get(p.toLowerCase());if(!m)return;let h=m.filter(w=>!l.has(w)),v=(f=h.find(w=>!w.getAttribute("entityname")))!==null&&f!==void 0?f:h[0];return v&&l.add(v),v},d=r.map(p=>{let f=String(p.attribute);return p.entityname===void 0?{expression:p,element:void 0}:{expression:p,element:u(a,i(p.entityname,f))}});for(let p of d)p.expression.entityname===void 0&&(p.element=c(String(p.expression.attribute)));for(let{expression:p,element:f}of d){let m=f??e.createElement("order");m.setAttribute("attribute",p.attribute),m.setAttribute("descending",String(p.descending)),p.entityname?m.setAttribute("entityname",p.entityname):p.entityname===""&&m.removeAttribute("entityname"),n.appendChild(m)}}function O8(e,t,r){let n=t.getElementsByTagName("entity")[0];if(n){for(let i of mt(n,"filter"))zu(i)||n.removeChild(i);(r.conditions.length>0||r.groups.length>0)&&n.appendChild(Ss(e,r))}}function Vu(e,t){return JSON.stringify(e)===JSON.stringify(t)}function x8(e,t,r){var n;let i=t.getElementsByTagName("entity")[0];if(!i)return;let a=mt(i,"link-entity").filter(m=>m.getAttribute("name")&&m.getAttribute("from")&&m.getAttribute("to")),o=(m,h)=>m.getAttribute(h)||"",s=new Array(r.length),l=new Set,u=m=>{r.forEach((h,v)=>{if(s[v])return;let w=a.filter(D=>!l.has(D)&&m(D,h));if(w.length!==1)return;let C=w[0];r.some((D,O)=>O!==v&&!s[O]&&m(C,D))||(s[v]=C,l.add(C))})};u((m,h)=>!!h.alias&&o(m,"name")===h.name&&o(m,"alias")===h.alias),u((m,h)=>o(m,"name")===h.name&&o(m,"from")===h.from&&o(m,"to")===h.to),u((m,h)=>o(m,"name")===h.name&&o(m,"from")===h.from),u((m,h)=>o(m,"name")===h.name&&o(m,"to")===h.to),u((m,h)=>o(m,"name")===h.name);let c=r.map((m,h)=>h).filter(m=>!s[m]),d=a.filter(m=>!l.has(m)),p=new Map;for(let m of d){let h=p.get(o(m,"name"));h?h.push(m):p.set(o(m,"name"),[m])}let f=new Map;for(let m of c){let h=f.get(r[m].name);h?h.push(m):f.set(r[m].name,[m])}for(let[m,h]of f){let v=(n=p.get(m))!==null&&n!==void 0?n:[];v.length===h.length&&h.forEach((w,C)=>{s[w]=v[C],l.add(v[C])})}r.forEach((m,h)=>{let v=s[h];if(v){SI(e,v,m);return}let w=e.createElement("link-entity");SI(e,w,m),i.appendChild(w)});for(let m of a)l.has(m)||i.removeChild(m)}var L8=new Set(["inner","outer"]);function F8(e,t,r,n){if(!t.getElementsByTagName("entity")[0])return;let a=new Set,o=t.getElementsByTagName("link-entity");for(let c=0;c<o.length;c+=1){let d=o[c],p=d.getAttribute("name"),f=d.getAttribute("alias");p&&a.add(p),f&&a.add(f)}let s=new Set;for(let c=0;c<o.length;c+=1)s.add(o[c]);let l=c=>{let d=n?.get(Rm(c));return!!d&&d.every(p=>s.has(p))},u=r.filter(c=>c.relatedEntity&&!a.has(c.relatedEntity)&&!l(c));if(u.length!==0)throw new NI.ValidationError("view",e.id,u.map(c=>{var d;let p=((d=e.linkEntities)!==null&&d!==void 0?d:[]).some(f=>f.name===c.relatedEntity||f.alias===c.relatedEntity);return(0,zt.issue)(`/columns/${r.indexOf(c)}`,"view-column-dangling-link",`column '${c.name}' has relatedEntity '${c.relatedEntity}', but no matching join remains in linkEntities. `+(p?"Remove the column too, or keep the join.":"That join is NESTED (a join off a join), which the typed layer does not model, so it cannot be re-declared in linkEntities \u2014 it only survives while the join above it does. Remove the column, or restore the parent join this push replaced."))}))}function SI(e,t,r){t.setAttribute("name",r.name),t.setAttribute("from",r.from),t.setAttribute("to",r.to),r.alias?t.setAttribute("alias",r.alias):t.removeAttribute("alias"),r.linkType?t.setAttribute("link-type",r.linkType):L8.has(t.getAttribute("link-type")||"")&&t.removeAttribute("link-type");let n=mt(t,"filter").find(a=>!zu(a)),i=r.filters&&(r.filters.conditions.length>0||r.filters.groups.length>0)?Ss(e,r.filters):null;n&&i?t.replaceChild(i,n):n?t.removeChild(n):i&&t.appendChild(i)}function k8(e){var t;let r=new DOMParser().parseFromString("<fetch/>","text/xml"),n=r.documentElement;n.setAttribute("version","1.0"),n.setAttribute("mapping","logical");let i=r.createElement("entity");i.setAttribute("name",e.entityLogicalName),n.appendChild(i);let a=new Map;for(let o of(t=e.linkEntities)!==null&&t!==void 0?t:[]){let s=r.createElement("link-entity");s.setAttribute("name",o.name),s.setAttribute("from",o.from),s.setAttribute("to",o.to),o.alias&&s.setAttribute("alias",o.alias),o.linkType&&s.setAttribute("link-type",o.linkType),o.filters&&(o.filters.conditions.length>0||o.filters.groups.length>0)&&s.appendChild(Ss(r,o.filters)),i.appendChild(s);for(let l of[o.alias||o.name,o.name])a.has(l)||a.set(l,s)}for(let o of[...e.columns].sort((s,l)=>s.order-l.order)){let s=r.createElement("attribute");if(o.relatedEntity){RI(s,o);let l=a.get(o.relatedEntity);l||(l=r.createElement("link-entity"),l.setAttribute("name",o.relatedEntity),i.appendChild(l),a.set(o.relatedEntity,l)),l.appendChild(s)}else s.setAttribute("name",o.name),i.appendChild(s)}for(let o of e.sort){let s=r.createElement("order");s.setAttribute("attribute",o.attribute),s.setAttribute("descending",String(o.descending)),o.entityname&&s.setAttribute("entityname",o.entityname),i.appendChild(s)}return(e.filters.conditions.length>0||e.filters.groups.length>0)&&i.appendChild(Ss(r,e.filters)),new XMLSerializer().serializeToString(r)}function Ss(e,t){let r=e.createElement("filter");r.setAttribute("type",t.type);for(let n of t.conditions){let i=e.createElement("condition");i.setAttribute("attribute",n.attribute),i.setAttribute("operator",n.operator),n.entityname&&i.setAttribute("entityname",n.entityname),n.value!==void 0&&i.setAttribute("value",n.value),r.appendChild(i)}for(let n of t.groups)r.appendChild(Ss(e,n));return r}function M8(e,t){var r;let n=new DOMParser().parseFromString("<grid/>","text/xml"),i=n.documentElement,a=[...e.columns].sort((s,l)=>s.order-l.order);i.setAttribute("name","resultset"),i.setAttribute("jump",((r=a[0])===null||r===void 0?void 0:r.name)||t||`${e.entityLogicalName}id`),i.setAttribute("select","1"),i.setAttribute("icon","1"),i.setAttribute("preview","1");let o=n.createElement("row");o.setAttribute("name","result"),o.setAttribute("id",t||`${e.entityLogicalName}id`),i.appendChild(o);for(let s of a){let l=n.createElement("cell");l.setAttribute("name",s.name),l.setAttribute("width",String(s.width)),o.appendChild(l)}return new XMLSerializer().serializeToString(n)}function B8(){return{adapter:new Gu,api:g8.viewApi,publish:(e,t,r)=>(0,bI.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,bI.boundEntityPublishScope)(t)}}ja.viewRegistration=B8});function Wu(e,t){return e==="SetFieldValue"&&t!==void 0&&U8.has(t.attributeType)&&(t.requiredLevel==="None"||t.requiredLevel==="Recommended")}var U8,Om=T(()=>{"use strict";U8=new Set(["Integer","Double","Decimal","Money","String","Memo","DateTime","Picklist","Lookup"])});function LI(e){return e!=="Entity"&&e!=="AllForms"&&typeof e=="string"&&e.trim()!==""}function xm(e){return e==="AllForms"||LI(e)?1:2}function Lm(e){return LI(e)?e:null}function FI(e,t){return{"@odata.type":"#Microsoft.Dynamics.CRM.workflow",name:e.name,description:e.description,workflowid:t,ondemand:!1,subprocess:!1,triggeroncreate:!1,triggerondelete:!1,category:Ha.WorkflowCategory.BusinessRule,type:Ha.WorkflowTypeCode.Definition,mode:1,scope:Ha.WorkflowScope.Organization,primaryentity:e.entityLogicalName,iscrmuiworkflow:!0,processtriggerscope:xm(e.scope),processtriggerformid:Lm(e.scope)}}var Ha,kI=T(()=>{"use strict";Ha=se(si());});function MI(e,t=0){return(at[e[t+0]]+at[e[t+1]]+at[e[t+2]]+at[e[t+3]]+"-"+at[e[t+4]]+at[e[t+5]]+"-"+at[e[t+6]]+at[e[t+7]]+"-"+at[e[t+8]]+at[e[t+9]]+"-"+at[e[t+10]]+at[e[t+11]]+at[e[t+12]]+at[e[t+13]]+at[e[t+14]]+at[e[t+15]]).toLowerCase()}var at,BI=T(()=>{at=[];for(let e=0;e<256;++e)at.push((e+256).toString(16).slice(1))});function Fm(){return ju>Hu.length-16&&((0,UI.randomFillSync)(Hu),ju=0),Hu.slice(ju,ju+=16)}var UI,Hu,ju,$I=T(()=>{UI=require("crypto"),Hu=new Uint8Array(256),ju=Hu.length});var qI,km,VI=T(()=>{qI=require("crypto"),km={randomUUID:qI.randomUUID}});function $8(e,t,r){if(km.randomUUID&&!t&&!e)return km.randomUUID();e=e||{};let n=e.random??e.rng?.()??Fm();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){if(r=r||0,r<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let i=0;i<16;++i)t[r+i]=n[i];return t}return MI(n)}var At,GI=T(()=>{VI();$I();BI();At=$8});var Mm=T(()=>{GI()});var zI=T(()=>{"use strict";});var Bm=y(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.WorkflowConditionOperator=rr.WorkflowAttributeType=rr.SystemStep=rr.FieldRequiredLevelTypes=rr.AttributeDateTimeBehavior=void 0;rr.AttributeDateTimeBehavior={None:0,Dynamic:1,DateOnly:2,StaticTimeZoneInvariant:3,UserLocal:4};rr.FieldRequiredLevelTypes={None:"0",Required:"1",Recommended:"2"};rr.SystemStep={IdentifyContact:"IdentifyContact",IdentifyAccount:"IdentifyAccount",IdentifyCustomer:"IdentifyCustomer",IdentifyCase:"IdentifyCase",Solution:"Solution",Resolve:"Resolve"};rr.WorkflowAttributeType={Boolean:"0",Customer:"1",DateTime:"2",Decimal:"3",Float:"4",Integer:"5",Lookup:"6",Money:"7",Owner:"8",PartyList:"9",Picklist:"10",Key:"11",State:"12",Status:"13",String:"14",UniqueIdentifier:"15",EntityNameReference:"16",Entity:"17",EntityCollection:"18",BpfProcess:"19",BpfStageCategory:"20",BpfStage:"21",EntityReferenceCollection:"22",MultiSelectPicklist:"23",BigType:"24"};rr.WorkflowConditionOperator={IsNull:"0",NotNull:"1",LogicalAnd:"2",LogicalOr:"3",IN:"4",NotIn:"5",NotInNull:"51",Equal:"6",NotEqual:"7",Contains:"8",DoesNotContain:"9",BeginsWith:"10",DoesNotBeginWith:"11",EndsWith:"12",DoesNotEndWith:"13",GreaterThan:"14",GreaterThanOrEqual:"15",LessThan:"16",LessThanOrEqual:"17",EqualUserId:"18",NotEqualUserId:"19",On:"20",NotOn:"21",OnOrAfter:"22",OnOrBefore:"23",Yesterday:"24",Today:"25",Tomorrow:"26",NextSevenDays:"27",LastSevenDays:"28",NextWeek:"29",LastWeek:"30",ThisWeek:"31",NextMonth:"32",LastMonth:"33",ThisMonth:"34",NextYear:"35",LastYear:"36",ThisYear:"37",Anytime:"38",LastXHours:"39",NextXHours:"40",LastXDays:"41",NextXDays:"42",LastXWeeks:"43",NextXWeeks:"44",LastXMonths:"45",NextXMonths:"46",LastXYears:"47",NextXYears:"48",Under:"49",NotUnder:"50"}});function JI(e){switch(e){case"Boolean":return Ce.WorkflowAttributeType.Boolean;case"Customer":return Ce.WorkflowAttributeType.Customer;case"DateTime":return Ce.WorkflowAttributeType.DateTime;case"Decimal":return Ce.WorkflowAttributeType.Decimal;case"Double":return Ce.WorkflowAttributeType.Float;case"Integer":return Ce.WorkflowAttributeType.Integer;case"Lookup":return Ce.WorkflowAttributeType.Lookup;case"Money":return Ce.WorkflowAttributeType.Money;case"Owner":return Ce.WorkflowAttributeType.Owner;case"Picklist":return Ce.WorkflowAttributeType.Picklist;case"State":return Ce.WorkflowAttributeType.State;case"Status":return Ce.WorkflowAttributeType.Status;case"Uniqueidentifier":case"UniqueIdentifier":return Ce.WorkflowAttributeType.UniqueIdentifier;case"BigInt":return Ce.WorkflowAttributeType.BigType;default:return Ce.WorkflowAttributeType.String}}function t_(e){return e&&e!==Ce.WorkflowAttributeType.String?e:void 0}function G8(e){return{__class:e_,parameterName:"primaryEntity",entityName:e}}function WI(e){return{__class:$m,type:Um,typeSet:!1,behavior:Ce.AttributeDateTimeBehavior.None,method:KI,parameters:[e]}}function jI(e,t,r=Ce.WorkflowAttributeType.String){return{__class:XI,type:r,behavior:Ce.AttributeDateTimeBehavior.None,typeSet:!1,entity:G8(t),attributeName:e}}function z8(e,t=Ce.WorkflowAttributeType.String){return{__class:YI,type:t,behavior:Ce.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function W8(e){return{__class:ZI,type:Um,typeSet:!1,behavior:Ce.AttributeDateTimeBehavior.None,days:e,hours:"0",minutes:"0",months:"0",years:"0"}}function r_(e,t){let r=q8[e.operator],n=WI(jI(e.leftField,t,e.leftWorkflowType)),i;e.dateArithmetic?i=W8(e.right.value??"0"):e.right.kind==="field"?i=jI(e.right.field??"",t,e.right.workflowType):i=z8(e.right.value??"",e.right.workflowType??e.leftWorkflowType);let a=WI(i);return{__class:$m,type:Um,typeSet:!1,behavior:Ce.AttributeDateTimeBehavior.None,method:QI,parameters:[r,n,a]}}function n_(e){return typeof e=="object"&&e.__class===$m}function j8(e){return typeof e=="object"&&e.__class===ZI}function Ju(e){return n_(e)&&e.method===KI&&e.parameters.length>0?Ju(e.parameters[0]):e}function HI(e){if(typeof e!="object"||e.__class!==XI)return null;let t=e.entity;if(t&&t.__class&&t.__class!==e_)return null;let r=e.attributeName;return r?{field:r,workflowType:t_(e.type)}:null}function i_(e){if(!e)return null;let t=Ju(e);if(!n_(t)||t.method!==QI||t.parameters.length!==3)return null;let r=t.parameters[0],n=V8[String(r)];if(!n)return null;let i=HI(Ju(t.parameters[1]));if(!i)return null;let a=Ju(t.parameters[2]);if(j8(a))return n!=="+"&&n!=="-"?null:{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:String(a.days??"")},dateArithmetic:!0};let o=HI(a);if(o)return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"field",field:o.field,workflowType:o.workflowType}};if(typeof a=="object"&&a.__class===YI){let s=a.primitiveValue;return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:s!=null?String(s):"",workflowType:t_(a.type)}}}return null}function Vm(e){let t=(e??"").trim();if(!/^\d+$/.test(t))return!1;let r=Number(t);return Number.isSafeInteger(r)&&r>=qm&&r<=Ja}function Oi(e){if(!e||!e.leftField)return"incomplete";if(e.right.kind==="field")return e.right.field&&e.right.field.trim()?null:"incomplete";let t=e.right.value;return!t||!t.trim()?"incomplete":e.dateArithmetic&&!Vm(t)?"invalidDayCount":null}function Ka(e){return Oi(e)===null}var Ce,KI,QI,Um,XI,YI,$m,ZI,e_,q8,V8,qm,Ja,Ns=T(()=>{"use strict";Ce=se(Bm());KI="0",QI="3",Um="0",XI="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",YI="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",$m="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",ZI="TimeSpanExpression:#Microsoft.Crm.Workflow.Expressions",e_="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions";q8={"+":0,"-":1,"*":2,"/":3},V8={0:"+",1:"-",2:"*",3:"/"};qm=0,Ja=2147483647});function J8(e){return e.startsWith("__")&&!H8.has(e)}function K8(e){let t=Object.create(null);return Object.keys(e).forEach(r=>{J8(r)&&(t[r]=e[r])}),Object.keys(t).length>0?t:void 0}function h_(e){return e.__class==="BinaryExpression:#Microsoft.Crm.Workflow.Expressions"}function Is(e){return e.__class==="UnaryExpression:#Microsoft.Crm.Workflow.Expressions"}function Gm(e){return h_(e)||Is(e)}function Q8(e){return e.__class==="ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel"}function Ds(){return{list:[]}}function zm(e,t,r){return e&&e.list.length>0?{list:[{...e.list[0],description:t},...e.list.slice(1)]}:{list:[{labelId:At(),languageCode:r,description:t}]}}function Hm(e){return{__class:"PrimaryEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:"primaryEntity",entityName:e}}function Yu(e,t,r){return{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,entity:Hm(t),attributeName:e}}function Xa(e,t){return{__class:"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",type:t,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function Z8(e){return e.bpfField==="StageCategory"?e.stageType==="SelectedStage"?y_:v_:g_}function b_(e){return e.bpfField==="StageCategory"?z.WorkflowAttributeType.BpfStageCategory:z.WorkflowAttributeType.BpfProcess}function e6(e,t){let r=b_(e),n=e.bpfField==="StageCategory"?{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,entity:{__class:"RelatedEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:`related_${o_}_${a_}`,entityName:a_,relatedAttributeName:o_},attributeName:Y8}:Yu(X8,t,r);return{__class:"MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,method:Jm,parameters:[Z8(e),n]}}function t6(e){let t=e;if(t.__class!=="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"||String(t.method)!==Jm)return null;let r=(t.parameters??[])[0];if(typeof r!="string")return null;let n=r.replace(/^"+|"+$/g,"");return n===v_?{bpfField:"StageCategory",stageType:"ActiveStage"}:n===y_?{bpfField:"StageCategory",stageType:"SelectedStage"}:n===g_?{bpfField:"ProcessName"}:null}function Ku(e){if(!e)return!1;let t=e;if(t.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"&&String(t.method)===Jm){let r=(t.parameters??[])[0];if(typeof r=="string"&&r6.has(r.replace(/^"+|"+$/g,"")))return!0}return Is(e)?Ku(e.operand):h_(e)?Ku(e.left)||(e.right??[]).some(Ku):!1}function w_(e){return{__class:"LookupExpression:#Microsoft.Crm.Workflow.Expressions",type:e.workflowType??z.WorkflowAttributeType.Lookup,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,entityType:e.entityType,label:e.label??"",staticValue:Xa(e.id.replace(/[{}]/g,""),z.WorkflowAttributeType.UniqueIdentifier)}}function s_(e){return e==="ContainsData"||e==="DoesNotContainData"}function l_(e,t){return{__class:"UnaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:t,operand:e}}function u_(e,t){let r=e.valueType==="Lookup"?e.lookupValue?.workflowType??z.WorkflowAttributeType.Lookup:e.valueWorkflowType??z.WorkflowAttributeType.String,n=jm[e.operator]??z.WorkflowConditionOperator.Equal;if(e.source==="BusinessProcess"){let o=e6(e,t);if(s_(e.operator))return l_(o,n);let s=b_(e);return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:o,right:[Xa(e.value??"",s)]}}let i=Yu(e.field,t,r);if(s_(e.operator))return l_(i,n);let a;if(e.valueType==="Field"&&e.valueField)a=[Yu(e.valueField,t,r)];else if(e.valueType==="Lookup"){if(!e.lookupValue)throw new Error("Lookup condition is missing its record value.");a=[w_(e.lookupValue)]}else e.valueType==="Clear"?a=[Xa(null,r)]:e.valueType==="Expression"?a=[Xu(e.valueType,e.value,e.valueField,t,e.expression,e.rawExpression)]:a=[Xa(e.value??"",r)];return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:i,right:a}}function n6(e,t,r){if(e.length===0)return null;let n=u_(e[0],r);for(let i=1;i<e.length;i++){let a=e[i].connector??t;n={__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:a==="AND"?z.WorkflowConditionOperator.LogicalAnd:z.WorkflowConditionOperator.LogicalOr,left:n,right:[u_(e[i],r)]}}return n}function Qu(e){if(!e)return{valueType:"Value",value:""};if(e.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions")return{valueType:"Field",valueField:e.attributeName};if(e.__class==="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions")return e.primitiveValue==null?{valueType:"Clear",valueWorkflowType:e.type}:{valueType:"Value",value:e.primitiveValue!=null?String(e.primitiveValue):""};if(e.__class==="LookupExpression:#Microsoft.Crm.Workflow.Expressions"){let t=e.staticValue,r=typeof t=="object"&&t?.__class==="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"?t.primitiveValue:t;return{valueType:"Lookup",lookupValue:{entityType:e.entityType,id:String(r??""),label:e.label,...e.type!==z.WorkflowAttributeType.Lookup?{workflowType:e.type}:{}}}}if(e.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"){let t=i_(e);return t?{valueType:"Expression",expression:t}:{valueType:"Expression",rawExpression:e}}return{valueType:"Value",value:""}}function i6(e){let t=m_[e.conditionOperatoroperator]??"Equals",r=t==="ContainsData"||t==="DoesNotContainData",n=Is(e)?e.operand:e.left,i=Is(e)?[]:e.right,a=t6(n);if(a){let d=i[0];return{id:At(),field:"",fieldDisplayName:"",source:"BusinessProcess",bpfField:a.bpfField,...a.stageType?{stageType:a.stageType}:{},operator:t,valueType:"Value",value:d?.primitiveValue!=null&&!r?String(d.primitiveValue):""}}let o=n.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",s=n.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions"?n.attributeName:"",l=o?n.type:void 0,u=r?{valueType:"Value"}:Qu(i[0]),c=u.valueWorkflowType??l;return{id:At(),field:s,fieldDisplayName:s,operator:t,...u,...c?{valueWorkflowType:c}:{}}}function c_(e){if(!e||!Gm(e))return{clauses:[],logic:"AND"};let t=[],r=(a,o)=>{let s=a.conditionOperatoroperator;if(Is(a)||s!==z.WorkflowConditionOperator.LogicalAnd&&s!==z.WorkflowConditionOperator.LogicalOr){t.push({...i6(a),...o?{connector:o}:{}});return}let l=s===z.WorkflowConditionOperator.LogicalAnd?"AND":"OR";Gm(a.left)&&r(a.left,o),a.right.filter(Gm).forEach(u=>r(u,l))};r(e,void 0);let i=t.slice(1).map(a=>a.connector??"AND")[0]??"AND";return{clauses:t,logic:i}}function Xu(e,t,r,n,i,a,o,s){if(e==="Field"&&r)return Yu(r,n,z.WorkflowAttributeType.String);if(e==="Expression"){if(i)return r_(i,n);if(a!=null)return a}return e==="Lookup"&&o?w_(o):e==="Clear"?Xa(null,s??z.WorkflowAttributeType.String):Xa(t??"",z.WorkflowAttributeType.String)}function Wm(e,t){return{propertyName:e,propertyValueExpr:t}}function Qa(e){return`Step_${e.value++}`}function nr(e,t){let r=(t.counts[e]??0)+1,n=`${e}${r}`;for(;t.used.has(n);)r+=1,n=`${e}${r}`;return t.counts[e]=r,t.used.add(n),n}function d_(e,t,r){return e&&!r.used.has(e)?(r.used.add(e),e):nr(t,r)}function a6(e){return e===f_.StateCode.Activated?"Active":"Draft"}function o6(e,t){let r=e.processtriggerscope,n=e.processtriggerformid;return r===1?n&&n.trim()!==""?n:"AllForms":r===2?"Entity":t??"Entity"}function A_(e,t=1033){return new Ya({languageCode:t}).serialize(e)}function C_(e){return new Ya().deserialize(e)}var f_,z,H8,jm,m_,Jm,g_,v_,y_,X8,Y8,a_,o_,r6,Km,Ya,Qm=T(()=>{"use strict";Mm();f_=se(si());zI();Ns();z=se(Bm());H8=new Set(["__class"]);jm={Equals:z.WorkflowConditionOperator.Equal,DoesNotEqual:z.WorkflowConditionOperator.NotEqual,IsGreaterThan:z.WorkflowConditionOperator.GreaterThan,IsLessThan:z.WorkflowConditionOperator.LessThan,IsGreaterThanEqualTo:z.WorkflowConditionOperator.GreaterThanOrEqual,IsLessThanEqualTo:z.WorkflowConditionOperator.LessThanOrEqual,Contains:z.WorkflowConditionOperator.Contains,DoesNotContain:z.WorkflowConditionOperator.DoesNotContain,BeginsWith:z.WorkflowConditionOperator.BeginsWith,DoesNotBeginWith:z.WorkflowConditionOperator.DoesNotBeginWith,EndsWith:z.WorkflowConditionOperator.EndsWith,DoesNotEndWith:z.WorkflowConditionOperator.DoesNotEndWith,On:z.WorkflowConditionOperator.On,NotOn:z.WorkflowConditionOperator.NotOn,ContainsData:z.WorkflowConditionOperator.NotNull,DoesNotContainData:z.WorkflowConditionOperator.IsNull},m_={};for(let e of Object.keys(jm))m_[jm[e]]=e;Jm="23",g_="BpfProcess",v_="ActiveStageCategory",y_="SelectedStageCategory",X8="processid",Y8="stagecategory",a_="processstage",o_="stageid";r6=new Set(["ActiveStage","SelectedStage","Stage"]);Km={setFieldValue:"Set Field Value",setDefaultValue:"Set Default Value",lockUnlock:"Lock/Unlock",setBusinessRequired:"Set Business Required",setVisibility:"Set Visibility",recommendation:"Recommendation",showErrorMessage:"Show Error Message",condition:"Condition"};Ya=class{resolveLabel;languageCode;entityName="";stepCounter={value:0};idCounter={counts:{},used:new Set};constructor(t={}){this.resolveLabel=t.resolveLabel??(r=>Km[r]),this.languageCode=t.languageCode??1033}label(t){return this.resolveLabel(t)}serialize(t){let r=t.wfomRoot;this.entityName=t.entityLogicalName,this.stepCounter={value:r?Number(r.nextStepIndex):1},this.idCounter={counts:{},used:new Set};let n=t.scope!=="Entity"&&t.scope!=="AllForms"?t.scope:null,i=t.rootCondition?[this.serializeConditionNode(t.rootCondition)]:[],a={...r?.reservedProperties??{},__class:"WorkflowStep:#Microsoft.Crm.Workflow.ObjectModel",id:r?.id??t.ruleId??At(),name:r?.name??"Step_0",description:r!==void 0?r.description:t.description||null,stepLabels:Ds(),argumentsArray:[],primaryEntityName:r?.primaryEntityName??this.entityName,nextStepIndex:String(this.stepCounter.value),isCrmUIWorkflow:!0,category:r?.category??"2",businessProcessType:r?.businessProcessType??"0",mode:r?.mode??"0",title:r?.title??t.name,formId:n,workflowEntityId:r?.workflowEntityId??t.ruleId??"",variables:r?.variables??[],inputs:r?.inputs??[],steps:{list:i}};return JSON.stringify(a)}makeApplyActionStep(t){return{__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",id:nr("SetAttributeValueStep",this.idCounter),description:t.displayName||"New Action",name:t.stepName??Qa(this.stepCounter),stepLabels:{list:[]},specification:Wm(t.field,Xu(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType)),entity:Hm(this.entityName)}}makeRecommendationActionStep(t,r,n){let i=r.map(l=>this.makeApplyActionStep(l)),a=t??"",o=n?.stepLabels,s=zm(o,a,this.languageCode);return{__class:"ActionStep:#Microsoft.Crm.Workflow.ObjectModel",id:d_(n?.id,"ActionStep",this.idCounter),name:n?.name??Qa(this.stepCounter),description:n?.description??"Action step",stepLabels:s,steps:{list:i},actionId:null,actionType:n?.actionType??"4",processId:n?.processId??At(),uniqueName:n?.uniqueName??`id_${At().replace(/-/g,"")}ActionStep`}}serializeAction(t){let r=Hm(this.entityName),n=t.stepName??Qa(this.stepCounter),i=t.stepLabels??Ds(),a={name:n,stepLabels:i,description:t.displayName},o=t.type;switch(o){case"SetFieldValue":return{...a,id:nr("SetAttributeValueStep",this.idCounter),__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:Wm(t.field,Xu(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"SetDefaultValue":return{...a,id:nr("SetDefaultValueStep",this.idCounter),__class:"SetDefaultValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:Wm(t.field,Xu(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"LockUnlock":return{...a,id:nr("SetDisplayModeStep",this.idCounter),__class:"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isReadOnly:t.lock,entity:r};case"SetBusinessRequired":return{...a,id:nr("SetFieldRequiredLevelStep",this.idCounter),__class:"SetFieldRequiredLevelStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",requiredLevel:t.required?z.FieldRequiredLevelTypes.Required:z.FieldRequiredLevelTypes.None,entity:r};case"SetVisibility":return{...a,id:nr("SetVisibilityStep",this.idCounter),__class:"SetVisibilityStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isVisible:t.visible,entity:r};case"ShowErrorMessage":{let s=t.errorMessage||t.displayName,l=zm(t.stepLabels,s,this.languageCode);return{...a,id:nr("SetMessageStep",this.idCounter),__class:"SetMessageStep:#Microsoft.Crm.Workflow.ObjectModel",stepLabels:l,name:s,controlId:t.field,entity:r,level:t.messageLevel??"error",actionSteps:t.messageActionSteps??{list:[]}}}case"Recommendation":{let s=t.messageText??t.recommendationTitle??t.displayName,l=zm(t.stepLabels,s,this.languageCode),u={list:[this.makeRecommendationActionStep(t.acceptanceText,t.applyActions??[],t.recommendationActionStepMeta)]};return{...a,id:nr("SetMessageStep",this.idCounter),__class:"SetMessageStep:#Microsoft.Crm.Workflow.ObjectModel",stepLabels:l,description:t.recommendationTitle||t.displayName,controlId:t.field,entity:r,level:"RECOMMENDATION",actionSteps:u}}default:throw new Error(`Unsupported action type: ${o}`)}}serializeConditionNode(t){let r=t.stepName??Qa(this.stepCounter),n=nr("ConditionStep",this.idCounter),i=[],a=t,o=!0;for(;a;){let s=a.rawConditionExpression??n6(a.clauses,a.logic,this.entityName),l=o?a.branchName??Qa(this.stepCounter):Qa(this.stepCounter),c={__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:o?d_(a.branchId,"ConditionBranchStep",this.idCounter):nr("ConditionBranchStep",this.idCounter),name:l,description:a.displayName,stepLabels:Ds(),conditionExpression:s??void 0,steps:{list:a.trueBranch.map(p=>this.serializeBranchItem(p))}};i.push(c);let d=a.falseBranch;if(d.length===1&&d[0].kind==="condition"){a=d[0],o=!1;continue}d.length>0&&i.push(this.makeTerminalElseBranch(d)),a=void 0}return{__class:"ConditionStep:#Microsoft.Crm.Workflow.ObjectModel",id:n,name:r,description:"",stepLabels:Ds(),containsElsebranch:i.length>1,steps:{list:i}}}makeTerminalElseBranch(t){return{__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:nr("ConditionBranchStep",this.idCounter),name:"Else",description:null,stepLabels:Ds(),conditionExpression:void 0,steps:{list:t.map(r=>this.serializeBranchItem(r))}}}serializeBranchItem(t){return t.kind==="condition"?this.serializeConditionNode(t):this.serializeAction(t)}deserialize(t){let r=t,n=null,i;if(t.wfomJson)try{let a=JSON.parse(t.wfomJson);i={id:a.id==="WorkflowStep0"||!a.id?t.workflowid??At():a.id,name:a.name,description:a.description,nextStepIndex:a.nextStepIndex,category:a.category==="0"||a.category===0?"2":a.category,businessProcessType:a.businessProcessType,mode:a.mode,title:a.title||t.name||"",primaryEntityName:a.primaryEntityName==="1"||!a.primaryEntityName?t.primaryentity??"":a.primaryEntityName,workflowEntityId:a.workflowEntityId==="00000000-0000-0000-0000-000000000000"||!a.workflowEntityId?t.workflowid??"":a.workflowEntityId,formId:a.formId,variables:a.variables,inputs:a.inputs,reservedProperties:K8(a)};let s=(a.steps?.list??[]).find(l=>l.__class==="ConditionStep:#Microsoft.Crm.Workflow.ObjectModel");s&&(n=this.deserializeConditionStep(s))}catch{}return{ruleId:t.workflowid??null,name:t.name??"",description:t.description??"",entityLogicalName:t.primaryentity??"",scope:o6(r,i?.formId),status:a6(t.statecode),rootCondition:n,wfomRoot:i}}deserializeConditionStep(t){let r=(t.steps?.list??[]).filter(Q8);return this.buildConditionNodeFromBranches(r,t,!0)}buildConditionNodeFromBranches(t,r,n){let[i,...a]=t,{clauses:o,logic:s}=c_(i?.conditionExpression),l=this.deserializeBranch(i?.steps?.list??[]),u=this.deserializeElseChain(a,r),c=i?.description||i?.name||r.description||r.name||this.label("condition");return{kind:"condition",id:(n?r.id:i?.id)??At(),displayName:c,clauses:o,logic:s,trueBranch:l,falseBranch:u,isCollapsed:!1,stepName:n?r.name:void 0,branchId:n?i?.id:void 0,branchName:n?i?.name:void 0,...Ku(i?.conditionExpression)?{rawConditionExpression:i?.conditionExpression}:{}}}deserializeElseChain(t,r){if(t.length===0)return[];let[n]=t,{clauses:i}=c_(n.conditionExpression);return i.length===0?this.deserializeBranch(n.steps?.list??[]):[this.buildConditionNodeFromBranches(t,r,!1)]}deserializeBranch(t){return t.map(r=>r.__class==="ConditionStep:#Microsoft.Crm.Workflow.ObjectModel"?this.deserializeConditionStep(r):this.deserializeAction(r)).filter(r=>r!==null)}parseRecommendationApplyActions(t){let n=(t?.list??[])[0];if(!n)return{applyActions:[]};let i={id:n.id,name:n.name,description:n.description??void 0,stepLabels:n.stepLabels,processId:n.processId,uniqueName:n.uniqueName,actionType:n.actionType},a=n.stepLabels?.list,o=a&&a.length>0?a[0].description??"":"";return{applyActions:(n.steps?.list??[]).filter(l=>l.__class==="SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel").map(l=>{let u=l.specification;return{id:l.id||At(),field:u?.propertyName??"",stepName:l.name??void 0,displayName:l.description??void 0,...Qu(u?.propertyValueExpr)}}),meta:i,acceptanceText:o}}deserializeAction(t){switch(t.__class){case"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=Qu(t.specification.propertyValueExpr);return{kind:"action",id:t.id,type:"SetFieldValue",displayName:t.description||t.name||this.label("setFieldValue"),stepName:t.name,stepLabels:t.stepLabels,field:t.specification.propertyName,...r}}case"SetDefaultValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=Qu(t.specification.propertyValueExpr);return{kind:"action",id:t.id,type:"SetDefaultValue",displayName:t.description||t.name||this.label("setDefaultValue"),stepName:t.name,stepLabels:t.stepLabels,field:t.specification.propertyName,...r}}case"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel":return{kind:"action",id:t.id,type:"LockUnlock",displayName:t.description||t.name||this.label("lockUnlock"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,lock:t.isReadOnly};case"SetFieldRequiredLevelStep:#Microsoft.Crm.Workflow.ObjectModel":return{kind:"action",id:t.id,type:"SetBusinessRequired",displayName:t.description||t.name||this.label("setBusinessRequired"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,required:t.requiredLevel!==z.FieldRequiredLevelTypes.None};case"SetVisibilityStep:#Microsoft.Crm.Workflow.ObjectModel":return{kind:"action",id:t.id,type:"SetVisibility",displayName:t.description||t.name||this.label("setVisibility"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,visible:t.isVisible};case"SetMessageStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=t.stepLabels?.list,n=r&&r.length>0?r[0].description??"":"";if((t.level??"").toUpperCase()==="RECOMMENDATION"){let{applyActions:i,meta:a,acceptanceText:o}=this.parseRecommendationApplyActions(t.actionSteps);return{kind:"action",id:t.id,type:"Recommendation",displayName:t.description||this.label("recommendation"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,recommendationTitle:t.description||"",messageText:n,acceptanceText:o,applyActions:i,recommendationActionStepMeta:a}}return{kind:"action",id:t.id,type:"ShowErrorMessage",displayName:t.description||this.label("showErrorMessage"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,errorMessage:n||t.name||"",messageLevel:t.level??void 0,messageActionSteps:t.actionSteps}}case"ActionStep:#Microsoft.Crm.Workflow.ObjectModel":{let{applyActions:r,meta:n,acceptanceText:i}=this.parseRecommendationApplyActions({list:[t]});return{kind:"action",id:t.id,type:"Recommendation",displayName:t.name||this.label("recommendation"),stepName:t.name,stepLabels:t.stepLabels,field:t.actionControl?.controlId??"",recommendationTitle:t.name||"",messageText:t.description||"",acceptanceText:i,applyActions:r,recommendationActionStepMeta:n}}default:return null}}}});var E_=T(()=>{"use strict";});function ti(e){return!s6.has(e)}function I_(e){return e==="Equals"||e==="DoesNotEqual"}function Zu(e){return N_.has(e)?l6:f6.has(e)?u6:D_.has(e)?c6:h6.has(e)?p6:d6}function __(e){return Zu(e)[0]}function T_(e,t){return Zu(t).includes(e)}function S_(e){return N_.has(e)?"string":e==="Money"?"money":e==="Integer"||e==="BigInt"?"integer":e==="Decimal"||e==="Double"?"decimal":D_.has(e)?"date":m6.has(e)?"boolean":"other"}function ec(e,t){let r=S_(e),n=S_(t);return r==="other"||n==="other"?e===t:r===n}var s6,l6,u6,c6,d6,p6,N_,f6,D_,m6,h6,Xm=T(()=>{"use strict";E_();s6=new Set(["ContainsData","DoesNotContainData"]);l6=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],u6=["Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],c6=["On","NotOn","Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],d6=["Equals","DoesNotEqual","ContainsData","DoesNotContainData"],p6=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],N_=new Set(["String","Memo","EntityName"]),f6=new Set(["Integer","BigInt","Money","Decimal","Double"]),D_=new Set(["DateTime"]),m6=new Set(["Boolean"]),h6=new Set(["Lookup","Owner","Customer"])});function th(e){return g6.has(e.type)}function Ym(e,t,r,n,i,a,o){let s=i.get(r);!s||!v6.has(s.attributeType)||n!=="Value"||o?.operator&&!I_(o.operator)||a.push({nodeId:e,kind:"INVALID_VALUE_TYPE_FOR_FIELD",message:`${t}: please select a record for this lookup field; a typed text value cannot be saved.`,target:o?.target,itemId:o?.itemId,messageKey:"Validation.InvalidValueTypeForField",messageParams:{label:t}})}function Zm(e){return!!(e?.entityType?.trim()&&e.id?.trim())}function eh(e,t,r){return{nodeId:e,kind:"INVALID_DAY_COUNT",message:`Please enter a whole number of days between 0 and ${Ja}.`,target:t,itemId:r,messageKey:"Validation.InvalidDayCount",messageParams:{max:Ja}}}function P_(e,t,r,n,i,a,o,s){if(i!=="Clear")return;let l=a.get(n);Wu(r,l)||o.push({nodeId:e,kind:"INVALID_CLEAR_FOR_FIELD",message:`${t}: Clear is only supported for optional fields with a legacy-compatible type.`,target:s?.target,itemId:s?.itemId,messageKey:"Validation.InvalidClearForField",messageParams:{label:t}})}function rc(e){if(!e)return!1;for(let t of[...e.trueBranch,...e.falseBranch])if(t.kind==="action"){if(th(t))return!0}else if(rc(t))return!0;return!1}function rh(e,t){if(e.id===t)return e;for(let r of[...e.trueBranch,...e.falseBranch]){if(r.id===t)return r;if(r.kind==="condition"){let n=rh(r,t);if(n)return n}}return null}function Za(e,t){for(let r=0;r<e.trueBranch.length;r++){let n=e.trueBranch[r];if(n.id===t)return{node:e,branch:"true",index:r};if(n.kind==="condition"){let i=Za(n,t);if(i)return i}}for(let r=0;r<e.falseBranch.length;r++){let n=e.falseBranch[r];if(n.id===t)return{node:e,branch:"false",index:r};if(n.kind==="condition"){let i=Za(n,t);if(i)return i}}return null}function nh(e,t){return{...e,trueBranch:R_(e.trueBranch,t),falseBranch:R_(e.falseBranch,t)}}function R_(e,t){return e.filter(r=>r.id!==t).map(r=>r.kind==="condition"?nh(r,t):r)}function ri(e,t,r){return e.id===t?r(e):{...e,trueBranch:e.trueBranch.map(n=>n.kind==="condition"?ri(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="condition"?ri(n,t,r):n)}}function tc(e,t,r){return{...e,trueBranch:e.trueBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?tc(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?tc(n,t,r):n)}}function O_(e,t,r,n){return ri(e,t,i=>({...i,trueBranch:r==="true"?[...i.trueBranch,n]:i.trueBranch,falseBranch:r==="false"?[...i.falseBranch,n]:i.falseBranch}))}function ih(e){return e.length===1&&e[0].kind==="condition"}function b6(e){let t=0,r=e??void 0;for(;r;){t+=1;let{falseBranch:n}=r;if(ih(n)){r=n[0];continue}n.length>0&&(t+=1),r=void 0}return t}function w6(e){return!!e&&b6(e)<y6}function A6(e,t){if(!e)return;let r=(n,i)=>{if(n.id===t)return i;let a=[];if(ih(n.falseBranch)){let o=r(n.falseBranch[0],i);if(o)return o}else a.push(...n.falseBranch.filter(o=>o.kind==="condition"));a.push(...n.trueBranch.filter(o=>o.kind==="condition"));for(let o of a){let s=r(o,o);if(s)return s}};return r(e,e)}function x_(e,t,r){let n=A6(e,t);return!n||!w6(n)?e:ri(e,t,i=>L_(i,r))}function L_(e,t){if(ih(e.falseBranch))return{...e,falseBranch:[L_(e.falseBranch[0],t)]};let r=ah(t);return r.falseBranch=e.falseBranch,{...e,falseBranch:[r]}}function F_(e,t){let r=Za(e,t);if(!r||r.branch!=="false")return e;let n=r.node.falseBranch[r.index];if(!n||n.kind!=="condition")return e;let i=n.falseBranch;return ri(e,r.node.id,a=>({...a,falseBranch:i}))}function k_(e,t,r){let n=Za(e,t);if(!n)return e;let i=a=>{let o=[...a],s=o[n.index+r];return s?(o[n.index+r]=o[n.index],o[n.index]=s,o):a};return ri(e,n.node.id,a=>({...a,trueBranch:n.branch==="true"?i(a.trueBranch):a.trueBranch,falseBranch:n.branch==="false"?i(a.falseBranch):a.falseBranch}))}function ah(e){return{kind:"condition",id:At(),displayName:e??"New Condition",clauses:[],logic:"AND",trueBranch:[],falseBranch:[],isCollapsed:!1}}function M_(e,t){let r={kind:"action",id:At(),type:e,displayName:t??`New ${e}`};switch(e){case"Recommendation":return{...r,type:"Recommendation",field:"",recommendationTitle:"",messageText:"",applyActions:[{id:At(),field:"",valueType:"Value",value:""}]};case"LockUnlock":return{...r,type:"LockUnlock",field:"",lock:!0};case"ShowErrorMessage":return{...r,type:"ShowErrorMessage",field:"",errorMessage:""};case"SetFieldValue":return{...r,type:"SetFieldValue",field:"",valueType:"Value",value:""};case"SetDefaultValue":return{...r,type:"SetDefaultValue",field:"",valueType:"Value",value:""};case"SetBusinessRequired":return{...r,type:"SetBusinessRequired",field:"",required:!0};case"SetVisibility":return{...r,type:"SetVisibility",field:"",visible:!0};default:return{...r,type:"SetFieldValue",field:"",valueType:"Value",value:""}}}function B_(e){if(!e)return[];let t=[];return U_(e,t),[...new Set(t)]}function U_(e,t){e.clauses.forEach(r=>{r.field&&t.push(r.field)}),[...e.trueBranch,...e.falseBranch].forEach(r=>{r.kind==="condition"?U_(r,t):"field"in r&&r.field&&t.push(r.field)})}function $_(e,t=[]){if(!e)return[{nodeId:"root",kind:"NO_CONDITION",message:"A business rule must include at least one condition.",target:"node"}];let r=[],n=new Map(t.map(i=>[i.logicalName,i]));return q_(e,r,n),rc(e)||r.push({nodeId:"root",kind:"NO_ACTION",message:"A business rule must include at least one action step.",target:"node"}),r}function q_(e,t,r){let n=!!e.rawConditionExpression;e.clauses.length===0&&!n&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Add at least one clause to this condition.",target:"node",messageKey:"Validation.AddClause"}),e.clauses.forEach(i=>{if(n)return;if(i.source==="BusinessProcess"){i.bpfField?i.value||t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause.",target:"clauseValue",itemId:i.id}):t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Please select a business process field for this clause.",target:"clauseField",itemId:i.id,messageKey:"Validation.SelectBusinessProcessField"});return}let a=i.valueType==="Expression"&&!i.rawExpression?Oi(i.expression):null;if(!i.field)t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Please select a field for this clause.",target:"clauseField",itemId:i.id});else if(ti(i.operator)&&i.valueType==="Value"&&!i.value)t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause.",target:"clauseValue",itemId:i.id});else if(ti(i.operator)&&i.valueType==="Value"&&i.value){let o=r.get(i.field);o?.maxLength&&i.value.length>o.maxLength&&t.push({nodeId:e.id,kind:"CLAUSE_VALUE_TOO_LONG",message:`Value exceeds the field's maximum length of ${o.maxLength} characters.`,target:"clauseValue",itemId:i.id,messageParams:{maxLength:o.maxLength}})}else ti(i.operator)&&i.valueType==="Expression"&&!i.rawExpression&&!Ka(i.expression)&&t.push(a==="invalidDayCount"?eh(e.id,"clauseValue",i.id):{nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please complete the formula for this clause.",target:"clauseValue",itemId:i.id,messageKey:"Validation.CompleteClauseFormula"});ti(i.operator)&&i.valueType==="Lookup"&&(Zm(i.lookupValue)||t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please select a lookup record for this clause.",target:"clauseValue",itemId:i.id,messageKey:"Validation.EmptyClauseLookupValue"})),ti(i.operator)&&Ym(e.id,"Condition",i.field,i.valueType,r,t,{operator:i.operator,target:"clauseValue",itemId:i.id})}),[...e.trueBranch,...e.falseBranch].forEach(i=>{if(i.kind==="condition")q_(i,t,r);else{if(!("field"in i)||!i.field)t.push({nodeId:i.id,kind:"EMPTY_ACTION_FIELD",message:`${i.type}: a target field is required.`,target:"actionField",messageParams:{actionType:i.type}});else if((i.type==="SetFieldValue"||i.type==="SetDefaultValue")&&(i.valueType??"Value")==="Value"&&!i.value?.trim())t.push({nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:`${i.type}: please provide a value.`,target:"actionValue",messageParams:{actionType:i.type}});else if((i.type==="SetFieldValue"||i.type==="SetDefaultValue")&&i.valueType==="Value"&&i.value){let a=r.get(i.field);a?.maxLength&&i.value.length>a.maxLength&&t.push({nodeId:i.id,kind:"ACTION_VALUE_TOO_LONG",message:`${i.type}: value exceeds the field's maximum length of ${a.maxLength} characters.`,target:"actionValue",messageParams:{actionType:i.type,maxLength:a.maxLength}})}else if((i.type==="SetFieldValue"||i.type==="SetDefaultValue")&&i.valueType==="Field"){if(!i.valueField)t.push({nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:`${i.type}: please select a field to copy from.`,target:"actionValue",messageKey:"Validation.SelectActionSourceField",messageParams:{actionType:i.type}});else if(r.size>0){let a=r.get(i.field),o=r.get(i.valueField);a&&o&&!ec(a.attributeType,o.attributeType)&&t.push({nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:`${i.type}: the source field's type is not compatible with the target field.`,target:"actionValue",messageKey:"Validation.IncompatibleActionSourceField",messageParams:{actionType:i.type}})}}else if((i.type==="SetFieldValue"||i.type==="SetDefaultValue")&&i.valueType==="Expression"){let a=i.rawExpression?null:Oi(i.expression);!i.rawExpression&&!Ka(i.expression)&&t.push(a==="invalidDayCount"?eh(i.id,"actionValue"):{nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:`${i.type}: please complete the formula.`,target:"actionValue",messageKey:"Validation.CompleteActionFormula",messageParams:{actionType:i.type}})}else(i.type==="SetFieldValue"||i.type==="SetDefaultValue")&&i.valueType==="Lookup"&&!Zm(i.lookupValue)&&t.push({nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:`${i.type}: please complete the lookup record.`,target:"actionValue",messageKey:"Validation.EmptyActionLookupValue",messageParams:{actionType:i.type}});if((i.type==="SetFieldValue"||i.type==="SetDefaultValue")&&i.field&&(Ym(i.id,i.type,i.field,i.valueType,r,t,{target:"actionValue"}),P_(i.id,i.type,i.type,i.field,i.valueType,r,t,{target:"actionValue"})),i.type==="ShowErrorMessage"&&!i.errorMessage?.trim()&&t.push({nodeId:i.id,kind:"EMPTY_ACTION_MESSAGE",message:"Show error message: please enter an error message.",target:"actionMessage"}),i.type==="Recommendation"){let a=i.applyActions??[];i.recommendationTitle?.trim()||t.push({nodeId:i.id,kind:"EMPTY_RECOMMENDATION_TITLE",message:"Recommendation: please enter a recommendation title.",target:"recommendationTitle"}),i.messageText?.trim()||t.push({nodeId:i.id,kind:"EMPTY_RECOMMENDATION_MESSAGE",message:"Recommendation: please enter a recommendation message.",target:"recommendationMessage"}),a.length===0&&t.push({nodeId:i.id,kind:"RECOMMENDATION_NO_APPLY_ACTION",message:"Recommendation: add at least one action to apply.",target:"node"}),a.forEach(o=>{if(!o.field)t.push({nodeId:i.id,kind:"EMPTY_ACTION_FIELD",message:"Recommendation: a target field is required for each action to apply.",target:"applyActionField",itemId:o.id,messageKey:"Validation.RecommendationApplyField"});else if(o.valueType==="Field")o.valueField||t.push({nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please select a field to copy from.",target:"applyActionValue",itemId:o.id,messageKey:"Validation.RecommendationApplySourceField"});else if(o.valueType==="Expression"){let s=o.rawExpression?null:Oi(o.expression);!o.rawExpression&&!Ka(o.expression)&&t.push(s==="invalidDayCount"?eh(i.id,"applyActionValue",o.id):{nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the formula.",target:"applyActionValue",itemId:o.id,messageKey:"Validation.RecommendationApplyFormula"})}else o.valueType==="Lookup"?Zm(o.lookupValue)||t.push({nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the lookup record.",target:"applyActionValue",itemId:o.id,messageKey:"Validation.RecommendationApplyLookupValue"}):o.valueType==="Clear"||o.value?.trim()||t.push({nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please enter a value for each action to apply.",target:"applyActionValue",itemId:o.id,messageKey:"Validation.RecommendationApplyValue"});o.field&&(Ym(i.id,"Recommendation",o.field,o.valueType,r,t,{target:"applyActionValue",itemId:o.id}),P_(i.id,"Recommendation","SetFieldValue",o.field,o.valueType,r,t,{target:"applyActionValue",itemId:o.id}))})}}})}var g6,v6,y6,oh=T(()=>{"use strict";Mm();Om();Xm();Ns();g6=new Set(["LockUnlock","ShowErrorMessage","Recommendation","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]);v6=new Set(["Lookup","Customer","Owner"]);y6=10});var V_={};Zr(V_,{DAY_COUNT_MAX:()=>Ja,DAY_COUNT_MIN:()=>qm,DEFAULT_DESERIALIZE_LABELS:()=>Km,WorkflowJsonMapper:()=>Ya,addElseIfInTree:()=>x_,appendToBranch:()=>O_,areFieldKindsCompatible:()=>ec,attributeTypeToWorkflowType:()=>JI,buildWorkflowEntity:()=>FI,collectUsedFields:()=>B_,createEmptyAction:()=>M_,createEmptyCondition:()=>ah,deserializeWorkflowJson:()=>C_,findNode:()=>rh,findParent:()=>Za,getDefaultOperatorForFieldType:()=>__,getExpressionModelIssue:()=>Oi,getOperatorsForFieldType:()=>Zu,hasAnyTriggerGeneratingAction:()=>rc,isDayCountValid:()=>Vm,isExpressionModelComplete:()=>Ka,isOperatorCompatible:()=>T_,isTriggerGeneratingAction:()=>th,moveBranchItemInTree:()=>k_,operatorNeedsValue:()=>ti,processTriggerFormIdFromScope:()=>Lm,processTriggerScopeFromScope:()=>xm,removeElseIfInTree:()=>F_,removeNodeFromTree:()=>nh,serializeToWorkflowJson:()=>A_,supportsClearForActionType:()=>Wu,updateActionInTree:()=>tc,updateConditionInTree:()=>ri,validateBusinessRule:()=>$_});var G_=T(()=>{"use strict";Om();kI();Qm();Qm();oh();oh();Xm();Ns();Ns();});var sh=y(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});nc.cloneJson=void 0;function C6(e){return JSON.parse(JSON.stringify(e))}nc.cloneJson=C6});var e2=y(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.BUSINESS_RULE_NULL_GUID=ni.businessRuleRegistration=ni.BusinessRuleAdapter=void 0;var z_=st(),_s=(G_(),_r(V_)),W_=hr(),j_=ee(),E6=sh(),Wr=zr(),S6=bd(),N6=st();function D6(e){return Q_((0,E6.cloneJson)(e))}function Q_(e){var t,r;let n=i=>(i??[]).map(a=>I6(a)?Q_(a):a);return{...e,logic:(t=e.logic)!==null&&t!==void 0?t:"AND",clauses:(r=e.clauses)!==null&&r!==void 0?r:[],trueBranch:n(e.trueBranch),falseBranch:n(e.falseBranch)}}function I6(e){return Object.prototype.hasOwnProperty.call(e,"type")?!1:Object.prototype.hasOwnProperty.call(e,"clauses")||Object.prototype.hasOwnProperty.call(e,"trueBranch")||Object.prototype.hasOwnProperty.call(e,"falseBranch")||Object.prototype.hasOwnProperty.call(e,"logic")}function _6(e){var t;if(e===null||typeof e!="object"||Array.isArray(e))throw new j_.ValidationError("businessRule","(new)","/rootCondition",`rootCondition must be a condition object or null, got ${Array.isArray(e)?"array":typeof e}`);if(Object.prototype.hasOwnProperty.call(e,"type"))throw new j_.ValidationError("businessRule",(t=e.id)!==null&&t!==void 0?t:"(new)","/rootCondition","rootCondition looks like an ACTION (it carries 'type'), but it must be a condition. Wrap the action in a condition's trueBranch instead \u2014 a bare action would compile to an empty rule that saves successfully and does nothing.");return e}var T6="00000000-0000-0000-0000-000000000000";ni.BUSINESS_RULE_NULL_GUID=T6;var P6=new Set(["Recommendation","LockUnlock","ShowErrorMessage","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]),R6=["ruleId","name","description","entityLogicalName","scope","status","rootCondition"],O6=["kind","id","displayName","logic","clauses","trueBranch","falseBranch"],x6=["id","field","fieldDisplayName","operator","valueType","value","valueField","lookupValue","expression","rawExpression","valueWorkflowType"];function Cr(e,t){return e===void 0?t:{...e,...t}}var xi=["kind","id","type","displayName","field","stepName","stepLabels"],H_=["valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression"],L6={Recommendation:[...xi,"recommendationTitle","messageText","acceptanceText","applyActions","recommendationActionStepMeta"],LockUnlock:[...xi,"lock"],ShowErrorMessage:[...xi,"errorMessage","messageLevel","messageActionSteps"],SetFieldValue:[...xi,...H_],SetDefaultValue:[...xi,...H_],SetBusinessRequired:[...xi,"required"],SetVisibility:[...xi,"visible"]};function H(e,t){return t===void 0?{}:{[e]:t}}function X_(e){var t;return e===void 0?void 0:{...e,label:(t=e.label)!==null&&t!==void 0?t:""}}function lh(e){return{valueType:e.valueType,...H("valueWorkflowType",e.valueWorkflowType),...H("value",e.value),...H("valueField",e.valueField),...H("lookupValue",X_(e.lookupValue)),...H("expression",e.expression),...H("rawExpression",e.rawExpression)}}function Y_(e,t){let r=new Set(t),n={};for(let[i,a]of Object.entries(e))r.has(i)||a!==void 0&&(n[i]=a);return Object.keys(n).length>0?n:void 0}var F6=["id","field","valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression","stepName","displayName"];function k6(e){return Cr(e.bag,{id:e.id,field:e.field,...lh(e),...H("stepName",e.stepName),...H("displayName",e.displayName)})}function M6(e){let t=Y_(e,F6);return{id:e.id,field:e.field,valueType:e.valueType,...H("valueWorkflowType",e.valueWorkflowType),...H("value",e.value),...H("valueField",e.valueField),...H("lookupValue",e.lookupValue),...H("expression",e.expression),...H("rawExpression",e.rawExpression),...H("stepName",e.stepName),...H("displayName",e.displayName),...H("bag",t)}}function J_(e){return{valueType:e.valueType,...H("valueWorkflowType",e.valueWorkflowType),...H("value",e.value),...H("valueField",e.valueField),...H("lookupValue",e.lookupValue),...H("expression",e.expression),...H("rawExpression",e.rawExpression)}}function K_(e){throw new Error(`Unsupported business-rule action type: ${e.type}`)}var B6=new Set(["INVALID_CLEAR_FOR_FIELD","INVALID_VALUE_TYPE_FOR_FIELD","CLAUSE_VALUE_TOO_LONG","ACTION_VALUE_TOO_LONG"]),U6=new Set,$6="INVALID_CLEAR_FOR_FIELD";function q6(e){let t=n=>{var i;return(0,Wr.isJsonObject)(n)&&(n.label===""||n.label===void 0)?{...n,label:String((i=n.id)!==null&&i!==void 0?i:"")}:n},r=n=>{if(!(0,Wr.isJsonObject)(n))return n;let i={...n};"lookupValue"in i&&(i.lookupValue=t(i.lookupValue)),Array.isArray(i.applyActions)&&(i.applyActions=i.applyActions.map(r));for(let a of["clauses","trueBranch","falseBranch"])Array.isArray(i[a])&&(i[a]=i[a].map(r));return i};return r(e)}var ic=class{toArtifact(t){let r=this.residualBag(t,R6),n={id:t.ruleId,name:t.name,description:t.description,entityLogicalName:t.entityLogicalName,scope:t.scope,status:t.status,rootCondition:t.rootCondition?this.conditionToJson(t.rootCondition):null};return r&&(n.bag=r),n}fromArtifact(t){let r=t.rootCondition?this.conditionFromJson(t.rootCondition):null;return Cr(t.bag,{ruleId:t.id,name:t.name,description:t.description,entityLogicalName:t.entityLogicalName,scope:t.scope,status:t.status,rootCondition:r})}fromApiResponse(t){var r;let n=t??{},i={...(r=n.Entity)!==null&&r!==void 0?r:{},wfomJson:n.WfomJson},a=(0,_s.deserializeWorkflowJson)(i);return this.toArtifact(a)}toApiPayload(t){var r;let n=this.fromArtifact(t);n.wfomRoot&&(n.wfomRoot={...n.wfomRoot,name:t.name,title:t.name,primaryEntityName:t.entityLogicalName||n.wfomRoot.primaryEntityName});let i=(0,_s.serializeToWorkflowJson)(n),a=(r=n.ruleId)!==null&&r!==void 0?r:(0,z_.newId)();return{Entity:this.buildWorkflowEntity(n,a),WfomJson:i,status:t.status}}createDefault(t){var r,n,i,a,o,s;let l={ruleId:(r=t.id)!==null&&r!==void 0?r:null,name:(n=t.name)!==null&&n!==void 0?n:"New business rule",description:(i=t.description)!==null&&i!==void 0?i:"",entityLogicalName:(a=t.entityLogicalName)!==null&&a!==void 0?a:"",scope:(o=t.scope)!==null&&o!==void 0?o:"Entity",status:(s=t.status)!==null&&s!==void 0?s:"Draft",rootCondition:t.rootCondition===void 0?(0,_s.createEmptyCondition)():t.rootCondition===null?null:this.conditionFromJson(D6(_6(t.rootCondition)))},u=this.toArtifact(l);return u.id||(u.id=(0,z_.newId)()),u}assignMissingIds(t){return(0,N6.assignMissingIds)(t)}validate(t){let r=[],n=t.rootCondition;return n==null?r:(0,Wr.isJsonObject)(n)?(Z_(n,"/rootCondition",r),r):(r.push((0,Wr.issue)("/rootCondition","condition-must-be-object",`rootCondition must be a JSON object or null, got ${typeof n}`)),r)}semanticIssues(t,r=[]){let n;try{n=this.fromArtifact(t)}catch(o){return[(0,Wr.issue)("/rootCondition","rule-not-representable",o instanceof Error?o.message:String(o))]}let i=n.rootCondition===null?null:q6(n.rootCondition),a;return r.length===0?a=B6:r.some(o=>o.requiredLevel!==void 0)?a=U6:a=new Set([$6]),(0,_s.validateBusinessRule)(i,r).filter(o=>!a.has(o.kind)).map(o=>(0,Wr.issue)(`/rootCondition (${o.nodeId})`,`business-rule-${o.kind}`,o.message))}issuesBlockingPush(t,r=[],n){return this.semanticIssues(t,r)}residualBag(t,r){return Y_(t,r)}buildWorkflowEntity(t,r){return(0,_s.buildWorkflowEntity)(t,r)}conditionToJson(t){let r=this.residualBag(t,O6),n={id:t.id,displayName:t.displayName,logic:t.logic,clauses:t.clauses.map(i=>this.clauseToJson(i)),trueBranch:t.trueBranch.map(i=>this.branchItemToJson(i)),falseBranch:t.falseBranch.map(i=>this.branchItemToJson(i))};return r&&(n.bag=r),n}clauseToJson(t){let r=this.residualBag(t,x6),n={id:t.id,field:t.field,fieldDisplayName:t.fieldDisplayName,operator:t.operator,valueType:t.valueType,...t.value!==void 0?{value:t.value}:{},...t.valueField!==void 0?{valueField:t.valueField}:{},...t.lookupValue!==void 0?{lookupValue:t.lookupValue}:{},...t.expression!==void 0?{expression:t.expression}:{},...t.rawExpression!==void 0?{rawExpression:t.rawExpression}:{},...t.valueWorkflowType!==void 0?{valueWorkflowType:t.valueWorkflowType}:{}};return r&&(n.bag=r),n}branchItemToJson(t){return t.kind==="condition"?this.conditionToJson(t):this.actionToJson(t)}actionToJson(t){let r=this.residualBag(t,L6[t.type]),n={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...H("stepName",t.stepName),...H("stepLabels",t.stepLabels),...H("bag",r)};switch(t.type){case"Recommendation":return{...n,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...H("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(M6),...H("recommendationActionStepMeta",t.recommendationActionStepMeta)};case"LockUnlock":return{...n,type:"LockUnlock",lock:t.lock};case"ShowErrorMessage":return{...n,type:"ShowErrorMessage",errorMessage:t.errorMessage,...H("messageLevel",t.messageLevel),...H("messageActionSteps",t.messageActionSteps)};case"SetFieldValue":return{...n,type:"SetFieldValue",...J_(t)};case"SetDefaultValue":return{...n,type:"SetDefaultValue",...J_(t)};case"SetBusinessRequired":return{...n,type:"SetBusinessRequired",required:t.required};case"SetVisibility":return{...n,type:"SetVisibility",visible:t.visible};default:return K_(t)}}conditionFromJson(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:{};return Cr(n,{kind:"condition",isCollapsed:typeof n.isCollapsed=="boolean"?n.isCollapsed:!1,id:t.id,displayName:t.displayName,logic:t.logic,clauses:t.clauses.map(i=>this.clauseFromJson(i)),trueBranch:t.trueBranch.map(i=>this.branchItemFromJson(i)),falseBranch:t.falseBranch.map(i=>this.branchItemFromJson(i))})}clauseFromJson(t){var r;return Cr(t.bag,{id:t.id,field:t.field,fieldDisplayName:(r=t.fieldDisplayName)!==null&&r!==void 0?r:t.field,operator:t.operator,valueType:t.valueType,...H("value",t.value),...H("valueField",t.valueField),...H("lookupValue",X_(t.lookupValue)),...H("expression",t.expression),...H("rawExpression",t.rawExpression),...H("valueWorkflowType",t.valueWorkflowType)})}branchItemFromJson(t){return this.isConditionJson(t)?this.conditionFromJson(t):this.actionFromJson(t)}actionFromJson(t){if(!P6.has(t.type))throw new Error(`Unsupported business-rule action type: ${t.type}`);G6(t);let r={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...H("stepName",t.stepName),...H("stepLabels",t.stepLabels)};switch(t.type){case"Recommendation":return Cr(t.bag,{...r,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...H("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(k6),...H("recommendationActionStepMeta",t.recommendationActionStepMeta)});case"LockUnlock":return Cr(t.bag,{...r,type:"LockUnlock",lock:t.lock});case"ShowErrorMessage":return Cr(t.bag,{...r,type:"ShowErrorMessage",errorMessage:t.errorMessage,...H("messageLevel",t.messageLevel),...H("messageActionSteps",t.messageActionSteps)});case"SetFieldValue":return Cr(t.bag,{...r,type:"SetFieldValue",...lh(t)});case"SetDefaultValue":return Cr(t.bag,{...r,type:"SetDefaultValue",...lh(t)});case"SetBusinessRequired":return Cr(t.bag,{...r,type:"SetBusinessRequired",required:t.required});case"SetVisibility":return Cr(t.bag,{...r,type:"SetVisibility",visible:t.visible});default:return K_(t)}}isConditionJson(t){return Object.prototype.hasOwnProperty.call(t,"clauses")&&Object.prototype.hasOwnProperty.call(t,"logic")&&!Object.prototype.hasOwnProperty.call(t,"type")}};ni.BusinessRuleAdapter=ic;function Z_(e,t,r){(0,Wr.optionalEnum)(e,"logic",["AND","OR"],t,"condition-logic-invalid",r),(0,Wr.childObjects)(e,"clauses",t,"clause",r);for(let n of["trueBranch","falseBranch"])(0,Wr.childObjects)(e,n,t,"branchItem",r).forEach(({node:a,index:o})=>{"clauses"in a||"trueBranch"in a||"falseBranch"in a?Z_(a,`${t}/${n}/${o}`,r):V6(a,`${t}/${n}/${o}`,r)})}function V6(e,t,r){e.type==="SetDefaultValue"&&e.valueType==="Clear"&&r.push((0,Wr.issue)(`${t}/valueType`,"clear-only-set-field-value","Clear is only supported for SetFieldValue actions."))}function G6(e){if(e.type==="SetDefaultValue"&&e.valueType==="Clear")throw new Error("Clear is only supported for SetFieldValue actions.")}function z6(){return{adapter:new ic,api:S6.businessRuleApi,publish:(e,t,r)=>(0,W_.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,W_.boundEntityPublishScope)(t)}}ni.businessRuleRegistration=z6});var g2=y(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.appRegistration=ii.AppAdapter=ii.HEADER_NAV_BOOLEAN_RULE=void 0;var vn=zr(),Ze=Mn(),Ps=mi(),W6=hr(),j6=ql(),uh=Ml(),ch=Un(),H6=st(),J6=le(),c2=Ji(),d2=ee(),p2=Ul();Object.defineProperty(ii,"HEADER_NAV_BOOLEAN_RULE",{enumerable:!0,get:function(){return p2.HEADER_NAV_BOOLEAN_RULE}});var lc="7.0.0.0",t2=`<SiteMap IntroducedVersion="${lc}"></SiteMap>`,r2="/_imgs/imagestrips/transparent_spacer.gif",n2="/_imgs/TableIconsFluentV9/document_one_page_sparkle.svg",K6=["Entity","Url","DefaultDashboard","Page","GenPageId"],Ts="sitemapId",i2="sitemapName",Q6="sitemapNameUnique",a2="aiDescription",o2="[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}",X6=new RegExp(`^(?:\\{${o2}\\}|${o2})$`);function s2(e,t){if(!X6.test(e.trim()))throw new d2.ValidationError("app",t,[{pointer:"/sitemapId",rule:"app-sitemapid-guid",message:`sitemapId must be a GUID; received '${e}'.`}]);return e.trim()}function l2(e,t,r){if(e===void 0)return r;if(typeof e!="boolean")throw new d2.ValidationError("app",t,[f2(e)]);return e}function f2(e){return(0,vn.issue)("/headerAndNavigationRefresh",p2.HEADER_NAV_BOOLEAN_RULE,`headerAndNavigationRefresh must be a boolean, got ${typeof e}`)}function Y6(e){let t=n=>{let i=e[n];return typeof i=="string"&&i.trim()!==""?i.trim():void 0},r=n=>{let i=t(n);if(i!==void 0)try{return(0,J6.normalizeGuid)(i,n)}catch{return}};switch(e.type){case"Entity":return t("entity")&&`Entity:${t("entity").toLowerCase()}`;case"URL":return t("url")&&`URL:${t("url").toLowerCase()}`;case"DashBoard":return r("dashboardId")&&`DashBoard:${r("dashboardId")}`;case"CustomPage":return t("page")&&`CustomPage:${t("page").toLowerCase()}`;case"GenPage":return r("genPageId")&&`GenPage:${r("genPageId")}`;default:return}}var uc=class{constructor(t=c2.DEFAULT_LCID){this.lcid=t}toArtifact(t){let{bag:r,modeledEls:n}=ac(t,"Area");return{id:"",name:"",uniqueName:"",description:"",siteMap:{areas:n.map(i=>this.areaToJson(i)),bag:r},bag:(0,Ze.emptyBag)()}}fromArtifact(t){(0,ch.installDomShim)();let r=this.assignMissingIds(JSON.parse(JSON.stringify(t))),n=new DOMParser().parseFromString("<root/>","text/xml"),i=this.rootToRaw(r);return(0,Ze.rebuildRaw)(i,(0,Ps.domEngine)(n),null)}fromApiResponse(t){var r,n,i,a,o,s,l,u,c,d,p;(0,ch.installDomShim)();let f=t??{},m=(r=f.$sitemap)!==null&&r!==void 0?r:f,h=(0,Ps.parseXmlRoot)((n=m.sitemapxml)!==null&&n!==void 0?n:t2,t2),v=this.toArtifact(h);return v.id=(i=f.appmoduleid)!==null&&i!==void 0?i:"",v.name=(a=f.name)!==null&&a!==void 0?a:"",v.uniqueName=(o=f.uniquename)!==null&&o!==void 0?o:"",v.description=(s=f.description)!==null&&s!==void 0?s:"",f.aiappdescription&&(v.aiDescription=f.aiappdescription),v.bag={a:[[Ts,(u=(l=m.sitemapid)!==null&&l!==void 0?l:f._sitemapid_value)!==null&&u!==void 0?u:""],[i2,(c=m.sitemapname)!==null&&c!==void 0?c:""],[Q6,(d=m.sitemapnameunique)!==null&&d!==void 0?d:""],[a2,(p=f.aiappdescription)!==null&&p!==void 0?p:""]],c:[]},v}toApiPayload(t,r){var n,i,a,o,s,l,u,c,d,p,f,m,h,v;(0,ch.installDomShim)();let w=(0,Ps.serializeNode)(this.fromArtifact(t)),C=[],E=[];for(let O of(i=(n=t.siteMap)===null||n===void 0?void 0:n.areas)!==null&&i!==void 0?i:[])for(let x of(a=O.groups)!==null&&a!==void 0?a:[])for(let F of(o=x.subAreas)!==null&&o!==void 0?o:[])F.type==="Entity"&&F.entity?C.push(F.entity):F.type==="DashBoard"&&F.dashboardId&&E.push(F.dashboardId);let D=(s=t.bag)!==null&&s!==void 0?s:(0,Ze.emptyBag)();return{sitemapId:ph(D,Ts)||(t.sitemapId?s2(t.sitemapId,t.id):""),sitemapxml:w,sitemapname:ph(D,i2)||t.name,appModuleId:t.id,appModuleName:t.name,appModuleDescription:t.description,...t.aiDescription!==void 0&&t.aiDescription!==(r?r.aiDescription:ph(D,a2))?{appModuleAiDescription:t.aiDescription}:{},appModuleUniqueName:t.uniqueName,...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},...t.headerAndNavigationRefresh===void 0?{}:{appSettings:{[uh.HEADER_AND_NAVIGATION_REFRESH]:l2(t.headerAndNavigationRefresh,(l=t.id)!==null&&l!==void 0?l:"(unknown)",!0)?uh.APP_SETTING_ON:uh.APP_SETTING_OFF}},...typeof t.published=="boolean"?{published:t.published}:{},entities:C,components:{forms:(c=(u=t.components)===null||u===void 0?void 0:u.forms)!==null&&c!==void 0?c:[],views:(p=(d=t.components)===null||d===void 0?void 0:d.views)!==null&&p!==void 0?p:[],charts:(m=(f=t.components)===null||f===void 0?void 0:f.charts)!==null&&m!==void 0?m:[],dashboards:[...(v=(h=t.components)===null||h===void 0?void 0:h.dashboards)!==null&&v!==void 0?v:[],...E]}}}createDefault(t){var r,n,i,a,o,s;let l=!((r=t.siteMap)===null||r===void 0)&&r.areas&&t.siteMap.areas.length>0?t.siteMap.areas:[{id:"",title:"Area",groups:[{id:"",title:"Group",subAreas:[]}]}],u=(n=t.id)!==null&&n!==void 0?n:(0,H6.newId)();return{id:u,name:(i=t.name)!==null&&i!==void 0?i:"New App",uniqueName:(a=t.uniqueName)!==null&&a!==void 0?a:"",description:(o=t.description)!==null&&o!==void 0?o:"",...t.aiDescription?{aiDescription:t.aiDescription}:{},siteMap:{areas:l},...t.sitemapId?{sitemapId:s2(t.sitemapId,u)}:{},...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},headerAndNavigationRefresh:l2(t.headerAndNavigationRefresh,(s=t.id)!==null&&s!==void 0?s:"(new)",!0),...typeof t.published=="boolean"?{published:t.published}:{},...t.components?{components:t.components}:{}}}assignMissingIds(t){let r=t;if(!r||typeof r!="object")return t;let n=r.siteMap;return n&&Array.isArray(n.areas)?n.areas.forEach(mh):Array.isArray(r.areas)?r.areas.forEach(mh):Array.isArray(r.groups)?mh(r):Array.isArray(r.subAreas)?h2(r):"type"in r&&cc(r,"subarea"),t}validate(t){let r=[],n=t.published;n!==void 0&&typeof n!="boolean"&&r.push((0,vn.issue)("/published","published-must-be-boolean",`published must be a boolean, got ${typeof n}`));let i=t.siteMap,a=t.headerAndNavigationRefresh;if(a!==void 0&&typeof a!="boolean"&&r.push(f2(a)),i==null)return r;if(!(0,vn.isJsonObject)(i))return r.push((0,vn.issue)("/siteMap","sitemap-must-be-object",`siteMap must be a JSON object, got ${typeof i}`)),r;let o=(0,vn.childObjects)(i,"areas","/siteMap","area",r),s=new Map;return o.forEach(({node:l,index:u})=>{let c=`/siteMap/areas/${u}`;(0,vn.childObjects)(l,"groups",c,"group",r).forEach(({node:p,index:f})=>{let m=`${c}/groups/${f}`;(0,vn.childObjects)(p,"subAreas",m,"subArea",r).forEach(({node:v,index:w})=>{let C=`${m}/subAreas/${w}`;(0,vn.optionalEnum)(v,"type",["Entity","URL","DashBoard","CustomPage","GenPage"],C,"subarea-type-invalid",r);let E=Y6(v);if(!E)return;let D=s.get(E);if(D===void 0){s.set(E,C);return}r.push((0,vn.issue)(C,"subarea-duplicate-target",`the sitemap already navigates to this target at ${D}; a duplicate SubArea would pin it twice and a single removeElement would leave one behind`))})})}),r}applyServerIdentity(t,r){let n=r[Ts];if(!n)return;t.bag||(t.bag=(0,Ze.emptyBag)());let i=t.bag.a.find(a=>a[0]===Ts);i?i[1]=n:t.bag.a.push([Ts,n])}areaToJson(t){var r;let{bag:n,modeledEls:i}=ac(t,"Group"),a={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:dh(t,this.lcid),groups:i.map(l=>this.groupToJson(l)),bag:n},o=t.getAttribute("Icon");o&&(a.icon=o);let s=t.getAttribute("VectorIcon");return s&&(a.vectorIcon=s),a}groupToJson(t){var r;let{bag:n,modeledEls:i}=ac(t,"SubArea");return{id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:dh(t,this.lcid),subAreas:i.map(a=>this.subAreaToJson(a)),bag:n}}subAreaToJson(t){var r;let{bag:n}=ac(t,null),i=Z6(t),a={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",type:i,title:dh(t,this.lcid),bag:n};if(i==="Entity"){let l=t.getAttribute("Entity");l&&(a.entity=l)}else if(i==="DashBoard"){let l=t.getAttribute("DefaultDashboard");l&&(a.dashboardId=l);let u=t.getAttribute("Url");u&&(a.dashboardUrl=u)}else if(i==="CustomPage"){let l=t.getAttribute("Page");l&&(a.page=l)}else if(i==="GenPage"){let l=t.getAttribute("GenPageId");l&&(a.genPageId=l)}else{let l=t.getAttribute("Url");l&&(a.url=l)}let o=t.getAttribute("Icon");o&&o!==r2&&(a.icon=o);let s=t.getAttribute("VectorIcon");return s&&(a.vectorIcon=s),a}rootToRaw(t){var r,n,i,a;let o=(n=(r=t.siteMap)===null||r===void 0?void 0:r.bag)!==null&&n!==void 0?n:(0,Ze.emptyBag)(),l=oc(o)?[["IntroducedVersion",lc]]:[],u=((a=(i=t.siteMap)===null||i===void 0?void 0:i.areas)!==null&&a!==void 0?a:[]).map(c=>this.areaToRaw(c));return{n:"SiteMap",a:(0,Ze.mergeAttrs)(o.a,l),c:(0,Ze.spliceChildren)(o.c,u)}}areaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,Ze.emptyBag)(),i=oc(n),a=[],o=[];t.id&&a.push(["Id",t.id]),i&&a.push(["ShowGroups","true"],["ResourceId","SitemapDesigner.NewTitle"],["DescriptionResourceId","SitemapDesigner.NewTitle"],["IntroducedVersion",lc]),t.icon!==void 0?a.push(["Icon",t.icon]):sc(n.a,"Icon")&&o.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):sc(n.a,"VectorIcon")&&o.push("VectorIcon");let s=t.groups.map(u=>this.groupToRaw(u)),l=fh((0,Ze.spliceChildren)(n.c,s),t.title,i,this.lcid);return{n:"Area",a:(0,Ze.mergeAttrs)(n.a,a,o),c:l}}groupToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,Ze.emptyBag)(),i=oc(n),a=[];t.id&&a.push(["Id",t.id]),i&&a.push(["ResourceId","SitemapDesigner.NewGroup"],["DescriptionResourceId","SitemapDesigner.NewGroup"],["ToolTipResourseId","SitemapDesigner.Unknown"],["IntroducedVersion",lc],["IsProfile","false"]);let o=t.subAreas.map(l=>this.subAreaToRaw(l)),s=fh((0,Ze.spliceChildren)(n.c,o),t.title,i,this.lcid);return{n:"Group",a:(0,Ze.mergeAttrs)(n.a,a),c:s}}subAreaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,Ze.emptyBag)(),i=oc(n),a=t7(n.a,t.type),o=[],s=[];t.id&&o.push(["Id",t.id]),n7(o,t),i?(o.push(["ResourceId","SitemapDesigner.NewSubArea"],["Client","All,Outlook,OutlookLaptopClient,OutlookWorkstationClient,Web"],["Sku","All,OnPremise,Live,SPLA"],["AvailableOffline","true"],["PassParams","false"]),t.icon&&o.push(["Icon",t.icon])):t.icon!==void 0?o.push(["Icon",t.icon]):sc(a,"Icon",r2)&&s.push("Icon"),t.vectorIcon!==void 0?o.push(["VectorIcon",t.vectorIcon]):sc(a,"VectorIcon")?t.type==="GenPage"?o.push(["VectorIcon",n2]):s.push("VectorIcon"):t.type==="GenPage"&&!e7(a,"VectorIcon")&&o.push(["VectorIcon",n2]);let l=fh((0,Ze.spliceChildren)(n.c,[]),t.title,i,this.lcid);return{n:"SubArea",a:(0,Ze.mergeAttrs)(a,o,s),c:l}}};ii.AppAdapter=uc;function ac(e,t){let r=(0,Ps.nodeLikeFromDom)(e).getAllProperties().map(s=>[s.key,s.value]),n=[],i=[],a=e.childNodes,o=0;for(let s=0;s<a.length;s+=1){let l=a[s];l.nodeType!==1&&l.nodeType!==3||(l.nodeType===1&&t!==null&&l.tagName===t?i.push(l):n.push({i:o,node:(0,Ze.rawFromNode)((0,Ps.nodeLikeFromDom)(l))}),o+=1)}return{bag:{a:r,c:n},modeledEls:i}}function u2(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let a=n[i];a.nodeType===1&&a.tagName===t&&r.push(a)}return r}function dh(e,t){var r;let n=u2(e,"Titles")[0];if(!n)return"";let a=u2(n,"Title").find(o=>o.getAttribute("LCID")===String(t));return a&&(r=a.getAttribute("Title"))!==null&&r!==void 0?r:""}function Z6(e){return e.getAttribute("GenPageId")?"GenPage":e.getAttribute("Entity")?"Entity":e.getAttribute("Page")?"CustomPage":e.getAttribute("DefaultDashboard")?"DashBoard":"URL"}function oc(e){return e.a.length===0&&e.c.length===0}function e7(e,t){return e.some(([r])=>r===t)}function sc(e,t,r){let n=e.find(([a])=>a===t),i=n?.[1];return!!i&&i!==r}function ph(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function t7(e,t){let r=r7(t);return e.filter(([n])=>!K6.includes(n)||r.has(n)).map(n=>[n[0],n[1]])}function r7(e){switch(e){case"Entity":return new Set(["Entity"]);case"URL":return new Set(["Url"]);case"DashBoard":return new Set(["DefaultDashboard","Url"]);case"CustomPage":return new Set(["Page"]);case"GenPage":return new Set(["GenPageId"]);default:return new Set}}function n7(e,t){var r,n,i,a,o;switch(t.type){case"Entity":e.push(["Entity",(r=t.entity)!==null&&r!==void 0?r:""]);break;case"URL":e.push(["Url",(n=t.url)!==null&&n!==void 0?n:""]);break;case"DashBoard":e.push(["DefaultDashboard",(i=t.dashboardId)!==null&&i!==void 0?i:""]),t.dashboardUrl!==void 0&&e.push(["Url",t.dashboardUrl]);break;case"CustomPage":e.push(["Page",(a=t.page)!==null&&a!==void 0?a:""]);break;case"GenPage":e.push(["GenPageId",(o=t.genPageId)!==null&&o!==void 0?o:""]);break;default:break}}function fh(e,t,r,n){if(!t)return e;let i=e.findIndex(a=>a.n==="Titles");if(i>=0){let a=e.slice();return a[i]=i7(e[i],t,n),a}return r?[a7(t,n),...e]:e}function i7(e,t,r){let n=!1,i=e.c.map(a=>!n&&a.n==="Title"&&o7(a,"LCID")===String(r)?(n=!0,{n:a.n,a:(0,Ze.mergeAttrs)(a.a,[["Title",t]]),c:a.c}):a);return n||i.unshift(m2(t,r)),{n:e.n,a:e.a.map(a=>[a[0],a[1]]),c:i}}function a7(e,t){return{n:"Titles",a:[],c:[m2(e,t)]}}function m2(e,t){return{n:"Title",a:[["LCID",String(t)],["Title",e]],c:[]}}function o7(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function s7(e){let t="0123456789abcdef",r="";for(let n=0;n<e;n+=1)r+=t[Math.floor(Math.random()*t.length)];return r}function cc(e,t){e&&(typeof e.id!="string"||e.id.length===0)&&(e.id=`${t}_${s7(8)}`)}function mh(e){var t;cc(e,"area");for(let r of(t=e.groups)!==null&&t!==void 0?t:[])h2(r)}function h2(e){var t;cc(e,"group");for(let r of(t=e.subAreas)!==null&&t!==void 0?t:[])cc(r,"subarea")}function l7(e=c2.DEFAULT_LCID){return{adapter:new uc(e),api:j6.appApi,languageSensitive:!0,publish:(t,r)=>(0,W6.publishAppModule)(t,r),publishScope:t=>({envelope:"appmodule",targetIds:[t]})}}ii.appRegistration=l7});var v2={};Zr(v2,{ActionType:()=>gh,AppActionOrigin:()=>Sh,AppActionVisibilityType:()=>Eh,ButtonType:()=>yh,CannotUpdateAppActionColumns:()=>u7,Context:()=>wh,IconType:()=>vh,Location:()=>bh,OnClickEventType:()=>Ch,Scope:()=>Ah,VisibilityType:()=>hh});var hh,gh,vh,yh,bh,wh,Ah,Ch,Eh,Sh,u7,y2=T(()=>{"use strict";(function(e){e[e.NotSupported=0]="NotSupported",e[e.Show=1]="Show",e[e.ClassicRules=2]="ClassicRules",e[e.Expression=3]="Expression"})(hh||(hh={}));(function(e){e[e.NotSupported=0]="NotSupported",e[e.None=1]="None",e[e.JavaScript=2]="JavaScript",e[e.Expression=3]="Expression"})(gh||(gh={}));(function(e){e[e.NoIcon=0]="NoIcon",e[e.UseIcon=1]="UseIcon",e[e.UseWebResource=2]="UseWebResource"})(vh||(vh={}));(function(e){e[e.Standard=0]="Standard",e[e.Dropdown=1]="Dropdown",e[e.Split=2]="Split",e[e.Group=3]="Group"})(yh||(yh={}));(function(e){e[e.Form=0]="Form",e[e.HomePageGrid=1]="HomePageGrid",e[e.SubGridStandard=2]="SubGridStandard",e[e.SubGridAssociated=3]="SubGridAssociated",e[e.QuickForm=4]="QuickForm",e[e.Global=5]="Global",e[e.Dashboard=6]="Dashboard"})(bh||(bh={}));(function(e){e[e.All=0]="All",e[e.Entity=1]="Entity"})(wh||(wh={}));(function(e){e[e.App=0]="App",e[e.Entity=1]="Entity",e[e.Global=2]="Global"})(Ah||(Ah={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.JavaScript=2]="JavaScript"})(Ch||(Ch={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.ClassicRules=2]="ClassicRules"})(Eh||(Eh={}));(function(e){e[e.Default=0]="Default",e[e.Migrated=1]="Migrated",e[e.MigratedClone=2]="MigratedClone"})(Sh||(Sh={}));u7=["appactionid","appmoduleid","context","contextvalue","location","name","type","uniquename","isdisabled","origin"]});var C2=y(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});pc.commandApi=void 0;var b2=$t(),Er=Ee(),A2=ee(),ir=le(),c7="OnClickEventJavaScriptWebResourceId($select=name,webresourceid),IconWebResourceId($select=name,webresourceid)";async function dc(e,t){let r=`/EntityDefinitions(LogicalName='${(0,ir.odataPathLiteral)(t)}')${(0,ir.odataQuery)([["$select","MetadataId"]])}`,i=(0,Er.ensureSuccess)(await e.get(r),e.apiUrl(r)).body,a=i?.MetadataId;return a?(0,ir.normalizeGuid)(a,"entityMetadataId"):""}pc.commandApi={async get(e,t){let r=t,n=await dc(e,r),i=n?`_contextentity_value eq ${n}`:`contextvalue eq '${(0,ir.odataLiteral)(r)}'`,a=`/appactions${(0,ir.odataQuery)([["$expand",c7],["$filter",i]])}`,o,s=await(0,b2.collectPages)(e,a,"fetchArtifact('command')",c=>{o=c}),l={entityLogicalName:r,entityMetadataId:n,appActions:s},u={};for(let c of s){let d=typeof c.appactionid=="string"?c.appactionid:void 0;if(d){let p=c["@odata.etag"];u[(0,ir.normalizeGuid)(d,"appactionid")]=typeof p=="string"?p:null}}return{raw:l,etag:o?(0,Er.readEtag)(o):null,memberEtags:u}},async list(e,t){let r=t?.entityLogicalName;return r?[{type:"command",id:r,name:`${r} commands`,entityLogicalName:r,isDirty:!1}]:[]},async create(e,t){let r=t,n=r.entityMetadataId||await dc(e,r.entityLogicalName);return w2(e,{...r,entityMetadataId:n},!1)},async update(e,t,r,n,i){let a=r,o=a.entityMetadataId||await dc(e,a.entityLogicalName);return w2(e,{...a,entityMetadataId:o},!0,i)},async delete(e,t){let r=await dc(e,t),n=r?`_contextentity_value eq ${r}`:`contextvalue eq '${(0,ir.odataLiteral)(t)}'`,i=`/appactions${(0,ir.odataQuery)([["$select","appactionid"],["$filter",n]])}`,a=await(0,b2.collectPages)(e,i,"deleteArtifact('command')");for(let o of a)o.appactionid&&await(0,Er.deleteRecord)(e,"appactions",o.appactionid)}};async function w2(e,t,r,n){let i=t.entityMetadataId?(0,ir.normalizeGuid)(t.entityMetadataId,"entityMetadataId"):"",a=p7(t.rows),o={};try{await d7(e,t,a,i,r,n,o)}catch(s){throw(0,A2.withPartialTokens)(s,{memberEtags:o})}return{id:t.entityLogicalName,etag:null,memberEtags:o}}async function d7(e,t,r,n,i,a,o){var s,l,u;for(let c of r)if(i&&c.exists){let d=(0,ir.normalizeGuid)(c.appactionid,"id"),p=(s=a?.[d])!==null&&s!==void 0?s:c.etag,f=(0,Er.echoWrite)("appactionid",p?{"If-Match":p}:void 0),m=`/appactions(${d})${f.query}`,h=(0,Er.ensureSuccess)(await e.patch(m,c.body,f.options),e.apiUrl(m));o[d]=(0,Er.readEtag)(h)}else{let d=(0,Er.echoWrite)("appactionid"),p=`/appactions${d.query}`,f={...c.body};if(f["[email protected]"]===void 0){if(!n)throw new A2.SdkError("COMMAND_CONTEXT_ENTITY_UNRESOLVED",`Cannot create app action '${c.appactionid}' for entity '${t.entityLogicalName}': the entity MetadataId could not be resolved, so the required ContextEntity bind cannot be set. A row written without it is created but is permanently unreadable \u2014 commandApi.get filters on _contextentity_value. Verify the entity logical name exists and is readable, then retry.`);f["[email protected]"]=`/entities(${n})`}let m=(0,Er.ensureSuccess)(await e.post(p,f,d.options),e.apiUrl(p)),h=(0,Er.readCreatedId)(m,"appactionid");h&&(o[(0,ir.normalizeGuid)(h,"appactionid")]=(0,Er.readEtag)(m))}for(let c of[...(l=t.deletedRowIds)!==null&&l!==void 0?l:[]].reverse()){let d=(0,ir.normalizeGuid)(c,"id");await(0,Er.deleteRecord)(e,"appactions",d,(u=a?.[d])!==null&&u!==void 0?u:void 0),delete o[d]}}function p7(e){let t=new Map(e.map(a=>[a.appactionid,a])),r=new Set,n=[],i=a=>{if(r.has(a.appactionid))return;let o=a.body["[email protected]"];if(typeof o=="string"){let s=/\(([^)]+)\)/.exec(o),l=s?t.get(s[1]):void 0;l&&i(l)}r.add(a.appactionid),n.push(a)};return e.forEach(i),n}});var F2=y(eo=>{"use strict";Object.defineProperty(eo,"__esModule",{value:!0});eo.commandRegistration=eo.CommandAdapter=void 0;var $e=(y2(),_r(v2)),E2=hr(),ar=zr(),f7=C2(),m7=st(),to=le(),Ih="$ClientSvg:",_h=".svg",h7=2,g7=1,v7=1,D2="entityMetadataId",y7=new Set(["@odata.etag","IconWebResourceId","OnClickEventJavaScriptWebResourceId","VisibilityFormulaComponentLibraryId","OnClickEventFormulaComponentLibraryId","ContextEntity","_appmoduleid_value","_contextentity_value","_createdby_value","_createdonbehalfby_value","_iconwebresourceid_value","_modifiedby_value","_modifiedonbehalfby_value","_onclickeventformulacomponentlibraryid_value","_onclickeventjavascriptwebresourceid_value","_organizationid_value","_parentappactionid_value","_visibilityformulacomponentlibraryid_value","createdon","modifiedon","overriddencreatedon","overwritetime","componentstate","componentidunique","solutionid","ismanaged","iscustomizable","versionnumber","importsequencenumber","timezoneruleversionnumber","utcconversiontimezonecode","statecode","statuscode","scope"]),fc=class{toArtifact(t){var r,n,i,a,o,s;let l=(r=t.appActions)!==null&&r!==void 0?r:[],u=(n=t.entityLogicalName)!==null&&n!==void 0?n:"",c=new Map;for(let f of l){let m=typeof f._parentappactionid_value=="string"&&f._parentappactionid_value?f._parentappactionid_value:"",h=(i=c.get(m))!==null&&i!==void 0?i:[];h.push(f),c.set(m,h)}let d=new Map;for(let f of(a=c.get(""))!==null&&a!==void 0?a:[]){let m=E7(f.location),h=(o=d.get(m))!==null&&o!==void 0?o:[];h.push(f),d.set(m,h)}let p=[];for(let[f,m]of d)p.push({location:f,groups:w7(m,c,R2(f),u)});return{id:u,entityLogicalName:u,commandBars:C7(p),bag:{a:[[D2,(s=t.entityMetadataId)!==null&&s!==void 0?s:""]]}}}fromArtifact(t){return{entityLogicalName:t.entityLogicalName,entityMetadataId:Ph(t),appActions:Nh(t).map(r=>r.row)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t,r){let n=new Set(r?Nh(r).map(l=>l.appactionid):[]),i=Nh(t,new Set([...n].map(l=>l.toLowerCase()))),a=new Set(i.map(l=>l.appactionid)),o=i.map(l=>{let u=l.exists||n.has(l.appactionid);return{appactionid:l.appactionid,exists:u,etag:l.etag,body:u?F7(l.row):L2(l.row)}}),s=[...n].filter(l=>!a.has(l));return{entityLogicalName:t.entityLogicalName,entityMetadataId:Ph(t),rows:o,...s.length>0?{deletedRowIds:s}:{}}}createDefault(t){var r,n,i,a;let o=(n=(r=t.entityLogicalName)!==null&&r!==void 0?r:t.id)!==null&&n!==void 0?n:"";return{id:(i=t.id)!==null&&i!==void 0?i:o,entityLogicalName:o,commandBars:(a=t.commandBars)!==null&&a!==void 0?a:[]}}assignMissingIds(t){return(0,m7.assignMissingIds)(t)}validate(t){let r=[];return(0,ar.childObjects)(t,"commandBars","","commandBar",r).forEach(({node:i,index:a})=>{let o=`/commandBars/${a}`;(0,ar.optionalEnum)(i,"location",["MainTab","ContextualTab","HomeTab"],o,"bar-location-invalid",r),(0,ar.childObjects)(i,"groups",o,"group",r).forEach(({node:l,index:u})=>{let c=`${o}/groups/${u}`;I2(l.bag)||((0,ar.optionalGuidId)(l,"id",c,"group-id-invalid",r),typeof l.title=="string"&&l.title.length>0&&r.push({pointer:`${c}/title`,rule:"group-toplevel-title-unsupported",message:"a new top-level command group cannot have a title: Dataverse rejects a Group row with no parent (0x80040265). Leave the title empty to hold the commands without creating a group row, or nest them under a FlyoutAnchor control, which supplies the parent a group needs."})),_2((0,ar.childObjects)(l,"controls",c,"control",r),`${c}/controls`,r)})}),r}};eo.CommandAdapter=fc;function I2(e){let t=e?.a;return Array.isArray(t)&&t.length>0}function _2(e,t,r){e.forEach(({node:n,index:i})=>{let a=`${t}/${i}`;I2(n.bag)||(0,ar.optionalGuidId)(n,"id",a,"control-id-invalid",r),(0,ar.optionalEnum)(n,"type",["Button","FlyoutAnchor","SplitButton"],a,"control-type-invalid",r);let o=n.location;o!==void 0&&(typeof o!="number"||!Number.isInteger(o)||o<0||o>6)&&r.push((0,ar.issue)(`${a}/location`,"control-location-invalid",`location must be an integer 0-6 when present, got ${JSON.stringify(o)}`)),n.action!==void 0&&n.action!==null&&((0,ar.isJsonObject)(n.action)?(0,ar.optionalEnum)(n.action,"type",["javascript"],`${a}/action`,"action-type-invalid",r):r.push((0,ar.issue)(`${a}/action`,"control-action-must-be-object",`a control action must be a JSON object when present, got ${typeof n.action}`)));let s=(0,ar.childObjects)(n,"children",a,"control",r);s.length>0&&_2(s,`${a}/children`,r)})}function Th(e){return{a:Object.entries(e)}}function b7(e){return Object.fromEntries(e.a)}function mc(e,t){if(e){for(let[r,n]of e.a)if(r===t)return n}}function Ph(e){let t=mc(e.bag,D2);return typeof t=="string"?t:""}function w7(e,t,r,n){var i,a;let o=[],s=[];for(let l of gc(e))l.type===$e.ButtonType.Group?o.push({id:P2(l.name,n),title:typeof l.grouptitle=="string"?l.grouptitle:"",controls:gc((a=t.get((i=l.appactionid)!==null&&i!==void 0?i:""))!==null&&a!==void 0?a:[]).map(u=>hc(u,t,r,n)),bag:Th(l)}):s.push(hc(l,t,r,n));return s.length>0&&o.unshift({id:L7(n,r),title:"",controls:s}),o}function Rh(e){let t=e.bag?mc(e.bag,"appactionid"):void 0;return typeof t=="string"&&t.trim()!==""?t:e.id}function hc(e,t,r,n){var i,a,o,s,l;let u=P2(e.name,n),c={id:u,type:S7(e.type),label:typeof e.buttonlabeltext=="string"?e.buttonlabeltext:"",command:typeof e.appactionid=="string"?e.appactionid:u,bag:Th(e)},d=T2(e);d&&(c.icon=d);let p=A7(e);p&&(c.action=p),typeof e.hidden=="boolean"&&(c.hidden=e.hidden),typeof e.isdisabled=="boolean"&&(c.disabled=e.isdisabled),typeof e.location=="number"&&e.location!==r&&(c.location=e.location);let f=t.get((i=e.appactionid)!==null&&i!==void 0?i:"");if(f&&f.length>0){let m=[],h=[];for(let v of gc(f))if(v.type===$e.ButtonType.Group){let w=(a=v.appactionid)!==null&&a!==void 0?a:"",C=Th(v);c.flyoutGroupId===void 0&&(c.flyoutGroupId=(o=v.appactionid)!==null&&o!==void 0?o:void 0,c.flyoutGroupBag=C);let E=[];for(let D of gc((l=t.get((s=v.appactionid)!==null&&s!==void 0?s:""))!==null&&l!==void 0?l:[])){let O=hc(D,t,r,n);m.push(O),E.push(Rh(O))}h.push({id:w,bag:C,childIds:E})}else m.push(hc(v,t,r,n));c.children=m,h.length>1&&(c.flyoutGroups=h)}return c}function T2(e){var t;if(!((t=e.IconWebResourceId)===null||t===void 0)&&t.name)return e.IconWebResourceId.name;if(e.fonticon)return e.fonticon.startsWith(Ih)?e.fonticon.slice(Ih.length)+_h:e.fonticon}function A7(e){var t;let r=e.onclickeventjavascriptfunctionname;if(typeof r!="string"||!r)return;let n=e.OnClickEventJavaScriptWebResourceId,i=e._onclickeventjavascriptwebresourceid_value,a={type:"javascript",webResourceId:(t=typeof i=="string"?i:n?.webresourceid)!==null&&t!==void 0?t:"",functionName:r};n?.name&&(a.libraryName=n.name);let o=e.onclickeventjavascriptparameters;return typeof o=="string"&&o&&(a.parameters=o),a}function S2(e){return typeof e.sequence=="number"?e.sequence:typeof e.buttonsequencepriority=="number"?e.buttonsequencepriority:0}function gc(e){return[...e].sort((t,r)=>S2(t)-S2(r))}function C7(e){let t={MainTab:0,ContextualTab:1,HomeTab:2};return[...e].sort((r,n)=>{var i,a;return((i=t[r.location])!==null&&i!==void 0?i:9)-((a=t[n.location])!==null&&a!==void 0?a:9)})}function P2(e,t){if(!e)return"";if(e.indexOf("{!EntityLogicalName}")>=0)return e.replace("{!EntityLogicalName}",t);let r=e.split("!");return r.length===2?r[1]:e}function E7(e){switch(e){case $e.Location.Form:case $e.Location.QuickForm:return"MainTab";case $e.Location.HomePageGrid:case $e.Location.Dashboard:return"HomeTab";default:return"ContextualTab"}}function R2(e){switch(e){case"MainTab":return $e.Location.Form;case"HomeTab":return $e.Location.HomePageGrid;default:return $e.Location.SubGridStandard}}function S7(e){switch(e){case $e.ButtonType.Dropdown:return"FlyoutAnchor";case $e.ButtonType.Split:return"SplitButton";default:return"Button"}}function N7(e){switch(e){case"FlyoutAnchor":return $e.ButtonType.Dropdown;case"SplitButton":return $e.ButtonType.Split;default:return $e.ButtonType.Standard}}function D7(e){var t;return e.bag&&e.bag.a.length>0?!0:((t=e.title)!==null&&t!==void 0?t:"").length>0}function O2(e,t){var r,n,i;return((n=(r=e.bag)===null||r===void 0?void 0:r.a.length)!==null&&n!==void 0?n:0)>0?!0:t.has(((i=e.id)!==null&&i!==void 0?i:"").toLowerCase())}function Nh(e,t=new Set){var r,n,i,a;let o=[],s=Ph(e);for(let l of(r=e.commandBars)!==null&&r!==void 0?r:[]){let u=R2(l.location),c=((n=l.groups)!==null&&n!==void 0?n:[]).flatMap(f=>{var m;return(m=f.controls)!==null&&m!==void 0?m:[]}),d=c.length>0&&c.every(f=>!O2(f,t)),p=0;for(let f of(i=l.groups)!==null&&i!==void 0?i:[]){let m;if(D7(f)){let h=_7(f,u,void 0,e,s);o.push(h),m=h.appactionid}for(let h of(a=f.controls)!==null&&a!==void 0?a:[])x2(h,u,m,e,s,o,d?p:void 0,t),p+=1}}return o}function x2(e,t,r,n,i,a,o,s=new Set){var l;let u=I7(e,t,r,n,i,o);a.push(u);let c=(l=e.children)!==null&&l!==void 0?l:[];if(c.length===0&&!(e.flyoutGroups&&e.flyoutGroups.length>0))return;let d=c.every(h=>!O2(h,s)),p=(h,v,w)=>{x2(h,t,v,n,i,a,d?w:void 0,s)},f=e.flyoutGroups;if(f&&f.length>0){let h=new Map(c.map(D=>[Rh(D),D])),v=new Set,w=0,C;for(let[D,O]of f.entries()){let x=O.id||(D===0?Dh(u.appactionid):xh("flyout-group",`${u.appactionid}#${D}`)),F=N2(x,t,u.appactionid,n,i,O.bag);a.push(F);let M=F.appactionid;C===void 0&&(C=M);for(let P of O.childIds){let q=h.get(P);!q||v.has(P)||(v.add(P),p(q,M,w),w+=1)}}let E=C??Dh(u.appactionid);for(let D of c){let O=Rh(D);v.has(O)||(v.add(O),p(D,E,w),w+=1)}return}let m=e.flyoutGroupId||Dh(u.appactionid);a.push(N2(m,t,u.appactionid,n,i,e.flyoutGroupBag));for(let[h,v]of c.entries())p(v,m,h)}function I7(e,t,r,n,i,a){let o=Oh(e,t,r,n,i),s=o.row;a!==void 0&&typeof s.sequence!="number"&&(s.sequence=a);let l=T2(s);return e.location!==void 0&&(s.location=e.location),s.type=N7(e.type),s.buttonlabeltext=e.label,P7(s,e.icon,l),O7(s,e.action),R7(s),e.hidden!==void 0&&(s.hidden=e.hidden),e.disabled!==void 0&&(s.isdisabled=e.disabled),{...o,row:s}}function _7(e,t,r,n,i){let a=Oh(e,t,r,n,i);return a.row.type=$e.ButtonType.Group,a.row.grouptitle=e.title,a}function N2(e,t,r,n,i,a){let o=Oh({id:e,bag:a},t,r,n,i),s=o.row;return s["[email protected]"]=`/appactions(${(0,to.normalizeGuid)(r,"Command flyout group id")})`,s.type=$e.ButtonType.Group,s.grouptitle===void 0&&(s.grouptitle=""),s.isgrouptitlehidden===void 0&&(s.isgrouptitlehidden=!0),o}function Oh(e,t,r,n,i){let a,o,s,l;if(e.bag&&e.bag.a.length>0){a=b7(e.bag),o=!0;let u=mc(e.bag,"@odata.etag");s=typeof u=="string"?u:null;let c=mc(e.bag,"appactionid");l=typeof c=="string"&&c?c:e.id}else l=e.id,a=T7(l,t,n,i),o=!1,s=null;return r?a["[email protected]"]=`/appactions(${(0,to.normalizeGuid)(r,"Command parent appaction id")})`:o&&typeof a._parentappactionid_value=="string"&&a._parentappactionid_value&&a.type!==$e.ButtonType.Group&&(a["[email protected]"]=null),delete a._parentappactionid_value,{appactionid:l,exists:o,etag:s,row:a}}function T7(e,t,r,n){let i={appactionid:e,name:`${e}!${e.replace(/-/g,"").slice(0,32)}`,uniquename:"",location:t,context:$e.Context.Entity,contextvalue:r.entityLogicalName,scope:$e.Scope.Entity};return n&&(i["[email protected]"]=`/entities(${(0,to.normalizeGuid)(n,"Command context entity metadata id")})`),i}function P7(e,t,r){if(t===r){let n=e._iconwebresourceid_value;typeof n=="string"&&n&&!e.fonticon&&(e["[email protected]"]=`/webresourceset(${(0,to.normalizeGuid)(n,"Command icon web resource id")})`);return}if(t===void 0){e.fonticon="",e.IconWebResourceId=null;return}e.fonticon=t.toLowerCase().endsWith(_h)?Ih+t.slice(0,t.length-_h.length):t,e.IconWebResourceId=null}function R7(e){let t=(n,i)=>{let a=e[n];if(typeof a!="string"||a.length===0||e[`${i}@odata.bind`]!==void 0)return;let o=(0,to.normalizeGuid)(a,`Command ${i}`);e[`${i}@odata.bind`]=`/canvasapps(${o})`};e.onclickeventtype===g7&&t("_onclickeventformulacomponentlibraryid_value","OnClickEventFormulaComponentLibraryId");let r=e.visibilitytype;(!r||r===v7)&&t("_visibilityformulacomponentlibraryid_value","VisibilityFormulaComponentLibraryId")}function O7(e,t){if(!(!t||t.type!=="javascript")){if(e.onclickeventtype=h7,t.webResourceId){let r=(0,to.normalizeGuid)(t.webResourceId,"Command action web resource id");e["[email protected]"]=`/webresourceset(${r})`}e.onclickeventjavascriptfunctionname=t.functionName,t.parameters!==void 0&&(e.onclickeventjavascriptparameters=t.parameters)}}function x7(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return t>>>0}function xh(e,t){let r="";for(let n=0;n<4;n+=1)r+=x7(`${n}:${e}:${t}`).toString(16).padStart(8,"0");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`}function Dh(e){return xh("flyout-group",e)}function L7(e,t){return xh("loose-group",`${e}|${t}`)}function L2(e){let t={...e};for(let r of y7)delete t[r];return t}function F7(e){let t=L2(e);for(let r of $e.CannotUpdateAppActionColumns)delete t[r];return t}function k7(){return{adapter:new fc,api:f7.commandApi,publish:(e,t,r)=>(0,E2.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,E2.boundEntityPublishScope)(t)}}eo.commandRegistration=k7});var k2=y(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});vc.chartApi=void 0;var M7=$t(),or=Ee(),Rs=le(),B7="savedqueryvisualizationid,name,description,primaryentitytypecode,datadescription,presentationdescription,charttype,type,isdefault",U7="savedqueryvisualizationid,name,primaryentitytypecode,charttype,isdefault";vc.chartApi={async get(e,t){let n=`/savedqueryvisualizations(${(0,Rs.normalizeGuid)(t,"id")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Rs.odataQuery)([["$select",B7]]),i=(0,or.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,or.readEtag)(i)}},async list(e,t){let r=`/savedqueryvisualizations${(0,Rs.odataQuery)([["$select",U7],["$filter",t?.entityLogicalName?`primaryentitytypecode eq '${(0,Rs.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,M7.collectPages)(e,r,"listArtifacts('chart')")).map(i=>{var a,o;return{type:"chart",id:(a=i.savedqueryvisualizationid)!==null&&a!==void 0?a:"",name:(o=i.name)!==null&&o!==void 0?o:"",entityLogicalName:i.primaryentitytypecode,isDirty:!1}})},async create(e,t,r){let n=t,i=(0,or.echoWrite)("savedqueryvisualizationid"),a=`/savedqueryvisualizations${i.query}`,o=(0,or.ensureSuccess)(await e.post(a,(0,or.withClientMintedId)({name:n.name,description:n.description,datadescription:n.datadescription,presentationdescription:n.presentationdescription,primaryentitytypecode:n.primaryentitytypecode,charttype:n.charttype,isdefault:n.isdefault},"savedqueryvisualizationid",r),i.options),e.apiUrl(a));return{id:(0,or.resolveCreatedId)(o,"savedqueryvisualizationid","chart",r),etag:(0,or.readEtag)(o)}},async update(e,t,r,n){let i=r,a=(0,Rs.normalizeGuid)(t,"id"),o=(0,or.echoWrite)("savedqueryvisualizationid",{"If-Match":(0,or.requireEtag)(n,"chart",a)}),s=`/savedqueryvisualizations(${a})${o.query}`,l=(0,or.ensureSuccess)(await e.patch(s,{name:i.name,description:i.description,datadescription:i.datadescription,presentationdescription:i.presentationdescription},o.options),e.apiUrl(s));return{id:a,etag:(0,or.readEtag)(l)}},delete(e,t){return(0,or.deleteRecord)(e,"savedqueryvisualizations",t)}}});var eT=y(no=>{"use strict";Object.defineProperty(no,"__esModule",{value:!0});no.chartRegistration=no.ChartAdapter=void 0;var Lh=Mn(),M2=zr(),jr=mi(),B2=hr(),$7=k2(),Fh=Un(),q7=st(),V7=["Column","StackedColumn","StackedColumn100","Bar","StackedBar","StackedBar100","Area","StackedArea","StackedArea100","Line","Pie","Doughnut","Funnel","Tag"],G7=new Map(V7.map(e=>[e.toLowerCase(),e]));function G2(e){var t;return e&&(t=G7.get(e.toLowerCase()))!==null&&t!==void 0?t:"Column"}function z7(){return'<Chart Palette="BrightPastel"><Series><Series ChartType="Column" ChartArea="Default" /></Series><ChartAreas><ChartArea Name="Default" /></ChartAreas><Legends><Legend Name="Default" /></Legends></Chart>'}function W7(e){var t,r;let n=e.entityLogicalName,i=e.series.map((h,v)=>({alias:`agg_${v}`,series:h})),a=e.categories.map((h,v)=>({alias:`grp_${v}`,category:h})),o=h=>`<attribute alias="${h.alias}" name="${ro(h.series.attribute)}" aggregate="${ro(h.series.aggregate)}" />`,s=h=>`<attribute alias="${h.alias}" name="${ro(h.category.attribute)}" groupby="true"${h.category.dateGrouping?` dategrouping="${ro(h.category.dateGrouping)}"`:""} />`,l=[],u=new Map,c=(h,v)=>{if(!h){l.push(v);return}let w=u.get(h);w?w.push(v):u.set(h,[v])};i.forEach(h=>c(h.series.relatedEntity,o(h))),a.forEach(h=>c(h.category.relatedEntity,s(h)));let d=[...u.entries()].map(([h,v])=>`<link-entity name="${ro(h)}">${v.join("")}</link-entity>`).join(""),p=l.join("")+d,f=i.map(h=>`<measurecollection><measure alias="${h.alias}" /></measurecollection>`).join(""),m=(r=(t=a[0])===null||t===void 0?void 0:t.alias)!==null&&r!==void 0?r:"";return`<datadefinition><fetchcollection><fetch mapping="logical" aggregate="true"><entity name="${ro(n)}">${p}</entity></fetch></fetchcollection><categorycollection><category alias="${m}">${f}</category></categorycollection></datadefinition>`}var yc=class{toArtifact(t){var r,n,i,a,o,s,l;(0,Fh.installDomShim)();let u=(r=t.datadescription)!==null&&r!==void 0?r:"",c=(n=t.presentationdescription)!==null&&n!==void 0?n:"",d=(0,jr.parseXmlRoot)(u,"<datadefinition/>"),p=(0,jr.parseXmlRoot)(c,"<Chart/>");return{id:(i=t.savedqueryvisualizationid)!==null&&i!==void 0?i:"",name:(a=t.name)!==null&&a!==void 0?a:"",description:(o=t.description)!==null&&o!==void 0?o:"",entityLogicalName:(s=t.primaryentitytypecode)!==null&&s!==void 0?s:"",chartType:z2(p),isDefault:(l=t.isdefault)!==null&&l!==void 0?l:!1,series:H2(d),categories:J2(d),presentation:W2(p),dataBag:u?(0,jr.projectElementBag)(d):void 0,presentationBag:c?(0,jr.projectElementBag)(p):void 0,rowBag:j7(t.charttype,t.type)}}fromArtifact(t){(0,Fh.installDomShim)();let{datadescription:r,presentationdescription:n}=H7(t);return{savedqueryvisualizationid:t.id,name:t.name,description:t.description,primaryentitytypecode:t.entityLogicalName,datadescription:r,presentationdescription:n,charttype:U2(t.rowBag,"charttype"),type:U2(t.rowBag,"type"),isdefault:t.isDefault}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t){var r,n,i,a,o,s,l;let u=this.fromArtifact(t);return{name:(r=u.name)!==null&&r!==void 0?r:"",description:(n=u.description)!==null&&n!==void 0?n:"",datadescription:(i=u.datadescription)!==null&&i!==void 0?i:"",presentationdescription:(a=u.presentationdescription)!==null&&a!==void 0?a:"",primaryentitytypecode:(o=u.primaryentitytypecode)!==null&&o!==void 0?o:"",charttype:(s=u.charttype)!==null&&s!==void 0?s:0,isdefault:(l=u.isdefault)!==null&&l!==void 0?l:!1}}createDefault(t){var r,n,i,a,o,s,l;(0,Fh.installDomShim)();let u=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,q7.newId)(),name:(i=t.name)!==null&&i!==void 0?i:"New Chart",description:(a=t.description)!==null&&a!==void 0?a:"",entityLogicalName:u,chartType:(o=t.chartType)!==null&&o!==void 0?o:"Column",isDefault:(s=t.isDefault)!==null&&s!==void 0?s:!1,series:t.series&&t.series.length>0?t.series:[{attribute:"createdon",aggregate:"count"}],categories:t.categories&&t.categories.length>0?t.categories:[{attribute:"createdon",dateGrouping:"month"}],presentation:(l=t.presentation)!==null&&l!==void 0?l:{palette:"BrightPastel",showLegend:!0}}}assignMissingIds(t){return t}validate(t){let r=[],n=t;return(0,M2.childObjects)(n,"series","","series",r),(0,M2.childObjects)(n,"categories","","category",r),r}};no.ChartAdapter=yc;function j7(e,t){let r=[];return e!==void 0&&r.push(["charttype",String(e)]),t!==void 0&&r.push(["type",String(t)]),r.length>0?{a:r,c:[]}:void 0}function U2(e,t){if(!e)return;let r=e.a.find(([i])=>i===t);if(!r)return;let n=parseInt(r[1],10);return Number.isNaN(n)?void 0:n}function z2(e){let t=e.getElementsByTagName("Series");for(let r=0;r<t.length;r+=1)if(t[r].getAttribute("ChartType"))return G2(t[r].getAttribute("ChartType"));return"Column"}function W2(e){var t;let r={showLegend:e.getElementsByTagName("Legend").length>0},n=e.getAttribute("Palette");n&&(r.palette=n);let i=e.getElementsByTagName("Title")[0],a=((t=i?.textContent)!==null&&t!==void 0?t:"").trim();return a&&(r.title=a),r}function bc(e){return e.getElementsByTagName("fetch")[0]}function j2(e){let t=new Map;if(!e)return t;let r=e.getElementsByTagName("link-entity");for(let n=0;n<r.length;n+=1){let i=r[n],a=i.getAttribute("name");if(!a)continue;let o=i.getElementsByTagName("attribute");for(let s=0;s<o.length;s+=1){let l=o[s],u=l.getAttribute("alias")||l.getAttribute("name");u&&t.set(u,a)}}return t}function H2(e){let t=bc(e);if(!t)return[];let r=j2(t),n=t.getElementsByTagName("attribute"),i=[];for(let a=0;a<n.length;a+=1){let o=n[a],s=o.getAttribute("aggregate");if(!s)continue;let l=o.getAttribute("name");if(!l)continue;let u={attribute:l,aggregate:s},c=o.getAttribute("charttype");c&&(u.seriesType=G2(c));let d=o.getAttribute("alias");d&&(u.alias=d);let p=d??l,f=r.get(p);f&&(u.relatedEntity=f),i.push(u)}return i}function J2(e){var t;let r=bc(e);if(!r)return[];let n=j2(r),i=r.getElementsByTagName("attribute"),a=[];for(let o=0;o<i.length;o+=1){let s=i[o];if(((t=s.getAttribute("groupby"))!==null&&t!==void 0?t:"").toLowerCase()!=="true")continue;let l=s.getAttribute("name");if(!l)continue;let u={attribute:l},c=s.getAttribute("dategrouping");c&&(u.dateGrouping=c);let d=s.getAttribute("alias");d&&(u.alias=d);let p=d??l,f=n.get(p);f&&(u.relatedEntity=f),a.push(u)}return a}function H7(e){if(!$2(e.dataBag)||!$2(e.presentationBag)){let a=W7(e);return{datadescription:a,presentationdescription:pz(e,a)}}let t=new DOMParser().parseFromString("<root/>","text/xml"),r=q2(e.dataBag,"datadefinition",t),n=q2(e.presentationBag,"Chart",t),i=H2(r);if(!kh(e.series,i)){let a=Mh(r);J7(t,r,e.series);let o=Mh(r),s=o.length>0?o:e.series.map(()=>"");K2(t,n,s,a,e.chartType)}return kh(e.categories,J2(r))||K7(t,r,e.categories),e.chartType!==z2(n)&&Y2(n,e.chartType),kh(e.presentation,W2(n))||Z2(n,e.presentation),{datadescription:(0,jr.serializeNode)(r),presentationdescription:(0,jr.serializeNode)(n)}}function $2(e){return!!e&&(e.c.length>0||e.a.length>0)}function K2(e,t,r,n,i){let a,o=t.childNodes;for(let d=0;d<o.length;d+=1)if(o[d].nodeType===1&&o[d].tagName==="Series"){a=o[d];break}a||(a=e.createElement("Series"),t.insertBefore(a,t.firstChild));let s=[],l=a.childNodes;for(let d=0;d<l.length;d+=1)l[d].nodeType===1&&l[d].tagName==="Series"&&s.push(l[d]);let u=new Map;n.forEach((d,p)=>{let f=s[p];if(!f)return;let m=u.get(d);m?m.push(f):u.set(d,[f])});let c=r.map(d=>{let p=u.get(d),f=p&&p.length>0?p.shift():void 0;if(f)return f;let m=e.createElement("Series");m.setAttribute("ChartType",i);let h=s.length>0?s[0].getAttribute("ChartArea"):null;return h&&m.setAttribute("ChartArea",h),m});for(let d of s)a.removeChild(d);for(let d of c)a.appendChild(d)}function Mh(e){let t=[],r=e.getElementsByTagName("measure");for(let n=0;n<r.length;n+=1)t.push(r[n].getAttribute("alias")||"");return t}function q2(e,t,r){let n={n:t,a:(0,Lh.mergeAttrs)(e.a,[]),c:(0,Lh.spliceChildren)(e.c,[])};return(0,Lh.rebuildRaw)(n,(0,jr.domEngine)(r),null)}function J7(e,t,r){let n=bc(t),i=n?.getElementsByTagName("entity")[0];!n||!i||Q2(e,t,i,rz(n),r,iz,{aliasPrefix:"aggregate_column",addRef:Y7,removeRef:tz})}function K7(e,t,r){let n=bc(t),i=n?.getElementsByTagName("entity")[0];!n||!i||Q2(e,t,i,nz(n),r,az,{aliasPrefix:"groupby_column",addRef:Z7,removeRef:ez})}function Q2(e,t,r,n,i,a,o){let s=new Map;for(let f of n){let m=f.getAttribute("alias");m&&s.set(m,f)}let l=new Set,u=[],c=(f,m)=>{var h;let v=oz(r,f),w=m.relatedEntity;(v??void 0)!==(w??void 0)&&((h=f.parentNode)===null||h===void 0||h.removeChild(f),V2(e,r,f,w))};for(let f of i){let m=f.alias?s.get(f.alias):void 0;m&&!l.has(m)?(a(m,f),c(m,f),l.add(m)):u.push(f)}let d=n.filter(f=>!l.has(f)),p=0;for(let f of u)if(p<d.length){let m=d[p];a(m,f),c(m,f),l.add(m),p+=1}else{let m=e.createElement("attribute"),h=f.alias||X7(t,o.aliasPrefix);m.setAttribute("alias",h),a(m,f),V2(e,r,m,f.relatedEntity),o.addRef(e,t,h)}for(let f of n)if(!l.has(f)){let m=f.getAttribute("alias");m&&o.removeRef(t,m),lz(f)}}function Q7(e){let t=new Set;for(let r of["attribute","measure","category"]){let n=e.getElementsByTagName(r);for(let i=0;i<n.length;i+=1){let a=n[i].getAttribute("alias");a&&t.add(a)}}return t}function X7(e,t){let r=Q7(e);if(!r.has(t))return t;for(let n=2;;n+=1){let i=`${t}_${n}`;if(!r.has(i))return i}}function X2(e,t){let r=t.getElementsByTagName("categorycollection")[0];if(r)return r;let n=e.createElement("categorycollection");return t.appendChild(n),n}function Y7(e,t,r){let n=X2(e,t),i=n.getElementsByTagName("category")[0];i||(i=e.createElement("category"),n.appendChild(i));let a=e.createElement("measurecollection"),o=e.createElement("measure");o.setAttribute("alias",r),a.appendChild(o),i.appendChild(a)}function Z7(e,t,r){let n=X2(e,t),i=e.createElement("category");i.setAttribute("alias",r),n.appendChild(i)}function ez(e,t){let r=e.getElementsByTagName("category");for(let n=0;n<r.length;n+=1)r[n].getAttribute("alias")===t&&r[n].removeAttribute("alias")}function tz(e,t){var r;let n=e.getElementsByTagName("measure"),i=[];for(let a=0;a<n.length;a+=1)n[a].getAttribute("alias")===t&&i.push(n[a]);for(let a of i){let o=a.parentNode;o?.removeChild(a),o&&o.tagName==="measurecollection"&&!cz(o)&&((r=o.parentNode)===null||r===void 0||r.removeChild(o))}}function rz(e){let t=[],r=e.getElementsByTagName("attribute");for(let n=0;n<r.length;n+=1)r[n].getAttribute("aggregate")&&t.push(r[n]);return t}function nz(e){var t;let r=[],n=e.getElementsByTagName("attribute");for(let i=0;i<n.length;i+=1)((t=n[i].getAttribute("groupby"))!==null&&t!==void 0?t:"").toLowerCase()==="true"&&r.push(n[i]);return r}function iz(e,t){e.setAttribute("name",t.attribute),e.setAttribute("aggregate",t.aggregate),t.seriesType&&e.setAttribute("charttype",t.seriesType)}function az(e,t){e.setAttribute("name",t.attribute),e.setAttribute("groupby","true"),t.dateGrouping?e.setAttribute("dategrouping",t.dateGrouping):e.getAttribute("dategrouping")!==null&&e.removeAttribute("dategrouping")}function oz(e,t){let r=t.parentNode;for(;r&&r!==e;){let n=r;if(n.nodeType===1&&n.tagName==="link-entity")return n.getAttribute("name")||void 0;r=n.parentNode}}function V2(e,t,r,n){n?sz(e,t,n).appendChild(r):t.appendChild(r)}function sz(e,t,r){let n=t.getElementsByTagName("link-entity");for(let a=0;a<n.length;a+=1)if(n[a].getAttribute("name")===r)return n[a];let i=e.createElement("link-entity");return i.setAttribute("name",r),t.appendChild(i),i}function lz(e){let t=e.parentNode;if(t&&(t.removeChild(e),t.tagName==="link-entity"&&!uz(t))){let r=t.parentNode;r&&r.removeChild(t)}}function uz(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1){let n=t[r];if(n.nodeType===1){let i=n.tagName;if(i==="attribute"||i==="link-entity")return!0}}return!1}function cz(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1)if(t[r].nodeType===1)return!0;return!1}function Y2(e,t){let r=e.getElementsByTagName("Series"),n=!1;for(let i=0;i<r.length;i+=1)r[i].getAttribute("ChartType")&&(r[i].setAttribute("ChartType",t),n=!0);if(!n){for(let i=0;i<r.length;i+=1)if(!dz(r[i])){r[i].setAttribute("ChartType",t);return}}}function dz(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1){let n=t[r];if(n.nodeType===1&&n.tagName==="Series")return!0}return!1}function Z2(e,t){var r;let n=e.ownerDocument;if(t.palette!==void 0&&e.setAttribute("Palette",t.palette),t.showLegend!==void 0){let i=[],a=e.getElementsByTagName("Legends");for(let o=0;o<a.length;o+=1)i.push(a[o]);if(t.showLegend&&i.length===0){let o=n.createElement("Legends"),s=n.createElement("Legend");s.setAttribute("Name","Default"),o.appendChild(s),e.appendChild(o)}else if(!t.showLegend)for(let o of i)(r=o.parentNode)===null||r===void 0||r.removeChild(o)}if(t.title!==void 0){let i=e.getElementsByTagName("Title")[0];i&&(i.textContent=t.title)}}function pz(e,t){let r=(0,jr.parseXmlRoot)(z7(),"<Chart/>");Y2(r,e.chartType),Z2(r,e.presentation);let n=Mh((0,jr.parseXmlRoot)(t,"<datadefinition/>"));return n.length>0&&K2(r.ownerDocument,r,n,n.slice(0,1),e.chartType),(0,jr.serializeNode)(r)}function kh(e,t){return JSON.stringify(e)===JSON.stringify(t)}function ro(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function fz(){return{adapter:new yc,api:$7.chartApi,publish:(e,t,r)=>(0,B2.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,B2.boundEntityPublishScope)(t)}}no.chartRegistration=fz});var tT=y(wc=>{"use strict";Object.defineProperty(wc,"__esModule",{value:!0});wc.dashboardApi=void 0;var mz=$t(),sr=Ee(),Os=le(),hz="formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber",gz="formid,name,type,objecttypecode",vz=0,yz=10;wc.dashboardApi={async get(e,t){let n=`/systemforms(${(0,Os.normalizeGuid)(t,"id")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Os.odataQuery)([["$select",hz]]),i=(0,sr.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,sr.readEtag)(i)}},async list(e,t){let r=[`(type eq ${vz} or type eq ${yz})`];t?.entityLogicalName&&r.push(`objecttypecode eq '${(0,Os.odataLiteral)(t.entityLogicalName)}'`);let n=`/systemforms${(0,Os.odataQuery)([["$select",gz],["$filter",r.join(" and ")]])}`;return(await(0,mz.collectPages)(e,n,"listArtifacts('dashboard')")).map(a=>{var o,s;return{type:"dashboard",id:(o=a.formid)!==null&&o!==void 0?o:"",name:(s=a.name)!==null&&s!==void 0?s:"",entityLogicalName:a.objecttypecode,isDirty:!1}})},async create(e,t,r){let n=t,i=(0,sr.echoWrite)("formid"),a=`/systemforms${i.query}`,o={name:n.name,description:n.description,formxml:n.formxml,istabletenabled:n.istabletenabled,type:n.type};n.objecttypecode&&(o.objecttypecode=n.objecttypecode);let s=(0,sr.ensureSuccess)(await e.post(a,(0,sr.withClientMintedId)(o,"formid",r),i.options),e.apiUrl(a));return{id:(0,sr.resolveCreatedId)(s,"formid","dashboard",r),etag:(0,sr.readEtag)(s)}},async update(e,t,r,n){let i=r,a=(0,Os.normalizeGuid)(t,"id"),o=(0,sr.echoWrite)("formid",{"If-Match":(0,sr.requireEtag)(n,"dashboard",a)}),s=`/systemforms(${a})${o.query}`,l=(0,sr.ensureSuccess)(await e.patch(s,{name:i.name,description:i.description,formxml:i.formxml,istabletenabled:i.istabletenabled},o.options),e.apiUrl(s));return{id:a,etag:(0,sr.readEtag)(l)}},delete(e,t){return(0,sr.deleteRecord)(e,"systemforms",t)}}});var fT=y(Hr=>{"use strict";Object.defineProperty(Hr,"__esModule",{value:!0});Hr.dashboardRegistration=Hr.TILE_CLASS_ID=Hr.DashboardAdapter=void 0;var Ls=Mn(),lr=mi(),Bh=hr(),xs=zr(),bz=tT(),Uh=Un(),Li=st(),sT=le(),lT=Ji(),rT="0",$h="10",wz=new Map([["{E7A81278-8635-4D9E-8D4D-59480B391C5B}","chart"],["{FD2A7985-3187-444E-908D-6624B21F69C0}","iframe"],["{9FDF5F91-88B1-47F4-AD53-C11EFC01A01D}","webresource"],["{EE9078C8-6946-4E2C-B8F8-35E65F4BE6A8}","stream"],["{06375649-C143-495E-A496-C962E5B4488E}","timeline"],["{8C54228C-1B25-4909-A12A-F2B968BB0D62}","powerbi"],["{F9A8A302-114E-466A-B582-6771B2AE0D92}","assistant"]]),Az="{3FF9A528-DD50-4ACA-8F10-2E5ED73513AD}",Cc=class{constructor(t=lT.DEFAULT_LCID){this.lcid=t}toArtifact(t){var r,n,i,a;(0,Uh.installDomShim)();let o=(r=t.formxml)!==null&&r!==void 0?r:"",s=(0,lr.parseXmlRoot)(o,"<form/>");return{id:(n=t.formid)!==null&&n!==void 0?n:"",name:(i=t.name)!==null&&i!==void 0?i:"",description:(a=t.description)!==null&&a!==void 0?a:"",dashboardType:Cz(t.type),entityLogicalName:t.objecttypecode?t.objecttypecode:null,enabledForMobile:!!t.istabletenabled,layoutType:Ez(s),components:nT(s,this.lcid),bag:(0,lr.projectElementBag)(s)}}fromArtifact(t){var r;return(0,Uh.installDomShim)(),{formid:t.id,name:t.name,description:t.description,type:t.dashboardType==="Interactive"?$h:rT,objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",istabletenabled:t.enabledForMobile,formxml:iT(t,this.lcid)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t){return{name:t.name,description:t.description,formxml:iT(t,this.lcid),istabletenabled:t.enabledForMobile,type:t.dashboardType==="Interactive"?$h:rT,objecttypecode:t.entityLogicalName}}createDefault(t){var r,n,i,a,o,s,l,u;(0,Uh.installDomShim)();let c=(0,lr.parseXmlRoot)(kz(),"<form/>");return{id:(r=t.id)!==null&&r!==void 0?r:(0,Li.newId)(),name:(n=t.name)!==null&&n!==void 0?n:"New Dashboard",description:(i=t.description)!==null&&i!==void 0?i:"",dashboardType:(a=t.dashboardType)!==null&&a!==void 0?a:"Standard",entityLogicalName:(o=t.entityLogicalName)!==null&&o!==void 0?o:null,enabledForMobile:(s=t.enabledForMobile)!==null&&s!==void 0?s:!1,layoutType:(l=t.layoutType)!==null&&l!==void 0?l:0,components:(u=t.components)!==null&&u!==void 0?u:nT(c,this.lcid),bag:(0,lr.projectElementBag)(c)}}assignMissingIds(t){if(t&&typeof t=="object"&&!Array.isArray(t)&&"position"in t&&!("components"in t)){let r=t;(typeof r.id!="string"||r.id.length===0)&&(r.id=(0,Li.newId)())}return t}validate(t){let r=[],n=(0,xs.childObjects)(t,"components","","component",r),i=new Set;return n.forEach(({node:a,index:o})=>{let s=`/components/${o}`;for(let l of["position","parameters"]){let u=a[l];u!==void 0&&!(0,xs.isJsonObject)(u)&&r.push((0,xs.issue)(`${s}/${l}`,`component-${l}-must-be-object`,`a component ${l} must be a JSON object when present, got ${u===null?"null":typeof u}`))}if((0,xs.isJsonObject)(a.position)){let l=Fs(a.position);i.has(l)?r.push((0,xs.issue)(`${s}/position`,"component-position-collision",`two components occupy the same dashboard position (${l}); move one to a free cell`)):i.add(l)}}),r}};Hr.DashboardAdapter=Cc;function Cz(e){return String(e??"")===$h?"Interactive":"Standard"}function Ez(e){let t=e?.getAttribute("formLayout")||e?.getAttribute("layoutType"),r=parseInt(t??"",10);return Number.isNaN(r)?0:r}function Q(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let a=n[i];a.nodeType===1&&a.tagName.toLowerCase()===t&&r.push(a)}return r}function nT(e,t){let r=[];return Q(e,"tabs").flatMap(i=>Q(i,"tab")).forEach((i,a)=>{Q(i,"columns").flatMap(s=>Q(s,"column")).forEach((s,l)=>{Q(s,"sections").flatMap(c=>Q(c,"section")).forEach((c,d)=>{Sz(c,{tabIndex:a,columnIndex:l,sectionIndex:d},r,t)})})}),r}function Sz(e,t,r,n){Q(e,"rows").flatMap(a=>Q(a,"row")).forEach((a,o)=>{Q(a,"cell").forEach((s,l)=>{let u=Nz(s,{...t,rowIndex:o,cellIndex:l},n);u&&r.push(u)})})}function Nz(e,t,r){var n,i;let a=dT((n=e.getAttribute("id"))!==null&&n!==void 0?n:"");if(a.toLowerCase().startsWith("spacer"))return null;let o=Q(e,"control")[0];if(!o)return null;let s=(i=o.getAttribute("classid"))!==null&&i!==void 0?i:"",l=_z(o),u=Tz(s,l,o),c=Dz(o);return{id:o.getAttribute("id")||a,type:u,name:cT(e,r),classId:s,position:t,colspan:qh(e,"colspan",1),rowspan:qh(e,"rowspan",1),parameters:l,bag:(0,lr.projectElementBag)(e),...c?{icProperties:c}:{}}}function uT(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1){let n=t[r];if(n.nodeType===1&&n.tagName.toLowerCase()==="icproperties")return n}}function Dz(e){let t=uT(e);return t?(0,lr.serializeNode)(t):void 0}function Iz(e,t,r){let n=uT(t);if(!r){n&&t.removeChild(n);return}let i=new DOMParser().parseFromString(r,"text/xml").documentElement,a=(0,Ls.rebuildRaw)((0,Ls.rawFromNode)((0,lr.nodeLikeFromDom)(i)),(0,lr.domEngine)(e),null);n&&(0,lr.serializeNode)(n)===(0,lr.serializeNode)(a)||(n?t.replaceChild(a,n):t.appendChild(a))}function cT(e,t){var r,n;let i=Q(e,"labels")[0];if(!i)return"";let a=Q(i,"label"),o=(r=a.find(s=>s.getAttribute("languagecode")===String(t)))!==null&&r!==void 0?r:a[0];return(n=o?.getAttribute("description"))!==null&&n!==void 0?n:""}function _z(e){var t;let r={},n=Q(e,"parameters")[0];if(!n)return r;let i=n.childNodes;for(let a=0;a<i.length;a+=1){let o=i[a];o.nodeType===1&&(r[o.tagName]=((t=o.textContent)!==null&&t!==void 0?t:"").trim())}return r}function Tz(e,t,r){var n;let i=wz.get(e.toUpperCase());return i?i==="chart"?t.ChartGridMode==="Chart"?"chart":"list":i==="assistant"&&((n=r.getAttribute("uniqueid"))!==null&&n!==void 0?n:"").toUpperCase()===Az?"assistant":i:"unknown"}function qh(e,t,r){var n;let i=parseInt((n=e.getAttribute(t))!==null&&n!==void 0?n:"",10);return Number.isNaN(i)?r:i}function dT(e){return e.replace(/^\{/,"").replace(/\}$/,"")}function Pz(e,t){let r={n:"form",a:(0,Ls.mergeAttrs)(e.bag.a,[]),c:(0,Ls.spliceChildren)(e.bag.c,[])};return(0,Ls.rebuildRaw)(r,(0,lr.domEngine)(t),null)}function iT(e,t){let r=new DOMParser().parseFromString("<root/>","text/xml"),n=Pz(e,r);return xz(r,n,e.components,t),Rz(r,n,e.components,t),(0,lr.serializeNode)(n)}function Rz(e,t,r,n){let i=pT(t);for(let a of r)i.has(Fs(a.position))||Oz(e,t,a,n)}function Oz(e,t,r,n){var i,a,o,s;let l=(a=(i=r.position)===null||i===void 0?void 0:i.sectionIndex)!==null&&a!==void 0?a:0,u=Mz(t,e,l);for(let q of Q(u,"row"))Q(q,"cell").some($=>Q($,"control").length>0)||u.removeChild(q);let c=r.classId||Hr.TILE_CLASS_ID[r.type]||Hr.TILE_CLASS_ID.iframe,d=r.rowspan&&r.rowspan>0?r.rowspan:4,p=r.bag&&aT(r.bag,"id")?String(aT(r.bag,"id")):Ac((0,Li.newId)()),f=r.id?Ac(r.id):Ac((0,Li.newId)()),m=u.parentNode,h=Math.max(1,parseInt(m&&m.getAttribute&&m.getAttribute("columns")||"1",10)||1),v=Math.min(Math.max(1,r.colspan&&r.colspan>0?r.colspan:1),h),w=Q(u,"row"),C=w[w.length-1],E=C?Q(C,"cell").reduce((q,$)=>q+qh($,"colspan",1),0):0;(!C||E+v>h)&&(C=e.createElement("row"),u.appendChild(C));let D=e.createElement("cell");D.setAttribute("id",p),D.setAttribute("colspan",String(v)),D.setAttribute("rowspan",String(d)),D.setAttribute("showlabel","true");let O=e.createElement("labels"),x=e.createElement("label");x.setAttribute("description",(o=r.name)!==null&&o!==void 0?o:""),x.setAttribute("languagecode",String(n)),O.appendChild(x),D.appendChild(O);let F=e.createElement("control");F.setAttribute("id",f),F.setAttribute("classid",Ac(c));let M=e.createElement("parameters"),P=(s=r.parameters)!==null&&s!==void 0?s:{};for(let q of Object.keys(P)){let $=(0,sT.createSafeXmlElement)(e,q,"dashboard tile parameter");$.textContent=P[q],M.appendChild($)}F.appendChild(M),D.appendChild(F),C.appendChild(D)}function aT(e,t){if(!e)return;let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function xz(e,t,r,n){var i;let a=pT(t),o=new Set(r.map(s=>Fs(s.position)));for(let s of r){let l=a.get(Fs(s.position));if(!l)continue;let u=Q(l,"control")[0];u&&(Lz(e,l,s.name,n),Fz(e,u,s.parameters),oT(l,"colspan",s.colspan),oT(l,"rowspan",s.rowspan),s.icProperties!==void 0&&Iz(e,u,s.icProperties))}for(let[s,l]of a)o.has(s)||(i=l.parentNode)===null||i===void 0||i.removeChild(l)}function pT(e){let t=new Map;return Q(e,"tabs").flatMap(n=>Q(n,"tab")).forEach((n,i)=>{Q(n,"columns").flatMap(o=>Q(o,"column")).forEach((o,s)=>{Q(o,"sections").flatMap(u=>Q(u,"section")).forEach((u,c)=>{Q(u,"rows").flatMap(p=>Q(p,"row")).forEach((p,f)=>{Q(p,"cell").forEach((m,h)=>{var v;dT((v=m.getAttribute("id"))!==null&&v!==void 0?v:"").toLowerCase().startsWith("spacer")||Q(m,"control")[0]&&t.set(Fs({tabIndex:i,columnIndex:s,sectionIndex:c,rowIndex:f,cellIndex:h}),m)})})})})}),t}function Fs(e){let t=e??{};return`${t.tabIndex}.${t.columnIndex}.${t.sectionIndex}.${t.rowIndex}.${t.cellIndex}`}function Lz(e,t,r,n){if(r===cT(t,n))return;let i=Q(t,"labels")[0];i||(i=e.createElement("labels"),t.appendChild(i));let a=Q(i,"label").find(o=>o.getAttribute("languagecode")===String(n));a||(a=e.createElement("label"),a.setAttribute("languagecode",String(n)),i.appendChild(a)),a.setAttribute("description",r)}function Fz(e,t,r){var n;if(!r)return;let i=Object.keys(r);if(i.length===0)return;let a=Q(t,"parameters")[0];a||(a=e.createElement("parameters"),t.appendChild(a));let o=new Map,s=a.childNodes;for(let l=0;l<s.length;l+=1){let u=s[l];u.nodeType===1&&o.set(u.tagName,u)}for(let l of i){let u=r[l],c=o.get(l);if(c)((n=c.textContent)!==null&&n!==void 0?n:"")!==u&&(c.textContent=u);else{let d=(0,sT.createSafeXmlElement)(e,l,"dashboard component parameter");d.textContent=u,a.appendChild(d)}}}function oT(e,t,r){var n;((n=e.getAttribute(t))!==null&&n!==void 0?n:"")!==String(r)&&e.setAttribute(t,String(r))}function kz(e=2){let t=`{${(0,Li.newId)()}}`,r=`{${(0,Li.newId)()}}`,n=`{${(0,Li.newId)()}}`,i=Math.max(1,Math.floor(e));return`<form><tabs><tab id="${t}" name="General" showlabel="true" expanded="true" verticallayout="true"><columns><column width="100%"><sections><section id="${r}" name="Section 1" showlabel="false" columns="${i}"><rows><row><cell id="${n}" rowspan="12" colspan="${i}" showlabel="true" /></row></rows></section></sections></column></columns></tab></tabs></form>`}Hr.TILE_CLASS_ID={chart:"E7A81278-8635-4D9E-8D4D-59480B391C5B",list:"E7A81278-8635-4D9E-8D4D-59480B391C5B",iframe:"FD2A7985-3187-444E-908D-6624B21F69C0",webresource:"9FDF5F91-88B1-47F4-AD53-C11EFC01A01D"};function Ac(e){return`{${e.replace(/[{}]/g,"")}}`}function Mz(e,t,r){var n;let i=Q(e,"tabs").flatMap(u=>Q(u,"tab"))[0];if(!i)throw new Error("addDashboardTile: dashboard formxml has no <tab>");let a=Q(i,"columns").flatMap(u=>Q(u,"column"))[0];if(!a)throw new Error("addDashboardTile: dashboard formxml has no <column>");let o=Q(a,"sections").flatMap(u=>Q(u,"section")),s=(n=o[r])!==null&&n!==void 0?n:o[0];if(!s)throw new Error("addDashboardTile: dashboard formxml has no <section>");let l=Q(s,"rows")[0];return l||(l=t.createElement("rows"),s.appendChild(l)),l}function Bz(e=lT.DEFAULT_LCID){return{adapter:new Cc(e),api:bz.dashboardApi,languageSensitive:!0,publish:(t,r,n)=>n?.entityLogicalName?(0,Bh.publishBoundEntity)(t,n):(0,Bh.publishDashboardById)(t,r),publishScope:(t,r)=>r?.entityLogicalName?(0,Bh.boundEntityPublishScope)(r):{envelope:"dashboard",targetIds:[t]}}}Hr.dashboardRegistration=Bz});var _T=y(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});Nc.genPageApi=void 0;var Sc=$t(),ET=dl(),Ne=Ee(),ie=le(),Sr=Fl(),Le=ee(),ST=st();function Uz(e){if(ArrayBuffer.isView(e)){let r=e;return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}if(Object.prototype.toString.call(e)==="[object ArrayBuffer]")return new Uint8Array(e);let t=globalThis;if(t.Buffer&&t.Buffer.isBuffer(e)){let r=e;return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}}var Jr="uxagentprojects",ki="uxagentprojectfiles",Bs="agentconversationmessages",Us="uxagentprojectid",Ct="uxagentprojectfileid",Mi="agentconversationmessageid",ks=`${Us},name`,$z=`${Ct},filename,filetype`,NT=2e8,DT=200000001,Bi={"MSCRM.IncludeUnpublished":"true"},Vh={};function Fi(e,t){return{"MSCRM.VersioningChangeset":e,...Bi,...t}}async function zh(e,t,r,n){var i;let a=`/${t}(${r})`+(0,ie.odataQuery)([["$select",n]]),o=(0,Ne.ensureSuccess)(await e.get(a,{headers:{...Bi}}),e.apiUrl(a));return{row:(i=o.body)!==null&&i!==void 0?i:{},etag:(0,Ne.readEtag)(o)}}async function Ec(e,t,r=Bi){let n=`/${ki}(${t})/filecontent/$value`,i=await e.get(n,{headers:{...r}});if(i.status===404)return{status:"unavailable",reason:"missing"};(0,Ne.ensureSuccess)(i,e.apiUrl(n));let a=i.body,o=Uz(a);if(o)return{status:"available",data:(0,Sr.bytesToBase64)(o)};if(typeof a=="string")return{status:"available",data:(0,Sr.utf8ToBase64)(a)};throw new Le.SdkError("GENPAGE_CONTENT_UNREADABLE",`Read the content of file '${t}' but the injected HttpClient returned a body this SDK cannot encode (${typeof a}). Return the response as a string, Uint8Array, Buffer, or ArrayBuffer; a byte-returning transport is required to round-trip non-UTF8 assets.`)}function IT(e){let t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}async function qz(e,t,r,n,i,a){if(!e.supportsBinaryPatch)throw new Le.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED",`Refusing to push generative-page file '${t}': its content cannot be written because the injected HttpClient does not implement patchRaw(). A Dataverse File column is not writable through a JSON body, so saving the row without its bytes would report success for a page whose source never uploaded.`);let o=`/${ki}(${t})/filecontent`,s=(0,Sr.base64ToBytes)(n);(0,ie.assertNoControlChars)(r,"generative-page file name"),(0,Ne.ensureSuccess)(await e.patchRaw(o,s,{headers:Fi(i,{"Content-Type":"application/octet-stream","Content-Length":String(s.byteLength),"x-ms-file-name":IT(r),...a?{"If-Match":"*"}:{}})}),e.apiUrl(o))}async function Ms(e,t,r=Bi){let n=`/${ki}`+(0,ie.odataQuery)([["$select",$z],["$filter",`_${Us}_value eq ${t}`]]);return(await(0,Sc.collectPages)(e,n,"fetchArtifact('genPage')",void 0,{headers:{...r}})).map(a=>({row:a,etag:typeof a["@odata.etag"]=="string"?a["@odata.etag"]:null}))}async function Gh(e,t){let r=`/${Bs}`+(0,ie.odataQuery)([["$select",`${Mi},message,messagesender,createdon`],["$filter",`_regardingobjectid_value eq ${t}`],["$orderby","createdon asc,versionnumber asc"]]);return(0,Sc.collectPages)(e,r,"fetchArtifact('genPage')",void 0,{headers:{...Bi}})}async function mT(e,t){var r,n,i;let{row:a,etag:o}=await zh(e,Jr,t,ks),s=new Map;for(let{row:l,etag:u}of await Ms(e,t))s.set((0,ie.normalizeGuid)(String((r=l[Ct])!==null&&r!==void 0?r:""),Ct),{filename:String((n=l.filename)!==null&&n!==void 0?n:""),filetype:Number(l.filetype),etag:u});return{name:String((i=a.name)!==null&&i!==void 0?i:""),etag:o,rows:s}}function hT(e,t,r){var n,i,a,o,s;let l=[];r||l.push({kind:"createProject",name:t.name});let u=new Set;for(let c of(n=t.files)!==null&&n!==void 0?n:[]){let d=(0,ie.normalizeGuid)(c.id,"file id");u.add(d);let p=r?.rows.get(d);if(c.content.status==="retain"){if(!r)throw new Le.SdkError("GENPAGE_RETAIN_ON_CREATE",`Refusing to create generative page '${e}': file '${c.name}' asks to keep content the page does not have yet. This is an SDK defect \u2014 the page's rows were not written.`);if(!p)throw new Le.SdkError("GENPAGE_RETAINED_ROW_MISSING",`Refusing to write generative page '${e}': file '${c.name}' was to be kept unchanged but is not on the server. Re-fetch the page and retry.`);continue}p&&c.unchanged||(p?(p.filename!==c.name||p.filetype!==c.fileType)&&l.push({kind:"renameRow",file:c}):l.push({kind:"createRow",file:c}),c.content.status==="available"&&l.push({kind:"content",file:c,data:c.content.data,existing:p!==void 0}))}for(let c of(i=r?.rows.keys())!==null&&i!==void 0?i:[])u.has(c)||l.push({kind:"deleteRow",fileId:c});(!r||l.length>0||r.name!==t.name||((o=(a=t.messages)===null||a===void 0?void 0:a.length)!==null&&o!==void 0?o:0)>0)&&l.push({kind:"patchProject",name:t.name});for(let c of(s=t.messages)!==null&&s!==void 0?s:[])l.push({kind:"message",turn:c});return l}function jh(e){let t=(0,Sr.base64ToUtf8)(e);return(0,Sr.utf8ToBase64)(t)===(0,Sr.bytesToBase64)((0,Sr.base64ToBytes)(e))?t:void 0}function Vz(e,t,r,n){var i,a,o,s,l,u,c,d;let p=t.sender==="user"?{changeSet:n,dataSources:(a=(i=r.messageContext)===null||i===void 0?void 0:i.dataSources)!==null&&a!==void 0?a:[],model:(s=(o=r.messageContext)===null||o===void 0?void 0:o.model)!==null&&s!==void 0?s:"",enabledTools:(u=(l=r.messageContext)===null||l===void 0?void 0:l.enabledTools)!==null&&u!==void 0?u:[],configurableTools:(d=(c=r.messageContext)===null||c===void 0?void 0:c.configurableTools)!==null&&d!==void 0?d:[]}:{changeSet:n};return{...t.id?{[Mi]:(0,ie.normalizeGuid)(t.id,"message id")}:{},"[email protected]":`/${Jr}(${e})`,message:t.message,messagecontext:JSON.stringify(p),messagesender:t.sender==="user"?NT:DT}}async function Gz(e,t,r){var n,i,a,o;let s=((n=r.messages)!==null&&n!==void 0?n:[]).map(p=>p.id).filter(p=>typeof p=="string"&&p!=="").map(p=>(0,ie.normalizeGuid)(p,"message id"));if(s.length===0)return r;let l=`/${Bs}`+(0,ie.odataQuery)([["$select",`${Mi},message,messagesender,_regardingobjectid_value`],["$filter",s.map(p=>`${Mi} eq ${p}`).join(" or ")]]),u=await(0,Sc.collectPages)(e,l,"pushArtifact('genPage')",void 0,{headers:{...Bi}});if(u.length===0)return r;let c=new Map(u.map(p=>{var f;return[String((f=p[Mi])!==null&&f!==void 0?f:"").toLowerCase(),p]})),d=[];for(let p of(i=r.messages)!==null&&i!==void 0?i:[]){let f=p.id?c.get((0,ie.normalizeGuid)(p.id,"message id")):void 0;if(!f){d.push(p);continue}if(!(String((a=f.message)!==null&&a!==void 0?a:"")===p.message&&Number(f.messagesender)===(p.sender==="user"?NT:DT)&&String((o=f._regardingobjectid_value)!==null&&o!==void 0?o:"").toLowerCase()===t))throw new Le.SdkError("GENPAGE_TURN_CONFLICT",`Refusing to push generative page '${t}': its pending turn's identity is already recorded \u2014 as a DIFFERENT ${p.sender} message. An earlier push of this turn did commit (its response was lost), and the turn was changed since. Nothing was written, and the turn is still pending. To record it as a new turn, remove '/newTurn/id' (a new identity is minted on the next push); to keep only what was recorded, remove '/newTurn'.`)}return{...r,messages:d}}function Wh(e,t,r,n){switch(t.kind){case"createProject":return{method:"POST",path:`/${Jr}`,body:(0,Ne.withClientMintedId)({name:t.name},Us,e),headers:Fi(n)};case"createRow":return{method:"POST",path:`/${ki}`,body:(0,Ne.withClientMintedId)({filename:t.file.name,filetype:t.file.fileType,[`${Us}@odata.bind`]:`/${Jr}(${e})`},Ct,(0,ie.normalizeGuid)(t.file.id,"file id")),headers:Fi(n)};case"renameRow":return{method:"PATCH",path:`/${ki}(${(0,ie.normalizeGuid)(t.file.id,"file id")})`,body:{filename:t.file.name,filetype:t.file.fileType},headers:Fi(n,{"If-Match":"*"})};case"content":{let i=jh(t.data);if(i===void 0)throw new Le.SdkError("GENPAGE_CONTENT_NOT_TEXT",`File '${t.file.name}' is not UTF-8 text and cannot ride in a change set.`);return(0,ie.assertNoControlChars)(t.file.name,"generative-page file name"),{method:"PATCH",path:`/${ki}(${(0,ie.normalizeGuid)(t.file.id,"file id")})/filecontent`,rawBody:i,contentType:"application/octet-stream; charset=utf-8",headers:Fi(n,{"x-ms-file-name":IT(t.file.name),...t.existing?{"If-Match":"*"}:{}})}}case"deleteRow":return{method:"DELETE",path:`/${ki}(${t.fileId})`,headers:Fi(n,{"If-Match":"*"})};case"patchProject":return{method:"PATCH",path:`/${Jr}(${e})`,body:{name:t.name},headers:Fi(n,{"If-Match":"*"})};case"message":return{method:"POST",path:`/${Bs}`,body:Vz(e,t.turn,r,n)};default:{let i=t;throw new Le.SdkError("GENPAGE_WRITE_UNKNOWN",`Unknown generative-page write: ${JSON.stringify(i)}`)}}}function gT(e,t){return e.supportsAtomicBatch&&t.every(r=>r.kind!=="content"||jh(r.data)!==void 0)}async function vT(e,t,r,n,i){await(0,ET.postChangeSet)(e,r.map(a=>Wh(t,a,n,i)),`generative page '${t}' (${r.length} operation(s))`)}async function yT(e,t,r,n,i){var a;let o=[];for(let s of r){if(s.kind==="message"){o.push(s);continue}if(s.kind==="content"){await qz(e,(0,ie.normalizeGuid)(s.file.id,"file id"),s.file.name,s.data,i,s.existing);continue}let l=Wh(t,s,n,i),u={headers:(a=l.headers)!==null&&a!==void 0?a:{}},c=l.method==="POST"?await e.post(l.path,l.body,u):l.method==="PATCH"?await e.patch(l.path,l.body,u):await e.delete(l.path,u);(0,Ne.ensureSuccess)(c,e.apiUrl(l.path))}if(o.length===0)return{warnings:[],turnRecorded:!0};try{let s=o.map(l=>Wh(t,l,n,i));if(e.supportsAtomicBatch)await(0,ET.postChangeSet)(e,s,`the conversation turn of generative page '${t}'`);else for(let l of s)(0,Ne.ensureSuccess)(await e.post(l.path,l.body),e.apiUrl(l.path));return{warnings:[],turnRecorded:!0}}catch(s){return{warnings:[`Generative page '${t}' was saved, but its conversation turn could not be recorded (${s instanceof Error?s.message:String(s)}). The turn is kept: the next push of the page records it.`],turnRecorded:!1}}}async function bT(e,t,r,n,i,a,o){var s;let l=u=>({id:t,etag:null,memberEtags:{},warnings:[...o,u]});try{let u=await mT(e,t),c=new Map;for(let E of r)(E.kind==="createRow"||E.kind==="renameRow"||E.kind==="content")&&c.set((0,ie.normalizeGuid)(E.file.id,"file id"),E.file);let d=[];u.name!==n.name&&d.push(`the page is named '${u.name}', not '${n.name}'`);for(let[E,D]of c){let O=u.rows.get(E);O&&(O.filename!==D.name||O.filetype!==D.fileType)&&d.push(`file '${D.name}' is stored as '${O.filename}' (type ${O.filetype})`)}for(let E of r){if(E.kind!=="content")continue;let D=await Ec(e,(0,ie.normalizeGuid)(E.file.id,"file id")),O=(0,Sr.bytesToBase64)((0,Sr.base64ToBytes)(E.data));(D.status!=="available"||D.data!==O)&&d.push(D.status==="available"?`file '${E.file.name}' holds ${(0,Sr.base64ToBytes)(D.data).byteLength} byte(s) that differ from the ${(0,Sr.base64ToBytes)(O).byteLength} written`:`file '${E.file.name}' holds no content`)}let p=new Set(r.filter(E=>E.kind==="content").map(E=>(0,ie.normalizeGuid)(E.file.id,"file id")));for(let[E,D]of c)!p.has(E)&&(await Ec(e,E)).status==="available"&&d.push(`file '${D.name}' holds content this push did not write`);if(d.length>0)return l(`Generative page '${t}' was written, but reading it back does not match what was sent: ${d.join("; ")}. The local baseline is now unusable: re-fetch the page to see what the server holds \u2014 the next push will refuse rather than overwrite blind.`);let f=await mT(e,t),m=[...f.rows.keys()],h=f.etag!==u.etag||f.rows.size!==u.rows.size||m.some(E=>{var D,O;return((D=u.rows.get(E))===null||D===void 0?void 0:D.etag)!==((O=f.rows.get(E))===null||O===void 0?void 0:O.etag)}),v=m.length!==i.size||m.some(E=>!i.has(E)),w={},C=[];for(let[E,D]of f.rows){let O=c.has(E)||!a?D.etag:(s=a.get(E))!==null&&s!==void 0?s:null;w[E]=O,O!==D.etag&&C.push(D.filename)}return h||v||!f.etag||Object.values(w).some(E=>!E)?l(`Generative page '${t}' was written, but its files changed on the server while the write was in progress, so the new concurrency tokens cannot be trusted. The local baseline is now unusable: re-fetch the page before editing it again \u2014 the next push will refuse rather than overwrite blind.`):zz({id:t,etag:f.etag,memberEtags:w},[...o,...C.map(E=>`Generative page '${t}' was written, but its file '${E}' changed on the server while this push ran \u2014 another writer edited it. This push did not touch that file, so the next one refuses until you re-fetch the page and see their change.`)])}catch(u){return l(`The generative page was written, but reading it back failed (${u instanceof Error?u.message:String(u)}). The local baseline is unusable: re-fetch the page before editing it \u2014 the next push will refuse rather than overwrite blind.`)}}Nc.genPageApi={async get(e,t){var r;let n=(0,ie.normalizeGuid)(t,"id"),{row:i,etag:a}=await zh(e,Jr,n,ks),o=await Ms(e,n),s={},l=[];for(let{row:c,etag:d}of o){let p=(0,ie.normalizeGuid)(String((r=c[Ct])!==null&&r!==void 0?r:""),Ct);s[p]=d;let f=await Ec(e,p);l.push({...c,content:f})}let u=await Gh(e,n);return{raw:{project:i,files:l,conversation:u},etag:a,memberEtags:s}},async getPublished(e,t){var r,n;let i=(0,ie.normalizeGuid)(t,"id"),a=`/${Jr}(${i})`+(0,ie.odataQuery)([["$select",ks]]),o=await e.get(a);if(o.status===404)return null;(0,Ne.ensureSuccess)(o,e.apiUrl(a));let s=(r=o.body)!==null&&r!==void 0?r:{},l={},u=[],c=await Ms(e,i,Vh);for(let{row:v,etag:w}of c){let C=(0,ie.normalizeGuid)(String((n=v[Ct])!==null&&n!==void 0?n:""),Ct);l[C]=w,u.push({...v,content:await Ec(e,C,Vh)})}let d=v=>v.map(({row:w,etag:C})=>`${String(w[Ct])}@${String(C)}`).sort().join("|"),p=()=>new Le.SdkError("GENPAGE_PUBLISHED_READ_MOVED",`The published projection of generative page '${i}' changed while it was being read, so what was read is not one published state. PublishXml is asynchronous \u2014 re-read shortly.`),f=await e.get(a);if(f.status===404)throw p();(0,Ne.ensureSuccess)(f,e.apiUrl(a));let m=await Ms(e,i,Vh);if([(0,Ne.readEtag)(o),(0,Ne.readEtag)(f),...[...c,...m].map(v=>v.etag)].some(v=>!v))throw new Le.SdkError("GENPAGE_PUBLISHED_READ_UNVERSIONED",`The published projection of generative page '${i}' answered without a version token for the page or one of its rows, so what was read cannot be proven to be one published state.`);if((0,Ne.readEtag)(f)!==(0,Ne.readEtag)(o)||d(m)!==d(c))throw p();return{raw:{project:s,files:u,conversation:[]},etag:(0,Ne.readEtag)(o),memberEtags:l}},async list(e,t){let r=`/${Jr}`+(0,ie.odataQuery)([["$select",ks]]);return(await(0,Sc.collectPages)(e,r,"listArtifacts('genPage')",void 0,{headers:{...Bi}})).map(i=>{var a,o;return{type:"genPage",id:String((a=i[Us])!==null&&a!==void 0?a:""),name:String((o=i.name)!==null&&o!==void 0?o:""),isDirty:!1}})},async create(e,t,r){var n;let i=t;CT(e,i);let a=r?(0,ie.normalizeGuid)(r,"id"):(0,ST.newId)();AT(e,a,i);let o=hT(a,i,void 0),s=wT(),l=[],u=!0;gT(e,o)?await vT(e,a,o,i,s):{warnings:l,turnRecorded:u}=await yT(e,a,o,i,s);let c=new Set(((n=i.files)!==null&&n!==void 0?n:[]).map(p=>(0,ie.normalizeGuid)(p.id,"file id"))),d=await bT(e,a,o,i,c,void 0,l);return u?d:{...d,intentPending:!0}},async update(e,t,r,n,i){var a,o;let s=r,l=(0,ie.normalizeGuid)(t,"id");CT(e,s);let u=await Gz(e,l,s);AT(e,l,u);let c=await Ms(e,l),{row:d,etag:p}=await zh(e,Jr,l,ks);if(n&&p&&n!==p)throw new Le.SdkError(Ne.VERSION_CONFLICT_CODE,`Generative page '${l}' changed on the server after it was fetched (baseline ${n}, server ${p}) \u2014 another writer edited it. A page row accepts no If-Match validator, so this push would silently overwrite them. Re-fetch the page and re-apply the edit.`);if(!n||!p)throw new Le.SdkError(Ne.VERSION_CONFLICT_CODE,`Cannot verify generative page '${l}' before writing: ${n?"the server did not return the page's current token":"no baseline token was recorded"}. This entity accepts no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);let f=new Map(c.map(({row:F})=>{var M,P;return[(0,ie.normalizeGuid)(String((M=F[Ct])!==null&&M!==void 0?M:""),Ct),{filename:String((P=F.filename)!==null&&P!==void 0?P:""),filetype:Number(F.filetype)}]})),m=new Set(f.keys()),h=new Set(((a=u.files)!==null&&a!==void 0?a:[]).map(F=>(0,ie.normalizeGuid)(F.id,"file id")));if(!i)throw new Le.SdkError(Ne.VERSION_CONFLICT_CODE,`Cannot verify the files of generative page '${l}' before writing: no child baseline was recorded. These rows accept no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);let v=new Set(Object.keys(i).map(F=>F.toLowerCase()));for(let F of h)if(!m.has(F)&&v.has(F))throw new Le.SdkError(Ne.VERSION_CONFLICT_CODE,`Generative-page file '${F}' existed when this page was fetched but is gone from the server now \u2014 another writer deleted it. Refusing to recreate it, because a blind re-create would undo that delete. Re-fetch the page and re-apply the edit.`);for(let F of m)if(!v.has(F))throw new Le.SdkError(Ne.VERSION_CONFLICT_CODE,`Generative-page file '${F}' is on the server but absent from this page's baseline \u2014 another writer added it after the page was fetched, so its contents cannot be verified. Refusing to write over or delete it. Re-fetch the page so the addition is part of your baseline.`);let w=new Map(c.map(({row:F,etag:M})=>{var P;return[(0,ie.normalizeGuid)(String((P=F[Ct])!==null&&P!==void 0?P:""),Ct),M]}));for(let[F,M]of Object.entries(i)){let P=F.toLowerCase();if(!m.has(P))continue;let q=w.get(P);if(!M||!q)throw new Le.SdkError(Ne.VERSION_CONFLICT_CODE,`Cannot verify generative-page file '${P}' before writing: ${M?"the server did not return its current token":"no baseline token was recorded"}. A file row accepts no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);if(M!==q)throw new Le.SdkError(Ne.VERSION_CONFLICT_CODE,`Generative-page file '${P}' changed on the server after this page was fetched (baseline ${M}, server ${q}) \u2014 another writer edited it. A file row accepts no If-Match validator, so this push would silently overwrite that change. Re-fetch the page and re-apply the edit.`)}let C=hT(l,u,{rows:f,name:String((o=d.name)!==null&&o!==void 0?o:"")});if(C.length===0)return{id:l,etag:p,memberEtags:Object.fromEntries(c.map(({row:F,etag:M})=>{var P;return[(0,ie.normalizeGuid)(String((P=F[Ct])!==null&&P!==void 0?P:""),Ct),M]}))};let E=wT(),D=[],O=!0;gT(e,C)?await vT(e,l,C,u,E):{warnings:D,turnRecorded:O}=await yT(e,l,C,u,E);let x=await bT(e,l,C,u,h,w,D);return O?x:{...x,intentPending:!0}},async delete(e,t){var r;let n=(0,ie.normalizeGuid)(t,"id"),i=await Gh(e,n);await(0,Ne.deleteRecord)(e,Jr,n);let a=new Set(i.map(l=>{var u;return String((u=l[Mi])!==null&&u!==void 0?u:"")}).filter(l=>l!=="")),o=!1;try{for(let l of await Gh(e,n)){let u=String((r=l[Mi])!==null&&r!==void 0?r:"");u!==""&&a.add(u)}}catch{o=!0}let s=[];for(let l of a)try{await(0,Ne.deleteRecord)(e,Bs,l)}catch(u){u instanceof Le.ConnectionError&&u.statusCode===404||s.push(l)}if(s.length>0||o)throw new Le.SdkError("GENPAGE_HISTORY_NOT_DELETED",`Generative page '${n}' was deleted, but its conversation history was not fully removed`+(s.length>0?` \u2014 ${s.length} of ${a.size} message(s) could not be (${s.join(", ")})`:"")+(o?" \u2014 and re-reading it after the delete failed, so a late turn may remain":"")+`. They no longer belong to any page; delete them as ${Bs} rows regarding '${n}'.`)}};function wT(){return`uxagentproject_${(0,ST.newId)()}`}function zz(e,t){var r;return t.length===0?e:{...e,warnings:[...(r=e.warnings)!==null&&r!==void 0?r:[],...t]}}function AT(e,t,r){var n,i;if(((i=(n=r.messages)===null||n===void 0?void 0:n.length)!==null&&i!==void 0?i:0)>1&&!e.supportsAtomicBatch)throw new Le.SdkError("GENPAGE_TURN_NOT_ATOMIC",`Refusing to write generative page '${t}': its new turn has a prompt AND a reply, which must be recorded together, and the injected HttpClient does not implement postRaw() \u2014 one request at a time, a failure between the two would leave half a turn. Implement postRaw(), or record the prompt alone (omit newTurn.agentMessage). Nothing was written.`)}function CT(e,t){var r,n;if(((r=t.files)!==null&&r!==void 0?r:[]).some(o=>o.content.status==="available"&&!o.unchanged)&&!e.supportsBinaryPatch&&!e.supportsAtomicBatch)throw new Le.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED","Refusing to write this generative page: it has file content to upload, but the injected HttpClient implements neither patchRaw() nor postRaw(). A Dataverse File column is not writable through a JSON body, so proceeding would create the page and its rows and then fail, leaving a page whose source never uploaded.");if(((n=t.files)!==null&&n!==void 0?n:[]).some(o=>o.content.status==="available"&&!o.unchanged&&jh(o.content.data)===void 0)&&!e.supportsBinaryPatch)throw new Le.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED","Refusing to write this generative page: a file's content is not UTF-8 text, which only the binary channel can carry, and the injected HttpClient does not implement patchRaw().")}});var zT=y(ao=>{"use strict";Object.defineProperty(ao,"__esModule",{value:!0});ao.genPageRegistration=ao.GenPageAdapter=void 0;var Wz=_T(),jz=hr(),pe=zr(),Rc=st(),Oc=Fl(),Ui=ee(),TT=mp(),Hh=kd(),ai=2e8,$T=200000001,bn={source:{name:"src/pages/page.tsx",fileType:ai},output:{name:"src/pages/page.compiled",fileType:$T},config:{name:"config.json",fileType:ai},prompt:{name:"firstPrompt.json",fileType:ai}},qT=Object.keys(bn),Hz=["dataSources","model","connectorBindings","actionBindings"],Jz=["userMessage","agentMessage"],PT=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Kz={source:"6f1c2a4e9b3d47a1b85c0e2f7d914a63",output:"a8e53d17c2f64b09a1d7e4b8c3f2069d",config:"3b97f0c64e2a4d8f95b1c7a0e6d3f814",prompt:"d24e8b51f7a34c6e8b09d5f1a2c7e3b6"},Qz="9c3e7a15d2b84f6e8a01c5d7b3f9e240";function VT(e,t){var r;let n=e.replace(/[{}-]/g,"").toLowerCase(),i=[];for(let o=0;o<32;o+=1)i.push(parseInt((r=n[o])!==null&&r!==void 0?r:"0",16)^parseInt(t[o],16));i[12]=4,i[16]=i[16]&3|8;let a=i.map(o=>(Number.isNaN(o)?0:o).toString(16)).join("");return`${a.slice(0,8)}-${a.slice(8,12)}-${a.slice(12,16)}-${a.slice(16,20)}-${a.slice(20)}`}function Dc(e,t){return VT(e,Kz[t])}function Xz(e,t){let r=VT(e,Qz),n=parseInt(r.slice(24),16)%2**47+(t==="agent"?1:0);return`${r.slice(0,24)}${n.toString(16).padStart(12,"0")}`}function RT(e){return typeof e=="string"&&e.trim()!==""?e:(0,Rc.newId)()}function yn(e){return(0,pe.isJsonObject)(e)?e:{}}function io(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function Ic(e){return JSON.parse(JSON.stringify(e))}function Yz(e){let t=yn(e);return t.status==="available"&&typeof t.data=="string"?{status:"available",data:t.data}:{status:"unavailable",reason:t.reason==="unpublished"?"unpublished":"missing"}}function _c(e){if(!e||e.status!=="available")return;let t=(0,Oc.base64ToUtf8)(e.data);return(0,Oc.utf8ToBase64)(t)===e.data?t:void 0}function Tc(e){if(e!==void 0)try{let t=JSON.parse(e.replace(/^\uFEFF/,""));return(0,pe.isJsonObject)(t)?t:void 0}catch{return}}function OT(e,t){if(t===ai&&e.includes("page.tsx"))return"source";if(t===$T&&e.includes(".compiled"))return"output";if(t===ai&&e===bn.config.name)return"config";if(t===ai&&e===bn.prompt.name)return"prompt"}function xT(e){let t=e.toLowerCase();return qT.some(r=>bn[r].name.toLowerCase()===t)}function Jh(e){return Object.fromEntries(e)}function GT(e,t,r,n){let i=[],a=new Set,o=new Set(t),s=l=>{if(a.has(l))return;let u=o.has(l)?e[l]:r&&Object.prototype.hasOwnProperty.call(r,l)?r[l]:void 0;u!==void 0&&(a.add(l),i.push([l,u]))};return(n??[]).forEach(s),t.forEach(s),Object.keys(r??{}).forEach(s),Jh(i)}function LT(e){var t,r,n;return GT({dataSources:(t=e.dataSources)!==null&&t!==void 0?t:[],model:e.model,connectorBindings:e.connectorBindings,actionBindings:e.actionBindings},Hz,(r=e.bag)===null||r===void 0?void 0:r.config,(n=e.bag)===null||n===void 0?void 0:n.configKeys)}function FT(e){var t,r;return GT({userMessage:e.firstPrompt,agentMessage:e.firstAgentMessage},Jz,(t=e.bag)===null||t===void 0?void 0:t.prompt,(r=e.bag)===null||r===void 0?void 0:r.promptKeys)}function kT(e,t,r){let n=[];for(let[i,a]of Object.entries(r))if(i==="dataSources"){if(!Array.isArray(a)||!a.every(o=>typeof o=="string"))return!1;e.dataSources=a}else if(i==="model"){if(typeof a!="string")return!1;e.model=a}else i==="connectorBindings"?e.connectorBindings=a:i==="actionBindings"?e.actionBindings=a:n.push([i,a]);return t.configKeys=Object.keys(r),n.length>0&&(t.config=Jh(n)),!0}function MT(e,t,r){let n=[];for(let[i,a]of Object.entries(r))if(i==="userMessage"||i==="agentMessage"){if(typeof a!="string")return!1;i==="userMessage"?e.firstPrompt=a:e.firstAgentMessage=a}else n.push([i,a]);return t.promptKeys=Object.keys(r),n.length>0&&(t.prompt=Jh(n)),!0}function qs(e){var t,r;return e.source!==void 0||Object.keys((r=(t=e.bag)===null||t===void 0?void 0:t.rows)!==null&&r!==void 0?r:{}).length>0}var Zz=["dataSources","model","connectorBindings","actionBindings","firstPrompt","firstAgentMessage"];function BT(e){return qs(e)?[]:Zz.filter(t=>e[t]!==void 0).map(t=>(0,pe.issue)(`/${t}`,"genpage-raw-structured-field",`${t} cannot be applied: this page is in raw-file mode \u2014 it has no source and no managed rows, so a push writes its files[] exactly as they are, and ${t} nowhere. Set source to make the page managed (the SDK then writes config.json and firstPrompt.json from the typed fields; a file in files[] holding one of those names must be removed first), or change the file that stores the value in files[] directly.`))}function UT(){return(0,pe.issue)("/source","genpage-source-required","the page's source cannot be removed: its source row still exists, and a page without one cannot run. Set a new source, or delete the page with deleteRemoteArtifact.")}function Pc(e){return{status:"available",data:(0,Oc.utf8ToBase64)(e)}}function $s(e,t){var r,n;return{id:String((r=e.uxagentprojectid)!==null&&r!==void 0?r:""),name:String((n=e.name)!==null&&n!==void 0?n:""),files:t}}var xc=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){let r=t,n=yn(r?.project),i=(Array.isArray(r?.files)?r.files:[]).map(v=>{var w,C,E;let D=yn(v);return{id:String((w=D.uxagentprojectfileid)!==null&&w!==void 0?w:""),name:String((C=D.filename)!==null&&C!==void 0?C:""),fileType:Number((E=D.filetype)!==null&&E!==void 0?E:ai),content:Yz(D.content)}}),a=Array.isArray(r?.conversation)?r.conversation.map(v=>{var w,C;let E=yn(v);return{sender:Number(E.messagesender)===200000001?"agent":"user",message:String((w=E.message)!==null&&w!==void 0?w:""),createdOn:String((C=E.createdon)!==null&&C!==void 0?C:"")}}):void 0,o=v=>a?{...v,conversation:a}:v,s=new Map,l=[],u=!0;for(let v of i){let w=OT(v.name,v.fileType);w?((s.has(w)||v.name!==bn[w].name)&&(u=!1),s.set(w,v)):(xT(v.name)&&(u=!1),l.push(v))}if(!u||s.size===0)return o($s(n,i));let c=$s(n,l),d={rows:{}};for(let[v,w]of s)d.rows[v]=w.id;let p=s.get("source");if(p){let v=_c(p.content);if(v===void 0)return o($s(n,i));c.source=v}let f=s.get("output");f&&(d.output=f.content);let m=s.get("config");if(m){let v=Tc(_c(m.content));if(!v||!kT(c,d,v))return o($s(n,i))}let h=s.get("prompt");if(h){let v=Tc(_c(h.content));if(!v||!MT(c,d,v))return o($s(n,i))}return c.bag=d,o(c)}async toApiPayload(t,r,n){var i,a,o,s,l,u,c,d,p,f,m,h,v,w,C;if(r&&!io((i=t.conversation)!==null&&i!==void 0?i:[],(a=r.conversation)!==null&&a!==void 0?a:[]))throw new Ui.ValidationError("genPage",t.id,[(0,pe.issue)("/conversation","genpage-conversation-read-only","conversation is the page's recorded history and cannot be edited. Record a new turn with newTurn; revert the edit to conversation before pushing.")]);let E=BT(t);if(E.length>0)throw new Ui.ValidationError("genPage",t.id,E);let D=[],O=r===void 0,x=O&&t.firstPrompt===void 0&&t.newTurn?{...t,firstPrompt:t.newTurn.prompt,...t.newTurn.agentMessage!==void 0?{firstAgentMessage:t.newTurn.agentMessage}:{}}:t;if(qs(x)){let P=(s=(o=x.bag)===null||o===void 0?void 0:o.rows)!==null&&s!==void 0?s:{},q=X=>{var me;return(me=P[X])!==null&&me!==void 0?me:Dc(x.id,X)},$=(X,me,Re)=>{D.push({id:q(X),name:bn[X].name,fileType:bn[X].fileType,content:me,unchanged:Re})};if(x.source!==void 0){$("source",Pc(x.source),!O&&r?.source===x.source&&P.source!==void 0);let X=!O&&r?.source===x.source&&io((l=r?.dataSources)!==null&&l!==void 0?l:[],(u=x.dataSources)!==null&&u!==void 0?u:[]),me=_c((c=x.bag)===null||c===void 0?void 0:c.output);X&&P.output!==void 0&&(0,TT.isLoadableGenPageOutput)(me)?$("output",{status:"retain"},!0):$("output",Pc(await this.compile(x,x.source,n)),!1)}else{if(P.source!==void 0)throw new Ui.ValidationError("genPage",x.id,[UT()]);if(P.output!==void 0){if(!O&&!io((d=r?.dataSources)!==null&&d!==void 0?d:[],(p=x.dataSources)!==null&&p!==void 0?p:[]))throw new Ui.ValidationError("genPage",x.id,[(0,pe.issue)("/dataSources","genpage-source-required","the page has no source row, so its output cannot be recompiled for new data sources; set a source to change them.")]);$("output",{status:"retain"},!0)}}let qe=LT(x),Nt=!O&&r!==void 0&&io(LT(r),qe);(O||P.config!==void 0||!Nt)&&$("config",Pc(JSON.stringify(qe)),Nt&&P.config!==void 0);let ke=FT(x),He=!O&&r!==void 0&&io(FT(r),ke);(P.prompt!==void 0||Object.keys(ke).length>0&&!He)&&$("prompt",Pc(JSON.stringify(ke)),He&&P.prompt!==void 0)}for(let P of(f=x.files)!==null&&f!==void 0?f:[]){let q=(m=r?.files)===null||m===void 0?void 0:m.find($=>$.id===P.id);D.push({id:P.id,name:P.name,fileType:P.fileType,content:P.content,unchanged:q!==void 0&&io(q,P)})}let F=[];if(x.newTurn){let P=x.newTurn.id,q=$=>P?{id:Xz(P,$)}:{};F.push({...q("user"),sender:"user",message:x.newTurn.prompt}),x.newTurn.agentMessage&&F.push({...q("agent"),sender:"agent",message:x.newTurn.agentMessage})}let M=(v=(h=x.bag)===null||h===void 0?void 0:h.config)!==null&&v!==void 0?v:{};return{name:x.name,files:D,...F.length>0?{messages:F,messageContext:{dataSources:(w=x.dataSources)!==null&&w!==void 0?w:[],model:(C=x.model)!==null&&C!==void 0?C:"",enabledTools:Array.isArray(M.enabledTools)?M.enabledTools:[],configurableTools:Array.isArray(M.configurableTools)?M.configurableTools:[]}}:{}}}committed(t,r,n={intentPending:!1}){let i=this.serverState(t,r);return n.intentPending&&t.newTurn!==void 0?{artifact:{...i,newTurn:Ic(t.newTurn)},baseline:i}:{artifact:i,baseline:i}}serverState(t,r){var n,i,a,o,s,l;if(!qs(t)&&!t.newTurn)return t;let u=Ic(t);if(delete u.newTurn,!qs(t))return u;let c={...(n=u.bag)!==null&&n!==void 0?n:{},rows:{...(a=(i=u.bag)===null||i===void 0?void 0:i.rows)!==null&&a!==void 0?a:{}}};for(let d of(o=r.files)!==null&&o!==void 0?o:[]){let p=qT.find(m=>bn[m].name===d.name&&bn[m].fileType===d.fileType);if(!p||u.files.some(m=>m.id===d.id)||(c.rows[p]=d.id,d.content.status!=="available"))continue;let f=(0,Oc.base64ToUtf8)(d.content.data);p==="output"?c.output={status:"available",data:d.content.data}:p==="config"?(delete c.config,delete u.dataSources,delete u.model,delete u.connectorBindings,delete u.actionBindings,kT(u,c,(s=Tc(f))!==null&&s!==void 0?s:{})):p==="prompt"&&(delete c.prompt,delete u.firstPrompt,delete u.firstAgentMessage,MT(u,c,(l=Tc(f))!==null&&l!==void 0?l:{}))}return u.bag=c,u}baselineContent(t){var r;let n={...t};return delete n.conversation,delete n.newTurn,n.files=[...(r=t.files)!==null&&r!==void 0?r:[]].sort((i,a)=>i.id<a.id?-1:i.id>a.id?1:0),n}normalize(t){let r=t.newTurn;return!(0,pe.isJsonObject)(r)||typeof r.id=="string"&&PT.test(r.id)?t:{...t,newTurn:{...r,id:(0,Rc.newId)()}}}async compile(t,r,n){var i;let a=(i=t.dataSources)!==null&&i!==void 0?i:[],o=[],s=[];if(a.forEach((p,f)=>{var m;let h=(m=n?.resolveEntity)===null||m===void 0?void 0:m.call(n,p);h&&h.columnDetailComplete===!0?o.push(h):s.push((0,pe.issue)(`/dataSources/${f}`,h?"genpage-data-source-incomplete":"genpage-data-source-unresolved",h?`the column metadata of data source '${p}' could not be read completely (a choice or lookup request failed), so the page cannot be compiled with its enums. Retry the push.`:`the metadata of data source '${p}' could not be read, so the page cannot be compiled with its enums. Check the table's logical name and that it exists in this environment.`))}),s.length>0)throw new Ui.ValidationError("genPage",t.id,s);if(!n?.loadTypeScript)throw new Ui.ValidationError("genPage",t.id,[(0,pe.issue)("/source","genpage-compiler-unavailable","no TypeScript compiler is available to compile the page")]);let l=await n.loadTypeScript(),u=o.length>0?(0,Hh.buildGenPageRuntimeTypes)(o):void 0,c=o.length>0?(0,Hh.buildGenPageLegacyEnums)(o):void 0,d=(0,TT.compileGenPage)(l,r,u,c);if(d.diagnostics.length>0)throw new Ui.ValidationError("genPage",t.id,d.diagnostics.map(eW));return d.code}metadataNeeds(t){return t.source===void 0||!Array.isArray(t.dataSources)?[]:t.dataSources.filter(r=>typeof r=="string"&&r!=="").map(r=>({entityLogicalName:r,fieldName:"",needsColumnDetail:!0}))}createDefault(t){var r,n;let i=RT(t.id),a={id:i,name:(r=t.name)!==null&&r!==void 0?r:"New page",files:((n=t.files)!==null&&n!==void 0?n:[]).map(o=>{var s,l,u;return{id:RT(o.id),name:(s=o.name)!==null&&s!==void 0?s:"index.tsx",fileType:(l=o.fileType)!==null&&l!==void 0?l:ai,content:(u=o.content)!==null&&u!==void 0?u:{status:"available",data:""}}})};t.source!==void 0&&(a.source=t.source),t.dataSources!==void 0&&(a.dataSources=[...t.dataSources]);for(let o of["model","firstPrompt","firstAgentMessage"])t[o]!==void 0&&(a[o]=t[o]);return t.newTurn!==void 0&&(a.newTurn={...t.newTurn}),t.connectorBindings!==void 0&&(a.connectorBindings=Ic(t.connectorBindings)),t.actionBindings!==void 0&&(a.actionBindings=Ic(t.actionBindings)),a.source!==void 0&&(a.bag={rows:{source:Dc(i,"source"),output:Dc(i,"output"),config:Dc(i,"config")}}),a}assignMissingIds(t){if(t==null)return{id:(0,Rc.newId)()};if(!(0,pe.isJsonObject)(t))return t;let r=t;return(Object.keys(r).length===0||"id"in r||"content"in r||"fileType"in r||Array.isArray(r.files))&&(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,Rc.newId)()),r}validate(t){let r=[],n=t;for(let s of["source","model","firstPrompt","firstAgentMessage"])n[s]!==void 0&&typeof n[s]!="string"&&r.push((0,pe.issue)(`/${s}`,"genpage-field-type",`${s} must be a string, got ${typeof n[s]}`));if(n.source===void 0&&yn(yn(n.bag).rows).source!==void 0&&r.push(UT()),r.push(...BT(t)),n.newTurn!==void 0){let s=yn(n.newTurn);(!(0,pe.isJsonObject)(n.newTurn)||typeof s.prompt!="string"||s.prompt.trim()==="")&&r.push((0,pe.issue)("/newTurn/prompt","genpage-turn-prompt","newTurn needs a non-empty prompt")),s.agentMessage!==void 0&&typeof s.agentMessage!="string"&&r.push((0,pe.issue)("/newTurn/agentMessage","genpage-field-type","newTurn.agentMessage must be a string")),s.id!==void 0&&(typeof s.id!="string"||!PT.test(s.id))&&r.push((0,pe.issue)("/newTurn/id","genpage-turn-id","newTurn.id is the turn's identity, which the SDK mints \u2014 remove it, or keep the GUID it minted"))}if(n.dataSources!==void 0)if(!Array.isArray(n.dataSources))r.push((0,pe.issue)("/dataSources","genpage-data-sources-array","dataSources must be an array of table logical names"));else{let s=new Set;n.dataSources.forEach((l,u)=>{typeof l!="string"||!Hh.TABLE_LOGICAL_NAME.test(l)?r.push((0,pe.issue)(`/dataSources/${u}`,"genpage-data-source-name",`a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(l)}'`)):s.has(l)?r.push((0,pe.issue)(`/dataSources/${u}`,"genpage-data-source-duplicate",`data source '${l}' is listed twice`)):s.add(l)})}n.conversation!==void 0&&!Array.isArray(n.conversation)&&r.push((0,pe.issue)("/conversation","genpage-conversation-array","conversation must be an array"));let i=n.files;if(i!==void 0&&!Array.isArray(i))return r.push((0,pe.issue)("/files","files-must-be-array",`files must be an array, got ${typeof i}`)),r;let a=qs(t),o=new Map;return(Array.isArray(i)?i:[]).forEach((s,l)=>{let u=`/files/${l}`,c=yn(s),d=typeof c.id=="string"?c.id.trim().toLowerCase():"";if(d==="")r.push((0,pe.issue)(u,"file-id-required","a generative-page file needs an id"));else{let v=o.get(d);v!==void 0?r.push((0,pe.issue)(u,"file-id-duplicate",`two files share the id '${c.id}' (also at /files/${v}); a file's id is its identity, so a duplicate makes an edit ambiguous`)):o.set(d,l)}let p=typeof c.name=="string"?c.name:"",f=p.split("/");p===""||/[\u0000-\u001F\u007F]/.test(p)||p.includes("\\")||f.some(v=>v===""||v==="."||v==="..")?r.push((0,pe.issue)(u+"/name","file-name-invalid",`a file name must be a relative path of non-empty '/'-separated segments (no '.', '..', backslash or control character \u2014 its last segment is sent as an HTTP header); got '${p}'`)):a&&(xT(p)||OT(p,Number(c.fileType))!==void 0)&&r.push((0,pe.issue)(u+"/name","file-name-reserved",`'${p}' would be read by the maker portal as one of the page's managed rows (its source, output, config or first prompt), which the SDK writes from source and the configuration fields; it cannot also be a file in files[]`));let m=c.content;if(m===void 0){r.push((0,pe.issue)(u+"/content","file-content-required","content is required: omitting it is indistinguishable from an empty file, and the two have opposite effects on the next push"));return}let h=yn(m);h.status==="available"?typeof h.data!="string"&&r.push((0,pe.issue)(u+"/content/data","file-content-data-invalid","available content needs base64 `data`")):h.status!=="unavailable"&&r.push((0,pe.issue)(u+"/content/status","file-content-status-invalid",`content.status must be 'available' or 'unavailable', got ${String(h.status)}`))}),r}};ao.GenPageAdapter=xc;function eW(e){let t=`line ${e.line}, column ${e.column}`;return e.rule==="genpage-source-syntax"?(0,pe.issue)("/source",e.rule,`${t}: ${e.message} (TS${e.code}) \u2014 the page cannot run, so it was not pushed`):(0,pe.issue)("/source",e.rule,`${t}: ${e.message}`)}function tW(){return{adapter:new xc,api:Wz.genPageApi,publish:(e,t)=>(0,jz.publishGenPageById)(e,t),publishScope:e=>({envelope:"uxagentproject",targetIds:[e]}),rebaselineAfterPublish:!0}}ao.genPageRegistration=tW});var jT=y(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});kc.reconcileBpfSecurityRoles=void 0;var Fc=Ee(),Lc=le(),rW="Global",WT={create:"Create",read:"Read",write:"Write",delete:"Delete"};async function nW(e,t){var r,n;let i=`/EntityDefinitions(LogicalName='${(0,Lc.odataPathLiteral)(t)}')?$select=LogicalName,Privileges`,o=(n=(r=(0,Fc.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||r===void 0?void 0:r.Privileges)!==null&&n!==void 0?n:[],s={},l=new Set;return Object.keys(WT).forEach(u=>{let c=o.find(d=>d.PrivilegeType===WT[u]);if(c){let d=(0,Lc.normalizeGuid)(c.PrivilegeId,"PrivilegeId");s[u]=d,l.add(d)}}),{byAccess:s,all:l}}async function iW(e,t){var r,n;let i=`/RetrieveRolePrivilegesRole(RoleId=${t})`,o=(n=(r=(0,Fc.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||r===void 0?void 0:r.RolePrivileges)!==null&&n!==void 0?n:[];return new Set(o.map(s=>(0,Lc.normalizeGuid)(s.PrivilegeId,"PrivilegeId")))}async function aW(e,t,r){if(r.length===0)return;let n={Privileges:r.map(a=>({Depth:rW,PrivilegeId:a}))},i=`/roles(${t})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;(0,Fc.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function oW(e,t,r){let n={Privilege:{"@odata.type":"Microsoft.Dynamics.CRM.privilege",privilegeid:r}},i=`/roles(${t})/Microsoft.Dynamics.CRM.RemovePrivilegeRole`;(0,Fc.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function sW(e,t,r){var n;if(!r||r.length===0)return;let i=await nW(e,t.toLowerCase());for(let a of r){let o=(0,Lc.normalizeGuid)(a.roleId,"roleId"),s=new Set(((n=a.access)!==null&&n!==void 0?n:[]).map(p=>i.byAccess[p]).filter(p=>!!p)),l=await iW(e,o),u=new Set([...l].filter(p=>i.all.has(p))),c=[...s].filter(p=>!u.has(p)),d=[...u].filter(p=>!s.has(p));await aW(e,o,c);for(let p of d)await oW(e,o,p)}}kc.reconcileBpfSecurityRoles=sW});var tP=y($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});$c.bpfApi=void 0;var ur=si(),lW=$t(),cr=ee(),Et=Ee(),wn=le(),uW=jT(),cW={"Content-Type":"application/json",Accept:"application/json"},Mc={...cW,Prefer:"return=representation"},dW=new Set([408,502,503,504]),pW=`category eq ${ur.WorkflowCategory.BusinessProcessFlow} and type eq ${ur.WorkflowTypeCode.Definition} and businessprocesstype eq ${ur.BusinessProcessType.BusinessFlow}`,fW="workflowid,name,description,primaryentity,statecode,category,type,businessprocesstype,processorder",mW="workflowid,name,uniquename,description,primaryentity,statecode,statuscode,category,type,businessprocesstype,processorder,xaml,clientdata",hW=["xaml","name","description","processorder"];async function HT(e,t){var r;if(t.status!=="Active"||!t.securityRoles||t.securityRoles.length===0)return;let n=String((r=t.record.uniquename)!==null&&r!==void 0?r:"");n!==""&&await(0,uW.reconcileBpfSecurityRoles)(e,n,t.securityRoles)}async function eP(e,t,r){let n={statecode:ur.StateCode.Activated,statuscode:ur.StatusCode.Activated},i=`/workflows(${t})`,a={...Mc};return r&&(a["If-Match"]=r),(0,Et.ensureSuccess)(await e.patch(i,n,{headers:a}),e.apiUrl(i))}async function JT(e,t,r){return(0,Et.readEtag)(await eP(e,t,r))}function KT(e,t){return new cr.SdkError("BPF_WRITE_NOT_ECHOED",`The ${t} of business process flow '${e}' was applied, but the server returned no concurrency token for it (this environment did not honour 'Prefer: return=representation'), so the next step could not be conditioned on a token this push produced and was NOT sent. `+Uc(e))}async function Bc(e,t){var r;let n=`/workflows(${t})${(0,wn.odataQuery)([["$select","statecode"]])}`,i=(0,Et.ensureSuccess)(await e.get(n),e.apiUrl(n)),a=(r=i.body)===null||r===void 0?void 0:r.statecode,o=Number(a);if(a==null||a===""||!Number.isFinite(o))throw new cr.SdkError("BPF_STATE_UNREADABLE",`Reading the state of business process flow '${t}' answered HTTP ${i.status} without a usable statecode, so whether it is Active cannot be decided.`);return o}async function Kh(e,t,r){if(await Bc(e,t)!==ur.StateCode.Activated)return{deactivated:!1,etag:null};let n={statecode:ur.StateCode.Draft,statuscode:ur.StatusCode.Draft},i=`/workflows(${t})`,a={...Mc};r&&(a["If-Match"]=r);let o;try{o=await e.patch(i,n,{headers:a})}catch(l){return await QT(e,t,l)}if(dW.has(o.status))return await QT(e,t,new cr.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",`Deactivating business process flow '${t}' answered HTTP ${o.status} from an intermediary, so whether it committed is unknown.`));let s=(0,Et.ensureSuccess)(o,e.apiUrl(i));return{deactivated:!0,etag:(0,Et.readEtag)(s)}}async function QT(e,t,r){let n;try{n=await Bc(e,t)}catch{n=void 0}if(n===ur.StateCode.Draft)return{deactivated:!0,etag:null,uncertainCause:r};if(n===ur.StateCode.Activated)throw r;let i=new cr.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",`Deactivating business process flow '${t}' did not complete, and its state could not be re-read \u2014 it MAY be left DISABLED and needs reconciling. Original failure: ${r instanceof Error?r.message:String(r)}`);throw i.cause=r,i}async function XT(e,t){let r=(0,wn.normalizeGuid)(t,"workflowid");try{return await eP(e,r,null),"restored"}catch{try{let n=await Bc(e,r);return n===ur.StateCode.Activated?"restored":n===ur.StateCode.Draft?"disabled":"unknown"}catch{return"unknown"}}}function YT(e,t,r,n){let i=`Original failure: ${n instanceof Error?n.message:String(n)}`,a=r==="disabled"?new cr.SdkError("BPF_LEFT_DEACTIVATED",`Business process flow '${e}' was deactivated ${t}, and it could NOT be reactivated \u2014 it is left DISABLED. ${i}`):new cr.SdkError("BPF_REACTIVATE_OUTCOME_UNKNOWN",`Business process flow '${e}' was deactivated ${t}, and whether it was reactivated could not be confirmed \u2014 it MAY be left DISABLED and needs checking. ${i}`);return a.cause=n,a}async function gW(e,t){try{return await Bc(e,t),"survived"}catch(r){return r instanceof cr.ConnectionError&&r.statusCode===404?"removed":"unknown"}}async function vW(e,t,r){if(r)try{let{deactivated:n,etag:i}=await Kh(e,t,r),a=n?i:r;if(a)return await(0,Et.deleteRecord)(e,"workflows",t,a),"removed"}catch{}return gW(e,t)}function Uc(e){return`Adopt the server's copy with fetchArtifact('bpf', '${e}', { overwrite: true }) \u2014 it REPLACES the local copy, so keep any outstanding local changes aside first \u2014 then re-apply them and push.`}function ZT(e,t){return new cr.SdkError("BPF_CREATE_NO_TOKEN",`Created business process flow '${e}' but the server returned no concurrency token for it (this environment did not honour 'Prefer: return=representation'), so the next push would have nothing to condition on. ${t} It was NOT rolled back: deleting it without a token could remove an edit made since. ${Uc(e)}`)}function yW(e,t){let r=new cr.SdkError("BPF_CREATE_NOT_ROLLED_BACK",`Creating business process flow '${e}' failed part-way, and the rollback could NOT remove it \u2014 it still EXISTS, possibly Active and half-configured. (The rollback deletes only on a token this create produced, so a row somebody has since edited is left in place on purpose; a delete the platform refused or failed leaves it too.) ${Uc(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return r.cause=t,r}function bW(e,t){let r=new cr.SdkError("BPF_CREATE_ROLLBACK_OUTCOME_UNKNOWN",`Creating business process flow '${e}' failed part-way, and whether its rollback removed the process could not be confirmed \u2014 it MAY still exist, possibly Active and half-configured. ${Uc(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return r.cause=t,r}function wW(e,t){let r=new cr.SdkError("BPF_CREATE_REMOVED_AFTER_CONFLICT",`Creating business process flow '${e}' was interrupted: another writer changed it right after it was created, so this push's next step was refused rather than overwrite or activate their edit \u2014 and the process has since been removed. Nothing is left behind and there is nothing to fetch. If the removal was deliberate, stop here; otherwise push again to re-create it at the same id. Original failure: ${t instanceof Error?t.message:String(t)}`);return r.cause=t,r}function AW(e){let t={};for(let r of hW)e[r]!==void 0&&(t[r]=e[r]);return t}$c.bpfApi={async get(e,t){let n=`/workflows(${(0,wn.normalizeGuid)(t,"id")})${(0,wn.odataQuery)([["$select",mW]])}`,i=(0,Et.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,Et.readEtag)(i)}},async list(e,t){let r=[pW];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,wn.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,wn.odataQuery)([["$select",fW],["$filter",r.join(" and ")]])}`;return(await(0,lW.collectPages)(e,n,"listArtifacts('bpf')")).map(a=>{var o,s;return{type:"bpf",id:(o=a.workflowid)!==null&&o!==void 0?o:"",name:(s=a.name)!==null&&s!==void 0?s:"",entityLogicalName:a.primaryentity,isDirty:!1}})},async create(e,t){let r=t,n=(0,wn.normalizeGuid)(r.record.workflowid,"workflowid"),i="/workflows",a=(0,Et.ensureSuccess)(await e.post(i,r.record,{headers:Mc}),e.apiUrl(i)),o=(0,Et.readEtag)(a);if(!o)throw ZT(n,r.status==="Active"?"The process EXISTS as Draft and was NOT activated \u2014 an activation that cannot be conditioned on our own write could activate somebody else's edit.":"The process EXISTS as Draft.");let s=o;try{r.status==="Active"&&(s=await JT(e,n,o)),await HT(e,r)}catch(l){let u=await vW(e,n,s);throw u==="survived"?yW(n,l):u==="unknown"?bW(n,l):l instanceof cr.SdkError&&l.code===Et.VERSION_CONFLICT_CODE?wW(n,l):l}if(!s)throw ZT(n,"The process EXISTS and IS Active, but its activation returned no token.");return{id:n,etag:s}},async update(e,t,r,n){let i=r,a=(0,wn.normalizeGuid)(t,"id"),o=(0,Et.requireEtag)(n,"bpf",a),{deactivated:s,etag:l,uncertainCause:u}=await Kh(e,a,o);try{if(u!==void 0)throw u;let c=o;if(s){if(!l)throw KT(a,"deactivation");c=l}let d=`/workflows(${a})`,p=(0,Et.ensureSuccess)(await e.patch(d,AW(i.record),{headers:{...Mc,"If-Match":c}}),e.apiUrl(d)),f=(0,Et.readEtag)(p);if(i.status==="Active"){if(!f)throw KT(a,"definition write");f=await JT(e,a,f)}return await HT(e,i),{id:a,etag:f}}catch(c){if(s){let d=await XT(e,a);if(d!=="restored")throw YT(a,"to apply an edit, the edit failed",d,c)}throw c}},async delete(e,t){let r=(0,wn.normalizeGuid)(t,"id"),{deactivated:n}=await Kh(e,r,null);try{await(0,Et.deleteRecord)(e,"workflows",r)}catch(i){if(n){let a=await XT(e,r);if(a!=="restored")throw YT(r,"so it could be deleted, the delete failed",a,i)}throw i}}}});var BP=y(so=>{"use strict";Object.defineProperty(so,"__esModule",{value:!0});so.bpfRegistration=so.BpfAdapter=void 0;var qc=si(),CW=tP(),Qh=Mn(),$i=mi(),mP=Un(),Wt=zr(),Bt=st(),Kr=ee(),EW=100,Yh='<?xml version="1.0" encoding="utf-16"?>',rP=1033,hP="mxswa:Workflow",SW="mxswa:ActivityReference.Properties",NW="mcwo:StepLabel",DW="mcwb:Control",nP="mcwb:Control.ControlDisplayName",gP="mcwb:Control.DataFieldName",vP="DataFieldName",iP="ControlDisplayName",yP="Literal",Vc="x:Null",aP="x:String",Zh="x:Key",eg="DisplayName",zc="Activities",IW="StepLabels",bP="StageId",wP="StageCategory",AP="NextStageId",CP="ProcessStepId",tg="IsProcessRequired",EP="EntityComposite",SP="StageComposite",NP="StepComposite";function Xh(e){return(0,Wt.isJsonObject)(e)?e:{}}function Qr(e){if(!e)return[];let t=[],r=e.childNodes;for(let n=0;n<r.length;n+=1){let i=r[n];i.nodeType===1&&t.push(i)}return t}function qi(e,t){var r;return(r=Qr(e).find(n=>n.tagName===t))!==null&&r!==void 0?r:null}function Xr(e){return qi(e,SW)}function St(e,t){var r;return(r=Qr(e).find(n=>n.getAttribute(Zh)===t))!==null&&r!==void 0?r:null}function oo(e,t){var r;return((r=e.getAttribute("AssemblyQualifiedName"))!==null&&r!==void 0?r:"").includes(t)}function Cn(e){var t;return!e||!e.firstChild?"":(t=e.firstChild.nodeValue)!==null&&t!==void 0?t:""}function DP(e,t,r){e.firstChild?e.firstChild.nodeValue=r:e.appendChild(t.createTextNode(r))}function Vs(e){var t;let r=(t=e.getAttribute(eg))!==null&&t!==void 0?t:"",n=r.indexOf(": ");return n>=0?r.slice(n+2):r}function IP(e,t){var r;let n=(r=e.getAttribute(eg))!==null&&r!==void 0?r:"",i=n.indexOf(": ");e.setAttribute(eg,i>=0?n.slice(0,i+2)+t:t)}function _P(e,t){let r=St(e,IW),n=qi(r,NW);n&&n.setAttribute("Description",t)}function _W(e){let t=St(e,wP);if(!t||t.tagName===Vc)return;let r=Cn(t).trim();return r===""?void 0:Number(r)}function TW(e){let t=St(e,AP);if(!t||t.tagName===Vc)return;let r=Cn(t).trim();return r===""?void 0:r}function TP(e){let t=PP(e);if(!t)return;let r=OP(t,vP,gP);return r===""?void 0:r}function rg(e,t){let r=Qr(e);for(;r.length>0;){let n=r.pop();if(n.tagName===t)return n;for(let i of Qr(n))r.push(i)}return null}function PP(e){let t=St(Xr(e),zc);return t?rg(t,DW):null}function RP(e,t){let r=e.attributes;for(let n=0;n<r.length;n+=1)if(r[n].name===t)return!0;return!1}function OP(e,t,r){var n;return RP(e,t)?(n=e.getAttribute(t))!==null&&n!==void 0?n:"":LW(e,r)}function oP(e,t,r,n){if(RP(e,t)){e.setAttribute(t,n);return}if(qi(e,r)){PW(e,r,n);return}throw new Kr.InvalidArgumentError(`BPF step control exposes neither a '${t}' attribute nor a <${r}> wrapper to bind a column`)}function PW(e,t,r){let n=qi(e,t),i=n?rg(n,yP):null;i&&i.setAttribute("Value",r)}function xP(e){return Vs(e)}function Wc(e){let t=qi(e,hP),r=[];for(let n of Qr(t).filter(i=>oo(i,EP))){let i=St(Xr(n),zc);for(let a of Qr(i).filter(o=>oo(o,SP)))r.push({el:a,entity:xP(n)})}return r}function ng(e){let t=St(Xr(e),zc);return Qr(t).filter(r=>oo(r,NP))}function RW(e){let t=Xr(e),r=Cn(St(t,tg)).trim().toLowerCase(),n=TP(e),i={id:Cn(St(t,CP)),name:Vs(e)};return n!==void 0&&(i.fieldName=n),r==="true"&&(i.required=!0),i}function OW(e,t){let r=Xr(e),n=_W(r),i=TW(r),a={id:Cn(St(r,bP)),name:Vs(e),entityLogicalName:t,steps:ng(e).map(RW)};return n!==void 0&&(a.category=n),i!==void 0&&(a.nextStageId=i),a}function xW(e){return Wc(e).map(({el:t,entity:r})=>OW(t,r))}function An(e){return new Kr.NotImplementedError("bpf-structural-authoring",`${e} is not supported yet (this phase authors identity, stage/step names, step required, step field binding, stage categories, and adding/removing/reordering stages & steps on a single-table process; branching, actions, security-role wiring and multi-table processes land in later phases). The rest of the process round-trips losslessly.`)}function LW(e,t){var r;let n=qi(e,t),i=n?rg(n,yP):null;return(r=i?.getAttribute("Value"))!==null&&r!==void 0?r:""}function ig(e,t){var r;let n=e.createElement(t.tagName),i=t.attributes;for(let o=0;o<i.length;o+=1)n.setAttribute(i[o].name,i[o].value);let a=t.childNodes;for(let o=0;o<a.length;o+=1){let s=a[o];s.nodeType===1?n.appendChild(ig(e,s)):s.nodeType===3&&n.appendChild(e.createTextNode((r=s.nodeValue)!==null&&r!==void 0?r:""))}return n}function LP(e){return St(Xr(e),zc)}function FW(e,t,r){var n;let i=t.entityLogicalName&&t.entityLogicalName.trim()!==""?t.entityLogicalName:r,a=!((n=t.steps[0])===null||n===void 0)&&n.id&&t.steps[0].id.trim()!==""?t.steps[0].id:(0,Bt.newId)(),{body:o}=jc(ag(i,(0,Bt.newId)(),t.id,a));return ig(e,Wc((0,$i.parseXmlRoot)(o,"<Activity/>"))[0].el)}function kW(e,t){let{body:r}=jc(ag("account",(0,Bt.newId)(),(0,Bt.newId)(),t.id));return ig(e,ng(Wc((0,$i.parseXmlRoot)(r,"<Activity/>"))[0].el)[0])}function FP(e,t){for(;e.firstChild;)e.removeChild(e.firstChild);for(let r of t)e.appendChild(r)}function kP(e,t,r,n){let i=St(e,r);if(!i||!i.parentNode){if(n!==void 0&&n!=="")throw An(`setting '${r}' on a stage whose xaml does not expose that slot`);return}let a=i.parentNode;if(n===void 0||n===""){if(i.tagName!==Vc){let s=t.createElement(Vc);s.setAttribute(Zh,r),a.replaceChild(s,i)}return}if(i.tagName===aP){Cn(i)!==n&&DP(i,t,n);return}let o=t.createElement(aP);o.setAttribute(Zh,r),o.appendChild(t.createTextNode(n)),a.replaceChild(o,i)}function MW(e,t,r){kP(e,t,wP,r===void 0?void 0:String(r))}function BW(e,t,r){kP(e,t,AP,r)}function MP(e,t,r){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(r(e[n])!==t[n])return!1;return!0}function sP(e){return Cn(St(Xr(e),bP))}function lP(e){return Cn(St(Xr(e),CP))}function uP(e,t,r){var n,i,a,o;let s=Xr(e);r.name!==Vs(e)&&(IP(e,r.name),_P(s,r.name));let l=Cn(St(s,tg)).trim().toLowerCase()==="true";if(((n=r.required)!==null&&n!==void 0?n:!1)!==l){let u=St(s,tg);u&&DP(u,t,r.required?"True":"False")}if(((i=r.fieldName)!==null&&i!==void 0?i:"")!==((a=TP(e))!==null&&a!==void 0?a:"")){let u=PP(e);if(!u)throw new Kr.InvalidArgumentError("BPF step has no <mcwb:Control> element to bind a column to");let c=(o=r.fieldName)!==null&&o!==void 0?o:"";oP(u,vP,gP,c),c!==""&&OP(u,iP,nP)===""&&oP(u,iP,nP,c)}}function cP(e,t,r,n){var i;let a=Xr(e);if(!a)throw new Kr.InvalidArgumentError("BPF stage composite has no <\u2026ActivityReference.Properties>");if(r.name!==Vs(e)&&(IP(e,r.name),_P(a,r.name)),MW(a,t,r.category),BW(a,t,n),r.relationshipName&&r.relationshipName.trim()!=="")throw An("a stage relationship / table change (multi-table authoring)");if(r.actions&&r.actions.length>0||r.branch)throw An("stage actions or conditional branching");let o=LP(e);if(!o)throw new Kr.InvalidArgumentError("BPF stage has no [Activities] collection");let s=(i=r.steps)!==null&&i!==void 0?i:[];if(s.length===0)throw new Kr.InvalidArgumentError(`BPF stage '${r.name}' must have at least one step`);let l=ng(e);if(MP(l,s.map(d=>d.id),lP)){l.forEach((d,p)=>uP(d,t,s[p]));return}let u=new Map(l.map(d=>[lP(d),d]));if(Qr(o).some(d=>!oo(d,NP)))throw An("adding, removing or reordering steps on a stage that also contains branching or actions");let c=s.map(d=>{var p;return(p=u.get(d.id))!==null&&p!==void 0?p:kW(t,d)});FP(o,c),c.forEach((d,p)=>uP(d,t,s[p]))}function UW(e,t,r){let n=qi(e,hP);if(!n)throw new Kr.InvalidArgumentError("BPF xaml has no <mxswa:Workflow> root activity");if(r.globalActions&&r.globalActions.length>0)throw An("global (process-completed/abandoned) actions");if(!r.stages||r.stages.length===0)throw new Kr.InvalidArgumentError("a BPF must have at least one stage");let i=Wc(e),a=i.map(p=>p.el);if(MP(a,r.stages.map(p=>p.id),sP)){i.forEach(({el:p,entity:f},m)=>{let h=r.stages[m];if(h.entityLogicalName&&h.entityLogicalName.trim()!==""&&h.entityLogicalName!==f)throw An(`changing a stage's table ('${h.entityLogicalName}' vs the process's '${f}')`);cP(p,t,h,h.nextStageId)});return}let o=Qr(n).filter(p=>oo(p,EP));if(o.length!==1)throw An("adding, removing or reordering stages on a multi-table process");let s=o[0],l=xP(s),u=LP(s);if(!u)throw new Kr.InvalidArgumentError("BPF primary entity composite has no [Activities] collection");if(Qr(u).some(p=>!oo(p,SP)))throw An("adding, removing or reordering stages on a process whose primary composite holds non-stage activities (multi-table nesting or advanced constructs)");for(let p of r.stages)if(p.entityLogicalName&&p.entityLogicalName.trim()!==""&&p.entityLogicalName!==l)throw An(`a stage on a different table ('${p.entityLogicalName}') than the process primary ('${l}')`);let c=new Map(a.map(p=>[sP(p),p])),d=r.stages.map(p=>{var f;return(f=c.get(p.id))!==null&&f!==void 0?f:FW(t,p,l)});FP(u,d),d.forEach((p,f)=>{let m=f<d.length-1?r.stages[f+1].id:void 0;cP(p,t,r.stages[f],m)})}function jc(e){let t=e.match(/^<\?xml[^>]*\?>\s*/),r=t?t[0]:"";return{prolog:r,body:e.slice(r.length)}}function $W(e){var t,r,n,i,a,o;(0,mP.installDomShim)();let s=(t=e.bag)===null||t===void 0?void 0:t.xaml;if(s){let p=new DOMParser().parseFromString("<root/>","text/xml"),f={n:"Activity",a:(0,Qh.mergeAttrs)(s.a,[]),c:(0,Qh.spliceChildren)(s.c,[])};return{root:(0,Qh.rebuildRaw)(f,(0,$i.domEngine)(p),null),prolog:(n=(r=e.bag)===null||r===void 0?void 0:r.xamlProlog)!==null&&n!==void 0?n:Yh,eol:(a=(i=e.bag)===null||i===void 0?void 0:i.xamlEol)!==null&&a!==void 0?a:"lf"}}let l=e.stages[0],u=(o=l?.steps)===null||o===void 0?void 0:o[0],c=ag(e.entityLogicalName,(0,Bt.newId)(),l?.id&&l.id.trim()!==""?l.id:(0,Bt.newId)(),u?.id&&u.id.trim()!==""?u.id:(0,Bt.newId)()),{body:d}=jc(c);return{root:(0,$i.parseXmlRoot)(d,"<Activity/>"),prolog:Yh,eol:"lf"}}function qW(e){let{root:t,prolog:r,eol:n}=$W(e);UW(t,t.ownerDocument,e);let i=(0,$i.serializeNode)(t);return n==="crlf"&&(i=i.replace(/\n/g,`\r+`)),r+i}function VW(e){return e.uniqueName&&e.uniqueName.trim()!==""?e.uniqueName:`new_${(e.name||"businessprocessflow").toLowerCase().replace(/[^a-z0-9]/g,"")||"businessprocessflow"}`}var Gc=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var r,n;(0,mP.installDomShim)();let i=t,a=typeof i.xaml=="string"?i.xaml:"",o={id:i.workflowid?String(i.workflowid):null,name:String((r=i.name)!==null&&r!==void 0?r:""),entityLogicalName:String((n=i.primaryentity)!==null&&n!==void 0?n:""),status:Number(i.statecode)===1?"Active":"Draft",stages:[]};if(i.uniquename&&(o.uniqueName=String(i.uniquename)),i.description!=null&&i.description!==""&&(o.description=String(i.description)),i.processorder!=null&&i.processorder!==""&&(o.order=Number(i.processorder)),a.trim()!==""){let{prolog:s,body:l}=jc(a),u=(0,$i.parseXmlRoot)(l,"<Activity/>");o.stages=xW(u),o.bag={xaml:(0,$i.projectElementBag)(u),xamlProlog:s,xamlEol:/\r\n/.test(a)?"crlf":"lf"}}return o}toApiPayload(t){var r;let n={workflowid:t.id&&t.id.trim()!==""?t.id:(0,Bt.newId)(),name:t.name,uniquename:VW(t),primaryentity:t.entityLogicalName,xaml:qW(t),category:qc.WorkflowCategory.BusinessProcessFlow,type:qc.WorkflowTypeCode.Definition,businessprocesstype:qc.BusinessProcessType.BusinessFlow,scope:qc.WorkflowScope.Organization,processorder:(r=t.order)!==null&&r!==void 0?r:EW};t.description!==void 0&&(n.description=t.description);let i={record:n,status:t.status};if(t.securityRoles&&t.securityRoles.length>0){if(t.status!=="Active")throw new Kr.InvalidArgumentError('securityRoles require the BPF to be Active \u2014 the backing table they grant access to is created on activation; set status to "Active" to wire security roles');i.securityRoles=t.securityRoles}return i}createDefault(t){var r,n,i;let a=t.stages&&t.stages.length>0?t.stages.map(pP):[pP({id:(0,Bt.newId)(),name:"New Stage",steps:[]})],o={id:t.id&&t.id.trim()!==""?t.id:(0,Bt.newId)(),name:(r=t.name)!==null&&r!==void 0?r:"New business process flow",entityLogicalName:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",status:(i=t.status)!==null&&i!==void 0?i:"Draft",stages:a};return t.uniqueName&&(o.uniqueName=t.uniqueName),t.description!==void 0&&(o.description=t.description),t.order!==void 0&&(o.order=t.order),t.globalActions!==void 0&&(o.globalActions=t.globalActions),t.securityRoles!==void 0&&(o.securityRoles=t.securityRoles),o}assignMissingIds(t){let r=Xh(t);(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,Bt.newId)());for(let n of["stages","steps","actions","globalActions"]){let i=r[n];Array.isArray(i)&&i.forEach(a=>this.assignMissingIds(a))}return r}validate(t){let r=[],n=t.stages;if(n!==void 0&&!Array.isArray(n))return r.push((0,Wt.issue)("/stages","stages-must-be-array",`stages must be an array, got ${typeof n}`)),r;let i=Array.isArray(n)?n:[];i.length>30&&r.push((0,Wt.issue)("/stages","too-many-stages",`a BPF allows at most 30 stages, got ${i.length}`));let a=new Set,o=new Map;i.forEach((l,u)=>{let c=`/stages/${u}`,d=Xh(l),p=typeof d.id=="string"?d.id.trim():"";p===""?r.push((0,Wt.issue)(`${c}/id`,"stage-id-required","a stage needs an id")):o.has(p.toLowerCase())?r.push((0,Wt.issue)(`${c}/id`,"stage-id-duplicate",`two stages share the id '${l.id}' (also at /stages/${o.get(p.toLowerCase())})`)):o.set(p.toLowerCase(),u),typeof l.entityLogicalName=="string"&&l.entityLogicalName!==""&&a.add(l.entityLogicalName);let f=Array.isArray(l.steps)?l.steps:[];f.length===0&&r.push((0,Wt.issue)(`${c}/steps`,"stage-needs-step","a BPF stage must have at least one step")),f.length>30&&r.push((0,Wt.issue)(`${c}/steps`,"too-many-steps",`a stage allows at most 30 steps, got ${f.length}`));let m=new Map;f.forEach((h,v)=>{let w=`${c}/steps/${v}`,C=typeof Xh(h).id=="string"?h.id.trim():"";C===""?r.push((0,Wt.issue)(`${w}/id`,"step-id-required","a step needs an id")):m.has(C.toLowerCase())?r.push((0,Wt.issue)(`${w}/id`,"step-id-duplicate",`two steps in this stage share the id '${h.id}'`)):m.set(C.toLowerCase(),v)}),l.branch&&!dP(i,l.branch.nextStageId)&&r.push((0,Wt.issue)(`${c}/branch/nextStageId`,"branch-target-unknown",`branch nextStageId '${l.branch.nextStageId}' does not match any stage id`)),typeof l.nextStageId=="string"&&l.nextStageId!==""&&!dP(i,l.nextStageId)&&r.push((0,Wt.issue)(`${c}/nextStageId`,"next-stage-unknown",`nextStageId '${l.nextStageId}' does not match any stage id`))}),a.size>5&&r.push((0,Wt.issue)("/stages","too-many-tables",`a BPF spans at most 5 tables, got ${a.size}`));let s=GW(i);return s>=0&&r.push((0,Wt.issue)(`/stages/${s}/nextStageId`,"next-stage-cycle","the stage nextStageId links form a cycle; the flow must be acyclic")),r}};so.BpfAdapter=Gc;function GW(e){let t=new Map(e.map(r=>[r.id,r]));for(let r=0;r<e.length;r+=1){let n=new Set,i=e[r];for(;i&&typeof i.nextStageId=="string"&&i.nextStageId!=="";){if(n.has(i.id))return r;n.add(i.id),i=t.get(i.nextStageId)}}return-1}function dP(e,t){return e.some(r=>r.id===t)}function pP(e){var t,r;let n=e.steps&&e.steps.length>0?e.steps.map(fP):[fP({id:(0,Bt.newId)(),name:"New Step"})],i={id:e.id&&e.id.trim()!==""?e.id:(0,Bt.newId)(),name:(t=e.name)!==null&&t!==void 0?t:"New Stage",entityLogicalName:(r=e.entityLogicalName)!==null&&r!==void 0?r:"",steps:n};return e.category!==void 0&&(i.category=e.category),e.nextStageId!==void 0&&(i.nextStageId=e.nextStageId),e.relationshipName!==void 0&&(i.relationshipName=e.relationshipName),e.actions!==void 0&&(i.actions=e.actions),e.branch!==void 0&&(i.branch=e.branch),i}function fP(e){var t;let r={id:e.id&&e.id.trim()!==""?e.id:(0,Bt.newId)(),name:(t=e.name)!==null&&t!==void 0?t:"New Step"};return e.fieldName!==void 0&&(r.fieldName=e.fieldName),e.required!==void 0&&(r.required=e.required),r}function ag(e,t,r,n){return`${Yh}<Activity x:Class="XrmWorkflow00000000000000000000000000000000" xmlns="http://schemas.microsoft.com/netfx/2009/xaml/activities" xmlns:mcwb="clr-namespace:Microsoft.Crm.Workflow.BusinessProcessFlowActivities;assembly=Microsoft.Crm.Workflow, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" xmlns:mcwo="clr-namespace:Microsoft.Crm.Workflow.ObjectModel;assembly=Microsoft.Crm, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" xmlns:mva="clr-namespace:Microsoft.VisualBasic.Activities;assembly=System.Activities, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" xmlns:mxs="clr-namespace:Microsoft.Xrm.Sdk;assembly=Microsoft.Xrm.Sdk, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" xmlns:mxswa="clr-namespace:Microsoft.Xrm.Sdk.Workflow.Activities;assembly=Microsoft.Xrm.Sdk.Workflow, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" xmlns:scg="clr-namespace:System.Collections.Generic;assembly=mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" xmlns:sco="clr-namespace:System.Collections.ObjectModel;assembly=mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" xmlns:srs="clr-namespace:System.Runtime.Serialization;assembly=System.Runtime.Serialization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" xmlns:this="clr-namespace:" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"><x:Members><x:Property Name="InputEntities" Type="InArgument(scg:IDictionary(x:String, mxs:Entity))" /><x:Property Name="CreatedEntities" Type="InArgument(scg:IDictionary(x:String, mxs:Entity))" /></x:Members><this:XrmWorkflow00000000000000000000000000000000.InputEntities><InArgument x:TypeArguments="scg:IDictionary(x:String, mxs:Entity)" /></this:XrmWorkflow00000000000000000000000000000000.InputEntities><this:XrmWorkflow00000000000000000000000000000000.CreatedEntities><InArgument x:TypeArguments="scg:IDictionary(x:String, mxs:Entity)" /></this:XrmWorkflow00000000000000000000000000000000.CreatedEntities><mva:VisualBasic.Settings>Assembly references and imported namespaces for internal implementation</mva:VisualBasic.Settings><mxswa:Workflow><mxswa:ActivityReference AssemblyQualifiedName="Microsoft.Crm.Workflow.Activities.EntityComposite, Microsoft.Crm.Workflow, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" DisplayName="EntityStep1: ${e}"><mxswa:ActivityReference.Properties><sco:Collection x:TypeArguments="Variable" x:Key="Variables" /><sco:Collection x:TypeArguments="Activity" x:Key="Activities"><mxswa:ActivityReference AssemblyQualifiedName="Microsoft.Crm.Workflow.Activities.StageComposite, Microsoft.Crm.Workflow, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" DisplayName="StageStep2: New Stage"><mxswa:ActivityReference.Properties><sco:Collection x:TypeArguments="Variable" x:Key="Variables" /><sco:Collection x:TypeArguments="Activity" x:Key="Activities"><mxswa:ActivityReference AssemblyQualifiedName="Microsoft.Crm.Workflow.Activities.StepComposite, Microsoft.Crm.Workflow, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" DisplayName="StepStep3: New Step"><mxswa:ActivityReference.Properties><sco:Collection x:TypeArguments="Variable" x:Key="Variables" /><sco:Collection x:TypeArguments="Activity" x:Key="Activities"><Sequence DisplayName="ControlStep4"><mcwb:Control ControlId="${t}" IsSystemControl="False" IsUnbound="False" SystemStepType="0"><mcwb:Control.ClassId><InArgument x:TypeArguments="x:String"><Literal x:TypeArguments="x:String" Value="" /></InArgument></mcwb:Control.ClassId><mcwb:Control.ControlDisplayName><InArgument x:TypeArguments="x:String"><Literal x:TypeArguments="x:String" Value="" /></InArgument></mcwb:Control.ControlDisplayName><mcwb:Control.DataFieldName><InArgument x:TypeArguments="x:String"><Literal x:TypeArguments="x:String" Value="" /></InArgument></mcwb:Control.DataFieldName><mcwb:Control.Parameters><InArgument x:TypeArguments="x:String"><Literal x:TypeArguments="x:String" Value="" /></InArgument></mcwb:Control.Parameters></mcwb:Control></Sequence></sco:Collection><sco:Collection x:TypeArguments="mcwo:StepLabel" x:Key="StepLabels"><mcwo:StepLabel Description="New Step" LabelId="${n}" LanguageCode="${rP}" /></sco:Collection><x:String x:Key="ProcessStepId">${n}</x:String><x:Boolean x:Key="IsProcessRequired">False</x:Boolean></mxswa:ActivityReference.Properties></mxswa:ActivityReference></sco:Collection><sco:Collection x:TypeArguments="mcwo:StepLabel" x:Key="StepLabels"><mcwo:StepLabel Description="New Stage" LabelId="${r}" LanguageCode="${rP}" /></sco:Collection><x:String x:Key="StageId">${r}</x:String><x:Null x:Key="StageCategory" /><x:Null x:Key="NextStageId" /></mxswa:ActivityReference.Properties></mxswa:ActivityReference></sco:Collection><x:Null x:Key="RelationshipName" /><x:Null x:Key="AttributeName" /><x:Boolean x:Key="IsClosedLoop">False</x:Boolean></mxswa:ActivityReference.Properties></mxswa:ActivityReference></mxswa:Workflow></Activity>`}function zW(){return{adapter:new Gc,api:CW.bpfApi,languageSensitive:!0}}so.bpfRegistration=zW});var UP=y(Hc=>{"use strict";Object.defineProperty(Hc,"__esModule",{value:!0});Hc.buildRegistrations=void 0;var WW=gI(),jW=xI(),HW=e2(),JW=g2(),KW=F2(),QW=eT(),XW=fT(),YW=zT(),ZW=BP();function ej(e){let t=new Map;return t.set("form",(0,WW.formRegistration)(e)),t.set("view",(0,jW.viewRegistration)()),t.set("businessRule",(0,HW.businessRuleRegistration)()),t.set("app",(0,JW.appRegistration)(e)),t.set("command",(0,KW.commandRegistration)()),t.set("chart",(0,QW.chartRegistration)()),t.set("dashboard",(0,XW.dashboardRegistration)(e)),t.set("genPage",(0,YW.genPageRegistration)()),t.set("bpf",(0,ZW.bpfRegistration)()),t}Hc.buildRegistrations=ej});var JP=y(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.removeRowSummary=Fe.configureRowSummary=Fe.buildGptDynamicPrompt=Fe.setAppAiFeatures=Fe.getAiReadiness=Fe.saveSettingValue=Fe.retrieveSetting=Fe.AI_GATE=void 0;var Nr=Ee(),et=le(),$P=st(),En=ee();Fe.AI_GATE={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabled",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"EnableNLGridSearch",nlChart:"NLChartVisualizationSetting",summaries:"EnableFormInsights",m365:"m365copilotmodelappenabled"};var zP={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabledOnByDefault",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"NLGridSearchSetting",nlChart:"NLChartDataVisualizationSetting",m365:"m365copilotmodelappenabled"},tj=new Set(Object.entries(Fe.AI_GATE).filter(([e,t])=>zP[e]===t).map(([e])=>e)),rj={formFill:{enabled:"2",disabled:"1"},formFillSuggestions:{enabled:"2",disabled:"1"},formFillSmartPaste:{enabled:"2",disabled:"1"},formFillFiles:{enabled:"2",disabled:"1"}};function og(e){return rj[e]}var Jc=1e6;function nj(e,t){let r=og(t),n=()=>{throw new En.InvalidArgumentError(`setAppAiFeatures: '${t}' must be a boolean or an integer between 0 and ${Jc} (e.g. 0, 1, 2); got '${String(e)}'.`)},i=a=>r?a?r.enabled:r.disabled:a?"1":"0";if(typeof e=="boolean")return i(e);if(typeof e=="number")return!Number.isSafeInteger(e)||e<0||e>Jc?n():String(e);if(typeof e=="string"){let a=e.trim(),o=a.toLowerCase();if(o==="true")return i(!0);if(o==="false")return i(!1);if(/^[0-9]+$/.test(a)){let s=a.replace(/^0+(?=[0-9])/,"");return s.length>String(Jc).length||Number(s)>Jc?n():s}}return n()}function ij(e,t){let r=og(t);return r?e===r.enabled:e!=="0"}async function aj(e,t){var r,n,i;let a=`/appmodules${(0,et.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,et.odataLiteral)(t)}'`]])}`,o=await e.get(a);return o.status>=200&&o.status<300?(i=((n=(r=o.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0])===null||i===void 0?void 0:i.appmoduleid:void 0}async function oj(e,t){var r,n;let i=`/appmodules${(0,et.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,et.odataLiteral)(t)}'`]])}`,a;try{a=await e.get(i)}catch(l){throw new En.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup failed (${l.message}). Retry, or omit appModuleId to verify by name.`)}if(a.status<200||a.status>=300)throw new En.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned HTTP ${a.status}. Retry, or omit appModuleId to verify by name.`);let o=(r=a.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(o))throw new En.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a malformed body.`);if(o.length===0)return;let s=(n=o[0])===null||n===void 0?void 0:n.appmoduleid;if(!s)throw new En.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a row with no appmoduleid.`);return s}var qP=new WeakMap;async function sj(e,t){var r,n,i;let a=qP.get(e);if(a||(a=new Map,qP.set(e,a)),a.has(t))return a.get(t);let o=`/settingdefinitions${(0,et.odataQuery)([["$select","settingdefinitionid"],["$filter",`uniquename eq '${(0,et.odataLiteral)(t)}'`]])}`,s=await e.get(o),l=s.status>=200&&s.status<300?(i=((n=(r=s.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0])===null||i===void 0?void 0:i.settingdefinitionid:void 0;return l&&a.set(t,l),l}async function lj(e,t,r){var n,i;let a=await sj(e,r);if(!t||!a)return;let o=`/appsettings${(0,et.odataQuery)([["$select","value"],["$filter",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${a}`]])}`,s=await e.get(o);if(s.status<200||s.status>=300)return;let l=(i=(n=s.body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[];return l.length>0?{exists:!0,value:l[0].value}:{exists:!1}}var uj=4,cj=500,VP=20,GP=3e4;function dj(e){if(e===void 0)return uj;if(!Number.isFinite(e))throw new En.InvalidArgumentError(`setAppAiFeatures: verifyAttempts must be a finite integer between 1 and ${VP}; got ${e}.`);return Math.min(VP,Math.max(1,Math.floor(e)))}function pj(e){if(e===void 0)return cj;if(!Number.isFinite(e))throw new En.InvalidArgumentError(`setAppAiFeatures: verifyDelayMs must be a finite number between 0 and ${GP}; got ${e}.`);return Math.min(GP,Math.max(0,Math.floor(e)))}async function fj(e,t,r,n,i,a,o){let s,l,u,c=!1;for(let d=0;d<a;d+=1){d>0&&await new Promise(f=>setTimeout(f,o*d));let p;try{let f=await t();f?(p=await lj(e,f,n),p===void 0&&(u="the app-scope override row could not be read (insufficient access or unresolvable ids)")):u=`the app '${r}' could not be resolved to an appmoduleid \u2014 a newly created app is not readable until it is published, so either publish it first or pass \`appModuleId\` in the options to verify without the lookup`}catch(f){p=void 0,u=f.message}c=p!==void 0,l=p?.exists;try{s=(await Kc(e,n,{appUniqueName:r})).value}catch{}if(p?.exists&&p.value===i)return{result:"proven",effectiveValue:p.value,appOverrideExists:!0}}return c?{result:"absent",effectiveValue:s,appOverrideExists:l}:{result:"unverifiable",effectiveValue:s,appOverrideExists:void 0,reason:u}}function WP(e,t,r){if(t===2)return String(e).toLowerCase()==="true";let n=r?og(r):void 0;return n?e===n.enabled:e!=null&&e!=="0"&&e!==""}async function Kc(e,t,r={}){var n,i;let a=[`SettingName='${(0,et.odataPathLiteral)(t)}'`];r.appUniqueName&&a.push(`AppUniqueName='${(0,et.odataPathLiteral)(r.appUniqueName)}'`);let o=`/RetrieveSetting(${a.join(",")})`,l=(i=(n=(0,Nr.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.SettingDetail)!==null&&i!==void 0?i:{};return{value:l.Value,dataType:l.DataType}}Fe.retrieveSetting=Kc;async function jP(e,t,r,n={}){let i={SettingName:t,Value:r};n.appUniqueName&&(i.AppUniqueName=n.appUniqueName),n.solutionUniqueName&&(i.SolutionUniqueName=n.solutionUniqueName),(0,Nr.ensureSuccess)(await e.post("/SaveSettingValue",i),e.apiUrl("/SaveSettingValue"))}Fe.saveSettingValue=jP;async function mj(e,t={}){let r={};for(let[n,i]of Object.entries(Fe.AI_GATE)){let{value:a,dataType:o}=await Kc(e,i,t);r[n]={enabled:WP(a,o,n),setting:i,value:a}}return r}Fe.getAiReadiness=mj;async function hj(e,t,r,n={}){var i,a;if(!t||!t.trim())throw new En.InvalidArgumentError("setAppAiFeatures: a non-empty appUniqueName is required (an empty value would write the setting at organization scope, affecting every app).");let o=dj(n.verifyAttempts),s=pj(n.verifyDelayMs),l=[];for(let[h,v]of Object.entries(r)){if(v===void 0)continue;let w=zP[h];w&&l.push({feature:h,setting:w,requestedValue:nj(v,h)})}let u=[],c=n.appModuleId?(0,et.normalizeGuid)(n.appModuleId,"appModuleId"):void 0;if(c){let h=await oj(e,t);if(h&&(0,et.normalizeGuid)(h,"appModuleId")!==c)throw new En.InvalidArgumentError(`setAppAiFeatures: appModuleId '${c}' does not belong to app '${t}' (which resolves to '${h}'). Settings are written by unique name, so verifying against a different app would report success for a write that never landed.`)}let d,p=async()=>c||(d||(d=await aj(e,t)),d),f=new Map,m=async h=>{if(tj.has(h))return;let v=Fe.AI_GATE[h];if(v){if(!f.has(v))try{let{value:w,dataType:C}=await Kc(e,v);f.set(v,{enabled:WP(w,C,h),setting:v,value:w})}catch{f.set(v,void 0)}return f.get(v)}};for(let{feature:h,setting:v,requestedValue:w}of l)try{await jP(e,v,w,{appUniqueName:t,solutionUniqueName:n.solutionUniqueName});let C=await fj(e,p,t,v,w,o,s),E={feature:h,setting:v,requestedValue:w,effectiveValue:C.effectiveValue,appOverrideExists:C.appOverrideExists};if(C.result==="proven")u.push({...E,status:"applied"});else if(C.result==="absent"){let D=ij(w,h)?await m(h):void 0;D&&!D.enabled?u.push({...E,status:"skipped",reason:`the write was issued and no app-scope override holding '${w}' was observed for '${v}' after ${o} attempt(s); the org readiness gate '${D.setting}' reads '${D.value}', so an environment admin must enable it before this app can turn the feature on`}):u.push({...E,status:"notPersisted",reason:`the write reported success but no app-scope override holding '${w}' was observed for '${v}' after ${o} attempt(s) \u2014 it reads '${(i=C.effectiveValue)!==null&&i!==void 0?i:""}' for this app (Dataverse can accept an app-scope write without storing it)`})}else u.push({...E,status:"unverified",reason:`the write was issued but could not be confirmed: ${(a=C.reason)!==null&&a!==void 0?a:"the app-scope override row could not be read"}. The value may or may not be in force \u2014 verify manually before relying on it.`})}catch(C){u.push({feature:h,setting:v,requestedValue:w,status:"failed",reason:C.message})}return{applied:u.filter(h=>h.status==="applied").map(h=>h.feature),skipped:u.filter(h=>h.status==="skipped").map(h=>h.feature),notPersisted:u.filter(h=>h.status==="notPersisted").map(h=>h.feature),unverified:u.filter(h=>h.status==="unverified").map(h=>h.feature),failed:u.filter(h=>h.status==="failed").map(h=>h.feature),outcomes:u}}Fe.setAppAiFeatures=hj;var gj="GptPowerPrompt",vj='{ "consumptionSource": "Api", "partnerSource": "AIBuilder", "consumptionSourceVersion": "GptApiClient"}';function HP(e){var t,r,n,i;let a=e.entityLogicalName,o=[{type:"literal",text:e.instruction.replace(/\s*$/,"")+" "}];return e.columns.forEach((s,l)=>{o.push({type:"data",id:`${a}.${s.logical}`,text:s.display}),l<e.columns.length-1&&o.push({type:"literal",text:", "})}),{version:"GptDynamicPrompt-2",prompt:o,definitions:{inputs:[{id:"RecordId",text:"RecordId",type:"text"},{id:"LanguageCode",text:"LanguageCode",type:"text"}],formulas:[],data:[{id:a,displayName:a,type:"dataverseTable",filters:[{filterType:"equal",attribute:e.primaryKey,valueType:"inputVariable",value:"RecordId"}]}],output:{formats:[(t=e.outputFormat)!==null&&t!==void 0?t:"text"]}},modelParameters:{modelType:"default",gptParameters:{temperature:(r=e.temperature)!==null&&r!==void 0?r:0}},settings:{recordRetrievalLimit:(n=e.recordRetrievalLimit)!==null&&n!==void 0?n:30,shouldPreserveRecordLinks:null,runtime:null,enableReasoning:(i=e.enableReasoning)!==null&&i!==void 0?i:!0},code:"",signature:""}}Fe.buildGptDynamicPrompt=HP;async function yj(e,t){var r,n;let i=`/EntityDefinitions(LogicalName='${(0,et.odataPathLiteral)(t)}')${(0,et.odataQuery)([["$select","MetadataId"]])}`;return(n=(r=(0,Nr.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||r===void 0?void 0:r.MetadataId)!==null&&n!==void 0?n:""}async function bj(e,t,r={}){var n,i,a,o,s;let l=`ais_RowSummary_${t.entityLogicalName}`,u=`/aiskillconfigs${(0,et.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,et.odataLiteral)(l)}'`],["$top",1]])}`,c=((i=(n=(0,Nr.ensureSuccess)(await e.get(u),e.apiUrl(u)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[])[0];if(c)return{modelId:c._aimodel_value,aiSkillConfigId:c.aiskillconfigid};let d=`/msdyn_aitemplates${(0,et.odataQuery)([["$select","msdyn_aitemplateid"],["$filter",`msdyn_uniquename eq '${gj}'`],["$top",1]])}`,p=((s=(o=(a=(0,Nr.ensureSuccess)(await e.get(d),e.apiUrl(d)).body)===null||a===void 0?void 0:a.value)===null||o===void 0?void 0:o[0])!==null&&s!==void 0?s:{}).msdyn_aitemplateid,f=(0,$P.newId)(),m=(0,$P.newId)(),h=JSON.stringify(HP(t)),v={ModelId:f,RunConfigurationId:m,ModelName:`${t.entityLogicalName} row summary`,TemplateId:p,CustomConfiguration:h,Source:vj,RunConfiguration:""};(0,Nr.ensureSuccess)(await e.post("/AIModelPublish",v),e.apiUrl("/AIModelPublish"));try{let w=await yj(e,t.entityLogicalName),C={uniquename:l,description:`${t.entityLogicalName} row summary`,"[email protected]":`/entities(${w})`,"[email protected]":`/msdyn_aimodels(${f})`,aiskill:"RowSummary"},E=(0,Nr.ensureSuccess)(await e.post("/aiskillconfigs",C),e.apiUrl("/aiskillconfigs")),D=(0,Nr.requireCreatedId)(E,"aiskillconfigid","row-summary skill");return{modelId:f,aiSkillConfigId:D}}catch(w){try{await e.delete(`/msdyn_aimodels(${f})`)}catch{}throw w}}Fe.configureRowSummary=bj;async function wj(e,t){var r,n;let i=`ais_RowSummary_${t.entityLogicalName}`,a=`/aiskillconfigs${(0,et.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,et.odataLiteral)(i)}'`],["$top",1]])}`,o=((n=(r=(0,Nr.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0];if(!o)return;let s=`/aiskillconfigs(${o.aiskillconfigid})`;if((0,Nr.ensureSuccess)(await e.delete(s),e.apiUrl(s)),o._aimodel_value){let l=`/msdyn_aimodels(${o._aimodel_value})`;(0,Nr.ensureSuccess)(await e.delete(l),e.apiUrl(l))}}Fe.removeRowSummary=wj});var XP=y(lo=>{"use strict";Object.defineProperty(lo,"__esModule",{value:!0});lo.findArtifact=lo.resolveArtifact=void 0;var ot=le(),Sn=xl(),Aj=ql(),Cj=$t(),Ej=Ee(),KP=ee();async function QP(e,t,r){let n="/uxagentprojects"+(0,ot.odataQuery)([["$select","uxagentprojectid,name"],["$filter",`name eq '${(0,ot.odataLiteral)(t)}'`],...r!==void 0?[["$top",String(r)]]:[]]);return(await(0,Cj.collectPages)(e,n,"resolveArtifact('genPage')",void 0,{headers:{"MSCRM.IncludeUnpublished":"true"}})).map(a=>({id:String(a.uxagentprojectid),name:String(a.name)}))}async function Sj(e,t,r){var n,i,a,o,s,l,u,c,d,p,f,m,h;switch(t){case"app":{let v=(0,Aj.unpublishedAppModulesQuery)("appmoduleid,name,appmoduleidunique",`uniquename eq '${(0,ot.odataLiteral)((n=r.uniqueName)!==null&&n!==void 0?n:"")}'`,1),C=(i=(0,Ej.ensureSuccess)(await e.get(v),e.apiUrl(v)).body)===null||i===void 0?void 0:i.value,E=C&&C[0];return E?[{id:String(E.appmoduleid),name:String(E.name),appModuleIdUnique:String(E.appmoduleidunique)}]:[]}case"dashboard":return(await(0,Sn.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,ot.odataLiteral)((a=r.name)!==null&&a!==void 0?a:"")}' and type eq 0`,top:10})||[]).map(w=>({id:String(w.formid),name:String(w.name)}));case"command":{let v=await(0,Sn.queryRecords)(e,"appaction",{select:["appactionid","buttonlabeltext"],filter:`contextvalue eq '${(0,ot.odataLiteral)((o=r.entity)!==null&&o!==void 0?o:"")}'`,top:1});return v&&v.length?[{id:String(r.entity),entity:String(r.entity)}]:[]}case"form":return(await(0,Sn.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,ot.odataLiteral)((s=r.name)!==null&&s!==void 0?s:"")}' and objecttypecode eq '${(0,ot.odataLiteral)((l=r.entity)!==null&&l!==void 0?l:"")}'`,top:10})||[]).map(w=>({id:String(w.formid),name:String(w.name)}));case"chart":return(await(0,Sn.queryRecords)(e,"savedqueryvisualization",{select:["savedqueryvisualizationid","name"],filter:`name eq '${(0,ot.odataLiteral)((u=r.name)!==null&&u!==void 0?u:"")}' and primaryentitytypecode eq '${(0,ot.odataLiteral)((c=r.entity)!==null&&c!==void 0?c:"")}'`,top:10})||[]).map(w=>({id:String(w.savedqueryvisualizationid),name:String(w.name)}));case"view":return(await(0,Sn.queryRecords)(e,"savedquery",{select:["savedqueryid","name"],filter:`name eq '${(0,ot.odataLiteral)((d=r.name)!==null&&d!==void 0?d:"")}' and returnedtypecode eq '${(0,ot.odataLiteral)((p=r.entity)!==null&&p!==void 0?p:"")}'`,top:10})||[]).map(w=>({id:String(w.savedqueryid),name:String(w.name)}));case"webResource":return(await(0,Sn.queryRecords)(e,"webresource",{select:["webresourceid","name"],filter:`name eq '${(0,ot.odataLiteral)((f=r.name)!==null&&f!==void 0?f:"")}'`,top:1})||[]).map(w=>({id:String(w.webresourceid),name:String(w.name)}));case"solution":return(await(0,Sn.queryRecords)(e,"solution",{select:["solutionid","uniquename"],filter:`uniquename eq '${(0,ot.odataLiteral)((m=r.uniqueName)!==null&&m!==void 0?m:"")}'`,top:1})||[]).map(w=>({id:String(w.solutionid),name:String(w.uniquename)}));case"genPage":return QP(e,(h=r.name)!==null&&h!==void 0?h:"");default:return[]}}lo.resolveArtifact=Sj;async function Nj(e,t,r){var n,i,a,o,s,l,u;let c=(0,ot.odataLiteral)((n=r.name)!==null&&n!==void 0?n:""),d=(0,ot.odataLiteral)((i=r.entity)!==null&&i!==void 0?i:"");if(t==="command"){let v=await(0,Sn.queryRecords)(e,"appaction",{select:["appactionid"],filter:`contextvalue eq '${(0,ot.odataLiteral)((a=r.entity)!==null&&a!==void 0?a:"")}'`,top:1});return v&&v.length?String(r.entity):null}if(t==="genPage"){let v=await QP(e,(o=r.name)!==null&&o!==void 0?o:"",2);if(v.length>1)throw new KP.AmbiguousArtifactError(t,(s=r.name)!==null&&s!==void 0?s:"",v.length);return v.length===1?v[0].id:null}let p=Dj(t,c,d,r),f=t!=="app",m=await(0,Sn.queryRecords)(e,p.set,{select:[p.idField],filter:p.filter,top:f?2:1});if(f&&m&&m.length>1)throw new KP.AmbiguousArtifactError(t,(u=(l=r.name)!==null&&l!==void 0?l:r.uniqueName)!==null&&u!==void 0?u:"",m.length);let h=m&&m[0]&&m[0][p.idField];return h!=null?String(h):null}lo.findArtifact=Nj;function Dj(e,t,r,n){var i;switch(e){case"view":return{set:"savedquery",idField:"savedqueryid",filter:`returnedtypecode eq '${r}' and name eq '${t}'`};case"chart":return{set:"savedqueryvisualization",idField:"savedqueryvisualizationid",filter:`primaryentitytypecode eq '${r}' and name eq '${t}'`};case"form":return{set:"systemform",idField:"formid",filter:`objecttypecode eq '${r}' and name eq '${t}'`};case"app":return{set:"appmodule",idField:"appmoduleid",filter:`uniquename eq '${(0,ot.odataLiteral)((i=n.uniqueName)!==null&&i!==void 0?i:"")}'`};case"dashboard":return{set:"systemform",idField:"formid",filter:`name eq '${t}' and type eq 0`};default:throw new Error(`Unsupported findable kind: ${e}`)}}});var ZP=y(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});Xc.seedRecordGraph=void 0;var YP=xl(),Ij=pl(),Qc=le(),_j=ee();async function Tj(e,t,r={}){var n,i,a,o,s;let l=(n=r.createdIds)!==null&&n!==void 0?n:{},u=(i=r.entitySetFor)!==null&&i!==void 0?i:(p=>(0,Ij.resolveEntitySetName)(e,p)),c={},d=p=>{var f;return(f=c[p])!==null&&f!==void 0?f:l[p]};for(let p of t){let f=p.entityLogical.toLowerCase(),m=(a=p.matchOn)===null||a===void 0?void 0:a.toLowerCase(),h=[];for(let x of p.records){let F={...x.body};for(let M of(o=x.binds)!==null&&o!==void 0?o:[]){let P=M.parentEntity.toLowerCase(),q=(s=d(P))===null||s===void 0?void 0:s[M.parentIndex];if(!q)throw new _j.InvalidArgumentError(`Cannot resolve bind '${M.navProperty}' on a '${f}' record: parent '${M.parentEntity}'[${M.parentIndex}] has no created id. Seed the parent group before the child, or supply it via options.createdIds.`);let $=(0,Qc.assertODataName)(await u(P),`entity set for parent '${M.parentEntity}'`),qe=(0,Qc.normalizeGuid)(q,`parent id for bind '${M.navProperty}'`);F[`${M.navProperty}@odata.bind`]=`/${$}(${qe})`}h.push(F)}let v=m?h.map(x=>{let F=x[m];return F!=null&&F!==""?String(F):null}):h.map(()=>null),w=new Map;if(m){let x=(0,Qc.assertODataName)(m,"RecordGraph matchOn key"),F=[...new Set(v.filter(M=>M!==null))];if(F.length){let M=F.map(q=>`${x} eq '${(0,Qc.odataLiteral)(q)}'`).join(" or "),P=await(0,YP.queryRecords)(e,f,{select:[x,`${f}id`],filter:M,top:5e3});for(let q of P??[]){let $=q[x];$!=null&&w.set(String($).toLowerCase(),String(q[`${f}id`]))}}}let C=[],E=new Map,D=h.map((x,F)=>{let M=v[F];if(M&&w.has(M.toLowerCase()))return null;if(M){let P=M.toLowerCase(),q=E.get(P);if(q!==void 0)return q;let $=C.push(x)-1;return E.set(P,$),$}return C.push(x)-1}),O=C.length?await(0,YP.createRecordsBulk)(e,f,C):[];c[f]=h.map((x,F)=>{let M=v[F];return M&&w.has(M.toLowerCase())?w.get(M.toLowerCase()):O[D[F]]})}return{createdIds:c}}Xc.seedRecordGraph=Tj});var uR=y(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.getEntityPrivileges=ht.addEntityPrivilegesToRole=ht.deleteSecurityRole=ht.createPersonaRole=ht.createSecurityRole=ht.SDK_ROLE_MARKER=void 0;var Dr=Ee(),tt=le(),jt=ee(),Yc={read:"Read",create:"Create",write:"Write",delete:"Delete",append:"Append",appendTo:"AppendTo",assign:"Assign",share:"Share"},lg={user:"Basic",businessUnit:"Local",parentChild:"Deep",organization:"Global"},eR={user:1,businessUnit:2,parentChild:3,organization:4},sg={user:"CanBeBasic",businessUnit:"CanBeLocal",parentChild:"CanBeDeep",organization:"CanBeGlobal"};ht.SDK_ROLE_MARKER="Authored by @maker-studio/cds-maker-sdk (persona/security role).";function Pj(e){return Object.prototype.hasOwnProperty.call(Yc,e)?Yc[e]:void 0}function Rj(e){return Object.prototype.hasOwnProperty.call(lg,e)}var tR=new WeakMap,rR=new WeakMap;async function aR(e,t){var r,n;(0,tt.assertODataName)(t,"entity logical name");let i=tR.get(e);i||(i=new Map,tR.set(e,i));let a=i.get(t);if(a)return a;let o=`/EntityDefinitions(LogicalName='${(0,tt.odataPathLiteral)(t)}')${(0,tt.odataQuery)([["$select","LogicalName,Privileges"]])}`,l=(n=(r=(0,Dr.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||r===void 0?void 0:r.Privileges)!==null&&n!==void 0?n:[];if(l.length===0)throw new jt.InvalidArgumentError(`Entity '${t}' exposes no privileges (unknown or non-securable entity).`);return i.set(t,l),l}async function Oj(e){var t,r,n;let i=rR.get(e);if(i)return i;let a=`/businessunits${(0,tt.odataQuery)([["$select","businessunitid"],["$filter","_parentbusinessunitid_value eq null"],["$top",1]])}`,l=(n=((r=(t=(0,Dr.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||t===void 0?void 0:t.value)!==null&&r!==void 0?r:[])[0])===null||n===void 0?void 0:n.businessunitid;if(!l)throw new jt.InvalidArgumentError("Could not resolve the root business unit.");let u=(0,tt.normalizeGuid)(l,"businessUnitId");return rR.set(e,u),u}async function oR(e,t){var r;let n=new Map;for(let i of t){if(!i.access||i.access.length===0)throw new jt.InvalidArgumentError(`Entity '${i.entity}' privilege request has no access levels.`);let a=(r=i.scope)!==null&&r!==void 0?r:"user";if(!Rj(a))throw new jt.InvalidArgumentError(`Unknown privilege scope '${a}' for entity '${i.entity}'.`);let o=await aR(e,i.entity);for(let s of i.access){let l=Pj(s);if(!l)throw new jt.InvalidArgumentError(`Unknown access level '${s}' for entity '${i.entity}'.`);let u=o.find(m=>m.PrivilegeType===l);if(!u)throw new jt.InvalidArgumentError(`Entity '${i.entity}' does not support '${s}' access.`);let c=sg[a];if(u[c]===!1)throw new jt.InvalidArgumentError(`Privilege '${u.Name}' on '${i.entity}' does not support the '${a}' scope.`);let d=(0,tt.normalizeGuid)(u.PrivilegeId,"PrivilegeId"),p=n.get(d);if(!p){n.set(d,{privilegeName:u.Name,privilegeType:l,scope:a,entities:new Set([i.entity])});continue}if(p.scope===a){p.entities.add(i.entity);continue}if(!(p.entities.size===1&&p.entities.has(i.entity))){let m=[...p.entities].sort().join(", ");throw new jt.InvalidArgumentError(`Entities '${m}' and '${i.entity}' share the Dataverse privilege '${u.Name}' but request different scopes; a role holds one depth per privilege. Use the same scope for all entities that share this privilege, or split them.`)}p.scope=eR[a]>eR[p.scope]?a:p.scope}}return[...n.entries()].map(([i,a])=>({entity:[...a.entities].sort().join(", "),privilegeId:i,privilegeName:a.privilegeName,privilegeType:a.privilegeType,scope:a.scope}))}async function xj(e,t,r,n){if(r.length===0&&!n)return;let i={Privileges:r.map(o=>({Depth:lg[o.scope],PrivilegeId:o.privilegeId}))},a=`/roles(${t})/Microsoft.Dynamics.CRM.ReplacePrivilegesRole`;(0,Dr.ensureSuccess)(await e.post(a,i),e.apiUrl(a))}async function nR(e,t,r,n,i){var a,o;let s=`/${t}(${r})/${n}${(0,tt.odataQuery)([["$select","roleid"],["$filter",`roleid eq ${i}`]])}`;return((o=(a=(0,Dr.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||a===void 0?void 0:a.value)!==null&&o!==void 0?o:[]).length>0}async function Lj(e,t,r){var n,i;let a=[],o=[],s={"@odata.id":e.apiUrl(`/roles(${t})`)};for(let l of(n=r?.teams)!==null&&n!==void 0?n:[]){let u=(0,tt.normalizeGuid)(l,"teamId");if(!await nR(e,"teams",u,"teamroles_association",t)){let c=`/teams(${u})/teamroles_association/$ref`;(0,Dr.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}a.push(u)}for(let l of(i=r?.users)!==null&&i!==void 0?i:[]){let u=(0,tt.normalizeGuid)(l,"userId");if(!await nR(e,"systemusers",u,"systemuserroles_association",t)){let c=`/systemusers(${u})/systemuserroles_association/$ref`;(0,Dr.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}o.push(u)}return{teams:a,users:o}}async function iR(e,t,r){var n,i;let a=`/roles${(0,tt.odataQuery)([["$select","roleid,description,ismanaged"],["$filter",`name eq '${(0,tt.odataLiteral)(t)}' and _businessunitid_value eq ${r}`]])}`,l=((i=(n=(0,Dr.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]).filter(d=>!!d.roleid);if(l.length===0)return;let u=d=>{var p;return d.ismanaged!==!0&&((p=d.description)!==null&&p!==void 0?p:"")===ht.SDK_ROLE_MARKER};if(l.some(d=>!u(d)))throw new jt.InvalidArgumentError(`A role named '${t}' already exists in this business unit and was not created by the SDK; refusing to modify or assign it. Choose a different persona/role name.`);if(l.length>1)throw new jt.InvalidArgumentError(`Multiple (${l.length}) SDK-owned roles named '${t}' exist in this business unit; refusing to reuse one arbitrarily. Remove the duplicate role(s) and retry.`);let c=l[0].roleid;return c?(0,tt.normalizeGuid)(c,"roleId"):void 0}function Fj(e){var t,r;return{teams:((t=e?.teams)!==null&&t!==void 0?t:[]).map(n=>(0,tt.normalizeGuid)(n,"teamId")),users:((r=e?.users)!==null&&r!==void 0?r:[]).map(n=>(0,tt.normalizeGuid)(n,"userId"))}}function sR(e){return e.map(t=>({entity:t.entity,privilegeName:t.privilegeName,privilegeType:t.privilegeType,scope:t.scope}))}async function lR(e,t){var r,n;let i=(r=t.name)===null||r===void 0?void 0:r.trim();if(!i)throw new jt.InvalidArgumentError("createSecurityRole: a non-empty role name is required.");let a=t.businessUnitId?(0,tt.normalizeGuid)(t.businessUnitId,"businessUnitId"):await Oj(e),o=await oR(e,(n=t.privileges)!==null&&n!==void 0?n:[]),s=Fj(t.assignTo),l=await iR(e,i,a),u=l!==void 0;if(!l){let d="/roles",p={name:i,description:ht.SDK_ROLE_MARKER,"[email protected]":`/businessunits(${a})`};try{let f=(0,Dr.ensureSuccess)(await e.post(d,p),e.apiUrl(d));l=(0,tt.normalizeGuid)((0,Dr.requireCreatedId)(f,"roleid","role"),"roleId")}catch(f){let m;try{m=await iR(e,i,a)}catch{m=void 0}if(!m)throw f;l=m}}await xj(e,l,o,u);let c=await Lj(e,l,s);return{roleId:l,name:i,reused:u,appliedPrivileges:sR(o),assignedTeams:c.teams,assignedUsers:c.users}}ht.createSecurityRole=lR;async function kj(e,t){var r,n;let i=(r=t.persona)===null||r===void 0?void 0:r.trim();if(!i)throw new jt.InvalidArgumentError("createPersonaRole: a non-empty persona name is required.");let a=[...t.jobs.flatMap(o=>{var s;return(s=o.privileges)!==null&&s!==void 0?s:[]}),...(n=t.additionalPrivileges)!==null&&n!==void 0?n:[]];return lR(e,{name:i,businessUnitId:t.businessUnitId,privileges:a,assignTo:t.assignTo})}ht.createPersonaRole=kj;async function Mj(e,t){let n=`/roles(${(0,tt.normalizeGuid)(t,"roleId")})`;(0,Dr.ensureSuccess)(await e.delete(n),e.apiUrl(n))}ht.deleteSecurityRole=Mj;async function Bj(e,t,r){let n=(0,tt.normalizeGuid)(t,"roleId");if(r.length===0)throw new jt.InvalidArgumentError("addEntityPrivilegesToRole requires at least one entity privilege (an empty grant would be a silent no-op).");let i=await oR(e,r),a={Privileges:i.map(s=>({Depth:lg[s.scope],PrivilegeId:s.privilegeId}))},o=`/roles(${n})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;return(0,Dr.ensureSuccess)(await e.post(o,a),e.apiUrl(o)),sR(i)}ht.addEntityPrivilegesToRole=Bj;var Uj=new Map(Object.keys(Yc).map(e=>[Yc[e],e]));async function $j(e,t){return(await aR(e,t)).map(n=>{let i=Object.keys(sg).filter(o=>n[sg[o]]!==!1),a=Uj.get(n.PrivilegeType);return{name:n.Name,privilegeId:n.PrivilegeId,privilegeType:n.PrivilegeType,...a?{access:a}:{},scopes:i}})}ht.getEntityPrivileges=$j});var gR=y(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.createMakerSdk=Ht.MakerSdk=Ht.PUSH_NOT_ATTEMPTED_CODE=Ht.ALREADY_EXISTS_CODE=void 0;var cR=bd(),re=ee(),dr=tl(),qj=R0(),hR=M0(),Gs=G0(),Vj=Ad(),Gj=lv(),ug=uv(),zj=Ev(),rt=pl(),dR=up(),Nn=xl(),Zc=Ky(),uo=Ml(),Wj=Ul(),gt=rb(),jj=mp(),Hj=Sp(),Jj=UP(),Kj=st(),Qj=Ji(),Dn=sh(),zs=Sd(),Xj=3e5,Ir=Ee(),oi=le(),co=JP(),pR=XP(),Yj=ZP(),Zj=Nm(),Ws=uR();function eH(e){let t=e.workspaceStorage;if(t==null)throw new Error("createMakerSdk requires a workspaceStorage. Node callers can build one with `createNodeWorkspaceStorage(path)` from '@maker-studio/cds-maker-sdk/node'; a host with no filesystem implements WorkspaceStorage directly.");return new hR.WorkspaceManager(tH,e.instanceUrl,(0,Vj.assertStorageContract)(t))}Ht.ALREADY_EXISTS_CODE="ARTIFACT_ALREADY_EXISTS";Ht.PUSH_NOT_ATTEMPTED_CODE="PUSH_NOT_ATTEMPTED";var tH="<injected workspaceStorage>",ed=class{constructor(t){var r,n;this.artifactLocks=new Map,this.languageCode=(r=t.languageCode)!==null&&r!==void 0?r:Qj.DEFAULT_LCID,this.cacheStalenessMs=(n=t.cacheStalenessMs)!==null&&n!==void 0?n:Xj,this.compiler={load:(0,jj.createGenPageTypeScriptLoader)(t.typescript)},this.workspace=eH(t),this.versions=new Gs.VersionManager(this.workspace),this.dataverse=new Gj.DataverseClient(t.instanceUrl,t.httpClient,t.solutionUniqueName),this.registrations=(0,Jj.buildRegistrations)(this.languageCode)}async initWorkspace(){await this.workspace.init()}async getManifest(){return this.workspace.getManifest()}async cleanWorkspace(){await this.workspace.clean()}withArtifactLock(t,r,n){var i;let a=`${t}\0${(0,hR.canonicalArtifactId)(r)}`,s=((i=this.artifactLocks.get(a))!==null&&i!==void 0?i:Promise.resolve()).then(n,n),l=s.then(()=>{},()=>{});return this.artifactLocks.set(a,l),l.then(()=>{this.artifactLocks.get(a)===l&&this.artifactLocks.delete(a)}),s}async fetchArtifact(t,r,n){return this.withArtifactLock(t,r,()=>this.fetchArtifactUnlocked(t,r,n))}async fetchArtifactUnlocked(t,r,n){var i,a;let o=this.requireRegistration(t,"fetchArtifact"),{raw:s,etag:l,memberEtags:u,siblingEtags:c}=await o.api.get(this.dataverse,r),d=o.adapter.fromApiResponse(s);if(!n?.overwrite&&await this.versions.isDirty(t,r)){let p=(a=(i=await this.versions.getMeta(t,r))===null||i===void 0?void 0:i.etag)!==null&&a!==void 0?a:null;if(p&&l&&p!==l)throw new re.LocalEditsWouldBeLostError(t,r,p,l);let f=await this.workspace.readArtifact(t,r);if(f){let m=await this.versions.getMeta(t,r);if(m&&!m.etag&&l){if(!(0,zs.deepEqual)(m.snapshot,d))throw new re.LocalEditsWouldBeLostError(t,r,p,l);await this.versions.storeMeta(t,r,{...m,etag:l,fetchedAt:(0,Ir.nowIso)()})}return(0,Dn.cloneJson)(f)}}return await this.workspace.writeArtifact(t,r,d),await this.versions.storeMeta(t,r,{etag:l,languageCode:this.languageCode,projectionVersion:Gs.PROJECTION_VERSION,fetchedAt:(0,Ir.nowIso)(),snapshot:(0,Dn.cloneJson)(d),...u?{memberEtags:u}:{},...c?{siblingEtags:c}:{}}),(0,Dn.cloneJson)(d)}async fetchArtifactList(t,r){return this.requireRegistration(t,"fetchArtifactList").api.list(this.dataverse,r)}async fetchSolution(t){var r;let n=await(0,gt.fetchSolutionComponents)(this.dataverse,t),i=[],a=[];for(let o of n)try{let s=await this.resolveComponentType(o);if(!s){a.push({componentId:o.objectId,componentType:o.componentType,workflowCategory:o.workflowCategory,reason:"unsupported"});continue}let l=await this.fetchArtifact(s,o.objectId);i.push({type:s,id:o.objectId,name:typeof l.name=="string"?l.name:(r=o.displayName)!==null&&r!==void 0?r:o.objectId,entityLogicalName:typeof l.entityLogicalName=="string"?l.entityLogicalName:void 0,lastFetched:(0,Ir.nowIso)(),isDirty:!1})}catch(s){a.push({componentId:o.objectId,componentType:o.componentType,workflowCategory:o.workflowCategory,reason:"failed",error:po(s)})}return await this.workspace.updateManifest({lastSyncAt:(0,Ir.nowIso)()}),{summaries:i,skipped:a}}async fetchEntityMetadata(t){let r=await(0,ug.fetchEntityMetadataFromApi)(this.dataverse,t);return await this.workspace.writeEntityMetadata(t,r),r}generateGenPageRuntimeTypes(t,r){return(0,zj.generateGenPageRuntimeTypes)(n=>this.fetchEntityMetadata(n),t,r)}findTables(t,r){return(0,ug.findTables)(this.dataverse,t,r)}findColumns(t,r,n){return(0,ug.findColumns)(this.dataverse,t,r,n)}createTable(t){return(0,rt.createTable)(this.dataverse,t)}createColumn(t,r){return(0,rt.createColumn)(this.dataverse,t,r)}createColumns(t,r){return(0,rt.createColumns)(this.dataverse,t,r)}updateColumn(t,r,n){return(0,rt.updateColumn)(this.dataverse,t,r,n)}deleteColumn(t,r){return(0,rt.deleteColumn)(this.dataverse,t,r)}setFormSecurityRoles(t,r){return(0,dR.setFormSecurityRoles)(this.dataverse,t,r)}getFormSecurityRoles(t){return(0,dR.getFormSecurityRoles)(this.dataverse,t)}setColumnVisualization(t,r,n){return(0,rt.setColumnVisualization)(this.dataverse,t,r,n)}getColumnVisualization(t,r){return(0,rt.getColumnVisualization)(this.dataverse,t,r)}createCustomerColumn(t,r){return(0,rt.createCustomerColumn)(this.dataverse,t,r)}insertStatusValue(t,r){return(0,rt.insertStatusValue)(this.dataverse,t,r)}updateTable(t,r){return(0,rt.updateTable)(this.dataverse,t,r)}async setEntityIcon(t,r){if(await(0,rt.updateTable)(this.dataverse,t,{iconVectorName:r.vector,iconSmallName:r.small,iconMediumName:r.medium,iconLargeName:r.large}),r.publish!==!1){let n=`<importexportxml><entities><entity>${(0,oi.xmlText)(t)}</entity></entities></importexportxml>`;(0,Ir.ensureSuccess)(await this.dataverse.post("/PublishXml",{ParameterXml:n}),this.dataverse.apiUrl("/PublishXml"))}}createAlternateKey(t,r){return(0,rt.createAlternateKey)(this.dataverse,t,r)}deleteAlternateKey(t,r){return(0,rt.deleteAlternateKey)(this.dataverse,t,r)}createRelationship(t){return(0,rt.createRelationship)(this.dataverse,t)}deleteRelationship(t){return(0,rt.deleteRelationship)(this.dataverse,t)}createGlobalOptionSet(t){return(0,rt.createGlobalOptionSet)(this.dataverse,t)}deleteGlobalOptionSet(t){return(0,rt.deleteGlobalOptionSet)(this.dataverse,t)}deleteTable(t){return(0,rt.deleteTable)(this.dataverse,t)}createSecurityRole(t){return(0,Ws.createSecurityRole)(this.dataverse,t)}createPersonaRole(t){return(0,Ws.createPersonaRole)(this.dataverse,t)}deleteSecurityRole(t){return(0,Ws.deleteSecurityRole)(this.dataverse,t)}addEntityPrivilegesToRole(t,r){return(0,Ws.addEntityPrivilegesToRole)(this.dataverse,t,r)}getEntityPrivileges(t){return(0,Ws.getEntityPrivileges)(this.dataverse,t)}createRecord(t,r){return(0,Nn.createRecord)(this.dataverse,t,r)}createRecordsBulk(t,r){return(0,Nn.createRecordsBulk)(this.dataverse,t,r)}updateRecord(t,r,n){return(0,Nn.updateRecord)(this.dataverse,t,r,n)}upsertRecord(t,r,n){return(0,Nn.upsertRecord)(this.dataverse,t,r,n)}deleteRecord(t,r){return(0,Nn.deleteRecord)(this.dataverse,t,r)}getRecord(t,r,n){return(0,Nn.getRecord)(this.dataverse,t,r,n)}queryRecords(t,r){return(0,Nn.queryRecords)(this.dataverse,t,r)}seedRecordGraph(t,r){return(0,Yj.seedRecordGraph)(this.dataverse,t,r)}resolveArtifact(t,r){return(0,pR.resolveArtifact)(this.dataverse,t,r)}findArtifact(t,r){return(0,pR.findArtifact)(this.dataverse,t,r)}async deleteAppCascade(t,r){let n=await(0,Hj.deleteAppCascade)(this.dataverse,t,r),i=(0,oi.normalizeGuid)(t,"appModuleId");return await this.workspace.readArtifact("app",i)&&await this.workspace.deleteArtifact("app",i),n}associateRecords(t,r,n){return(0,Nn.associateRecords)(this.dataverse,t,r,n)}disassociateRecords(t,r,n,i){return(0,Nn.disassociateRecords)(this.dataverse,t,r,n,i)}createWebResource(t){return(0,Zc.createWebResource)(this.dataverse,t)}updateWebResource(t,r){return(0,Zc.updateWebResource)(this.dataverse,t,r)}getWebResource(t){return(0,Zc.getWebResource)(this.dataverse,t)}deleteWebResource(t){return(0,Zc.deleteWebResource)(this.dataverse,t)}getAppSettings(t){return(0,uo.readAppSettings)(this.dataverse,t)}setAppSetting(t,r,n){return(0,uo.setAppSetting)(this.dataverse,t,r,n)}setHeaderAndNavigationRefresh(t,r){if(typeof r!="boolean")throw new re.ValidationError("app",t,[{pointer:"/headerAndNavigationRefresh",rule:Wj.HEADER_NAV_BOOLEAN_RULE,message:`enabled must be a boolean, got ${typeof r}`}]);return(0,uo.setAppSetting)(this.dataverse,t,uo.HEADER_AND_NAVIGATION_REFRESH,r?uo.APP_SETTING_ON:uo.APP_SETTING_OFF)}getSolution(t){return(0,gt.getSolution)(this.dataverse,t)}createPublisher(t){return(0,gt.createPublisher)(this.dataverse,t)}createSolution(t){return(0,gt.createSolution)(this.dataverse,t)}setSolutionVersion(t,r){return(0,gt.setSolutionVersion)(this.dataverse,t,r)}addSolutionComponent(t){return(0,gt.addSolutionComponent)(this.dataverse,t)}removeSolutionComponent(t,r,n){return(0,gt.removeSolutionComponent)(this.dataverse,t,r,n)}exportSolution(t){return(0,gt.exportSolution)(this.dataverse,t)}importSolution(t){return(0,gt.importSolution)(this.dataverse,t)}deleteSolution(t){return(0,gt.deleteSolution)(this.dataverse,t)}async getArtifact(t,r){return this.withArtifactLock(t,r,()=>this.getArtifactUnlocked(t,r))}async getArtifactUnlocked(t,r){return(0,Dn.cloneJson)(await this.readRaw(t,r))}async readRaw(t,r){return await this.revalidateIfStale(t,r),this.readLocal(t,r)}async readForMutation(t,r,n){if(await this.revalidateIfStale(t,r)==="refreshed-changed")throw new re.StaleArtifactError(t,r,n);return this.readLocal(t,r)}async readLocal(t,r){let n=await this.workspace.readArtifact(t,r);if(!n)throw new re.ArtifactNotFoundError(t,r);return n}async revalidateIfStale(t,r){let n=await this.versions.getMeta(t,r);if(!n)return"skipped";let i=n.fetchedAt?Date.parse(n.fetchedAt):NaN,a=Date.now()-i;if(!Number.isNaN(i)&&this.cacheStalenessMs>0&&a<=this.cacheStalenessMs)return"fresh";if(await this.versions.isDirty(t,r))return"skipped";let o=await this.workspace.readArtifact(t,r);await this.fetchArtifactUnlocked(t,r);let s=await this.workspace.readArtifact(t,r);return(0,zs.deepEqual)(o,s)?"refreshed-unchanged":"refreshed-changed"}async queryTree(t,r,n){return this.withArtifactLock(t,r,async()=>{let i=await this.getArtifactUnlocked(t,r),a=dr.JsonPointer.resolve(i,n);if(a===void 0)throw new re.PathNotFoundError(t,r,n);return a})}async findElements(t,r,n){return this.withArtifactLock(t,r,async()=>(0,qj.findElements)(await this.getArtifactUnlocked(t,r),n))}async withDirtyFlags(t){let r=[];for(let n of t)r.push({...n,isDirty:await this.versions.isDirty(n.type,n.id)});return r}async listArtifacts(t,r){return this.withDirtyFlags(await this.workspace.listArtifacts(t,r))}async getEntityMetadata(t){let r=await this.workspace.readEntityMetadata(t);if(!r)throw new re.ArtifactNotFoundError("entityMetadata",t);return r}async getFieldMetadata(t,r){let i=(await this.getEntityMetadata(t)).attributes.find(a=>a.logicalName===r);if(!i)throw new re.PathNotFoundError("entityMetadata",t,r);return i}async updateElement(t,r,n,i){return this.withArtifactLock(t,r,async()=>{let a=await this.readForMutation(t,r,n),o=dr.JsonPointer.resolve(a,n);if(o===void 0)throw new re.PathNotFoundError(t,r,n);let s=In(o)&&In(i)?{...o,...i}:i;return dr.JsonPointer.set(a,n,(0,Dn.cloneJson)(s)),this.assertStructurallyValid(t,r,a,n),await this.workspace.writeArtifact(t,r,a),this.getArtifactUnlocked(t,r)})}async addElement(t,r,n,i,a){return this.withArtifactLock(t,r,async()=>{let o=await this.readForMutation(t,r,n),s=dr.JsonPointer.resolve(o,n);if(s===void 0)throw new re.PathNotFoundError(t,r,n);if(!Array.isArray(s)){if(!In(s)||!In(i))throw new re.ValidationError(t,r,n,"parent must be an array, or an object with an object of properties to add");if(a?.position!==void 0)throw new re.ValidationError(t,r,n,"position is not supported for an object parent");let c={};for(let d of Object.keys(i)){if(d==="id")throw new re.ValidationError(t,r,n,"refusing to write 'id' \u2014 that re-keys the node rather than adding a property");let p=(0,Dn.cloneJson)(i[d]);c[d]=Array.isArray(p)?p.map(f=>In(f)?this.assignMissingIds(t,f):f):In(p)?this.assignMissingIds(t,p):p}for(let d of Object.keys(c))dr.JsonPointer.set(o,dr.JsonPointer.append(n,d),c[d]);return this.assertStructurallyValid(t,r,o,n),await this.workspace.writeArtifact(t,r,o),this.getArtifactUnlocked(t,r)}let l=this.assignMissingIds(t,(0,Dn.cloneJson)(i)),u=nH(s,a?.position);return s.splice(u,0,l),this.assertStructurallyValid(t,r,o,n),await this.workspace.writeArtifact(t,r,o),this.getArtifactUnlocked(t,r)})}async moveElement(t,r,n,i,a){return this.withArtifactLock(t,r,async()=>{var o;let s=await this.readForMutation(t,r,n),l=dr.JsonPointer.resolve(s,n);if(l===void 0)throw new re.PathNotFoundError(t,r,n);let u=dr.JsonPointer.resolve(s,i);if(u===void 0)throw new re.PathNotFoundError(t,r,i);if(!Array.isArray(u))throw new re.ValidationError(t,r,i,"move target must be an array");if(i===n||i.startsWith(`${n}/`))throw new re.ValidationError(t,r,i,"cannot move an element into its own subtree");dr.JsonPointer.remove(s,n);let c=(o=a?.index)!==null&&o!==void 0?o:u.length;u.splice(Math.max(0,Math.min(c,u.length)),0,l),mR(u);let d=dr.JsonPointer.resolve(s,fR(n));return Array.isArray(d)&&d!==u&&mR(d),this.assertStructurallyValid(t,r,s,i),await this.workspace.writeArtifact(t,r,s),this.getArtifactUnlocked(t,r)})}async removeElement(t,r,n){return this.withArtifactLock(t,r,async()=>{let i=await this.readForMutation(t,r,n);if(dr.JsonPointer.resolve(i,n)===void 0)throw new re.PathNotFoundError(t,r,n);return dr.JsonPointer.remove(i,n),this.assertStructurallyValid(t,r,i,fR(n)),await this.workspace.writeArtifact(t,r,i),this.getArtifactUnlocked(t,r)})}assertStructurallyValid(t,r,n,i){var a,o,s;let l=this.registrations.get(t),u=(s=(o=l==null?void 0:(a=l.adapter).validate)===null||o===void 0?void 0:o.call(a,n,i))!==null&&s!==void 0?s:[];if(u.length>0)throw new re.ValidationError(t,r,u)}retrieveSetting(t,r){return(0,co.retrieveSetting)(this.dataverse,t,r)}saveSettingValue(t,r,n){return(0,co.saveSettingValue)(this.dataverse,t,r,n)}getAiReadiness(t){return(0,co.getAiReadiness)(this.dataverse,t)}setAppAiFeatures(t,r,n){return(0,co.setAppAiFeatures)(this.dataverse,t,r,n)}configureRowSummary(t,r){return(0,co.configureRowSummary)(this.dataverse,t,r)}removeRowSummary(t){return(0,co.removeRowSummary)(this.dataverse,t)}async enrichDefaultViews(t,r,n={}){let i=await(0,Zj.findDefaultViews)(this.dataverse,t,n),a=[];for(let o of i)await this.fetchArtifact("view",o.id),await this.updateElement("view",o.id,"/columns",r),(await this.pushArtifact("view",o.id)).saved&&a.push(o.id);if(a.length){let o=await this.publishArtifact("view",a[0]);if(o.publish.kind==="failed")throw new re.SdkError("ENRICH_DEFAULT_VIEWS_PUBLISH_FAILED",`enrichDefaultViews: ${a.length} view(s) on '${t}' were saved but the publish FAILED, so none of them is live (${o.publish.error.message}). Re-publish the entity to make them visible; the saves themselves are unaffected.`)}return{updated:a}}async createArtifact(t,r){let n=this.requireRegistration(t,"createArtifact"),i=n.adapter.assignMissingIds(n.adapter.createDefault(r)),a=i.id;if(!a)throw new re.ValidationError(t,"(new)","/id","created artifact must have an id");return this.withArtifactLock(t,a,async()=>(await this.workspace.writeArtifact(t,a,i),(0,Dn.cloneJson)(i)))}async deleteArtifact(t,r){return this.withArtifactLock(t,r,async()=>{await this.workspace.deleteArtifact(t,r)})}async deleteRemoteArtifact(t,r){return this.withArtifactLock(t,r,async()=>{await this.requireRegistration(t,"deleteRemoteArtifact").api.delete(this.dataverse,r),await this.workspace.readArtifact(t,r)&&await this.workspace.deleteArtifact(t,r)})}async publishArtifact(t,r,n){return this.withArtifactLock(t,r,()=>this.publishArtifactUnlocked(t,r,n))}async publishArtifactUnlocked(t,r,n){var i;let a=await this.readRaw(t,r),o=this.registrations.get(t);if(!o?.publish)return{type:t,id:r,shipped:!1,publish:{kind:"notApplicable"}};let s=(i=o.publishScope)===null||i===void 0?void 0:i.call(o,r,a);try{await o.publish(this.dataverse,r,a)}catch(u){return{type:t,id:r,shipped:!1,publish:{kind:"failed",error:po(u)},...s?{publishScope:s}:{}}}if(o.rebaselineAfterPublish&&await this.rebaselineAfterPublish(o,t,r),!n?.verify)return{type:t,id:r,shipped:!1,publish:{kind:"submitted"},...s?{publishScope:s}:{}};let l=await this.verifyPublished(t,r,a);return{type:t,id:r,shipped:l.kind==="verified",publish:l,...s?{publishScope:s}:{}}}async rebaselineAfterPublish(t,r,n){try{let i=await this.versions.getMeta(r,n);if(!i)return;let{raw:a,etag:o,memberEtags:s,siblingEtags:l}=await t.api.get(this.dataverse,n),u=t.adapter.fromApiResponse(a),c=d=>{var p,f,m;return(m=(f=(p=t.adapter).baselineContent)===null||f===void 0?void 0:f.call(p,d))!==null&&m!==void 0?m:d};if(!o||!(0,zs.deepEqual)(c(i.snapshot),c(u)))return;await this.versions.storeMeta(r,n,{...i,etag:o,fetchedAt:(0,Ir.nowIso)(),...s?{memberEtags:s}:{},...l?{siblingEtags:l}:{}})}catch{}}async verifyPublished(t,r,n){var i,a,o,s,l;if(t!=="app"){let u=this.registrations.get(t);return u?.api.getPublished?this.verifyPublishedContent(u,t,r,n):{kind:"unverifiable",reason:`published-projection verification is not characterised for '${t}'; the publish was submitted`}}try{let u=`/appmodules(${(0,oi.normalizeGuid)(r,"id")})${(0,oi.odataQuery)([["$select","appmoduleid,name,description"]])}`,c=await this.dataverse.get(u);if(c.status>=200&&c.status<300){let d=(i=c.body)!==null&&i!==void 0?i:{},p=await this.workspace.readArtifact("app",r);if(!p)return{kind:"verified"};let f=[];return((a=p.name)!==null&&a!==void 0?a:"")!==((o=d.name)!==null&&o!==void 0?o:"")&&f.push("name"),((s=p.description)!==null&&s!==void 0?s:"")!==((l=d.description)!==null&&l!==void 0?l:"")&&f.push("description"),f.length>0?{kind:"unverifiable",reason:`the published projection does not yet match the saved app (${f.join(", ")} still differ). PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists`}:{kind:"verified"}}return{kind:"unverifiable",reason:`the published projection answered HTTP ${c.status}`}}catch(u){return{kind:"unverifiable",reason:po(u).message}}}async verifyPublishedContent(t,r,n,i){var a,o,s;try{let l=p=>{var f,m,h;return(h=(m=(f=t.adapter).baselineContent)===null||m===void 0?void 0:m.call(f,p))!==null&&h!==void 0?h:p},u=l(i),c=(a=await this.versions.getMeta(r,n))===null||a===void 0?void 0:a.snapshot;if(c===void 0||!(0,zs.deepEqual)(u,l(c)))return{kind:"unverifiable",reason:`the local ${r} holds edits that were never pushed, so no publish could have shipped them \u2014 push, then publish again`};let d=await((s=(o=t.api).getPublished)===null||s===void 0?void 0:s.call(o,this.dataverse,n));return d?(0,zs.deepEqual)(u,l(t.adapter.fromApiResponse(d.raw)))?{kind:"verified"}:{kind:"unverifiable",reason:"the published projection does not show what was pushed. PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists"}:{kind:"unverifiable",reason:`the ${r} is not in the published projection yet. PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists`}}catch(l){return{kind:"unverifiable",reason:po(l).message}}}async pushArtifact(t,r){return this.withArtifactLock(t,r,()=>this.pushArtifactUnlocked(t,r))}async prepareArtifactUnlocked(t,r){var n,i;let a=this.requireRegistration(t,"pushArtifact"),o=await this.readLocal(t,r),s=(i=(n=a.adapter).normalize)===null||i===void 0?void 0:i.call(n,o);s&&s!==o&&(await this.workspace.writeArtifact(t,r,s),o=s);let l=await this.versions.getMeta(t,r);this.assertLanguageMatches(t,r,l,a),this.assertProjectionMatches(t,r,l);let u=await this.buildMetadataContext(a.adapter,o),c=await a.adapter.toApiPayload(o,l?.snapshot,u);return await this.assertSemanticallyComplete(a,t,r,o,l===null,l?.everActivated),{type:t,id:r,reg:a,json:o,meta:l,payload:c}}async assertSemanticallyComplete(t,r,n,i,a,o){var s;let l=t.adapter.issuesBlockingPush;if(!l)return;let u=i.entityLogicalName,c=u?await this.workspace.readEntityMetadata(u):null,d=((s=c?.attributes)!==null&&s!==void 0?s:[]).map(f=>({logicalName:f.logicalName,displayName:f.displayName,attributeType:f.attributeType,isCustomAttribute:f.isCustomAttribute,...f.maxLength!==void 0?{maxLength:f.maxLength}:{},...f.options?{options:f.options.map(m=>({value:m.value,label:m.label}))}:{},...f.targets?{targets:f.targets}:{}})),p=l.call(t.adapter,i,d,{isCreate:a,everActivated:o});if(p.length>0)throw new re.ValidationError(r,n,p)}async pushArtifactUnlocked(t,r){return this.executePrepared(await this.prepareArtifactUnlocked(t,r))}async executePrepared(t){var r,n,i,a,o,s;let{type:l,id:u,reg:c,json:d,meta:p,payload:f}=t;try{let m=p?await c.api.update(this.dataverse,u,f,p.etag,p.memberEtags,p.siblingEtags):await this.createWithMintedId(c,l,u,f),h=u;p||(m.serverIdentity&&c.adapter.applyServerIdentity&&c.adapter.applyServerIdentity(d,m.serverIdentity),m.id&&m.id!==u&&(d.id=m.id,await this.workspace.deleteArtifact(l,u),h=m.id));let v=c.adapter.committed?c.adapter.committed(d,f,{intentPending:m.intentPending===!0}):{artifact:d,baseline:d};return(!p||v.artifact!==d)&&await this.workspace.writeArtifact(l,h,v.artifact),await this.versions.storeMeta(l,h,{etag:m.etag,languageCode:this.languageCode,projectionVersion:Gs.PROJECTION_VERSION,fetchedAt:(0,Ir.nowIso)(),snapshot:(0,Dn.cloneJson)(v.baseline),...m.memberEtags?{memberEtags:m.memberEtags}:{},...m.siblingEtags?{siblingEtags:m.siblingEtags}:{}}),{type:l,id:h,saved:!0,shipped:!1,publish:(r=m.publish)!==null&&r!==void 0?r:{kind:"notRequested"},...m.publish&&m.publish.kind!=="notRequested"?(()=>{var w;let C=(w=c.publishScope)===null||w===void 0?void 0:w.call(c,h,d);return C?{publishScope:C}:{}})():{},...m.warnings&&m.warnings.length>0?{warnings:m.warnings}:{}}}catch(m){let h=(0,re.readPartialTokens)(m);if(h&&p){let v={...(n=p.memberEtags)!==null&&n!==void 0?n:{},...(i=h.memberEtags)!==null&&i!==void 0?i:{}},w={...(a=p.siblingEtags)!==null&&a!==void 0?a:{},...(o=h.siblingEtags)!==null&&o!==void 0?o:{}};await this.versions.storeMeta(l,u,{...p,...Object.keys(v).length>0?{memberEtags:v}:{},...Object.keys(w).length>0?{siblingEtags:w}:{}})}if(m instanceof re.SdkError&&m.code===Ht.ALREADY_EXISTS_CODE)return{type:l,id:u,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:m};if(m instanceof re.SdkError&&m.code===cR.WFOM_API_UNAVAILABLE_CODE)return{type:l,id:u,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:m};if(m instanceof re.SdkError&&m.code===cR.BUSINESS_RULE_LEFT_DEACTIVATED_CODE)return{type:l,id:u,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:m};if(m instanceof re.SdkError&&m.code===Ir.VERSION_CONFLICT_CODE)return{type:l,id:u,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:new re.VersionConflictError(l,u,(s=p?.etag)!==null&&s!==void 0?s:null,null,m.message)};throw m}}assertLanguageMatches(t,r,n,i){if(i?.languageSensitive&&!(n?.languageCode===void 0||n.languageCode===this.languageCode))throw new re.SdkError("ARTIFACT_LANGUAGE_MISMATCH",`Refusing to push ${t} '${r}': it was fetched with languageCode ${n.languageCode} but this SDK is configured with ${this.languageCode}. Pushing would rewrite labels read in one language as labels in another. Re-fetch with languageCode ${this.languageCode}, or create the SDK with languageCode ${n.languageCode}.`)}assertProjectionMatches(t,r,n){var i;if(n&&n.projectionVersion!==Gs.PROJECTION_VERSION)throw new re.SdkError("ARTIFACT_PROJECTION_STALE",`Refusing to push ${t} '${r}': its workspace copy was produced by projection version ${(i=n.projectionVersion)!==null&&i!==void 0?i:"unknown (pre-versioning)"}, but this SDK produces version ${Gs.PROJECTION_VERSION}. The parsers changed in between, so an unedited part of this artifact can no longer be told apart from an edited one and pushing could overwrite server content the caller never touched. Re-fetch it with fetchArtifact('${t}', '${r}') and re-apply any local edits.`)}async createWithMintedId(t,r,n,i){try{return await t.api.create(this.dataverse,i,n)}catch(a){throw!(a instanceof re.SdkError)||a.code!==Ir.VERSION_CONFLICT_CODE?a:new re.SdkError(Ht.ALREADY_EXISTS_CODE,`Cannot create ${r} '${n}': a record already exists at that id, so an earlier push of this artifact committed before its local version metadata was saved. No duplicate was created. Run fetchArtifact('${r}', '${n}', { overwrite: true }) to adopt the existing record's identity, etag and snapshot \u2014 the overwrite is required, because this local copy has never been pushed, so a plain fetch keeps it and adopts nothing; it REPLACES the local copy, so keep any outstanding local changes aside first \u2014 then re-apply them and push again: a conditional update, provided the adopted record is complete. If the earlier push committed only PART of a multi-row artifact (e.g. an app's appmodule without its sitemap), that update refuses, naming what is missing and how to remove the partial record. This is not done automatically because the only recovery available here would be an UNCONDITIONAL overwrite, which would destroy any edit made to the record in the meantime.`)}}async buildMetadataContext(t,r){var n,i;let a=(i=(n=t.metadataNeeds)===null||n===void 0?void 0:n.call(t,r))!==null&&i!==void 0?i:[],o=new Set(a.map(u=>u.entityLogicalName).filter(u=>!!u)),s=new Set(a.filter(u=>u.needsColumnDetail).map(u=>u.entityLogicalName)),l=new Map;for(let u of o){let c=await this.workspace.readEntityMetadata(u);if(c&&s.has(u)&&(c.columnDetailComplete!==!0||c.attributes.some(d=>typeof d.attributeTypeName!="string"))&&(c=null),!c)try{await this.fetchEntityMetadata(u),c=await this.workspace.readEntityMetadata(u)}catch{}c&&l.set(u,c)}return{resolveField:(u,c)=>{let d=l.get(u),p=d?.attributes.find(f=>f.logicalName===c);return p?{displayName:p.displayName,attributeType:p.attributeType}:void 0},resolveEntity:u=>l.get(u),loadTypeScript:()=>this.compiler.load()}}async pushAll(){let t=await this.getDirtyArtifacts();await this.warmBatchMetadata(t);let r=new Map;for(let i=0;i<t.length;i+=1){let a=t[i];try{await this.withArtifactLock(a.type,a.id,()=>this.prepareArtifactUnlocked(a.type,a.id))}catch(o){r.set(i,{type:a.type,id:a.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:po(o)})}}if(r.size>0)return t.map((i,a)=>{var o;return(o=r.get(a))!==null&&o!==void 0?o:{type:i.type,id:i.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:new re.SdkError(Ht.PUSH_NOT_ATTEMPTED_CODE,`Not attempted: ${r.size} artifact(s) in this batch could not be prepared, so no writes were issued. Fix the reported failures and push again.`)}});let n=[];for(let i of t)try{n.push(await this.pushArtifact(i.type,i.id))}catch(a){n.push({type:i.type,id:i.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:po(a)})}return n}async warmBatchMetadata(t){var r,n,i;let a=new Set;for(let o of t){let s=this.registrations.get(o.type);if(!s)continue;let l;try{l=await this.readLocal(o.type,o.id)}catch{continue}let u=l.entityLogicalName;u&&a.add(u);for(let c of(i=(n=(r=s.adapter).metadataNeeds)===null||n===void 0?void 0:n.call(r,l))!==null&&i!==void 0?i:[])c.entityLogicalName&&a.add(c.entityLogicalName)}for(let o of a)if(!await this.workspace.readEntityMetadata(o))try{await this.fetchEntityMetadata(o)}catch{}}async getDirtyArtifacts(){return(await this.withDirtyFlags(await this.workspace.listArtifacts())).filter(r=>r.isDirty)}async diffArtifact(t,r){return this.versions.diff(t,r)}assignMissingIds(t,r){let n=this.registrations.get(t);return n?n.adapter.assignMissingIds(r):(0,Kj.assignMissingIds)(r)}async resolveComponentType(t){switch(t.componentType){case gt.SolutionComponentType.SavedQuery:return"view";case gt.SolutionComponentType.SavedQueryVisualization:return"chart";case gt.SolutionComponentType.AppModule:return"app";case gt.SolutionComponentType.UxAgentProject:return"genPage";case gt.SolutionComponentType.Workflow:return t.workflowCategory===2?"businessRule":t.workflowCategory===4&&await this.isBusinessFlowWorkflow(t.objectId)?"bpf":void 0;case gt.SolutionComponentType.SystemForm:return await this.isDashboardForm(t.objectId)?"dashboard":"form";default:return}}async isDashboardForm(t){let n=`/systemforms(${(0,oi.normalizeGuid)(t,"formId")})${(0,oi.odataQuery)([["$select","type"]])}`,i=(0,Ir.ensureSuccess)(await this.dataverse.get(n),this.dataverse.apiUrl(n)),a=Number(i.body.type);return a===0||a===10}async isBusinessFlowWorkflow(t){let n=`/workflows(${(0,oi.normalizeGuid)(t,"workflowId")})${(0,oi.odataQuery)([["$select","businessprocesstype"]])}`,i=(0,Ir.ensureSuccess)(await this.dataverse.get(n),this.dataverse.apiUrl(n));return Number(i.body.businessprocesstype)===0}requireRegistration(t,r){let n=this.registrations.get(t);if(!n)throw new re.NotImplementedError(r,`no adapter registered for artifact type '${t}'`);return n}};Ht.MakerSdk=ed;function rH(e){return new ed(e)}Ht.createMakerSdk=rH;function po(e){return e instanceof Error?e:new Error(String(e))}function In(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function fR(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function mR(e){e.length===0||!e.every(t=>In(t)&&typeof t.order=="number")||e.forEach((t,r)=>{t.order=r})}function nH(e,t){if(t===void 0||t==="end")return e.length;if(t==="start")return 0;if("index"in t)return Math.max(0,Math.min(t.index,e.length));if("before"in t){let n=e.findIndex(i=>In(i)&&i.id===t.before);return n<0?e.length:n}let r=e.findIndex(n=>In(n)&&n.id===t.after);return r<0?e.length:r+1}});var vR=y(td=>{"use strict";Object.defineProperty(td,"__esModule",{value:!0});td.ARTIFACT_TYPES=void 0;td.ARTIFACT_TYPES=["form","view","businessRule","app","command","chart","dashboard","genPage","bpf"]});var bR=y(yR=>{"use strict";Object.defineProperty(yR,"__esModule",{value:!0})});var AR=y(wR=>{"use strict";Object.defineProperty(wR,"__esModule",{value:!0})});var ER=y(CR=>{"use strict";Object.defineProperty(CR,"__esModule",{value:!0})});var NR=y(SR=>{"use strict";Object.defineProperty(SR,"__esModule",{value:!0})});var IR=y(DR=>{"use strict";Object.defineProperty(DR,"__esModule",{value:!0})});var TR=y(_R=>{"use strict";Object.defineProperty(_R,"__esModule",{value:!0})});var RR=y(PR=>{"use strict";Object.defineProperty(PR,"__esModule",{value:!0})});var xR=y(OR=>{"use strict";Object.defineProperty(OR,"__esModule",{value:!0})});var FR=y(LR=>{"use strict";Object.defineProperty(LR,"__esModule",{value:!0})});var MR=y(kR=>{"use strict";Object.defineProperty(kR,"__esModule",{value:!0})});var UR=y(BR=>{"use strict";Object.defineProperty(BR,"__esModule",{value:!0})});var qR=y($R=>{"use strict";Object.defineProperty($R,"__esModule",{value:!0})});var GR=y(VR=>{"use strict";Object.defineProperty(VR,"__esModule",{value:!0})});var WR=y(zR=>{"use strict";Object.defineProperty(zR,"__esModule",{value:!0})});var HR=y(jR=>{"use strict";Object.defineProperty(jR,"__esModule",{value:!0})});var KR=y(JR=>{"use strict";Object.defineProperty(JR,"__esModule",{value:!0})});var XR=y(QR=>{"use strict";Object.defineProperty(QR,"__esModule",{value:!0})});var ZR=y(YR=>{"use strict";Object.defineProperty(YR,"__esModule",{value:!0})});var tO=y(eO=>{"use strict";Object.defineProperty(eO,"__esModule",{value:!0})});var nO=y(rO=>{"use strict";Object.defineProperty(rO,"__esModule",{value:!0})});var iO=y(oe=>{"use strict";var iH=oe&&oe.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),_e=oe&&oe.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&iH(t,e,r)};Object.defineProperty(oe,"__esModule",{value:!0});oe.createMakerSdk=void 0;var aH=gR();Object.defineProperty(oe,"createMakerSdk",{enumerable:!0,get:function(){return aH.createMakerSdk}});_e(vR(),oe);_e(bR(),oe);_e(AR(),oe);_e(ER(),oe);_e(NR(),oe);_e(IR(),oe);_e(TR(),oe);_e(RR(),oe);_e(xR(),oe);_e(FR(),oe);_e(MR(),oe);_e(UR(),oe);_e(qR(),oe);_e(GR(),oe);_e(Ul(),oe);_e(WR(),oe);_e(HR(),oe);_e(KR(),oe);_e(XR(),oe);_e(ZR(),oe);_e(tO(),oe);_e(nO(),oe);_e(ee(),oe)});var dg=y(Yr=>{"use strict";var oH=Yr&&Yr.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),sH=Yr&&Yr.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),sO=Yr&&Yr.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&oH(t,e,r);return sH(t,e),t};Object.defineProperty(Yr,"__esModule",{value:!0});Yr.NodeFileSystemStorage=void 0;var je=sO(require("fs")),vt=sO(require("path")),aO=ee(),oO=Cd();async function lO(e){let t;try{t=await je.promises.lstat(e)}catch{return}if(t.isSymbolicLink()){try{await je.promises.unlink(e)}catch{await je.promises.rmdir(e)}return}if(!t.isDirectory()){await je.promises.unlink(e);return}for(let r of await je.promises.readdir(e))await lO(vt.join(e,r));await je.promises.rmdir(e)}var cg=class{constructor(t){this.root=t}getRoot(){return this.root}pathFor(t,r=!0){return this.assertWithinRoot(vt.join(this.root,...t),r)}realPathThroughNearestAncestor(t){let r=t,n=[];for(;!je.existsSync(r);){n.unshift(vt.basename(r));let i=vt.dirname(r);if(i===r)return vt.resolve(t);r=i}return vt.resolve(je.realpathSync(r),...n)}assertWithinRoot(t,r){let n=vt.resolve(this.root),i=vt.resolve(t);if(i!==n&&!i.startsWith(n+vt.sep))throw new aO.PathTraversalError(t,this.root);let a=this.realPathThroughNearestAncestor(n),o=r?this.realPathThroughNearestAncestor(i):vt.resolve(this.realPathThroughNearestAncestor(vt.dirname(i)),vt.basename(i));if(o!==a&&!o.startsWith(a+vt.sep))throw new aO.PathTraversalError(t,this.root);return i}async readText(t){let r=this.pathFor(t);if(!je.existsSync(r))return null;try{return await(0,oO.retryTransientIoAsync)(()=>je.promises.readFile(r,"utf8"))}catch(n){if(n.code==="ENOENT")return null;throw n}}async writeTextAtomic(t,r){let n=this.pathFor(t),i=vt.dirname(n);await je.promises.mkdir(i,{recursive:!0});let a=vt.join(i,`.${vt.basename(n)}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);try{await je.promises.writeFile(a,r,"utf8"),await(0,oO.retryTransientIoAsync)(()=>je.promises.rename(a,n))}catch(o){try{je.existsSync(a)&&await je.promises.unlink(a)}catch{}throw o}}async deleteFile(t){let r=this.pathFor(t);je.existsSync(r)&&await je.promises.unlink(r)}async deleteByPrefix(t){await lO(this.pathFor(t,!1))}async ensureContainer(t){await je.promises.mkdir(this.pathFor(t),{recursive:!0})}async exists(t){return je.existsSync(this.pathFor(t))}};Yr.NodeFileSystemStorage=cg});var uO=y(Ut=>{"use strict";var lH=Ut&&Ut.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),uH=Ut&&Ut.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),cH=Ut&&Ut.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&lH(t,e,r);return uH(t,e),t};Object.defineProperty(Ut,"__esModule",{value:!0});Ut.loadNodeTypeScript=Ut.createNodeWorkspaceStorage=Ut.NodeFileSystemStorage=void 0;var dH=dg(),pH=dg();Object.defineProperty(Ut,"NodeFileSystemStorage",{enumerable:!0,get:function(){return pH.NodeFileSystemStorage}});function fH(e){return new dH.NodeFileSystemStorage(e)}Ut.createNodeWorkspaceStorage=fH;async function mH(){return await Promise.resolve().then(()=>cH(require("typescript")))}Ut.loadNodeTypeScript=mH});var _n={};module.exports=_r(_n);Pn(_n,se(iO()),module.exports);Pn(_n,se(uO()),module.exports);diff --git a/plugins/model-apps/scripts/verify-model-app.js b/plugins/model-apps/scripts/verify-model-app.jsindex 9f4ca7044..b5f03cb7a 100644--- a/plugins/model-apps/scripts/verify-model-app.js+++ b/plugins/model-apps/scripts/verify-model-app.js@@ -244,9 +244,9 @@ function readerFor(sdk, appUnique, opts) {// feature and reports the read failure as a not-present check, which is the fail-closed direction —// a verify that cannot prove a feature is in effect must not claim it is.retrieveSetting: async (name, opts) => sdk.retrieveSetting(name, opts || {}),- // formDefaultState(entity, formId): the selected Main form's actual default flag. The identity- // check in verify-spec proves the form row exists; this separate read proves the platform state- // that chooses which form opens by default. Errors propagate to verify-spec as a fail-closed+ // formDefaultState(entity, formId): a Main form's actual default flag. The identity+ // check in verify-spec proves the form row exists; this separate read proves both the selected+ // default and any spec-declared sibling that must no longer hold the default slot. Errors propagate as a fail-closed// finding, because a missing proof is not evidence that promotion succeeded.// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/systemformformDefaultState: async (_entity, formId) => {diff --git a/plugins/model-apps/skills/app-builder/SKILL.md b/plugins/model-apps/skills/app-builder/SKILL.mdindex 06fb39730..54cc4a762 100644--- a/plugins/model-apps/skills/app-builder/SKILL.md+++ b/plugins/model-apps/skills/app-builder/SKILL.md@@ -73,9 +73,9 @@ prod-ready** app; don't under-build (a bare table list) or over-build (surfacesthe platform rejects one without, so use a Boolean flag for a manual check-off). Reach for one whenthe user describes work moving through **phases** — "triage →investigate → resolve", "lead → qualify → close". Author it `Active` (the default) or the stage bar- does not appear at all. v1 is single-entity and linear: cross-entity stages, branching, stage- actions and security-role grants are **rejected** by the spec gate, so offer Maker for those rather- than writing them into the spec.+ does not appear at all. Who may run a flow is `securityRoles: { "personas": [...] }` (Active flows+ only). v1 is single-entity and linear: cross-entity stages, branching and stage actions are+ **rejected** by the spec gate, so offer Maker for those rather than writing them into the spec.- **Surfaces** — **generative pages** (modern dashboards / overviews / analytics / landing — the default),classic dashboards (opt-in), external URLs- **App shell** — the app module + sitemap, with per-subarea icons. Turn on the **modern shell** with@@ -459,7 +459,13 @@ node "${PLUGIN_ROOT}/scripts/teardown-model-app.js" \- **`--allow-destructive`** — authorize destructive operations. For `build --apply`: authorizesoverwriting an existing app in unattended mode, and allows explicit-layout form-field removals orsitemap-target drops; also authorizes DETACHING a `pages-removed` page's nav subarea (the page- record is left deployed — it is not deleted). For `teardown --apply`: **required** — all deletes+ record is left deployed — it is not deleted). For form and sitemap removals, the authority covers+ the removals the last refusal or approved run recorded; if live state would lose anything more,+ the apply halts, lists only the newly destructive removals, and records that new list for review.+ A field or sitemap target that appears during a run is kept or halted before push, never removed+ unseen. The record is consumed only after a full successful build that ran the removal phases and+ kept nothing; it is kept on failures, partial runs, changed-only runs, unreadable records, and+ failed discovery. For `teardown --apply`: **required** — all deletesare destructive by construction, so teardown without this flag halts before touching anything.- **Pages-phase safety HALTs.** The build halts on identity or safety violations rather thanproceeding with potentially wrong state. Surface the HALT reason and follow the recovery hint:@@ -609,22 +615,26 @@ child view id. Each step emits `[n/total]`.re-syncing an existing app's sitemap, and finalizing the sitemap after generative pages each publishthat one artifact (an unpublished edit to a live artifact is invisible). A fresh build without`--publish` still leaves new tables/columns/relationships staged-but-unpublished in the solution.-- **Idempotent — but ADDITIVE, not yet full desired-state convergence.** Existing+- **Idempotent — but not full desired-state convergence.** Existingsolution/tables/columns/relationships/views/charts/forms/commands/dashboards are detected and**reused**, so re-runs and existing-table envs work without collisions. **The caveat for EDITS:** a- rebuild is *additive* — it creates what's missing but does **not** re-apply changes to an artifact- that already exists (a changed column type, a removed view column — `reconcileView` only *adds* —- an edited form/command/dashboard), and never removes an artifact you dropped from the spec. **To- apply a structural edit, `teardown --apply` then rebuild fresh.** `--verify` catches this: it- checks **content** (a view's column set, relationship + command existence), so an unapplied edit- surfaces as a loud `verify FAIL`, not a false pass. Full in-place convergence is tracked in- `docs/app-builder-capabilities.md`.+ rebuild never removes an artifact you dropped from the spec, and re-applies only part of an edit to+ one that already exists. A **form** converges its fields (added; for an explicit layout, dropped ones+ pruned — see `prune: false` below), column counts and spans. A **view** only *adds* columns: a+ column removed from the spec, or a new column order, does **not** apply, and neither do its filters+ or sort. A changed column type, and an edited command or dashboard, are not re-applied at all; an+ existing chart takes only a changed description.+ **To apply one of those edits, change it in Maker, or `teardown --apply` then rebuild fresh.**+ `--verify` catches what is **missing** — a spec view column, filter condition or sort key (authored+ sort keys must also keep their order), a relationship, command or dashboard — as a loud+ `verify FAIL`. It tolerates **extra** deployed content, so a view column, filter or sort key you+ removed from the spec still passes, just as one a maker added by hand does.- Not in scope (later): **conditional** command visibility (Power-Fx-only), **titledcommand groups** (from-scratch — needs an SDK-synthesized parent row), lookup/associated views,multi-area sitemaps, **column-level (field) security**, and **access teams / hierarchy security**(both tracked SDK follow-ups). The security surface today is role-per-persona plus per-form roleassignment, and both of those ship. Also out of scope: the BPF knobs the spec gate rejects- (cross-entity stages, branching, stage actions, security-role grants).+ (cross-entity stages, branching, stage actions).- **Environment-gated (may not work where you are running):**- **Business rules** (`businessRules[]`). The SDK writes a rule through the bound`CreateProcessWithWfomJson` member — the same one the modern business-rule designer uses — anddiff --git a/plugins/model-apps/skills/genpage/SKILL.md b/plugins/model-apps/skills/genpage/SKILL.mdindex 866696ac7..04569d885 100644--- a/plugins/model-apps/skills/genpage/SKILL.md+++ b/plugins/model-apps/skills/genpage/SKILL.md@@ -41,7 +41,7 @@ This skill orchestrates specialist agents across the create and edit flows:5. **`genpage-connector-builder`** — top-level orchestrator dispatch when an edit adds,replaces, discovers, removes, or clears connector bindings; preserves unchanged bindings- when the edit does not touch them, or when the `connectors` rollback gate is off.+ when the edit does not touch them.**`genpage-customapi-builder`** — the same top-level dispatch when an edit adds, replaces,discovers, removes, or clears Custom API bindings.6. **`genpage-edit-planner`** — reads the downloaded page artifacts, gathers change@@ -310,8 +310,8 @@ missing and stop, so the run can be re-driven with the decision supplied.#### 1a. Connector discovery is orchestrator-owned and never speculative`genpage-connector-builder` is dispatched only by this top-level orchestrator,-not by `genpage-planner`. This keeps connector discovery and its rollback gate in one-agent while avoiding nested `Task` calls from the planner.+not by `genpage-planner`. This keeps connector discovery in one agent while avoiding+nested `Task` calls from the planner.**Never run discovery before the planner returns** — not even when `$ARGUMENTS`obviously mentions SharePoint, Teams, Office 365 or a custom REST source.@@ -334,10 +334,9 @@ So the sequence is always: plan first, then discover, then re-plan.`<working-dir>/connector-bindings.md` and verify `<working-dir>/connectors.json`is a bare JSON array, then re-run the planner with the refreshed contract.-The builder remains the single owner of connector discovery and of the `connectors`-rollback gate: it probes first, writes `No connector bindings.` + `[]` when the gate-is off or the page needs no connector, and performs all connection discovery only-when one is required.+The builder remains the single owner of connector discovery: it writes+`No connector bindings.` + `[]` when the page needs no connector, and performs all+connection discovery only when one is required.#### 1b. Custom API discovery is orchestrator-owned too@@ -467,7 +466,7 @@ It returns a single JSON object:```json{"ok": true | false,- "blocker": null | "az_missing" | "az_not_logged_in" | "pac_not_logged_in"+ "blocker": null | "usage" | "az_missing" | "az_not_logged_in" | "pac_not_logged_in"| "no_env_url" | "whoami_403" | "whoami_401" | "whoami_error","message": "human-readable next step","warnings": ["..."],@@ -485,6 +484,8 @@ It returns a single JSON object:- **`ok: false`** → show the `message` field to the user verbatim and**stop the workflow**. The script already includes a fix-it command for everyblocker (run `az login`, etc.).+- **`blocker: "usage"`** is the one exception: the `check-auth.js` command line itself was wrong (a+ mistyped flag or a missing value). Fix the invocation and run it again instead of stopping.Capture `envUrl` from the result — Phase 2b passes it to the entity-builder.@@ -563,32 +564,19 @@ After generating, read the RuntimeTypes.ts file to verify it generated correctly### Phase 4.5: Connector Bindings (Conditional)-**Re-probe the rollback gate here — do not rely on the plan content alone.** Connectors-are GA and the flag ships ON, so this normally passes; it exists so a plan authored-while the feature was on cannot deploy connectors after it has been turned off:--```powershell-node "${PLUGIN_ROOT}/scripts/lib/feature-flags.js" connectors-```--**If it prints `disabled`:** the outcome is `Connectors: none` **regardless of what the-plan's `## Connector Bindings` section says**. Skip the rest of this phase — do not-create or pass `connectors.json`, and do not add `--connectors` on upload. (Backstop:-`list-connections.js` / `create-connection-reference.js` also fail closed with exit 3.)--**If it prints `enabled`:** read the plan's `## Connector Bindings` section and treat it-as bindings **only when it contains an actual binding table** (a `| Logical Name | …`-header with at least one data row). If the section is `No connector bindings.`, empty,-missing, or malformed, the page has no connectors: skip this phase entirely — do not-create or pass `connectors.json`, and do not add `--connectors` on upload.+Read the plan's `## Connector Bindings` section and treat it as bindings **only when+it contains an actual binding table** (a `| Logical Name | …` header with at least+one data row). If the section is `No connector bindings.`, empty, missing, or+malformed, the page has no connectors: skip this phase entirely — do not create or+pass `connectors.json`, and do not add `--connectors` on upload.**Carry this decision into code generation.** The outcome is `Connectors: <n>binding(s)` or `Connectors: none` for the rest of the run, and Phase 5 **must** passit verbatim in every page-builder dispatch — otherwise the generated page could calla connector this run never binds, and the page fails at runtime instead of simply-omitting the feature. Note the dispatch value is the **binding count**, not the flag-state: a disabled gate and an empty binding table both produce `none`, because the-page-builder only ever needs to know how many bindings it may call.+omitting the feature. The dispatch value is the **binding count**, not a flag state:+an empty binding table produces `none`, because the page-builder only ever needs to+know how many bindings it may call.When there are real bindings, the `genpage-connector-builder` agent already wrote`<working-dir>/connectors.json` during planning — verify it exists and matches the@@ -712,11 +700,10 @@ subagent. Inline the page-builder workflow directly in the orchestrator:1. Read `${PLUGIN_ROOT}/references/rules.md`2. Read the sample listed in the plan's `## Relevant Samples`-3. Only when the Phase 4.5 probe printed `enabled` **and** the plan's- `## Connector Bindings` section contains an **actual binding table** (a- `| Logical Name | …` header with at least one data row), also read- `${PLUGIN_ROOT}/references/connectors.md`. Treat a `No connector bindings.`- sentinel, an empty/missing/malformed section, **or a `disabled` probe** as+3. Only when the plan's `## Connector Bindings` section contains an **actual+ binding table** (a `| Logical Name | …` header with at least one data row),+ also read `${PLUGIN_ROOT}/references/connectors.md`. Treat a+ `No connector bindings.` sentinel or an empty/missing/malformed section ashaving no connectors (same contract as Phase 4.5 and genpage-page-builder).3b. Only when the Phase 4.6 probe printed `enabled` **and** the plan's`## Custom API Bindings` section contains an **actual binding table** (a@@ -789,7 +776,7 @@ For each page, pass a prompt that includes:- Target file name (e.g., "candidate-tracker.tsx")- Absolute path to `genpage-plan.md`- Data mode (see below) — either a RuntimeTypes path or an explicit mock flag-- **Connectors: `none` or `<n> binding(s)`** — the Phase 4.5 outcome, verbatim+- **Connectors: `none` or `<n> binding(s)`** — the Phase 4.5 binding-count outcome, verbatim- **Telemetry: `enabled` or `disabled`** — the Phase 4.7 probe result, verbatim- Working directory- Plugin root: `${PLUGIN_ROOT}`@@ -916,7 +903,9 @@ foreach ($f in 'prompt.txt', 'agent-message.txt', 'page-name.txt') {Then write, with the file tool, `<working-dir>/prompt.txt` holding the prompt, `<working-dir>/agent-message.txt` theagent message and, on a create, `<working-dir>/page-name.txt` the page's display name — each exactly its text (atrailing line break on the name is ignored). `genpage-upload.js` refuses any of them that is a link, a hard link or a-folder, but only after the write.+folder, but only after the write. The name is the one value passed to pac inline: where pac is installed as a+`pac.cmd` shim (Windows), a name containing a double quote or `%` is refused before anything is uploaded, so pick+one without them.**Log the invocation into `workflow-log.md` under a `## Phase 6 — Deploy` section before running it.** Record the flags and the prompt-file path, plus the prompt's scope, so the approved text is preserved semantically without embedding arbitrary text as an executable command. Format:diff --git a/plugins/model-apps/skills/genpage/edit-flow.md b/plugins/model-apps/skills/genpage/edit-flow.mdindex 6a17950f5..32f224ca0 100644--- a/plugins/model-apps/skills/genpage/edit-flow.md+++ b/plugins/model-apps/skills/genpage/edit-flow.md@@ -132,8 +132,7 @@ Also read `config.json.connectorBindings` and `config.json.actionBindings`.> - **Add / replace / discover connector data:** invoke `genpage-connector-builder`> via `Task` with **Mode: `edit`**, the working directory, `${PLUGIN_ROOT}`, the> `envUrl` from Edit Phase 1, the existing bindings, and the edit intent. The-> builder owns the rollback gate: when connectors are off it preserves existing-> bindings and adds none; otherwise it discovers and returns the updated set. It+> builder discovers and returns the updated set. It> writes `<working-dir>/connectors.json` (bare array) and> `<working-dir>/connector-bindings.md`.> - **Remove one (or some) connectors:** invoke `genpage-connector-builder` the@@ -351,7 +350,7 @@ It is written to a file and passed as `--prompt-file`; see SKILL.md Phase 6Connector binding rules for edit deploy:- **Add / replace / discover / remove one connector:** the `genpage-connector-builder`- agent (Mode: `edit`) has already gated on the flag and written the full desired+ agent (Mode: `edit`) has already written the full desiredbinding set to `<working-dir>/connectors.json` (a removal writes the remainingbindings). Pre-flight that `pac model genpage upload --help` contains `--connectors`and include `--connectors '<working-dir>/connectors.json'` in the upload — this is a@@ -403,6 +402,13 @@ Omit `--data-sources` when `config.json.dataSources` was empty.Omit `--connectors` when connector bindings are unchanged.Omit `--actions` when Custom API bindings are unchanged.+An update without `--name`/`--name-file` gives the page its **sitemap title** as its name (measured:+a page renamed with `--name-file` reverted to the title on the next update that omitted it). An edit+that does not rename the page can omit it. To rename a page, pass `--name-file` on this update, and+tell the user its navigation title is the app's sitemap entry and is not changed by the upload. Where+pac is installed as a `pac.cmd` shim (Windows), a name containing a double quote or `%` is refused+before anything is uploaded.+## Edit Phase 7: Verify (Optional)Offer browser verification via `AskUserQuestion` (same flow as Phase 7 in the create flow — see SKILL.md).diff --git a/plugins/model-apps/skills/telemetry/telemetry-workflow.md b/plugins/model-apps/skills/telemetry/telemetry-workflow.mdindex ecb094f48..1f4ad00c1 100644--- a/plugins/model-apps/skills/telemetry/telemetry-workflow.md+++ b/plugins/model-apps/skills/telemetry/telemetry-workflow.md@@ -24,7 +24,10 @@ telemetry for this plugin. Default to `status` when no argument is given.and correlation IDs, and Dataverse organization and Entra tenant GUIDs when PACis signed in.Power Pages can also include the signed-in user's Entra object ID as- `eventInfo.aadObjectId` when PAC exposes it; Model Apps excludes it.+ `eventInfo.aadObjectId` when PAC exposes it, and the SPA framework of the+ Power Pages code site being worked in (`react`, `vue`, `angular`, or `astro`)+ as `eventInfo.framework`. The framework name describes the scaffold only —+ it is never a site name or path. Model Apps excludes both.When plugin telemetry is enabled, the local diagnostic mirror retains the sameevent fields even when transmission is off.A plugin whose committed telemetry config has `disabled: true` writes no mirror.diff --git a/plugins/power-pages/scripts/lib/telemetry/lib/agent-info.js b/plugins/power-pages/scripts/lib/telemetry/lib/agent-info.jsindex 3904f5bc1..aa6ec840b 100644--- a/plugins/power-pages/scripts/lib/telemetry/lib/agent-info.js+++ b/plugins/power-pages/scripts/lib/telemetry/lib/agent-info.js@@ -2,11 +2,12 @@const fs = require("node:fs");const path = require("node:path");-const { execFileSync } = require("node:child_process");+const { runNative } = require("./native-exec");let pacCliVersionCache;-// Reads the PAC CLI version once per process via `pac --version`. Best-effort+// Reads the PAC CLI version once per process via `pac --version`, started by+// absolute path from PATH (see native-exec.js). Best-effort// and fail-closed: missing executable, timeout, or unparseable output all// resolve to "".//@@ -20,7 +21,7 @@ function readPacCliVersion(opts = {}) {pacCliVersionCache = "";return "";}- const exec = typeof opts._exec === "function" ? opts._exec : execFileSync;+ const exec = typeof opts._exec === "function" ? opts._exec : runNative;let stdout = "";try {stdout = exec("pac", ["--version"], {diff --git a/plugins/power-pages/scripts/lib/telemetry/lib/native-exec.js b/plugins/power-pages/scripts/lib/telemetry/lib/native-exec.jsnew file mode 100644index 000000000..0b11f96e6--- /dev/null+++ b/plugins/power-pages/scripts/lib/telemetry/lib/native-exec.js@@ -0,0 +1,100 @@+"use strict";++const fs = require("node:fs");+const path = require("node:path");+const { execFileSync } = require("node:child_process");++// Starts a native command-line tool (pac) by absolute path, never by bare name.+//+// The telemetry hooks run in the user's project folder. Given a bare name,+// Node 20 on Windows looks for the executable in the working directory before+// PATH (measured: a `pac.exe` in the working directory ran; Node 22 no longer+// looks there), so a `pac.exe` left in a project would run instead of the real+// one. Resolving the name here, against absolute PATH entries only, gives the+// same answer on every Node version and platform.+//+// Only native executables are considered. These calls run without a shell, and+// Windows cannot start a .cmd or .bat that way, so a pac.cmd install is not+// found, as it was not before either.++function isFile(p) {+ try {+ return fs.statSync(p).isFile();+ } catch {+ return false;+ }+}++// A candidate the OS would actually start: a regular file and, off Windows,+// one the user may execute. Node's own lookup skips a non-executable `pac`+// earlier on PATH and keeps searching, so this does too.+function isRunnable(p, platform) {+ if (!isFile(p)) return false;+ if (platform === "win32") return true;+ try {+ fs.accessSync(p, fs.constants.X_OK);+ return true;+ } catch {+ return false;+ }+}++// Windows variable names are case-insensitive. When an env object carries+// several spellings (a copied `Path` plus an added `PATH`), Node passes the+// child the lexicographically first one, so read that same one.+function envValue(env, name, platform) {+ if (platform !== "win32") return env[name];+ const key = Object.keys(env)+ .filter((k) => k.toUpperCase() === name.toUpperCase())+ .sort()[0];+ return key === undefined ? undefined : env[key];+}++/**+ * Absolute path of a native executable found on PATH, or null. Relative PATH+ * entries (an empty entry means "the current directory" on POSIX) are skipped.+ * On Windows `.com` then `.exe` is tried whatever PATHEXT says, as Node's own+ * shell-free lookup does.+ */+function resolveNative(+ name,+ { platform = process.platform, env = process.env, exists = (p) => isRunnable(p, platform) } = {}+) {+ const win = platform === "win32";+ const p = win ? path.win32 : path.posix;+ const dirs = String(envValue(env, "PATH", platform) || "")+ .split(win ? ";" : ":")+ .map((d) => d.trim().replace(/^"(.*)"$/, "$1"))+ .filter((d) => d && p.isAbsolute(d));+ const exts = win ? [".com", ".exe"] : [""];+ for (const dir of dirs) {+ for (const ext of exts) {+ const candidate = p.join(dir, name + ext);+ if (exists(candidate)) return candidate;+ }+ }+ return null;+}++/**+ * execFileSync-shaped: returns stdout, and throws when the tool is not on PATH+ * (code ENOENT) or the run fails (with err.stdout attached, as execFileSync+ * does). Callers treat any throw as "no data".+ */+function runNative(name, args, options = {}, deps = {}) {+ const file = resolveNative(name, deps);+ if (!file) {+ const err = new Error(`${name} was not found on PATH`);+ err.code = "ENOENT";+ throw err;+ }+ return execFileSync(file, args, {+ encoding: options.encoding,+ timeout: options.timeout,+ stdio: options.stdio,+ windowsHide: true,+ shell: false,+ });+}++module.exports = { resolveNative, runNative };diff --git a/plugins/power-pages/scripts/lib/telemetry/lib/pac-auth.js b/plugins/power-pages/scripts/lib/telemetry/lib/pac-auth.jsindex 71b268b59..0eb4ec6a3 100644--- a/plugins/power-pages/scripts/lib/telemetry/lib/pac-auth.js+++ b/plugins/power-pages/scripts/lib/telemetry/lib/pac-auth.js@@ -1,11 +1,13 @@"use strict";-const { execFileSync } = require("node:child_process");+const { runNative } = require("./native-exec");-// Reads PAC CLI auth state by shelling out to `pac auth who` and parsing the+// Reads PAC CLI auth state by running `pac auth who` and parsing the// banner output. Matches the convention used by// plugins/power-pages/scripts/lib/validation-helpers.js (getPacAuthInfo /// getEnvironmentUrl) so telemetry stays consistent with the rest of the repo.+// pac is started by absolute path from PATH, never by bare name (see+// native-exec.js).//// PAC's JSON profile files are an internal/undocumented format that varies// across versions. The banner output is stable and is what other code paths@@ -40,7 +42,7 @@ function readPacAuth(opts = {}) {cache = null;return null;}- const exec = typeof opts._exec === "function" ? opts._exec : execFileSync;+ const exec = typeof opts._exec === "function" ? opts._exec : runNative;let output;try {output = exec("pac", ["auth", "who"], {diff --git a/plugins/power-pages/skills/telemetry/telemetry-workflow.md b/plugins/power-pages/skills/telemetry/telemetry-workflow.mdindex 74416e61c..6683c182a 100644--- a/plugins/power-pages/skills/telemetry/telemetry-workflow.md+++ b/plugins/power-pages/skills/telemetry/telemetry-workflow.md@@ -27,7 +27,7 @@ telemetry for this plugin. Default to `status` when no argument is given.`eventInfo.aadObjectId` when PAC exposes it, and the SPA framework of thePower Pages code site being worked in (`react`, `vue`, `angular`, or `astro`)as `eventInfo.framework`. The framework name describes the scaffold only —- it is never a site name or path.+ it is never a site name or path. Model Apps excludes both.When plugin telemetry is enabled, the local diagnostic mirror retains the sameevent fields even when transmission is off.A plugin whose committed telemetry config has `disabled: true` writes no mirror.diff --git a/scripts/tests/validate-secure-process-execution.test.js b/scripts/tests/validate-secure-process-execution.test.jsindex 9975977b4..6084bbbf3 100644--- a/scripts/tests/validate-secure-process-execution.test.js+++ b/scripts/tests/validate-secure-process-execution.test.js@@ -99,6 +99,10 @@ test('production path rules are explicit and exclude tests, fixtures, generated,'plugins/power-pages/skills/example/scripts/validate-example.js','plugins/power-pages/skills/example/scripts/validate-example.mjs','plugins/power-pages/scripts/tool.cjs',+ 'plugins/model-apps/hooks/hook.js',+ 'plugins/model-apps/scripts/tool.js',+ 'plugins/model-apps/scripts/lib/process-runner.js',+ 'plugins/model-apps/scripts/_vendor-build/build.js',];const rejected = ['plugins/power-pages/scripts/tests/tool.test.js',@@ -108,6 +112,9 @@ test('production path rules are explicit and exclude tests, fixtures, generated,'plugins/power-pages/skills/example/assets/tool.js','plugins/power-pages/skills/example/references/tool.js','plugins/power-pages/scripts/tool.json',+ 'plugins/model-apps/scripts/tests/tool.test.js',+ 'plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs',+ 'plugins/model-apps/skills/example/scripts/tool.js',];for (const filePath of accepted) assert.equal(shouldScan(filePath), true, filePath);@@ -166,6 +173,24 @@ test('audited exceptions require exact path, rule, callee, and call and fail onassert.deepEqual(drifted.audited, []);});+// Why model-apps is in scope: its Windows CLI calls once ran through `shell: true`, which joins the+// arguments unquoted for cmd.exe. The scan must keep that from coming back in any form.+test('model-apps production code cannot start a shell or a cmd.exe line of its own', () => {+ const filePath = 'plugins/model-apps/scripts/lib/example.js';+ const shellTrue = [+ "const { execFileSync } = require('node:child_process');",+ "execFileSync('az', ['account', 'get-access-token', '--resource', envUrl], { shell: process.platform === 'win32' });",+ '',+ ].join('\n');+ assert.deepEqual(analyzeSource(shellTrue, filePath).map((f) => f.rule), ['ambiguous-shell-option']);+ const execString = [+ "const { execSync } = require('child_process');",+ 'execSync(`az account get-access-token --resource ${envUrl}`);',+ '',+ ].join('\n');+ assert.deepEqual(analyzeSource(execString, filePath).map((f) => f.rule), ['dynamic-shell-command']);+ assert.equal(shouldScan(filePath), true);+});test('audited exception schema requires a review reason', () => {assert.throws(() => validateExceptions([{@@ -179,11 +204,20 @@ test('audited exception schema requires a review reason', () => {);});-test('repository-wide audit is clean with no audited exceptions', () => {+test('repository-wide audit is clean, and the only audited exceptions are the process runner and the telemetry library', () => {const result = auditRepository(REPOSITORY_ROOT);assert.deepEqual(result.findings, []);- assert.deepEqual(AUDITED_EXCEPTIONS, []);- assert.deepEqual(result.audited, []);+ const runner = AUDITED_EXCEPTIONS.filter((e) => e.path === 'plugins/model-apps/scripts/lib/process-runner.js');+ assert.equal(runner.length, 8, 'the runner: four child_process calls, two rules each');+ const telemetry = AUDITED_EXCEPTIONS.filter((e) => /\/scripts\/lib\/telemetry\/lib\/native-exec\.js$/.test(e.path));+ assert.deepEqual(telemetry.map((e) => e.path).sort(), [+ 'plugins/model-apps/scripts/lib/telemetry/lib/native-exec.js',+ 'plugins/power-pages/scripts/lib/telemetry/lib/native-exec.js',+ ], 'the shared telemetry library: its one resolved-path call, in each scanned copy');+ assert.ok(telemetry.every((e) => e.rule === 'nonconstant-executable'), 'the telemetry call keeps shell:false provable');+ assert.equal(AUDITED_EXCEPTIONS.length, runner.length + telemetry.length, 'nothing else is excepted');+ assert.deepEqual(result.audited, AUDITED_EXCEPTIONS);+ assert.ok(result.files.includes('plugins/model-apps/scripts/lib/dataverse-auth.js'), 'model-apps scripts are in scope');assert.ok(result.files.length > 100, 'expected a repository-wide production scan');});@@ -193,6 +227,7 @@ test('CLI audit emits actionable diagnostics and succeeds for the repository', (});assert.equal(result.status, 0, result.stderr);- assert.doesNotMatch(result.stdout, /^AUDITED /m);- assert.match(result.stdout, /validation passed \(\d+ production files, 0 audited exceptions\)/);+ assert.equal((result.stdout.match(/^AUDITED plugins\/model-apps\/scripts\/lib\/process-runner\.js /gm) || []).length, 8);+ assert.equal((result.stdout.match(/^AUDITED plugins\/[a-z-]+\/scripts\/lib\/telemetry\/lib\/native-exec\.js /gm) || []).length, 2);+ assert.match(result.stdout, /validation passed \(\d+ production files, 10 audited exceptions\)/);});diff --git a/scripts/validate-secure-process-execution.js b/scripts/validate-secure-process-execution.jsindex 8f3d023b9..232b4722f 100644--- a/scripts/validate-secure-process-execution.js+++ b/scripts/validate-secure-process-execution.js@@ -3,7 +3,7 @@'use strict';/**- * Deterministic child_process policy for production Power Pages JavaScript.+ * Deterministic child_process policy for production Power Pages and Model Apps JavaScript.** This repository intentionally has no root npm dependency graph, so CI cannot* assume an installed parser. The analyzer below uses a conservative JavaScript@@ -31,6 +31,7 @@ const path = require('path');const REPOSITORY_ROOT = path.resolve(__dirname, '..');const POWER_PAGES_ROOT = 'plugins/power-pages';+const MODEL_APPS_ROOT = 'plugins/model-apps';const CHILD_PROCESS_MODULES = new Set(['child_process', 'node:child_process']);const PROCESS_METHODS = new Set(['exec',@@ -51,6 +52,8 @@ const SCAN_ROOTS = Object.freeze([`${POWER_PAGES_ROOT}/hooks`,`${POWER_PAGES_ROOT}/scripts`,`${POWER_PAGES_ROOT}/skills`,+ `${MODEL_APPS_ROOT}/hooks`,+ `${MODEL_APPS_ROOT}/scripts`,]);const EXCLUDED_DIRECTORY_NAMES = new Set(['test',@@ -63,9 +66,48 @@ const EXCLUDED_DIRECTORY_NAMES = new Set(['node_modules',]);-// Exceptions must remain rare, exact, and removable. The current production-// tree needs none; drift behavior stays covered by synthetic tests below.-const AUDITED_EXCEPTIONS = Object.freeze([]);+// Exceptions must remain rare, exact, and removable. Drift behavior stays covered+// by synthetic tests.+//+// model-apps' own scripts start every external CLI through one module,+// scripts/lib/process-runner.js, which resolves the executable to an absolute path at+// run time and merges the caller's options under its own shell:false (and, for a+// Windows batch shim, a checked cmd.exe command line). Neither can be proven+// statically, so its four child_process calls are audited exceptions: each one.+//+// The shared telemetry library (shared/telemetry/lib, copied into each adopting+// plugin as scripts/lib/telemetry/lib) cannot use one plugin's runner. It starts pac+// through its own native-exec.js, which resolves the name to an absolute native+// executable on PATH, never the working directory, and runs it with shell:false. That+// resolved path is its one non-literal executable, audited once per scanned copy.+const RUNNER_PATH = `${MODEL_APPS_ROOT}/scripts/lib/process-runner.js`;+const RUNNER_REASON = 'model-apps process runner: absolute executable resolved at run time; '+ + 'options merged under shell:false, batch-shim arguments checked before spawning.';+const TELEMETRY_EXEC_CALL = 'execFileSync ( file , args , { encoding : options . encoding , '+ + 'timeout : options . timeout , stdio : options . stdio , windowsHide : true , shell : false , } )';+const TELEMETRY_EXEC_REASON = 'shared telemetry library: pac resolved to an absolute native '+ + 'executable on PATH, run with shell:false.';+const AUDITED_EXCEPTIONS = Object.freeze([+ ...[+ ['execFileSync', 'childProcess . execFileSync ( inv . file , inv . args , withOptions ( inv , options ) )'],+ ['spawnSync', 'childProcess . spawnSync ( inv . file , inv . args , withOptions ( inv , options ) )'],+ ['execFile', 'childProcess . execFile ( inv . file , inv . args , withOptions ( inv , options ) , callback )'],+ ['spawn', 'childProcess . spawn ( inv . file , inv . args , withOptions ( inv , options ) )'],+ ].flatMap(([callee, call]) => ['nonconstant-executable', 'ambiguous-shell-option'].map((rule) => Object.freeze({+ path: RUNNER_PATH,+ rule,+ callee,+ call,+ reason: RUNNER_REASON,+ }))),+ ...[POWER_PAGES_ROOT, MODEL_APPS_ROOT].map((root) => Object.freeze({+ path: `${root}/scripts/lib/telemetry/lib/native-exec.js`,+ rule: 'nonconstant-executable',+ callee: 'execFileSync',+ call: TELEMETRY_EXEC_CALL,+ reason: TELEMETRY_EXEC_REASON,+ })),+]);function decodeStringLiteral(raw) {if (typeof raw !== 'string' || raw.length < 2) return null;@@ -1028,6 +1070,8 @@ function shouldScan(relativePath) {if (segments.some((segment) => EXCLUDED_DIRECTORY_NAMES.has(segment))) return false;if (normalized.startsWith(`${POWER_PAGES_ROOT}/hooks/`)) return true;if (normalized.startsWith(`${POWER_PAGES_ROOT}/scripts/`)) return true;+ if (normalized.startsWith(`${MODEL_APPS_ROOT}/hooks/`)) return true;+ if (normalized.startsWith(`${MODEL_APPS_ROOT}/scripts/`)) return true;return normalized.startsWith(`${POWER_PAGES_ROOT}/skills/`) &&normalized.includes('/scripts/');}@@ -1144,7 +1188,7 @@ function runCli(argv = process.argv.slice(2)) {if (options.help) {process.stdout.write('Usage: node scripts/validate-secure-process-execution.js [--root <repository>]\n' +- 'Audits production Power Pages hooks, shared scripts, and skill scripts.\n'+ 'Audits production Power Pages hooks, shared scripts, and skill scripts, and Model Apps hooks and scripts.\n');return 0;}diff --git a/shared/skills/telemetry/telemetry-workflow.md b/shared/skills/telemetry/telemetry-workflow.mdindex 7183c52e2..6683c182a 100644--- a/shared/skills/telemetry/telemetry-workflow.md+++ b/shared/skills/telemetry/telemetry-workflow.md@@ -24,7 +24,10 @@ telemetry for this plugin. Default to `status` when no argument is given.and correlation IDs, and Dataverse organization and Entra tenant GUIDs when PACis signed in.Power Pages can also include the signed-in user's Entra object ID as- `eventInfo.aadObjectId` when PAC exposes it; Model Apps excludes it.+ `eventInfo.aadObjectId` when PAC exposes it, and the SPA framework of the+ Power Pages code site being worked in (`react`, `vue`, `angular`, or `astro`)+ as `eventInfo.framework`. The framework name describes the scaffold only —+ it is never a site name or path. Model Apps excludes both.When plugin telemetry is enabled, the local diagnostic mirror retains the sameevent fields even when transmission is off.A plugin whose committed telemetry config has `disabled: true` writes no mirror.diff --git a/shared/telemetry/lib/agent-info.js b/shared/telemetry/lib/agent-info.jsindex 3904f5bc1..aa6ec840b 100644--- a/shared/telemetry/lib/agent-info.js+++ b/shared/telemetry/lib/agent-info.js@@ -2,11 +2,12 @@const fs = require("node:fs");const path = require("node:path");-const { execFileSync } = require("node:child_process");+const { runNative } = require("./native-exec");let pacCliVersionCache;-// Reads the PAC CLI version once per process via `pac --version`. Best-effort+// Reads the PAC CLI version once per process via `pac --version`, started by+// absolute path from PATH (see native-exec.js). Best-effort// and fail-closed: missing executable, timeout, or unparseable output all// resolve to "".//@@ -20,7 +21,7 @@ function readPacCliVersion(opts = {}) {pacCliVersionCache = "";return "";}- const exec = typeof opts._exec === "function" ? opts._exec : execFileSync;+ const exec = typeof opts._exec === "function" ? opts._exec : runNative;let stdout = "";try {stdout = exec("pac", ["--version"], {diff --git a/shared/telemetry/lib/native-exec.js b/shared/telemetry/lib/native-exec.jsnew file mode 100644index 000000000..0b11f96e6--- /dev/null+++ b/shared/telemetry/lib/native-exec.js@@ -0,0 +1,100 @@+"use strict";++const fs = require("node:fs");+const path = require("node:path");+const { execFileSync } = require("node:child_process");++// Starts a native command-line tool (pac) by absolute path, never by bare name.+//+// The telemetry hooks run in the user's project folder. Given a bare name,+// Node 20 on Windows looks for the executable in the working directory before+// PATH (measured: a `pac.exe` in the working directory ran; Node 22 no longer+// looks there), so a `pac.exe` left in a project would run instead of the real+// one. Resolving the name here, against absolute PATH entries only, gives the+// same answer on every Node version and platform.+//+// Only native executables are considered. These calls run without a shell, and+// Windows cannot start a .cmd or .bat that way, so a pac.cmd install is not+// found, as it was not before either.++function isFile(p) {+ try {+ return fs.statSync(p).isFile();+ } catch {+ return false;+ }+}++// A candidate the OS would actually start: a regular file and, off Windows,+// one the user may execute. Node's own lookup skips a non-executable `pac`+// earlier on PATH and keeps searching, so this does too.+function isRunnable(p, platform) {+ if (!isFile(p)) return false;+ if (platform === "win32") return true;+ try {+ fs.accessSync(p, fs.constants.X_OK);+ return true;+ } catch {+ return false;+ }+}++// Windows variable names are case-insensitive. When an env object carries+// several spellings (a copied `Path` plus an added `PATH`), Node passes the+// child the lexicographically first one, so read that same one.+function envValue(env, name, platform) {+ if (platform !== "win32") return env[name];+ const key = Object.keys(env)+ .filter((k) => k.toUpperCase() === name.toUpperCase())+ .sort()[0];+ return key === undefined ? undefined : env[key];+}++/**+ * Absolute path of a native executable found on PATH, or null. Relative PATH+ * entries (an empty entry means "the current directory" on POSIX) are skipped.+ * On Windows `.com` then `.exe` is tried whatever PATHEXT says, as Node's own+ * shell-free lookup does.+ */+function resolveNative(+ name,+ { platform = process.platform, env = process.env, exists = (p) => isRunnable(p, platform) } = {}+) {+ const win = platform === "win32";+ const p = win ? path.win32 : path.posix;+ const dirs = String(envValue(env, "PATH", platform) || "")+ .split(win ? ";" : ":")+ .map((d) => d.trim().replace(/^"(.*)"$/, "$1"))+ .filter((d) => d && p.isAbsolute(d));+ const exts = win ? [".com", ".exe"] : [""];+ for (const dir of dirs) {+ for (const ext of exts) {+ const candidate = p.join(dir, name + ext);+ if (exists(candidate)) return candidate;+ }+ }+ return null;+}++/**+ * execFileSync-shaped: returns stdout, and throws when the tool is not on PATH+ * (code ENOENT) or the run fails (with err.stdout attached, as execFileSync+ * does). Callers treat any throw as "no data".+ */+function runNative(name, args, options = {}, deps = {}) {+ const file = resolveNative(name, deps);+ if (!file) {+ const err = new Error(`${name} was not found on PATH`);+ err.code = "ENOENT";+ throw err;+ }+ return execFileSync(file, args, {+ encoding: options.encoding,+ timeout: options.timeout,+ stdio: options.stdio,+ windowsHide: true,+ shell: false,+ });+}++module.exports = { resolveNative, runNative };diff --git a/shared/telemetry/lib/pac-auth.js b/shared/telemetry/lib/pac-auth.jsindex 71b268b59..0eb4ec6a3 100644--- a/shared/telemetry/lib/pac-auth.js+++ b/shared/telemetry/lib/pac-auth.js@@ -1,11 +1,13 @@"use strict";-const { execFileSync } = require("node:child_process");+const { runNative } = require("./native-exec");-// Reads PAC CLI auth state by shelling out to `pac auth who` and parsing the+// Reads PAC CLI auth state by running `pac auth who` and parsing the// banner output. Matches the convention used by// plugins/power-pages/scripts/lib/validation-helpers.js (getPacAuthInfo /// getEnvironmentUrl) so telemetry stays consistent with the rest of the repo.+// pac is started by absolute path from PATH, never by bare name (see+// native-exec.js).//// PAC's JSON profile files are an internal/undocumented format that varies// across versions. The banner output is stable and is what other code paths@@ -40,7 +42,7 @@ function readPacAuth(opts = {}) {cache = null;return null;}- const exec = typeof opts._exec === "function" ? opts._exec : execFileSync;+ const exec = typeof opts._exec === "function" ? opts._exec : runNative;let output;try {output = exec("pac", ["auth", "who"], {