Skip to content

A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.

model-apps 2.11.0: a table opens with its default form, navigation kept on rebuild, AI setting values, teardown and download fixes, SDK refresh (#653)

Akshay Maloof1a38ba706c9
diff --git a/evals/model-apps/app-builder/lib/facts.js b/evals/model-apps/app-builder/lib/facts.js
index dbf55f9cf..bd7876957 100644
--- a/evals/model-apps/app-builder/lib/facts.js
+++ b/evals/model-apps/app-builder/lib/facts.js
@@ -15,6 +15,7 @@ const { planFor, PHASES, appDef, viewDef, chartDef, compileFormIntent, formField
const { subgridSectionIntent } = pluginLib('artifact-intent.js');
const { schemaFacts } = pluginLib('schema-facts.js');
const { verifySpec } = pluginLib('verify-spec.js');
+const { isMainForm, plannedMainFormSequence } = pluginLib('form-order.js');
// Round-trip (edit/download) + teardown oracles: both plugin primitives are PURE — planTeardown does
// no I/O, and hydrateSpec takes an injected `read`, so we can grade the download→rebuild round-trip
// and the reverse-of-build teardown plan fully offline (no live env). See EVAL_GUIDE.md.
@@ -415,24 +416,29 @@ function makeAllPresentReader(spec) {
// Build a sitemap XML fragment covering the entity subareas declared in appShell. The page/icon
// checks in verifySpec only fire for implemented pages (source.kind==='tsx') — intent-only specs
- // skip them — so omitting GenPage XML is safe for our offline-only fixtures.
- const tags = [];
+ // skip them — so omitting GenPage XML is safe for our offline-only fixtures. Nested the way Dataverse
+ // stores a sitemap: verifySpec reads nav entries only as a SubArea directly under SiteMap/Area/Group.
+ const areasXml = [];
for (const a of (spec.appShell && spec.appShell.areas) || []) {
- if (a.icon) tags.push(`<Area Icon="${lc(a.icon)}"/>`);
+ const groupsXml = [];
for (const g of a.groups || []) {
+ const tags = [];
for (const sa of g.subAreas || []) {
const attrs = [];
if (sa.entity) attrs.push(`Entity="${lc(sa.entity)}"`);
if (sa.page) attrs.push(`Type="GenPage" GenPageId="gp-${sa.page}"`);
// Dashboard subarea: verifySpec resolves the dashboard id via queryRecords (which returns
- // formid 'x' below) and then confirms a SubArea points at THAT id via DefaultDashboard.
- if (sa.dashboard) attrs.push(`Type="Dashboard" DefaultDashboard="x"`);
+ // formid 'x' below) and then confirms a SubArea points at THAT id via DefaultDashboard — and
+ // carries the dashboard launcher Url, as every dashboard entry the build writes does.
+ if (sa.dashboard) attrs.push(`Type="Dashboard" DefaultDashboard="x" Url="/workplace/home_dashboards.aspx"`);
if (sa.icon) attrs.push(`Icon="${lc(sa.icon)}"`);
tags.push(`<SubArea ${attrs.join(' ')}/>`);
}
+ groupsXml.push(`<Group>${tags.join('')}</Group>`);
}
+ areasXml.push(`<Area${a.icon ? ` Icon="${lc(a.icon)}"` : ''}>${groupsXml.join('')}</Area>`);
}
- const xml = `<SiteMap>${tags.join('')}</SiteMap>`;
+ const xml = `<SiteMap>${areasXml.join('')}</SiteMap>`;
// Business rules and BPFs are both `workflows` rows, and verifySpec reads them with a raw OData
// filter rather than by name — so an "all present" reader has to answer that query specifically.
@@ -457,28 +463,49 @@ function makeAllPresentReader(spec) {
return [{ workflowid: `wf-${wanted}`, statecode: (hit.status || 'Active') === 'Active' ? 1 : 0 }];
};
+ // A table's Main form order is part of the spec too (AB#6736948), so each Main form resolves to its
+ // OWN id (`form:<name>`) and its formxml carries the <DisplayConditions Order> the build writes, in
+ // the build's order (lib/form-order.js). Every other lookup keeps the shared 'x' — dashboards resolve
+ // through it in the sitemap above. A Main form is named as verify names it: its `name`, else
+ // "<entity> form".
+ const mainFormName = (f) => f.name || `${f.entity} form`;
+ const withOrder = (xml, entityLogical, form) => {
+ const at = (plannedMainFormSequence(spec, entityLogical) || []).indexOf(form);
+ return xml.replace(/<\/form>$/, `<DisplayConditions Order="${at < 0 ? 0 : at}" FallbackForm="true"><Everyone /></DisplayConditions></form>`);
+ };
+
return {
findTable: async (logical) => (entities.has(logical) ? { logicalName: logical } : null),
findColumns: async (logical) => columnsByEntity[logical] || [],
// All view/chart/form/dashboard existence checks pass — the reader always reports present. A
// `role` query (verifySpec's persona-role check) returns an SDK-authored (marker) role, and a
// `businessunit` query returns a root BU so the BU-scoped, fail-closed role check resolves offline.
- queryRecords: async (set, opts) => (set === 'role'
- ? [{ roleid: 'role-x', description: SDK_ROLE_MARKER, ismanaged: false }]
- : set === 'businessunit'
- ? [{ businessunitid: '00000000-0000-0000-0000-000000000001' }]
- : set === 'workflow'
- ? workflowRow(opts && opts.filter)
- : [{ savedqueryid: 'x', savedqueryvisualizationid: 'x', formid: 'x' }]),
+ queryRecords: async (set, opts) => {
+ const filter = String((opts && opts.filter) || '');
+ const mainForm = set === 'systemform' && / type eq 2\b/.test(filter) && /\bname eq '((?:[^']|'')*)'/.exec(filter);
+ if (mainForm) return [{ formid: `form:${mainForm[1].replace(/''/g, "'")}` }];
+ return set === 'role'
+ ? [{ roleid: 'role-x', description: SDK_ROLE_MARKER, ismanaged: false }]
+ : set === 'businessunit'
+ ? [{ businessunitid: '00000000-0000-0000-0000-000000000001' }]
+ : set === 'workflow'
+ ? workflowRow(opts && opts.filter)
+ : [{ savedqueryid: 'x', savedqueryvisualizationid: 'x', formid: 'x' }];
+ },
sitemapXml: async () => xml,
// The layout oracle. An "all present" reader that cannot read layouts would make verify report
// every explicit form as UNVERIFIED — correct behaviour, but a fixture gap rather than a finding
// about the spec. Rendering the AUTHORED layout is the honest synthesis here: the reader's whole
- // premise is "the environment already matches the spec".
- formTopology: async (entityLogical, _formId) => {
- const form = (spec.forms || []).find((f) => lc(f.entity) === lc(entityLogical)
- && Array.isArray(f.tabs) && f.tabs.length);
- return form ? formXmlForAuthoredLayout(form) : null;
+ // premise is "the environment already matches the spec". A Main form with an auto layout has no
+ // authored tabs to render, so it answers with its form order alone.
+ formTopology: async (entityLogical, formId) => {
+ const named = /^form:([\s\S]*)$/.exec(String(formId || ''));
+ const form = named
+ ? (spec.forms || []).find((f) => isMainForm(f) && lc(f.entity) === lc(entityLogical) && mainFormName(f) === named[1])
+ : (spec.forms || []).find((f) => lc(f.entity) === lc(entityLogical) && Array.isArray(f.tabs) && f.tabs.length);
+ if (!form) return null;
+ const layout = Array.isArray(form.tabs) && form.tabs.length ? formXmlForAuthoredLayout(form) : '<form><tabs></tabs></form>';
+ return isMainForm(form) ? withOrder(layout, lc(entityLogical), form) : layout;
},
};
}
diff --git a/plugins/model-apps/.claude-plugin/plugin.json b/plugins/model-apps/.claude-plugin/plugin.json
index 352459352..6cc2d6845 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.10.0",
+ "version": "2.11.0",
"description": "Build model-driven Power Apps end to end: /app-builder authors whole apps (tables, relationships, forms, views, charts, security roles, app + sitemap) from a natural-language intent, and /genpage builds generative pages with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI > 2.10.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.",
"author": {
"name": "Microsoft",
diff --git a/plugins/model-apps/.plugin/plugin.json b/plugins/model-apps/.plugin/plugin.json
index 352459352..6cc2d6845 100644
--- a/plugins/model-apps/.plugin/plugin.json
+++ b/plugins/model-apps/.plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "model-apps",
- "version": "2.10.0",
+ "version": "2.11.0",
"description": "Build model-driven Power Apps end to end: /app-builder authors whole apps (tables, relationships, forms, views, charts, security roles, app + sitemap) from a natural-language intent, and /genpage builds generative pages with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI > 2.10.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.",
"author": {
"name": "Microsoft",
diff --git a/plugins/model-apps/AGENTS.md b/plugins/model-apps/AGENTS.md
index 1526a34d8..cfdf61d4e 100644
--- a/plugins/model-apps/AGENTS.md
+++ b/plugins/model-apps/AGENTS.md
@@ -142,7 +142,20 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
primary) via `findFieldCellPointer`+`removeElement`, keyed by a declared semantic identity so a rebuild
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`
+ a row-spanning cell above still reserves is kept, and so is a row that was already empty.
+ **Which form a table opens with** (AB#6736948, `lib/form-order.js`) is decided by the table's Main
+ Form Set order — each Main form's formxml `<DisplayConditions Order>` — not by `systemform.isdefault`
+ (measured: moving the flag reorders nothing, and a table's three new forms, all at the same order,
+ were served with the `isdefault` form last). After every form exists, the forms phase promotes the default (an explicit
+ `isDefault` or `entities[].mainFormOrder[0]` on any table; the first Main form only on a table the
+ spec owns) and then writes Order 0..n-1 onto the spec's Main forms, the ones it does not list keeping
+ their stored relative order. On a table it orders nothing on, a Main form it creates is created after the
+ table's others: its order is written into the new form's own `<DisplayConditions>` before the first
+ push (`createInPlace`), so no interrupted run or later failure can leave it at the Order 0 every new
+ form gets — a later build could not tell it is new. Only declared forms are written, order-only through `setFormSecurityRoles` so roles
+ survive; a table ordered by hand (`securityRoles.order`) is left alone; the step is best-effort (✗ and
+ a warning, never a halt). Verify checks the stored order (`form-order`) and what the public
+ `RetrieveFilteredForms` serves the user running it (`form-order-served`). 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
@@ -239,6 +252,36 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
without the pages phase the change is applied only after the live-page gate, so a gate halt leaves
nothing behind; a page-backed app's standalone header push refuses a copy still holding an earlier
run's unpushed edits (`app-copy-unpushed-edits`) rather than replay them.
+ **An existing app's sitemap is rewritten ONTO its live nodes (AB#6726727).** The App Spec describes a
+ node's label/title, target and icons only, and the SDK serializes a node without its fetched `bag` from
+ scratch (new `Id`, `ResourceId="SitemapDesigner.NewSubArea"`, broad `Client`/`Sku`,
+ `AvailableOffline="true"`). Both existing-app writers (the app-shell write and the pages finalizer)
+ therefore pass appDef's tree through `adoptLiveSitemap` (`scripts/lib/sitemap-merge.js`) first: a
+ subarea corresponds by navigation target (a URL keeps the case of its path and query), an area or
+ group by a label its level uses once, then by the navigation entries it holds, then by the id an
+ earlier build gave it (a node none of these identifies is written as new rather than guessed); the
+ live `id` and `bag` are kept, and only
+ what the spec sets is overlaid — chrome it does not name is still removed, as before. Because the SDK
+ only patches an existing `<Titles>` on a node with a bag, and reads an empty title as "no edit", a
+ title added to an entry that had none, or removed from one, is reconciled in the adopted bag at the
+ SDK's language (other languages' titles are kept). Every dashboard entry carries exactly
+ `Url="/workplace/home_dashboards.aspx"` — the designer writes it on every dashboard entry and
+ recognizes one only by the whole Url, and the runtime keys the dashboard glyph on it with a
+ case-sensitive match — and verify fails an entry without it (`subarea-dashboard-launcher`, which
+ reads only real nav entries — a `SubArea` directly under `SiteMap/Area/Group`, never one in a comment
+ or elsewhere — as the kept-icon check below does). With a
+ **baseline** — `.maker-workspace/last-applied.json`, written atomically by a successful apply and
+ by download, stamped with its environment and app (`scripts/lib/deployed-baseline.js`) — a nav entry's
+ title/icon that the spec has not changed since, but the designer has, is kept and reported rather
+ than reverted (`keepsLiveValue`); without one the spec wins and every change to an existing entry is
+ reported. Baseline entries are lined up with live ones by the ids the baseline RECORDED for its
+ environment (`__deployedIds`: what the apply resolved, or what the download read), never by the
+ spec's own `dashboardId`/`pageId`, which may be another environment's. Verify accepts a kept icon by
+ the same rule and identities, and only on a live entry that exists. A downloaded dashboard carries
+ `dashboards[].dashboardId`, which build, verify and teardown resolve before the name
+ (`findPinnedDashboard`) — when it resolves it is the only candidate, and teardown still requires
+ solution membership — so a dashboard renamed in the designer is reused, with a warning since a build
+ never renames one, instead of a second being created under the stale name.
**DATA-MODEL Dataverse labels are stamped with the ORGANIZATION's base language, not a hardcoded
1033.** `resolveLanguageCode` (`scripts/lib/entity-provision.js`) reads `organization.languagecode`
once per build and threads it into every label-emitting SDK call in that phase (tables, columns,
@@ -372,8 +415,9 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
412 every time). This is why
**`scripts/lib/sdk-http-client.js` must implement `postRaw`**: the SDK will not fall back to two
sequential deletes, so a transport without it fails every teardown with `APP_DELETE_NOT_ATOMIC` (see
- that file for the wire contract, why a `$batch` is never retried, and why a conditional write that
- gets no answer is never re-sent). Pinned by
+ that file for the wire contract, why a `$batch` is sent once unless its answer proves nothing in it
+ ran — a SQL deadlock or a 429 — and why a conditional write that gets no answer is never re-sent).
+ Pinned by
`scripts/tests/app-delete-real-bundle.test.js` against the real bundle — every other teardown test
drives a mock and would stay green through a regression here.
The empty solution container goes last — but a **built-in
@@ -397,7 +441,9 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
- **`scripts/download-model-app.js` → `scripts/lib/hydrate-spec.js`** — the **edit flow**: pulls a
*deployed* app back into an editable App Spec + page code (sitemap → `appShell` with icons, **every**
generative page via `pac model genpage download`, referenced entities/tables, icon web resources,
- dashboards, solution).
+ dashboards, solution). It reads through a throwaway SDK workspace, never the folder's
+ `.maker-workspace` — a copy an interrupted build left there made the download fail, or describe edits
+ that were never deployed — and writes only the baseline (`last-applied.json`) into it.
**Round-trip scope (be precise — do not claim "complete"):** tables, sitemap/appShell, generative pages,
classic dashboards, icons, and solution round-trip; **forms, views, charts, and commands do NOT yet
round-trip.** (View hydration was tried and reverted — LIVE-verified that the deployed savedquery set
@@ -534,8 +580,10 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
and the exact admin action needed (Power Platform Admin Center → Environments → Settings → Product →
Features) for anything off. Never fails. The `ai-features` build phase calls this logic internally and
uses `RetrieveSetting`/`SaveSettingValue` (SDK) for app-level feature flags and `AIModelPublish` +
- `aiskillconfigs` for per-table row summaries. Feature values are `true`/`false` (the numeric settings'
- 1/0) or an explicit integer such as `2` ("on for everyone"), bounded to `0..1000000` — the same range
+ `aiskillconfigs` for per-table row summaries. Feature values are `true`/`false` — encoded by the
+ plugin to each setting's own On/Off value (On is `2` everywhere; Off is `1`, but `0` for `nlChart`;
+ `AI_SETTING_CODEC` in `lib/ai-app-settings.js`, AB#6714731) before the SDK sees them — or an explicit
+ integer written verbatim, bounded to `0..1000000` — the same range
the SDK enforces, so validation rejects an out-of-range value up front instead of aborting the build
half-applied. The SDK **proves every write** against the app-scope override row, retrying with backoff
(an immediate read can still return the environment fallback, which previously produced a false
@@ -705,6 +753,7 @@ scripts/
op-diff.js ← destructive-op diff + --allow-destructive / --non-interactive gating
artifact-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-order.js ← the Main Form Set order: which Main form a table opens with, and which forms the build orders (shared by the spec gate, 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)
@@ -731,6 +780,8 @@ scripts/
pageref-resolver.js ← PAGEREF_<key> → GenPageId nav resolver
page-manifest.js ← durable <app>_pagemanifest read/write
sitemap-pages.js ← pure GenPageId extractors + fail-closed fetchSitemap MEMBERSHIP reader + cross-app scan
+ sitemap-merge.js ← pure: re-attach an existing app's rewritten sitemap to its live nodes (ids + everything the spec cannot describe), keep designer nav edits the spec did not make
+ deployed-baseline.js ← `.maker-workspace/last-applied.json`: the spec last applied or downloaded, stamped with its environment + app and the dashboard/page ids deployed there
ai-candidates.js ← selects good-candidate tables for auto row-summary mode
ai-prompt.js ← generates tailored Copilot row-summary prompts
_graph.js ← entity topological ordering (shared by build + teardown)
@@ -739,7 +790,7 @@ scripts/
content-hash.js / hash.js ← content-aware phase diff: fold on-disk .tsx/contentPath byte hashes into the diff (changed-only)
classify-changes.js ← changed-only: classify a spec diff → fast (page-content) | full | noop + sticky debt
apply-snapshot.js ← changed-only: pure eligibility state machine (identity bind, debt, tombstone, generation CAS)
- apply-snapshot-store.js ← changed-only: atomic snapshot write + workspace lease + invalidate/claim/tombstone/delete + distrust marker
+ apply-snapshot-store.js ← changed-only: atomic snapshot write (writeFileAtomic, also the baseline's) + workspace lease + invalidate/claim/tombstone/delete + distrust marker
apply-snapshot-index.js ← changed-only: build result.created → snapshot artifact map
workspace-paths.js ← the `.maker-workspace` name + the guard that gates destructive --clear-workspace cleanup
changed-only-flow.js ← changed-only: --changed-only orchestration (decide fast/full, live identity, snapshot lifecycle)
@@ -1159,7 +1210,7 @@ changes. **Never patch the bundle** to work around an SDK defect: the next re-ve
reverts it and the hash in `PROVENANCE.json` stops matching. Fix it upstream and re-vendor.
**Vendored-SDK contract invariants (regression net).** When you bump the SDK and re-vendor, the
-skill relies on behaviors that must survive. Four test files lock them — run all against every
+skill relies on behaviors that must survive. The test files below lock them — run all against every
rebuilt bundle.
**Re-vendor from a COMMIT, and check the recorded provenance.** `scripts/_vendor-build/build.js`
@@ -1230,6 +1281,26 @@ fails on any un-awaited `provision.*`/`sdk.*` call to those methods (annotate a
`sdk-async-ok`), and a **dynamic check** that the real bundle still returns Promises for exactly that
list — so if a future SDK makes one synchronous again, the scan can't go on enforcing a dead rule.
+`scripts/tests/workspace-projection-real-bundle.test.js` — the **upgrade** guard. The SDK refuses to
+push a workspace copy stamped with another parser version (`ARTIFACT_PROJECTION_STALE`), so a
+re-vendor that raises it makes every existing `.maker-workspace` old. Upgrades stay invisible only
+because a plain fetch re-reads a clean old copy (and the build fetches every existing form, view,
+chart and app before editing it); a copy still holding an interrupted build's edits is kept by that
+fetch and refused at push — or, when the environment's copy has moved since, refused by the fetch
+itself (`LOCAL_EDITS_WOULD_BE_LOST`, measured live on a 2.10.0 workspace). For the push refusal the
+runner names the manual reset every workspace-reset remedy shares
+(`RESET_WORKSPACE` in `lib/entity-provision.js`): stop other builds and teardowns on the workspace
+first — the changed-only snapshot holds their leases and a running teardown's registration — then
+delete everything except `last-applied.json` (the navigation baseline) and `destructive-approval.json`
+(the approved removals), which no re-run can rebuild. The build does not reset the copy itself: the
+SDK's per-artifact lock is per process, so an overwrite could discard another build's newer edits on
+the same workspace. For the fetch refusal it asks for a review first: the environment has changed
+since the copy was fetched (maybe by a maker — the same copy is what a concurrent-edit halt keeps as
+a fence), so rebuilding the same spec over a cleared copy could overwrite that change. The halt says
+to look at the change in Maker and put into the spec what should stay, then make the same reset. (A
+re-download is no substitute: it captures no forms, views or charts, and an interrupted first build
+can leave them before the app exists.)
+
**Live end-to-end (app-builder — writes to a real Dataverse env; optional).** All build/verify/
teardown scripts are **dry-run by default**; add `--apply` to write.
diff --git a/plugins/model-apps/CHANGELOG.md b/plugins/model-apps/CHANGELOG.md
index 3750e38c3..54feca528 100644
--- a/plugins/model-apps/CHANGELOG.md
+++ b/plugins/model-apps/CHANGELOG.md
@@ -5,7 +5,63 @@ 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.10.0
+## [Unreleased] — 2.11.0
+
+AI features are written with each setting's own values, rebuilding an existing app no longer
+rewrites its navigation, a table opens with the form the spec makes its default, and the vendored
+SDK is refreshed.
+
+### Added
+
+- **`entities[].mainFormOrder`** (AB#6736948) — a table's Main forms in the order they are offered,
+ first to last; the first is the one the table opens with. Works on existing tables.
+
+### Fixed
+
+- **A table opens with its default form** (AB#6736948). What opens is decided by the order of a
+ table's Main forms, not the default flag, and new forms all share one position — so a table with
+ several Main forms could open with an alternate one. The build now also puts the default form
+ first, and `--verify` checks the order. `isDefault` on an existing table used to be ignored; a form
+ the build adds to an existing table now goes after its other Main forms.
+- **A teardown no longer stops when Dataverse is busy.** A delete refused with 429 (another
+ customization still running) is re-sent like other throttled requests; the solution delete that
+ ends a teardown used to fail and leave the solution behind.
+- **Download reads what is deployed.** It no longer reads through the folder's `.maker-workspace`,
+ where a copy an interrupted build left could make it fail or return edits never deployed.
+- **Rebuilding an existing app keeps its navigation as it is** (AB#6726727). Every nav entry was
+ rewritten as a new one, so an unrelated edit turned a designer-made dashboard entry's icon into a
+ placeholder and dropped its other settings. Entries now keep their id and everything the spec does
+ not describe; dashboard entries carry the designer's launcher Url, and `--verify` fails one without
+ it.
+- **A nav title or icon changed in the designer after a download is kept**, with a warning, instead of
+ being reverted by the stale spec. Download records the spec as a baseline for that environment.
+- **A dashboard renamed in the designer** is reused by the id a download now records
+ (`dashboards[].dashboardId`); it used to be recreated under the old name.
+- **AI feature values** (AB#6714731). `true` wrote `1` outside the form-fill family: *Off* for
+ natural-language grid search and M365 Copilot, *Auto* for NL charts, and `--verify` expected the
+ same. `true` now writes `2` (*On*) for every feature, so the next build of an AI-enabled app turns
+ NL grid search back on. `false` writes that setting's *Off*: `1`, or `0` for NL charts.
+- **`ai-preflight`** no longer shows ✓ for an app with M365 Copilot off, and reports NL charts' *Auto*
+ as the platform default rather than on.
+- **`appShell` keys the build does not read are errors** ([#631]). A `title` on an area or group (they
+ take `label`) used to deploy an untitled one while lint, the build and `--verify` passed.
+- **A SQL deadlock no longer fails a delete or a build.** A request SQL rolled back as a deadlock
+ victim is re-sent (up to three times): a record delete, or an app delete's change set, by the
+ plugin; a read, an app create or a publish by the refreshed SDK. A build that halts on one runs
+ again like one that halts on a SQL timeout; a teardown used to stop on it.
+
+### Changed
+
+- **The vendored SDK is refreshed.** A workspace saved by an earlier version is re-read on the next
+ build; a copy an interrupted build left holding unpushed edits halts it and names the step to take.
+ A remedy that asks you to clear `.maker-workspace` now says to stop other runs on it first and to
+ keep `last-applied.json` and `destructive-approval.json`.
+- **An explicit `false` for NL grid search or M365** now writes *Off* (`1`) instead of the platform
+ default (`0`). A spec that omits `m365` still leaves it at `0`.
+
+[#631]: https://github.com/microsoft/power-platform-skills/issues/631
+
+## [2.10.0]
Connector authoring loses its feature flag, `--allow-destructive` removes only what a maker was
shown, and the vendored SDK is refreshed.
diff --git a/plugins/model-apps/docs/app-builder-capabilities.md b/plugins/model-apps/docs/app-builder-capabilities.md
index ba873586a..c129e3271 100644
--- a/plugins/model-apps/docs/app-builder-capabilities.md
+++ b/plugins/model-apps/docs/app-builder-capabilities.md
@@ -22,7 +22,7 @@ apart deliberately.
- Deterministic, **idempotent** build engine — discovers via the SDK (`findTables`/`findColumns`/`fetchEntityMetadata`) and creates only what's missing; new / existing / mixed envs all work.
- **All Dataverse access via the vendored headless SDK**; metadata cached under `<app-folder>/.maker-workspace/` for reuse.
- Phase selection (`--only`/`--skip`/`--from`/`--to`), `[n/total]` narration, `BuildHalt` gate, dry-run by default, `--sample-data` / `--publish` opt-in.
-- Bounded-concurrency for independent ops; one publish round-trip per entity + the app. `az`-token HttpClient with transient (429 / 5xx) retry.
+- Bounded-concurrency for independent ops; one publish round-trip per entity + the app. `az`-token HttpClient with transient (429 / 5xx) retry, honouring `Retry-After` up to 60 s; a record delete, or a change set of conditional deletes (an app and its sitemap), is sent once unless its answer proves it did not run: SQL rolled it back as a deadlock victim (`Sql Number: 1205` — for a change set, on every operation it answers; re-sent up to three times), or the server refused to start it with a 429 (re-sent on the throttle schedule).
- Guardrail lint (`spec-lint.js`) + hard validator (`app-spec.js`). 🧪 full `node:test` suite + the vendored SDK's Jest suite green (`node scripts/run-tests.js --with-sdk <ppux>`).
### Data model (Tier 1) — ✅ verified live
@@ -142,6 +142,7 @@ apart deliberately.
- App module + sitemap; **multi-area sitemaps** — every `appShell.areas[]` maps to its own `<Area>` (icon + groups + subareas; order follows array order). The app is **self-contained for export/import**: its **sitemap** is added to the solution (componenttype 62), and its **tile icon** is an in-solution web resource — `app.icon` (a declared image web resource) or a generated default SVG — never an arbitrary external/managed icon.
- Generative pages (**genpage-first**) for overview / dashboard surfaces — uploaded via `pac model genpage upload`; the SDK finalizes the sitemap with `GenPage` subareas.
- Dashboards (chart / list / iframe / webresource tiles) with **sitemap placement** (auto-pinned as an app component). Tiles render in a **multi-column grid** (2-wide) rather than one stacked full-width column.
+- **Rebuilding an existing app keeps its navigation** (AB#6726727). The build used to hand the SDK a sitemap recomputed from the spec with no trace of the live nodes, so every entry was re-created from scratch — new ids and the designer's defaults for a *new* entry — and a designer-made dashboard entry lost its launcher `Url` and with it the dashboard icon. Each entry the spec keeps is now written onto the live entry it corresponds to (`scripts/lib/sitemap-merge.js`), so everything the spec cannot describe survives, and every dashboard entry carries `Url="/workplace/home_dashboards.aspx"`, as the designer writes it. A title or icon changed in the designer since the spec's baseline (the last apply or download for that environment) is kept and reported; with no baseline the build reports each change it makes to an existing entry. A downloaded dashboard is bound by the id the download recorded, so one renamed in the designer is not recreated under its old name.
- Modern command-bar buttons — functional **JS on-click** + static hidden/disabled, incl. **flyout / split-button menus**.
- Web resources (JS / HTML / CSS) shipped + added to the solution; idempotent (reuse by name).
@@ -159,11 +160,19 @@ apart deliberately.
actual setting are *different rows*, and a gate can read off while the feature is switched on at
environment scope — so it runs in every app on that org. Live-measured: gate `EnableNLGridSearch`
= `false` while `NLGridSearchSetting` = `2` at environment scope (NL search on), and
- `NLChartDataVisualizationSetting` = `1` by default (NL charts on). Preflight resolves the
+ `NLChartDataVisualizationSetting` = `1` by default — *Auto*, its platform default. Preflight resolves the
effective value per feature — app-scope override → environment → default — reports those as
*in effect via the environment/default setting*, and **suppresses the admin action**, so nobody is
sent to the admin centre to switch on something already running. A value it cannot read never
- counts as in effect, so a genuine action is never hidden.
+ counts as in effect, so a genuine action is never hidden. A platform-default value (*Default*, or
+ *Auto* for charts) is reported as the platform's decision, neither on nor off.
+- **Every per-app AI setting is a tri-state, and `1` is not "on"** (AB#6714731). Per the platform's
+ own settings UI, form fill (all four settings), NL grid search and M365 store 0 = *Default*,
+ 1 = *Off*, 2 = *On*, and NL charts store 0 = *Off*, 1 = *Auto*, 2 = *On*. Builds used to write `1`
+ for `true` outside the form-fill family — turning NL grid search and M365 **off** and leaving
+ charts on *Auto* — and `--verify` expected the same `1`. The plugin now encodes every flag itself
+ (`true` → `2`; `false` → that setting's *Off*) and verifies against the same table, so the next
+ build of an affected app writes `2`.
- **Form fill is a real "off", not a naming mix-up** (measured 2026-08-28). Unlike NL search, the
gate and the per-app setting share one name — `FormFillBarUXEnabled` — confirmed against the
SDK's own `AI_GATE`/per-app maps, so there is no second setting hiding a different answer. It
@@ -250,7 +259,7 @@ apart deliberately.
### 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 (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).
+- `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 a downloaded spec's pinned `dashboardId` first, else by name) and matching the sitemap's `DefaultDashboard` — so a value reused elsewhere can't produce a false pass — and that entry must carry the dashboard launcher `Url`, without which the app shows a placeholder icon for it. **Multi-area sitemaps** and the dashboard-subarea path were re-verified live (positive + negative).
### Teardown — ✅ verified live
- `teardown-model-app.js` deletes exactly what an App Spec declares, in dependency-safe order (app → dashboards → commands → business rules → business process flows → forms → **security roles** → charts → views → relationships → AI row summaries → tables [children-first] → web-resources → global choices → solution). Forms/charts/views/relationships are removed **before** tables (a table delete doesn't reliably cascade cross-references); **web resources are removed AFTER tables** (a table's icon web resource is referenced by the table). A business rule / business process flow is deactivated before it is deleted, because Dataverse refuses to delete an activated process.
diff --git a/plugins/model-apps/references/app-spec-schema-advanced.md b/plugins/model-apps/references/app-spec-schema-advanced.md
index 042e93921..8036283ea 100644
--- a/plugins/model-apps/references/app-spec-schema-advanced.md
+++ b/plugins/model-apps/references/app-spec-schema-advanced.md
@@ -241,8 +241,8 @@ works through.
plot a different table's data over this view.
- **Dashboard names must be unique**, compared the way Dataverse compares them: ignoring case,
accents, full/half width and trailing spaces (`Overview`, `OVERVIEW `, `Café`/`Cafe`) — but not a
- leading space, and not a vowel sign in scripts where it is a letter. A dashboard has no other
- identity in the spec — a sitemap subarea names it and a rebuild finds it by name — so two that
+ leading space, and not a vowel sign in scripts where it is a letter. A sitemap subarea names a
+ dashboard, and a rebuild finds it by name unless the spec pins its id (below), so two names that
compare equal would collapse into one. A download **withholds** such a pair and says why, rather
than emit a spec that cannot be rebuilt: rename one in Maker and download again. Because a name can
also match **another app's** dashboard, ownership comes from the app's solution, which holds every
@@ -255,6 +255,15 @@ works through.
- Built after views/charts (it references their ids). The dashboard is **global** (not entity-scoped)
and added to the solution. To surface it in the app nav, add a `dashboard` sitemap subarea (below) —
that also auto-pins it as an app component.
+- **`dashboardId` (optional — what a download writes).** A downloaded spec carries each dashboard's
+ deployed id (bare GUID, environment-specific, like `pages[].pageId`); leave it out of an authored
+ spec. A rebuild binds to that dashboard **before** trying the name, so one renamed in the designer
+ since the download is reused — a build never renames an existing dashboard, so it warns and names
+ the new name to put in the spec — instead of a second dashboard being created under the old name
+ and the nav entry pointed at it. In an environment without that id (the spec was downloaded
+ elsewhere) the name is used as usual. Verify and teardown resolve the pin the same way — when it
+ resolves it is the only candidate — and teardown still deletes only a dashboard the app's solution
+ holds.
- **ID-passthrough tiles (what a download emits).** A tile may instead carry the *deployed* ids —
`viewId` (+ `visualizationId` for a chart) and the target `entity` — with no `chart`/`view` name.
That form binds to artifacts that **already exist**, which is what a downloaded app needs: its
diff --git a/plugins/model-apps/references/app-spec-schema.md b/plugins/model-apps/references/app-spec-schema.md
index fe291e0df..f85171018 100644
--- a/plugins/model-apps/references/app-spec-schema.md
+++ b/plugins/model-apps/references/app-spec-schema.md
@@ -356,7 +356,7 @@ spec with its last snapshot, not with the deployed row, so it does not notice).
}
```
- **Unknown table keys are REJECTED, not ignored.** A table accepts exactly the keys above
- plus `statusReasons` / `alternateKeys`. Anything else — a misspelled `pluralname`, or a
+ plus `statusReasons` / `alternateKeys` / `mainFormOrder`. Anything else — a misspelled `pluralname`, or a
`languageCode` / `localizedLabels` asking for a per-table language or a parallel label block —
fails validation naming the alternative, rather than validating clean and being dropped from the
build.
@@ -459,7 +459,8 @@ without needing a business rule or a plug-in to enforce it.
### entity sub-sections (optional)
```jsonc
"statusReasons": [ { "label": "In Review", "state": "Active" } ], // custom status values
-"alternateKeys": [ { "schemaName": "new_emailkey", "displayName": "Email Key", "columns": ["new_email"] } ]
+"alternateKeys": [ { "schemaName": "new_emailkey", "displayName": "Email Key", "columns": ["new_email"] } ],
+"mainFormOrder": ["Work Item", "Work Item — Summary"] // the Main Form Set order — see forms[] → "Which form a table opens with"
```
## Conditional features — read `app-spec-schema-advanced.md` when you use one
@@ -571,6 +572,11 @@ why they need naming here at all.
set, and `existing` means the build cannot prove it owns the table, so rewriting another app's
default views is not a safe default. Set **`"enrichDefaultViews": true`** to override that when you
know the reused table is yours. Author-declared `views[]` are separate and always win.
+- **A view is found by its name on its table, so a name the table already has is that view.** A view
+ named like the platform's own "Active &lt;Plural&gt;", or like any view already on the table, is not
+ created a second time: the build adds the spec's columns to the existing view (removing none) and
+ writes its `description`, but does not reapply its `filters` or `sort` — it warns instead. Give the
+ view its own name to get a separate one.
## charts[]
```jsonc
@@ -660,15 +666,18 @@ why they need naming here at all.
default and only ever applies to a table THIS build owns (a custom, publisher-prefixed, non-`existing`
table); it never touches a reused/system table. Teardown reactivates the stock form before deleting
ours, so a torn-down table is left clean.
-- **`isDefault`** *(optional, boolean, Main forms only)* — which Main form the table **opens with**.
- Exactly one Main form per table may set it; the fallback is the first Main form in spec order, so
- selection is order-independent either way (it is applied once, after every form exists, rather than
- each form racing to promote itself). A promotion the environment refuses is reported as a warning
- and fails `--verify`, which proves the deployed `systemform.isdefault` independently — so a build
- 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.
+- **`isDefault`** *(optional, boolean, Main forms only)* — which Main form the table **opens with**:
+ the build marks it `systemform.isdefault` **and** puts it first in the table's Main Form Set order —
+ the flag alone does not decide what opens (see *Which form a table opens with* below). Exactly one
+ Main form per table may set it. Set explicitly, it applies on **any** table, `existing: true`
+ included; without it, a table this spec creates opens with its first Main form in spec order. It is
+ applied once, after every form exists, rather than each form racing to promote itself. A promotion
+ the environment refuses is reported as a warning and fails `--verify`, which proves the deployed
+ `systemform.isdefault` independently — so a build 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 be
named "Information" without colliding. A `formType:"Main"` edit reconciles **only** the Main form;
@@ -686,6 +695,48 @@ why they need naming here at all.
is truthy in JS and would silently enable a handler you meant to disable.
The build fetches the pushed form, injects the handlers, then publishes it.
+### Which form a table opens with — `isDefault` and `entities[].mainFormOrder`
+
+A table's Main forms are served in its **Main Form Set order**, and a user opens the **first one
+they may open** — unless they switched forms earlier: the platform remembers the last Main form each
+user opened for a table and opens that one for them while they may still open it. The order is
+stored on each form (its formxml `<DisplayConditions Order="n">`), and `systemform.isdefault` does
+not change it: measured, moving the flag reordered nothing, and a table's three new Main forms — all
+at the same order, as every new form is — were served with the `isdefault` form *last*.
+
+- **`forms[].isDefault: true`** — this form opens first: it becomes the table's default **and** comes
+ first in the order. Applied on any table.
+- **`entities[].mainFormOrder`** — the order itself, first to last, as names of the table's Main forms
+ in `forms[]`:
+ ```jsonc
+ { "schemaName": "contoso_workitem", "existing": true,
+ "mainFormOrder": ["Work Item", "Work Item — Summary", "My Work — Work Item"] }
+ ```
+ The first form is the one the table opens with (an `isDefault` form must be first). A partial list
+ puts the listed forms first; the table's other spec forms follow in their current order. Each name
+ is spelled as in `forms[]`, and must not match another Main form of the table ignoring case and
+ accents — Dataverse, and so the build, compares form names that way, and could not tell them apart.
+- **Neither set:** on a table this spec creates, the first Main form in spec order comes first and
+ the others follow in spec order. On any other table the order is left as it is, and a Main form the
+ build *creates* there is put after the table's other Main forms — adding an alternate form does not
+ change what the table opens with. If none of those forms has an order yet, the new form comes first
+ and the build warns; it also warns when the new form comes before a form that has no order (a form
+ without one is served after every form that has one). The new form's place is part of creating it,
+ so an interrupted build cannot leave it first.
+- **Only forms in `forms[]` are written.** A Main form the spec does not declare keeps its order; if
+ it would still come first, the build warns and `--verify` fails, naming it. Move it down in Maker
+ (**Form settings → Form order**), or declare it and list it in `mainFormOrder`.
+- **`securityRoles.order`** writes the same attribute. A table where a Main form sets it is ordered by
+ hand: the build leaves its order alone, and the spec cannot also give it `mainFormOrder`.
+- **Also deciding what a user sees:** their security roles — a form restricted by `securityRoles` is
+ served only to those roles, and everyone else opens the next form they may open — and their
+ remembered form, which is per user, not configuration (they change it by switching forms). An app
+ offers **every** active Main form of its tables, including forms the spec does not declare (the
+ stock "Information" form among them); a spec cannot leave one out today.
+- **`--verify`** checks the stored order (`form-order`) and the order the platform serves the user
+ running verify (`form-order-served`, read with the public `RetrieveFilteredForms` function). When
+ that user may not open the first form, the check is reported as not applicable, not as a pass.
+
### Explicit layout — tabs, form-columns, sections
| Level | Key | Meaning |
@@ -878,7 +929,9 @@ fail to add anyone. Every malformed shape is a hard error for that reason.
This direction fails closed (access never silently widens), but it does mean "undo" is an explicit
`{ "everyone": true }`.
- **`fallbackForm`** *(optional)* — show this form to users whose roles have no form of their own.
-- **`order`** *(optional, non-negative integer)* — display order among the entity's forms.
+- **`order`** *(optional, non-negative integer)* — this form's place in the table's Main Form Set
+ (the same attribute `isDefault` and `entities[].mainFormOrder` set; see *Which form a table opens
+ with*). A table where a form sets it is ordered by hand, and cannot also have `mainFormOrder`.
- Both `fallbackForm` and `order` are **preserved** when omitted, so a later build that sets only
`personas` does not reset them.
@@ -1016,6 +1069,24 @@ custom control), but the spec validator emits a warning.
of a `dashboards[]` entry — auto-pinned as an app component so the app includes it), `url`, or
`page` (the **`key`** of a `pages[]` generative page at schemaVersion 2; the **name** for legacy specs
— surfaced as a `GenPage` sitemap subarea).
+- **Areas and groups take `label`; subareas take `title`.** Each level accepts only the keys the build
+ reads — area: `label`, `icon`, `vectorIcon`, `iconDescription`, `groups`; group: `label`,
+ `iconDescription`, `subAreas`; subarea: `title`, one target, `icon`, `vectorIcon`, `iconDescription` —
+ and anything else is a validation error, so a `title` on an area says "did you mean `label`?" rather
+ than deploying an untitled area.
+- **Rebuilding an existing app keeps what the spec cannot describe.** Each nav entry the spec keeps is
+ written onto the live entry it corresponds to (a subarea by its target; an area or group by its
+ label), so the live entry's id, its other attributes (`Client`, `Sku`, `AvailableOffline`, …) and its
+ titles in other languages survive; only the label, title, target and icons the spec sets are applied.
+ A `dashboard` entry is written the way the designer writes one, with
+ `Url="/workplace/home_dashboards.aspx"` — without it the app shows a placeholder icon for the entry,
+ and `--verify` fails it.
+- **A nav change made in the designer after a download is kept, not reverted.** Download and every
+ successful apply record the spec as a baseline in `.maker-workspace/last-applied.json`, for that
+ environment and app. When the spec still has the baseline's title or icon for an entry and the
+ environment has something else, the build keeps the environment's value and says so, and `--verify`
+ accepts it — change the spec to change it. With no baseline for the environment, the spec wins and the
+ build reports each change it makes to an existing entry.
- **`url` is either a real http(s) link or a web-resource reference** — `$webresource:<name>` (the form
the Site Map Designer writes for a "custom page backed by an HTML web resource") or the equivalent
`/WebResources/<name>` path. A web-resource reference **passes through as-is**, like a platform icon
@@ -1117,7 +1188,10 @@ set a custom status with `statusReason`. All are topologically inserted and boun
## ai (optional — AI feature flags and row-summary configuration)
Controls AI-powered features that the platform activates at the app/table level. The block is
-entirely optional; omitting it leaves every AI feature at its platform default.
+entirely optional; omitting it writes no AI setting, so the app's existing AI settings are left as
+they are — a feature follows the environment's value only where the app has no value of its own
+(removing an app-scope value is not something the build does). Any `ai` block writes every feature
+below as an app-scope value, which overrides the environment's.
> **Admin-gated.** AI features turn on only where the environment administrator has enabled them
> in Power Platform Admin Center (Environments → Settings → Product → Features). The `ai-features`
@@ -1136,15 +1210,20 @@ entirely optional; omitting it leaves every AI feature at its platform default.
//
// `false` DOES NOT MEAN "leave alone". It writes an explicit app-scope override that BEATS the
// org value, so setting it on a feature the org has enabled turns that feature OFF for this app.
- // To leave a feature as the environment provides it, omit the whole `ai.appFeatures` block.
+ // To defer a feature to the platform instead, give it that setting's platform-default value — still
+ // an app-scope value, so the app gets the platform's default rather than the environment's setting.
//
- // The numeric value written is NOT a flat 1/0 — it differs by family (captured from the bundle):
- // formFill, formFillSuggestions, formFillSmartPaste, formFillFiles -> true writes 2, false writes 1
- // nlSearch, nlChart, m365 -> true writes 1, false writes 0
- // For the form-fill family the tri-state is 0 = platform default, 1 = DISABLED, 2 = enabled, so
- // `false` there means "explicitly disabled", not "unset".
- // An explicit integer (0-1000000) is also accepted for a platform-defined value; the bound mirrors
- // the SDK's own, so an out-of-range value is rejected here rather than aborting the build half-applied.
+ // Every one of these settings is a tri-state, and the numbers differ by setting (taken from the
+ // platform's own settings UI):
+ // formFill, formFillSuggestions, formFillSmartPaste, formFillFiles, nlSearch, m365
+ // -> 0 = Default (defer to the platform), 1 = Off, 2 = On
+ // nlChart -> 0 = Off, 1 = Auto (its platform default), 2 = On
+ // The build writes `true` as 2 for every feature and `false` as that setting's Off — 1, or 0 for
+ // nlChart. (Before AB#6714731 it wrote 1 for `true` outside the form-fill family, which is Off for
+ // nlSearch and m365 and only Auto for nlChart.)
+ // An explicit integer (0-1000000) is written verbatim, e.g. to choose the platform default; the
+ // bound mirrors the SDK's own, so an out-of-range value is rejected here rather than aborting the
+ // build half-applied.
//
// These write PER-APP settings, which are distinct from the org-level admin gates the build
// preflights. The gate is NOT a precondition: every write is attempted and then verified, and a
@@ -1155,10 +1234,10 @@ entirely optional; omitting it leaves every AI feature at its platform default.
// DISABLING is treated identically — a `false` is written whatever the gate says, which is why an
// incorrect `false` is the more damaging mistake of the two.
"appFeatures": {
- "formFill": true, // Copilot-assisted form fill (data entry)
- "nlSearch": true, // natural-language grid/view search (data exploration)
- "nlChart": 2, // natural-language chart / AI data visualization — on for everyone
- "m365": false // M365 Copilot integration (opt-in; defaults false)
+ "formFill": true, // Copilot-assisted form fill (data entry) — writes 2 (On)
+ "nlSearch": true, // natural-language grid/view search (data exploration) — writes 2 (On)
+ "nlChart": 1, // natural-language chart / AI data visualization — 1 = Auto, the platform decides
+ "m365": false // M365 Copilot integration — writes 1 (Off); by default it is left at 0 (Default)
},
// summaries: configure the row-summary (Copilot summary card) feature per table.
"summaries": {
@@ -1205,9 +1284,9 @@ auto-selects tables that are good row-summary candidates and skips those that ar
> rule described below as enforced by the *lint* is one an unlinted spec will carry into a
> build and fail at the platform. Where it matters, the rule names its gate.
-- `ai.appFeatures` keys must be one of `formFill · nlSearch · nlChart · m365`; values must be a boolean or an integer between `0` and `1000000` (hard error) — the same range the SDK enforces, so an out-of-range value is rejected here rather than aborting the build half-applied. The boolean spelling is **not** a flat `1`/`0`: the **form-fill family** (`formFill` and its siblings) writes `2` for `true` and **`1` for `false`**, where `1` means *disabled* and `0` means *platform default*; `nlSearch`/`nlChart`/`m365` write `1`/`0`. Use an explicit integer for a platform value like "on for everyone".
-- **`false` is not "leave alone".** It writes an app-scope override that beats the org value, and unlike enabling it is **not** gated — so `false` on a feature the org has enabled will turn that feature off for this app. To inherit the environment's setting, omit `ai.appFeatures` entirely.
-- Omitting `ai.appFeatures` does **not** mean "no AI features": a spec carrying any `ai` block gets the defaults `formFill · nlSearch · nlChart` on and `m365` off, and `--verify` reconciles that whole resolved set.
+- `ai.appFeatures` keys must be one of `formFill · formFillSuggestions · formFillSmartPaste · formFillFiles · nlSearch · nlChart · m365`; values must be a boolean or an integer between `0` and `1000000` (hard error) — the same range the SDK enforces, so an out-of-range value is rejected here rather than aborting the build half-applied. The boolean spelling is **not** a flat `1`/`0`: `true` writes `2` (*On*) for every feature, and `false` writes that setting's *Off* — `1` for most, but **`0` for `nlChart`**, whose `1` means *Auto*. `0` means *Default* (defer to the platform) everywhere except `nlChart`. Use an explicit integer for any other state, such as the platform default.
+- **`false` is not "leave alone".** It writes an app-scope override that beats the org value, and unlike enabling it is **not** gated — so `false` on a feature the org has enabled will turn that feature off for this app. To defer a feature to the platform, give it the setting's platform-default value instead (`0`, or `1` for `nlChart`).
+- Omitting `ai.appFeatures` does **not** mean "no AI features": a spec carrying any `ai` block gets the defaults `formFill · nlSearch · nlChart` on (`2`) and `m365` left at its platform default (`0`), and `--verify` reconciles that whole resolved set.
- `ai.summaries.default` must be `"auto"` or `"off"` (hard error).
- `ai.summaries.tables` keys must match a declared entity `schemaName` (case-insensitive, hard error).
- `columns[]` entries must be declared column `schemaName` values on that entity (hard error in both validate and lint).
diff --git a/plugins/model-apps/scripts/ai-preflight.js b/plugins/model-apps/scripts/ai-preflight.js
index 0996fce14..992f9722b 100644
--- a/plugins/model-apps/scripts/ai-preflight.js
+++ b/plugins/model-apps/scripts/ai-preflight.js
@@ -74,28 +74,38 @@ function runPreflight(readiness, effective = {}) {
for (const [key, meta] of Object.entries(FEATURE_META)) {
const f = readiness[key];
if (!f) continue;
+ // Where a feature's readiness gate IS its own per-app setting (the form-fill toolbar,
+ // predictions, files, and M365), the SDK decides `enabled` with its own codec, which — as
+ // vendored — knows only the form-fill family's scale, so M365's Off (`1`) reads as enabled.
+ // Read that value through this plugin's codec instead. A gate that is a different row (NL search,
+ // NL charts, smart paste, summaries) is a boolean the SDK already reads correctly, so it keeps
+ // the SDK's answer.
+ const enabled = f.setting === AI_APP_SETTING[key] && f.value !== undefined && f.value !== null
+ ? settingIsOn(f.value, key) === true
+ : f.enabled;
const eff = effective[key] || {};
// Only a POSITIVE reading counts. `eff.error` (could not look, or the setting is not
// provisioned here) must never be read as "in effect" — that would suppress a real admin action.
const inEffect = eff.on === true;
// "Platform default" is a SPECIFIC state, not a synonym for "we could not decide". Only a
- // codec-governed feature sitting at its default value ('0') defers to flighting; an
- // unrecognised value like '3' or 'yes' is simply indeterminate, and calling that "the platform
- // decides" would invent a fact. Both suppress the ✓/✗ claim, but only one earns the explanation.
+ // codec-governed feature sitting at its own platform-default value ('0' for most, '1' — Auto —
+ // for charts) defers to the platform; an unrecognised value like '3' or 'yes' is simply
+ // indeterminate, and calling that "the platform decides" would invent a fact. Both suppress the
+ // ✓/✗ claim, but only one earns the explanation.
const codec = AI_SETTING_CODEC[key];
const effectiveDefault = eff.on === undefined && !eff.error && codec
- && eff.value !== undefined && String(eff.value).trim() === '0';
+ && eff.value !== undefined && String(eff.value).trim() === codec.platformDefault;
const effectiveIndeterminate = eff.on === undefined && !eff.error && eff.value !== undefined && !effectiveDefault;
features.push({
feature: key,
- enabled: f.enabled,
+ enabled,
setting: f.setting,
...(eff.value !== undefined ? { effectiveValue: eff.value, effectiveScope: eff.scope } : {}),
...(inEffect ? { inEffect: true } : {}),
...(effectiveDefault ? { effectiveDefault: true } : {}),
...(effectiveIndeterminate ? { effectiveIndeterminate: true } : {}),
});
- if (!f.enabled && !inEffect) {
+ if (!enabled && !inEffect) {
adminActions.push(meta.action(f));
}
}
@@ -103,6 +113,29 @@ function runPreflight(readiness, effective = {}) {
return { features, adminActions };
}
+/**
+ * One feature's line of the readiness report. "Not enabled" is not one state, so there are four:
+ * ✓ in effect through a setting the readiness gate does not read; ? at the platform default (the
+ * platform decides); ? a value this plugin does not recognise; otherwise ✓ or ✗ from the gate.
+ */
+function featureLine(f) {
+ const label = FEATURE_META[f.feature]?.label || f.feature;
+ if (f.inEffect && !f.enabled) {
+ // The distinction that matters: running, but not because of anything this app declares.
+ return ` ✓ ${label} (${f.setting}) — in effect via the ${f.effectiveScope} setting (value "${f.effectiveValue}"), though the readiness gate reads off\n`;
+ }
+ if (f.effectiveDefault) {
+ // "Platform default" is not off. `0` (Default) for most of these settings and `1` (Auto) for
+ // charts defer to the platform, so the feature may well be running; printing ✗ would assert
+ // something we cannot see.
+ return ` ? ${label} (${f.setting}) — set to the platform default ("${f.effectiveValue}"), so whether it runs is decided by the platform, not by this environment\n`;
+ }
+ if (f.effectiveIndeterminate) {
+ return ` ? ${label} (${f.setting}) — holds an unrecognised value ("${f.effectiveValue}"), so its state cannot be determined from here\n`;
+ }
+ return ` ${f.enabled ? '✓' : '✗'} ${label} (${f.setting})\n`;
+}
+
async function main() {
const argv = process.argv.slice(2);
const { flags } = parseArgs(argv);
@@ -164,21 +197,7 @@ async function main() {
process.stderr.write('\nAI Feature Readiness\n');
process.stderr.write('====================\n');
- for (const f of report.features) {
- const label = FEATURE_META[f.feature]?.label || f.feature;
- if (f.inEffect && !f.enabled) {
- // The distinction that matters: running, but not because of anything this app declares.
- process.stderr.write(` ✓ ${label} (${f.setting}) — in effect via the ${f.effectiveScope} setting (value "${f.effectiveValue}"), though the readiness gate reads off\n`);
- } else if (f.effectiveDefault) {
- // "Platform default" is not off. For the AI form-fill family `0` means "defer to flighting",
- // so the feature may well be running; printing ✗ would assert something we cannot see.
- process.stderr.write(` ? ${label} (${f.setting}) — set to the platform default ("${f.effectiveValue}"), so whether it runs is decided by service flighting, not by this environment\n`);
- } else if (f.effectiveIndeterminate) {
- process.stderr.write(` ? ${label} (${f.setting}) — holds an unrecognised value ("${f.effectiveValue}"), so its state cannot be determined from here\n`);
- } else {
- process.stderr.write(` ${f.enabled ? '✓' : '✗'} ${label} (${f.setting})\n`);
- }
- }
+ for (const f of report.features) process.stderr.write(featureLine(f));
if (report.adminActions.length) {
process.stderr.write('\nAdmin actions required:\n');
for (const a of report.adminActions) {
@@ -200,7 +219,7 @@ async function main() {
emitResult(true, { ok: true, ...report });
}
-module.exports = { runPreflight };
+module.exports = { runPreflight, featureLine };
if (require.main === module) {
main().catch((err) => {
diff --git a/plugins/model-apps/scripts/build-model-app.js b/plugins/model-apps/scripts/build-model-app.js
index 3d3d8e9d6..cd3d04cbb 100644
--- a/plugins/model-apps/scripts/build-model-app.js
+++ b/plugins/model-apps/scripts/build-model-app.js
@@ -21,11 +21,12 @@ 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.
const { resolveAuthoringLanguage } = require('./lib/entity-provision.js');
-const { createAzHttpClient } = require('./lib/sdk-http-client.js');
-const { parseArgs, validateFlags, readAliasedFlag, readJsonArg, emitResult, dataverseRequest, readProvisionedLanguages, preflightAuth } = require('./lib/dataverse-auth.js');
+const { createAzHttpClient, SQL_DEADLOCK_VICTIM } = require('./lib/sdk-http-client.js');
+const { parseArgs, validateFlags, readAliasedFlag, readJsonArg, emitResult, dataverseRequest, readProvisionedLanguages, preflightAuth, dataverseOrigin } = require('./lib/dataverse-auth.js');
const { openJournal } = require('./lib/build-journal.js');
const { diffPhases, summarizeDiff } = require('./lib/phase-diff.js');
const { annotateContentHashes, pageSourceFileErrors } = require('./lib/content-hash.js');
+const { baselinePath, confinedReader, writeBaseline, readBaseline } = require('./lib/deployed-baseline.js');
const { runChangedOnlyApply, resolveLiveIdentity } = require('./lib/changed-only-flow.js');
const applySnapshotStore = require('./lib/apply-snapshot-store.js');
const { classifyOps, sitemapTargets } = require('./lib/op-diff.js');
@@ -601,6 +602,9 @@ async function buildModelApp(spec, opts, deps) {
authorizedSitemapRemovals,
allowDestructive: opts.allowDestructive, // pages phase gates destructive page removals (Imp6)
changedOnly: opts.changedOnly, // #changed-only: pages-only fast-apply seams (resolvedAppId + skipSitemapFinalize)
+ // AB#6726727: the spec last applied to, or downloaded from, this environment — lets the sitemap
+ // rewrite keep a nav change made in the designer since then instead of reverting it.
+ baselineSpec: opts.baselineSpec,
emit,
});
break;
@@ -671,7 +675,7 @@ async function buildModelApp(spec, opts, deps) {
// written and every later run would fall back to a full build. Without the second, the
// `--changed-only` FAST path (which runs `phases: ['pages']`, so it produces no skip list
// at all) fails the same way on every run after the first.
- const vr = await deps.verify(spec, { environmentSkipped: r.skipped, phases: opts.phases });
+ const vr = await deps.verify(spec, { environmentSkipped: r.skipped, phases: opts.phases, baselineSpec: opts.baselineSpec });
const present = vr.checks.length - vr.missing.length;
log(`\n${vr.ok ? '✓ verify PASS' : `✗ verify FAIL — ${vr.missing.length} missing`} (${present}/${vr.checks.length} present)`);
// Named explicitly rather than folded into the pass, so a green verify never reads as
@@ -767,7 +771,10 @@ function isTransientHalt(err) {
return (
status === 429 ||
status === 503 ||
- /CustomizationLockException|another solution (install|removal)|try again later|SQL timeout|concurrent [dD]elete/i.test(msg)
+ /CustomizationLockException|another solution (install|removal)|try again later|SQL timeout|concurrent [dD]elete/i.test(msg) ||
+ // A SQL deadlock victim was rolled back, so the idempotent build can simply run again — the same
+ // footing as the "SQL timeout" above, with a less ambiguous outcome (see SQL_DEADLOCK_VICTIM).
+ SQL_DEADLOCK_VICTIM.test(msg)
);
}
@@ -824,6 +831,32 @@ function assertSnapshotInvalidated(store, workspaceDir) {
return inv;
}
+// #3: after a clean apply, persist the applied spec so the NEXT dry-run can diff against it and show
+// what changed. Only on a real, successful, FULL apply, OR a changed-only fast apply (whose deployed
+// state matches the spec: unchanged artifacts persist idempotently and the changed pages were just
+// re-uploaded). A partial --stage data apply is NOT the whole desired state, so it must not overwrite
+// the snapshot. Gated on EFFECTIVE success (verify passed) — a build that applied but whose auto-verify
+// found a silent partial must NOT record its spec as the deployed baseline (Sol #13). Best-effort:
+// returns whether the baseline was written, and never throws.
+//
+// The spec is persisted ANNOTATED with on-disk content hashes (#2) so the next dry-run's diff can
+// detect a .tsx / contentPath byte edit, not just a spec-JSON change. It records the content that was
+// actually deployed by THIS apply, stamped with the environment and app it was deployed to, and the
+// dashboard/page ids this apply resolved there (AB#6726727: the sitemap baseline lines entries up by
+// them, and a spec downloaded elsewhere carries another environment's). `write` is a test seam.
+function persistAppliedBaseline(r, { spec, opts, workspaceDir, appDirAbs, baselineIdentity }, write = writeBaseline) {
+ const fullPhaseApply = (opts.phases || PHASES).length === PHASES.length;
+ const changedOnlyApplied = !!(r && r.changedOnly && (r.changedOnly.decision === 'fast' || r.changedOnly.decision === 'full'));
+ const effectiveSuccess = !!(r && r.ok && (!r.verify || r.verify.ok));
+ if (!(effectiveSuccess && opts.apply && !r.dryRun && (fullPhaseApply || changedOnlyApplied))) return false;
+ try {
+ write(workspaceDir, spec, { appDir: appDirAbs, ...baselineIdentity, created: r.created, previous: opts.baselineSpec });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
async function main() {
const argv = process.argv.slice(2);
const { positional, flags } = parseArgs(argv);
@@ -958,23 +991,16 @@ async function main() {
// #3 (track the diff): on a DRY-RUN, if a prior apply left a snapshot, report which phases changed
// since — so a small edit is visibly "only pages changed", not a re-read of the whole plan. Advisory
// only (it does not yet gate --apply; see docs/app-builder-capabilities.md). Never fatal.
- const lastAppliedPath = path.join(workspaceDir, 'last-applied.json');
+ const lastAppliedPath = baselinePath(workspaceDir);
// #2 (content-aware diff): resolve a page codeFile / web-resource contentPath the SAME way the build
- // engine does — relative to the app folder (opts.appDir) — and return its bytes, or null when it can't
- // be read. Confined to appDir: a '..'-escaping or absolute path (already rejected at spec-validation
- // time) resolves outside and returns null rather than reading an arbitrary file. A null result makes
- // annotateContentHashes emit __contentSha:null, so an unreadable/vanished source reads as CHANGED
- // (fail-closed) instead of a silent no-op. Bytes are read raw (Buffer) so the hash matches regardless
- // of encoding; the diff only cares whether the bytes changed, not how they decode.
+ // engine does — relative to the app folder (opts.appDir) — confined to it (deployed-baseline.js).
const appDirAbs = path.resolve(opts.appDir || '.');
- const readContent = (relPath) => {
- try {
- const abs = path.resolve(appDirAbs, relPath);
- const rel = path.relative(appDirAbs, abs);
- if (rel === '..' || rel.startsWith('..' + path.sep) || path.isAbsolute(rel)) return null;
- return fs.readFileSync(abs);
- } catch { return null; }
- };
+ const readContent = confinedReader(appDirAbs);
+ // The environment and app a baseline must describe to count (see deployed-baseline.js).
+ const baselineIdentity = { environment: dataverseOrigin(env), appUniqueName: appUniqueName(spec) };
+ // AB#6726727: the same snapshot is the sitemap rewrite's baseline. Read BEFORE the apply, which
+ // replaces it on success; a missing or mismatched one just means the spec wins and the build says so.
+ if (opts.apply) opts.baselineSpec = readBaseline(workspaceDir, baselineIdentity) || undefined;
if (!opts.apply) {
try {
if (fs.existsSync(lastAppliedPath)) {
@@ -1045,21 +1071,7 @@ async function main() {
} finally {
cleanup();
}
- // #3: after a clean apply, persist the applied spec so the NEXT dry-run can diff against it and show
- // what changed. Only on a real, successful, FULL apply, OR a changed-only fast apply (whose deployed
- // state matches the spec: unchanged artifacts persist idempotently and the changed pages were just
- // re-uploaded). A partial --stage data apply is NOT the whole desired state, so it must not overwrite
- // the snapshot. Gated on EFFECTIVE success (verify passed) — a build that applied but whose auto-verify
- // found a silent partial must NOT record its spec as the deployed baseline (Sol #13). Best-effort.
- const fullPhaseApply = (opts.phases || PHASES).length === PHASES.length;
- const changedOnlyApplied = !!(r && r.changedOnly && (r.changedOnly.decision === 'fast' || r.changedOnly.decision === 'full'));
- const effectiveSuccess = r.ok && (!r.verify || r.verify.ok);
- if (effectiveSuccess && opts.apply && !r.dryRun && (fullPhaseApply || changedOnlyApplied)) {
- // Persist the applied spec ANNOTATED with on-disk content hashes (#2) so the next dry-run's diff can
- // detect a .tsx / contentPath byte edit, not just a spec-JSON change. Records the content that was
- // actually deployed by THIS apply.
- try { fs.writeFileSync(lastAppliedPath, JSON.stringify(annotateContentHashes(spec, readContent))); } catch { /* non-fatal */ }
- }
+ persistAppliedBaseline(r, { spec, opts, workspaceDir, appDirAbs, baselineIdentity });
// emitResult() calls process.exit(), so emit AFTER cleanup() has run. A build that applied cleanly
// but whose auto-verify found missing artifacts exits NON-ZERO (the silent-partial signal R3 exists
// to raise), while r still carries the full build + verify detail.
@@ -1070,4 +1082,4 @@ async function main() {
if (require.main === module) {
main().catch((err) => emitResult(false, err));
}
-module.exports = { buildModelApp, planFor, isTransientHalt, checkCollisions, discoverOpDiffState, envTruthy, parseLanguageCode, assertSnapshotInvalidated };
+module.exports = { buildModelApp, planFor, isTransientHalt, checkCollisions, discoverOpDiffState, envTruthy, parseLanguageCode, assertSnapshotInvalidated, persistAppliedBaseline };
diff --git a/plugins/model-apps/scripts/download-model-app.js b/plugins/model-apps/scripts/download-model-app.js
index ff05c74d9..a01bf6fde 100644
--- a/plugins/model-apps/scripts/download-model-app.js
+++ b/plugins/model-apps/scripts/download-model-app.js
@@ -8,8 +8,10 @@
// Usage: node download-model-app.js --env <orgUrl> --app <appId|uniqueName|displayName> --out <dir> [--allow-lossy-download]
const fs = require('node:fs');
+const os = require('node:os');
const path = require('node:path');
-const { parseArgs, validateFlags, emitResult, preflightAuth } = require('./lib/dataverse-auth.js');
+const { parseArgs, validateFlags, emitResult, preflightAuth, dataverseOrigin } = require('./lib/dataverse-auth.js');
+const { writeBaseline } = require('./lib/deployed-baseline.js');
const { createAzHttpClient } = require('./lib/sdk-http-client.js');
const { hydrateSpec, descriptionFromDataverse, withDescription } = require('./lib/hydrate-spec.js');
const { makeGenpageCli } = require('./lib/genpage-cli.js');
@@ -366,13 +368,32 @@ function relationshipsSkippedWarning(skipped) {
return `${lines.join('\n')}\n`;
}
-async function makeProvision(env, workspaceDir) {
- const { createMakerSdk, createNodeWorkspaceStorage } = require('./vendor/cds-maker-sdk.cjs');
- const httpClient = createAzHttpClient(env);
- fs.mkdirSync(workspaceDir, { recursive: true });
- const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(workspaceDir), instanceUrl: env, httpClient });
- await sdk.initWorkspace();
- return sdk;
+// The SDK a download reads through, on a THROWAWAY workspace that is removed afterwards — never the
+// output folder's `.maker-workspace`, which is the workspace a later build in that folder uses. A
+// download must describe what is DEPLOYED, and reading through that workspace could not promise it: a
+// copy an interrupted build left holding unpushed edits made the SDK throw LOCAL_EDITS_WOULD_BE_LOST
+// once the server had moved (the download failed), and was returned as if it were the app when the
+// server had not (the download silently described edits that were never deployed). Nothing a download
+// fetches is of use to the next build either: its plain fetch replaces a clean copy with the server's.
+//
+// Construction happens INSIDE the guard: the constructor builds the filesystem adapter and can throw,
+// and the caller's `finally` is not reachable until this function returns (as in build-model-app.js).
+// `deps` is a test seam: the bundle's factories, the HTTP client, and the temp-directory calls.
+async function makeDownloadSdk(env, deps = {}) {
+ const workspaceDir = (deps.mkdtempSync || fs.mkdtempSync)(path.join(os.tmpdir(), 'model-app-download-'));
+ const cleanup = () => (deps.rmSync || fs.rmSync)(workspaceDir, { recursive: true, force: true });
+ try {
+ const { createMakerSdk, createNodeWorkspaceStorage } = (deps.createMakerSdk && deps.createNodeWorkspaceStorage)
+ ? deps
+ : require('./vendor/cds-maker-sdk.cjs');
+ const httpClient = deps.httpClient || (deps.createHttpClient || createAzHttpClient)(env);
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(workspaceDir), instanceUrl: env, httpClient });
+ await sdk.initWorkspace();
+ return { sdk, workspaceDir, cleanup };
+ } catch (err) {
+ cleanup();
+ throw err;
+ }
}
// Resolve `--app` to an app GUID. Accepts the app's id, its immutable `uniquename`, or — as a
@@ -2282,8 +2303,21 @@ async function runDownload({ sdk, genpageCli, outDir, appId, appUnique, allowLos
return { ok: true, spec, pages, entities, webResources, droppedSubareas, droppedSubareaDetails, dashboardReconstructionError, dashboardWarnings, notRoundTripped, relationships, relationshipsSkipped, ...(solutionCandidates ? { solutionCandidates } : {}) };
}
-async function main() {
- const argv = process.argv.slice(2);
+async function main(deps = {}) {
+ const argv = deps.argv || process.argv.slice(2);
+ // Test seam: every side effect of main() — the process streams and exit, the result printer, the
+ // auth probe, and the helpers that reach Dataverse or pac — can be replaced. Each call still names the
+ // real function (`io.emitResult(...)`), so a reader, and the source-level contract tests, see which runs.
+ const io = {
+ stderr: deps.stderr || process.stderr,
+ exit: deps.exit || process.exit,
+ emitResult: deps.emitResult || emitResult,
+ preflightAuth: deps.preflightAuth || preflightAuth,
+ makeDownloadSdk: deps.makeDownloadSdk || makeDownloadSdk,
+ makeGenpageCli: deps.makeGenpageCli || makeGenpageCli,
+ runDownload: deps.runDownload || runDownload,
+ validateAppSpec: deps.validateAppSpec || validateAppSpec,
+ };
const { positional, flags } = parseArgs(argv);
const USAGE = 'Usage: node download-model-app.js --env <url> --app <appId|uniqueName|displayName> --out <dir> [--allow-lossy-download]';
// `--allow-lossy-download` is a real boolean switch, so it stays out of needValue; everything else
@@ -2293,16 +2327,18 @@ async function main() {
needValue: ['env', 'app', 'out', 'output'],
});
if (flagError) {
- process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);
- process.exit(1);
+ io.stderr.write(`✗ ${flagError}\n${USAGE}\n`);
+ io.exit(1);
+ return;
}
const env = flags.env;
const appArg = flags.app || positional[0];
const outArg = flags.out || flags.output;
const allowLossyDownload = flags['allow-lossy-download'] === true;
if (!env || !appArg) {
- process.stderr.write(USAGE + '\n');
- process.exit(1);
+ io.stderr.write(USAGE + '\n');
+ io.exit(1);
+ return;
}
const outDir = path.resolve(outArg || '.');
fs.mkdirSync(outDir, { recursive: true });
@@ -2312,73 +2348,93 @@ async function main() {
// not surface as an error here — it degrades to an EMPTY spec: no forms, no views, no columns, and
// guessed primary attributes, reported as a success. That is AB#6686423's symptom, and this is the
// gate that stops it being mistaken for a round-trip gap.
- const auth = await preflightAuth(env);
- if (!auth.ok && !auth.inconclusive) { emitResult(false, { ok: false, error: auth.error }); return; }
+ const auth = await io.preflightAuth(env);
+ if (!auth.ok && !auth.inconclusive) { io.emitResult(false, { ok: false, error: auth.error }); return; }
// An INCONCLUSIVE probe must not block: it goes through a client with a weaker retry policy than
// the one the download itself uses, so a transient 5xx here would otherwise fail a run that would
// have succeeded. Surface it and continue.
- if (auth.inconclusive) process.stderr.write(`⚠ ${auth.error}\n`);
- const sdk = await makeProvision(env, path.join(outDir, '.maker-workspace'));
- const resolved = await resolveAppId(sdk, appArg);
- if (resolved.error) { emitResult(false, { ok: false, error: resolved.error }); return; }
- const appId = resolved.appId;
- // Narrate a display-name match so the operator learns the app's stable identity: the unique name
- // is what every later build/teardown must be given, and it survives a rename of the display name.
- if (resolved.matchedBy === 'displayName') {
- process.stderr.write(`(resolved display name '${appArg}' to app unique name '${resolved.uniqueName}' — prefer the unique name, it is immutable)\n`);
- }
+ if (auth.inconclusive) io.stderr.write(`⚠ ${auth.error}\n`);
+ // Results are only RECORDED inside the guarded region and printed in `finally`, after the throwaway
+ // workspace is removed: the real printer ends the process (emitResult calls process.exit), so a
+ // cleanup placed after it never ran — every download used to leave its temp workspace behind.
+ let session;
+ let outcome = null;
+ const finish = (ok, payload) => { outcome = [ok, payload]; };
+ try {
+ session = await io.makeDownloadSdk(env, deps);
+ const sdk = session.sdk;
+ const resolved = await resolveAppId(sdk, appArg);
+ if (resolved.error) { finish(false, { ok: false, error: resolved.error }); return; }
+ const appId = resolved.appId;
+ // Narrate a display-name match so the operator learns the app's stable identity: the unique name
+ // is what every later build/teardown must be given, and it survives a rename of the display name.
+ if (resolved.matchedBy === 'displayName') {
+ io.stderr.write(`(resolved display name '${appArg}' to app unique name '${resolved.uniqueName}' — prefer the unique name, it is immutable)\n`);
+ }
- // Resolve the app's unique name early — needed for fetchSitemap (MEMBERSHIP) + manifest lookup.
- const appRows = await sdk.queryRecords('appmodule', { select: ['uniquename'], filter: `appmoduleid eq ${appId}`, top: 1 });
- const appUnique = appRows && appRows[0] && appRows[0].uniquename;
- const genpageCli = makeGenpageCli(env);
-
- const result = await runDownload({ sdk, genpageCli, outDir, appId, appUnique, allowLossy: allowLossyDownload });
- if (!result.ok) { emitResult(false, result); return; }
-
- const { spec, pages, entities, webResources, droppedSubareas, droppedSubareaDetails, dashboardReconstructionError, dashboardWarnings, notRoundTripped, solutionCandidates } = result;
- if (droppedSubareas > 0 || dashboardReconstructionError) {
- const droppedList = (droppedSubareaDetails || [])
- .map((d) => `${d.type}${d.id ? `:${d.id}` : ''}${d.title ? ` (${d.title})` : ''}`)
- .join(', ');
- const dashboardMessage = dashboardReconstructionError ? ` Dashboard reconstruction failed: ${dashboardReconstructionError}.` : '';
- // Per-dashboard reasons, when there are any. Naming the subarea without saying WHY it dropped
- // sends the reader looking at their sitemap when the cause is an unreadable artifact.
- const causeMessage = (dashboardWarnings && dashboardWarnings.length)
- ? ` Cause: ${dashboardWarnings.join('; ')}.`
- : '';
- const message = `${droppedSubareas} sitemap subarea(s) could not be round-tripped${droppedList ? `: ${droppedList}` : ''}.${dashboardMessage}${causeMessage} A rebuild from this spec will DROP them from the app nav.`;
- if (!allowLossyDownload) {
- process.stderr.write(`ERROR: ${message}\nPass --allow-lossy-download to write the partial spec anyway.\n`);
- emitResult(false, { ok: false, error: message, droppedSubareas, droppedSubareaDetails, dashboardReconstructionError, ...(dashboardWarnings && dashboardWarnings.length ? { dashboardWarnings } : {}) });
+ // Resolve the app's unique name early — needed for fetchSitemap (MEMBERSHIP) + manifest lookup.
+ const appRows = await sdk.queryRecords('appmodule', { select: ['uniquename'], filter: `appmoduleid eq ${appId}`, top: 1 });
+ const appUnique = appRows && appRows[0] && appRows[0].uniquename;
+ const genpageCli = io.makeGenpageCli(env);
+
+ const result = await io.runDownload({ sdk, genpageCli, outDir, appId, appUnique, allowLossy: allowLossyDownload });
+ if (!result.ok) { finish(false, result); return; }
+
+ const { spec, pages, entities, webResources, droppedSubareas, droppedSubareaDetails, dashboardReconstructionError, dashboardWarnings, notRoundTripped, solutionCandidates } = result;
+ if (droppedSubareas > 0 || dashboardReconstructionError) {
+ const droppedList = (droppedSubareaDetails || [])
+ .map((d) => `${d.type}${d.id ? `:${d.id}` : ''}${d.title ? ` (${d.title})` : ''}`)
+ .join(', ');
+ const dashboardMessage = dashboardReconstructionError ? ` Dashboard reconstruction failed: ${dashboardReconstructionError}.` : '';
+ // Per-dashboard reasons, when there are any. Naming the subarea without saying WHY it dropped
+ // sends the reader looking at their sitemap when the cause is an unreadable artifact.
+ const causeMessage = (dashboardWarnings && dashboardWarnings.length)
+ ? ` Cause: ${dashboardWarnings.join('; ')}.`
+ : '';
+ const message = `${droppedSubareas} sitemap subarea(s) could not be round-tripped${droppedList ? `: ${droppedList}` : ''}.${dashboardMessage}${causeMessage} A rebuild from this spec will DROP them from the app nav.`;
+ if (!allowLossyDownload) {
+ io.stderr.write(`ERROR: ${message}\nPass --allow-lossy-download to write the partial spec anyway.\n`);
+ finish(false, { ok: false, error: message, droppedSubareas, droppedSubareaDetails, dashboardReconstructionError, ...(dashboardWarnings && dashboardWarnings.length ? { dashboardWarnings } : {}) });
+ return;
+ }
+ io.stderr.write(`WARNING: ${message}\n`);
+ }
+ // `reconstructed: true` — this spec was rebuilt from a DEPLOYED app, not authored. Authoring-only
+ // rules become warnings, because refusing to write a description of an app that already exists
+ // leaves the author with no artifact at all (see the pageInput producer rule).
+ const validation = io.validateAppSpec(spec, { profile: 'plan', reconstructed: true });
+ if (!validation.ok) {
+ finish(false, { ok: false, error: 'downloaded App Spec failed validation', errors: validation.errors });
return;
}
- process.stderr.write(`WARNING: ${message}\n`);
- }
- // `reconstructed: true` — this spec was rebuilt from a DEPLOYED app, not authored. Authoring-only
- // rules become warnings, because refusing to write a description of an app that already exists
- // leaves the author with no artifact at all (see the pageInput producer rule).
- const validation = validateAppSpec(spec, { profile: 'plan', reconstructed: true });
- if (!validation.ok) {
- emitResult(false, { ok: false, error: 'downloaded App Spec failed validation', errors: validation.errors });
- return;
- }
- for (const w of validation.warnings || []) process.stderr.write(`WARNING: ${w}\n`);
- // A defaulted `directEntry` must not be silent. hydrateSpec injects a conservative `emptyState` for
- // pages that predate the field (otherwise this download would have hard-failed above and written no
- // spec at all), but the author has to know a behaviour was chosen for them so they can change it.
- const defaulted = spec.directEntryDefaulted || [];
- if (defaulted.length) {
- process.stderr.write(
- `WARNING: ${defaulted.length} page(s) declare pageInput but predate directEntry — defaulted to `
- + `{ "behavior": "emptyState" }: ${defaulted.join(', ')}.\n`
- + ' Review each: change to "selector" if opening the page from the navigation should show a record picker.\n'
- );
+ for (const w of validation.warnings || []) io.stderr.write(`WARNING: ${w}\n`);
+ // A defaulted `directEntry` must not be silent. hydrateSpec injects a conservative `emptyState` for
+ // pages that predate the field (otherwise this download would have hard-failed above and written no
+ // spec at all), but the author has to know a behaviour was chosen for them so they can change it.
+ const defaulted = spec.directEntryDefaulted || [];
+ if (defaulted.length) {
+ io.stderr.write(
+ `WARNING: ${defaulted.length} page(s) declare pageInput but predate directEntry — defaulted to `
+ + `{ "behavior": "emptyState" }: ${defaulted.join(', ')}.\n`
+ + ' Review each: change to "selector" if opening the page from the navigation should show a record picker.\n'
+ );
+ }
+ const specPath = path.join(outDir, 'app-spec.json');
+ preserveAuthoredLanguageCode(spec, specPath);
+ fs.writeFileSync(specPath, JSON.stringify(spec, null, 2));
+ // AB#6726727: the spec just written IS this app's deployed state, so it is the baseline a later build
+ // lines the live sitemap up against — a nav change made in the designer after this download is then
+ // kept, not reverted by the now-stale spec. Its dashboard and page ids were read from this
+ // environment, so they are recorded as its deployed ids. Best-effort: a spec with no baseline still
+ // builds, and the build then reports each nav change it makes.
+ try {
+ writeBaseline(path.join(outDir, '.maker-workspace'), spec, { appDir: outDir, environment: dataverseOrigin(env), appUniqueName: appUnique, fromSpec: true });
+ } catch { /* non-fatal */ }
+ finish(true, { ok: true, spec: specPath, pages: pages.length, entities: entities.length, webResources: webResources.length, droppedSubareas, ...(notRoundTripped ? { notRoundTripped } : {}), ...(defaulted.length ? { directEntryDefaulted: defaulted } : {}), ...(solutionCandidates ? { solutionCandidates } : {}) });
+ } finally {
+ try { if (session) session.cleanup(); } catch { /* best-effort: the result below matters more */ }
+ if (outcome) io.emitResult(...outcome);
}
- const specPath = path.join(outDir, 'app-spec.json');
- preserveAuthoredLanguageCode(spec, specPath);
- fs.writeFileSync(specPath, JSON.stringify(spec, null, 2));
- emitResult(true, { ok: true, spec: specPath, pages: pages.length, entities: entities.length, webResources: webResources.length, droppedSubareas, ...(notRoundTripped ? { notRoundTripped } : {}), ...(defaulted.length ? { directEntryDefaulted: defaulted } : {}), ...(solutionCandidates ? { solutionCandidates } : {}) });
}
// Carry an AUTHOR-PINNED `languageCode` across a download, and only from the spec already on disk.
@@ -2419,4 +2475,4 @@ if (require.main === module) {
main().catch((err) => emitResult(false, err));
}
-module.exports = { untypedColumnNames, collectGlobalChoices, finalizeGlobalChoices, roundTrippedAware, isRoleRestrictedFormXml, notRoundTrippedSummary, notRoundTrippedWarning, relationshipsSkippedWarning, labelFromDataverse, columnDisplayName, resolveAppId, collectSitemap, appComponentEntities, parseDownloadedPages, assignPageKeys, missingDownloads, entityFromMetadata, readEntityWithDescriptions, readDescriptionInventory, readAppShellSettings, iconWebResources, readDashboards, readRelationships, droppedSubareaCount, recoverAppSolution, runDownload, preserveAuthoredLanguageCode };
+module.exports = { untypedColumnNames, collectGlobalChoices, finalizeGlobalChoices, roundTrippedAware, isRoleRestrictedFormXml, notRoundTrippedSummary, notRoundTrippedWarning, relationshipsSkippedWarning, labelFromDataverse, columnDisplayName, resolveAppId, collectSitemap, appComponentEntities, parseDownloadedPages, assignPageKeys, missingDownloads, entityFromMetadata, readEntityWithDescriptions, readDescriptionInventory, readAppShellSettings, iconWebResources, readDashboards, readRelationships, droppedSubareaCount, recoverAppSolution, runDownload, preserveAuthoredLanguageCode, makeDownloadSdk, main };
diff --git a/plugins/model-apps/scripts/lib/ai-app-settings.js b/plugins/model-apps/scripts/lib/ai-app-settings.js
index e0e64a840..5e809c5b9 100644
--- a/plugins/model-apps/scripts/lib/ai-app-settings.js
+++ b/plugins/model-apps/scripts/lib/ai-app-settings.js
@@ -42,18 +42,25 @@ const AI_APP_SETTING = {
// ON/OFF values are NOT uniform across these settings, and `1` is not universally "on".
//
-// MIRRORS the SDK's `SETTING_CODEC` (api/AiApi.ts), which cites the first-party admin UI:
-// FormFillBarUXEnabled / formPredictEnabled / smart-paste-on-by-default:
-// 0 = default (defer to flighting) 1 = DISABLED 2 = ENABLED
-// So the obvious `true -> '1'` mapping writes DISABLED for every one of them, and `0` means
-// "platform default", which is NOT the same as off. Settings absent from this table keep the plain
-// numeric convention ('1' on, '0' off) — deliberately, because their semantics are not evidenced
-// the same way.
+// Each value is taken from the platform's own settings UI — the maker designer's tri-state dropdown
+// and the admin center's feature settings — which is the only first-party statement of what the
+// stored numbers mean:
+// FormFillBarUXEnabled, NLGridSearchSetting, m365copilotmodelappenabled — and the rest of the
+// form-fill family — use the shared tri-state dropdown: 0 = Default, 1 = Off, 2 = On.
+// NLChartDataVisualizationSetting is ordered differently: 0 = Off, 1 = Auto, 2 = On, and its
+// setting definition's default value is 1.
+// So the obvious `true -> '1'` writes Off for grid search and M365, and only Auto for charts —
+// which is what every build wrote until AB#6714731, while `--verify` agreed, because it expected
+// the same wrong values. `platformDefault` is the value that defers to the platform; it is neither
+// on nor off, and it differs by setting.
const AI_SETTING_CODEC = {
- formFill: { enabled: '2', disabled: '1' },
- formFillSuggestions: { enabled: '2', disabled: '1' },
- formFillSmartPaste: { enabled: '2', disabled: '1' },
- formFillFiles: { enabled: '2', disabled: '1' },
+ formFill: { enabled: '2', disabled: '1', platformDefault: '0' },
+ formFillSuggestions: { enabled: '2', disabled: '1', platformDefault: '0' },
+ formFillSmartPaste: { enabled: '2', disabled: '1', platformDefault: '0' },
+ formFillFiles: { enabled: '2', disabled: '1', platformDefault: '0' },
+ nlSearch: { enabled: '2', disabled: '1', platformDefault: '0' },
+ nlChart: { enabled: '2', disabled: '0', platformDefault: '1' },
+ m365: { enabled: '2', disabled: '1', platformDefault: '0' },
};
// Derived, never hand-maintained: the validator's allow-list IS the set of features we can write.
@@ -64,10 +71,12 @@ const AI_FEATURE_KEYS = new Set(Object.keys(AI_APP_SETTING));
// same bound turns a mid-build abort into an up-front spec error naming the offending field.
const AI_FEATURE_MAX_VALUE = 1000000;
-// What the build requests when a spec opts into `ai` without naming a feature. `m365` is off by
-// default because it surfaces the app inside M365 Copilot, which is a deliberate choice rather
-// than a sensible default.
-const DEFAULT_APP_FEATURES = { formFill: true, nlSearch: true, nlChart: true, m365: false };
+// What the build requests when a spec opts into `ai` without naming a feature. `m365` is not turned
+// on by default, because it surfaces the app inside M365 Copilot, which is a deliberate choice rather
+// than a sensible default. Nor is it forced off: it gets `0` (Default), the app-scope value every
+// default build has written. That is still an override — the app gets the platform's default, not
+// the environment's value — and an explicit `false` writes Off instead.
+const DEFAULT_APP_FEATURES = { formFill: true, nlSearch: true, nlChart: true, m365: 0 };
/**
* Does this spec opt into AI at all?
@@ -109,14 +118,12 @@ function resolveAiFlags(spec) {
/**
* Normalize a requested flag to the string the setting actually stores.
*
- * `true`/`false` are ergonomic spellings, but what they MEAN is per setting: for the AI form-fill
- * family on is `'2'` and off is `'1'` (`'0'` is the platform default, not off), while everything else
- * keeps the plain `'1'`/`'0'` convention. Any explicit integer is used verbatim.
+ * `true`/`false` are ergonomic spellings, but what they MEAN is per setting (see AI_SETTING_CODEC):
+ * on is `'2'` for every feature, while off is `'1'` for most and `'0'` for `nlChart`. Any explicit
+ * integer is used verbatim.
*
- * `feature` is required for a codec-governed setting. Without it a boolean maps to `'1'`, which for
- * the form-fill family means DISABLED — and since the build writes through the SDK (which applies
- * the codec), a verifier using the wrong spelling reports a correctly-applied feature as missing.
- * That mismatch is the reason this takes a feature at all.
+ * `feature` is required. Without it a boolean falls back to the plain `'1'`/`'0'`, which is wrong for
+ * every setting here — a verifier using that spelling reports a correctly-applied feature as missing.
*/
function featureWantValue(requested, feature) {
if (typeof requested !== 'boolean') return String(requested).trim();
@@ -125,21 +132,75 @@ function featureWantValue(requested, feature) {
return requested ? '1' : '0';
}
+/**
+ * The flags the build hands `setAppAiFeatures`, with every boolean already encoded to the value the
+ * setting stores. The SDK passes an explicit value through unchanged, but maps a boolean through its
+ * own codec, which (as of the vendored bundle) covers only the form-fill family and writes `'1'` for
+ * `true` everywhere else. Encoding here keeps what is written, and what `--verify` expects, in one
+ * table: this module's.
+ */
+function encodeAiFlags(flags) {
+ if (!flags) return flags;
+ const out = {};
+ for (const [feature, requested] of Object.entries(flags)) out[feature] = featureWantValue(requested, feature);
+ return out;
+}
+
+/**
+ * Move the SDK's `skipped` verdicts that are not ENABLES to `notPersisted`, rewriting their reasons.
+ *
+ * `skipped` means "no override appeared, and the feature's org gate reads off", and its reason tells
+ * an admin to enable the feature "before this app can turn the feature on". The vendored SDK only
+ * reaches for the gate when it thinks the request enables the feature — and it decides that with a
+ * codec that knows only the form-fill family, so any non-zero value counts. A correctly encoded Off
+ * for grid search or M365 (`'1'`) therefore came back telling the admin to switch the feature ON.
+ * A gate that governs turning a feature on cannot explain why a request that does not turn it on was
+ * not stored, so that request is simply not persisted.
+ *
+ * `encodedFlags` is what the build sent (see encodeAiFlags). Mutates and returns `result`.
+ */
+function rebucketNonEnablingSkips(result, encodedFlags) {
+ if (!result || !Array.isArray(result.skipped) || !result.skipped.length) return result;
+ const enables = (feature) => {
+ const codec = AI_SETTING_CODEC[feature];
+ // A feature this module has no codec for keeps the SDK's verdict: there is no table to say otherwise.
+ return !codec || String(encodedFlags && encodedFlags[feature]).trim() === codec.enabled;
+ };
+ const moved = result.skipped.filter((f) => !enables(f));
+ if (!moved.length) return result;
+ result.skipped = result.skipped.filter(enables);
+ result.notPersisted = [...(Array.isArray(result.notPersisted) ? result.notPersisted : []), ...moved];
+ for (const o of result.outcomes || []) {
+ if (!o || !moved.includes(o.feature)) continue;
+ const value = o.requestedValue !== undefined ? o.requestedValue : encodedFlags[o.feature];
+ o.status = 'notPersisted';
+ o.reason = `the write reported success but no app-scope override holding '${value}' was observed for '${o.setting || AI_APP_SETTING[o.feature]}' (Dataverse can accept an app-scope write without storing it); the feature's org gate reads off, but it governs turning the feature on, which this request does not`;
+ }
+ return result;
+}
+
/**
* Compare a stored setting value against a requested one.
*
* Deliberately NOT dependent on the setting's `dataType`. A Dataverse Boolean setting (dataType 2)
- * reports `'true'`/`'false'` rather than `'1'`/`'0'`, so the two spellings must be reconciled — but
+ * reports `'true'`/`'false'` rather than a number, so the two spellings must be reconciled — but
* branching on a dataType read makes the comparison depend on a SECOND request that can fail
* independently, which silently turned a correctly-applied feature into a FAIL when that read
* errored. Normalizing both sides unconditionally is a no-op for the numeric values these settings
- * actually store (live: the override rows hold '1'/'0'), while still accepting the boolean
+ * actually store (live: the override rows hold '0'/'1'/'2'), while still accepting the boolean
* spelling — so it is strictly safer and has no hidden dependency.
+ *
+ * Pass `feature` whenever it is known: a Boolean spelling then means that feature's own on/off
+ * value. Without it, `'true'`/`'false'` fall back to `'1'`/`'0'` — which for every per-app AI setting
+ * would equate `'true'` with Off.
*/
-function sameSettingValue(a, b) {
+function sameSettingValue(a, b, feature) {
+ const codec = feature && AI_SETTING_CODEC[feature];
const onOff = (v) => {
const s = String(v === undefined || v === null ? '' : v).trim().toLowerCase();
- return s === 'true' ? '1' : s === 'false' ? '0' : s;
+ if (s === 'true') return codec ? codec.enabled : '1';
+ if (s === 'false') return codec ? codec.disabled : '0';
+ return s;
};
return onOff(a) === onOff(b);
}
@@ -266,10 +327,11 @@ async function effectiveSettingValue(read, appModuleId, setting) {
* Is a setting value "on" FOR THIS FEATURE?
*
* Values are stored as STRINGS ("0"/"1"/"2"/"true"/"false"), so plain JS truthiness is wrong twice
- * over — it calls "0" true and "false" true. Worse, the numeric meaning is not uniform: for the
- * AI form-fill family `1` means DISABLED and `2` means ENABLED, so a "non-zero is on" rule reports a
- * deliberately disabled feature as running. `0` there means "platform default" (defer to flighting),
- * which is genuinely UNKNOWN rather than off — reporting it as off overstates what we know.
+ * over — it calls "0" true and "false" true. Worse, the numeric meaning is not uniform: for most of
+ * these settings `1` means Off and `2` means On, and for `nlChart` `0` is Off and `1` is Auto, so a
+ * "non-zero is on" rule reports a deliberately disabled feature as running. A setting's platform
+ * default (Default, or Auto for charts) defers to the platform, which is genuinely UNKNOWN rather
+ * than off — reporting it as off overstates what we know.
*
* `feature` is optional so existing callers keep the plain numeric convention; pass it whenever the
* feature is known, which is every caller inside this plugin.
@@ -283,7 +345,7 @@ function settingIsOn(value, feature) {
if (codec) {
if (s === codec.enabled) return true;
if (s === codec.disabled) return false;
- // '0' = platform default: not a claim either way.
+ // The platform default (Default, or Auto for charts): not a claim either way.
return undefined;
}
const n = Number(s);
@@ -318,6 +380,8 @@ module.exports = {
specOptsIntoAi,
resolveAiFlags,
featureWantValue,
+ encodeAiFlags,
+ rebucketNonEnablingSkips,
sameSettingValue,
resolveAppModuleId,
proveAppOverride,
diff --git a/plugins/model-apps/scripts/lib/app-spec.js b/plugins/model-apps/scripts/lib/app-spec.js
index 82dfc67c4..033848a9d 100644
--- a/plugins/model-apps/scripts/lib/app-spec.js
+++ b/plugins/model-apps/scripts/lib/app-spec.js
@@ -3,6 +3,7 @@
const path = require('node:path');
const { normalizeSpecShape } = require('./spec-shape.js');
+const { isMainForm, selectDefaultForm, ordersByHand } = require('./form-order.js');
// URL scheme allowlist for spec-supplied URLs that the built app will RENDER (iframe dashboard tiles,
// sitemap URL subareas). Only http(s) is allowed — a `javascript:`, `data:`, `vbscript:`, or `file:`
@@ -33,7 +34,7 @@ const FORM_GUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{
// PrivilegeScope depth, least->most permissive (user->Basic … organization->Global)
// Keep these in lockstep with the SDK; vendor-sdk-smoke asserts the vendored bundle still exposes them.
const ACCESS_LEVELS = new Set(['read', 'create', 'write', 'delete', 'append', 'appendTo', 'assign', 'share']);
-const { AI_FEATURE_KEYS, AI_FEATURE_MAX_VALUE } = require('./ai-app-settings.js');
+const { AI_FEATURE_KEYS, AI_FEATURE_MAX_VALUE, AI_SETTING_CODEC } = require('./ai-app-settings.js');
const PRIVILEGE_SCOPES = new Set(['user', 'businessUnit', 'parentChild', 'organization']);
// The exact ownership marker the vendored SDK (cds-maker-sdk SecurityApi) stamps on the `description`
@@ -652,7 +653,7 @@ const ENTITY_KEYS = new Set([
'schemaName', 'displayName', 'pluralName', 'description', 'primaryAttribute', 'columns',
'hasNotes', 'quickCreate', 'existing', 'enrichDefaultViews',
'vectorIcon', 'iconDescription', 'icon',
- 'statusReasons', 'alternateKeys',
+ 'statusReasons', 'alternateKeys', 'mainFormOrder',
]);
// What to write INSTEAD, for the keys an author is most likely to reach for. A bare "unknown key"
@@ -666,6 +667,52 @@ const ENTITY_KEY_HINTS = Object.assign(Object.create(null), {
localizedLabels: ' — write the LCID map on the label FIELD itself (e.g. "displayName": { "1033": "Baseline", "3082": "Línea base" }), not in a separate per-table block; see references/app-spec-schema.md → "Localized labels"',
});
+// The keys the build READS on each `appShell` level (appDef, sdk-build.js), for the same reason as
+// ENTITY_KEYS (#537). The levels name their title differently — areas and groups take `label`,
+// subareas take `title` — and a key with no reader was accepted and dropped: an area written with
+// `title` deployed untitled while lint, the build and `--verify` all passed (#631). Adding a key here
+// without a reader would re-open that hole. `iconDescription` is read by the icon-authoring step,
+// not the build, and is validated where it is used.
+const APP_SHELL_KEYS = {
+ area: new Set(['label', 'icon', 'vectorIcon', 'iconDescription', 'groups']),
+ group: new Set(['label', 'iconDescription', 'subAreas']),
+ subArea: new Set(['title', 'entity', 'dashboard', 'url', 'page', 'icon', 'vectorIcon', 'iconDescription']),
+};
+// The mix-ups an author is most likely to make, with the fix. Prototype-less for the reason given
+// on ENTITY_KEY_HINTS: the lookup key comes from the spec.
+const LABEL_NOT_TITLE = ' — did you mean `label`? Areas and groups take `label`; only subAreas take `title`';
+const APP_SHELL_KEY_HINTS = {
+ area: Object.assign(Object.create(null), { title: LABEL_NOT_TITLE, subAreas: ' — subAreas belong to a group: areas[].groups[].subAreas' }),
+ group: Object.assign(Object.create(null), {
+ title: LABEL_NOT_TITLE,
+ icon: ' — a sitemap group has no icon; set it on the area or on each subArea',
+ vectorIcon: ' — a sitemap group has no icon; set it on the area or on each subArea',
+ groups: ' — groups belong to an area: areas[].groups',
+ }),
+ subArea: Object.assign(Object.create(null), {
+ label: ' — did you mean `title`? SubAreas take `title`; areas and groups take `label`',
+ table: ' — did you mean `entity`?',
+ }),
+};
+
+// Report every key on one `appShell` node that the build does not read. Guarded like the entity
+// check: a non-object node is reported by the shape checks, and enumerating a caller's object can
+// throw (a Proxy), which must become an error rather than escape the validator.
+function reportUnknownAppShellKeys(node, level, where, errors) {
+ if (!node || typeof node !== 'object' || Array.isArray(node)) return;
+ let keys;
+ try {
+ keys = Object.keys(node);
+ } catch {
+ errors.push(`${where} could not be inspected: enumerating its keys threw`);
+ return;
+ }
+ for (const k of keys) {
+ if (APP_SHELL_KEYS[level].has(k)) continue;
+ errors.push(`${where}: unknown key '${k}'${APP_SHELL_KEY_HINTS[level][k] || ''} (allowed: ${[...APP_SHELL_KEYS[level]].join(', ')})`);
+ }
+}
+
// The column logical names an entity legitimately exposes to a rule / process step: its declared
// columns, its primary name column, and any lookup a relationship creates ON it (a lookup is a real
// column on the referencing table, just declared elsewhere in the spec).
@@ -2047,6 +2094,77 @@ function validateAppSpec(spec, opts = {}) {
}
}
+ // AB#6736948: `entities[].mainFormOrder` — the table's Main Form Set order, first to last. The first
+ // form is the one the table opens with; lib/form-order.js has the platform's model of it and what
+ // was measured. Every name must address exactly one Main form of the table in forms[], because the
+ // build writes the order onto the forms it resolves, and a name it cannot resolve would silently
+ // leave a different form first.
+ for (const e of spec.entities || []) {
+ if (!e || typeof e !== 'object' || e.mainFormOrder === undefined) continue;
+ const label = `entity '${e.schemaName}'`;
+ const list = e.mainFormOrder;
+ if (!Array.isArray(list) || !list.length || list.some((n) => typeof n !== 'string' || !n.trim())) {
+ errors.push(`${label}: mainFormOrder must be a non-empty array of Main form names from forms[] (got ${describeSpecValue(list)})`);
+ continue;
+ }
+ const key = String(e.schemaName || '').toLowerCase();
+ const formsOfEntity = (spec.forms || []).filter((f) => f && typeof f === 'object' && String(f.entity || '').toLowerCase() === key);
+ const mains = formsOfEntity.filter(isMainForm);
+ const seen = new Set();
+ for (const name of list) {
+ // Repeats are compared case-insensitively: Dataverse matches a form name that way, so two
+ // spellings of one name would still be one form.
+ const k = name.trim().toLowerCase();
+ if (seen.has(k)) { errors.push(`${label}: mainFormOrder lists '${name}' more than once`); continue; }
+ seen.add(k);
+ // The build finds a deployed form with a server-side `name eq` filter, which compares names the way
+ // Dataverse does — ignoring case and, in most languages, accents (dashboardNameKey: a dashboard is a
+ // systemform too, so its measured folding is a form name's) — so Main forms whose names compare
+ // equal there are one name to the build, and the order could not address either. The listed name
+ // must still be spelled exactly as in forms[]: it is a cross-reference into this spec, resolved
+ // exactly (listedMainForms, form-order.js).
+ const twins = mains.filter((f) => dashboardNameKey(f.name) === dashboardNameKey(name));
+ const matches = twins.filter((f) => f.name === name);
+ if (twins.length > 1) {
+ const spellings = [...new Set(twins.map((f) => `'${f.name}'`))];
+ errors.push(`${label}: mainFormOrder names '${name}', but ${twins.length} Main forms of this table share that name${spellings.length > 1 ? ` (${spellings.join(', ')}: Dataverse compares form names ignoring case and, in most languages, accents)` : ''} — rename one so the order can address it`);
+ } else if (!matches.length) {
+ const other = formsOfEntity.find((f) => f.name === name);
+ errors.push(other
+ ? `${label}: mainFormOrder names '${name}', a ${other.formType} form — only Main forms are in the Main Form Set`
+ : `${label}: mainFormOrder names '${name}', which is not a Main form of this table in forms[] (its Main forms: ${mains.map((f) => `'${f.name || '(unnamed)'}'`).join(', ') || 'none'})`);
+ }
+ }
+ const flagged = mains.find((f) => f.isDefault === true);
+ if (flagged && list[0] !== flagged.name) {
+ errors.push(`${label}: form '${flagged.name}' sets isDefault, so it must come first in mainFormOrder (which starts with '${list[0]}') — the first form in the order is the one the table opens with`);
+ }
+ const byHand = mains.filter((f) => f.securityRoles && typeof f.securityRoles === 'object' && f.securityRoles.order !== undefined);
+ if (byHand.length) {
+ errors.push(`${label}: mainFormOrder and forms[].securityRoles.order (on ${byHand.map((f) => `'${f.name || f.entity}'`).join(', ')}) both set this table's form order — keep one of them`);
+ }
+ }
+ // `securityRoles.order` writes the same attribute, so a table ordered that way is ordered by hand and
+ // the build leaves it alone — which means the default form opens first only when ITS order is the
+ // lowest. Warned, not rejected: the combination is legal and can be exactly what the author meant.
+ const orderedByHandSeen = new Set();
+ for (const f of spec.forms || []) {
+ if (!isMainForm(f)) continue;
+ const key = String(f.entity || '').toLowerCase();
+ if (orderedByHandSeen.has(key)) continue;
+ orderedByHandSeen.add(key);
+ const entSpec = (spec.entities || []).find((e) => e && String(e.schemaName || '').toLowerCase() === key);
+ if (!ordersByHand(spec, key) || (entSpec && entSpec.mainFormOrder !== undefined)) continue;
+ const chosen = selectDefaultForm(spec, key);
+ if (!chosen) continue;
+ const mine = chosen.form.securityRoles && chosen.form.securityRoles.order;
+ const rivals = (spec.forms || []).filter((o) => o !== chosen.form && isMainForm(o) && String(o.entity || '').toLowerCase() === key
+ && o.securityRoles && Number.isInteger(o.securityRoles.order) && (!Number.isInteger(mine) || o.securityRoles.order <= mine));
+ if (!Number.isInteger(mine) || rivals.length) {
+ warnings.push(`entity '${key}': forms[].securityRoles.order sets this table's form order, so the build does not reorder its Main forms — '${chosen.form.name || key}' opens first only if its securityRoles.order is lower than every other Main form's${rivals.length ? ` (${rivals.map((o) => `'${o.name || key}': ${o.securityRoles.order}`).join(', ')})` : ''}. Or declare entities[].mainFormOrder instead.`);
+ }
+ }
+
// #6: a Main form that sets deactivateOtherMainForms must be the ONLY Main form declared for its
// entity. NOTE the original rationale — "forms build concurrently and every Main form is promoted,
// so a sibling can win the isdefault race" — no longer holds: promotion is now a single serialized
@@ -2520,6 +2638,7 @@ function validateAppSpec(spec, opts = {}) {
const viewTables = entitiesByName(spec.views);
const chartTables = entitiesByName(spec.charts);
const seenDashboardNames = new Map(); // dashboardNameKey → the first dashboard's name as written
+ const seenDashboardIds = new Map(); // pinned dashboardId (bare, lower) → the dashboard's name as written
// The table a name-based chart/list tile shows, or null when it cannot be determined (reported).
const tileTable = (d, t) => {
const tables = viewTables.get(t.view);
@@ -2540,6 +2659,22 @@ function validateAppSpec(spec, opts = {}) {
};
for (const d of spec.dashboards || []) {
if (!d || !d.name) { errors.push('a dashboard is missing a name'); continue; }
+ // A DOWNLOADED dashboard carries its deployed id (edit-snapshot only, like pages[].pageId), which a
+ // rebuild binds to before trying the name. Two entries pinning one id would bind two nav targets
+ // to one dashboard, so each must be a distinct GUID.
+ if (d.dashboardId !== undefined) {
+ // A bare GUID, or one in braces as Dataverse writes it in sitemap XML — both braces or none: an id
+ // with a lone brace is malformed, not one to bind a dashboard to.
+ const raw = typeof d.dashboardId === 'string' ? d.dashboardId.trim() : '';
+ const pin = (/^\{.*\}$/.test(raw) ? raw.slice(1, -1) : raw).toLowerCase();
+ if (!FORM_GUID_RE.test(pin)) {
+ errors.push(`dashboard '${d.name}': dashboardId must be a GUID (got ${JSON.stringify(d.dashboardId)}) — it is the deployed dashboard's id, which a download writes; leave it out of an authored spec`);
+ } else if (seenDashboardIds.has(pin)) {
+ errors.push(`dashboard '${d.name}': has the same dashboardId as dashboard '${seenDashboardIds.get(pin)}' — each entry must pin a different dashboard`);
+ } else {
+ seenDashboardIds.set(pin, d.name);
+ }
+ }
// A sitemap subarea and the build both find a dashboard BY NAME, the build through a server-side
// filter that ignores case (and usually accents), so two names that compare equal there cannot be
// told apart: both subareas resolve to one dashboard and the other silently leaves the nav
@@ -2816,6 +2951,20 @@ function validateAppSpec(spec, opts = {}) {
warnings.push(`${label}: icon reference '${val}' points at a custom web resource ('${wrName}') that is NOT declared in webResources[] — it will render only on an environment that already has it (a rebuild into a fresh env shows a broken icon). Declare that web resource so the build recreates it; a downloaded spec does this automatically.`);
}
};
+ (spec.appShell && spec.appShell.areas || []).forEach((a, ai) => {
+ // Named by whatever the author wrote, so a mistaken `title` still identifies the node it is on.
+ const nodeName = (n, i) => {
+ const v = n && typeof n === 'object' ? (n.label || n.title) : '';
+ return typeof v === 'string' && v.trim() ? `"${v}"` : `#${i + 1}`;
+ };
+ reportUnknownAppShellKeys(a, 'area', `sitemap area ${nodeName(a, ai)}`, errors);
+ ((a && a.groups) || []).forEach((g, gi) => {
+ reportUnknownAppShellKeys(g, 'group', `sitemap group ${nodeName(g, gi)} in area ${nodeName(a, ai)}`, errors);
+ ((g && g.subAreas) || []).forEach((sa, si) => {
+ reportUnknownAppShellKeys(sa, 'subArea', `sitemap subArea ${nodeName(sa, si)} in group ${nodeName(g, gi)}`, errors);
+ });
+ });
+ });
for (const a of (spec.appShell && spec.appShell.areas) || []) {
checkIcon(a.icon, `sitemap area "${a.label || ''}"`);
checkPortableIconRef(a.icon, `sitemap area "${a.label || ''}"`);
@@ -3120,8 +3269,9 @@ function validateAppSpec(spec, opts = {}) {
for (const [k, v] of Object.entries(spec.ai.appFeatures)) {
if (!AI_FEATURE_KEYS.has(k)) errors.push(`ai.appFeatures: unknown key '${k}' (allowed: ${AI_FEATURE_KEYS_LIST})`);
// These map to NUMERIC Dataverse app settings, not booleans: `true`/`false` are the
- // ergonomic spellings of 1/0, but the platform also defines other values (notably 2 =
- // "on for everyone"), which a boolean-only contract made inexpressible (ADO 6560699).
+ // ergonomic spellings of each setting's On/Off value (see AI_SETTING_CODEC), but every one
+ // of them is a tri-state, and a boolean-only contract made the third state — notably `0`,
+ // the platform default for most — inexpressible (ADO 6560699).
// Accept a boolean or a non-negative integer; reject anything else (a string like '2'
// would silently bypass the range check downstream).
//
@@ -3131,7 +3281,10 @@ function validateAppSpec(spec, opts = {}) {
// front, where the maker gets a message naming the field. `isSafeInteger` (not
// `isInteger`) because beyond 2^53 an "integer" double no longer round-trips.
if (typeof v !== 'boolean' && !(typeof v === 'number' && Number.isSafeInteger(v) && v >= 0 && v <= AI_FEATURE_MAX_VALUE)) {
- errors.push(`ai.appFeatures.${k}: must be a boolean or an integer between 0 and ${AI_FEATURE_MAX_VALUE} (e.g. true, false, or 2 for "on for everyone")`);
+ // The example names THIS setting's platform default: it is 0 for most, but 1 (Auto) for
+ // nlChart, where 0 means Off.
+ const platformDefault = AI_SETTING_CODEC[k] ? AI_SETTING_CODEC[k].platformDefault : '0';
+ errors.push(`ai.appFeatures.${k}: must be a boolean or an integer between 0 and ${AI_FEATURE_MAX_VALUE} (e.g. true, false, or ${platformDefault} to leave it to the platform default)`);
}
}
}
diff --git a/plugins/model-apps/scripts/lib/apply-snapshot-store.js b/plugins/model-apps/scripts/lib/apply-snapshot-store.js
index 60515a510..c530478db 100644
--- a/plugins/model-apps/scripts/lib/apply-snapshot-store.js
+++ b/plugins/model-apps/scripts/lib/apply-snapshot-store.js
@@ -48,23 +48,25 @@ function snapshotAbsent(workspaceDir) {
}
}
-// Atomic write. The temp file MUST be in the same directory as the target — rename() is only atomic
-// within a single filesystem, and a workspace-local temp guarantees that. fsync the fd before rename so
-// the bytes are durable, not just in the page cache. A crash leaves EITHER the prior snapshot or the new
-// one, never a partial write. The temp name carries pid+timestamp so two racing writers don't collide on
-// the temp path itself (the rename still yields one final winner; the CAS decides which SHOULD win).
-function writeSnapshotAtomic(workspaceDir, envelope) {
- fs.mkdirSync(workspaceDir, { recursive: true });
- const target = snapshotPath(workspaceDir);
+// Atomic write of `text` to `target`. The temp file MUST be in the same directory as the target —
+// rename() is only atomic within a single filesystem, and a temp beside the target guarantees that. fsync
+// the fd before rename so the bytes are durable, not just in the page cache. A crash leaves EITHER the
+// prior file or the new one, never a partial write. The temp name carries pid+timestamp so two racing
+// writers don't collide on the temp path itself (the rename still yields one final winner; for the
+// snapshot, the CAS decides which SHOULD win). writeFileSync on the descriptor writes the whole text: one
+// writeSync may write only part of it (see createExclusive), and a short write fsynced and renamed into
+// place is exactly the partial file this exists to prevent. A write that fails at any step removes its
+// temp and leaves the target as it was. The sitemap baseline (deployed-baseline.js) is written through it too.
+function writeFileAtomic(target, text) {
const tmp = `${target}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
- const fd = fs.openSync(tmp, 'w');
- try {
- fs.writeSync(fd, serializeEnvelope(envelope));
- fs.fsyncSync(fd);
- } finally {
- fs.closeSync(fd);
- }
try {
+ const fd = fs.openSync(tmp, 'w');
+ try {
+ fs.writeFileSync(fd, text);
+ fs.fsyncSync(fd);
+ } finally {
+ fs.closeSync(fd);
+ }
fs.renameSync(tmp, target);
} catch (e) {
try { fs.unlinkSync(tmp); } catch { /* best-effort cleanup of the orphaned temp */ }
@@ -72,6 +74,11 @@ function writeSnapshotAtomic(workspaceDir, envelope) {
}
}
+function writeSnapshotAtomic(workspaceDir, envelope) {
+ fs.mkdirSync(workspaceDir, { recursive: true });
+ writeFileAtomic(snapshotPath(workspaceDir), serializeEnvelope(envelope));
+}
+
// Create a CLAIM `file` holding `text` exclusively ('wx' — one writer wins), and remove it again when the write
// itself fails. writeFileSync with 'wx' creates the file BEFORE it writes, so a write that failed (ENOSPC) left an
// empty claim behind — and a claim is removed only by its creator (acquireLease), so every later attempt refused.
@@ -686,6 +693,7 @@ module.exports = {
leasePath,
readSnapshot,
snapshotAbsent,
+ writeFileAtomic,
writeSnapshotAtomic,
processAlive,
createExclusive,
diff --git a/plugins/model-apps/scripts/lib/deployed-baseline.js b/plugins/model-apps/scripts/lib/deployed-baseline.js
new file mode 100644
index 000000000..cbf62e099
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/deployed-baseline.js
@@ -0,0 +1,134 @@
+'use strict';
+// `<workspace>/last-applied.json`: the App Spec as last applied to — or downloaded from — ONE app in
+// ONE environment.
+//
+// Two readers use it:
+// * the dry run's advisory "phases changed since the last apply" diff (build-model-app.js), and
+// * the sitemap rewrite's baseline (AB#6726727): a nav entry the spec has not changed since this
+// snapshot, but the environment has, is kept rather than reverted (sitemap-merge.js).
+// The second is only sound against the app and environment the snapshot describes. The same spec
+// folder can be pointed at another environment, where "live differs from the snapshot" says nothing
+// about who changed what, so the snapshot records both and a baseline is returned only on an exact
+// match. A snapshot written before these stamps existed is not a baseline for the same reason.
+//
+// Written after a successful full apply and by download, whose output IS the deployed state. Nothing
+// here may fail a build or a download: without a baseline the spec wins, and the build says so.
+//
+// The snapshot is stored as schemaVersion 2 (migrateAppSpec), the shape every loaded spec has, so a
+// page is always referenced by its key. Beside it, `__deployedIds` records the id each dashboard (by
+// name) and page (by key) has in THIS environment, which the sitemap baseline lines entries up by
+// (chromeByTargetKey, sitemap-merge.js). The spec's own `dashboardId` / `pageId` cannot serve: a spec
+// downloaded from one environment keeps that environment's ids when it is built into another, where
+// the build falls back to the name and resolves different ones.
+
+const fs = require('node:fs');
+const path = require('node:path');
+const { annotateContentHashes } = require('./content-hash.js');
+const { migrateAppSpec } = require('./app-spec.js');
+const { writeFileAtomic } = require('./apply-snapshot-store.js');
+
+const FILE = 'last-applied.json';
+// Stored beside the spec's own top-level keys. phase-diff.js compares only its per-phase slices, so
+// no stamp can make the advisory diff report a change.
+const ENVIRONMENT_KEY = '__environment';
+const APP_KEY = '__appUniqueName';
+const IDS_KEY = '__deployedIds';
+
+function baselinePath(workspaceDir) {
+ return path.join(workspaceDir, FILE);
+}
+
+/**
+ * A `readFile(relPath)` for annotateContentHashes, confined to `appDir`: a page codeFile or
+ * web-resource contentPath is resolved the way the build engine resolves it (relative to the app
+ * folder), and one that escapes the folder — already rejected at validation — reads as null rather
+ * than reaching an arbitrary file. A null hash reads as CHANGED (see content-hash.js), so an
+ * unreadable source can never make the diff report a silent no-op. Bytes are raw, so the hash does
+ * not depend on an encoding.
+ */
+function confinedReader(appDir) {
+ const root = path.resolve(appDir || '.');
+ return (relPath) => {
+ try {
+ const abs = path.resolve(root, relPath);
+ const rel = path.relative(root, abs);
+ if (rel === '..' || rel.startsWith('..' + path.sep) || path.isAbsolute(rel)) return null;
+ return fs.readFileSync(abs);
+ } catch {
+ return null;
+ }
+ };
+}
+
+/**
+ * The id each dashboard (by name) and page (by key) of the migrated `spec` has in this environment,
+ * as `{ dashboards: { <name>: id }, pages: { <key>: id } }`, from the first source that has it:
+ * - `fromSpec`: the spec's own `dashboardId` / `pageId` — a download's, read from this environment;
+ * - `created`: what this build resolved (its `result.created`);
+ * - `previous`: the ids the prior baseline recorded — a changed-only apply resolves only the pages
+ * it uploads, and an id it did not re-resolve is still the one it had.
+ * An entry no source has is left out, so the next build resolves it itself.
+ */
+function deployedIdsFor(spec, { created, previous, fromSpec = false } = {}) {
+ const own = (map, name) => (map && typeof map === 'object' && Object.prototype.hasOwnProperty.call(map, name) ? map[name] : undefined);
+ const prior = (previous && previous[IDS_KEY]) || {};
+ const list = (v) => (Array.isArray(v) ? v : []);
+ // Object.fromEntries defines each name as an own data property — a dashboard named `__proto__` is
+ // recorded, not turned into the object's prototype.
+ const dashboards = Object.fromEntries(list(spec && spec.dashboards)
+ .filter((d) => d && typeof d.name === 'string' && d.name)
+ .map((d) => [d.name, (fromSpec && d.dashboardId) || own(created && created.dashboards, d.name) || own(prior.dashboards, d.name)])
+ .filter(([, id]) => typeof id === 'string' && id));
+ const pages = Object.fromEntries(list(spec && spec.pages)
+ .filter((p) => p && typeof p.key === 'string' && p.key)
+ .map((p) => [p.key, (fromSpec && p.pageId) || own(created && created.pages, p.key) || own(prior.pages, p.key)])
+ .filter(([, id]) => typeof id === 'string' && id));
+ return { dashboards, pages };
+}
+
+/**
+ * Record `spec` as the state of `appUniqueName` in `environment` (a canonical origin, e.g.
+ * `https://contoso.crm.dynamics.com`), with the deployed ids `deployedIdsFor` finds from `created`,
+ * `previous` and — for a download — `fromSpec`. Throws on a write error; callers treat it as non-fatal.
+ */
+function writeBaseline(workspaceDir, spec, { appDir, environment, appUniqueName, created, previous, fromSpec } = {}) {
+ const v2 = migrateAppSpec(spec);
+ const snapshot = {
+ ...annotateContentHashes(v2, confinedReader(appDir)),
+ [ENVIRONMENT_KEY]: environment || null,
+ [APP_KEY]: appUniqueName || null,
+ [IDS_KEY]: deployedIdsFor(v2, { created, previous, fromSpec }),
+ };
+ fs.mkdirSync(workspaceDir, { recursive: true });
+ // Atomically, like the apply snapshot: a crash or a full disk part-way through a plain write left a
+ // truncated file, which reads as no baseline — and without one the spec wins over every nav change made
+ // in the designer. A failed write now leaves the previous snapshot of this app and environment, which is
+ // still right about everything the latest apply did not change.
+ writeFileAtomic(baselinePath(workspaceDir), JSON.stringify(snapshot));
+}
+
+/**
+ * The snapshot, when it describes `appUniqueName` in `environment`; otherwise null (missing,
+ * unreadable, another app or environment, or written before the stamps existed). Returned as
+ * schemaVersion 2 whatever shape it was stored in.
+ */
+function readBaseline(workspaceDir, { environment, appUniqueName }) {
+ let snapshot;
+ try {
+ snapshot = JSON.parse(fs.readFileSync(baselinePath(workspaceDir), 'utf8'));
+ } catch {
+ return null;
+ }
+ if (!snapshot || typeof snapshot !== 'object' || Array.isArray(snapshot)) return null;
+ if (!environment || snapshot[ENVIRONMENT_KEY] !== environment) return null;
+ // App unique names are case-insensitive in Dataverse.
+ const app = typeof snapshot[APP_KEY] === 'string' ? snapshot[APP_KEY].toLowerCase() : '';
+ if (!appUniqueName || app !== String(appUniqueName).toLowerCase()) return null;
+ try {
+ return migrateAppSpec(snapshot);
+ } catch {
+ return null;
+ }
+}
+
+module.exports = { baselinePath, confinedReader, deployedIdsFor, writeBaseline, readBaseline };
diff --git a/plugins/model-apps/scripts/lib/entity-provision.js b/plugins/model-apps/scripts/lib/entity-provision.js
index a29e07e99..77106938b 100644
--- a/plugins/model-apps/scripts/lib/entity-provision.js
+++ b/plugins/model-apps/scripts/lib/entity-provision.js
@@ -546,13 +546,63 @@ function makeRunner({ emit, total }) {
return undefined;
}
emit({ phase, status: 'error', label, n: myN, total, detail: String((err && err.message) || err) });
- throw new BuildHalt(`${phase} failed: ${(err && err.message) || err}`, { phase, code: (err && err.code) || 'sdk-error', recoverable, cause: err });
+ throw new BuildHalt(`${phase} failed: ${(err && err.message) || err}${operatorRemedy(err)}`, { phase, code: (err && err.code) || 'sdk-error', recoverable, cause: err });
}
};
const skip = (phase, label) => { emit({ phase, status: 'skip', label, n: (n += 1), total }); };
return { run, mapLimit, skip, emit, total };
}
+// How an operator resets a workspace by hand, where the build cannot do it itself. Most of `.maker-workspace`
+// is state a re-run rebuilds — the SDK's copies are re-read from the environment, and without the
+// changed-only snapshot the next `--changed-only` run just does a full build — but two files record things
+// the environment cannot give back:
+// - last-applied.json, what was last applied or downloaded: the baseline that keeps a nav change made in
+// the designer from being reverted by a stale spec (AB#6726727);
+// - destructive-approval.json, the removals a maker approved: without it the next --allow-destructive
+// authorizes whatever that run finds, not what was shown.
+// And the changed-only snapshot can hold a RUNNING teardown's registration and a build's lease, which are
+// that run's guard against a concurrent one: deleting them under a live run removes it. Every remedy that
+// resets the workspace says exactly this.
+const RESET_WORKSPACE = 'stop any other build or teardown using the .maker-workspace directory (or the --workspace one), then delete everything in it except last-applied.json and destructive-approval.json';
+
+// Some SDK refusals end with the SDK call that fixes them — `fetchArtifact(...)` — which an operator of this
+// plugin cannot make. Where the operator's step is known, the halt names it too.
+//
+// ARTIFACT_PROJECTION_STALE: the SDK refuses to push a workspace copy projected by a different version of its
+// parsers — one an earlier version of this plugin saved. The build's plain fetch re-reads every CLEAN copy
+// before it edits one, so the refusal is reached only by a copy still holding edits an earlier build never
+// pushed (an interrupted build, say): a plain fetch keeps those while the server has not moved. The edits
+// were projected from the spec, so the re-run after a reset re-applies them.
+//
+// The build does NOT reset the copy itself, although `fetchArtifact(..., { overwrite: true })` would. The
+// SDK's per-artifact lock is per process, so an overwrite here could replace the copy a second build on
+// the same workspace has just re-read and edited, and that build would then push without its edit —
+// reporting success. The manual reset starts by stopping every other run, which is what makes it safe.
+//
+// LOCAL_EDITS_WOULD_BE_LOST: a plain fetch keeps a copy holding unpushed edits only while the environment's
+// copy has NOT moved; once it has, the fetch refuses rather than discard the edits, and the SDK's advice —
+// "Push or discard your edits first, or pass { overwrite: true }" — is again an API call. Two things leave
+// such a copy: an interrupted build (measured live on a 2.10.0 workspace, where the build then stopped at a
+// form's fetch, not its push), and a push refused as a concurrent edit (VERSION_CONFLICT), after which the
+// copy is KEPT on purpose as the fence that stops a blind re-run (see discardUnrecordedEdits, sdk-build.js).
+// Either way the environment has changed since, maybe by a maker, so clearing the copy and rebuilding the
+// same spec could overwrite that change: the navigation baseline covers nav chrome only, and not a field the
+// spec changed too. So the halt asks for the one step only a person can take first — look at the change and
+// put into the spec what should stay — and then the usual reset. A re-download is no substitute: it does not
+// capture forms, views or charts, and the artifact may predate the app (an interrupted FIRST build leaves
+// views and forms before the app exists). Both codes are pinned against the real bundle in
+// workspace-projection-real-bundle.test.js.
+function operatorRemedy(err) {
+ if (err && err.code === 'ARTIFACT_PROJECTION_STALE') {
+ return ` — the workspace copy was saved by an earlier version of this plugin and still holds edits no build pushed (an interrupted build, say). To reset it, ${RESET_WORKSPACE}, and re-run: the build re-reads the copies and re-applies every edit from the spec.`;
+ }
+ if (err && err.code === 'LOCAL_EDITS_WOULD_BE_LOST') {
+ return ` — the environment's copy changed after this workspace copy was fetched, and the workspace copy holds edits no build pushed (an interrupted build, or one halted by a concurrent edit). A re-run applies the spec over that change, so first look at it in Maker and put into the spec anything that should stay; then ${RESET_WORKSPACE}, and re-run.`;
+ }
+ return '';
+}
+
// Whether a push RESULT is a failure. The SDK reports some failures by value instead of throwing (see
// requireSuccessfulPush below for which, and why both spellings of the commit flag are read). Shared so
// every caller that reacts to a failed push decides "failed" exactly as the halt does.
@@ -605,7 +655,7 @@ function requireSuccessfulPush(result, what, warn) {
// conditional update. The SDK's own advice (`fetchArtifact(..., { overwrite: true })`) is an API
// call an operator of this plugin cannot make, so this names the step they can.
if (sdkCode === 'ARTIFACT_ALREADY_EXISTS') {
- throw new BuildHalt(`push ${label} failed: ${detail} — a row already exists at that id and no duplicate was created. The workspace still holds the local copy that push never recorded, and a re-run keeps it and halts here again: delete the .maker-workspace directory (or the --workspace one), then re-run the build to adopt the existing row.`, { ...opts, code: 'already-exists' });
+ throw new BuildHalt(`push ${label} failed: ${detail} — a row already exists at that id and no duplicate was created. The workspace still holds the local copy that push never recorded, and a re-run keeps it and halts here again. To reset it, ${RESET_WORKSPACE}, and re-run the build to adopt the existing row.`, { ...opts, code: 'already-exists' });
}
// No code at all is the bare 412 this guard was originally written for, and `VERSION_CONFLICT`
// is the code the SDK actually attaches to one — both mean the artifact moved under us, and
@@ -1352,4 +1402,4 @@ async function provisionSampleData({ sdk, provision, runner, spec, dataModel })
return { records: result.records, entitySetFor };
}
-module.exports = { makeRunner, requireSuccessfulPush, pushFailed, reportPartialPush, errorCodeChain, makeEntitySetResolver, resolveLanguageCode, resolveAuthoringLanguage, provisionSolution, provisionDataModel, provisionSampleData, buildSeedGroup, BuildHalt, SDK_COLUMN_TYPE, isVisualizationUnsupported, localizedLabelLcidsInSpec, checkLocalizedLabelLanguages, findExistingTable, findExistingColumns, relationshipExists };
+module.exports = { makeRunner, runBestEffort, requireSuccessfulPush, pushFailed, reportPartialPush, errorCodeChain, RESET_WORKSPACE, makeEntitySetResolver, resolveLanguageCode, resolveAuthoringLanguage, provisionSolution, provisionDataModel, provisionSampleData, buildSeedGroup, BuildHalt, SDK_COLUMN_TYPE, isVisualizationUnsupported, localizedLabelLcidsInSpec, checkLocalizedLabelLanguages, findExistingTable, findExistingColumns, relationshipExists };
diff --git a/plugins/model-apps/scripts/lib/form-order.js b/plugins/model-apps/scripts/lib/form-order.js
new file mode 100644
index 000000000..6d89e48c5
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/form-order.js
@@ -0,0 +1,182 @@
+'use strict';
+// Main Form Set order (AB#6736948): which Main form a table opens with, and the order its form
+// switcher lists them in. Shared by the spec gate (app-spec.js), the build (sdk-build.js) and verify
+// (verify-spec.js), so the three cannot disagree about which forms are ordered, or how.
+//
+// The platform keeps the order on each FORM, not on the table. A Main form's formxml carries
+// <DisplayConditions Order="1" FallbackForm="true"><Everyone /></DisplayConditions>
+// and a user is served the forms they may open sorted by that `Order`. MEASURED live, on a throwaway
+// table with three Main forms:
+// - changing only the three `Order` values reversed the order the public RetrieveFilteredForms
+// function returns (the forms a given user may open, first to last);
+// - moving `systemform.isdefault` to another form did not reorder it;
+// - forms with an EQUAL `Order` are put in an order the platform chooses, which `isdefault` does not
+// decide: three new forms, all at the `Order="0"` a new form carries, were served with the
+// `isdefault` form LAST — so a table whose Main forms the build had just created did NOT open with
+// the form the build marked as the default;
+// - a form with no <DisplayConditions> at all is served after every form that has one.
+// So the order is plain formxml, written through the same supported call that sets a form's security
+// roles (the SDK's setFormSecurityRoles) — the private messages behind Maker's "Form order" dialog are
+// not needed. What a user actually opens also depends on two things this module does not control: the
+// form they last switched to for that table (remembered per user, and opened first while they may
+// still open it), and which forms their security roles allow.
+// See: https://learn.microsoft.com/power-apps/maker/model-driven-apps/assign-form-order
+// https://learn.microsoft.com/power-apps/maker/model-driven-apps/control-access-forms
+// https://learn.microsoft.com/power-apps/developer/model-driven-apps/form-xml-schema (FormDisplayConditionsType)
+// https://learn.microsoft.com/power-apps/developer/data-platform/webapi/reference/retrievefilteredforms
+
+const lower = (s) => String(s === undefined || s === null ? '' : s).toLowerCase();
+
+/** A `forms[]` entry that is a Main form (`formType` omitted means Main). */
+const isMainForm = (f) => !!f && typeof f === 'object' && (f.formType === undefined || f.formType === 'Main');
+
+function entitySpecFor(spec, entityLogical) {
+ const key = lower(entityLogical);
+ return ((spec && spec.entities) || []).find((e) => e && lower(e.schemaName) === key) || null;
+}
+
+/**
+ * True for a table this spec creates and owns: declared, not `existing`, and named with the spec's
+ * publisher prefix. Only there does the build make an IMPLICIT choice about what the table opens with
+ * — re-pointing a reused or system table is an environment-wide change the author did not ask for. An
+ * explicit `isDefault` or `mainFormOrder` is applied on any table.
+ */
+function isOwnCustomTable(spec, entityLogical) {
+ const entSpec = entitySpecFor(spec, entityLogical);
+ const prefix = spec && spec.solution && spec.solution.publisherPrefix;
+ return !!(entSpec && entSpec.existing !== true && prefix
+ && lower(entSpec.schemaName).startsWith(lower(prefix) + '_'));
+}
+
+/** The spec's Main forms for a table, in spec order. */
+function declaredMainForms(spec, entityLogical) {
+ const key = lower(entityLogical);
+ return ((spec && spec.forms) || []).filter((f) => isMainForm(f) && lower(f.entity) === key);
+}
+
+/**
+ * The table's `entities[].mainFormOrder`, resolved to its Main form entries, or null when it declares
+ * none. A name that resolves to nothing, or a repeat, is left out here — the spec gate rejects both.
+ */
+function listedMainForms(spec, entityLogical) {
+ const entSpec = entitySpecFor(spec, entityLogical);
+ if (!entSpec || !Array.isArray(entSpec.mainFormOrder)) return null;
+ const mains = declaredMainForms(spec, entityLogical);
+ const out = [];
+ for (const name of entSpec.mainFormOrder) {
+ const f = mains.find((m) => m.name === name);
+ if (f && !out.includes(f)) out.push(f);
+ }
+ return out;
+}
+
+/**
+ * The Main form a table opens with, as the spec declares it: `{ form, explicit }`, or null.
+ * `forms[].isDefault` first, then the first entry of `entities[].mainFormOrder` (the spec gate makes
+ * the two agree); both apply on any table. Failing both, and only on a table the spec owns, the first
+ * Main form in spec order (AB#6686426's fallback).
+ */
+function selectDefaultForm(spec, entityLogical) {
+ const mains = declaredMainForms(spec, entityLogical);
+ const flagged = mains.find((f) => f.isDefault === true);
+ if (flagged) return { form: flagged, explicit: true };
+ const listed = listedMainForms(spec, entityLogical);
+ if (listed && listed.length) return { form: listed[0], explicit: true };
+ if (mains.length && isOwnCustomTable(spec, entityLogical)) return { form: mains[0], explicit: false };
+ return null;
+}
+
+/**
+ * True when a Main form of the table sets `securityRoles.order`. That writes the same `Order`
+ * attribute, so the author is ordering these forms by hand and the build leaves the order to them.
+ */
+function ordersByHand(spec, entityLogical) {
+ return declaredMainForms(spec, entityLogical)
+ .some((f) => f.securityRoles && typeof f.securityRoles === 'object' && f.securityRoles.order !== undefined);
+}
+
+/**
+ * The spec's Main forms of a table in the order the build gives them, first to last, or null when the
+ * build orders none of them. `current` maps a form entry to its stored `Order` (a number, or undefined
+ * when the form has no <DisplayConditions>).
+ *
+ * The forms `mainFormOrder` lists come first, in that order; without a list, the default form alone
+ * comes first. The spec's other Main forms follow in their CURRENT relative order (ties, and forms with
+ * no `Order`, in spec order), so an order a maker set in Maker is kept for every form the spec says
+ * nothing about. Forms the spec does not declare are never in the result: the build does not write them.
+ */
+function plannedMainFormSequence(spec, entityLogical, current = new Map()) {
+ if (ordersByHand(spec, entityLogical)) return null;
+ const listed = listedMainForms(spec, entityLogical);
+ let head = listed && listed.length ? listed : null;
+ if (!head) {
+ const chosen = selectDefaultForm(spec, entityLogical);
+ if (!chosen) return null;
+ head = [chosen.form];
+ }
+ const rank = (f) => { const o = current.get(f); return Number.isFinite(o) ? o : Infinity; };
+ const rest = declaredMainForms(spec, entityLogical)
+ .filter((f) => !head.includes(f))
+ .map((f, i) => ({ f, i }))
+ // Infinity - Infinity is NaN, which is falsy, so two forms without an Order fall through to spec order.
+ .sort((a, b) => (rank(a.f) - rank(b.f)) || (a.i - b.i))
+ .map((x) => x.f);
+ return [...head, ...rest];
+}
+
+/**
+ * A form's `<DisplayConditions>` as stored in its formxml: `{ present, order }`. Shapes seen live:
+ * <DisplayConditions Order="0" FallbackForm="true"><Everyone /></DisplayConditions>
+ * <DisplayConditions FallbackForm="true" Order="3"><Everyone /></DisplayConditions>
+ * <DisplayConditions Order="2" FallbackForm="false"><Role Id="{GUID}" /></DisplayConditions>
+ * Attribute order varies, so `Order` is read by name from the start tag (which may also be
+ * self-closing). `order` is undefined when the attribute is absent or is not an integer.
+ */
+function displayConditionsOrder(formxml) {
+ const tag = /<DisplayConditions\b([^>]*?)\/?>/.exec(String(formxml || ''));
+ if (!tag) return { present: false, order: undefined };
+ const attr = /\sOrder\s*=\s*(?:"([^"]*)"|'([^']*)')/.exec(tag[1]);
+ const raw = attr ? (attr[1] !== undefined ? attr[1] : attr[2]) : undefined;
+ return { present: true, order: raw !== undefined && /^\s*-?\d+\s*$/.test(raw) ? Number(raw) : undefined };
+}
+
+/**
+ * Compare the order a user is served (form ids, first to last) with the build's order for the spec's
+ * forms (`planned`: `[{ name, id }]`, first to last). Returns one of:
+ * { ok: true }
+ * { ok: false, reason: 'order', before, after } — `before` is served ahead of `after`, which the spec
+ * puts first
+ * { ok: false, reason: 'ahead', aheadId } — a form the spec does not put first is served first
+ * { ok: null, reason: 'first-not-served' } — this user may not open the first planned form, so
+ * what users open cannot be judged from their answer
+ * and, always, `missing`: the planned forms this user is not served (their security roles), which the
+ * served order cannot place.
+ */
+function compareServedOrder(planned, served) {
+ const norm = (id) => lower(String(id === undefined || id === null ? '' : id).replace(/[{}]/g, '').trim());
+ const servedIds = (served || []).map(norm);
+ const pos = new Map();
+ servedIds.forEach((id, i) => { if (!pos.has(id)) pos.set(id, i); });
+ const missing = planned.filter((p) => !pos.has(norm(p.id))).map((p) => p.name);
+ const offered = planned.filter((p) => pos.has(norm(p.id)));
+ for (let i = 1; i < offered.length; i += 1) {
+ if (pos.get(norm(offered[i].id)) < pos.get(norm(offered[i - 1].id))) {
+ return { ok: false, reason: 'order', before: offered[i].name, after: offered[i - 1].name, missing };
+ }
+ }
+ if (!planned.length || !pos.has(norm(planned[0].id))) return { ok: null, reason: 'first-not-served', missing };
+ if (servedIds[0] !== norm(planned[0].id)) return { ok: false, reason: 'ahead', aheadId: servedIds[0], missing };
+ return { ok: true, missing };
+}
+
+module.exports = {
+ isMainForm,
+ isOwnCustomTable,
+ declaredMainForms,
+ listedMainForms,
+ selectDefaultForm,
+ ordersByHand,
+ plannedMainFormSequence,
+ displayConditionsOrder,
+ compareServedOrder,
+};
diff --git a/plugins/model-apps/scripts/lib/hydrate-spec.js b/plugins/model-apps/scripts/lib/hydrate-spec.js
index e3476bfd3..8036ba77d 100644
--- a/plugins/model-apps/scripts/lib/hydrate-spec.js
+++ b/plugins/model-apps/scripts/lib/hydrate-spec.js
@@ -1,5 +1,5 @@
'use strict';
-const { isSafeHttpUrl, webResourceNameFromRef } = require('./app-spec.js');
+const { isSafeHttpUrl, webResourceNameFromRef, FORM_GUID_RE } = require('./app-spec.js');
// Reconstruct a COMPLETE app-spec from a DEPLOYED app (the edit flow's "pull everything" step). Pure
// + testable: `read` supplies the deployed state — the app (sitemap JSON, via the SDK's app read
// path which surfaces entity/genPage/icon subareas), its generative pages (via pac list+download),
@@ -250,7 +250,15 @@ async function hydrateSpec(read) {
// Dashboards are reconstructed with id-passthrough tiles (each tile carries the deployed
// view/chart ids), so a rebuild recreates the dashboard against the EXISTING views/charts
// without needing views[]/charts[] declared (which would else duplicate them or fail validation).
- dashboards: dashboards.map((d) => ({ name: d.name, ...(d.description ? { description: d.description } : {}), tiles: d.tiles })),
+ // Each also carries its deployed id (`dashboardId`, edit-snapshot only, like pages[].pageId): a
+ // rebuild binds to that dashboard even after it is renamed in the designer, where finding it by
+ // the spec's now-stale name would create a second one under the old name (AB#6726727).
+ dashboards: dashboards.map((d) => {
+ const pin = String(d.id === undefined || d.id === null ? '' : d.id).replace(/[{}]/g, '').toLowerCase();
+ // Only a real GUID is pinned: validation rejects anything else, and a download must never write
+ // a spec its own validator refuses.
+ return { name: d.name, ...(FORM_GUID_RE.test(pin) ? { dashboardId: pin } : {}), ...(d.description ? { description: d.description } : {}), tiles: d.tiles };
+ }),
pages: pages.map((p) => (hasKeys
// v2 shape: key + name + optional semantics + source discriminant (kind:'tsx', codeFile)
? {
diff --git a/plugins/model-apps/scripts/lib/sdk-build.js b/plugins/model-apps/scripts/lib/sdk-build.js
index bdffab783..62394b821 100644
--- a/plugins/model-apps/scripts/lib/sdk-build.js
+++ b/plugins/model-apps/scripts/lib/sdk-build.js
@@ -38,15 +38,27 @@ const {
labelText,
choiceValueMap,
BPF_ROLE_ACCESS,
+ dashboardNameKey,
} = require('./app-spec.js');
const { PHASES } = require('./stages.js');
const { topoOrderEntities, entityByLogical } = require('./_graph.js');
+const {
+ isMainForm,
+ isOwnCustomTable,
+ declaredMainForms,
+ listedMainForms,
+ selectDefaultForm,
+ ordersByHand,
+ plannedMainFormSequence,
+} = require('./form-order.js');
const {
makeRunner,
+ runBestEffort,
requireSuccessfulPush,
pushFailed,
reportPartialPush,
errorCodeChain,
+ RESET_WORKSPACE,
makeEntitySetResolver,
provisionSolution,
provisionDataModel,
@@ -88,7 +100,8 @@ const { fetchSitemap, fetchAppsForPages } = require('./sitemap-pages.js');
// classifies every generative navigateTo pageId at a REAL call site (never a decoy string / comment GUID).
const { extractNavTargets, navReferencedKeys, navMalformedRefs, resolvePageRefs, navTargetParity } = require('./pageref-resolver.js');
const { selectSummaryTables } = require('./ai-candidates.js');
-const { AI_APP_SETTING, resolveAiFlags, specOptsIntoAi, featureWantValue, sameSettingValue, resolveAppModuleId, proveAppOverride } = require('./ai-app-settings.js');
+const { AI_APP_SETTING, resolveAiFlags, encodeAiFlags, rebucketNonEnablingSkips, specOptsIntoAi, featureWantValue, sameSettingValue, resolveAppModuleId, proveAppOverride } = require('./ai-app-settings.js');
+const { DASHBOARD_LAUNCHER_URL, adoptLiveSitemap, chromeByTargetKey, describeSitemapNotes } = require('./sitemap-merge.js');
const { buildPromptSpec } = require('./ai-prompt.js');
const { odataLit } = require('./odata.js');
const { isRestrictedSolution } = require('./system-solutions.js');
@@ -171,6 +184,23 @@ async function findDashboardsByName(sdk, name) {
return rows.map((r) => ({ id: String(r.formid), name: String(r.name) }));
}
+// The dashboard a downloaded spec's `dashboards[].dashboardId` pins — the one it was read from — as
+// `{ id, name }`, or null when this environment has no row with that id (a spec downloaded from another
+// environment, or a dashboard deleted since). A row that exists but is not a dashboard (systemform
+// `type` 0) is a wrong pin and throws: pointing a nav entry at a form would break it. Shared by build,
+// verify and teardown, so all three bind the same dashboard.
+async function findPinnedDashboard(sdk, pin) {
+ const id = String(pin === undefined || pin === null ? '' : pin).trim().replace(/^\{|\}$/g, '').toLowerCase();
+ if (!FORM_GUID_RE.test(id)) return null;
+ const rows = await sdk.queryRecords('systemform', { select: ['formid', 'name', 'type'], filter: `formid eq ${id}`, top: 1 });
+ const row = rows && rows[0];
+ if (!row) return null;
+ if (row.type !== undefined && row.type !== null && Number(row.type) !== 0) {
+ throw new Error(`dashboardId ${id} is a type-${row.type} form, not a dashboard — correct the id, or remove it to find the dashboard by name`);
+ }
+ return { id: String(row.formid), name: String(row.name === undefined || row.name === null ? '' : row.name) };
+}
+
// Web-resource kinds (App Spec `type`) -> SDK createWebResource `type` token. The SDK maps
// the token to the Dataverse webresourcetype code (js=3, html=1, css=2, …).
const WEB_RESOURCE_KINDS = new Set(['js', 'html', 'css', 'xml', 'png', 'jpg', 'gif', 'xsl', 'ico', 'svg', 'resx']);
@@ -477,6 +507,18 @@ function planFor(spec, opts) {
if ((f.events || []).length) items.push({ phase: 'forms', label: `wire ${f.events.length} event handler(s) on ${f.entity}` });
if ((f.quickViews || []).length) items.push({ phase: 'forms', label: `place ${f.quickViews.length} quick-view(s) on ${f.entity}` });
}
+ // AB#6736948: one step per table with Main forms, after all of them exist — it sets the table's Main
+ // Form Set order, or keeps it (a form new on a table the spec orders nothing on goes after the others).
+ // None where the author orders the forms by hand (`securityRoles.order`).
+ if (has('forms')) {
+ const orderSteps = new Set();
+ for (const f of (spec.forms || []).filter(isMainForm)) {
+ const key = String(f.entity || '').toLowerCase();
+ if (!key || orderSteps.has(key)) continue;
+ orderSteps.add(key);
+ if (!ordersByHand(spec, key)) items.push({ phase: 'forms', label: `form order for ${f.entity}` });
+ }
+ }
if (has('business-rules')) for (const r of spec.businessRules || []) items.push({ phase: 'business-rules', label: `business rule "${r.name}" on ${r.entity}` });
if (has('business-process-flows')) for (const p of spec.businessProcessFlows || []) {
const stages = (p.stages || []).length;
@@ -947,7 +989,10 @@ function appDef(spec, result, opts = {}) {
if (s.dashboard) {
const dashboardId = (result.dashboards || {})[s.dashboard];
if (!dashboardId) throw new Error(`sitemap subarea "${s.title}" references dashboard '${s.dashboard}' which wasn't built — declare it in dashboards[] and don't skip the dashboards phase`);
- return { ...withVector, type: 'DashBoard', dashboardId };
+ // The designer gives every dashboard entry it creates this launcher Url, recognizes a dashboard
+ // entry by it, and the runtime shows the dashboard glyph only for it — without it the entry
+ // renders a placeholder icon (AB#6726727). The SDK's from-scratch node omits it.
+ return { ...withVector, type: 'DashBoard', dashboardId, dashboardUrl: DASHBOARD_LAUNCHER_URL };
}
if (s.page) {
const genPageId = (result.pages || {})[s.page];
@@ -1072,7 +1117,7 @@ async function haltOnUnpublishedAppHeader(provision, appId, pushed, name) {
reset = false;
}
const workspace = reset ? ''
- : ' First delete the .maker-workspace directory (or the --workspace one): it still holds this run\'s unpushed copy of the app, which a re-run would refuse to overwrite.';
+ : ` First reset the workspace, which still holds this run's unpushed copy of the app (a re-run would refuse to overwrite it): ${RESET_WORKSPACE}.`;
const why = neverPublished
? 'the app has never been published, and Dataverse refuses a write to its name, description or routing description until it is'
: 'the app has an unpublished change to its name, description or routing description (saved in Maker, or by a build whose publish did not complete), and Dataverse refuses another write to those fields until it is published';
@@ -1128,7 +1173,7 @@ async function discardUnrecordedEdits(provision, appId, error, thrown) {
async function refuseUnpushedAppCopy(provision, appId, name) {
const listed = (await provision.listArtifacts('app')).find((a) => a && a.id === appId);
if (listed && listed.isDirty) {
- throw new BuildHalt(`app ${name}: the workspace copy holds edits an earlier run did not push (an interrupted build, say), and this run's push of the app would send them too. Delete the .maker-workspace directory (or the --workspace one) and re-run.`, { phase: 'app-shell', code: 'app-copy-unpushed-edits', recoverable: true });
+ throw new BuildHalt(`app ${name}: the workspace copy holds edits an earlier run did not push (an interrupted build, say), and this run's push of the app would send them too. To reset it, ${RESET_WORKSPACE}, and re-run.`, { phase: 'app-shell', code: 'app-copy-unpushed-edits', recoverable: true });
}
}
@@ -1677,6 +1722,22 @@ async function assertAuthorizedSitemapRewrite(provision, appId, nextSiteMap, aut
}
}
+// The sitemap to write over an EXISTING app: `desired` re-attached to the live nodes it corresponds
+// to, so each keeps its live id and everything the App Spec cannot describe (AB#6726727; see
+// sitemap-merge.js). The live tree is the workspace copy, which the caller has just fetched — and
+// the removal fence may have re-fetched with overwrite — so it is exactly what this write replaces.
+// `opts.baselineSpec` is the spec last applied to, or downloaded from, this environment; with it a
+// nav-entry change made in the designer since then is kept rather than reverted by a stale spec.
+async function siteMapOverLive(provision, appId, desired, opts, created) {
+ const live = await provision.getArtifact('app', appId) || {};
+ const baseChrome = opts.baselineSpec ? chromeByTargetKey(opts.baselineSpec, created) : undefined;
+ // The LCID the SDK was constructed with — the one it reads and writes sitemap titles in.
+ const lcid = opts.preResolvedLanguageCode || opts.languageCode || undefined;
+ const { siteMap, notes } = adoptLiveSitemap(desired, live.siteMap, { baseChrome, lcid });
+ if (typeof opts.warn === 'function') for (const line of describeSitemapNotes(notes)) opts.warn(line);
+ return siteMap;
+}
+
async function runSdkBuild(spec, opts = {}) {
const { sdk, apply = false, sampleData = false, publish = false } = opts;
const emit = opts.emit || (() => undefined);
@@ -3017,7 +3078,173 @@ async function runSdkBuild(spec, opts = {}) {
return promoted;
};
- // helper: create an artifact — or UPDATE it in place if it already exists — then add to the solution.
+ // AB#6736948 — write one table's Main Form Set order (lib/form-order.js has the platform model and
+ // the measurements behind it).
+ //
+ // Only forms the spec declares are ever written. Where the spec orders the table — `mainFormOrder`,
+ // an explicit `isDefault`, or any table the spec owns — its Main forms get Order 0..n-1 in the
+ // planned order, skipping any already in place. Elsewhere the order belongs to the environment, and
+ // the build touches it only to put a Main form it CREATED in this run after the table's other Main
+ // forms: a new form carries Order 0, so it would otherwise tie with the form everyone opens today —
+ // or, on a table whose forms carry no order at all, displace it. A table the author orders by hand
+ // (`securityRoles.order`) is left alone entirely.
+ //
+ // Best-effort like the promotion above: a failed read or write is reported (✗ and a warning) and
+ // `--verify` fails on the order it reads back, but the build goes on.
+ const canOrderForms = () => typeof provision.getFormSecurityRoles === 'function'
+ && typeof provision.setFormSecurityRoles === 'function' && typeof provision.queryRecords === 'function';
+ const writeFormOrder = async (formId, order, stored) => {
+ // The SDK re-attaches an existing <DisplayConditions> and changes only the attributes it is given,
+ // so the form's roles and fallback setting are kept. A form with no <DisplayConditions> has nothing
+ // to attach an order to (the SDK refuses), so it gets the element a new form is created with —
+ // offered to everyone, eligible as a fallback — which is what having none means.
+ await provision.setFormSecurityRoles(formId, stored ? { order } : { everyone: true, fallbackForm: true, order });
+ };
+ // The table's ACTIVE Main forms other than `exceptIds`, each with its stored order (undefined: none).
+ const otherMainForms = async (entityLogical, exceptIds) => {
+ const rows = await provision.queryRecords('systemform', {
+ select: ['formid', 'name'],
+ filter: `objecttypecode eq '${odataLit(entityLogical)}' and type eq 2 and formactivationstate eq 1`,
+ top: 250,
+ });
+ const out = [];
+ for (const r of rows || []) {
+ const id = normalizeFormId(r && r.formid);
+ if (!id || exceptIds.has(id)) continue;
+ const stored = await provision.getFormSecurityRoles(id);
+ out.push({ id, name: String((r && r.name) || id), order: stored ? stored.order : undefined });
+ }
+ return out;
+ };
+ const applyMainFormOrder = async (entityLogical, idOfForm) => {
+ const mains = declaredMainForms(spec, entityLogical);
+ if (!mains.length || ordersByHand(spec, entityLogical)) return;
+ const entityName = mains[0].entity;
+ const q = (f) => `'${f.name || `${entityName} form`}'`;
+ const warn = (m) => { if (typeof opts.warn === 'function') opts.warn(m); };
+ const planned = plannedMainFormSequence(spec, entityLogical);
+ if (!canOrderForms()) {
+ runner.skip('forms', `form order for ${entityName} (this SDK cannot read or write a form's order)`);
+ return;
+ }
+ if (planned) {
+ const notBuilt = mains.filter((f) => !idOfForm.get(f));
+ if (notBuilt.length) {
+ runner.skip('forms', `form order for ${entityName} (${notBuilt.map(q).join(', ')} not built in this run)`);
+ return;
+ }
+ const listed = listedMainForms(spec, entityLogical);
+ const head = listed && listed.length ? listed : planned.slice(0, 1);
+ const more = mains.length - head.length;
+ await runBestEffort(runner, 'forms', `form order for ${entityName}: ${head.map(q).join(' > ')}${more ? `, then ${more} more` : ''}`, async () => {
+ const stored = new Map();
+ for (const f of mains) stored.set(f, await provision.getFormSecurityRoles(idOfForm.get(f)));
+ const current = new Map(mains.map((f) => [f, stored.get(f) ? stored.get(f).order : undefined]));
+ const sequence = plannedMainFormSequence(spec, entityLogical, current);
+ for (let i = 0; i < sequence.length; i += 1) {
+ if (current.get(sequence[i]) === i) continue;
+ await writeFormOrder(idOfForm.get(sequence[i]), i, stored.get(sequence[i]));
+ }
+ // A form this spec does not declare is never written — but one whose order does not put it
+ // after the first form can still be what the table opens with. Say so now; `--verify` checks
+ // the order the platform actually serves. The order above is already written, so a table form
+ // that cannot be read here (another publisher's, say) costs this warning, not the step.
+ let others = [];
+ try {
+ others = await otherMainForms(entityLogical, new Set(mains.map((f) => normalizeFormId(idOfForm.get(f)))));
+ } catch (err) {
+ warn(`'${entityName}': could not read its other Main forms to check that none comes before ${q(sequence[0])} (${(err && err.message) || err}); \`--verify\` checks the order the platform serves.`);
+ }
+ for (const o of others.filter((x) => Number.isFinite(x.order) && x.order <= 0)) {
+ warn(`'${entityName}': Main form '${o.name}', which this spec does not declare, has form order ${o.order} — not after ${q(sequence[0])} (0) — so the platform may open the table with it. Move it down in Maker (Form settings > Form order), or declare it in forms[] and list it in entities[].mainFormOrder.`);
+ }
+ }, opts.warn, `could not set the Main Form Set order of '${entityName}'`);
+ return;
+ }
+ // A Main form this run CREATED on this table was created already after the table's other Main forms
+ // (createInPlace, below): its order was part of the create. What is left is to say what that means.
+ const created = mains.filter((f) => idOfForm.get(f) && createdFormsThisRun.has(normalizeFormId(idOfForm.get(f))));
+ if (!created.length) {
+ runner.skip('forms', `form order for ${entityName} (no new Main form — its order is left as it is)`);
+ return;
+ }
+ await runBestEffort(runner, 'forms', `form order for ${entityName} (${created.map(q).join(', ')} after its other Main forms)`, async () => {
+ const list = created.map(q).join(', ');
+ const plural = created.length > 1;
+ const snapshot = await appendSnapshotFor(entityLogical);
+ if (snapshot.error) {
+ warn(`'${entityName}': could not read its other Main forms (${(snapshot.error && snapshot.error.message) || snapshot.error}), so ${list} ${plural ? 'were' : 'was'} created at the end of the form order (order ${APPEND_FALLBACK_ORDER} and up). Check the order in Maker (Form settings > Form order).`);
+ return;
+ }
+ const unplaced = created.filter((f) => !createdInPlace.has(f));
+ if (unplaced.length) {
+ warn(`'${entityName}': ${unplaced.map(q).join(', ')} ${unplaced.length > 1 ? 'were' : 'was'} created without a form order the build could set, so ${unplaced.length > 1 ? 'they' : 'it'} may come first. Set the order in Maker (Form settings > Form order), or declare the table's order with entities[].mainFormOrder.`);
+ }
+ if (snapshot.base < 0) {
+ warn(`'${entityName}': none of its other Main forms has a form order, so ${list} now come${plural ? '' : 's'} first — users without a remembered form open the table with ${q(created[0])}. To keep the form it opened with, set forms[].isDefault or entities[].mainFormOrder, or set the order in Maker (Form settings > Form order).`);
+ return;
+ }
+ // A form with no order at all is served after every form that has one, so the new form(s) come before
+ // it — and a user whose roles do not offer them an ordered form, and who therefore opened that one,
+ // now opens the new form instead.
+ const unranked = snapshot.others.filter((o) => !Number.isFinite(o.order));
+ if (unranked.length) {
+ warn(`'${entityName}': ${list} now come${plural ? '' : 's'} before ${unranked.map((o) => `'${o.name}'`).join(', ')}, which ${unranked.length > 1 ? 'have' : 'has'} no form order (a form without one is served after every form that has one) — so a user who opened ${unranked.length > 1 ? 'one of them' : 'it'} may now open ${q(created[0])}. To keep ${unranked.length > 1 ? 'their' : 'its'} place, give ${unranked.length > 1 ? 'them' : 'it'} an order in Maker (Form settings > Form order), or declare the table's order with entities[].mainFormOrder.`);
+ }
+ }, opts.warn, `could not check the place of the new Main form(s) of '${entityName}'`);
+ };
+
+ // AB#6736948 — a Main form the build CREATES on a table whose order it does not set is created already
+ // after the table's other Main forms. Its order is written into the new form's own <DisplayConditions>
+ // (the SDK gives every new form one, at Order 0, in its root bag) BEFORE the first push, so the order is
+ // part of the create: no interrupted run and no later failure can leave the form at Order 0, which can
+ // put it ahead of the form the table opens with. A separate write after the create, as first tried,
+ // left exactly that on any failure between the two — and a later build cannot tell the form is new.
+ //
+ // The place is (highest order among the table's other Main forms) + 1 + (the form's index among the
+ // spec's Main forms of that table), so several new forms keep spec order without coordinating (the
+ // gaps are harmless: the order only sorts). The other forms are read ONCE per table, and every creator
+ // awaits that one read before its own push, so no form this run creates is in it.
+ const APPEND_FALLBACK_ORDER = 100000;
+ const appendSnapshots = new Map(); // entity -> Promise<{ others, base } | { error }>
+ const appendSnapshotFor = (entityLogical) => {
+ if (!appendSnapshots.has(entityLogical)) {
+ appendSnapshots.set(entityLogical, otherMainForms(entityLogical, new Set()).then(
+ (others) => {
+ const orders = others.map((o) => o.order).filter(Number.isFinite);
+ return { others, base: orders.length ? Math.max(...orders) : -1 };
+ },
+ (error) => ({ error })
+ ));
+ }
+ return appendSnapshots.get(entityLogical);
+ };
+ const createdInPlace = new Set(); // spec form entries whose create carried their order
+ const createInPlace = async (formId, specForm) => {
+ if (!specForm || !isMainForm(specForm) || !canOrderForms()) return;
+ const entityLogical = String(specForm.entity || '').toLowerCase();
+ if (plannedMainFormSequence(spec, entityLogical) || ordersByHand(spec, entityLogical)) return;
+ const snapshot = await appendSnapshotFor(entityLogical);
+ const idx = Math.max(0, declaredMainForms(spec, entityLogical).indexOf(specForm));
+ // Unreadable neighbours: put it past any order Maker assigns (the step says so).
+ const order = snapshot.error ? APPEND_FALLBACK_ORDER + idx : snapshot.base + 1 + idx;
+ // The root bag of a new form, as the SDK builds it (abridged):
+ // { "c": [ { "i": 1, "node": { "n": "header", … } }, { "i": 2, "node": { "n": "footer", … } },
+ // { "i": 3, "node": { "n": "DisplayConditions", "a": [["Order", "0"], ["FallbackForm", "true"]],
+ // "c": [{ "n": "Everyone", "a": [], "c": [] }] } } ] }
+ // Only the Order attribute changes; the node is replaced whole through the generic surface, as the
+ // form-events region is (wireFormEvents).
+ const art = await provision.getArtifact('form', formId);
+ const bag = (art && art.bag && Array.isArray(art.bag.c)) ? art.bag.c : [];
+ const at = bag.findIndex((e) => e && e.node && e.node.n === 'DisplayConditions');
+ if (at < 0) return;
+ const entry = JSON.parse(JSON.stringify(bag[at]));
+ const attrs = Array.isArray(entry.node.a) ? entry.node.a : [];
+ const has = attrs.some((p) => Array.isArray(p) && p[0] === 'Order');
+ entry.node.a = has ? attrs.map((p) => (Array.isArray(p) && p[0] === 'Order' ? ['Order', String(order)] : p)) : [['Order', String(order)], ...attrs];
+ await provision.updateElement('form', formId, `/bag/c/${at}`, entry);
+ createdInPlace.add(specForm);
+ };
const buildArtifact = (type, def, meta) => runner.run(`${type}s`, `${type} "${def.name}"`, async () => {
// Update-in-place: editing a deployed spec must land, so a form is reconciled (fields +
// sub-grids) and a view has its columns reconciled, instead of the artifact being reused
@@ -3042,6 +3269,8 @@ async function runSdkBuild(spec, opts = {}) {
if (type === 'form') {
id = await createFormShell(def);
createdFormsThisRun.add(normalizeFormId(id));
+ // AB#6736948: on a table whose order the build does not set, the form is created in its place.
+ await createInPlace(id, meta && meta.specForm);
await addSubgrids(id, def.__subgrids);
} else {
id = (await provision.createArtifact(type, def)).id;
@@ -3208,7 +3437,7 @@ async function runSdkBuild(spec, opts = {}) {
return { f, def };
}));
const ids = await runner.mapLimit(defs, concurrency, async (d) => {
- const id = await buildArtifact('form', d.def);
+ const id = await buildArtifact('form', d.def, { specForm: d.f });
const wantedEvents = (d.f.events || []).filter((ev) => FORM_EVENTS.has(ev.event) && ev.library && ev.function);
if (wantedEvents.length) {
await runner.run('forms', `wire ${wantedEvents.length} event handler(s) on ${d.f.entity}`, async () => {
@@ -3233,40 +3462,48 @@ async function runSdkBuild(spec, opts = {}) {
// with therefore depended on completion order — an alternate read-only or OnSave-blocked form
// could silently become the default, changing normal app behaviour.
//
- // Selection is explicit first (`forms[].isDefault`), then a documented stable fallback: the FIRST
- // Main form in spec order. Both are order-independent, which is the property that was missing.
- // Still guarded to a table THIS build owns — re-pointing the default form of a system or reused
- // table is an environment-wide side effect.
+ // Selection is explicit first (`forms[].isDefault`, then the first entry of
+ // `entities[].mainFormOrder`), then a documented stable fallback: the FIRST Main form in spec
+ // order. All are order-independent, which is the property that was missing. The FALLBACK is still
+ // guarded to a table THIS build owns — re-pointing the default form of a system or reused table is
+ // an environment-wide side effect nobody asked for — but an explicit choice is applied on any
+ // table (AB#6736948: an `isDefault` on an existing table used to be dropped without a word).
+ // `lib/form-order.js` holds the rule, shared with the spec gate and verify.
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 demotion
+ const idOfForm = new Map(); // spec form entry -> the id this run built or reconciled
defs.forEach((d, i) => {
+ if (ids[i]) idOfForm.set(d.f, ids[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)) {
- mainByEntity.set(key, { id: ids[i], f: d.f });
- }
});
- for (const [entityLogical, chosen] of mainByEntity) {
- const entSpec = entityByLogical(spec, entityLogical);
- const prefix = spec.solution && spec.solution.publisherPrefix;
- const isOwnCustomTable = !!(entSpec && entSpec.existing !== true && prefix &&
- String(entSpec.schemaName).toLowerCase().startsWith(String(prefix).toLowerCase() + '_'));
- if (!isOwnCustomTable) continue;
+ for (const entityLogical of mainIdsByEntity.keys()) {
+ const chosen = selectDefaultForm(spec, entityLogical);
+ const chosenId = chosen && idOfForm.get(chosen.form);
+ if (!chosenId) continue;
+ mainByEntity.set(entityLogical, { id: chosenId, f: chosen.form });
// 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, mainIdsByEntity.get(entityLogical) || []);
+ // did not set, which is what `result.created.defaultForms` claims. Deactivating the other Main
+ // forms stays limited to a table this build owns, whatever the spec says: it is destructive.
+ const deactivateOthers = chosen.form.deactivateOtherMainForms === true && isOwnCustomTable(spec, entityLogical);
+ const promoted = await promoteDefaultForm(chosenId, entityLogical, deactivateOthers, mainIdsByEntity.get(entityLogical) || []);
if (promoted) promotedEntities.add(entityLogical);
}
if (promotedEntities.size) result.created.defaultForms = Object.fromEntries(
[...mainByEntity].filter(([k]) => promotedEntities.has(k)).map(([k, v]) => [k, v.id])
);
+ // AB#6736948 — the Main Form Set order. `isdefault` alone does not decide what a table opens with:
+ // the order does (see lib/form-order.js for the measurements), so the default form is also put
+ // first. Once per table, after every form exists and after the promotion above.
+ for (const entityLogical of mainIdsByEntity.keys()) {
+ await applyMainFormOrder(entityLogical, idOfForm);
+ }
+
// overwrites the first. That is correct for what the map is for — the app shell wires one form
// per entity — but it is invisible to a consumer reading the emitted JSON, who reasonably
// concludes the other ids were lost. `created.formIds` below is keyed by the (entity, formType,
@@ -3757,6 +3994,18 @@ async function runSdkBuild(spec, opts = {}) {
// Global (no entity); placement in the app sitemap is manual for now.
if (has('dashboards')) {
for (const dash of spec.dashboards || []) {
+ // AB#6726727: a DOWNLOADED dashboard is bound by the id it was read from before anything is tried
+ // by name. Renamed in the designer since, its spec name finds nothing — and the name path below
+ // would then create a second dashboard under the old name and point the nav entry at that.
+ const pinned = dash.dashboardId ? await findPinnedDashboard(provision, dash.dashboardId) : null;
+ if (pinned) {
+ if (dashboardNameKey(pinned.name) !== dashboardNameKey(dash.name) && typeof opts.warn === 'function') {
+ opts.warn(`dashboard "${dash.name}": the dashboard this spec was downloaded from (${pinned.id}) is now named '${pinned.name}'. It is reused under that name — a build does not rename an existing dashboard — so set the spec's name to '${pinned.name}' to match.`);
+ }
+ runner.skip('dashboards', `dashboard "${dash.name}" (exists — reuse by its dashboardId; tile edits aren't applied on rebuild, recreate to change)`);
+ result.created.dashboards[dash.name] = pinned.id;
+ continue;
+ }
// Additive discover-reconcile (design §14): a dashboard is global (identity = name), so a rebuild
// or retry must REUSE the existing one instead of createArtifact-ing a duplicate every run (the old
// behavior). Discovery is `resolveArtifact('dashboard', { name })` — findArtifact does NOT support
@@ -3939,7 +4188,7 @@ async function runSdkBuild(spec, opts = {}) {
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);
+ await provision.updateElement('app', existingId, '/siteMap', await siteMapOverLive(provision, existingId, def.siteMap, opts, result.created));
const aiDescriptionChanged = await applyAppAiDescription(provision, spec, existingId);
requireSuccessfulPush(await pushAppHeader(provision, existingId, def.name, aiDescriptionChanged), `app ${def.name}`, opts.warn);
reportPartialPush(await provision.publishArtifact('app', existingId), `app ${def.name}`, opts.warn);
@@ -4224,7 +4473,7 @@ async function runSdkBuild(spec, opts = {}) {
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);
+ await provision.updateElement('app', result.created.app, '/siteMap', await siteMapOverLive(provision, result.created.app, full.siteMap, opts, result.created));
// #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.
const headerChanged = await applyAppAiDescription(provision, spec, result.created.app);
@@ -4366,12 +4615,13 @@ async function runSdkBuild(spec, opts = {}) {
// A modest retry budget still helps: on an established app the override row is queryable ~580ms
// after the write (measured live), so the SDK's 4-attempt/500ms default is tight but the budget
// is only ever spent when the row is genuinely absent.
- const r = await provision.setAppAiFeatures(appUnique, flags, {
+ const encodedFlags = encodeAiFlags(flags);
+ const r = rebucketNonEnablingSkips(await provision.setAppAiFeatures(appUnique, encodedFlags, {
solutionUniqueName,
appModuleId: result.created.app || undefined,
verifyAttempts: 8,
verifyDelayMs: 1000,
- });
+ }), encodedFlags);
result.created.ai.appFeatures = r;
// `applied` is the SDK's ONLY success bucket: a feature reaches it only when the APP-SCOPE
// override row is proven present holding the requested value. Every other bucket is a
@@ -4383,7 +4633,9 @@ async function runSdkBuild(spec, opts = {}) {
// offered as the explanation. Since AB#6688904 the SDK ATTEMPTS every write
// and reads the gate only afterwards, to explain a failure that happened —
// it no longer pre-empts the write, so this bucket is now evidence, not a
- // prediction.
+ // prediction. Only a request that turns the feature ON keeps this bucket:
+ // rebucketNonEnablingSkips moves any other to notPersisted (the SDK's own
+ // test for "turns on" is wrong for grid search and M365).
// unverified — the write was issued but the proof could not be READ (no access to
// appsettings/settingdefinitions/appmodules, or a transport error).
// failed — the write threw. The SDK keeps going so the rest of the batch still
@@ -4881,7 +5133,7 @@ async function runSdkBuild(spec, opts = {}) {
try {
await provision.fetchArtifact('app', result.created.app);
reportPartialPush(await provision.publishArtifact('app', result.created.app), `app ${(spec.app && spec.app.name) || result.created.app}`, opts.warn);
- const retry = await provision.setAppAiFeatures(appUnique, retryFlags, {
+ const retry = await provision.setAppAiFeatures(appUnique, encodeAiFlags(retryFlags), {
solutionUniqueName: spec.solution && spec.solution.uniqueName,
appModuleId: result.created.app,
verifyAttempts: 6,
@@ -4907,7 +5159,7 @@ async function runSdkBuild(spec, opts = {}) {
const setting = AI_APP_SETTING[p.feature];
let proof = { error: app.error };
if (!app.error && setting) proof = await proveAppOverride(provision, app.appModuleId, setting);
- if (!proof.error && proof.exists && sameSettingValue(proof.value, featureWantValue(flags && flags[p.feature], p.feature))) {
+ if (!proof.error && proof.exists && sameSettingValue(proof.value, featureWantValue(flags && flags[p.feature], p.feature), p.feature)) {
reproven.push(p.feature);
reprovenBy.set(p.feature, 'confirmed present after publish by the build\u2019s own override-row proof');
continue;
@@ -4943,4 +5195,4 @@ async function runSdkBuild(spec, opts = {}) {
return result;
}
-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 };
+module.exports = { runSdkBuild, normalizeFormId, planFor, annotateLivePlan, resolvePhases, PHASES, BuildHalt, SDK_COLUMN_TYPE, viewDef, defaultViewColumns, subgridLabel, enrichesDefaultViews, dashboardsInSolution, findDashboardsByName, findPinnedDashboard, artifactIdentityQuery, resolveExistingFormId, FORM_TYPE_CODE, chartDef, dashboardTileOpts, dashboardComponent, compileFormIntent, formFieldLogicals, appDef, appUniqueName, applyAppAiDescription, haltOnUnpublishedAppHeader, pushAppHeader, commandsByEntity, commandDef, businessRuleDef, businessRuleFilter, bpfDef, bpfFilter, webResourceOpts, WEB_RESOURCE_KINDS, FORM_EVENTS, acquireAppPagesLease, personaRoleSpecFor, resolveRoleBusinessUnit, roleBuClause, roleGrantLabel, resolveRoleGrantTarget };
diff --git a/plugins/model-apps/scripts/lib/sdk-http-client.js b/plugins/model-apps/scripts/lib/sdk-http-client.js
index 6e7429253..9227dc836 100644
--- a/plugins/model-apps/scripts/lib/sdk-http-client.js
+++ b/plugins/model-apps/scripts/lib/sdk-http-client.js
@@ -12,6 +12,184 @@
// throw purely on a non-2xx HTTP status.
const { dataverseOrigin, getAuthToken, makeRequest } = require('./dataverse-auth.js');
+// How Dataverse reports that SQL Server chose a request's transaction as a deadlock VICTIM and rolled
+// it back. Two live captures, both HTTP 500 (a process-flow delete during a teardown, and PublishXml):
+// HTTP 500 from …/api/data/v9.0/workflows(<id>): Sql error: Generic SQL error. CRM ErrorCode: -2147204784 Sql ErrorCode: -2146232060 Sql Number: 1205
+// {"error":{"code":"0x80044150","message":" Sql error: Generic SQL error. CRM ErrorCode: -2147204784 Sql ErrorCode: -2146232060 Sql Number: 1205"}}
+// Only the SQL number identifies it; the code and message text are shared with every other SQL error.
+// The vendored SDK recognizes the same marker for its own re-send of reads, app creates and PublishXml.
+const SQL_DEADLOCK_VICTIM = /\bSql Number:\s*1205\b/i;
+// At most this many re-sends of a deadlock victim, 1 s / 2 s / 4 s apart — the SDK's own schedule.
+const DEADLOCK_RESENDS = 3;
+// The longest `Retry-After` honoured in full. Dataverse's service protection limits answer 429 with
+// `Retry-After` in seconds and ask the caller to wait that long; a request sent sooner is refused again
+// and spends one of the few attempts. The cap keeps a large value from stalling a build or a teardown
+// for minutes per attempt.
+// See: https://learn.microsoft.com/power-apps/developer/data-platform/api-limits#retry-operations
+const RETRY_AFTER_CAP_MS = 60000;
+
+/**
+ * The wait a response asks for in `Retry-After`, in milliseconds, capped at RETRY_AFTER_CAP_MS; 0 when
+ * the header is absent or unreadable. RFC 9110 allows two forms, delay-seconds and an HTTP date:
+ * Retry-After: 20
+ * Retry-After: Wed, 30 Sep 2026 10:00:20 GMT
+ * Node lowercases response header names; a test double may not, so the name is matched case-insensitively.
+ * See: https://www.rfc-editor.org/rfc/rfc9110#field.retry-after
+ */
+function retryAfterMs(headers, now = Date.now()) {
+ if (!headers || typeof headers !== 'object') return 0;
+ const key = Object.keys(headers).find((k) => k.toLowerCase() === 'retry-after');
+ if (key === undefined) return 0;
+ const raw = String(Array.isArray(headers[key]) ? headers[key][0] : headers[key]).trim();
+ let ms = 0;
+ if (/^\d+$/.test(raw)) ms = Number(raw) * 1000;
+ else if (raw) {
+ const at = Date.parse(raw);
+ if (Number.isFinite(at)) ms = at - now;
+ }
+ return Number.isFinite(ms) && ms > 0 ? Math.min(ms, RETRY_AFTER_CAP_MS) : 0;
+}
+
+/** True when a raw transport response says SQL rolled this request back as a deadlock victim. */
+function isSqlDeadlockVictim(res) {
+ if (!res || res.statusCode !== 500 || res.body === undefined || res.body === null) return false;
+ return SQL_DEADLOCK_VICTIM.test(typeof res.body === 'string' ? res.body : JSON.stringify(res.body));
+}
+
+/**
+ * True when a `$batch` REQUEST may be sent again after a proven rollback: every operation in it is a
+ * DELETE conditioned on the exact row version its caller read. That is the vendored SDK's atomic app
+ * delete, the app and its sitemap in one change set (abridged):
+ * --batch_<id>
+ * Content-Type: multipart/mixed;boundary=changeset_<id>
+ *
+ * --changeset_<id>
+ * Content-Type: application/http
+ * Content-ID: 1
+ *
+ * DELETE https://contoso.crm.dynamics.com/api/data/v9.0/appmodules(<id>) HTTP/1.1
+ * If-Match: W/"1001"
+ *
+ * --changeset_<id>--
+ * --batch_<id>--
+ * A second send of such a batch meets the rows exactly as the first did, or is refused with 412: it cannot
+ * remove anything its caller did not read. No other batch qualifies. Notably the SDK updates a generative
+ * page's files in a batch of `If-Match: *` writes after checking their versions itself; sent again after
+ * a backoff, that batch would skip the check and overwrite another maker's edit. An unconditional DELETE
+ * does not qualify either (the SDK's create rollback sends those; it is sent once, as before).
+ */
+function isConditionalDeleteBatch(body) {
+ if (typeof body !== 'string') return false;
+ const lines = body.split(/\r?\n/);
+ const ops = [];
+ for (let i = 0; i < lines.length; i += 1) {
+ const request = /^([A-Z]+) \S+ HTTP\/1\.1$/.exec(lines[i]);
+ if (!request) continue;
+ let ifMatch;
+ for (let j = i + 1; j < lines.length && lines[j] !== ''; j += 1) {
+ const m = /^If-Match:\s*(\S.*?)\s*$/i.exec(lines[j]);
+ if (m) ifMatch = m[1];
+ }
+ ops.push({ method: request[1], ifMatch });
+ }
+ return ops.length > 0 && ops.every((op) => op.method === 'DELETE' && op.ifMatch && op.ifMatch !== '*');
+}
+
+/**
+ * True when a `$batch` ANSWER proves nothing in it committed, because SQL rolled every operation back as a
+ * deadlock victim. A change set is atomic: when an operation in it fails, the whole set is rolled back and
+ * only the failing operation is answered. Captured live on a teardown's app delete (HTTP 500 for the
+ * batch, abridged):
+ * --batchresponse_<id>
+ * Content-Type: multipart/mixed; boundary=changesetresponse_<id>
+ *
+ * --changesetresponse_<id>
+ * Content-Type: application/http
+ * Content-ID: 1
+ *
+ * HTTP/1.1 500 Internal Server Error
+ * {"error":{"code":"0x80044150","message":" Sql error: Generic SQL error. ... Sql Number: 1205"}}
+ * --changesetresponse_<id>--
+ * --batchresponse_<id>--
+ * The answer is read part by part (the text between delimiter lines, `--<boundary>`), and it proves the
+ * rollback only when it is complete (it closes the boundary it opened with: first line `--<boundary>`,
+ * last line `--<boundary>--`), it answers at least one operation, and EVERY operation's own part is a 500
+ * carrying the deadlock marker. Anything
+ * else (one success, another failure, an operation whose part does not name the deadlock itself, a
+ * truncated answer) is returned as it came.
+ */
+function isBatchDeadlockVictim(res) {
+ const results = batchResults(res);
+ return !!results && results.length > 0 && results.every((r) => r.status === '500' && SQL_DEADLOCK_VICTIM.test(r.text));
+}
+
+/**
+ * The operations a complete multipart `$batch` answer reports, as `{ status, text }` per part (the text
+ * between delimiter lines, `--<boundary>`), or null when the answer is not a complete multipart envelope
+ * (its first line `--<boundary>`, its last `--<boundary>--`). Parts without an `HTTP/1.1 <status>` line
+ * (the change-set headers) are not operations and are left out.
+ */
+function batchResults(res) {
+ if (!res || typeof res.body !== 'string') return null;
+ const lines = res.body.split(/\r?\n/);
+ const nonEmpty = lines.map((l) => l.trim()).filter(Boolean);
+ const outer = /^--(\S+)$/.exec(nonEmpty[0] || '');
+ if (!outer || nonEmpty[nonEmpty.length - 1] !== `--${outer[1]}--`) return null;
+ const parts = [];
+ let part = null;
+ for (const line of lines) {
+ if (/^--\S/.test(line)) {
+ if (part) parts.push(part);
+ part = [];
+ } else if (part) {
+ part.push(line);
+ }
+ }
+ return parts
+ .map((p) => ({ status: (p.map((l) => /^HTTP\/1\.1 (\d{3})\b/.exec(l)).find(Boolean) || [])[1], text: p.join('\n') }))
+ .filter((r) => r.status);
+}
+
+/**
+ * True when a `$batch` ANSWER proves the server refused to START it (HTTP 429), so nothing in it ran.
+ * Two shapes qualify:
+ * - the whole request refused before any operation was read: a plain error answer with status 429, not
+ * a multipart one — service protection limits answer this way, e.g.
+ * HTTP 429 {"error":{"code":"0x80072322","message":"Number of requests exceeded the limit of 6000 over time window of 300 seconds."}}
+ * - a complete multipart answer in which EVERY operation it answers is a 429 (read part by part, as
+ * isBatchDeadlockVictim reads a deadlock).
+ * An answer that starts as a multipart envelope but is cut short proves nothing and is returned as it came.
+ * See: https://learn.microsoft.com/power-apps/developer/data-platform/api-limits
+ */
+function isBatchThrottled(res) {
+ if (!res) return false;
+ const body = typeof res.body === 'string' ? res.body : '';
+ const first = body.split(/\r?\n/).map((l) => l.trim()).find(Boolean) || '';
+ if (!/^--\S/.test(first)) return res.statusCode === 429;
+ const results = batchResults(res);
+ return !!results && results.length > 0 && results.every((r) => r.status === '429');
+}
+
+/**
+ * The longest `Retry-After` the throttled operations of a multipart `$batch` answer carry in their OWN
+ * headers, in milliseconds (capped as retryAfterMs caps it); 0 when none does. An operation refused
+ * inside a batch is answered with its own status line and headers, which the outer response need not
+ * repeat:
+ * HTTP/1.1 429 Too Many Requests
+ * Retry-After: 30
+ * Content-Type: application/json; odata.metadata=minimal
+ */
+function batchRetryAfterMs(res, now = Date.now()) {
+ const results = batchResults(res);
+ if (!results) return 0;
+ let longest = 0;
+ for (const r of results) {
+ if (r.status !== '429') continue;
+ const m = /^Retry-After:[ \t]*(\S.*?)[ \t]*$/im.exec(r.text);
+ if (m) longest = Math.max(longest, retryAfterMs({ 'retry-after': m[1] }, now));
+ }
+ return longest;
+}
/**
* Build an HttpClient bound to one Dataverse org.
* @param {string} orgUrl - e.g. https://contoso.crm.dynamics.com
@@ -40,6 +218,7 @@ function createAzHttpClient(orgUrl, deps = {}) {
const request = deps.request || makeRequest;
const sleep = deps.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
const random = deps.random || Math.random;
+ const now = deps.now || Date.now;
// Transient HTTP statuses worth retrying with backoff — throttling, gateway hiccups, and
// SQL deadlocks (Dataverse surfaces deadlock 1205 as a 500 from PublishXml under load).
//
@@ -80,6 +259,9 @@ function createAzHttpClient(orgUrl, deps = {}) {
const base = Math.min(1000 * 2 ** attempt, 8000);
return base + Math.floor(random() * base * 0.25);
};
+ // The wait before re-sending an answered request: the backoff above, or longer when the answer asks
+ // for longer in `Retry-After` (retryAfterMs, capped).
+ const retryWaitMs = (res, attempt) => Math.max(backoffMs(attempt), retryAfterMs(res.headers, now()));
let token = null;
function ensureToken(options = {}) {
@@ -118,16 +300,19 @@ function createAzHttpClient(orgUrl, deps = {}) {
// - RECORD deletes (webresourceset, appmodule, savedquery, appaction, solutions, …) must NOT
// retry: Dataverse's "More than one concurrent Delete requests detected" guard PERMANENTLY
// wedges the record when a retry races the still-in-flight first delete (web-resource deletes
- // SQL-time-out under load and trip exactly this). One delete keeps the failure re-runnable.
+ // SQL-time-out under load and trip exactly this). One delete keeps the failure re-runnable —
+ // unless the server ANSWERS that it did not run it (see the re-sends below).
// - A `$batch` change set is a POST, but it CARRIES record deletes (the SDK deletes an app and
// its sitemap in one atomic change set), so it inherits the record-delete hazard above. It is
// also ambiguous on failure: the server may have committed while the response was lost, so a
// blind re-issue is exactly the racing retry that wedges the row. Issue it once and let the
- // SDK surface the unknown outcome to the caller.
+ // SDK surface the unknown outcome to the caller — unless it is a batch of conditional deletes and
+ // its answer proves no operation in it ran (see the re-sends below).
const method_ = String(method).toUpperCase();
const isMetadataDelete = /\/(EntityDefinitions|RelationshipDefinitions|GlobalOptionSetDefinitions)\b/i.test(url);
const isBatch = method_ === 'POST' && /\/\$batch(\?|$)/i.test(url);
- const noRetry = (method_ === 'DELETE' && !isMetadataDelete) || isBatch;
+ const recordDelete = method_ === 'DELETE' && !isMetadataDelete;
+ const noRetry = recordDelete || isBatch;
const isWrite = method_ !== 'GET';
// A CONDITIONAL write that got NO answer (a timeout or a dropped connection) is never re-sent.
// It may still commit — and if it does, the re-send carries a token the first attempt already
@@ -176,7 +361,35 @@ function createAzHttpClient(orgUrl, deps = {}) {
continue;
}
if (TRANSIENT.has(res.statusCode) && !last && !noRetry) {
- await sleep(backoffMs(attempt));
+ await sleep(retryWaitMs(res, attempt));
+ continue;
+ }
+ // A record DELETE or a `$batch` is otherwise never re-sent (see noRetry). Two ANSWERS are the
+ // exceptions, because in each the server says it did not run the request: nothing is still in
+ // flight to race the concurrent-delete guard, and nothing was deleted.
+ // - HTTP 429: the server refused to START the request. Measured live, in two teardowns: the
+ // solution delete that ends a teardown, sent right after the teardown's own table delete, was
+ // refused with
+ // HTTP 429 … solutions(<id>): Cannot start the requested operation [Uninstall] because there is
+ // another [EntityCustomization] running at this moment. … Please try again later.
+ // and both teardowns finished with the solution left behind. It is re-sent on the schedule of any
+ // other throttled request, honouring `Retry-After`.
+ // - A SQL deadlock VICTIM: SQL rolled the request's transaction back. Measured live: a teardown's
+ // process-flow delete failed exactly this way, and so did a teardown's app delete — a change set —
+ // which stopped the whole teardown with nothing removed; both were clean on a re-run.
+ // A batch is re-sent only when it is made of conditional deletes (isConditionalDeleteBatch) and its
+ // answer shows that no operation in it ran (isBatchThrottled, isBatchDeadlockVictim).
+ const conditionalDeleteBatch = isBatch && isConditionalDeleteBatch(bodyStr);
+ const throttled = (recordDelete && res.statusCode === 429) || (conditionalDeleteBatch && isBatchThrottled(res));
+ if (throttled && !last) {
+ // A batch refused operation by operation may carry the wait in that operation's own headers.
+ await sleep(Math.max(retryWaitMs(res, attempt), isBatch ? batchRetryAfterMs(res, now()) : 0));
+ continue;
+ }
+ const deadlocked = (recordDelete && isSqlDeadlockVictim(res))
+ || (conditionalDeleteBatch && isBatchDeadlockVictim(res));
+ if (deadlocked && attempt < DEADLOCK_RESENDS) {
+ await sleep(1000 * 2 ** attempt);
continue;
}
return {
@@ -208,4 +421,4 @@ function createAzHttpClient(orgUrl, deps = {}) {
};
}
-module.exports = { createAzHttpClient };
+module.exports = { createAzHttpClient, SQL_DEADLOCK_VICTIM, isBatchDeadlockVictim, isBatchThrottled, batchRetryAfterMs, isConditionalDeleteBatch, retryAfterMs, RETRY_AFTER_CAP_MS };
diff --git a/plugins/model-apps/scripts/lib/sdk-teardown.js b/plugins/model-apps/scripts/lib/sdk-teardown.js
index 3b01b5039..4a805274f 100644
--- a/plugins/model-apps/scripts/lib/sdk-teardown.js
+++ b/plugins/model-apps/scripts/lib/sdk-teardown.js
@@ -53,7 +53,7 @@
// the identical phase-grouped, status-marked log.
const { topoOrderEntities } = require('./_graph.js');
-const { appUniqueName, commandsByEntity, defaultViewColumns, enrichesDefaultViews, dashboardsInSolution, findDashboardsByName, resolveExistingFormId, resolveRoleBusinessUnit, roleBuClause, bpfFilter } = require('./sdk-build.js');
+const { appUniqueName, commandsByEntity, defaultViewColumns, enrichesDefaultViews, dashboardsInSolution, findDashboardsByName, findPinnedDashboard, resolveExistingFormId, resolveRoleBusinessUnit, roleBuClause, bpfFilter } = require('./sdk-build.js');
const { manifestResourceName, parseManifestBase64 } = require('./page-manifest.js');
const { relationshipSchemaName, manyToManySchemaName, lookupColumnsFor, SDK_ROLE_MARKER, canonicalPersonaName, FORM_GUID_RE } = require('./app-spec.js');
const { selectSummaryTables } = require('./ai-candidates.js');
@@ -347,13 +347,34 @@ const KIND_HANDLERS = {
// The name lookup fails closed like the membership read below. runTeardown reads an error that says
// "not found" — a failed paginated read, a proxy's 404 — as an empty resolution, so the dashboard was
// reported absent and the solution, the only thing a re-run can ask about ownership, then deleted.
+ //
+ // A downloaded spec also pins the dashboard it was read from (dashboards[].dashboardId), which the
+ // build and verify resolve BEFORE the name — so when the pin resolves it is the only candidate here
+ // too. Adding it to the name matches instead would also take a dashboard that has since been given
+ // the old name. It still has to pass the solution-membership rule below. When the pin resolves to
+ // nothing (a spec downloaded from another environment), the name decides, as it does for the build.
+ // The pin lookup fails closed like the name lookup.
+ let pinned = null;
+ if (target.dashboardId) {
+ try {
+ pinned = await findPinnedDashboard(sdk, target.dashboardId);
+ } catch (err) {
+ const e = new Error(`could not look up the dashboard pinned as '${target.name}' (${errMsg(err)}) — none is deleted; re-run the teardown`);
+ e.failClosed = true;
+ throw e;
+ }
+ }
let items;
- try {
- items = await findDashboardsByName(sdk, target.name);
- } catch (err) {
- const e = new Error(`could not look up dashboards named '${target.name}' (${errMsg(err)}) — none is deleted; re-run the teardown`);
- e.failClosed = true;
- throw e;
+ if (pinned) {
+ items = [pinned];
+ } else {
+ try {
+ items = await findDashboardsByName(sdk, target.name);
+ } catch (err) {
+ const e = new Error(`could not look up dashboards named '${target.name}' (${errMsg(err)}) — none is deleted; re-run the teardown`);
+ e.failClosed = true;
+ throw e;
+ }
}
if (!items.length) return [];
// Found by NAME, and Dataverse neither keeps names unique nor compares them exactly (it ignores
@@ -920,7 +941,7 @@ function planTeardown(spec) {
for (const d of spec.dashboards || []) {
// The solution travels with the step so the resolver can tell this app's dashboards from other
// apps' that share the name (see KIND_HANDLERS.dashboard).
- steps.push({ kind: 'dashboard', phase: 'dashboards', label: `dashboard "${d.name}"`, target: { name: d.name, solutionUniqueName: spec.solution && spec.solution.uniqueName } });
+ steps.push({ kind: 'dashboard', phase: 'dashboards', label: `dashboard "${d.name}"`, target: { name: d.name, solutionUniqueName: spec.solution && spec.solution.uniqueName, ...(d.dashboardId ? { dashboardId: d.dashboardId } : {}) } });
}
// Command bars: FAIL-CLOSED (data-loss guard, PR #229 review). Only tear down the bar for a table
// THIS spec CREATES (existing !== true) — a brand-new table has no pre-existing foreign buttons, and
diff --git a/plugins/model-apps/scripts/lib/sitemap-merge.js b/plugins/model-apps/scripts/lib/sitemap-merge.js
new file mode 100644
index 000000000..4bd1081e6
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/sitemap-merge.js
@@ -0,0 +1,472 @@
+'use strict';
+// Rewrite an EXISTING app's sitemap without destroying what the App Spec cannot describe
+// (AB#6726727).
+//
+// The build describes navigation from the App Spec (appDef, sdk-build.js), which carries each node's
+// label or title, its target and its icons — nothing else. The vendored SDK projects a FETCHED sitemap
+// into typed nodes that each keep a `bag`: every attribute and child the typed layer does not model
+// (`Url`, `Client`, `Sku`, `AvailableOffline`, `ResourceId`, titles in other languages, `<Privilege>`
+// entries). A node that arrives WITHOUT a bag is serialized from scratch with the classic designer's
+// defaults for a new node:
+//
+// <SubArea Id="sub_0_0_0" DefaultDashboard="…" ResourceId="SitemapDesigner.NewSubArea"
+// Client="All,Outlook,OutlookLaptopClient,OutlookWorkstationClient,Web"
+// Sku="All,OnPremise,Live,SPLA" AvailableOffline="true" PassParams="false">
+//
+// Every existing-app build handed the SDK bag-less nodes, so any edit — even an unrelated one —
+// rewrote every live node that way. A designer-made dashboard entry
+//
+// <SubArea Id="ops_dashboard" Url="/workplace/home_dashboards.aspx" DefaultDashboard="…"
+// Client="All,Web" AvailableOffline="false">
+//
+// lost its launcher `Url`, and with it the dashboard glyph: the runtime shows that glyph only for a
+// subarea whose Url is the dashboard launcher, and the designer only recognizes a subarea as a
+// dashboard entry by that Url (it writes it on every dashboard entry it creates).
+//
+// `adoptLiveSitemap` re-attaches each node the build wants to the LIVE node it corresponds to and
+// keeps the live `id` and `bag`, so the SDK re-emits the node as it was and overlays only the fields
+// the spec sets. A subarea corresponds by its navigation TARGET (the identity the SDK itself uses to
+// spot duplicates); areas and groups have no target, so they correspond by label, then by the id an
+// earlier build of this plugin gave them.
+
+// The fixed launcher path the designer gives every dashboard entry it creates, and the one the
+// runtime keys the dashboard glyph on.
+const DASHBOARD_LAUNCHER_URL = '/workplace/home_dashboards.aspx';
+
+// Whether a subarea Url is the dashboard launcher to BOTH of its consumers: the designer recognizes a
+// dashboard entry only when the whole Url equals the launcher (compared lower-cased), and the runtime
+// shows the dashboard glyph only when the Url contains it (compared case-SENSITIVELY). Only the exact
+// launcher satisfies both — `/WorkPlace/Home_Dashboards.aspx` passes the designer and fails the
+// runtime; a query suffix passes the runtime and fails the designer.
+function isDashboardLauncherUrl(url) {
+ return url === DASHBOARD_LAUNCHER_URL;
+}
+
+// A GUID as Dataverse may store it in sitemap XML (`{280948EC-…}`, bare, either case) → bare lower.
+const bareGuid = (v) => String(v === undefined || v === null ? '' : v).trim().replace(/^\{|\}$/g, '').toLowerCase();
+const text = (v) => (typeof v === 'string' ? v.trim() : '');
+
+// A URL target compared the way it is resolved. A web-resource reference names a Dataverse web
+// resource, whose names are case-insensitive, so it folds; an http(s) URL folds only its scheme and
+// host — a path or query value can be case-sensitive, and folding it would let an intended change of
+// case look like the live entry and be written back over.
+function urlIdentity(url) {
+ const u = text(url);
+ if (/^\$webresource:/i.test(u) || /^\/webresources\//i.test(u)) return u.toLowerCase();
+ const m = /^([a-z][a-z0-9+.-]*:\/\/[^/?#]*)(.*)$/i.exec(u);
+ return m ? m[1].toLowerCase() + m[2] : u;
+}
+
+/**
+ * The comparable identity of a subarea's navigation TARGET, or undefined when it has none.
+ *
+ * Like the SDK's own `subAreaTargetKey` (its duplicate check): `(type, target)`, GUIDs normalized,
+ * logical names case-folded — except a URL, which keeps the case of its path and query (urlIdentity).
+ * Neither the SubArea `Id` nor its title says where an entry navigates, so neither can identify it
+ * across a download → edit → build round trip.
+ */
+function subAreaTargetKey(sub) {
+ if (!sub || typeof sub !== 'object') return undefined;
+ switch (sub.type) {
+ case 'Entity': return text(sub.entity) ? `Entity:${text(sub.entity).toLowerCase()}` : undefined;
+ case 'URL': return text(sub.url) ? `URL:${urlIdentity(sub.url)}` : undefined;
+ case 'DashBoard': return bareGuid(sub.dashboardId) ? `DashBoard:${bareGuid(sub.dashboardId)}` : undefined;
+ case 'CustomPage': return text(sub.page) ? `CustomPage:${text(sub.page).toLowerCase()}` : undefined;
+ case 'GenPage': return bareGuid(sub.genPageId) ? `GenPage:${bareGuid(sub.genPageId)}` : undefined;
+ default: return undefined;
+ }
+}
+
+// The target attribute each subarea type carries. When a desired subarea is adopted, its target is
+// taken VERBATIM from the live node: the two compare equal only after normalization, and re-writing
+// `{280948EC-…}` as `280948ec-…` would change the XML for nothing. A URL is not listed: the spec's
+// own spelling is what it asks for, and its identity already differs only where case cannot matter.
+const TARGET_FIELD = { Entity: 'entity', DashBoard: 'dashboardId', CustomPage: 'page', GenPage: 'genPageId' };
+
+// Deep copy of a bag, so the tree handed to the SDK never aliases the workspace copy it was read from.
+const cloneBag = (bag) => (bag === undefined ? undefined : JSON.parse(JSON.stringify(bag)));
+
+// The attribute value of a raw bag node, e.g. `LCID` on `{ n: 'Title', a: [['LCID','1033'], ['Title','Ops']] }`.
+const rawAttr = (node, key) => {
+ const pair = node && Array.isArray(node.a) ? node.a.find(([k]) => k === key) : undefined;
+ return pair ? pair[1] : undefined;
+};
+
+/**
+ * Make an ADOPTED node's bag carry the title the spec asks for at the SDK's language, which the SDK
+ * will not do on its own for a node that has a bag. Its rebuild patches the `<Title LCID="…">` inside
+ * an EXISTING `<Titles>` (adding the entry when missing), but it only synthesizes the wrapper for a
+ * from-scratch node, and it reads an empty typed title as "no edit". So:
+ * - a title where the live node has no `<Titles>` at all: an empty wrapper is added first in the
+ * node (where the SDK puts a synthesized one) for the SDK to fill;
+ * - no title where the live node has one at this language: that `<Title>` is dropped, and the other
+ * languages' titles are kept — the bag-less write this replaces dropped every language.
+ * Bag children are `{ i, node }` with absolute child indices (modeled children fill the gaps), so an
+ * insertion shifts every index after it up, and a removal shifts every index after it down — or a
+ * modeled child would fill the vacated slot ahead of the kept ones, e.g. a `<SubArea>` written before
+ * the group's `<Descriptions>`, which the sitemap schema does not allow.
+ */
+function reconcileTitleChild(bag, title, liveTitle, lcid) {
+ if (!bag || !Array.isArray(bag.c)) return;
+ const lang = String(lcid);
+ const at = bag.c.findIndex((e) => e && e.node && e.node.n === 'Titles');
+ if (text(title)) {
+ if (at < 0) {
+ bag.c = [{ i: 0, node: { n: 'Titles', a: [], c: [] } }, ...bag.c.map((e) => ({ ...e, i: e.i + 1 }))];
+ }
+ return;
+ }
+ if (!text(liveTitle) || at < 0) return;
+ const titles = bag.c[at].node;
+ titles.c = (titles.c || []).filter((n) => !(n && n.n === 'Title' && rawAttr(n, 'LCID') === lang));
+ if (!titles.c.some((n) => n && n.n === 'Title')) {
+ const gone = bag.c[at].i;
+ bag.c = bag.c.filter((_, k) => k !== at).map((e) => (e.i > gone ? { ...e, i: e.i - 1 } : e));
+ }
+}
+
+// Icons compare case-insensitively: appDef lower-cases a bare web-resource name (the icon lookup is
+// case-insensitive), so a live `new_Icon.svg` and a spec `new_icon.svg` are the same icon. Titles
+// compare exactly — a changed capital is a real rename.
+const CHROME = [
+ { field: 'title', same: (a, b) => text(a) === text(b) },
+ { field: 'icon', same: (a, b) => text(a).toLowerCase() === text(b).toLowerCase() },
+ { field: 'vectorIcon', same: (a, b) => text(a).toLowerCase() === text(b).toLowerCase() },
+];
+
+/**
+ * Whether a rebuild KEEPS a live nav entry's `field` rather than writing the spec's value: the spec
+ * still has the value its baseline (`base`, from chromeByTargetKey) recorded for the entry and the
+ * environment no longer does — so the change was made there, after the baseline, and the spec is
+ * stale for that field rather than asking for it. (The spec and live values then differ, too.) The one
+ * rule both the build and `--verify` apply, so verify accepts exactly what the build kept.
+ */
+function keepsLiveValue(field, specValue, liveValue, base) {
+ const rule = CHROME.find((c) => c.field === field);
+ if (!rule || !base) return false;
+ return rule.same(specValue, base[field]) && !rule.same(liveValue, base[field]);
+}
+
+/**
+ * Re-attach `desired` (appDef's `siteMap`) to the `live` sitemap the SDK fetched for the same app.
+ *
+ * Returns `{ siteMap, notes }`. `siteMap` is a fresh tree: every node that corresponds to a live node
+ * carries the live `id` and `bag`; the rest are new and keep appDef's ids, renamed only where one
+ * would collide with an adopted id. `notes` lists what happened to existing nodes, for the build to
+ * report (`node` is 'area' | 'group' | 'subArea'):
+ * { kind: 'kept', node, target, field, live, spec } — see `baseChrome`
+ * { kind: 'changed', node, target, field, live, spec, intended? } — the build changes this value;
+ * `intended` when the baseline shows the spec did
+ *
+ * `opts.baseChrome` (optional) maps a subarea target key to `{ title, icon, vectorIcon }` as the spec
+ * last applied to — or downloaded from — this environment described it. With it, a value the spec
+ * has NOT changed since then but the environment HAS (a rename in the designer after the download)
+ * is kept, not silently reverted: the spec is stale for that field, not asking for a change. Without
+ * a baseline there is no telling the two apart, so the spec wins and the change is reported.
+ */
+function adoptLiveSitemap(desired, live, opts = {}) {
+ const baseChrome = opts.baseChrome instanceof Map ? opts.baseChrome : new Map();
+ // The language the SDK reads and writes titles in (its construction-time LCID).
+ const lcid = opts.lcid || 1033;
+ const liveAreas = (live && Array.isArray(live.areas)) ? live.areas : [];
+ const desiredAreas = (desired && Array.isArray(desired.areas)) ? desired.areas : [];
+ const kids = (node, key) => (node && Array.isArray(node[key]) ? node[key] : []);
+ const notes = [];
+
+ // Correspondence is decided in PASSES over a whole level, never node by node in document order: a
+ // weaker rule must not let an earlier node take a live node that a later one matches by a stronger
+ // rule. (A new first area gets appDef's `area_0`; if it could claim the live `area_0` by id before
+ // the moved area that is still labelled the same got to it, the two would swap identities.)
+ //
+ // Areas and groups have no target of their own. They correspond, in order of the evidence:
+ // 1. by a label their level uses exactly once, in the spec and live;
+ // 2. by the navigation entries they hold: a node and a live node whose entries are each other's
+ // strictly best overlap (the share of targets they have in common) are the same node — a relabelled
+ // one, or one of several with a repeated label. An entry can recur across areas (first-party
+ // sitemaps list a table under several), so it is the best overlap that counts, not any; a tie pairs
+ // nothing;
+ // 3. by the id this plugin gave them on an earlier build (`area_0`, `group_0_1`) — how a relabelled
+ // node with no entries to go by is recognized — but never a live node whose label an unpaired spec
+ // node still wants, nor two nodes whose entries all differ;
+ // 4. with no label at the SDK's language (a downloaded app titled only in another language) and no
+ // entries on either side, the next such live node in document order.
+ // A repeated label, or none, decides nothing by position where entries can speak. Taking the first
+ // live "Main", or the one whose id appDef's numbering happened to repeat, or the next unlabelled one,
+ // gave a new or reordered node another node's id and bag — with two live "Main"s and the first renamed
+ // in the spec, the one left took the renamed area's; with a leading area and a second "Main" added, the
+ // new leading `area_0` took the original's. A node none of the passes identifies is written as new
+ // rather than given another node's bag.
+ const sameTitle = (a, b) => text(a) !== '' && text(a).toLowerCase() === text(b).toLowerCase();
+ const labelKey = (n) => text(n && n.title).toLowerCase();
+ const sameId = (d, l) => text(l.id) !== '' && text(l.id).toLowerCase() === text(d.id).toLowerCase();
+ // How many nodes of a level carry each label (compared as sameTitle compares them).
+ const labelCounts = (list) => {
+ const counts = new Map();
+ for (const n of list) {
+ const k = n && typeof n === 'object' ? labelKey(n) : '';
+ if (k) counts.set(k, (counts.get(k) || 0) + 1);
+ }
+ return counts;
+ };
+ // The navigation targets of the entries under a node (subAreaTargetKey), as a Set.
+ const targetsOf = (subs) => {
+ const keys = new Set();
+ for (const sub of subs) {
+ const key = subAreaTargetKey(sub);
+ if (key) keys.add(key);
+ }
+ return keys;
+ };
+ const groupTargets = (group) => targetsOf(kids(group, 'subAreas'));
+ const areaTargets = (area) => targetsOf(kids(area, 'groups').flatMap((g) => kids(g, 'subAreas')));
+ const overlap = (a, b) => [...a].some((k) => b.has(k));
+ // The share of two nodes' targets they have in common (Jaccard): 1 for the same entries, 0 for none.
+ const similarity = (a, b) => {
+ if (!a.size || !b.size) return 0;
+ let common = 0;
+ for (const k of a) if (b.has(k)) common += 1;
+ return common / (a.size + b.size - common);
+ };
+ // The candidate with the strictly highest positive score, or null (none, or a tie at the top).
+ const strictBest = (scored) => {
+ let top = 0;
+ let at = null;
+ let tied = false;
+ for (const [candidate, score] of scored) {
+ if (score > top) { top = score; at = candidate; tied = false; } else if (score > 0 && score === top) tied = true;
+ }
+ return tied ? null : at;
+ };
+ const correspond = (want, have, targetsOfNode) => {
+ const live = have.filter((n) => n && typeof n === 'object');
+ const taken = new Set();
+ const match = new Array(want.length);
+ const pair = (i, l) => { match[i] = l; taken.add(l); };
+ const wantCounts = labelCounts(want);
+ const haveCounts = labelCounts(live);
+ const wantTargets = want.map((d) => (d && typeof d === 'object' ? targetsOfNode(d) : new Set()));
+ const haveTargets = new Map(live.map((l) => [l, targetsOfNode(l)]));
+ const stillWanted = (label) => label !== '' && want.some((d, i) => d && !match[i] && labelKey(d) === label);
+ const entriesDiffer = (i, l) => wantTargets[i].size > 0 && haveTargets.get(l).size > 0 && !overlap(wantTargets[i], haveTargets.get(l));
+ const unpaired = (fn) => want.forEach((d, i) => { if (!match[i] && d && typeof d === 'object') fn(d, i); });
+ unpaired((d, i) => {
+ if (wantCounts.get(labelKey(d)) !== 1 || haveCounts.get(labelKey(d)) !== 1) return;
+ const l = live.find((n) => !taken.has(n) && sameTitle(n.title, d.title));
+ if (l) pair(i, l);
+ });
+ // Repeated until nothing pairs: each pairing takes a candidate away, which can settle another's best.
+ for (let paired = true; paired;) {
+ paired = false;
+ unpaired((d, i) => {
+ if (!wantTargets[i].size) return;
+ const l = strictBest(live.filter((n) => !taken.has(n)).map((n) => [n, similarity(wantTargets[i], haveTargets.get(n))]));
+ if (!l) return;
+ const back = strictBest(want.map((o, j) => [j, !match[j] && o && typeof o === 'object' ? similarity(wantTargets[j], haveTargets.get(l)) : 0]));
+ if (back === i) { pair(i, l); paired = true; }
+ });
+ }
+ unpaired((d, i) => {
+ const l = live.find((n) => !taken.has(n) && sameId(d, n) && !stillWanted(labelKey(n)) && !entriesDiffer(i, n));
+ if (l) pair(i, l);
+ });
+ unpaired((d, i) => {
+ if (text(d.title) !== '' || wantTargets[i].size) return;
+ const l = live.find((n) => !taken.has(n) && text(n.title) === '' && !haveTargets.get(n).size);
+ if (l) pair(i, l);
+ });
+ return match;
+ };
+ const areaMatch = correspond(desiredAreas, liveAreas, areaTargets);
+ const groupMatch = desiredAreas.map((a, ai) => correspond(kids(a, 'groups'), kids(areaMatch[ai], 'groups'), groupTargets));
+
+ // Subareas correspond by navigation target: first within the live group their own group adopted (an
+ // entry that stayed put), then anywhere (an entry that moved). Each live node is adopted at most once.
+ const liveSubs = [];
+ for (const area of liveAreas) for (const group of kids(area, 'groups')) for (const sub of kids(group, 'subAreas')) {
+ const key = subAreaTargetKey(sub);
+ if (key) liveSubs.push({ sub, group, key });
+ }
+ const claimed = new Set();
+ const subMatch = desiredAreas.map((a) => kids(a, 'groups').map((g) => new Array(kids(g, 'subAreas').length)));
+ const subPass = (inOwnGroup) => desiredAreas.forEach((a, ai) => kids(a, 'groups').forEach((g, gi) => kids(g, 'subAreas').forEach((sub, si) => {
+ if (subMatch[ai][gi][si]) return;
+ const key = subAreaTargetKey(sub);
+ if (!key) return;
+ const own = groupMatch[ai][gi];
+ const hit = liveSubs.find((c) => !claimed.has(c.sub) && c.key === key && (!inOwnGroup || (own && c.group === own)));
+ if (hit) { subMatch[ai][gi][si] = hit; claimed.add(hit.sub); }
+ })));
+ subPass(true);
+ subPass(false);
+
+ const out = desiredAreas.map((area, ai) => {
+ const liveArea = areaMatch[ai];
+ const nextArea = { ...area, groups: [], __adopted: !!liveArea };
+ if (liveArea) {
+ nextArea.id = liveArea.id;
+ nextArea.bag = cloneBag(liveArea.bag);
+ reconcileTitleChild(nextArea.bag, area.title, liveArea.title, lcid);
+ if (text(area.title) !== text(liveArea.title)) {
+ notes.push({ kind: 'changed', node: 'area', target: `area "${text(liveArea.title) || liveArea.id}"`, field: 'title', live: text(liveArea.title), spec: text(area.title) });
+ }
+ }
+ kids(area, 'groups').forEach((group, gi) => {
+ const liveGroup = groupMatch[ai][gi];
+ const nextGroup = { ...group, subAreas: [], __adopted: !!liveGroup };
+ if (liveGroup) {
+ nextGroup.id = liveGroup.id;
+ nextGroup.bag = cloneBag(liveGroup.bag);
+ reconcileTitleChild(nextGroup.bag, group.title, liveGroup.title, lcid);
+ if (text(group.title) !== text(liveGroup.title)) {
+ notes.push({ kind: 'changed', node: 'group', target: `group "${text(liveGroup.title) || liveGroup.id}"`, field: 'title', live: text(liveGroup.title), spec: text(group.title) });
+ }
+ }
+ kids(group, 'subAreas').forEach((sub, si) => {
+ const pick = subMatch[ai][gi][si];
+ const nextSub = { ...sub, __adopted: !!pick };
+ if (pick) {
+ const liveSub = pick.sub;
+ nextSub.id = liveSub.id;
+ nextSub.bag = cloneBag(liveSub.bag);
+ const field = TARGET_FIELD[sub.type];
+ if (field && liveSub[field] !== undefined) nextSub[field] = liveSub[field];
+ // Every dashboard entry gets the exact launcher Url — the shape earlier builds wrote had none,
+ // which is what restores its glyph — since only that exact string satisfies both the designer
+ // and the runtime (isDashboardLauncherUrl). A live entry that already has it is unchanged.
+ if (sub.type === 'DashBoard') nextSub.dashboardUrl = DASHBOARD_LAUNCHER_URL;
+ const base = baseChrome.get(pick.key);
+ const label = text(liveSub.title) || text(sub.title) || pick.key;
+ for (const { field: f, same } of CHROME) {
+ if (same(sub[f], liveSub[f])) {
+ // Equal as far as the platform cares (an icon name differing only in case): re-emit the
+ // live string, so the node round-trips byte-for-byte.
+ if (text(liveSub[f])) nextSub[f] = liveSub[f];
+ continue;
+ }
+ if (keepsLiveValue(f, sub[f], liveSub[f], base)) {
+ // Changed in the environment since the baseline, untouched in the spec: keep it.
+ if (text(liveSub[f])) nextSub[f] = liveSub[f];
+ else delete nextSub[f];
+ notes.push({ kind: 'kept', node: 'subArea', target: `nav entry "${label}"`, field: f, live: text(liveSub[f]), spec: text(sub[f]) });
+ } else {
+ notes.push({ kind: 'changed', node: 'subArea', target: `nav entry "${label}"`, field: f, live: text(liveSub[f]), spec: text(sub[f]), ...(base ? { intended: true } : {}) });
+ }
+ }
+ reconcileTitleChild(nextSub.bag, nextSub.title, liveSub.title, lcid);
+ }
+ nextGroup.subAreas.push(nextSub);
+ });
+ nextArea.groups.push(nextGroup);
+ });
+ return nextArea;
+ });
+
+ // Ids must stay unique across the sitemap. An adopted node keeps its live id; a new node keeps
+ // appDef's positional id unless an adopted node already holds it (appDef numbers by position, so a
+ // new `area_1` can meet an adopted live `area_1` that has moved). Adopted ids are reserved FIRST so
+ // a new node earlier in the document can never take one.
+ const used = new Set();
+ const nodes = [];
+ for (const a of out) {
+ nodes.push(a);
+ for (const g of a.groups) {
+ nodes.push(g);
+ for (const s of g.subAreas) nodes.push(s);
+ }
+ }
+ for (const n of nodes) if (n.__adopted && text(n.id)) used.add(text(n.id).toLowerCase());
+ for (const n of nodes) {
+ const adopted = n.__adopted;
+ delete n.__adopted;
+ if (adopted) continue;
+ let id = text(n.id) || 'node';
+ if (used.has(id.toLowerCase())) {
+ let i = 2;
+ while (used.has(`${id}_${i}`.toLowerCase())) i += 1;
+ id = `${id}_${i}`;
+ }
+ n.id = id;
+ used.add(id.toLowerCase());
+ }
+ return { siteMap: { ...(desired || {}), areas: out }, notes };
+}
+
+// The id a plain `{ <name or key>: id }` map holds for `name` — only as the map's OWN entry, so a
+// dashboard named `constructor` never resolves to Object.prototype's.
+const ownId = (map, name) => (map && typeof map === 'object' && Object.prototype.hasOwnProperty.call(map, name) ? map[name] : undefined);
+const idMap = (v) => (v && typeof v === 'object' && !Array.isArray(v) ? v : {});
+
+// Every subarea of an App Spec, in document order.
+function specSubAreas(spec) {
+ const out = [];
+ const list = (v) => (Array.isArray(v) ? v : []);
+ for (const a of list(spec && spec.appShell && spec.appShell.areas)) {
+ for (const g of list(a && a.groups)) for (const s of list(g && g.subAreas)) if (s && typeof s === 'object') out.push(s);
+ }
+ return out;
+}
+
+/**
+ * The target key (see subAreaTargetKey) an App Spec subarea navigates to in one environment. A table
+ * or URL target is in the spec itself; a dashboard (named) or a page (by key — schemaVersion 2, which
+ * every loaded spec and every baseline is migrated to) takes its id from `ids`:
+ * `{ dashboards: { <name>: id }, pages: { <key>: id } }`. Undefined without a target or an id.
+ */
+function specSubAreaTargetKey(s, ids = {}) {
+ if (!s || typeof s !== 'object') return undefined;
+ if (s.entity) return subAreaTargetKey({ type: 'Entity', entity: s.entity });
+ if (s.dashboard) return subAreaTargetKey({ type: 'DashBoard', dashboardId: ownId(idMap(ids.dashboards), s.dashboard) });
+ if (s.page) return subAreaTargetKey({ type: 'GenPage', genPageId: ownId(idMap(ids.pages), s.page) });
+ if (s.url) return subAreaTargetKey({ type: 'URL', url: s.url });
+ return undefined;
+}
+
+/**
+ * The chrome (`title`, `icon`, `vectorIcon`) a BASELINE spec gives each nav entry, keyed by the target
+ * key the entry has in this environment — the key `adoptLiveSitemap` matches live entries by.
+ *
+ * A dashboard or page takes its id from the ids the baseline RECORDED for this environment
+ * (`__deployedIds`, written with it — see deployed-baseline.js) before `ids`, the ids this build (its
+ * `result.created`) or verify resolved: after the author renames a dashboard in the spec, as the
+ * build's warning asks, the baseline still names it by the old name, and only the recorded id still
+ * connects it to the live entry. The spec's own `dashboardId` / `pageId` are never read: a spec
+ * downloaded from one environment and built into another carries the first one's ids. An entry with
+ * no id either way is left out, and the spec then simply wins.
+ */
+function chromeByTargetKey(baseline, ids = {}) {
+ const map = new Map();
+ const recorded = idMap(baseline && baseline.__deployedIds);
+ // Spread copies own keys as data properties (never through the __proto__ setter), recorded ids last.
+ const resolved = {
+ dashboards: { ...idMap(ids.dashboards), ...idMap(recorded.dashboards) },
+ pages: { ...idMap(ids.pages), ...idMap(recorded.pages) },
+ };
+ for (const s of specSubAreas(baseline)) {
+ const key = specSubAreaTargetKey(s, resolved);
+ if (!key) continue;
+ // A target listed twice is ambiguous, so neither occurrence is used as a baseline.
+ map.set(key, map.has(key) ? null : { title: s.title, icon: s.icon, vectorIcon: s.vectorIcon });
+ }
+ for (const [k, v] of map) if (v === null) map.delete(k);
+ return map;
+}
+/**
+ * One warning line per note worth reporting. A `changed` subarea note the baseline explains (the spec
+ * itself changed the value) is the edit the author asked for, so it is not repeated back.
+ */
+function describeSitemapNotes(notes) {
+ const shown = (v) => (v ? `'${v}'` : '(none)');
+ const lines = [];
+ for (const n of notes || []) {
+ if (n.kind === 'kept') {
+ lines.push(`${n.target}: kept the environment's ${n.field} ${shown(n.live)} — it changed there after this spec was last applied or downloaded, and the spec still has ${shown(n.spec)}. Change the spec to change it.`);
+ } else if (n.kind === 'changed' && n.node === 'subArea' && !n.intended) {
+ lines.push(`${n.target}: ${n.field} changes from ${shown(n.live)} to the spec's ${shown(n.spec)}. No baseline in this spec's workspace records the entry, so a change made in the designer cannot be told from one made in the spec.`);
+ } else if (n.kind === 'changed' && n.node !== 'subArea') {
+ lines.push(`${n.target}: ${n.field} changes from ${shown(n.live)} to the spec's ${shown(n.spec)}.`);
+ }
+ }
+ return lines;
+}
+
+module.exports = { DASHBOARD_LAUNCHER_URL, isDashboardLauncherUrl, subAreaTargetKey, specSubAreaTargetKey, specSubAreas, adoptLiveSitemap, chromeByTargetKey, keepsLiveValue, describeSitemapNotes };
diff --git a/plugins/model-apps/scripts/lib/sitemap-pages.js b/plugins/model-apps/scripts/lib/sitemap-pages.js
index aa4338e5b..3e2046351 100644
--- a/plugins/model-apps/scripts/lib/sitemap-pages.js
+++ b/plugins/model-apps/scripts/lib/sitemap-pages.js
@@ -18,19 +18,19 @@ const DESC_ATTR = /\bDescription="([^"]*)"/i;
// Exact 36-char GUID pattern used for structural validation in `isMalformed`.
const GUID_36 = /^[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}$/;
-// Decode the 5 predefined XML entities so a sitemap Title like "Orders &amp; Overview" becomes a usable page
-// NAME ("Orders & Overview") on the download round-trip. Sitemap free-text is XML-ESCAPED by the SDK's
-// safe-DOM factory, so we must reverse it before treating a Title as a name.
-// &amp; is decoded LAST so "a &amp;lt; b" → "a &lt; b" (not "a < b" — double-encoded sequences are rare but
-// ordering matters; only a single decode pass is done intentionally).
+// Decode XML character references so a sitemap Title like "Orders &amp; Overview" becomes a usable page
+// NAME ("Orders & Overview") on the download round-trip, and a Url compares as the SDK reads it. Sitemap
+// free-text is XML-ESCAPED by the SDK's safe-DOM factory, so it must be reversed before a Title is treated as
+// a name — and a serializer may write any character as a numeric reference (`&#38;`, `&#x26;`), not only
+// through the five predefined entities. ONE pass, so a double-encoded "a &amp;lt; b" decodes to "a &lt; b",
+// never "a < b". A reference to no character (out of range, or a surrogate) is left as written.
+const XML_PREDEFINED = { lt: '<', gt: '>', amp: '&', quot: '"', apos: "'" };
function decodeXmlEntities(s) {
- return String(s)
- .replace(/&lt;/g, '<')
- .replace(/&gt;/g, '>')
- .replace(/&quot;/g, '"')
- .replace(/&#39;/g, "'")
- .replace(/&apos;/g, "'")
- .replace(/&amp;/g, '&'); // &amp; LAST so "&amp;lt;" → "&lt;" not "<"
+ return String(s).replace(/&(?:#x([0-9a-fA-F]+)|#([0-9]+)|(lt|gt|amp|quot|apos));/g, (ref, hex, dec, name) => {
+ if (name) return XML_PREDEFINED[name];
+ const cp = hex !== undefined ? parseInt(hex, 16) : parseInt(dec, 10);
+ return cp <= 0x10ffff && !(cp >= 0xd800 && cp <= 0xdfff) ? String.fromCodePoint(cp) : ref;
+ });
}
function sitemapGenPages(xml) {
diff --git a/plugins/model-apps/scripts/lib/verify-spec.js b/plugins/model-apps/scripts/lib/verify-spec.js
index dd141471b..ff8997d22 100644
--- a/plugins/model-apps/scripts/lib/verify-spec.js
+++ b/plugins/model-apps/scripts/lib/verify-spec.js
@@ -9,7 +9,10 @@ const { matchContainer, isEngineOwnedSection, isEngineHostSection, claimedByAuth
const { authoredSectionNames } = require('./app-spec.js');
const { decodeXmlEntities } = require('./sitemap-pages.js');
const { normalizePageSource, relationshipSchemaName, manyToManySchemaName, SDK_ROLE_MARKER, canonicalPersonaName, bpfUniqueName, BPF_ROLE_ACCESS, generatedTabName, generatedSectionName, formColumnsOf } = require('./app-spec.js');
-const { resolveExistingFormId, resolveRoleBusinessUnit, roleBuClause, appUniqueName, businessRuleFilter, bpfFilter, viewDef, dashboardsInSolution, findDashboardsByName } = require('./sdk-build.js');
+const { resolveExistingFormId, resolveRoleBusinessUnit, roleBuClause, appUniqueName, businessRuleFilter, bpfFilter, viewDef, dashboardsInSolution, findDashboardsByName, findPinnedDashboard } = require('./sdk-build.js');
+const { DASHBOARD_LAUNCHER_URL, isDashboardLauncherUrl, subAreaTargetKey, specSubAreaTargetKey, specSubAreas, chromeByTargetKey, keepsLiveValue } = require('./sitemap-merge.js');
+// Recorded on an icon check the build's keep rule satisfies (keepsLiveValue, sitemap-merge.js).
+const KEPT_BY_DESIGNER = 'kept as the environment has it: changed in the designer since the spec\u2019s baseline, which the spec still matches';
const { extractNavTargets } = require('./pageref-resolver.js');
const { AI_APP_SETTING, resolveAiFlags, specOptsIntoAi, featureWantValue, sameSettingValue, resolveAppModuleId, proveAppOverride } = require('./ai-app-settings.js');
const { declaredPrivileges, compareRolePrivileges } = require('./role-privileges.js');
@@ -18,6 +21,7 @@ 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');
+const { isMainForm, selectDefaultForm, plannedMainFormSequence, displayConditionsOrder, compareServedOrder } = require('./form-order.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
@@ -58,24 +62,20 @@ async function verifySpec(spec, read, opts = {}) {
const selectedDefaultForms = new Map();
const declaredMainFormsByEntity = new Map();
for (const f of spec.forms || []) {
- const formType = f.formType || 'Main';
- if (formType !== 'Main') continue;
+ if (!isMainForm(f)) continue;
const entity = String(f.entity || '').toLowerCase();
if (!entity) continue;
- // Mirror the BUILD's promotion guard exactly (sdk-build.js `isOwnCustomTable`): the build
- // refuses to re-point the default form of a reused or stock table, because that is an
- // environment-wide side effect on a table the spec does not own. Asserting `isdefault` for a
- // table the build deliberately never promotes makes `--verify` permanently unsatisfiable for any
- // spec that puts a Main form on `account`, `contact`, or an `existing: true` table.
- const entSpec = (spec.entities || []).find((e) => e && String(e.schemaName || '').toLowerCase() === entity);
- const prefix = spec.solution && spec.solution.publisherPrefix;
- 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);
+ }
+ // Mirror the BUILD's choice exactly (lib/form-order.js `selectDefaultForm`, which sdk-build.js
+ // promotes): an explicit `isDefault` or `mainFormOrder` on any table, the first-Main-form fallback
+ // only on a table the spec owns. Asserting `isdefault` for a table the build deliberately never
+ // promotes would make `--verify` permanently unsatisfiable for any spec that puts a Main form on
+ // `account`, `contact`, or an `existing: true` table without choosing its default.
+ for (const entity of declaredMainFormsByEntity.keys()) {
+ const chosen = selectDefaultForm(spec, entity);
+ if (chosen) selectedDefaultForms.set(entity, chosen.form);
}
// Entities + their declared columns.
@@ -211,7 +211,18 @@ async function verifySpec(spec, read, opts = {}) {
// same-named dashboard of another app sorted first and failed a correctly wired app. Memoized per
// name, so each name is read once.
const ownDashboards = new Map();
+ // A downloaded dashboard's pinned id (dashboards[].dashboardId) is what the build binds first, so it
+ // is what verify checks first — after a rename in the designer the name alone finds nothing.
+ const pinByName = new Map((spec.dashboards || []).filter((d) => d && d.name && d.dashboardId).map((d) => [d.name, d.dashboardId]));
const identifyDashboard = async (name) => {
+ if (pinByName.has(name)) {
+ try {
+ const pinned = await findPinnedDashboard(read, pinByName.get(name));
+ if (pinned) return { id: pinned.id };
+ } catch (e) {
+ return { id: null, detail: `its dashboardId could not be resolved (${(e && e.message) || e}) — unverified, not proven correct` };
+ }
+ }
let rows = null;
try {
rows = await findDashboardsByName(read, name);
@@ -319,6 +330,74 @@ async function verifySpec(spec, read, opts = {}) {
}
}
+ // AB#6736948 — the Main Form Set order, for every table the build orders (lib/form-order.js). Two
+ // checks, because they answer different questions:
+ // form-order what is STORED: each form's published <DisplayConditions Order>, which must
+ // rise along the build's order. Independent of who runs verify.
+ // form-order-served what the platform SERVES: the public RetrieveFilteredForms answer for the user
+ // running verify. It sees what the stored check cannot — a form this spec does
+ // not declare whose order puts it first — but only through that user's security
+ // roles, so a form they may not open cannot be placed from their answer: that is
+ // reported as not verifiable here, never as a pass.
+ // Neither sees a user's remembered form (the one they last switched to), which opens first for them
+ // while they may open it; it is per user and not configuration (references/app-spec-schema.md).
+ if (typeof read.formTopology === 'function') {
+ for (const [entityLogical, declared] of declaredMainFormsByEntity) {
+ if (!plannedMainFormSequence(spec, entityLogical)) continue;
+ const resolved = resolvedMainFormsByEntity.get(entityLogical) || [];
+ const idOf = new Map(resolved.map((r) => [r.form, r.id]));
+ const nameOf = new Map(resolved.map((r) => [r.form, r.name]));
+ // A form that did not resolve is already reported missing by its own check; its place cannot be.
+ if (declared.some((f) => !idOf.get(f))) continue;
+ const current = new Map();
+ let readError = null;
+ for (const f of declared) {
+ try {
+ current.set(f, displayConditionsOrder(await read.formTopology(entityLogical, idOf.get(f))).order);
+ } catch (e) {
+ readError = `'${nameOf.get(f)}': ${(e && e.message) || e}`;
+ break;
+ }
+ }
+ const sequence = plannedMainFormSequence(spec, entityLogical, current);
+ const label = `${entityLogical}: ${sequence.map((f) => nameOf.get(f)).join(' > ')}`;
+ if (readError) {
+ add('form-order', label, false, `could not read the deployed form order (${readError})`);
+ continue;
+ }
+ let problem = '';
+ for (let i = 0; i < sequence.length && !problem; i += 1) {
+ const o = current.get(sequence[i]);
+ const prev = i > 0 ? current.get(sequence[i - 1]) : undefined;
+ if (!Number.isFinite(o)) problem = `'${nameOf.get(sequence[i])}' has no form order in its published formxml`;
+ else if (i > 0 && !(o > prev)) problem = `'${nameOf.get(sequence[i])}' (order ${o}) is not after '${nameOf.get(sequence[i - 1])}' (order ${prev})`;
+ }
+ add('form-order', label, !problem, problem ? `${problem} — build the spec again with --publish to put them in this order` : '');
+ if (problem || typeof read.servedMainForms !== 'function') continue;
+
+ let served = null;
+ try { served = await read.servedMainForms(entityLogical); } catch (e) {
+ add('form-order-served', entityLogical, false, `could not read the order the platform serves (RetrieveFilteredForms): ${(e && e.message) || e}`);
+ continue;
+ }
+ const planned = sequence.map((f) => ({ name: nameOf.get(f), id: idOf.get(f) }));
+ const cmp = compareServedOrder(planned, (served || []).map((s) => s.id));
+ const first = planned[0].name;
+ if (cmp.ok === null) {
+ environmentSkipped.push(`form-order-served:${entityLogical} (the user running verify may not open '${first}' — check it as a user with that form's security roles)`);
+ } else if (cmp.reason === 'order') {
+ add('form-order-served', `${entityLogical} opens with '${first}'`, false, `'${cmp.before}' is served before '${cmp.after}' — build the spec again with --publish`);
+ } else if (cmp.reason === 'ahead') {
+ const ahead = (served || []).find((s) => String(s.id).replace(/[{}]/g, '').toLowerCase() === cmp.aheadId);
+ const aheadName = (ahead && ahead.name) || cmp.aheadId;
+ add('form-order-served', `${entityLogical} opens with '${first}'`, false,
+ `users without a remembered form open '${aheadName}' first: a Main form this spec does not declare, whose form order is not after '${first}'. Move it down in Maker (Form settings > Form order), or declare it in forms[] and list it in entities[].mainFormOrder`);
+ } else {
+ add('form-order-served', `${entityLogical} opens with '${first}'`, true);
+ }
+ }
+ }
+
// 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
// reader can list a child entity's relationship schema names (`entityRelationships`). Match the same
@@ -686,6 +765,41 @@ async function verifySpec(spec, read, opts = {}) {
// icon, the owning entity) so an icon/entity value reused elsewhere in the XML can't satisfy an
// unrelated check (e.g. an Area icon must not make a missing SubArea icon look present).
const xml = (await read.sitemapXml()) || '';
+ // AB#6726727: a rebuild KEEPS a nav entry's icon that changed in the designer since the spec's
+ // baseline while the spec did not (sitemap-merge.js), and its own --verify must not fail on that.
+ // Such a failing icon check is accepted only when the build's rule (keepsLiveValue) holds for the
+ // LIVE entry the subarea targets — found by the target key the build matches on, resolved with the
+ // dashboard and page ids this verify resolves, so an entry missing from the sitemap (or a sitemap
+ // that could not be read) still fails. Resolved once, and only if an icon check fails.
+ let keepContext = null;
+ const keptByBuild = async (sa, field) => {
+ if (!opts.baselineSpec) return false;
+ if (!keepContext) keepContext = (async () => {
+ const ids = { dashboards: {}, pages: {} };
+ const dashboards = [];
+ for (const s of specSubAreas(spec)) {
+ if (!s.dashboard) continue;
+ const own = await ownDashboard(s.dashboard);
+ if (own.id) dashboards.push([s.dashboard, own.id]);
+ }
+ ids.dashboards = Object.fromEntries(dashboards);
+ if (specSubAreas(spec).some((s) => s.page)) {
+ // The same page identity the page checks below use: the spec's own pageId, then the manifest's.
+ let man = null;
+ try { man = typeof read.manifest === 'function' ? await read.manifest() : null; } catch { man = null; }
+ const byKey = new Map(((man && man.pages) || []).filter((p) => p && p.key && p.pageId).map((p) => [p.key, p.pageId]));
+ ids.pages = Object.fromEntries((spec.pages || []).filter((p) => p && (p.key || p.name))
+ .map((p) => [p.key || p.name, p.pageId || byKey.get(p.key || p.name)]).filter(([, id]) => id));
+ }
+ return { ids, live: liveNavEntries(xml), base: chromeByTargetKey(opts.baselineSpec, ids) };
+ })();
+ const { ids, live, base } = await keepContext;
+ const key = specSubAreaTargetKey(sa, ids);
+ // An unreadable sitemap (liveNavEntries answered null) proves nothing was kept.
+ const entries = key && live ? live.get(key) : undefined;
+ if (!entries || entries.length !== 1) return false;
+ return keepsLiveValue(field, sa[field], entries[0][field], base.get(key));
+ };
for (const a of (spec.appShell && spec.appShell.areas) || []) {
if (a.icon) add('area-icon', a.label || '', hasElement(xml, 'Area', { Icon: a.icon }));
if (a.vectorIcon) add('area-vectorIcon', a.label || '', hasElement(xml, 'Area', { VectorIcon: a.vectorIcon }));
@@ -697,19 +811,39 @@ async function verifySpec(spec, read, opts = {}) {
// some dashboard subarea exists, and not at another app's same-named dashboard, which the
// name lookup returns too (see ownDashboard above). Absent or unidentifiable => not present.
const own = await ownDashboard(sa.dashboard);
- add('subarea', sa.title || sa.dashboard, own.id ? subareaHasDashboard(xml, own.id) : false, own.id ? '' : own.detail);
+ const wired = own.id ? subareaHasDashboard(xml, own.id) : false;
+ add('subarea', sa.title || sa.dashboard, wired, own.id ? '' : own.detail);
+ // AB#6726727: pointing at the dashboard is not enough. An entry without the launcher Url shows
+ // a placeholder icon and is not a dashboard entry to the designer — the shape earlier builds
+ // wrote over designer-made entries, which the check above passed.
+ if (wired) {
+ const launcher = subareaDashboardHasLauncher(xml, own.id);
+ // Wired, but by a `<SubArea …>` that is no nav entry (in a comment, outside
+ // SiteMap/Area/Group), or in a sitemap the walk cannot read: there is no entry to fault
+ // for a missing Url, so say what is actually wrong.
+ const detail = launcher ? ''
+ : dashboardNavEntries(xml, own.id).length
+ ? `its nav entry has no Url="${DASHBOARD_LAUNCHER_URL}", so the app shows a placeholder icon for it and the designer does not treat it as a dashboard entry — a rebuild restores it`
+ : 'no nav entry points at it: the SubArea that does is not directly under SiteMap/Area/Group (or is inside a comment), or the sitemap XML could not be read';
+ add('subarea-dashboard-launcher', sa.title || sa.dashboard, launcher, detail);
+ }
}
if (sa.icon) {
// Prefer matching the icon on the SubArea that also declares this entity; fall back to any
// SubArea carrying the icon when the subarea has no entity identity.
const present = sa.entity ? hasElement(xml, 'SubArea', { Entity: sa.entity, Icon: sa.icon }) : hasElement(xml, 'SubArea', { Icon: sa.icon });
- add('subarea-icon', sa.title || '', present);
+ // AB#6726727: an icon changed in the designer since the spec's baseline, which the spec has not
+ // changed, is one the build deliberately KEEPS — accepted here in exactly that case, or the
+ // build's own --verify would fail on it.
+ const kept = !present && await keptByBuild(sa, 'icon');
+ add('subarea-icon', sa.title || '', present || kept, kept ? KEPT_BY_DESIGNER : '');
}
if (sa.vectorIcon) {
// VectorIcon serializes as its own sitemap attribute, so check it independently from the
// raster Icon attribute while keeping the same SubArea scoping rules.
const present = sa.entity ? hasElement(xml, 'SubArea', { Entity: sa.entity, VectorIcon: sa.vectorIcon }) : hasElement(xml, 'SubArea', { VectorIcon: sa.vectorIcon });
- add('subarea-vectorIcon', sa.title || '', present);
+ const kept = !present && await keptByBuild(sa, 'vectorIcon');
+ add('subarea-vectorIcon', sa.title || '', present || kept, kept ? KEPT_BY_DESIGNER : '');
}
}
}
@@ -1105,8 +1239,8 @@ async function verifySpec(spec, read, opts = {}) {
for (const [feature, requested] of Object.entries(requestedFeatures)) {
const setting = AI_APP_SETTING[feature];
if (!setting) continue; // unknown key — validation already reports it
- // Feature-aware: `true` means '2' for the form-fill family and '1' elsewhere. Comparing
- // against the wrong spelling reports a correctly-applied feature as missing.
+ // Feature-aware: `true` is '2' for every AI setting, while `false` is '1' for most and '0' for
+ // nlChart. Comparing against the wrong spelling reports a correctly-applied feature as missing.
const want = featureWantValue(requested, feature);
// (1) Authoritative: does an app-scope override row exist, holding `want`?
@@ -1126,7 +1260,7 @@ async function verifySpec(spec, read, opts = {}) {
// Fail-closed: when the proof could not be run we could LOOK and looking failed, so we must not
// claim PASS on the strength of a value that may simply be the environment default.
- const present = !proof.error && proof.exists && sameSettingValue(proof.value, want);
+ const present = !proof.error && proof.exists && sameSettingValue(proof.value, want, feature);
const inForce = effective === undefined ? '(unreadable)' : effective === '' ? '(unset)' : effective;
add('ai-feature', feature, present, present ? '' :
proof.error
@@ -1564,6 +1698,76 @@ function subareaHasDashboard(xml, dashId) {
return false;
}
+// The live nav entries pointing at dashboard `dashId`, read by the nav-entry walk (liveNavEntries below):
+// only a `SubArea` element directly under SiteMap/Area/Group counts, never one in a comment, a CDATA
+// section, a processing instruction or elsewhere in the document. None when the walk cannot account for
+// the sitemap (fail-closed), so nothing unreadable can vouch for an entry.
+function dashboardNavEntries(xml, dashId) {
+ const live = liveNavEntries(xml);
+ return (live && live.get(subAreaTargetKey({ type: 'DashBoard', dashboardId: dashId }))) || [];
+}
+
+// True when a nav entry pointing at `dashId` also carries the dashboard launcher Url, e.g.
+// <SubArea Id="ops" Url="/workplace/home_dashboards.aspx" DefaultDashboard="{280948EC-…}" …>
+// Read through the walk rather than by matching `<SubArea …>` start tags in the raw text, which would take
+// a decoy in a comment or outside navigation carrying the Url as the entry. The Url is compared
+// XML-decoded, as the runtime and the designer read it (isDashboardLauncherUrl, sitemap-merge.js).
+function subareaDashboardHasLauncher(xml, dashId) {
+ return dashboardNavEntries(xml, dashId).some((e) => isDashboardLauncherUrl(e.url));
+}
+
+// The live nav entries in sitemap XML, by navigation target (subAreaTargetKey, sitemap-merge.js) — the
+// identity a rebuild matches live entries by — each with its icons and Url. For example
+// <SubArea Id="ops" Url="/workplace/home_dashboards.aspx" DefaultDashboard="{280948EC-…}" VectorIcon="$webresource:new_ops.svg">
+// becomes 'DashBoard:280948ec-…' → [{ icon: undefined, vectorIcon: '$webresource:new_ops.svg', url: '/workplace/home_dashboards.aspx' }].
+// An entry's type is read the way the vendored SDK reads it — GenPageId, then Entity, then Page, then
+// DefaultDashboard, else it is a URL entry — so the two agree on what an entry targets.
+// Only ELEMENTS count, and only where the vendored SDK models navigation: a `SubArea` element (that exact
+// name — not `SubArea-Archived`, not `SubAreaÜ`) directly under `SiteMap/Area/Group`. A SubArea anywhere
+// else is kept by the SDK as opaque XML and is no nav entry, and a `<SubArea …>` inside a comment, a CDATA
+// section or a processing instruction is text — so those three are removed first, and the remaining tags
+// are walked with an element stack. A name is read whole, whatever its characters (XML names may be
+// Unicode), so every element boundary is on the stack. A value may hold a raw `>`, so a tag is matched
+// quote by quote. Values are fully XML-decoded (`&amp;`, and numeric references such as `&#38;`), in
+// either quote style, before they are compared with the spec's.
+//
+// FAIL-CLOSED: the answer is null — no entries, so verify grants no "kept" exemption and the icon check
+// stands as it would without a baseline — for anything this walk cannot account for completely: a `<`
+// that starts no element tag (which is also how a document type declaration, whose entities could expand
+// into elements, is turned away), or a closing tag that does not close the innermost open element.
+const NAV_PATH = ['SiteMap', 'Area', 'Group'];
+const XML_TAG = /<(\/?)([^\s/>"'=!?]+)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
+const XML_ATTR = /\s([^\s/>"'=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;
+function liveNavEntries(xml) {
+ const markup = String(xml || '')
+ .replace(/<!--[\s\S]*?-->/g, '')
+ .replace(/<!\[CDATA\[[\s\S]*?\]\]>/g, '')
+ .replace(/<\?[\s\S]*?\?>/g, '');
+ const tags = [...markup.matchAll(XML_TAG)];
+ // In well-formed XML every remaining `<` starts a tag: text escapes it, and an attribute value cannot hold one.
+ if (tags.length !== (markup.match(/</g) || []).length) return null;
+ const byKey = new Map();
+ const open = [];
+ for (const [, closing, name, body, selfClosing] of tags) {
+ if (closing) {
+ if (open[open.length - 1] !== name) return null;
+ open.pop();
+ continue;
+ }
+ if (name === 'SubArea' && open.length === NAV_PATH.length && NAV_PATH.every((n, i) => open[i] === n)) {
+ const attrs = Object.create(null);
+ for (const m of body.matchAll(XML_ATTR)) attrs[m[1]] = decodeXmlEntities(m[2] !== undefined ? m[2] : m[3]);
+ const type = attrs.GenPageId ? 'GenPage' : attrs.Entity ? 'Entity' : attrs.Page ? 'CustomPage' : attrs.DefaultDashboard ? 'DashBoard' : 'URL';
+ const key = subAreaTargetKey({ type, entity: attrs.Entity, url: attrs.Url, dashboardId: attrs.DefaultDashboard, page: attrs.Page, genPageId: attrs.GenPageId });
+ if (key) {
+ if (!byKey.has(key)) byKey.set(key, []);
+ byKey.get(key).push({ icon: attrs.Icon, vectorIcon: attrs.VectorIcon, url: attrs.Url });
+ }
+ }
+ if (!selfClosing) open.push(name);
+ }
+ return open.length ? null : byKey;
+}
// True when some sitemap `<SubArea GenPageId="<id>">` in the XML binds this page id. Generative-page
// subareas store the id in the GenPageId attribute SPECIFICALLY (vendor cds-maker-sdk.cjs:50 parses
// /GenPageId="([0-9a-fA-F-]{36})"/), so match THAT attribute only — a decoy id elsewhere on the
@@ -1587,4 +1791,4 @@ function appShellReferencesPage(spec, key) {
return false;
}
-module.exports = { verifySpec, hasElement, subareaHasDashboard, subareaHasGenPage, appShellReferencesPage, layoutColumnNames, parseFetchXml };
+module.exports = { verifySpec, hasElement, subareaHasDashboard, subareaDashboardHasLauncher, liveNavEntries, subareaHasGenPage, appShellReferencesPage, layoutColumnNames, parseFetchXml };
diff --git a/plugins/model-apps/scripts/tests/ai-app-features-real-bundle.test.js b/plugins/model-apps/scripts/tests/ai-app-features-real-bundle.test.js
index 8a7a4d0aa..b0700e0b2 100644
--- a/plugins/model-apps/scripts/tests/ai-app-features-real-bundle.test.js
+++ b/plugins/model-apps/scripts/tests/ai-app-features-real-bundle.test.js
@@ -264,34 +264,73 @@ test('REAL BUNDLE: a malformed appModuleId is rejected up front', async () => {
await assert.rejects(() => sdk.setAppAiFeatures(APP, { formFill: true }, { ...FAST, appModuleId: 'not-a-guid' }));
});
-// The boolean spelling is NOT a flat 1/0, and the schema doc said it was. That inaccuracy caused a
-// real incident: `appFeatures: { nlSearch: false, nlChart: false }` was written believing it meant
-// "leave alone", and it DISABLED two features a live app was inheriting as on. For the form-fill
-// family the tri-state is 0 = platform default, 1 = DISABLED, 2 = enabled, so `false` there is an
-// explicit off rather than an unset.
+// The boolean spelling is NOT a flat 1/0, and the schema doc once said it was. That inaccuracy caused
+// a real incident: `appFeatures: { nlSearch: false, nlChart: false }` was written believing it meant
+// "leave alone", and it changed two features a live app was inheriting as on.
//
-// Pinned against the real bundle in BOTH directions, so a re-vendor that changes the encoding fails
-// here instead of silently making the documentation wrong again.
-test('REAL BUNDLE: the boolean-to-numeric mapping is per-family, not a flat 1/0', async () => {
- const EXPECTED = {
- formFill: { setting: 'FormFillBarUXEnabled', onValue: '2', offValue: '1' },
- nlSearch: { setting: 'NLGridSearchSetting', onValue: '1', offValue: '0' },
- nlChart: { setting: 'NLChartDataVisualizationSetting', onValue: '1', offValue: '0' },
- m365: { setting: 'm365copilotmodelappenabled', onValue: '1', offValue: '0' },
- };
-
- for (const [feature, want] of Object.entries(EXPECTED)) {
- for (const [flag, expected] of [[true, want.onValue], [false, want.offValue]]) {
- // Gate reported ON so the SDK writes in both directions (enabling is gated; disabling is not).
+// Every per-app AI setting is a tri-state: most are 0 = Default, 1 = Off, 2 = On, while NL charts are
+// 0 = Off, 1 = Auto, 2 = On (the platform's own settings UI). The vendored SDK's boolean mapping knows
+// only the form-fill family, so `true` reached grid search and M365 as '1' — Off — and charts as
+// '1' — Auto (AB#6714731). The build therefore encodes every flag itself (`encodeAiFlags`) and hands
+// the SDK explicit values, which it writes verbatim.
+//
+// Pinned against the real bundle for every feature in BOTH directions, so a re-vendor that starts
+// re-mapping explicit values fails here instead of silently writing the wrong state.
+test('REAL BUNDLE: every feature\u2019s encoded On/Off value is written verbatim and proven', async () => {
+ const { AI_APP_SETTING, AI_SETTING_CODEC, encodeAiFlags } = require('../lib/ai-app-settings.js');
+ const features = Object.keys(AI_APP_SETTING);
+ assert.deepStrictEqual(Object.keys(AI_SETTING_CODEC).sort(), [...features].sort(), 'every per-app setting has a codec entry');
+ for (const feature of features) {
+ for (const [flag, expected] of [[true, AI_SETTING_CODEC[feature].enabled], [false, AI_SETTING_CODEC[feature].disabled]]) {
+ const encoded = encodeAiFlags({ [feature]: flag });
+ assert.strictEqual(encoded[feature], expected, `${feature}=${flag}: encoded value`);
const { sdk, calls } = await freshSdk({ gate: '2', effective: '2', overrideRows: [{ appsettingid: 'a1', value: expected }] });
- await sdk.setAppAiFeatures(APP, { [feature]: flag }, { appModuleId: APP_ID, verifyAttempts: 1, verifyDelayMs: 1 });
+ const r = await sdk.setAppAiFeatures(APP, encoded, { appModuleId: APP_ID, verifyAttempts: 1, verifyDelayMs: 1 });
const save = calls.find((c) => c.method === 'POST' && /SaveSettingValue/i.test(c.url));
assert.ok(save, `${feature}=${flag}: a SaveSettingValue must be issued`);
- assert.strictEqual(save.body.SettingName, want.setting, `${feature}: setting name`);
- assert.strictEqual(String(save.body.Value), expected,
- `${feature}=${flag} must write ${expected} — the docs previously claimed a flat 1/0, which is wrong for the form-fill family`);
+ assert.strictEqual(save.body.SettingName, AI_APP_SETTING[feature], `${feature}: setting name`);
+ assert.strictEqual(String(save.body.Value), expected, `${feature}=${flag} must write ${expected}`);
+ assert.deepStrictEqual(r.applied, [feature], `${feature}=${flag}: the SDK proves the override holding ${expected}`);
}
}
+ // The absolute values, so an edit to the codec cannot drift unnoticed.
+ assert.deepStrictEqual(encodeAiFlags({ formFill: true, nlSearch: true, nlChart: true, m365: true }), { formFill: '2', nlSearch: '2', nlChart: '2', m365: '2' });
+ assert.deepStrictEqual(encodeAiFlags({ formFill: false, nlSearch: false, nlChart: false, m365: false }), { formFill: '1', nlSearch: '1', nlChart: '0', m365: '1' });
+});
+
+// Why the build encodes at all: the SDK's own boolean mapping, as vendored. If a re-vendor makes this
+// fail because the SDK now maps these features correctly, delete this test — the build's own encoding
+// stays correct, because an explicit value passes through verbatim.
+test('REAL BUNDLE (known SDK gap): a raw boolean `true` still writes 1 for grid search, charts and M365', async () => {
+ for (const [feature, setting] of [['nlSearch', 'NLGridSearchSetting'], ['nlChart', 'NLChartDataVisualizationSetting'], ['m365', 'm365copilotmodelappenabled']]) {
+ const { sdk, calls } = await freshSdk({ gate: '2', effective: '2', overrideRows: [{ appsettingid: 'a1', value: '1' }] });
+ await sdk.setAppAiFeatures(APP, { [feature]: true }, { appModuleId: APP_ID, verifyAttempts: 1, verifyDelayMs: 1 });
+ const save = calls.find((c) => c.method === 'POST' && /SaveSettingValue/i.test(c.url));
+ assert.strictEqual(save.body.SettingName, setting);
+ assert.strictEqual(String(save.body.Value), '1', `${feature}: the SDK maps true to '1' (Off, or Auto for charts), which is why the build never passes it a boolean`);
+ }
+});
+
+test('REAL BUNDLE: an encoded OFF that did not persist is not blamed on an org gate that governs turning it ON', async () => {
+ // The same gap from the other side: the SDK reads any non-zero value as enabling, so an absent
+ // override for grid search Off ('1') with its gate off comes back `skipped`, telling an admin to
+ // enable the feature. The build re-buckets it before anything reads the result.
+ const { encodeAiFlags, rebucketNonEnablingSkips } = require('../lib/ai-app-settings.js');
+ const encoded = encodeAiFlags({ nlSearch: false });
+ const { sdk } = await freshSdk({ gate: '0', effective: '0', overrideRows: [] });
+ const r = await sdk.setAppAiFeatures(APP, encoded, FAST);
+ assert.deepStrictEqual(r.skipped, ['nlSearch'], 'the SDK still labels it skipped (if this fails, the SDK gap closed)');
+ rebucketNonEnablingSkips(r, encoded);
+ assert.deepStrictEqual([r.skipped, r.notPersisted], [[], ['nlSearch']]);
+ assert.strictEqual(r.outcomes[0].status, 'notPersisted');
+ assert.doesNotMatch(r.outcomes[0].reason, /must enable/);
+ assert.match(r.outcomes[0].reason, /holding '1'/);
+ // An enabling request keeps the SDK's verdict and its admin-action reason.
+ const on = encodeAiFlags({ nlSearch: true });
+ const { sdk: sdk2 } = await freshSdk({ gate: '0', effective: '0', overrideRows: [] });
+ const r2 = rebucketNonEnablingSkips(await sdk2.setAppAiFeatures(APP, on, FAST), on);
+ assert.deepStrictEqual(r2.skipped, ['nlSearch']);
+ assert.match(r2.outcomes[0].reason, /must enable/);
});
test('REAL BUNDLE: disabling is NOT gated — a false is written even when the org gate is off', async () => {
diff --git a/plugins/model-apps/scripts/tests/ai-preflight.test.js b/plugins/model-apps/scripts/tests/ai-preflight.test.js
index 5219d0529..2c3f3645e 100644
--- a/plugins/model-apps/scripts/tests/ai-preflight.test.js
+++ b/plugins/model-apps/scripts/tests/ai-preflight.test.js
@@ -24,11 +24,11 @@ test('runPreflight lists features and produces admin actions for disabled ones',
test('runPreflight returns no admin actions when all features are enabled', () => {
const readiness = {
- formFill: { enabled: true, setting: 'FormFillBarUXEnabled', value: '1' },
+ formFill: { enabled: true, setting: 'FormFillBarUXEnabled', value: '2' },
nlSearch: { enabled: true, setting: 'EnableNLGridSearch', value: 'true' },
nlChart: { enabled: true, setting: 'NLChartVisualizationSetting', value: 'true' },
summaries: { enabled: true, setting: 'EnableFormInsights', value: 'true' },
- m365: { enabled: true, setting: 'm365copilotmodelappenabled', value: '1' },
+ m365: { enabled: true, setting: 'm365copilotmodelappenabled', value: '2' },
};
const r = runPreflight(readiness);
assert.strictEqual(r.features.length, 5);
@@ -37,11 +37,11 @@ test('runPreflight returns no admin actions when all features are enabled', () =
test('runPreflight summaries admin action mentions AI insight cards', () => {
const readiness = {
- formFill: { enabled: true, setting: 'FormFillBarUXEnabled', value: '1' },
+ formFill: { enabled: true, setting: 'FormFillBarUXEnabled', value: '2' },
nlSearch: { enabled: true, setting: 'EnableNLGridSearch', value: 'true' },
nlChart: { enabled: true, setting: 'NLChartVisualizationSetting', value: 'true' },
summaries: { enabled: false, setting: 'EnableFormInsights', value: 'false' },
- m365: { enabled: true, setting: 'm365copilotmodelappenabled', value: '1' },
+ m365: { enabled: true, setting: 'm365copilotmodelappenabled', value: '2' },
};
const r = runPreflight(readiness);
assert.strictEqual(r.adminActions.length, 1);
@@ -54,7 +54,7 @@ test('runPreflight features include feature name, enabled flag, and setting', ()
nlSearch: { enabled: true, setting: 'EnableNLGridSearch', value: 'true' },
nlChart: { enabled: true, setting: 'NLChartVisualizationSetting', value: 'true' },
summaries: { enabled: true, setting: 'EnableFormInsights', value: 'true' },
- m365: { enabled: true, setting: 'm365copilotmodelappenabled', value: '1' },
+ m365: { enabled: true, setting: 'm365copilotmodelappenabled', value: '2' },
};
const r = runPreflight(readiness);
const ff = r.features.find((f) => f.feature === 'formFill');
@@ -182,7 +182,7 @@ test('ai-preflight CLI passes the app scope, prints admin actions, emits the rep
test('ai-preflight CLI reports all-enabled status without admin actions', async () => {
const readiness = {
- formFill: { enabled: true, setting: 'FormFillBarUXEnabled', value: '1' },
+ formFill: { enabled: true, setting: 'FormFillBarUXEnabled', value: '2' },
};
const harness = loadPreflightCli({
parseResult: { flags: { env: 'https://org.example' } },
@@ -325,10 +325,102 @@ test('a codec DISABLED value is off, not on', () => {
assert.strictEqual(settingIsOn('1', 'formFill'), false, "'1' is DISABLED for the form-fill family");
assert.strictEqual(settingIsOn('2', 'formFill'), true, "'2' is ENABLED");
assert.strictEqual(settingIsOn('0', 'formFill'), undefined, "'0' is the platform default, not off");
- // A feature with no codec keeps the plain numeric convention.
- assert.strictEqual(settingIsOn('1', 'nlSearch'), true);
+ // AB#6714731: NL grid search and M365 use the same 0 Default / 1 Off / 2 On dropdown, so `1` is
+ // Off there too. Reading it as on is how every build's "enable NL search" (which wrote `1`) was
+ // reported, and verified, as enabled.
+ assert.strictEqual(settingIsOn('1', 'nlSearch'), false, "'1' is Off for NL grid search");
assert.strictEqual(settingIsOn('2', 'nlSearch'), true);
- assert.strictEqual(settingIsOn('0', 'nlSearch'), false);
+ assert.strictEqual(settingIsOn('0', 'nlSearch'), undefined, "'0' is Default for NL grid search, not off");
+ assert.strictEqual(settingIsOn('1', 'm365'), false, "'1' is Off for M365");
+ assert.strictEqual(settingIsOn('2', 'm365'), true);
+ assert.strictEqual(settingIsOn('0', 'm365'), undefined);
+ // NL charts order the same three states differently: 0 = Off, 1 = Auto (its default), 2 = On.
+ assert.strictEqual(settingIsOn('0', 'nlChart'), false, "'0' is Off for NL charts");
+ assert.strictEqual(settingIsOn('1', 'nlChart'), undefined, "'1' is Auto for NL charts: the platform decides");
+ assert.strictEqual(settingIsOn('2', 'nlChart'), true);
// And with no feature key at all, the old convention still applies for existing callers.
assert.strictEqual(settingIsOn('1'), true);
+});
+
+test("NL charts' Auto ('1') is reported as the platform default, and its Off ('0') is not", () => {
+ // The preflight's "platform default" explanation is keyed on each setting's OWN default, so a
+ // hard-coded '0' would call chart Off "the platform decides" and chart Auto an unrecognised value.
+ const readiness = { nlChart: { enabled: false, setting: 'NLChartVisualizationSetting', value: 'false' } };
+ const auto = runPreflight(readiness, { nlChart: { value: '1', scope: 'default', on: undefined } }).features[0];
+ assert.strictEqual(auto.effectiveDefault, true, 'Auto is the chart setting\u2019s platform default');
+ assert.ok(!auto.effectiveIndeterminate);
+ const off = runPreflight(readiness, { nlChart: { value: '0', scope: 'app', on: false } }).features[0];
+ assert.ok(!off.effectiveDefault, "'0' is Off for charts, not the platform default");
+ assert.ok(!off.effectiveIndeterminate, 'Off is a definite state, not an unrecognised value');
+ // For grid search the same '0' IS the platform default.
+ const nl = runPreflight({ nlSearch: { enabled: false, setting: 'EnableNLGridSearch', value: 'false' } },
+ { nlSearch: { value: '0', scope: 'default', on: undefined } }).features[0];
+ assert.strictEqual(nl.effectiveDefault, true);
+});
+
+test('a readiness gate that IS the feature\u2019s own setting is read with the feature\u2019s scale', () => {
+ // M365's readiness gate is `m365copilotmodelappenabled` itself, and the vendored SDK reads any
+ // non-zero value there as enabled — so an app switched Off (`1`) was reported ✓ with no admin action.
+ const readiness = { m365: { enabled: true, setting: 'm365copilotmodelappenabled', value: '1' } };
+ const r = runPreflight(readiness);
+ assert.strictEqual(r.features[0].enabled, false, "'1' is Off for M365, whatever the SDK's reading says");
+ assert.strictEqual(r.adminActions.length, 1);
+ assert.match(r.adminActions[0], /M365 Copilot integration/);
+ assert.strictEqual(runPreflight({ m365: { enabled: false, setting: 'm365copilotmodelappenabled', value: '2' } }).features[0].enabled, true);
+ // A gate that is a DIFFERENT row (a boolean org switch) keeps the SDK's reading untouched.
+ const nl = runPreflight({ nlSearch: { enabled: true, setting: 'EnableNLGridSearch', value: '1' } });
+ assert.strictEqual(nl.features[0].enabled, true);
+ assert.strictEqual(nl.adminActions.length, 0);
+});
+
+test('encodeAiFlags hands the SDK each setting\u2019s own value (AB#6714731)', () => {
+ const { encodeAiFlags, resolveAiFlags } = require('../lib/ai-app-settings.js');
+ // A default AI build: form fill, grid search and charts On; M365 left at its platform default.
+ assert.deepStrictEqual(encodeAiFlags(resolveAiFlags({ ai: {} })), { formFill: '2', nlSearch: '2', nlChart: '2', m365: '0' });
+ // Off differs by setting; an explicit integer is the caller's own value and passes through.
+ assert.deepStrictEqual(encodeAiFlags({ nlSearch: false, nlChart: false, m365: false, formFillFiles: false }),
+ { nlSearch: '1', nlChart: '0', m365: '1', formFillFiles: '1' });
+ assert.deepStrictEqual(encodeAiFlags({ nlChart: 1, m365: 2, formFill: 0 }), { nlChart: '1', m365: '2', formFill: '0' });
+ assert.strictEqual(encodeAiFlags(null), null, 'a spec that opts out of ai writes nothing');
+});
+
+test('sameSettingValue reads a Boolean spelling as the feature\u2019s own On/Off', () => {
+ const { sameSettingValue } = require('../lib/ai-app-settings.js');
+ assert.strictEqual(sameSettingValue('true', '2', 'nlSearch'), true);
+ assert.strictEqual(sameSettingValue('true', '1', 'nlSearch'), false, "'1' is Off for grid search, so 'true' must not match it");
+ assert.strictEqual(sameSettingValue('false', '1', 'm365'), true);
+ assert.strictEqual(sameSettingValue('false', '0', 'nlChart'), true, "'0' is Off for charts");
+ assert.strictEqual(sameSettingValue(' 2 ', '2', 'formFill'), true);
+ // Without a feature, the generic '1'/'0' reading still applies.
+ assert.strictEqual(sameSettingValue('true', '1'), true);
+});
+
+test('an invalid ai.appFeatures value names that setting\u2019s own platform default', () => {
+ const { validateAppSpec } = require('../lib/app-spec.js');
+ const base = { solution: { uniqueName: 'S', publisherPrefix: 'new' }, app: { name: 'A' }, entities: [] };
+ const errs = (features) => validateAppSpec({ ...base, ai: { appFeatures: features } }).errors || [];
+ assert.ok(errs({ nlSearch: 'on' }).some((e) => /ai\.appFeatures\.nlSearch: .*or 0 to leave it to the platform default/.test(e)));
+ // For charts 0 is Off; the platform default is 1 (Auto).
+ assert.ok(errs({ nlChart: 'on' }).some((e) => /ai\.appFeatures\.nlChart: .*or 1 to leave it to the platform default/.test(e)));
});
+
+// Each verdict the readiness report can print (featureLine). "Not enabled" is not one state: a feature
+// can be in effect through a setting the readiness gate does not read, deferred to the platform, or
+// hold a value this plugin does not recognise — and printing ✗ for any of them would assert something
+// the preflight cannot see.
+test('featureLine prints one of four verdicts, in that precedence, and falls back to the feature key', () => {
+ const { featureLine } = require('../ai-preflight.js');
+ assert.strictEqual(featureLine({ feature: 'nlSearch', setting: 'NLGridSearchSetting', enabled: false, inEffect: true, effectiveScope: 'app', effectiveValue: '2' }),
+ ' ✓ Natural language search (NLGridSearchSetting) — in effect via the app setting (value "2"), though the readiness gate reads off\n');
+ assert.strictEqual(featureLine({ feature: 'nlChart', setting: 'NLChartDataVisualizationSetting', enabled: false, effectiveDefault: true, effectiveValue: '1' }),
+ ' ? Natural language charts (NLChartDataVisualizationSetting) — set to the platform default ("1"), so whether it runs is decided by the platform, not by this environment\n');
+ assert.strictEqual(featureLine({ feature: 'm365', setting: 'm365copilotmodelappenabled', enabled: false, effectiveIndeterminate: true, effectiveValue: '7' }),
+ ' ? M365 Copilot integration (m365copilotmodelappenabled) — holds an unrecognised value ("7"), so its state cannot be determined from here\n');
+ assert.strictEqual(featureLine({ feature: 'formFill', setting: 'FormFillBarUXEnabled', enabled: true }), ' ✓ Form fill assist toolbar (FormFillBarUXEnabled)\n');
+ assert.strictEqual(featureLine({ feature: 'formFill', setting: 'FormFillBarUXEnabled', enabled: false }), ' ✗ Form fill assist toolbar (FormFillBarUXEnabled)\n');
+ assert.strictEqual(featureLine({ feature: 'somethingNew', setting: 'X', enabled: true }), ' ✓ somethingNew (X)\n');
+ // In effect wins over "platform default"; an enabled gate does not hide that the setting defers.
+ assert.match(featureLine({ feature: 'nlSearch', setting: 'S', enabled: false, inEffect: true, effectiveDefault: true, effectiveScope: 'organization', effectiveValue: '0' }), /^ {2}✓ .*in effect via the organization setting/);
+ assert.match(featureLine({ feature: 'nlSearch', setting: 'S', enabled: true, effectiveDefault: true, effectiveValue: '0' }), /^ {2}\? .*platform default/);
+ assert.match(featureLine({ feature: 'nlSearch', setting: 'S', enabled: true, inEffect: true, effectiveValue: '2' }), /^ {2}✓ Natural language search \(S\)\n$/, 'in effect AND enabled is the plain ✓');
+});
diff --git a/plugins/model-apps/scripts/tests/app-delete-real-bundle.test.js b/plugins/model-apps/scripts/tests/app-delete-real-bundle.test.js
index 473b0a8c7..d28094a95 100644
--- a/plugins/model-apps/scripts/tests/app-delete-real-bundle.test.js
+++ b/plugins/model-apps/scripts/tests/app-delete-real-bundle.test.js
@@ -350,3 +350,121 @@ test('REAL BUNDLE + REAL TRANSPORT: the plugin HttpClient satisfies the SDK atom
assert.strictEqual(sitemapIfMatch && sitemapIfMatch[1], SITEMAP_ROW_ETAG,
'the header-borne row token must reach the SDK through the real transport');
});
+
+// Measured live: a teardown's app delete — this change set — lost a SQL deadlock, and the whole teardown
+// stopped with nothing removed. A change set is atomic, so that answer proves nothing committed, and the
+// transport re-sends the same batch (sdk-http-client.js, isBatchDeadlockVictim). The first answer below is
+// the captured one: HTTP 500 for the batch, and only the failing operation answered inside it.
+test('REAL BUNDLE + REAL TRANSPORT: an app delete whose change set lost a SQL deadlock is re-sent and succeeds', async () => {
+ const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'appdel-'));
+ tempDirs.push(dir);
+ const batches = [];
+ const slept = [];
+ const deadlocked = [
+ '--batchresponse_x', 'Content-Type: multipart/mixed; boundary=changesetresponse_x', '',
+ '--changesetresponse_x', 'Content-Type: application/http', 'Content-Transfer-Encoding: binary', 'Content-ID: 1', '',
+ 'HTTP/1.1 500 Internal Server Error', 'Content-Type: application/json; odata.metadata=minimal; odata.streaming=true', 'OData-Version: 4.0', '',
+ JSON.stringify({ error: { code: '0x80044150', message: ' Sql error: Generic SQL error. CRM ErrorCode: -2147204784 Sql ErrorCode: -2146232060 Sql Number: 1205' } }),
+ '--changesetresponse_x--', '--batchresponse_x--', '',
+ ].join('\r\n');
+ const request = async ({ url, body }) => {
+ const meta = /EntityDefinitions\(LogicalName='([^']+)'\)/.exec(url);
+ if (meta) return { statusCode: 200, headers: {}, body: JSON.stringify({ LogicalName: meta[1], EntitySetName: `${meta[1]}s` }) };
+ if (/\/\$batch$/.test(url)) {
+ batches.push(body);
+ return batches.length === 1 ? { statusCode: 500, headers: {}, body: deadlocked } : { statusCode: 200, headers: {}, body: batchResponseFor(body) };
+ }
+ if (/\/appmodules\([^)]+\)/.test(url)) return { statusCode: 200, headers: {}, body: JSON.stringify(appRow()) };
+ if (SITEMAP_BY_ID.test(url)) return { statusCode: 200, headers: { etag: SITEMAP_ROW_ETAG }, body: JSON.stringify({ sitemapid: SITEMAP_ID }) };
+ if (url.includes('/sitemaps')) return { statusCode: 200, headers: {}, body: JSON.stringify({ value: [sitemapRow()] }) };
+ return { statusCode: 200, headers: {}, body: JSON.stringify({ value: [] }) };
+ };
+ const httpClient = createAzHttpClient('https://example.crm.dynamics.com', { getToken: () => 'TOK', request, sleep: async (ms) => { slept.push(ms); } });
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(dir), instanceUrl: 'https://example.crm.dynamics.com', httpClient });
+ await sdk.initWorkspace();
+
+ const r = await sdk.deleteAppCascade(APP_ID, APP_UNIQUE_ID);
+ assert.ok(r.success, `cascade reported failure: ${JSON.stringify(r.failures)}`);
+ assert.strictEqual(batches.length, 2, 'the deadlocked change set was sent once more');
+ assert.strictEqual(batches[1], batches[0], 'the same change set, byte for byte (the same conditional DELETEs)');
+ assert.deepStrictEqual(slept, [1000]);
+});
+
+// A 429 is the other answer that proves nothing ran: the server refused to START the request. Two shapes
+// are re-sent (sdk-http-client.js, isBatchThrottled): the whole batch refused before any operation was read
+// (service protection answers with a plain error), and a change set whose one answered operation is a 429
+// (the customization lock the platform holds right after a table delete).
+for (const [shape, refusal] of [
+ ['the whole request refused (service protection)', { statusCode: 429, headers: { 'retry-after': '3' }, body: JSON.stringify({ error: { code: '0x80072322', message: 'Number of requests exceeded the limit of 6000 over time window of 300 seconds.' } }) }],
+ ['its change set refused (customization lock)', { statusCode: 429, headers: {}, body: [
+ '--batchresponse_y', 'Content-Type: multipart/mixed; boundary=changesetresponse_y', '',
+ '--changesetresponse_y', 'Content-Type: application/http', 'Content-Transfer-Encoding: binary', 'Content-ID: 1', '',
+ 'HTTP/1.1 429 Too Many Requests', 'Content-Type: application/json; odata.metadata=minimal', 'OData-Version: 4.0', '',
+ JSON.stringify({ error: { code: '0x80071151', message: 'Cannot start the requested operation [Delete] because there is another [EntityCustomization] running at this moment.' } }),
+ '--changesetresponse_y--', '--batchresponse_y--', '',
+ ].join('\r\n') }],
+]) {
+ test(`REAL BUNDLE + REAL TRANSPORT: an app delete refused with 429 — ${shape} — is re-sent and succeeds`, async () => {
+ const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'appdel-'));
+ tempDirs.push(dir);
+ const batches = [];
+ const slept = [];
+ const request = async ({ url, body }) => {
+ const meta = /EntityDefinitions\(LogicalName='([^']+)'\)/.exec(url);
+ if (meta) return { statusCode: 200, headers: {}, body: JSON.stringify({ LogicalName: meta[1], EntitySetName: `${meta[1]}s` }) };
+ if (/\/\$batch$/.test(url)) {
+ batches.push(body);
+ return batches.length === 1 ? refusal : { statusCode: 200, headers: {}, body: batchResponseFor(body) };
+ }
+ if (/\/appmodules\([^)]+\)/.test(url)) return { statusCode: 200, headers: {}, body: JSON.stringify(appRow()) };
+ if (SITEMAP_BY_ID.test(url)) return { statusCode: 200, headers: { etag: SITEMAP_ROW_ETAG }, body: JSON.stringify({ sitemapid: SITEMAP_ID }) };
+ if (url.includes('/sitemaps')) return { statusCode: 200, headers: {}, body: JSON.stringify({ value: [sitemapRow()] }) };
+ return { statusCode: 200, headers: {}, body: JSON.stringify({ value: [] }) };
+ };
+ const httpClient = createAzHttpClient('https://example.crm.dynamics.com', { getToken: () => 'TOK', request, random: () => 0, sleep: async (ms) => { slept.push(ms); } });
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(dir), instanceUrl: 'https://example.crm.dynamics.com', httpClient });
+ await sdk.initWorkspace();
+
+ const r = await sdk.deleteAppCascade(APP_ID, APP_UNIQUE_ID);
+ assert.ok(r.success, `cascade reported failure: ${JSON.stringify(r.failures)}`);
+ assert.strictEqual(batches.length, 2, 'the refused change set was sent once more');
+ assert.strictEqual(batches[1], batches[0], 'the same change set, byte for byte');
+ assert.deepStrictEqual(slept, [refusal.headers['retry-after'] ? 3000 : 1000], 'the throttle backoff, or longer when Retry-After asks');
+ });
+}
+
+// Measured live, in two teardowns: the solution delete that ends a teardown was refused with
+// `[Uninstall] … another [EntityCustomization] running … Please try again later`, and both finished with the
+// solution left behind. The same answer, through the real SDK's deleteSolution and the plugin transport.
+test('REAL BUNDLE + REAL TRANSPORT: a solution delete refused with 429 is re-sent; one refused every time surfaces as the failure it is', async () => {
+ const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
+ const SOLUTION_ID = '44444444-4444-4444-4444-444444444444';
+ const refused = { statusCode: 429, headers: {}, body: JSON.stringify({ error: { code: '0x80071151', message: 'Cannot start the requested operation [Uninstall] because there is another [EntityCustomization] running at this moment. Use Solution History for more details. -- The solution installation or removal failed due to the installation or removal of another solution at the same time. Please try again later.' } }) };
+ const run = async (answers) => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'soldel-'));
+ tempDirs.push(dir);
+ const deletes = [];
+ const request = async ({ url, method }) => {
+ if (method === 'DELETE') { deletes.push(url); return answers(deletes.length); }
+ return { statusCode: 200, headers: {}, body: JSON.stringify({ value: [] }) };
+ };
+ const httpClient = createAzHttpClient('https://example.crm.dynamics.com', { getToken: () => 'TOK', request, sleep: async () => {} });
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(dir), instanceUrl: 'https://example.crm.dynamics.com', httpClient });
+ await sdk.initWorkspace();
+ let error = null;
+ try { await sdk.deleteSolution(SOLUTION_ID); } catch (e) { error = e; }
+ return { deletes, error };
+ };
+
+ const recovered = await run((n) => (n <= 2 ? refused : { statusCode: 204, headers: {}, body: '' }));
+ assert.strictEqual(recovered.error, null, recovered.error && recovered.error.message);
+ assert.strictEqual(recovered.deletes.length, 3, 'two refusals, then the delete that ran');
+ assert.ok(recovered.deletes.every((u) => u.includes(`solutions(${SOLUTION_ID})`)));
+
+ const stuck = await run(() => refused);
+ assert.ok(stuck.error, 'a lock that never clears is still reported, not swallowed');
+ assert.match(String(stuck.error.message), /429|EntityCustomization/);
+ assert.strictEqual(stuck.deletes.length, 6, 'six attempts, like any other throttled request');
+});
diff --git a/plugins/model-apps/scripts/tests/app-spec-keys.test.js b/plugins/model-apps/scripts/tests/app-spec-keys.test.js
index a0133ebfd..36f926567 100644
--- a/plugins/model-apps/scripts/tests/app-spec-keys.test.js
+++ b/plugins/model-apps/scripts/tests/app-spec-keys.test.js
@@ -356,6 +356,16 @@ test('#537: exotic values become validation errors, not raw crashes', () => {
const r2 = validateAppSpec(s2, { profile: 'plan' });
assert.strictEqual(r2.ok, false);
assert.ok(r2.errors.some((e) => /could not be inspected/.test(e)), JSON.stringify(r2.errors));
+});
+
+// #631: the appShell key allow-list is guarded the same way — a node whose keys cannot be enumerated
+// is an error naming it, never a crash out of the validator.
+test('#631: an appShell node whose keys cannot be enumerated becomes a validation error, not a crash', () => {
+ const s = base();
+ s.appShell = { areas: [new Proxy({ label: 'Main', groups: [] }, { ownKeys() { throw new Error('trap'); } })] };
+ const r = validateAppSpec(s, { profile: 'plan' });
+ assert.strictEqual(r.ok, false);
+ assert.ok(r.errors.some((e) => /could not be inspected: enumerating its keys threw/.test(e)), JSON.stringify(r.errors));
});
// --- review follow-ups on the #537 entity-key allow-list ----------------------------------------
diff --git a/plugins/model-apps/scripts/tests/applied-baseline.test.js b/plugins/model-apps/scripts/tests/applied-baseline.test.js
new file mode 100644
index 000000000..99f2f10c0
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/applied-baseline.test.js
@@ -0,0 +1,71 @@
+'use strict';
+// build-model-app.js `persistAppliedBaseline`: when a build records its spec as the environment's
+// deployed baseline (`.maker-workspace/last-applied.json`).
+//
+// The baseline is what the next build lines the live sitemap up against (AB#6726727): a nav entry the
+// designer changed since the baseline is kept, one the spec changed is written. So recording it after
+// a run that did NOT deploy the whole spec — a dry run, a partial `--phases` run, or an apply whose
+// verify found a silent partial — would make the next build treat undeployed spec values as deployed,
+// and revert designer changes it should have kept.
+const test = require('node:test');
+const assert = require('node:assert');
+
+const { persistAppliedBaseline } = require('../build-model-app.js');
+const { PHASES } = require('../lib/stages.js');
+
+const spec = { app: { name: 'A', uniqueName: 'new_a' } };
+const ctx = (opts) => ({ spec, opts, workspaceDir: '/ws', appDirAbs: '/app', baselineIdentity: { environment: 'https://contoso.crm.dynamics.com', appUniqueName: 'new_a' } });
+function recorder({ fail } = {}) {
+ const calls = [];
+ const write = (...args) => { calls.push(args); if (fail) throw new Error('disk full'); };
+ return { calls, write };
+}
+
+test('a verified full apply records the spec, its environment and app, the ids it created, and the previous baseline', () => {
+ const { calls, write } = recorder();
+ const created = { dashboards: { Ops: 'd1' }, pages: { home: 'p1' } };
+ const previous = { app: { name: 'old' } };
+ const r = { ok: true, verify: { ok: true }, created };
+ assert.strictEqual(persistAppliedBaseline(r, ctx({ apply: true, baselineSpec: previous }), write), true);
+ assert.deepStrictEqual(calls, [['/ws', spec, { appDir: '/app', environment: 'https://contoso.crm.dynamics.com', appUniqueName: 'new_a', created, previous }]]);
+});
+
+test('an apply without verify is recorded; one whose verify failed is not (a silent partial is not the deployed state)', () => {
+ for (const [verify, want] of [[undefined, true], [{ ok: true }, true], [{ ok: false }, false]]) {
+ const { calls, write } = recorder();
+ assert.strictEqual(persistAppliedBaseline({ ok: true, verify }, ctx({ apply: true }), write), want, JSON.stringify(verify));
+ assert.strictEqual(calls.length, want ? 1 : 0);
+ }
+});
+
+test('nothing is recorded for a failed build, a dry run, or a run that was not an apply', () => {
+ for (const [r, opts] of [
+ [{ ok: false }, { apply: true }],
+ [{ ok: true, dryRun: true }, { apply: true }],
+ [{ ok: true }, { apply: false }],
+ [{ ok: true }, {}],
+ [null, { apply: true }],
+ ]) {
+ const { calls, write } = recorder();
+ assert.strictEqual(persistAppliedBaseline(r, ctx(opts), write), false, JSON.stringify([r, opts]));
+ assert.deepStrictEqual(calls, []);
+ }
+});
+
+test('a partial --phases apply is not the whole desired state and is not recorded — unless it is a changed-only apply', () => {
+ const partial = { apply: true, phases: PHASES.slice(0, 2) };
+ const { calls, write } = recorder();
+ assert.strictEqual(persistAppliedBaseline({ ok: true }, ctx(partial), write), false);
+ assert.strictEqual(persistAppliedBaseline({ ok: true }, ctx({ apply: true, phases: [...PHASES] }), write), true, 'every phase listed is a full apply');
+ for (const decision of ['fast', 'full']) {
+ assert.strictEqual(persistAppliedBaseline({ ok: true, changedOnly: { decision } }, ctx(partial), write), true, decision);
+ }
+ assert.strictEqual(persistAppliedBaseline({ ok: true, changedOnly: { decision: 'refused' } }, ctx(partial), write), false);
+ assert.strictEqual(calls.length, 3);
+});
+
+test('a baseline that cannot be written never fails the build', () => {
+ const { calls, write } = recorder({ fail: true });
+ assert.strictEqual(persistAppliedBaseline({ ok: true }, ctx({ apply: true }), write), false);
+ assert.strictEqual(calls.length, 1);
+});
diff --git a/plugins/model-apps/scripts/tests/apply-snapshot-store.test.js b/plugins/model-apps/scripts/tests/apply-snapshot-store.test.js
index d555379c9..ca9b27fbd 100644
--- a/plugins/model-apps/scripts/tests/apply-snapshot-store.test.js
+++ b/plugins/model-apps/scripts/tests/apply-snapshot-store.test.js
@@ -33,6 +33,51 @@ test('writeSnapshotAtomic + readSnapshot round-trip and leave NO temp file behin
} finally { rm(d); }
});
+// The apply snapshot and the sitemap baseline (deployed-baseline.js) share this writer. A write that fails at any
+// step — the write, the fsync, the rename — leaves the target exactly as it was and no temp beside it, and the text
+// lands whole however the OS splits the write (a short write fsynced and renamed into place is a partial file).
+test('writeFileAtomic leaves the target as it was, and no temp, when any step fails — and writes the whole text', (t) => {
+ const d = ws();
+ try {
+ const target = path.join(d, 'file.json');
+ fs.writeFileSync(target, 'previous');
+ for (const [step, code] of [['writeSync', 'ENOSPC'], ['fsyncSync', 'EIO'], ['renameSync', 'EPERM']]) {
+ const mock = t.mock.method(fs, step, () => { throw Object.assign(new Error(`simulated ${code}`), { code }); });
+ // A Buffer goes through writeFileSync's own loop over fs.writeSync, so the write itself can be failed.
+ assert.throws(() => store.writeFileAtomic(target, Buffer.from('next')), { code }, step);
+ mock.mock.restore();
+ assert.strictEqual(fs.readFileSync(target, 'utf8'), 'previous', `${step}: the target is untouched`);
+ assert.deepStrictEqual(fs.readdirSync(d), ['file.json'], `${step}: no temp is left beside it`);
+ }
+ const text = JSON.stringify({ padding: 'x'.repeat(64) });
+ const realWriteSync = fs.writeSync;
+ let calls = 0;
+ const split = t.mock.method(fs, 'writeSync', (fd, data, ...rest) => {
+ calls += 1;
+ const buf = typeof data === 'string' ? Buffer.from(data, 'utf8') : data;
+ const offset = typeof data === 'string' ? 0 : (rest[0] || 0);
+ return realWriteSync(fd, buf, offset, 1);
+ });
+ store.writeFileAtomic(target, Buffer.from(text, 'utf8'));
+ split.mock.restore();
+ assert.strictEqual(calls, Buffer.byteLength(text), 'each byte went through its own write');
+ assert.strictEqual(fs.readFileSync(target, 'utf8'), text, 'the whole text landed');
+ assert.deepStrictEqual(fs.readdirSync(d), ['file.json']);
+ } finally { rm(d); }
+});
+
+test('writeSnapshotAtomic writes through writeFileAtomic: a write that fails leaves the previous snapshot', (t) => {
+ const d = ws();
+ try {
+ store.writeSnapshotAtomic(d, eligible('g1'));
+ const mock = t.mock.method(fs, 'renameSync', () => { throw Object.assign(new Error('simulated EPERM'), { code: 'EPERM' }); });
+ assert.throws(() => store.writeSnapshotAtomic(d, eligible('g2')), { code: 'EPERM' });
+ mock.mock.restore();
+ assert.strictEqual(store.readSnapshot(d).generation, 'g1', 'the previous snapshot is untouched');
+ assert.deepStrictEqual(fs.readdirSync(d).filter((f) => f.endsWith('.tmp')), [], 'and no temp is left');
+ } finally { rm(d); }
+});
+
test('readSnapshot: absent file -> null; garbage/foreign-schema -> null (fail-closed)', () => {
const d = ws();
try {
diff --git a/plugins/model-apps/scripts/tests/build-model-app.test.js b/plugins/model-apps/scripts/tests/build-model-app.test.js
index 3c8d714c8..9163d0791 100644
--- a/plugins/model-apps/scripts/tests/build-model-app.test.js
+++ b/plugins/model-apps/scripts/tests/build-model-app.test.js
@@ -280,6 +280,10 @@ test('isTransientHalt classifies lock/timeout/429/503 as transient, others not',
assert.ok(isTransientHalt({ message: 'Microsoft.Crm.ObjectModel.CustomizationLockException: ...' }));
assert.ok(isTransientHalt({ cause: { message: 'SQL timeout expired' } }));
assert.ok(isTransientHalt({ message: 'More than one concurrent Delete requests detected' }));
+ // A SQL deadlock victim was rolled back, so running the idempotent build again is safe — captured live.
+ assert.ok(isTransientHalt({ message: 'HTTP 500 from https://contoso.crm.dynamics.com/api/data/v9.0/workflows(1): Sql error: Generic SQL error. CRM ErrorCode: -2147204784 Sql ErrorCode: -2146232060 Sql Number: 1205' }));
+ assert.ok(!isTransientHalt({ message: 'Sql error: Generic SQL error. Sql Number: 547' }), 'another SQL error is not a deadlock');
+ assert.ok(!isTransientHalt({ transient: false, message: 'Sql Number: 1205' }), 'an explicit non-transient still wins');
// recoverable is a re-runnable-phase flag, NOT a transient signal — must not trigger a retry alone.
assert.ok(!isTransientHalt({ recoverable: true }));
assert.ok(!isTransientHalt({ message: 'validation failed', cause: { statusCode: 400 } }));
@@ -1792,7 +1796,7 @@ test('the verify options carry the ACTUAL phase list, not a constant', () => {
// Asserted on the SOURCE because the value has to be the caller's own `opts.phases`: a test that
// merely passes a phase list through would still accept `phases: PHASES`.
const src = fs.readFileSync(path.join(__dirname, '..', 'build-model-app.js'), 'utf8');
- assert.match(src, /deps\.verify\(spec, \{ environmentSkipped: r\.skipped, phases: opts\.phases \}\)/,
+ assert.match(src, /deps\.verify\(spec, \{ environmentSkipped: r\.skipped, phases: opts\.phases(, baselineSpec: opts\.baselineSpec)? \}\)/,
'verify must receive the invocation\'s OWN phases — a constant re-breaks the --changed-only fast path');
});
diff --git a/plugins/model-apps/scripts/tests/deployed-baseline.test.js b/plugins/model-apps/scripts/tests/deployed-baseline.test.js
new file mode 100644
index 000000000..4583177ba
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/deployed-baseline.test.js
@@ -0,0 +1,162 @@
+'use strict';
+// lib/deployed-baseline.js: the last-applied/downloaded spec is a sitemap baseline ONLY for the app and
+// environment it describes (AB#6726727).
+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 { baselinePath, confinedReader, deployedIdsFor, writeBaseline, readBaseline } = require('../lib/deployed-baseline.js');
+
+const ENV = 'https://contoso.crm.dynamics.com';
+const spec = () => ({ solution: { uniqueName: 'S', publisherPrefix: 'new' }, app: { name: 'A', uniqueName: 'new_a' }, pages: [{ key: 'home', name: 'Home', source: { kind: 'tsx', codeFile: 'pages/home.tsx' } }] });
+
+const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'baseline-'));
+
+test('a baseline is returned only for the app and environment it was written for', () => {
+ const dir = tmp();
+ try {
+ const ws = path.join(dir, '.maker-workspace');
+ fs.mkdirSync(path.join(dir, 'pages'));
+ fs.writeFileSync(path.join(dir, 'pages', 'home.tsx'), 'export default () => null;');
+ writeBaseline(ws, spec(), { appDir: dir, environment: ENV, appUniqueName: 'new_a' });
+ const got = readBaseline(ws, { environment: ENV, appUniqueName: 'NEW_A' });
+ assert.ok(got, 'same app (unique names are case-insensitive) and environment');
+ assert.strictEqual(got.app.uniqueName, 'new_a');
+ assert.match(got.pages[0].__contentSha, /^[0-9a-f]{64}$/, 'annotated like a build-written snapshot, so the dry-run diff does not over-report');
+ assert.strictEqual(readBaseline(ws, { environment: 'https://fabrikam.crm.dynamics.com', appUniqueName: 'new_a' }), null, 'another environment');
+ assert.strictEqual(readBaseline(ws, { environment: ENV, appUniqueName: 'new_b' }), null, 'another app');
+ assert.strictEqual(readBaseline(ws, { environment: null, appUniqueName: 'new_a' }), null, 'an environment that could not be identified');
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+// A plain write cut short by a crash or a full disk left a truncated file, which reads as no baseline — and
+// without one the spec wins over every nav change made in the designer. The baseline is written atomically
+// (writeFileAtomic, apply-snapshot-store.js), so a write that fails leaves the previous one, still readable.
+test('a baseline write that fails leaves the previous baseline readable, and no temp file', (t) => {
+ const dir = tmp();
+ try {
+ const ws = path.join(dir, '.maker-workspace');
+ const identity = { appDir: dir, environment: ENV, appUniqueName: 'new_a' };
+ writeBaseline(ws, spec(), identity);
+ const before = fs.readFileSync(baselinePath(ws), 'utf8');
+ const next = { ...spec(), app: { name: 'Renamed', uniqueName: 'new_a' } };
+ for (const step of ['fsyncSync', 'renameSync']) {
+ const mock = t.mock.method(fs, step, () => { throw Object.assign(new Error('no space left on device'), { code: 'ENOSPC' }); });
+ assert.throws(() => writeBaseline(ws, next, identity), { code: 'ENOSPC' }, step);
+ mock.mock.restore();
+ assert.strictEqual(fs.readFileSync(baselinePath(ws), 'utf8'), before, `${step}: the previous baseline is untouched`);
+ assert.strictEqual(readBaseline(ws, { environment: ENV, appUniqueName: 'new_a' }).app.name, 'A', step);
+ assert.deepStrictEqual(fs.readdirSync(ws), ['last-applied.json'], `${step}: no temp is left`);
+ }
+ writeBaseline(ws, next, identity);
+ assert.strictEqual(readBaseline(ws, { environment: ENV, appUniqueName: 'new_a' }).app.name, 'Renamed');
+ assert.deepStrictEqual(fs.readdirSync(ws), ['last-applied.json']);
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test('a snapshot with no stamps, or one that cannot be read, is not a baseline', () => {
+ const dir = tmp();
+ try {
+ fs.writeFileSync(baselinePath(dir), JSON.stringify(spec()));
+ assert.strictEqual(readBaseline(dir, { environment: ENV, appUniqueName: 'new_a' }), null, 'written before the stamps existed');
+ fs.writeFileSync(baselinePath(dir), '{ not json');
+ assert.strictEqual(readBaseline(dir, { environment: ENV, appUniqueName: 'new_a' }), null);
+ fs.writeFileSync(baselinePath(dir), '[]');
+ assert.strictEqual(readBaseline(dir, { environment: ENV, appUniqueName: 'new_a' }), null);
+ assert.strictEqual(readBaseline(path.join(dir, 'missing'), { environment: ENV, appUniqueName: 'new_a' }), null);
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test('the content reader stays inside the app folder', () => {
+ const dir = tmp();
+ try {
+ fs.writeFileSync(path.join(dir, 'in.txt'), 'x');
+ const read = confinedReader(dir);
+ assert.strictEqual(String(read('in.txt')), 'x');
+ assert.strictEqual(read('../outside.txt'), null);
+ assert.strictEqual(read(path.resolve(dir, '..', 'x.txt')), null);
+ assert.strictEqual(read('missing.txt'), null);
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+// AB#6726727: the sitemap baseline lines nav entries up by the ids a dashboard and page have in THIS
+// environment. A spec downloaded from another one keeps that one's ids, so an apply records what IT
+// resolved, and a download what it read.
+const A = 'aaaaaaaa-0000-0000-0000-000000000001';
+const B = 'bbbbbbbb-0000-0000-0000-000000000002';
+const F = 'ffffffff-0000-0000-0000-00000000000f';
+const withIds = () => ({ ...spec(), dashboards: [{ name: 'Ops', dashboardId: F }, { name: 'Sales' }], pages: [{ key: 'home', name: 'Home', pageId: F, source: { kind: 'tsx', codeFile: 'pages/home.tsx' } }, { key: 'about', name: 'About' }] });
+
+test('an apply records the ids it resolved, then the prior baseline\u2019s, and never the spec\u2019s own', () => {
+ const ids = deployedIdsFor(withIds(), {
+ created: { dashboards: { Ops: A }, pages: { home: B } },
+ previous: { __deployedIds: { dashboards: { Sales: B, Ops: F }, pages: { about: A } } },
+ });
+ assert.deepStrictEqual(ids, { dashboards: { Ops: A, Sales: B }, pages: { home: B, about: A } });
+ // Nothing resolved it and no prior baseline had it: left out, for the next build to resolve.
+ assert.deepStrictEqual(deployedIdsFor(withIds(), {}), { dashboards: {}, pages: {} });
+});
+
+test('a download records the ids it read from the environment', () => {
+ assert.deepStrictEqual(deployedIdsFor(withIds(), { fromSpec: true }), { dashboards: { Ops: F }, pages: { home: F } });
+});
+
+test('a name that is also an Object.prototype member is recorded as data, not as the prototype', () => {
+ const s = { dashboards: [{ name: '__proto__' }, { name: 'constructor' }] };
+ const ids = deployedIdsFor(s, { created: { dashboards: JSON.parse(`{"__proto__":"${A}"}`) } });
+ assert.deepStrictEqual(Object.keys(ids.dashboards), ['__proto__']);
+ assert.strictEqual(Object.getPrototypeOf(ids.dashboards), Object.prototype);
+ assert.strictEqual(JSON.parse(JSON.stringify(ids)).dashboards.__proto__, A);
+});
+
+test('the baseline is written with its deployed ids and read back as schemaVersion 2', () => {
+ const dir = tmp();
+ try {
+ const ws = path.join(dir, '.maker-workspace');
+ // A legacy (v1) download: the page is referenced from the nav by NAME, and has no key yet.
+ const legacy = { solution: { uniqueName: 'S', publisherPrefix: 'new' }, app: { name: 'A', uniqueName: 'new_a' },
+ pages: [{ name: 'Home Page', pageId: A, codeFile: 'pages/home.tsx' }],
+ appShell: { areas: [{ label: 'M', groups: [{ label: 'G', subAreas: [{ page: 'Home Page', title: 'Home' }] }] }] } };
+ writeBaseline(ws, legacy, { appDir: dir, environment: ENV, appUniqueName: 'new_a', fromSpec: true });
+ const got = readBaseline(ws, { environment: ENV, appUniqueName: 'new_a' });
+ const key = got.pages[0].key;
+ assert.ok(key, 'migrated: the page has a key');
+ assert.strictEqual(got.appShell.areas[0].groups[0].subAreas[0].page, key, 'and the nav references it by that key');
+ assert.deepStrictEqual(got.__deployedIds, { dashboards: {}, pages: { [key]: A } });
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+// readBaseline runs on EVERY build in a folder that has a baseline, so one the migrator cannot read must
+// degrade to "no baseline" (the build then reports each nav change it makes) — never throw out of the
+// build. The migrator is defensive enough that parsed JSON cannot make it throw, so the module is loaded
+// here against one that does.
+test('a baseline the migrator cannot read is no baseline, not a crash', () => {
+ const dir = tmp();
+ const modPath = require.resolve('../lib/deployed-baseline.js');
+ const specPath = require.resolve('../lib/app-spec.js');
+ const saved = { mod: require.cache[modPath], spec: require.cache[specPath] };
+ try {
+ const ws = path.join(dir, '.maker-workspace');
+ writeBaseline(ws, { ...spec(), pages: [] }, { appDir: dir, environment: ENV, appUniqueName: 'new_a' });
+ assert.ok(readBaseline(ws, { environment: ENV, appUniqueName: 'new_a' }), 'readable with the real migrator');
+ delete require.cache[modPath];
+ require.cache[specPath] = { ...saved.spec, exports: { ...saved.spec.exports, migrateAppSpec: () => { throw new Error('unreadable'); } } };
+ const fresh = require('../lib/deployed-baseline.js');
+ assert.strictEqual(fresh.readBaseline(ws, { environment: ENV, appUniqueName: 'new_a' }), null);
+ } finally {
+ require.cache[specPath] = saved.spec;
+ if (saved.mod) require.cache[modPath] = saved.mod; else delete require.cache[modPath];
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
diff --git a/plugins/model-apps/scripts/tests/download-workspace-isolation.test.js b/plugins/model-apps/scripts/tests/download-workspace-isolation.test.js
new file mode 100644
index 000000000..abeb16411
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/download-workspace-isolation.test.js
@@ -0,0 +1,563 @@
+'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 {
+ main,
+ makeDownloadSdk,
+} = require('../download-model-app.js');
+const { writeBaseline } = require('../lib/deployed-baseline.js');
+
+const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');
+const APP_ID = '11111111-1111-1111-1111-111111111111';
+const APP_UNIQUE_ID = '22222222-2222-2222-2222-222222222222';
+const APP_UNIQUE = 'new_workspaceprobe';
+const SITEMAP_ID = '33333333-3333-3333-3333-333333333333';
+const TABLE_METADATA_ID = '44444444-4444-4444-4444-444444444444';
+const ENV = 'https://contoso.crm.dynamics.com';
+
+const tempDirs = [];
+test.after(() => {
+ for (const dir of tempDirs) fs.rmSync(dir, { recursive: true, force: true });
+});
+
+function tmp(prefix) {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
+ tempDirs.push(dir);
+ return dir;
+}
+
+function listRelativeFiles(root) {
+ if (!fs.existsSync(root)) return [];
+ const out = [];
+ const walk = (dir) => {
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
+ const abs = path.join(dir, entry.name);
+ if (entry.isDirectory()) walk(abs);
+ else out.push(path.relative(root, abs));
+ }
+ };
+ walk(root);
+ return out.sort();
+}
+
+function minimalSpec() {
+ return {
+ schemaVersion: 2,
+ solution: { uniqueName: 'WorkspaceProbe', publisherPrefix: 'new' },
+ app: { name: 'Workspace Probe', uniqueName: APP_UNIQUE },
+ entities: [],
+ pages: [],
+ appShell: { areas: [] },
+ };
+}
+
+function fakeMainDeps({ outDir, makeDownloadSdkImpl, runDownloadImpl, emitResults, stderr }) {
+ const sdk = {
+ queryRecords: async (logical, opts = {}) => {
+ assert.strictEqual(logical, 'appmodule');
+ const filter = opts.filter || '';
+ if (/uniquename eq/.test(filter)) return [{ appmoduleid: APP_ID }];
+ if (/appmoduleid eq/.test(filter)) return [{ uniquename: APP_UNIQUE }];
+ return [];
+ },
+ };
+ return {
+ argv: ['--env', ENV, '--app', APP_UNIQUE, '--out', outDir],
+ stderr: stderr || { write: () => {} },
+ emitResult: (ok, payload) => emitResults.push({ ok, payload }),
+ preflightAuth: async () => ({ ok: true }),
+ makeGenpageCli: () => ({ unused: true }),
+ makeDownloadSdk: makeDownloadSdkImpl || (async () => ({ sdk, cleanup: () => {} })),
+ runDownload: runDownloadImpl || (async ({ sdk: gotSdk, outDir: gotOutDir, appId, appUnique }) => {
+ assert.strictEqual(gotSdk, sdk);
+ assert.strictEqual(gotOutDir, outDir);
+ assert.strictEqual(appId, APP_ID);
+ assert.strictEqual(appUnique, APP_UNIQUE);
+ return {
+ ok: true,
+ spec: minimalSpec(),
+ pages: [],
+ entities: [],
+ webResources: [],
+ droppedSubareas: 0,
+ droppedSubareaDetails: [],
+ dashboardWarnings: [],
+ };
+ }),
+ validateAppSpec: () => ({ ok: true, warnings: [] }),
+ };
+}
+
+// The real result printer ends the process (emitResult calls process.exit), so nothing after it runs:
+// the throwaway workspace must be gone BEFORE the result is printed. A cleanup in a `finally` the
+// printer never returned to used to leave one temp workspace behind per download. The fake printer
+// here throws where the real one exits, so it cannot hide that the way a returning fake did.
+test('the throwaway workspace is removed BEFORE the result is printed, since the real printer ends the process', async () => {
+ for (const scenario of ['success', 'a download that fails', 'an app that cannot be resolved']) {
+ const outDir = tmp('download-exit-');
+ const tempWorkspace = tmp('model-app-download-exit-');
+ const EXIT = new Error('process.exit');
+ let existedAtPrint = null;
+ let printed = 0;
+ const deps = fakeMainDeps({
+ outDir,
+ emitResults: [],
+ runDownloadImpl: scenario === 'a download that fails' ? async () => ({ ok: false, error: 'dashboard read failed' }) : undefined,
+ });
+ const cleanup = () => fs.rmSync(tempWorkspace, { recursive: true, force: true });
+ const base = deps.makeDownloadSdk;
+ deps.makeDownloadSdk = scenario === 'an app that cannot be resolved'
+ ? async () => ({ sdk: { queryRecords: async () => [] }, cleanup })
+ : async (...args) => ({ ...(await base(...args)), cleanup });
+ let printedOk = null;
+ deps.emitResult = (ok) => { printed += 1; printedOk = ok; existedAtPrint = fs.existsSync(tempWorkspace); throw EXIT; };
+ await assert.rejects(main(deps), (e) => e === EXIT, scenario);
+ assert.strictEqual(printed, 1, `${scenario}: the result is printed once`);
+ assert.strictEqual(printedOk, scenario === 'success', `${scenario}: the printed outcome`);
+ assert.strictEqual(existedAtPrint, false, `${scenario}: the temp workspace still existed when the result was printed`);
+ }
+});
+
+test('makeDownloadSdk constructs the real bundle through its default import path, in a temp workspace it then removes', async () => {
+ const made = await makeDownloadSdk(ENV, { httpClient: realBundleHttp({ etag: 'W/"1"', description: 'Server description' }) });
+ try {
+ assert.strictEqual((await made.sdk.fetchArtifact('app', APP_ID)).description, 'Server description');
+ assert.ok(path.resolve(made.workspaceDir).startsWith(path.resolve(os.tmpdir())), `the workspace is a temp directory: ${made.workspaceDir}`);
+ assert.ok(fs.existsSync(path.join(made.workspaceDir, 'manifest.json')), 'the SDK initialized the throwaway workspace');
+ } finally {
+ made.cleanup();
+ }
+ assert.ok(!fs.existsSync(made.workspaceDir), 'cleanup removes it');
+});
+
+test('constructs the download SDK on a temp workspace outside the output folder, never on the folder workspace', async () => {
+ const outDir = tmp('download-out-');
+ const constructed = [];
+ const made = await makeDownloadSdk(ENV, {
+ mkdtempSync: (prefix) => {
+ assert.match(prefix, /model-app-download-$/);
+ return tmp('model-app-download-');
+ },
+ createHttpClient: () => ({ get: async () => ({ status: 200, headers: {}, body: { value: [] } }) }),
+ createNodeWorkspaceStorage: (workspaceDir) => {
+ constructed.push(workspaceDir);
+ return { workspaceDir };
+ },
+ createMakerSdk: ({ workspaceStorage }) => ({
+ workspaceStorage,
+ initWorkspace: async () => {},
+ }),
+ });
+ try {
+ assert.strictEqual(constructed.length, 1);
+ assert.ok(!constructed[0].startsWith(outDir), `SDK workspace must be outside output folder: ${constructed[0]}`);
+ assert.notStrictEqual(constructed[0], path.join(outDir, '.maker-workspace'));
+ assert.ok(fs.existsSync(constructed[0]), 'temp workspace exists while the download SDK is in use');
+ } finally {
+ made.cleanup();
+ }
+ assert.ok(!fs.existsSync(constructed[0]), 'cleanup removes the temp workspace after a successful download');
+});
+
+test('removes the temp workspace when the download throws after SDK construction', async () => {
+ const outDir = tmp('download-main-');
+ const emitResults = [];
+ const tempWorkspace = tmp('model-app-download-');
+ let cleaned = false;
+ const sdk = { queryRecords: async () => [{ appmoduleid: APP_ID, uniquename: APP_UNIQUE }] };
+ await assert.rejects(
+ main(fakeMainDeps({
+ outDir,
+ emitResults,
+ makeDownloadSdkImpl: async () => ({
+ sdk,
+ workspaceDir: tempWorkspace,
+ cleanup: () => {
+ cleaned = true;
+ fs.rmSync(tempWorkspace, { recursive: true, force: true });
+ },
+ }),
+ runDownloadImpl: async () => { throw new Error('mid-download failure'); },
+ })),
+ /mid-download failure/
+ );
+ assert.strictEqual(cleaned, true);
+ assert.ok(!fs.existsSync(tempWorkspace), 'temp workspace is removed even when a later download step throws');
+ assert.deepStrictEqual(emitResults, [], 'unexpected throws still propagate to the CLI catch path');
+});
+
+test('CLI argument errors exit before creating any SDK workspace', async () => {
+ for (const [argv, pattern] of [
+ [['--env'], /--env requires a value/],
+ [['--app', APP_UNIQUE], /^Usage:/],
+ ]) {
+ let exited = 0;
+ let madeSdk = false;
+ let text = '';
+ await main({
+ argv,
+ stderr: { write: (s) => { text += s; } },
+ exit: (code) => { exited = code; },
+ preflightAuth: async () => { throw new Error('preflight should not run'); },
+ makeDownloadSdk: async () => { madeSdk = true; },
+ });
+ assert.strictEqual(exited, 1);
+ assert.match(text, pattern);
+ assert.strictEqual(madeSdk, false);
+ }
+});
+
+test('auth failure reports through emitResult before creating the download SDK', async () => {
+ const outDir = tmp('download-auth-');
+ const emitResults = [];
+ let madeSdk = false;
+ await main({
+ argv: ['--env', ENV, '--app', APP_UNIQUE, '--out', outDir],
+ stderr: { write: () => {} },
+ emitResult: (ok, payload) => emitResults.push({ ok, payload }),
+ preflightAuth: async () => ({ ok: false, error: 'not authorized' }),
+ makeDownloadSdk: async () => { madeSdk = true; },
+ });
+ assert.deepStrictEqual(emitResults, [{ ok: false, payload: { ok: false, error: 'not authorized' } }]);
+ assert.strictEqual(madeSdk, false);
+});
+
+test('CLI keeps existing messages for inconclusive auth, display-name resolution, lossy download, validation, and defaulted directEntry', async () => {
+ async function runCase({ appArg = APP_UNIQUE, auth = { ok: true }, runDownloadImpl, validateAppSpec, allowLossy = false }) {
+ const outDir = tmp('download-main-branches-');
+ const emitResults = [];
+ let text = '';
+ const sdk = {
+ queryRecords: async (logical, opts = {}) => {
+ assert.strictEqual(logical, 'appmodule');
+ const filter = opts.filter || '';
+ if (/uniquename eq/.test(filter)) return appArg === APP_UNIQUE ? [{ appmoduleid: APP_ID }] : [];
+ if (/name eq/.test(filter)) return [{ appmoduleid: APP_ID, uniquename: APP_UNIQUE, name: appArg }];
+ if (/appmoduleid eq/.test(filter)) return [{ uniquename: APP_UNIQUE }];
+ return [];
+ },
+ };
+ await main({
+ argv: ['--env', ENV, '--app', appArg, '--out', outDir, ...(allowLossy ? ['--allow-lossy-download'] : [])],
+ stderr: { write: (s) => { text += s; } },
+ emitResult: (ok, payload) => emitResults.push({ ok, payload }),
+ preflightAuth: async () => auth,
+ makeDownloadSdk: async () => ({ sdk, cleanup: () => {} }),
+ makeGenpageCli: () => ({}),
+ runDownload: runDownloadImpl,
+ validateAppSpec: validateAppSpec || (() => ({ ok: true, warnings: [] })),
+ });
+ return { emitResults, text, outDir };
+ }
+
+ const lossyResult = {
+ ok: true,
+ spec: minimalSpec(),
+ pages: [],
+ entities: [],
+ webResources: [],
+ droppedSubareas: 1,
+ droppedSubareaDetails: [{ type: 'DashBoard', id: 'dash-1', title: 'Operations' }],
+ dashboardReconstructionError: 'dashboard read failed',
+ dashboardWarnings: ['dashboard Operations could not be read'],
+ };
+
+ const inconclusiveDisplay = await runCase({
+ appArg: 'Workspace Probe',
+ auth: { ok: false, inconclusive: true, error: 'auth probe timed out' },
+ runDownloadImpl: async () => ({ ...lossyResult, droppedSubareas: 0, dashboardReconstructionError: undefined, dashboardWarnings: [] }),
+ });
+ assert.match(inconclusiveDisplay.text, /auth probe timed out/);
+ assert.match(inconclusiveDisplay.text, /resolved display name 'Workspace Probe' to app unique name 'new_workspaceprobe'/);
+ assert.strictEqual(inconclusiveDisplay.emitResults[0].ok, true);
+
+ const lossyBlocked = await runCase({ runDownloadImpl: async () => lossyResult });
+ assert.match(lossyBlocked.text, /Pass --allow-lossy-download/);
+ assert.match(lossyBlocked.text, / Cause: dashboard Operations could not be read\./, 'a per-dashboard reason is named');
+ assert.strictEqual(lossyBlocked.emitResults[0].ok, false);
+ assert.deepStrictEqual(lossyBlocked.emitResults[0].payload.dashboardWarnings, ['dashboard Operations could not be read']);
+
+ // A subarea dropped with no per-dashboard reason: the message says what dropped and nothing it does
+ // not know, and the payload carries no empty reason list.
+ const lossyNoCause = await runCase({ runDownloadImpl: async () => ({ ...lossyResult, dashboardReconstructionError: undefined, dashboardWarnings: [] }) });
+ assert.match(lossyNoCause.text, /ERROR: 1 sitemap subarea\(s\) could not be round-tripped: DashBoard:dash-1 \(Operations\)\. A rebuild from this spec will DROP them from the app nav\./);
+ assert.doesNotMatch(lossyNoCause.text, /Cause:/);
+ assert.strictEqual(lossyNoCause.emitResults[0].ok, false);
+ assert.strictEqual('dashboardWarnings' in lossyNoCause.emitResults[0].payload, false);
+
+ const lossyAllowed = await runCase({ allowLossy: true, runDownloadImpl: async () => lossyResult });
+ assert.match(lossyAllowed.text, /WARNING: 1 sitemap subarea/);
+ assert.strictEqual(lossyAllowed.emitResults[0].ok, true);
+
+ const validationFailed = await runCase({
+ runDownloadImpl: async () => ({ ...lossyResult, droppedSubareas: 0, dashboardReconstructionError: undefined, dashboardWarnings: [] }),
+ validateAppSpec: () => ({ ok: false, errors: ['bad spec'] }),
+ });
+ assert.deepStrictEqual(validationFailed.emitResults[0].payload, { ok: false, error: 'downloaded App Spec failed validation', errors: ['bad spec'] });
+
+ const defaulted = await runCase({
+ runDownloadImpl: async () => ({
+ ...lossyResult,
+ spec: { ...minimalSpec(), directEntryDefaulted: ['overview'] },
+ pages: [{ pageId: 'p1' }],
+ entities: [{ schemaName: 'new_ticket' }],
+ webResources: [{ name: 'new_icon' }],
+ droppedSubareas: 0,
+ dashboardReconstructionError: undefined,
+ dashboardWarnings: [],
+ notRoundTripped: { views: ['Active Tickets'] },
+ solutionCandidates: { recovered: true },
+ }),
+ validateAppSpec: () => ({ ok: true, warnings: ['review warning'] }),
+ });
+ assert.match(defaulted.text, /WARNING: review warning/);
+ assert.match(defaulted.text, /defaulted to/);
+ assert.strictEqual(defaulted.emitResults[0].payload.pages, 1);
+ assert.deepStrictEqual(defaulted.emitResults[0].payload.directEntryDefaulted, ['overview']);
+ assert.deepStrictEqual(defaulted.emitResults[0].payload.notRoundTripped, { views: ['Active Tickets'] });
+ assert.deepStrictEqual(defaulted.emitResults[0].payload.solutionCandidates, { recovered: true });
+});
+
+test('baseline write remains best-effort when the folder workspace path cannot be a directory', async () => {
+ const outDir = tmp('download-baseline-fails-');
+ fs.writeFileSync(path.join(outDir, '.maker-workspace'), 'not a directory');
+ const emitResults = [];
+ await main(fakeMainDeps({ outDir, emitResults }));
+ assert.strictEqual(emitResults[0].ok, true);
+ assert.strictEqual(fs.readFileSync(path.join(outDir, '.maker-workspace'), 'utf8'), 'not a directory');
+});
+
+test('removes the temp workspace when SDK construction or initWorkspace throws', async () => {
+ for (const [what, createMakerSdk] of [
+ ['constructor throws', () => { throw new Error('constructor failed'); }],
+ ['initWorkspace throws', () => ({ initWorkspace: async () => { throw new Error('init failed'); } })],
+ ]) {
+ let tempWorkspace;
+ await assert.rejects(
+ makeDownloadSdk(ENV, {
+ mkdtempSync: () => {
+ tempWorkspace = tmp('model-app-download-');
+ return tempWorkspace;
+ },
+ createHttpClient: () => ({}),
+ createNodeWorkspaceStorage: (workspaceDir) => ({ workspaceDir }),
+ createMakerSdk,
+ }),
+ /failed/,
+ what
+ );
+ assert.ok(tempWorkspace, `${what}: precondition`);
+ assert.ok(!fs.existsSync(tempWorkspace), `${what}: temp workspace must not be stranded`);
+ }
+});
+
+test('writes the deployed baseline to the folder workspace with the same content as the previous path', async () => {
+ const outDir = tmp('download-baseline-');
+ const emitResults = [];
+ const spec = minimalSpec();
+ await main(fakeMainDeps({
+ outDir,
+ emitResults,
+ runDownloadImpl: async () => ({
+ ok: true,
+ spec,
+ pages: [],
+ entities: [],
+ webResources: [],
+ droppedSubareas: 0,
+ droppedSubareaDetails: [],
+ dashboardWarnings: [],
+ }),
+ }));
+
+ const actual = fs.readFileSync(path.join(outDir, '.maker-workspace', 'last-applied.json'), 'utf8');
+ const controlWorkspace = tmp('download-baseline-control-');
+ writeBaseline(controlWorkspace, spec, {
+ appDir: outDir,
+ environment: ENV,
+ appUniqueName: APP_UNIQUE,
+ fromSpec: true,
+ });
+ const expected = fs.readFileSync(path.join(controlWorkspace, 'last-applied.json'), 'utf8');
+ assert.strictEqual(actual, expected);
+ assert.deepStrictEqual(emitResults.map((r) => r.ok), [true]);
+});
+
+test('leaves the folder workspace untouched except for last-applied.json when it already exists', async () => {
+ const outDir = tmp('download-existing-workspace-');
+ const workspace = path.join(outDir, '.maker-workspace');
+ fs.mkdirSync(workspace, { recursive: true });
+ fs.writeFileSync(path.join(workspace, 'keep.txt'), 'keep');
+ const before = listRelativeFiles(workspace);
+
+ await main(fakeMainDeps({ outDir, emitResults: [] }));
+
+ assert.deepStrictEqual(listRelativeFiles(workspace), [...before, 'last-applied.json'].sort());
+ assert.ok(!fs.existsSync(path.join(workspace, 'manifest.json')), 'download must not create an SDK manifest in the folder workspace');
+ assert.ok(!fs.existsSync(path.join(workspace, '.metadata')), 'download must not create SDK metadata in the folder workspace');
+});
+
+test('creates only last-applied.json in the folder workspace when no folder workspace existed', async () => {
+ const outDir = tmp('download-no-workspace-');
+ await main(fakeMainDeps({ outDir, emitResults: [] }));
+ assert.deepStrictEqual(listRelativeFiles(path.join(outDir, '.maker-workspace')), ['last-applied.json']);
+});
+
+test('main wires the real download SDK factory to a throwaway workspace and still writes only the baseline to the folder workspace', async () => {
+ const outDir = tmp('download-main-real-factory-');
+ const emitResults = [];
+ const constructed = [];
+ await main({
+ argv: ['--env', ENV, '--app', APP_UNIQUE, '--out', outDir],
+ stderr: { write: () => {} },
+ emitResult: (ok, payload) => emitResults.push({ ok, payload }),
+ preflightAuth: async () => ({ ok: true }),
+ createHttpClient: () => ({}),
+ createNodeWorkspaceStorage: (workspaceDir) => {
+ constructed.push(workspaceDir);
+ return { workspaceDir };
+ },
+ createMakerSdk: ({ workspaceStorage }) => ({
+ initWorkspace: async () => {
+ fs.mkdirSync(workspaceStorage.workspaceDir, { recursive: true });
+ fs.writeFileSync(path.join(workspaceStorage.workspaceDir, 'manifest.json'), '{}');
+ },
+ queryRecords: async (logical, opts = {}) => {
+ assert.strictEqual(logical, 'appmodule');
+ const filter = opts.filter || '';
+ if (/uniquename eq/.test(filter)) return [{ appmoduleid: APP_ID }];
+ if (/appmoduleid eq/.test(filter)) return [{ uniquename: APP_UNIQUE }];
+ return [];
+ },
+ }),
+ makeGenpageCli: () => ({}),
+ runDownload: async () => ({
+ ok: true,
+ spec: minimalSpec(),
+ pages: [],
+ entities: [],
+ webResources: [],
+ droppedSubareas: 0,
+ droppedSubareaDetails: [],
+ dashboardWarnings: [],
+ }),
+ validateAppSpec: () => ({ ok: true, warnings: [] }),
+ });
+
+ assert.strictEqual(emitResults[0].ok, true);
+ assert.strictEqual(constructed.length, 1);
+ assert.notStrictEqual(constructed[0], path.join(outDir, '.maker-workspace'));
+ assert.ok(!constructed[0].startsWith(outDir), `download factory used output folder: ${constructed[0]}`);
+ assert.ok(!fs.existsSync(constructed[0]), 'main cleans the real factory temp workspace');
+ assert.deepStrictEqual(listRelativeFiles(path.join(outDir, '.maker-workspace')), ['last-applied.json']);
+});
+
+function realBundleHttp(state) {
+ const appRow = () => ({
+ appmoduleid: APP_ID,
+ appmoduleidunique: APP_UNIQUE_ID,
+ name: 'Workspace Probe',
+ uniquename: APP_UNIQUE,
+ description: state.description,
+ componentstate: 0,
+ '@odata.etag': state.etag,
+ });
+ const sitemapRow = () => ({
+ sitemapid: SITEMAP_ID,
+ sitemapnameunique: APP_UNIQUE,
+ sitemapxml: '<SiteMap><Area><Group><SubArea Entity="new_ticket" /></Group></Area></SiteMap>',
+ '@odata.etag': state.etag,
+ });
+ return {
+ get: async (url) => {
+ const meta = /EntityDefinitions\(LogicalName='([^']+)'\)/.exec(url);
+ if (meta) return { status: 200, headers: {}, body: { LogicalName: meta[1], MetadataId: TABLE_METADATA_ID, EntitySetName: `${meta[1]}s` } };
+ if (/\/appmodulecomponents/.test(url)) {
+ const wantsSitemap = /componenttype(%20| )eq(%20| )62/.test(url);
+ return { status: 200, headers: {}, body: { value: wantsSitemap ? [{ objectid: SITEMAP_ID, componenttype: 62 }] : [{ objectid: TABLE_METADATA_ID, componenttype: 1 }] } };
+ }
+ if (/\/sitemaps/.test(url)) {
+ const multi = /RetrieveUnpublishedMultiple/i.test(url) || /\/sitemaps\?/.test(url);
+ return { status: 200, headers: { etag: state.etag }, body: multi ? { value: [sitemapRow()] } : sitemapRow() };
+ }
+ if (/\/appmodules/.test(url)) {
+ const multi = /RetrieveUnpublishedMultiple/i.test(url) || /\/appmodules\?/.test(url);
+ return { status: 200, headers: { etag: state.etag }, body: multi ? { value: [appRow()] } : appRow() };
+ }
+ return { status: 200, headers: {}, body: { value: [] } };
+ },
+ post: async () => ({ status: 204, headers: {}, body: {} }),
+ patch: async () => ({ status: 204, headers: { etag: state.etag }, body: {} }),
+ delete: async () => ({ status: 204, headers: {}, body: {} }),
+ put: async () => ({ status: 204, headers: {}, body: {} }),
+ };
+}
+
+async function realSdk(workspaceDir, state) {
+ const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
+ const sdk = createMakerSdk({
+ workspaceStorage: createNodeWorkspaceStorage(workspaceDir),
+ instanceUrl: ENV,
+ httpClient: realBundleHttp(state),
+ });
+ await sdk.initWorkspace();
+ return sdk;
+}
+
+test('REAL BUNDLE: moved server makes the old folder workspace throw, while the isolated download reads deployed content', async () => {
+ const outDir = tmp('download-real-moved-');
+ const workspace = path.join(outDir, '.maker-workspace');
+ const state = { etag: 'W/"1"', description: 'Server description v1' };
+ const oldSdk = await realSdk(workspace, state);
+ await oldSdk.fetchArtifact('app', APP_ID);
+ await oldSdk.updateElement('app', APP_ID, '/description', 'Local unpushed edit');
+ Object.assign(state, { etag: 'W/"2"', description: 'Server description v2' });
+
+ await assert.rejects(oldSdk.fetchArtifact('app', APP_ID), (err) => err && err.code === 'LOCAL_EDITS_WOULD_BE_LOST');
+
+ const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
+ const isolated = await makeDownloadSdk(ENV, {
+ createMakerSdk,
+ createNodeWorkspaceStorage,
+ createHttpClient: () => realBundleHttp(state),
+ });
+ try {
+ const deployed = await isolated.sdk.fetchArtifact('app', APP_ID);
+ assert.strictEqual(deployed.description, 'Server description v2');
+ assert.ok(!isolated.workspaceDir.startsWith(outDir), 'download workspace must be outside the output folder');
+ } finally {
+ isolated.cleanup();
+ }
+ assert.ok(!fs.existsSync(isolated.workspaceDir), 'real-bundle isolated workspace is removed');
+});
+
+test('REAL BUNDLE: unchanged server makes the old folder workspace return local edits, while the isolated download reads deployed content', async () => {
+ const outDir = tmp('download-real-clean-');
+ const workspace = path.join(outDir, '.maker-workspace');
+ const state = { etag: 'W/"1"', description: 'Server description' };
+ const oldSdk = await realSdk(workspace, state);
+ await oldSdk.fetchArtifact('app', APP_ID);
+ await oldSdk.updateElement('app', APP_ID, '/description', 'Local unpushed edit');
+
+ const oldPath = await oldSdk.fetchArtifact('app', APP_ID);
+ assert.strictEqual(oldPath.description, 'Local unpushed edit', 'old download path would silently read the unpushed local copy');
+
+ const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
+ const isolated = await makeDownloadSdk(ENV, {
+ createMakerSdk,
+ createNodeWorkspaceStorage,
+ createHttpClient: () => realBundleHttp(state),
+ });
+ try {
+ const deployed = await isolated.sdk.fetchArtifact('app', APP_ID);
+ assert.strictEqual(deployed.description, 'Server description');
+ } finally {
+ isolated.cleanup();
+ }
+ assert.ok(!fs.existsSync(isolated.workspaceDir), 'real-bundle isolated workspace is removed');
+});
diff --git a/plugins/model-apps/scripts/tests/entity-provision.test.js b/plugins/model-apps/scripts/tests/entity-provision.test.js
index 1588777dd..a0f920908 100644
--- a/plugins/model-apps/scripts/tests/entity-provision.test.js
+++ b/plugins/model-apps/scripts/tests/entity-provision.test.js
@@ -1016,7 +1016,7 @@ test('requireSuccessfulPush distinguishes an already-exists collision from a ver
(e) => {
assert.strictEqual(e.name, 'BuildHalt');
assert.strictEqual(e.code, 'already-exists');
- assert.match(e.message, /delete the \.maker-workspace directory/, 'the halt must name the step that clears it');
+ assert.match(e.message, /To reset it, stop any other build or teardown using the \.maker-workspace directory \(or the --workspace one\), then delete everything in it except last-applied\.json and destructive-approval\.json, and re-run the build to adopt the existing row\./, 'the halt must name the step that clears it, keeping the baseline and the approval record');
assert.match(e.message, /halts here again/, 'and say why a plain re-run does not');
assert.doesNotMatch(e.message, /re-download the app/);
assert.doesNotMatch(e.message, /adopt it \(fetchArtifact\)/, 'a plain fetch adopts nothing here — it must not be prescribed');
diff --git a/plugins/model-apps/scripts/tests/form-order-build.test.js b/plugins/model-apps/scripts/tests/form-order-build.test.js
new file mode 100644
index 000000000..ed30b99e3
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/form-order-build.test.js
@@ -0,0 +1,615 @@
+'use strict';
+// AB#6736948 — the build sets each table's Main Form Set order (lib/form-order.js).
+//
+// What a table opens with is decided by the ORDER of its Main forms (each form's formxml
+// `<DisplayConditions Order="n">`), not by `systemform.isdefault`: measured live, moving `isdefault` did
+// not reorder the forms a user is served, and three new forms at EQUAL Order (every new form carries
+// Order 0) were served with the `isdefault` form LAST. So a build that only promoted `isdefault` left a
+// table with three new Main forms opening with an alternate one. These tests drive the forms phase against a
+// small model of the environment's forms and pin, per scenario, which forms get which Order, which are
+// never touched, and what the build says when it cannot make its choice stick.
+const test = require('node:test');
+const assert = require('node:assert');
+
+const { runSdkBuild, planFor } = require('../lib/sdk-build.js');
+const { makeSimpleMockSdk } = require('./helpers/mock-sdk.js');
+
+const FORM_TYPE = { Main: 2, QuickCreate: 7, QuickView: 6 };
+const T = 'new_workitem';
+// The bug's own forms: a standard form, an alternate persona form and a reduced summary form.
+const STD = 'Work Item';
+const ALT = 'My Work \u2014 Work Item';
+const SUM = 'Work Item \u2014 Summary';
+
+function specFor({ existing = false, forms, mainFormOrder, personas } = {}) {
+ return {
+ solution: { uniqueName: 'FO', displayName: 'FO', publisherPrefix: 'new' },
+ app: { name: 'FO App', description: 'd' },
+ entities: [{
+ schemaName: T, displayName: 'Work Item', pluralName: 'Work Items',
+ primaryAttribute: { schemaName: 'new_name', displayName: 'Name' },
+ columns: [{ schemaName: 'new_notes', displayName: 'Notes', type: 'Memo' }],
+ ...(existing ? { existing: true } : {}),
+ ...(mainFormOrder ? { mainFormOrder } : {}),
+ }],
+ forms: forms || [
+ { entity: T, name: STD, formType: 'Main' },
+ { entity: T, name: ALT, formType: 'Main' },
+ { entity: T, name: SUM, formType: 'Main' },
+ ],
+ ...(personas ? { personas } : {}),
+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'W', subAreas: [{ entity: T, title: 'Work Items' }] }] }] },
+ };
+}
+
+// A model of the environment's forms, answering exactly the reads and writes the forms phase makes.
+// `seed` lists forms that already exist: { id, name, entity?, type?, active?, isdefault?, dc? } where `dc`
+// is the form's <DisplayConditions> ({ everyone | roleIds, fallbackForm, order }) or undefined for none.
+// A form the build creates behaves as the SDK's does: its local copy carries the <DisplayConditions> the
+// SDK gives every new form (Order 0, offered to everyone) in its root bag, and it exists on the server —
+// with whatever that copy says — only once it is pushed.
+function makeEnv(seed = [], failures = {}, options = {}) {
+ const { sdk } = makeSimpleMockSdk();
+ const provision = Object.create(sdk);
+ const forms = new Map();
+ const log = [];
+ const add = (f) => forms.set(f.id, { entity: T, type: 2, active: true, isdefault: false, ...f, dc: f.dc ? { ...f.dc } : undefined });
+ seed.forEach(add);
+ const byName = (name) => [...forms.values()].find((f) => f.name === name);
+ const unpushed = new Map(); // local id -> what the server will record when it is pushed
+ provision.createArtifact = async (t, def) => {
+ const art = await sdk.createArtifact(t, def);
+ if (t === 'form') {
+ const local = await sdk.getArtifact('form', art.id);
+ if (!options.noDisplayConditions) {
+ local.bag.c.push({ i: 3, node: { n: 'DisplayConditions', a: [['Order', '0'], ['FallbackForm', 'true']], c: [{ n: 'Everyone', a: [], c: [] }] } });
+ }
+ unpushed.set(art.id, { entity: def.entityLogicalName, name: def.name, type: FORM_TYPE[def.formType || 'Main'] });
+ }
+ return art;
+ };
+ provision.pushArtifact = async (t, id) => {
+ const out = await sdk.pushArtifact(t, id);
+ if (t === 'form' && unpushed.has(id)) {
+ const meta = unpushed.get(id);
+ unpushed.delete(id);
+ const local = await sdk.getArtifact('form', id);
+ const node = (local.bag.c.find((e) => e && e.node && e.node.n === 'DisplayConditions') || {}).node;
+ const order = node ? Number((node.a.find(([n]) => n === 'Order') || [])[1]) : undefined;
+ add({ id, ...meta, dc: node ? { everyone: true, fallbackForm: true, order } : undefined });
+ log.push(['created', meta.name, order]);
+ }
+ return out;
+ };
+ provision.queryRecords = async (entity, o = {}) => {
+ if (entity === 'solution') return [];
+ if (entity !== 'systemform') return [{ publisherid: 'pub-1' }];
+ const filter = String(o.filter || '');
+ const byId = /^formid eq (\S+)$/.exec(filter);
+ if (byId) {
+ const f = forms.get(byId[1]);
+ return f ? [{ formid: f.id, isdefault: f.isdefault, objecttypecode: f.entity, type: f.type, name: f.name, formactivationstate: f.active ? 1 : 0 }] : [];
+ }
+ const ent = /objecttypecode eq '([^']+)'/.exec(filter);
+ if (!ent) return [];
+ const name = / name eq '((?:[^']|'')*)'/.exec(filter);
+ const type = / type eq (\d+)/.exec(filter);
+ const activeOnly = / formactivationstate eq 1/.test(filter);
+ return [...forms.values()]
+ .filter((f) => f.entity === ent[1]
+ && (!name || f.name === name[1].replace(/''/g, "'"))
+ && (!type || f.type === Number(type[1]))
+ && (!activeOnly || f.active))
+ .map((f) => ({ formid: f.id, name: f.name, formactivationstate: f.active ? 1 : 0, isdefault: f.isdefault }));
+ };
+ provision.updateRecord = async (entity, id, patch) => {
+ const f = entity === 'systemform' && forms.get(id);
+ if (!f) return;
+ if (patch.isdefault !== undefined) { f.isdefault = patch.isdefault; log.push(['isdefault', f.name, patch.isdefault]); }
+ if (patch.formactivationstate !== undefined) { f.active = patch.formactivationstate === 1; log.push(['activation', f.name, patch.formactivationstate]); }
+ };
+ provision.getFormSecurityRoles = async (id) => {
+ if (failures.failRead && (!failures.readOnly || failures.readOnly(id))) throw new Error(failures.failRead);
+ const f = forms.get(id);
+ if (!f) throw new Error(`no form ${id}`);
+ return f.dc ? { ...f.dc } : undefined;
+ };
+ // The SDK's contract (vendored FormApi): roles/everyone REPLACE the element; order/fallbackForm alone
+ // re-attach the existing one and change only those attributes — and are refused when there is none.
+ provision.setFormSecurityRoles = async (id, opts) => {
+ const f = forms.get(id);
+ if (!f) throw new Error(`no form ${id}`);
+ log.push(['set', f.name, opts]);
+ if (failures.failWrite) throw new Error(failures.failWrite);
+ const wantsElement = opts.everyone || (opts.roleIds && opts.roleIds.length > 0);
+ if (!wantsElement) {
+ if (!f.dc) throw new Error('`order`/`fallbackForm` were supplied without `roleIds` or `everyone`, but this form has no <DisplayConditions> to attach them to');
+ if (opts.order !== undefined) f.dc.order = opts.order;
+ if (opts.fallbackForm !== undefined) f.dc.fallbackForm = opts.fallbackForm;
+ return;
+ }
+ const prior = f.dc || {};
+ f.dc = {
+ ...(opts.everyone ? { everyone: true } : { roleIds: [...opts.roleIds] }),
+ fallbackForm: opts.fallbackForm !== undefined ? opts.fallbackForm : (prior.fallbackForm !== undefined ? prior.fallbackForm : false),
+ ...(opts.order !== undefined ? { order: opts.order } : (prior.order !== undefined ? { order: prior.order } : {})),
+ };
+ };
+ provision.addSolutionComponent = async () => undefined;
+ const order = (name) => { const f = byName(name); return f && f.dc ? f.dc.order : undefined; };
+ const writes = () => log.filter((l) => l[0] === 'set').map(([, name, opts]) => [name, opts]);
+ // The order each new form was CREATED with, in creation order: [name, order].
+ const created = () => log.filter((l) => l[0] === 'created').map(([, name, order]) => [name, order]);
+ return { provision, forms, log, byName, order, writes, created, failures };
+}
+
+async function build(spec, env, { phases = ['forms'], extraProvision, workspaceDir } = {}) {
+ const { sdk } = makeSimpleMockSdk();
+ if (extraProvision) Object.assign(env.provision, extraProvision);
+ const events = [];
+ const warnings = [];
+ const res = await runSdkBuild(spec, {
+ sdk, provisionSdk: env.provision, apply: true, phases, ...(workspaceDir ? { workspaceDir } : {}),
+ emit: (e) => events.push(e), warn: (m) => warnings.push(String(m)),
+ });
+ const step = (re) => events.filter((e) => e.phase === 'forms' && e.status !== 'start' && re.test(e.label));
+ return { res, events, warnings, step };
+}
+
+// --- a table the spec owns (created by this build) ---------------------------------------------------
+
+test('own table, three new Main forms, no choice made: the first in spec order is put first (0), the others follow in spec order', async () => {
+ const env = makeEnv();
+ const { res, step, warnings } = await build(specFor(), env);
+ assert.strictEqual(res.ok, true);
+ assert.deepStrictEqual([env.order(STD), env.order(ALT), env.order(SUM)], [0, 1, 2]);
+ // Every new form arrives with Order 0, so the first is already in place: only the others are written.
+ assert.deepStrictEqual(env.writes(), [[ALT, { order: 1 }], [SUM, { order: 2 }]]);
+ assert.deepStrictEqual(env.created(), [[STD, 0], [ALT, 0], [SUM, 0]], 'a table the spec orders is ordered after the creates, not in them');
+ assert.strictEqual(env.byName(STD).isdefault, true, 'the same form is still promoted to isdefault');
+ const [s] = step(/^form order for new_workitem/);
+ assert.strictEqual(s.status, 'ok');
+ assert.strictEqual(s.label, "form order for new_workitem: 'Work Item', then 2 more");
+ assert.deepStrictEqual(warnings.filter((w) => /form order/.test(w)), []);
+});
+
+test('own table, isDefault on the summary form: it comes first, and the others keep spec order after it', async () => {
+ const spec = specFor();
+ spec.forms[2].isDefault = true;
+ const env = makeEnv();
+ await build(spec, env);
+ assert.deepStrictEqual([env.order(SUM), env.order(STD), env.order(ALT)], [0, 1, 2]);
+ assert.strictEqual(env.byName(SUM).isdefault, true);
+ assert.strictEqual(env.byName(STD).isdefault, false);
+});
+
+test('own table, entities[].mainFormOrder (partial): the listed forms first in list order, then the rest', async () => {
+ const env = makeEnv();
+ const { step } = await build(specFor({ mainFormOrder: [SUM, ALT] }), env);
+ assert.deepStrictEqual([env.order(SUM), env.order(ALT), env.order(STD)], [0, 1, 2]);
+ assert.strictEqual(env.byName(SUM).isdefault, true, 'the first listed form is the default too');
+ assert.strictEqual(step(/^form order for/)[0].label, `form order for new_workitem: '${SUM}' > '${ALT}', then 1 more`);
+});
+
+test('a rebuild with everything already in place writes nothing (idempotent)', async () => {
+ const env = makeEnv([
+ { id: 'a', name: STD, dc: { everyone: true, fallbackForm: true, order: 0 } },
+ { id: 'b', name: ALT, dc: { everyone: true, fallbackForm: true, order: 1 } },
+ { id: 'c', name: SUM, dc: { everyone: true, fallbackForm: true, order: 2 } },
+ ]);
+ const { step } = await build(specFor(), env);
+ assert.deepStrictEqual(env.writes(), []);
+ assert.strictEqual(step(/^form order for/)[0].status, 'ok');
+});
+
+test('own table rebuilt after a maker reordered the NON-default forms: their order is kept, only the default is put back first', async () => {
+ // In Maker: My Work first, then the default Work Item, then Summary moved above My Work... i.e. the
+ // stored order is SUM 0, ALT 1, STD 2. The spec says nothing about ALT vs SUM, so their relative order
+ // (SUM before ALT) must survive; only STD — the default — is moved back to the front.
+ const env = makeEnv([
+ { id: 'a', name: STD, dc: { everyone: true, fallbackForm: true, order: 2 } },
+ { id: 'b', name: ALT, dc: { everyone: true, fallbackForm: true, order: 1 } },
+ { id: 'c', name: SUM, dc: { everyone: true, fallbackForm: true, order: 0 } },
+ ]);
+ await build(specFor(), env);
+ assert.deepStrictEqual([env.order(STD), env.order(SUM), env.order(ALT)], [0, 1, 2]);
+});
+
+test('a Main form with NO <DisplayConditions> gets the element a new form has (everyone, fallback) plus its order — an order alone would be refused', async () => {
+ const env = makeEnv([
+ { id: 'a', name: STD, dc: { everyone: true, fallbackForm: true, order: 0 } },
+ { id: 'b', name: ALT, dc: undefined },
+ { id: 'c', name: SUM, dc: { everyone: true, fallbackForm: true, order: 1 } },
+ ]);
+ await build(specFor(), env);
+ // Stored order before: STD 0, SUM 1, ALT none (sorts last) → STD, SUM, ALT.
+ assert.deepStrictEqual(env.writes(), [[ALT, { everyone: true, fallbackForm: true, order: 2 }]]);
+ assert.deepStrictEqual(env.byName(ALT).dc, { everyone: true, fallbackForm: true, order: 2 });
+});
+
+test('a role-restricted Main form keeps its roles and fallback setting when only its order is written', async () => {
+ const env = makeEnv([
+ { id: 'a', name: STD, dc: { everyone: true, fallbackForm: true, order: 0 } },
+ { id: 'b', name: ALT, dc: { roleIds: ['r1', 'r2'], fallbackForm: false, order: 0 } },
+ { id: 'c', name: SUM, dc: { everyone: true, fallbackForm: true, order: 0 } },
+ ]);
+ await build(specFor(), env);
+ assert.deepStrictEqual(env.byName(ALT).dc, { roleIds: ['r1', 'r2'], fallbackForm: false, order: 1 });
+ assert.deepStrictEqual(env.writes().find(([n]) => n === ALT), [ALT, { order: 1 }], 'an order-only write, never a role write');
+});
+
+test('a Main form this spec does not declare is never written, and one that is not after the first form is named in a warning', async () => {
+ const env = makeEnv([
+ { id: 'x', name: 'Legacy', dc: { everyone: true, fallbackForm: true, order: 0 } },
+ { id: 'y', name: 'Information', dc: undefined },
+ { id: 'z', name: 'Later', dc: { everyone: true, fallbackForm: true, order: 7 } },
+ ]);
+ const { warnings } = await build(specFor(), env);
+ assert.ok(!env.writes().some(([n]) => ['Legacy', 'Information', 'Later'].includes(n)), JSON.stringify(env.writes()));
+ const w = warnings.filter((m) => /which this spec does not declare/.test(m));
+ assert.strictEqual(w.length, 1, JSON.stringify(warnings));
+ assert.match(w[0], /Main form 'Legacy'.*form order 0.*not after 'Work Item' \(0\).*Form settings > Form order/);
+ assert.strictEqual(env.byName('Legacy').isdefault, false, 'nor is its default flag touched');
+});
+
+test('an unreadable undeclared form does not undo a written order: the step succeeds and says what it could not check', async () => {
+ const env = makeEnv([{ id: 'x', name: 'Managed Elsewhere', dc: { everyone: true, fallbackForm: true, order: 0 } }]);
+ const base = env.provision.getFormSecurityRoles;
+ env.provision.getFormSecurityRoles = async (id) => { if (id === 'x') throw new Error('read refused (403)'); return base(id); };
+ const { step, warnings } = await build(specFor(), env);
+ assert.strictEqual(step(/^form order for/)[0].status, 'ok');
+ assert.deepStrictEqual([env.order(STD), env.order(ALT), env.order(SUM)], [0, 1, 2]);
+ const w = warnings.find((m) => /could not read its other Main forms/.test(m));
+ assert.ok(w, JSON.stringify(warnings));
+ assert.match(w, /read refused \(403\).*--verify/);
+});
+
+test('an inactive undeclared Main form is not warned about: it is never served', async () => {
+ const env = makeEnv([{ id: 'x', name: 'Retired', active: false, dc: { everyone: true, fallbackForm: true, order: 0 } }]);
+ const { warnings } = await build(specFor(), env);
+ assert.deepStrictEqual(warnings.filter((m) => /does not declare/.test(m)), []);
+});
+
+test('QuickCreate and QuickView forms are never ordered, and do not count as Main forms', async () => {
+ const spec = specFor({
+ forms: [
+ { entity: T, name: STD, formType: 'Main' },
+ { entity: T, name: 'Quick', formType: 'QuickCreate' },
+ { entity: T, name: 'Card', formType: 'QuickView' },
+ { entity: T, name: ALT, formType: 'Main' },
+ ],
+ });
+ const env = makeEnv();
+ const { step } = await build(spec, env);
+ assert.deepStrictEqual(env.writes(), [[ALT, { order: 1 }]]);
+ assert.strictEqual(step(/^form order for/).length, 1);
+ assert.strictEqual(step(/^form order for/)[0].label, "form order for new_workitem: 'Work Item', then 1 more");
+});
+
+test('two tables are ordered independently', async () => {
+ const spec = specFor();
+ spec.entities.push({ schemaName: 'new_task', displayName: 'Task', pluralName: 'Tasks', primaryAttribute: { schemaName: 'new_name', displayName: 'Name' } });
+ spec.forms.push({ entity: 'new_task', name: 'Task', formType: 'Main' }, { entity: 'new_task', name: 'Task Board', formType: 'Main', isDefault: true });
+ const env = makeEnv();
+ const { step } = await build(spec, env);
+ assert.deepStrictEqual([env.order(STD), env.order(ALT), env.order(SUM)], [0, 1, 2]);
+ assert.deepStrictEqual([env.order('Task Board'), env.order('Task')], [0, 1]);
+ assert.strictEqual(step(/^form order for/).length, 2);
+});
+
+test('the order is written AFTER every form exists and after the default is promoted', async () => {
+ const env = makeEnv();
+ await build(specFor(), env);
+ const promoted = env.log.findIndex((l) => l[0] === 'isdefault' && l[2] === true);
+ const firstWrite = env.log.findIndex((l) => l[0] === 'set');
+ assert.ok(promoted >= 0 && firstWrite > promoted, JSON.stringify(env.log));
+ assert.strictEqual(env.forms.size, 3, 'all three forms existed before any order was written');
+});
+
+// --- an EXISTING table (the bug: authoring the order of a table the spec did not create) -------------
+
+function existingTable(orders = { std: 0, alt: 1, sum: 2 }, extra = []) {
+ return makeEnv([
+ { id: 'e1', name: STD, isdefault: true, dc: { everyone: true, fallbackForm: true, order: orders.std } },
+ { id: 'e2', name: ALT, dc: { everyone: true, fallbackForm: true, order: orders.alt } },
+ { id: 'e3', name: SUM, dc: { everyone: true, fallbackForm: true, order: orders.sum } },
+ ...extra,
+ ]);
+}
+
+test('existing table, standard + alternate persona + summary forms, NO choice in the spec: nothing is reordered or promoted', async () => {
+ const env = existingTable({ std: 1, alt: 0, sum: 2 });
+ env.byName(STD).isdefault = false;
+ env.byName(ALT).isdefault = true;
+ const { step, warnings } = await build(specFor({ existing: true }), env);
+ assert.deepStrictEqual(env.writes(), []);
+ assert.deepStrictEqual(env.log.filter((l) => l[0] === 'isdefault'), [], 'the default of a table the spec does not own is not re-pointed implicitly');
+ assert.deepStrictEqual(step(/^form order for/).map((e) => [e.status, e.label]), [['skip', 'form order for new_workitem (no new Main form — its order is left as it is)']]);
+ assert.deepStrictEqual(warnings.filter((w) => /form order/.test(w)), []);
+});
+
+test('existing table, explicit isDefault on the standard form: promoted AND put first; the others keep their stored relative order', async () => {
+ // Regression for AB#6736948: an isDefault on an existing table used to be dropped without a word.
+ const env = existingTable({ std: 2, alt: 0, sum: 1 });
+ env.byName(STD).isdefault = false;
+ env.byName(ALT).isdefault = true;
+ const spec = specFor({ existing: true });
+ spec.forms[0].isDefault = true;
+ const { res } = await build(spec, env);
+ assert.deepStrictEqual([env.order(STD), env.order(ALT), env.order(SUM)], [0, 1, 2]);
+ assert.strictEqual(env.byName(STD).isdefault, true);
+ assert.strictEqual(env.byName(ALT).isdefault, false, 'the declared sibling that held the default is cleared');
+ assert.strictEqual(res.created.defaultForms[T], 'e1');
+});
+
+test('existing table, entities[].mainFormOrder: exactly the declared order, on forms the build reconciled (not created)', async () => {
+ const env = existingTable({ std: 0, alt: 1, sum: 2 });
+ await build(specFor({ existing: true, mainFormOrder: [SUM, STD, ALT] }), env);
+ assert.deepStrictEqual([env.order(SUM), env.order(STD), env.order(ALT)], [0, 1, 2]);
+ assert.strictEqual(env.byName(SUM).isdefault, true);
+ assert.strictEqual(env.byName(STD).isdefault, false);
+});
+
+test('existing table, deactivateOtherMainForms on the explicit default is NOT applied: deactivation stays limited to a table the build owns', async () => {
+ const env = existingTable({ std: 0, alt: 1, sum: 2 }, [{ id: 'u1', name: 'Information', dc: undefined }]);
+ const spec = specFor({ existing: true, forms: [{ entity: T, name: STD, formType: 'Main', isDefault: true, deactivateOtherMainForms: true }] });
+ await build(spec, env);
+ assert.deepStrictEqual(env.log.filter((l) => l[0] === 'activation'), []);
+ assert.strictEqual(env.byName('Information').active, true);
+});
+
+test('existing table, a NEW alternate form and no choice: it is put after the table\u2019s other Main forms, which are not touched', async () => {
+ // AC 2: adding an alternate form must not change what the table opens with. A new form carries Order 0,
+ // which would tie with the form everyone opens today — and the platform, not the build, orders a tie.
+ const env = makeEnv([
+ { id: 'e1', name: STD, isdefault: true, dc: { everyone: true, fallbackForm: true, order: 0 } },
+ { id: 'e3', name: SUM, dc: { everyone: true, fallbackForm: true, order: 3 } },
+ { id: 'u1', name: 'Information', dc: undefined },
+ ]);
+ const { step, warnings } = await build(specFor({ existing: true }), env);
+ // Highest other order (3) + 1 + its index among the spec's Main forms (1): created at 5, in ONE write —
+ // the create — never at the Order 0 every new form starts with.
+ assert.deepStrictEqual(env.created(), [[ALT, 5]]);
+ assert.deepStrictEqual(env.writes(), [], 'no separate order write');
+ assert.strictEqual(env.order(STD), 0);
+ assert.strictEqual(env.order(SUM), 3);
+ assert.strictEqual(env.byName('Information').dc, undefined);
+ assert.deepStrictEqual(env.log.filter((l) => l[0] === 'isdefault'), []);
+ assert.deepStrictEqual(step(/^form order for/).map((e) => [e.status, e.label]), [['ok', `form order for new_workitem ('${ALT}' after its other Main forms)`]]);
+ // …but ahead of 'Information', which has no order and so is served after every form that has one.
+ assert.deepStrictEqual(warnings.filter((w) => /form order/.test(w)).map((w) => /before 'Information', which has no form order/.test(w)), [true]);
+});
+
+test('existing table, two new forms: both are created after the others, in spec order, from ONE read of the others', async () => {
+ const env = makeEnv([{ id: 'e1', name: STD, dc: { everyone: true, fallbackForm: true, order: 5 } }]);
+ let reads = 0;
+ const query = env.provision.queryRecords;
+ env.provision.queryRecords = async (set, o) => { if (set === 'systemform' && /formactivationstate eq 1/.test(String(o && o.filter))) reads += 1; return query(set, o); };
+ await build(specFor({ existing: true }), env);
+ // 5 + 1 + index (1, 2). Created concurrently, yet neither new form is among the "others" the other read.
+ assert.deepStrictEqual(env.created().sort(), [[ALT, 7], [SUM, 8]]);
+ assert.deepStrictEqual(env.writes(), []);
+ assert.strictEqual(reads, 1, 'the table\u2019s other forms are read once');
+});
+
+test('existing table whose other Main forms carry no order: the new form cannot be put after them, so the build says it now comes first', async () => {
+ const env = makeEnv([{ id: 'u1', name: 'Information', dc: undefined }, { id: 'e1', name: STD, dc: undefined }]);
+ const spec = specFor({ existing: true, forms: [{ entity: T, name: STD, formType: 'Main' }, { entity: T, name: ALT, formType: 'Main' }] });
+ const { warnings, step } = await build(spec, env);
+ assert.deepStrictEqual(env.writes(), []);
+ assert.deepStrictEqual(env.created(), [[ALT, 1]], 'no other form has an order to follow: -1 + 1 + its index');
+ const w = warnings.find((m) => /none of its other Main forms has a form order/.test(m));
+ assert.ok(w, JSON.stringify(warnings));
+ assert.match(w, new RegExp(`'${ALT}' now comes first .*forms\\[\\]\\.isDefault or entities\\[\\]\\.mainFormOrder`));
+ assert.strictEqual(step(/^form order for/)[0].status, 'ok');
+});
+
+// --- tables ordered by hand, and what cannot be done -----------------------------------------------------
+
+test('a table ordered by hand (securityRoles.order) gets no order step at all, and the security phase still writes its order', async () => {
+ const spec = specFor({
+ personas: [{ persona: 'Dispatcher', jobs: [{ name: 'Assign', privileges: [{ entity: T, access: ['read'] }] }] }],
+ });
+ spec.forms[1].securityRoles = { everyone: true, order: 5 };
+ const env = makeEnv();
+ const { step } = await build(spec, env, {
+ phases: ['forms', 'security'],
+ extraProvision: { createPersonaRole: async () => ({ roleId: 'dddddddd-dddd-dddd-dddd-dddddddddddd', reused: false, appliedPrivileges: [], assignedTeams: [], assignedUsers: [] }) },
+ });
+ assert.deepStrictEqual(step(/^form order for/), []);
+ assert.deepStrictEqual(env.writes(), [[ALT, { everyone: true, order: 5 }]], 'only the author\u2019s own securityRoles write');
+ assert.deepStrictEqual(planFor(spec, { phases: ['forms'] }).filter((p) => /form order/.test(p.label)), []);
+});
+
+test('securityRoles WITHOUT an order keeps the position the forms phase gave the form', async () => {
+ const spec = specFor({
+ personas: [{ persona: 'Dispatcher', jobs: [{ name: 'Assign', privileges: [{ entity: T, access: ['read'] }] }] }],
+ });
+ spec.forms[1].securityRoles = { personas: ['Dispatcher'] };
+ const env = makeEnv();
+ await build(spec, env, {
+ phases: ['forms', 'security'],
+ extraProvision: { createPersonaRole: async () => ({ roleId: 'dddddddd-dddd-dddd-dddd-dddddddddddd', reused: false, appliedPrivileges: [], assignedTeams: [], assignedUsers: [] }) },
+ });
+ assert.deepStrictEqual(env.byName(ALT).dc, { roleIds: ['dddddddd-dddd-dddd-dddd-dddddddddddd'], fallbackForm: true, order: 1 });
+});
+
+test('a declared Main form the forms phase produced no id for: the table is not ordered, and the step names the form', async () => {
+ // The guard behind this skip: ordering the other forms without that one would leave it at Order 0,
+ // tied with the first — so the order the step reports would not be the order users are served.
+ const env = makeEnv();
+ const basePush = env.provision.pushArtifact;
+ env.provision.pushArtifact = async (t, id) => {
+ const out = await basePush(t, id);
+ const f = env.forms.get(id);
+ return t === 'form' && f && f.name === SUM ? { ...out, id: undefined } : out;
+ };
+ const { step } = await build(specFor(), env);
+ assert.deepStrictEqual(step(/^form order for/).map((e) => [e.status, e.label]), [['skip', `form order for new_workitem ('${SUM}' not built in this run)`]]);
+ assert.deepStrictEqual(env.writes(), []);
+});
+
+test('a failed form create still halts the build, before any order is written', async () => {
+ const env = makeEnv();
+ const base = env.provision.createArtifact;
+ env.provision.createArtifact = (t, def) => {
+ if (t === 'form' && def.name === SUM) throw new Error('create refused');
+ return base(t, def);
+ };
+ await assert.rejects(runSdkBuild(specFor(), {
+ sdk: makeSimpleMockSdk().sdk, provisionSdk: env.provision, apply: true, phases: ['forms'],
+ emit: () => {}, warn: () => {},
+ }), /create refused/);
+ assert.deepStrictEqual(env.writes(), []);
+});
+
+test('an SDK without the form-order calls: the step is skipped with the reason, and nothing breaks', async () => {
+ const env = makeEnv();
+ env.provision.getFormSecurityRoles = undefined;
+ const { res, step } = await build(specFor(), env);
+ assert.strictEqual(res.ok, true);
+ assert.deepStrictEqual(step(/^form order for/).map((e) => [e.status, e.label]), [['skip', "form order for new_workitem (this SDK cannot read or write a form's order)"]]);
+});
+
+test('a failed order READ is reported (✗ + warning) and the build goes on — it never halts', async () => {
+ const env = makeEnv([], { failRead: 'read refused (403)' });
+ const { res, step, warnings } = await build(specFor(), env);
+ assert.strictEqual(step(/^form order for/)[0].status, 'error');
+ assert.ok(warnings.some((w) => /could not set the Main Form Set order of 'new_workitem': read refused \(403\)/.test(w)), JSON.stringify(warnings));
+ assert.ok(res.created.formIds[`${T}|Main|${SUM}`], 'the forms themselves are built');
+});
+
+test('a failed order WRITE is reported and the build goes on', async () => {
+ const env = makeEnv([], { failWrite: 'write refused (429)' });
+ const { step, warnings } = await build(specFor(), env);
+ assert.strictEqual(step(/^form order for/)[0].status, 'error');
+ assert.ok(warnings.some((w) => /could not set the Main Form Set order of 'new_workitem': write refused \(429\)/.test(w)), JSON.stringify(warnings));
+});
+
+test('when the table\u2019s other forms cannot be read, the new form is created at the end of the order, and the build says so', async () => {
+ const env = makeEnv([{ id: 'e1', name: STD, dc: { everyone: true, fallbackForm: true, order: 0 } }], { failRead: 'read refused (403)' });
+ const { step, warnings } = await build(specFor({ existing: true }), env);
+ assert.deepStrictEqual(env.created().sort(), [[ALT, 100001], [SUM, 100002]], 'past any order Maker assigns, still in spec order');
+ assert.strictEqual(step(/^form order for/)[0].status, 'ok');
+ const w = warnings.find((m) => /could not read its other Main forms/.test(m));
+ assert.ok(w, JSON.stringify(warnings));
+ assert.match(w, /read refused \(403\).*created at the end of the form order \(order 100000 and up\)/);
+});
+
+// --- the plan ---------------------------------------------------------------------------------------------
+
+test('planFor lists one form-order step per table with Main forms, after that table\u2019s forms', () => {
+ const spec = specFor();
+ spec.entities.push({ schemaName: 'new_task', displayName: 'Task', pluralName: 'Tasks', primaryAttribute: { schemaName: 'new_name', displayName: 'Name' } });
+ spec.forms.push({ entity: 'new_task', name: 'Quick Task', formType: 'QuickCreate' });
+ const labels = planFor(spec, { phases: ['forms'] }).map((p) => p.label);
+ assert.deepStrictEqual(labels.filter((l) => /form order/.test(l)), ['form order for new_workitem'], 'a table with only a QuickCreate form has no Main Form Set');
+ assert.ok(labels.indexOf('form order for new_workitem') > labels.lastIndexOf('form for new_workitem'));
+ assert.deepStrictEqual(planFor(spec, { phases: ['views'] }).filter((p) => /form order/.test(p.label)), [], 'no step when the forms phase does not run');
+});
+
+test('the step count stays honest: every planned form-order step is emitted exactly once', async () => {
+ for (const [spec, env] of [
+ [specFor(), makeEnv()],
+ [specFor({ existing: true }), existingTable()],
+ [specFor({ existing: true }), makeEnv([{ id: 'e1', name: STD, dc: { everyone: true, fallbackForm: true, order: 0 } }])],
+ ]) {
+ const planned = planFor(spec, { phases: ['forms'] }).filter((p) => /form order/.test(p.label)).length;
+ const { step } = await build(spec, env);
+ assert.strictEqual(step(/^form order for/).length, planned);
+ }
+});
+
+// --- a new form is created in its place --------------------------------------------------------------
+//
+// On a table whose order the build does not set, a new Main form's order is part of its create. A separate
+// write after the create left the form at Order 0 — possibly ahead of the form the table opened with — on
+// any failure between the two, and a later build cannot tell the form is new, so it could never repair it.
+
+const existingWithOriginal = () => makeEnv([{ id: 'e1', name: STD, isdefault: true, dc: { everyone: true, fallbackForm: true, order: 5 } }]);
+const addAlternate = () => specFor({ existing: true, forms: [{ entity: T, name: STD, formType: 'Main' }, { entity: T, name: ALT, formType: 'Main' }] });
+
+test('a new form on an existing table is created in its place: its create carries the order', async () => {
+ const env = existingWithOriginal();
+ const pushes = [];
+ const push = env.provision.pushArtifact;
+ env.provision.pushArtifact = async (t, id) => { pushes.push([t, id]); return push(t, id); };
+ await build(addAlternate(), env);
+ assert.deepStrictEqual(env.created(), [[ALT, 7]], '5 + 1 + index 1');
+ assert.deepStrictEqual(env.writes(), []);
+ assert.strictEqual(env.order(STD), 5, 'the original is not touched');
+ const altId = env.byName(ALT).id;
+ assert.strictEqual(pushes.filter(([t, id]) => t === 'form' && id === altId).length, 1, 'one push creates it, already placed');
+});
+
+test('a build interrupted after creating one new form leaves nothing out of place, and the next build places the rest after it', async () => {
+ const env = existingWithOriginal();
+ const spec = specFor({ existing: true, forms: [{ entity: T, name: STD, formType: 'Main' }, { entity: T, name: ALT, formType: 'Main' }, { entity: T, name: SUM, formType: 'Main' }] });
+ const base = env.provision.createArtifact;
+ let refuse = true;
+ env.provision.createArtifact = async (t, def) => {
+ if (refuse && t === 'form' && def.name === SUM) { await new Promise((r) => setTimeout(r, 20)); throw new Error('interrupted'); }
+ return base(t, def);
+ };
+ await assert.rejects(build(spec, env), /interrupted/);
+ assert.strictEqual(env.order(ALT), 7, 'what was created is already after the original');
+ refuse = false;
+ await build(spec, env);
+ assert.strictEqual(env.order(ALT), 7, 'and is not moved');
+ // ALT is one of the table's others now: 7 + 1 + index 2.
+ assert.strictEqual(env.order(SUM), 10);
+ assert.ok(env.order(STD) < env.order(ALT) && env.order(ALT) < env.order(SUM));
+});
+
+test('a later new form goes after a form an earlier build created', async () => {
+ const env = makeEnv([
+ { id: 'e1', name: STD, dc: { everyone: true, fallbackForm: true, order: 5 } },
+ { id: 'e2', name: ALT, dc: { everyone: true, fallbackForm: true, order: 7 } },
+ ]);
+ // The new form is FIRST in the spec, yet the forms already on the table stay ahead of it.
+ await build(specFor({ existing: true, forms: [{ entity: T, name: SUM, formType: 'Main' }, { entity: T, name: STD, formType: 'Main' }, { entity: T, name: ALT, formType: 'Main' }] }), env);
+ assert.deepStrictEqual(env.created(), [[SUM, 8]]);
+});
+
+test('a failure placing a new form fails its create before anything is pushed', async () => {
+ const env = existingWithOriginal();
+ const update = env.provision.updateElement;
+ env.provision.updateElement = async (t, id, ptr, value) => {
+ if (t === 'form' && /^\/bag\/c\/\d+$/.test(ptr)) throw new Error('local copy refused the edit');
+ return update(t, id, ptr, value);
+ };
+ await assert.rejects(build(addAlternate(), env), /local copy refused the edit/);
+ assert.strictEqual(env.byName(ALT), undefined, 'the form was never pushed, so nothing is left at Order 0');
+});
+
+test('a new form whose SDK copy carries no <DisplayConditions> is created as the SDK makes it, and the build says so', async () => {
+ const env = makeEnv([{ id: 'e1', name: STD, dc: { everyone: true, fallbackForm: true, order: 5 } }], {}, { noDisplayConditions: true });
+ const { warnings } = await build(addAlternate(), env);
+ assert.deepStrictEqual(env.created(), [[ALT, undefined]]);
+ assert.ok(warnings.some((w) => new RegExp(`'${ALT}' was created without a form order the build could set`).test(w)), JSON.stringify(warnings));
+});
+
+test('forms on a table the spec orders, or orders by hand, are not placed in their create', async () => {
+ const own = makeEnv();
+ await build(specFor(), own);
+ assert.deepStrictEqual(own.created(), [[STD, 0], [ALT, 0], [SUM, 0]], 'the order step orders them after the creates');
+ const byHand = makeEnv([{ id: 'e1', name: STD, dc: { everyone: true, fallbackForm: true, order: 5 } }]);
+ await build(specFor({ existing: true, forms: [{ entity: T, name: STD, formType: 'Main', securityRoles: { everyone: true, order: 1 } }, { entity: T, name: ALT, formType: 'Main' }] }), byHand);
+ assert.deepStrictEqual(byHand.created(), [[ALT, 0]], 'the author orders this table');
+});
+
+// A form with no order at all is served after every form that has one. Appending the new form after the
+// ORDERED forms therefore still puts it ahead of such a form — and a user whose roles offer them no ordered
+// form, who therefore opened that one, now opens the new form. The build cannot fix that without writing a
+// form the spec does not declare, so it says so.
+test('a new form appended ahead of a form with NO order says so, naming it', async () => {
+ const env = makeEnv([
+ { id: 'r1', name: 'Dispatcher Only', dc: { roleIds: ['r'], fallbackForm: false, order: 0 } },
+ { id: 'u1', name: 'Information', dc: undefined },
+ ]);
+ const { warnings } = await build(specFor({ existing: true, forms: [{ entity: T, name: ALT, formType: 'Main' }] }), env);
+ assert.strictEqual(env.order(ALT), 1);
+ const w = warnings.find((m) => /no form order/.test(m));
+ assert.ok(w, JSON.stringify(warnings));
+ assert.match(w, new RegExp(`'${ALT}' now comes before 'Information', which has no form order .* a user who opened it may now open '${ALT}'`));
+});
diff --git a/plugins/model-apps/scripts/tests/form-order-reader.test.js b/plugins/model-apps/scripts/tests/form-order-reader.test.js
new file mode 100644
index 000000000..cf4ee7955
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/form-order-reader.test.js
@@ -0,0 +1,107 @@
+'use strict';
+const test = require('node:test');
+const assert = require('node:assert');
+const { readerFor } = require('../verify-model-app.js');
+
+const USER = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee';
+const FORM_A = '11111111-1111-1111-1111-111111111111';
+const FORM_B = '22222222-2222-2222-2222-222222222222';
+
+function sdkFor({ who = { status: 200, body: { UserId: `{${USER.toUpperCase()}}` } }, retrieve = { status: 200, body: { value: [] } }, rows = [] } = {}) {
+ const calls = [];
+ const sdk = {
+ dataverse: {
+ get: async (url) => {
+ calls.push({ type: 'get', url });
+ if (url === '/WhoAmI') return who;
+ return typeof retrieve === 'function' ? retrieve(url) : retrieve;
+ },
+ },
+ queryRecords: async (set, opts) => {
+ calls.push({ type: 'queryRecords', set, opts });
+ assert.strictEqual(set, 'systemform');
+ return rows;
+ },
+ findTables: async () => [],
+ findColumns: async () => [],
+ };
+ return { sdk, calls };
+}
+
+test('servedMainForms calls RetrieveFilteredForms with the lower-cased entity and caller alias, then maps ids to names', async () => {
+ const { sdk, calls } = sdkFor({
+ retrieve: { status: 200, body: { value: [{ formid: `{${FORM_A.toUpperCase()}}` }, { formid: FORM_B }] } },
+ rows: [{ formid: FORM_A.toUpperCase(), name: 'Work Item' }, { formid: `{${FORM_B}}`, name: 'My Work — Work Item' }],
+ });
+
+ const served = await readerFor(sdk, 'new_workitems', {}).servedMainForms('NEW_WorkItem');
+
+ assert.deepStrictEqual(served, [
+ { id: FORM_A, name: 'Work Item' },
+ { id: FORM_B, name: 'My Work — Work Item' },
+ ]);
+ const retrieveCall = calls.find((c) => c.type === 'get' && c.url !== '/WhoAmI');
+ assert.strictEqual(
+ retrieveCall.url,
+ `/systemforms/Microsoft.Dynamics.CRM.RetrieveFilteredForms(EntityLogicalName=@e,FormType=@t,User=@u)?@e='new_workitem'&@t=2&@u={'@odata.id':'systemusers(${USER})'}`,
+ );
+ const nameQuery = calls.find((c) => c.type === 'queryRecords');
+ assert.deepStrictEqual(nameQuery.opts.select, ['formid', 'name']);
+ assert.strictEqual(nameQuery.opts.filter, "objecttypecode eq 'new_workitem' and type eq 2");
+});
+
+test('WhoAmI is memoized across servedMainForms calls for two entities', async () => {
+ const { sdk, calls } = sdkFor({
+ retrieve: { status: 200, body: { value: [] } },
+ rows: [],
+ });
+ const reader = readerFor(sdk, 'new_workitems', {});
+
+ await reader.servedMainForms('new_workitem');
+ await reader.servedMainForms('new_case');
+
+ assert.strictEqual(calls.filter((c) => c.type === 'get' && c.url === '/WhoAmI').length, 1);
+ assert.strictEqual(calls.filter((c) => c.type === 'get' && c.url !== '/WhoAmI').length, 2);
+});
+
+test('a served id with no systemform name row falls back to the normalized id', async () => {
+ const { sdk } = sdkFor({
+ retrieve: { status: 200, body: { value: [{ formid: `{${FORM_A.toUpperCase()}}` }] } },
+ rows: [],
+ });
+
+ assert.deepStrictEqual(await readerFor(sdk, 'new_workitems', {}).servedMainForms('new_workitem'), [
+ { id: FORM_A, name: FORM_A },
+ ]);
+});
+
+test('RetrieveFilteredForms non-2xx responses throw with the HTTP status', async () => {
+ const { sdk } = sdkFor({ retrieve: { status: 403, body: { error: { message: 'denied' } } } });
+
+ await assert.rejects(readerFor(sdk, 'new_workitems', {}).servedMainForms('new_workitem'), /RetrieveFilteredForms returned HTTP 403/);
+});
+
+test('WhoAmI non-2xx or missing canonical GUID throws before interpolating a user into RetrieveFilteredForms', async (t) => {
+ for (const [name, who] of [
+ ['non-2xx WhoAmI', { status: 401, body: { UserId: USER } }],
+ ['missing canonical GUID', { status: 200, body: { UserId: 'not-a-guid' } }],
+ ]) {
+ await t.test(name, async () => {
+ const { sdk, calls } = sdkFor({ who });
+
+ await assert.rejects(readerFor(sdk, 'new_workitems', {}).servedMainForms('new_workitem'), /WhoAmI returned no user id/);
+ assert.deepStrictEqual(calls.map((c) => c.url).filter(Boolean), ['/WhoAmI']);
+ });
+ }
+});
+
+test('entity logical names containing quotes are OData-escaped in both RetrieveFilteredForms and name lookups', async () => {
+ const { sdk, calls } = sdkFor({ retrieve: { status: 200, body: { value: [] } }, rows: [] });
+
+ await readerFor(sdk, 'new_workitems', {}).servedMainForms("NEW_O'Hare");
+
+ const retrieveCall = calls.find((c) => c.type === 'get' && c.url !== '/WhoAmI');
+ assert.match(retrieveCall.url, /@e='new_o''hare'/);
+ const nameQuery = calls.find((c) => c.type === 'queryRecords');
+ assert.strictEqual(nameQuery.opts.filter, "objecttypecode eq 'new_o''hare' and type eq 2");
+});
diff --git a/plugins/model-apps/scripts/tests/form-order-real-bundle.test.js b/plugins/model-apps/scripts/tests/form-order-real-bundle.test.js
new file mode 100644
index 000000000..f495f1d41
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/form-order-real-bundle.test.js
@@ -0,0 +1,147 @@
+'use strict';
+// REAL BUNDLE: Main Form Set order is stored in a form's published formxml DisplayConditions. The
+// build relies on the SDK preserving roles/fallback while changing only Order, and on refusing an
+// order-only write when there is no DisplayConditions element to attach it to.
+const test = require('node:test');
+const assert = require('node:assert');
+const os = require('node:os');
+const path = require('node:path');
+const fs = require('node:fs');
+
+const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');
+const FORM_ID = '11111111-1111-1111-1111-111111111111';
+const ROLE_A = '22222222-2222-2222-2222-222222222222';
+const ROLE_B = '33333333-3333-3333-3333-333333333333';
+
+const tempDirs = [];
+test.after(() => { for (const dir of tempDirs) fs.rmSync(dir, { recursive: true, force: true }); });
+
+async function freshSdk(initialXml) {
+ const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'form-order-sdk-'));
+ tempDirs.push(dir);
+ const calls = [];
+ const state = { formxml: initialXml, etag: 'W/"form-etag-1"' };
+ const httpClient = {
+ get: async (url) => {
+ calls.push({ verb: 'get', url: String(url) });
+ if (/RetrieveUnpublished\(\)/.test(url)) {
+ return { status: 200, headers: {}, body: { formid: FORM_ID, formxml: state.formxml, '@odata.etag': state.etag } };
+ }
+ if (/\/systemforms\(/.test(url)) {
+ return { status: 200, headers: {}, body: { formid: FORM_ID, '@odata.etag': state.etag } };
+ }
+ return { status: 200, headers: {}, body: { value: [] } };
+ },
+ patch: async (url, body, options) => {
+ calls.push({ verb: 'patch', url: String(url), body, options });
+ if (body && body.formxml) state.formxml = body.formxml;
+ state.etag = 'W/"form-etag-2"';
+ return { status: 204, headers: {}, body: {} };
+ },
+ post: async () => ({ status: 204, headers: {}, body: {} }),
+ delete: async () => ({ status: 204, headers: {}, body: {} }),
+ put: async () => ({ status: 204, headers: {}, body: {} }),
+ };
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(dir), instanceUrl: 'https://contoso.crm.dynamics.com', httpClient });
+ await sdk.initWorkspace();
+ return { sdk, calls, state };
+}
+
+const patchCall = (calls) => calls.find((c) => c.verb === 'patch');
+const withoutDisplayConditions = (xml) => String(xml).replace(/<DisplayConditions\b[^>]*>(?:.|\n)*?<\/DisplayConditions>/, '').replace(/<DisplayConditions\b[^>]*\/>/, '');
+
+test('getFormSecurityRoles reads DisplayConditions Order and returns undefined when none exists', async () => {
+ const live = '<form><tabs><tab name="general" /></tabs><DisplayConditions Order="0" FallbackForm="true"><Everyone /></DisplayConditions></form>';
+ const withOrder = await freshSdk(live);
+ assert.deepStrictEqual(await withOrder.sdk.getFormSecurityRoles(FORM_ID), { everyone: true, fallbackForm: true, order: 0 });
+
+ const withoutOrder = await freshSdk('<form><tabs><tab name="general" /></tabs></form>');
+ assert.strictEqual(await withoutOrder.sdk.getFormSecurityRoles(FORM_ID), undefined);
+});
+
+test('setFormSecurityRoles order-only write preserves Everyone, FallbackForm, untouched XML, and uses the read etag', async () => {
+ const original = '<form><tabs><tab name="general"><labels><label description="General" languagecode="1033" /></labels></tab></tabs><DisplayConditions Order="0" FallbackForm="true"><Everyone /></DisplayConditions></form>';
+ const { sdk, calls } = await freshSdk(original);
+
+ await sdk.setFormSecurityRoles(FORM_ID, { order: 2 });
+
+ const patch = patchCall(calls);
+ assert.ok(patch, 'the SDK must PATCH the form row');
+ assert.match(patch.body.formxml, /Order="2"/);
+ assert.match(patch.body.formxml, /FallbackForm="true"/);
+ assert.match(patch.body.formxml, /<Everyone\s*\/>/);
+ assert.strictEqual(patch.options.headers['If-Match'], 'W/"form-etag-1"');
+ assert.strictEqual(withoutDisplayConditions(patch.body.formxml), withoutDisplayConditions(original), 'tabs and other formxml stay byte-for-byte unchanged');
+});
+
+test('order-only write on a role-restricted form preserves both roles and FallbackForm=false', async () => {
+ const original = `<form><tabs><tab name="general" /></tabs><DisplayConditions Order="0" FallbackForm="false"><Role Id="{${ROLE_A}}" /><Role Id="{${ROLE_B}}" /></DisplayConditions></form>`;
+ const { sdk, calls } = await freshSdk(original);
+
+ await sdk.setFormSecurityRoles(FORM_ID, { order: 2 });
+
+ const xml = patchCall(calls).body.formxml;
+ assert.match(xml, /Order="2"/);
+ assert.match(xml, /FallbackForm="false"/);
+ assert.match(xml, new RegExp(`<Role Id="\\{${ROLE_A}\\}"\\s*/>`));
+ assert.match(xml, new RegExp(`<Role Id="\\{${ROLE_B}\\}"\\s*/>`));
+ assert.strictEqual(withoutDisplayConditions(xml), withoutDisplayConditions(original));
+});
+
+test('forms without DisplayConditions refuse order-only writes, while everyone+fallback+order adds the element', async () => {
+ const original = '<form><tabs><tab name="general" /></tabs></form>';
+ const { sdk, calls } = await freshSdk(original);
+
+ await assert.rejects(sdk.setFormSecurityRoles(FORM_ID, { order: 2 }), /without `roleIds` or `everyone`/);
+ assert.strictEqual(calls.some((c) => c.verb === 'patch'), false, 'the refused order-only write must not PATCH');
+
+ await sdk.setFormSecurityRoles(FORM_ID, { everyone: true, fallbackForm: true, order: 1 });
+
+ const xml = patchCall(calls).body.formxml;
+ assert.match(xml, /<DisplayConditions\b[^>]*Order="1"[^>]*FallbackForm="true"[^>]*>/);
+ assert.match(xml, /<Everyone\s*\/>/);
+ assert.strictEqual(withoutDisplayConditions(xml), withoutDisplayConditions(original), 'adding DisplayConditions leaves the existing form body unchanged');
+});
+
+// The build places a Main form it creates on a table whose order it does not set IN ITS CREATE
+// (createInPlace, sdk-build.js): it finds the <DisplayConditions> the SDK gives the new form in its root
+// bag and replaces that node before the first push. This pins the SDK side of that: if the node moved or
+// were rebuilt at push time, forms would silently be created at Order 0 again.
+test('a new form carries <DisplayConditions Order="0"> in its root bag, and an edit to it before the first push is what the create writes', async () => {
+ const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'form-order-create-'));
+ tempDirs.push(dir);
+ const posts = [];
+ const httpClient = {
+ get: async (url) => {
+ const meta = /EntityDefinitions\(LogicalName='([^']+)'\)/.exec(url);
+ return { status: 200, headers: {}, body: meta ? { LogicalName: meta[1], EntitySetName: `${meta[1]}s`, ObjectTypeCode: 10001, MetadataId: '44444444-4444-4444-4444-444444444444' } : { value: [] } };
+ },
+ post: async (url, body) => { posts.push({ url: String(url), body }); return { status: 204, headers: { 'OData-EntityId': `${url}(55555555-5555-5555-5555-555555555555)` }, body: undefined }; },
+ patch: async () => ({ status: 204, headers: {}, body: {} }),
+ delete: async () => ({ status: 204, headers: {}, body: {} }),
+ put: async () => ({ status: 204, headers: {}, body: {} }),
+ };
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(dir), instanceUrl: 'https://contoso.crm.dynamics.com', httpClient });
+ await sdk.initWorkspace();
+
+ const art = await sdk.createArtifact('form', { name: 'Work Item \u2014 Board', entityLogicalName: 'new_workitem', formType: 'Main' });
+ const local = await sdk.getArtifact('form', art.id);
+ const at = local.bag.c.findIndex((e) => e && e.node && e.node.n === 'DisplayConditions');
+ assert.ok(at >= 0, `no DisplayConditions in the new form's root bag: ${JSON.stringify(local.bag.c.map((e) => e.node && e.node.n))}`);
+ assert.deepStrictEqual(local.bag.c[at].node.a, [['Order', '0'], ['FallbackForm', 'true']]);
+ assert.deepStrictEqual(local.bag.c[at].node.c.map((c) => c.n), ['Everyone']);
+
+ const entry = JSON.parse(JSON.stringify(local.bag.c[at]));
+ entry.node.a = entry.node.a.map(([n, v]) => (n === 'Order' ? [n, '7'] : [n, v]));
+ await sdk.updateElement('form', art.id, `/bag/c/${at}`, entry);
+ await sdk.pushArtifact('form', art.id);
+
+ const create = posts.find((p) => /\/systemforms(\?|$)/.test(p.url));
+ assert.ok(create, 'the form is created with one POST');
+ const xml = String(create.body && create.body.formxml);
+ assert.match(xml, /<DisplayConditions Order="7" FallbackForm="true"><Everyone \/><\/DisplayConditions>/);
+ assert.strictEqual((xml.match(/<DisplayConditions\b/g) || []).length, 1, 'one element, not a second default one');
+ assert.match(xml, /<header\b/, 'the rest of the form is written as the SDK built it');
+});
diff --git a/plugins/model-apps/scripts/tests/form-order-spec.test.js b/plugins/model-apps/scripts/tests/form-order-spec.test.js
new file mode 100644
index 000000000..eb0715043
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/form-order-spec.test.js
@@ -0,0 +1,287 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert');
+const { validateAppSpec } = require('../lib/app-spec.js');
+
+const WORK_ITEM = 'contoso_workitem';
+const PROJECT = 'contoso_project';
+const MAIN_NAMES = ['Work Item', 'My Work — Work Item', 'Work Item — Summary'];
+
+function main(entity, name, over = {}) {
+ return { entity, name, formType: 'Main', layout: 'auto', ...over };
+}
+
+function baseSpec() {
+ return {
+ solution: { uniqueName: 'ContosoWorkItems', publisherPrefix: 'contoso' },
+ app: { name: 'Work Items' },
+ entities: [
+ {
+ schemaName: WORK_ITEM,
+ displayName: 'Work Item',
+ pluralName: 'Work Items',
+ primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name' },
+ columns: [],
+ mainFormOrder: [...MAIN_NAMES],
+ },
+ {
+ schemaName: PROJECT,
+ displayName: 'Project',
+ pluralName: 'Projects',
+ primaryAttribute: { schemaName: 'contoso_projectname', displayName: 'Name' },
+ columns: [],
+ },
+ ],
+ forms: [
+ ...MAIN_NAMES.map((name) => main(WORK_ITEM, name)),
+ { entity: WORK_ITEM, name: 'Quick Work Item', formType: 'QuickCreate', layout: 'auto' },
+ { entity: WORK_ITEM, name: 'Work Item Quick View', formType: 'QuickView', layout: 'auto' },
+ main(PROJECT, 'Project Main'),
+ ],
+ views: [],
+ charts: [],
+ appShell: { areas: [] },
+ };
+}
+
+function clone(value) {
+ return JSON.parse(JSON.stringify(value));
+}
+
+function validate(spec) {
+ return validateAppSpec(spec, { profile: 'plan' });
+}
+
+function workItemEntity(spec) {
+ return spec.entities.find((e) => e.schemaName === WORK_ITEM);
+}
+
+function workItemForm(spec, name) {
+ return spec.forms.find((f) => f.entity === WORK_ITEM && f.name === name);
+}
+
+function withoutMainFormOrder() {
+ const s = baseSpec();
+ delete workItemEntity(s).mainFormOrder;
+ return s;
+}
+
+function errorFor(mutator, pattern) {
+ const s = baseSpec();
+ mutator(s);
+ const r = validate(s);
+ const errors = r.errors || [];
+ assert.strictEqual(r.ok, false, JSON.stringify(r));
+ assert.match(errors.join(' | '), pattern);
+ assert.ok(errors.some((e) => e.includes(`entity '${WORK_ITEM}'`) && pattern.test(e)), JSON.stringify(errors));
+}
+
+test('baseline helper produces a valid spec for focused mainFormOrder mutations', () => {
+ const r = validate(baseSpec());
+
+ assert.deepStrictEqual(r.errors, []);
+ assert.deepStrictEqual(r.warnings, []);
+ assert.strictEqual(r.ok, true);
+});
+
+test('mainFormOrder is an allowed entity key and may list every Main form', () => {
+ const r = validate(baseSpec());
+
+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
+ assert.ok(!(r.errors || []).some((e) => /unknown key 'mainFormOrder'/.test(e)));
+ assert.ok(!(r.errors || []).some((e) => /mainFormOrder/.test(e)));
+});
+
+test('mainFormOrder accepts partial and single-entry orders', () => {
+ for (const order of [
+ ['My Work — Work Item', 'Work Item'],
+ ['Work Item — Summary'],
+ ]) {
+ const s = baseSpec();
+ workItemEntity(s).mainFormOrder = order;
+ const r = validate(s);
+ assert.strictEqual(r.ok, true, `${JSON.stringify(order)}: ${JSON.stringify(r.errors)}`);
+ assert.ok(!(r.errors || []).some((e) => /mainFormOrder/.test(e)), JSON.stringify(r.errors));
+ }
+});
+
+test('mainFormOrder rejects non-array, empty, non-string, and blank values with table context', () => {
+ for (const bad of ['Work Item', { first: 'Work Item' }, [], ['Work Item', 42], ['Work Item', ' ']]) {
+ errorFor(
+ (s) => { workItemEntity(s).mainFormOrder = bad; },
+ /mainFormOrder must be a non-empty array of Main form names from forms\[\]/
+ );
+ }
+});
+
+test('mainFormOrder rejects duplicate names case-insensitively', () => {
+ errorFor(
+ (s) => { workItemEntity(s).mainFormOrder = ['Work Item', 'work item']; },
+ /mainFormOrder lists 'work item' more than once/
+ );
+});
+
+test('mainFormOrder rejects unknown names while listing the table Main forms', () => {
+ errorFor(
+ (s) => { workItemEntity(s).mainFormOrder = ['Missing Form']; },
+ /mainFormOrder names 'Missing Form', which is not a Main form of this table in forms\[\] \(its Main forms: 'Work Item', 'My Work — Work Item', 'Work Item — Summary'\)/
+ );
+});
+
+test('mainFormOrder rejects QuickCreate and QuickView names because they are not in the Main Form Set', () => {
+ errorFor(
+ (s) => { workItemEntity(s).mainFormOrder = ['Quick Work Item']; },
+ /mainFormOrder names 'Quick Work Item', a QuickCreate form — only Main forms are in the Main Form Set/
+ );
+ errorFor(
+ (s) => { workItemEntity(s).mainFormOrder = ['Work Item Quick View']; },
+ /mainFormOrder names 'Work Item Quick View', a QuickView form — only Main forms are in the Main Form Set/
+ );
+});
+
+test('mainFormOrder rejects a Main form name that belongs to another table', () => {
+ errorFor(
+ (s) => { workItemEntity(s).mainFormOrder = ['Project Main']; },
+ /mainFormOrder names 'Project Main', which is not a Main form of this table in forms\[\]/
+ );
+});
+
+test('mainFormOrder rejects ambiguous same-table Main form names', () => {
+ errorFor(
+ (s) => {
+ s.forms.push(main(WORK_ITEM, 'Work Item'));
+ workItemEntity(s).mainFormOrder = ['Work Item'];
+ },
+ /mainFormOrder names 'Work Item', but 2 Main forms of this table share that name/
+ );
+});
+
+// The build finds a deployed form by name with a server-side filter that ignores case (and, in most languages,
+// accents), so Main forms whose names differ only that way are one name to it, and the order could address neither.
+test('mainFormOrder rejects Main forms whose names differ only by case or accents', () => {
+ errorFor(
+ (s) => {
+ s.forms.push(main(WORK_ITEM, 'work item'));
+ workItemEntity(s).mainFormOrder = ['Work Item'];
+ },
+ /mainFormOrder names 'Work Item', but 2 Main forms of this table share that name \('Work Item', 'work item': Dataverse compares form names ignoring case/
+ );
+ errorFor(
+ (s) => {
+ s.forms.push(main(WORK_ITEM, 'Wörk Item'));
+ workItemEntity(s).mainFormOrder = ['Wörk Item'];
+ },
+ /mainFormOrder names 'Wörk Item', but 2 Main forms of this table share that name/
+ );
+ // Only Main forms are in the Main Form Set, and the build looks a form up by its type too: a Quick View with a
+ // case-variant name is no twin.
+ const quickView = baseSpec();
+ quickView.forms.push({ entity: WORK_ITEM, name: 'work item', formType: 'QuickView', layout: 'auto' });
+ const r = validate(quickView);
+ assert.ok(!(r.errors || []).some((e) => /share that name/.test(e)), JSON.stringify(r.errors));
+ // The listed name is a cross-reference into forms[], so it must still be spelled exactly as there.
+ errorFor(
+ (s) => { workItemEntity(s).mainFormOrder = ['WORK ITEM']; },
+ /mainFormOrder names 'WORK ITEM', which is not a Main form of this table in forms\[\] \(its Main forms: 'Work Item'/
+ );
+});
+
+test('mainFormOrder must agree with an explicit default form', () => {
+ errorFor(
+ (s) => {
+ workItemForm(s, 'Work Item — Summary').isDefault = true;
+ workItemEntity(s).mainFormOrder = ['Work Item', 'My Work — Work Item', 'Work Item — Summary'];
+ },
+ /form 'Work Item — Summary' sets isDefault, so it must come first in mainFormOrder/
+ );
+});
+
+test('mainFormOrder cannot be combined with securityRoles.order on a Main form', () => {
+ errorFor(
+ (s) => {
+ workItemForm(s, 'My Work — Work Item').securityRoles = { everyone: true, order: 0 };
+ },
+ /mainFormOrder and forms\[\]\.securityRoles\.order .* both set this table's form order/
+ );
+});
+
+test('securityRoles.order warns when the selected default has no explicit order', () => {
+ const s = withoutMainFormOrder();
+ workItemForm(s, 'Work Item').isDefault = true;
+ workItemForm(s, 'My Work — Work Item').securityRoles = { everyone: true, order: 0 };
+
+ const r = validate(s);
+
+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
+ assert.match((r.warnings || []).join(' | '), /entity 'contoso_workitem': forms\[\]\.securityRoles\.order sets this table's form order/);
+ assert.match((r.warnings || []).join(' | '), /'Work Item' opens first only if its securityRoles\.order is lower/);
+});
+
+test('securityRoles.order warning names a rival with a lower order', () => {
+ const s = withoutMainFormOrder();
+ workItemForm(s, 'Work Item').isDefault = true;
+ workItemForm(s, 'Work Item').securityRoles = { everyone: true, order: 2 };
+ workItemForm(s, 'My Work — Work Item').securityRoles = { everyone: true, order: 1 };
+
+ const r = validate(s);
+
+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
+ assert.match((r.warnings || []).join(' | '), /'My Work — Work Item': 1/);
+});
+
+test('securityRoles.order does not warn when the selected default has the strictly lowest order', () => {
+ const s = withoutMainFormOrder();
+ workItemForm(s, 'Work Item').isDefault = true;
+ workItemForm(s, 'Work Item').securityRoles = { everyone: true, order: 0 };
+ workItemForm(s, 'My Work — Work Item').securityRoles = { everyone: true, order: 1 };
+
+ const r = validate(s);
+
+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
+ assert.deepStrictEqual((r.warnings || []).filter((w) => /securityRoles\.order sets this table's form order/.test(w)), []);
+});
+
+test('securityRoles.order warns when the default ties another Main form order', () => {
+ const s = withoutMainFormOrder();
+ workItemForm(s, 'Work Item').isDefault = true;
+ workItemForm(s, 'Work Item').securityRoles = { everyone: true, order: 1 };
+ workItemForm(s, 'My Work — Work Item').securityRoles = { everyone: true, order: 1 };
+
+ const r = validate(s);
+
+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
+ assert.match((r.warnings || []).join(' | '), /'My Work — Work Item': 1/);
+});
+
+test('securityRoles.order warns for the owned-table first-Main fallback but not an existing table with no selected default', () => {
+ const own = withoutMainFormOrder();
+ workItemForm(own, 'My Work — Work Item').securityRoles = { everyone: true, order: 0 };
+ assert.match((validate(own).warnings || []).join(' | '), /'Work Item' opens first only if its securityRoles\.order is lower/);
+
+ const existing = withoutMainFormOrder();
+ workItemEntity(existing).existing = true;
+ workItemForm(existing, 'My Work — Work Item').securityRoles = { everyone: true, order: 0 };
+ const r = validate(existing);
+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
+ assert.deepStrictEqual((r.warnings || []).filter((w) => /securityRoles\.order sets this table's form order/.test(w)), []);
+});
+
+test('securityRoles.order emits no warning when mainFormOrder is present because the error covers the conflict', () => {
+ const s = baseSpec();
+ workItemForm(s, 'My Work — Work Item').securityRoles = { everyone: true, order: 0 };
+
+ const r = validate(s);
+
+ assert.strictEqual(r.ok, false);
+ assert.match((r.errors || []).join(' | '), /both set this table's form order/);
+ assert.deepStrictEqual((r.warnings || []).filter((w) => /securityRoles\.order sets this table's form order/.test(w)), []);
+});
+
+test('helper cloning keeps test mutations isolated', () => {
+ const a = clone(baseSpec());
+ const b = clone(baseSpec());
+ workItemEntity(a).mainFormOrder = ['Work Item'];
+
+ assert.deepStrictEqual(workItemEntity(b).mainFormOrder, MAIN_NAMES);
+});
diff --git a/plugins/model-apps/scripts/tests/form-order-verify.test.js b/plugins/model-apps/scripts/tests/form-order-verify.test.js
new file mode 100644
index 000000000..e540b61c5
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/form-order-verify.test.js
@@ -0,0 +1,271 @@
+'use strict';
+const test = require('node:test');
+const assert = require('node:assert');
+const { verifySpec } = require('../lib/verify-spec.js');
+
+const ENTITY = 'new_workitem';
+const EXISTING_ENTITY = 'account';
+const WORK = 'Work Item';
+const MY_WORK = 'My Work — Work Item';
+const SUMMARY = 'Work Item — Summary';
+const LEGACY = 'Legacy';
+const IDS = {
+ [WORK]: '11111111-1111-1111-1111-111111111111',
+ [MY_WORK]: '22222222-2222-2222-2222-222222222222',
+ [SUMMARY]: '33333333-3333-3333-3333-333333333333',
+ [LEGACY]: '44444444-4444-4444-4444-444444444444',
+};
+
+function specFor({
+ entity = ENTITY,
+ existing = false,
+ forms = [
+ { entity, name: WORK, formType: 'Main' },
+ { entity, name: MY_WORK, formType: 'Main' },
+ { entity, name: SUMMARY, formType: 'Main' },
+ ],
+ entityProps = {},
+} = {}) {
+ return {
+ solution: { publisherPrefix: 'new' },
+ app: { name: 'Work Items', uniqueName: 'new_workitems' },
+ entities: [{ schemaName: entity, columns: [], ...(existing ? { existing: true } : {}), ...entityProps }],
+ views: [],
+ charts: [],
+ appShell: { areas: [] },
+ forms,
+ };
+}
+
+function formxml(order) {
+ if (order === undefined) return '<form><tabs /></form>';
+ return `<form><DisplayConditions Order="${order}" FallbackForm="true"><Everyone /></DisplayConditions><tabs /></form>`;
+}
+
+function readFor({
+ entity = ENTITY,
+ ids = IDS,
+ orders = { [WORK]: 0, [MY_WORK]: 1, [SUMMARY]: 2 },
+ served,
+ missingNames = [],
+ topologyThrows = {},
+ includeFormTopology = true,
+ includeServedMainForms = true,
+ includeFormDefaultState = true,
+ defaultNames = [WORK],
+} = {}) {
+ const missing = new Set(missingNames);
+ const byId = new Map(Object.entries(ids).map(([name, id]) => [id.toLowerCase(), name]));
+ return {
+ findTable: async (logical) => ({ logicalName: logical }),
+ findColumns: async () => [],
+ sitemapXml: async () => '',
+ queryRecords: async (set, opts) => {
+ if (set !== 'systemform') return [];
+ const filter = String(opts && opts.filter || '');
+ const idMatch = /formid eq ([0-9a-fA-F-]{36})/.exec(filter);
+ if (idMatch) {
+ const id = idMatch[1].toLowerCase();
+ const name = byId.get(id);
+ return name && !missing.has(name) ? [{ formid: idMatch[1], name, objecttypecode: entity, type: 2 }] : [];
+ }
+ const entityMatch = /objecttypecode eq '([^']+)'/.exec(filter);
+ if (entityMatch && entityMatch[1].toLowerCase() !== entity.toLowerCase()) return [];
+ const nameMatch = /name eq '([^']+)'/.exec(filter);
+ if (!nameMatch) return [];
+ const name = nameMatch[1].replace(/''/g, "'");
+ if (!ids[name] || missing.has(name)) return [];
+ return [{ formid: ids[name], name, objecttypecode: entity, type: 2 }];
+ },
+ ...(includeFormDefaultState ? {
+ formDefaultState: async (_entity, formId) => ({ isDefault: defaultNames.some((n) => ids[n] && ids[n].toLowerCase() === String(formId).toLowerCase()) }),
+ } : {}),
+ ...(includeFormTopology ? {
+ formTopology: async (_entity, formId) => {
+ const name = byId.get(String(formId).toLowerCase());
+ if (topologyThrows[name]) throw new Error(topologyThrows[name]);
+ return formxml(orders[name]);
+ },
+ } : {}),
+ ...(includeServedMainForms ? {
+ servedMainForms: async () => {
+ if (served instanceof Error) throw served;
+ return (served || [WORK, MY_WORK, SUMMARY]).map((entry) => typeof entry === 'string'
+ ? { id: ids[entry], name: entry }
+ : entry);
+ },
+ } : {}),
+ };
+}
+
+const checksOf = (result, kind) => result.checks.filter((c) => c.kind === kind);
+const checkOf = (result, kind) => result.checks.find((c) => c.kind === kind);
+
+test('own custom table passes stored and served Main Form Set order when Work Item opens first', async () => {
+ const result = await verifySpec(specFor(), readFor());
+
+ assert.strictEqual(result.ok, true, JSON.stringify(result.missing));
+ assert.deepStrictEqual(checksOf(result, 'form-order').map((c) => [c.present, c.name]), [[true, `${ENTITY}: ${WORK} > ${MY_WORK} > ${SUMMARY}`]]);
+ assert.deepStrictEqual(checksOf(result, 'form-order-served').map((c) => [c.present, c.name]), [[true, `${ENTITY} opens with '${WORK}'`]]);
+});
+
+test('stored order failure names both forms and skips the served-order proof', async () => {
+ const result = await verifySpec(specFor(), readFor({ orders: { [WORK]: 1, [MY_WORK]: 0, [SUMMARY]: 2 } }));
+
+ assert.strictEqual(result.ok, false);
+ const stored = checkOf(result, 'form-order');
+ assert.strictEqual(stored.present, false);
+ assert.match(stored.detail, /'My Work — Work Item' \(order 0\) is not after 'Work Item' \(order 1\)/);
+ assert.strictEqual(checksOf(result, 'form-order-served').length, 0, 'served order is not meaningful when stored order already failed');
+});
+
+test('a declared Main form without DisplayConditions fails as having no form order', async () => {
+ const result = await verifySpec(specFor(), readFor({ orders: { [WORK]: undefined, [MY_WORK]: 1, [SUMMARY]: 2 } }));
+
+ const stored = checkOf(result, 'form-order');
+ assert.strictEqual(stored.present, false);
+ assert.match(stored.detail, /'Work Item' has no form order/);
+});
+
+test('equal stored Orders fail because the platform decides ties', async () => {
+ const result = await verifySpec(specFor(), readFor({ orders: { [WORK]: 0, [MY_WORK]: 0, [SUMMARY]: 2 } }));
+
+ const stored = checkOf(result, 'form-order');
+ assert.strictEqual(stored.present, false);
+ assert.match(stored.detail, /'My Work — Work Item' \(order 0\) is not after 'Work Item' \(order 0\)/);
+});
+
+test('a formxml read error fails the stored order proof and names the form', async () => {
+ const result = await verifySpec(specFor(), readFor({ topologyThrows: { [MY_WORK]: 'formxml denied' } }));
+
+ const stored = checkOf(result, 'form-order');
+ assert.strictEqual(stored.present, false);
+ assert.match(stored.detail, /could not read the deployed form order \('My Work — Work Item': formxml denied\)/);
+});
+
+test('an undeclared form served first fails with the Maker remedy', async () => {
+ const result = await verifySpec(specFor(), readFor({ served: [LEGACY, WORK, MY_WORK, SUMMARY] }));
+
+ const served = checkOf(result, 'form-order-served');
+ assert.strictEqual(served.present, false);
+ assert.match(served.detail, /users without a remembered form open 'Legacy' first/);
+ assert.match(served.detail, /Move it down in Maker \(Form settings > Form order\), or declare it/);
+});
+
+test('declared forms served in the wrong relative order fail and name the inversion', async () => {
+ const result = await verifySpec(specFor(), readFor({ served: [WORK, SUMMARY, MY_WORK] }));
+
+ const served = checkOf(result, 'form-order-served');
+ assert.strictEqual(served.present, false);
+ assert.match(served.detail, /'Work Item — Summary' is served before 'My Work — Work Item'/);
+});
+
+test('when the verifying user cannot open the first planned form, served order is environment-skipped', async () => {
+ const result = await verifySpec(specFor(), readFor({ served: [MY_WORK, SUMMARY] }));
+
+ assert.strictEqual(checksOf(result, 'form-order-served').length, 0);
+ assert.ok(result.environmentSkipped.some((entry) => entry.startsWith(`form-order-served:${ENTITY}`) && entry.includes(WORK)), JSON.stringify(result.environmentSkipped));
+});
+
+test('servedMainForms read failures fail the served-order check with the error text', async () => {
+ const result = await verifySpec(specFor(), readFor({ served: new Error('RetrieveFilteredForms 503') }));
+
+ const served = checkOf(result, 'form-order-served');
+ assert.strictEqual(served.present, false);
+ assert.match(served.detail, /RetrieveFilteredForms 503/);
+});
+
+test('a reader without servedMainForms still proves stored order without crashing', async () => {
+ const result = await verifySpec(specFor(), readFor({ includeServedMainForms: false }));
+
+ assert.strictEqual(result.ok, true, JSON.stringify(result.missing));
+ assert.strictEqual(checksOf(result, 'form-order').length, 1);
+ assert.strictEqual(checksOf(result, 'form-order-served').length, 0);
+});
+
+test('a reader without formTopology adds no form-order checks at all', async () => {
+ const result = await verifySpec(specFor(), readFor({ includeFormTopology: false, includeServedMainForms: false }));
+
+ assert.strictEqual(checksOf(result, 'form-order').length, 0);
+ assert.strictEqual(checksOf(result, 'form-order-served').length, 0);
+});
+
+test('existing table without explicit default or mainFormOrder has no default or order ownership checks', async () => {
+ const result = await verifySpec(specFor({ entity: EXISTING_ENTITY, existing: true }), readFor({ entity: EXISTING_ENTITY }));
+
+ assert.strictEqual(result.ok, true, JSON.stringify(result.missing));
+ assert.strictEqual(checksOf(result, 'form-default').length, 0);
+ assert.strictEqual(checksOf(result, 'form-order').length, 0);
+ assert.strictEqual(checksOf(result, 'form-order-served').length, 0);
+});
+
+test('existing table with explicit isDefault checks default promotion and form order', async () => {
+ const forms = [
+ { entity: EXISTING_ENTITY, name: WORK, formType: 'Main', isDefault: true },
+ { entity: EXISTING_ENTITY, name: MY_WORK, formType: 'Main' },
+ { entity: EXISTING_ENTITY, name: SUMMARY, formType: 'Main' },
+ ];
+
+ const result = await verifySpec(
+ specFor({ entity: EXISTING_ENTITY, existing: true, forms }),
+ readFor({ entity: EXISTING_ENTITY, defaultNames: [WORK] }),
+ );
+
+ assert.strictEqual(result.ok, true, JSON.stringify(result.missing));
+ assert.ok(checksOf(result, 'form-default').some((c) => c.name === `${EXISTING_ENTITY}.${WORK}` && c.present));
+ assert.strictEqual(checksOf(result, 'form-order').length, 1);
+});
+
+test('mainFormOrder drives the expected full and partial order before current stored order fills the rest', async (t) => {
+ await t.test('full list is authoritative', async () => {
+ const result = await verifySpec(
+ specFor({ entityProps: { mainFormOrder: [SUMMARY, WORK, MY_WORK] } }),
+ readFor({ orders: { [SUMMARY]: 0, [WORK]: 1, [MY_WORK]: 2 }, served: [SUMMARY, WORK, MY_WORK], defaultNames: [SUMMARY] }),
+ );
+
+ assert.strictEqual(result.ok, true, JSON.stringify(result.missing));
+ assert.strictEqual(checkOf(result, 'form-order').name, `${ENTITY}: ${SUMMARY} > ${WORK} > ${MY_WORK}`);
+ });
+
+ await t.test('partial list comes first and unspecified forms keep stored relative order', async () => {
+ const result = await verifySpec(
+ specFor({ entityProps: { mainFormOrder: [SUMMARY] } }),
+ readFor({ orders: { [SUMMARY]: 0, [MY_WORK]: 1, [WORK]: 2 }, served: [SUMMARY, MY_WORK, WORK], defaultNames: [SUMMARY] }),
+ );
+
+ assert.strictEqual(result.ok, true, JSON.stringify(result.missing));
+ assert.strictEqual(checkOf(result, 'form-order').name, `${ENTITY}: ${SUMMARY} > ${MY_WORK} > ${WORK}`);
+ });
+});
+
+test('a table ordered by hand through securityRoles.order has no automatic order checks', async () => {
+ const forms = [
+ { entity: ENTITY, name: WORK, formType: 'Main', securityRoles: { order: 0 } },
+ { entity: ENTITY, name: MY_WORK, formType: 'Main' },
+ { entity: ENTITY, name: SUMMARY, formType: 'Main' },
+ ];
+
+ const result = await verifySpec(specFor({ forms }), readFor());
+
+ assert.strictEqual(checksOf(result, 'form-order').length, 0);
+ assert.strictEqual(checksOf(result, 'form-order-served').length, 0);
+});
+
+test('a declared Main form that does not resolve is reported missing and suppresses order checks for that table', async () => {
+ const result = await verifySpec(specFor(), readFor({ missingNames: [SUMMARY] }));
+
+ const missingForm = result.checks.find((c) => c.kind === 'form' && c.name === SUMMARY);
+ assert.ok(missingForm);
+ assert.strictEqual(missingForm.present, false);
+ assert.strictEqual(checksOf(result, 'form-order').length, 0);
+ assert.strictEqual(checksOf(result, 'form-order-served').length, 0);
+});
+
+test('result.ok follows order-check results: failing order makes it false and passing order leaves it true', async () => {
+ const pass = await verifySpec(specFor(), readFor());
+ const fail = await verifySpec(specFor(), readFor({ orders: { [WORK]: 1, [MY_WORK]: 0, [SUMMARY]: 2 } }));
+
+ assert.strictEqual(pass.ok, true, JSON.stringify(pass.missing));
+ assert.strictEqual(fail.ok, false);
+ assert.ok(fail.missing.some((m) => m.kind === 'form-order'));
+});
diff --git a/plugins/model-apps/scripts/tests/form-order.test.js b/plugins/model-apps/scripts/tests/form-order.test.js
new file mode 100644
index 000000000..841008cd1
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/form-order.test.js
@@ -0,0 +1,329 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert');
+
+const {
+ isMainForm,
+ isOwnCustomTable,
+ declaredMainForms,
+ listedMainForms,
+ selectDefaultForm,
+ ordersByHand,
+ plannedMainFormSequence,
+ displayConditionsOrder,
+ compareServedOrder,
+} = require('../lib/form-order.js');
+
+const WORK_ITEM = 'contoso_workitem';
+const OTHER_TABLE = 'contoso_project';
+
+function main(name, over = {}) {
+ return { entity: WORK_ITEM, name, formType: 'Main', ...over };
+}
+
+function quick(name, formType = 'QuickCreate', over = {}) {
+ return { entity: WORK_ITEM, name, formType, ...over };
+}
+
+function spec(over = {}) {
+ return {
+ solution: { publisherPrefix: 'contoso' },
+ entities: [{ schemaName: WORK_ITEM }, { schemaName: OTHER_TABLE }],
+ forms: [
+ main('Work Item'),
+ main('My Work — Work Item'),
+ main('Work Item — Summary'),
+ quick('Work Item Quick'),
+ { entity: OTHER_TABLE, name: 'Project Main', formType: 'Main' },
+ ],
+ ...over,
+ };
+}
+
+test('isMainForm treats omitted formType as Main and rejects non-Main or malformed inputs', () => {
+ assert.strictEqual(isMainForm({ name: 'No Type' }), true);
+ assert.strictEqual(isMainForm({ formType: 'Main' }), true);
+ assert.strictEqual(isMainForm({ formType: 'QuickCreate' }), false);
+ assert.strictEqual(isMainForm({ formType: 'QuickView' }), false);
+ assert.strictEqual(isMainForm(null), false);
+ assert.strictEqual(isMainForm(undefined), false);
+ assert.strictEqual(isMainForm('Main'), false);
+});
+
+test('isOwnCustomTable recognizes declared owned custom tables case-insensitively', () => {
+ assert.strictEqual(isOwnCustomTable(spec(), 'CONTOSO_WORKITEM'), true);
+ assert.strictEqual(isOwnCustomTable({
+ solution: { publisherPrefix: 'ConToSo' },
+ entities: [{ schemaName: 'contoso_WorkItem' }],
+ }, 'CONTOSO_WORKITEM'), true);
+ assert.strictEqual(isOwnCustomTable(null, WORK_ITEM), false);
+ assert.strictEqual(isOwnCustomTable(spec({ entities: [{ schemaName: WORK_ITEM, existing: true }] }), WORK_ITEM), false);
+ assert.strictEqual(isOwnCustomTable(spec({ entities: [{ schemaName: 'other_workitem' }] }), 'other_workitem'), false);
+ assert.strictEqual(isOwnCustomTable({ solution: {}, entities: [{ schemaName: WORK_ITEM }] }, WORK_ITEM), false);
+ assert.strictEqual(isOwnCustomTable(spec(), 'contoso_missing'), false);
+});
+
+test('declaredMainForms returns only one entity Main forms in spec order', () => {
+ const s = spec({
+ forms: [
+ main('Work Item'),
+ { entity: WORK_ITEM.toUpperCase(), name: 'My Work — Work Item', formType: 'Main' },
+ quick('Quick Only'),
+ { entity: OTHER_TABLE, name: 'Project Main', formType: 'Main' },
+ main('Work Item — Summary'),
+ ],
+ });
+
+ assert.deepStrictEqual(declaredMainForms(s, 'CONTOSO_WORKITEM').map((f) => f.name), [
+ 'Work Item',
+ 'My Work — Work Item',
+ 'Work Item — Summary',
+ ]);
+ assert.deepStrictEqual(declaredMainForms(null, WORK_ITEM), []);
+ assert.deepStrictEqual(declaredMainForms(s, null), []);
+ assert.deepStrictEqual(declaredMainForms(s, undefined), []);
+});
+
+test('listedMainForms returns null when mainFormOrder is absent or not an array', () => {
+ assert.strictEqual(listedMainForms(spec(), WORK_ITEM), null);
+ assert.strictEqual(listedMainForms(spec({ entities: [{ schemaName: WORK_ITEM, mainFormOrder: 'Work Item' }] }), WORK_ITEM), null);
+ assert.strictEqual(listedMainForms(spec(), 'contoso_missing'), null);
+});
+
+test('listedMainForms resolves exact Main-form names in list order and drops unresolved entries', () => {
+ const s = spec({
+ entities: [{ schemaName: WORK_ITEM, mainFormOrder: [
+ 'My Work — Work Item',
+ 'work item',
+ 'Work Item',
+ 'Work Item',
+ 'Work Item Quick',
+ 'Missing',
+ ] }],
+ });
+
+ assert.deepStrictEqual(listedMainForms(s, WORK_ITEM).map((f) => f.name), [
+ 'My Work — Work Item',
+ 'Work Item',
+ ]);
+});
+
+// The spec gate rejects a name that differs only by case ("not a Main form of this table"), so the
+// helper must not quietly resolve it either — otherwise a build and its gate would disagree about which
+// form an entry names. Here the wrong-case entry stands alone, ahead of an exact one.
+test('listedMainForms does not resolve a name that matches a form only case-insensitively', () => {
+ const s = spec({ entities: [{ schemaName: WORK_ITEM, mainFormOrder: ['work item', 'My Work — Work Item'] }] });
+ assert.deepStrictEqual(listedMainForms(s, WORK_ITEM).map((f) => f.name), ['My Work — Work Item']);
+});
+
+test('selectDefaultForm honors explicit defaults, mainFormOrder, owned fallback, and object identity', () => {
+ const explicitExisting = spec({
+ entities: [{ schemaName: WORK_ITEM, existing: true }],
+ forms: [main('Work Item'), main('My Work — Work Item', { isDefault: true })],
+ });
+ assert.deepStrictEqual(selectDefaultForm(explicitExisting, WORK_ITEM), {
+ form: explicitExisting.forms[1],
+ explicit: true,
+ });
+
+ const listedExisting = spec({
+ entities: [{ schemaName: WORK_ITEM, existing: true, mainFormOrder: ['My Work — Work Item'] }],
+ forms: [main('Work Item'), main('My Work — Work Item')],
+ });
+ assert.deepStrictEqual(selectDefaultForm(listedExisting, WORK_ITEM), {
+ form: listedExisting.forms[1],
+ explicit: true,
+ });
+
+ const ownedFallback = spec({ forms: [main('Work Item'), main('My Work — Work Item')] });
+ assert.deepStrictEqual(selectDefaultForm(ownedFallback, WORK_ITEM), {
+ form: ownedFallback.forms[0],
+ explicit: false,
+ });
+
+ assert.strictEqual(selectDefaultForm(spec({
+ entities: [{ schemaName: WORK_ITEM, existing: true }],
+ forms: [main('Work Item'), main('My Work — Work Item')],
+ }), WORK_ITEM), null);
+ assert.strictEqual(selectDefaultForm(spec({ forms: [quick('Quick Only')] }), WORK_ITEM), null);
+
+ const unresolvedList = spec({
+ entities: [{ schemaName: WORK_ITEM, mainFormOrder: ['Missing'] }],
+ forms: [main('Work Item'), main('My Work — Work Item')],
+ });
+ assert.deepStrictEqual(selectDefaultForm(unresolvedList, WORK_ITEM), {
+ form: unresolvedList.forms[0],
+ explicit: false,
+ });
+});
+
+test('ordersByHand only counts securityRoles.order on Main forms of the requested entity', () => {
+ assert.strictEqual(ordersByHand(spec({ forms: [main('Work Item', { securityRoles: { order: 0 } })] }), WORK_ITEM), true);
+ assert.strictEqual(ordersByHand(spec({ forms: [main('Work Item', { securityRoles: {} })] }), WORK_ITEM), false);
+ assert.strictEqual(ordersByHand(spec({ forms: [main('Work Item', { securityRoles: null }), main('Other', { securityRoles: 'roles' })] }), WORK_ITEM), false);
+ assert.strictEqual(ordersByHand(spec({ forms: [quick('Quick Only', 'QuickCreate', { securityRoles: { order: 0 } })] }), WORK_ITEM), false);
+ assert.strictEqual(ordersByHand(spec({ forms: [{ entity: OTHER_TABLE, name: 'Project Main', formType: 'Main', securityRoles: { order: 0 } }] }), WORK_ITEM), false);
+});
+
+test('plannedMainFormSequence declines to order hand-ordered forms and existing tables with no choice', () => {
+ assert.strictEqual(plannedMainFormSequence(spec({ forms: [main('Work Item', { securityRoles: { order: 0 } })] }), WORK_ITEM), null);
+ assert.strictEqual(plannedMainFormSequence(spec({
+ entities: [{ schemaName: WORK_ITEM, existing: true }],
+ forms: [main('Work Item'), main('My Work — Work Item')],
+ }), WORK_ITEM), null);
+});
+
+test('plannedMainFormSequence puts the owned fallback or explicit default first and keeps spec-order ties', () => {
+ const owned = spec({ forms: [main('Work Item'), main('My Work — Work Item'), main('Work Item — Summary')] });
+ assert.deepStrictEqual(plannedMainFormSequence(owned, WORK_ITEM).map((f) => f.name), [
+ 'Work Item',
+ 'My Work — Work Item',
+ 'Work Item — Summary',
+ ]);
+
+ const explicit = spec({ forms: [main('Work Item'), main('My Work — Work Item'), main('Work Item — Summary', { isDefault: true })] });
+ assert.deepStrictEqual(plannedMainFormSequence(explicit, WORK_ITEM, new Map()).map((f) => f.name), [
+ 'Work Item — Summary',
+ 'Work Item',
+ 'My Work — Work Item',
+ ]);
+});
+
+test('plannedMainFormSequence preserves current order only for non-head forms', () => {
+ const s = spec({ forms: [main('Work Item'), main('My Work — Work Item', { isDefault: true }), main('Work Item — Summary'), main('Later')] });
+ const current = new Map([
+ [s.forms[0], 10],
+ [s.forms[1], 99],
+ [s.forms[2], 1],
+ ]);
+
+ assert.deepStrictEqual(plannedMainFormSequence(s, WORK_ITEM, current).map((f) => f.name), [
+ 'My Work — Work Item',
+ 'Work Item — Summary',
+ 'Work Item',
+ 'Later',
+ ]);
+});
+
+test('plannedMainFormSequence breaks equal stored orders by spec order', () => {
+ const s = spec({ forms: [main('Work Item'), main('My Work — Work Item'), main('Work Item — Summary')] });
+ const current = new Map([[s.forms[1], 7], [s.forms[2], 7]]);
+
+ assert.deepStrictEqual(plannedMainFormSequence(s, WORK_ITEM, current).map((f) => f.name), [
+ 'Work Item',
+ 'My Work — Work Item',
+ 'Work Item — Summary',
+ ]);
+});
+
+test('plannedMainFormSequence applies full and partial mainFormOrder without undeclared live forms', () => {
+ const full = spec({
+ entities: [{ schemaName: WORK_ITEM, mainFormOrder: ['Work Item — Summary', 'Work Item', 'My Work — Work Item'] }],
+ forms: [main('Work Item'), main('My Work — Work Item'), main('Work Item — Summary')],
+ });
+ assert.deepStrictEqual(plannedMainFormSequence(full, WORK_ITEM).map((f) => f.name), [
+ 'Work Item — Summary',
+ 'Work Item',
+ 'My Work — Work Item',
+ ]);
+
+ const partial = spec({
+ entities: [{ schemaName: WORK_ITEM, mainFormOrder: ['Work Item — Summary'] }],
+ forms: [main('Work Item'), main('My Work — Work Item'), main('Work Item — Summary')],
+ });
+ const current = new Map([[partial.forms[0], 5], [partial.forms[1], 2], [{ name: 'Live Only' }, 0]]);
+ assert.deepStrictEqual(plannedMainFormSequence(partial, WORK_ITEM, current).map((f) => f.name), [
+ 'Work Item — Summary',
+ 'My Work — Work Item',
+ 'Work Item',
+ ]);
+});
+
+test('plannedMainFormSequence applies explicit defaults on existing tables', () => {
+ const s = spec({
+ entities: [{ schemaName: WORK_ITEM, existing: true }],
+ forms: [main('Work Item'), main('My Work — Work Item', { isDefault: true })],
+ });
+
+ assert.deepStrictEqual(plannedMainFormSequence(s, WORK_ITEM).map((f) => f.name), [
+ 'My Work — Work Item',
+ 'Work Item',
+ ]);
+});
+
+test('displayConditionsOrder parses live DisplayConditions shapes and safe absence cases', () => {
+ assert.deepStrictEqual(displayConditionsOrder('<DisplayConditions Order="0" FallbackForm="true"><Everyone /></DisplayConditions>'), { present: true, order: 0 });
+ assert.deepStrictEqual(displayConditionsOrder('<DisplayConditions FallbackForm="true" Order="3"><Everyone /></DisplayConditions>'), { present: true, order: 3 });
+ assert.deepStrictEqual(displayConditionsOrder('<DisplayConditions Order="2" FallbackForm="false"><Role Id="{GUID}" /></DisplayConditions>'), { present: true, order: 2 });
+ assert.deepStrictEqual(displayConditionsOrder('<DisplayConditions Order="4" />'), { present: true, order: 4 });
+ assert.deepStrictEqual(displayConditionsOrder("<DisplayConditions Order='7'></DisplayConditions>"), { present: true, order: 7 });
+ assert.deepStrictEqual(displayConditionsOrder('<DisplayConditions FallbackForm="true" />'), { present: true, order: undefined });
+ assert.deepStrictEqual(displayConditionsOrder('<DisplayConditions Order="a" />'), { present: true, order: undefined });
+ assert.deepStrictEqual(displayConditionsOrder('<DisplayConditions Order="1.5" />'), { present: true, order: undefined });
+ assert.deepStrictEqual(displayConditionsOrder('<DisplayConditions Order="" />'), { present: true, order: undefined });
+ assert.deepStrictEqual(displayConditionsOrder('<DisplayConditions Order="-2" />'), { present: true, order: -2 });
+ assert.deepStrictEqual(displayConditionsOrder('<DisplayConditionsX Order="1" />'), { present: false, order: undefined });
+ assert.deepStrictEqual(displayConditionsOrder('<DisplayConditions xOrder="5" FallbackOrder="6" />'), { present: true, order: undefined });
+ assert.deepStrictEqual(displayConditionsOrder(null), { present: false, order: undefined });
+ assert.deepStrictEqual(displayConditionsOrder(undefined), { present: false, order: undefined });
+ assert.deepStrictEqual(displayConditionsOrder(42), { present: false, order: undefined });
+ assert.deepStrictEqual(displayConditionsOrder('<DisplayConditions Order = "8" />'), { present: true, order: 8 });
+});
+
+test('compareServedOrder accepts matching order, normalized ids, and duplicate served ids', () => {
+ const planned = [
+ { name: 'Work Item', id: '{AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA}' },
+ { name: 'My Work — Work Item', id: 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb' },
+ ];
+
+ assert.deepStrictEqual(compareServedOrder(planned, [
+ 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
+ '{BBBBBBBB-BBBB-BBBB-BBBB-BBBBBBBBBBBB}',
+ '{BBBBBBBB-BBBB-BBBB-BBBB-BBBBBBBBBBBB}',
+ ]), { ok: true, missing: [] });
+});
+
+test('compareServedOrder reports relative-order, ahead, first-not-served, missing, and empty-planned outcomes', () => {
+ const planned = [
+ { name: 'Work Item', id: 'form-a' },
+ { name: 'My Work — Work Item', id: 'form-b' },
+ { name: 'Work Item — Summary', id: 'form-c' },
+ ];
+
+ assert.deepStrictEqual(compareServedOrder(planned, ['form-b', 'form-a']), {
+ ok: false,
+ reason: 'order',
+ before: 'My Work — Work Item',
+ after: 'Work Item',
+ missing: ['Work Item — Summary'],
+ });
+ assert.deepStrictEqual(compareServedOrder(planned, ['{LIVE-FIRST}', 'FORM-A', 'form-b']), {
+ ok: false,
+ reason: 'ahead',
+ aheadId: 'live-first',
+ missing: ['Work Item — Summary'],
+ });
+ assert.deepStrictEqual(compareServedOrder(planned, ['form-b']), {
+ ok: null,
+ reason: 'first-not-served',
+ missing: ['Work Item', 'Work Item — Summary'],
+ });
+ assert.deepStrictEqual(compareServedOrder([], ['form-a']), {
+ ok: null,
+ reason: 'first-not-served',
+ missing: [],
+ });
+});
+
+test('compareServedOrder treats omitted served lists and nullish ids consistently', () => {
+ assert.deepStrictEqual(compareServedOrder([{ name: 'Work Item', id: 'form-a' }]), {
+ ok: null,
+ reason: 'first-not-served',
+ missing: ['Work Item'],
+ });
+ assert.deepStrictEqual(compareServedOrder([{ name: 'No Id', id: null }], [undefined]), {
+ ok: true,
+ missing: [],
+ });
+});
diff --git a/plugins/model-apps/scripts/tests/golden/journal.project-tracker.txt b/plugins/model-apps/scripts/tests/golden/journal.project-tracker.txt
index 7da6e9a8d..c4d751259 100644
--- a/plugins/model-apps/scripts/tests/golden/journal.project-tracker.txt
+++ b/plugins/model-apps/scripts/tests/golden/journal.project-tracker.txt
@@ -12,6 +12,8 @@ views start enrich default views for new_project
views ok enrich default views for new_project
forms start form "Project"
forms ok form "Project"
+forms start form order for new_project: 'Project'
+forms ok form order for new_project: 'Project'
app-shell start app icon (generated) new_projecttracker_icon
app-shell ok app icon (generated) new_projecttracker_icon
app-shell start app "Project Tracker"
diff --git a/plugins/model-apps/scripts/tests/golden/journal.support-desk.txt b/plugins/model-apps/scripts/tests/golden/journal.support-desk.txt
index b602c1bac..f68a6a865 100644
--- a/plugins/model-apps/scripts/tests/golden/journal.support-desk.txt
+++ b/plugins/model-apps/scripts/tests/golden/journal.support-desk.txt
@@ -56,6 +56,12 @@ forms start form "Comment"
forms ok form "Customer"
forms ok form "Comment"
forms ok form "Ticket"
+forms start form order for new_customer: 'Customer'
+forms ok form order for new_customer: 'Customer'
+forms start form order for new_ticket: 'Ticket'
+forms ok form order for new_ticket: 'Ticket'
+forms start form order for new_comment: 'Comment'
+forms ok form order for new_comment: 'Comment'
app-shell start app icon (generated) new_supportdesk_icon
app-shell ok app icon (generated) new_supportdesk_icon
app-shell start app "Support Desk"
diff --git a/plugins/model-apps/scripts/tests/golden/plan.project-tracker.txt b/plugins/model-apps/scripts/tests/golden/plan.project-tracker.txt
index 86873591b..02be2c40a 100644
--- a/plugins/model-apps/scripts/tests/golden/plan.project-tracker.txt
+++ b/plugins/model-apps/scripts/tests/golden/plan.project-tracker.txt
@@ -5,6 +5,7 @@ data-model column new_project.new_status (Choice)
views view "Active Projects" for new_project
views enrich default views for new_project
forms form for new_project
+forms form order for new_project
app-shell app module "Project Tracker" + sitemap
app-shell app icon (generated) new_projecttracker_icon
pages finalize sitemap (genpage subareas)
diff --git a/plugins/model-apps/scripts/tests/golden/plan.support-desk.txt b/plugins/model-apps/scripts/tests/golden/plan.support-desk.txt
index 089c427ba..988b280f1 100644
--- a/plugins/model-apps/scripts/tests/golden/plan.support-desk.txt
+++ b/plugins/model-apps/scripts/tests/golden/plan.support-desk.txt
@@ -27,6 +27,9 @@ charts chart "Tickets by Status" (Column) for new_ticket
forms form for new_customer (sub-grids: new_ticket)
forms form for new_ticket (sub-grids: new_comment)
forms form for new_comment
+forms form order for new_customer
+forms form order for new_ticket
+forms form order for new_comment
app-shell app module "Support Desk" + sitemap
app-shell app icon (generated) new_supportdesk_icon
pages finalize sitemap (genpage subareas)
diff --git a/plugins/model-apps/scripts/tests/helpers/mock-sdk.js b/plugins/model-apps/scripts/tests/helpers/mock-sdk.js
index 7a4dc2b17..0727fa4c3 100644
--- a/plugins/model-apps/scripts/tests/helpers/mock-sdk.js
+++ b/plugins/model-apps/scripts/tests/helpers/mock-sdk.js
@@ -61,8 +61,15 @@ function makeSimpleMockSdk() {
updateRecord: async () => undefined,
addSolutionComponent: async () => undefined,
publishArtifact: async (type, id) => ({ type, id, shipped: true, publish: { kind: 'verified' } }),
+ // A form's <DisplayConditions> as a new form carries them (Order 0, offered to everyone). The forms
+ // phase reads them to set each table's Main Form Set order (AB#6736948), and writes only the forms
+ // that are not yet in place — so a table with one Main form costs no write.
+ getFormSecurityRoles: async () => ({ everyone: true, fallbackForm: true, order: 0 }),
+ setFormSecurityRoles: async (formId, opts) => { calls.push(['setFormSecurityRoles', formId, opts]); },
getAiReadiness: async (opts) => { calls.push(['getAiReadiness', opts]); return { enabled: true }; },
- setAppAiFeatures: async (appUnique, flags, opts) => { calls.push(['setAppAiFeatures', appUnique, flags, opts]); return { applied: Object.keys(flags).filter((k) => flags[k]), skipped: [] }; },
+ // The real SDK writes every requested value (Off included) and lists each one it proves; the
+ // build encodes flags to setting values first, so no feature arrives here as a falsy boolean.
+ setAppAiFeatures: async (appUnique, flags, opts) => { calls.push(['setAppAiFeatures', appUnique, flags, opts]); return { applied: Object.keys(flags), skipped: [] }; },
configureRowSummary: async (promptSpec, opts) => { calls.push(['configureRowSummary', promptSpec, opts]); return { modelId: 'model-' + promptSpec.entityLogicalName, aiSkillConfigId: 'skill-' + promptSpec.entityLogicalName }; },
// Task 15: teardown SDK methods
resolveArtifact: async (kind, identity) => { calls.push(['resolveArtifact', kind, identity]); return []; },
diff --git a/plugins/model-apps/scripts/tests/hydrate-spec.test.js b/plugins/model-apps/scripts/tests/hydrate-spec.test.js
index faf12c4d7..3f8489951 100644
--- a/plugins/model-apps/scripts/tests/hydrate-spec.test.js
+++ b/plugins/model-apps/scripts/tests/hydrate-spec.test.js
@@ -161,7 +161,13 @@ test('hydrateSpec preserves entity + URL subareas and icons; omits a DashBoard w
test('hydrateSpec round-trips a DashBoard subarea + dashboards[] (id-passthrough tiles) when a dashboards reader is present', async () => {
const read = deployedRead();
- read.dashboards = async () => [{ id: 'D-1', name: 'Ops Overview', tiles: [
+ // The sitemap stores the id braced and upper-cased, and the dashboards reader hands it back as read
+ // (lower-cased, braces kept); the pin is written bare and lower-case.
+ const DASH = '280948EC-7BBB-5279-B106-2BDD09451A3A';
+ const app = await read.app();
+ app.siteMap.areas[0].groups[0].subAreas.find((s) => s.type === 'DashBoard').dashboardId = `{${DASH}}`;
+ read.app = async () => app;
+ read.dashboards = async () => [{ id: `{${DASH}}`.toLowerCase(), name: 'Ops Overview', tiles: [
{ type: 'chart', name: 'Orders by Status', entity: 'new_order', viewId: 'v1', visualizationId: 'c1' },
{ type: 'list', name: 'Active Orders', entity: 'new_order', viewId: 'v1' },
] }];
@@ -172,6 +178,9 @@ test('hydrateSpec round-trips a DashBoard subarea + dashboards[] (id-passthrough
// dashboards[] reconstructed with the id-passthrough tiles
assert.strictEqual(spec.dashboards.length, 1);
assert.strictEqual(spec.dashboards[0].name, 'Ops Overview');
+ // AB#6726727: pinned to the dashboard it was read from, so a rename in the designer cannot turn a
+ // rebuild into a second, stale-named dashboard.
+ assert.strictEqual(spec.dashboards[0].dashboardId, DASH.toLowerCase());
assert.deepStrictEqual(spec.dashboards[0].tiles[0], { type: 'chart', name: 'Orders by Status', entity: 'new_order', viewId: 'v1', visualizationId: 'c1' });
// and the whole spec still validates (id-based tiles need no declared views[]/charts[])
const r = validateAppSpec(spec);
@@ -313,7 +322,7 @@ test('an UNDECLARED web-resource subarea still validates — it is a live/OOB re
solution: { uniqueName: 'S', publisherPrefix: 'new' },
app: { name: 'A' },
entities: [{ schemaName: 'new_o', displayName: 'O', primaryAttribute: { schemaName: 'new_name', displayName: 'N' }, columns: [] }],
- appShell: { areas: [{ title: 'M', groups: [{ title: 'G', subAreas: [{ title: 'Home', url: '$webresource:new_homepage.html' }] }] }] },
+ appShell: { areas: [{ label: 'M', groups: [{ label: 'G', subAreas: [{ title: 'Home', url: '$webresource:new_homepage.html' }] }] }] },
};
const v = validateAppSpec(spec, { profile: 'plan' });
assert.strictEqual(v.ok, true, 'validation errors: ' + JSON.stringify(v.errors));
diff --git a/plugins/model-apps/scripts/tests/lint-app-spec.test.js b/plugins/model-apps/scripts/tests/lint-app-spec.test.js
index 73fe6a23c..59967f10f 100644
--- a/plugins/model-apps/scripts/tests/lint-app-spec.test.js
+++ b/plugins/model-apps/scripts/tests/lint-app-spec.test.js
@@ -399,3 +399,74 @@ test('CLI rejects prototype-named flags that never become own properties', () =>
assert.match(out.stderr, /unknown flag\(s\): --(__proto__|constructor)/);
}
});
+
+// #631. The key names differ by level — areas and groups take `label`, subAreas take `title` — and a
+// key the build does not read was accepted and dropped, so an area written with `title` deployed
+// untitled while this CLI, the build and --verify all reported success. Reproduced here with the
+// reporter's own shape and command.
+test('#631: `title` on an area or group fails lint and names `label`', () => {
+ const s = good();
+ s.appShell = { areas: [{ title: 'Main', groups: [{ title: 'Smoke', subAreas: [{ entity: 'c_order' }] }] }] };
+ const r = lintSpec(s);
+ assert.strictEqual(r.ok, false, 'must not lint clean');
+ assert.ok(r.errors.some((e) => /sitemap area "Main": unknown key 'title' — did you mean `label`\?/.test(e)), JSON.stringify(r.errors));
+ assert.ok(r.errors.some((e) => /sitemap group "Smoke" in area "Main": unknown key 'title' — did you mean `label`\?/.test(e)), JSON.stringify(r.errors));
+
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'lint631-'));
+ try {
+ fs.writeFileSync(path.join(dir, 'app-spec.json'), JSON.stringify(s));
+ let out;
+ try {
+ out = { code: 0, stdout: execFileSync(process.execPath, [CLI, '--spec', '@app-spec.json', '--profile', 'plan', '--json'], { cwd: dir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }) };
+ } catch (err) {
+ out = { code: err.status, stdout: String(err.stdout || '') };
+ }
+ assert.notStrictEqual(out.code, 0, 'the CLI must exit non-zero');
+ assert.match(out.stdout, /unknown key 'title'/);
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test('#631: the other likely mix-ups name their fix, and every key the build reads is accepted', () => {
+ const s = good();
+ s.appShell = { areas: [{ label: 'Main', groups: [{ label: 'G', icon: 'x.png', subAreas: [{ label: 'Orders', entity: 'c_order' }] }] }] };
+ const r = lintSpec(s);
+ assert.ok(r.errors.some((e) => /sitemap subArea "Orders" in group "G": unknown key 'label' — did you mean `title`\?/.test(e)), JSON.stringify(r.errors));
+ assert.ok(r.errors.some((e) => /sitemap group "G" in area "Main": unknown key 'icon' — a sitemap group has no icon/.test(e)), JSON.stringify(r.errors));
+
+ const ok = good();
+ ok.appShell = { areas: [{ label: 'Main', icon: '/_imgs/area.png', vectorIcon: '/WebResources/c_/icons/a.svg', iconDescription: 'a stack of papers',
+ groups: [{ label: 'G', iconDescription: 'a folder', subAreas: [
+ { title: 'Orders', entity: 'c_order', icon: '/_imgs/o.png', vectorIcon: '/WebResources/c_/icons/o.svg', iconDescription: 'a receipt' },
+ { title: 'Help', url: 'https://contoso.example/help' },
+ ] }] }] };
+ const clean = lintSpec(ok);
+ assert.ok(!clean.errors.some((e) => /unknown key/.test(e)), JSON.stringify(clean.errors));
+});
+
+// AB#6726727: a downloaded dashboard carries the id it was read from (edit-snapshot, like pages[].pageId).
+// It must be a GUID, and two entries cannot pin one dashboard — both nav entries would bind to it.
+test('dashboards[].dashboardId must be a distinct GUID; a braced one is accepted, a lone brace is not', () => {
+ const withDashboards = (dashboards) => {
+ const s = good();
+ s.views = [{ entity: 'c_order', name: 'All Orders', columns: ['c_name'] }];
+ s.dashboards = dashboards;
+ return lintSpec(s);
+ };
+ const tile = [{ type: 'list', view: 'All Orders' }];
+ const bad = withDashboards([{ name: 'Ops', dashboardId: 'd-1', tiles: tile }]);
+ assert.ok(bad.errors.some((e) => /dashboard 'Ops': dashboardId must be a GUID/.test(e)), JSON.stringify(bad.errors));
+ const dup = withDashboards([
+ { name: 'Ops', dashboardId: 'aaaa1111-2222-3333-4444-555566667777', tiles: tile },
+ { name: 'Other', dashboardId: '{AAAA1111-2222-3333-4444-555566667777}', tiles: tile },
+ ]);
+ assert.ok(dup.errors.some((e) => /dashboard 'Other': has the same dashboardId as dashboard 'Ops'/.test(e)), JSON.stringify(dup.errors));
+ const ok = withDashboards([{ name: 'Ops', dashboardId: '{AAAA1111-2222-3333-4444-555566667777}', tiles: tile }]);
+ assert.ok(!ok.errors.some((e) => /dashboardId/.test(e)), JSON.stringify(ok.errors));
+ // Both braces or none: an id with a lone brace is malformed, not one to bind a dashboard to.
+ for (const lone of ['{aaaa1111-2222-3333-4444-555566667777', 'aaaa1111-2222-3333-4444-555566667777}', '{{aaaa1111-2222-3333-4444-555566667777}}']) {
+ const r = withDashboards([{ name: 'Ops', dashboardId: lone, tiles: tile }]);
+ assert.ok(r.errors.some((e) => /dashboard 'Ops': dashboardId must be a GUID/.test(e)), `${lone}: ${JSON.stringify(r.errors)}`);
+ }
+});
diff --git a/plugins/model-apps/scripts/tests/sdk-build.test.js b/plugins/model-apps/scripts/tests/sdk-build.test.js
index 89ab1e24a..5d6ab2517 100644
--- a/plugins/model-apps/scripts/tests/sdk-build.test.js
+++ b/plugins/model-apps/scripts/tests/sdk-build.test.js
@@ -386,7 +386,9 @@ function mockSdk(opts = {}) {
},
setEntityIcon: async (logical, icons) => { calls.push({ name: 'setEntityIcon', args: [logical, icons] }); return { id: logical }; },
getAiReadiness: async (opts) => { calls.push({ name: 'getAiReadiness', args: [opts] }); return { enabled: true }; },
- setAppAiFeatures: async (appUnique, flags, opts) => { calls.push({ name: 'setAppAiFeatures', args: [appUnique, flags, opts] }); return { applied: Object.keys(flags).filter((k) => flags[k]), skipped: [] }; },
+ // The real SDK writes every requested value (Off included) and lists each one it proves; the
+ // build encodes flags to setting values first, so no feature arrives here as a falsy boolean.
+ setAppAiFeatures: async (appUnique, flags, opts) => { calls.push({ name: 'setAppAiFeatures', args: [appUnique, flags, opts] }); return { applied: Object.keys(flags), skipped: [] }; },
configureRowSummary: async (promptSpec, opts) => { calls.push({ name: 'configureRowSummary', args: [promptSpec, opts] }); return { modelId: 'model-' + promptSpec.entityLogicalName, aiSkillConfigId: 'skill-' + promptSpec.entityLogicalName }; },
// Security authoring. createPersonaRole echoes a RoleResult; opts.roleConflict simulates the SEC-1
// fail-closed (a hand-built same-name role) so the security phase's BuildHalt is testable. opts.rolesExist
@@ -626,6 +628,59 @@ const ROUTING = 'Dispatch work: assigning and rescheduling tickets. Prefer My Wo
const appShellPhases = ['solution', 'data-model', 'app-shell'];
const appCalls = (calls, name, pred = () => true) => find(calls, name).filter((c) => c.args[0] === 'app' && pred(c));
+// AB#6726727: an existing app's sitemap is written ONTO its live nodes. Handing the SDK appDef's bag-less
+// tree rebuilt every live node from scratch (new ids, designer defaults for a NEW node), which is how an
+// unrelated edit turned a designer-made dashboard entry into a placeholder-icon one.
+const LIVE_SITEMAP = () => ({
+ areas: [{ id: 'area_live', title: 'Main', bag: { a: [['Id', 'area_live'], ['ResourceId', 'Contoso.Area']], c: [{ i: 0, node: { n: 'Titles', a: [], c: [{ n: 'Title', a: [['LCID', '1033'], ['Title', 'Main']], c: [] }] } }] },
+ groups: [{ id: 'grp_live', title: 'Records', bag: { a: [['Id', 'grp_live'], ['IsProfile', 'false']], c: [{ i: 0, node: { n: 'Titles', a: [], c: [{ n: 'Title', a: [['LCID', '1033'], ['Title', 'Records']], c: [] }] } }] },
+ subAreas: [{ id: 'cust_live', type: 'Entity', entity: 'new_customer', title: 'Our customers',
+ bag: { a: [['Id', 'cust_live'], ['Entity', 'new_customer'], ['Client', 'All,Web'], ['AvailableOffline', 'false']], c: [{ i: 0, node: { n: 'Titles', a: [], c: [{ n: 'Title', a: [['LCID', '1033'], ['Title', 'Our customers']], c: [] }] } }] } }] }] }],
+});
+const siteMapWrite = (calls) => appCalls(calls, 'updateElement', (c) => c.args[2] === '/siteMap')[0];
+
+test('app-shell: an existing app\u2019s sitemap is written onto its live nodes, not in place of them', async () => {
+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingSitemap: LIVE_SITEMAP() });
+ const warnings = [];
+ await runSdkBuild(makeSpec(), { sdk, apply: true, phases: appShellPhases, warn: (m) => warnings.push(m) });
+ const written = siteMapWrite(calls).args[3];
+ const [area] = written.areas;
+ const [group] = area.groups;
+ const [sub] = group.subAreas;
+ assert.deepStrictEqual([area.id, group.id, sub.id], ['area_live', 'grp_live', 'cust_live'], 'live ids kept');
+ assert.deepStrictEqual(sub.bag, LIVE_SITEMAP().areas[0].groups[0].subAreas[0].bag, 'everything the spec cannot describe rides along');
+ assert.deepStrictEqual(area.bag, LIVE_SITEMAP().areas[0].bag);
+ assert.strictEqual(sub.title, 'Customers', 'the spec still sets what it describes');
+ // With no baseline the spec wins — and the build says so instead of doing it silently.
+ assert.ok(warnings.some((w) => /nav entry "Our customers": title changes from 'Our customers' to the spec's 'Customers'/.test(w)), JSON.stringify(warnings));
+});
+
+test('app-shell: with a baseline, a nav title renamed in the designer since is kept, and reported', async () => {
+ // The baseline (last applied / downloaded) said 'Customers'; the spec still does; the designer has
+ // since renamed the entry to 'Our customers'. The spec is stale for that field, not asking for a change.
+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingSitemap: LIVE_SITEMAP() });
+ const warnings = [];
+ await runSdkBuild(makeSpec(), { sdk, apply: true, phases: appShellPhases, baselineSpec: makeSpec(), warn: (m) => warnings.push(m) });
+ assert.strictEqual(siteMapWrite(calls).args[3].areas[0].groups[0].subAreas[0].title, 'Our customers');
+ assert.ok(warnings.some((w) => /kept the environment's title 'Our customers'/.test(w)), JSON.stringify(warnings));
+ // A title the SPEC changed since the baseline is applied, without a word.
+ const { sdk: sdk2, calls: calls2 } = mockSdk({ artifactsExist: true, existingSitemap: LIVE_SITEMAP() });
+ const edited = makeSpec();
+ edited.appShell.areas[0].groups[0].subAreas[0].title = 'Clients';
+ const quiet = [];
+ await runSdkBuild(edited, { sdk: sdk2, apply: true, phases: appShellPhases, baselineSpec: makeSpec(), warn: (m) => quiet.push(m) });
+ assert.strictEqual(siteMapWrite(calls2).args[3].areas[0].groups[0].subAreas[0].title, 'Clients');
+ assert.ok(!quiet.some((w) => /nav entry/.test(w)), JSON.stringify(quiet));
+});
+
+test('app-shell: a dashboard entry is written with the designer\u2019s launcher Url', () => {
+ const spec = makeSpec();
+ spec.dashboards = [{ name: 'Ops', tiles: [{ type: 'list', view: 'Active Tickets' }] }];
+ spec.appShell.areas[0].groups[0].subAreas.push({ dashboard: 'Ops', title: 'Operations' });
+ const sub = appDef(spec, { dashboards: { Ops: 'dash-1' } }).siteMap.areas[0].groups[0].subAreas[1];
+ assert.deepStrictEqual(sub, { id: 'sub_0_0_1', title: 'Operations', type: 'DashBoard', dashboardId: 'dash-1', dashboardUrl: '/workplace/home_dashboards.aspx' });
+});
+
test('#583 appDef carries app.aiDescription only when the spec sets one', () => {
const built = { forms: {}, views: {}, charts: {}, dashboards: {} };
assert.ok(!('aiDescription' in appDef(makeSpec(), built)));
@@ -671,7 +726,9 @@ test('#583 an existing app whose routing description already matches is left alo
test('#583 a spec with no routing description never reads or writes one', async () => {
const { sdk, calls } = mockSdk({ artifactsExist: true, existingAppAiDescription: 'Written by the platform.' });
await runSdkBuild(makeSpec(), { sdk, apply: true, phases: appShellPhases });
- assert.strictEqual(appCalls(calls, 'getArtifact').length, 0, 'not even read');
+ // One read, for the live sitemap the rewrite re-attaches to (AB#6726727) — the routing description
+ // is never looked at: applyAppAiDescription returns before reading when the spec sets none.
+ assert.strictEqual(appCalls(calls, 'getArtifact').length, 1, 'read once, for the sitemap');
assert.strictEqual(appCalls(calls, 'updateElement', (c) => c.args[2] === '/aiDescription').length, 0);
assert.strictEqual(appCalls(calls, 'addElement', (c) => c.args[2] === '').length, 0);
});
@@ -700,6 +757,7 @@ test('#583 the deferred routing-description push refuses a copy holding an earli
await assert.rejects(runSdkBuild(spec, { sdk, apply: true, phases: appShellPhases }), (e) => {
assert.strictEqual(e.code, 'app-copy-unpushed-edits', e.message);
assert.match(e.message, /holds edits an earlier run did not push/);
+ assert.match(e.message, /To reset it, stop any other build or teardown using the \.maker-workspace directory \(or the --workspace one\), then delete everything in it except last-applied\.json and destructive-approval\.json, and re-run\./, 'the baseline and the approval record are kept');
return true;
});
assert.strictEqual(appCalls(calls, 'addElement', (c) => c.args[2] === '').length, 0, 'nothing applied');
@@ -769,7 +827,7 @@ test('#583 when the workspace copy cannot be reset, the halt names the workspace
sdk.dataverse = draftReader({ status: 200, body: { value: [{ componentstate: 1 }] } });
await assert.rejects(runSdkBuild(routingSpec(), { sdk, apply: true, phases: appShellPhases }), (e) => {
assert.strictEqual(e.code, 'app-header-unpublished', e.message);
- assert.match(e.message, /then re-run the build\. First delete the \.maker-workspace directory \(or the --workspace one\)/);
+ assert.match(e.message, /then re-run the build\. First reset the workspace, which still holds this run's unpushed copy of the app \(a re-run would refuse to overwrite it\): stop any other build or teardown using the \.maker-workspace directory \(or the --workspace one\), then delete everything in it except last-applied\.json and destructive-approval\.json\./);
return true;
});
});
@@ -953,6 +1011,25 @@ test('#583 any other thrown push error propagates unchanged, and resets the copy
assert.strictEqual(appCalls(dropped.calls, 'fetchArtifact', (c) => c.args[2] && c.args[2].overwrite === true).length, 1);
});
+// The vendored SDK refuses to push a copy an earlier plugin version projected and an interrupted build
+// left holding unpushed edits (workspace-projection-real-bundle.test.js pins the real refusal). From a real
+// build the halt names the manual reset, which starts by stopping every other run on the workspace: the
+// build does not overwrite the copy itself, because another build on the same workspace may hold newer edits.
+test('a push refused for an earlier version\u2019s workspace copy halts with the manual reset', async () => {
+ const { sdk, calls } = mockSdk({ artifactsExist: true });
+ const push = sdk.pushArtifact;
+ sdk.pushArtifact = async (t, id) => {
+ if (t !== 'app') return push(t, id);
+ calls.push({ name: 'pushArtifact', args: [t, id] });
+ throw Object.assign(new Error(`Refusing to push app '${id}': its workspace copy was produced by projection version 3, but this SDK produces version 5.`), { code: 'ARTIFACT_PROJECTION_STALE' });
+ };
+ await assert.rejects(runSdkBuild(makeSpec(), { sdk, apply: true, phases: appShellPhases }), (e) => {
+ assert.strictEqual(e.code, 'ARTIFACT_PROJECTION_STALE', e.message);
+ assert.match(e.message, /To reset it, stop any other build or teardown using the \.maker-workspace directory \(or the --workspace one\), then delete everything in it except last-applied\.json and destructive-approval\.json, and re-run/);
+ return true;
+ });
+});
+
test('#583 a returned push failure resets the copy, but a concurrent edit keeps it as the fence', async () => {
const withCode = (code, message) => ({ saved: false, shipped: false, publish: { kind: 'notRequested' }, error: Object.assign(new Error(message), code ? { code } : {}) });
for (const [what, result, haltCode, resets] of [
@@ -1653,6 +1730,59 @@ test('dashboards: an existing dashboard is reused (no duplicate) and reported in
assert.ok(find(calls, 'resolveArtifact').some((c) => c.args[0] === 'dashboard' && c.args[1].name === 'Ops'), 'discovered via resolveArtifact');
});
+// AB#6726727: a downloaded dashboard carries the id it was read from (dashboards[].dashboardId), and the
+// build binds it by that id first. Renamed in the designer since, the spec's name finds nothing — and the
+// name path would then create a SECOND dashboard under the old name and point the nav entry at it.
+const PINNED_DASH = '280948ec-7bbb-5279-b106-2bdd09451a3a';
+const answerPinned = (sdk, rows) => {
+ const base = sdk.queryRecords;
+ sdk.queryRecords = async (entity, o) => {
+ const m = entity === 'systemform' && /^formid eq ([0-9a-f-]{36})$/.exec((o && o.filter) || '');
+ if (m) return rows[m[1]] ? [rows[m[1]]] : [];
+ return base(entity, o);
+ };
+ return sdk;
+};
+const pinnedSpec = (pin = PINNED_DASH) => {
+ const spec = makeSpec();
+ spec.dashboards = [{ name: 'Command Center - Event operations', dashboardId: pin, tiles: [{ type: 'list', view: 'Active Tickets', name: 'Recent' }] }];
+ return spec;
+};
+
+test('dashboards: a pinned dashboardId is reused after a rename, and the name difference is reported', async () => {
+ const { sdk, calls } = mockSdk();
+ answerPinned(sdk, { [PINNED_DASH]: { formid: PINNED_DASH, name: 'Event operations', type: 0 } });
+ const warnings = [];
+ const result = await runSdkBuild(pinnedSpec(`{${PINNED_DASH.toUpperCase()}}`), { sdk, apply: true, warn: (m) => warnings.push(m) });
+ assert.strictEqual(result.created.dashboards['Command Center - Event operations'], PINNED_DASH);
+ assert.ok(!find(calls, 'createArtifact').some((c) => c.args[0] === 'dashboard'), 'no second, stale-named dashboard');
+ assert.ok(!find(calls, 'resolveArtifact').some((c) => c.args[0] === 'dashboard'), 'bound by id — the name is not looked up');
+ assert.ok(warnings.some((w) => /is now named 'Event operations'.*set the spec's name to 'Event operations'/.test(w)), JSON.stringify(warnings));
+ // Same name: nothing to report.
+ const quiet = [];
+ const { sdk: sdk2 } = mockSdk();
+ answerPinned(sdk2, { [PINNED_DASH]: { formid: PINNED_DASH, name: 'COMMAND CENTER - EVENT OPERATIONS ', type: 0 } });
+ await runSdkBuild(pinnedSpec(), { sdk: sdk2, apply: true, warn: (m) => quiet.push(m) });
+ assert.ok(!quiet.some((w) => /is now named/.test(w)), 'a name Dataverse compares equal is the same name');
+});
+
+test('dashboards: a pin this environment does not have falls back to the name (a spec downloaded elsewhere)', async () => {
+ const spec = pinnedSpec();
+ spec.dashboards[0].name = 'Ops';
+ const { sdk, calls } = mockSdk({ existingDashboards: ['Ops'] });
+ answerPinned(sdk, {});
+ const result = await runSdkBuild(spec, { sdk, apply: true });
+ assert.strictEqual(result.created.dashboards.Ops, 'dashboard-existing-Ops');
+ assert.ok(!find(calls, 'createArtifact').some((c) => c.args[0] === 'dashboard'));
+});
+
+test('dashboards: a pin that names a form, not a dashboard, halts instead of wiring the nav entry to it', async () => {
+ const { sdk, calls } = mockSdk();
+ answerPinned(sdk, { [PINNED_DASH]: { formid: PINNED_DASH, name: 'Account', type: 2 } });
+ await assert.rejects(runSdkBuild(pinnedSpec(), { sdk, apply: true }), /dashboardId 280948ec-7bbb-5279-b106-2bdd09451a3a is a type-2 form, not a dashboard/);
+ assert.ok(!find(calls, 'createArtifact').some((c) => c.args[0] === 'dashboard'));
+});
+
// Names are neither unique nor compared exactly, so the lookup can return several dashboards. Reusing
// the first one returned silently bound the app to an arbitrary one — possibly another app's. The app's
// own is the one its solution holds; when that does not single one out the build halts, creating nothing.
@@ -3552,7 +3682,9 @@ test('ai-features phase enables app features and configures summaries for candid
assert.ok(find(calls, 'configureRowSummary').length >= 1, 'configureRowSummary called for candidate table(s)');
const featureCall = find(calls, 'setAppAiFeatures')[0];
assert.ok(featureCall.args[0].includes('support'), 'app unique name derived from spec (contains app name slug)');
- assert.strictEqual(featureCall.args[1].formFill, true, 'formFill flag merged from spec.ai.appFeatures');
+ // Encoded by the build, not left to the SDK's boolean mapping (AB#6714731): On is '2' for every
+ // feature, and m365 stays at its platform default '0' unless the spec asks.
+ assert.deepStrictEqual(featureCall.args[1], { formFill: '2', nlSearch: '2', nlChart: '2', m365: '0' }, 'formFill flag merged from spec.ai.appFeatures, all encoded');
assert.ok(result.created.ai && result.created.ai.appFeatures, 'appFeatures populated on result');
assert.ok(result.created.ai.summaries && Object.keys(result.created.ai.summaries).length >= 1, 'summaries populated on result');
});
@@ -3865,6 +3997,47 @@ test('ai-features phase: a `skipped` feature the re-issue cannot recover is repo
assert.ok(!r.created.ai.appFeatures.applied.includes('nlSearch'), 'and it is NOT claimed as applied');
});
+test('ai-features phase: both writes hand the SDK each setting\u2019s value, never a boolean (AB#6714731)', async () => {
+ // The vendored SDK maps a boolean through a codec that knows only the form-fill family, so `true`
+ // reached NL grid search and M365 as '1' (Off) and NL charts as '1' (Auto). The build encodes
+ // every flag itself, and the SDK writes an explicit value verbatim — including on the
+ // post-publish re-issue, which is the write that actually lands on a new app.
+ const { sdk, calls } = withAiResults([
+ { applied: ['formFill'], skipped: [], notPersisted: ['nlSearch', 'nlChart', 'm365'], unverified: [], failed: [], outcomes: [] },
+ { applied: ['nlSearch', 'nlChart', 'm365'], skipped: [], notPersisted: [], unverified: [], failed: [], outcomes: [] },
+ ]);
+ const spec = makeSpec({ ai: { appFeatures: { nlSearch: true, nlChart: false, m365: false }, summaries: { default: 'off' } } });
+ await runSdkBuild(spec, { sdk, apply: true, phases: ['app-shell', 'ai-features'] });
+ const writes = find(calls, 'setAppAiFeatures');
+ assert.strictEqual(writes.length, 2);
+ assert.deepStrictEqual(writes[0].args[1], { formFill: '2', nlSearch: '2', nlChart: '0', m365: '1' });
+ assert.deepStrictEqual(writes[1].args[1], { nlSearch: '2', nlChart: '0', m365: '1' }, 'the re-issue is encoded too');
+ // An explicit integer is the caller's own setting value and passes through untouched.
+ const { sdk: sdk2, calls: calls2 } = withAiResults([{ applied: ['formFill', 'nlSearch', 'nlChart', 'm365'], skipped: [], notPersisted: [], unverified: [], failed: [], outcomes: [] }]);
+ await runSdkBuild(makeSpec({ ai: { appFeatures: { nlChart: 1, m365: 2 }, summaries: { default: 'off' } } }), { sdk: sdk2, apply: true, phases: ['app-shell', 'ai-features'] });
+ assert.deepStrictEqual(find(calls2, 'setAppAiFeatures')[0].args[1], { formFill: '2', nlSearch: '2', nlChart: '1', m365: '2' });
+});
+
+test('ai-features phase: an OFF write that did not persist is NOT PERSISTED, not ADMIN GATE OFF', async () => {
+ // The SDK labels any non-zero request as enabling, so grid search Off ('1') with its org gate off
+ // came back `skipped`, and the build told the operator an admin must enable the feature — for a
+ // request to turn it off.
+ const sdkSkip = {
+ applied: [], skipped: ['nlSearch'], notPersisted: [], unverified: [], failed: [],
+ outcomes: [{ feature: 'nlSearch', setting: 'NLGridSearchSetting', requestedValue: '1', status: 'skipped', appOverrideExists: false,
+ reason: "the org readiness gate 'EnableNLGridSearch' reads 'false', so an environment admin must enable it before this app can turn the feature on" }],
+ };
+ const { sdk, calls } = withAiResults([sdkSkip, { applied: [], skipped: [], notPersisted: [], unverified: [], failed: [], outcomes: [] }]);
+ const events = [];
+ const r = await runSdkBuild(makeSpec({ ai: { appFeatures: { nlSearch: false }, summaries: { default: 'off' } } }), { sdk, apply: true, phases: ['app-shell', 'ai-features'], emit: (e) => events.push(e) });
+ assert.strictEqual(find(calls, 'setAppAiFeatures').length, 2, 'still re-issued after publish');
+ const warnings = events.filter((e) => e.phase === 'ai-features' && e.status === 'skip').map((e) => e.label);
+ assert.ok(warnings.some((l) => /NOT PERSISTED: nlSearch/.test(l)), JSON.stringify(warnings));
+ assert.ok(!warnings.some((l) => /ADMIN GATE OFF|must enable/.test(l)), JSON.stringify(warnings));
+ const af = r.created.ai.appFeatures;
+ assert.deepStrictEqual([af.skipped, af.notPersisted], [[], ['nlSearch']], 'the --json result agrees with the report');
+});
+
test('ai-features phase: passes a raised verify budget so a fresh app module is not falsely reported', async () => {
// Regression guard for a live false `notPersisted`: this phase runs moments after app-shell CREATED
// the app module, and the SDK's default budget (4 attempts / 500ms linear ~= 3s) expired before the
diff --git a/plugins/model-apps/scripts/tests/sdk-http-client.test.js b/plugins/model-apps/scripts/tests/sdk-http-client.test.js
index f2a696aee..83b43dccb 100644
--- a/plugins/model-apps/scripts/tests/sdk-http-client.test.js
+++ b/plugins/model-apps/scripts/tests/sdk-http-client.test.js
@@ -1,7 +1,7 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert');
-const { createAzHttpClient } = require('../lib/sdk-http-client.js');
+const { createAzHttpClient, retryAfterMs, isBatchThrottled, batchRetryAfterMs, RETRY_AFTER_CAP_MS } = require('../lib/sdk-http-client.js');
// A fake transport that records the last request and returns a scripted response.
function fakeTransport(scripted) {
@@ -147,6 +147,41 @@ test('does NOT retry a RECORD delete on a network error either (single delete, n
assert.strictEqual(calls, 1, 'exactly one record DELETE was sent (no network-error retry)');
});
+// A record delete that LOST A SQL DEADLOCK is the exception: the server answered that it rolled the
+// transaction back, so nothing is in flight to race and nothing was deleted. Captured live on a
+// teardown's process-flow delete.
+const DEADLOCK_500 = { statusCode: 500, headers: {}, body: JSON.stringify({ error: { code: '0x80044150', message: ' Sql error: Generic SQL error. CRM ErrorCode: -2147204784 Sql ErrorCode: -2146232060 Sql Number: 1205' } }) };
+test('DOES re-send a RECORD delete that lost a SQL deadlock (1205), at most three times, 1 s / 2 s / 4 s', async () => {
+ const slept = [];
+ const { request, calls } = fakeTransport(() => (calls.length <= 2 ? DEADLOCK_500 : { statusCode: 204, headers: {}, body: '' }));
+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request, sleep: async (ms) => { slept.push(ms); } });
+ const res = await http.delete('https://org.crm.dynamics.com/api/data/v9.0/workflows(1)');
+ assert.strictEqual(res.status, 204);
+ assert.strictEqual(calls.length, 3);
+ assert.deepStrictEqual(slept, [1000, 2000]);
+
+ const { request: always, calls: calls2 } = fakeTransport(DEADLOCK_500);
+ const slept2 = [];
+ const http2 = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request: always, sleep: async (ms) => { slept2.push(ms); } });
+ const gaveUp = await http2.delete('https://org.crm.dynamics.com/api/data/v9.0/workflows(1)');
+ assert.strictEqual(gaveUp.status, 500, 'after the last re-send the deadlock surfaces unchanged');
+ assert.strictEqual(calls2.length, 4, 'four attempts in all');
+ assert.deepStrictEqual(slept2, [1000, 2000, 4000]);
+});
+
+test('a 500 that is NOT a deadlock victim, or a $batch, still gets exactly one record delete', async () => {
+ for (const body of ['', JSON.stringify({ error: { message: 'Sql error: Generic SQL error. Sql Number: 12050' } }), JSON.stringify({ error: { message: 'The transaction was rolled back or committed' } })]) {
+ const { request, calls } = fakeTransport({ statusCode: 500, headers: {}, body });
+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request, sleep: async () => {} });
+ await http.delete('https://org.crm.dynamics.com/api/data/v9.0/workflows(1)');
+ assert.strictEqual(calls.length, 1, `not re-sent for ${JSON.stringify(body)}`);
+ }
+ const { request, calls } = fakeTransport(DEADLOCK_500);
+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request, sleep: async () => {} });
+ await http.postRaw('https://org.crm.dynamics.com/api/data/v9.0/$batch', '--b\r\n', { headers: { 'Content-Type': 'multipart/mixed;boundary=b' } });
+ assert.strictEqual(calls.length, 1, 'a $batch answer that does not show its operations\u2019 results is not re-sent');
+});
+
test('DOES retry a METADATA delete (EntityDefinitions) on a network error — async-idempotent, gets cosmetic 404', async () => {
const { request, calls } = fakeTransport(() =>
calls.length <= 1 ? { error: 'ETIMEDOUT' } : { statusCode: 404, headers: {}, body: '' }
@@ -307,6 +342,245 @@ test('postRaw does NOT retry a $batch on a network error either', async () => {
assert.strictEqual(calls.length, 1, 'an ambiguous batch outcome is never re-issued blindly');
});
+// An ANSWERED batch whose change set lost a SQL deadlock is the exception, when the batch is made of
+// conditional deletes: a change set is atomic, so the answer proves nothing in it committed, and a second
+// send meets the rows as the first did or is refused with 412. Captured live on a teardown's app delete
+// (the app and its sitemap in one change set); the whole teardown stopped on it with nothing removed.
+const batchAnswer = (...parts) => [
+ '--batchresponse_b1',
+ 'Content-Type: multipart/mixed; boundary=changesetresponse_c1',
+ '',
+ ...parts.flatMap(([status, json], i) => [
+ '--changesetresponse_c1', 'Content-Type: application/http', 'Content-Transfer-Encoding: binary', `Content-ID: ${i + 1}`, '',
+ status, 'REQ_ID: 00000000-0000-0000-0000-000000000000', 'Content-Type: application/json; odata.metadata=minimal', 'OData-Version: 4.0', '',
+ json || '',
+ ]),
+ '--changesetresponse_c1--',
+ '--batchresponse_b1--',
+ '',
+].join('\r\n');
+const DEADLOCK_PART = ['HTTP/1.1 500 Internal Server Error', JSON.stringify({ error: { code: '0x80044150', message: ' Sql error: Generic SQL error. CRM ErrorCode: -2147204784 Sql ErrorCode: -2146232060 Sql Number: 1205' } })];
+const BATCH_DEADLOCK_500 = { statusCode: 500, headers: {}, body: batchAnswer(DEADLOCK_PART) };
+// A batch request as the SDK renders one: `ops` are [method, url, extra header lines].
+const batchRequest = (...ops) => [
+ '--batch_b', 'Content-Type: multipart/mixed;boundary=changeset_c', '',
+ ...ops.flatMap(([method, url, headers = []], i) => ['--changeset_c', 'Content-Type: application/http', 'Content-Transfer-Encoding: binary', `Content-ID: ${i + 1}`, '', `${method} ${url} HTTP/1.1`, ...headers, '']),
+ '--changeset_c--', '--batch_b--', '',
+].join('\r\n');
+// The SDK's atomic app delete: the app and its sitemap, each conditioned on the row version it read.
+const APP_DELETE = batchRequest(
+ ['DELETE', 'https://org.crm.dynamics.com/api/data/v9.0/appmodules(11111111-1111-1111-1111-111111111111)', ['If-Match: W/"1001"']],
+ ['DELETE', 'https://org.crm.dynamics.com/api/data/v9.0/sitemaps(33333333-3333-3333-3333-333333333333)', ['If-Match: W/"2002"']],
+);
+const postBatch = (http, body = APP_DELETE) => http.postRaw('https://org.crm.dynamics.com/api/data/v9.0/$batch', body, { headers: { 'Content-Type': 'multipart/mixed;boundary=batch_b' } });
+
+test('postRaw DOES re-send a $batch whose change set lost a SQL deadlock, at most three times, 1 s / 2 s / 4 s', async () => {
+ const slept = [];
+ const { request, calls } = fakeTransport(() => (calls.length <= 1 ? BATCH_DEADLOCK_500 : { statusCode: 200, headers: {}, body: BATCH_RESPONSE }));
+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request, sleep: async (ms) => { slept.push(ms); } });
+ const res = await postBatch(http);
+ assert.strictEqual(res.status, 200);
+ assert.strictEqual(res.body, BATCH_RESPONSE, 'the SDK reads the re-sent batch\u2019s own answer, raw');
+ assert.strictEqual(calls.length, 2);
+ assert.strictEqual(calls[1].body, calls[0].body, 'the same change set, byte for byte');
+ assert.deepStrictEqual(slept, [1000]);
+
+ const { request: always, calls: calls2 } = fakeTransport(BATCH_DEADLOCK_500);
+ const slept2 = [];
+ const http2 = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request: always, sleep: async (ms) => { slept2.push(ms); } });
+ const gaveUp = await postBatch(http2);
+ assert.strictEqual(gaveUp.status, 500, 'after the last re-send the deadlock surfaces unchanged');
+ assert.strictEqual(gaveUp.body, BATCH_DEADLOCK_500.body);
+ assert.strictEqual(calls2.length, 4, 'four attempts in all');
+ assert.deepStrictEqual(slept2, [1000, 2000, 4000]);
+});
+
+test('postRaw re-sends a $batch ONLY when its answer proves every operation was rolled back as a deadlock victim', async () => {
+ const answers = {
+ 'an operation that committed beside the deadlocked one': batchAnswer(['HTTP/1.1 204 No Content'], DEADLOCK_PART),
+ // A nested SQL error can repeat the marker, so counting markers alone is not the proof: a committed
+ // operation beside it still means the batch must not be sent again.
+ 'an operation that committed beside a failure that names the deadlock twice': batchAnswer(['HTTP/1.1 204 No Content'], ['HTTP/1.1 500 Internal Server Error', JSON.stringify({ error: { message: 'Sql Number: 1205 (inner: Sql Number: 1205)' } })]),
+ 'a failure that is not a deadlock': batchAnswer(['HTTP/1.1 412 Precondition Failed', JSON.stringify({ error: { code: '0x80060882', message: 'The version of the existing record doesn\'t match' } })]),
+ 'a 500 without the deadlock number': batchAnswer(['HTTP/1.1 500 Internal Server Error', JSON.stringify({ error: { message: 'Sql error: Generic SQL error. Sql Number: 12050' } })]),
+ 'two failed operations, only one of them a deadlock': batchAnswer(DEADLOCK_PART, ['HTTP/1.1 500 Internal Server Error', JSON.stringify({ error: { message: 'Generic SQL error' } })]),
+ // Each operation must name the deadlock in its OWN part: one part repeating the marker proves nothing
+ // about the other (independent operations can be answered separately).
+ 'the marker twice in one operation, none in the other': batchAnswer(['HTTP/1.1 500 Internal Server Error', JSON.stringify({ error: { message: 'Sql Number: 1205 (inner: Sql Number: 1205)' } })], ['HTTP/1.1 500 Internal Server Error', JSON.stringify({ error: { message: 'Generic SQL error' } })]),
+ 'a truncated answer (no closing delimiter)': batchAnswer(DEADLOCK_PART).replace(/--batchresponse_b1--\r\n$/, ''),
+ // Only a 500 is a rolled-back deadlock victim; another status whose message quotes one is not.
+ 'another status whose error quotes the deadlock': batchAnswer(['HTTP/1.1 400 Bad Request', JSON.stringify({ error: { message: 'Validation failed (inner: Sql Number: 1205)' } })]),
+ 'a complete answer with no operation results': '--batchresponse_b1\r\n--batchresponse_b1--\r\n',
+ };
+ for (const [what, body] of Object.entries(answers)) {
+ const { request, calls } = fakeTransport({ statusCode: 500, headers: {}, body });
+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request, sleep: async () => {} });
+ const res = await postBatch(http);
+ assert.strictEqual(calls.length, 1, `not re-sent: ${what}`);
+ assert.strictEqual(res.body, body, `and the answer reaches the SDK as it came: ${what}`);
+ }
+ // A batch that is not made of conditional deletes is never sent again, whatever its answer. The SDK
+ // updates a generative page's files with `If-Match: *` after checking their versions itself: a second
+ // send after the backoff would skip that check and overwrite another maker's edit.
+ const requests = {
+ 'unconditional writes (a generative page update)': batchRequest(['PATCH', 'https://org.crm.dynamics.com/api/data/v9.0/uxagentprojectfiles(1)', ['If-Match: *']]),
+ 'a DELETE with no condition (the SDK\u2019s create rollback)': batchRequest(['DELETE', 'https://org.crm.dynamics.com/api/data/v9.0/appmodules(1)']),
+ 'a DELETE conditioned on anything': batchRequest(['DELETE', 'https://org.crm.dynamics.com/api/data/v9.0/appmodules(1)', ['If-Match: *']]),
+ 'a conditional DELETE beside a write': batchRequest(['DELETE', 'https://org.crm.dynamics.com/api/data/v9.0/appmodules(1)', ['If-Match: W/"1"']], ['POST', 'https://org.crm.dynamics.com/api/data/v9.0/sitemaps', []]),
+ // Deliberately only DELETEs: a write conditioned on its own row can still rest on rows the batch does
+ // not condition on, which a second send would not look at again.
+ 'writes each conditioned on a row version': batchRequest(['PATCH', 'https://org.crm.dynamics.com/api/data/v9.0/appmodules(1)', ['If-Match: W/"1"']], ['PATCH', 'https://org.crm.dynamics.com/api/data/v9.0/sitemaps(2)', ['If-Match: W/"2"']]),
+ 'no operation at all': '--b\r\n',
+ };
+ for (const [what, body] of Object.entries(requests)) {
+ const { request, calls } = fakeTransport(BATCH_DEADLOCK_500);
+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request, sleep: async () => {} });
+ await postBatch(http, body);
+ assert.strictEqual(calls.length, 1, `not re-sent: ${what}`);
+ }
+ // The same deadlocked answer to anything but a $batch or a record delete is left to the status retry.
+ const { request, calls } = fakeTransport(() => (calls.length <= 1 ? BATCH_DEADLOCK_500 : { statusCode: 200, headers: {}, body: '{}' }));
+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request, sleep: async () => {} });
+ await http.get('https://org.crm.dynamics.com/api/data/v9.0/accounts');
+ assert.strictEqual(calls.length, 2, 'a GET keeps its ordinary transient retry');
+});
+
+// A 429 is the other answer that proves a delete did not run: the server refused to START it. Captured live
+// at the end of two teardowns — the solution delete, refused while the platform was still finishing the
+// teardown's own table delete — and both teardowns stopped with the solution left behind.
+const UNINSTALL_429 = { statusCode: 429, headers: {}, body: JSON.stringify({ error: { code: '0x80071151', message: 'Cannot start the requested operation [Uninstall] because there is another [EntityCustomization] running at this moment. Use Solution History for more details. -- The solution installation or removal failed due to the installation or removal of another solution at the same time. Please try again later.' } }) };
+test('DOES re-send a RECORD delete refused with 429 (it was never started), on the throttle schedule', async () => {
+ const slept = [];
+ const { request, calls } = fakeTransport(() => (calls.length <= 2 ? UNINSTALL_429 : { statusCode: 204, headers: {}, body: '' }));
+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request, random: () => 0.5, sleep: async (ms) => { slept.push(ms); } });
+ const res = await http.delete('https://org.crm.dynamics.com/api/data/v9.0/solutions(1)');
+ assert.strictEqual(res.status, 204);
+ assert.strictEqual(calls.length, 3);
+ assert.deepStrictEqual(slept, [1125, 2250], 'the jittered backoff every other throttled request gets');
+
+ const { request: always, calls: calls2 } = fakeTransport(UNINSTALL_429);
+ const http2 = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request: always, sleep: async () => {} });
+ const gaveUp = await http2.delete('https://org.crm.dynamics.com/api/data/v9.0/solutions(1)');
+ assert.strictEqual(gaveUp.status, 429, 'after the last attempt the refusal surfaces unchanged');
+ assert.strictEqual(gaveUp.body.error.code, '0x80071151');
+ assert.strictEqual(calls2.length, 6, 'six attempts in all, like any other throttled request');
+});
+
+test('postRaw DOES re-send a $batch of conditional deletes that was refused with 429, in either shape', async () => {
+ const answers = {
+ // Service protection refuses the whole request before reading an operation: a plain error answer.
+ 'the whole request refused': { statusCode: 429, headers: {}, body: JSON.stringify({ error: { code: '0x80072322', message: 'Number of requests exceeded the limit of 6000 over time window of 300 seconds.' } }) },
+ 'the whole request refused, no body': { statusCode: 429, headers: {}, body: '' },
+ 'its change set refused': { statusCode: 429, headers: {}, body: batchAnswer(['HTTP/1.1 429 Too Many Requests', UNINSTALL_429.body]) },
+ 'every operation refused, whatever the outer status': { statusCode: 200, headers: {}, body: batchAnswer(['HTTP/1.1 429 Too Many Requests', '{}'], ['HTTP/1.1 429 Too Many Requests', '{}']) },
+ };
+ for (const [what, refused] of Object.entries(answers)) {
+ const { request, calls } = fakeTransport(() => (calls.length <= 1 ? refused : { statusCode: 200, headers: {}, body: BATCH_RESPONSE }));
+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request, sleep: async () => {} });
+ const res = await postBatch(http);
+ assert.strictEqual(calls.length, 2, `re-sent: ${what}`);
+ assert.strictEqual(calls[1].body, calls[0].body, `the same change set, byte for byte: ${what}`);
+ assert.strictEqual(res.body, BATCH_RESPONSE, `the SDK reads the re-sent batch's own answer: ${what}`);
+ }
+});
+
+test('postRaw re-sends a 429 $batch ONLY when it is made of conditional deletes and the answer proves nothing ran', async () => {
+ const answers = {
+ 'an operation that committed beside the refused one': batchAnswer(['HTTP/1.1 204 No Content'], ['HTTP/1.1 429 Too Many Requests', '{}']),
+ 'a refusal beside another failure': batchAnswer(['HTTP/1.1 429 Too Many Requests', '{}'], ['HTTP/1.1 500 Internal Server Error', '{}']),
+ 'a multipart answer cut short': batchAnswer(['HTTP/1.1 429 Too Many Requests', '{}']).replace(/--batchresponse_b1--\r\n$/, ''),
+ 'a complete answer with no operation results': '--batchresponse_b1\r\n--batchresponse_b1--\r\n',
+ };
+ for (const [what, body] of Object.entries(answers)) {
+ const { request, calls } = fakeTransport({ statusCode: 429, headers: {}, body });
+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request, sleep: async () => {} });
+ const res = await postBatch(http);
+ assert.strictEqual(calls.length, 1, `not re-sent: ${what}`);
+ assert.strictEqual(res.body, body, `and the answer reaches the SDK as it came: ${what}`);
+ }
+ // A 429 cannot make an unsafe batch safe: a second send of a generative page's `If-Match: *` update
+ // after the wait would skip the version check the SDK made before the first.
+ const requests = {
+ 'unconditional writes (a generative page update)': batchRequest(['PATCH', 'https://org.crm.dynamics.com/api/data/v9.0/uxagentprojectfiles(1)', ['If-Match: *']]),
+ 'a DELETE with no condition (the SDK\u2019s create rollback)': batchRequest(['DELETE', 'https://org.crm.dynamics.com/api/data/v9.0/appmodules(1)']),
+ };
+ for (const [what, body] of Object.entries(requests)) {
+ const { request, calls } = fakeTransport({ statusCode: 429, headers: {}, body: '' });
+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request, sleep: async () => {} });
+ await postBatch(http, body);
+ assert.strictEqual(calls.length, 1, `not re-sent: ${what}`);
+ }
+ // Only a 429 proves the record delete was not started; the other throttling-like statuses do not.
+ for (const status of [500, 502, 503, 504]) {
+ const { request, calls } = fakeTransport({ statusCode: status, headers: {}, body: '' });
+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request, sleep: async () => {} });
+ await http.delete('https://org.crm.dynamics.com/api/data/v9.0/solutions(1)');
+ assert.strictEqual(calls.length, 1, `a record delete answered ${status} is sent once`);
+ }
+});
+
+test('a throttled answer\u2019s Retry-After is honoured, up to a cap, when it asks for longer than the backoff', async () => {
+ const NOW = Date.parse('2026-09-30T10:00:00Z');
+ const cases = [
+ ['20', 20000],
+ ['600', RETRY_AFTER_CAP_MS],
+ ['Wed, 30 Sep 2026 10:00:30 GMT', 30000],
+ ['Wed, 30 Sep 2026 09:59:00 GMT', 1125], // already past: the backoff
+ ['0', 1125],
+ ['soon', 1125],
+ ['1', 1125], // shorter than the backoff: the backoff
+ ];
+ for (const [value, want] of cases) {
+ for (const [what, send] of [['a GET', (h) => h.get('https://org.crm.dynamics.com/x')], ['a record delete', (h) => h.delete('https://org.crm.dynamics.com/api/data/v9.0/solutions(1)')]]) {
+ const slept = [];
+ const { request, calls } = fakeTransport(() => (calls.length <= 1 ? { statusCode: 429, headers: { 'retry-after': value }, body: '' } : { statusCode: 204, headers: {}, body: '' }));
+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request, random: () => 0.5, now: () => NOW, sleep: async (ms) => { slept.push(ms); } });
+ await send(http);
+ assert.deepStrictEqual(slept, [want], `${what}, Retry-After: ${value}`);
+ }
+ }
+ assert.strictEqual(retryAfterMs({ 'Retry-After': '7' }), 7000, 'the header name is matched case-insensitively');
+ assert.strictEqual(retryAfterMs({ 'retry-after': ['9'] }), 9000);
+ assert.strictEqual(retryAfterMs({}), 0);
+ assert.strictEqual(retryAfterMs(undefined), 0);
+ assert.strictEqual(retryAfterMs({ 'retry-after': '-5' }), 0);
+});
+
+// An operation refused inside a batch is answered with its own headers, so its Retry-After can sit in the
+// part rather than on the outer response. Ignoring it spent the six attempts in ~23 s while the server had
+// asked for 30.
+test('a batch refused operation by operation waits for the Retry-After in the refused operation\u2019s own headers', async () => {
+ const NOW = Date.parse('2026-09-30T10:00:00Z');
+ const part = (retryAfter) => ['HTTP/1.1 429 Too Many Requests' + (retryAfter ? `\r\nRetry-After: ${retryAfter}` : ''), '{}'];
+ const cases = [
+ ['30 in the part, none outside', { headers: {}, parts: [part('30')] }, 30000],
+ ['an HTTP date in the part', { headers: {}, parts: [part('Wed, 30 Sep 2026 10:00:45 GMT')] }, 45000],
+ ['the longest of two parts', { headers: {}, parts: [part('5'), part('40')] }, 40000],
+ ['capped', { headers: {}, parts: [part('600')] }, RETRY_AFTER_CAP_MS],
+ ['the outer header when it asks for longer', { headers: { 'retry-after': '50' }, parts: [part('10')] }, 50000],
+ ['the backoff when neither asks for longer', { headers: {}, parts: [part()] }, 1125],
+ ];
+ for (const [what, { headers, parts }, want] of cases) {
+ const slept = [];
+ const refused = { statusCode: 429, headers, body: batchAnswer(...parts) };
+ const { request, calls } = fakeTransport(() => (calls.length <= 1 ? refused : { statusCode: 200, headers: {}, body: BATCH_RESPONSE }));
+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request, random: () => 0.5, now: () => NOW, sleep: async (ms) => { slept.push(ms); } });
+ await postBatch(http);
+ assert.deepStrictEqual(slept, [want], what);
+ }
+ assert.strictEqual(batchRetryAfterMs({ body: batchAnswer(['HTTP/1.1 204 No Content\r\nRetry-After: 30']) }), 0, 'only a refused operation\u2019s wait counts');
+ assert.strictEqual(batchRetryAfterMs({ body: '{"error":{}}' }), 0, 'a plain answer has no parts');
+ assert.strictEqual(batchRetryAfterMs(undefined), 0);
+});
+
+test('isBatchThrottled reads the answer, not the outer status alone', () => {
+ assert.strictEqual(isBatchThrottled({ statusCode: 429, body: '{"error":{}}' }), true);
+ assert.strictEqual(isBatchThrottled({ statusCode: 503, body: '{"error":{}}' }), false);
+ assert.strictEqual(isBatchThrottled({ statusCode: 429, body: batchAnswer(['HTTP/1.1 204 No Content']) }), false);
+ assert.strictEqual(isBatchThrottled({ statusCode: 500, body: batchAnswer(['HTTP/1.1 429 Too Many Requests', '{}']) }), true);
+ assert.strictEqual(isBatchThrottled(undefined), false);
+});
+
test('postRaw still refreshes the token once on 401 (rejected before processing, so it is safe)', async () => {
const { request, calls } = fakeTransport(() =>
calls.length <= 1 ? { statusCode: 401, headers: {}, body: '' } : { statusCode: 200, headers: {}, body: BATCH_RESPONSE }
diff --git a/plugins/model-apps/scripts/tests/sdk-surface-contract.test.js b/plugins/model-apps/scripts/tests/sdk-surface-contract.test.js
index 62d5f8264..a14c0bc57 100644
--- a/plugins/model-apps/scripts/tests/sdk-surface-contract.test.js
+++ b/plugins/model-apps/scripts/tests/sdk-surface-contract.test.js
@@ -90,6 +90,9 @@ const SKILL_SDK_SURFACE = [
// `systemformrole` entity — they live inside `formxml` as `<DisplayConditions>`, so this dedicated
// call is the only way to write them.
'setFormSecurityRoles',
+ // Reads a form's <DisplayConditions> back — including its `Order`, the form's place in the table's
+ // Main Form Set, which the forms phase sets and keeps (AB#6736948).
+ 'getFormSecurityRoles',
// Written by the app-shell phase for `app.newLook` — the modern shell is a per-app SETTING
// (`NewLookAlwaysOn`), not an appmodule column.
'saveSettingValue',
diff --git a/plugins/model-apps/scripts/tests/sdk-teardown.test.js b/plugins/model-apps/scripts/tests/sdk-teardown.test.js
index f09bb8679..79484997d 100644
--- a/plugins/model-apps/scripts/tests/sdk-teardown.test.js
+++ b/plugins/model-apps/scripts/tests/sdk-teardown.test.js
@@ -789,6 +789,45 @@ test('teardown deletes only the dashboards the app\'s solution holds, never anot
assert.match(unnamed.skip.label, /this spec names no solution, so nothing proves a dashboard named 'Operations' is this app's/);
});
+// AB#6726727: a downloaded spec pins the dashboard it was read from, and the build binds it by that id —
+// so after a rename in the designer the spec's name finds nothing, but the dashboard is still this
+// spec's. Teardown finds it by the pin too, as a CANDIDATE: the solution still decides.
+test('teardown finds a pinned dashboard renamed since the download, and still asks the solution', async () => {
+ const PIN = 'aaaa1111-2222-3333-4444-555566667777';
+ const OTHER = 'bbbb1111-2222-3333-4444-555566667777';
+ const spec = { solution: { uniqueName: 'ContosoSln', publisherPrefix: 'new' }, app: { name: 'A' }, entities: [],
+ dashboards: [{ name: 'Command Center - Event operations', dashboardId: PIN, tiles: [] }] };
+ const run = async ({ inSolution, pinned = { formid: PIN, name: 'Event operations', type: 0 }, failPin = false, byName = [] }) => {
+ const deleted = [];
+ const sdk = {
+ resolveArtifact: async (kind) => (kind === 'solution' ? [{ id: 'sol-1', name: 'ContosoSln' }] : kind === 'dashboard' ? byName : []),
+ deleteRemoteArtifact: async (type, id) => { deleted.push(id); },
+ deleteAppCascade: async () => {},
+ deleteSolution: async () => {},
+ queryRecords: async (set, opts) => {
+ if (set === 'systemform' && opts.filter === `formid eq ${PIN}`) { if (failPin) throw new Error('HTTP 503'); return pinned ? [pinned] : []; }
+ if (set === 'solution') return [{ solutionid: 'sol-1' }];
+ if (set === 'solutioncomponent') return inSolution.filter((id) => opts.filter.includes(`objectid eq ${id}`)).map((objectid) => ({ objectid }));
+ return [];
+ },
+ };
+ const r = await runTeardown(spec, { apply: true }, { sdk, emit: () => {} });
+ return { deleted, r };
+ };
+ assert.deepStrictEqual((await run({ inSolution: [PIN] })).deleted, [PIN], 'found by its pin, deleted because the solution holds it');
+ assert.deepStrictEqual((await run({ inSolution: [] })).deleted, [], 'a pin is not proof of ownership on its own');
+ // A resolving pin is the ONLY candidate: another dashboard that has since been given the old name —
+ // even one in the same solution — is not this spec's, and build and verify would not pick it either.
+ const reused = await run({ inSolution: [PIN, OTHER], byName: [{ id: OTHER, name: 'Command Center - Event operations' }] });
+ assert.deepStrictEqual(reused.deleted, [PIN]);
+ // A pin this environment does not have: the name decides, as it does for the build.
+ assert.deepStrictEqual((await run({ inSolution: [OTHER], pinned: null, byName: [{ id: OTHER, name: 'Command Center - Event operations' }] })).deleted, [OTHER]);
+ assert.deepStrictEqual((await run({ inSolution: [PIN], pinned: null })).deleted, [], 'no pin row and no name match: nothing');
+ const failed = await run({ inSolution: [PIN], failPin: true });
+ assert.deepStrictEqual(failed.deleted, []);
+ assert.ok(failed.r.errors.some((e) => /could not look up the dashboard pinned as 'Command Center - Event operations'/.test(e.message)), JSON.stringify(failed.r.errors));
+});
+
// The solution is what a re-run asks to tell this app's dashboards from same-named ones. Deleted after
// a failed step, it left the retry nothing to prove them by: the retry kept them for good, and their
// tiles then blocked the chart and view deletes on every later run. So a teardown with a failed step
diff --git a/plugins/model-apps/scripts/tests/sitemap-adopt-real-bundle.test.js b/plugins/model-apps/scripts/tests/sitemap-adopt-real-bundle.test.js
new file mode 100644
index 000000000..0ded1fc17
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/sitemap-adopt-real-bundle.test.js
@@ -0,0 +1,251 @@
+'use strict';
+// REAL-BUNDLE tests for rewriting an existing app's sitemap (AB#6726727).
+//
+// Reported: an unrelated edit to an app rebuilt its designer-made dashboard entry
+// <SubArea Id="ops_dashboard" Url="/workplace/home_dashboards.aspx" DefaultDashboard="…" Client="All,Web" AvailableOffline="false">
+// as a brand-new one
+// <SubArea Id="sub_0_0_0" DefaultDashboard="…" ResourceId="SitemapDesigner.NewSubArea" Client="All,Outlook,…" Sku="…" AvailableOffline="true" PassParams="false">
+// and the dashboard's icon became a placeholder. The runtime shows the dashboard glyph only for a
+// subarea whose Url is the dashboard launcher, and the SDK serializes a node that arrives without its
+// fetched `bag` from scratch — which is what every existing-app build handed it.
+//
+// These drive the real `appDef`, the real `adoptLiveSitemap` and the real vendored SDK over a fake
+// Dataverse, and read the sitemap XML the SDK actually writes.
+const test = require('node:test');
+const assert = require('node:assert');
+const os = require('node:os');
+const path = require('node:path');
+const fs = require('node:fs');
+
+const { appDef } = require('../lib/sdk-build.js');
+const { adoptLiveSitemap, chromeByTargetKey, describeSitemapNotes } = require('../lib/sitemap-merge.js');
+const { subareaDashboardHasLauncher, subareaHasDashboard } = require('../lib/verify-spec.js');
+const { deployedIdsFor } = require('../lib/deployed-baseline.js');
+
+const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');
+const APP_ID = '11111111-1111-1111-1111-111111111111';
+const APP_UNIQUE = 'new_eventcenter';
+const APP_IDUNIQUE = '33333333-3333-3333-3333-333333333333';
+const TABLE_METADATA_ID = '22222222-2222-2222-2222-222222222222';
+const SITEMAP_ID = '55555555-5555-5555-5555-555555555555';
+const DASH = '280948ec-7bbb-5279-b106-2bdd09451a3a';
+
+// The designer-made entry, with the formatting Dataverse really uses: a braced upper-case GUID and a
+// second-language title the App Spec cannot express.
+const LEGACY_DASHBOARD_TAG = `<SubArea Id="ops_dashboard" Url="/workplace/home_dashboards.aspx" DefaultDashboard="{${DASH.toUpperCase()}}" Client="All,Web" AvailableOffline="false">`;
+const deployedXml = ({ dashTitle = 'Event operations', dashTag = LEGACY_DASHBOARD_TAG } = {}) =>
+ '<SiteMap IntroducedVersion="7.0.0.0">'
+ + '<Area Id="area_ops" ShowGroups="true" ResourceId="Contoso.AreaRes"><Titles><Title LCID="1033" Title="Operations" /><Title LCID="1036" Title="Opérations" /></Titles>'
+ + '<Group Id="grp_main" ResourceId="Contoso.GroupRes" IsProfile="false"><Titles><Title LCID="1033" Title="Main" /></Titles>'
+ + `${dashTag}<Titles><Title LCID="1033" Title="${dashTitle}" /><Title LCID="1036" Title="Opérations (FR)" /></Titles></SubArea>`
+ + '<SubArea Id="feedback_sub" Entity="new_feedback" Client="All,Web" AvailableOffline="false" ResourceId="Contoso.FeedbackRes"><Titles><Title LCID="1033" Title="Feedback" /></Titles></SubArea>'
+ + '</Group></Area></SiteMap>';
+
+const tempDirs = [];
+test.after(() => { for (const d of tempDirs) fs.rmSync(d, { recursive: true, force: true }); });
+
+/** A real SDK over a fake Dataverse whose app carries `xml` as its sitemap. */
+async function freshSdk(xml) {
+ const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sitemap-adopt-'));
+ tempDirs.push(dir);
+ const written = [];
+ const appRow = () => ({ appmoduleid: APP_ID, appmoduleidunique: APP_IDUNIQUE, name: 'Event Center', uniquename: APP_UNIQUE, description: '' });
+ const sitemapRow = () => ({ sitemapid: SITEMAP_ID, sitemapnameunique: APP_UNIQUE, sitemapxml: xml, '@odata.etag': 'W/"1"' });
+ const httpClient = {
+ get: async (url) => {
+ const m = /EntityDefinitions\(LogicalName='([^']+)'\)/.exec(url);
+ if (m) return { status: 200, headers: {}, body: { LogicalName: m[1], MetadataId: TABLE_METADATA_ID, EntitySetName: `${m[1]}s` } };
+ if (/\/appmodulecomponents/.test(url)) {
+ const wantsSitemap = /componenttype(%20| )eq(%20| )62/.test(url);
+ return { status: 200, headers: {}, body: { value: wantsSitemap ? [{ objectid: SITEMAP_ID, componenttype: 62 }] : [{ objectid: TABLE_METADATA_ID, componenttype: 1 }] } };
+ }
+ if (/\/sitemaps/.test(url)) {
+ const multi = /RetrieveUnpublishedMultiple/i.test(url) || /\/sitemaps\?/.test(url);
+ return { status: 200, headers: { etag: 'W/"1"' }, body: multi ? { value: [sitemapRow()] } : sitemapRow() };
+ }
+ if (/\/appmodules/.test(url)) {
+ const multi = /RetrieveUnpublishedMultiple/i.test(url) || /\/appmodules\?/.test(url);
+ return { status: 200, headers: { etag: 'W/"1"' }, body: multi ? { value: [appRow()] } : appRow() };
+ }
+ if (/\/roles/.test(url)) return { status: 200, headers: {}, body: { value: [{ roleid: '66666666-6666-6666-6666-666666666666' }] } };
+ return { status: 200, headers: {}, body: { value: [] } };
+ },
+ post: async (url, body) => {
+ if (/\/sitemaps\b/.test(url) && body && body.sitemapxml) written.push(String(body.sitemapxml));
+ return { status: 204, headers: { 'odata-entityid': `https://x/y(${APP_ID})` }, body: {} };
+ },
+ patch: async (url, body) => {
+ if (/\/sitemaps\(/.test(url) && body && body.sitemapxml) written.push(String(body.sitemapxml));
+ return { status: 204, headers: {}, body: {} };
+ },
+ delete: async () => ({ status: 204, headers: {}, body: {} }),
+ put: async () => ({ status: 204, headers: {}, body: {} }),
+ };
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(dir), instanceUrl: 'https://contoso.crm.dynamics.com', httpClient });
+ await sdk.initWorkspace();
+ return { sdk, lastXml: () => written[written.length - 1] || '' };
+}
+
+// The downloaded spec's view of that app, with one unrelated edit: a vector icon on Feedback.
+const specFor = ({ dashTitle = 'Event operations', feedbackIcon } = {}) => ({
+ solution: { uniqueName: 'EventCenter', publisherPrefix: 'new' },
+ app: { name: 'Event Center', uniqueName: APP_UNIQUE },
+ appShell: { areas: [{ label: 'Operations', groups: [{ label: 'Main', subAreas: [
+ { dashboard: 'Command Center - Event operations', title: dashTitle },
+ { entity: 'new_feedback', title: 'Feedback', ...(feedbackIcon ? { vectorIcon: feedbackIcon } : {}) },
+ ] }] }] },
+});
+const CREATED = { dashboards: { 'Command Center - Event operations': DASH } };
+
+/** What the build does for an existing app: fetch, appDef, re-attach, write, push. */
+async function rebuild(xml, spec, opts = {}) {
+ const { sdk, lastXml } = await freshSdk(xml);
+ await sdk.fetchArtifact('app', APP_ID);
+ const live = await sdk.getArtifact('app', APP_ID);
+ const { siteMap, notes } = adoptLiveSitemap(appDef(spec, CREATED).siteMap, live.siteMap, opts);
+ await sdk.updateElement('app', APP_ID, '/siteMap', siteMap);
+ await sdk.pushArtifact('app', APP_ID);
+ return { xml: lastXml(), notes };
+}
+const tagOf = (xml, re) => ((xml.match(/<SubArea\b[^>]*>/g) || []).find((t) => re.test(t)) || '');
+
+test('REAL BUNDLE: an unrelated edit leaves a designer-made dashboard entry byte-for-byte as it was', async () => {
+ const { xml } = await rebuild(deployedXml(), specFor({ feedbackIcon: '$webresource:new_feedback.svg' }));
+ assert.ok(xml, 'a sitemap was written');
+ assert.ok(xml.includes(`${LEGACY_DASHBOARD_TAG}<Titles><Title LCID="1033" Title="Event operations" /><Title LCID="1036" Title="Opérations (FR)" /></Titles></SubArea>`),
+ `the dashboard entry must round-trip unchanged:\n${xml}`);
+ assert.doesNotMatch(xml, /SitemapDesigner\.NewSubArea|sub_0_0_0/, 'no node was rebuilt from scratch');
+ // The edit itself landed, on the entry's own node, keeping everything else that node carried.
+ const feedback = tagOf(xml, /Entity="new_feedback"/);
+ assert.match(feedback, /Id="feedback_sub"/);
+ assert.match(feedback, /VectorIcon="\$webresource:new_feedback\.svg"/);
+ assert.match(feedback, /ResourceId="Contoso\.FeedbackRes"/);
+ assert.match(feedback, /AvailableOffline="false"/);
+ // Areas and groups keep their ids, attributes and other-language titles too.
+ assert.match(xml, /<Area Id="area_ops" ShowGroups="true" ResourceId="Contoso\.AreaRes"><Titles><Title LCID="1033" Title="Operations" \/><Title LCID="1036" Title="Opérations" \/><\/Titles>/);
+ assert.match(xml, /<Group Id="grp_main" ResourceId="Contoso\.GroupRes" IsProfile="false">/);
+ assert.ok(subareaHasDashboard(xml, DASH) && subareaDashboardHasLauncher(xml, DASH), 'verify passes the entry');
+});
+
+test('REAL BUNDLE: an entry an earlier build wrote without the launcher Url gets it back', async () => {
+ // The damaged shape from the report. Verify's new check fails it; a rebuild repairs it in place.
+ const damaged = `<SubArea Id="sub_0_0_0" DefaultDashboard="${DASH}" ResourceId="SitemapDesigner.NewSubArea" Client="All,Outlook,OutlookLaptopClient,OutlookWorkstationClient,Web" Sku="All,OnPremise,Live,SPLA" AvailableOffline="true" PassParams="false">`;
+ const before = deployedXml({ dashTag: damaged });
+ assert.ok(subareaHasDashboard(before, DASH) && !subareaDashboardHasLauncher(before, DASH), 'precondition: verify now FAILS the damaged entry');
+ const { xml } = await rebuild(before, specFor());
+ const tag = tagOf(xml, /DefaultDashboard=/);
+ assert.match(tag, /Id="sub_0_0_0"/, 'the same node, not a replacement');
+ assert.match(tag, /Url="\/workplace\/home_dashboards\.aspx"/);
+ assert.ok(subareaDashboardHasLauncher(xml, DASH));
+});
+
+test('REAL BUNDLE: a fresh app\u2019s dashboard entry is written the way the designer writes one', async () => {
+ const { sdk, lastXml } = await freshSdk('<SiteMap></SiteMap>');
+ const def = appDef(specFor(), CREATED, { iconWebResourceId: '77777777-7777-7777-7777-777777777777' });
+ const art = await sdk.createArtifact('app', def);
+ await sdk.pushArtifact('app', art.id);
+ const xml = lastXml();
+ assert.match(tagOf(xml, /DefaultDashboard=/), /Url="\/workplace\/home_dashboards\.aspx"/);
+ assert.ok(subareaDashboardHasLauncher(xml, DASH));
+});
+
+test('REAL BUNDLE: a nav title renamed in the designer after the download is kept, not reverted', async () => {
+ // Downloaded as 'Command Center - Event operations', renamed to 'Event operations' in the designer,
+ // then an unrelated edit is built from the stale spec.
+ const stale = specFor({ dashTitle: 'Command Center - Event operations', feedbackIcon: '$webresource:new_feedback.svg' });
+ const baseline = specFor({ dashTitle: 'Command Center - Event operations' });
+ const { xml, notes } = await rebuild(deployedXml({ dashTitle: 'Event operations' }), stale, { baseChrome: chromeByTargetKey(baseline, CREATED) });
+ assert.match(xml, /<Title LCID="1033" Title="Event operations" \/>/, 'the designer rename survives');
+ assert.doesNotMatch(xml, /Command Center - Event operations/);
+ const lines = describeSitemapNotes(notes);
+ assert.ok(lines.some((l) => /kept the environment's title 'Event operations'/.test(l)), JSON.stringify(lines));
+ // Without a baseline the spec wins — and the build says so rather than doing it silently.
+ const noBase = await rebuild(deployedXml({ dashTitle: 'Event operations' }), stale);
+ assert.match(noBase.xml, /Title="Command Center - Event operations"/);
+ assert.ok(describeSitemapNotes(noBase.notes).some((l) => /title changes from 'Event operations' to the spec's 'Command Center - Event operations'/.test(l)));
+});
+
+test('REAL BUNDLE: a title the spec itself changes is applied, with nothing to report', async () => {
+ const baseline = specFor();
+ const edited = specFor({ dashTitle: 'Live operations' });
+ const { xml, notes } = await rebuild(deployedXml(), edited, { baseChrome: chromeByTargetKey(baseline, CREATED) });
+ assert.match(xml, /<Title LCID="1033" Title="Live operations" \/><Title LCID="1036" Title="Opérations \(FR\)" \/>/, 'patched in place; the French title stays');
+ assert.deepStrictEqual(describeSitemapNotes(notes), []);
+});
+
+// The SDK only PATCHES an existing <Titles> on a node that has a bag, and reads an empty typed title as
+// "no edit" — so a title added to an entry that had none, or removed from one that had it, must be
+// reconciled in the adopted bag, or it would silently not happen (it did happen on the bag-less path).
+test('REAL BUNDLE: a title added to an entry that had none is written; a removed one is dropped, other languages kept', async () => {
+ const untitled = '<SiteMap IntroducedVersion="7.0.0.0"><Area Id="area_ops" ResourceId="Contoso.AreaRes"><Titles><Title LCID="1033" Title="Operations" /></Titles>'
+ + '<Group Id="grp_main"><Titles><Title LCID="1033" Title="Main" /></Titles>'
+ + `${LEGACY_DASHBOARD_TAG}<Titles><Title LCID="1033" Title="Event operations" /></Titles></SubArea>`
+ + '<SubArea Id="feedback_sub" Entity="new_feedback" Client="All,Web" /></Group></Area></SiteMap>';
+ const added = await rebuild(untitled, specFor());
+ assert.match(tagOf(added.xml, /Entity="new_feedback"/), /Id="feedback_sub"/);
+ assert.match(added.xml, /<SubArea Id="feedback_sub" Entity="new_feedback" Client="All,Web"><Titles><Title LCID="1033" Title="Feedback" \/><\/Titles><\/SubArea>/, added.xml);
+
+ const spec = specFor();
+ delete spec.appShell.areas[0].groups[0].subAreas[0].title; // the dashboard entry's title removed
+ const removed = await rebuild(deployedXml(), spec);
+ const dash = removed.xml.slice(removed.xml.indexOf(LEGACY_DASHBOARD_TAG), removed.xml.indexOf('</SubArea>', removed.xml.indexOf(LEGACY_DASHBOARD_TAG)));
+ assert.doesNotMatch(dash, /LCID="1033"/, 'the title at the SDK\u2019s language is gone');
+ assert.match(dash, /<Title LCID="1036" Title="Opérations \(FR\)" \/>/, 'another language\u2019s title is not the spec\u2019s to drop');
+});
+
+test('REAL BUNDLE: renaming the dashboard in the spec, as the build asks, keeps the baseline lined up', async () => {
+ // Downloaded (pinned) as 'Command Center - Event operations'; renamed in the designer; the author then
+ // follows the build's warning and renames it in the spec too. The baseline still names it by the old
+ // name, so only the id the download recorded can line its nav entry up with the live one.
+ const PINNED = (s) => { s.dashboards = [{ name: s.appShell.areas[0].groups[0].subAreas[0].dashboard, dashboardId: DASH, tiles: [{ type: 'list', entity: 'account', viewId: 'v1' }] }]; return s; };
+ const downloaded = PINNED(specFor({ dashTitle: 'Command Center - Event operations' }));
+ const baseline = { ...downloaded, __deployedIds: deployedIdsFor(downloaded, { fromSpec: true }) };
+ const renamed = PINNED(specFor({ dashTitle: 'Command Center - Event operations' }));
+ renamed.appShell.areas[0].groups[0].subAreas[0].dashboard = 'Event operations';
+ renamed.dashboards[0].name = 'Event operations';
+ const created = { dashboards: { 'Event operations': DASH } }; // what this build resolved (by the pin)
+ const { sdk, lastXml } = await freshSdk(deployedXml({ dashTitle: 'Event operations' }));
+ await sdk.fetchArtifact('app', APP_ID);
+ const live = await sdk.getArtifact('app', APP_ID);
+ const { siteMap } = adoptLiveSitemap(appDef(renamed, created).siteMap, live.siteMap, { baseChrome: chromeByTargetKey(baseline, created) });
+ await sdk.updateElement('app', APP_ID, '/siteMap', siteMap);
+ await sdk.pushArtifact('app', APP_ID);
+ assert.match(lastXml(), /<Title LCID="1033" Title="Event operations" \/>/, 'the designer\u2019s nav title is kept');
+ assert.doesNotMatch(lastXml(), /Command Center - Event operations/);
+});
+
+test('REAL BUNDLE: a spec downloaded from another environment lines up by the ids the build resolved HERE', async () => {
+ // Its pin names the other environment's dashboard, which does not exist here, so the build fell back
+ // to the name and resolved DASH — and the baseline it wrote records DASH, not the pin. Recording the
+ // pin would line the entry up with nothing, and the next build would revert the designer's rename.
+ const FOREIGN = 'ffffffff-1111-2222-3333-444444444444';
+ const pinned = () => {
+ const s = specFor({ dashTitle: 'Command Center - Event operations' });
+ s.dashboards = [{ name: 'Command Center - Event operations', dashboardId: FOREIGN, tiles: [{ type: 'list', entity: 'account', viewId: 'v1' }] }];
+ return s;
+ };
+ const applied = pinned();
+ const baseline = { ...applied, __deployedIds: deployedIdsFor(applied, { created: CREATED }) };
+ assert.deepStrictEqual(baseline.__deployedIds.dashboards, { 'Command Center - Event operations': DASH });
+ const { xml, notes } = await rebuild(deployedXml({ dashTitle: 'Event operations' }), pinned(), { baseChrome: chromeByTargetKey(baseline, CREATED) });
+ assert.match(xml, /<Title LCID="1033" Title="Event operations" \/>/, 'the designer\u2019s rename is kept');
+ assert.ok(describeSitemapNotes(notes).some((l) => /kept the environment's title 'Event operations'/.test(l)));
+});
+
+test('REAL BUNDLE: removing a group\u2019s title leaves its description ahead of its entries', async () => {
+ // A group an earlier build created (so it corresponds by its id) that the designer gave a description.
+ // Its label is then removed from the spec: the title goes, and the description must stay before the
+ // subareas, where the sitemap schema requires it.
+ const xml = '<SiteMap IntroducedVersion="7.0.0.0"><Area Id="area_0" ShowGroups="true"><Titles><Title LCID="1033" Title="Operations" /></Titles>'
+ + '<Group Id="group_0_0"><Titles><Title LCID="1033" Title="Main" /></Titles><Descriptions><Description LCID="1033" Description="Day-to-day work" /></Descriptions>'
+ + `${LEGACY_DASHBOARD_TAG}<Titles><Title LCID="1033" Title="Event operations" /></Titles></SubArea>`
+ + '<SubArea Id="feedback_sub" Entity="new_feedback" Client="All,Web"><Titles><Title LCID="1033" Title="Feedback" /></Titles></SubArea>'
+ + '</Group></Area></SiteMap>';
+ const spec = specFor();
+ delete spec.appShell.areas[0].groups[0].label;
+ const out = await rebuild(xml, spec);
+ const group = out.xml.slice(out.xml.indexOf('<Group'), out.xml.indexOf('</Group>'));
+ assert.match(group, /^<Group Id="group_0_0"><Descriptions><Description LCID="1033" Description="Day-to-day work" \/><\/Descriptions><SubArea Id="ops_dashboard"/, group);
+ assert.doesNotMatch(group, /<Titles><Title LCID="1033" Title="Main"/, 'the removed title is gone');
+});
diff --git a/plugins/model-apps/scripts/tests/sitemap-icon-real-bundle.test.js b/plugins/model-apps/scripts/tests/sitemap-icon-real-bundle.test.js
index 0764b9a62..12fcb37c5 100644
--- a/plugins/model-apps/scripts/tests/sitemap-icon-real-bundle.test.js
+++ b/plugins/model-apps/scripts/tests/sitemap-icon-real-bundle.test.js
@@ -5,24 +5,26 @@
// half of that is fixed upstream, but MEASURING it here changed the conclusion about the plugin, so
// both halves are pinned below and each says which path it speaks for.
//
-// WHOLE-NODE REPLACE (what `sdk-build.js` does — `updateElement('app', id, '/siteMap', appDef(...).siteMap)`)
-// `appDef` projects the sitemap fresh from the App Spec, so the node handed to `updateElement` is a
-// brand-new object tree with no `bag`. Nothing is merged forward, so a dropped `icon` cannot survive
-// — MEASURED identical on the pre- and post-fix bundles. The plugin never exhibited AB#6688906 here.
+// RE-ATTACHED REWRITE (what `sdk-build.js` does for an existing app since AB#6726727)
+// `appDef` projects the sitemap fresh from the App Spec, and `adoptLiveSitemap` re-attaches each node
+// to the live node it corresponds to, keeping that node's `bag` — every attribute and child the App
+// Spec cannot describe. It used to hand `updateElement` the bag-less tree, which could not carry a
+// dropped `icon` forward but also rebuilt every live node from scratch: a designer-made dashboard
+// entry lost its launcher Url and its icon. So the plugin now depends on the SDK's removal rule for
+// a dropped chrome attribute, exactly like an in-place reconcile — which is what the first test pins.
//
-// IN-PLACE MUTATE (what the SDK's own reproduction does, and what any future in-place reconcile would)
+// IN-PLACE MUTATE (what the SDK's own reproduction does)
// The fetched node keeps its `bag`, so `mergeAttrs` carried the deployed `Icon` forward forever. This
// is the real defect, and the fix is what these tests exist to keep.
//
-// Both are worth pinning. The first documents a load-bearing and non-obvious property of the plugin's
-// path — full replacement — which a change to in-place reconcile would silently reverse, walking the
-// plugin straight into the bug. The second is the only executable check of the fix available here (the
-// SDK's own Jest suite cannot run in this repo: its `canvas` native module is built for the Node-20 ABI).
+// The SDK's own Jest suite cannot run in this repo (its `canvas` native module is built for the
+// Node-20 ABI), so these are the only executable checks of that fix available here.
const test = require('node:test');
const assert = require('node:assert');
const os = require('node:os');
const path = require('node:path');
const fs = require('node:fs');
+const { adoptLiveSitemap } = require('../lib/sitemap-merge.js');
const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');
@@ -99,31 +101,37 @@ async function freshSdk() {
/** The `<SubArea …>` start tag only — an Area-level `Icon` must never satisfy a SubArea assertion. */
const subAreaTag = (xml) => (/<SubArea\b[^>]*>/.exec(xml) || [''])[0];
-test('REAL BUNDLE: the plugin\u2019s whole-/siteMap replace cannot carry a dropped Icon forward', async () => {
+test('REAL BUNDLE: the plugin\u2019s rewrite removes a dropped Icon and keeps the rest of the live node', async () => {
const { sdk, lastSitemapXml } = await freshSdk();
const deployed = await sdk.fetchArtifact('app', APP_ID);
assert.strictEqual(deployed.siteMap.areas[0].groups[0].subAreas[0].icon, 'contoso_legacy.png',
'precondition: the deployed app really does carry the legacy raster icon');
- // Exactly what `sdk-build.js` does: hand `updateElement` a freshly projected siteMap. `appDef` is a
- // pure function of the App Spec, so this tree has no `bag` anywhere in it.
- await sdk.updateElement('app', APP_ID, '/siteMap', {
- areas: [{ id: 'Area1', title: 'Main', groups: [{ id: 'Group1', title: 'Main', subAreas: [{ id: 'Sub1', type: 'Entity', entity: 'new_torder', title: 'Orders', vectorIcon: VECTOR_REF }] }] }],
- });
+ // Exactly what `sdk-build.js` does for an existing app: appDef's bag-less tree (its positional ids),
+ // re-attached to the live nodes, then written.
+ const desired = {
+ areas: [{ id: 'area_0', title: 'Main', groups: [{ id: 'group_0_0', title: 'Main', subAreas: [{ id: 'sub_0_0_0', type: 'Entity', entity: 'new_torder', title: 'Orders', vectorIcon: VECTOR_REF }] }] }],
+ };
+ const { siteMap } = adoptLiveSitemap(desired, (await sdk.getArtifact('app', APP_ID)).siteMap);
+ await sdk.updateElement('app', APP_ID, '/siteMap', siteMap);
await sdk.pushArtifact('app', APP_ID);
const tag = subAreaTag(lastSitemapXml());
assert.ok(tag, 'a sitemap was serialized and written');
assert.match(tag, /VectorIcon="\$webresource:contoso_vec\.svg"/);
// `\sIcon=` cannot match inside `VectorIcon=` — the preceding character is `r`.
- assert.doesNotMatch(tag, /\sIcon="/, 'the legacy raster icon must not survive the replace');
-
- // The OTHER half of the same fact, asserted so the mechanism is unambiguous: the deployed bag is
- // DISCARDED, not merged. That is why no icon can survive — and it is also why maker-authored chrome
- // the App Spec does not model does not survive a rebuild either. That trade-off is pre-existing and
- // deliberate (the spec is the source of truth for the sitemap); it is pinned here so a future move
- // to in-place reconcile is a visible decision rather than an accident.
- assert.doesNotMatch(tag, /Contoso\.SubRes/, 'the deployed bag is replaced, not merged');
+ assert.doesNotMatch(tag, /\sIcon="/, 'the legacy raster icon the spec dropped must not survive');
+ // The node is the live one, not a replacement: its id and the chrome the App Spec cannot describe
+ // survive (AB#6726727).
+ assert.match(tag, /Id="Sub1"/);
+ assert.match(tag, /ResourceId="Contoso\.SubRes"/);
+ assert.match(tag, /ToolTipResourseId="Contoso\.Tip"/);
+ // Chrome the App Spec DOES model stays the spec's to decide: this spec names no Area icon, so the
+ // deployed one is removed, as it was before (a downloaded spec carries it, so a round trip keeps it).
+ const areaTag = (/<Area\b[^>]*>/.exec(lastSitemapXml()) || [''])[0];
+ assert.match(areaTag, /Id="Area1"/);
+ assert.doesNotMatch(areaTag, /\sIcon="/);
+ assert.match(areaTag, /ResourceId="Contoso\.AreaRes"/, 'while the Area keeps what the spec cannot describe');
});
test('REAL BUNDLE: an IN-PLACE reconcile drops a removed Icon while keeping the rest of the bag', async () => {
diff --git a/plugins/model-apps/scripts/tests/sitemap-merge.test.js b/plugins/model-apps/scripts/tests/sitemap-merge.test.js
new file mode 100644
index 000000000..925d74d9a
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/sitemap-merge.test.js
@@ -0,0 +1,310 @@
+'use strict';
+// Unit tests for lib/sitemap-merge.js (AB#6726727). The end-to-end behaviour through the real SDK is in
+// sitemap-adopt-real-bundle.test.js; these pin the correspondence rules one at a time.
+const { test } = require('node:test');
+const assert = require('node:assert');
+const { adoptLiveSitemap, chromeByTargetKey, describeSitemapNotes, subAreaTargetKey, specSubAreaTargetKey, keepsLiveValue, isDashboardLauncherUrl, DASHBOARD_LAUNCHER_URL } = require('../lib/sitemap-merge.js');
+
+const bag = (id, extra = []) => ({ a: [['Id', id], ...extra], c: [] });
+const entitySub = (id, entity, title, b) => ({ id, type: 'Entity', entity, title, ...(b ? { bag: b } : {}) });
+const tree = (areas) => ({ areas });
+
+test('a subarea corresponds by its navigation target, compared the way it resolves', () => {
+ assert.strictEqual(subAreaTargetKey({ type: 'Entity', entity: ' New_Order ' }), 'Entity:new_order');
+ assert.strictEqual(subAreaTargetKey({ type: 'DashBoard', dashboardId: '{280948EC-7BBB-5279-B106-2BDD09451A3A}' }), 'DashBoard:280948ec-7bbb-5279-b106-2bdd09451a3a');
+ assert.strictEqual(subAreaTargetKey({ type: 'GenPage', genPageId: 'ABC' }), 'GenPage:abc');
+ // Scheme and host fold; a path or query value can be case-sensitive, so it does not.
+ assert.strictEqual(subAreaTargetKey({ type: 'URL', url: 'HTTPS://Contoso.example/Help?key=AbC' }), 'URL:https://contoso.example/Help?key=AbC');
+ // A web-resource reference names a case-insensitive web resource.
+ assert.strictEqual(subAreaTargetKey({ type: 'URL', url: '$webresource:New_Home.html' }), 'URL:$webresource:new_home.html');
+ assert.strictEqual(subAreaTargetKey({ type: 'Entity' }), undefined, 'no target, no identity');
+ assert.strictEqual(subAreaTargetKey(null), undefined);
+});
+
+test('a URL whose case changed in the spec is a new entry, written as the spec spells it', () => {
+ const live = tree([{ id: 'a', title: 'M', groups: [{ id: 'g', title: 'G', subAreas: [{ id: 'help', type: 'URL', url: 'https://contoso.example/help?key=abc', title: 'Help', bag: bag('help') }] }] }]);
+ const desired = tree([{ id: 'area_0', title: 'M', groups: [{ id: 'group_0_0', title: 'G', subAreas: [{ id: 'sub_0_0_0', type: 'URL', url: 'https://contoso.example/help?key=AbC', title: 'Help' }] }] }]);
+ const sub = adoptLiveSitemap(desired, live).siteMap.areas[0].groups[0].subAreas[0];
+ assert.strictEqual(sub.url, 'https://contoso.example/help?key=AbC', 'the spec\u2019s token, not the live one');
+ const sameHostCase = tree([{ id: 'area_0', title: 'M', groups: [{ id: 'group_0_0', title: 'G', subAreas: [{ id: 'sub_0_0_0', type: 'URL', url: 'HTTPS://CONTOSO.example/help?key=abc', title: 'Help' }] }] }]);
+ const adopted = adoptLiveSitemap(sameHostCase, live).siteMap.areas[0].groups[0].subAreas[0];
+ assert.strictEqual(adopted.id, 'help', 'only the scheme and host differ: the same entry');
+ assert.strictEqual(adopted.url, 'HTTPS://CONTOSO.example/help?key=abc', 'and the spec\u2019s spelling is still what is written');
+});
+
+test('an adopted subarea keeps the live id, bag and target spelling; the spec sets only what it describes', () => {
+ const live = tree([{ id: 'a1', title: 'Main', bag: bag('a1'), groups: [{ id: 'g1', title: 'G', bag: bag('g1'), subAreas: [
+ { id: 'ops', type: 'DashBoard', dashboardId: '{280948EC-7BBB-5279-B106-2BDD09451A3A}', dashboardUrl: '/workplace/home_dashboards.aspx', title: 'Ops', bag: bag('ops', [['Client', 'All,Web']]) },
+ ] }] }]);
+ const desired = tree([{ id: 'area_0', title: 'Main', groups: [{ id: 'group_0_0', title: 'G', subAreas: [
+ { id: 'sub_0_0_0', type: 'DashBoard', dashboardId: '280948ec-7bbb-5279-b106-2bdd09451a3a', dashboardUrl: DASHBOARD_LAUNCHER_URL, title: 'Ops' },
+ ] }] }]);
+ const { siteMap } = adoptLiveSitemap(desired, live);
+ const sub = siteMap.areas[0].groups[0].subAreas[0];
+ assert.strictEqual(sub.id, 'ops');
+ assert.strictEqual(sub.dashboardId, '{280948EC-7BBB-5279-B106-2BDD09451A3A}', 'the live spelling, so the XML does not change for nothing');
+ assert.strictEqual(sub.dashboardUrl, '/workplace/home_dashboards.aspx');
+ assert.deepStrictEqual(sub.bag.a, bag('ops', [['Client', 'All,Web']]).a);
+ assert.notStrictEqual(sub.bag, live.areas[0].groups[0].subAreas[0].bag, 'a copy — never aliases the workspace copy');
+ assert.ok(!('__adopted' in sub) && !('__adopted' in siteMap.areas[0]), 'no bookkeeping leaks to the SDK');
+});
+
+test('every adopted dashboard entry gets exactly the launcher both its consumers accept', () => {
+ // The designer recognizes a dashboard entry only when the whole Url equals the launcher; the
+ // runtime's glyph test is a case-SENSITIVE substring match. Only the exact string passes both.
+ const live = tree([{ id: 'a', title: 'M', groups: [{ id: 'g', title: 'G', subAreas: [
+ { id: 'd', type: 'DashBoard', dashboardId: 'x', dashboardUrl: '/somewhere/else.aspx', title: 'D', bag: bag('d') },
+ { id: 'e', type: 'DashBoard', dashboardId: 'y', title: 'E', bag: bag('e') },
+ { id: 'f', type: 'DashBoard', dashboardId: 'z', dashboardUrl: '/WorkPlace/Home_Dashboards.aspx', title: 'F', bag: bag('f') },
+ { id: 'h', type: 'DashBoard', dashboardId: 'w', dashboardUrl: '/workplace/home_dashboards.aspx?pagetype=dashboard', title: 'H', bag: bag('h') },
+ ] }] }]);
+ const desired = tree([{ id: 'area_0', title: 'M', groups: [{ id: 'group_0_0', title: 'G', subAreas: ['x', 'y', 'z', 'w'].map((id, i) => (
+ { id: `s${i}`, type: 'DashBoard', dashboardId: id, dashboardUrl: DASHBOARD_LAUNCHER_URL, title: 'T' })) }] }]);
+ const subs = adoptLiveSitemap(desired, live).siteMap.areas[0].groups[0].subAreas;
+ assert.deepStrictEqual(subs.map((s) => [s.id, s.dashboardUrl]), [['d', DASHBOARD_LAUNCHER_URL], ['e', DASHBOARD_LAUNCHER_URL], ['f', DASHBOARD_LAUNCHER_URL], ['h', DASHBOARD_LAUNCHER_URL]]);
+ assert.ok(isDashboardLauncherUrl('/workplace/home_dashboards.aspx'));
+ for (const bad of ['/WorkPlace/Home_Dashboards.aspx', '/workplace/home_dashboards.aspx?x=1', '/main.aspx', undefined]) assert.ok(!isDashboardLauncherUrl(bad), String(bad));
+});
+
+test('a same-target twin in the entry\u2019s own group is preferred; each live node is adopted at most once', () => {
+ const live = tree([{ id: 'a', title: 'M', groups: [
+ { id: 'g1', title: 'One', subAreas: [entitySub('in_one', 'new_x', 'X', bag('in_one'))] },
+ { id: 'g2', title: 'Two', subAreas: [entitySub('in_two', 'new_x', 'X', bag('in_two'))] },
+ ] }]);
+ const desired = tree([{ id: 'area_0', title: 'M', groups: [
+ { id: 'group_0_0', title: 'Two', subAreas: [entitySub('sub_0_0_0', 'new_x', 'X'), entitySub('sub_0_0_1', 'new_x', 'X'), entitySub('sub_0_0_2', 'new_x', 'X')] },
+ ] }]);
+ const subs = adoptLiveSitemap(desired, live).siteMap.areas[0].groups[0].subAreas;
+ assert.deepStrictEqual(subs.map((s) => s.id), ['in_two', 'in_one', 'sub_0_0_2'], 'own group first, then elsewhere, then new');
+ assert.strictEqual(subs[2].bag, undefined, 'a new entry is built from scratch');
+});
+
+test('areas and groups correspond by label, then by the id an earlier build gave them, then (unlabelled) in order', () => {
+ const live = tree([
+ { id: 'designer_area', title: 'Operations', bag: bag('designer_area'), groups: [] },
+ { id: 'area_1', title: 'Renamed live', bag: bag('area_1'), groups: [] },
+ { id: 'fr_only', title: '', bag: bag('fr_only'), groups: [] },
+ ]);
+ const desired = tree([
+ { id: 'area_0', title: 'operations', groups: [] },
+ { id: 'area_1', title: 'Spec label', groups: [] },
+ { id: 'area_2', title: '', groups: [] },
+ ]);
+ const { siteMap, notes } = adoptLiveSitemap(desired, live);
+ assert.deepStrictEqual(siteMap.areas.map((a) => a.id), ['designer_area', 'area_1', 'fr_only']);
+ assert.ok(notes.some((n) => n.node === 'area' && n.live === 'Renamed live' && n.spec === 'Spec label'));
+ assert.ok(describeSitemapNotes(notes).some((l) => /area "Renamed live": title changes from 'Renamed live' to the spec's 'Spec label'\.$/.test(l)));
+});
+
+// Areas and groups have no target of their own. A label used once on each side identifies one; a repeated label
+// cannot say which live node is which, and neither can position once nodes are added, removed or moved: taking
+// the first live "Main", or the one whose id appDef's numbering repeated, gave a new or reordered node another
+// node's id and bag. The navigation entries a node holds can, when they point at exactly one live node. A node
+// nothing identifies is written as new rather than given another node's bag.
+test('areas and groups with a repeated label pair by the entries they hold, never by position alone', () => {
+ const entries = (prefix, entities, live) => entities.map((e) => ({ id: `${prefix}_${e}`, type: 'Entity', entity: e, title: e, ...(live ? { bag: bag(`${prefix}_${e}`) } : {}) }));
+ const liveNode = (id, title, icon, kidsKey, kidsValue) => ({ id, title, bag: bag(id, [['Icon', icon]]), [kidsKey]: kidsValue });
+ const liveArea = (id, title, icon, entities = []) => liveNode(id, title, icon, 'groups', entities.length ? [{ id: `${id}_g`, title: 'G', bag: bag(`${id}_g`), subAreas: entries(id, entities, true) }] : []);
+ const specArea = (id, title, entities = []) => ({ id, title, groups: entities.length ? [{ id: `${id}_g`, title: 'G', subAreas: entries(`w${id}`, entities, false) }] : [] });
+ const icon = (n) => (n.bag ? n.bag.a.find((p) => p[0] === 'Icon')[1] : null);
+ const areas = (desired, live) => adoptLiveSitemap(tree(desired), tree(live)).siteMap.areas.map((a) => [a.id, icon(a)]);
+ // Two live "Main"s and the first renamed in the spec: each is recognized by its entries, plugin or designer ids alike.
+ for (const [x, y] of [['area_0', 'area_1'], ['d_x', 'd_y']]) {
+ assert.deepStrictEqual(areas([specArea('area_0', 'Ops', ['a']), specArea('area_1', 'Main', ['b'])],
+ [liveArea(x, 'Main', 'first.svg', ['a']), liveArea(y, 'Main', 'second.svg', ['b'])]), [[x, 'first.svg'], [y, 'second.svg']], x);
+ }
+ // One live "Main"; the spec adds a leading area (appDef's `area_0`, the live "Main"'s id) and a second "Main".
+ assert.deepStrictEqual(areas([specArea('area_0', 'New', ['n']), specArea('area_1', 'Main', ['m']), specArea('area_2', 'Main', ['x'])],
+ [liveArea('area_0', 'Main', 'original.svg', ['m'])]), [['area_0_2', null], ['area_0', 'original.svg'], ['area_2', null]]);
+ // The original "Main" moved first, a new "Main" given the live one's `area_1`, and "Other" moved last.
+ assert.deepStrictEqual(areas([specArea('area_0', 'Main', ['m']), specArea('area_1', 'Main', ['n']), specArea('area_2', 'Other', ['o'])],
+ [liveArea('area_0', 'Other', 'other.svg', ['o']), liveArea('area_1', 'Main', 'original.svg', ['m'])]),
+ [['area_1', 'original.svg'], ['area_1_2', null], ['area_0', 'other.svg']]);
+ // Under a repeated label, nodes with no entries to go by are not guessed at — not by id, not by order.
+ assert.deepStrictEqual(areas([specArea('area_0', 'Ops'), specArea('area_1', 'Main')],
+ [liveArea('area_0', 'Main', 'first.svg'), liveArea('area_1', 'Main', 'second.svg')]), [['area_0', null], ['area_1', null]]);
+ assert.deepStrictEqual(areas([specArea('area_0', 'Main'), specArea('area_1', 'Main')],
+ [liveArea('d_x', 'Main', 'first.svg'), liveArea('d_y', 'Main', 'second.svg')]), [['area_0', null], ['area_1', null]]);
+ // An entry both hold is not enough when another spec node holds one of the live node's entries too, nor when
+ // the spec node's entries are spread over two live nodes.
+ assert.deepStrictEqual(areas([specArea('area_0', 'Left', ['a']), specArea('area_1', 'Right', ['b'])],
+ [liveArea('d_x', 'Both', 'both.svg', ['a', 'b'])]), [['area_0', null], ['area_1', null]]);
+ assert.deepStrictEqual(areas([specArea('area_0', 'Merged', ['a', 'b'])],
+ [liveArea('d_x', 'P', 'p.svg', ['a']), liveArea('d_y', 'Q', 'q.svg', ['b'])]), [['area_0', null]]);
+ // Once entries pair its namesake, a renamed "Main" without entries is recognized by its id — also when the spec
+ // gives it entries of its own.
+ assert.deepStrictEqual(areas([specArea('area_0', 'Ops'), specArea('area_1', 'Main', ['m'])],
+ [liveArea('area_0', 'Main', 'first.svg'), liveArea('area_1', 'Main', 'second.svg', ['m'])]), [['area_0', 'first.svg'], ['area_1', 'second.svg']]);
+ assert.deepStrictEqual(areas([specArea('area_0', 'Ops', ['n'])], [liveArea('area_0', 'Main', 'first.svg')]), [['area_0', 'first.svg']]);
+ // A relabelled node is recognized by its entries; an id alone never pairs nodes whose entries all differ.
+ assert.deepStrictEqual(areas([specArea('area_0', 'Ops', ['m'])], [liveArea('d_x', 'Main', 'first.svg', ['m'])]), [['d_x', 'first.svg']]);
+ assert.deepStrictEqual(areas([specArea('area_0', 'New', ['n'])], [liveArea('area_0', 'Main', 'first.svg', ['m'])]), [['area_0', null]]);
+ // Nodes with no label at the SDK's language pair by their entries too — by the best overlap, since an entry can
+ // recur across areas — and in document order only when neither side has entries. Split between two new areas,
+ // the original's entries identify neither, and the order does not hand it to the unrelated leading one.
+ assert.deepStrictEqual(areas([specArea('area_0', '', ['a', 'b', 'c']), specArea('area_1', '', ['a', 'd'])],
+ [liveArea('d_x', '', 'first.svg', ['a', 'b', 'c']), liveArea('d_y', '', 'second.svg', ['a', 'd'])]), [['d_x', 'first.svg'], ['d_y', 'second.svg']]);
+ assert.deepStrictEqual(areas([specArea('area_0', '', ['a', 'd']), specArea('area_1', '', ['a', 'b', 'c'])],
+ [liveArea('d_x', '', 'first.svg', ['a', 'b', 'c']), liveArea('d_y', '', 'second.svg', ['a', 'd'])]), [['d_y', 'second.svg'], ['d_x', 'first.svg']]);
+ assert.deepStrictEqual(areas([specArea('area_0', '', ['n']), specArea('area_1', '', ['a']), specArea('area_2', '', ['b'])],
+ [liveArea('area_0', '', 'original.svg', ['a', 'b'])]), [['area_0', null], ['area_1', null], ['area_2', null]]);
+ assert.deepStrictEqual(areas([specArea('area_0', ''), specArea('area_1', '', ['n'])],
+ [liveArea('d_x', '', 'first.svg'), liveArea('d_y', '', 'second.svg', ['m'])]), [['d_x', 'first.svg'], ['area_1', null]]);
+ // Order is the evidence only where neither side has entries: one side's entries, unmatched, identify nothing.
+ assert.deepStrictEqual(areas([specArea('area_0', '', ['n'])], [liveArea('d_x', '', 'first.svg')]), [['area_0', null]]);
+ assert.deepStrictEqual(areas([specArea('area_0', '')], [liveArea('d_x', '', 'first.svg', ['a'])]), [['area_0', null]]);
+ // A tie can settle once another node pairs: {a} is as close to {a,b} as to {a,c} until {a,b} takes its match.
+ assert.deepStrictEqual(areas([specArea('area_0', '', ['a']), specArea('area_1', '', ['a', 'b'])],
+ [liveArea('d_x', '', 'first.svg', ['a', 'b']), liveArea('d_y', '', 'second.svg', ['a', 'c'])]), [['d_y', 'second.svg'], ['d_x', 'first.svg']]);
+ // Groups follow the same rules within their area: a renamed first "G", and a reorder with a new "G" added.
+ const liveGroup = (id, title, icon, entities) => liveNode(id, title, icon, 'subAreas', entries(id, entities, true));
+ const specGroup = (id, title, entities) => ({ id, title, subAreas: entries(`w${id}`, entities, false) });
+ const groups = (desired, live) => adoptLiveSitemap(tree([{ id: 'area_0', title: 'A', groups: desired }]),
+ tree([{ id: 'area_0', title: 'A', bag: bag('area_0'), groups: live }])).siteMap.areas[0].groups.map((g) => [g.id, icon(g)]);
+ assert.deepStrictEqual(groups([specGroup('group_0_0', 'Renamed', ['a']), specGroup('group_0_1', 'G', ['b'])],
+ [liveGroup('group_0_0', 'G', 'g1.svg', ['a']), liveGroup('group_0_1', 'G', 'g2.svg', ['b'])]), [['group_0_0', 'g1.svg'], ['group_0_1', 'g2.svg']]);
+ assert.deepStrictEqual(groups([specGroup('group_0_0', 'G', ['m']), specGroup('group_0_1', 'G', ['n']), specGroup('group_0_2', 'Other', ['o'])],
+ [liveGroup('group_0_0', 'Other', 'go.svg', ['o']), liveGroup('group_0_1', 'G', 'gm.svg', ['m'])]),
+ [['group_0_1', 'gm.svg'], ['group_0_1_2', null], ['group_0_0', 'go.svg']]);
+ assert.deepStrictEqual(groups([specGroup('group_0_0', '', ['n']), specGroup('group_0_1', '', ['a']), specGroup('group_0_2', '', ['b'])],
+ [liveGroup('group_0_0', '', 'g.svg', ['a', 'b'])]), [['group_0_0', null], ['group_0_1', null], ['group_0_2', null]]);
+});
+
+test('a new node never takes an id an adopted node holds', () => {
+ // appDef numbers by position, so a NEW first area is `area_0` — the id an adopted, moved area keeps.
+ const live = tree([{ id: 'area_0', title: 'Existing', bag: bag('area_0'), groups: [{ id: 'group_0_0', title: 'G', bag: bag('group_0_0'), subAreas: [] }] }]);
+ const desired = tree([
+ { id: 'area_0', title: 'Brand new', groups: [{ id: 'group_0_0', title: 'New group', subAreas: [] }] },
+ { id: 'area_1', title: 'Existing', groups: [{ id: 'group_1_0', title: 'G', subAreas: [] }] },
+ ]);
+ const ids = adoptLiveSitemap(desired, live).siteMap.areas.flatMap((a) => [a.id, ...a.groups.map((g) => g.id)]);
+ assert.deepStrictEqual(ids, ['area_0_2', 'group_0_0_2', 'area_0', 'group_0_0']);
+ assert.strictEqual(new Set(ids.map((i) => i.toLowerCase())).size, ids.length);
+});
+
+test('chrome the spec has not changed since the baseline, but the environment has, is kept', () => {
+ const live = tree([{ id: 'a', title: 'M', groups: [{ id: 'g', title: 'G', subAreas: [
+ { ...entitySub('s', 'new_x', 'Renamed in designer', bag('s')), icon: 'New_Icon.PNG', vectorIcon: '/WebResources/new_/x.svg' },
+ ] }] }]);
+ const desired = tree([{ id: 'area_0', title: 'M', groups: [{ id: 'group_0_0', title: 'G', subAreas: [
+ { ...entitySub('sub', 'new_x', 'Original'), icon: 'new_icon.png', vectorIcon: '/WebResources/new_/y.svg' },
+ ] }] }]);
+ const baseSpec = { appShell: { areas: [{ label: 'M', groups: [{ label: 'G', subAreas: [{ entity: 'new_x', title: 'Original', icon: 'new_icon.png', vectorIcon: '/WebResources/new_/x.svg' }] }] }] } };
+ const { siteMap, notes } = adoptLiveSitemap(desired, live, { baseChrome: chromeByTargetKey(baseSpec) });
+ const sub = siteMap.areas[0].groups[0].subAreas[0];
+ assert.strictEqual(sub.title, 'Renamed in designer', 'kept: unchanged in the spec, changed live');
+ assert.strictEqual(sub.icon, 'New_Icon.PNG', 'the same icon (case aside) is re-emitted as the live string');
+ assert.strictEqual(sub.vectorIcon, '/WebResources/new_/y.svg', 'changed in the spec since the baseline: applied');
+ assert.deepStrictEqual(notes.map((n) => [n.kind, n.field]), [['kept', 'title'], ['changed', 'vectorIcon']]);
+ assert.deepStrictEqual(describeSitemapNotes(notes).length, 1, 'an edit the spec made is not repeated back');
+});
+
+test('a kept value that is absent live is removed from the typed node, not written as empty', () => {
+ const live = tree([{ id: 'a', title: 'M', groups: [{ id: 'g', title: 'G', subAreas: [entitySub('s', 'new_x', 'X', bag('s'))] }] }]);
+ const desired = tree([{ id: 'area_0', title: 'M', groups: [{ id: 'group_0_0', title: 'G', subAreas: [{ ...entitySub('sub', 'new_x', 'X'), icon: 'old.png' }] }] }]);
+ const baseSpec = { appShell: { areas: [{ label: 'M', groups: [{ label: 'G', subAreas: [{ entity: 'new_x', title: 'X', icon: 'old.png' }] }] }] } };
+ const sub = adoptLiveSitemap(desired, live, { baseChrome: chromeByTargetKey(baseSpec) }).siteMap.areas[0].groups[0].subAreas[0];
+ assert.ok(!('icon' in sub), 'the designer removed the icon; the stale spec does not put it back');
+});
+
+test('chromeByTargetKey resolves dashboards and pages through this build\u2019s ids and drops ambiguous targets', () => {
+ const spec = { appShell: { areas: [{ label: 'M', groups: [{ label: 'G', subAreas: [
+ { dashboard: 'Ops', title: 'Operations' },
+ { page: 'home', title: 'Home' },
+ { dashboard: 'Unbuilt', title: 'Nope' },
+ { entity: 'new_x', title: 'X one' }, { entity: 'NEW_X', title: 'X two' },
+ { url: 'https://contoso.example/help', title: 'Help' },
+ ] }] }] } };
+ const map = chromeByTargetKey(spec, { dashboards: { Ops: '{AAAAAAAA-0000-0000-0000-000000000001}' }, pages: { home: 'BBBBBBBB-0000-0000-0000-000000000002' } });
+ assert.deepStrictEqual([...map.keys()].sort(), ['DashBoard:aaaaaaaa-0000-0000-0000-000000000001', 'GenPage:bbbbbbbb-0000-0000-0000-000000000002', 'URL:https://contoso.example/help']);
+ assert.strictEqual(chromeByTargetKey(null).size, 0);
+});
+
+test('chromeByTargetKey takes the ids the baseline recorded here first, and never the spec\u2019s own', () => {
+ const A = 'aaaaaaaa-0000-0000-0000-000000000001';
+ const B = 'bbbbbbbb-0000-0000-0000-000000000002';
+ const F = 'ffffffff-0000-0000-0000-00000000000f';
+ // Downloaded elsewhere: the spec's pins are ANOTHER environment's (F). Built here by name, it resolved
+ // A, which the baseline recorded; the author then renamed the dashboard in the spec.
+ const baseline = {
+ dashboards: [{ name: 'Ops', dashboardId: F }],
+ pages: [{ key: 'home', name: 'Overview', pageId: F }],
+ appShell: { areas: [{ groups: [{ subAreas: [{ dashboard: 'Ops', title: 'Ops' }, { page: 'home', title: 'Home' }] }] }] },
+ __deployedIds: { dashboards: { Ops: A }, pages: {} },
+ };
+ const map = chromeByTargetKey(baseline, { dashboards: { Operations: A }, pages: { home: B } });
+ assert.deepStrictEqual([...map.keys()].sort(), [`DashBoard:${A}`, `GenPage:${B}`], 'recorded first, then this run\u2019s; the spec\u2019s pins never');
+ // Recorded ids win over this run's for the same name.
+ assert.ok(chromeByTargetKey(baseline, { dashboards: { Ops: B } }).has(`DashBoard:${A}`));
+ // A name that is also an Object.prototype member resolves to nothing, not to a function.
+ const odd = { appShell: { areas: [{ groups: [{ subAreas: [{ dashboard: 'constructor', title: 'X' }] }] }] } };
+ assert.strictEqual(chromeByTargetKey(odd, {}).size, 0);
+});
+
+test('a page is referenced by its key; a page NAMED like another page\u2019s key does not capture it', () => {
+ // Valid v2: "home" is one page's key and the other page's name. A reference is a key.
+ const A = 'aaaaaaaa-0000-0000-0000-000000000001';
+ const B = 'bbbbbbbb-0000-0000-0000-000000000002';
+ const baseline = {
+ schemaVersion: 2,
+ pages: [{ key: 'home', name: 'Overview' }, { key: 'reports', name: 'home' }],
+ appShell: { areas: [{ groups: [{ subAreas: [{ page: 'home', title: 'Start' }, { page: 'reports', title: 'Reports' }] }] }] },
+ __deployedIds: { dashboards: {}, pages: { home: A, reports: B } },
+ };
+ const map = chromeByTargetKey(baseline);
+ assert.strictEqual(map.get(`GenPage:${A}`).title, 'Start');
+ assert.strictEqual(map.get(`GenPage:${B}`).title, 'Reports');
+ assert.strictEqual(specSubAreaTargetKey({ page: 'home' }, { pages: { home: A } }), `GenPage:${A}`);
+});
+
+test('keepsLiveValue is the keep rule: spec unchanged since the baseline, environment changed', () => {
+ const base = { title: 'T', icon: 'old.png' };
+ assert.strictEqual(keepsLiveValue('icon', 'old.png', 'designer.png', base), true);
+ assert.strictEqual(keepsLiveValue('icon', 'OLD.PNG', 'designer.png', base), true, 'icons compare case-insensitively');
+ assert.strictEqual(keepsLiveValue('icon', 'new.png', 'designer.png', base), false, 'the spec changed it: written');
+ assert.strictEqual(keepsLiveValue('icon', 'old.png', 'old.png', base), false, 'nothing differs');
+ assert.strictEqual(keepsLiveValue('icon', 'old.png', 'designer.png', undefined), false, 'no baseline: the spec wins');
+ assert.strictEqual(keepsLiveValue('title', 'T', 't', base), true, 'a changed capital is a real rename');
+ assert.strictEqual(keepsLiveValue('nope', 'a', 'b', base), false);
+});
+
+test('removing a node\u2019s last title keeps its other children ahead of the nodes the spec models', () => {
+ // A group titled only at the SDK's language, with a description: <Titles/><Descriptions/><SubArea/>.
+ // Its title is removed. The Descriptions child must move up to the vacated first slot — the sitemap
+ // schema puts Titles and Descriptions before the SubAreas — rather than a SubArea filling it.
+ const groupBag = { a: [['Id', 'group_0_0']], c: [
+ { i: 0, node: { n: 'Titles', a: [], c: [{ n: 'Title', a: [['LCID', '1033'], ['Title', 'Main']] }] } },
+ { i: 1, node: { n: 'Descriptions', a: [], c: [{ n: 'Description', a: [['LCID', '1033'], ['Description', 'D']] }] } },
+ ] };
+ const live = tree([{ id: 'area_0', title: 'M', bag: bag('area_0'), groups: [{ id: 'group_0_0', title: 'Main', bag: groupBag, subAreas: [entitySub('s', 'new_x', 'X', bag('s'))] }] }]);
+ const desired = tree([{ id: 'area_0', title: 'M', groups: [{ id: 'group_0_0', title: undefined, subAreas: [entitySub('sub_0_0_0', 'new_x', 'X')] }] }]);
+ const group = adoptLiveSitemap(desired, live).siteMap.areas[0].groups[0];
+ assert.deepStrictEqual(group.bag.c.map((e) => [e.i, e.node.n]), [[0, 'Descriptions']]);
+ assert.deepStrictEqual(groupBag.c.map((e) => e.i), [0, 1], 'the live bag is not touched');
+ // A title in another language keeps the wrapper, and every index with it.
+ groupBag.c[0].node.c.push({ n: 'Title', a: [['LCID', '1036'], ['Title', 'Principal']] });
+ const kept = adoptLiveSitemap(desired, live).siteMap.areas[0].groups[0];
+ assert.deepStrictEqual(kept.bag.c.map((e) => [e.i, e.node.n]), [[0, 'Titles'], [1, 'Descriptions']]);
+ assert.deepStrictEqual(kept.bag.c[0].node.c.map((t) => t.a[0][1]), ['1036']);
+});
+
+test('nothing live (a first write, or an unreadable copy) leaves the desired tree as it is', () => {
+ const desired = tree([{ id: 'area_0', title: 'M', groups: [{ id: 'group_0_0', title: 'G', subAreas: [entitySub('sub_0_0_0', 'new_x', 'X')] }] }]);
+ for (const live of [undefined, null, {}, { areas: 'nope' }]) {
+ const { siteMap, notes } = adoptLiveSitemap(desired, live);
+ assert.deepStrictEqual(siteMap, desired);
+ assert.deepStrictEqual(notes, []);
+ }
+});
+
+// Every target type the SDK's duplicate check keys has a key here too, and nothing else gets one: a
+// subarea without a target cannot be lined up with a live entry by anything but position.
+test('subAreaTargetKey: a CustomPage is keyed by its page name, case-folded; no target or an unknown type has no key', () => {
+ assert.strictEqual(subAreaTargetKey({ type: 'CustomPage', page: 'new_Board_Abc12' }), 'CustomPage:new_board_abc12');
+ assert.strictEqual(subAreaTargetKey({ type: 'CustomPage' }), undefined);
+ assert.strictEqual(subAreaTargetKey({ type: 'WebResource', url: '/WebResources/x.htm' }), undefined);
+ assert.strictEqual(subAreaTargetKey({ type: 'Entity' }), undefined);
+ assert.strictEqual(subAreaTargetKey(null), undefined);
+ assert.strictEqual(specSubAreaTargetKey({ title: 'Only a title' }), undefined);
+ assert.strictEqual(specSubAreaTargetKey(null), undefined);
+});
diff --git a/plugins/model-apps/scripts/tests/sitemap-pages.test.js b/plugins/model-apps/scripts/tests/sitemap-pages.test.js
index b0ab3675f..2031d81e3 100644
--- a/plugins/model-apps/scripts/tests/sitemap-pages.test.js
+++ b/plugins/model-apps/scripts/tests/sitemap-pages.test.js
@@ -1,7 +1,7 @@
'use strict';
const { test } = require('node:test');
const assert = require('node:assert');
-const { sitemapGenPages, sitemapGenPageIds, fetchSitemap, fetchAppsForPages } = require('../lib/sitemap-pages.js');
+const { sitemapGenPages, sitemapGenPageIds, fetchSitemap, fetchAppsForPages, decodeXmlEntities } = require('../lib/sitemap-pages.js');
const GP_OVERVIEW = '13ecbc57-a3a4-4132-b0a2-a6c6b12691e8';
const GP_DETAIL = '5c0a4889-45fd-46ea-91a8-ff876914d644';
@@ -30,6 +30,17 @@ test('sitemapGenPages: one entry per GenPage subarea, XML-entity-decoded title,
assert.strictEqual(byId.get(GP_DETAIL), 'Order Detail');
});
+test('decodeXmlEntities: predefined entities and numeric references, in one pass', () => {
+ assert.strictEqual(decodeXmlEntities('Orders &amp; Overview &lt;b&gt; &quot;q&quot; &apos;a&apos;'), 'Orders & Overview <b> "q" \'a\'');
+ // A serializer may spell any character as a numeric reference, decimal or hex.
+ assert.strictEqual(decodeXmlEntities('?a=1&#38;b=2&#x26;c=3&#39;'), "?a=1&b=2&c=3'");
+ assert.strictEqual(decodeXmlEntities('&#x1F600;'), '\u{1F600}');
+ // One pass: a double-encoded sequence decodes once, never twice.
+ assert.strictEqual(decodeXmlEntities('a &amp;lt; b &amp;#38; c'), 'a &lt; b &#38; c');
+ // A reference to no character, or not a reference at all, is left as written.
+ assert.strictEqual(decodeXmlEntities('&#xD800; &#1114112; &nbsp; & alone'), '&#xD800; &#1114112; &nbsp; & alone');
+});
+
test('sitemapGenPageIds: sorted-unique lower-cased ids; a page attached twice is deduped', () => {
const twice = XML.replace('</Group>', ` <SubArea Id="s5" GenPageId="${GP_OVERVIEW.toUpperCase()}" Title="dup" />\n </Group>`);
assert.deepStrictEqual(sitemapGenPageIds(twice), [GP_OVERVIEW, GP_DETAIL].sort());
diff --git a/plugins/model-apps/scripts/tests/verify-model-app.test.js b/plugins/model-apps/scripts/tests/verify-model-app.test.js
index 74b1215c7..80083dfe7 100644
--- a/plugins/model-apps/scripts/tests/verify-model-app.test.js
+++ b/plugins/model-apps/scripts/tests/verify-model-app.test.js
@@ -305,6 +305,8 @@ function loadVerifyCli({ parseResult, validateResult = { ok: true }, verifyResul
return { app: { name: 'Support Desk' }, solution: { publisherPrefix: 'new' } };
},
emitResult: (ok, payload) => events.push({ type: 'emitResult', ok, payload }),
+ // Pure, so the real one — the CLI uses it to identify the environment's baseline.
+ dataverseOrigin: require('../lib/dataverse-auth.js').dataverseOrigin,
};
}
if (id === './lib/sdk-http-client.js') {
diff --git a/plugins/model-apps/scripts/tests/verify-spec.test.js b/plugins/model-apps/scripts/tests/verify-spec.test.js
index 43493f01b..869f197bd 100644
--- a/plugins/model-apps/scripts/tests/verify-spec.test.js
+++ b/plugins/model-apps/scripts/tests/verify-spec.test.js
@@ -1,7 +1,7 @@
'use strict';
const { test } = require('node:test');
const assert = require('node:assert');
-const { verifySpec, hasElement, parseFetchXml } = require('../lib/verify-spec.js');
+const { verifySpec, hasElement, parseFetchXml, liveNavEntries, subareaDashboardHasLauncher } = require('../lib/verify-spec.js');
const { sitemapXmlFor } = require('../verify-model-app.js');
const { SDK_ROLE_MARKER } = require('../lib/app-spec.js');
@@ -138,6 +138,227 @@ test('verifySpec: dashboard subarea resolves the dashboard id and matches the si
assert.ok(bad.missing.some((m) => m.kind === 'subarea'), 'a different dashboard id does not satisfy the check');
});
+// AB#6726727: an entry wired to the dashboard but without the launcher Url shows a placeholder icon, and
+// the designer does not treat it as a dashboard entry. That is the shape earlier builds wrote over
+// designer-made entries, and the wiring check alone passed it.
+test('verifySpec: a dashboard nav entry must carry the launcher Url', async () => {
+ const DASH = 'aaaa1111-2222-3333-4444-555566667777';
+ const spec = { entities: [], views: [], charts: [], forms: [], appShell: { areas: [{ groups: [{ subAreas: [{ dashboard: 'Ops', title: 'Ops' }] }] }] } };
+ const reader = (tag) => ({
+ findTable: async () => null, findColumns: async () => [],
+ queryRecords: async (set, opts) => (set === 'systemform' && /name eq 'Ops'/.test(opts.filter) ? [{ formid: DASH }] : []),
+ sitemapXml: async () => `<SiteMap><Area><Group>${tag}</Group></Area></SiteMap>`,
+ });
+ const launcher = (r) => r.checks.find((c) => c.kind === 'subarea-dashboard-launcher');
+ const damaged = await verifySpec(spec, reader(`<SubArea Id="sub_0_0_0" DefaultDashboard="${DASH}" ResourceId="SitemapDesigner.NewSubArea" />`));
+ assert.strictEqual(launcher(damaged).present, false);
+ assert.match(launcher(damaged).detail, /placeholder icon/);
+ // Attribute order and GUID spelling are Dataverse's to choose.
+ const designer = await verifySpec(spec, reader(`<SubArea DefaultDashboard="{${DASH.toUpperCase()}}" Id="ops" Url="/workplace/home_dashboards.aspx" Client="All,Web" />`));
+ assert.strictEqual(launcher(designer).present, true);
+ // Only the entry for THIS dashboard counts: another entry's launcher Url proves nothing.
+ const elsewhere = await verifySpec(spec, reader(`<SubArea Id="x" DefaultDashboard="${DASH}" /><SubArea Id="y" Url="/workplace/home_dashboards.aspx" DefaultDashboard="99999999-0000-0000-0000-000000000000" />`));
+ assert.strictEqual(launcher(elsewhere).present, false);
+ // Only the exact launcher satisfies both consumers: the runtime's glyph test is case-sensitive, and
+ // the designer compares the whole Url.
+ for (const url of ['/WorkPlace/Home_Dashboards.aspx', '/workplace/home_dashboards.aspx?pagetype=dashboard']) {
+ const near = await verifySpec(spec, reader(`<SubArea Id="ops" Url="${url.replace(/&/g, '&amp;')}" DefaultDashboard="${DASH}" />`));
+ assert.strictEqual(launcher(near).present, false, url);
+ }
+ // Not wired at all: the wiring check fails, and there is no second check to double-count it.
+ const unwired = await verifySpec(spec, reader('<SubArea Id="x" Entity="account" />'));
+ assert.strictEqual(launcher(unwired), undefined);
+});
+
+// Only a real nav entry — a SubArea directly under SiteMap/Area/Group — can carry the launcher Url for its
+// dashboard. A `<SubArea …>` in a comment, a CDATA section, a processing instruction or anywhere else is
+// no entry, so a decoy there carrying the Url must not pass the real entry that lacks it.
+test('verifySpec: a SubArea that is no nav entry cannot satisfy the dashboard launcher check', async () => {
+ const DASH = 'aaaa1111-2222-3333-4444-555566667777';
+ const spec = { entities: [], views: [], charts: [], forms: [], appShell: { areas: [{ groups: [{ subAreas: [{ dashboard: 'Ops', title: 'Ops' }] }] }] } };
+ const readerOf = (xml) => ({
+ findTable: async () => null, findColumns: async () => [],
+ queryRecords: async (set, opts) => (set === 'systemform' && /name eq 'Ops'/.test(opts.filter) ? [{ formid: DASH }] : []),
+ sitemapXml: async () => xml,
+ });
+ const launcher = (r) => r.checks.find((c) => c.kind === 'subarea-dashboard-launcher');
+ const decoy = `<SubArea Id="decoy" Url="/workplace/home_dashboards.aspx" DefaultDashboard="${DASH}" />`;
+ const damaged = `<SubArea Id="ops" DefaultDashboard="{${DASH.toUpperCase()}}" />`;
+ for (const xml of [
+ `<SiteMap><Area><Group>${damaged}<!-- ${decoy} --></Group></Area></SiteMap>`,
+ `<SiteMap><Area><Group>${damaged}<![CDATA[${decoy}]]></Group></Area></SiteMap>`,
+ `<?decoy ${decoy}?><SiteMap><Area><Group>${damaged}</Group></Area></SiteMap>`,
+ `<SiteMap>${decoy}<Area><Group>${damaged}</Group></Area></SiteMap>`,
+ `<SiteMap><Area>${decoy}<Group>${damaged}</Group></Area></SiteMap>`,
+ `<SiteMap><Area><Group><SubArea Id="outer" Entity="account">${decoy}</SubArea>${damaged}</Group></Area></SiteMap>`,
+ ]) {
+ const r = await verifySpec(spec, readerOf(xml));
+ assert.strictEqual(launcher(r).present, false, xml);
+ assert.match(launcher(r).detail, /placeholder icon/, xml);
+ assert.strictEqual(subareaDashboardHasLauncher(xml, DASH), false, xml);
+ }
+ // Only a decoy wires it, or the walk cannot read the sitemap at all: no nav entry to fault for a missing
+ // Url, so the check fails with what is actually wrong.
+ for (const xml of [
+ `<SiteMap><Area><Group><!-- ${decoy} --></Group></Area></SiteMap>`,
+ `<SiteMap><Area>${decoy}</Area></SiteMap>`,
+ `<!DOCTYPE SiteMap><SiteMap><Area><Group>${decoy}</Group></Area></SiteMap>`,
+ ]) {
+ const r = await verifySpec(spec, readerOf(xml));
+ assert.strictEqual(launcher(r).present, false, xml);
+ assert.match(launcher(r).detail, /no nav entry points at it/, xml);
+ }
+ // The real entry passes with children of its own and its Url read XML-decoded, as the runtime reads it.
+ const real = `<SiteMap><Area><Group><SubArea Id="ops" Url="&#47;workplace/home_dashboards.aspx" DefaultDashboard="{${DASH.toUpperCase()}}"><Titles><Title LCID="1033" Title="Ops" /></Titles></SubArea></Group></Area></SiteMap>`;
+ assert.strictEqual(launcher(await verifySpec(spec, readerOf(real))).present, true);
+ assert.strictEqual(subareaDashboardHasLauncher(real, DASH), true);
+});
+
+test('verifySpec: a pinned dashboardId verifies a dashboard renamed since the download', async () => {
+ const PIN = 'aaaa1111-2222-3333-4444-555566667777';
+ const spec = { entities: [], views: [], charts: [], forms: [],
+ dashboards: [{ name: 'Command Center - Event operations', dashboardId: PIN, tiles: [{ type: 'list', entity: 'account', viewId: 'v1' }] }],
+ appShell: { areas: [{ groups: [{ subAreas: [{ dashboard: 'Command Center - Event operations', title: 'Event operations' }] }] }] } };
+ const read = {
+ findTable: async () => null, findColumns: async () => [],
+ queryRecords: async (set, opts) => {
+ if (set !== 'systemform') return [];
+ if (opts.filter === `formid eq ${PIN}`) return [{ formid: PIN, name: 'Event operations', type: 0 }];
+ return []; // the stale name finds nothing
+ },
+ sitemapXml: async () => `<SiteMap><Area><Group><SubArea Id="ops" Url="/workplace/home_dashboards.aspx" DefaultDashboard="{${PIN.toUpperCase()}}" /></Group></Area></SiteMap>`,
+ };
+ const r = await verifySpec(spec, read);
+ for (const kind of ['dashboard', 'subarea', 'subarea-dashboard-launcher']) {
+ const chk = r.checks.find((c) => c.kind === kind);
+ assert.ok(chk && chk.present, `${kind}: ${JSON.stringify(chk)}`);
+ }
+});
+
+// The build KEEPS a nav entry's icon that was changed in the designer since the spec's baseline when
+// the spec still has the baseline's value (sitemap-merge.js), so verify must accept exactly that case —
+// or the build's own --verify fails on a value it deliberately left alone.
+test('verifySpec: an icon the build kept from the designer passes only in the case the build keeps it', async () => {
+ const spec = { entities: [{ schemaName: 'new_order', displayName: 'Order', primaryAttribute: { schemaName: 'new_name', displayName: 'Name' }, columns: [] }], views: [], charts: [], forms: [],
+ appShell: { areas: [{ groups: [{ subAreas: [{ entity: 'new_order', title: 'Orders', vectorIcon: '$webresource:new_old.svg' }] }] }] } };
+ const read = {
+ findTable: async () => ({ logicalName: 'new_order' }), findColumns: async () => [{ logicalName: 'new_name' }],
+ sitemapXml: async () => '<SiteMap><Area><Group><SubArea Id="o" Entity="new_order" VectorIcon="$webresource:new_designer.svg" /></Group></Area></SiteMap>',
+ };
+ const vec = (r) => r.checks.find((c) => c.kind === 'subarea-vectorIcon');
+ assert.strictEqual(vec(await verifySpec(spec, read)).present, false, 'no baseline: the spec value is required');
+ const kept = vec(await verifySpec(spec, read, { baselineSpec: JSON.parse(JSON.stringify(spec)) }));
+ assert.strictEqual(kept.present, true, 'the spec still has the baseline value: the designer\u2019s is kept');
+ assert.match(kept.detail, /changed in the designer since the spec\u2019s baseline/);
+ // The SPEC changed it since the baseline: the build writes it, so it must be there.
+ const baseline = JSON.parse(JSON.stringify(spec));
+ baseline.appShell.areas[0].groups[0].subAreas[0].vectorIcon = '$webresource:new_older.svg';
+ assert.strictEqual(vec(await verifySpec(spec, read, { baselineSpec: baseline })).present, false, 'an edit the spec made is still verified');
+});
+
+// The exemption is for a value the build KEPT on an entry that is there — never for a missing entry,
+// whose icon check is the one thing that fails when a URL entry is gone (there is no separate check).
+test('verifySpec: a nav entry missing from the sitemap fails its icon check, baseline or not', async () => {
+ const spec = { entities: [], views: [], charts: [], forms: [],
+ appShell: { areas: [{ groups: [{ subAreas: [{ url: 'https://contoso.example/help?a=1&b=2', title: 'Help', vectorIcon: '$webresource:new_help.svg' }] }] }] } };
+ const baselineSpec = JSON.parse(JSON.stringify(spec));
+ const vec = (r) => r.checks.find((c) => c.kind === 'subarea-vectorIcon');
+ for (const xml of ['<SiteMap />', '', null]) {
+ const read = { findTable: async () => null, findColumns: async () => [], sitemapXml: async () => xml };
+ assert.strictEqual(vec(await verifySpec(spec, read, { baselineSpec })).present, false, JSON.stringify(xml));
+ }
+ // The same entry present with a designer icon IS kept — its URL matched after the XML escaping is read.
+ const read = { findTable: async () => null, findColumns: async () => [],
+ sitemapXml: async () => '<SiteMap><Area><Group><SubArea Id="h" Url="https://contoso.example/help?a=1&amp;b=2" VectorIcon="$webresource:new_designer.svg" /></Group></Area></SiteMap>' };
+ assert.strictEqual(vec(await verifySpec(spec, read, { baselineSpec })).present, true);
+ // Two live entries for the same target: which one the build kept cannot be told, so nothing is.
+ const twice = { ...read, sitemapXml: async () => '<SiteMap><Area><Group><SubArea Id="h" Url="https://contoso.example/help?a=1&amp;b=2" VectorIcon="$webresource:new_designer.svg" /><SubArea Id="h2" Url="https://contoso.example/help?a=1&amp;b=2" /></Group></Area></SiteMap>' };
+ assert.strictEqual(vec(await verifySpec(spec, twice, { baselineSpec })).present, false);
+});
+
+// Only real elements are navigation, and their values are read the way an XML parser reads them.
+test('verifySpec: a kept icon is judged on real SubArea elements, fully XML-decoded', async () => {
+ const spec = { entities: [], views: [], charts: [], forms: [],
+ appShell: { areas: [{ groups: [{ subAreas: [{ url: 'https://contoso.example/help?a=1&b=2', title: 'Help', vectorIcon: '$webresource:new_help.svg' }] }] }] } };
+ const baselineSpec = JSON.parse(JSON.stringify(spec));
+ const vec = (r) => r.checks.find((c) => c.kind === 'subarea-vectorIcon');
+ const liveOf = (inner) => ({ findTable: async () => null, findColumns: async () => [], sitemapXml: async () => `<SiteMap><Area><Group>${inner}</Group></Area></SiteMap>` });
+ // `extra` goes FIRST: an attribute holding a raw `>` must come before the ones the match needs.
+ const entry = (url, extra = '') => `<SubArea Id="h"${extra} Url="${url}" VectorIcon="$webresource:new_designer.svg" />`;
+ // Commented out, or inside CDATA or a processing instruction, an entry is text — nothing was kept.
+ for (const wrapped of [`<!-- ${entry('https://contoso.example/help?a=1&amp;b=2')} -->`, `<![CDATA[${entry('https://contoso.example/help?a=1&amp;b=2')}]]>`, `<?note ${entry('https://contoso.example/help?a=1&amp;b=2')} ?>`]) {
+ assert.strictEqual(vec(await verifySpec(spec, liveOf(wrapped), { baselineSpec })).present, false, wrapped);
+ }
+ // Nor is an element the SDK does not model as navigation: another name that starts the same way, or a
+ // SubArea anywhere but directly under SiteMap/Area/Group (the SDK keeps those as opaque XML).
+ const url = 'https://contoso.example/help?a=1&amp;b=2';
+ for (const other of [
+ `<SubArea-Archived Id="h" Url="${url}" VectorIcon="$webresource:new_designer.svg" />`,
+ `<SubArea:Archived Id="h" Url="${url}" VectorIcon="$webresource:new_designer.svg" />`,
+ `<SubAreaÜ Id="h" Url="${url}" VectorIcon="$webresource:new_designer.svg" />`,
+ `<保存>${entry(url)}</保存>`,
+ `<Descriptions>${entry(url)}</Descriptions>`,
+ `<SubArea Id="outer" Entity="account">${entry(url)}</SubArea>`,
+ ]) {
+ assert.strictEqual(vec(await verifySpec(spec, liveOf(other), { baselineSpec })).present, false, other);
+ }
+ // A document the walk cannot account for completely grants no exemption at all: a document type
+ // declaration, a `<` that starts no tag, a closing tag out of order.
+ for (const xml of [
+ `<!DOCTYPE SiteMap><SiteMap><Area><Group>${entry(url)}</Group></Area></SiteMap>`,
+ `<SiteMap><Area><Group>${entry(url)} a < b</Group></Area></SiteMap>`,
+ `<SiteMap><Area><Group>${entry(url)}</Area></Group></SiteMap>`,
+ `<SiteMap><Area><Group>${entry(url)}`,
+ ]) {
+ const read = { findTable: async () => null, findColumns: async () => [], sitemapXml: async () => xml };
+ assert.strictEqual(vec(await verifySpec(spec, read, { baselineSpec })).present, false, xml);
+ assert.strictEqual(liveNavEntries(xml), null, `unreadable: ${xml}`);
+ }
+ // ...while the real entry after such a sibling is still found: the walk returns to the Group level.
+ assert.strictEqual(vec(await verifySpec(spec, liveOf(`<Descriptions><Description LCID="1033" Description="x" /></Descriptions>${entry(url)}`), { baselineSpec })).present, true);
+ // A numeric reference, either quote style, and a raw `>` inside a value are all the same live entry.
+ for (const live of [
+ entry('https://contoso.example/help?a=1&#38;b=2'),
+ entry('https://contoso.example/help?a=1&#x26;b=2'),
+ "<SubArea Id='h' Url='https://contoso.example/help?a=1&amp;b=2' VectorIcon='$webresource:new_designer.svg' />",
+ entry('https://contoso.example/help?a=1&amp;b=2', ' Description="a > b"'),
+ ]) {
+ assert.strictEqual(vec(await verifySpec(spec, liveOf(live), { baselineSpec })).present, true, live);
+ }
+});
+
+// Verify must line the baseline up the way the build does: by the id each dashboard and page resolves
+// to here. A pin the author dropped, while the name still finds the same dashboard, is the same entry.
+test('verifySpec: an icon kept on a dashboard or page entry is judged by the ids resolved here', async () => {
+ const A = 'aaaa1111-2222-3333-4444-555566667777';
+ const P = 'bbbb1111-2222-3333-4444-555566667777';
+ const spec = { schemaVersion: 2, entities: [], views: [], charts: [], forms: [],
+ dashboards: [{ name: 'Ops', tiles: [{ type: 'list', entity: 'account', viewId: 'v1' }] }],
+ pages: [{ key: 'home', name: 'Home', source: { kind: 'tsx', codeFile: 'home.tsx' } }],
+ appShell: { areas: [{ groups: [{ subAreas: [
+ { dashboard: 'Ops', title: 'Ops', vectorIcon: '$webresource:new_old.svg' },
+ { page: 'home', title: 'Home', vectorIcon: '$webresource:new_oldpage.svg' },
+ ] }] }] } };
+ const baselineSpec = JSON.parse(JSON.stringify(spec));
+ baselineSpec.dashboards[0].dashboardId = A; // downloaded pinned; the author has since dropped the pin
+ baselineSpec.__deployedIds = { dashboards: { Ops: A }, pages: { home: P } };
+ const read = {
+ findTable: async () => null, findColumns: async () => [],
+ queryRecords: async (set, opts) => (set === 'systemform' && /name eq 'Ops'/.test(opts.filter) ? [{ formid: A, name: 'Ops' }] : []),
+ manifest: async () => ({ pages: [{ key: 'home', pageId: P }] }),
+ sitemapPageIds: async () => [P], existenceIds: async () => [P],
+ sitemapXml: async () => '<SiteMap><Area><Group>'
+ + `<SubArea Id="ops" Url="/workplace/home_dashboards.aspx" DefaultDashboard="{${A.toUpperCase()}}" VectorIcon="$webresource:new_designer.svg" />`
+ + `<SubArea Id="home" GenPageId="${P}" VectorIcon="$webresource:new_designerpage.svg" />`
+ + '</Group></Area></SiteMap>',
+ };
+ const icons = (r) => r.checks.filter((c) => c.kind === 'subarea-vectorIcon').map((c) => [c.name, c.present]);
+ assert.deepStrictEqual(icons(await verifySpec(spec, read, { baselineSpec })), [['Ops', true], ['Home', true]]);
+ // Without the ids a dashboard or page resolves to here, nothing lines up and both are required again.
+ const unresolved = { ...read, queryRecords: async () => [], manifest: async () => ({ pages: [] }) };
+ assert.deepStrictEqual(icons(await verifySpec(spec, unresolved, { baselineSpec })), [['Ops', false], ['Home', false]]);
+});
+
test('sitemapXmlFor resolves appmodule -> component 62 -> sitemap', async () => {
const sdk = {
queryRecords: async (set) => {
@@ -861,21 +1082,23 @@ const aiRead = (overrides, effective, opts = {}) => {
};
};
const ALL_ON = { formFill: true, nlSearch: true, nlChart: true, m365: true };
-// The AI form-fill family does not use 1/0: 0 = platform default, 1 = DISABLED, 2 = ENABLED
-// (SDK SETTING_CODEC, mirroring the admin UI). An ENABLED override therefore holds '2'.
+// Every per-app AI setting is a tri-state, not 1/0, and On is '2' for all of them: most use
+// 0 = Default, 1 = Off, 2 = On, while NL charts use 0 = Off, 1 = Auto, 2 = On (the platform's own
+// settings UI; AB#6714731). An ENABLED override therefore holds '2'.
const ALL_SETTINGS_ON = {
FormFillBarUXEnabled: '2',
- NLGridSearchSetting: '1',
- NLChartDataVisualizationSetting: '1',
- m365copilotmodelappenabled: '1',
+ NLGridSearchSetting: '2',
+ NLChartDataVisualizationSetting: '2',
+ m365copilotmodelappenabled: '2',
};
// The overrides a DEFAULT build writes: `resolveAiFlags` seeds formFill/nlSearch/nlChart on and
-// m365 off for any spec carrying `ai`, and verify reconciles that whole set — so a test focusing on
-// ONE feature must still satisfy the other three or it is asserting on unrelated misses.
+// leaves m365 at its platform default ('0') for any spec carrying `ai`, and verify reconciles that
+// whole set — so a test focusing on ONE feature must still satisfy the other three or it is
+// asserting on unrelated misses.
const DEFAULT_SETTINGS = {
FormFillBarUXEnabled: '2',
- NLGridSearchSetting: '1',
- NLChartDataVisualizationSetting: '1',
+ NLGridSearchSetting: '2',
+ NLChartDataVisualizationSetting: '2',
m365copilotmodelappenabled: '0',
};
const aiMissing = (r, feature) => r.missing.find((m) => m.kind === 'ai-feature' && m.name === feature);
@@ -924,16 +1147,35 @@ test('verifySpec: an explicit numeric AI value (2 = on for everyone) is compared
assert.strictEqual(match.ok, true, JSON.stringify(match.missing));
});
-test('verifySpec: an explicit OFF request is verified against 0, not treated as dont-care', async () => {
+test('verifySpec: an explicit OFF request is verified against the setting\u2019s Off value, not treated as dont-care', async () => {
const r = await verifyAi({ ...AI_BASE, ai: { appFeatures: { formFill: false } } }, aiRead({ ...DEFAULT_SETTINGS, FormFillBarUXEnabled: '2' }));
assert.strictEqual(r.ok, false);
- // An explicit disable is still WRITTEN (disabling is never gated), so the override must hold '0'.
+ // An explicit disable is still WRITTEN (disabling is never gated), so the override must hold Off.
// OFF for this family is '1' (DISABLED). '0' would be the platform default — deliberately NOT
- // accepted as off, because it defers to flighting rather than turning the feature off.
+ // accepted as off, because it defers to the platform rather than turning the feature off.
const ok = await verifyAi({ ...AI_BASE, ai: { appFeatures: { formFill: false } } }, aiRead({ ...DEFAULT_SETTINGS, FormFillBarUXEnabled: '1' }));
assert.strictEqual(ok.ok, true, JSON.stringify(ok.missing));
});
+test('verifySpec: Off is each setting\u2019s own value \u2014 1 for grid search and M365, 0 for charts (AB#6714731)', async () => {
+ const spec = { ...AI_BASE, ai: { appFeatures: { formFill: true, nlSearch: false, nlChart: false, m365: false } } };
+ const ok = await verifyAi(spec, aiRead({ FormFillBarUXEnabled: '2', NLGridSearchSetting: '1', NLChartDataVisualizationSetting: '0', m365copilotmodelappenabled: '1' }));
+ assert.strictEqual(ok.ok, true, JSON.stringify(ok.missing));
+ // What earlier builds wrote for `false` was '0' everywhere: Off for charts, but only Default for grid
+ // search and M365, which defers to the platform rather than turning the feature off.
+ const old = await verifyAi(spec, aiRead({ FormFillBarUXEnabled: '2', NLGridSearchSetting: '0', NLChartDataVisualizationSetting: '0', m365copilotmodelappenabled: '0' }));
+ assert.deepStrictEqual(old.missing.filter((m) => m.kind === 'ai-feature').map((m) => m.name).sort(), ['m365', 'nlSearch']);
+});
+
+test('verifySpec: the values earlier builds wrote for ON do not verify as on (AB#6714731)', async () => {
+ // `true` used to be written as '1' outside the form-fill family — Off for grid search and M365,
+ // Auto for charts — and verify expected the same '1', so the build and its check agreed on it.
+ const r = await verifyAi({ ...AI_BASE, ai: { appFeatures: ALL_ON } }, aiRead({ FormFillBarUXEnabled: '2', NLGridSearchSetting: '1', NLChartDataVisualizationSetting: '1', m365copilotmodelappenabled: '1' }));
+ assert.deepStrictEqual(r.missing.filter((m) => m.kind === 'ai-feature').map((m) => m.name).sort(), ['m365', 'nlChart', 'nlSearch']);
+ assert.match(aiMissing(r, 'nlSearch').detail, /requested '2'/);
+ assert.match(aiMissing(r, 'nlChart').detail, /holds '1'/);
+});
+
test('verifySpec: an unreadable override row fails CLOSED (cannot prove => not present)', async () => {
// We could look and looking failed, so we must not claim PASS on the strength of an effective value
// that may simply be the environment default — even though it matches the request here.
@@ -969,8 +1211,9 @@ test('verifySpec: an undeclared feature is still checked when the spec declares
// The partial-declaration half of the same hole: `{ appFeatures: { m365: true } }` still causes
// the build to write formFill/nlSearch/nlChart.
const spec = { ...AI_BASE, ai: { appFeatures: { m365: true } } };
- const r = await verifyAi(spec, aiRead({ m365copilotmodelappenabled: '1' }));
+ const r = await verifyAi(spec, aiRead({ m365copilotmodelappenabled: '2' }));
assert.strictEqual(r.checks.filter((c) => c.kind === 'ai-feature').length, 4);
+ assert.ok(!aiMissing(r, 'm365'), 'the declared feature itself is in place');
assert.ok(aiMissing(r, 'formFill'), 'the undeclared formFill default is reconciled');
assert.strictEqual(r.ok, false);
});
@@ -1053,17 +1296,20 @@ test('verifySpec: a Boolean-spelled override value compares as on/off, independe
// The normalization is deliberately UNCONDITIONAL: branching on a `dataType` read made the
// authoritative comparison depend on a second request that can fail independently, so a transport
// error on that read silently flipped a correctly-applied feature to FAIL.
- // Requested on nlSearch, not formFill: this asserts that a Boolean SPELLING of the stored value is
- // reconciled with the requested one, and that only makes sense for a setting whose on/off really
- // is 1/0. The form-fill family is a 0/1/2 enum (0 = platform default, 1 = disabled, 2 = enabled)
- // and never stores 'true'/'false', so pointing this at formFill would assert a shape the platform
- // cannot produce — and, with the request and the stub naming different settings, it could pass or
- // fail for reasons unrelated to the normalisation under test.
+ // No per-app AI setting is Boolean today — all of them store 0/1/2 — so this guards the
+ // normalisation itself: a Boolean spelling means the feature's OWN on/off value ('true' is '2'),
+ // never the generic '1', which for grid search is Off. Mapping it to '1' would let a stored
+ // 'true' satisfy an explicit OFF request.
const spec = { ...AI_BASE, ai: { appFeatures: { nlSearch: true } } };
return verifyAi(spec, aiRead({ ...DEFAULT_SETTINGS, NLGridSearchSetting: 'true' })).then(async (on) => {
assert.strictEqual(on.ok, true, JSON.stringify(on.missing));
const off = await verifyAi(spec, aiRead({ ...DEFAULT_SETTINGS, NLGridSearchSetting: 'false' }));
assert.strictEqual(off.ok, false, 'a Boolean-spelled setting reading false must still fail');
+ const wantOff = { ...AI_BASE, ai: { appFeatures: { nlSearch: false } } };
+ const inverted = await verifyAi(wantOff, aiRead({ ...DEFAULT_SETTINGS, NLGridSearchSetting: 'true' }));
+ assert.ok(aiMissing(inverted, 'nlSearch'), "a stored 'true' must not satisfy an explicit OFF ('1') request");
+ const offOk = await verifyAi(wantOff, aiRead({ ...DEFAULT_SETTINGS, NLGridSearchSetting: 'false' }));
+ assert.ok(!aiMissing(offOk, 'nlSearch'), "a stored 'false' is this setting's Off");
});
});
@@ -1909,6 +2155,32 @@ test('verify checks dashboard EXISTENCE only when the reader cannot read tiles (
assert.strictEqual(chk.present, true);
});
+// A pinned dashboardId is what the build binds first, so a read of it that FAILS leaves the dashboard
+// unverified — it must not fall through to the name (which may find another app's namesake) or pass.
+test('verifySpec: a pinned dashboardId whose read fails is reported unverified, not proven', async () => {
+ const PIN = 'aaaa1111-2222-3333-4444-555566667777';
+ const spec = { entities: [], views: [], charts: [], forms: [],
+ dashboards: [{ name: 'Operations', dashboardId: PIN, tiles: [{ type: 'list', entity: 'account', viewId: 'v1' }] }],
+ appShell: { areas: [{ groups: [{ subAreas: [{ dashboard: 'Operations', title: 'Operations' }] }] }] } };
+ let byName = 0;
+ const read = {
+ findTable: async () => null, findColumns: async () => [],
+ queryRecords: async (set, opts) => {
+ if (set !== 'systemform') return [];
+ if (opts.filter === `formid eq ${PIN}`) throw new Error('read refused (403)');
+ byName += 1;
+ return [{ formid: 'bbbb1111-2222-3333-4444-555566667777', name: 'Operations', type: 0 }];
+ },
+ sitemapXml: async () => '<SiteMap><Area><Group><SubArea Id="ops" Url="/workplace/home_dashboards.aspx" DefaultDashboard="{BBBB1111-2222-3333-4444-555566667777}" /></Group></Area></SiteMap>',
+ };
+ const r = await verifySpec(spec, read);
+ const chk = r.checks.find((c) => c.kind === 'dashboard');
+ assert.ok(chk && !chk.present, JSON.stringify(chk));
+ assert.match(chk.detail, /its dashboardId could not be resolved \(read refused \(403\)\) — unverified, not proven correct/);
+ assert.strictEqual(r.ok, false);
+ assert.strictEqual(byName, 0, 'the name is not tried after the pinned read failed — it could find another app\u2019s namesake');
+});
+
test('verify ignores non-chart tiles when proving a dashboard', async () => {
const chk = await dashCheck({ components: [{ type: 'list', name: 'L', parameters: { TargetEntityType: 'new_ticket', ViewId: DASH_VIEW } }, { type: 'iframe', name: 'I', parameters: { Url: 'https://x' } }] });
assert.strictEqual(chk.present, true, chk.detail);
diff --git a/plugins/model-apps/scripts/tests/workspace-projection-real-bundle.test.js b/plugins/model-apps/scripts/tests/workspace-projection-real-bundle.test.js
new file mode 100644
index 000000000..c348549c5
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/workspace-projection-real-bundle.test.js
@@ -0,0 +1,170 @@
+'use strict';
+// REAL BUNDLE: a workspace saved by an earlier version of this plugin, read by the SDK it vendors now.
+//
+// The SDK stamps every workspace copy with the version of the parsers that projected it
+// (`projectionVersion`) and REFUSES to push a copy stamped with another version
+// (ARTIFACT_PROJECTION_STALE): after a parser change, an untouched part of an old copy reads as edited,
+// and pushing it could overwrite server content nobody touched. Every re-vendor that raises the version
+// makes every existing `.maker-workspace` "old". The upgrade stays invisible because of two SDK
+// behaviours the build relies on, pinned here:
+// 1. a plain fetch RE-READS a clean old copy (no unpushed edits) and stamps it current — and the build
+// fetches every existing form, view, chart and app before it edits one;
+// 2. a plain fetch KEEPS a copy that still holds unpushed edits (an interrupted build's) while the
+// server has not moved, so that copy is refused at push — and the build then names a manual reset an
+// operator can make safely (stop other runs first), instead of the SDK's own `fetchArtifact(...)` advice.
+// Driven against the app artifact over a fake Dataverse (the same shape as
+// app-ai-description-real-bundle.test.js), because the projection check is the same for every type.
+const test = require('node:test');
+const assert = require('node:assert');
+const os = require('node:os');
+const path = require('node:path');
+const fs = require('node:fs');
+const { makeRunner, BuildHalt } = require('../lib/entity-provision.js');
+
+const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');
+const APP_ID = '11111111-1111-1111-1111-111111111111';
+const APP_UNIQUE = 'new_probeapp';
+const TABLE_METADATA_ID = '22222222-2222-2222-2222-222222222222';
+const SITEMAP_ID = '55555555-5555-5555-5555-555555555555';
+const SITEMAP_XML = '<SiteMap IntroducedVersion="7.0.0.0"><Area Id="area_0" ShowGroups="true"><Titles><Title LCID="1033" Title="Main" /></Titles>'
+ + '<Group Id="group_0_0"><Titles><Title LCID="1033" Title="Main" /></Titles>'
+ + '<SubArea Id="sub_0_0_0" Entity="new_torder" Client="All" Sku="All"><Titles><Title LCID="1033" Title="Orders" /></Titles></SubArea>'
+ + '</Group></Area></SiteMap>';
+
+const tempDirs = [];
+test.after(() => { for (const d of tempDirs) fs.rmSync(d, { recursive: true, force: true }); });
+
+async function freshSdk() {
+ const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'projection-'));
+ tempDirs.push(dir);
+ const writes = [];
+ // `state.etag` is the rows' version, read on every call, so a test can move the environment under the SDK.
+ const state = { etag: 'W/"1"' };
+ const appRow = () => ({ appmoduleid: APP_ID, appmoduleidunique: '33333333-3333-3333-3333-333333333333', name: 'Probe', uniquename: APP_UNIQUE, description: 'Tickets', componentstate: 0, '@odata.etag': state.etag });
+ const sitemapRow = () => ({ sitemapid: SITEMAP_ID, sitemapnameunique: APP_UNIQUE, sitemapxml: SITEMAP_XML, '@odata.etag': state.etag });
+ const httpClient = {
+ get: async (url) => {
+ const m = /EntityDefinitions\(LogicalName='([^']+)'\)/.exec(url);
+ if (m) return { status: 200, headers: {}, body: { LogicalName: m[1], MetadataId: TABLE_METADATA_ID, EntitySetName: `${m[1]}s` } };
+ if (/\/appmodulecomponents/.test(url)) {
+ // componenttype 62 is the SITEMAP component; 1 is a table. The filter arrives URL-encoded.
+ const wantsSitemap = /componenttype(%20| )eq(%20| )62/.test(url);
+ return { status: 200, headers: {}, body: { value: wantsSitemap ? [{ objectid: SITEMAP_ID, componenttype: 62 }] : [{ objectid: TABLE_METADATA_ID, componenttype: 1 }] } };
+ }
+ if (/\/sitemaps/.test(url)) {
+ const multi = /RetrieveUnpublishedMultiple/i.test(url) || /\/sitemaps\?/.test(url);
+ return { status: 200, headers: { etag: state.etag }, body: multi ? { value: [sitemapRow()] } : sitemapRow() };
+ }
+ if (/\/appmodules/.test(url)) {
+ const multi = /RetrieveUnpublishedMultiple/i.test(url) || /\/appmodules\?/.test(url);
+ return { status: 200, headers: { etag: state.etag }, body: multi ? { value: [appRow()] } : appRow() };
+ }
+ return { status: 200, headers: {}, body: { value: [] } };
+ },
+ post: async (url, body) => { writes.push({ verb: 'post', url: String(url), body }); return { status: 204, headers: {}, body: {} }; },
+ patch: async (url, body) => { writes.push({ verb: 'patch', url: String(url), body }); return { status: 204, headers: { etag: 'W/"2"' }, body: {} }; },
+ delete: async () => ({ status: 204, headers: {}, body: {} }),
+ put: async () => ({ status: 204, headers: {}, body: {} }),
+ };
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(dir), instanceUrl: 'https://contoso.crm.dynamics.com', httpClient });
+ await sdk.initWorkspace();
+ return { sdk, dir, writes, state };
+}
+
+// Stamp the stored copy the way the plugin's previous SDK left it. The vendored SDK that shipped with
+// 2.10.0 wrote projection 3; nothing else about the copy changes, which is exactly the upgraded state.
+function stampOlderProjection(dir, id) {
+ const metaFile = path.join(dir, '.metadata', 'apps', `${id}.meta.json`);
+ assert.ok(fs.existsSync(metaFile), `the SDK keeps the app's metadata at ${metaFile}`);
+ const meta = JSON.parse(fs.readFileSync(metaFile, 'utf8'));
+ assert.ok(Number.isInteger(meta.projectionVersion) && meta.projectionVersion > 3,
+ `precondition: the vendored SDK stamps a projection newer than 3 (got ${meta.projectionVersion})`);
+ fs.writeFileSync(metaFile, JSON.stringify({ ...meta, projectionVersion: 3 }), 'utf8');
+}
+
+const appWrites = (writes) => writes.filter((w) => w.verb === 'patch' && /\/appmodules\(/.test(w.url));
+
+test('REAL BUNDLE: a clean copy from an earlier projection is refused at push, and a plain fetch re-reads it', async () => {
+ const { sdk, dir, writes } = await freshSdk();
+ await sdk.fetchArtifact('app', APP_ID);
+ stampOlderProjection(dir, APP_ID);
+
+ // The hazard is real: an old copy is never pushed as it stands.
+ await assert.rejects(sdk.pushArtifact('app', APP_ID), (e) => e && e.code === 'ARTIFACT_PROJECTION_STALE');
+ assert.strictEqual(writes.length, 0, 'the refusal writes nothing');
+
+ // The build's existing-app path is exactly this: a plain fetch, then its edits, then the push.
+ await sdk.fetchArtifact('app', APP_ID);
+ await sdk.updateElement('app', APP_ID, '/description', 'Tickets and orders');
+ const pushed = await sdk.pushArtifact('app', APP_ID);
+ assert.strictEqual(pushed.saved, true, 'the re-read copy pushes');
+ assert.strictEqual(appWrites(writes).length, 1, 'with one header write');
+ assert.strictEqual(appWrites(writes)[0].body.description, 'Tickets and orders');
+});
+
+// An earlier build's copy: edited, never pushed, stamped with the old projection. A plain fetch keeps it.
+async function interruptedCopy() {
+ const made = await freshSdk();
+ await made.sdk.fetchArtifact('app', APP_ID);
+ await made.sdk.updateElement('app', APP_ID, '/description', 'Edited by an interrupted build');
+ stampOlderProjection(made.dir, APP_ID);
+ const kept = await made.sdk.fetchArtifact('app', APP_ID);
+ assert.strictEqual(kept.description, 'Edited by an interrupted build', 'the server has not moved, so the plain fetch keeps the unpushed copy');
+ return made;
+}
+
+test('REAL BUNDLE: an old copy holding unpushed edits is refused at push, and the halt names a reset that stops other runs and keeps the baseline and approvals', async () => {
+ const { sdk, writes } = await interruptedCopy();
+ const events = [];
+ const runner = makeRunner({ emit: (e) => events.push(e), total: 1 });
+ await assert.rejects(() => runner.run('app-shell', 'app "Probe"', () => sdk.pushArtifact('app', APP_ID)), (err) => {
+ assert.ok(err instanceof BuildHalt, 'the refusal halts the build');
+ assert.strictEqual(err.code, 'ARTIFACT_PROJECTION_STALE', 'with the SDK code kept for the caller');
+ assert.match(err.message, /Refusing to push app/, 'the SDK reason stays in the message');
+ assert.match(err.message, /earlier version of this plugin/, 'it says where the copy came from');
+ assert.match(err.message, /To reset it, stop any other build or teardown using the \.maker-workspace directory \(or the --workspace one\), then delete everything in it except last-applied\.json and destructive-approval\.json, and re-run/,
+ 'and names the step an operator can take, keeping the navigation baseline and the approval record');
+ return true;
+ });
+ assert.strictEqual(writes.length, 0, 'nothing was written');
+ assert.ok(events.some((e) => e.status === 'error' && e.phase === 'app-shell'), 'the failure is reported on the phase');
+ // The build does not reset the copy itself (an overwrite could discard another build's newer edits):
+ // after the halt it still holds the interrupted build's edit, for the manual reset to remove.
+ assert.strictEqual((await sdk.getArtifact('app', APP_ID)).description, 'Edited by an interrupted build');
+});
+// The other way such a copy surfaces: the environment's copy moved after it was fetched (published or edited
+// in Maker, or the concurrent edit a VERSION_CONFLICT halt kept the copy against), so the build's plain fetch
+// refuses before any push. Measured live on a 2.10.0 workspace. The SDK's advice (`{ overwrite: true }`) is an
+// API call, and clearing the copy straight away would let the same spec overwrite the change — so the halt
+// asks for a look at the change first (it may be another maker's), and only then the usual reset.
+test('REAL BUNDLE: a copy holding unpushed edits over a moved environment halts at the fetch, asking for a review before the reset', async () => {
+ const { sdk, writes, state } = await interruptedCopy();
+ state.etag = 'W/"2"';
+ const runner = makeRunner({ emit: () => {}, total: 1 });
+ await assert.rejects(() => runner.run('forms', 'app "Probe"', () => sdk.fetchArtifact('app', APP_ID)), (err) => {
+ assert.ok(err instanceof BuildHalt);
+ assert.strictEqual(err.code, 'LOCAL_EDITS_WOULD_BE_LOST', 'the SDK code is kept');
+ assert.match(err.message, /the environment's copy changed after this workspace copy was fetched/);
+ assert.match(err.message, /A re-run applies the spec over that change, so first look at it in Maker and put into the spec anything that should stay; then stop any other build or teardown using the \.maker-workspace directory \(or the --workspace one\), then delete everything in it except last-applied\.json and destructive-approval\.json, and re-run\./,
+ 'the review comes before the reset: the copy may be the fence a concurrent-edit halt keeps');
+ return true;
+ });
+ assert.strictEqual(writes.length, 0, 'nothing was written');
+});
+
+test('the runner adds no remedy to an SDK error it has none for', async () => {
+ const { SdkError } = require(BUNDLE);
+ const runner = makeRunner({ emit: () => {}, total: 1 });
+ // Including another refusal phrased like a stale projection: a language mismatch keeps the SDK's remedy.
+ const mismatch = `Refusing to push form '${APP_ID}': it was fetched with languageCode 1036 but this SDK is configured with 1033.`;
+ for (const [code, message] of [['PATH_NOT_FOUND', 'No node at /tabs/9'], ['ARTIFACT_LANGUAGE_MISMATCH', mismatch]]) {
+ await assert.rejects(
+ () => runner.run('forms', 'form "Customer"', async () => { throw new SdkError(code, message); }),
+ (err) => {
+ assert.strictEqual(err.message, `forms failed: ${message}`);
+ assert.strictEqual(err.code, code);
+ return true;
+ });
+ }
+});
diff --git a/plugins/model-apps/scripts/vendor/PROVENANCE.json b/plugins/model-apps/scripts/vendor/PROVENANCE.json
index 096ad7d14..b1951cab1 100644
--- a/plugins/model-apps/scripts/vendor/PROVENANCE.json
+++ b/plugins/model-apps/scripts/vendor/PROVENANCE.json
@@ -1,14 +1,14 @@
{
- "commit": "0f263094d8fe3acd74049a6dfa336932682f8324",
- "subject": "AB#39863285 Configure executive summary block UX",
+ "commit": "dac2cf1e3bed12ff733754e1045b95a1e4b180e2",
+ "subject": "cds-maker-sdk: form-embed follow-ups — per-table tokens, edit after publish, embed conversion, SQL deadlock re-send, read-back adoption",
"dirtySdkPackage": 0,
- "libBuiltAt": "2026-09-28T20:54:48.427Z",
- "newestSrcAt": "2026-09-28T18:13:56.883Z",
+ "libBuiltAt": "2026-09-30T01:00:29.443Z",
+ "newestSrcAt": "2026-09-30T00:27:58.502Z",
"libIsStale": false,
"nostub": false,
"esbuildVersion": "0.28.1",
"nodeVersion": "v20.20.2",
- "builtAt": "2026-09-28T20:57:40.665Z",
- "bundleSha256": "83939ecfb8c1e936c322ad71bfb60394e9ccbbe0a729452ed8f5f4eee9ce72f7",
- "bundleBytes": 790605
+ "builtAt": "2026-09-30T01:01:39.005Z",
+ "bundleSha256": "e3bb276bd822c35609a18f3730d11e0430ca7cf38ea07f341c454f803f576b59",
+ "bundleBytes": 818077
}
diff --git a/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs b/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs
index e63145ad3..16f3d8d3f 100644
--- a/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs
+++ b/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs
@@ -25,33 +25,33 @@
}
globalThis.document=globalThis.document||globalThis.window.document;
})();
-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}:
+var S1=Object.create;var hl=Object.defineProperty;var N1=Object.getOwnPropertyDescriptor;var D1=Object.getOwnPropertyNames;var I1=Object.getPrototypeOf,_1=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}},pn=(e,t)=>{for(var r in t)hl(e,r,{get:t[r],enumerable:!0})},ml=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of D1(t))!_1.call(e,i)&&i!==r&&hl(e,i,{get:()=>t[i],enumerable:!(n=N1(t,i))||n.enumerable});return e},qn=(e,t,r)=>(ml(e,t,"default"),r&&ml(r,t,"default")),ce=(e,t,r)=>(r=e!=null?S1(I1(e)):{},ml(t||!e||!e.__esModule?hl(r,"default",{value:e,enumerable:!0}):r,e)),Mr=e=>ml(hl({},"__esModule",{value:!0}),e);var Ai=y(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.DateTimeBehavior=D.PrecisionSource=D.StringFormatName=D.SourceType=D.ImeMode=D.SolutionEntityTypeCodeExtToComponentTypeCode=D.SolutionComponentTypeCodeToEntityTypeCodeExt=D.SolutionComponentVirtualAttributeSubtype=D.EntityTypeCode=D.SolutionComponentTypeCodeExt=D.RootComponentBehavior=D.SolutionComponentTypeCode=D.EntityKeyIndexStatus=D.ViewStateCode=D.ViewStatusCode=D.RelationshipSecurityTypes=D.CascadeType=D.RelationshipTypeExt=D.RelationshipType=D.AppSubType=D.BusinessProcessType=D.WorkflowCategory=D.WorkflowScope=D.WorkflowTypeCode=D.StatusCodeEnabledDisabled=D.StateCodeEnabledDisabled=D.StatusCode=D.StateCode=D.OptionSetType=D.AttributeTypeCodeNum=D.AttributeFormatName=D.AttributeFormatCode=D.AttributeTypeName=D.AttributeTypeCode=D.PluginSourceType=D.AuthType=D.PluginIsolationMode=D.ComponentState=D.ChartType=D.ChartsType=D.ViewType=D.AttributeType=D.ActivationState=D.FormPresentation=D.FormType=D.TableTypeCode=D.TableTypes=D.ActivityTypeMask=D.PrincipalType=D.OwnershipTypes=void 0;D.QueryType=D.KnownCustomSolutionComponentEntitySetName=D.TeamTypeEnum=D.EnvironmentVariableDefinitionTypeEnum=D.ConnectorTypeEnum=D.RoleInheritance=D.DefaultRoleTemplates=D.DeleteDependencyErrorCode=D.ServiceEndpointConnectionMode=D.ServiceEndpointContract=D.ServiceNamespaceFormat=D.ConnectionRoleCategory=D.ReportTypeCode=D.SdkMessageProcessingMode=D.SupportedDeployment=D.SdkMessageProcessingStage=D.WebResourceTypeCode=D.IntegerFormat=D.DateTimeFormat=void 0;var s0;(function(e){e.None="None",e.UserOwned="UserOwned",e.TeamOwned="TeamOwned",e.BusinessOwned="BusinessOwned",e.OrganizationOwned="OrganizationOwned",e.BusinessParented="BusinessParented",e.Filtered="Filtered"})(s0||(D.OwnershipTypes=s0={}));var l0;(function(e){e.User="Microsoft.Dynamics.CRM.systemuser",e.Team="Microsoft.Dynamics.CRM.team"})(l0||(D.PrincipalType=l0={}));var u0;(function(e){e[e.DoNotDisplayInActivityMenus=0]="DoNotDisplayInActivityMenus",e[e.DisplayInActivityMenus=1]="DisplayInActivityMenus"})(u0||(D.ActivityTypeMask=u0={}));var c0;(function(e){e.Activity="Activity",e.Virtual="Virtual",e.Standard="Standard",e.Elastic="Elastic"})(c0||(D.TableTypes=c0={}));var d0;(function(e){e.Standard="Standard",e.Virtual="Virtual",e.Elastic="Elastic"})(d0||(D.TableTypeCode=d0={}));var p0;(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"})(p0||(D.FormType=p0={}));var f0;(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(f0||(D.FormPresentation=f0={}));var m0;(function(e){e[e.Inactive=0]="Inactive",e[e.Active=1]="Active"})(m0||(D.ActivationState=m0={}));var h0;(function(e){e[e.String=0]="String",e[e.Number=1]="Number",e[e.Picklist=2]="Picklist"})(h0||(D.AttributeType=h0={}));var g0;(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"})(g0||(D.ViewType=g0={}));var v0;(function(e){e[e.ASPChart=0]="ASPChart",e[e.PowerBI=1]="PowerBI"})(v0||(D.ChartsType=v0={}));var y0;(function(e){e[e.DataAndInteractionCentric=0]="DataAndInteractionCentric",e[e.InteractionCentric=1]="InteractionCentric"})(y0||(D.ChartType=y0={}));var b0;(function(e){e[e.Published=0]="Published",e[e.Unpublished=1]="Unpublished",e[e.Deleted=2]="Deleted",e[e.DeletedUnpublished=3]="DeletedUnpublished"})(b0||(D.ComponentState=b0={}));var w0;(function(e){e[e.None=1]="None",e[e.Sandbox=2]="Sandbox",e[e.External=3]="External"})(w0||(D.PluginIsolationMode=w0={}));var A0;(function(e){e[e.BasicAuth=0]="BasicAuth"})(A0||(D.AuthType=A0={}));var E0;(function(e){e[e.Database=0]="Database",e[e.Disk=1]="Disk",e[e.Normal=2]="Normal",e[e.AzureWebApp=3]="AzureWebApp"})(E0||(D.PluginSourceType=E0={}));var C0;(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"})(C0||(D.AttributeTypeCode=C0={}));var S0;(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"})(S0||(D.AttributeTypeName=S0={}));var N0;(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"})(N0||(D.AttributeFormatCode=N0={}));var D0;(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"})(D0||(D.AttributeFormatName=D0={}));var I0;(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"})(I0||(D.AttributeTypeCodeNum=I0={}));var _0;(function(e){e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean"})(_0||(D.OptionSetType=_0={}));var T0;(function(e){e[e.Draft=0]="Draft",e[e.Activated=1]="Activated"})(T0||(D.StateCode=T0={}));var P0;(function(e){e[e.Draft=1]="Draft",e[e.Activated=2]="Activated"})(P0||(D.StatusCode=P0={}));var R0;(function(e){e[e.Enabled=0]="Enabled",e[e.Disabled=1]="Disabled"})(R0||(D.StateCodeEnabledDisabled=R0={}));var O0;(function(e){e[e.Enabled=1]="Enabled",e[e.Disabled=2]="Disabled"})(O0||(D.StatusCodeEnabledDisabled=O0={}));var x0;(function(e){e[e.Definition=1]="Definition",e[e.Activation=2]="Activation",e[e.Template=3]="Template"})(x0||(D.WorkflowTypeCode=x0={}));var F0;(function(e){e[e.User=1]="User",e[e.BusinessUnit=2]="BusinessUnit",e[e.ParentChildBusinessUnit=3]="ParentChildBusinessUnit",e[e.Organization=4]="Organization"})(F0||(D.WorkflowScope=F0={}));var L0;(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"})(L0||(D.WorkflowCategory=L0={}));var k0;(function(e){e[e.None=-1]="None",e[e.BusinessFlow=0]="BusinessFlow",e[e.TaskFlow=1]="TaskFlow"})(k0||(D.BusinessProcessType=k0={}));var M0;(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"})(M0||(D.AppSubType=M0={}));var B0;(function(e){e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(B0||(D.RelationshipType=B0={}));var U0;(function(e){e.ManyToOneRelationship="ManyToOneRelationship",e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(U0||(D.RelationshipTypeExt=U0={}));var $0;(function(e){e.NoCascade="NoCascade",e.Cascade="Cascade",e.Active="Active",e.UserOwned="UserOwned",e.RemoveLink="RemoveLink",e.Restrict="Restrict"})($0||(D.CascadeType=$0={}));var q0;(function(e){e.None="None",e.Append="Append",e.ParentChild="ParentChild",e.Pointer="Pointer",e.Inheritance="Inheritance"})(q0||(D.RelationshipSecurityTypes=q0={}));var V0;(function(e){e[e.Active=1]="Active",e[e.Inactive=2]="Inactive"})(V0||(D.ViewStatusCode=V0={}));var G0;(function(e){e[e.Active=0]="Active",e[e.Inactive=1]="Inactive"})(G0||(D.ViewStateCode=G0={}));var z0;(function(e){e.Active="Active",e.Failed="Failed",e.InProgress="InProgress",e.Pending="Pending"})(z0||(D.EntityKeyIndexStatus=z0={}));var W0;(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"})(W0||(D.SolutionComponentTypeCode=W0={}));var j0;(function(e){e[e.IncludeSubcomponents=0]="IncludeSubcomponents",e[e.DoNotIncludeSubcomponents=1]="DoNotIncludeSubcomponents",e[e.IncludeAsShellOnly=2]="IncludeAsShellOnly"})(j0||(D.RootComponentBehavior=j0={}));var gl;(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"})(gl||(D.SolutionComponentTypeCodeExt=gl={}));var vl;(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"})(vl||(D.EntityTypeCode=vl={}));var H0;(function(e){e.MultiSelectPicklist="MultiSelectPicklist",e.File="File",e.Image="Image"})(H0||(D.SolutionComponentVirtualAttributeSubtype=H0={}));function T1(e){let t=gl[e];return vl[t]}D.SolutionComponentTypeCodeToEntityTypeCodeExt=T1;function P1(e){let t=vl[e];return gl[t]}D.SolutionEntityTypeCodeExtToComponentTypeCode=P1;var K0;(function(e){e.Active="Active",e.Auto="Auto",e.Disabled="Disabled",e.Inactive="Inactive"})(K0||(D.ImeMode=K0={}));var J0;(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"})(J0||(D.SourceType=J0={}));var Q0;(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"})(Q0||(D.StringFormatName=Q0={}));var X0;(function(e){e[e.PrecisionProperty=0]="PrecisionProperty",e[e.Organization=1]="Organization",e[e.TransactionCurrency=2]="TransactionCurrency"})(X0||(D.PrecisionSource=X0={}));var Y0;(function(e){e.UserLocal="UserLocal",e.DateOnly="DateOnly",e.TimeZoneIndependent="TimeZoneIndependent"})(Y0||(D.DateTimeBehavior=Y0={}));var Z0;(function(e){e.DateOnly="DateOnly",e.DateAndTime="DateAndTime"})(Z0||(D.DateTimeFormat=Z0={}));var ev;(function(e){e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale"})(ev||(D.IntegerFormat=ev={}));var tv;(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"})(tv||(D.WebResourceTypeCode=tv={}));var rv;(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"})(rv||(D.SdkMessageProcessingStage=rv={}));var nv;(function(e){e[e.ServerOnly=0]="ServerOnly",e[e.OutlookClientOnly=1]="OutlookClientOnly",e[e.Both=2]="Both"})(nv||(D.SupportedDeployment=nv={}));var iv;(function(e){e[e.Synchronous=0]="Synchronous",e[e.Asynchronous=1]="Asynchronous"})(iv||(D.SdkMessageProcessingMode=iv={}));var av;(function(e){e[e.ReportingServicesReport=1]="ReportingServicesReport",e[e.OtherReport=2]="OtherReport",e[e.LinkedReport=3]="LinkedReport"})(av||(D.ReportTypeCode=av={}));var ov;(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"})(ov||(D.ConnectionRoleCategory=ov={}));var sv;(function(e){e[e.Name=1]="Name",e[e.Address=2]="Address"})(sv||(D.ServiceNamespaceFormat=sv={}));var lv;(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"})(lv||(D.ServiceEndpointContract=lv={}));var uv;(function(e){e[e.Normal=1]="Normal",e[e.Federated=2]="Federated"})(uv||(D.ServiceEndpointConnectionMode=uv={}));var cv;(function(e){e.CannotDeleteInUseComponent="0x8004f01f",e.CannotDeleteInUseAttribute="0x80048418",e.CannotDeleteInUseOptionSet="0x80048417",e.CannotDeleteInUseEntity="0x80048420",e.CannotUninstallWithDependencies="0x8004F01D"})(cv||(D.DeleteDependencyErrorCode=cv={}));var dv;(function(e){e.SystemAdministrator="627090FF-40A3-4053-8790-584EDC5BE201",e.SystemCustomizer="119F245C-3CC8-4B62-B31C-D1A046CED15D"})(dv||(D.DefaultRoleTemplates=dv={}));var pv;(function(e){e[e.DefaultTeamPrivilege=0]="DefaultTeamPrivilege",e[e.DirectUserAndTeamPrivilege=1]="DirectUserAndTeamPrivilege"})(pv||(D.RoleInheritance=pv={}));var fv;(function(e){e[e.NotSpecified=0]="NotSpecified",e[e.CustomConnector=1]="CustomConnector"})(fv||(D.ConnectorTypeEnum=fv={}));var mv;(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"})(mv||(D.EnvironmentVariableDefinitionTypeEnum=mv={}));var hv;(function(e){e[e.Owner=0]="Owner",e[e.Access=1]="Access",e[e.AADSecurityGroup=2]="AADSecurityGroup",e[e.AADOfficeGroup=3]="AADOfficeGroup"})(hv||(D.TeamTypeEnum=hv={}));var gv;(function(e){e.Bots="bots"})(gv||(D.KnownCustomSolutionComponentEntitySetName=gv={}));var vv;(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"})(vv||(D.QueryType=vv={}))});var te=y(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.IncompatibleWorkspaceError=re.PathTraversalError=re.AmbiguousArtifactError=re.JsonPointerError=re.NotImplementedError=re.WorkspaceNotInitializedError=re.ConnectionError=re.VersionConflictError=re.LocalEditsWouldBeLostError=re.StaleArtifactError=re.InvalidArgumentError=re.ValidationError=re.PathNotFoundError=re.ArtifactNotFoundError=re.readPartialTokens=re.withPartialTokens=re.SdkError=void 0;var ot=class extends Error{constructor(t,r){super(r),this.code=t,Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}};re.SdkError=ot;var yv=Symbol.for("cds-maker-sdk.partialWriteTokens");function R1(e,t){return typeof e=="object"&&e!==null&&(e[yv]=t),e}re.withPartialTokens=R1;function O1(e){let t=e;for(let r=0;t&&typeof t=="object"&&r<8;r++){let n=t[yv];if(n&&typeof n=="object")return n;t=t.cause}}re.readPartialTokens=O1;var xd=class extends ot{constructor(t,r){super("ARTIFACT_NOT_FOUND",`Artifact ${t}/${r} not found in workspace`),this.type=t,this.id=r}};re.ArtifactNotFoundError=xd;var Fd=class extends ot{constructor(t,r,n){super("PATH_NOT_FOUND",`Path ${n} not found in ${t}/${r}`),this.type=t,this.id=r,this.pointer=n}};re.PathNotFoundError=Fd;var Ld=class extends ot{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"}};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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}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
+`)),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"}};re.ValidationError=Ld;var kd=class extends ot{constructor(t){super("INVALID_ARGUMENT",t)}};re.InvalidArgumentError=kd;var Md=class extends ot{constructor(t,r,n,i="revalidated"){super("STALE_ARTIFACT",i==="pushed"?`Cannot apply the edit at ${n} to ${t}/${r}: a push made after this pointer's copy was read replaced the local copy with the record the server holds, which differs from that copy (ids and defaults the SDK filled in at save, a rewrite the platform made on save, or another writer's save), so the pointer may now identify a different node. Read the whole artifact (getArtifact), re-derive the pointer, and retry.`:`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,this.reason=i}};re.StaleArtifactError=Md;var Bd=class extends ot{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}};re.LocalEditsWouldBeLostError=Bd;var Ud=class extends ot{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}};re.VersionConflictError=Ud;var $d=class extends ot{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}};re.ConnectionError=$d;var qd=class extends ot{constructor(t){super("WORKSPACE_NOT_INITIALIZED",`Workspace not initialized at ${t}. Call initWorkspace() first.`),this.workspacePath=t}};re.WorkspaceNotInitializedError=qd;var Vd=class extends ot{constructor(t,r){super("NOT_IMPLEMENTED",`Operation '${t}' is not implemented yet${r?`: ${r}`:""}.`),this.operation=t}};re.NotImplementedError=Vd;var Gd=class extends ot{constructor(t,r){super("INVALID_JSON_POINTER",`Invalid JSON Pointer '${t}': ${r}`),this.pointer=t}};re.JsonPointerError=Gd;var zd=class extends ot{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}};re.AmbiguousArtifactError=zd;var Wd=class extends ot{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}};re.PathTraversalError=Wd;var jd=class extends ot{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}};re.IncompatibleWorkspaceError=jd});var ae=y(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.odataQuery=Ue.normalizeGuid=Ue.createSafeXmlElement=Ue.assertNoControlChars=Ue.assertODataName=Ue.assertXmlName=Ue.xmlText=Ue.odataPathLiteral=Ue.odataLiteral=void 0;var yl=te();function bv(e){return String(e??"").replace(/'/g,"''")}Ue.odataLiteral=bv;function x1(e){return encodeURIComponent(bv(e))}Ue.odataPathLiteral=x1;function F1(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}Ue.xmlText=F1;function wv(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 yl.InvalidArgumentError(`${t} must be a valid XML element name (got '${e}')`);return e}Ue.assertXmlName=wv;function L1(e,t){let r=String(e??"");if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw new yl.InvalidArgumentError(`${t} must be a valid OData identifier (letters, digits, underscore): got '${e}'`);return e}Ue.assertODataName=L1;function k1(e,t){if(/[\u0000-\u001F\u007F]/.test(String(e??"")))throw new yl.InvalidArgumentError(`${t} must not contain control characters (including CR/LF): they would inject additional lines into the request`);return e}Ue.assertNoControlChars=k1;function M1(e,t,r){return e.createElement(wv(t,r))}Ue.createSafeXmlElement=M1;var B1=/^[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 U1(e,t){let r=String(e??""),n=r.length===38&&r.startsWith("{")&&r.endsWith("}")?r.slice(1,-1):r;if(!B1.test(n))throw new yl.InvalidArgumentError(`${t} must be a valid GUID (got '${e}')`);return n.toLowerCase()}Ue.normalizeGuid=U1;function $1(e){let t=[];for(let[r,n]of e)n!=null&&n!==""&&t.push(`${r}=${encodeURIComponent(String(n))}`);return t.length>0?`?${t.join("&")}`:""}Ue.odataQuery=$1});var be=y(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.nowIso=Q.isAlreadyDeleted=Q.deleteRecord=Q.resendDeadlockVictim=Q.DEADLOCK_BACKOFF_MS=Q.isSqlDeadlockVictim=Q.ensureSuccess=Q.resolveCreatedId=Q.requireCreatedId=Q.withClientMintedId=Q.readCreatedId=Q.readRowEtag=Q.readEtag=Q.requireEtag=Q.echoWrite=Q.UPDATE_NO_ETAG_CODE=Q.VERSION_CONFLICT_CODE=void 0;var sa=te(),la=ae();Q.VERSION_CONFLICT_CODE="VERSION_CONFLICT";Q.UPDATE_NO_ETAG_CODE="ARTIFACT_UPDATE_NO_ETAG";function q1(e,t){return{query:`?$select=${encodeURIComponent(e)}`,options:{headers:{...t??{},Prefer:"return=representation"}}}}Q.echoWrite=q1;function V1(e,t,r){if(!e)throw new sa.SdkError(Q.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}Q.requireEtag=V1;function Av(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}Q.readEtag=Av;async function G1(e,t,r,n){let i=`/${t}(${n})${(0,la.odataQuery)([["$select",r]])}`;return Av(Kd(await e.get(i),e.apiUrl(i)))}Q.readRowEtag=G1;function Hd(e,t){var r;let n=e.body;if(n&&typeof n[t]=="string")return(0,la.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,la.normalizeGuid)(o[1],t)}return null}Q.readCreatedId=Hd;function z1(e,t,r){return r?{...e,[t]:(0,la.normalizeGuid)(r,t)}:e}Q.withClientMintedId=z1;function W1(e,t,r){let n=Hd(e,t);if(!n)throw new sa.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`);return n}Q.requireCreatedId=W1;function j1(e,t,r,n){let i=Hd(e,t);if(i)return i;if(n)return(0,la.normalizeGuid)(n,t);throw new sa.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`)}Q.resolveCreatedId=j1;function Kd(e,t){if(e.status===412)throw new sa.SdkError(Q.VERSION_CONFLICT_CODE,`Version conflict (412) from ${t}`);if(e.status<200||e.status>=300)throw new sa.ConnectionError(t,e.status,K1(e.body),e.body);return e}Q.ensureSuccess=Kd;function Ev(e){if(e.status!==500||e.body===void 0||e.body===null)return!1;let t=typeof e.body=="string"?e.body:JSON.stringify(e.body);return/\bSql Number:\s*1205\b/i.test(t)}Q.isSqlDeadlockVictim=Ev;Q.DEADLOCK_BACKOFF_MS=[1e3,2e3,4e3];async function H1(e){for(let t=0;;t+=1){let r=await e();if(t>=Q.DEADLOCK_BACKOFF_MS.length||!Ev(r))return r;await new Promise(n=>setTimeout(n,Q.DEADLOCK_BACKOFF_MS[t]))}}Q.resendDeadlockVictim=H1;function K1(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 J1(e,t,r,n){let i=(0,la.normalizeGuid)(r,"id"),a=`/${t}(${i})`;Kd(await e.delete(a,n?{headers:{"If-Match":n}}:void 0),e.apiUrl(a))}Q.deleteRecord=J1;function Q1(e){return e instanceof sa.ConnectionError&&e.statusCode===404}Q.isAlreadyDeleted=Q1;function X1(){return new Date().toISOString()}Q.nowIso=X1});var Pt=y(ua=>{"use strict";Object.defineProperty(ua,"__esModule",{value:!0});ua.describeMalformedValue=ua.collectPages=void 0;var Cv=be(),Jd=te();async function Y1(e,t,r,n,i){let a=[],o=new Set,s=e.apiUrl(t),l=(0,Cv.ensureSuccess)(await e.get(t,i),s);for(n?.(l);;){let u=l.body,c=u?.value;if(!Array.isArray(c))throw new Jd.ConnectionError(s,l.status,`${r}: paginated read returned a malformed page \u2014 expected an OData 'value' array but got ${Qd(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 Jd.ConnectionError(s,l.status,`${r}: paginated read returned a malformed @odata.nextLink (${Qd(d)}); cannot follow it, and refusing to return partial results.`);if(o.has(d))throw new Jd.InvalidArgumentError(`${r}: aborting pagination \u2014 the server returned a repeated @odata.nextLink ('${d}'), which would loop indefinitely.`);o.add(d),s=d,l=(0,Cv.ensureSuccess)(await e.getAbsolute(d,i),d)}return a}ua.collectPages=Y1;function Qd(e){return e===null?"null":e===void 0?"undefined (missing)":`a ${typeof e}`}ua.describeMalformedValue=Qd});var Xd=y(Br=>{"use strict";Object.defineProperty(Br,"__esModule",{value:!0});Br.businessRuleApi=Br.BUSINESS_RULE_LEFT_DEACTIVATED_CODE=Br.WFOM_API_UNAVAILABLE_CODE=void 0;var fn=Ai(),Z1=Pt(),st=be(),Vn=ae(),wl=te();Br.WFOM_API_UNAVAILABLE_CODE="BUSINESS_RULE_API_UNAVAILABLE";Br.BUSINESS_RULE_LEFT_DEACTIVATED_CODE="BUSINESS_RULE_LEFT_DEACTIVATED";async function Sv(e,t,r,n){let i=`/workflows(${rx})/Microsoft.Dynamics.CRM.${t}`;try{return(0,st.ensureSuccess)(await e.post(i,{Entity:r.Entity,WfomJson:r.WfomJson},{headers:n}),e.apiUrl(i))}catch(a){throw a?.statusCode!==404?a:new wl.SdkError(Br.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 ex(e,t){let r=`/workflows(${t})${(0,Vn.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,st.readEtag)(n),statecode:typeof i?.statecode=="number"?i.statecode:null,statuscode:typeof i?.statuscode=="number"?i.statuscode:null}}catch{return null}}async function tx(e,t,r){let n=await ex(e,t);if(n===null||n.etag===null)throw new wl.SdkError(st.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 wl.SdkError(st.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 rx="00000000-0000-0000-0000-000000000000",bl={"Content-Type":"application/json",Accept:"application/json","OData-Version":"4.0","OData-MaxVersion":"4.0"},nx="workflowid,name,description,primaryentity,statecode,category,type",ix="category eq 2 and type eq 1";async function Nv(e,t,r){var n;if(r==="Draft")return null;let i=(0,Vn.normalizeGuid)(t,"workflowid"),a=r==="Active",o={statecode:a?fn.StateCode.Activated:fn.StateCode.Draft,statuscode:a?fn.StatusCode.Activated:fn.StatusCode.Draft},s=`/workflows(${i})`,l=(0,st.ensureSuccess)(await e.patch(s,o,{headers:bl}),e.apiUrl(s));return(n=(0,st.readEtag)(l))!==null&&n!==void 0?n:await ko(e,i)}async function ko(e,t){let r=`/workflows(${t})${(0,Vn.odataQuery)([["$select","workflowid"]])}`;try{let n=await e.get(r);return n.status>=200&&n.status<300?(0,st.readEtag)(n):null}catch{return null}}async function ax(e,t,r){let n=await ko(e,t),i=await r(),a=(0,st.readEtag)(i);if(a)return{response:i,etag:a};let o=await ko(e,t);return{response:i,etag:n!==null&&n===o?o:null}}Br.businessRuleApi={async get(e,t){let r=(0,Vn.normalizeGuid)(t,"id"),n=`/workflows(${r})/Microsoft.Dynamics.CRM.RetrieveProcessWithWfomJson`,{response:i,etag:a}=await ax(e,r,async()=>(0,st.ensureSuccess)(await e.get(n),e.apiUrl(n)));return{raw:i.body,etag:a}},async list(e,t){let r=[ix];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,Vn.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,Vn.odataQuery)([["$select",nx],["$filter",r.join(" and ")]])}`;return(await(0,Z1.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,Vn.normalizeGuid)(n.Entity.workflowid,"workflowid"),a=await Sv(e,"CreateProcessWithWfomJson",n,bl),o=(0,st.resolveCreatedId)(a,"workflowid","business rule",i),s=null;try{s=await Nv(e,o,n.status)}catch(l){try{await(0,st.deleteRecord)(e,"workflows",o)}catch{}throw l}return{id:o,etag:(r=s??(0,st.readEtag)(a))!==null&&r!==void 0?r:await ko(e,o)}},async update(e,t,r,n){var i,a;let o=r,s=(0,Vn.normalizeGuid)(t,"id"),l=`/workflows(${s})`,u={...bl,"If-Match":(0,st.requireEtag)(n,"business rule",s)},c=await tx(e,s,u["If-Match"]),d=c.statecode===fn.StateCode.Activated;d&&(0,st.ensureSuccess)(await e.patch(l,{statecode:fn.StateCode.Draft,statuscode:fn.StatusCode.Draft},{headers:u}),e.apiUrl(l));let p;try{p=await Sv(e,"UpdateProcessWithWfomJson",o,u)}catch(m){if(d)try{(0,st.ensureSuccess)(await e.patch(l,{statecode:fn.StateCode.Activated,statuscode:(i=c.statuscode)!==null&&i!==void 0?i:fn.StatusCode.Activated},{headers:bl}),e.apiUrl(l))}catch(h){throw new wl.SdkError(Br.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 Nv(e,s,o.status);return{id:s,etag:(a=f??(0,st.readEtag)(p))!==null&&a!==void 0?a:await ko(e,s)}},delete(e,t){return(0,st.deleteRecord)(e,"workflows",t)}}});var ca=y(El=>{"use strict";Object.defineProperty(El,"__esModule",{value:!0});El.JsonPointer=void 0;var Kt=te(),Al=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 Kt.JsonPointerError(t,'non-empty pointers must start with "/"');return t.substring(1).split("/").map(r=>{if(/~(?![01])/.test(r))throw new Kt.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 Kt.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 Kt.JsonPointerError(r,`'${o}' is not a valid array index`);if(s>a.length)throw new Kt.JsonPointerError(r,`array index '${o}' is out of range`);a[s]=n}else{if(e.isReservedToken(o))throw new Kt.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 Kt.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 Kt.JsonPointerError(r,`array index '${a}' is out of range`);i.splice(o,1)}else{if(e.isReservedToken(a))throw new Kt.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 Kt.JsonPointerError(r,"add target must be an array");u.push(n);return}let o=e.resolve(t,r);if(!Array.isArray(o))throw new Kt.JsonPointerError(r,"add target must be an array");let s=i===void 0?o.length:i;if(s<0||s>o.length)throw new Kt.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 Kt.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=Al;Al.RESERVED_TOKENS=new Set(["__proto__","prototype","constructor"])});var Iv=y(Cl=>{"use strict";Object.defineProperty(Cl,"__esModule",{value:!0});Cl.findElements=void 0;var Dv=ca();function ox(e,t){let r=[];return Yd(e,"",t,r),r}Cl.findElements=ox;function Yd(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)=>{Yd(i,Dv.JsonPointer.append(t,a),r,n)});else for(let i of Object.keys(e))Yd(e[i],Dv.JsonPointer.append(t,i),r,n)}});var Zd=y(Ur=>{"use strict";Object.defineProperty(Ur,"__esModule",{value:!0});Ur.assertMutationResult=Ur.assertExistsResult=Ur.assertReadResult=Ur.assertStorageContract=void 0;var sx=["readText","writeTextAtomic","deleteFile","deleteByPrefix"],lx=["ensureContainer","exists"];function ux(e){if(typeof e!="object"||e===null)throw new Error("workspaceStorage must be an object implementing WorkspaceStorage.");for(let t of sx)if(typeof e[t]!="function")throw new Error(`workspaceStorage is missing the required method '${t}'.`);for(let t of lx){let r=e[t];if(r!==void 0&&typeof r!="function")throw new Error(`workspaceStorage.${t} must be a function when present.`)}return e}Ur.assertStorageContract=ux;function cx(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.`)}Ur.assertReadResult=cx;function dx(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.`)}Ur.assertExistsResult=dx;function px(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.`)}Ur.assertMutationResult=px});var ep=y(da=>{"use strict";Object.defineProperty(da,"__esModule",{value:!0});da.retryTransientIoAsync=da.retryTransientIo=void 0;var fx=new Set(["EPERM","EACCES","EBUSY","UNKNOWN"]),mx=5,_v=10;function hx(e){for(let t=1;;t+=1)try{return e()}catch(r){if(!Tv(r,t))throw r;vx(_v*t)}}da.retryTransientIo=hx;async function gx(e){for(let t=1;;t+=1)try{return await e()}catch(r){if(!Tv(r,t))throw r;await new Promise(n=>setTimeout(n,_v*t))}}da.retryTransientIoAsync=gx;function Tv(e,t){let r=e.code;return t<mx&&!!r&&fx.has(r)}function vx(e){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}catch{let t=Date.now()+e;for(;Date.now()<t;);}}});var xv=y(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.canonicalArtifactId=Jt.WorkspaceManager=Jt.WORKSPACE_SCHEMA_VERSION=Jt.retryTransientIo=void 0;var Ar=Zd(),Sl=te(),yx=ep();Object.defineProperty(Jt,"retryTransientIo",{enumerable:!0,get:function(){return yx.retryTransientIo}});function Pv(e){let t=e;return typeof t.pathFor=="function"&&typeof t.getRoot=="function"?e:null}Jt.WORKSPACE_SCHEMA_VERSION=1;var Gn={form:"forms",view:"views",businessRule:"business-rules",app:"apps",command:"commands",chart:"charts",dashboard:"dashboards",genPage:"gen-pages",bpf:"business-process-flows"},bx="manifest.json",Mo=".metadata",Rv="entities";function Ov(e){try{return Promise.resolve(e())}catch(t){return Promise.reject(t)}}var tp=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),[Gn[t],`${Bo(r)}.json`]}metaKey(t,r){return this.assertSafeId(r),[Mo,Gn[t],`${Bo(r)}.meta.json`]}entityKey(t){return this.assertSafeId(t),[Mo,Rv,`${t}.json`]}fsStore(){let t=Pv(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=Pv(this.storage);return t?t.getRoot():this.workspaceLabel}getArtifactDir(t){return this.fsStore().pathFor([Gn[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 Sl.PathTraversalError(String(t),this.workspaceLabel)}get manifestKey(){return[bx]}async init(){if(this.storage.ensureContainer){let t=this.storage.ensureContainer.bind(this.storage),r=[[Mo,Rv]];for(let i of Object.keys(Gn))r.push([Gn[i]],[Mo,Gn[i]]);let n=await Promise.allSettled(r.map(i=>Ov(()=>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 Sl.WorkspaceNotInitializedError(this.workspaceLabel)}async clean(){let t=Object.keys(Gn).map(i=>[Gn[i]]);t.push([Mo]);let r=await Promise.allSettled(t.map(i=>Ov(()=>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=Bo(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 Sl.WorkspaceNotInitializedError(this.workspaceLabel);if(t.schemaVersion!==void 0&&t.schemaVersion>Jt.WORKSPACE_SCHEMA_VERSION)throw new Sl.IncompatibleWorkspaceError(t.schemaVersion,Jt.WORKSPACE_SCHEMA_VERSION);return t}async writeManifest(t){await this.writeJson(this.manifestKey,{...t,schemaVersion:Jt.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=Bo(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}};Jt.WorkspaceManager=tp;function Bo(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()}Jt.canonicalArtifactId=Bo});var rp=y(pa=>{"use strict";Object.defineProperty(pa,"__esModule",{value:!0});pa.deepEqual=pa.deepDiff=void 0;var wx=ca();function Ax(e,t){let r=[];return Lv(e,t,"",r,0),r}pa.deepDiff=Ax;var Nl=Symbol("missing"),Dl=512;function Lv(e,t,r,n,i){if(e===t)return;if(i>Dl)throw new RangeError(`deepDiff exceeded the maximum supported depth of ${Dl}`);let a=Il(e),o=Il(t);if(a&&o&&Array.isArray(e)===Array.isArray(t)){let s=Ex(e,t);for(let l of s){let u=Fv(e,l),c=Fv(t,l),d=wx.JsonPointer.append(r,l);u===Nl?n.push({pointer:d,type:"added",newValue:c}):c===Nl?n.push({pointer:d,type:"removed",oldValue:u}):Lv(u,c,d,n,i+1)}return}kv(e,t)||n.push({pointer:r,type:"modified",oldValue:e,newValue:t})}function Il(e){return e!==null&&typeof e=="object"}function Ex(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 Fv(e,t){if(Array.isArray(e)){let r=Number(t);return r<e.length?e[r]:Nl}return t in e?e[t]:Nl}function kv(e,t){return Mv(e,t,0)}pa.deepEqual=kv;function Mv(e,t,r){if(e===t)return!0;if(r>Dl)throw new RangeError(`deepEqual exceeded the maximum supported depth of ${Dl}`);if(!Il(e)||!Il(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&&Mv(e[a],t[a],r+1))}});var Uv=y(fa=>{"use strict";Object.defineProperty(fa,"__esModule",{value:!0});fa.VersionManager=fa.PROJECTION_VERSION=void 0;var Bv=rp();fa.PROJECTION_VERSION=5;var np=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,Bv.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,Bv.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}};fa.VersionManager=np});var qv=y((ip,$v)=>{(function(e,t){typeof define=="function"&&define.amd?define([],t):typeof ip=="object"?$v.exports=t():e.compareVersions=t()})(ip,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 jv=y(Re=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.EnvironmentFlowHostingType=Re.EnvironmentDisableReasonCode=Re.EnvironmentMigrationConstants=Re.EnvironmentProvisioningStates=Re.EnvironmentLocations=Re.EnvironmentCreationTypeConstants=Re.EnvironmentType=Re.EnvironmentSkuConstants=Re.environmentPermissions=Re.DatabaseType=void 0;var Vv;(function(e){e.CommonDataService="CommonDataService",e.None="None"})(Vv||(Re.DatabaseType=Vv={}));Re.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"};Re.EnvironmentSkuConstants={NotSpecified:"NotSpecified",Standard:"Standard",Premium:"Premium",Developer:"Developer",Basic:"Basic",Production:"Production",Sandbox:"Sandbox",Trial:"Trial",Default:"Default",Teams:"Teams",Platform:"Platform"};var Gv;(function(e){e[e.CDS2=0]="CDS2",e[e.CDS1=1]="CDS1",e[e.Empty=2]="Empty"})(Gv||(Re.EnvironmentType=Gv={}));Re.EnvironmentCreationTypeConstants={NotSpecified:"NotSpecified",Legacy:"Legacy",DefaultTenant:"DefaultTenant",User:"User",CommonDataModelLegacy:"CommonDataModelLegacy"};Re.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"};Re.EnvironmentProvisioningStates={NotSpecified:"NotSpecified",Succeeded:"Succeeded",Deleting:"Deleting",Deleted:"Deleted",FailedDeleting:"FailedDeleting",LinkedDatabaseProvisioning:"LinkedDatabaseProvisioning",LinkedDatabaseFailedProvisioning:"LinkedDatabaseFailedProvisioning",LinkedDatabaseFailedConfiguring:"LinkedDatabaseFailedConfiguring",LinkedDatabaseUnavailable:"LinkedDatabaseUnavailable",Creating:"Creating"};Re.EnvironmentMigrationConstants={phases:{completed:"Completed"}};var zv;(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"})(zv||(Re.EnvironmentDisableReasonCode=zv={}));var Wv;(function(e){e.LogicApps="LogicApps",e.SelfHostSingleTenant="SelfHostSingleTenant",e.SelfHostMultiTenant="SelfHostMultiTenant"})(Wv||(Re.EnvironmentFlowHostingType=Wv={}))});var ey=y(S=>{"use strict";var Cx=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 Sx=Cx(qv()),he=jv(),Uo=op();function Nx(e){let t=hn(e);return t&&t.version}S.getCrmVersion=Nx;function hn(e){return e&&e.properties&&e.properties.linkedEnvironmentMetadata}S.getLinkedEnvironmentMetadata=hn;function mn(e,t){return e?!!e[t]:!1}S.doesUserHavePermission=mn;S.crmBapSolutionId="00000001-0000-0000-0001-00000000009b";S.DEFAULT_SOLUTION_ID="fd140aaf-4df4-11dd-bd17-0019b9312238";S.DEFAULT_SOLUTION_UNIQUE_NAME="Default";function Ei(e){return!!hn(e)&&Hv(e)}S.environmentHasCds2Database=Ei;function Dx(e){if(e&&Ei(e)){let t=zn(e);return(0,Uo.getCrmAdminSecurityRolesUrl)(t)}return""}S.getSecurityUsersUrl=Dx;function Ix(e){if(e&&Ei(e)){let t=zn(e);return(0,Uo.getCrmAdminSecurityUsersUrl)(t)}return""}S.getSecurityRolesUrl=Ix;function _x(e){if(e&&Ei(e)){let t=zn(e);(0,Uo.getCrmAllSolutionsUrl)(t)}return""}S.getAllSolutionsUrl=_x;function Tx(e){if(e&&Ei(e)){let t=zn(e);return(0,Uo.getCrmAllPublishersUrl)(t)}return""}S.getAllPublishersUrl=Tx;function Px(e){return e&&Ei(e)?zn(e):""}S.getAllThemesUrl=Px;function Hv(e){return!!e&&e.properties&&!!e.properties.provisioningState&&e.properties.provisioningState.toUpperCase()===he.EnvironmentProvisioningStates.Succeeded.toUpperCase()}S.isEnvironmentInSuccessfulState=Hv;function Rx(e){if(e&&Ei(e)){let t=zn(e);return(0,Uo.getCrmDevResourcesUrl)(t)}return""}S.getDevResourcesUrl=Rx;function Ox(e){return`${e}designer/app/{${S.crmBapSolutionId}}/CreateNewApp}}`}S.getCrmAppDesignerUrl=Ox;function zn(e){let t=hn(e);if(t){let r=t.instanceUrl;return r?r.endsWith("/")?r:r+"/":""}return""}S.getCrmInstanceUrl=zn;function xx(e){let t=hn(e);return t?t.uniqueName:""}S.getCrmInstanceName=xx;function Fx(e){return hn(e)?he.EnvironmentType.CDS2:e&&e.properties&&e.properties.namespace?he.EnvironmentType.CDS1:he.EnvironmentType.Empty}S.getEnvironmentType=Fx;function Lx(e){return e&&e.properties&&e.properties.environmentSku===he.EnvironmentSkuConstants.Developer}S.isDevEnvironment=Lx;function kx(e){return e&&e.properties&&e.properties.environmentSku===he.EnvironmentSkuConstants.Production}S.isProdEnvironment=kx;function Mx(e){return e&&e.properties&&e.properties.environmentSku===he.EnvironmentSkuConstants.Sandbox}S.isSandboxEnvironment=Mx;function $o(e){return e&&e.properties&&e.properties.environmentSku===he.EnvironmentSkuConstants.Teams}S.isTeamsEnvironment=$o;function Bx(e){return e&&e.properties&&e.properties.environmentSku===he.EnvironmentSkuConstants.Platform}S.isPlatformEnvironment=Bx;var Ux=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.environmentSku)===he.EnvironmentSkuConstants.Trial};S.isTrialEnvironment=Ux;function $x(e){return e&&e.properties&&(e.properties.isDefault||e.properties.creationType===he.EnvironmentCreationTypeConstants.DefaultTenant)}S.isDefaultEnvironment=$x;function qx(e){return e&&e.properties&&!!e.properties.states&&!!e.properties.states.runtime&&e.properties.states.runtime.id==="Disabled"}S.isDisabledEnvironment=qx;function Vx(e){return e&&e.properties&&mn(e.properties.permissions,he.environmentPermissions.CreateDatabase)}S.canUserCreateDatabase=Vx;function Gx(e){return!!(e&&e.properties&&e.properties.provisioningState&&Zv(e.properties.provisioningState,he.EnvironmentProvisioningStates.LinkedDatabaseProvisioning))}S.isDatabaseInProvisioningState=Gx;function zx(e){return!!e&&!!e.properties&&e.properties.provisioningState===he.EnvironmentProvisioningStates.Creating}S.isEnvironmentInCreatingState=zx;function Wx(e){return e&&e.properties&&(e.properties.provisioningState===he.EnvironmentProvisioningStates.Deleted||e.properties.provisioningState===he.EnvironmentProvisioningStates.Deleting||e.properties.provisioningState===he.EnvironmentProvisioningStates.FailedDeleting)}S.isEnvironmentInDeletedState=Wx;function jx(e){return!!e&&!!e.properties&&!!e.properties.expirationTime&&Date.parse(e.properties.expirationTime)<Date.now()}S.isEnvironmentExpired=jx;function Hx(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=Hx;function Kx(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Test"}S.isEnvironmentInTestCluster=Kx;function Jx(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Preprod"}S.isEnvironmentInPreprodCluster=Jx;function Qx(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="FirstRelease"}S.isEnvironmentInFirstReleaseCluster=Qx;function Xx(e){return e&&e.name||""}S.getEnvironmentName=Xx;function Yx(e){return e&&e.properties&&e.properties.displayName||""}S.getEnvironmentDisplayName=Yx;var Kv="9.1.0.8202";S.cdsVersionSupportingOSColorEdit="9.1.0000.20708";function Zx(e){return Xv(e,Kv)}S.doesCds2EnvironmentSupportApiVersion9_1=Zx;function eF(e){return ap(e,Kv)}S.doesCds2VersionSupportApiVersion9_1=eF;function Jv(e){let t=hn(e);if(t)return t.securityGroupId}function Qv(e){return e&&e.properties&&e.properties.connectedGroups}function tF(e,t){let r=Qv(e);return!!r&&!!r.find(n=>n.id===t)||Jv(e)===t}S.hasSecurityGroupId=tF;function rF(e){let t=Qv(e);return t&&t.length>0&&t[0].id?t[0].id:Jv(e)}S.getSecurityOrConnectedGroupId=rF;function Xv(e,t){let r=e.version;return r?ap(r,t):!1}S.isCds2EnvironmentVersionAtLeast=Xv;function ap(e,t){return t?e?(0,Sx.default)(e,t)>=0:!1:!0}S.checkVersions=ap;function nF(e){return e&&e.properties&&e.properties.updateCadence&&e.properties.updateCadence.id||"NotSpecified"}S.getEnvironmentUpdateCadence=nF;function iF(e){let t=hn(e);return t?Number(t.baseLanguage):0}S.getEnvironmentLanguageCode=iF;function Yv(e){let t=hn(e);return t?t.instanceApiUrl:void 0}S.getEnvironmentInstanceApiUrl=Yv;function aF(e){let t=Yv(e);return t?t+"/api/data/v9.2":""}S.getEnvironmentWebApiUrl=aF;function oF(e){let t=zn(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=oF;var sF=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.databaseType)===he.DatabaseType.CommonDataService};S.hasCommonDataServiceDatabase=sF;var lF=e=>{var t;return mn((t=e.properties)===null||t===void 0?void 0:t.permissions,he.environmentPermissions.AdminReadEnvironment)};S.doesUserHaveAdminPermission=lF;var uF=e=>{var t;return mn((t=e.properties)===null||t===void 0?void 0:t.permissions,he.environmentPermissions.CreatePowerApp)};S.doesUserHaveCreateAppPermission=uF;var cF=e=>(0,S.doesUserHaveAdminPermission)(e)&&(0,S.hasCommonDataServiceDatabase)(e)?!0:(0,S.doesUserHaveCreateAppPermission)(e)?$o(e)||(0,S.doesUserHaveDatabaseTablePermissions)(e):!1;S.isUserMakerWithDataAccess=cF;var dF=e=>(0,S.doesUserHaveCreateAppPermission)(e)&&!$o(e)&&!(0,S.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,S.doesUserHaveAdminPermission)(e)||!(0,S.hasCommonDataServiceDatabase)(e));S.isUserMakerWithoutDataAccess=dF;var pF=e=>[he.environmentPermissions.CreateDatabaseEntities,he.environmentPermissions.ListDatabaseEntities,he.environmentPermissions.UpdateDatabaseEntities,he.environmentPermissions.DeleteDatabaseEntities].every(t=>{var r;return mn((r=e.properties)===null||r===void 0?void 0:r.permissions,t)});S.doesUserHaveDatabaseTablePermissions=pF;var fF=e=>{var t;return mn((t=e.properties)===null||t===void 0?void 0:t.permissions,he.environmentPermissions.CreateDatabase)};S.doesUserHaveCreateDatabasePermission=fF;function Zv(e,t){return!e&&!t?!0:!e||!t?!1:e.toUpperCase()===t.toUpperCase()}S.equalsIgnoreCase=Zv;var mF=e=>{var t;return mn((t=e.properties)===null||t===void 0?void 0:t.permissions,he.environmentPermissions.CreateFlow)};S.doesUserHaveCreateFlowPermission=mF;var hF=e=>(0,S.doesUserHaveAdminPermission)(e)&&(0,S.hasCommonDataServiceDatabase)(e)?!0:(0,S.doesUserHaveCreateFlowPermission)(e)?$o(e)||(0,S.doesUserHaveDatabaseTablePermissions)(e):!1;S.isUserPautoMakerWithDataAccess=hF;var gF=e=>(0,S.doesUserHaveCreateFlowPermission)(e)&&!$o(e)&&!(0,S.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,S.doesUserHaveAdminPermission)(e)||!(0,S.hasCommonDataServiceDatabase)(e));S.isUserPautoMakerWithoutDataAccess=gF;var vF=e=>{var t,r;return!mn((t=e.properties)===null||t===void 0?void 0:t.permissions,he.environmentPermissions.CreateFlow)&&mn((r=e.properties)===null||r===void 0?void 0:r.permissions,he.environmentPermissions.ReadEnvironment)};S.doesUserHaveFlowRunOnlyPermission=vF});var op=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 ty=ey();A.ODATA_MAX_PAGE_SIZE="odata.maxpagesize";A.ODATA_NEXT_LINK="@odata.nextLink";A.cdsServiceUrl="https://cds-org/";var Vo;(function(e){e.AllSolutions="11",e.AllPublishers="10",e.DevResources="05"})(Vo||(Vo={}));function yF(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=yF;function bF(e,t){let r=`dType=1&isproactivecheck=true&objecttype=7100&operationtype=dependenciesforuninstall&objectid=${t}`;return`${e}tools/dependency/dependencyviewdialog.aspx?${r}`}A.getShowSolutionDependenciesUrl=bF;function wF(e,t){return`${e}tools/muiProvisioning/Dialogs/LangTranslationsImport.aspx?dType=1&appSolutionId=${t}`}A.getImportSolutionTranslationUrl=wF;function AF(e,t){return`${e}_grid/cmds/dlg_exportsolution.aspx?command=exporttranslation&appSolutionId=${t}`}A.getExportSolutionTranslationUrl=AF;function EF(e,t){return e!==void 0&&t!==void 0&&`CrmTranslations_${e}_${t.replace(/[.]/g,"_")}.zip`||""}A.getExportTranslationFileName=EF;function CF(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=CF;function sp(e,t){return`${e}tools/systemcustomization/systemCustomization.aspx?pid=${t}`}function SF(e){return sp(e,Vo.AllSolutions)}A.getCrmAllSolutionsUrl=SF;function NF(e){return sp(e,Vo.AllPublishers)}A.getCrmAllPublishersUrl=NF;function DF(e){return sp(e,Vo.DevResources)}A.getCrmDevResourcesUrl=DF;function IF(e,t=ty.crmBapSolutionId){return`${e}designer/app/${t}#/CreateNewApp`}A.getCrmAppDesignerUrl=IF;function _F(e){return`${e}apps`}A.getCrmMyAppsUrl=_F;function TF(e){return ry(e,"role")+"&forceUCI=0"}A.getCrmAdminSecurityRolesUrl=TF;function PF(e){return`${ry(e,"systemuser")}&forceclassic=1`}A.getCrmAdminSecurityUsersUrl=PF;function ry(e,t){return`${e}main.aspx?pagetype=entitylist&etn=${t}`}function RF(e,t){return`${e}main.aspx?appid=${t}`}A.getPlayAppModuleUrl=RF;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 OF(e,t,r=ty.crmBapSolutionId){return`${e}designer/app/${r}/${t}/AppDesignerCanvas/${t}`}A.getAppModuleDesignerUrl=OF;function xF(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=xF;function FF(e,t,r){return`/e/${e}/s/${t}/dashboard/${r}`}A.getOpenModernDashboardUrl=FF;function LF(e,t,r){let n=r!==void 0?r.toString():void 0;return`/e/${e}/s/${t}/dashboard/new${n?`/${n}`:""}`}A.getNewModernDashboardUrl=LF;function kF(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=kF;function MF(e,t,r,n){return`/e/${e}/s/${t}/n/${r}/dashboard/${n}`}A.getOpenModernEntityDashboardUrl=MF;function BF(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${t}%7d&extraqs=etc=${r||""}`+(n?`%26id=${n}`:"")+"&pagetype=vizdesigner"}A.getChartDesignerUrl=BF;function UF(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=UF;function $F(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=$F;function qF(e,t){return`${e}Tools/ProcessControl/UnifiedProcessDesigner.aspx?id=${t}`}A.getBusinessProcessFlowDesignerUrl=qF;function VF(e,t,r){return`${e}CRMReports/reportproperty.aspx?appSolutionId=%7b${r}%7d&disablePersonal=true&id=%7b${t}%7d`}A.getReportDesignerUrl=VF;function GF(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=GF;function zF(e,t){return`${e}WebResources/${t}`}A.getWebResourceFileUrl=zF;function WF(e,t,r){return`${e}designer/sitemap/${r}/${t}/SiteMapHome/${t}`}A.getSiteMapDesignerUrl=WF;function jF(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=jF;function HF(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=HF;function KF(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=KF;function JF(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=JF;function QF(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=QF;function XF(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=XF;function YF(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=YF;function ZF(e){return`${e}tools/publisher/edit.aspx`}A.getCreateNewPublisherUrl=ZF;function eL(e,t){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?appSolutionId=${t}`}A.getCreateNewArticleTemplateUrl=eL;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 tL(e,t){return`${A.xrmApiUrl}/RetrieveRequiredComponents(ObjectId=${e},ComponentType=${t})`}A.getRequiredComponentsQueryUrl=tL;function rL(e,t){return`${A.cdsServiceUrl}${A.xrmApiUrl}/RetrieveDependentComponentsWithMetadata(ObjectId=${e},ComponentType=${t})`}A.getDependentComponentsWithMetadataQueryUrl=rL;A.solutionsQueryUrl="/api/data/v9.0/solutions?$expand=publisherid&$filter=(isvisible eq true)";function nL(e){return`/api/data/v9.0/solutions?$expand=publisherid&$filter=(uniquename eq '${e}')`}A.getSolutionsByUniqueNameQueryUrl=nL;function iL(e){return`/api/data/v9.0/solutions(${e})?$expand=publisherid`}A.getSolutionQueryUrl=iL;function aL(e){return`${e}api/data/v9.1/ProvisionLanguageForUser`}A.getProvisionLanguageUrl=aL;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 oL(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`}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
+ &$orderby=starttime desc`}A.getDeploymentStageRunsUrl=oL;function sL(e,t,r){return`/api/data/v9.1/RetrieveDeploymentPipelineInfo(DeploymentPipelineId=${e},SourceEnvironmentId='${t}',ArtifactName='${r}')`}A.retrieveDeploymentPipelineInfoUrl=sL;function lL(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}')`}A.retrievePipelinesUrl=Hx;function Jx(e){return`/api/data/v9.0/deploymentstages
+ &$filter=(environmentid eq '${e}')`}A.retrievePipelinesUrl=lL;function uL(e){return`/api/data/v9.0/deploymentstages
?$filter=(_deploymentpipelineid_value eq ${e})
&$select=name,description,deploymentstageid,_previousdeploymentstageid_value
- &$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
+ &$expand=targetdeploymentenvironmentid($select=deploymentenvironmentid,environmentid,name)`}A.retrieveDeploymentStagesUrl=uL;function cL(){return"/api/data/v9.0/deploymentstageruns?$select=deploymentstagerunid"}A.createDeploymentStageRunUrl=cL;function dL(e){return`/api/data/v9.0/deploymentstageruns(${e})`}A.updateDeploymentStageRunUrl=dL;function pL(){return"/api/data/v9.0/DeployPackageAsync"}A.deployPackageAsyncUrl=pL;function fL(){return"/api/data/v9.0/ValidatePackageAsync"}A.validatePackageAsyncUrl=fL;function mL(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=mL;function hL(e){return`/api/data/v9.0/deploymentstageruns(${e})
+ ?$select=aigenerateddeploymentnotes,deploymentstagerunid`}A.getAIGeneratedDeploymentNotesUrl=hL;function gL(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`}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=_deploymentstageid_value,deploymentstagerunid,stagerunstatus,operation,operationstatus,suboperation,artifactname`}A.deployOperationStatusUrl=gL;function vL(e){return`/api/data/v9.0/solutions(${e})
+ ?$select=solutionid,uniquename,version`}A.devSolutionInfoUrl=vL;function yL(e){return`/api/data/v9.0/deploymentenvironments
?$select=deploymentenvironmentid,environmentid,environmenttype,name
- &$filter=(environmentid eq '${e}')`}A.retrieveDeploymentEnvironmentInfoUrl=nL;var iL=e=>`/api/data/v9.0/systemusers
+ &$filter=(environmentid eq '${e}')`}A.retrieveDeploymentEnvironmentInfoUrl=yL;var bL=e=>`/api/data/v9.0/systemusers
?$select=azureactivedirectoryobjectid
- &$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)}
+ &$filter=(applicationid eq '${e}')`;A.SPNPrincipalIdUrl=bL;function wL(){return"/api/data/v9.0/appmodules?$filter=(uniquename eq 'AppDeploymentConfiguration')"}A.retrieveDeploymentPipelineConfigAppUrl=wL;A.retrieveFeatureControlSettingsByNamespaceUrl="/api/data/v9.1/RetrieveFeatureControlSettingsByNamespace";function AL(e){return`/api/data/v9.0/settingdefinitions${e}`}A.getSettingDefinitionsUri=AL;A.OrgSettingOverrideName="organizationsettings";function EL(e,t=!1){let r=`/api/data/v9.0/${A.OrgSettingOverrideName}${e}`;return t?`${A.cdsServiceUrl}${r}`:r}A.getOrgSettingOverrideUri=EL;A.AppSettingOverrideName="appsettings";function CL(e,t=!1){let r=`/api/data/v9.0/${A.AppSettingOverrideName}${e}`;return t?`${A.cdsServiceUrl.replace("/$","")}${r}`:r}A.getAppSettingOverrideUri=CL;var qo;(function(e){e[e.All=0]="All",e[e.IsPlatformOnly=1]="IsPlatformOnly",e[e.NotPlatformOnly=2]="NotPlatformOnly"})(qo||(A.RetrievePlatform=qo={}));function SL(e,t,r,n=qo.All,i=!1){let a=[];e&&a.push(`AppUniqueName='${e}'`),t!=null&&a.push(`ReleaseLevel=${t}`),r&&a.push(`RetrieveHiddenSettings=${r}`),n!==qo.All&&a.push(`RetrievePlatformSettings=${n===qo.IsPlatformOnly?1:0}`);let o="/api/data/v9.0/RetrieveUnpublishedOverridableSettingsInfo";return a.length&&(o=`${o}(${a.join(",")})`),i?`${A.cdsServiceUrl}${o}`:o}A.getPowerSettingsUri=SL;function NL(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=NL;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 IL(e){return`tools/systemcustomization/businessrules/businessRulesDesigner.aspx?BRlaunchpoint=BRGrid&appSolutionId={${e}}`}A.getBusinessRuleDesignerUri=IL;function ny({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=ny;function _L({baseUrl:e,environmentInstanceUrl:t,entityLogicalName:r,recordId:n}){let i=e||ny({environmentInstanceUrl:t,entityLogicalName:r});return i&&n?`${i}&id=${n}`:void 0}A.getUCIEntityRecordEditUrl=_L;A.retrieveOrganizationResources=`${A.cdsServiceUrl}api/data/v9.0/RetrieveOrganizationResources`});var ay=y(_l=>{"use strict";Object.defineProperty(_l,"__esModule",{value:!0});_l.DataverseClient=void 0;var TL=op(),Ci=te(),iy=be(),lp=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}/${TL.xrmApiUrl}${n}`}async send(t,r){try{return await r()}catch(n){throw n instanceof Ci.SdkError?n:new Ci.ConnectionError(t,0,n instanceof Error?n.message:String(n),n)}}get(t,r){let n=this.apiUrl(t);return(0,iy.resendDeadlockVictim)(()=>this.send(n,()=>this.httpClient.get(n,r)))}getAbsolute(t,r){return this.assertSameOrigin(t),(0,iy.resendDeadlockVictim)(()=>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 Ci.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${t}'`)}if(r.protocol!==n.protocol||r.host!==n.host)throw new Ci.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 Ci.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 Ci.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 Ci.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)))}};_l.DataverseClient=lp});var oy=y(Wn=>{"use strict";Object.defineProperty(Wn,"__esModule",{value:!0});Wn.findColumns=Wn.findTables=Wn.fetchEntityMetadataFromApi=void 0;var cp=be(),ir=ae();function $r(e){var t,r;return(r=(t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)!==null&&r!==void 0?r:""}function ma(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 Go(e,t){return(await dp(e,t)).rows}async function dp(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 qr(e){return`/EntityDefinitions(LogicalName='${(0,ir.odataPathLiteral)(e)}')`}async function PL(e,t,r){let n=await Go(e,`${qr(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata${(0,ir.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 RL(e,t,r){var n;let i=await Go(e,`${qr(t)}/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata${(0,ir.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:$r(s.Label),...ma(s.Label)?{localizedLabel:ma(s.Label)}:{}}}))}}function up(e){var t;return{value:(t=e.Value)!==null&&t!==void 0?t:0,label:$r(e.Label),...e.InvariantName?{invariantName:e.InvariantName}:{},...e.Color?{color:e.Color}:{}}}async function OL(e,t){var r;let n=l=>dp(e,l).catch(()=>({rows:[],ok:!1})),i=["PicklistAttributeMetadata","MultiSelectPicklistAttributeMetadata","StateAttributeMetadata","StatusAttributeMetadata"],a=await Promise.all(i.map(l=>n(`${qr(t)}/Attributes/Microsoft.Dynamics.CRM.${l}${(0,ir.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(up));let s=await n(`${qr(t)}/Attributes/Microsoft.Dynamics.CRM.BooleanAttributeMetadata${(0,ir.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,[up(u.FalseOption),up(u.TrueOption)])}return{byColumn:o,complete:s.ok&&a.every(l=>l.ok)}}async function xL(e,t,r){let{rows:n,ok:i}=await dp(e,`${qr(t)}/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata${(0,ir.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 FL(e,t){var r,n,i,a;let o=[],s=await Go(e,`${qr(t)}/OneToManyRelationships${(0,ir.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 Go(e,`${qr(t)}/ManyToOneRelationships${(0,ir.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 Go(e,`${qr(t)}/ManyToManyRelationships${(0,ir.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 LL(e,t){var r,n,i,a,o;let s=`${qr(t)}`+(0,ir.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,cp.ensureSuccess)(await e.get(s),e.apiUrl(s)).body,c=((r=u.Attributes)!==null&&r!==void 0?r:[]).map(h=>{var v,b,E;return{logicalName:h.LogicalName,displayName:$r(h.DisplayName),...ma(h.DisplayName)?{localizedDisplayName:ma(h.DisplayName)}:{},attributeType:(v=h.AttributeType)!==null&&v!==void 0?v:"Unknown",isCustomAttribute:!!h.IsCustomAttribute,attributeTypeName:(E=(b=h.AttributeTypeName)===null||b===void 0?void 0:b.Value)!==null&&E!==void 0?E:"",...typeof h.IsValidForUpdate=="boolean"?{isValidForUpdate:h.IsValidForUpdate}:{},...typeof h.IsValidForRead=="boolean"?{isValidForRead:h.IsValidForRead}:{},...h.AttributeOf?{attributeOf:h.AttributeOf}:{},...$r(h.Description)?{description:$r(h.Description)}:{}}}),d=new Map(c.map(h=>[h.logicalName,h])),[,,p,f,m]=await Promise.all([PL(e,t,d),RL(e,t,d),OL(e,t),xL(e,t,d),FL(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:$r(u.DisplayName),...ma(u.DisplayName)?{localizedDisplayName:ma(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,...$r(u.Description)?{description:$r(u.Description)}:{},columnDetailComplete:p.complete&&f,attributes:c,relationships:m}}Wn.fetchEntityMetadataFromApi=LL;async function kL(e,t,r){var n,i;let a=`/EntityDefinitions${(0,ir.odataQuery)([["$select","LogicalName,SchemaName,EntitySetName,DisplayName,IsCustomEntity"]])}`,s=(i=(n=(0,cp.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:$r(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}Wn.findTables=kL;async function ML(e,t,r,n){var i,a;let o=`${qr(t)}/Attributes`+(0,ir.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute"]]),l=(a=(i=(0,cp.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:$r(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}Wn.findColumns=ML});var mp=y(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.renderTypeRegistrations=Rt.buildGenPageLegacyEnums=Rt.renderGenPageAuthoringTypes=Rt.buildGenPageRuntimeTypes=Rt.toDesignerEntity=Rt.TABLE_LOGICAL_NAME=void 0;Rt.TABLE_LOGICAL_NAME=/^[a-z_][a-z0-9_]*$/;function pp(e){return e.replace(/[\r\n\u2028\u2029]+/g," ")}var BL=new Set(["createdby","createdon","createdonbehalfby","importsequencenumber","modifiedby","modifiedon","modifiedonbehalfby","overriddencreatedon","ownerid","owningbusinessunit","owningteam","owninguser","timezoneruleversionnumber","utcconversiontimezonecode","versionnumber"]);function Tl(e){var t;return((t=e.attributeTypeName)!==null&&t!==void 0?t:"").replace(/Type$/,"").toLowerCase()}function uy(e){var t,r;let n=e.choices;if(!n||n.length===0)return;let i=Tl(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 sy(e,t){return e.logicalName<t.logicalName?-1:e.logicalName>t.logicalName?1:0}function cy(e){return!BL.has(e.logicalName)&&(!e.attributeOf||Tl(e)==="image")&&e.isValidForRead!==!1}var ly=new Set(["boolean","picklist","multiselectpicklist","state","status"]);function dy(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(sy),i=e.attributes.filter(a=>!r.has(a.logicalName)).sort(sy);return[...n,...i]}function fp(e){var t;let r=[],n=new Set,i=dy(e);for(let a of i){let o=Tl(a),s=o==="image";cy(a)&&(s&&a.attributeOf&&n.add(a.attributeOf),r.push({AttributeTypeName:o,IsReadOnly:!a.isValidForUpdate,LogicalName:a.logicalName,OptionSet:uy(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))}}Rt.toDesignerEntity=fp;function py(e,t="None"){let r={};for(let n of e)r[n.logicalName]=fp(n);return hy(r,t)}Rt.buildGenPageRuntimeTypes=py;var fy=`export interface TableRegistrations extends BaseTableRegistrations {
+`,my=`export interface EnumRegistrations extends BaseEnumRegistrations {
+`;function UL(e,t){return e.length>0?py(e,t).text:vy(`${fy}}
+`,`${my}}
+`,"","")}Rt.renderGenPageAuthoringTypes=UL;function $L(e){let t=new Set;for(let n of e)for(let i of fp(n).Attributes)ly.has(i.AttributeTypeName)&&t.add(`${n.logicalName}_${i.LogicalName}`);let r=new Map;for(let n of e)for(let i of dy(n)){let a=`${n.logicalName}_${i.logicalName}`,o=uy(i);if(cy(i)||!ly.has(Tl(i))||!o||t.has(a)||r.has(a))continue;let s={name:a,runtime:{},labels:new Map};r.set(a,{declaration:gy(a,o,!1,s),model:s})}return r}Rt.buildGenPageLegacyEnums=$L;function hy(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=fy,u=my,c="",d="";for(let p of a){s&&p.Description&&(c+=`// ${pp(p.Description)}
`),c+=`export type ${p.LogicalName} = TableRow<{
// Primary Key Column
readonly ${p.PrimaryIdAttribute}: string,
@@ -60,21 +60,21 @@ var cO=Object.create;var Hs=Object.defineProperty;var dO=Object.getOwnPropertyDe
`;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},
+ ${f.IsReadOnly||v.every(E=>!e[E])?" readonly ":""}_${f.LogicalName}_value: `;let b="";for(let E of v)b+=`${b.length===0?"":" | "}\`/${E}(\${string})\``;m+=`${b},
`;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},
+`;let b=(n=i.get(v))!==null&&n!==void 0?n:{name:v,runtime:{},labels:new Map};i.set(v,b),d+=gy(v,f.OptionSet,o,b),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)}
+`;break;default:h=!1}h&&(s&&f.Description&&(c+=` // ${pp(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)}
+`,{text:vy(l,u,c,d),enums:i}}Rt.renderTypeRegistrations=hy;function gy(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: ${pp(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`
+`}function vy(e,t,r,n){return`
// ---------------- Type Definitions which can be imported from ./RuntimeTypes -------------------------
${e}
${t}
@@ -345,19 +345,19 @@ 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
+`}});var wy=y(Pl=>{"use strict";Object.defineProperty(Pl,"__esModule",{value:!0});Pl.generateGenPageRuntimeTypes=void 0;var by=mp(),Si=te(),yy=new Set(["None","ColorsDefaultsConstraints","ColorsDefaultsConstraintsDescriptions"]),Ni="generateGenPageRuntimeTypes";async function qL(e,t,r){let n=VL(t),i=GL(r),a=[];for(let o of n){let s=await e(o);if(s.columnDetailComplete!==!0)throw new Si.SdkError("GENPAGE_DATA_SOURCE_INCOMPLETE",`${Ni}: 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,by.renderGenPageAuthoringTypes)(a,i)}Pl.generateGenPageRuntimeTypes=qL;function VL(e){if(!Array.isArray(e))throw new Si.InvalidArgumentError(`${Ni}: dataSources must be an array of table logical names`);let t=new Set;for(let r of e){if(typeof r!="string"||!by.TABLE_LOGICAL_NAME.test(r))throw new Si.InvalidArgumentError(`${Ni}: a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(r)}'`);if(t.has(r))throw new Si.InvalidArgumentError(`${Ni}: data source '${r}' is listed twice; a page's dataSources hold each table once`);t.add(r)}return[...t]}function GL(e){if(e===void 0)return"None";if(e===null||typeof e!="object"||Array.isArray(e))throw new Si.InvalidArgumentError(`${Ni}: options must be an object`);let t=Object.keys(e).filter(n=>n!=="detail");if(t.length>0)throw new Si.InvalidArgumentError(`${Ni}: unknown option '${t[0]}' (the only option is 'detail')`);let r=e.detail===void 0?"None":e.detail;if(typeof r!="string"||!yy.has(r))throw new Si.InvalidArgumentError(`${Ni}: detail must be one of ${[...yy].map(n=>`'${n}'`).join(", ")}, got '${String(r)}'`);return r}});var ha=y(Rl=>{"use strict";Object.defineProperty(Rl,"__esModule",{value:!0});Rl.DEFAULT_LCID=void 0;Rl.DEFAULT_LCID=1033});var lt=y(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0});Vr.assignMissingIds=Vr.pointerTouchesValueMap=Vr.isValueMapKey=Vr.newId=void 0;var zL=ca();function Ay(){return globalThis.crypto.randomUUID().toLowerCase()}Vr.newId=Ay;function WL(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var gp=new Set(["parameters","bag","expression","rawExpression","lookupValue","stepLabels","genPage","inputData"]);function jL(e){return gp.has(e)}Vr.isValueMapKey=jL;function HL(e){return zL.JsonPointer.parse(e).some(t=>gp.has(t))}Vr.pointerTouchesValueMap=HL;function KL(e){return hp(e),e}Vr.assignMissingIds=KL;function hp(e){if(Array.isArray(e)){e.forEach(t=>hp(t));return}if(WL(e)){(typeof e.id!="string"||e.id.length===0)&&(e.id=Ay());for(let t of Object.keys(e))t==="id"||gp.has(t)||hp(e[t])}}});var Ol=y(jn=>{"use strict";Object.defineProperty(jn,"__esModule",{value:!0});jn.postChangeSet=jn.parseChangeSetStatuses=jn.renderChangeSet=void 0;var Di=te(),JL=be(),Ey=lt(),zo=ae();function Cy(e,t){let r=`batch_${(0,Ey.newId)()}`,n=`changeset_${(0,Ey.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 Di.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 Di.InvalidArgumentError(`batch operation ${s.method} ${s.path} has a body containing the batch boundary`);(0,zo.assertNoControlChars)(s.path,"batch operation path"),s.etag&&(0,zo.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,zo.assertNoControlChars)(f,"batch operation header name"),(0,zo.assertNoControlChars)(m,"batch operation header value"),!/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/.test(f))throw new Di.InvalidArgumentError(`batch operation header name '${f}' is not a valid HTTP token`);return s.contentType!==void 0&&(0,zo.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}}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
+`),batchId:r,contentIds:i}}jn.renderChangeSet=Cy;function Sy(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),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=="<"&&"&lt;"||e==">"&&"&gt;"||e=="&"&&"&amp;"||e=='"'&&"&quot;"||"&#"+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,`
+`);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 b=(a=/^Content-ID:\s*(\S+)/im.exec(m))===null||a===void 0?void 0:a[1];if(b===void 0||d.has(b)||!u.has(b))return;d.add(b),c.push(Number(v[1]))}return c.length===0?void 0:c}jn.parseChangeSetStatuses=Sy;async function QL(e,t,r){if(t.length===0)return;let{body:n,batchId:i,contentIds:a}=Cy(e,t),o=await e.postBatch(n,i),s=e.apiUrl("/$batch");if((0,JL.ensureSuccess)(o,s),typeof o.body!="string"||o.body.length===0)throw new Di.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=Sy(o.body,a);if(l===void 0)throw new Di.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 Di.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 Di.ConnectionError(s,u,`atomic write of ${r} was rolled back: the change set reported HTTP ${u}`)}jn.postChangeSet=QL});var xl=y(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.updateTable=X.deleteAlternateKey=X.createAlternateKey=X.deleteGlobalOptionSet=X.createGlobalOptionSet=X.deleteRelationship=X.deleteColumn=X.updateColumn=X.deleteTable=X.createRelationship=X.insertStatusValue=X.createCustomerColumn=X.createColumns=X.setColumnVisualization=X.getColumnVisualization=X.createColumn=X.createTable=X.resolveEntitySetName=X.pluralFallback=void 0;var de=be(),J=ae(),Gr=ha(),we=te(),XL=Ol(),YL={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 Fe(e,t){return{"@odata.type":"Microsoft.Dynamics.CRM.Label",LocalizedLabels:ZL(e,t)}}var Ny=65535;function ZL(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 we.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 we.InvalidArgumentError(`localized label key '${a}' is not an LCID (expected a canonical positive integer, e.g. 1033)`);let s=Number(a);if(s>Ny)throw new we.InvalidArgumentError(`localized label LCID ${s} is out of range (1-${Ny})`);if(i.has(s))throw new we.InvalidArgumentError(`localized label LCID ${s} is specified more than once`);if(i.add(s),typeof o!="string")throw new we.InvalidArgumentError(`localized label for LCID ${s} must be a string`);return r(o,s)})}function Ty(e){return typeof e=="string"?`${e}s`:Object.fromEntries(Object.entries(e).map(([t,r])=>{if(typeof r!="string")throw new we.InvalidArgumentError(`localized label for LCID ${t} must be a string`);return[t,`${r}s`]}))}X.pluralFallback=Ty;function Wo(e){return{Value:e,CanBeChanged:!0,ManagedPropertyLogicalName:"canmodifyrequirementlevelsettings"}}function bp(e){let t=e.indexOf("_");return t>0?e.slice(0,t):e}function Dy(e,t,r){let n=e[t];n&&typeof n=="object"?n.Value=r:e[t]={Value:r}}function jo(e){let t=(0,de.readCreatedId)(e,"MetadataId");if(!t)throw new we.InvalidArgumentError("Dataverse did not return a MetadataId for the created metadata component");return t}function ek(e,t,r){var n,i,a,o,s,l,u,c,d,p,f,m,h,v,b,E,C,N,R,O,F,k,P,V;if(t.defaultValue!==void 0&&e!=="boolean")throw new we.InvalidArgumentError(`createColumn: 'defaultValue' applies to boolean columns, but '${t.schemaName}' is of type '${e}'.`);if(t.integerFormat!==void 0&&e!=="integer")throw new we.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:(b=t.maxValue)!==null&&b!==void 0?b:1e9};case"boolean":return{"@odata.type":"Microsoft.Dynamics.CRM.BooleanAttributeMetadata",AttributeType:"Boolean",AttributeTypeName:{Value:"BooleanType"},DefaultValue:(E=t.defaultValue)!==null&&E!==void 0?E:!1,OptionSet:{"@odata.type":"Microsoft.Dynamics.CRM.BooleanOptionSetMetadata",TrueOption:{Value:1,Label:Fe((C=t.trueLabel)!==null&&C!==void 0?C:"Yes",r)},FalseOption:{Value:0,Label:Fe((N=t.falseLabel)!==null&&N!==void 0?N:"No",r)}}};case"dateTime":return{"@odata.type":"Microsoft.Dynamics.CRM.DateTimeAttributeMetadata",AttributeType:"DateTime",AttributeTypeName:{Value:"DateTimeType"},Format:(R=t.dateFormat)!==null&&R!==void 0?R:"DateAndTime"};case"choice":return Iy(t,r,!1);case"multiChoice":return Iy(t,r,!0);case"file":return{"@odata.type":"Microsoft.Dynamics.CRM.FileAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"FileType"},MaxSizeInKB:(O=t.maxSizeKb)!==null&&O!==void 0?O: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:(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:(P=t.maxLength)!==null&&P!==void 0?P:100,AutoNumberFormat:(V=t.autoNumberFormat)!==null&&V!==void 0?V:""};default:throw new we.InvalidArgumentError(`unsupported column type '${String(e)}'`)}}function Iy(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 we.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:Fe(a.label,t)}))},i}var vp=new WeakMap;async function tk(e,t){var r,n;let i=(r=vp.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,de.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.EntitySetName;if(!s)throw new we.InvalidArgumentError(`could not resolve EntitySetName for '${t}'`);(0,J.assertODataName)(s,`server-derived EntitySetName for '${t}'`);let l=vp.get(e);return l||(l=new Map,vp.set(e,l)),l.set(t,s),s}X.resolveEntitySetName=tk;async function rk(e,t){var r,n,i,a,o,s,l,u,c,d,p,f,m,h,v;let b=(r=t.languageCode)!==null&&r!==void 0?r:Gr.DEFAULT_LCID,E=bp(t.schemaName),C=(n=t.primaryColumnSchemaName)!==null&&n!==void 0?n:`${E}_Name`,N={"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},SchemaName:C,RequiredLevel:Wo("None"),MaxLength:(i=t.primaryColumnMaxLength)!==null&&i!==void 0?i:100,FormatName:{Value:"Text"},DisplayName:Fe((a=t.primaryColumnDisplayName)!==null&&a!==void 0?a:"Name",b),IsPrimaryName:!0};t.primaryColumnAutoNumberFormat&&(N.AutoNumberFormat=t.primaryColumnAutoNumberFormat),t.columns&&Oy(t.columns,"createTable");let R={"@odata.type":"Microsoft.Dynamics.CRM.EntityMetadata",SchemaName:t.schemaName,DisplayName:Fe(t.displayName,b),DisplayCollectionName:Fe((o=t.pluralName)!==null&&o!==void 0?o:Ty(t.displayName),b),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:[N,...((c=t.columns)!==null&&c!==void 0?c:[]).map(Be=>wp(Be,b))]};t.description&&(R.Description=Fe(t.description,b));let O="/EntityDefinitions",F=(0,de.ensureSuccess)(await e.post(O,R),e.apiUrl(O)),k=jo(F),P=`/EntityDefinitions(${k})`+(0,J.odataQuery)([["$select","LogicalName,EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute"]]),V=Math.max(1,Math.trunc((d=t.readBackAttempts)!==null&&d!==void 0?d:6)),q=Math.max(0,(p=t.readBackDelayMs)!==null&&p!==void 0?p:1e3),ze;for(let Be=1;Be<=V;Be+=1){let Qe=await e.get(P);if(Qe.status>=200&&Qe.status<300){ze=Qe;break}Qe.status!==404&&(0,de.ensureSuccess)(Qe,e.apiUrl(P)),Be<V&&q>0&&await new Promise(Z=>setTimeout(Z,q))}if(!ze)throw new we.SdkError("TABLE_METADATA_NOT_VISIBLE",`Table '${t.schemaName}' WAS CREATED (MetadataId ${k}) but its metadata was still not readable after ${V} 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 Tt=ze.body;return{logicalName:(f=Tt.LogicalName)!==null&&f!==void 0?f:t.schemaName.toLowerCase(),metadataId:k,entitySetName:(m=Tt.EntitySetName)!==null&&m!==void 0?m:"",primaryIdAttribute:(h=Tt.PrimaryIdAttribute)!==null&&h!==void 0?h:`${t.schemaName.toLowerCase()}id`,primaryNameAttribute:(v=Tt.PrimaryNameAttribute)!==null&&v!==void 0?v:C.toLowerCase()}}X.createTable=rk;function wp(e,t){var r,n;let i=(r=e.languageCode)!==null&&r!==void 0?r:t,a={...ek(e.type,e,i),SchemaName:e.schemaName,RequiredLevel:Wo((n=e.required)!==null&&n!==void 0?n:"None"),DisplayName:Fe(e.displayName,i)};return e.description&&(a.Description=Fe(e.description,i)),e.sourceType&&e.sourceType!=="Simple"&&(a.SourceType=e.sourceType==="Rollup"?2:1,e.formulaDefinition&&(a.FormulaDefinition=e.formulaDefinition)),Py(a,e),a}function Py(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 nk(e,t,r){var n;let i=wp(r,(n=r.languageCode)!==null&&n!==void 0?n:Gr.DEFAULT_LCID),a=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Attributes`,o=(0,de.ensureSuccess)(await e.post(a,i),e.apiUrl(a)),s={logicalName:r.schemaName.toLowerCase(),metadataId:jo(o)};if(r.visualization&&r.visualization!=="None")try{await Ly(e,t,s.logicalName,s.metadataId,r.visualization)}catch(l){let u=new we.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}X.createColumn=nk;var ga="/controlconfigurations",Ry="CustomRenderersConfiguration",yp={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 Oy(e,t){let r=e.find(n=>n.visualization&&n.visualization!=="None");if(r)throw new we.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 xy(e){return JSON.stringify({type:yp[e]})}function ik(e){if(!e)return"None";let t;try{t=JSON.parse(e)}catch{return"None"}let r=t?.type,n=Object.keys(yp).find(i=>yp[i]===r);return n??"None"}async function Fy(e,t,r){var n,i;let a=`entitylogicalname eq '${(0,J.odataLiteral)(t)}' and Attribute/logicalname eq '${(0,J.odataLiteral)(r)}'`,o=`${ga}${(0,J.odataQuery)([["$select","name,uniquename,metadatajson"],["$expand","Attribute($select=name,logicalname)"],["$filter",a]])}`,l=(i=(n=(0,de.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 ak(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,de.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||n===void 0?void 0:n.MetadataId;if(!o)throw new we.InvalidArgumentError(`cannot resolve column '${r}' on '${t}' to set its visualization`);return(0,J.normalizeGuid)(o,"MetadataId")}async function Ly(e,t,r,n,i){let a={name:Ry,uniquename:`msdyn_${t}_${r}_customrenderers`,metadatajson:xy(i),"[email protected]":`/attributes(${(0,J.normalizeGuid)(n,"MetadataId")})`,entitylogicalname:t};(0,de.ensureSuccess)(await e.post(ga,a),e.apiUrl(ga))}async function ok(e,t,r){var n;let i=await Fy(e,t,r);return ik((n=i[0])===null||n===void 0?void 0:n.metadatajson)}X.getColumnVisualization=ok;async function sk(e,t,r,n){let a=(await Fy(e,t,r)).map(u=>u.controlconfigurationid).filter(u=>!!u);if(n==="None"){for(let u of a){let c=`${ga}(${(0,J.normalizeGuid)(u,"controlconfigurationid")})`;(0,de.ensureSuccess)(await e.delete(c),e.apiUrl(c))}return}let[o,...s]=a,l=await ak(e,t,r);if(o){let u=`${ga}(${(0,J.normalizeGuid)(o,"controlconfigurationid")})`,c={name:Ry,metadatajson:xy(n),"[email protected]":`/attributes(${l})`,entitylogicalname:t};(0,de.ensureSuccess)(await e.patch(u,c),e.apiUrl(u))}else await Ly(e,t,r,l,n);for(let u of s){let c=`${ga}(${(0,J.normalizeGuid)(u,"controlconfigurationid")})`;(0,de.ensureSuccess)(await e.delete(c),e.apiUrl(c))}}X.setColumnVisualization=sk;async function lk(e,t,r){if(r.length===0)return;if(Oy(r,"createColumns"),!e.supportsAtomicBatch)throw new we.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,XL.postChangeSet)(e,r.map(i=>{var a;return{method:"POST",path:n,body:wp(i,(a=i.languageCode)!==null&&a!==void 0?a:Gr.DEFAULT_LCID)}}),`${r.length} column(s) on '${t}'`)}X.createColumns=lk;async function uk(e,t,r){var n,i,a,o;let s=(n=r.languageCode)!==null&&n!==void 0?n:Gr.DEFAULT_LCID,l=bp(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:Fe(r.displayName,s),RequiredLevel:Wo((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,de.ensureSuccess)(await e.post("/CreateCustomerRelationships",d),e.apiUrl("/CreateCustomerRelationships")),{logicalName:r.schemaName.toLowerCase(),metadataId:""}}X.createCustomerColumn=uk;async function ck(e,t,r){var n,i,a,o,s;let l=(n=r.languageCode)!==null&&n!==void 0?n:Gr.DEFAULT_LCID,u={EntityLogicalName:t,AttributeLogicalName:"statuscode",Label:Fe(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,de.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)}X.insertStatusValue=ck;async function dk(e,t){var r,n,i,a,o;let s=(r=t.languageCode)!==null&&r!==void 0?r:Gr.DEFAULT_LCID,l,u;if(t.type==="OneToMany"){if(!t.referencedEntity||!t.referencingEntity)throw new we.InvalidArgumentError("OneToMany relationship requires referencedEntity and referencingEntity");let p=(n=t.lookupSchemaName)!==null&&n!==void 0?n:`${bp(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:Wo((i=t.lookupRequired)!==null&&i!==void 0?i:"None"),DisplayName:Fe((a=t.lookupDisplayName)!==null&&a!==void 0?a:t.referencedEntity,s)}}}else{if(!t.entity1||!t.entity2)throw new we.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,de.ensureSuccess)(await e.post(c,l),e.apiUrl(c));return{schemaName:t.schemaName,metadataId:jo(d),lookupLogicalName:u}}X.createRelationship=dk;async function pk(e,t){let r=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')`;(0,de.ensureSuccess)(await e.delete(r),e.apiUrl(r))}X.deleteTable=pk;async function fk(e,t,r,n){var i,a;let o=(i=n.languageCode)!==null&&i!==void 0?i:Gr.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,de.ensureSuccess)(await e.get(l),e.apiUrl(l)).body,d=YL[(a=c.AttributeType)!==null&&a!==void 0?a:""];if(!c.MetadataId||!d)throw new we.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,de.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=Fe(n.displayName,o)),n.description!==void 0&&(m.Description=Fe(n.description,o)),n.required!==void 0&&(m.RequiredLevel=Wo(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 we.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 we.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),Py(m,n);let h=`${s}(${p})`;(0,de.ensureSuccess)(await e.put(h,m,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(h))}X.updateColumn=fk;async function mk(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,de.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new we.InvalidArgumentError(`column '${r}' not found on '${t}'`);let l=`${i}(${(0,J.normalizeGuid)(s,"MetadataId")})`;(0,de.ensureSuccess)(await e.delete(l),e.apiUrl(l))}X.deleteColumn=mk;async function hk(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,de.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 we.InvalidArgumentError(`relationship '${t}' not found`);let l=`/RelationshipDefinitions(${(0,J.normalizeGuid)(s,"MetadataId")})`;(0,de.ensureSuccess)(await e.delete(l),e.apiUrl(l))}X.deleteRelationship=hk;async function _y(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,de.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 gk(e,t){var r;let n=t.name.toLowerCase(),i=await _y(e,n);if(i)return{name:n,metadataId:i};let a=(r=t.languageCode)!==null&&r!==void 0?r:Gr.DEFAULT_LCID,o={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",Name:n,DisplayName:Fe(t.displayName,a),IsGlobal:!0,OptionSetType:"Picklist",Options:t.options.map(l=>({Value:l.value,Label:Fe(l.label,a)}))};t.description&&(o.Description=Fe(t.description,a));let s="/GlobalOptionSetDefinitions";try{let l=(0,de.ensureSuccess)(await e.post(s,o),e.apiUrl(s));return{name:n,metadataId:jo(l)}}catch(l){let u;try{u=await _y(e,n)}catch{u=void 0}if(u)return{name:n,metadataId:u};throw l}}X.createGlobalOptionSet=gk;async function vk(e,t){let r=`/GlobalOptionSetDefinitions(Name='${(0,J.odataPathLiteral)(t.toLowerCase())}')`;(0,de.ensureSuccess)(await e.delete(r),e.apiUrl(r))}X.deleteGlobalOptionSet=vk;async function yk(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:Gr.DEFAULT_LCID,a={"@odata.type":"Microsoft.Dynamics.CRM.EntityKeyMetadata",SchemaName:r.schemaName,DisplayName:Fe(r.displayName,i),KeyAttributes:r.keyAttributes},o=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Keys`,s=(0,de.ensureSuccess)(await e.post(o,a),e.apiUrl(o));return{logicalName:r.schemaName.toLowerCase(),metadataId:jo(s)}}X.createAlternateKey=yk;async function bk(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,de.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new we.InvalidArgumentError(`alternate key '${r}' not found on '${t}'`);let l=`${i}(${(0,J.normalizeGuid)(s,"MetadataId")})`;(0,de.ensureSuccess)(await e.delete(l),e.apiUrl(l))}X.deleteAlternateKey=bk;async function wk(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:Gr.DEFAULT_LCID,a=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')`,s=(0,de.ensureSuccess)(await e.get(a),e.apiUrl(a)).body,l=s.MetadataId;if(!l)throw new we.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=Fe(r.displayName,i)),r.pluralName!==void 0&&(s.DisplayCollectionName=Fe(r.pluralName,i)),r.description!==void 0&&(s.Description=Fe(r.description,i)),r.auditEnabled!==void 0&&Dy(s,"IsAuditEnabled",r.auditEnabled),r.duplicateDetectionEnabled!==void 0&&Dy(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,de.ensureSuccess)(await e.put(c,s,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(c))}X.updateTable=wk});var Kn=y(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.rebuildRaw=Ot.assembleChildren=Ot.spliceChildren=Ot.mergeAttrs=Ot.rawFromNode=Ot.emptyBag=void 0;var Hn=te(),ky=1e6,Ll=512;function Ak(){return{a:[],c:[]}}Ot.emptyBag=Ak;function My(e,t=0){if(t>Ll)throw new Hn.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${Ll}`);return{n:e.getNodeName(),a:e.getAllProperties().map(r=>[r.key,r.value]),c:e.getAllChildren().map(r=>My(r,t+1))}}Ot.rawFromNode=My;function Ek(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}Ot.mergeAttrs=Ek;function Fl(e,t){let r=new Set;for(let s of e){let l=s.i;if(!Number.isInteger(l)||l<0||l>ky)throw new Hn.InvalidArgumentError(`Bag child index must be an integer in [0, ${ky}] (got ${String(l)})`);if(r.has(l))throw new Hn.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}Ot.spliceChildren=Fl;function Ck(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)}Ot.assembleChildren=Ck;function By(e,t,r,n=0){if(n>Ll)throw new Hn.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${Ll}`);Sk(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,By(a,t,i,n+1));return i}Ot.rebuildRaw=By;function Sk(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Hn.InvalidArgumentError(`Malformed hybrid node at depth ${t}: expected a JSON object`);let r=e;if(typeof r.n!="string")throw new Hn.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 Hn.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 Hn.InvalidArgumentError(`Malformed hybrid node '${r.n}': each attribute must be a [string, string] pair`)}});var va=y(gn=>{"use strict";function Nk(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 Ep(e,t){return t===void 0&&(t=Object),t&&typeof t.freeze=="function"?t.freeze(e):e}function Dk(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 Uy=Ep({HTML:"text/html",isHTML:function(e){return e===Uy.HTML},XML_APPLICATION:"application/xml",XML_TEXT:"text/xml",XML_XHTML_APPLICATION:"application/xhtml+xml",XML_SVG_IMAGE:"image/svg+xml"}),$y=Ep({HTML:"http://www.w3.org/1999/xhtml",isHTML:function(e){return e===$y.HTML},SVG:"http://www.w3.org/2000/svg",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"}),kl=/[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]/,Ap=new RegExp("[\\-\\.0-9"+kl.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),Ik=new RegExp("^"+kl.source+Ap.source+"*(?::"+kl.source+Ap.source+"*)?$");gn.assign=Dk;gn.find=Nk;gn.freeze=Ep;gn.MIME_TYPE=Uy;gn.NAMESPACE=$y;gn.nameStartChar=kl;gn.nameChar=Ap;gn.tagNamePattern=Ik});var Fp=y(wn=>{var Cp=va(),zr=Cp.find,Ko=Cp.NAMESPACE,ya=Cp.tagNamePattern;function _k(e){return e!==""}function Tk(e){return e?e.split(/[\t\n\f\r ]+/).filter(_k):[]}function Pk(e,t){return e.hasOwnProperty(t)||(e[t]=!0),e}function qy(e){if(!e)return[];var t=Tk(e);return Object.keys(t.reduce(Pk,{}))}function Rk(e){return function(t){return e&&e.indexOf(t)!==-1}}function Qo(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function Ft(e,t){var r=e.prototype;if(!(r instanceof t)){let i=function(){};var n=i;i.prototype=t.prototype,i=new i,Qo(r,i),e.prototype=r=i}r.constructor!=e&&(typeof e!="function"&&console.error("unknown Class:"+e),r.constructor=e)}var Lt={},ar=Lt.ELEMENT_NODE=1,ba=Lt.ATTRIBUTE_NODE=2,Ho=Lt.TEXT_NODE=3,Jy=Lt.CDATA_SECTION_NODE=4,Qy=Lt.ENTITY_REFERENCE_NODE=5,Ok=Lt.ENTITY_NODE=6,Sp=Lt.PROCESSING_INSTRUCTION_NODE=7,Np=Lt.COMMENT_NODE=8,Xy=Lt.DOCUMENT_NODE=9,Yy=Lt.DOCUMENT_TYPE_NODE=10,vn=Lt.DOCUMENT_FRAGMENT_NODE=11,xk=Lt.NOTATION_NODE=12,pt={},Ye={},RJ=pt.INDEX_SIZE_ERR=(Ye[1]="Index size error",1),OJ=pt.DOMSTRING_SIZE_ERR=(Ye[2]="DOMString size error",2),xt=pt.HIERARCHY_REQUEST_ERR=(Ye[3]="Hierarchy request error",3),xJ=pt.WRONG_DOCUMENT_ERR=(Ye[4]="Wrong document",4),Vy=pt.INVALID_CHARACTER_ERR=(Ye[5]="Invalid character",5),FJ=pt.NO_DATA_ALLOWED_ERR=(Ye[6]="No data allowed",6),LJ=pt.NO_MODIFICATION_ALLOWED_ERR=(Ye[7]="No modification allowed",7),Zy=pt.NOT_FOUND_ERR=(Ye[8]="Not found",8),kJ=pt.NOT_SUPPORTED_ERR=(Ye[9]="Not supported",9),Gy=pt.INUSE_ATTRIBUTE_ERR=(Ye[10]="Attribute in use",10),Er=pt.INVALID_STATE_ERR=(Ye[11]="Invalid state",11),MJ=pt.SYNTAX_ERR=(Ye[12]="Syntax error",12),BJ=pt.INVALID_MODIFICATION_ERR=(Ye[13]="Invalid modification",13),UJ=pt.NAMESPACE_ERR=(Ye[14]="Invalid namespace",14),$J=pt.INVALID_ACCESS_ERR=(Ye[15]="Invalid access",15);function ie(e,t){if(t instanceof Error)var r=t;else r=this,Error.call(this,Ye[e]),this.message=Ye[e],Error.captureStackTrace&&Error.captureStackTrace(this,ie);return r.code=e,t&&(this.message=this.message+": "+t),r}ie.prototype=Error.prototype;Qo(pt,ie);function yn(){}yn.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++)xp(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 wa(e,t){this._node=e,this._refresh=t,Dp(this)}function Dp(e){var t=e._node._inc||e._node.ownerDocument._inc;if(e._inc!==t){var r=e._refresh(e._node);if(pb(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];Qo(r,e),e._inc=t}}wa.prototype.item=function(e){return Dp(this),this[e]||null};Ft(wa,yn);function Bl(){this._nameIndex=Object.create(null)}function eb(e,t){for(var r=e.length;r--;)if(e[r]===t)return r}function Fk(e,t){e._nameIndex[t.nodeName]=t}function tb(e,t){e._nameIndex[t.nodeName]===t&&delete e._nameIndex[t.nodeName]}function zy(e,t,r,n){if(n?(t[eb(t,n)]=r,tb(t,n)):t[t.length++]=r,Fk(t,r),e){r.ownerElement=e;var i=e.ownerDocument;i&&(n&&ib(i,e,n),Lk(i,e,r))}}function Wy(e,t,r){var n=eb(t,r);if(n>=0){for(var i=t.length-1;n<i;)t[n]=t[++n];if(t.length=i,tb(t,r),e){var a=e.ownerDocument;a&&(ib(a,e,r),r.ownerElement=null)}}else throw new ie(Zy,new Error(e.tagName+"@"+r))}Bl.prototype={length:0,item:yn.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 ie(Gy);var r=this._nameIndex[e.nodeName];return zy(this._ownerElement,this,e,r),r},setNamedItemNS:function(e){var t=e.ownerElement,r;if(t&&t!=this._ownerElement)throw new ie(Gy);return r=this.getNamedItemNS(e.namespaceURI,e.localName),zy(this._ownerElement,this,e,r),r},removeNamedItem:function(e){var t=this.getNamedItem(e);return Wy(this._ownerElement,this,t),t},removeNamedItemNS:function(e,t){var r=this.getNamedItemNS(e,t);return Wy(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 rb(){}rb.prototype={hasFeature:function(e,t){return!0},createDocument:function(e,t,r){var n=new Xo;if(n.implementation=this,n.childNodes=new yn,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 Gl;return n.name=e,n.nodeName=e,n.publicId=t||"",n.systemId=r||"",n}};function pe(){}pe.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 $l(this,e,t)},replaceChild:function(e,t){$l(this,e,t,ob),t&&this.removeChild(t)},removeChild:function(e){return ab(this,e)},appendChild:function(e){return this.insertBefore(e,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(e){return db(this.ownerDocument||this,this,e)},normalize:function(){Xe(this,null,{enter:function(e){for(var t=e.firstChild;t;){var r=t.nextSibling;if(r!==null&&r.nodeType===Ho&&t.nodeType===Ho){for(var n=[],i=r;i!==null&&i.nodeType===Ho;)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("")),Vl(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==ba?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==ba?t.ownerDocument:t.parentNode}return null},isDefaultNamespace:function(e){var t=this.lookupPrefix(e);return t==null}};function nb(e){return e=="<"&&"&lt;"||e==">"&&"&gt;"||e=="&"&&"&amp;"||e=='"'&&"&quot;"||"&#"+e.charCodeAt()+";"}Qo(Lt,pe);Qo(Lt,pe.prototype);function Ul(e,t){return Xe(e,null,{enter:function(r){return t(r)?Xe.STOP:!0}})===Xe.STOP}function Xe(e,t,r){for(var n=[{node:e,context:t,phase:Xe.ENTER}];n.length>0;){var i=n.pop();if(i.phase===Xe.ENTER){var a=r.enter(i.node,i.context);if(a===Xe.STOP)return Xe.STOP;if(n.push({node:i.node,context:a,phase:Xe.EXIT}),a==null)continue;for(var o=i.node.lastChild;o;)n.push({node:o,context:a,phase:Xe.ENTER}),o=o.previousSibling}else r.exit&&r.exit(i.node,i.context)}}Xe.STOP=Symbol("walkDOM.STOP");Xe.ENTER=0;Xe.EXIT=1;function Xo(){this.ownerDocument=this}function Lk(e,t,r){e&&e._inc++;var n=r.namespaceURI;n===Ko.XMLNS&&(t._nsMap[r.prefix?r.localName:""]=r.value)}function ib(e,t,r,n){e&&e._inc++;var i=r.namespaceURI;i===Ko.XMLNS&&delete t._nsMap[r.prefix?r.localName:""]}function Vl(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 ab(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,Vl(e.ownerDocument,e),t}function kk(e){return e&&(e.nodeType===pe.DOCUMENT_NODE||e.nodeType===pe.DOCUMENT_FRAGMENT_NODE||e.nodeType===pe.ELEMENT_NODE)}function Mk(e){return e&&(Wr(e)||Ip(e)||bn(e)||e.nodeType===pe.DOCUMENT_FRAGMENT_NODE||e.nodeType===pe.COMMENT_NODE||e.nodeType===pe.PROCESSING_INSTRUCTION_NODE)}function bn(e){return e&&e.nodeType===pe.DOCUMENT_TYPE_NODE}function Wr(e){return e&&e.nodeType===pe.ELEMENT_NODE}function Ip(e){return e&&e.nodeType===pe.TEXT_NODE}function jy(e,t){var r=e.childNodes||[];if(zr(r,Wr)||bn(t))return!1;var n=zr(r,bn);return!(t&&n&&r.indexOf(n)>r.indexOf(t))}function Hy(e,t){var r=e.childNodes||[];function n(a){return Wr(a)&&a!==t}if(zr(r,n))return!1;var i=zr(r,bn);return!(t&&i&&r.indexOf(i)>r.indexOf(t))}function Bk(e,t,r){if(!kk(e))throw new ie(xt,"Unexpected parent node type "+e.nodeType);if(r&&r.parentNode!==e)throw new ie(Zy,"child not in parent");if(!Mk(t)||bn(t)&&e.nodeType!==pe.DOCUMENT_NODE)throw new ie(xt,"Unexpected node type "+t.nodeType+" for parent node type "+e.nodeType)}function Uk(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===pe.DOCUMENT_FRAGMENT_NODE){var a=i.filter(Wr);if(a.length>1||zr(i,Ip))throw new ie(xt,"More than one element or text in fragment");if(a.length===1&&!jy(e,r))throw new ie(xt,"Element in fragment can not be inserted before doctype")}if(Wr(t)&&!jy(e,r))throw new ie(xt,"Only one element can be added and only after doctype");if(bn(t)){if(zr(n,bn))throw new ie(xt,"Only one doctype is allowed");var o=zr(n,Wr);if(r&&n.indexOf(o)<n.indexOf(r))throw new ie(xt,"Doctype can only be inserted before an element");if(!r&&o)throw new ie(xt,"Doctype can not be appended since element is present")}}function ob(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===pe.DOCUMENT_FRAGMENT_NODE){var a=i.filter(Wr);if(a.length>1||zr(i,Ip))throw new ie(xt,"More than one element or text in fragment");if(a.length===1&&!Hy(e,r))throw new ie(xt,"Element in fragment can not be inserted before doctype")}if(Wr(t)&&!Hy(e,r))throw new ie(xt,"Only one element can be added and only after doctype");if(bn(t)){let l=function(u){return bn(u)&&u!==r};var s=l;if(zr(n,l))throw new ie(xt,"Only one doctype is allowed");var o=zr(n,Wr);if(r&&n.indexOf(o)<n.indexOf(r))throw new ie(xt,"Doctype can only be inserted before an element")}}function $l(e,t,r,n){Bk(e,t,r),e.nodeType===pe.DOCUMENT_NODE&&(n||Uk)(e,t,r);var i=t.parentNode;if(i&&i.removeChild(t),t.nodeType===vn){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;Jo(a,l)}while(a!==o&&(a=a.nextSibling));return Vl(e.ownerDocument||e,e),t.nodeType==vn&&(t.firstChild=t.lastChild=null),t}function Jo(e,t){if(e.ownerDocument!==t){if(e.ownerDocument=t,e.nodeType===ar&&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;)Jo(i,t),i=i.nextSibling}}function $k(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,Vl(e.ownerDocument,e,t);var r=e.ownerDocument||e;return Jo(t,r),t}Xo.prototype={nodeName:"#document",nodeType:Xy,doctype:null,documentElement:null,_inc:1,insertBefore:function(e,t){if(e.nodeType==vn){for(var r=e.firstChild;r;){var n=r.nextSibling;this.insertBefore(r,t),r=n}return e}return $l(this,e,t),Jo(e,this),this.documentElement===null&&e.nodeType===ar&&(this.documentElement=e),e},removeChild:function(e){return this.documentElement==e&&(this.documentElement=null),ab(this,e)},replaceChild:function(e,t){$l(this,e,t,ob),Jo(e,this),t&&this.removeChild(t),Wr(e)&&(this.documentElement=e)},importNode:function(e,t){return qk(this,e,t)},getElementById:function(e){var t=null;return Ul(this.documentElement,function(r){if(r.nodeType==ar&&r.getAttribute("id")==e)return t=r,!0}),t},getElementsByClassName:function(e){var t=qy(e);return new wa(this,function(r){var n=[];return t.length>0&&Ul(r.documentElement,function(i){if(i!==r&&i.nodeType===ar){var a=i.getAttribute("class");if(a){var o=e===a;if(!o){var s=qy(a);o=t.every(Rk(s))}o&&n.push(i)}}}),n})},createElement:function(e){var t=new Ii;t.ownerDocument=this,t.nodeName=e,t.tagName=e,t.localName=e,t.childNodes=new yn;var r=t.attributes=new Bl;return r._ownerElement=t,t},createDocumentFragment:function(){var e=new zl;return e.ownerDocument=this,e.childNodes=new yn,e},createTextNode:function(e){var t=new _p;return t.ownerDocument=this,t.appendData(e),t},createComment:function(e){var t=new Tp;return t.ownerDocument=this,t.appendData(e),t},createCDATASection:function(e){if(e.indexOf("]]>")!==-1)throw new ie(Vy,'data contains "]]>"');var t=new Pp;return t.ownerDocument=this,t.appendData(e),t},createProcessingInstruction:function(e,t){var r=new Op;return r.ownerDocument=this,r.tagName=r.nodeName=r.target=e,r.nodeValue=r.data=t,r},createAttribute:function(e){var t=new ql;return t.ownerDocument=this,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},createEntityReference:function(e){if(!ya.test(e))throw new ie(Vy,'not a valid xml name "'+e+'"');var t=new Rp;return t.ownerDocument=this,t.nodeName=e,t},createElementNS:function(e,t){var r=new Ii,n=t.split(":"),i=r.attributes=new Bl;return r.childNodes=new yn,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 ql,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}};Ft(Xo,pe);function Ii(){this._nsMap={}}Ii.prototype={nodeType:ar,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===vn?this.insertBefore(e,null):$k(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 wa(this,function(t){var r=[];return Ul(t,function(n){n!==t&&n.nodeType==ar&&(e==="*"||n.tagName==e)&&r.push(n)}),r})},getElementsByTagNameNS:function(e,t){return new wa(this,function(r){var n=[];return Ul(r,function(i){i!==r&&i.nodeType===ar&&(e==="*"||i.namespaceURI===e)&&(t==="*"||i.localName==t)&&n.push(i)}),n})}};Xo.prototype.getElementsByTagName=Ii.prototype.getElementsByTagName;Xo.prototype.getElementsByTagNameNS=Ii.prototype.getElementsByTagNameNS;Ft(Ii,pe);function ql(){}ql.prototype.nodeType=ba;Ft(ql,pe);function Yo(){}Yo.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(Ye[xt])},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}};Ft(Yo,pe);function _p(){}_p.prototype={nodeName:"#text",nodeType:Ho,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}};Ft(_p,Yo);function Tp(){}Tp.prototype={nodeName:"#comment",nodeType:Np};Ft(Tp,Yo);function Pp(){}Pp.prototype={nodeName:"#cdata-section",nodeType:Jy};Ft(Pp,Yo);function Gl(){}Gl.prototype.nodeType=Yy;Ft(Gl,pe);function sb(){}sb.prototype.nodeType=xk;Ft(sb,pe);function lb(){}lb.prototype.nodeType=Ok;Ft(lb,pe);function Rp(){}Rp.prototype.nodeType=Qy;Ft(Rp,pe);function zl(){}zl.prototype.nodeName="#document-fragment";zl.prototype.nodeType=vn;Ft(zl,pe);function Op(){}Op.prototype.nodeType=Sp;Ft(Op,pe);function ub(){}ub.prototype.serializeToString=function(e,t,r,n){return cb.call(e,t,r,n)};pe.prototype.toString=cb;function cb(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 xp(this,i,e,t,l,n),i.join("")}function Ky(e,t,r){var n=e.prefix||"",i=e.namespaceURI;if(!i||n==="xml"&&i===Ko.XML||i===Ko.XMLNS)return!1;for(var a=r.length;a--;){var o=r[a];if(o.prefix===n)return o.namespace!==i}return!0}function Ml(e,t,r,n){if(n&&!ya.test(t))throw new ie(Er,'The attribute name "'+t+'" is not a valid XML QName');e.push(" ",t,'="',r.replace(/[<>&"\t\n\r]/g,nb),'"')}function xp(e,t,r,n,i,a){i||(i=[]),Xe(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 ar:var c=o.attributes,d=c.length,p=o.tagName;u=Ko.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 b=l[v];if(b.prefix===""&&b.namespace===o.namespaceURI){m=b.namespace;break}}if(m!==o.namespaceURI)for(var v=l.length-1;v>=0;v--){var b=l[v];if(b.namespace===o.namespaceURI){b.prefix&&(f=b.prefix+":"+p);break}}}if(a&&!ya.test(f))throw new ie(Er,'The element name "'+f+'" is not a valid XML QName');t.push("<",f);for(var E=l.slice(),C=0;C<d;C++){var N=c.item(C);N.prefix=="xmlns"?E.push({prefix:N.localName,namespace:N.value}):N.nodeName=="xmlns"&&E.push({prefix:"",namespace:N.value})}for(var C=0;C<d;C++){var N=c.item(C);if(Ky(N,u,E)){var R=N.prefix||"",O=N.namespaceURI;Ml(t,R?"xmlns:"+R:"xmlns",O,a),E.push({prefix:R,namespace:O})}var F=n?n(N):N;F&&(typeof F=="string"?t.push(F):Ml(t,F.name,F.value,a))}if(p===f&&Ky(o,u,E)){var k=o.prefix||"",O=o.namespaceURI;Ml(t,k?"xmlns:"+k:"xmlns",O,a),E.push({prefix:k,namespace:O})}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):xp(P,t,u,n,E.slice(),a),P=P.nextSibling;return t.push("</",p,">"),null}return{ns:E,isHTML:u,tag:f}}else return t.push("/>"),null;case Xy:case vn:return{ns:l.slice(),isHTML:u,tag:null};case ba:return Ml(t,o.name,o.value,a),null;case Ho:return t.push(o.data.replace(/[<&>]/g,nb)),null;case Jy:if(a&&o.data.indexOf("]]>")!==-1)throw new ie(Er,'The CDATASection data contains "]]>"');return t.push("<![CDATA[",o.data.replace(/]]>/g,"]]]]><![CDATA[>"),"]]>"),null;case Np:if(a&&o.data.indexOf("-->")!==-1)throw new ie(Er,'The comment node data contains "-->"');return t.push("<!--",o.data,"-->"),null;case Yy:if(a){if(!ya.test(o.name))throw new ie(Er,'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 ie(Er,"DocumentType publicId is not a valid PubidLiteral");if(o.systemId&&!/^("[^"]*"|'[^']*')$/.test(o.systemId))throw new ie(Er,"DocumentType systemId is not a valid SystemLiteral");if(o.internalSubset&&o.internalSubset.indexOf("]>")!==-1)throw new ie(Er,'DocumentType internalSubset contains "]>"')}var V=o.publicId,q=o.systemId;if(t.push("<!DOCTYPE ",o.name),V)t.push(" PUBLIC ",V),q&&q!="."&&t.push(" ",q),t.push(">");else if(q&&q!=".")t.push(" SYSTEM ",q,">");else{var ze=o.internalSubset;ze&&t.push(" [",ze,"]"),t.push(">")}return null;case Sp:if(a){if(!ya.test(o.target)||o.target.indexOf(":")!==-1||o.target.toLowerCase()==="xml")throw new ie(Er,'The processing instruction target "'+o.target+'" is not a valid XML NCName or is reserved');if(o.data.indexOf("?>")!==-1)throw new ie(Er,'The ProcessingInstruction data contains "?>"')}return t.push("<?",o.target," ",o.data,"?>"),null;case Qy:if(a&&!ya.test(o.nodeName))throw new ie(Er,'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 qk(e,t,r){var n;return Xe(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===ba||r;return s?o:null}}),n}function db(e,t,r){var n;return Xe(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 yn),o.ownerDocument=e;var u=r;switch(o.nodeType){case ar:var c=i.attributes,d=o.attributes=new Bl,p=c.length;d._ownerElement=o;for(var f=0;f<p;f++)o.setAttributeNode(db(e,c.item(f),!0));break;case ba:u=!0}return a!==null?a.appendChild(o):n=o,u?o:null}}),n}function pb(e,t,r){e[t]=r}try{Object.defineProperty&&(Object.defineProperty(wa.prototype,"length",{get:function(){return Dp(this),this.$$length}}),Object.defineProperty(pe.prototype,"textContent",{get:function(){if(this.nodeType===ar||this.nodeType===vn){var e=[];return Xe(this,null,{enter:function(t){if(t.nodeType===ar||t.nodeType===vn)return!0;if(t.nodeType===Sp||t.nodeType===Np)return null;e.push(t.nodeValue)}}),e.join("")}return this.nodeValue},set:function(e){switch(this.nodeType){case ar:case vn: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}}}),pb=function(e,t,r){e["$$"+t]=r})}catch{}wn.DocumentType=Gl;wn.DOMException=ie;wn.DOMImplementation=rb;wn.Element=Ii;wn.Node=pe;wn.NodeList=yn;wn.walkDOM=Xe;wn.XMLSerializer=ub});var mb=y(Zo=>{"use strict";var fb=va().freeze;Zo.XML_ENTITIES=fb({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'});Zo.HTML_ENTITIES=fb({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"});Zo.entityMap=Zo.HTML_ENTITIES});var bb=y(kp=>{var rs=va().NAMESPACE,Lp=va().tagNamePattern,Aa=0,Jn=1,Ea=2,es=3,Ca=4,Sa=5,ts=6,Wl=7;function Na(e,t){this.message=e,this.locator=t,Error.captureStackTrace&&Error.captureStackTrace(this,Na)}Na.prototype=new Error;Na.prototype.name=Na.name;function vb(){}vb.prototype={parse:function(e,t,r){var n=this.domBuilder;n.startDocument(),jk(t,t={}),Vk(e,t,r,n,this.errorHandler),n.endDocument()}};function Vk(e,t,r,n,i){function a(Z){if(Z>65535){Z-=65536;var ye=55296+(Z>>10),xe=56320+(Z&1023);return String.fromCharCode(ye,xe)}else return String.fromCharCode(Z)}function o(Z){var ye=Z.slice(1,-1);return Object.hasOwnProperty.call(r,ye)?r[ye]:ye.charAt(0)==="#"?a(parseInt(ye.substr(1).replace("x","0x"))):(i.error("entity not found:"+Z),Z)}function s(Z){if(Z>h){var ye=e.substring(h,Z).replace(/&#?\w+;/g,o);p&&l(h),n.characters(ye,0,Z-h),h=Z}}function l(Z,ye){for(;Z>=c&&(ye=d.exec(e));)u=ye.index,c=u+ye[0].length,p.lineNumber++;p.columnNumber=Z-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 b=n.doc,E=b.createTextNode(e.substr(h));b.appendChild(E),n.currentElement=E}return}switch(v>h&&s(v),e.charAt(v+1)){case"/":var q=e.indexOf(">",v+3),C=e.substring(v+2,q).replace(/^([\s\S]*?[^ \t\n\r])?[ \t\n\r]*$/,"$1"),N=f.pop();q<0?(C=e.substring(v+2).replace(/[\s<].*/,""),i.error("end tag name: "+C+" is not complete:"+N.tagName),q=v+1+C.length):C.match(/\s</)?(C=C.replace(/[\s<].*/,""),i.error("end tag name: "+C+" maybe not complete"),q=v+1+C.length):/[ \t\n\r]/.test(C)&&Lp.test(C.split(/[ \t\n\r]/)[0])&&i.error('end tag name is followed by whitespace and trailing content: "'+C+'"');var R=N.localNSMap,O=N.tagName==C,F=O||N.tagName&&N.tagName.toLowerCase()==C.toLowerCase();if(F){if(n.endElement(N.uri,N.localName,C),R)for(var k in R)Object.prototype.hasOwnProperty.call(R,k)&&n.endPrefixMapping(k);O||i.fatalError("end tag name: "+C+" is not match the current start tagName:"+N.tagName)}else f.push(N);q++;break;case"?":p&&l(v),q=Kk(e,v,n);break;case"!":p&&l(v),q=Hk(e,v,n,i);break;default:p&&l(v);var P=new yb,V=f[f.length-1].currentNSMap,q=Gk(e,v,P,V,o,i),ze=P.length;if(!P.closed&&Wk(e,q,P.tagName,m)&&(P.closed=!0,r.nbsp||i.warning("unclosed xml attribute")),p&&ze){for(var Tt=hb(p,{}),Be=0;Be<ze;Be++){var Qe=P[Be];l(Qe.offset),Qe.locator=hb(p,{})}n.locator=Tt,gb(P,n,V)&&f.push(P),n.locator=p}else gb(P,n,V)&&f.push(P);rs.isHTML(P.uri)&&!P.closed?q=zk(e,q,P.tagName,o,n):q++}}catch(Z){if(Z instanceof Na)throw Z;i.error("element parse error: "+Z),q=-1}q>h?h=q:s(Math.max(v,h)+1)}}function hb(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}function Gk(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=Aa;;){var d=e.charAt(u);if(c===Aa&&d==="<")throw new Error("unexpected < in tag name: "+e.slice(t,u));switch(d){case"=":if(c===Jn)s=e.slice(t,u),c=es;else if(c===Ea)c=es;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(c===es||c===Jn)if(c===Jn&&(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=Sa;else throw new Error("attribute value no end '"+d+"' match");else if(c==Ca)l=e.slice(t,u),o(s,l,t),a.warning('attribute "'+s+'" missed start quot('+d+")!!"),t=u+1,c=Sa;else throw new Error('attribute value must after "="');break;case"/":switch(c){case Aa:r.setTagName(e.slice(t,u));case Sa:case ts:case Wl:c=Wl,r.closed=!0;case Ca:case Jn:break;case Ea:r.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return a.error("unexpected end of input"),c==Aa&&r.setTagName(e.slice(t,u)),u;case">":switch(c){case Aa:r.setTagName(e.slice(t,u));case Sa:case ts:case Wl:break;case Ca:case Jn:l=e.slice(t,u),l.slice(-1)==="/"&&(r.closed=!0,l=l.slice(0,-1));case Ea:c===Ea&&(l=s),c==Ca?(a.warning('attribute "'+l+'" missed quot(")!'),o(s,l,t)):((!rs.isHTML(n[""])||!l.match(/^(?:disabled|checked|selected)$/i))&&a.warning('attribute "'+l+'" missed value!! "'+l+'" instead!!'),o(l,l,t));break;case es:throw new Error("attribute value missed!!")}return u;case"\x80":d=" ";default:if(d<=" ")switch(c){case Aa:r.setTagName(e.slice(t,u)),c=ts;break;case Jn:s=e.slice(t,u),c=Ea;break;case Ca:var l=e.slice(t,u);a.warning('attribute "'+l+'" missed quot(")!!'),o(s,l,t);case Sa:c=ts;break}else switch(c){case Ea:var p=r.tagName;(!rs.isHTML(n[""])||!s.match(/^(?:disabled|checked|selected)$/i))&&a.warning('attribute "'+s+'" missed value!! "'+s+'" instead2!!'),o(s,s,t),t=u,c=Jn;break;case Sa:a.warning('attribute space is required"'+s+'"!!');case ts:c=Jn,t=u;break;case es:c=Ca,t=u;break;case Wl:throw new Error("elements closed character '/' and '>' must be connected to")}}u++}}function gb(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=rs.XMLNS,t.startPrefixMapping(c,s))}for(var d=e.length;d--;){a=e[d];var l=a.prefix;l&&(l==="xml"&&(a.uri=rs.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 zk(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 Wk(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 jk(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function Hk(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=Jk(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 Kk(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 yb(){this.attributeNames={}}yb.prototype={setTagName:function(e){if(!Lp.test(e))throw new Error("invalid tagName:"+e);this.tagName=e},addValue:function(e,t,r){if(!Lp.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 Jk(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}kp.XMLReader=vb;kp.ParseError=Na});var Db=y(Hl=>{var Qk=va(),Xk=Fp(),wb=mb(),Cb=bb(),Yk=Xk.DOMImplementation,Ab=Qk.NAMESPACE,Zk=Cb.ParseError,eM=Cb.XMLReader;function Sb(e){return e.replace(/\r[\n\u0085]/g,`
`).replace(/[\r\u0085\u2028]/g,`
-`)}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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/\r/g,"&#xD;").replace(/\n/g,"&#xA;").replace(/\t/g,"&#x9;")}function YF(e){return Fy(e),String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}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(`
+`)}function Nb(e){this.options=e||{locator:{}}}Nb.prototype.parseFromString=function(e,t){var r=this.options,n=new eM,i=r.domBuilder||new ns,a=r.errorHandler,o=r.locator,s=r.xmlns||{},l=/\/x?html?$/.test(t),u=l?wb.HTML_ENTITIES:wb.XML_ENTITIES;o&&i.setDocumentLocator(o),n.errorHandler=tM(a,i,o),n.domBuilder=r.domBuilder||i,l&&(s[""]=Ab.HTML),s.xml=s.xml||Ab.XML;var c=r.normalizeLineEndings||Sb;return e&&typeof e=="string"?n.parse(c(e),s,u):n.errorHandler.error("invalid doc source"),i.doc};function tM(e,t,r){if(!e){if(t instanceof ns)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+Mp(r))}||function(){}}return a("warning"),a("error"),a("fatalError"),n}function ns(){this.cdata=!1}function Da(e,t){t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber}ns.prototype={startDocument:function(){this.doc=new Yk().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;jl(this,a),this.currentElement=a,this.locator&&Da(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&&Da(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&&Da(this.locator,r),jl(this,r)},ignorableWhitespace:function(e,t,r){},characters:function(e,t,r){if(e=Eb.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&&Da(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=Eb.apply(this,arguments);var n=this.doc.createComment(e);this.locator&&Da(this.locator,n),jl(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&&Da(this.locator,i),jl(this,i),this.doc.doctype=i}},warning:function(e){console.warn("[xmldom warning] "+e,Mp(this.locator))},error:function(e){console.error("[xmldom error] "+e,Mp(this.locator))},fatalError:function(e){throw new Zk(e,this.locator)}};function Mp(e){if(e)return`
+@`+(e.systemId||"")+"#[line:"+e.lineNumber+",col:"+e.columnNumber+"]"}function Eb(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){ns.prototype[e]=function(){return null}});function jl(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}Hl.__DOMHandler=ns;Hl.normalizeLineEndings=Sb;Hl.DOMParser=Nb});var Jl=y(Kl=>{var Ib=Fp();Kl.DOMImplementation=Ib.DOMImplementation;Kl.XMLSerializer=Ib.XMLSerializer;Kl.DOMParser=Db().DOMParser});var Qn=y(Ql=>{"use strict";Object.defineProperty(Ql,"__esModule",{value:!0});Ql.installDomShim=void 0;var _b=Jl(),Tb=!1,rM={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 nM(){if(Tb)return;let e=globalThis;typeof e.DOMParser>"u"&&(e.DOMParser=_b.DOMParser),typeof e.XMLSerializer>"u"&&(e.XMLSerializer=_b.XMLSerializer),typeof e.Node>"u"&&(e.Node=rM),Tb=!0}Ql.installDomShim=nM});var _i=y(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.projectElementBag=Le.serializeNode=Le.domEngine=Le.nodeLikeFromDom=Le.parseXmlRoot=Le.EMPTY_FORM_SENTINEL=Le.TEXT_SENTINEL=void 0;var iM=Kn(),is=te(),aM=Qn();Le.TEXT_SENTINEL="#text";Le.EMPTY_FORM_SENTINEL="#empty";var Yl=new WeakSet;function oM(e,t){(0,aM.installDomShim)();let r=e&&e.trim()!==""?e:t,i=new DOMParser().parseFromString(r,"text/xml").documentElement;if(!i)throw new is.InvalidArgumentError("XML source has no root element (empty or malformed input)");return lM(i),uM(i),pM(i,r),i}Le.parseXmlRoot=oM;var sM=new Set([1,3]);function lM(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(!sM.has(a.nodeType))throw new is.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 uM(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 is.InvalidArgumentError(`Unsupported document-level XML node (type ${o.nodeType}: declaration / comment / processing-instruction outside the root element) cannot be round-tripped`)}}function cM(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 dM(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 Rb(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 pM(e,t){let r=cM(t),n=dM(e),i=Math.min(r.length,n.length);for(let a=0;a<i;a+=1){if(r[a])continue;let o=n[a];Rb(o)||Yl.add(o)}}function Bp(e){let t=e.nodeType===3;return{getNodeName:()=>t?Le.TEXT_SENTINEL:e.tagName,getAllProperties:()=>{var r;if(t)return[{key:Le.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 Yl.has(e)&&!Rb(e)&&i.push({key:Le.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(Bp(a))}return r}}}Le.nodeLikeFromDom=Bp;function fM(e){return{make:t=>t===Le.TEXT_SENTINEL?e.createTextNode(""):e.createElement(t),setProp:(t,r,n)=>{t.nodeType===3?t.nodeValue=n:r===Le.EMPTY_FORM_SENTINEL?Yl.add(t):t.setAttribute(r,n)},addChild:(t,r)=>{t.appendChild(r)}}}Le.domEngine=fM;function Ob(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 Xl(r);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))throw Xl(r);t+=1;continue}if(r>=56320&&r<=57343)throw Xl(r)}}function Xl(e){let t=e.toString(16).toUpperCase().padStart(4,"0");return new is.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 mM(e){return Ob(e),String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/\r/g,"&#xD;").replace(/\n/g,"&#xA;").replace(/\t/g,"&#x9;")}function hM(e){return Ob(e),String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function gM(e){return xb(e,0)}Le.serializeNode=gM;var Pb=512;function xb(e,t){var r;if(t>Pb)throw new is.InvalidArgumentError(`XML nesting exceeds the maximum supported depth of ${Pb}`);if(e.nodeType===3)return hM((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+'="'+mM(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 Yl.has(n)?i+"></"+n.tagName+">":i+" />";i+=">";for(let l of o)i+=xb(l,t+1);return i+"</"+n.tagName+">"}function vM(e){let t=Bp(e);return{a:t.getAllProperties().map(r=>[r.key,r.value]),c:t.getAllChildren().map((r,n)=>({i:n,node:(0,iM.rawFromNode)(r)}))}}Le.projectElementBag=vM});var Cr=y(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.rejectUnknownKeys=ft.childObjects=ft.optionalGuidId=ft.optionalEnum=ft.eachObject=ft.issue=ft.isJsonObject=void 0;function Fb(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}ft.isJsonObject=Fb;function Ia(e,t,r,n){return n?{pointer:e,rule:t,message:r,fatal:n}:{pointer:e,rule:t,message:r}}ft.issue=Ia;function Lb(e,t,r,n){if(!Array.isArray(e))return[];let i=[];return e.forEach((a,o)=>{Fb(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}ft.eachObject=Lb;function yM(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)}`))}ft.optionalEnum=yM;var bM=/^(?:\{[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 wM(e,t,r,n,i){let a=e[t];typeof a=="string"&&a!==""&&!bM.test(a)&&i.push(Ia(`${r}/${t}`,n,`${t} must be a GUID or empty, got '${a}'`))}ft.optionalGuidId=wM;function AM(e,t,r,n,i){let a=e[t],o=`${r}/${t}`;return a===void 0?[]:Array.isArray(a)?Lb(a,o,n,i):(i.push(Ia(o,`${n}-list-must-be-array`,`${t} must be an array when present, got ${typeof a}`)),[])}ft.childObjects=AM;function EM(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}`))}}ft.rejectUnknownKeys=EM});var Xp=y(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.genPageEmbedIssues=B.mintEmbedIdentity=B.hasGenPage=B.applyEmbedCellDefaults=B.applyEmbedControlDefaults=B.mayCommitEmbedState=B.commitEmbedState=B.reconcileEmbedDescriptions=B.embedAppendIndex=B.activeEmbedBindings=B.projectGenPageEmbeds=B.isRecognizedEmbed=B.isUnbound=B.effectiveClassId=B.effectiveFormType=B.inputDataFrom=B.classifyBinding=B.isStaticParameter=B.entryParameter=B.pageEntries=B.descriptionFor=B.descriptionsRegion=B.controlUniqueIds=B.controlUniqueId=B.typedCells=B.rawText=B.rawAttr=B.normGuid=B.GENPAGE_FORM_FACTORS=B.GENPAGE_EMBED_ROWSPAN=B.GENPAGE_CONTROL_NAME=B.CUSTOM_CONTROL_CLASS_ID=void 0;var CM=Jl(),SM=ca(),Up=lt(),or=Cr();B.CUSTOM_CONTROL_CLASS_ID="F9A8A302-114E-466A-B582-6771B2AE0D92";B.GENPAGE_CONTROL_NAME="MscrmControls.UxAgentControl";B.GENPAGE_EMBED_ROWSPAN=6;B.GENPAGE_FORM_FACTORS=["2","0","1"];var NM=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function kt(e){if(typeof e!="string")return"";let t=e.trim().toLowerCase();return t.startsWith("{")&&t.endsWith("}")&&(t=t.slice(1,-1)),NM.test(t)?t:""}B.normGuid=kt;function Xn(e,t){let r=le(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}B.rawAttr=Xn;function os(e){return le(e?.c).filter(t=>typeof t?.n=="string"&&t.n.startsWith("<")).map(t=>t.n.slice(1)).join("")}B.rawText=os;function le(e){return Array.isArray(e)?e:[]}function Wp(e,t){let r=le(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}function Bb(e){return typeof e=="string"?e.trim().replace(/^\{|\}$/g,"").toUpperCase():""}function Ub(e){return jr(e).map(t=>t.cell)}B.typedCells=Ub;function jr(e){let t=[];return le(e?.tabs).forEach((r,n)=>{le(ge(r)?r.columns:void 0).forEach((i,a)=>{le(ge(i)?i.sections:void 0).forEach((o,s)=>{le(ge(o)?o.rows:void 0).forEach((l,u)=>{le(ge(l)?l.cells:void 0).forEach((c,d)=>{ge(c)&&t.push({cell:c,pointer:`/tabs/${n}/columns/${a}/sections/${s}/rows/${u}/cells/${d}`})})})})})}),t}function An(e){return ge(e)?kt(Wp(e.bag,"uniqueid")):""}B.controlUniqueId=An;function DM(e){let t=new Set;for(let{cell:r}of jr(e)){let n=Ri(r.control)?An(r.control):"";n&&t.add(n)}return t}function IM(e){let t=new Map;for(let{cell:r}of jr(e)){let n=ge(r.control)?An(r.control):"";n&&!t.has(n)&&t.set(n,r.control)}return t}function _M(e){return e!==void 0&&e.genPage===void 0&&(Kp(e)!==B.CUSTOM_CONTROL_CLASS_ID||!ru(e))}function $p(e,t){if(ge(e)){t(e);for(let r of le(e.c))$p(r,t)}}function Ti(e,t){var r;if(ge(e)){for(let n of le(e.c))$p(n?.node,t);for(let n of le((r=e.w)===null||r===void 0?void 0:r.c))$p(n?.node,t)}}function eu(e){let t=new Map,r=i=>{var a;i&&t.set(i,((a=t.get(i))!==null&&a!==void 0?a:0)+1)},n=i=>{i.n==="control"&&r(kt(Xn(i,"uniqueid")))};return Ti(e?.bag,n),le(e?.tabs).forEach(i=>{ge(i)&&(Ti(i.bag,n),le(i.columns).forEach(a=>{ge(a)&&(Ti(a.bag,n),le(a.sections).forEach(o=>{ge(o)&&(Ti(o.bag,n),le(o.rows).forEach(s=>{ge(s)&&(Ti(s.bag,n),le(s.cells).forEach(l=>{ge(l)&&(Ti(l.bag,n),ge(l.control)&&(r(An(l.control)),Ti(l.control.bag,n)))}))}))}))}))}),t}B.controlUniqueIds=eu;function _a(e){return le(e?.c).find(t=>{var r;return((r=t?.node)===null||r===void 0?void 0:r.n)==="controlDescriptions"})}B.descriptionsRegion=_a;function Pi(e,t){var r;let n=kt(t);if(n)return le((r=_a(e))===null||r===void 0?void 0:r.node.c).find(i=>i?.n==="controlDescription"&&kt(Xn(i,"forControl"))===n)}B.descriptionFor=Pi;function ss(e){return le(e.c).filter($b)}B.pageEntries=ss;function $b(e){return e?.n==="customControl"&&Xn(e,"name")===B.GENPAGE_CONTROL_NAME}function qp(e,t){let r=le(e.c).find(n=>n?.n==="parameters");return le(r?.c).find(n=>n?.n===t)}B.entryParameter=qp;function Vp(e){return Xn(e,"static")==="true"}B.isStaticParameter=Vp;function ls(e){let t=ss(e);if(t.length===0)return{kind:"none"};let r,n;for(let i=0;i<t.length;i+=1){let a=qp(t[i],"RefId");if(!a||!Vp(a))return{kind:"unsupported"};let o=kt(os(a));if(!o)return{kind:"unsupported"};let s=qp(t[i],"PageInput");if(s&&!Vp(s))return{kind:"unsupported"};let l=s?os(s):void 0;if(i===0)r=o,n=l;else if(o!==r||l!==n)return{kind:"unsupported"}}return n===void 0?{kind:"projectable",pageId:r}:{kind:"projectable",pageId:r,pageInputRaw:n}}B.classifyBinding=ls;function ge(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function jp(e){if(e===void 0)return;let t;try{t=JSON.parse(e)}catch{return}return ge(t)&&ge(t.data)?t.data:void 0}B.inputDataFrom=jp;function Hp(e){var t;return(t=e.formType)!==null&&t!==void 0?t:"Main"}B.effectiveFormType=Hp;function Kp(e){return Bb(e.classId!==void 0?e.classId:Wp(e.bag,"classid"))}B.effectiveClassId=Kp;function ru(e){return!e.fieldName}B.isUnbound=ru;function Jp(e,t){if(Hp(e)!=="Main"||!ru(t)||Kp(t)!==B.CUSTOM_CONTROL_CLASS_ID)return!1;let r=An(t),n=r?Pi(e.bag,r):void 0;return n!==void 0&&ls(n).kind==="projectable"}B.isRecognizedEmbed=Jp;function TM(e){for(let t of Ub(e)){let r=t.control;if(!r||!Jp(e,r))continue;let n=ls(Pi(e.bag,An(r)));if(n.kind!=="projectable")continue;let i=jp(n.pageInputRaw);r.genPage=i===void 0?{pageId:n.pageId}:{pageId:n.pageId,inputData:i}}}B.projectGenPageEmbeds=TM;var PM=new Set(["pageId","inputData"]);function as(e){let t=[];for(let r=0;r<e.childNodes.length;r+=1){let n=e.childNodes[r];n.nodeType===1&&t.push(n)}return t}function RM(e){let t=[],r=u=>c=>t.push(`${u}: ${c}`),i=new CM.DOMParser({errorHandler:{warning:r("warning"),error:r("error"),fatalError:r("fatalError")}}).parseFromString(e,"text/xml").documentElement;if(!i||t.length>0)throw new Error(`the formxml does not parse cleanly${t.length>0?` (${t[0]})`:""}`);let a=new Set,o=i.getElementsByTagName("control");for(let u=0;u<o.length;u+=1){let c=kt(o[u].getAttribute("uniqueid"));c&&a.add(c)}let s=as(i).find(u=>u.nodeName==="controlDescriptions"),l=new Map;for(let u of s?as(s):[]){let c=kt(u.getAttribute("forControl"));if(!(u.nodeName!=="controlDescription"||!c||!a.has(c)))for(let d of as(u)){if(d.nodeName!=="customControl"||d.getAttribute("name")!==B.GENPAGE_CONTROL_NAME)continue;let p=as(d).find(h=>h.nodeName==="parameters"),f=p?as(p).find(h=>h.nodeName==="RefId"):void 0,m=f&&f.getAttribute("static")==="true"?kt(f.textContent):"";m&&l.set(`${c}|${m}`,[c,m])}}return[...l.values()]}B.activeEmbedBindings=RM;function Zl(e){return{n:`<${e}`,a:[],c:[]}}function Gp(e,t){return{n:e,a:[["type","SingleLine.Text"],["static","true"]],c:[Zl(t)]}}function zp(e,t){let r={};if(t!==void 0)try{let n=JSON.parse(t);ge(n)&&(r=n)}catch{}return JSON.stringify({...r,data:e})}function OM(e,t,r){return{n:"controlDescription",a:[["forControl",e]],c:B.GENPAGE_FORM_FACTORS.map(n=>({n:"customControl",a:[["name",B.GENPAGE_CONTROL_NAME],["formFactor",n]],c:[{n:"parameters",a:[],c:[Gp("RefId",t),...r===void 0?[]:[Gp("PageInput",zp(r))]]}]}))}}function tu(e,t){if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,n)=>tu(r,t[n]));if(ge(e)&&ge(t)){let r=Object.keys(e);return r.length===Object.keys(t).length&&r.every(n=>n in t&&tu(e[n],t[n]))}return e===t}function xM(e,t,r){let n=le(e.c).find(u=>u?.n==="parameters");if(!n||!Array.isArray(n.c))return;let i=n.c.find(u=>u?.n==="RefId");i&&kt(os(i))!==t&&(i.c=[Zl(t)]);let a=n.c.findIndex(u=>u?.n==="PageInput"),o=a>=0?n.c[a]:void 0,s=o?os(o):void 0;if(tu(jp(s),r))return;if(r!==void 0){o?o.c=[Zl(zp(r,s))]:n.c.push(Gp("PageInput",zp(r)));return}let l=JSON.parse(s);delete l.data,Object.keys(l).length===0?n.c.splice(a,1):o.c=[Zl(JSON.stringify(l))]}function Qp(e){let t=le(e?.c),r=t.reduce((n,i)=>i.i>n?i.i:n,-1);return Math.max(r,t.length)+1}B.embedAppendIndex=Qp;function FM(e,t){var r;let n=e.bag,i=_a(n);if(i&&t){let a=eu(t),o=eu(e),s=DM(t),l=IM(e),u=le(i.node.c),c=[];for(let d of u){let p=d?.n==="controlDescription"&&ss(d).length>0?kt(Xn(d,"forControl")):"";if(!p||!a.has(p))c.push(d);else if(o.has(p))if(s.has(p)&&_M(l.get(p))&&tu(d,Pi(t.bag,p))){let f=le(d.c).filter(m=>!$b(m));f.length>0&&c.push({...d,c:f})}else c.push(d)}(c.length!==u.length||c.some((d,p)=>d!==u[p]))&&(i.node.c=c)}for(let{cell:a}of jr(e)){let o=a.control;if(!Ri(o)||!ge(o.genPage))continue;let s=kt(o.genPage.pageId),l=o.genPage.inputData,u=An(o);if(!u){if(nu(o)!==void 0)continue;u=Gb(o)}let c=Pi(n,u);if(c){for(let f of ss(c))xM(f,s,l);continue}i||(i={i:Qp(n),node:{n:"controlDescriptions",a:[],c:[]}},n.c.push(i));let d=((r=Wp(o.bag,"uniqueid"))!==null&&r!==void 0?r:"").trim(),p=d.startsWith("{")?d:`{${u}}`;i.node.c.push(OM(p,s,l))}}B.reconcileEmbedDescriptions=FM;function LM(e,t){let r=_a(e.bag),n=t!==void 0&&(r===void 0||JSON.stringify(r.node)!==JSON.stringify(t)),i=jr(e).some(({cell:o})=>Ri(o.control)&&(o.rowspan===void 0||o.control.classId===void 0||o.control.showLabel===void 0||o.control.label===void 0||o.control.fieldName===void 0));if(!n&&!i)return e;let a=JSON.parse(JSON.stringify(e));if(n){let o=JSON.parse(JSON.stringify(t)),s=_a(a.bag);s?s.node=o:(a.bag=ge(a.bag)?a.bag:{a:[],c:[]},a.bag.c=le(a.bag.c),a.bag.c.push({i:Qp(e.bag),node:o}))}for(let{cell:o}of jr(a))Ri(o.control)&&(qb(o.control),Vb(o));return a}B.commitEmbedState=LM;function kM(e){if(jr(e).some(({cell:r})=>Ri(r.control)))return!0;let t=_a(e.bag);return le(t?.node.c).some(r=>r?.n==="controlDescription"&&ss(r).length>0)}B.mayCommitEmbedState=kM;function qb(e){e.classId===void 0&&(e.classId=B.CUSTOM_CONTROL_CLASS_ID),e.showLabel===void 0&&(e.showLabel=!1),e.label===void 0&&(e.label=""),e.fieldName===void 0&&(e.fieldName=null)}B.applyEmbedControlDefaults=qb;function Vb(e){e.rowspan===void 0&&(e.rowspan=B.GENPAGE_EMBED_ROWSPAN)}B.applyEmbedCellDefaults=Vb;function Ri(e){return ge(e)&&e.genPage!==void 0}B.hasGenPage=Ri;function kb(e){return Ri(e.control)&&(!e.control.id||!e.id||nu(e.control)===void 0)}function nu(e){let t=le(ge(e.bag)?e.bag.a:void 0).find(n=>Array.isArray(n)&&n[0]==="uniqueid");if(!t)return;let r=t[1];return typeof r=="string"&&r.trim()===""?void 0:r}function MM(e){if(!jr(e).some(({cell:r})=>kb(r)))return e;let t=JSON.parse(JSON.stringify(e));for(let{cell:r}of jr(t)){if(!kb(r))continue;let n=r.control;n.id||(n.id=(0,Up.newId)()),r.id||(r.id=(0,Up.newId)()),nu(n)===void 0&&Gb(n)}return t}B.mintEmbedIdentity=MM;function Gb(e){let t=(0,Up.newId)(),r=`{${t}}`;if(!ge(e.bag))return e.bag={a:[["uniqueid",r]],c:[]},t;let n=le(e.bag.a),i=n.find(a=>Array.isArray(a)&&a[0]==="uniqueid");return i?i[1]=r:n.push(["uniqueid",r]),e.bag.a=n,e.bag.c=le(e.bag.c),t}function Mb(e){return e===null?"null":Array.isArray(e)?"an array":typeof e}function BM(e){let t=le(e.c).filter(r=>r?.n==="customControl").map(r=>{var n,i;return(i=(n=Xn(r,"name"))!==null&&n!==void 0?n:Xn(r,"id"))!==null&&i!==void 0?i:"(unnamed)"});return[...new Set(t)].join(", ")||"(no custom control)"}function UM(e){let t=[],r;for(let{cell:n,pointer:i}of jr(e)){let a=n.control;if(!ge(a))continue;let o=`${i}/control`;if(a.genPage===void 0){$M(e,a,o,t);continue}r=r??eu(e),qM(e,a,o,r,t)}return t}B.genPageEmbedIssues=UM;function $M(e,t,r,n){if(!Jp(e,t))return;let i=ls(Pi(e.bag,An(t)));n.push((0,or.issue)(r,"genpage-embed-removed",`this control still embeds generative page ${i.pageId}: removing genPage alone would leave that binding on the form. To remove the embed, remove the cell (or set the cell's control to null); to change the page, edit genPage/pageId. A copy fetched by an older SDK (projection 3) shows no genPage at all \u2014 re-fetch the form.`))}function qM(e,t,r,n,i){var a;let o=`${r}/genPage`,s=t.genPage;if(!ge(s))i.push((0,or.issue)(o,"genpage-embed-shape",`genPage must be an object { pageId, inputData? }, got ${Mb(s)}.`+(s===null?" To remove an embed, remove the cell (or set the cell's control to null).":"")));else{(typeof s.pageId!="string"||!kt(s.pageId))&&i.push((0,or.issue)(`${o}/pageId`,"genpage-embed-shape",`genPage.pageId must be the id (a GUID) of a generative page, got ${s.pageId===void 0?"nothing":JSON.stringify(s.pageId)}`)),s.inputData!==void 0&&!ge(s.inputData)&&i.push((0,or.issue)(`${o}/inputData`,"genpage-embed-shape",`genPage.inputData must be a JSON object \u2014 the page reads it as pageInput.data \u2014 got ${Mb(s.inputData)}`));for(let f of Object.keys(s))PM.has(f)||i.push((0,or.issue)(SM.JsonPointer.append(o,f),"genpage-embed-unknown-key",`'${f}' is not a genPage property (pageId, inputData), and would be SILENTLY DROPPED at serialization.`))}ru(t)||i.push((0,or.issue)(`${r}/fieldName`,"genpage-embed-bound",`a generative-page embed is an unbound control, but this one is bound to column '${t.fieldName}'. Set fieldName to null, or embed the page in a new cell.`)),t.classId!==void 0&&Bb(t.classId)!==B.CUSTOM_CONTROL_CLASS_ID&&i.push((0,or.issue)(`${r}/classId`,"genpage-embed-class-id",`a generative-page embed is the custom control {${B.CUSTOM_CONTROL_CLASS_ID}}, but classId is ${JSON.stringify(t.classId)}. Omit classId (the SDK defaults it) or set it to that class.`));let l=Hp(e);l!=="Main"&&i.push((0,or.issue)(o,"genpage-embed-main-form-only",`a generative page can be embedded only in a Main form, as in the maker portal; this is a ${l} form.`));let u=nu(t);u!==void 0&&!kt(u)&&i.push((0,or.issue)(`${r}/bag`,"genpage-embed-unique-id",`this embed's uniqueid ${JSON.stringify(u)} is not a GUID, and its page binding is keyed by it. Remove it from the bag (the SDK mints one) or set a GUID.`));let c=An(t);if(!c)return;let d=Pi(e.bag,c),p=d?ls(d):void 0;d&&p?.kind==="none"?i.push((0,or.issue)(o,"genpage-embed-other-control",`this control is already bound to another custom control (${BM(d)}). genPage would have to delete that binding to take its place, so embed the page in a new cell instead.`)):p?.kind==="unsupported"&&i.push((0,or.issue)(o,"genpage-embed-unsupported-binding","this control already embeds a page through a binding genPage cannot represent exactly \u2014 a RefId or PageInput bound to a column, a RefId that is not a page id, or form factors that disagree. Taking it over would silently turn it into a static binding, so embed the page in a new cell instead.")),((a=n.get(c))!==null&&a!==void 0?a:0)>1&&i.push((0,or.issue)(`${r}/bag`,"genpage-embed-duplicate-unique-id",`this embed's uniqueid {${c}} is also carried by another control on the form, so both would share one binding. Author the copy without its bag and the SDK mints a new identity for it.`))}});var Zp=y(Yn=>{"use strict";Object.defineProperty(Yn,"__esModule",{value:!0});Yn.findMissingGenPages=Yn.GENPAGE_LOOKUP_CHUNK=void 0;var VM=Pt(),Yp=ae();Yn.GENPAGE_LOOKUP_CHUNK=50;async function GM(e,t,r){let n=[...new Set(t.map(a=>(0,Yp.normalizeGuid)(a,"uxagentprojectid")))],i=new Set;for(let a=0;a<n.length;a+=Yn.GENPAGE_LOOKUP_CHUNK){let o=n.slice(a,a+Yn.GENPAGE_LOOKUP_CHUNK),s="/uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Yp.odataQuery)([["$select","uxagentprojectid"],["$filter",o.map(u=>`uxagentprojectid eq ${u}`).join(" or ")]]),l=await(0,VM.collectPages)(e,s,r);for(let u of l){let c=u.uxagentprojectid;typeof c=="string"&&c.trim()!==""&&i.add((0,Yp.normalizeGuid)(c,"uxagentprojectid"))}}return n.filter(a=>!i.has(a))}Yn.findMissingGenPages=GM});var tf=y(sr=>{"use strict";Object.defineProperty(sr,"__esModule",{value:!0});sr.patchSystemForm=sr.assertSystemFormContentUnchanged=sr.readSystemFormContentEtag=sr.readSystemFormRowEtag=sr.unpublishedSystemFormPath=void 0;var Mt=be(),zM=ae(),ef=te();function iu(e,t="formid"){return`/systemforms(${e})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,zM.odataQuery)([["$select",t]])}sr.unpublishedSystemFormPath=iu;function zb(e,t){return(0,Mt.readRowEtag)(e,"systemforms","formid",t)}sr.readSystemFormRowEtag=zb;async function WM(e,t){let r=iu(t);return(0,Mt.readEtag)((0,Mt.ensureSuccess)(await e.get(r),e.apiUrl(r)))}sr.readSystemFormContentEtag=WM;async function Wb(e,t,r,n,i){(0,Mt.requireEtag)(i,r,t);let a=(0,Mt.readEtag)((0,Mt.ensureSuccess)(await e.get(n),e.apiUrl(n)));if(a===null)throw new ef.SdkError(Mt.VERSION_CONFLICT_CODE,`Refusing to write ${r} '${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(a!==i)throw new ef.SdkError(Mt.VERSION_CONFLICT_CODE,`Version conflict writing ${r} '${t}': its formxml changed on the server since it was read (held ${i}, server ${a}). Re-fetch the ${r} and re-apply the change.`)}sr.assertSystemFormContentUnchanged=Wb;async function jM(e,t,r,n,i,a){(0,Mt.requireEtag)(i,r,t);let o=await zb(e,t);if(o===null)throw new ef.SdkError(Mt.VERSION_CONFLICT_CODE,`Refusing to write ${r} '${t}': its row version could not be read, so the write could not be made conditional and would risk silently overwriting a concurrent edit.`);await Wb(e,t,r,iu(t),i);let s=(0,Mt.echoWrite)("formid",{"If-Match":o}),l=`/systemforms(${t})${s.query}`;return(0,Mt.ensureSuccess)(await e.patch(l,n,s.options),e.apiUrl(l)),HM(e,t,r,a)}sr.patchSystemForm=jM;async function HM(e,t,r,n){let i;try{let a=iu(t,n.select),o=(0,Mt.ensureSuccess)(await e.get(a),e.apiUrl(a)),s=o.body,l=(0,Mt.readEtag)(o),u=typeof s?.formid=="string"&&s.formid.replace(/[{}]/g,"").toLowerCase()===t,c=typeof s?.formxml=="string"&&s.formxml.trim()!=="",d=n.required.filter(p=>s?.[p]===void 0||s?.[p]===null);if(l&&u&&c&&d.length===0)return{id:t,etag:l,readBack:s};i=l?!u||!c?`the read did not return this ${r}'s document`:`the read did not return its ${d.join(", ")}`:"the read returned no version"}catch(a){i=a instanceof Error?a.message:String(a)}return{id:t,etag:null,warnings:[`The ${r} was saved, but its new version could not be read (${i}). The SDK holds no version for it now, so the next push is refused: re-fetch the ${r} before editing it again.`]}}});var of=y(Bt=>{"use strict";Object.defineProperty(Bt,"__esModule",{value:!0});Bt.getFormSecurityRoles=Bt.setFormSecurityRoles=Bt.formApi=Bt.FORM_GENPAGE_TARGET_UNVERIFIABLE=Bt.FORM_GENPAGE_TARGET_NOT_FOUND=void 0;var KM=Pt(),ut=be(),lr=ae(),Oi=te(),rf=_i(),Hb=Xp(),JM=Zp(),au=tf();Bt.FORM_GENPAGE_TARGET_NOT_FOUND="FORM_GENPAGE_TARGET_NOT_FOUND";Bt.FORM_GENPAGE_TARGET_UNVERIFIABLE="FORM_GENPAGE_TARGET_UNVERIFIABLE";var Kb="formid,formxml,name,type,objecttypecode,formpresentation,formactivationstate,uniquename,description,versionnumber",QM={select:Kb,required:["name","type","objecttypecode"]},XM="formid,name,type,objecttypecode",YM=2,ZM={Main:YM,QuickView:6,QuickCreate:7,Card:11};Bt.formApi={async get(e,t){let n=`/systemforms(${(0,lr.normalizeGuid)(t,"id")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,lr.odataQuery)([["$select",Kb]]),i=(0,ut.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,ut.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=>ZM[u]))],o=[i.length===1?`type eq ${i[0]}`:`(${i.map(u=>`type eq ${u}`).join(" or ")})`];t?.entityLogicalName&&o.push(`objecttypecode eq '${(0,lr.odataLiteral)(t.entityLogicalName)}'`);let s=`/systemforms${(0,lr.odataQuery)([["$select",XM],["$filter",o.join(" and ")]])}`;return(await(0,KM.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=jb(t);n!==void 0&&await Jb(e,af(n,"payload"),[]);let i=(0,ut.echoWrite)("formid"),a=`/systemforms${i.query}`,o=(0,ut.ensureSuccess)(await e.post(a,(0,ut.withClientMintedId)(t,"formid",r),i.options),e.apiUrl(a));return{id:(0,ut.resolveCreatedId)(o,"formid","form",r),etag:(0,ut.readEtag)(o)}},async update(e,t,r,n){let i=(0,lr.normalizeGuid)(t,"id"),a=jb(r);return a!==void 0&&await tB(e,i,a,n),(0,au.patchSystemForm)(e,i,"form",r,n,QM)},readToken(e,t){return(0,au.readSystemFormContentEtag)(e,(0,lr.normalizeGuid)(t,"id"))},delete(e,t){return(0,ut.deleteRecord)(e,"systemforms",t)}};var nf="DisplayConditions";async function eB(e,t,r){var n,i,a,o;if(r.everyone&&r.roleIds&&r.roleIds.length>0)throw new Oi.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,lr.normalizeGuid)(t,"formId"),l=`/systemforms(${s})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,lr.odataQuery)([["$select","formid,formxml"]]),u=(0,ut.ensureSuccess)(await e.get(l),e.apiUrl(l)),c=(0,ut.readEtag)(u),d=u.body,p=d?.formxml;if(!p)throw new Oi.InvalidArgumentError(`form '${s}' returned no formxml, so its roles cannot be set`);let f=(0,rf.parseXmlRoot)(p,"<form/>"),m=f.ownerDocument;if(!m)throw new Oi.InvalidArgumentError(`form '${s}' produced no owner document`);let h=Qb(f,nf),v=h?.hasAttribute("Order")&&(n=h.getAttribute("Order"))!==null&&n!==void 0?n:void 0,b=h?.getAttribute("FallbackForm")||void 0;h&&f.removeChild(h);let E=!!r.everyone||((a=(i=r.roleIds)===null||i===void 0?void 0:i.length)!==null&&a!==void 0?a:0)>0;if(!E&&(r.order!==void 0||r.fallbackForm!==void 0)){if(!h)throw new Oi.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(E){let F=m.createElement(nf),k=r.order!==void 0?String(r.order):v;k!==void 0&&F.setAttribute("Order",k);let P=r.fallbackForm!==void 0?String(r.fallbackForm):b??"false";if(F.setAttribute("FallbackForm",P),r.everyone)F.appendChild(m.createElement("Everyone"));else for(let V of(o=r.roleIds)!==null&&o!==void 0?o:[]){let q=m.createElement("Role");q.setAttribute("Id",`{${(0,lr.normalizeGuid)(V,"roleId")}}`),F.appendChild(q)}f.appendChild(F)}let N=(0,rf.serializeNode)(f);await(0,au.assertSystemFormContentUnchanged)(e,s,"form",l,c);let R=await(0,au.readSystemFormRowEtag)(e,s),O=`/systemforms(${s})`;(0,ut.ensureSuccess)(await e.patch(O,{formxml:N},{headers:{"Content-Type":"application/json","If-Match":(0,ut.requireEtag)(R,"form",s)}}),e.apiUrl(O))}Bt.setFormSecurityRoles=eB;function jb(e){let t=e?.formxml;return typeof t=="string"&&t.includes(Hb.GENPAGE_CONTROL_NAME)?t:void 0}function af(e,t){try{return(0,Hb.activeEmbedBindings)(e)}catch(r){throw new Oi.SdkError(Bt.FORM_GENPAGE_TARGET_UNVERIFIABLE,`Refusing to push the form: the ${t} formxml could not be parsed, so the generative pages it embeds cannot be verified (${r instanceof Error?r.message:String(r)}).`)}}async function Jb(e,t,r){let n=new Set(r.map(([o,s])=>`${o}|${s}`)),i=t.filter(([o,s])=>!n.has(`${o}|${s}`)).map(([,o])=>o);if(i.length===0)return;let a=await(0,JM.findMissingGenPages)(e,i,"form generative-page preflight");if(a.length>0)throw new Oi.SdkError(Bt.FORM_GENPAGE_TARGET_NOT_FOUND,`Refusing to push the form: it embeds generative page(s) ${a.map(o=>`'${o}'`).join(", ")} that do not exist in this environment. Push the page before the form that embeds it.`)}async function tB(e,t,r,n){var i;(0,ut.requireEtag)(n,"form",t);let a=`/systemforms(${t})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,lr.odataQuery)([["$select","formid,formxml"]]),o=(0,ut.ensureSuccess)(await e.get(a),e.apiUrl(a)),s=(0,ut.readEtag)(o);if(s===null||s!==n)throw new Oi.SdkError(ut.VERSION_CONFLICT_CODE,`Version conflict writing form '${t}': its formxml changed on the server since it was read (held ${n}, server ${s??"(unreadable)"}). Re-fetch the form and re-apply the change.`);let l=(i=o.body)===null||i===void 0?void 0:i.formxml,u=typeof l=="string"&&l!==""?af(l,"server"):[];await Jb(e,af(r,"payload"),u)}function Qb(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 rB(e,t){var r,n;let a=`/systemforms(${(0,lr.normalizeGuid)(t,"formId")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,lr.odataQuery)([["$select","formid,formxml"]]),s=(r=(0,ut.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||r===void 0?void 0:r.formxml;if(!s)return;let l=(0,rf.parseXmlRoot)(s,"<form/>"),u=Qb(l,nf);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 b=(n=v.getAttribute("Id"))!==null&&n!==void 0?n:"";b&&c.push(b.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)}:{}}}Bt.getFormSecurityRoles=rB});var lu=y(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.disassociateRecords=Oe.associateRecords=Oe.createRecordsBulk=Oe.upsertRecord=Oe.queryAllRecords=Oe.queryRecords=Oe.getRecord=Oe.deleteRecord=Oe.updateRecord=Oe.createRecord=void 0;var nB=Pt(),Sr=be(),mt=ae(),ou=te(),Hr=xl();function su(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 iB(e,t,r){let i=`/${await(0,Hr.resolveEntitySetName)(e,t)}`,a=(0,Sr.ensureSuccess)(await e.post(i,su(r)),e.apiUrl(i)),o=(0,Sr.readCreatedId)(a,`${t}id`);if(!o)throw new ou.InvalidArgumentError(`Dataverse did not return an id for the created '${t}' row`);return{id:o,entityType:t}}Oe.createRecord=iB;async function aB(e,t,r,n){let i=(0,mt.normalizeGuid)(r,"id"),o=`/${await(0,Hr.resolveEntitySetName)(e,t)}(${i})`;(0,Sr.ensureSuccess)(await e.patch(o,su(n)),e.apiUrl(o))}Oe.updateRecord=aB;async function oB(e,t,r){let n=(0,mt.normalizeGuid)(r,"id"),a=`/${await(0,Hr.resolveEntitySetName)(e,t)}(${n})`;(0,Sr.ensureSuccess)(await e.delete(a),e.apiUrl(a))}Oe.deleteRecord=oB;async function sB(e,t,r,n){var i;let a=(0,mt.normalizeGuid)(r,"id"),o=await(0,Hr.resolveEntitySetName)(e,t),s=(0,mt.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:{}}Oe.getRecord=sB;function lB(e){return e?.fetchXml?(0,mt.odataQuery)([["fetchXml",e.fetchXml]]):(0,mt.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 Xb(e,t,r){var n,i;if(r?.paginate){if(r.top!==void 0)throw new ou.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 ou.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,Hr.resolveEntitySetName)(e,t)}${lB(r)}`;return r?.paginate?(0,nB.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:[]}Oe.queryRecords=Xb;async function uB(e,t,r){return Xb(e,t,{...r,paginate:!0})}Oe.queryAllRecords=uB;function cB(e){if("id"in e)return`(${(0,mt.normalizeGuid)(e.id,"id")})`;let t=typeof e.value=="string"?`'${(0,mt.odataPathLiteral)(e.value)}'`:e.value;return`(${(0,mt.assertODataName)(e.key,"alternate key name")}=${t})`}async function dB(e,t,r,n){let i=cB(r),o=`/${await(0,Hr.resolveEntitySetName)(e,t)}${i}`,s=(0,Sr.ensureSuccess)(await e.patch(o,su(n)),e.apiUrl(o)),l=s.status===201,u=(0,Sr.readCreatedId)(s,`${t}id`);return{id:u??("id"in r?(0,mt.normalizeGuid)(r.id,"id"):""),created:l}}Oe.upsertRecord=dB;async function pB(e,t,r){var n,i;if(r.length===0)return[];let a=await(0,Hr.resolveEntitySetName)(e,t),o=r.map(c=>({"@odata.type":`Microsoft.Dynamics.CRM.${t}`,...su(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 ou.InvalidArgumentError(`CreateMultiple on '${t}' returned ${u.length} id(s) for ${r.length} row(s)`);return u}Oe.createRecordsBulk=pB;async function fB(e,t,r,n){let i=(0,mt.normalizeGuid)(r,"id"),a=(0,mt.normalizeGuid)(n.targetId,"targetId"),o=await(0,Hr.resolveEntitySetName)(e,t),s=await(0,Hr.resolveEntitySetName)(e,n.targetEntity),l=(0,mt.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))}Oe.associateRecords=fB;async function mB(e,t,r,n,i){let a=(0,mt.normalizeGuid)(r,"id"),o=(0,mt.normalizeGuid)(i,"targetId"),s=await(0,Hr.resolveEntitySetName)(e,t),l=(0,mt.assertODataName)(n,"relationshipName"),u=`/${s}(${a})/${l}(${o})/$ref`;(0,Sr.ensureSuccess)(await e.delete(u),e.apiUrl(u))}Oe.disassociateRecords=mB});var Nr=y(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.publishBoundEntity=Ze.boundEntityPublishScope=Ze.publishGenPageById=Ze.publishDashboardById=Ze.publishWebResourceById=Ze.publishEntity=Ze.publishAppModule=Ze.publishXml=void 0;var Yb=be(),us=ae(),Zb="/PublishXml";async function Ta(e,t){(0,Yb.ensureSuccess)(await(0,Yb.resendDeadlockVictim)(()=>e.post(Zb,{ParameterXml:t})),e.apiUrl(Zb))}Ze.publishXml=Ta;function hB(e,t){return Ta(e,`<importexportxml><appmodules><appmodule>${(0,us.xmlText)(t)}</appmodule></appmodules></importexportxml>`)}Ze.publishAppModule=hB;function ew(e,t){return Ta(e,`<importexportxml><entities><entity>${(0,us.xmlText)(t)}</entity></entities></importexportxml>`)}Ze.publishEntity=ew;function gB(e,t){return Ta(e,`<importexportxml><webresources><webresource>${(0,us.xmlText)(t)}</webresource></webresources></importexportxml>`)}Ze.publishWebResourceById=gB;function vB(e,t){return Ta(e,`<importexportxml><dashboards><dashboard>${(0,us.xmlText)(t)}</dashboard></dashboards></importexportxml>`)}Ze.publishDashboardById=vB;function yB(e,t){return Ta(e,`<importexportxml><uxagentprojects><uxagentproject>${(0,us.xmlText)(t)}</uxagentproject></uxagentprojects></importexportxml>`)}Ze.publishGenPageById=yB;function bB(e){let t=e?.entityLogicalName;return t?{envelope:"entity",entityLogicalName:t,blastRadiusWarning:"ENTITY_ENVELOPE_ALSO_SHIPS_UNRELATED_UNPUBLISHED_CHANGES"}:{envelope:"entity"}}Ze.boundEntityPublishScope=bB;function wB(e,t){let r=t?.entityLogicalName;return r?ew(e,r):Promise.resolve()}Ze.publishBoundEntity=wB});var cu=y(Kr=>{"use strict";Object.defineProperty(Kr,"__esModule",{value:!0});Kr.base64ToUtf8=Kr.base64ToBytes=Kr.bytesToBase64=Kr.utf8ToBase64=void 0;var sf=32768,Ut="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function uu(){return globalThis}function AB(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 EB(e){let t="";for(let r=0;r<e.length;r+=sf)t+=String.fromCharCode(...e.subarray(r,r+sf));return t}function CB(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+="/":Ut.indexOf(n)>=0&&(t+=n)}for(t.length%4===1&&(t=t.slice(0,-1));t.length%4!==0;)t+="=";return t}function SB(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+=Ut[i>>18&63]+Ut[i>>12&63]+Ut[i>>6&63]+Ut[i&63]}let n=e.length-r;if(n===1){let i=e[r]<<16;t+=`${Ut[i>>18&63]}${Ut[i>>12&63]}==`}else if(n===2){let i=e[r]<<16|e[r+1]<<8,a=Ut[i>>18&63],o=Ut[i>>12&63],s=Ut[i>>6&63];t+=`${a}${o}${s}=`}return t}function NB(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=Ut.indexOf(e[a])<<18|Ut.indexOf(e[a+1])<<12|(e[a+2]==="="?0:Ut.indexOf(e[a+2]))<<6|(e[a+3]==="="?0:Ut.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 DB(e){let t=uu();if(t.Buffer)return t.Buffer.from(e,"utf8").toString("base64");let r=t.TextEncoder;return tw(r?new r().encode(e):AB(e))}Kr.utf8ToBase64=DB;function tw(e){let t=uu();return t.Buffer?t.Buffer.from(e).toString("base64"):t.btoa?t.btoa(EB(e)):SB(e)}Kr.bytesToBase64=tw;function rw(e){let t=uu();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"base64"));let r=CB(e);if(t.atob){let n=t.atob(r);return Uint8Array.from(n,i=>i.charCodeAt(0))}return NB(r)}Kr.base64ToBytes=rw;function IB(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>=sf&&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 _B(e){let t=uu();return t.Buffer?t.Buffer.from(e,"base64").toString("utf8"):IB(rw(e))}Kr.base64ToUtf8=_B});var ow=y(Jr=>{"use strict";Object.defineProperty(Jr,"__esModule",{value:!0});Jr.deleteWebResource=Jr.getWebResource=Jr.updateWebResource=Jr.createWebResource=void 0;var TB=Nr(),cs=be(),du=ae(),PB=cu(),nw=te(),RB={html:1,css:2,js:3,xml:4,png:5,jpg:6,gif:7,xsl:9,ico:10,svg:11,resx:12};function iw(e){if(e.contentBase64!==void 0)return e.contentBase64;if(e.content!==void 0)return(0,PB.utf8ToBase64)(e.content)}async function aw(e,t){return(0,TB.publishWebResourceById)(e,t)}async function OB(e,t){var r;let n=iw(t);if(n===void 0)throw new nw.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:RB[t.type],content:n};t.description&&(i.description=t.description);let a=(0,cs.ensureSuccess)(await e.post("/webresourceset",i),e.apiUrl("/webresourceset")),o=(0,cs.readCreatedId)(a,"webresourceid");if(!o)throw new nw.InvalidArgumentError(`Dataverse did not return an id for web resource '${t.name}'`);return t.publish!==!1&&await aw(e,o),{id:o,name:t.name}}Jr.createWebResource=OB;async function xB(e,t,r){let n=(0,du.normalizeGuid)(t,"id"),i={},a=iw(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,cs.ensureSuccess)(await e.patch(o,i),e.apiUrl(o)),r.publish!==!1&&await aw(e,n)}Jr.updateWebResource=xB;async function FB(e,t){var r;let i=`/webresourceset(${(0,du.normalizeGuid)(t,"id")})${(0,du.odataQuery)([["$select","name,displayname,webresourcetype,content,description"]])}`;return(r=(0,cs.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)!==null&&r!==void 0?r:{}}Jr.getWebResource=FB;async function LB(e,t){let n=`/webresourceset(${(0,du.normalizeGuid)(t,"id")})`;(0,cs.ensureSuccess)(await e.delete(n),e.apiUrl(n))}Jr.deleteWebResource=LB});var pu=y(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.applyAppSettings=et.setAppSetting=et.readAppSettings=et.resolveSettingDefinitions=et.APP_SETTING_UNSET=et.APP_SETTING_OFF=et.APP_SETTING_ON=et.HEADER_AND_NAVIGATION_REFRESH=void 0;var Pa=be(),En=ae();et.HEADER_AND_NAVIGATION_REFRESH="HeaderAndNavigationRefresh";et.APP_SETTING_ON="2";et.APP_SETTING_OFF="1";et.APP_SETTING_UNSET="0";function uw(e,t){return"/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,En.odataQuery)([["$select",e],["$filter",t]])}async function cw(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,En.odataLiteral)(c)}'`).join(" or "),s=`/settingdefinitions${(0,En.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",o]])}`,u=((n=(r=(0,Pa.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}et.resolveSettingDefinitions=cw;async function kB(e,t){var r,n,i,a;let o=(0,En.normalizeGuid)(t,"App id"),s=uw("appsettingid,value,_settingdefinitionid_value",`_parentappmoduleid_value eq ${o}`),u=((n=(r=(0,Pa.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,En.normalizeGuid)(h,"Setting definition id")}`).join(" or "),f=`/settingdefinitions${(0,En.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",p]])}`,m=(0,Pa.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,b;let E=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=E?.uniquename)!==null&&h!==void 0?h:p._settingdefinitionid_value)!==null&&v!==void 0?v:"",value:(b=p.value)!==null&&b!==void 0?b:"",...E?.displayname?{displayName:E.displayname}:{}}})}et.readAppSettings=kB;async function sw(e,t,r){var n,i,a;let o=uw("appsettingid,value",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${r}`),l=((i=(n=(0,Pa.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 dw(e,t,r,n){let i=(0,En.normalizeGuid)(t,"App id"),o=(await cw(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,En.normalizeGuid)(s,"Setting definition id"),u=await sw(e,i,l);if(u)return lw(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 sw(e,i,l)}catch{m=void 0}if(m)return lw(e,m,n);throw p&&(0,Pa.ensureSuccess)(p,e.apiUrl(c)),f}et.setAppSetting=dw;async function lw(e,t,r){if(t.value===r)return"unchanged";let n=`/appsettings(${(0,En.normalizeGuid)(t.id,"App setting id")})`;return(0,Pa.ensureSuccess)(await e.patch(n,{value:r}),e.apiUrl(n)),"updated"}async function MB(e,t,r){var n;let i=[];for(let[a,o]of Object.entries(r??{}))try{await dw(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}et.applyAppSettings=MB});var mu=y(fu=>{"use strict";Object.defineProperty(fu,"__esModule",{value:!0});fu.HEADER_NAV_BOOLEAN_RULE=void 0;fu.HEADER_NAV_BOOLEAN_RULE="headerAndNavigationRefresh-must-be-boolean"});var fw=y(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.deleteSolution=oe.importSolution=oe.exportSolution=oe.removeSolutionComponent=oe.addSolutionComponent=oe.setSolutionVersion=oe.createSolution=oe.createPublisher=oe.getSolution=oe.fetchSolutionComponents=oe.SolutionComponentType=void 0;var pw=Pt(),Dr=be(),$t=ae(),xi=te();oe.SolutionComponentType={SavedQuery:26,Workflow:29,SavedQueryVisualization:59,SystemForm:60,AppModule:80,UxAgentProject:10372};var BB=[oe.SolutionComponentType.SavedQuery,oe.SolutionComponentType.Workflow,oe.SolutionComponentType.SavedQueryVisualization,oe.SolutionComponentType.SystemForm,oe.SolutionComponentType.AppModule,oe.SolutionComponentType.UxAgentProject];async function UB(e,t){let r=(0,$t.normalizeGuid)(t,"solutionId"),n=BB.map(s=>`msdyn_componenttype eq ${s}`).join(" or "),i=`/msdyn_solutioncomponentsummaries${(0,$t.odataQuery)([["$select","msdyn_objectid,msdyn_componenttype,msdyn_workflowcategory,msdyn_displayname,msdyn_name"],["$filter",`msdyn_solutionid eq ${r} and (${n})`]])}`,o=(await(0,pw.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 $B(e,r,o)]}oe.fetchSolutionComponents=UB;async function $B(e,t,r){let n=new Set(r.map(s=>s.objectId.toLowerCase())),i=`/solutioncomponents${(0,$t.odataQuery)([["$select","objectid,componenttype"],["$filter",`_solutionid_value eq ${t} and componenttype eq ${oe.SolutionComponentType.UxAgentProject}`]])}`,a=await(0,pw.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:oe.SolutionComponentType.UxAgentProject}))}return o}function qB(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 VB(e,t){var r,n,i,a,o,s,l,u,c,d;let p=String(t??"").trim();if(!p)throw new xi.InvalidArgumentError("getSolution: a solution unique name or id is required.");let f=qB(p)?`solutionid eq ${(0,$t.normalizeGuid)(p,"solutionId")}`:`uniquename eq '${(0,$t.odataLiteral)(p)}'`,m=`/solutions${(0,$t.odataQuery)([["$select","solutionid,uniquename,friendlyname,version,ismanaged"],["$expand","publisherid($select=publisherid,uniquename,customizationprefix,customizationoptionvalueprefix)"],["$filter",f]])}`,b=((n=(r=(0,Dr.ensureSuccess)(await e.get(m),e.apiUrl(m)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0];if(!b?.solutionid)throw new xi.InvalidArgumentError(`No solution found for '${t}'.`);let E=b.publisherid;if(!E?.publisherid)throw new xi.InvalidArgumentError(`Solution '${(i=b.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 E))throw new xi.InvalidArgumentError(`Solution '${(a=b.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,$t.normalizeGuid)(b.solutionid,"solutionId"),uniqueName:(o=b.uniquename)!==null&&o!==void 0?o:"",friendlyName:(s=b.friendlyname)!==null&&s!==void 0?s:"",version:(l=b.version)!==null&&l!==void 0?l:"",isManaged:!!b.ismanaged,publisherId:(0,$t.normalizeGuid)(E.publisherid,"publisherId"),publisherUniqueName:(u=E.uniquename)!==null&&u!==void 0?u:"",publisherPrefix:(c=E.customizationprefix)!==null&&c!==void 0?c:"",publisherOptionValuePrefix:(d=E.customizationoptionvalueprefix)!==null&&d!==void 0?d:0}}oe.getSolution=VB;async function GB(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,Dr.ensureSuccess)(await e.post("/publishers",n),e.apiUrl("/publishers")),a=(0,Dr.readCreatedId)(i,"publisherid");if(!a)throw new xi.InvalidArgumentError(`Dataverse did not return an id for publisher '${t.uniqueName}'`);return{id:a,uniqueName:t.uniqueName}}oe.createPublisher=GB;async function zB(e,t){var r;let n=(0,$t.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,Dr.ensureSuccess)(await e.post("/solutions",i),e.apiUrl("/solutions")),o=(0,Dr.readCreatedId)(a,"solutionid");if(!o)throw new xi.InvalidArgumentError(`Dataverse did not return an id for solution '${t.uniqueName}'`);return{id:o,uniqueName:t.uniqueName}}oe.createSolution=zB;async function WB(e,t,r){let i=`/solutions(${(0,$t.normalizeGuid)(t,"solutionId")})`;(0,Dr.ensureSuccess)(await e.patch(i,{version:r}),e.apiUrl(i))}oe.setSolutionVersion=WB;async function jB(e,t){var r;let i={ComponentId:(0,$t.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,Dr.ensureSuccess)(await e.post("/AddSolutionComponent",i),e.apiUrl("/AddSolutionComponent"))}oe.addSolutionComponent=jB;async function HB(e,t,r,n){let a={SolutionComponent:{"@odata.type":"Microsoft.Dynamics.CRM.solutioncomponent",solutioncomponentid:(0,$t.normalizeGuid)(t,"componentId")},ComponentType:r,SolutionUniqueName:n};(0,Dr.ensureSuccess)(await e.post("/RemoveSolutionComponent",a),e.apiUrl("/RemoveSolutionComponent"))}oe.removeSolutionComponent=HB;async function KB(e,t){var r,n;let i={SolutionName:t.solutionName,Managed:(r=t.managed)!==null&&r!==void 0?r:!1},o=(n=(0,Dr.ensureSuccess)(await e.post("/ExportSolution",i),e.apiUrl("/ExportSolution")).body)===null||n===void 0?void 0:n.ExportSolutionFile;if(!o)throw new xi.InvalidArgumentError(`ExportSolution returned no file for '${t.solutionName}'`);return{base64:o}}oe.exportSolution=KB;async function JB(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,$t.normalizeGuid)(t.importJobId,"importJobId")),(0,Dr.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution"))}oe.importSolution=JB;async function QB(e,t){let n=`/solutions(${(0,$t.normalizeGuid)(t,"solutionId")})`;(0,Dr.ensureSuccess)(await e.delete(n),e.apiUrl(n))}oe.deleteSolution=QB});var df=y(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.compileGenPage=Ee.legacyEnumsNeeded=Ee.createGenPageTypeScriptLoader=Ee.acceptGenPageTypeScript=Ee.isLoadableGenPageOutput=Ee.GENPAGE_RUNTIME_TYPES_END=Ee.GENPAGE_RUNTIME_TYPES_BEGIN=Ee.GENPAGE_TYPESCRIPT_VERSION=void 0;var Ra=te();Ee.GENPAGE_TYPESCRIPT_VERSION="5.8.3";Ee.GENPAGE_RUNTIME_TYPES_BEGIN="// --- BEGIN GENERATED RUNTIME TYPES ---";Ee.GENPAGE_RUNTIME_TYPES_END="// --- END GENERATED RUNTIME TYPES ---";var XB=/(import\s+[^'"]+)(['"`])(\.\/RuntimeTypes)\2;?\s*/g,Zn="./RuntimeTypes",YB=/\b(import\s.+from\s+['"]|import\s*['"]|export\s)/;function ZB(e){return e!==void 0&&e!==""&&YB.test(e)}Ee.isLoadableGenPageOutput=ZB;var mw=["transpileModule","createSourceFile","createProgram","getParseTreeNode","flattenDiagnosticMessageText","forEachChild","getModifiers","canHaveModifiers","isImportDeclaration","isExportDeclaration","isExportAssignment","isStringLiteral"];function vw(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?mw.filter(s=>typeof n?.[s]!="function"):[...mw];if(!n||i.length>0)throw new Ra.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@${Ee.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js.`);let a=typeof n.version=="string"?n.version:"",o=Ee.GENPAGE_TYPESCRIPT_VERSION.split(".").slice(0,2).join(".");if(a.split(".").slice(0,2).join(".")!==o)throw new Ra.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 (${Ee.GENPAGE_TYPESCRIPT_VERSION}). Another version can emit different JavaScript for the same page. Supply typescript@${Ee.GENPAGE_TYPESCRIPT_VERSION}.`);return n}Ee.acceptGenPageTypeScript=vw;function eU(e){let t;return()=>{if(!t){if(e===void 0)return Promise.reject(new Ra.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@${Ee.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js. Nothing was written.`));t=Promise.resolve().then(()=>typeof e=="function"?e():e).then(vw).catch(r=>{throw t=void 0,r instanceof Ra.SdkError?r:new Ra.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}}Ee.createGenPageTypeScriptLoader=eU;var yw=e=>`${e.kind}:${e.pos}:${e.end}`;function tU(e,t){return()=>r=>{let n=i=>{let a=e.getParseTreeNode(i);a&&t.add(yw(a)),e.forEachChild(i,n)};return n(r),r}}function cf(e){return{target:e.ScriptTarget.ES5,module:e.ModuleKind.ES2020,jsx:e.JsxEmit.React}}function hw(e,t,r){var n;let i=e.transpileModule(t,{compilerOptions:cf(e),reportDiagnostics:!0,...r?{transformers:{after:[tU(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 gw=e=>e.startsWith(".")||e.startsWith("/"),lf={line:1,column:1};function uf(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):lf},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 lf}}}function rU(e,t,r,n){var i,a;let o=[],s=uf(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(b=>b.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 E=m.exportClause;E&&e.isNamedExports(E)&&E.elements.some(N=>N.name.text==="default")&&(p=!0);let C=m.moduleSpecifier&&e.isStringLiteral(m.moduleSpecifier)?m.moduleSpecifier.text:void 0;C===Zn?l(s.statement(C,"export"),d,"a page cannot re-export from './RuntimeTypes': that module does not exist at runtime"):C!==void 0&&gw(C)&&c(s.statement(C,"export"),C);continue}if(!e.isImportDeclaration(m)||!e.isStringLiteral(m.moduleSpecifier))continue;let h=m.moduleSpecifier.text,v=m.importClause;if(h!==Zn){gw(h)&&c(s.statement(h,"import"),h),v?.name&&f.add(v.name.text);let E=v?.namedBindings;E&&e.isNamespaceImport(E)?f.add(E.name.text):E&&e.isNamedImports(E)&&E.elements.forEach(C=>f.add(C.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 b=v.namedBindings;if(b&&e.isNamespaceImport(b))l(s.binding(b.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(b&&e.isNamedImports(b))for(let E of b.elements){let C=E.name.text,N=(a=(i=E.propertyName)===null||i===void 0?void 0:i.text)!==null&&a!==void 0?a:C,R=s.element(h,C);N!==C?l(R,d,`'${N} as ${C}' would be undefined at runtime: the enum is inlined as '${N}', so import it under its own name`):n?.text?n.enums.has(C)||l(R,"genpage-runtime-types-unresolved",`'${C}' 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(R,"genpage-runtime-types-unresolved",`'${C}' 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(lf,"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 bw(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===Zn},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 nU(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=bw(e,t,cf(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(yw(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 iU(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===Zn)}function aU(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===Zn).map(o=>o.getStart(r))),i=!0;return{code:t.replace(XB,(...o)=>(n.has(o[o.length-2])||(i=!1),"")),exact:i}}function ww(e,t,r){if(!r||r.size===0)return[];let n=bw(e,t,{...cf(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===Zn&&((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))}Ee.legacyEnumsNeeded=ww;function oU(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 sU(e,t,r,n){let i=new Set,a=hw(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=oU(r,n,ww(e,s,n)),u=[...rU(e,s,o,l),...nU(e,o,l,i)];if(!l?.text)return{code:a.code,diagnostics:u};let c=hw(e,l.text);if(c.diagnostics.length>0)throw new Ra.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=aU(e,a.code),p=d.code;return u.length===0&&!d.exact?u.push({...uf(e,o).statement(Zn,"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&&iU(e,p)&&u.push({...uf(e,o).statement(Zn,"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:[Ee.GENPAGE_RUNTIME_TYPES_BEGIN,c.code,Ee.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
+`),diagnostics:u}}Ee.compileGenPage=sU});var gu=y(ei=>{"use strict";Object.defineProperty(ei,"__esModule",{value:!0});ei.appApi=ei.deleteAppResolvingOnce=ei.unpublishedAppModulesQuery=void 0;var _w=Pt(),lU=wf(),uU=Zp(),Aw=Nr(),cU=pu(),ve=be(),fe=ae(),gf=lt(),dU=Ol(),Ae=te(),pU=(0,fe.odataQuery)([["$select","appmoduleid,name,uniquename,description,aiappdescription"]]),pf="appmoduleid,name,uniquename,description,aiappdescription";function Tw(e,t,r){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,fe.odataQuery)([["$select",e],["$filter",t],["$top",r]])}ei.unpublishedAppModulesQuery=Tw;function ff(e,t){return Tw(e,t?`appmoduleid eq ${t}`:void 0,t?1:void 0)}function hu(e,t){return"/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,fe.odataQuery)([["$select",t],["$filter",`sitemapid eq ${e}`],["$top",1]])}function Oa(e){var t;let r=(t=e.body)===null||t===void 0?void 0:t.value;if(Array.isArray(r))return r[0]}function fU(e){let t=e?.["@odata.etag"];return typeof t=="string"?t:null}function vf(e,t){if(typeof e!="string")return!1;try{return(0,fe.normalizeGuid)(e,"sitemapid")===t}catch{return!1}}function ds(e){let t=new Set,r=[];for(let n of e??[])n&&!t.has(n)&&(t.add(n),r.push(n));return r}function mU(e){return`cdsapp_${(e||"").replace(/[^a-zA-Z0-9]/g,"")||"app"}`}async function Pw(e,t){var r,n;let i=u=>{throw new Ae.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,fe.odataQuery)([["$select","sitemapid"],["$filter",`sitemapnameunique eq '${(0,fe.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 hU(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,fe.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 yf(e){return e instanceof Error?e.message:String(e)}async function gU(e,t){var r,n,i;try{let a=`/roles${(0,fe.odataQuery)([["$select","roleid"],["$filter","name eq 'System Administrator'"],["$top",1]])}`,s=(i=(n=(r=(0,ve.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,ve.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 (${yf(a)}); it will not be visible or playable until a role is granted access to it.`}}async function vU(e,t){let r=[];async function n(s,l,u){try{return(await(0,_w.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}' (${yf(c)}); they were NOT added to the app.`),[]}}let[i,a,o]=await Promise.all([n(`/systemforms${(0,fe.odataQuery)([["$select","formid"],["$filter",`objecttypecode eq '${(0,fe.odataLiteral)(t)}' and type eq 2 and formactivationstate eq 1`]])}`,"formid","forms"),n(`/savedqueries${(0,fe.odataQuery)([["$select","savedqueryid"],["$filter",`returnedtypecode eq '${(0,fe.odataLiteral)(t)}' and querytype eq 0 and statecode eq 0`]])}`,"savedqueryid","views"),n(`/savedqueryvisualizations${(0,fe.odataQuery)([["$select","savedqueryvisualizationid"],["$filter",`primaryentitytypecode eq '${(0,fe.odataLiteral)(t)}'`]])}`,"savedqueryvisualizationid","charts")]);return{forms:i,views:a,charts:o,warnings:r}}var Ew=new WeakMap;async function yU(e,t){let r=Ew.get(e);r||(r=new Map,Ew.set(e,r));let n=r.get(t);if(n!==void 0)return n;let i=await bU(e,t);return i&&r.set(t,i),i}async function Cw(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 bU(e,t){let r=`/EntityDefinitions(LogicalName='${(0,fe.odataPathLiteral)(t)}')${(0,fe.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 Sw(e,t){let r=[],n=ds(t.entities),i=4,a=await Cw(n,i,f=>yU(e,f)),o=n.filter((f,m)=>!a[m]);if(o.length>0)throw new Ae.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 ds(t.components.forms))r.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:f});for(let f of ds(t.components.views))r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:f});for(let f of ds(t.components.charts))r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:f});for(let f of ds(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 Cw(n,i,f=>vU(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 Nw(e,t,r){if(r.length===0)return;let n="/AddAppComponents";(0,ve.ensureSuccess)(await e.post(n,{AppId:t,Components:r}),e.apiUrl(n))}function wU(e){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,fe.odataQuery)([["$select","appmoduleid,appmoduleidunique"],["$filter",`appmoduleid eq ${e}`],["$top",1]])}async function Dw(e,t,r){var n;if(r.length===0)return;let i=wU(t),a=await e.get(i);if(a.status<200||a.status>=300)throw new Ae.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=Oa(a),s=o?.appmoduleidunique;if(typeof s!="string"||!s)throw new Ae.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,fe.odataQuery)([["$select","objectid,componenttype"],["$filter",`_appmoduleidunique_value eq ${(0,fe.normalizeGuid)(s,`App '${t}' appmoduleidunique`)} and componenttype eq 1`]])}`,u=await e.get(l);if(u.status<200||u.status>=300)throw new Ae.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 Ae.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 Ae.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 AU(e,t,r){let n=`/appmodules(${t})`,i=`/sitemaps(${r.sitemapId})`;try{let a=await EU(e,r.sitemapId,r.sitemapNameUnique);if(a==="absent"){r.serverRefusedSitemap&&(0,ve.ensureSuccess)(await e.delete(n),e.apiUrl(n));return}if(a==="foreign"){r.serverRefusedSitemap&&(0,ve.ensureSuccess)(await e.delete(n),e.apiUrl(n));return}if(e.supportsAtomicBatch){if(!r.sitemapWriteToken)return;await Ow(e,[{path:n},{path:i,etag:r.sitemapWriteToken}])}}catch{}}async function EU(e,t,r){var n,i,a;let o=hu(t,"sitemapid,sitemapnameunique"),s=await e.get(o);if(s.status<200||s.status>=300)throw new Ae.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 Ae.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 Rw(e,t){var r;let n=(0,fe.normalizeGuid)(t,"id"),i=h=>{throw new Ae.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})${pU}`,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 Pw(e,s);if(!l)return{uniquename:s,appEtag:(0,ve.readEtag)(o)};let u=(0,fe.normalizeGuid)(l,"sitemapId"),c=await bf(e,u),d=hu(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=Oa(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(!vf(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,ve.readEtag)(o),sitemapEtag:c}}async function CU(e,t,r){let n=(0,fe.normalizeGuid)(t,"id"),i=await Rw(e,n);await r?.(i.sitemapXml),await xw(e,n,i)}ei.deleteAppResolvingOnce=CU;async function Ow(e,t){let r=`batch_${(0,gf.newId)()}`,n=`changeset_${(0,gf.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,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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),r&&(n=n.replace(/"/g,"&quot;").replace(/'/g,"&apos;"))),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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}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);
+`),o=await e.postBatch(a,r),s=e.apiUrl("/$batch");(0,ve.ensureSuccess)(o,s);let l=`app '${t[0].path}'`;if(typeof o.body!="string"||o.body.length===0)throw new Ae.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,dU.parseChangeSetStatuses)(o.body,i.map((d,p)=>String(p+1)));if(u===void 0)throw new Ae.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 Ae.ConnectionError(s,c,`atomic delete of ${l} was rolled back: the change set reported HTTP ${c}`);if(u.length!==i.length)throw new Ae.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 bf(e,t){try{let r=await e.get(`/sitemaps(${t})?$select=sitemapid`);return r.status<200||r.status>=300?null:(0,ve.readEtag)(r)}catch{return null}}async function mf(e,t,r,n){if(!n)return null;let i=await bf(e,t);if(!i)return null;try{let a=await e.get(hu(t,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"));if(a.status<200||a.status>=300)return null;let o=Oa(a);return!o||!vf(o.sitemapid,t)||o.sitemapnameunique!==n||o.sitemapxml!==r.sitemapxml||o.sitemapname!==r.sitemapname?null:i}catch{return null}}function SU(e){return e>=400&&e<500&&e!==408&&e!==429}function hf(e,t,r){if(!e)throw new Ae.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 xw(e,t,r){let n=`/appmodules(${t})`;if(!r.sitemapId){await NU(e,n,hf(r.appEtag,t,"app"));return}if(!e.supportsAtomicBatch)throw new Ae.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 Ow(e,[{path:n,etag:hf(r.appEtag,t,"app")},{path:`/sitemaps(${r.sitemapId})`,etag:hf(r.sitemapEtag,t,"sitemap")}])}async function NU(e,t,r){(0,ve.ensureSuccess)(await e.delete(t,{headers:{"If-Match":r}}),e.apiUrl(t))}async function Iw(e,t){if(!/GenPageId/i.test(t))return;let r;try{r=[...new Set((0,lU.collectGenPageIds)(t))]}catch(i){throw new Ae.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 (${yf(i)}).`)}if(r.length===0)return;let n=await(0,uU.findMissingGenPages)(e,r,"sitemap generative-page preflight");if(n.length>0)throw new Ae.SdkError("SITEMAP_TARGET_NOT_FOUND",`Refusing to push the app: its sitemap navigates to generative page(s) ${n.map(i=>`'${i}'`).join(", ")} that do not exist in this environment. Push the page before the app that links to it.`)}function DU(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")}ei.appApi={async get(e,t){var r;let n=(0,fe.normalizeGuid)(t,"id"),i=ff(pf,n),a=(0,ve.ensureSuccess)(await e.get(i),e.apiUrl(i)),o=(r=Oa(a))!==null&&r!==void 0?r:{};if(!o.appmoduleid)throw new Ae.SdkError("APP_NOT_FOUND",`App '${n}' was not found (checked the unpublished-aware projection, which includes drafts).`);let s=await Pw(e,o.uniquename),l=s?(0,fe.normalizeGuid)(s,"sitemapId"):void 0,u=null;if(l){u=await bf(e,l);let d=hu(l,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"),p=(0,ve.ensureSuccess)(await e.get(d),e.apiUrl(d)),f=Oa(p),m=h=>{throw new Ae.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 Ae.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(!vf(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=fU(o);return{raw:o,etag:u,...o.appmoduleid?{siblingEtags:{[(0,fe.normalizeGuid)(o.appmoduleid,"appmoduleid")]:c}}:{}}},async list(e,t){let r=ff(pf);return(await(0,_w.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 Iw(e,n.sitemapxml);let i=n.iconWebResourceId?void 0:await hU(e),a=n.iconWebResourceId||i?.id;if(!a)throw new Ae.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||mU(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,ve.ensureSuccess)(await(0,ve.resendDeadlockVictim)(()=>e.post(u,(0,ve.withClientMintedId)(l,"appmoduleid",r))),e.apiUrl(u)),d=(0,ve.resolveCreatedId)(c,"appmoduleid","app module",r),p=null,f=null,m=[];o&&m.push(o);let h={kind:"notRequested"},v=n.sitemapId?(0,fe.normalizeGuid)(n.sitemapId,"sitemapId"):(0,gf.newId)(),b=!1,E={sitemapxml:n.sitemapxml,sitemapname:n.sitemapname};try{let N="/sitemaps",R=(0,ve.echoWrite)("sitemapid"),O=await e.post(`${N}${R.query}`,{sitemapid:v,sitemapnameunique:s,...E},R.options);b=SU(O.status);let F=(0,ve.ensureSuccess)(O,e.apiUrl(N));f=(0,ve.readEtag)(F),p=f??await mf(e,v,E,s);let k=await Sw(e,n);m.push(...k.warnings);let P=k.components;P.unshift({"@odata.type":"Microsoft.Dynamics.CRM.sitemap",sitemapid:v}),await Nw(e,d,P),await Dw(e,d,k.tables);let V=await gU(e,d);V&&m.push(V),n.appSettings&&Object.keys(n.appSettings).length>0&&m.push(...await(0,cU.applyAppSettings)(e,d,n.appSettings)),n.published!==!1&&(await(0,Aw.publishAppModule)(e,d),h={kind:"submitted"})}catch(N){throw await AU(e,d,{sitemapId:v,sitemapNameUnique:s,serverRefusedSitemap:b,sitemapWriteToken:f}),N}let C=null;if(h.kind==="submitted")try{let N=await e.get(`/appmodules(${d})?$select=appmoduleid`);N.status>=200&&N.status<300&&(C=(0,ve.readEtag)(N))}catch{}return{id:d,etag:p,serverIdentity:{sitemapId:v},siblingEtags:{[d]:C},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,fe.normalizeGuid)(t,"id");if(await Iw(e,h.sitemapxml),!h.sitemapId)throw new Ae.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 b=(0,fe.normalizeGuid)(h.sitemapId,"sitemapId");if(!n)throw new Ae.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 E=await Sw(e,h),C=`/appmodules(${v})`,N=(o=a?.[v])!==null&&o!==void 0?o:null,R=!0,O=!1,F;try{let xe=ff(pf,v),$n=await e.get(xe);if($n.status>=200&&$n.status<300){let nr=(s=Oa($n))!==null&&s!==void 0?s:{};O=!0,F=typeof nr.uniquename=="string"&&nr.uniquename?nr.uniquename:void 0,R=String((l=nr.name)!==null&&l!==void 0?l:"")!==String((u=h.appModuleName)!==null&&u!==void 0?u:"")||String((c=nr.description)!==null&&c!==void 0?c:"")!==String((d=h.appModuleDescription)!==null&&d!==void 0?d:"")||h.appModuleAiDescription!==void 0&&String((p=nr.aiappdescription)!==null&&p!==void 0?p:"")!==String(h.appModuleAiDescription)}}catch{}let k=N;if(R){let xe=O?N:null,$n=xe?(0,ve.echoWrite)("appmoduleid",{"If-Match":xe}):{query:"",options:void 0},nr=await e.patch(`${C}${$n.query}`,{name:h.appModuleName,description:h.appModuleDescription,...h.appModuleAiDescription!==void 0?{aiappdescription:h.appModuleAiDescription}:{}},$n.options);if(DU(nr))throw new Ae.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,ve.ensureSuccess)(nr,e.apiUrl(C)),k=(0,ve.readEtag)(nr)}let P={sitemapxml:h.sitemapxml,sitemapname:h.sitemapname},V=F||h.appModuleUniqueName||void 0,q=(0,ve.echoWrite)("sitemapid",{"If-Match":n}),ze=`/sitemaps(${b})`,Tt;try{Tt=(0,ve.ensureSuccess)(await e.patch(`${ze}${q.query}`,{...P},q.options),e.apiUrl(ze))}catch(xe){throw(0,Ae.withPartialTokens)(xe,{siblingEtags:{[v]:k}})}let Be=[...E.warnings];try{await Nw(e,v,E.components),await Dw(e,v,E.tables)}catch(xe){Be.push(`App '${v}': one or more components were not pinned (${xe.message}). Navigation may reference content not included in the app; re-push to retry.`)}let Qe={kind:"notRequested"},Z=k,ye=(f=(0,ve.readEtag)(Tt))!==null&&f!==void 0?f:await mf(e,b,P,V);if(h.published===!0){try{await(0,Aw.publishAppModule)(e,v),Qe={kind:"submitted"}}catch(xe){Qe={kind:"failed",error:xe},Be.push(`App '${v}': saved, but publishing failed (${xe.message}). The app remains unpublished; re-push to retry.`)}if(Qe.kind==="submitted"){Z=null;try{let xe=await e.get(`/appmodules(${v})?$select=appmoduleid`);xe.status>=200&&xe.status<300&&(Z=(0,ve.readEtag)(xe)),ye=(m=await mf(e,b,P,V))!==null&&m!==void 0?m:ye}catch{}}}return{id:v,etag:ye,siblingEtags:{[v]:Z},publish:Qe,...Be.length>0?{warnings:Be}:{}}},async delete(e,t){let r=(0,fe.normalizeGuid)(t,"id");await xw(e,r,await Rw(e,r))}}});var wf=y(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.deleteAppCascade=xa.collectGenPageIds=void 0;var IU=gu(),_U=te(),Af=ae(),TU=Jl();function Fw(e){let t=[],r=s=>l=>t.push(`${s}: ${l}`),i=new TU.DOMParser({errorHandler:{warning:r("warning"),error:r("error"),fatalError:r("fatalError")}}).parseFromString(e,"text/xml").documentElement;if(!i||t.length>0)throw new _U.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,Af.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}xa.collectGenPageIds=Fw;async function PU(e,t,r){let n=(0,Af.normalizeGuid)(t,"appModuleId");(0,Af.normalizeGuid)(r,"appModuleIdUnique");let i=[],a=[],o=[];await(0,IU.deleteAppResolvingOnce)(e,n,l=>{l!==void 0&&o.push(...Fw(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}}xa.deleteAppCascade=PU});var Lw={};pn(Lw,{Guid:()=>L});var L,We=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 M,ht=T(()=>{"use strict";$e();M=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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),r&&(n=n.replace(/"/g,"&quot;").replace(/'/g,"&apos;"))),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 kw={};pn(kw,{ScriptUtilities:()=>_});var _,$e=T(()=>{"use strict";We();ht();_=class e{static IsNullOrUndefined(t){return t==null||t===void 0}static IsMacMachine(){return navigator.platform.indexOf("Mac")!==-1}static IsNullOrEmptyGuid(t){return M.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:M.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 vu,yu,Fi,bu,Ef,wu,Cf=T(()=>{"use strict";(function(e){e[e.FormElementNodeChange=0]="FormElementNodeChange",e[e.FormElementAttributeChange=1]="FormElementAttributeChange"})(vu||(vu={}));yu=class{type;targetNode;constructor(t,r){this.type=t,this.targetNode=r}},Fi=class extends yu{key;oldValue;newValue;constructor(t,r,n,i){super(vu.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)}},bu=class extends yu{property;oldValue;newValue;constructor(t,r,n,i){super(vu.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)}},Ef=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()})}},wu=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 Ef(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 Mw={};pn(Mw,{ChartGridMode:()=>ur,ColumnLayoutWidths:()=>LU,ComponentCategory:()=>Eu,ComponentType:()=>Sf,ControlLayoutTypes:()=>Rf,DisplayConditionsInfo:()=>xU,ElementNames:()=>w,ElementProperties:()=>g,ElementType:()=>Df,EntityAttributeProperty:()=>If,EventType:()=>ps,FormActivationState:()=>Pf,FormCanvasServiceScope:()=>HU,FormDesignerSideBarTab:()=>Nf,FormPresentation:()=>_f,FormState:()=>Au,FormType:()=>je,HeaderDensityType:()=>ti,LookUpTable:()=>Qr,MORE_TAB_PREFIX:()=>MU,NavBarChildElementType:()=>Tf,PREVIEW_ID_HEADER_FLYOUT:()=>qU,PREVIEW_ID_HEADER_OVERFLOW_BUTTON:()=>GU,PREVIEW_ID_NAVIGATION_AREA:()=>UU,PREVIEW_ID_QUICKCREATE_ROOT:()=>WU,PREVIEW_ID_TAB:()=>zU,PREVIEW_ID_TAB_LIST:()=>VU,PREVIEW_ID_TAB_PANEL:()=>$U,PropertyModelKeys:()=>Ff,PropertyModelSectionKeys:()=>kU,RELATED_TAB_ID:()=>Lf,RELATED_TAB_PREFIX:()=>BU,SectionDefaultProperties:()=>FU,SectionLayoutTypes:()=>Te,TabContentType:()=>Of,TabDefaultProperties:()=>ri,TabLayoutTypes:()=>_e,TelemetryPropertyNames:()=>jU,UnboundControlPropertyKeys:()=>xf,compositeAddressFields:()=>OU,compositeFieldNames:()=>Qt,compositeFields:()=>RU});var je,Sf,Nf,w,g,Df,Qt,RU,OU,If,Qr,Au,ti,_f,xU,Tf,Pf,_e,FU,ri,Te,Rf,Of,LU,xf,Ff,kU,ps,ur,Lf,MU,BU,UU,$U,qU,VU,GU,zU,WU,jU,Eu,HU,ee=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"})(je||(je={}));(function(e){e[e.Form=0]="Form",e[e.Dialog=1]="Dialog"})(Sf||(Sf={}));(function(e){e[e.Components=0]="Components",e[e.Properties=1]="Properties",e[e.Relationship=2]="Relationship",e[e.BusinessRules=3]="BusinessRules"})(Nf||(Nf={}));(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"})(w||(w={}));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"})(Df||(Df={}));Qt={fullname:"fullname",yomifullname:"yomifullname",address1_composite:"address1_composite",address2_composite:"address2_composite",address3_composite:"address3_composite",billto:"billto_composite",shipto:"shipto_composite"},RU=[Qt.fullname,Qt.yomifullname,Qt.address1_composite,Qt.address2_composite,Qt.address3_composite,Qt.billto,Qt.shipto],OU=[Qt.address1_composite,Qt.address2_composite,Qt.address3_composite,Qt.billto,Qt.shipto];(function(e){e[e.IsValidForForm=0]="IsValidForForm",e[e.IsValidForCreate=1]="IsValidForCreate"})(If||(If={}));(function(e){e[e.DependencyFieldTable=0]="DependencyFieldTable",e[e.LockedFieldTable=1]="LockedFieldTable"})(Qr||(Qr={}));(function(e){e[e.Published=0]="Published",e[e.Draft=1]="Draft",e[e.New=2]="New",e[e.SaveAs=3]="SaveAs"})(Au||(Au={}));(function(e){e.Low="Low",e.HighReadOnlyValues="HighReadOnlyValues",e.HighWithControls="HighWithControls"})(ti||(ti={}));(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(_f||(_f={}));xU={TopOrderFormId:"topOrderFormId",NextDisplayOrder:"nextDisplayOrder"};(function(e){e[e.NavBarRelationShipItem=0]="NavBarRelationShipItem",e[e.NavBarItem=1]="NavBarItem"})(Tf||(Tf={}));(function(e){e[e.InActive=0]="InActive",e[e.Active=1]="Active"})(Pf||(Pf={}));(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"})(_e||(_e={}));FU={ShowLabel:"false",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_"},ri={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"})(Te||(Te={}));(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"})(Rf||(Rf={}));(function(e){e.cardSections="cardSections",e.singleComponent="singleComponent",e.default="default",e.expandAvailableSpace="expandAvailableSpace"})(Of||(Of={}));LU={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"})(xf||(xf={}));(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"})(Ff||(Ff={}));kU={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"})(ps||(ps={}));(function(e){e.All="All",e.Chart="Chart",e.Grid="Grid"})(ur||(ur={}));Lf="tab_related3b554255-7717-4d17-bb7f-9936fb1e75ca",MU="more_tab_",BU="related_tab_",UU="preview_id_navigation_area",$U="tab-section",qU="headerFieldsFlyout",VU="tablist",GU="header_overflowButton",zU="tab",WU="quickCreateRoot",jU={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"})(Eu||(Eu={}));HU="CellCanvasServiceScope"});var Bw={};pn(Bw,{Attribute:()=>Cu,FormElementNode:()=>H});var Cu,H,tt=T(()=>{"use strict";$e();ht();Cf();ee();We();Cu=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-${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(w.form);r&&r.raiseMetadataChange(t)}trackPropertyAddition(t,r){this.trackPropertyCollectionChange(()=>{this.properties.push(new Cu(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 Fi(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 Fi(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 Fi(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 bu(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 Fi(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:M.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 w.formCell:let t=this.getAncestor(w.formSection);return t||(t=this.getAncestor(w.formHeader),t)||(t=this.getAncestor(w.formFooter),t)?t:null;case w.formSection:return this.getAncestor(w.formTab);case w.formTab:return this.getAncestor(w.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(w.form);return t?t.changeTracker():null}}});var Uw={};pn(Uw,{ControlClassId:()=>I,ControlNamePrefixes:()=>Su,getControlDisplayNames:()=>KU});function KU(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,Su,Li=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={}));Su={[I.WebResourceHTMLControl]:"WebResource",[I.WebResourceImageControl]:"WebResource",[I.IframeControl]:"IFRAME",[I.SearchWidgetControl]:"Search widget",[I.SubgridControl]:"Subgrid",[I.TimelineControl]:"Timeline",[I.QuickViewControl]:"QuickviewControl"}});var ki=y((bQ,qw)=>{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{}}}),$w=function(){return fs};Object.setPrototypeOf($w,fs);qw.exports=$w});var Et,Cn,Vw,Gw,Fa=T(()=>{"use strict";Et="cds-designer-models",Cn="FormCustomControl",Vw="FormCell",Gw="Form"});var La,Ct,ms=T(()=>{"use strict";La=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}},Ct=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 Mi,kf=T(()=>{"use strict";ms();ee();Mi=class e{static lockedFieldCount=new Ct;static dependencyFieldCount=new Ct;static getNecessaryLookUpTable(t){switch(t){case Qr.DependencyFieldTable:return e.dependencyFieldCount;case Qr.LockedFieldTable:return e.lockedFieldCount}}static initCanvasLockedFieldLookUp(t){switch(t){case Qr.DependencyFieldTable:e.dependencyFieldCount=new Ct;case Qr.LockedFieldTable:e.lockedFieldCount=new Ct}}}});var Nu,zw=T(()=>{"use strict";We();$e();ee();tt();Nu=class extends H{constructor(t){super(w.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(w.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 jw,Hw,St,x,Ww,ni,Bi,ka,Mf,Bf,Ma=T(()=>{"use strict";jw={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"},Hw={GroupDefinition:"GroupDefinition"},St={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"})(x||(x={}));(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"})(Ww||(Ww={}));(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"})(ni||(ni={}));(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"})(Bi||(Bi={}));(function(e){e[e.Bound=0]="Bound",e[e.Input=1]="Input",e[e.Output=2]="Output"})(ka||(ka={}));Mf=[x.LookupCustomer,x.LookupOwner,x.LookupPartyList,x.LookupRegarding,x.LookupSimple],Bf=[x.WholeNone,x.WholeDuration,x.WholeLanguage,x.WholeTimeZone,x.FP,x.Decimal]});function Sn(){return Xr||(Xr=window._makerConfig,Xr&&window?.location?.search?.indexOf("useProductionConfig")>-1&&(Xr={...Xr,region:"prod",graphQLEndpoint:"https://graph.make.powerapps.com/"}),Xr?.region==="prod"&&(Xr={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/"}}},...Xr}),Xr||{aadClientId:"a8f7a65c-f5ba-4859-b2d6-df772c264e9d",location:"cus",region:"test",publicPath:"/",graphQLEndpoint:"https://graph.make.test.powerapps.com/"})}var Xr,Du=T(()=>{"use strict";});function Kw(e,t,r){if(!e)return Iu.has(e)||(window._ppux?.log?.("PPUX/Geo/NonExistent",{eventType:"Trace",team:"Shell",severity:"Error",errorCode:"GeoIsEmpty"}),Iu.add("")),!1;if(e){if(e=e.toLowerCase(),Iu.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}}),Iu.add(e),!1}return!0}function JU(e){return Kw(e,Uf,"Location dictionary")?Uf[e.toLowerCase()]:"us"}function QU(){let e=Sn().location.toLowerCase();return Kw(e,Uf,"Current location dictionary")?e:"us"}var Iu,Uf,FQ,Jw=T(()=>{"use strict";Du();Iu=new Set,Uf={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"};FQ=JU(QU())});var G,kQ,Qw=T(()=>{"use strict";G={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"},kQ={[G.USWest]:{geoName:"us",regionShortName:"wus"},[G.USCentral]:{geoName:"us",regionShortName:"cus"},[G.USEast]:{geoName:"us",regionShortName:"eus"},[G.USEast2]:{geoName:"us",regionShortName:"eus2"},[G.USWestCentral]:{geoName:"us",regionShortName:"wcus"},[G.USWest2]:{geoName:"us",regionShortName:"wus2"},[G.USSouthCentral]:{geoName:"br",regionShortName:"scus"},[G.BrazilSouth]:{geoName:"br",regionShortName:"sbr"},[G.UKSouth]:{geoName:"uk",regionShortName:"suk"},[G.UKWest]:{geoName:"uk",regionShortName:"wuk"},[G.JapanEast]:{geoName:"jp",regionShortName:"ejp"},[G.JapanWest]:{geoName:"jp",regionShortName:"wjp"},[G.IndiaCentral]:{geoName:"in",regionShortName:"cin"},[G.IndiaSouth]:{geoName:"in",regionShortName:"sin"},[G.ItalyNorth]:{geoName:"it",regionShortName:"nit"},[G.GermanyWestCentral]:{geoName:"de",regionShortName:"wcde"},[G.GermanyNorth]:{geoName:"de",regionShortName:"nde"},[G.EuropeNorth]:{geoName:"eu",regionShortName:"neu"},[G.EuropeWest]:{geoName:"eu",regionShortName:"weu"},[G.AustraliaEast]:{geoName:"au",regionShortName:"eau"},[G.AustraliaSouthEast]:{geoName:"au",regionShortName:"seau"},[G.AsiaSouthEast]:{geoName:"as",regionShortName:"seas"},[G.AsiaEast]:{geoName:"as",regionShortName:"eas"},[G.CanadaCentral]:{geoName:"ca",regionShortName:"cca"},[G.CanadaEast]:{geoName:"ca",regionShortName:"eca"},[G.SouthAfricaNorth]:{geoName:"za",regionShortName:"nza"},[G.SouthAfricaWest]:{geoName:"za",regionShortName:"wza"},[G.FranceCentral]:{geoName:"fr",regionShortName:"cfr"},[G.FranceSouth]:{geoName:"fr",regionShortName:"sfr"},[G.UAENorth]:{geoName:"ae",regionShortName:"nae"},[G.UAECentral]:{geoName:"ae",regionShortName:"cae"},[G.SwedenCentral]:{geoName:"se",regionShortName:"cse"},[G.SwitzerlandNorth]:{geoName:"ch",regionShortName:"nch"},[G.SwitzerlandWest]:{geoName:"ch",regionShortName:"wch"},[G.NorwayEast]:{geoName:"no",regionShortName:"eno"},[G.NorwayWest]:{geoName:"no",regionShortName:"wno"},[G.KoreaCentral]:{geoName:"kr",regionShortName:"ckr"},[G.KoreaSouth]:{geoName:"kr",regionShortName:"skr"},[G.SingaporeSouthEast]:{geoName:"sg",regionShortName:"seas"},[G.PolandCentral]:{geoName:"pl",regionShortName:"cpl"},[G.QatarCentral]:{geoName:"qa",regionShortName:"cqa"},[G.NewZealandNorth]:{geoName:"nz",regionShortName:"nnz"},[G.GovernmentUSTexas]:{geoName:"us",regionShortName:"ugtx"},[G.GovernmentUSVirginia]:{geoName:"us",regionShortName:"ugva"},[G.GovernmentUSDodCentral]:{regionShortName:"udc"},[G.GovernmentUSDodEast]:{regionShortName:"ude"},[G.ChinaEast]:{regionShortName:"cne"},[G.ChinaEast2]:{regionShortName:"cne2"},[G.ChinaEast3]:{regionShortName:"cne3"},[G.ChinaNorth]:{regionShortName:"cnn"},[G.ChinaNorth2]:{regionShortName:"cnn2"},[G.ChinaNorth3]:{regionShortName:"cnn3"},[G.UssecEast]:{geoName:"us",regionShortName:"erx"},[G.UssecWest]:{geoName:"us",regionShortName:"wrx"},[G.UsnatEast]:{geoName:"us",regionShortName:"eex"},[G.UsnatWest]:{geoName:"us",regionShortName:"wex"}}});var Xw=T(()=>{"use strict";Du();});var hs=T(()=>{"use strict";Du();Jw();Qw();Xw();});function gs(e,t){return Yw?Yw.isOverridden(e,t):{overridden:!1}}var Yw,vs=T(()=>{"use strict";});var $f=T(()=>{"use strict";hs();vs();});function XU(e,t){let{region:r}=Sn();return()=>{let n=e.settings[t];if(n.allowOverrides){let s=gs(e.packageName,t);if(s.overridden)return typeof s.value=="string"?YU(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 YU(e){return isNaN(Number(e))?e==="true"?!0:e==="false"?!1:e:Number(e)}function ZU(e){let t=e.packageName;if(_u.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=>Vf(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=>!Pu(i))){let i=`error parsing settings config for package ${t}, setting ${r} has invalid region`;throw console.error(i),new Error(i)}})}function ys(e){ZU(e);let t={};return Object.keys(e.settings).forEach(r=>{t[r]={enumerable:!0,get:XU(e,r)}}),_u.set(e.packageName,e),Object.defineProperties({},t)}function qf(e,t){return _u.has(e)?!!_u.get(e).settings[t]:!1}var _u,Tu=T(()=>{"use strict";hs();vs();Gf();bs();_u=new Map});function Zw(e,t){let{region:r}=Sn();return()=>{let n=gs(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 e$(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=>qf(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=>!Pu(i))){let i=`error parsing feature gates config for package ${t}, feature ${r} has invalid region`;throw console.error(i),new Error(i)}})}function zf(e){e$(e);let t={};Object.keys(e.features).forEach(i=>{t[i]={enumerable:!0,configurable:!0,get:Zw(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:Zw(e,a.toString())}}),Object.defineProperties(r,i),n.clear()}},Ru.set(e.packageName,e),Object.defineProperties(r,t)}function Vf(e,t){return Ru.has(e)?!!Ru.get(e).features[t]:!1}var Ru,Gf=T(()=>{"use strict";hs();bs();vs();Tu();Ru=new Map});var tA=y((sX,eA)=>{"use strict";eA.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 iA=y(Wf=>{"use strict";var t$=Object.prototype.hasOwnProperty,r$;function rA(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch{return null}}function nA(e){try{return encodeURIComponent(e)}catch{return null}}function n$(e){for(var t=/([^=?#&]+)=?([^&]*)/g,r={},n;n=t.exec(e);){var i=rA(n[1]),a=rA(n[2]);i===null||a===null||i in r||(r[i]=a)}return r}function i$(e,t){t=t||"";var r=[],n,i;typeof t!="string"&&(t="?");for(i in e)if(t$.call(e,i)){if(n=e[i],!n&&(n===null||n===r$||isNaN(n))&&(n=""),i=nA(i),n=nA(n),i===null||n===null)continue;r.push(i+"="+n)}return r.length?t+r.join("&"):""}Wf.stringify=i$;Wf.parse=n$});var Kf=y((uX,cA)=>{"use strict";var oA=tA(),Ou=iA(),sA=/[\n\r\t]/g,a$=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,o$=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,s$=/^[a-zA-Z]:/,l$=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;function Hf(e){return(e||"").toString().replace(l$,"")}var jf=[["#","hash"],["?","query"],function(t,r){return Yr(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]],aA={hash:1,query:1};function lA(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 Zr(unescape(e.pathname),{});else if(i==="string"){n=new Zr(e,{});for(a in aA)delete n[a]}else if(i==="object"){for(a in e)a in aA||(n[a]=e[a]);n.slashes===void 0&&(n.slashes=a$.test(e.href))}return n}function Yr(e){return e==="file:"||e==="ftp:"||e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function uA(e,t){e=Hf(e),e=e.replace(sA,""),t=t||{};var r=o$.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)):Yr(n)?s=r[4]:n?i&&(s=s.slice(2)):o>=2&&Yr(t.protocol)&&(s=r[4]),{protocol:n,slashes:i||Yr(n),slashesCount:o,rest:s}}function u$(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 Zr(e,t,r){if(e=Hf(e),e=e.replace(sA,""),!(this instanceof Zr))return new Zr(e,t,r);var n,i,a,o,s,l,u=jf.slice(),c=typeof t,d=this,p=0;for(c!=="object"&&c!=="string"&&(r=t,t=null),r&&typeof r!="function"&&(r=Ou.parse),t=lA(t),i=uA(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||s$.test(e))||!i.slashes&&(i.protocol||i.slashesCount<2||!Yr(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=u$(d.pathname,t.pathname)),d.pathname.charAt(0)!=="/"&&Yr(d.protocol)&&(d.pathname="/"+d.pathname),oA(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:"&&Yr(d.protocol)&&d.host?d.protocol+"//"+d.host:"null",d.href=d.toString()}function c$(e,t,r){var n=this;switch(e){case"query":typeof t=="string"&&t.length&&(t=(r||Ou.parse)(t)),n[e]=t;break;case"port":n[e]=t,oA(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<jf.length;o++){var s=jf[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:"&&Yr(n.protocol)&&n.host?n.protocol+"//"+n.host:"null",n.href=n.toString(),n}function d$(e){(!e||typeof e!="function")&&(e=Ou.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||Yr(r.protocol)?"//":"");return r.username?(a+=r.username,r.password&&(a+=":"+r.password),a+="@"):r.password?(a+=":"+r.password,a+="@"):r.protocol!=="file:"&&Yr(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}Zr.prototype={set:c$,toString:d$};Zr.extractProtocol=uA;Zr.location=lA;Zr.trimLeft=Hf;Zr.qs=Ou;cA.exports=Zr});var p$,dA=T(()=>{"use strict";p$=ce(Kf());});function Jf(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 xu=T(()=>{"use strict";});var Qf,Xf,Yf=T(()=>{"use strict";xu();Qf=class{features=new Map;register(t,r){let n=Jf(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()}},Xf=new Qf});var Zf=T(()=>{"use strict";});function Pu(e){return f$.has(e)}var f$,bs=T(()=>{"use strict";$f();Gf();Tu();vs();$f();dA();Yf();xu();Zf();f$=new Set(["tie","test","prod","preview","preprod","gov","high","dod","mooncake","ex","rx"])});var m$,pA=T(()=>{"use strict";bs();m$=ys({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 Fu,U,z,Ui,Ba,Lu,fA,mA,em,ws=T(()=>{"use strict";ms();Fu=class{name;constructor(t){this.name=t}toString(){return this.name}getName(){return this.name}getDisplayNameResourceKey(){return em.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"})(U||(U={}));(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"})(z||(z={}));Ui=class extends Fu{constructor(t){super(t)}static get None(){return"None"}static get SystemRequired(){return"SystemRequired"}static get ApplicationRequired(){return"ApplicationRequired"}static get Recommended(){return"Recommended"}},Ba=class e extends Fu{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?Lu.Persistent:parseInt(Lu[this.name])}};(function(e){e[e.Persistent=0]="Persistent",e[e.Calculated=1]="Calculated",e[e.Rollup=2]="Rollup"})(Lu||(Lu={}));(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"})(fA||(fA={}));(function(e){e[e.Attribute=0]="Attribute",e[e.Organization=1]="Organization",e[e.Currency=2]="Currency"})(mA||(mA={}));em=class e{static resourceKeyMap=e.initResourceKeyMap();static initResourceKeyMap(){let t=new La;return t.add(U.TwoOptions,"SystemCustomization.type.bit.label"),t.add(U.Customer,"SystemCustomization.type.customer.label"),t.add(U.CustomerType,"SystemCustomization.type.customer.label"),t.add(U.DateTime,"SystemCustomization.type.datetime.label"),t.add(U.DecimalNumber,"SystemCustomization.type.decimal.label"),t.add(U.FloatingPointNumber,"SystemCustomization.type.float.label"),t.add(U.WholeNumber,"SystemCustomization.type.int.label"),t.add(U.LookupType,"SystemCustomization.type.lookup.label"),t.add(U.Lookup,"SystemCustomization.type.lookup.label"),t.add(U.MultipleLineofText,"SystemCustomization.type.ntext.label"),t.add(U.Currency,"SystemCustomization.type.money.label"),t.add(U.Owner,"SystemCustomization.type.owner.label"),t.add(U.OwnerType,"SystemCustomization.type.owner.label"),t.add(U.PartyList,"SystemCustomization.type.partylist.label"),t.add(U.PartyListType,"SystemCustomization.type.partylist.label"),t.add(U.OptionSet,"SystemCustomization.type.picklist.label"),t.add(U.State,"SystemCustomization.type.state.label"),t.add(U.Status,"SystemCustomization.type.status.label"),t.add(U.SingleLineofText,"SystemCustomization.type.nvarchar.label"),t.add(U.UniqueIdentifier,"SystemCustomization.type.uniqueidentifier.label"),t.add(U.UniqueIdentifierType,"SystemCustomization.type.uniqueidentifiertype.label"),t.add(U.CalendarRulesType,"SystemCustomization.type.calendarrules.label"),t.add(U.VirtualType,"SystemCustomization.type.virtual.label"),t.add(U.BigInt,"SystemCustomization.type.bigint.label"),t.add(U.ManagedPropertyType,"SystemCustomization.type.managedproperty.label"),t.add(U.EntityNameType,"SystemCustomization.type.entityname.label"),t.add(U.Image,"SystemCustomization.type.image.label"),t.add(U.MultiSelectOptionSet,"SystemCustomization.type.multiselectpicklist.label"),t.add(U.PrimaryNameAttributeType,"SystemCustomization.type.primaryname.label"),t.add(U.LookupType,"SystemCustomization.type.lookuptype.label"),t.add(U.Subject,"SystemCustomization.type.subject.label"),t.add(z.Email,"SystemCustomization.String.Format.email"),t.add(z.Text,"SystemCustomization.String.Format.text"),t.add(z.TextArea,"SystemCustomization.String.Format.textarea"),t.add(z.Url,"SystemCustomization.String.Format.url"),t.add(z.TickerSymbol,"SystemCustomization.String.Format.tickersymbol"),t.add(z.PhoneticGuide,"SystemCustomization.String.Format.phoneticguide"),t.add(z.VersionNumber,"SystemCustomization.String.Format.versionnumber"),t.add(z.Phone,"SystemCustomization.String.Format.phone"),t.add(z.None,"SystemCustomization.Integer.Format."),t.add(z.Duration,"SystemCustomization.Integer.Format.duration"),t.add(z.TimeZone,"SystemCustomization.Integer.Format.timezone"),t.add(z.Language,"SystemCustomization.Integer.Format.language"),t.add(z.Locale,"SystemCustomization.Integer.Format.language"),t.add(z.DateOnly,"SystemCustomization.DateTime.Format.date"),t.add(z.DateAndTime,"SystemCustomization.DateTime.Format.datetime"),t.add(z.Regarding,"SystemCustomization.Lookup.Format.regarding"),t.add(Ba.Persistent,"SystemCustomization.String.Source.persistent"),t.add(Ba.Calculated,"SystemCustomization.String.Source.calculated"),t.add(Ba.Rollup,"SystemCustomization.String.Source.rollup"),t.add(Ba.None,"SystemCustomization.String.Source.none"),t}static getDisplayNameResourceKey(t){return e.resourceKeyMap.getValue(t)}}});var yA,rm,Ua,$i,tm,ku,$a,Nn,De,hA,gA,vA,Ir=T(()=>{"use strict";yA={ThreeEqColumn_FirstColumn:34,ThreeEqColumn_SecondColumn:33,ThreeEqColumn_ThirdColumn:33,FiveEqColumn:20},rm={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"})(Ua||(Ua={}));(function(e){e.Left="Left",e.Right="Right",e.Center="Center"})($i||($i={}));(function(e){e[e.Mobile=0]="Mobile",e[e.Tablet=1]="Tablet",e[e.Web=2]="Web"})(tm||(tm={}));ku=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"})($a||($a={}));Nn=class{static StartTag="<"},De={ShowLabel:"true",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_",labelAlignment:$i.Left,labelPosition:$a.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"})(hA||(hA={}));(function(e){e.TabWithLockedFieldRemoval="TabWithLockedFieldRemoval",e.SectionWithLockedFieldRemoval="SectionWithLockedFieldRemoval",e.LockedSectionRemoval="LockedSectionRemoval",e.LockedFieldRemoval="LockedFieldRemoval",e.RequiredFieldRemoval="RequiredFieldRemoval",e.LastRemainingTab="LastRemainingTab",e.UnknownRemoval="UnknownRemoval"})(gA||(gA={}));(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"})(vA||(vA={}))});var nm,bA=T(()=>{"use strict";(function(e){e.DefaultValue="defaultValue",e.Loaded="loaded"})(nm||(nm={}))});var EA,h$,wA,sY,lY,As,AA,uY,cY,CA=T(()=>{"use strict";EA=ce(ki());$e();Fa();pA();ws();Ir();Ma();ee();h$=ce(Ai());bA();(function(e){e.Model="Model",e.Canvas="Canvas",e.CustomPages="CustomPages"})(wA||(wA={}));sY={Read:Bi.Read,Edit:Bi.Edit,Both:Bi.Both,Container:Bi.Container},lY={input:ka.Input,bound:ka.Bound,output:ka.Output};(function(e){e[e.dataset=0]="dataset",e[e.property=1]="property",e[e.groups=2]="groups",e[e.group=3]="group"})(As||(As={}));(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"})(AA||(AA={}));uY=new Set([x.Currency,x.Decimal,x.FP,x.Multiple,x.SingleLineEmail,x.SingleLinePhone,x.SingleLineText,x.SingleLineTextArea,x.SingleLineURL,x.SingleLineTickerSymbol,x.WholeNone,x.WholeDuration,x.WholeLanguage,x.WholeTimeZone,x.Enum,x.LookupSimple,x.LookupCustomer,x.LookupOwner,x.LookupPartyList,x.LookupRegarding,x.TwoOptions,x.Boolean,x.PowerBIReport,x.DateAndTimeDateAndTime,x.DateAndTimeDateOnly,x.OptionSet,x.MultiSelectOptionSet,x.CardForm]),cY={numbers:[x.WholeNone,x.FP,x.Decimal,x.Currency],text:[x.SingleLineText,x.SingleLineTextArea,x.Multiple],lookup:[x.LookupSimple,x.LookupCustomer,x.LookupOwner,x.LookupPartyList,x.LookupRegarding],dates:[x.DateAndTimeDateOnly,x.DateAndTimeDateAndTime],allFields:[x.TwoOptions,x.DateAndTimeDateOnly,x.DateAndTimeDateAndTime,x.FP,x.Decimal,x.WholeNone,x.WholeDuration,x.WholeTimeZone,x.WholeLanguage,x.LookupSimple,x.LookupCustomer,x.LookupOwner,x.LookupPartyList,x.LookupRegarding,x.Multiple,x.OptionSet,x.SingleLineText,x.SingleLineTextArea,x.SingleLineEmail,x.SingleLineURL,x.SingleLineTickerSymbol,x.SingleLinePhone]}});var _r,Mu,SA=T(()=>{"use strict";_r=ce(ki());We();$e();ht();Fa();Ma();CA();ws();ee();tt();Ir();Mu=class extends H{constructor(t){super(w.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(St.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===St.name)?.value}getParameterChildrenValues(t,r,n){if(this.isDataSet(t)){let i=r.find(u=>u.key===St.name)?.value,a={Name:i,Type:x.Grid,Columns:[]},l=this.getParameters().get(St.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(Nn.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:Hw.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===As.dataset?a.get(St.dataset)?.some(f=>this.getDatasetName(f)===d)||r.push({Name:d,Value:{Name:d,Columns:[],Type:x.Grid}}):c.propertyType===As.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,_r.trackInfoTrace)(Et,{eventName:`${Cn}/parametersToJSON`,eventData:{message:`Configuration metadata for custom control parameter ${o} is not available for custom control : ${this.name}.`}}),r=[];break}}}else(0,_r.trackErrorTrace)(Et,{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,_r.trackErrorTrace)(Et,{eventName:`${Cn}/parametersToJSON`,eventData:{message:"Custom Control Manifest not found"}},new Error(`No custom control manifest found for ${this.name}`))}catch(n){(0,_r.trackErrorTrace)(Et,{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===St.name)?.value;if(a)return this.getParameterChildrenValues(t,r);{let s=new Error(`No dataset manifest info for ${o}`);(0,_r.trackErrorTrace)(Et,{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=>!Mf.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===ni.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(jw.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:M.IsStrictTrue(this.getFormComponentValueByParameterName(g.AllowFilterOff)),DisableQuickFind:M.IsStrictTrue(this.getFormComponentValueByParameterName(g.DisableQuickFind)),EnableViewPicker:!M.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,_r.trackErrorTrace)(Et,{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,_r.trackErrorTrace)(Et,{eventName:`${Cn}/parameterJSON`,eventData:{message:"Missing property type info"}},p)}else{let l=new Error(`No property manifest info for ${t}`);(0,_r.trackWarningTrace)(Et,{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 U.Customer:return x.LookupCustomer;case U.Owner:return x.LookupOwner;case U.PartyList:return x.LookupPartyList;default:return n===z.Regarding?x.LookupRegarding:x.LookupSimple}}isLookupType(t){return Mf.includes(t)}isNumberTypeProperty(t,r){return Bf.includes(r)||t.ofTypeGroup.some(n=>Bf.includes(n))}isDataSet(t){return St.dataset===t}isGroups(t){return!!t[0].getAllProperties().find(n=>n.key==="isGroup"&&n.value==="true")}}});var j,im=T(()=>{"use strict";j=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 $,qa,He,Bu=T(()=>{"use strict";We();ms();$e();ht();ws();Li();im();Ir();$=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"}},qa=class{static get RelationshipAssistant(){return"3ff9a528-dd50-4aca-8f10-2e5ed73513ad"}static get PredictiveLeadScoring(){return"6f503f2a-d033-4106-b62c-f8f2e5f01a57"}},He=class e{static FieldControlIds=e.initializeFieldControls();static UnboundControlIds=e.initializeUnboundControls();static ControlsAllowedForReferencePanel=e.initializeReferencePanelControls();static ControlsAllowedForFooter=e.initializeFooterControls();static CustomControlIdMap=new Ct;static initializeFieldControls(){let t=new Ct,r=e.getControlName(U.SingleLineofText,z.Phone);t.add(r,new L($.PhoneNumberControl));let n=e.getControlName(U.SingleLineofText,z.TextArea);t.add(n,new L($.TextAreaControl));let i=e.getControlName(U.SingleLineofText,z.Text);t.add(i,new L($.TextBoxControl));let a=e.getControlName(U.SingleLineofText,z.Email);t.add(a,new L($.EmailAddressControl));let o=e.getControlName(U.SingleLineofText,z.Url);t.add(o,new L($.UrlControl));let s=e.getControlName(U.SingleLineofText,z.TickerSymbol);t.add(s,new L($.TickerControl));let l=e.getControlName(U.SingleLineofText,z.PhoneticGuide);t.add(l,new L($.TextBoxControl));let u=e.getControlName(U.WholeNumber,z.Duration);t.add(u,new L($.DurationControl));let c=e.getControlName(U.WholeNumber,z.Language);t.add(c,new L($.LanguagePickerControl));let d=e.getControlName(U.WholeNumber,z.TimeZone);t.add(d,new L($.TimeZonePicklistControl));let p=e.getControlName(U.WholeNumber,z.None);t.add(p,new L($.IntegerControl));let f=e.getControlName(U.DateTime,z.DateOnly);t.add(f,new L($.DateTimeControl));let m=e.getControlName(U.DateTime,z.DateAndTime);t.add(m,new L($.DateTimeControl));let h=e.getControlName(U.LookupType,z.None);t.add(h,new L($.LookupControl));let v=e.getControlName(U.CustomerType,z.None);t.add(v,new L($.LookupControl));let b=e.getControlName(U.FloatingPointNumber,z.None);t.add(b,new L($.FloatControl));let E=e.getControlName(U.DecimalNumber,z.None);t.add(E,new L($.DecimalControl));let C=e.getControlName(U.Currency,z.None);t.add(C,new L($.MoneyControl));let N=e.getControlName(U.MultipleLineofText,z.None);t.add(N,new L($.TextAreaControl));let R=e.getControlName(U.MultipleLineofText,z.Text);t.add(R,new L($.TextAreaControl));let O=e.getControlName(U.MultipleLineofText,z.TextArea);t.add(O,new L($.TextAreaControl));let F=e.getControlName(U.MultipleLineofText,z.Email);t.add(F,new L($.EmailBodyControl));let k=e.getControlName(U.OptionSet,z.None);t.add(k,new L($.PicklistControl));let P=e.getControlName(U.TwoOptions,z.None);t.add(P,new L($.RadioControl));let V=e.getControlName(U.Image,z.None);t.add(V,new L($.WebResourceImageControl));let q=e.getControlName(U.Image,z.None);t.add(q,new L($.WebResourceHtmlControl));let ze=e.getControlName(U.TwoOptions,"Radio");t.add(ze,new L($.RadioControl));let Tt=e.getControlName(U.TwoOptions,"CheckBox");t.add(Tt,new L($.CheckBoxControl));let Be=e.getControlName(U.TwoOptions,"List");t.add(Be,new L($.PicklistControl));let Qe=e.getControlName(U.State,z.None);t.add(Qe,new L($.PicklistControl));let Z=e.getControlName(U.Status,z.None);t.add(Z,new L($.PicklistStatusControl));let ye=e.getControlName(U.OwnerType,z.None);t.add(ye,new L($.LookupControl));let xe=e.getControlName(U.PartyListType,z.None);t.add(xe,new L($.PartyListControl));let $n=e.getControlName(U.LookupType,z.Regarding);t.add($n,new L($.RegardingControl));let nr=e.getControlName(U.MultiSelectOptionSet,z.None);return t.add(nr,new L($.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===$.CustomControl}static initializeUnboundControls(){let t=new Ct;return t.add($.ACIControl,j.ACIControl),t.add($.IframeControl,j.IframeControl),t.add($.SearchWidgetControl,j.SearchWidgetControl),t.add($.MapsControl,j.MapsControl),t.add($.QuickFormCollectionControl,j.QuickFormCollectionControl),t.add($.GridControl,j.SubGridControl),t.add($.WebResourceImageControl,j.WebResourceImageControl),t.add($.WebResourceHtmlControl,j.WebResourceHtmlControl),t.add($.ReferencePanelSearchWidget,j.SearchWidgetControl),t.add($.ReferencePanelQuickFormCollectionControl,j.QuickFormCollectionControl),t.add($.ReferencePanelSubgridControl,j.SubGridControl),t.add($.TimerControl,j.TimerControl),t.add($.TimeLineControl,j.NotesControl),t.add($.TimeLineControlUC,j.NotesControl),t.add($.SocialInsightControl,j.SocialInsightControl),t.add(qa.RelationshipAssistant,j.CustomControl),t}static initializeReferencePanelControls(){let t=new Ct;return t.add($.IframeControl,j.IframeControl),t.add($.ReferencePanelSearchWidget,j.SearchWidgetControl),t.add($.ReferencePanelQuickFormCollectionControl,j.QuickFormCollectionControl),t.add($.ReferencePanelSubgridControl,j.SubGridControl),t.add($.WebResourceHtmlControl,j.WebResourceHtmlControl),t.add($.WebResourceImageControl,j.WebResourceHtmlControl),t}static initializeFooterControls(){let t=new La;return t.add(Ua.IFRAME,!0),t.add(Ua.SPACER,!0),t.add(Ua.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(De.referencePanelNamePrefix)===0}static isUnboundFormControlByIdentifier(t){return _.IsNullOrUndefined(t)||_.IsNullOrUndefined(t.guidString)?!1:e.UnboundControlIds.containsKey(t.guidString)}static getUnboundFormControlName(t){let r=M.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)?M.EmptyString:e.UnboundControlIds.getValue(t.guidString).toString()}static isSpacerControl(t){return t===$.SpacerControl}static GetRowSpan(t){let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===$.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 j.IframeControl:case j.ACIControl:case j.SocialInsightControl:return 6;case j.SubGridControl:case j.CustomControl:return 4;case j.WebResourceImageControl:return 15;case j.WebResourceHtmlControl:return 15;case j.MapsControl:return 8;case j.SearchWidgetControl:return 10;case j.NotesControl:case j.TimeLineControl:return 15;case j.TimerControl:return 2;default:}}static isLookUpControl(t){return!_.IsNullOrUndefined(t)&&t.ClassId.guidString===$.LookupControl}static isRelationshipAssistantOrLeadScoringControl(t){return!_.IsNullOrUndefined(t)&&e.isRelationshipAssistantOrLeadScoring(t.UniqueId)}static isRelationshipAssistantOrLeadScoring(t){return!_.IsNullOrUndefined(t)&&(t.guidString===qa.RelationshipAssistant||t.guidString===qa.PredictiveLeadScoring)}static isRelationshipAssistantControl(t){return!_.IsNullOrUndefined(t)&&e.isRelationshipAssistant(t.UniqueId)}static isRelationshipAssistant(t){return!_.IsNullOrUndefined(t)&&t.guidString===qa.RelationshipAssistant}static getUniqueIdentifierForControl(t){if(_.IsNullOrUndefined(t))return null;let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===$.CustomControl&&!_.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}return r}}});var Uu,NA=T(()=>{"use strict";Uu=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 qi,Va,DA,IA,ii,_A,TA,am=T(()=>{"use strict";(function(e){e[e.Center=0]="Center",e[e.Left=1]="Left",e[e.Right=2]="Right"})(qi||(qi={}));(function(e){e[e.Left=0]="Left",e[e.Top=1]="Top"})(Va||(Va={}));(function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle"})(DA||(DA={}));(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"})(IA||(IA={}));(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"})(ii||(ii={}));(function(e){e[e.None=0]="None",e[e.SystemRequired=1]="SystemRequired",e[e.ApplicationRequired=2]="ApplicationRequired",e[e.Recommended=3]="Recommended"})(_A||(_A={}));(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"})(TA||(TA={}))});var Ga,PA=T(()=>{"use strict";bs();Ga=zf({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 RA(e){return{...e,extractConfig:t=>g$(t,Object.keys(e.fallback))}}function g$(e,t){let r={};for(let n of t)typeof e[n]<"u"&&(r[n]=e[n]);return r}var om=T(()=>{"use strict";});var sm=y((BY,xA)=>{var Es=new Proxy(function(){return Es},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Es},apply:function(){return Es},construct:function(){return{}}}),OA=function(){return Es};Object.setPrototypeOf(OA,Es);xA.exports=OA});var kA=y((UY,LA)=>{var Cs=new Proxy(function(){return Cs},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Cs},apply:function(){return Cs},construct:function(){return{}}}),FA=function(){return Cs};Object.setPrototypeOf(FA,Cs);LA.exports=FA});var lm=y(($Y,BA)=>{var Ss=new Proxy(function(){return Ss},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Ss},apply:function(){return Ss},construct:function(){return{}}}),MA=function(){return Ss};Object.setPrototypeOf(MA,Ss);BA.exports=MA});var $A=y((qY,UA)=>{function v$(){this.__data__=[],this.size=0}UA.exports=v$});var za=y((VY,qA)=>{function y$(e,t){return e===t||e!==e&&t!==t}qA.exports=y$});var Ns=y((GY,VA)=>{var b$=za();function w$(e,t){for(var r=e.length;r--;)if(b$(e[r][0],t))return r;return-1}VA.exports=w$});var zA=y((zY,GA)=>{var A$=Ns(),E$=Array.prototype,C$=E$.splice;function S$(e){var t=this.__data__,r=A$(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():C$.call(t,r,1),--this.size,!0}GA.exports=S$});var jA=y((WY,WA)=>{var N$=Ns();function D$(e){var t=this.__data__,r=N$(t,e);return r<0?void 0:t[r][1]}WA.exports=D$});var KA=y((jY,HA)=>{var I$=Ns();function _$(e){return I$(this.__data__,e)>-1}HA.exports=_$});var QA=y((HY,JA)=>{var T$=Ns();function P$(e,t){var r=this.__data__,n=T$(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}JA.exports=P$});var Ds=y((KY,XA)=>{var R$=$A(),O$=zA(),x$=jA(),F$=KA(),L$=QA();function Wa(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])}}Wa.prototype.clear=R$;Wa.prototype.delete=O$;Wa.prototype.get=x$;Wa.prototype.has=F$;Wa.prototype.set=L$;XA.exports=Wa});var ZA=y((JY,YA)=>{var k$=Ds();function M$(){this.__data__=new k$,this.size=0}YA.exports=M$});var tE=y((QY,eE)=>{function B$(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}eE.exports=B$});var nE=y((XY,rE)=>{function U$(e){return this.__data__.get(e)}rE.exports=U$});var aE=y((YY,iE)=>{function $$(e){return this.__data__.has(e)}iE.exports=$$});var um=y((ZY,oE)=>{var q$=typeof global=="object"&&global&&global.Object===Object&&global;oE.exports=q$});var Tr=y((eZ,sE)=>{var V$=um(),G$=typeof self=="object"&&self&&self.Object===Object&&self,z$=V$||G$||Function("return this")();sE.exports=z$});var Is=y((tZ,lE)=>{var W$=Tr(),j$=W$.Symbol;lE.exports=j$});var pE=y((rZ,dE)=>{var uE=Is(),cE=Object.prototype,H$=cE.hasOwnProperty,K$=cE.toString,_s=uE?uE.toStringTag:void 0;function J$(e){var t=H$.call(e,_s),r=e[_s];try{e[_s]=void 0;var n=!0}catch{}var i=K$.call(e);return n&&(t?e[_s]=r:delete e[_s]),i}dE.exports=J$});var mE=y((nZ,fE)=>{var Q$=Object.prototype,X$=Q$.toString;function Y$(e){return X$.call(e)}fE.exports=Y$});var Vi=y((iZ,vE)=>{var hE=Is(),Z$=pE(),eq=mE(),tq="[object Null]",rq="[object Undefined]",gE=hE?hE.toStringTag:void 0;function nq(e){return e==null?e===void 0?rq:tq:gE&&gE in Object(e)?Z$(e):eq(e)}vE.exports=nq});var Dn=y((aZ,yE)=>{function iq(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}yE.exports=iq});var $u=y((oZ,bE)=>{var aq=Vi(),oq=Dn(),sq="[object AsyncFunction]",lq="[object Function]",uq="[object GeneratorFunction]",cq="[object Proxy]";function dq(e){if(!oq(e))return!1;var t=aq(e);return t==lq||t==uq||t==sq||t==cq}bE.exports=dq});var AE=y((sZ,wE)=>{var pq=Tr(),fq=pq["__core-js_shared__"];wE.exports=fq});var SE=y((lZ,CE)=>{var cm=AE(),EE=(function(){var e=/[^.]+$/.exec(cm&&cm.keys&&cm.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function mq(e){return!!EE&&EE in e}CE.exports=mq});var dm=y((uZ,NE)=>{var hq=Function.prototype,gq=hq.toString;function vq(e){if(e!=null){try{return gq.call(e)}catch{}try{return e+""}catch{}}return""}NE.exports=vq});var IE=y((cZ,DE)=>{var yq=$u(),bq=SE(),wq=Dn(),Aq=dm(),Eq=/[\\^$.*+?()[\]{}|]/g,Cq=/^\[object .+?Constructor\]$/,Sq=Function.prototype,Nq=Object.prototype,Dq=Sq.toString,Iq=Nq.hasOwnProperty,_q=RegExp("^"+Dq.call(Iq).replace(Eq,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Tq(e){if(!wq(e)||bq(e))return!1;var t=yq(e)?_q:Cq;return t.test(Aq(e))}DE.exports=Tq});var TE=y((dZ,_E)=>{function Pq(e,t){return e?.[t]}_E.exports=Pq});var ai=y((pZ,PE)=>{var Rq=IE(),Oq=TE();function xq(e,t){var r=Oq(e,t);return Rq(r)?r:void 0}PE.exports=xq});var qu=y((fZ,RE)=>{var Fq=ai(),Lq=Tr(),kq=Fq(Lq,"Map");RE.exports=kq});var Ts=y((mZ,OE)=>{var Mq=ai(),Bq=Mq(Object,"create");OE.exports=Bq});var LE=y((hZ,FE)=>{var xE=Ts();function Uq(){this.__data__=xE?xE(null):{},this.size=0}FE.exports=Uq});var ME=y((gZ,kE)=>{function $q(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}kE.exports=$q});var UE=y((vZ,BE)=>{var qq=Ts(),Vq="__lodash_hash_undefined__",Gq=Object.prototype,zq=Gq.hasOwnProperty;function Wq(e){var t=this.__data__;if(qq){var r=t[e];return r===Vq?void 0:r}return zq.call(t,e)?t[e]:void 0}BE.exports=Wq});var qE=y((yZ,$E)=>{var jq=Ts(),Hq=Object.prototype,Kq=Hq.hasOwnProperty;function Jq(e){var t=this.__data__;return jq?t[e]!==void 0:Kq.call(t,e)}$E.exports=Jq});var GE=y((bZ,VE)=>{var Qq=Ts(),Xq="__lodash_hash_undefined__";function Yq(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=Qq&&t===void 0?Xq:t,this}VE.exports=Yq});var WE=y((wZ,zE)=>{var Zq=LE(),e3=ME(),t3=UE(),r3=qE(),n3=GE();function ja(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])}}ja.prototype.clear=Zq;ja.prototype.delete=e3;ja.prototype.get=t3;ja.prototype.has=r3;ja.prototype.set=n3;zE.exports=ja});var KE=y((AZ,HE)=>{var jE=WE(),i3=Ds(),a3=qu();function o3(){this.size=0,this.__data__={hash:new jE,map:new(a3||i3),string:new jE}}HE.exports=o3});var QE=y((EZ,JE)=>{function s3(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}JE.exports=s3});var Ps=y((CZ,XE)=>{var l3=QE();function u3(e,t){var r=e.__data__;return l3(t)?r[typeof t=="string"?"string":"hash"]:r.map}XE.exports=u3});var ZE=y((SZ,YE)=>{var c3=Ps();function d3(e){var t=c3(this,e).delete(e);return this.size-=t?1:0,t}YE.exports=d3});var tC=y((NZ,eC)=>{var p3=Ps();function f3(e){return p3(this,e).get(e)}eC.exports=f3});var nC=y((DZ,rC)=>{var m3=Ps();function h3(e){return m3(this,e).has(e)}rC.exports=h3});var aC=y((IZ,iC)=>{var g3=Ps();function v3(e,t){var r=g3(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}iC.exports=v3});var Vu=y((_Z,oC)=>{var y3=KE(),b3=ZE(),w3=tC(),A3=nC(),E3=aC();function Ha(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])}}Ha.prototype.clear=y3;Ha.prototype.delete=b3;Ha.prototype.get=w3;Ha.prototype.has=A3;Ha.prototype.set=E3;oC.exports=Ha});var lC=y((TZ,sC)=>{var C3=Ds(),S3=qu(),N3=Vu(),D3=200;function I3(e,t){var r=this.__data__;if(r instanceof C3){var n=r.__data__;if(!S3||n.length<D3-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new N3(n)}return r.set(e,t),this.size=r.size,this}sC.exports=I3});var pm=y((PZ,uC)=>{var _3=Ds(),T3=ZA(),P3=tE(),R3=nE(),O3=aE(),x3=lC();function Ka(e){var t=this.__data__=new _3(e);this.size=t.size}Ka.prototype.clear=T3;Ka.prototype.delete=P3;Ka.prototype.get=R3;Ka.prototype.has=O3;Ka.prototype.set=x3;uC.exports=Ka});var dC=y((RZ,cC)=>{var F3="__lodash_hash_undefined__";function L3(e){return this.__data__.set(e,F3),this}cC.exports=L3});var fC=y((OZ,pC)=>{function k3(e){return this.__data__.has(e)}pC.exports=k3});var hC=y((xZ,mC)=>{var M3=Vu(),B3=dC(),U3=fC();function Gu(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new M3;++t<r;)this.add(e[t])}Gu.prototype.add=Gu.prototype.push=B3;Gu.prototype.has=U3;mC.exports=Gu});var vC=y((FZ,gC)=>{function $3(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}gC.exports=$3});var bC=y((LZ,yC)=>{function q3(e,t){return e.has(t)}yC.exports=q3});var fm=y((kZ,wC)=>{var V3=hC(),G3=vC(),z3=bC(),W3=1,j3=2;function H3(e,t,r,n,i,a){var o=r&W3,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&j3?new V3: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(!G3(t,function(b,E){if(!z3(f,E)&&(m===b||i(m,b,r,n,a)))return f.push(E)})){p=!1;break}}else if(!(m===h||i(m,h,r,n,a))){p=!1;break}}return a.delete(e),a.delete(t),p}wC.exports=H3});var mm=y((MZ,AC)=>{var K3=Tr(),J3=K3.Uint8Array;AC.exports=J3});var CC=y((BZ,EC)=>{function Q3(e){var t=-1,r=Array(e.size);return e.forEach(function(n,i){r[++t]=[i,n]}),r}EC.exports=Q3});var NC=y((UZ,SC)=>{function X3(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n}),r}SC.exports=X3});var PC=y(($Z,TC)=>{var DC=Is(),IC=mm(),Y3=za(),Z3=fm(),e4=CC(),t4=NC(),r4=1,n4=2,i4="[object Boolean]",a4="[object Date]",o4="[object Error]",s4="[object Map]",l4="[object Number]",u4="[object RegExp]",c4="[object Set]",d4="[object String]",p4="[object Symbol]",f4="[object ArrayBuffer]",m4="[object DataView]",_C=DC?DC.prototype:void 0,hm=_C?_C.valueOf:void 0;function h4(e,t,r,n,i,a,o){switch(r){case m4:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case f4:return!(e.byteLength!=t.byteLength||!a(new IC(e),new IC(t)));case i4:case a4:case l4:return Y3(+e,+t);case o4:return e.name==t.name&&e.message==t.message;case u4:case d4:return e==t+"";case s4:var s=e4;case c4:var l=n&r4;if(s||(s=t4),e.size!=t.size&&!l)return!1;var u=o.get(e);if(u)return u==t;n|=n4,o.set(e,t);var c=Z3(s(e),s(t),n,i,a,o);return o.delete(e),c;case p4:if(hm)return hm.call(e)==hm.call(t)}return!1}TC.exports=h4});var OC=y((qZ,RC)=>{function g4(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}RC.exports=g4});var oi=y((VZ,xC)=>{var v4=Array.isArray;xC.exports=v4});var LC=y((GZ,FC)=>{var y4=OC(),b4=oi();function w4(e,t,r){var n=t(e);return b4(e)?n:y4(n,r(e))}FC.exports=w4});var MC=y((zZ,kC)=>{function A4(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}kC.exports=A4});var UC=y((WZ,BC)=>{function E4(){return[]}BC.exports=E4});var VC=y((jZ,qC)=>{var C4=MC(),S4=UC(),N4=Object.prototype,D4=N4.propertyIsEnumerable,$C=Object.getOwnPropertySymbols,I4=$C?function(e){return e==null?[]:(e=Object(e),C4($C(e),function(t){return D4.call(e,t)}))}:S4;qC.exports=I4});var zC=y((HZ,GC)=>{function _4(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}GC.exports=_4});var si=y((KZ,WC)=>{function T4(e){return e!=null&&typeof e=="object"}WC.exports=T4});var HC=y((JZ,jC)=>{var P4=Vi(),R4=si(),O4="[object Arguments]";function x4(e){return R4(e)&&P4(e)==O4}jC.exports=x4});var gm=y((QZ,QC)=>{var KC=HC(),F4=si(),JC=Object.prototype,L4=JC.hasOwnProperty,k4=JC.propertyIsEnumerable,M4=KC((function(){return arguments})())?KC:function(e){return F4(e)&&L4.call(e,"callee")&&!k4.call(e,"callee")};QC.exports=M4});var YC=y((XZ,XC)=>{function B4(){return!1}XC.exports=B4});var zu=y((Rs,Ja)=>{var U4=Tr(),$4=YC(),tS=typeof Rs=="object"&&Rs&&!Rs.nodeType&&Rs,ZC=tS&&typeof Ja=="object"&&Ja&&!Ja.nodeType&&Ja,q4=ZC&&ZC.exports===tS,eS=q4?U4.Buffer:void 0,V4=eS?eS.isBuffer:void 0,G4=V4||$4;Ja.exports=G4});var Wu=y((YZ,rS)=>{var z4=9007199254740991,W4=/^(?:0|[1-9]\d*)$/;function j4(e,t){var r=typeof e;return t=t??z4,!!t&&(r=="number"||r!="symbol"&&W4.test(e))&&e>-1&&e%1==0&&e<t}rS.exports=j4});var vm=y((ZZ,nS)=>{var H4=9007199254740991;function K4(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=H4}nS.exports=K4});var aS=y((eee,iS)=>{var J4=Vi(),Q4=vm(),X4=si(),Y4="[object Arguments]",Z4="[object Array]",eV="[object Boolean]",tV="[object Date]",rV="[object Error]",nV="[object Function]",iV="[object Map]",aV="[object Number]",oV="[object Object]",sV="[object RegExp]",lV="[object Set]",uV="[object String]",cV="[object WeakMap]",dV="[object ArrayBuffer]",pV="[object DataView]",fV="[object Float32Array]",mV="[object Float64Array]",hV="[object Int8Array]",gV="[object Int16Array]",vV="[object Int32Array]",yV="[object Uint8Array]",bV="[object Uint8ClampedArray]",wV="[object Uint16Array]",AV="[object Uint32Array]",Ce={};Ce[fV]=Ce[mV]=Ce[hV]=Ce[gV]=Ce[vV]=Ce[yV]=Ce[bV]=Ce[wV]=Ce[AV]=!0;Ce[Y4]=Ce[Z4]=Ce[dV]=Ce[eV]=Ce[pV]=Ce[tV]=Ce[rV]=Ce[nV]=Ce[iV]=Ce[aV]=Ce[oV]=Ce[sV]=Ce[lV]=Ce[uV]=Ce[cV]=!1;function EV(e){return X4(e)&&Q4(e.length)&&!!Ce[J4(e)]}iS.exports=EV});var sS=y((tee,oS)=>{function CV(e){return function(t){return e(t)}}oS.exports=CV});var uS=y((Os,Qa)=>{var SV=um(),lS=typeof Os=="object"&&Os&&!Os.nodeType&&Os,xs=lS&&typeof Qa=="object"&&Qa&&!Qa.nodeType&&Qa,NV=xs&&xs.exports===lS,ym=NV&&SV.process,DV=(function(){try{var e=xs&&xs.require&&xs.require("util").types;return e||ym&&ym.binding&&ym.binding("util")}catch{}})();Qa.exports=DV});var ju=y((ree,pS)=>{var IV=aS(),_V=sS(),cS=uS(),dS=cS&&cS.isTypedArray,TV=dS?_V(dS):IV;pS.exports=TV});var bm=y((nee,fS)=>{var PV=zC(),RV=gm(),OV=oi(),xV=zu(),FV=Wu(),LV=ju(),kV=Object.prototype,MV=kV.hasOwnProperty;function BV(e,t){var r=OV(e),n=!r&&RV(e),i=!r&&!n&&xV(e),a=!r&&!n&&!i&&LV(e),o=r||n||i||a,s=o?PV(e.length,String):[],l=s.length;for(var u in e)(t||MV.call(e,u))&&!(o&&(u=="length"||i&&(u=="offset"||u=="parent")||a&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||FV(u,l)))&&s.push(u);return s}fS.exports=BV});var Hu=y((iee,mS)=>{var UV=Object.prototype;function $V(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||UV;return e===r}mS.exports=$V});var wm=y((aee,hS)=>{function qV(e,t){return function(r){return e(t(r))}}hS.exports=qV});var vS=y((oee,gS)=>{var VV=wm(),GV=VV(Object.keys,Object);gS.exports=GV});var bS=y((see,yS)=>{var zV=Hu(),WV=vS(),jV=Object.prototype,HV=jV.hasOwnProperty;function KV(e){if(!zV(e))return WV(e);var t=[];for(var r in Object(e))HV.call(e,r)&&r!="constructor"&&t.push(r);return t}yS.exports=KV});var Fs=y((lee,wS)=>{var JV=$u(),QV=vm();function XV(e){return e!=null&&QV(e.length)&&!JV(e)}wS.exports=XV});var ES=y((uee,AS)=>{var YV=bm(),ZV=bS(),eG=Fs();function tG(e){return eG(e)?YV(e):ZV(e)}AS.exports=tG});var SS=y((cee,CS)=>{var rG=LC(),nG=VC(),iG=ES();function aG(e){return rG(e,iG,nG)}CS.exports=aG});var IS=y((dee,DS)=>{var NS=SS(),oG=1,sG=Object.prototype,lG=sG.hasOwnProperty;function uG(e,t,r,n,i,a){var o=r&oG,s=NS(e),l=s.length,u=NS(t),c=u.length;if(l!=c&&!o)return!1;for(var d=l;d--;){var p=s[d];if(!(o?p in t:lG.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 b=e[p],E=t[p];if(n)var C=o?n(E,b,p,t,e,a):n(b,E,p,e,t,a);if(!(C===void 0?b===E||i(b,E,r,n,a):C)){h=!1;break}v||(v=p=="constructor")}if(h&&!v){var N=e.constructor,R=t.constructor;N!=R&&"constructor"in e&&"constructor"in t&&!(typeof N=="function"&&N instanceof N&&typeof R=="function"&&R instanceof R)&&(h=!1)}return a.delete(e),a.delete(t),h}DS.exports=uG});var TS=y((pee,_S)=>{var cG=ai(),dG=Tr(),pG=cG(dG,"DataView");_S.exports=pG});var RS=y((fee,PS)=>{var fG=ai(),mG=Tr(),hG=fG(mG,"Promise");PS.exports=hG});var xS=y((mee,OS)=>{var gG=ai(),vG=Tr(),yG=gG(vG,"Set");OS.exports=yG});var LS=y((hee,FS)=>{var bG=ai(),wG=Tr(),AG=bG(wG,"WeakMap");FS.exports=AG});var GS=y((gee,VS)=>{var Am=TS(),Em=qu(),Cm=RS(),Sm=xS(),Nm=LS(),qS=Vi(),Xa=dm(),kS="[object Map]",EG="[object Object]",MS="[object Promise]",BS="[object Set]",US="[object WeakMap]",$S="[object DataView]",CG=Xa(Am),SG=Xa(Em),NG=Xa(Cm),DG=Xa(Sm),IG=Xa(Nm),Gi=qS;(Am&&Gi(new Am(new ArrayBuffer(1)))!=$S||Em&&Gi(new Em)!=kS||Cm&&Gi(Cm.resolve())!=MS||Sm&&Gi(new Sm)!=BS||Nm&&Gi(new Nm)!=US)&&(Gi=function(e){var t=qS(e),r=t==EG?e.constructor:void 0,n=r?Xa(r):"";if(n)switch(n){case CG:return $S;case SG:return kS;case NG:return MS;case DG:return BS;case IG:return US}return t});VS.exports=Gi});var XS=y((vee,QS)=>{var Dm=pm(),_G=fm(),TG=PC(),PG=IS(),zS=GS(),WS=oi(),jS=zu(),RG=ju(),OG=1,HS="[object Arguments]",KS="[object Array]",Ku="[object Object]",xG=Object.prototype,JS=xG.hasOwnProperty;function FG(e,t,r,n,i,a){var o=WS(e),s=WS(t),l=o?KS:zS(e),u=s?KS:zS(t);l=l==HS?Ku:l,u=u==HS?Ku:u;var c=l==Ku,d=u==Ku,p=l==u;if(p&&jS(e)){if(!jS(t))return!1;o=!0,c=!1}if(p&&!c)return a||(a=new Dm),o||RG(e)?_G(e,t,r,n,i,a):TG(e,t,l,r,n,i,a);if(!(r&OG)){var f=c&&JS.call(e,"__wrapped__"),m=d&&JS.call(t,"__wrapped__");if(f||m){var h=f?e.value():e,v=m?t.value():t;return a||(a=new Dm),i(h,v,r,n,a)}}return p?(a||(a=new Dm),PG(e,t,r,n,i,a)):!1}QS.exports=FG});var tN=y((yee,eN)=>{var LG=XS(),YS=si();function ZS(e,t,r,n,i){return e===t?!0:e==null||t==null||!YS(e)&&!YS(t)?e!==e&&t!==t:LG(e,t,r,n,ZS,i)}eN.exports=ZS});var nN=y((bee,rN)=>{var kG=tN();function MG(e,t){return kG(e,t)}rN.exports=MG});var Im=y((wee,iN)=>{var BG=ai(),UG=(function(){try{var e=BG(Object,"defineProperty");return e({},"",{}),e}catch{}})();iN.exports=UG});var Ju=y((Aee,oN)=>{var aN=Im();function $G(e,t,r){t=="__proto__"&&aN?aN(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}oN.exports=$G});var _m=y((Eee,sN)=>{var qG=Ju(),VG=za();function GG(e,t,r){(r!==void 0&&!VG(e[t],r)||r===void 0&&!(t in e))&&qG(e,t,r)}sN.exports=GG});var uN=y((Cee,lN)=>{function zG(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}}lN.exports=zG});var dN=y((See,cN)=>{var WG=uN(),jG=WG();cN.exports=jG});var gN=y((Ls,Ya)=>{var HG=Tr(),hN=typeof Ls=="object"&&Ls&&!Ls.nodeType&&Ls,pN=hN&&typeof Ya=="object"&&Ya&&!Ya.nodeType&&Ya,KG=pN&&pN.exports===hN,fN=KG?HG.Buffer:void 0,mN=fN?fN.allocUnsafe:void 0;function JG(e,t){if(t)return e.slice();var r=e.length,n=mN?mN(r):new e.constructor(r);return e.copy(n),n}Ya.exports=JG});var bN=y((Nee,yN)=>{var vN=mm();function QG(e){var t=new e.constructor(e.byteLength);return new vN(t).set(new vN(e)),t}yN.exports=QG});var AN=y((Dee,wN)=>{var XG=bN();function YG(e,t){var r=t?XG(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}wN.exports=YG});var CN=y((Iee,EN)=>{function ZG(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}EN.exports=ZG});var DN=y((_ee,NN)=>{var e9=Dn(),SN=Object.create,t9=(function(){function e(){}return function(t){if(!e9(t))return{};if(SN)return SN(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}})();NN.exports=t9});var Tm=y((Tee,IN)=>{var r9=wm(),n9=r9(Object.getPrototypeOf,Object);IN.exports=n9});var TN=y((Pee,_N)=>{var i9=DN(),a9=Tm(),o9=Hu();function s9(e){return typeof e.constructor=="function"&&!o9(e)?i9(a9(e)):{}}_N.exports=s9});var RN=y((Ree,PN)=>{var l9=Fs(),u9=si();function c9(e){return u9(e)&&l9(e)}PN.exports=c9});var FN=y((Oee,xN)=>{var d9=Vi(),p9=Tm(),f9=si(),m9="[object Object]",h9=Function.prototype,g9=Object.prototype,ON=h9.toString,v9=g9.hasOwnProperty,y9=ON.call(Object);function b9(e){if(!f9(e)||d9(e)!=m9)return!1;var t=p9(e);if(t===null)return!0;var r=v9.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&ON.call(r)==y9}xN.exports=b9});var Pm=y((xee,LN)=>{function w9(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}LN.exports=w9});var Rm=y((Fee,kN)=>{var A9=Ju(),E9=za(),C9=Object.prototype,S9=C9.hasOwnProperty;function N9(e,t,r){var n=e[t];(!(S9.call(e,t)&&E9(n,r))||r===void 0&&!(t in e))&&A9(e,t,r)}kN.exports=N9});var BN=y((Lee,MN)=>{var D9=Rm(),I9=Ju();function _9(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?I9(r,s,l):D9(r,s,l)}return r}MN.exports=_9});var $N=y((kee,UN)=>{function T9(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}UN.exports=T9});var VN=y((Mee,qN)=>{var P9=Dn(),R9=Hu(),O9=$N(),x9=Object.prototype,F9=x9.hasOwnProperty;function L9(e){if(!P9(e))return O9(e);var t=R9(e),r=[];for(var n in e)n=="constructor"&&(t||!F9.call(e,n))||r.push(n);return r}qN.exports=L9});var Om=y((Bee,GN)=>{var k9=bm(),M9=VN(),B9=Fs();function U9(e){return B9(e)?k9(e,!0):M9(e)}GN.exports=U9});var WN=y((Uee,zN)=>{var $9=BN(),q9=Om();function V9(e){return $9(e,q9(e))}zN.exports=V9});var XN=y(($ee,QN)=>{var jN=_m(),G9=gN(),z9=AN(),W9=CN(),j9=TN(),HN=gm(),KN=oi(),H9=RN(),K9=zu(),J9=$u(),Q9=Dn(),X9=FN(),Y9=ju(),JN=Pm(),Z9=WN();function e5(e,t,r,n,i,a,o){var s=JN(e,r),l=JN(t,r),u=o.get(l);if(u){jN(e,r,u);return}var c=a?a(s,l,r+"",e,t,o):void 0,d=c===void 0;if(d){var p=KN(l),f=!p&&K9(l),m=!p&&!f&&Y9(l);c=l,p||f||m?KN(s)?c=s:H9(s)?c=W9(s):f?(d=!1,c=G9(l,!0)):m?(d=!1,c=z9(l,!0)):c=[]:X9(l)||HN(l)?(c=s,HN(s)?c=Z9(s):(!Q9(s)||J9(s))&&(c=j9(l))):d=!1}d&&(o.set(l,c),i(c,l,n,a,o),o.delete(l)),jN(e,r,c)}QN.exports=e5});var xm=y((qee,ZN)=>{var t5=pm(),r5=_m(),n5=dN(),i5=XN(),a5=Dn(),o5=Om(),s5=Pm();function YN(e,t,r,n,i){e!==t&&n5(t,function(a,o){if(i||(i=new t5),a5(a))i5(e,t,o,r,YN,n,i);else{var s=n?n(s5(e,o),a,o+"",e,t,i):void 0;s===void 0&&(s=a),r5(e,o,s)}},o5)}ZN.exports=YN});var Fm=y((Vee,eD)=>{function l5(e){return e}eD.exports=l5});var rD=y((Gee,tD)=>{function u5(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)}tD.exports=u5});var aD=y((zee,iD)=>{var c5=rD(),nD=Math.max;function d5(e,t,r){return t=nD(t===void 0?e.length-1:t,0),function(){for(var n=arguments,i=-1,a=nD(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),c5(e,this,s)}}iD.exports=d5});var sD=y((Wee,oD)=>{function p5(e){return function(){return e}}oD.exports=p5});var cD=y((jee,uD)=>{var f5=sD(),lD=Im(),m5=Fm(),h5=lD?function(e,t){return lD(e,"toString",{configurable:!0,enumerable:!1,value:f5(t),writable:!0})}:m5;uD.exports=h5});var pD=y((Hee,dD)=>{var g5=800,v5=16,y5=Date.now;function b5(e){var t=0,r=0;return function(){var n=y5(),i=v5-(n-r);if(r=n,i>0){if(++t>=g5)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}dD.exports=b5});var mD=y((Kee,fD)=>{var w5=cD(),A5=pD(),E5=A5(w5);fD.exports=E5});var gD=y((Jee,hD)=>{var C5=Fm(),S5=aD(),N5=mD();function D5(e,t){return N5(S5(e,t,C5),e+"")}hD.exports=D5});var yD=y((Qee,vD)=>{var I5=za(),_5=Fs(),T5=Wu(),P5=Dn();function R5(e,t,r){if(!P5(r))return!1;var n=typeof t;return(n=="number"?_5(r)&&T5(t,r.length):n=="string"&&t in r)?I5(r[t],e):!1}vD.exports=R5});var Lm=y((Xee,bD)=>{var O5=gD(),x5=yD();function F5(e){return O5(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&&x5(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})}bD.exports=F5});var AD=y((Yee,wD)=>{var L5=xm(),k5=Lm(),M5=k5(function(e,t,r,n){L5(e,t,r,n)});wD.exports=M5});var cr,ks=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"})(cr||(cr={}))});function CD(e,t,r="PROD"){let n=i=>`ShellSettings_ECS_ClientCache_${e}_${ED.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 ED,B5,SD=T(()=>{"use strict";ED=ce(lm()),B5=ce(sm());});var km,ND=T(()=>{"use strict";Tu();km=ys({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 ID,_D,TD,PD,Mm,U5,Qu,DD,Bm=T(()=>{"use strict";ID=ce(sm()),_D=ce(kA()),TD=ce(lm()),PD=ce(nN()),Mm=ce(AD());ks();SD();ND();U5=60*1e3,Qu=class{clientName;logger;ecsEndpoint;resolveLoadingPromise;loadingPromise=new Promise(t=>this.resolveLoadingPromise=t);_status=cr.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"?km.prodEcsEndpoint:km.integrationEcsEndpoint}client=new _D.default;init=async({clientVersion:t,getFilters:r,cacheStorage:n=ID.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:[TD.EcsConfigType.Default],hosts:[this.ecsEndpoint],initialAppActiveState:!0,getEcsParameters:o,databaseInterface:CD(this.clientName,n,this.endpointType),...a}),this.client.requestUpdate(),this._status===cr.NotLoaded&&(this._status=cr.Initialized)}catch(s){this._status=cr.Error,this.resolveLoadingPromise(),this.logEvent("FeaturesClient/initializationFailed",{ecsClientName:this.clientName,error:s},"Error")}i&&window.setInterval(()=>this.client.requestUpdate(),i*U5)};getConfig=t=>{let r=this.getMergedClientConfigByTeamName(t.teamName),n=r?t.extractConfig(r):{};return(0,Mm.default)({},t.fallback,n,t.override,DD)};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,PD.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,Mm.default)({},this.client.getConfig()?.config,this.clientConfigOverride,DD);getMergedClientConfigByTeamName=t=>this.getMergedClientConfig()?.[t];handleConfigUpdated=()=>{let t=this.client.getConfig();if(t===void 0)return;this.resolveLoadingPromise(),this._status=cr.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})}},DD=(e,t)=>{if(Array.isArray(t))return t}});var OD=y((ste,RD)=>{"use strict";var $5=()=>{let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e};RD.exports=$5});var Um=y((lte,FD)=>{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{}}}),xD=function(){return Ms};Object.setPrototypeOf(xD,Ms);FD.exports=xD});var MD=y((ute,kD)=>{var Bs=new Proxy(function(){return Bs},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Bs},apply:function(){return Bs},construct:function(){return{}}}),LD=function(){return Bs};Object.setPrototypeOf(LD,Bs);kD.exports=LD});var zD=y((cte,GD)=>{"use strict";var $m=MD(),q5={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},V5={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},G5={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},qD={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},qm={};qm[$m.ForwardRef]=G5;qm[$m.Memo]=qD;function BD(e){return $m.isMemo(e)?qD:qm[e.$$typeof]||q5}var z5=Object.defineProperty,W5=Object.getOwnPropertyNames,UD=Object.getOwnPropertySymbols,j5=Object.getOwnPropertyDescriptor,H5=Object.getPrototypeOf,$D=Object.prototype;function VD(e,t,r){if(typeof t!="string"){if($D){var n=H5(t);n&&n!==$D&&VD(e,n,r)}var i=W5(t);UD&&(i=i.concat(UD(t)));for(var a=BD(e),o=BD(t),s=0;s<i.length;++s){var l=i[s];if(!V5[l]&&!(r&&r[l])&&!(o&&o[l])&&!(a&&a[l])){var u=j5(t,l);try{z5(e,l,u)}catch{}}}}return e}GD.exports=VD});function jD(e,t,r){let[n,i]=(0,Za.useState)(e.getConfig(t));return(0,Za.useEffect)(()=>{if(!r?.subscribe&&e.status===cr.ConfigsLoaded)return;let a=e.subscribe(t,o=>{i(o),r?.subscribe||a.unsubscribe()});return a?.unsubscribe},[]),n}function HD(e){return function(t,r){return jD(e,t,r)}}function KD(e,t,r,n){let i=a=>{let o=jD(e,t,n),s={...a,...o};return Za.default.createElement(r,{...s})};return(0,WD.default)(i,r),i.displayName=`WithFeature(${r.name})`,i}function JD(e,t,r,n){return t.reduce((i,a)=>KD(e,a,i,n),r)}function QD(e){return function(t,r,n){return KD(e,t,r,n)}}var WD,Za,Vm=T(()=>{"use strict";WD=ce(zD()),Za=ce(Um());ks();});var YD=y((fte,XD)=>{var K5=xm(),J5=Lm(),Q5=J5(function(e,t,r){K5(e,t,r)});XD.exports=Q5});var Xu=y((mte,ZD)=>{var X5=Vi(),Y5=si(),Z5="[object Symbol]";function e8(e){return typeof e=="symbol"||Y5(e)&&X5(e)==Z5}ZD.exports=e8});var tI=y((hte,eI)=>{var t8=oi(),r8=Xu(),n8=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,i8=/^\w*$/;function a8(e,t){if(t8(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||r8(e)?!0:i8.test(e)||!n8.test(e)||t!=null&&e in Object(t)}eI.exports=a8});var iI=y((gte,nI)=>{var rI=Vu(),o8="Expected a function";function Gm(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(o8);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(Gm.Cache||rI),r}Gm.Cache=rI;nI.exports=Gm});var oI=y((vte,aI)=>{var s8=iI(),l8=500;function u8(e){var t=s8(e,function(n){return r.size===l8&&r.clear(),n}),r=t.cache;return t}aI.exports=u8});var lI=y((yte,sI)=>{var c8=oI(),d8=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,p8=/\\(\\)?/g,f8=c8(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(d8,function(r,n,i,a){t.push(i?a.replace(p8,"$1"):n||r)}),t});sI.exports=f8});var cI=y((bte,uI)=>{function m8(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}uI.exports=m8});var gI=y((wte,hI)=>{var dI=Is(),h8=cI(),g8=oi(),v8=Xu(),y8=1/0,pI=dI?dI.prototype:void 0,fI=pI?pI.toString:void 0;function mI(e){if(typeof e=="string")return e;if(g8(e))return h8(e,mI)+"";if(v8(e))return fI?fI.call(e):"";var t=e+"";return t=="0"&&1/e==-y8?"-0":t}hI.exports=mI});var yI=y((Ate,vI)=>{var b8=gI();function w8(e){return e==null?"":b8(e)}vI.exports=w8});var wI=y((Ete,bI)=>{var A8=oi(),E8=tI(),C8=lI(),S8=yI();function N8(e,t){return A8(e)?e:E8(e,t)?[e]:C8(S8(e))}bI.exports=N8});var EI=y((Cte,AI)=>{var D8=Xu(),I8=1/0;function _8(e){if(typeof e=="string"||D8(e))return e;var t=e+"";return t=="0"&&1/e==-I8?"-0":t}AI.exports=_8});var NI=y((Ste,SI)=>{var T8=Rm(),P8=wI(),R8=Wu(),CI=Dn(),O8=EI();function x8(e,t,r,n){if(!CI(e))return e;t=P8(t,e);for(var i=-1,a=t.length,o=a-1,s=e;s!=null&&++i<a;){var l=O8(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=CI(c)?c:R8(t[i+1])?[]:{})}T8(s,l,u),s=s[l]}return e}SI.exports=x8});var II=y((Nte,DI)=>{var F8=NI();function L8(e,t,r){return e==null?e:F8(e,t,r)}DI.exports=L8});function RI(e){let{query:t}=(0,PI.default)(window.location.href,!0);return M8(e,t),e}function M8(e,t){let r=k8+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+OI,u={};if(a===r)u=s;else if(a.startsWith(l)){let c=a.substring(l.length);(0,TI.default)(u,c,s)}(0,_I.default)(i,u)}catch{}}),Object.keys(i).length>0&&e.overrideClientConfig(i)}var _I,TI,PI,OI,k8,xI=T(()=>{"use strict";_I=ce(YD()),TI=ce(II()),PI=ce(Kf());OI=".",k8="ecs"+OI});function Zu(e,t,r){let n=RI(new Qu(e,t,r));function i(a){(0,Yu.useEffect)(()=>{n.init(a)},[])}return{featuresClient:n,createFeature:U8(n),useFeaturesClientInitParams:i,withFeatures:(a,o,s)=>JD(n,a,o,s)}}function U8(e){let t=HD(e),r=QD(e);return function(i){let a=RA(i);return a.getConfig=()=>e.getConfig(a),a.isLoaded=()=>e.status===cr.ConfigsLoaded,Xf.register(a,e.clientName),{useFeature:o=>t(a,o),withFeature:(o,s)=>r(a,o,s),feature:a}}}var B8,Yu,zm=T(()=>{"use strict";B8=ce(OD()),Yu=ce(Um());om();Bm();ks();Vm();xI();Yf();});var FI=T(()=>{"use strict";om();Bm();zm();ks();Vm();xu();Zf();});function ec(e){return{logEvent:(t,r,n)=>{switch(n){case"Error":(0,eo.trackErrorTrace)(e,{eventName:t,eventData:r});break;case"Warning":(0,eo.trackWarningTrace)(e,{eventName:t,eventData:r});break;default:(0,eo.trackInfoTrace)(e,{eventName:t,eventData:r});break}}}}var eo,Wm=T(()=>{"use strict";eo=ce(ki());});var Wte,jte,Hte,LI=T(()=>{"use strict";FI();Wm();({featuresClient:Wte,createFeature:jte,useFeaturesClientInitParams:Hte}=Zu("PowerApps-Shell-Test",ec("shell-features")))});var BI=y((Jte,MI)=>{var Us=new Proxy(function(){return Us},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Us},apply:function(){return Us},construct:function(){return{}}}),kI=function(){return Us};Object.setPrototypeOf(kI,Us);MI.exports=kI});var $8,q8,UI=T(()=>{"use strict";hs();$8=ce(BI()),q8=ce(ki());});var $I=T(()=>{"use strict";LI();Wm();UI();});var ire,to,are,qI=T(()=>{"use strict";$I();zm();({featuresClient:ire,createFeature:to,useFeaturesClientInitParams:are}=Zu("PowerApps-MakerPortal",ec("powerapps-features")))});var VI,GI,ure,cre,dre,pre,jm=T(()=>{"use strict";PA();qI();({feature:VI}=to({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:Ga.enableAutoInsertionOfCellInRow}})),{feature:GI}=to({teamName:"MakerPortal",owners:["aansu"],description:"Enable the one grid events for form designer",createdOn:"08/21/2024",fallback:{enableOneGridEventsForFormDesigner:Ga.enableOneGridEvents}}),{feature:ure}=to({teamName:"MakerPortal",owners:["adekulkarni"],description:"Disables PBI components and cleans them up from the form",createdOn:"01/03/2023",fallback:{enableFallbackFormTemplate:Ga.disablePBIComponents}}),{feature:cre}=to({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:Ga.enableAgentResponse}}),{feature:dre,useFeature:pre}=to({teamName:"MakerPortal",owners:["aansu"],description:"Enables delayed localization of custom control",createdOn:"06/08/2025",fallback:{enableDelayedLocalizationForCustomControls:Ga.enableDelayedLocalizationForCustomControls}})});var jI=y((mre,WI)=>{var $s=new Proxy(function(){return $s},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:$s},apply:function(){return $s},construct:function(){return{}}}),zI=function(){return $s};Object.setPrototypeOf(zI,$s);WI.exports=zI});var gt,li=T(()=>{"use strict";We();$e();ht();Bu();ee();tt();gt=class extends H{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 H(w.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(w.formControl);return t?t.disabled:!1}set readonly(t){let r=this.getFirstChild(w.formControl);r&&(r.disabled=t)}get allowfilteroff(){let t=this.getFirstChild(w.formControl);if(t)return t.getParam(g.AllowFilterOff)==="true"}set allowfilteroff(t){let r=this.getFirstChild(w.formControl);r&&!this.IsUnboundControl&&r.setParameter(g.AllowFilterOff,t)}get autoresolve(){let t=this.getFirstChild(w.formControl);if(t)return t.getParam(g.AutoResolve)==="true"}set autoresolve(t){let r=this.getFirstChild(w.formControl);r&&!this.IsUnboundControl&&r.setParameter(g.AutoResolve,t)}get defaultviewid(){let t=this.getFirstChild(w.formControl);return t?t.getParam(g.DefaultViewId):M.EmptyString}set defaultviewid(t){let r=this.getFirstChild(w.formControl);r&&!this.IsUnboundControl&&r.setParameter(g.DefaultViewId,t)}get dependentattributename(){let t=this.getFirstChild(w.formControl);return t?t.getParam(g.DependentAttributeName):M.EmptyString}set dependentattributename(t){let r=this.getFirstChild(w.formControl);r&&!this.IsUnboundControl&&r.setParameter(g.DependentAttributeName,t)}get dependentattributetype(){let t=this.getFirstChild(w.formControl);return t?t.getParam(g.DependentAttributeType):M.EmptyString}set dependentattributetype(t){let r=this.getFirstChild(w.formControl);r&&!this.IsUnboundControl&&r.setParameter(g.DependentAttributeType,t)}get disablequickfind(){let t=this.getFirstChild(w.formControl);if(t)return t.getParam(g.DisableQuickFind)==="true"}set disablequickfind(t){let r=this.getFirstChild(w.formControl);r&&!this.IsUnboundControl&&r.setParameter(g.DisableQuickFind,t)}get disableviewpicker(){let t=this.getFirstChild(w.formControl);if(t)return t.getParam(g.DisableViewPicker)==="true"}set disableviewpicker(t){let r=this.getFirstChild(w.formControl);r&&!this.IsUnboundControl&&r.setParameter(g.DisableViewPicker,t)}get filterrelationshipname(){let t=this.getFirstChild(w.formControl);return t?t.getParam(g.FilterRelationshipName):M.EmptyString}set filterrelationshipname(t){let r=this.getFirstChild(w.formControl);r&&!this.IsUnboundControl&&r.setParameter(g.FilterRelationshipName,t)}get availableviewids(){let t=this.getFirstChild(w.formControl);return t?t.getParam(g.AvailableViewIds):M.EmptyString}set availableviewids(t){let r=this.getFirstChild(w.formControl);r&&!this.IsUnboundControl&&r.setParameter(g.AvailableViewIds,t)}get IsUnboundControl(){let t=this.getFirstChild(w.formControl);if(t&&t.ClassId){let r=He.getUniqueIdentifierForControl(t);return!_.IsNullOrUndefined(r)&&He.isUnboundFormControlByIdentifier(r)}else return!1}IsAllowedUBCForAvailableOnPhone(){let t=this.getFirstChild(w.formControl);if(t){let n=He.getUniqueIdentifierForControl(t).guidString,i=n===$.GridControl||n===$.TimeLineControl||n===$.TimeLineControlUC;return this.IsUnboundControl?i:!0}return this.NodeName===w.formSection||this.NodeName===w.formTab}IsAllowedUBCForVisibleByDefault(){let t=this.getFirstChild(w.formControl);if(t){let n=He.getUniqueIdentifierForControl(t).guidString,i=n===$.MapsControl||n===$.WebResourceHtmlControl||n===$.WebResourceImageControl||n===$.IframeControl||n===$.SocialInsightControl;return this.IsUnboundControl?i:!0}else return!0}get events(){let t=this.getChildren(w.formEvents);return t.length===1?t[0].getAllChildren():[]}addEvent(t){this.addGrandChild(w.formEvents,t)}getUsedNodeNameSet(t){return null}getHighestIndexById(t,r){return null}}});var ro,Hm=T(()=>{"use strict";ht();ee();tt();ro=class extends H{constructor(t,r){super(w.dependency,t),M.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 HI,no,Km=T(()=>{"use strict";$e();Hm();ee();tt();li();(function(e){e[e.Form=0]="Form",e[e.Cell=1]="Cell",e[e.Tab=2]="Tab",e[e.Control=3]="Control"})(HI||(HI={}));no=class extends gt{constructor(t,r){super(w.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(w.EventHandlers);return t&&t.length?t[0].getChildren(w.handler):[]}getAllDependencies(){let t=this.getChildren(w.formDependencies);return t.length===0?[]:t[0].getAllChildren()}setDependencies(t){let r=this.getFirstChild(w.formDependencies);if(_.IsNullOrUndefined(r)){if(t.length===0)return;this.addChild(new H(w.formDependencies,this)),r=this.getFirstChild(w.formDependencies)}if(t.length===0)r.getParentNode().deleteChild(r);else{r.deleteAllChildren();for(let n of t)r.addChild(new ro(r,n.toString()))}}}});var Pr,qs=T(()=>{"use strict";We();ms();$e();Li();ee();tt();Ir();Pr=class extends H{previewVersion;constructor(t){super(w.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 Ct,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=(Nn.StartTag+r).toString(),a=this.parametersNode;if(a){let o=a.findFirst(s=>s&&s.getNodeName()===t);if(o)if(n){this.deleteFirstGrandChildOfName(w.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)===Nn.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 Ct;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()===je.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 io,Jm=T(()=>{"use strict";ht();Ma();qs();ee();tt();io=class extends Pr{constructor(t){super(t)}get targetEntityType(){return this.getParam(g.targetEntityType)||M.EmptyString}set targetEntityType(t){this.setParameter(g.targetEntityType,t)}get viewId(){return M.StripBraces(this.getParam(g.viewId))||M.EmptyString}set viewId(t){this.setParameter(g.viewId,M.AddBraces(t))}get viewIds(){return this.getParam(g.viewIds)||M.EmptyString}set viewIds(t){this.setParameter(g.viewIds,t)}get relationshipName(){return this.getParam(g.RelationshipName)||M.EmptyString}set relationshipName(t){this.setParameter(g.RelationshipName,t)}get isUserView(){return M.IsStrictTrue(this.getParam(g.isUserView))}set isUserView(t){this.setParameter(g.isUserView,t.toString())}get enableViewPicker(){return M.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 M.IsStrictTrue(this.getParam(g.enableQuickFind))}set enableQuickFind(t){this.setParameter(g.enableQuickFind,t)}get teamTemplateId(){return M.StripBraces(this.getParam(g.teamTemplateId))||M.EmptyString}set teamTemplateId(t){this.setParameter(g.teamTemplateId,M.AddBraces(t))}get chartId(){return this.getParam(g.visualizationId)||M.EmptyString}set chartId(t){this.setParameter(g.visualizationId,t)}get enableChartPicker(){return M.IsStrictTrue(this.getParam(g.enableChartPicker))}set enableChartPicker(t){this.setParameter(g.enableChartPicker,t)}get chartGridMode(){switch(this.getParam(g.chartGridMode)){case ur.Chart:return ur.Chart;case ur.Grid:return ur.Grid;default:return ur.All}}set chartGridMode(t){this.setParameter(g.chartGridMode,t)}updateChartGridMode(t){t?this.chartGridMode=ur.Chart:this.chartGridMode=this.enableChartPicker?ur.All:ur.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("<"+M.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 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(St.dataset)?n[i].getParameters().get(St.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 ao,Qm=T(()=>{"use strict";ht();Ma();qs();ee();ao=class extends Pr{constructor(t){super(t)}get defaultViewId(){return M.StripBraces(this.getParam(g.DefaultViewId))||M.EmptyString}set defaultViewId(t){this.setParameter(g.DefaultViewId,M.AddBraces(t))}get autoResolve(){return M.IsStrictTrue(this.getParam(g.AutoResolve))}set autoResolve(t){this.setParameter(g.AutoResolve,t)}get disableQuickFind(){return M.IsStrictTrue(this.getParam(g.DisableQuickFind))}set disableQuickFind(t){this.setParameter(g.DisableQuickFind,t)}get disableViewPicker(){return M.IsStrictTrue(this.getParam(g.DisableViewPicker))}set disableViewPicker(t){this.setParameter(g.DisableViewPicker,t)}get allowFilterOff(){return M.IsStrictTrue(this.getParam(g.AllowFilterOff))}set allowFilterOff(t){this.setParameter(g.AllowFilterOff,t)}get disableMru(){return M.IsStrictTrue(this.getParam(g.DisableMru))}set disableMru(t){this.setParameter(g.DisableMru,t)}get dependentAttributeName(){return this.getParam(g.DependentAttributeName)||M.EmptyString}set dependentAttributeName(t){this.setParameter(g.DependentAttributeName,t)}get dependentAttributeType(){return this.getParam(g.DependentAttributeType)||M.EmptyString}set dependentAttributeType(t){this.setParameter(g.DependentAttributeType,t)}get filterRelationshipName(){return this.getParam(g.FilterRelationshipName)||M.EmptyString}set filterRelationshipName(t){this.setParameter(g.FilterRelationshipName,t)}get availableViewIds(){return this.getParam(g.AvailableViewIds)||M.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("<"+M.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(St.value)?n[i].getParameters().get(St.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 KI,Xm,qt,Vs=T(()=>{"use strict";KI=ce(jI());li();ee();$e();We();Km();qs();Bu();im();kf();Ir();Li();Fa();Jm();Qm();Ym();ws();Xm="_",qt=class e extends gt{fieldPlaceholder;fieldRequiredLevel;isNewField;cellColType;dependentFields=[];constructor(t){super(w.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 Pr?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:!Mi.dependencyFieldCount.containsKey(this.control.id):!Mi.dependencyFieldCount.containsKey(this.control.dataFieldName)}createOnLoadEvent(){this.addEvent(new no(this,ps.onLoad))}get dependencies(){let t=this.getChildren(w.formEvents);for(let r of t){let n=r.getChildren(w.formEvent);for(let i of n)this.buildDependencyList(i,this.dependentFields)}return this.dependentFields}getNextAvailableControlName(t,r,n,i){let a;if(i&&Su[i])a=Su[i].replace(/ /g,Xm)+Xm;else{a="Control_";let u=new Error("Control class id does not exist or is undefined");(0,KI.trackErrorTrace)(Et,{eventName:`${Vw}/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===dr.Grid?(l=new io(this),l.indicationOfSubgrid=!0):a===dr.Lookup?l=new ao(this):l=new Pr(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=He.getUniqueIdentifierForControl(l);_.IsNullOrUndefined(d)||(He.getControlDataTypeByControlOrUniqueId(d)===j.QuickFormCollectionControl||!He.isUnboundFormControlByIdentifier(d)?a!==dr.Grid&&o&&u!==I.IframeControl&&u!==I.SubgridControl&&u!==I.ReferencePanelSubgridControl&&(l.dataFieldName=o,e.prototype.setProperty.call(l,g.disabled,"false")):(this.rowspan=He.GetRowSpan(l),(He.getControlDataTypeByControlOrUniqueId(d)===j.NotesControl||He.getControlDataTypeByControlOrUniqueId(d)===j.TimeLineControl)&&(e.prototype.setProperty.call(l,g.disabled,"false"),l.id=j.NotesControl)),(He.getUnboundControlNameFromIdentifier(n)===j.SubGridControl||He.getUnboundControlNameFromIdentifier(n)===j.NotesControl||He.getUnboundControlNameFromIdentifier(n)===j.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()===w.dependency&&s?r.push(s):this.buildDependencyList(o,r)}}}get control(){return this.getFirstChild(w.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(rm.ONE_COLUMN),n=Number(rm.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(w.formRow)}getParentSection(){return this.getAncestor(w.formSection)}getParentTab(){return this.getAncestor(w.formTab)}getParentForm(){return this.getAncestor(w.form)}isInHeader(){let t=this.getAncestor(w.formHeader);return!_.IsNullOrUndefined(t)}isInFooter(){let t=this.getAncestor(w.formFooter);return!_.IsNullOrUndefined(t)}isEmpty(){return _.IsNullOrUndefined(this.control)&&!this.IsUserSpacer}getHeaderFooter(){return this.isInHeader()?this.getAncestor(w.formHeader):this.isInFooter()?this.getAncestor(w.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 Te.TWO_COLUMN:r="11";break;case Te.THREE_COLUMN:r="111";break;case Te.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===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()===w.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()===w.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)===Xm&&(r++,n=parseInt(t.substr(r,t.length-r),10)),n}}});var oo,Zm=T(()=>{"use strict";ht();ee();tt();oo=class extends H{isInternal;constructor(t,r,n,i){super(w.library,t),this.isInternal=!!i,M.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 zi,eh=T(()=>{"use strict";$e();Vs();ee();tt();zi=class extends H{isRowAddedOnDragOver;constructor(t){super(w.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(w.formSection)}insertPaddingCellAtIndex(t){let r=new qt(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(w.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 V8(e){switch(e){case $i.Left:return qi.Left;case $i.Right:return qi.Right;case $i.Center:return qi.Center;default:return qi.Left}}function G8(e){switch(e){case $a.Left:return Va.Left;case $a.Top:return Va.Top;default:return Va.Left}}function JI(e){switch(e){case 1:return 1;case 2:return 11;case 3:return 111;case 4:return 1111;default:return 1}}var z8,en,Gs=T(()=>{"use strict";am();We();$e();ht();jm();Vs();ee();Ir();li();eh();z8=115,en=class e extends gt{colSpan=1;constructor(t,r){super(t,r)}getSectionType(){let t;switch(this.columns){case 1:t=Te.ONE_COLUMN;break;case 11:t=Te.TWO_COLUMN;break;case 111:t=Te.THREE_COLUMN;break;case 1111:t=Te.FOUR_COLUMN;break;default:t=this.colSpan-1}return t}setUniqueName(){let t=this.getParentTab(),r=De.namePrefix;if(t){let n=t.Name,i=t.TotalSectionsCount+1;r=n+De.namePrefix+i.toString()}else r+=Math.floor(Math.random()*1e3);this.setProperty(g.Name,r)}initializeDefaultProperties(t,r,n){if(n===Te.REFERENCE_PANEL){this.addProperty(g.rowheight,"25");let i=`${De.referencePanelNamePrefix}${L.NewGuid()}${De.namePrefix}`;this.addProperty(g.Name,i)}else this.setUniqueName();if(this.addProperty(g.id,new L(L.NewGuid()).guidString),this.addProperty(g.IsUserDefined,De.IsUserDefined),this.addProperty(g.locklevel,De.LockLevel),this.addProperty(g.showlabel,De.ShowLabel),this.addProperty(g.showbar,De.ShowBar),this.addProperty(g.layout,De.Layout),this.addProperty(g.Fieldlabelalignment,De.labelAlignment),this.addProperty(g.Fieldlabelposition,De.labelPosition),_.IsNullOrUndefined(n))this.addProperty(g.columnName,De.columns);else{let i=this.getColumnLayoutValue(n);this.addProperty(g.columnName,i)}this.addProperty(g.LabelWidth,De.LabelWidth),this.setDisplayName(r,t)}getColumnLayoutValue(t){let r;switch(t){case Te.TWO_COLUMN:r="11";break;case Te.THREE_COLUMN:r="111";break;case Te.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(M.EmptyString).forEach(r=>{t+=parseInt(r,10)}),t}get ColSpan(){return this.colSpan}initializeRow(t){if(t>0&&t<5){let r=new zi(null);if(this.addGrandChild(w.formRows,r),VI.getConfig().enableAutoInsertionOfCellInRow)for(let n=0;n<t;n++){let i=new qt(r);i.setDefaultProperties(!1),r.addCell(i)}}}initialize(t,r,n){this.initializeDefaultProperties(t,r,n),n===Te.REFERENCE_PANEL&&(n=Te.ONE_COLUMN),this.initializeRow(n+1)}setColSpan(t){this.colSpan=t}appendRow(t){this.addGrandChild(w.formRows,t)}insertRowAtIndex(t,r){this.addGrandChildAtIndex(w.formRows,t,r)}insertRowsAtIndex(t,r){if(t&&t.length>0)for(let n=0;n<t.length;n++)this.addGrandChildAtIndex(w.formRows,t[n],r+n)}indexOfRow(t){return this.rows.indexOf(t)}deleteRow(t){return this.deleteFirstGrandChildOfName(w.formRows,t)}deleteRows(t,r){this.deleteGrandChildren(w.formRows,t,r)}get rows(){return this.getRows()}getRows(){let t=this.getChildren(w.formRows);return t.length===0?[]:t[0].getChildren(w.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 JI(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(w.formColumn)}getParentTab(){return this.getAncestor(w.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=De.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)?De.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?z8: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:V8(this.fieldLabelAlignment),Position:G8(this.fieldLabelPosition)},Columns:JI(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()===w.formSection){let i=n;i.Name&&!M.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}isReferencePanelSection(){return!_.IsNullOrUndefined(this)&&!_.IsNullOrUndefined(this.Name)&&this.Name.indexOf(De.referencePanelNamePrefix)===0}getAllMultiRowCells(){return this.findAll(t=>{if(t.getNodeName()===w.formCell){let r=t;return!r.isEmpty()&&r.rowspan>1}return!1})}isHeaderOrFooterSection(){return this.NodeName===w.formFooter||this.NodeName===w.formHeader}}});var ui,tc=T(()=>{"use strict";ee();tt();Gs();ui=class e extends H{constructor(t){super(w.formColumn,t)}initializeDefaultProperties(t){this.addProperty(g.width,t.toString()+"%")}insertSectionAtIndex(t,r){this.addGrandChildAtIndex(w.formSections,t,r)}static createAndInitNewSection(t,r,n){let i=new en(w.formSection,null);return i.initialize(t,r,n),i}addSectionAtIndex(t,r){this.addGrandChildAtIndex(w.formSections,t,r)}initialize(t,r,n,i=Te.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(w.formTab)}get sections(){let t=this.getChildren("sections");return t.length!==1?[]:t[0].getChildren(w.formSection)}get width(){return this.getProperty(g.width)}set width(t){this.setProperty(g.width,t)}deleteSection(t){return this.deleteFirstGrandChildOfName(w.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 rc,QI=T(()=>{"use strict";We();ee();Ir();Gs();rc=class extends en{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,De.columns),this.setDisplayName(r,t)}}});var nc,XI=T(()=>{"use strict";tc();ee();QI();nc=class extends ui{addAndIntializeNavBarSection(t,r,n,i){let a=new rc(w.formSection,null);return a.initializeNavArea(t,r,i),this.addGrandChildAtIndex(w.formSections,a,n),a}}});var In,ic=T(()=>{"use strict";We();$e();ht();tc();ee();tt();li();In=class extends gt{tabContainsAutoExpandControl;autoExpandCell;constructor(t,r){super(w.formTab,t),this.tabContainsAutoExpandControl=!1}getParentForm(){return this.getAncestor(w.form)}getTabLayoutType(){let t;switch(this.columns.length){case 1:t=_e.ONE_COLUMN;break;case 2:if(parseInt(this.columns[0].width,10)===50&&parseInt(this.columns[1].width,10)===50){t=_e.TWO_COLUMN_EQUAL;break}if(parseInt(this.columns[0].width,10)===67&&parseInt(this.columns[1].width,10)===33){t=_e.TWO_COLUMN_WIDER_LEFT;break}if(parseInt(this.columns[0].width,10)===34&&parseInt(this.columns[1].width,10)===66){t=_e.TWO_COLUMN_WIDER_RIGHT;break}t=_e.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=_e.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=_e.THREE_COLUMN_WIDER_MID;break}t=_e.THREE_COLUMN_CUSTOM_LAYOUT;break;default:}return t}initializeProperties(t,r,n){this.addProperty(g.Name,ri.namePrefix+t.toString()),this.addProperty(g.id,new L(L.NewGuid()).guidString),this.addProperty(g.IsUserDefined,ri.IsUserDefined),this.addProperty(g.locklevel,ri.LockLevel),this.addProperty(g.showlabel,ri.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=Te.ONE_COLUMN,a=!0,o){let s=this.getChildren(w.formColumns)[0],l=[];switch(t){case _e.ONE_COLUMN:l.push(100);break;case _e.TWO_COLUMN_EQUAL:l.push(50),l.push(50);break;case _e.TWO_COLUMN_WIDER_LEFT:l.push(67),l.push(33);break;case _e.TWO_COLUMN_WIDER_RIGHT:l.push(34),l.push(66);break;case _e.THREE_COLUMN_EQUAL:l.push(34),l.push(33),l.push(33);break;case _e.THREE_COLUMN_WIDER_MID:l.push(28),l.push(44),l.push(28);break;default:}for(let u of l){let c=new ui(s);c.initialize(u,r,n,i),this.addGrandChild(w.formColumns,c)}}initialize(t,r,n,i,a,o=Te.ONE_COLUMN,s=!0,l){this.addChild(new H(w.formColumns,this)),this.initializeProperties(r,n,i),this.initializeColumns(t,n,a,o,s,l)}get columns(){let t=this.getChildren(w.formColumns);return t.length!==1?[]:t[0].getChildren(w.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(w.formColumns,t,r)}insertColumnAtIndex(t,r){this.addGrandChildAtIndex(w.formColumns,t,r)}deleteColumn(t){return this.deleteFirstGrandChildOfName(w.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()===w.formTab){let i=n;i.Name&&!M.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}}});var Wi,th=T(()=>{"use strict";We();ee();tt();Ir();XI();ic();Wi=class extends In{constructor(t,r,n){super(t,_e.THREE_COLUMN_EQUAL),this.setDisplayName(r,n),this.id=new L(L.NewGuid())}initializeDefaultProps(){this.addChild(new H(w.formColumns,this)),this.initializeFiveColumns()}get columns(){let t=this.getChildren("columns");return t.length!==1?[]:t[0].getChildren(w.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<ku.FIVE_COLUMN;t++){let r=new nc(this.getChildren(w.formColumns)[0]);r.initializeDefaultProperties(yA.FiveEqColumn),this.addGrandChild(w.formColumns,r)}}}});function j8(e){switch(e){case je.Main:return ii.Main;case je.QuickCreate:return ii.QuickCreate;case je.QuickViewForm:return ii.Quick;case je.Dialog:return ii.Dialog;default:return ii.None}}function H8(e,t){if(t===je.Main){if(e)switch(e.toLowerCase()){case"low":return ti.Low;case"highreadonlyvalues":return ti.HighReadOnlyValues;default:return ti.HighWithControls}return ti.Low}}var oc,W8,ac,YI=T(()=>{"use strict";NA();oc=ce(ki());am();$e();ht();Fa();jm();ee();Ma();Cf();Li();Vs();ee();li();Zm();th();ic();W8="1920";ac=class e extends gt{_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(w.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 wu,this._metadataChangeEvent=new Uu}get FormLibraries(){let t=this.getFirstChild(w.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 qt).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 qt){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()===w.internalLibraries),r=[],n="src";return t.length>0&&(r=t.map(i=>{let a=i.GetPropertyByParameter(n).replace("$webresource:",""),o=new oo(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,oc.trackErrorTrace)(Gw,{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 M.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 M.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 M.IsNullOrEmpty(this.getProperty(g.MaxWidth))?W8: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===je.Main?this.setProperty(g.HeaderDensityType,t):this.formType!==je.Main&&this.headerDensityType&&this.removeProperty(g.HeaderDensityType)}IsMainOrQuickCreateForm(){return this.formType===je.Main||this.formType===je.QuickCreate}get FormPresentation(){return this._formPresentation}get LanguageCode(){return this._langCode}set LanguageCode(t){this._langCode=t}get header(){let t=this.getChildren(w.formHeader);return t.length!==1?null:t[0]}set header(t){_.IsNullOrUndefined(t)||(this.deleteChild(this.header),this.addChild(t))}getAllDependencies(){return this.getChildren(w.quickFormDependencies).length===0?[]:this.ConvertModelToArray(this.getChildren(w.quickFormDependencies)[0].getAllChildren())}ConvertModelToArray(t){let r=[];return _.IsNullOrUndefined(t)||t.forEach(n=>{r.push(n.id)}),r}get footer(){let t=this.getChildren(w.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 In(null,t),a=this.getNextTabCounter(this.tabs.length+1);return i.initialize(t,a,this.LanguageCode,r,n),i}addTabAtIndex(t,r){this.addGrandChildAtIndex(w.formTabs,t,r)}createAndInitNewTabWithMarginalControl(t,r,n,i,a){let o=new In(null,_e.ONE_COLUMN),s=this.getNextTabCounter(this.tabs.length+1);o.initialize(_e.ONE_COLUMN,s,this.LanguageCode,r,n,a,!1),this.addGrandChildAtIndex(w.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===ri.namePrefix+t.toString())return this.getNextTabCounter(t+1);return t}get allTabs(){let t=this.getChildren(w.formTabs);return t.length!==1?[]:t[0].getChildren(w.formTab)}get CanvasNavigationTab(){if(this.tabs.length>0){let t=this.tabs[this.tabs.length-1];if(t instanceof Wi)return t}return null}get NavigationNode(){let t=this.getChildren(w.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(w.formTabs,t)}insertTabAtIndex(t,r){this.addGrandChildAtIndex(w.formTabs,t,r)}insertRelatedTab(t){let r=this.getAllGrandChildren(w.formTabs);if(!_.IsNullOrUndefined(r)){let n=r.length;this.insertTabAtIndex(t,n)}}get isfooterPresent(){return this.getChildren(w.formFooter).length>0}get displayCondition(){let t=this.getChildren(w.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(w.formTabs).indexOf(t)}get ControlDescriptions(){return this.getAllGrandChildren(w.controlDescriptions)}addControlDescriptionNode(t){this.addGrandChild(w.controlDescriptions,t)}deleteControlDescByForControlId(t){let r=this.getControlDescriptionByForControl(t);_.IsNullOrUndefined(r)||this.deleteFirstGrandChildOfName(w.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 qt))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 qt&&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,ni.EditableGridControl)||GI.getConfig()?.enableOneGridEventsForFormDesigner&&this.cellHasCustomControlWithName(t,ni.PowerAppsOneGrid)}isCellCanvasAppControl(t){return t?.control?.ClassId.guidString.toUpperCase()===I.CustomControl&&this.cellHasCustomControlWithName(t,ni.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()===w.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 Wi)){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,oc.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===je.Main?{HeaderDensity:H8(this.headerDensityType,this.formType)}:{},InlineEditGridRow:[],InlineQuickForms:[],QuickFormEntities:[],EventHandlers:[],LinkControlSections:[],FormType:j8(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 sc,rh,ZI=T(()=>{"use strict";We();$e();ee();tt();li();sc=class extends gt{constructor(t){super(w.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(w.formEveryOne)&&this.getChildren(w.formEveryOne)[0])}setRoleEveryone(){this.deleteAllChildren(),this.addChild(new rh(this))}},rh=class extends H{constructor(t){super(w.formEveryOne,t)}}});var lc,e_=T(()=>{"use strict";ee();tt();lc=class extends H{constructor(t,r){super(w.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 so,nh=T(()=>{"use strict";ee();Gs();so=class extends en{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(w.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 zs,t_=T(()=>{"use strict";ee();nh();zs=class extends so{_customFooter;constructor(t,r){super(w.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 Ws,r_=T(()=>{"use strict";ee();nh();Ws=class extends so{_customHeader;constructor(t,r){super(w.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 Vt,ji=T(()=>{"use strict";We();ht();ee();li();Vt=class e extends gt{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(w.Titles);return t.length===0?[]:t[0].getChildren(w.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(w.Title,null);n.setProperty(g.text,t),n.setProperty(g.LCID,String(r)),this.addGrandChild(w.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||M.EmptyString,this.setProperty(g.icon,t)}updateCommonProperties(t,r){this.Area=t.Area,this.Sequence=t.Sequence,this.setTitle(t.getDisplayName(r),r)}}});var js,n_=T(()=>{"use strict";(function(e){e[e.NavLinkNotAvailable=-1]="NavLinkNotAvailable",e[e.NavLinkIdConflict=-2]="NavLinkIdConflict",e[e.NavBarNotAvailable=-3]="NavBarNotAvailable"})(js||(js={}))});var uc,i_=T(()=>{"use strict";$e();ee();ji();n_();uc=class extends Vt{constructor(t){super(w.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)?js.NavLinkNotAvailable:r.length===1?this.deleteChild(r[0]):js.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 Se,K8,a_,nae,lo,ih=T(()=>{"use strict";We();ee();ji();(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"})(Se||(Se={}));K8=new Map([[Se.Info,"Info"],[Se.Sales,"Sales"],[Se.Service,"Service"],[Se.Marketing,"Marketing"],[Se.ProcessCenter,"ProcessCenter"]]),a_=new Map([["Info",Se.Info],["Sales",Se.Sales],["Service",Se.Service],["Marketing",Se.Marketing],["ProcessCenter",Se.ProcessCenter]]),nae=new Map([[Se.Info,9e3],[Se.Sales,9200],[Se.Service,9400],[Se.Marketing,9600],[Se.ProcessCenter,9800],[Se.InternetMarketing,1e4],[Se.Async,10200]]),lo=class extends Vt{constructor(t,r){super(w.formNavBarArea,r)}setDefaultPropertiesByType(t,r,n){this.AreaId=K8.get(t);let i=n?.(`navBarArea.title.${this.AreaId}`)??this.AreaId;this.setTitle(i,r)}get ParentNavigation(){return this.getAncestor(w.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 uo,ah=T(()=>{"use strict";ee();ji();uo=class extends Vt{constructor(t,r){super(w.formNavBarAreas,r)}get AllNavBarAreaItems(){return this.getChildren(w.formNavBarArea)}get ParentNavigation(){return this.getAncestor(w.formNavigation)}addNavBarArea(t){this.addChild(t)}}});var cc,o_=T(()=>{"use strict";$e();ee();ji();cc=class extends Vt{RelationshipNameUCIRuntime;constructor(t){super(w.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 dc,s_=T(()=>{"use strict";ee();ji();dc=class extends Vt{constructor(t){super(w.formNavBarItem,t)}get Url(){return this.getProperty(g.url)}set Url(t){this.setProperty(g.url,t)}}});var pc,l_=T(()=>{"use strict";We();ee();ih();ah();ji();pc=class extends Vt{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(w.formNavBarAreas)}setDefaultNavBarAreas(t,r){let n=[Se.Info,Se.Sales,Se.Service,Se.Marketing,Se.ProcessCenter];if(this.navBarAreas){let i=this.navBarAreas?.AllNavBarAreaItems;if(i&&i.length>0){let a=new Set(i.map(o=>a_.get(o.AreaId)));n=n.filter(o=>!a.has(o))}}else{let i=new uo(w.formNavBarAreas,this);i.isTransient=!0,this.addChild(i)}return n.length>0?(n.forEach(i=>{let a=new lo(w.formNavBarArea,this.navBarAreas);a.setDefaultPropertiesByType(i,t,r),this.navBarAreas.addNavBarArea(a)}),!0):!1}get navBar(){return this.getFirstChild(w.formNavBar)}get id(){return new L(Lf,!0)}replaceNavAreaToGivenIndex(t,r){this.navBarAreas?.AllNavBarAreaItems.indexOf(r)!==-1&&(this.deleteFirstGrandChildOfName(w.formNavBarAreas,r),this.addGrandChildAtIndex(w.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 u_={};pn(u_,{ControlType:()=>dr,DeserializationService:()=>lh,DeserializationServiceScope:()=>sh,DeserializedFormElementNode:()=>Gt});var oh,Gt,sh,dr,lh,Ym=T(()=>{"use strict";oh=ce(ki());We();$e();ht();Fa();kf();Li();zw();SA();Bu();YI();Vs();tc();qs();Hm();ee();ee();ZI();tt();Ir();Km();e_();t_();Jm();Qm();r_();Zm();eh();Gs();ic();i_();ih();ah();o_();s_();l_();Gt=class extends H{constructor(t,r){super(t,r)}insertProperty(t,r){this.addProperty(t,r)}insertChild(t){this.addChild(t)}},sh="DeserializationService";(function(e){e.Grid="Grid",e.Lookup="Lookup",e.Base="Base"})(dr||(dr={}));lh=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,oh.trackErrorTrace)(Et,{eventName:sh,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!==je.Dialog&&this.appendDefaultDisplayCondition(p),p}upsertFieldCount(t,r){let n=Mi.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 ac(r,n,i,a,o,s,l,u,c);return this.populateElementProperties(d,t.attributes),this.populateElementChildren(d,t.childNodes),s===je.Main&&(this.insertHeaderFooterElementProperties(w.formHeader,d,d.header),this.insertHeaderFooterElementProperties(w.formFooter,d,d.footer)),d}insertHeaderFooterElementProperties(t,r,n){if(_.IsNullOrUndefined(n)){let i=t===w.formHeader?new Ws(r,!0):new zs(r,!0);Gt.prototype.insertProperty.call(i,g.id,"{"+L.NewGuid()+"}"),Gt.prototype.insertProperty.call(i,g.Fieldlabelposition,"Top"),Gt.prototype.insertProperty.call(i,g.columnName,De.MarginalControlColumns),Gt.prototype.insertProperty.call(i,g.LabelWidth,De.LabelWidth),Gt.prototype.insertProperty.call(i,g.Fieldlabelalignment,"Left");let a=null,o=new zi(a);for(let s=0;s<i.maxColumns;s++){let l=new qt(o);Gt.prototype.insertProperty.call(l,g.id,"{"+L.NewGuid()+"}"),l.setDisplayName(M.EmptyString,this.lcid),Gt.prototype.insertProperty.call(l,g.showlabel,"false"),o.addCell(l)}i.appendRow(o),t===w.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 Gt(`<${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,oh.trackErrorTrace)(Et,{eventName:sh,eventData:{error:n}}),new Error(n)}for(let n=0;n<r.length;n++){let i=r.item(n);i&&(Gt.prototype.insertProperty.call(t,i.name,i.value),t.getNodeName()===w.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&&Gt.prototype.insertChild.call(t,a)}}createModelNode(t,r){switch(t.nodeName){case w.form:throw new Error("Form node shouldn't be created using this method");case w.formTab:return new In(r);case w.formColumn:return new ui(r);case w.formHeader:return new Ws(r,!1);case w.formFooter:return new zs(r,!1);case w.formSection:return new en(w.formSection,r);case w.formRow:return new zi(r);case w.formCell:return new qt(r);case w.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=dr.Grid;else if(l.name===g.classid&&l.value?.toLocaleUpperCase()===`{${I.LookupControl}}`)a=dr.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=dr.Lookup)}return a===dr.Grid?new io(r):a===dr.Lookup?new ao(r):new Pr(r);case w.formEvent:return new no(r,M.EmptyString);case w.dependency:return this.populateDependencyTable(t),new ro(r,M.EmptyString);case w.Handler:let o=[];return new lc(o,r);case w.formNavigation:return new pc(t.nodeName,r);case w.formNavBarArea:return new lo(t.nodeName,r);case w.formNavBarAreas:return new uo(t.nodeName,r);case w.formNavBar:return new uc(r);case w.formNavBarByRelationshipItem:return new cc(r);case w.formNavBarItem:return new dc(r);case w.formDisplayConditions:return new sc(r);case w.library:return new oo(r,M.EmptyString,M.EmptyString);case w.controlDescription:return new Nu(r);case w.customControl:return this.populateCustomControlConfigurationId(t),new Mu(r);default:return new Gt(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,Qr.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);He.CustomControlIdMap.upsert(l,a);break}}break}}}}});var c_={};pn(c_,{SerializationService:()=>uh,SerializationServiceScope:()=>J8,SerializedFormElementNode:()=>co});var J8,co,uh,d_=T(()=>{"use strict";ht();tt();Ir();th();J8="SerializationService",co=class extends H{fetchNodeName(){return this.getNodeName()}enumerateProperties(){return this.getAllProperties()}enumerateChildren(){return this.getAllChildren()}},uh=class{langCode;constructor(t){this.langCode=t}serializeFormXmlNode(t){let r=co.prototype.fetchNodeName.call(t);if(r.charAt(0)===Nn.StartTag)return M.EscapeXml(r.substr(1),!1);if(t.isTransient&&!t.isDirty())return M.EmptyString;let n=co.prototype.enumerateProperties.call(t),i=co.prototype.enumerateChildren.call(t);if(!(t instanceof Wi)){let a=`<${r}`;if(n.length!==0&&(a+=` ${this.getPropertiesString(n)}`),i.length===0)a+=" />";else{let o=M.EmptyString;for(let s of i)o+=this.serializeFormXmlNode(s);a+=`>${o}</${r}>`}return a}return M.EmptyString}getPropertiesString(t){let r=M.EmptyString;return t.forEach((n,i)=>{i!==0&&(r+=" "),r+=`${n.key}="${M.EscapeXml(n.value,!0)}"`}),r}}});var I_=y(Wt=>{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.classIdForAttributeType=Wt.QUICK_VIEW_CLASS_ID=Wt.NOTES_CLASS_ID=Wt.SUBGRID_CLASS_ID=Wt.formRegistration=Wt.FormAdapter=void 0;var _n=(We(),Mr(Lw)),Q8=($e(),Mr(kw)),X8=(tt(),Mr(Bw)),rt=(ee(),Mr(Mw)),qe=(Li(),Mr(Uw)),Y8=(Ym(),Mr(u_)),Z8=(d_(),Mr(c_)),Ke=Kn(),p_=Nr(),zt=Cr(),e6=of(),po=lt(),vt=Xp(),f_=te(),fh=ae(),mh=Qn(),w_=ha(),t6={[rt.FormType.Main]:"Main",[rt.FormType.QuickCreate]:"QuickCreate",[rt.FormType.QuickViewForm]:"QuickView",[rt.FormType.Card]:"Card"},fc={Main:rt.FormType.Main,QuickCreate:rt.FormType.QuickCreate,QuickView:rt.FormType.QuickViewForm,Card:rt.FormType.Card},r6=new Map(Object.entries(qe.ControlClassId).map(([e,t])=>[String(t).toUpperCase(),e]));function A_(e){var t;return e&&(t=r6.get(e.toUpperCase()))!==null&&t!==void 0?t:"Unknown"}function Hs(e){return e.getAllProperties().map(t=>[t.key,t.value])}function Hi(e){let t=new Map;for(let r of e.getAllProperties())t.has(r.key)||t.set(r.key,r.value);return t}function E_(e,t){return e.getAllChildren().find(r=>r.getNodeName()===t)}function hh(e,t){var r,n;let i=E_(e,"labels");if(!i)return"";let a=i.getAllChildren().filter(s=>s.getNodeName()==="label"),o=(r=a.find(s=>Hi(s).get("languagecode")===String(t)))!==null&&r!==void 0?r:a[0];return o&&(n=Hi(o).get("description"))!==null&&n!==void 0?n:""}function n6(e){let t=E_(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 C_(e){return/^1+$/.test(e)&&e.length>=1&&e.length<=4?e.length:1}function ch(e){let t=Math.min(Math.max(Math.trunc(e),1),4);return"1".repeat(t)}function Ks(e){return String(e??"").replace(/[{}]/g,"")}function dh(e){return`{${Ks(e)}}`}function m_(e,t){if(e===void 0||e==="")return t;let r=Number(e);return Number.isNaN(r)?t:r}function hc(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,Ke.rawFromNode)(u)})}),i<0)return{modeled:[],bag:{a:Hs(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,Ke.rawFromNode)(u)})}),{modeled:s,bag:{a:Hs(e),c:a,w:{n:o.getNodeName(),a:Hs(o),c:l}}}}function S_(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,Ke.rawFromNode)(a)})}),{modeled:n,bag:{a:Hs(e),c:i}}}function h_(e,t){let{modeled:r,bag:n}=hc(e,"tabs","tab");return{tabs:r.map(i=>i6(i,t)),bag:n}}function i6(e,t){var r,n;let i=Hi(e),{modeled:a,bag:o}=hc(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:hh(e,t),expanded:i.get("expanded")==="true",visible:i.has("visible")?i.get("visible")==="true":!0,columns:a.map(s=>a6(s,t)),bag:o}}function a6(e,t){let r=Hi(e),{modeled:n,bag:i}=hc(e,"sections","section");return{width:r.get("width"),sections:n.map(a=>o6(a,t)),bag:i}}function o6(e,t){var r,n,i;let a=Hi(e),{modeled:o,bag:s}=hc(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:hh(e,t),visible:a.has("visible")?a.get("visible")==="true":!0,showLabel:a.get("showlabel")==="true",columns:C_((i=a.get("columns"))!==null&&i!==void 0?i:"1"),rows:o.map(l=>s6(l,t)),bag:s}}function s6(e,t){let{modeled:r,bag:n}=S_(e,"cell",!1);return{cells:r.map(i=>l6(i,t)),bag:n}}function l6(e,t){var r;let n=Hi(e),{modeled:i,bag:a}=S_(e,"control",!0),o=hh(e,t),s=n.get("showlabel")==="true",l=i[0]?u6(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:m_(n.get("colspan"),1),rowspan:m_(n.get("rowspan"),1),control:l,bag:a}}function u6(e,t,r){var n,i;let a=Hi(e),o=Ks((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:A_(o),isRequired:a.get("isrequired")==="true",isReadOnly:a.get("disabled")==="true",label:t,showLabel:r,parameters:n6(e),bag:{a:Hs(e),c:e.getAllChildren().map((l,u)=>({i:u,node:(0,Ke.rawFromNode)(l)}))}}}function pi(e){return e.a.length===0&&e.c.length===0&&!e.w}function N_(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function Ki(e,t){var r;let n=new Set(e.a.map(o=>o[0])),i=pi(e),a=[];for(let o of t)if(n.has(o.key)){let s=(r=N_(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,Ke.mergeAttrs)(e.a,a)}var ci=(e,t)=>({key:e,matches:r=>r===t,render:()=>t,absentDefault:""}),di=(e,t,r=!1)=>({key:e,matches:n=>n==="true"===t,render:()=>String(t),absentDefault:String(r)}),g_=(e,t,r=1)=>({key:e,matches:n=>Number(n)===t,render:()=>String(t),absentDefault:String(r)});function gc(e,t){return{n:"labels",a:[],c:[{n:"label",a:[["description",e],["languagecode",String(t)]],c:[]}]}}function ph(e){return{n:"parameters",a:[],c:Object.keys(e).map(t=>({n:(0,fh.assertXmlName)(t,"Form control parameter name"),a:[],c:[{n:`<${e[t]}`,a:[],c:[]}]}))}}function c6(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 d6(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 gh(e,t,r){let n=e.c.findIndex(a=>a.node.n==="labels");if(n<0){if(!t||pi(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:gc(t,r)},...o]}}if(c6(e.c[n].node,r)===t)return e;let i=d6(e.c[n].node,t,r);return{...e,c:e.c.map((a,o)=>o===n?{...a,node:i}:a)}}function p6(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 f6(e,t){let r=Object.keys(e),n=Object.keys(t);return r.length===n.length&&r.every(i=>e[i]===t[i])}function m6(e,t){return e.a.some(r=>r[0]===t)?{...e,a:e.a.filter(r=>r[0]!==t)}:e}function h6(e,t){let r=e.c.findIndex(i=>i.node.n==="parameters");if(r<0){if(Object.keys(t).length===0||pi(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:ph(t)}]}}if(f6(p6(e.c[r].node),t))return e;let n=ph(t);return{...e,c:e.c.map((i,a)=>a===r?{...i,node:n}:i)}}function vc(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,Ke.spliceChildren)(e.w.c,r)};return(0,Ke.spliceChildren)(e.c,[o])}let i=n(),a={n:t,a:[],c:r};return e.c.length===0?[...i,a]:(0,Ke.spliceChildren)(e.c,[...i,a])}function g6(e,t){let r=e.tabs.map(n=>v6(n,t));return{n:"form",a:Ki(e.bag,[]),c:e.tabs.length===0&&pi(e.bag)?[]:vc(e.bag,"tabs",r,()=>[])}}function v6(e,t){let r=[ci("id",e.id),ci("name",e.name),di("expanded",e.expanded),di("visible",e.visible,!0)],n=e.columns.map(a=>y6(a,t)),i=gh(e.bag,e.label,t);return{n:"tab",a:Ki(i,r),c:vc(i,"columns",n,()=>e.label?[gc(e.label,t)]:[])}}function y6(e,t){let r=e.width!==void 0?[ci("width",e.width)]:[],n=e.sections.map(i=>b6(i,t));return{n:"column",a:Ki(e.bag,r),c:vc(e.bag,"sections",n,()=>[])}}function b6(e,t){let r=[ci("id",e.id),ci("name",e.name),di("showlabel",e.showLabel),di("visible",e.visible,!0),{key:"columns",matches:a=>C_(a)===e.columns,render:()=>ch(e.columns),absentDefault:ch(1)}],n=e.rows.map(a=>w6(a,t)),i=gh(e.bag,e.label,t);return{n:"section",a:Ki(i,r),c:vc(i,"rows",n,()=>e.label?[gc(e.label,t)]:[])}}function w6(e,t){let r=e.cells.map(n=>A6(n,t));return{n:"row",a:Ki(e.bag,[]),c:pi(e.bag)?r:(0,Ke.assembleChildren)(e.bag,r)}}function A6(e,t){let r=e.control?e.control.showLabel:N_(e.bag,"showlabel")==="true",n=[ci("id",e.id),di("showlabel",r),di("visible",e.visible,!0),g_("colspan",e.colspan),g_("rowspan",e.rowspan)],i=e.control?[E6(e.control)]:[],a;if(pi(e.bag))a=[...e.control&&e.control.label?[gc(e.control.label,t)]:[],...i];else{let o=e.control?gh(e.bag,e.control.label,t):e.bag;a=(0,Ke.assembleChildren)(o,i)}return{n:"cell",a:Ki(e.bag,n),c:a}}function E6(e){let t=[ci("id",e.id),{key:"classid",matches:i=>Ks(i)===e.classId,render:()=>dh(e.classId),absentDefault:""}];e.fieldName!==null&&t.push(ci("datafieldname",e.fieldName)),t.push(di("disabled",e.isReadOnly)),t.push(di("isrequired",e.isRequired));let r=e.fieldName===null?m6(e.bag,"datafieldname"):e.bag,n;return pi(r)?n=Object.keys(e.parameters).length>0?[ph(e.parameters)]:[]:n=(0,Ke.assembleChildren)(h6(r,e.parameters),[]),{n:"control",a:Ki(r,t),c:n}}var C6={make:(e,t)=>new X8.FormElementNode(e,t),setProp:(e,t,r)=>e.setProperty(t,r),addChild:(e,t)=>e.addChild(t)};function v_(e,t,r,n){(0,mh.installDomShim)();let i=N6(e,r);(0,vt.reconcileEmbedDescriptions)(i,n);let a=(0,Ke.rebuildRaw)(g6(i,t),C6,null);return new Z8.SerializationService(t).serializeFormXmlNode(a)}function S6(e){return JSON.parse(JSON.stringify(e))}function N6(e,t){var r;let n=S6(e);n.bag||(n.bag=(0,Ke.emptyBag)()),x6(n.bag),t&&D6(n,t);for(let i of(r=n.tabs)!==null&&r!==void 0?r:[])I6(i);return n}function D6(e,t){var r;let n=(r=e.entityLogicalName)!==null&&r!==void 0?r:"";vh(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=D_(s.attributeType)))})}function y_(e){let t=[];return vh(e,r=>t.push(r)),t}function vh(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 I6(e){e.id||(e.id=_n.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)_6(t);e.bag||(e.bag=(0,Ke.emptyBag)())}function _6(e){e.sections||(e.sections=[]);for(let t of e.sections)T6(t);e.bag||(e.bag=(0,Ke.emptyBag)()),e.width===void 0&&pi(e.bag)&&(e.width="100%")}function T6(e){e.id||(e.id=_n.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)P6(t);e.bag||(e.bag=(0,Ke.emptyBag)())}function P6(e){e.cells||(e.cells=[]);for(let t of e.cells)R6(t);e.bag||(e.bag=(0,Ke.emptyBag)())}function R6(e){(0,vt.hasGenPage)(e.control)&&(0,vt.applyEmbedCellDefaults)(e),e.id||(e.id=_n.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&&O6(e.control),e.bag||(e.bag=(0,Ke.emptyBag)())}function O6(e){var t;(0,vt.hasGenPage)(e)&&(0,vt.applyEmbedControlDefaults)(e),e.id||(e.id=_n.Guid.NewGuid()),e.classId===void 0&&(e.classId=String(qe.ControlClassId.TextboxControl)),e.fieldName===void 0&&(e.fieldName=null),e.type===void 0&&(e.type=e.fieldName?"Field":A_(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,fh.assertXmlName)(r,"Form control parameter name");e.bag||(e.bag=(0,Ke.emptyBag)())}function x6(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"&&!b_(a,"handlerUniqueId")&&a.a.push(["handlerUniqueId",dh(_n.Guid.NewGuid())])}}else if(r.n==="formLibraries")for(let n of r.c)n.n==="Library"&&!b_(n,"libraryUniqueId")&&n.a.push(["libraryUniqueId",dh(_n.Guid.NewGuid())])}}var mc=class{constructor(t=w_.DEFAULT_LCID){this.lcid=t}toArtifact(t,r){var n,i,a;let{tabs:o,bag:s}=h_(t,this.lcid),l={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=t6[t.formType])!==null&&a!==void 0?a:"Main",status:this.readActivationStatus(t),...r!==void 0&&r!==""?{description:r}:{},tabs:o,bag:s};return(0,vt.projectGenPageEmbeds)(l),l}fromArtifact(t){var r;return this.deserialize({formxml:v_(t,this.lcid),formid:t.id||(0,po.newId)(),objecttypecode:t.entityLogicalName,type:fc[t.formType],name:t.name,uniquename:t.name,description:(r=t.description)!==null&&r!==void 0?r:"",formpresentation:rt.FormPresentation.AirForm,formactivationstate:t.status==="Active"?rt.FormActivationState.Active:rt.FormActivationState.InActive})}fromApiResponse(t){var r,n,i,a,o,s,l;let u=t,c=(r=u.formxml)!==null&&r!==void 0?r:"",d=this.deserialize({formxml:c,formid:(n=u.formid)!==null&&n!==void 0?n:(0,po.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 L6(this.toArtifact(d,(l=u.description)!==null&&l!==void 0?l:void 0),c)}toApiPayload(t,r,n){let i=(0,vt.genPageEmbedIssues)(t);if(i.length>0)throw new f_.ValidationError("form",t.id,i);return{formxml:v_(t,this.lcid,n,r),name:t.name,type:fc[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 vh(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=(0,vt.genPageEmbedIssues)(t);if(f.length>0)throw new f_.ValidationError("form",t.id||"(new)",f);let m=t.tabs&&t.tabs.length>0?void 0:W6(this.lcid),h=m!==void 0?m:t.tabs.map(E=>k6(E,this.lcid)).join(""),v=this.deserialize({formxml:`<form><tabs>${h}</tabs></form>`,formid:t.id||(0,po.newId)(),objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",type:fc[(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:rt.FormPresentation.AirForm,formactivationstate:((s=t.status)!==null&&s!==void 0?s:"Active")==="Active"?rt.FormActivationState.Active:rt.FormActivationState.InActive}),b=this.toArtifact(v,t.description);if(t.tabs&&t.tabs.length>0){let E=y_(t);y_(b).forEach((C,N)=>{E[N]&&E[N].label===void 0&&delete C.label,E[N]&&E[N].genPage!==void 0&&(C.genPage=JSON.parse(JSON.stringify(E[N].genPage)))})}return{id:(l=t.id)!==null&&l!==void 0?l:b.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:b.tabs,bag:b.bag}}assignMissingIds(t){return(0,po.assignMissingIds)(t)}normalize(t){return(0,vt.mintEmbedIdentity)(t)}committed(t,r){var n,i,a,o,s,l;let u=r?.formxml;if(typeof u!="string"||!(0,vt.mayCommitEmbedState)(t))return{artifact:t,baseline:t};let c=this.deserialize({formxml:u,formid:t.id||(0,po.newId)(),objecttypecode:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",type:fc[(i=t.formType)!==null&&i!==void 0?i:"Main"],name:(a=t.name)!==null&&a!==void 0?a:"",uniquename:(o=t.name)!==null&&o!==void 0?o:"",description:(s=t.description)!==null&&s!==void 0?s:"",formpresentation:rt.FormPresentation.AirForm,formactivationstate:rt.FormActivationState.Active}),{bag:d}=h_(c,this.lcid),p=(0,vt.commitEmbedState)(t,(l=(0,vt.descriptionsRegion)(d))===null||l===void 0?void 0:l.node);return{artifact:p,baseline:p}}validate(t){return ez(t)}deserialize(t){(0,mh.installDomShim)();let r=Q8.ScriptUtilities.ParseXml(t.formxml),n=new Y8.DeserializationService(this.lcid).deSerializeFormXml(r,new _n.Guid(t.formid),t.objecttypecode,rt.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===rt.FormActivationState.InActive?"Inactive":"Active"}};Wt.FormAdapter=mc;function F6(e){var t;(0,mh.installDomShim)();let r=new DOMParser().parseFromString(e,"text/xml").getElementsByTagName("form")[0],n=new Set;for(let i=(t=r?.firstChild)!==null&&t!==void 0?t:null;i;i=i.nextSibling)i.nodeType===1&&(i.nodeName==="header"||i.nodeName==="footer")&&n.add(i.nodeName);return n}function L6(e,t){var r;if(!(!((r=e.bag)===null||r===void 0)&&r.c))return e;let n=F6(t),i=["header","footer"].filter(o=>!n.has(o)),a=e.bag.c.filter(o=>{var s;return i.includes((s=o?.node)===null||s===void 0?void 0:s.n)}).map(o=>o.i);return a.length>0&&(e.bag.c=e.bag.c.filter(o=>{var s;return!i.includes((s=o?.node)===null||s===void 0?void 0:s.n)}).map(o=>({...o,i:o.i-a.filter(s=>s<o.i).length}))),e}function Rr(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function yh(e,t){return e?`<labels><label description="${Rr(e)}" languagecode="${t}" /></labels>`:""}function bh(e){return e&&e.length>0?Ks(e):(0,po.newId)()}function k6(e,t){var r,n,i,a;let o=(r=e.columns)!==null&&r!==void 0?r:[],s=(o.length>0?o:[z6()]).map(l=>M6(l,t)).join("");return`<tab id="{${Rr(bh(e.id))}}" name="${Rr((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}">${yh(e.label,t)}<columns>${s}</columns></tab>`}function M6(e,t){var r,n;let i=((r=e.sections)!==null&&r!==void 0?r:[]).map(a=>B6(a,t)).join("");return`<column width="${Rr((n=e.width)!==null&&n!==void 0?n:"100%")}"><sections>${i}</sections></column>`}function B6(e,t){var r,n,i,a,o;let s=((r=e.rows)!==null&&r!==void 0?r:[]).map(l=>U6(l,t)).join("");return`<section id="{${Rr(bh(e.id))}}" name="${Rr((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="${ch((o=e.columns)!==null&&o!==void 0?o:1)}">${yh(e.label,t)}<rows>${s}</rows></section>`}function U6(e,t){var r;return`<row>${((r=e.cells)!==null&&r!==void 0?r:[]).map(n=>$6(n,t)).join("")}</row>`}function $6(e,t){var r,n,i,a,o;let s=q6(e),l=s.control,u=l?yh((r=l.label)!==null&&r!==void 0?r:"",t):"",c=l?V6(l):"";return`<cell id="{${Rr(bh(s.id))}}" showlabel="${l?(n=l.showLabel)!==null&&n!==void 0?n:!0:!1}" visible="${(i=s.visible)!==null&&i!==void 0?i:!0}" colspan="${(a=s.colspan)!==null&&a!==void 0?a:1}" rowspan="${(o=s.rowspan)!==null&&o!==void 0?o:1}">${u}${c}</cell>`}function q6(e){if(!(0,vt.hasGenPage)(e.control))return e;let t={...e.control};(0,vt.applyEmbedControlDefaults)(t);let r={...e,control:t};return(0,vt.applyEmbedCellDefaults)(r),r}function V6(e){var t,r,n;let i=e.fieldName?` datafieldname="${Rr(e.fieldName)}"`:"",a=G6(e.parameters),o=e.classId?Ks(e.classId):String(qe.ControlClassId.TextboxControl);return`<control id="${Rr((t=e.id)!==null&&t!==void 0?t:"")}" classid="{${Rr(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 G6(e){let t=Object.keys(e??{});return t.length===0?"":(t.forEach(n=>(0,fh.assertXmlName)(n,"Form control parameter name")),`<parameters>${t.map(n=>`<${n}>${Rr(e[n])}</${n}>`).join("")}</parameters>`)}function z6(){return{width:"100%",sections:[],bag:{a:[],c:[]}}}function W6(e){return`<tab id="{${_n.Guid.NewGuid()}}" name="tab_general" expanded="true" visible="true"><labels><label description="General" languagecode="${e}" /></labels><columns><column width="100%"><sections><section id="{${_n.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 j6(e=w_.DEFAULT_LCID){return{adapter:new mc(e),api:e6.formApi,languageSensitive:!0,publish:(t,r,n)=>(0,p_.publishBoundEntity)(t,n),publishScope:(t,r)=>(0,p_.boundEntityPublishScope)(r),rebaselineAfterPublish:"bracket"}}Wt.formRegistration=j6;var H6=new Set(["id","name","label","expanded","visible","columns","bag"]),K6=new Set(["id","width","sections","bag"]),J6=new Set(["id","name","label","visible","showLabel","columns","rows","bag"]),Q6=new Set(["id","cells","bag"]),X6=new Set(["id","visible","colspan","rowspan","control","bag"]),Y6=new Set(["id","classId","fieldName","type","isRequired","isReadOnly","label","showLabel","parameters","genPage","bag"]),Z6={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 ez(e){let t=[];return(0,zt.childObjects)(e,"tabs","","tab",t).forEach(({node:n,index:i})=>{let a=`/tabs/${i}`;(0,zt.rejectUnknownKeys)(n,H6,a,"tab",t),(0,zt.childObjects)(n,"columns",a,"column",t).forEach(({node:s,index:l})=>{let u=`${a}/columns/${l}`;(0,zt.rejectUnknownKeys)(s,K6,u,"column",t),(0,zt.childObjects)(s,"sections",u,"section",t).forEach(({node:d,index:p})=>{let f=`${u}/sections/${p}`;(0,zt.rejectUnknownKeys)(d,J6,f,"section",t),(0,zt.childObjects)(d,"rows",f,"row",t).forEach(({node:h,index:v})=>{let b=`${f}/rows/${v}`;(0,zt.rejectUnknownKeys)(h,Q6,b,"row",t),(0,zt.childObjects)(h,"cells",b,"cell",t).forEach(({node:C,index:N})=>{let R=`${b}/cells/${N}`;(0,zt.rejectUnknownKeys)(C,X6,R,"cell",t,Z6);let O=C.control;O!=null&&!(0,zt.isJsonObject)(O)?t.push((0,zt.issue)(`${R}/control`,"control-must-be-object-or-null",`a cell control must be a JSON object or null, got ${typeof O}`)):(0,zt.isJsonObject)(O)&&(0,zt.rejectUnknownKeys)(O,Y6,`${R}/control`,"control",t)})})})})}),t.push(...(0,vt.genPageEmbedIssues)(e)),t}Wt.SUBGRID_CLASS_ID=qe.ControlClassId.SubgridControl;Wt.NOTES_CLASS_ID=qe.ControlClassId.TimelineControl;Wt.QUICK_VIEW_CLASS_ID=qe.ControlClassId.QuickViewControl;var tz={Lookup:String(qe.ControlClassId.LookupControl),Customer:String(qe.ControlClassId.LookupControl),Owner:String(qe.ControlClassId.LookupControl),PartyList:String(qe.ControlClassId.PartyListControl),Boolean:String(qe.ControlClassId.BooleanControl),DateTime:String(qe.ControlClassId.DateTimeControl),Decimal:String(qe.ControlClassId.DecimalControl),Double:String(qe.ControlClassId.FloatingNumberControl),Money:String(qe.ControlClassId.CurrencyControl),Integer:String(qe.ControlClassId.IntegerControl),BigInt:String(qe.ControlClassId.IntegerControl),Memo:String(qe.ControlClassId.TextAreaControl),String:String(qe.ControlClassId.TextboxControl)},rz="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE";function D_(e){return e==="Picklist"||e==="State"||e==="Status"?rz:e&&tz[e]||String(qe.ControlClassId.TextboxControl)}Wt.classIdForAttributeType=D_;function b_(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}});var wh=y(fo=>{"use strict";Object.defineProperty(fo,"__esModule",{value:!0});fo.viewApi=fo.findDefaultViews=void 0;var T_=Pt(),Xt=be(),tn=ae(),nz="savedqueryid,name,description,fetchxml,layoutxml,querytype,returnedtypecode,isdefault",iz="savedqueryid,name,returnedtypecode,querytype,isdefault";async function az(e,t,r={}){var n;let i=new Set(((n=r.excludeViewIds)!==null&&n!==void 0?n:[]).filter(Boolean)),a=`returnedtypecode eq '${(0,tn.odataLiteral)(t)}' and querytype eq 0`,o=`/savedqueries${(0,tn.odataQuery)([["$select","savedqueryid,name,isdefault"],["$filter",a]])}`;return(await(0,T_.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:"")}})}fo.findDefaultViews=az;async function oz(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,tn.odataPathLiteral)(t)}')${(0,tn.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 __(e,t,r){if(!r||!/<grid\b/.test(t)||/<grid[^>]*\bobject=/.test(t))return t;let n=await oz(e,r);return n===void 0?t:t.replace(/<grid\b/,`<grid object="${n}"`)}fo.viewApi={async get(e,t){let r=(0,tn.normalizeGuid)(t,"id"),n=await(0,Xt.readRowEtag)(e,"savedqueries","savedqueryid",r),i=`/savedqueries(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,tn.odataQuery)([["$select",nz]]);return{raw:(0,Xt.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},readToken(e,t){return(0,Xt.readRowEtag)(e,"savedqueries","savedqueryid",(0,tn.normalizeGuid)(t,"id"))},async list(e,t){let r=`/savedqueries${(0,tn.odataQuery)([["$select",iz],["$filter",t?.entityLogicalName?`returnedtypecode eq '${(0,tn.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,T_.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,Xt.echoWrite)("savedqueryid"),a=`/savedqueries${i.query}`,o=await __(e,n.layoutxml,n.returnedtypecode),s=(0,Xt.ensureSuccess)(await e.post(a,(0,Xt.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,Xt.resolveCreatedId)(s,"savedqueryid","view",r),etag:(0,Xt.readEtag)(s)}},async update(e,t,r,n){let i=r,a=(0,tn.normalizeGuid)(t,"id"),o=(0,Xt.echoWrite)("savedqueryid",{"If-Match":(0,Xt.requireEtag)(n,"view",a)}),s=`/savedqueries(${a})${o.query}`,l=await __(e,i.layoutxml,i.returnedtypecode),u=(0,Xt.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,Xt.readEtag)(u)}},delete(e,t){return(0,Xt.deleteRecord)(e,"savedqueries",t)}}});var z_=y(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.viewRegistration=mo.ViewAdapter=void 0;var k_=te(),Yt=Cr(),Ah=Kn(),Ji=_i(),P_=Nr(),sz=wh(),Eh=Qn(),lz=lt(),M_=100,bc=class{toArtifact(t){var r,n,i,a,o,s,l,u;(0,Eh.installDomShim)();let c=(r=t.fetchxml)!==null&&r!==void 0?r:"",d=(n=t.layoutxml)!==null&&n!==void 0?n:"",p=(0,Ji.parseXmlRoot)(c,"<fetch/>"),f=(0,Ji.parseXmlRoot)(d,"<grid/>"),m=U_(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:cz(p),queryType:(l=t.querytype)!==null&&l!==void 0?l:0,isDefault:(u=t.isdefault)!==null&&u!==void 0?u:!1,columns:B_(f,p),filters:q_(p),sort:$_(p),...m.length>0?{linkEntities:m}:{},fetchBag:c?(0,Ji.projectElementBag)(p):void 0,layoutBag:d?(0,Ji.projectElementBag)(f):void 0}}fromArtifact(t){(0,Eh.installDomShim)();let{fetchxml:r,layoutxml:n}=R_(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,Eh.installDomShim)();let{fetchxml:s,layoutxml:l}=R_(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,lz.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,Yt.childObjects)(n,"columns","","column",r),(0,Yt.childObjects)(n,"sort","","sort",r),(0,Yt.childObjects)(n,"linkEntities","","linkEntity",r),uz(n.linkEntities,r);let i=n.filters;return i!=null&&((0,Yt.isJsonObject)(i)?Ch(i,"/filters",r):r.push((0,Yt.issue)("/filters","filters-must-be-object",`filters must be a JSON object, got ${typeof i}`))),r}};mo.ViewAdapter=bc;function uz(e,t){Array.isArray(e)&&e.forEach((r,n)=>{if(!(0,Yt.isJsonObject)(r))return;for(let a of["name","from","to"]){let o=r[a];(typeof o!="string"||o.trim()==="")&&t.push((0,Yt.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,Yt.isJsonObject)(i)?Ch(i,`/linkEntities/${n}/filters`,t):t.push((0,Yt.issue)(`/linkEntities/${n}/filters`,"filters-must-be-object",`filters must be a JSON object, got ${typeof i}`)))})}function Ch(e,t,r){(0,Yt.childObjects)(e,"conditions",t,"condition",r),(0,Yt.childObjects)(e,"groups",t,"filterGroup",r).forEach(({node:i,index:a})=>Ch(i,`${t}/groups/${a}`,r))}function cz(e){var t;let r=e.getElementsByTagName("entity")[0];return(t=r?.getAttribute("name"))!==null&&t!==void 0?t:""}function B_(e,t){var r;let n=Sh(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)?M_: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 Sh(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 U_(e){let t=e.getElementsByTagName("entity")[0];if(!t)return[];let r=[];for(let n of yt(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=yt(n,"filter").find(c=>!wc(c));r.push({name:i,from:a,to:o,...s?{alias:s}:{},...l==="inner"||l==="outer"?{linkType:l}:{},...u?{filters:Nh(u)}:{}})}return r}function $_(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 q_(e){let t=e.getElementsByTagName("entity")[0],r={type:"and",conditions:[],groups:[]};if(!t)return r;let n=yt(t,"filter").filter(i=>!wc(i)).map(Nh);return n.length===0?r:n.length===1?n[0]:{type:"and",conditions:[],groups:n}}function wc(e){if(e.getAttribute("isquickfindfields")==="1")return!0;if(yt(e,"filter").length>0)return!1;let t=yt(e,"condition");return t.length===0?!1:t.some(r=>r.getAttribute("isquickfindfields")==="1"||yt(r,"value").length>0||pz(r))}var dz=new Set(["attribute","operator","value","entityname","uiname","uitype"]);function pz(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&&!dz.has(i))return!0}return!1}function Nh(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(Nh(l))}return{type:n,conditions:i,groups:a}}function yt(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 Dh=e=>{var t,r;return`${(t=e.relatedEntity)!==null&&t!==void 0?t:""}::${(r=e.sourceAttribute)!==null&&r!==void 0?r:e.name}`};function fz(e,t){let r=Sh(e),n=new Map;for(let i of t){if(!i.relatedEntity)continue;let a=r.get(i.name);if(a){let o=Dh(i),s=n.get(o);s?s.push(a.link):n.set(o,[a.link])}}return n}function mz(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(Dh(s));return!!l&&l.some(u=>!i.has(u))});if(o.length!==0)throw new k_.ValidationError("view",e.id,o.map(s=>(0,Yt.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 R_(e){let t=hz(e.columns);if(!O_(e.fetchBag)||!O_(e.layoutBag))return{fetchxml:Iz({...e,columns:t}),layoutxml:_z({...e,columns:t},`${e.entityLogicalName}id`)};let r=new DOMParser().parseFromString("<root/>","text/xml"),n=x_(e.fetchBag,"fetch",r),i=x_(e.layoutBag,"grid",r),a=B_(i,n),o=!yc(t,a),s=!yc(e.sort,$_(n)),l=!yc(e.filters,q_(n)),u=e.linkEntities,c=u!==void 0&&!yc(u,U_(n)),d=c?fz(n,a):void 0;return c&&Sz(r,n,u),c&&(Dz(e,n,t,d),mz(e,n,t,d)),o?(F_(r,n,t,a),bz(r,i,t)):c&&F_(r,n,t,a),s&&Ez(r,n,e.sort),l&&Cz(r,n,e.filters),{fetchxml:(0,Ji.serializeNode)(n),layoutxml:(0,Ji.serializeNode)(i)}}function hz(e){return(e??[]).map((t,r)=>{var n,i;return{name:String(t.name).toLowerCase(),width:(n=t.width)!==null&&n!==void 0?n:M_,order:(i=t.order)!==null&&i!==void 0?i:r,...t.relatedEntity?{relatedEntity:t.relatedEntity}:{},...t.sourceAttribute?{sourceAttribute:String(t.sourceAttribute).toLowerCase()}:{}}})}function O_(e){return!!e&&(e.c.length>0||e.a.length>0)}function x_(e,t,r){let n={n:t,a:(0,Ah.mergeAttrs)(e.a,[]),c:(0,Ah.spliceChildren)(e.c,[])};return(0,Ah.rebuildRaw)(n,(0,Ji.domEngine)(r),null)}function F_(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))||gz(o,d);let u=Sh(t),c=new Set(yt(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||!G_(o,d.relatedEntity)))continue;let f=vz(e,o,d.relatedEntity),m=e.createElement("attribute");V_(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),yz(o,p),c.add(d.name)}}function V_(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 gz(e,t){if(t.relatedEntity){for(let r of yt(e,"link-entity"))if(!(r.getAttribute("alias")!==t.relatedEntity&&r.getAttribute("name")!==t.relatedEntity)){for(let n of yt(r,"attribute"))if((n.getAttribute("alias")||n.getAttribute("name"))===t.name){r.removeChild(n);return}}return}for(let r of yt(e,"attribute"))if(r.getAttribute("name")===t.name){e.removeChild(r);return}}function G_(e,t,r=!1){let n=a=>a.getAttribute("alias")===t||a.getAttribute("name")===t;for(let a of yt(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 vz(e,t,r){let n=G_(t,r);if(n)return n;let i=e.createElement("link-entity");return i.setAttribute("name",r),t.appendChild(i),i}function yz(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 bz(e,t,r){let n=t.getElementsByTagName("row")[0];if(!n)return;let i=[...r].sort((s,l)=>s.order-l.order),a=wz(n);if(Az(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 wz(e){return yt(e,"cell").filter(t=>!!t.getAttribute("name")&&t.getAttribute("ishidden")!=="1")}function Az(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 Ez(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 yt(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(b=>!l.has(b)),v=(f=h.find(b=>!b.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 Cz(e,t,r){let n=t.getElementsByTagName("entity")[0];if(n){for(let i of yt(n,"filter"))wc(i)||n.removeChild(i);(r.conditions.length>0||r.groups.length>0)&&n.appendChild(Js(e,r))}}function yc(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Sz(e,t,r){var n;let i=t.getElementsByTagName("entity")[0];if(!i)return;let a=yt(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 b=a.filter(N=>!l.has(N)&&m(N,h));if(b.length!==1)return;let E=b[0];r.some((N,R)=>R!==v&&!s[R]&&m(E,N))||(s[v]=E,l.add(E))})};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((b,E)=>{s[b]=v[E],l.add(v[E])})}r.forEach((m,h)=>{let v=s[h];if(v){L_(e,v,m);return}let b=e.createElement("link-entity");L_(e,b,m),i.appendChild(b)});for(let m of a)l.has(m)||i.removeChild(m)}var Nz=new Set(["inner","outer"]);function Dz(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(Dh(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 k_.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,Yt.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 L_(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):Nz.has(t.getAttribute("link-type")||"")&&t.removeAttribute("link-type");let n=yt(t,"filter").find(a=>!wc(a)),i=r.filters&&(r.filters.conditions.length>0||r.filters.groups.length>0)?Js(e,r.filters):null;n&&i?t.replaceChild(i,n):n?t.removeChild(n):i&&t.appendChild(i)}function Iz(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(Js(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){V_(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(Js(r,e.filters)),new XMLSerializer().serializeToString(r)}function Js(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(Js(e,n));return r}function _z(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 Tz(){return{adapter:new bc,api:sz.viewApi,publish:(e,t,r)=>(0,P_.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,P_.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}mo.viewRegistration=Tz});function Ac(e,t){return e==="SetFieldValue"&&t!==void 0&&Pz.has(t.attributeType)&&(t.requiredLevel==="None"||t.requiredLevel==="Recommended")}var Pz,Ih=T(()=>{"use strict";Pz=new Set(["Integer","Double","Decimal","Money","String","Memo","DateTime","Picklist","Lookup"])});function W_(e){return e!=="Entity"&&e!=="AllForms"&&typeof e=="string"&&e.trim()!==""}function _h(e){return e==="AllForms"||W_(e)?1:2}function Th(e){return W_(e)?e:null}function j_(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:ho.WorkflowCategory.BusinessRule,type:ho.WorkflowTypeCode.Definition,mode:1,scope:ho.WorkflowScope.Organization,primaryentity:e.entityLogicalName,iscrmuiworkflow:!0,processtriggerscope:_h(e.scope),processtriggerformid:Th(e.scope)}}var ho,H_=T(()=>{"use strict";ho=ce(Ai());});function K_(e,t=0){return(ct[e[t+0]]+ct[e[t+1]]+ct[e[t+2]]+ct[e[t+3]]+"-"+ct[e[t+4]]+ct[e[t+5]]+"-"+ct[e[t+6]]+ct[e[t+7]]+"-"+ct[e[t+8]]+ct[e[t+9]]+"-"+ct[e[t+10]]+ct[e[t+11]]+ct[e[t+12]]+ct[e[t+13]]+ct[e[t+14]]+ct[e[t+15]]).toLowerCase()}var ct,J_=T(()=>{ct=[];for(let e=0;e<256;++e)ct.push((e+256).toString(16).slice(1))});function Ph(){return Ec>Cc.length-16&&((0,Q_.randomFillSync)(Cc),Ec=0),Cc.slice(Ec,Ec+=16)}var Q_,Cc,Ec,X_=T(()=>{Q_=require("crypto"),Cc=new Uint8Array(256),Ec=Cc.length});var Y_,Rh,Z_=T(()=>{Y_=require("crypto"),Rh={randomUUID:Y_.randomUUID}});function Rz(e,t,r){if(Rh.randomUUID&&!t&&!e)return Rh.randomUUID();e=e||{};let n=e.random??e.rng?.()??Ph();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 K_(n)}var Nt,eT=T(()=>{Z_();X_();J_();Nt=Rz});var Oh=T(()=>{eT()});var tT=T(()=>{"use strict";});var xh=y(pr=>{"use strict";Object.defineProperty(pr,"__esModule",{value:!0});pr.WorkflowConditionOperator=pr.WorkflowAttributeType=pr.SystemStep=pr.FieldRequiredLevelTypes=pr.AttributeDateTimeBehavior=void 0;pr.AttributeDateTimeBehavior={None:0,Dynamic:1,DateOnly:2,StaticTimeZoneInvariant:3,UserLocal:4};pr.FieldRequiredLevelTypes={None:"0",Required:"1",Recommended:"2"};pr.SystemStep={IdentifyContact:"IdentifyContact",IdentifyAccount:"IdentifyAccount",IdentifyCustomer:"IdentifyCustomer",IdentifyCase:"IdentifyCase",Solution:"Solution",Resolve:"Resolve"};pr.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"};pr.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 aT(e){switch(e){case"Boolean":return Ne.WorkflowAttributeType.Boolean;case"Customer":return Ne.WorkflowAttributeType.Customer;case"DateTime":return Ne.WorkflowAttributeType.DateTime;case"Decimal":return Ne.WorkflowAttributeType.Decimal;case"Double":return Ne.WorkflowAttributeType.Float;case"Integer":return Ne.WorkflowAttributeType.Integer;case"Lookup":return Ne.WorkflowAttributeType.Lookup;case"Money":return Ne.WorkflowAttributeType.Money;case"Owner":return Ne.WorkflowAttributeType.Owner;case"Picklist":return Ne.WorkflowAttributeType.Picklist;case"State":return Ne.WorkflowAttributeType.State;case"Status":return Ne.WorkflowAttributeType.Status;case"Uniqueidentifier":case"UniqueIdentifier":return Ne.WorkflowAttributeType.UniqueIdentifier;case"BigInt":return Ne.WorkflowAttributeType.BigType;default:return Ne.WorkflowAttributeType.String}}function pT(e){return e&&e!==Ne.WorkflowAttributeType.String?e:void 0}function Fz(e){return{__class:dT,parameterName:"primaryEntity",entityName:e}}function rT(e){return{__class:Lh,type:Fh,typeSet:!1,behavior:Ne.AttributeDateTimeBehavior.None,method:oT,parameters:[e]}}function nT(e,t,r=Ne.WorkflowAttributeType.String){return{__class:lT,type:r,behavior:Ne.AttributeDateTimeBehavior.None,typeSet:!1,entity:Fz(t),attributeName:e}}function Lz(e,t=Ne.WorkflowAttributeType.String){return{__class:uT,type:t,behavior:Ne.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function kz(e){return{__class:cT,type:Fh,typeSet:!1,behavior:Ne.AttributeDateTimeBehavior.None,days:e,hours:"0",minutes:"0",months:"0",years:"0"}}function fT(e,t){let r=Oz[e.operator],n=rT(nT(e.leftField,t,e.leftWorkflowType)),i;e.dateArithmetic?i=kz(e.right.value??"0"):e.right.kind==="field"?i=nT(e.right.field??"",t,e.right.workflowType):i=Lz(e.right.value??"",e.right.workflowType??e.leftWorkflowType);let a=rT(i);return{__class:Lh,type:Fh,typeSet:!1,behavior:Ne.AttributeDateTimeBehavior.None,method:sT,parameters:[r,n,a]}}function mT(e){return typeof e=="object"&&e.__class===Lh}function Mz(e){return typeof e=="object"&&e.__class===cT}function Sc(e){return mT(e)&&e.method===oT&&e.parameters.length>0?Sc(e.parameters[0]):e}function iT(e){if(typeof e!="object"||e.__class!==lT)return null;let t=e.entity;if(t&&t.__class&&t.__class!==dT)return null;let r=e.attributeName;return r?{field:r,workflowType:pT(e.type)}:null}function hT(e){if(!e)return null;let t=Sc(e);if(!mT(t)||t.method!==sT||t.parameters.length!==3)return null;let r=t.parameters[0],n=xz[String(r)];if(!n)return null;let i=iT(Sc(t.parameters[1]));if(!i)return null;let a=Sc(t.parameters[2]);if(Mz(a))return n!=="+"&&n!=="-"?null:{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:String(a.days??"")},dateArithmetic:!0};let o=iT(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===uT){let s=a.primitiveValue;return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:s!=null?String(s):"",workflowType:pT(a.type)}}}return null}function Mh(e){let t=(e??"").trim();if(!/^\d+$/.test(t))return!1;let r=Number(t);return Number.isSafeInteger(r)&&r>=kh&&r<=go}function Qi(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&&!Mh(t)?"invalidDayCount":null}function vo(e){return Qi(e)===null}var Ne,oT,sT,Fh,lT,uT,Lh,cT,dT,Oz,xz,kh,go,Qs=T(()=>{"use strict";Ne=ce(xh());oT="0",sT="3",Fh="0",lT="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",uT="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",Lh="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",cT="TimeSpanExpression:#Microsoft.Crm.Workflow.Expressions",dT="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions";Oz={"+":0,"-":1,"*":2,"/":3},xz={0:"+",1:"-",2:"*",3:"/"};kh=0,go=2147483647});function Uz(e){return e.startsWith("__")&&!Bz.has(e)}function $z(e){let t=Object.create(null);return Object.keys(e).forEach(r=>{Uz(r)&&(t[r]=e[r])}),Object.keys(t).length>0?t:void 0}function DT(e){return e.__class==="BinaryExpression:#Microsoft.Crm.Workflow.Expressions"}function Ys(e){return e.__class==="UnaryExpression:#Microsoft.Crm.Workflow.Expressions"}function Bh(e){return DT(e)||Ys(e)}function qz(e){return e.__class==="ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel"}function Xs(){return{list:[]}}function Uh(e,t,r){return e&&e.list.length>0?{list:[{...e.list[0],description:t},...e.list.slice(1)]}:{list:[{labelId:Nt(),languageCode:r,description:t}]}}function Vh(e){return{__class:"PrimaryEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:"primaryEntity",entityName:e}}function _c(e,t,r){return{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:W.AttributeDateTimeBehavior.None,typeSet:!1,entity:Vh(t),attributeName:e}}function bo(e,t){return{__class:"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",type:t,behavior:W.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function zz(e){return e.bpfField==="StageCategory"?e.stageType==="SelectedStage"?TT:_T:IT}function PT(e){return e.bpfField==="StageCategory"?W.WorkflowAttributeType.BpfStageCategory:W.WorkflowAttributeType.BpfProcess}function Wz(e,t){let r=PT(e),n=e.bpfField==="StageCategory"?{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:W.AttributeDateTimeBehavior.None,typeSet:!1,entity:{__class:"RelatedEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:`related_${vT}_${gT}`,entityName:gT,relatedAttributeName:vT},attributeName:Gz}:_c(Vz,t,r);return{__class:"MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:W.AttributeDateTimeBehavior.None,typeSet:!1,method:Gh,parameters:[zz(e),n]}}function jz(e){let t=e;if(t.__class!=="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"||String(t.method)!==Gh)return null;let r=(t.parameters??[])[0];if(typeof r!="string")return null;let n=r.replace(/^"+|"+$/g,"");return n===_T?{bpfField:"StageCategory",stageType:"ActiveStage"}:n===TT?{bpfField:"StageCategory",stageType:"SelectedStage"}:n===IT?{bpfField:"ProcessName"}:null}function Nc(e){if(!e)return!1;let t=e;if(t.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"&&String(t.method)===Gh){let r=(t.parameters??[])[0];if(typeof r=="string"&&Hz.has(r.replace(/^"+|"+$/g,"")))return!0}return Ys(e)?Nc(e.operand):DT(e)?Nc(e.left)||(e.right??[]).some(Nc):!1}function RT(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:bo(e.id.replace(/[{}]/g,""),W.WorkflowAttributeType.UniqueIdentifier)}}function yT(e){return e==="ContainsData"||e==="DoesNotContainData"}function bT(e,t){return{__class:"UnaryExpression:#Microsoft.Crm.Workflow.Expressions",type:W.WorkflowAttributeType.Boolean,behavior:W.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:t,operand:e}}function wT(e,t){let r=e.valueType==="Lookup"?e.lookupValue?.workflowType??W.WorkflowAttributeType.Lookup:e.valueWorkflowType??W.WorkflowAttributeType.String,n=qh[e.operator]??W.WorkflowConditionOperator.Equal;if(e.source==="BusinessProcess"){let o=Wz(e,t);if(yT(e.operator))return bT(o,n);let s=PT(e);return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:W.WorkflowAttributeType.Boolean,behavior:W.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:o,right:[bo(e.value??"",s)]}}let i=_c(e.field,t,r);if(yT(e.operator))return bT(i,n);let a;if(e.valueType==="Field"&&e.valueField)a=[_c(e.valueField,t,r)];else if(e.valueType==="Lookup"){if(!e.lookupValue)throw new Error("Lookup condition is missing its record value.");a=[RT(e.lookupValue)]}else e.valueType==="Clear"?a=[bo(null,r)]:e.valueType==="Expression"?a=[Ic(e.valueType,e.value,e.valueField,t,e.expression,e.rawExpression)]:a=[bo(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 Kz(e,t,r){if(e.length===0)return null;let n=wT(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:W.WorkflowAttributeType.Boolean,behavior:W.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:a==="AND"?W.WorkflowConditionOperator.LogicalAnd:W.WorkflowConditionOperator.LogicalOr,left:n,right:[wT(e[i],r)]}}return n}function Dc(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=hT(e);return t?{valueType:"Expression",expression:t}:{valueType:"Expression",rawExpression:e}}return{valueType:"Value",value:""}}function Jz(e){let t=NT[e.conditionOperatoroperator]??"Equals",r=t==="ContainsData"||t==="DoesNotContainData",n=Ys(e)?e.operand:e.left,i=Ys(e)?[]:e.right,a=jz(n);if(a){let d=i[0];return{id:Nt(),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"}:Dc(i[0]),c=u.valueWorkflowType??l;return{id:Nt(),field:s,fieldDisplayName:s,operator:t,...u,...c?{valueWorkflowType:c}:{}}}function AT(e){if(!e||!Bh(e))return{clauses:[],logic:"AND"};let t=[],r=(a,o)=>{let s=a.conditionOperatoroperator;if(Ys(a)||s!==W.WorkflowConditionOperator.LogicalAnd&&s!==W.WorkflowConditionOperator.LogicalOr){t.push({...Jz(a),...o?{connector:o}:{}});return}let l=s===W.WorkflowConditionOperator.LogicalAnd?"AND":"OR";Bh(a.left)&&r(a.left,o),a.right.filter(Bh).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 Ic(e,t,r,n,i,a,o,s){if(e==="Field"&&r)return _c(r,n,W.WorkflowAttributeType.String);if(e==="Expression"){if(i)return fT(i,n);if(a!=null)return a}return e==="Lookup"&&o?RT(o):e==="Clear"?bo(null,s??W.WorkflowAttributeType.String):bo(t??"",W.WorkflowAttributeType.String)}function $h(e,t){return{propertyName:e,propertyValueExpr:t}}function yo(e){return`Step_${e.value++}`}function fr(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 ET(e,t,r){return e&&!r.used.has(e)?(r.used.add(e),e):fr(t,r)}function Qz(e){return e===ST.StateCode.Activated?"Active":"Draft"}function Xz(e,t){let r=e.processtriggerscope,n=e.processtriggerformid;return r===1?n&&n.trim()!==""?n:"AllForms":r===2?"Entity":t??"Entity"}function OT(e,t=1033){return new wo({languageCode:t}).serialize(e)}function xT(e){return new wo().deserialize(e)}var ST,W,Bz,qh,NT,Gh,IT,_T,TT,Vz,Gz,gT,vT,Hz,zh,wo,Wh=T(()=>{"use strict";Oh();ST=ce(Ai());tT();Qs();W=ce(xh());Bz=new Set(["__class"]);qh={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},NT={};for(let e of Object.keys(qh))NT[qh[e]]=e;Gh="23",IT="BpfProcess",_T="ActiveStageCategory",TT="SelectedStageCategory",Vz="processid",Gz="stagecategory",gT="processstage",vT="stageid";Hz=new Set(["ActiveStage","SelectedStage","Stage"]);zh={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"};wo=class{resolveLabel;languageCode;entityName="";stepCounter={value:0};idCounter={counts:{},used:new Set};constructor(t={}){this.resolveLabel=t.resolveLabel??(r=>zh[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??Nt(),name:r?.name??"Step_0",description:r!==void 0?r.description:t.description||null,stepLabels:Xs(),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:fr("SetAttributeValueStep",this.idCounter),description:t.displayName||"New Action",name:t.stepName??yo(this.stepCounter),stepLabels:{list:[]},specification:$h(t.field,Ic(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType)),entity:Vh(this.entityName)}}makeRecommendationActionStep(t,r,n){let i=r.map(l=>this.makeApplyActionStep(l)),a=t??"",o=n?.stepLabels,s=Uh(o,a,this.languageCode);return{__class:"ActionStep:#Microsoft.Crm.Workflow.ObjectModel",id:ET(n?.id,"ActionStep",this.idCounter),name:n?.name??yo(this.stepCounter),description:n?.description??"Action step",stepLabels:s,steps:{list:i},actionId:null,actionType:n?.actionType??"4",processId:n?.processId??Nt(),uniqueName:n?.uniqueName??`id_${Nt().replace(/-/g,"")}ActionStep`}}serializeAction(t){let r=Vh(this.entityName),n=t.stepName??yo(this.stepCounter),i=t.stepLabels??Xs(),a={name:n,stepLabels:i,description:t.displayName},o=t.type;switch(o){case"SetFieldValue":return{...a,id:fr("SetAttributeValueStep",this.idCounter),__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:$h(t.field,Ic(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"SetDefaultValue":return{...a,id:fr("SetDefaultValueStep",this.idCounter),__class:"SetDefaultValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:$h(t.field,Ic(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"LockUnlock":return{...a,id:fr("SetDisplayModeStep",this.idCounter),__class:"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isReadOnly:t.lock,entity:r};case"SetBusinessRequired":return{...a,id:fr("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:fr("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=Uh(t.stepLabels,s,this.languageCode);return{...a,id:fr("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=Uh(t.stepLabels,s,this.languageCode),u={list:[this.makeRecommendationActionStep(t.acceptanceText,t.applyActions??[],t.recommendationActionStepMeta)]};return{...a,id:fr("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??yo(this.stepCounter),n=fr("ConditionStep",this.idCounter),i=[],a=t,o=!0;for(;a;){let s=a.rawConditionExpression??Kz(a.clauses,a.logic,this.entityName),l=o?a.branchName??yo(this.stepCounter):yo(this.stepCounter),c={__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:o?ET(a.branchId,"ConditionBranchStep",this.idCounter):fr("ConditionBranchStep",this.idCounter),name:l,description:a.displayName,stepLabels:Xs(),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:Xs(),containsElsebranch:i.length>1,steps:{list:i}}}makeTerminalElseBranch(t){return{__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:fr("ConditionBranchStep",this.idCounter),name:"Else",description:null,stepLabels:Xs(),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??Nt():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:$z(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:Xz(r,i?.formId),status:Qz(t.statecode),rootCondition:n,wfomRoot:i}}deserializeConditionStep(t){let r=(t.steps?.list??[]).filter(qz);return this.buildConditionNodeFromBranches(r,t,!0)}buildConditionNodeFromBranches(t,r,n){let[i,...a]=t,{clauses:o,logic:s}=AT(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)??Nt(),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,...Nc(i?.conditionExpression)?{rawConditionExpression:i?.conditionExpression}:{}}}deserializeElseChain(t,r){if(t.length===0)return[];let[n]=t,{clauses:i}=AT(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||Nt(),field:u?.propertyName??"",stepName:l.name??void 0,displayName:l.description??void 0,...Dc(u?.propertyValueExpr)}}),meta:i,acceptanceText:o}}deserializeAction(t){switch(t.__class){case"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=Dc(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=Dc(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 FT=T(()=>{"use strict";});function fi(e){return!Yz.has(e)}function BT(e){return e==="Equals"||e==="DoesNotEqual"}function Tc(e){return kT.has(e)?Zz:i7.has(e)?e7:MT.has(e)?t7:o7.has(e)?n7:r7}function UT(e){return Tc(e)[0]}function $T(e,t){return Tc(t).includes(e)}function LT(e){return kT.has(e)?"string":e==="Money"?"money":e==="Integer"||e==="BigInt"?"integer":e==="Decimal"||e==="Double"?"decimal":MT.has(e)?"date":a7.has(e)?"boolean":"other"}function Pc(e,t){let r=LT(e),n=LT(t);return r==="other"||n==="other"?e===t:r===n}var Yz,Zz,e7,t7,r7,n7,kT,i7,MT,a7,o7,jh=T(()=>{"use strict";FT();Yz=new Set(["ContainsData","DoesNotContainData"]);Zz=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],e7=["Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],t7=["On","NotOn","Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],r7=["Equals","DoesNotEqual","ContainsData","DoesNotContainData"],n7=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],kT=new Set(["String","Memo","EntityName"]),i7=new Set(["Integer","BigInt","Money","Decimal","Double"]),MT=new Set(["DateTime"]),a7=new Set(["Boolean"]),o7=new Set(["Lookup","Owner","Customer"])});function Qh(e){return s7.has(e.type)}function Hh(e,t,r,n,i,a,o){let s=i.get(r);!s||!l7.has(s.attributeType)||n!=="Value"||o?.operator&&!BT(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 Kh(e){return!!(e?.entityType?.trim()&&e.id?.trim())}function Jh(e,t,r){return{nodeId:e,kind:"INVALID_DAY_COUNT",message:`Please enter a whole number of days between 0 and ${go}.`,target:t,itemId:r,messageKey:"Validation.InvalidDayCount",messageParams:{max:go}}}function qT(e,t,r,n,i,a,o,s){if(i!=="Clear")return;let l=a.get(n);Ac(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 Oc(e){if(!e)return!1;for(let t of[...e.trueBranch,...e.falseBranch])if(t.kind==="action"){if(Qh(t))return!0}else if(Oc(t))return!0;return!1}function Xh(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=Xh(r,t);if(n)return n}}return null}function Ao(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=Ao(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=Ao(n,t);if(i)return i}}return null}function Yh(e,t){return{...e,trueBranch:VT(e.trueBranch,t),falseBranch:VT(e.falseBranch,t)}}function VT(e,t){return e.filter(r=>r.id!==t).map(r=>r.kind==="condition"?Yh(r,t):r)}function mi(e,t,r){return e.id===t?r(e):{...e,trueBranch:e.trueBranch.map(n=>n.kind==="condition"?mi(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="condition"?mi(n,t,r):n)}}function Rc(e,t,r){return{...e,trueBranch:e.trueBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?Rc(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?Rc(n,t,r):n)}}function GT(e,t,r,n){return mi(e,t,i=>({...i,trueBranch:r==="true"?[...i.trueBranch,n]:i.trueBranch,falseBranch:r==="false"?[...i.falseBranch,n]:i.falseBranch}))}function Zh(e){return e.length===1&&e[0].kind==="condition"}function c7(e){let t=0,r=e??void 0;for(;r;){t+=1;let{falseBranch:n}=r;if(Zh(n)){r=n[0];continue}n.length>0&&(t+=1),r=void 0}return t}function d7(e){return!!e&&c7(e)<u7}function p7(e,t){if(!e)return;let r=(n,i)=>{if(n.id===t)return i;let a=[];if(Zh(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 zT(e,t,r){let n=p7(e,t);return!n||!d7(n)?e:mi(e,t,i=>WT(i,r))}function WT(e,t){if(Zh(e.falseBranch))return{...e,falseBranch:[WT(e.falseBranch[0],t)]};let r=eg(t);return r.falseBranch=e.falseBranch,{...e,falseBranch:[r]}}function jT(e,t){let r=Ao(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 mi(e,r.node.id,a=>({...a,falseBranch:i}))}function HT(e,t,r){let n=Ao(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 mi(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 eg(e){return{kind:"condition",id:Nt(),displayName:e??"New Condition",clauses:[],logic:"AND",trueBranch:[],falseBranch:[],isCollapsed:!1}}function KT(e,t){let r={kind:"action",id:Nt(),type:e,displayName:t??`New ${e}`};switch(e){case"Recommendation":return{...r,type:"Recommendation",field:"",recommendationTitle:"",messageText:"",applyActions:[{id:Nt(),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 JT(e){if(!e)return[];let t=[];return QT(e,t),[...new Set(t)]}function QT(e,t){e.clauses.forEach(r=>{r.field&&t.push(r.field)}),[...e.trueBranch,...e.falseBranch].forEach(r=>{r.kind==="condition"?QT(r,t):"field"in r&&r.field&&t.push(r.field)})}function XT(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 YT(e,r,n),Oc(e)||r.push({nodeId:"root",kind:"NO_ACTION",message:"A business rule must include at least one action step.",target:"node"}),r}function YT(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?Qi(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(fi(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(fi(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 fi(i.operator)&&i.valueType==="Expression"&&!i.rawExpression&&!vo(i.expression)&&t.push(a==="invalidDayCount"?Jh(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"});fi(i.operator)&&i.valueType==="Lookup"&&(Kh(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"})),fi(i.operator)&&Hh(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")YT(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&&!Pc(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:Qi(i.expression);!i.rawExpression&&!vo(i.expression)&&t.push(a==="invalidDayCount"?Jh(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"&&!Kh(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&&(Hh(i.id,i.type,i.field,i.valueType,r,t,{target:"actionValue"}),qT(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:Qi(o.expression);!o.rawExpression&&!vo(o.expression)&&t.push(s==="invalidDayCount"?Jh(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"?Kh(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&&(Hh(i.id,"Recommendation",o.field,o.valueType,r,t,{target:"applyActionValue",itemId:o.id}),qT(i.id,"Recommendation","SetFieldValue",o.field,o.valueType,r,t,{target:"applyActionValue",itemId:o.id}))})}}})}var s7,l7,u7,tg=T(()=>{"use strict";Oh();Ih();jh();Qs();s7=new Set(["LockUnlock","ShowErrorMessage","Recommendation","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]);l7=new Set(["Lookup","Customer","Owner"]);u7=10});var ZT={};pn(ZT,{DAY_COUNT_MAX:()=>go,DAY_COUNT_MIN:()=>kh,DEFAULT_DESERIALIZE_LABELS:()=>zh,WorkflowJsonMapper:()=>wo,addElseIfInTree:()=>zT,appendToBranch:()=>GT,areFieldKindsCompatible:()=>Pc,attributeTypeToWorkflowType:()=>aT,buildWorkflowEntity:()=>j_,collectUsedFields:()=>JT,createEmptyAction:()=>KT,createEmptyCondition:()=>eg,deserializeWorkflowJson:()=>xT,findNode:()=>Xh,findParent:()=>Ao,getDefaultOperatorForFieldType:()=>UT,getExpressionModelIssue:()=>Qi,getOperatorsForFieldType:()=>Tc,hasAnyTriggerGeneratingAction:()=>Oc,isDayCountValid:()=>Mh,isExpressionModelComplete:()=>vo,isOperatorCompatible:()=>$T,isTriggerGeneratingAction:()=>Qh,moveBranchItemInTree:()=>HT,operatorNeedsValue:()=>fi,processTriggerFormIdFromScope:()=>Th,processTriggerScopeFromScope:()=>_h,removeElseIfInTree:()=>jT,removeNodeFromTree:()=>Yh,serializeToWorkflowJson:()=>OT,supportsClearForActionType:()=>Ac,updateActionInTree:()=>Rc,updateConditionInTree:()=>mi,validateBusinessRule:()=>XT});var e2=T(()=>{"use strict";Ih();H_();Wh();Wh();tg();tg();jh();Qs();Qs();});var rg=y(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});xc.cloneJson=void 0;function f7(e){return JSON.parse(JSON.stringify(e))}xc.cloneJson=f7});var d2=y(hi=>{"use strict";Object.defineProperty(hi,"__esModule",{value:!0});hi.BUSINESS_RULE_NULL_GUID=hi.businessRuleRegistration=hi.BusinessRuleAdapter=void 0;var t2=lt(),Zs=(e2(),Mr(ZT)),r2=Nr(),n2=te(),m7=rg(),rn=Cr(),h7=Xd(),g7=lt();function v7(e){return s2((0,m7.cloneJson)(e))}function s2(e){var t,r;let n=i=>(i??[]).map(a=>y7(a)?s2(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 y7(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 b7(e){var t;if(e===null||typeof e!="object"||Array.isArray(e))throw new n2.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 n2.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 w7="00000000-0000-0000-0000-000000000000";hi.BUSINESS_RULE_NULL_GUID=w7;var A7=new Set(["Recommendation","LockUnlock","ShowErrorMessage","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]),E7=["ruleId","name","description","entityLogicalName","scope","status","rootCondition"],C7=["kind","id","displayName","logic","clauses","trueBranch","falseBranch"],S7=["id","field","fieldDisplayName","operator","valueType","value","valueField","lookupValue","expression","rawExpression","valueWorkflowType"];function Or(e,t){return e===void 0?t:{...e,...t}}var Xi=["kind","id","type","displayName","field","stepName","stepLabels"],i2=["valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression"],N7={Recommendation:[...Xi,"recommendationTitle","messageText","acceptanceText","applyActions","recommendationActionStepMeta"],LockUnlock:[...Xi,"lock"],ShowErrorMessage:[...Xi,"errorMessage","messageLevel","messageActionSteps"],SetFieldValue:[...Xi,...i2],SetDefaultValue:[...Xi,...i2],SetBusinessRequired:[...Xi,"required"],SetVisibility:[...Xi,"visible"]};function K(e,t){return t===void 0?{}:{[e]:t}}function l2(e){var t;return e===void 0?void 0:{...e,label:(t=e.label)!==null&&t!==void 0?t:""}}function ng(e){return{valueType:e.valueType,...K("valueWorkflowType",e.valueWorkflowType),...K("value",e.value),...K("valueField",e.valueField),...K("lookupValue",l2(e.lookupValue)),...K("expression",e.expression),...K("rawExpression",e.rawExpression)}}function u2(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 D7=["id","field","valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression","stepName","displayName"];function I7(e){return Or(e.bag,{id:e.id,field:e.field,...ng(e),...K("stepName",e.stepName),...K("displayName",e.displayName)})}function _7(e){let t=u2(e,D7);return{id:e.id,field:e.field,valueType:e.valueType,...K("valueWorkflowType",e.valueWorkflowType),...K("value",e.value),...K("valueField",e.valueField),...K("lookupValue",e.lookupValue),...K("expression",e.expression),...K("rawExpression",e.rawExpression),...K("stepName",e.stepName),...K("displayName",e.displayName),...K("bag",t)}}function a2(e){return{valueType:e.valueType,...K("valueWorkflowType",e.valueWorkflowType),...K("value",e.value),...K("valueField",e.valueField),...K("lookupValue",e.lookupValue),...K("expression",e.expression),...K("rawExpression",e.rawExpression)}}function o2(e){throw new Error(`Unsupported business-rule action type: ${e.type}`)}var T7=new Set(["INVALID_CLEAR_FOR_FIELD","INVALID_VALUE_TYPE_FOR_FIELD","CLAUSE_VALUE_TOO_LONG","ACTION_VALUE_TOO_LONG"]),P7=new Set,R7="INVALID_CLEAR_FOR_FIELD";function O7(e){let t=n=>{var i;return(0,rn.isJsonObject)(n)&&(n.label===""||n.label===void 0)?{...n,label:String((i=n.id)!==null&&i!==void 0?i:"")}:n},r=n=>{if(!(0,rn.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 Fc=class{toArtifact(t){let r=this.residualBag(t,E7),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 Or(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,Zs.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,Zs.serializeToWorkflowJson)(n),a=(r=n.ruleId)!==null&&r!==void 0?r:(0,t2.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,Zs.createEmptyCondition)():t.rootCondition===null?null:this.conditionFromJson(v7(b7(t.rootCondition)))},u=this.toArtifact(l);return u.id||(u.id=(0,t2.newId)()),u}assignMissingIds(t){return(0,g7.assignMissingIds)(t)}validate(t){let r=[],n=t.rootCondition;return n==null?r:(0,rn.isJsonObject)(n)?(c2(n,"/rootCondition",r),r):(r.push((0,rn.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,rn.issue)("/rootCondition","rule-not-representable",o instanceof Error?o.message:String(o))]}let i=n.rootCondition===null?null:O7(n.rootCondition),a;return r.length===0?a=T7:r.some(o=>o.requiredLevel!==void 0)?a=P7:a=new Set([R7]),(0,Zs.validateBusinessRule)(i,r).filter(o=>!a.has(o.kind)).map(o=>(0,rn.issue)(`/rootCondition (${o.nodeId})`,`business-rule-${o.kind}`,o.message))}issuesBlockingPush(t,r=[],n){return this.semanticIssues(t,r)}residualBag(t,r){return u2(t,r)}buildWorkflowEntity(t,r){return(0,Zs.buildWorkflowEntity)(t,r)}conditionToJson(t){let r=this.residualBag(t,C7),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,S7),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,N7[t.type]),n={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...K("stepName",t.stepName),...K("stepLabels",t.stepLabels),...K("bag",r)};switch(t.type){case"Recommendation":return{...n,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...K("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(_7),...K("recommendationActionStepMeta",t.recommendationActionStepMeta)};case"LockUnlock":return{...n,type:"LockUnlock",lock:t.lock};case"ShowErrorMessage":return{...n,type:"ShowErrorMessage",errorMessage:t.errorMessage,...K("messageLevel",t.messageLevel),...K("messageActionSteps",t.messageActionSteps)};case"SetFieldValue":return{...n,type:"SetFieldValue",...a2(t)};case"SetDefaultValue":return{...n,type:"SetDefaultValue",...a2(t)};case"SetBusinessRequired":return{...n,type:"SetBusinessRequired",required:t.required};case"SetVisibility":return{...n,type:"SetVisibility",visible:t.visible};default:return o2(t)}}conditionFromJson(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:{};return Or(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 Or(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,...K("value",t.value),...K("valueField",t.valueField),...K("lookupValue",l2(t.lookupValue)),...K("expression",t.expression),...K("rawExpression",t.rawExpression),...K("valueWorkflowType",t.valueWorkflowType)})}branchItemFromJson(t){return this.isConditionJson(t)?this.conditionFromJson(t):this.actionFromJson(t)}actionFromJson(t){if(!A7.has(t.type))throw new Error(`Unsupported business-rule action type: ${t.type}`);F7(t);let r={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...K("stepName",t.stepName),...K("stepLabels",t.stepLabels)};switch(t.type){case"Recommendation":return Or(t.bag,{...r,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...K("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(I7),...K("recommendationActionStepMeta",t.recommendationActionStepMeta)});case"LockUnlock":return Or(t.bag,{...r,type:"LockUnlock",lock:t.lock});case"ShowErrorMessage":return Or(t.bag,{...r,type:"ShowErrorMessage",errorMessage:t.errorMessage,...K("messageLevel",t.messageLevel),...K("messageActionSteps",t.messageActionSteps)});case"SetFieldValue":return Or(t.bag,{...r,type:"SetFieldValue",...ng(t)});case"SetDefaultValue":return Or(t.bag,{...r,type:"SetDefaultValue",...ng(t)});case"SetBusinessRequired":return Or(t.bag,{...r,type:"SetBusinessRequired",required:t.required});case"SetVisibility":return Or(t.bag,{...r,type:"SetVisibility",visible:t.visible});default:return o2(t)}}isConditionJson(t){return Object.prototype.hasOwnProperty.call(t,"clauses")&&Object.prototype.hasOwnProperty.call(t,"logic")&&!Object.prototype.hasOwnProperty.call(t,"type")}};hi.BusinessRuleAdapter=Fc;function c2(e,t,r){(0,rn.optionalEnum)(e,"logic",["AND","OR"],t,"condition-logic-invalid",r),(0,rn.childObjects)(e,"clauses",t,"clause",r);for(let n of["trueBranch","falseBranch"])(0,rn.childObjects)(e,n,t,"branchItem",r).forEach(({node:a,index:o})=>{"clauses"in a||"trueBranch"in a||"falseBranch"in a?c2(a,`${t}/${n}/${o}`,r):x7(a,`${t}/${n}/${o}`,r)})}function x7(e,t,r){e.type==="SetDefaultValue"&&e.valueType==="Clear"&&r.push((0,rn.issue)(`${t}/valueType`,"clear-only-set-field-value","Clear is only supported for SetFieldValue actions."))}function F7(e){if(e.type==="SetDefaultValue"&&e.valueType==="Clear")throw new Error("Clear is only supported for SetFieldValue actions.")}function L7(){return{adapter:new Fc,api:h7.businessRuleApi,publish:(e,t,r)=>(0,r2.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,r2.boundEntityPublishScope)(t)}}hi.businessRuleRegistration=L7});var I2=y(gi=>{"use strict";Object.defineProperty(gi,"__esModule",{value:!0});gi.appRegistration=gi.AppAdapter=gi.HEADER_NAV_BOOLEAN_RULE=void 0;var Tn=Cr(),nt=Kn(),tl=_i(),k7=Nr(),M7=gu(),ig=pu(),ag=Qn(),B7=lt(),U7=ae(),A2=ha(),E2=te(),C2=mu();Object.defineProperty(gi,"HEADER_NAV_BOOLEAN_RULE",{enumerable:!0,get:function(){return C2.HEADER_NAV_BOOLEAN_RULE}});var Bc="7.0.0.0",p2=`<SiteMap IntroducedVersion="${Bc}"></SiteMap>`,f2="/_imgs/imagestrips/transparent_spacer.gif",m2="/_imgs/TableIconsFluentV9/document_one_page_sparkle.svg",$7=["Entity","Url","DefaultDashboard","Page","GenPageId"],el="sitemapId",h2="sitemapName",q7="sitemapNameUnique",g2="aiDescription",v2="[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}",V7=new RegExp(`^(?:\\{${v2}\\}|${v2})$`);function y2(e,t){if(!V7.test(e.trim()))throw new E2.ValidationError("app",t,[{pointer:"/sitemapId",rule:"app-sitemapid-guid",message:`sitemapId must be a GUID; received '${e}'.`}]);return e.trim()}function b2(e,t,r){if(e===void 0)return r;if(typeof e!="boolean")throw new E2.ValidationError("app",t,[S2(e)]);return e}function S2(e){return(0,Tn.issue)("/headerAndNavigationRefresh",C2.HEADER_NAV_BOOLEAN_RULE,`headerAndNavigationRefresh must be a boolean, got ${typeof e}`)}function G7(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,U7.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=A2.DEFAULT_LCID){this.lcid=t}toArtifact(t){let{bag:r,modeledEls:n}=Lc(t,"Area");return{id:"",name:"",uniqueName:"",description:"",siteMap:{areas:n.map(i=>this.areaToJson(i)),bag:r},bag:(0,nt.emptyBag)()}}fromArtifact(t){(0,ag.installDomShim)();let r=this.assignMissingIds(JSON.parse(JSON.stringify(t))),n=new DOMParser().parseFromString("<root/>","text/xml"),i=this.rootToRaw(r);return(0,nt.rebuildRaw)(i,(0,tl.domEngine)(n),null)}fromApiResponse(t){var r,n,i,a,o,s,l,u,c,d,p;(0,ag.installDomShim)();let f=t??{},m=(r=f.$sitemap)!==null&&r!==void 0?r:f,h=(0,tl.parseXmlRoot)((n=m.sitemapxml)!==null&&n!==void 0?n:p2,p2),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:[[el,(u=(l=m.sitemapid)!==null&&l!==void 0?l:f._sitemapid_value)!==null&&u!==void 0?u:""],[h2,(c=m.sitemapname)!==null&&c!==void 0?c:""],[q7,(d=m.sitemapnameunique)!==null&&d!==void 0?d:""],[g2,(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,ag.installDomShim)();let b=(0,tl.serializeNode)(this.fromArtifact(t)),E=[],C=[];for(let R of(i=(n=t.siteMap)===null||n===void 0?void 0:n.areas)!==null&&i!==void 0?i:[])for(let O of(a=R.groups)!==null&&a!==void 0?a:[])for(let F of(o=O.subAreas)!==null&&o!==void 0?o:[])F.type==="Entity"&&F.entity?E.push(F.entity):F.type==="DashBoard"&&F.dashboardId&&C.push(F.dashboardId);let N=(s=t.bag)!==null&&s!==void 0?s:(0,nt.emptyBag)();return{sitemapId:sg(N,el)||(t.sitemapId?y2(t.sitemapId,t.id):""),sitemapxml:b,sitemapname:sg(N,h2)||t.name,appModuleId:t.id,appModuleName:t.name,appModuleDescription:t.description,...t.aiDescription!==void 0&&t.aiDescription!==(r?r.aiDescription:sg(N,g2))?{appModuleAiDescription:t.aiDescription}:{},appModuleUniqueName:t.uniqueName,...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},...t.headerAndNavigationRefresh===void 0?{}:{appSettings:{[ig.HEADER_AND_NAVIGATION_REFRESH]:b2(t.headerAndNavigationRefresh,(l=t.id)!==null&&l!==void 0?l:"(unknown)",!0)?ig.APP_SETTING_ON:ig.APP_SETTING_OFF}},...typeof t.published=="boolean"?{published:t.published}:{},entities:E,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:[],...C]}}}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,B7.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:y2(t.sitemapId,u)}:{},...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},headerAndNavigationRefresh:b2(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(ug):Array.isArray(r.areas)?r.areas.forEach(ug):Array.isArray(r.groups)?ug(r):Array.isArray(r.subAreas)?D2(r):"type"in r&&$c(r,"subarea"),t}validate(t){let r=[],n=t.published;n!==void 0&&typeof n!="boolean"&&r.push((0,Tn.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(S2(a)),i==null)return r;if(!(0,Tn.isJsonObject)(i))return r.push((0,Tn.issue)("/siteMap","sitemap-must-be-object",`siteMap must be a JSON object, got ${typeof i}`)),r;let o=(0,Tn.childObjects)(i,"areas","/siteMap","area",r),s=new Map;return o.forEach(({node:l,index:u})=>{let c=`/siteMap/areas/${u}`;(0,Tn.childObjects)(l,"groups",c,"group",r).forEach(({node:p,index:f})=>{let m=`${c}/groups/${f}`;(0,Tn.childObjects)(p,"subAreas",m,"subArea",r).forEach(({node:v,index:b})=>{let E=`${m}/subAreas/${b}`;(0,Tn.optionalEnum)(v,"type",["Entity","URL","DashBoard","CustomPage","GenPage"],E,"subarea-type-invalid",r);let C=G7(v);if(!C)return;let N=s.get(C);if(N===void 0){s.set(C,E);return}r.push((0,Tn.issue)(E,"subarea-duplicate-target",`the sitemap already navigates to this target at ${N}; a duplicate SubArea would pin it twice and a single removeElement would leave one behind`))})})}),r}applyServerIdentity(t,r){let n=r[el];if(!n)return;t.bag||(t.bag=(0,nt.emptyBag)());let i=t.bag.a.find(a=>a[0]===el);i?i[1]=n:t.bag.a.push([el,n])}areaToJson(t){var r;let{bag:n,modeledEls:i}=Lc(t,"Group"),a={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:og(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}=Lc(t,"SubArea");return{id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:og(t,this.lcid),subAreas:i.map(a=>this.subAreaToJson(a)),bag:n}}subAreaToJson(t){var r;let{bag:n}=Lc(t,null),i=z7(t),a={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",type:i,title:og(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!==f2&&(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,nt.emptyBag)(),l=kc(o)?[["IntroducedVersion",Bc]]:[],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,nt.mergeAttrs)(o.a,l),c:(0,nt.spliceChildren)(o.c,u)}}areaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,nt.emptyBag)(),i=kc(n),a=[],o=[];t.id&&a.push(["Id",t.id]),i&&a.push(["ShowGroups","true"],["ResourceId","SitemapDesigner.NewTitle"],["DescriptionResourceId","SitemapDesigner.NewTitle"],["IntroducedVersion",Bc]),t.icon!==void 0?a.push(["Icon",t.icon]):Mc(n.a,"Icon")&&o.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):Mc(n.a,"VectorIcon")&&o.push("VectorIcon");let s=t.groups.map(u=>this.groupToRaw(u)),l=lg((0,nt.spliceChildren)(n.c,s),t.title,i,this.lcid);return{n:"Area",a:(0,nt.mergeAttrs)(n.a,a,o),c:l}}groupToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,nt.emptyBag)(),i=kc(n),a=[];t.id&&a.push(["Id",t.id]),i&&a.push(["ResourceId","SitemapDesigner.NewGroup"],["DescriptionResourceId","SitemapDesigner.NewGroup"],["ToolTipResourseId","SitemapDesigner.Unknown"],["IntroducedVersion",Bc],["IsProfile","false"]);let o=t.subAreas.map(l=>this.subAreaToRaw(l)),s=lg((0,nt.spliceChildren)(n.c,o),t.title,i,this.lcid);return{n:"Group",a:(0,nt.mergeAttrs)(n.a,a),c:s}}subAreaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,nt.emptyBag)(),i=kc(n),a=j7(n.a,t.type),o=[],s=[];t.id&&o.push(["Id",t.id]),K7(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]):Mc(a,"Icon",f2)&&s.push("Icon"),t.vectorIcon!==void 0?o.push(["VectorIcon",t.vectorIcon]):Mc(a,"VectorIcon")?t.type==="GenPage"?o.push(["VectorIcon",m2]):s.push("VectorIcon"):t.type==="GenPage"&&!W7(a,"VectorIcon")&&o.push(["VectorIcon",m2]);let l=lg((0,nt.spliceChildren)(n.c,[]),t.title,i,this.lcid);return{n:"SubArea",a:(0,nt.mergeAttrs)(a,o,s),c:l}}};gi.AppAdapter=Uc;function Lc(e,t){let r=(0,tl.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,nt.rawFromNode)((0,tl.nodeLikeFromDom)(l))}),o+=1)}return{bag:{a:r,c:n},modeledEls:i}}function w2(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 og(e,t){var r;let n=w2(e,"Titles")[0];if(!n)return"";let a=w2(n,"Title").find(o=>o.getAttribute("LCID")===String(t));return a&&(r=a.getAttribute("Title"))!==null&&r!==void 0?r:""}function z7(e){return e.getAttribute("GenPageId")?"GenPage":e.getAttribute("Entity")?"Entity":e.getAttribute("Page")?"CustomPage":e.getAttribute("DefaultDashboard")?"DashBoard":"URL"}function kc(e){return e.a.length===0&&e.c.length===0}function W7(e,t){return e.some(([r])=>r===t)}function Mc(e,t,r){let n=e.find(([a])=>a===t),i=n?.[1];return!!i&&i!==r}function sg(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function j7(e,t){let r=H7(t);return e.filter(([n])=>!$7.includes(n)||r.has(n)).map(n=>[n[0],n[1]])}function H7(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 K7(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 lg(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]=J7(e[i],t,n),a}return r?[Q7(t,n),...e]:e}function J7(e,t,r){let n=!1,i=e.c.map(a=>!n&&a.n==="Title"&&X7(a,"LCID")===String(r)?(n=!0,{n:a.n,a:(0,nt.mergeAttrs)(a.a,[["Title",t]]),c:a.c}):a);return n||i.unshift(N2(t,r)),{n:e.n,a:e.a.map(a=>[a[0],a[1]]),c:i}}function Q7(e,t){return{n:"Titles",a:[],c:[N2(e,t)]}}function N2(e,t){return{n:"Title",a:[["LCID",String(t)],["Title",e]],c:[]}}function X7(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function Y7(e){let t="0123456789abcdef",r="";for(let n=0;n<e;n+=1)r+=t[Math.floor(Math.random()*t.length)];return r}function $c(e,t){e&&(typeof e.id!="string"||e.id.length===0)&&(e.id=`${t}_${Y7(8)}`)}function ug(e){var t;$c(e,"area");for(let r of(t=e.groups)!==null&&t!==void 0?t:[])D2(r)}function D2(e){var t;$c(e,"group");for(let r of(t=e.subAreas)!==null&&t!==void 0?t:[])$c(r,"subarea")}function Z7(e=A2.DEFAULT_LCID){return{adapter:new Uc(e),api:M7.appApi,languageSensitive:!0,publish:(t,r)=>(0,k7.publishAppModule)(t,r),publishScope:t=>({envelope:"appmodule",targetIds:[t]})}}gi.appRegistration=Z7});var _2={};pn(_2,{ActionType:()=>dg,AppActionOrigin:()=>bg,AppActionVisibilityType:()=>yg,ButtonType:()=>fg,CannotUpdateAppActionColumns:()=>eW,Context:()=>hg,IconType:()=>pg,Location:()=>mg,OnClickEventType:()=>vg,Scope:()=>gg,VisibilityType:()=>cg});var cg,dg,pg,fg,mg,hg,gg,vg,yg,bg,eW,T2=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"})(cg||(cg={}));(function(e){e[e.NotSupported=0]="NotSupported",e[e.None=1]="None",e[e.JavaScript=2]="JavaScript",e[e.Expression=3]="Expression"})(dg||(dg={}));(function(e){e[e.NoIcon=0]="NoIcon",e[e.UseIcon=1]="UseIcon",e[e.UseWebResource=2]="UseWebResource"})(pg||(pg={}));(function(e){e[e.Standard=0]="Standard",e[e.Dropdown=1]="Dropdown",e[e.Split=2]="Split",e[e.Group=3]="Group"})(fg||(fg={}));(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"})(mg||(mg={}));(function(e){e[e.All=0]="All",e[e.Entity=1]="Entity"})(hg||(hg={}));(function(e){e[e.App=0]="App",e[e.Entity=1]="Entity",e[e.Global=2]="Global"})(gg||(gg={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.JavaScript=2]="JavaScript"})(vg||(vg={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.ClassicRules=2]="ClassicRules"})(yg||(yg={}));(function(e){e[e.Default=0]="Default",e[e.Migrated=1]="Migrated",e[e.MigratedClone=2]="MigratedClone"})(bg||(bg={}));eW=["appactionid","appmoduleid","context","contextvalue","location","name","type","uniquename","isdisabled","origin"]});var x2=y(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});Vc.commandApi=void 0;var P2=Pt(),xr=be(),O2=te(),mr=ae(),tW="OnClickEventJavaScriptWebResourceId($select=name,webresourceid),IconWebResourceId($select=name,webresourceid)";async function qc(e,t){let r=`/EntityDefinitions(LogicalName='${(0,mr.odataPathLiteral)(t)}')${(0,mr.odataQuery)([["$select","MetadataId"]])}`,i=(0,xr.ensureSuccess)(await e.get(r),e.apiUrl(r)).body,a=i?.MetadataId;return a?(0,mr.normalizeGuid)(a,"entityMetadataId"):""}Vc.commandApi={async get(e,t){let r=t,n=await qc(e,r),i=n?`_contextentity_value eq ${n}`:`contextvalue eq '${(0,mr.odataLiteral)(r)}'`,a=`/appactions${(0,mr.odataQuery)([["$expand",tW],["$filter",i]])}`,o,s=await(0,P2.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,mr.normalizeGuid)(d,"appactionid")]=typeof p=="string"?p:null}}return{raw:l,etag:o?(0,xr.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 qc(e,r.entityLogicalName);return R2(e,{...r,entityMetadataId:n},!1)},async update(e,t,r,n,i){let a=r,o=a.entityMetadataId||await qc(e,a.entityLogicalName);return R2(e,{...a,entityMetadataId:o},!0,i)},async delete(e,t){let r=await qc(e,t),n=r?`_contextentity_value eq ${r}`:`contextvalue eq '${(0,mr.odataLiteral)(t)}'`,i=`/appactions${(0,mr.odataQuery)([["$select","appactionid"],["$filter",n]])}`,a=await(0,P2.collectPages)(e,i,"deleteArtifact('command')");for(let o of a)o.appactionid&&await(0,xr.deleteRecord)(e,"appactions",o.appactionid)}};async function R2(e,t,r,n){let i=t.entityMetadataId?(0,mr.normalizeGuid)(t.entityMetadataId,"entityMetadataId"):"",a=nW(t.rows),o={};try{await rW(e,t,a,i,r,n,o)}catch(s){throw(0,O2.withPartialTokens)(s,{memberEtags:o})}return{id:t.entityLogicalName,etag:null,memberEtags:o}}async function rW(e,t,r,n,i,a,o){var s,l,u;for(let c of r)if(i&&c.exists){let d=(0,mr.normalizeGuid)(c.appactionid,"id"),p=(s=a?.[d])!==null&&s!==void 0?s:c.etag,f=(0,xr.echoWrite)("appactionid",p?{"If-Match":p}:void 0),m=`/appactions(${d})${f.query}`,h=(0,xr.ensureSuccess)(await e.patch(m,c.body,f.options),e.apiUrl(m));o[d]=(0,xr.readEtag)(h)}else{let d=(0,xr.echoWrite)("appactionid"),p=`/appactions${d.query}`,f={...c.body};if(f["[email protected]"]===void 0){if(!n)throw new O2.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,xr.ensureSuccess)(await e.post(p,f,d.options),e.apiUrl(p)),h=(0,xr.readCreatedId)(m,"appactionid");h&&(o[(0,mr.normalizeGuid)(h,"appactionid")]=(0,xr.readEtag)(m))}for(let c of[...(l=t.deletedRowIds)!==null&&l!==void 0?l:[]].reverse()){let d=(0,mr.normalizeGuid)(c,"id");await(0,xr.deleteRecord)(e,"appactions",d,(u=a?.[d])!==null&&u!==void 0?u:void 0),delete o[d]}}function nW(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 j2=y(Eo=>{"use strict";Object.defineProperty(Eo,"__esModule",{value:!0});Eo.commandRegistration=Eo.CommandAdapter=void 0;var Ve=(T2(),Mr(_2)),F2=Nr(),hr=Cr(),iW=x2(),aW=lt(),Co=ae(),Eg="$ClientSvg:",Cg=".svg",oW=2,sW=1,lW=1,M2="entityMetadataId",uW=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"]),Gc=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=mW(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:dW(m,c,V2(f),u)});return{id:u,entityLogicalName:u,commandBars:fW(p),bag:{a:[[M2,(s=t.entityMetadataId)!==null&&s!==void 0?s:""]]}}}fromArtifact(t){return{entityLogicalName:t.entityLogicalName,entityMetadataId:Ng(t),appActions:wg(t).map(r=>r.row)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t,r){let n=new Set(r?wg(r).map(l=>l.appactionid):[]),i=wg(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?DW(l.row):W2(l.row)}}),s=[...n].filter(l=>!a.has(l));return{entityLogicalName:t.entityLogicalName,entityMetadataId:Ng(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,aW.assignMissingIds)(t)}validate(t){let r=[];return(0,hr.childObjects)(t,"commandBars","","commandBar",r).forEach(({node:i,index:a})=>{let o=`/commandBars/${a}`;(0,hr.optionalEnum)(i,"location",["MainTab","ContextualTab","HomeTab"],o,"bar-location-invalid",r),(0,hr.childObjects)(i,"groups",o,"group",r).forEach(({node:l,index:u})=>{let c=`${o}/groups/${u}`;B2(l.bag)||((0,hr.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."})),U2((0,hr.childObjects)(l,"controls",c,"control",r),`${c}/controls`,r)})}),r}};Eo.CommandAdapter=Gc;function B2(e){let t=e?.a;return Array.isArray(t)&&t.length>0}function U2(e,t,r){e.forEach(({node:n,index:i})=>{let a=`${t}/${i}`;B2(n.bag)||(0,hr.optionalGuidId)(n,"id",a,"control-id-invalid",r),(0,hr.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,hr.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,hr.isJsonObject)(n.action)?(0,hr.optionalEnum)(n.action,"type",["javascript"],`${a}/action`,"action-type-invalid",r):r.push((0,hr.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,hr.childObjects)(n,"children",a,"control",r);s.length>0&&U2(s,`${a}/children`,r)})}function Sg(e){return{a:Object.entries(e)}}function cW(e){return Object.fromEntries(e.a)}function zc(e,t){if(e){for(let[r,n]of e.a)if(r===t)return n}}function Ng(e){let t=zc(e.bag,M2);return typeof t=="string"?t:""}function dW(e,t,r,n){var i,a;let o=[],s=[];for(let l of jc(e))l.type===Ve.ButtonType.Group?o.push({id:q2(l.name,n),title:typeof l.grouptitle=="string"?l.grouptitle:"",controls:jc((a=t.get((i=l.appactionid)!==null&&i!==void 0?i:""))!==null&&a!==void 0?a:[]).map(u=>Wc(u,t,r,n)),bag:Sg(l)}):s.push(Wc(l,t,r,n));return s.length>0&&o.unshift({id:NW(n,r),title:"",controls:s}),o}function Dg(e){let t=e.bag?zc(e.bag,"appactionid"):void 0;return typeof t=="string"&&t.trim()!==""?t:e.id}function Wc(e,t,r,n){var i,a,o,s,l;let u=q2(e.name,n),c={id:u,type:hW(e.type),label:typeof e.buttonlabeltext=="string"?e.buttonlabeltext:"",command:typeof e.appactionid=="string"?e.appactionid:u,bag:Sg(e)},d=$2(e);d&&(c.icon=d);let p=pW(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 jc(f))if(v.type===Ve.ButtonType.Group){let b=(a=v.appactionid)!==null&&a!==void 0?a:"",E=Sg(v);c.flyoutGroupId===void 0&&(c.flyoutGroupId=(o=v.appactionid)!==null&&o!==void 0?o:void 0,c.flyoutGroupBag=E);let C=[];for(let N of jc((l=t.get((s=v.appactionid)!==null&&s!==void 0?s:""))!==null&&l!==void 0?l:[])){let R=Wc(N,t,r,n);m.push(R),C.push(Dg(R))}h.push({id:b,bag:E,childIds:C})}else m.push(Wc(v,t,r,n));c.children=m,h.length>1&&(c.flyoutGroups=h)}return c}function $2(e){var t;if(!((t=e.IconWebResourceId)===null||t===void 0)&&t.name)return e.IconWebResourceId.name;if(e.fonticon)return e.fonticon.startsWith(Eg)?e.fonticon.slice(Eg.length)+Cg:e.fonticon}function pW(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 L2(e){return typeof e.sequence=="number"?e.sequence:typeof e.buttonsequencepriority=="number"?e.buttonsequencepriority:0}function jc(e){return[...e].sort((t,r)=>L2(t)-L2(r))}function fW(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 q2(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 mW(e){switch(e){case Ve.Location.Form:case Ve.Location.QuickForm:return"MainTab";case Ve.Location.HomePageGrid:case Ve.Location.Dashboard:return"HomeTab";default:return"ContextualTab"}}function V2(e){switch(e){case"MainTab":return Ve.Location.Form;case"HomeTab":return Ve.Location.HomePageGrid;default:return Ve.Location.SubGridStandard}}function hW(e){switch(e){case Ve.ButtonType.Dropdown:return"FlyoutAnchor";case Ve.ButtonType.Split:return"SplitButton";default:return"Button"}}function gW(e){switch(e){case"FlyoutAnchor":return Ve.ButtonType.Dropdown;case"SplitButton":return Ve.ButtonType.Split;default:return Ve.ButtonType.Standard}}function vW(e){var t;return e.bag&&e.bag.a.length>0?!0:((t=e.title)!==null&&t!==void 0?t:"").length>0}function G2(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 wg(e,t=new Set){var r,n,i,a;let o=[],s=Ng(e);for(let l of(r=e.commandBars)!==null&&r!==void 0?r:[]){let u=V2(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=>!G2(f,t)),p=0;for(let f of(i=l.groups)!==null&&i!==void 0?i:[]){let m;if(vW(f)){let h=bW(f,u,void 0,e,s);o.push(h),m=h.appactionid}for(let h of(a=f.controls)!==null&&a!==void 0?a:[])z2(h,u,m,e,s,o,d?p:void 0,t),p+=1}}return o}function z2(e,t,r,n,i,a,o,s=new Set){var l;let u=yW(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=>!G2(h,s)),p=(h,v,b)=>{z2(h,t,v,n,i,a,d?b:void 0,s)},f=e.flyoutGroups;if(f&&f.length>0){let h=new Map(c.map(N=>[Dg(N),N])),v=new Set,b=0,E;for(let[N,R]of f.entries()){let O=R.id||(N===0?Ag(u.appactionid):_g("flyout-group",`${u.appactionid}#${N}`)),F=k2(O,t,u.appactionid,n,i,R.bag);a.push(F);let k=F.appactionid;E===void 0&&(E=k);for(let P of R.childIds){let V=h.get(P);!V||v.has(P)||(v.add(P),p(V,k,b),b+=1)}}let C=E??Ag(u.appactionid);for(let N of c){let R=Dg(N);v.has(R)||(v.add(R),p(N,C,b),b+=1)}return}let m=e.flyoutGroupId||Ag(u.appactionid);a.push(k2(m,t,u.appactionid,n,i,e.flyoutGroupBag));for(let[h,v]of c.entries())p(v,m,h)}function yW(e,t,r,n,i,a){let o=Ig(e,t,r,n,i),s=o.row;a!==void 0&&typeof s.sequence!="number"&&(s.sequence=a);let l=$2(s);return e.location!==void 0&&(s.location=e.location),s.type=gW(e.type),s.buttonlabeltext=e.label,AW(s,e.icon,l),CW(s,e.action),EW(s),e.hidden!==void 0&&(s.hidden=e.hidden),e.disabled!==void 0&&(s.isdisabled=e.disabled),{...o,row:s}}function bW(e,t,r,n,i){let a=Ig(e,t,r,n,i);return a.row.type=Ve.ButtonType.Group,a.row.grouptitle=e.title,a}function k2(e,t,r,n,i,a){let o=Ig({id:e,bag:a},t,r,n,i),s=o.row;return s["[email protected]"]=`/appactions(${(0,Co.normalizeGuid)(r,"Command flyout group id")})`,s.type=Ve.ButtonType.Group,s.grouptitle===void 0&&(s.grouptitle=""),s.isgrouptitlehidden===void 0&&(s.isgrouptitlehidden=!0),o}function Ig(e,t,r,n,i){let a,o,s,l;if(e.bag&&e.bag.a.length>0){a=cW(e.bag),o=!0;let u=zc(e.bag,"@odata.etag");s=typeof u=="string"?u:null;let c=zc(e.bag,"appactionid");l=typeof c=="string"&&c?c:e.id}else l=e.id,a=wW(l,t,n,i),o=!1,s=null;return r?a["[email protected]"]=`/appactions(${(0,Co.normalizeGuid)(r,"Command parent appaction id")})`:o&&typeof a._parentappactionid_value=="string"&&a._parentappactionid_value&&a.type!==Ve.ButtonType.Group&&(a["[email protected]"]=null),delete a._parentappactionid_value,{appactionid:l,exists:o,etag:s,row:a}}function wW(e,t,r,n){let i={appactionid:e,name:`${e}!${e.replace(/-/g,"").slice(0,32)}`,uniquename:"",location:t,context:Ve.Context.Entity,contextvalue:r.entityLogicalName,scope:Ve.Scope.Entity};return n&&(i["[email protected]"]=`/entities(${(0,Co.normalizeGuid)(n,"Command context entity metadata id")})`),i}function AW(e,t,r){if(t===r){let n=e._iconwebresourceid_value;typeof n=="string"&&n&&!e.fonticon&&(e["[email protected]"]=`/webresourceset(${(0,Co.normalizeGuid)(n,"Command icon web resource id")})`);return}if(t===void 0){e.fonticon="",e.IconWebResourceId=null;return}e.fonticon=t.toLowerCase().endsWith(Cg)?Eg+t.slice(0,t.length-Cg.length):t,e.IconWebResourceId=null}function EW(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,Co.normalizeGuid)(a,`Command ${i}`);e[`${i}@odata.bind`]=`/canvasapps(${o})`};e.onclickeventtype===sW&&t("_onclickeventformulacomponentlibraryid_value","OnClickEventFormulaComponentLibraryId");let r=e.visibilitytype;(!r||r===lW)&&t("_visibilityformulacomponentlibraryid_value","VisibilityFormulaComponentLibraryId")}function CW(e,t){if(!(!t||t.type!=="javascript")){if(e.onclickeventtype=oW,t.webResourceId){let r=(0,Co.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 SW(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 _g(e,t){let r="";for(let n=0;n<4;n+=1)r+=SW(`${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 Ag(e){return _g("flyout-group",e)}function NW(e,t){return _g("loose-group",`${e}|${t}`)}function W2(e){let t={...e};for(let r of uW)delete t[r];return t}function DW(e){let t=W2(e);for(let r of Ve.CannotUpdateAppActionColumns)delete t[r];return t}function IW(){return{adapter:new Gc,api:iW.commandApi,publish:(e,t,r)=>(0,F2.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,F2.boundEntityPublishScope)(t)}}Eo.commandRegistration=IW});var H2=y(Hc=>{"use strict";Object.defineProperty(Hc,"__esModule",{value:!0});Hc.chartApi=void 0;var _W=Pt(),Zt=be(),So=ae(),TW="savedqueryvisualizationid,name,description,primaryentitytypecode,datadescription,presentationdescription,charttype,type,isdefault",PW="savedqueryvisualizationid,name,primaryentitytypecode,charttype,isdefault";Hc.chartApi={async get(e,t){let r=(0,So.normalizeGuid)(t,"id"),n=await(0,Zt.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",r),i=`/savedqueryvisualizations(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,So.odataQuery)([["$select",TW]]);return{raw:(0,Zt.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},readToken(e,t){return(0,Zt.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",(0,So.normalizeGuid)(t,"id"))},async list(e,t){let r=`/savedqueryvisualizations${(0,So.odataQuery)([["$select",PW],["$filter",t?.entityLogicalName?`primaryentitytypecode eq '${(0,So.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,_W.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,Zt.echoWrite)("savedqueryvisualizationid"),a=`/savedqueryvisualizations${i.query}`,o=(0,Zt.ensureSuccess)(await e.post(a,(0,Zt.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,Zt.resolveCreatedId)(o,"savedqueryvisualizationid","chart",r),etag:(0,Zt.readEtag)(o)}},async update(e,t,r,n){let i=r,a=(0,So.normalizeGuid)(t,"id"),o=(0,Zt.echoWrite)("savedqueryvisualizationid",{"If-Match":(0,Zt.requireEtag)(n,"chart",a)}),s=`/savedqueryvisualizations(${a})${o.query}`,l=(0,Zt.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,Zt.readEtag)(l)}},delete(e,t){return(0,Zt.deleteRecord)(e,"savedqueryvisualizations",t)}}});var dP=y(Do=>{"use strict";Object.defineProperty(Do,"__esModule",{value:!0});Do.chartRegistration=Do.ChartAdapter=void 0;var Tg=Kn(),K2=Cr(),nn=_i(),J2=Nr(),RW=H2(),Pg=Qn(),OW=lt(),xW=["Column","StackedColumn","StackedColumn100","Bar","StackedBar","StackedBar100","Area","StackedArea","StackedArea100","Line","Pie","Doughnut","Funnel","Tag"],FW=new Map(xW.map(e=>[e.toLowerCase(),e]));function eP(e){var t;return e&&(t=FW.get(e.toLowerCase()))!==null&&t!==void 0?t:"Column"}function LW(){return'<Chart Palette="BrightPastel"><Series><Series ChartType="Column" ChartArea="Default" /></Series><ChartAreas><ChartArea Name="Default" /></ChartAreas><Legends><Legend Name="Default" /></Legends></Chart>'}function kW(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="${No(h.series.attribute)}" aggregate="${No(h.series.aggregate)}" />`,s=h=>`<attribute alias="${h.alias}" name="${No(h.category.attribute)}" groupby="true"${h.category.dateGrouping?` dategrouping="${No(h.category.dateGrouping)}"`:""} />`,l=[],u=new Map,c=(h,v)=>{if(!h){l.push(v);return}let b=u.get(h);b?b.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="${No(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="${No(n)}">${p}</entity></fetch></fetchcollection><categorycollection><category alias="${m}">${f}</category></categorycollection></datadefinition>`}var Kc=class{toArtifact(t){var r,n,i,a,o,s,l;(0,Pg.installDomShim)();let u=(r=t.datadescription)!==null&&r!==void 0?r:"",c=(n=t.presentationdescription)!==null&&n!==void 0?n:"",d=(0,nn.parseXmlRoot)(u,"<datadefinition/>"),p=(0,nn.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:tP(p),isDefault:(l=t.isdefault)!==null&&l!==void 0?l:!1,series:iP(d),categories:aP(d),presentation:rP(p),dataBag:u?(0,nn.projectElementBag)(d):void 0,presentationBag:c?(0,nn.projectElementBag)(p):void 0,rowBag:MW(t.charttype,t.type)}}fromArtifact(t){(0,Pg.installDomShim)();let{datadescription:r,presentationdescription:n}=BW(t);return{savedqueryvisualizationid:t.id,name:t.name,description:t.description,primaryentitytypecode:t.entityLogicalName,datadescription:r,presentationdescription:n,charttype:Q2(t.rowBag,"charttype"),type:Q2(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,Pg.installDomShim)();let u=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,OW.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,K2.childObjects)(n,"series","","series",r),(0,K2.childObjects)(n,"categories","","category",r),r}};Do.ChartAdapter=Kc;function MW(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 Q2(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 tP(e){let t=e.getElementsByTagName("Series");for(let r=0;r<t.length;r+=1)if(t[r].getAttribute("ChartType"))return eP(t[r].getAttribute("ChartType"));return"Column"}function rP(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 Jc(e){return e.getElementsByTagName("fetch")[0]}function nP(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 iP(e){let t=Jc(e);if(!t)return[];let r=nP(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=eP(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 aP(e){var t;let r=Jc(e);if(!r)return[];let n=nP(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 BW(e){if(!X2(e.dataBag)||!X2(e.presentationBag)){let a=kW(e);return{datadescription:a,presentationdescription:nj(e,a)}}let t=new DOMParser().parseFromString("<root/>","text/xml"),r=Y2(e.dataBag,"datadefinition",t),n=Y2(e.presentationBag,"Chart",t),i=iP(r);if(!Rg(e.series,i)){let a=Og(r);UW(t,r,e.series);let o=Og(r),s=o.length>0?o:e.series.map(()=>"");oP(t,n,s,a,e.chartType)}return Rg(e.categories,aP(r))||$W(t,r,e.categories),e.chartType!==tP(n)&&uP(n,e.chartType),Rg(e.presentation,rP(n))||cP(n,e.presentation),{datadescription:(0,nn.serializeNode)(r),presentationdescription:(0,nn.serializeNode)(n)}}function X2(e){return!!e&&(e.c.length>0||e.a.length>0)}function oP(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 Og(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 Y2(e,t,r){let n={n:t,a:(0,Tg.mergeAttrs)(e.a,[]),c:(0,Tg.spliceChildren)(e.c,[])};return(0,Tg.rebuildRaw)(n,(0,nn.domEngine)(r),null)}function UW(e,t,r){let n=Jc(t),i=n?.getElementsByTagName("entity")[0];!n||!i||sP(e,t,i,HW(n),r,JW,{aliasPrefix:"aggregate_column",addRef:GW,removeRef:jW})}function $W(e,t,r){let n=Jc(t),i=n?.getElementsByTagName("entity")[0];!n||!i||sP(e,t,i,KW(n),r,QW,{aliasPrefix:"groupby_column",addRef:zW,removeRef:WW})}function sP(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=XW(r,f),b=m.relatedEntity;(v??void 0)!==(b??void 0)&&((h=f.parentNode)===null||h===void 0||h.removeChild(f),Z2(e,r,f,b))};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||VW(t,o.aliasPrefix);m.setAttribute("alias",h),a(m,f),Z2(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),ZW(f)}}function qW(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 VW(e,t){let r=qW(e);if(!r.has(t))return t;for(let n=2;;n+=1){let i=`${t}_${n}`;if(!r.has(i))return i}}function lP(e,t){let r=t.getElementsByTagName("categorycollection")[0];if(r)return r;let n=e.createElement("categorycollection");return t.appendChild(n),n}function GW(e,t,r){let n=lP(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 zW(e,t,r){let n=lP(e,t),i=e.createElement("category");i.setAttribute("alias",r),n.appendChild(i)}function WW(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 jW(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"&&!tj(o)&&((r=o.parentNode)===null||r===void 0||r.removeChild(o))}}function HW(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 KW(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 JW(e,t){e.setAttribute("name",t.attribute),e.setAttribute("aggregate",t.aggregate),t.seriesType&&e.setAttribute("charttype",t.seriesType)}function QW(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 XW(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 Z2(e,t,r,n){n?YW(e,t,n).appendChild(r):t.appendChild(r)}function YW(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 ZW(e){let t=e.parentNode;if(t&&(t.removeChild(e),t.tagName==="link-entity"&&!ej(t))){let r=t.parentNode;r&&r.removeChild(t)}}function ej(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 tj(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1)if(t[r].nodeType===1)return!0;return!1}function uP(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(!rj(r[i])){r[i].setAttribute("ChartType",t);return}}}function rj(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 cP(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 nj(e,t){let r=(0,nn.parseXmlRoot)(LW(),"<Chart/>");uP(r,e.chartType),cP(r,e.presentation);let n=Og((0,nn.parseXmlRoot)(t,"<datadefinition/>"));return n.length>0&&oP(r.ownerDocument,r,n,n.slice(0,1),e.chartType),(0,nn.serializeNode)(r)}function Rg(e,t){return JSON.stringify(e)===JSON.stringify(t)}function No(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function ij(){return{adapter:new Kc,api:RW.chartApi,publish:(e,t,r)=>(0,J2.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,J2.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}Do.chartRegistration=ij});var hP=y(_o=>{"use strict";Object.defineProperty(_o,"__esModule",{value:!0});_o.dashboardApi=_o.dashboardEntity=void 0;var aj=Pt(),vi=be(),Io=ae(),pP=tf();function fP(e){return e&&e.toLowerCase()!=="none"?e:void 0}_o.dashboardEntity=fP;var mP="formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber",oj={select:mP,required:["name","type","objecttypecode","istabletenabled"]},sj="formid,name,type,objecttypecode",lj=0,uj=10;_o.dashboardApi={async get(e,t){let n=`/systemforms(${(0,Io.normalizeGuid)(t,"id")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Io.odataQuery)([["$select",mP]]),i=(0,vi.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,vi.readEtag)(i)}},async list(e,t){let r=[`(type eq ${lj} or type eq ${uj})`];t?.entityLogicalName&&r.push(`objecttypecode eq '${(0,Io.odataLiteral)(t.entityLogicalName)}'`);let n=`/systemforms${(0,Io.odataQuery)([["$select",sj],["$filter",r.join(" and ")]])}`;return(await(0,aj.collectPages)(e,n,"listArtifacts('dashboard')")).map(a=>{var o,s;let l=fP(a.objecttypecode);return{type:"dashboard",id:(o=a.formid)!==null&&o!==void 0?o:"",name:(s=a.name)!==null&&s!==void 0?s:"",...l?{entityLogicalName:l}:{},isDirty:!1}})},async create(e,t,r){let n=t,i=(0,vi.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,vi.ensureSuccess)(await e.post(a,(0,vi.withClientMintedId)(o,"formid",r),i.options),e.apiUrl(a));return{id:(0,vi.resolveCreatedId)(s,"formid","dashboard",r),etag:(0,vi.readEtag)(s)}},async update(e,t,r,n){let i=r;return(0,pP.patchSystemForm)(e,(0,Io.normalizeGuid)(t,"id"),"dashboard",{name:i.name,description:i.description,formxml:i.formxml,istabletenabled:i.istabletenabled},n,oj)},readToken(e,t){return(0,pP.readSystemFormContentEtag)(e,(0,Io.normalizeGuid)(t,"id"))},delete(e,t){return(0,vi.deleteRecord)(e,"systemforms",t)}}});var _P=y(an=>{"use strict";Object.defineProperty(an,"__esModule",{value:!0});an.dashboardRegistration=an.TILE_CLASS_ID=an.DashboardAdapter=void 0;var nl=Kn(),gr=_i(),xg=Nr(),rl=Cr(),AP=hP(),Fg=Qn(),Yi=lt(),EP=ae(),CP=ha(),gP="0",Lg="10",cj=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"]]),dj="{3FF9A528-DD50-4ACA-8F10-2E5ED73513AD}",Xc=class{constructor(t=CP.DEFAULT_LCID){this.lcid=t}toArtifact(t){var r,n,i,a,o;(0,Fg.installDomShim)();let s=(r=t.formxml)!==null&&r!==void 0?r:"",l=(0,gr.parseXmlRoot)(s,"<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:pj(t.type),entityLogicalName:(o=(0,AP.dashboardEntity)(t.objecttypecode))!==null&&o!==void 0?o:null,enabledForMobile:!!t.istabletenabled,layoutType:fj(l),components:vP(l,this.lcid),bag:(0,gr.projectElementBag)(l)}}fromArtifact(t){var r;return(0,Fg.installDomShim)(),{formid:t.id,name:t.name,description:t.description,type:t.dashboardType==="Interactive"?Lg:gP,objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",istabletenabled:t.enabledForMobile,formxml:yP(t,this.lcid)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t){return{name:t.name,description:t.description,formxml:yP(t,this.lcid),istabletenabled:t.enabledForMobile,type:t.dashboardType==="Interactive"?Lg:gP,objecttypecode:t.entityLogicalName}}createDefault(t){var r,n,i,a,o,s,l,u;(0,Fg.installDomShim)();let c=(0,gr.parseXmlRoot)(Dj(),"<form/>");return{id:(r=t.id)!==null&&r!==void 0?r:(0,Yi.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:vP(c,this.lcid),bag:(0,gr.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,Yi.newId)())}return t}validate(t){let r=[],n=(0,rl.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,rl.isJsonObject)(u)&&r.push((0,rl.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,rl.isJsonObject)(a.position)){let l=il(a.position);i.has(l)?r.push((0,rl.issue)(`${s}/position`,"component-position-collision",`two components occupy the same dashboard position (${l}); move one to a free cell`)):i.add(l)}}),r}};an.DashboardAdapter=Xc;function pj(e){return String(e??"")===Lg?"Interactive":"Standard"}function fj(e){let t=e?.getAttribute("formLayout")||e?.getAttribute("layoutType"),r=parseInt(t??"",10);return Number.isNaN(r)?0:r}function Y(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 vP(e,t){let r=[];return Y(e,"tabs").flatMap(i=>Y(i,"tab")).forEach((i,a)=>{Y(i,"columns").flatMap(s=>Y(s,"column")).forEach((s,l)=>{Y(s,"sections").flatMap(c=>Y(c,"section")).forEach((c,d)=>{mj(c,{tabIndex:a,columnIndex:l,sectionIndex:d},r,t)})})}),r}function mj(e,t,r,n){Y(e,"rows").flatMap(a=>Y(a,"row")).forEach((a,o)=>{Y(a,"cell").forEach((s,l)=>{let u=hj(s,{...t,rowIndex:o,cellIndex:l},n);u&&r.push(u)})})}function hj(e,t,r){var n,i;let a=DP((n=e.getAttribute("id"))!==null&&n!==void 0?n:"");if(a.toLowerCase().startsWith("spacer"))return null;let o=Y(e,"control")[0];if(!o)return null;let s=(i=o.getAttribute("classid"))!==null&&i!==void 0?i:"",l=yj(o),u=bj(s,l,o),c=gj(o);return{id:o.getAttribute("id")||a,type:u,name:NP(e,r),classId:s,position:t,colspan:kg(e,"colspan",1),rowspan:kg(e,"rowspan",1),parameters:l,bag:(0,gr.projectElementBag)(e),...c?{icProperties:c}:{}}}function SP(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 gj(e){let t=SP(e);return t?(0,gr.serializeNode)(t):void 0}function vj(e,t,r){let n=SP(t);if(!r){n&&t.removeChild(n);return}let i=new DOMParser().parseFromString(r,"text/xml").documentElement,a=(0,nl.rebuildRaw)((0,nl.rawFromNode)((0,gr.nodeLikeFromDom)(i)),(0,gr.domEngine)(e),null);n&&(0,gr.serializeNode)(n)===(0,gr.serializeNode)(a)||(n?t.replaceChild(a,n):t.appendChild(a))}function NP(e,t){var r,n;let i=Y(e,"labels")[0];if(!i)return"";let a=Y(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 yj(e){var t;let r={},n=Y(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 bj(e,t,r){var n;let i=cj.get(e.toUpperCase());return i?i==="chart"?t.ChartGridMode==="Chart"?"chart":"list":i==="assistant"&&((n=r.getAttribute("uniqueid"))!==null&&n!==void 0?n:"").toUpperCase()===dj?"assistant":i:"unknown"}function kg(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 DP(e){return e.replace(/^\{/,"").replace(/\}$/,"")}function wj(e,t){let r={n:"form",a:(0,nl.mergeAttrs)(e.bag.a,[]),c:(0,nl.spliceChildren)(e.bag.c,[])};return(0,nl.rebuildRaw)(r,(0,gr.domEngine)(t),null)}function yP(e,t){let r=new DOMParser().parseFromString("<root/>","text/xml"),n=wj(e,r);return Cj(r,n,e.components,t),Aj(r,n,e.components,t),(0,gr.serializeNode)(n)}function Aj(e,t,r,n){let i=IP(t);for(let a of r)i.has(il(a.position))||Ej(e,t,a,n)}function Ej(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=Ij(t,e,l);for(let V of Y(u,"row"))Y(V,"cell").some(q=>Y(q,"control").length>0)||u.removeChild(V);let c=r.classId||an.TILE_CLASS_ID[r.type]||an.TILE_CLASS_ID.iframe,d=r.rowspan&&r.rowspan>0?r.rowspan:4,p=r.bag&&bP(r.bag,"id")?String(bP(r.bag,"id")):Qc((0,Yi.newId)()),f=r.id?Qc(r.id):Qc((0,Yi.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),b=Y(u,"row"),E=b[b.length-1],C=E?Y(E,"cell").reduce((V,q)=>V+kg(q,"colspan",1),0):0;(!E||C+v>h)&&(E=e.createElement("row"),u.appendChild(E));let N=e.createElement("cell");N.setAttribute("id",p),N.setAttribute("colspan",String(v)),N.setAttribute("rowspan",String(d)),N.setAttribute("showlabel","true");let R=e.createElement("labels"),O=e.createElement("label");O.setAttribute("description",(o=r.name)!==null&&o!==void 0?o:""),O.setAttribute("languagecode",String(n)),R.appendChild(O),N.appendChild(R);let F=e.createElement("control");F.setAttribute("id",f),F.setAttribute("classid",Qc(c));let k=e.createElement("parameters"),P=(s=r.parameters)!==null&&s!==void 0?s:{};for(let V of Object.keys(P)){let q=(0,EP.createSafeXmlElement)(e,V,"dashboard tile parameter");q.textContent=P[V],k.appendChild(q)}F.appendChild(k),N.appendChild(F),E.appendChild(N)}function bP(e,t){if(!e)return;let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function Cj(e,t,r,n){var i;let a=IP(t),o=new Set(r.map(s=>il(s.position)));for(let s of r){let l=a.get(il(s.position));if(!l)continue;let u=Y(l,"control")[0];u&&(Sj(e,l,s.name,n),Nj(e,u,s.parameters),wP(l,"colspan",s.colspan),wP(l,"rowspan",s.rowspan),s.icProperties!==void 0&&vj(e,u,s.icProperties))}for(let[s,l]of a)o.has(s)||(i=l.parentNode)===null||i===void 0||i.removeChild(l)}function IP(e){let t=new Map;return Y(e,"tabs").flatMap(n=>Y(n,"tab")).forEach((n,i)=>{Y(n,"columns").flatMap(o=>Y(o,"column")).forEach((o,s)=>{Y(o,"sections").flatMap(u=>Y(u,"section")).forEach((u,c)=>{Y(u,"rows").flatMap(p=>Y(p,"row")).forEach((p,f)=>{Y(p,"cell").forEach((m,h)=>{var v;DP((v=m.getAttribute("id"))!==null&&v!==void 0?v:"").toLowerCase().startsWith("spacer")||Y(m,"control")[0]&&t.set(il({tabIndex:i,columnIndex:s,sectionIndex:c,rowIndex:f,cellIndex:h}),m)})})})})}),t}function il(e){let t=e??{};return`${t.tabIndex}.${t.columnIndex}.${t.sectionIndex}.${t.rowIndex}.${t.cellIndex}`}function Sj(e,t,r,n){if(r===NP(t,n))return;let i=Y(t,"labels")[0];i||(i=e.createElement("labels"),t.appendChild(i));let a=Y(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 Nj(e,t,r){var n;if(!r)return;let i=Object.keys(r);if(i.length===0)return;let a=Y(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,EP.createSafeXmlElement)(e,l,"dashboard component parameter");d.textContent=u,a.appendChild(d)}}}function wP(e,t,r){var n;((n=e.getAttribute(t))!==null&&n!==void 0?n:"")!==String(r)&&e.setAttribute(t,String(r))}function Dj(e=2){let t=`{${(0,Yi.newId)()}}`,r=`{${(0,Yi.newId)()}}`,n=`{${(0,Yi.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>`}an.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 Qc(e){return`{${e.replace(/[{}]/g,"")}}`}function Ij(e,t,r){var n;let i=Y(e,"tabs").flatMap(u=>Y(u,"tab"))[0];if(!i)throw new Error("addDashboardTile: dashboard formxml has no <tab>");let a=Y(i,"columns").flatMap(u=>Y(u,"column"))[0];if(!a)throw new Error("addDashboardTile: dashboard formxml has no <column>");let o=Y(a,"sections").flatMap(u=>Y(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=Y(s,"rows")[0];return l||(l=t.createElement("rows"),s.appendChild(l)),l}function _j(e=CP.DEFAULT_LCID){return{adapter:new Xc(e),api:AP.dashboardApi,languageSensitive:!0,publish:(t,r,n)=>n?.entityLogicalName?(0,xg.publishBoundEntity)(t,n):(0,xg.publishDashboardById)(t,r),publishScope:(t,r)=>r?.entityLogicalName?(0,xg.boundEntityPublishScope)(r):{envelope:"dashboard",targetIds:[t]},rebaselineAfterPublish:"bracket"}}an.dashboardRegistration=_j});var GP=y(ed=>{"use strict";Object.defineProperty(ed,"__esModule",{value:!0});ed.genPageApi=void 0;var Zc=Pt(),BP=Ol(),Ie=be(),se=ae(),Fr=cu(),ke=te(),UP=lt();function Tj(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 on="uxagentprojects",ea="uxagentprojectfiles",sl="agentconversationmessages",ll="uxagentprojectid",Dt="uxagentprojectfileid",ta="agentconversationmessageid",al=`${ll},name`,Pj=`${Dt},filename,filetype`,$P=2e8,qP=200000001,ra={"MSCRM.IncludeUnpublished":"true"},Mg={};function Zi(e,t){return{"MSCRM.VersioningChangeset":e,...ra,...t}}async function Ug(e,t,r,n){var i;let a=`/${t}(${r})`+(0,se.odataQuery)([["$select",n]]),o=(0,Ie.ensureSuccess)(await e.get(a,{headers:{...ra}}),e.apiUrl(a));return{row:(i=o.body)!==null&&i!==void 0?i:{},etag:(0,Ie.readEtag)(o)}}async function Yc(e,t,r=ra){let n=`/${ea}(${t})/filecontent/$value`,i=await e.get(n,{headers:{...r}});if(i.status===404)return{status:"unavailable",reason:"missing"};(0,Ie.ensureSuccess)(i,e.apiUrl(n));let a=i.body,o=Tj(a);if(o)return{status:"available",data:(0,Fr.bytesToBase64)(o)};if(typeof a=="string")return{status:"available",data:(0,Fr.utf8ToBase64)(a)};throw new ke.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 VP(e){let t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}async function Rj(e,t,r,n,i,a){if(!e.supportsBinaryPatch)throw new ke.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=`/${ea}(${t})/filecontent`,s=(0,Fr.base64ToBytes)(n);(0,se.assertNoControlChars)(r,"generative-page file name"),(0,Ie.ensureSuccess)(await e.patchRaw(o,s,{headers:Zi(i,{"Content-Type":"application/octet-stream","Content-Length":String(s.byteLength),"x-ms-file-name":VP(r),...a?{"If-Match":"*"}:{}})}),e.apiUrl(o))}async function ol(e,t,r=ra){let n=`/${ea}`+(0,se.odataQuery)([["$select",Pj],["$filter",`_${ll}_value eq ${t}`]]);return(await(0,Zc.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 Bg(e,t){let r=`/${sl}`+(0,se.odataQuery)([["$select",`${ta},message,messagesender,createdon`],["$filter",`_regardingobjectid_value eq ${t}`],["$orderby","createdon asc,versionnumber asc"]]);return(0,Zc.collectPages)(e,r,"fetchArtifact('genPage')",void 0,{headers:{...ra}})}async function TP(e,t){var r,n,i;let{row:a,etag:o}=await Ug(e,on,t,al),s=new Map;for(let{row:l,etag:u}of await ol(e,t))s.set((0,se.normalizeGuid)(String((r=l[Dt])!==null&&r!==void 0?r:""),Dt),{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 PP(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,se.normalizeGuid)(c.id,"file id");u.add(d);let p=r?.rows.get(d);if(c.content.status==="retain"){if(!r)throw new ke.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 ke.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 qg(e){let t=(0,Fr.base64ToUtf8)(e);return(0,Fr.utf8ToBase64)(t)===(0,Fr.bytesToBase64)((0,Fr.base64ToBytes)(e))?t:void 0}function Oj(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?{[ta]:(0,se.normalizeGuid)(t.id,"message id")}:{},"[email protected]":`/${on}(${e})`,message:t.message,messagecontext:JSON.stringify(p),messagesender:t.sender==="user"?$P:qP}}async function xj(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,se.normalizeGuid)(p,"message id"));if(s.length===0)return r;let l=`/${sl}`+(0,se.odataQuery)([["$select",`${ta},message,messagesender,_regardingobjectid_value`],["$filter",s.map(p=>`${ta} eq ${p}`).join(" or ")]]),u=await(0,Zc.collectPages)(e,l,"pushArtifact('genPage')",void 0,{headers:{...ra}});if(u.length===0)return r;let c=new Map(u.map(p=>{var f;return[String((f=p[ta])!==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,se.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"?$P:qP)&&String((o=f._regardingobjectid_value)!==null&&o!==void 0?o:"").toLowerCase()===t))throw new ke.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 $g(e,t,r,n){switch(t.kind){case"createProject":return{method:"POST",path:`/${on}`,body:(0,Ie.withClientMintedId)({name:t.name},ll,e),headers:Zi(n)};case"createRow":return{method:"POST",path:`/${ea}`,body:(0,Ie.withClientMintedId)({filename:t.file.name,filetype:t.file.fileType,[`${ll}@odata.bind`]:`/${on}(${e})`},Dt,(0,se.normalizeGuid)(t.file.id,"file id")),headers:Zi(n)};case"renameRow":return{method:"PATCH",path:`/${ea}(${(0,se.normalizeGuid)(t.file.id,"file id")})`,body:{filename:t.file.name,filetype:t.file.fileType},headers:Zi(n,{"If-Match":"*"})};case"content":{let i=qg(t.data);if(i===void 0)throw new ke.SdkError("GENPAGE_CONTENT_NOT_TEXT",`File '${t.file.name}' is not UTF-8 text and cannot ride in a change set.`);return(0,se.assertNoControlChars)(t.file.name,"generative-page file name"),{method:"PATCH",path:`/${ea}(${(0,se.normalizeGuid)(t.file.id,"file id")})/filecontent`,rawBody:i,contentType:"application/octet-stream; charset=utf-8",headers:Zi(n,{"x-ms-file-name":VP(t.file.name),...t.existing?{"If-Match":"*"}:{}})}}case"deleteRow":return{method:"DELETE",path:`/${ea}(${t.fileId})`,headers:Zi(n,{"If-Match":"*"})};case"patchProject":return{method:"PATCH",path:`/${on}(${e})`,body:{name:t.name},headers:Zi(n,{"If-Match":"*"})};case"message":return{method:"POST",path:`/${sl}`,body:Oj(e,t.turn,r,n)};default:{let i=t;throw new ke.SdkError("GENPAGE_WRITE_UNKNOWN",`Unknown generative-page write: ${JSON.stringify(i)}`)}}}function RP(e,t){return e.supportsAtomicBatch&&t.every(r=>r.kind!=="content"||qg(r.data)!==void 0)}async function OP(e,t,r,n,i){await(0,BP.postChangeSet)(e,r.map(a=>$g(t,a,n,i)),`generative page '${t}' (${r.length} operation(s))`)}async function xP(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 Rj(e,(0,se.normalizeGuid)(s.file.id,"file id"),s.file.name,s.data,i,s.existing);continue}let l=$g(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,Ie.ensureSuccess)(c,e.apiUrl(l.path))}if(o.length===0)return{warnings:[],turnRecorded:!0};try{let s=o.map(l=>$g(t,l,n,i));if(e.supportsAtomicBatch)await(0,BP.postChangeSet)(e,s,`the conversation turn of generative page '${t}'`);else for(let l of s)(0,Ie.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 FP(e,t,r,n,i,a,o){var s;let l=u=>({id:t,etag:null,memberEtags:{},warnings:[...o,u]});try{let u=await TP(e,t),c=new Map;for(let C of r)(C.kind==="createRow"||C.kind==="renameRow"||C.kind==="content")&&c.set((0,se.normalizeGuid)(C.file.id,"file id"),C.file);let d=[];u.name!==n.name&&d.push(`the page is named '${u.name}', not '${n.name}'`);for(let[C,N]of c){let R=u.rows.get(C);R&&(R.filename!==N.name||R.filetype!==N.fileType)&&d.push(`file '${N.name}' is stored as '${R.filename}' (type ${R.filetype})`)}for(let C of r){if(C.kind!=="content")continue;let N=await Yc(e,(0,se.normalizeGuid)(C.file.id,"file id")),R=(0,Fr.bytesToBase64)((0,Fr.base64ToBytes)(C.data));(N.status!=="available"||N.data!==R)&&d.push(N.status==="available"?`file '${C.file.name}' holds ${(0,Fr.base64ToBytes)(N.data).byteLength} byte(s) that differ from the ${(0,Fr.base64ToBytes)(R).byteLength} written`:`file '${C.file.name}' holds no content`)}let p=new Set(r.filter(C=>C.kind==="content").map(C=>(0,se.normalizeGuid)(C.file.id,"file id")));for(let[C,N]of c)!p.has(C)&&(await Yc(e,C)).status==="available"&&d.push(`file '${N.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 TP(e,t),m=[...f.rows.keys()],h=f.etag!==u.etag||f.rows.size!==u.rows.size||m.some(C=>{var N,R;return((N=u.rows.get(C))===null||N===void 0?void 0:N.etag)!==((R=f.rows.get(C))===null||R===void 0?void 0:R.etag)}),v=m.length!==i.size||m.some(C=>!i.has(C)),b={},E=[];for(let[C,N]of f.rows){let R=c.has(C)||!a?N.etag:(s=a.get(C))!==null&&s!==void 0?s:null;b[C]=R,R!==N.etag&&E.push(N.filename)}return h||v||!f.etag||Object.values(b).some(C=>!C)?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.`):Fj({id:t,etag:f.etag,memberEtags:b},[...o,...E.map(C=>`Generative page '${t}' was written, but its file '${C}' 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.`)}}ed.genPageApi={async get(e,t){var r;let n=(0,se.normalizeGuid)(t,"id"),{row:i,etag:a}=await Ug(e,on,n,al),o=await ol(e,n),s={},l=[];for(let{row:c,etag:d}of o){let p=(0,se.normalizeGuid)(String((r=c[Dt])!==null&&r!==void 0?r:""),Dt);s[p]=d;let f=await Yc(e,p);l.push({...c,content:f})}let u=await Bg(e,n);return{raw:{project:i,files:l,conversation:u},etag:a,memberEtags:s}},async getPublished(e,t){var r,n;let i=(0,se.normalizeGuid)(t,"id"),a=`/${on}(${i})`+(0,se.odataQuery)([["$select",al]]),o=await e.get(a);if(o.status===404)return null;(0,Ie.ensureSuccess)(o,e.apiUrl(a));let s=(r=o.body)!==null&&r!==void 0?r:{},l={},u=[],c=await ol(e,i,Mg);for(let{row:v,etag:b}of c){let E=(0,se.normalizeGuid)(String((n=v[Dt])!==null&&n!==void 0?n:""),Dt);l[E]=b,u.push({...v,content:await Yc(e,E,Mg)})}let d=v=>v.map(({row:b,etag:E})=>`${String(b[Dt])}@${String(E)}`).sort().join("|"),p=()=>new ke.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,Ie.ensureSuccess)(f,e.apiUrl(a));let m=await ol(e,i,Mg);if([(0,Ie.readEtag)(o),(0,Ie.readEtag)(f),...[...c,...m].map(v=>v.etag)].some(v=>!v))throw new ke.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,Ie.readEtag)(f)!==(0,Ie.readEtag)(o)||d(m)!==d(c))throw p();return{raw:{project:s,files:u,conversation:[]},etag:(0,Ie.readEtag)(o),memberEtags:l}},async list(e,t){let r=`/${on}`+(0,se.odataQuery)([["$select",al]]);return(await(0,Zc.collectPages)(e,r,"listArtifacts('genPage')",void 0,{headers:{...ra}})).map(i=>{var a,o;return{type:"genPage",id:String((a=i[ll])!==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;MP(e,i);let a=r?(0,se.normalizeGuid)(r,"id"):(0,UP.newId)();kP(e,a,i);let o=PP(a,i,void 0),s=LP(),l=[],u=!0;RP(e,o)?await OP(e,a,o,i,s):{warnings:l,turnRecorded:u}=await xP(e,a,o,i,s);let c=new Set(((n=i.files)!==null&&n!==void 0?n:[]).map(p=>(0,se.normalizeGuid)(p.id,"file id"))),d=await FP(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,se.normalizeGuid)(t,"id");MP(e,s);let u=await xj(e,l,s);kP(e,l,u);let c=await ol(e,l),{row:d,etag:p}=await Ug(e,on,l,al);if(n&&p&&n!==p)throw new ke.SdkError(Ie.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 ke.SdkError(Ie.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 k,P;return[(0,se.normalizeGuid)(String((k=F[Dt])!==null&&k!==void 0?k:""),Dt),{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,se.normalizeGuid)(F.id,"file id")));if(!i)throw new ke.SdkError(Ie.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 ke.SdkError(Ie.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 ke.SdkError(Ie.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 b=new Map(c.map(({row:F,etag:k})=>{var P;return[(0,se.normalizeGuid)(String((P=F[Dt])!==null&&P!==void 0?P:""),Dt),k]}));for(let[F,k]of Object.entries(i)){let P=F.toLowerCase();if(!m.has(P))continue;let V=b.get(P);if(!k||!V)throw new ke.SdkError(Ie.VERSION_CONFLICT_CODE,`Cannot verify generative-page file '${P}' before writing: ${k?"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(k!==V)throw new ke.SdkError(Ie.VERSION_CONFLICT_CODE,`Generative-page file '${P}' changed on the server after this page was fetched (baseline ${k}, server ${V}) \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 E=PP(l,u,{rows:f,name:String((o=d.name)!==null&&o!==void 0?o:"")});if(E.length===0)return{id:l,etag:p,memberEtags:Object.fromEntries(c.map(({row:F,etag:k})=>{var P;return[(0,se.normalizeGuid)(String((P=F[Dt])!==null&&P!==void 0?P:""),Dt),k]}))};let C=LP(),N=[],R=!0;RP(e,E)?await OP(e,l,E,u,C):{warnings:N,turnRecorded:R}=await xP(e,l,E,u,C);let O=await FP(e,l,E,u,h,b,N);return R?O:{...O,intentPending:!0}},async delete(e,t){var r;let n=(0,se.normalizeGuid)(t,"id"),i=await Bg(e,n);await(0,Ie.deleteRecord)(e,on,n);let a=new Set(i.map(l=>{var u;return String((u=l[ta])!==null&&u!==void 0?u:"")}).filter(l=>l!=="")),o=!1;try{for(let l of await Bg(e,n)){let u=String((r=l[ta])!==null&&r!==void 0?r:"");u!==""&&a.add(u)}}catch{o=!0}let s=[];for(let l of a)try{await(0,Ie.deleteRecord)(e,sl,l)}catch(u){u instanceof ke.ConnectionError&&u.statusCode===404||s.push(l)}if(s.length>0||o)throw new ke.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 ${sl} rows regarding '${n}'.`)}};function LP(){return`uxagentproject_${(0,UP.newId)()}`}function Fj(e,t){var r;return t.length===0?e:{...e,warnings:[...(r=e.warnings)!==null&&r!==void 0?r:[],...t]}}function kP(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 ke.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 MP(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 ke.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&&qg(o.content.data)===void 0)&&!e.supportsBinaryPatch)throw new ke.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 aR=y(Po=>{"use strict";Object.defineProperty(Po,"__esModule",{value:!0});Po.genPageRegistration=Po.GenPageAdapter=void 0;var Lj=GP(),kj=Nr(),me=Cr(),od=lt(),sd=cu(),na=te(),zP=df(),Vg=mp(),yi=2e8,tR=200000001,Rn={source:{name:"src/pages/page.tsx",fileType:yi},output:{name:"src/pages/page.compiled",fileType:tR},config:{name:"config.json",fileType:yi},prompt:{name:"firstPrompt.json",fileType:yi}},rR=Object.keys(Rn),Mj=["dataSources","model","connectorBindings","actionBindings"],Bj=["userMessage","agentMessage"],WP=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Uj={source:"6f1c2a4e9b3d47a1b85c0e2f7d914a63",output:"a8e53d17c2f64b09a1d7e4b8c3f2069d",config:"3b97f0c64e2a4d8f95b1c7a0e6d3f814",prompt:"d24e8b51f7a34c6e8b09d5f1a2c7e3b6"},$j="9c3e7a15d2b84f6e8a01c5d7b3f9e240";function nR(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 td(e,t){return nR(e,Uj[t])}function qj(e,t){let r=nR(e,$j),n=parseInt(r.slice(24),16)%2**47+(t==="agent"?1:0);return`${r.slice(0,24)}${n.toString(16).padStart(12,"0")}`}function jP(e){return typeof e=="string"&&e.trim()!==""?e:(0,od.newId)()}function Pn(e){return(0,me.isJsonObject)(e)?e:{}}function To(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function rd(e){return JSON.parse(JSON.stringify(e))}function Vj(e){let t=Pn(e);return t.status==="available"&&typeof t.data=="string"?{status:"available",data:t.data}:{status:"unavailable",reason:t.reason==="unpublished"?"unpublished":"missing"}}function nd(e){if(!e||e.status!=="available")return;let t=(0,sd.base64ToUtf8)(e.data);return(0,sd.utf8ToBase64)(t)===e.data?t:void 0}function id(e){if(e!==void 0)try{let t=JSON.parse(e.replace(/^\uFEFF/,""));return(0,me.isJsonObject)(t)?t:void 0}catch{return}}function HP(e,t){if(t===yi&&e.includes("page.tsx"))return"source";if(t===tR&&e.includes(".compiled"))return"output";if(t===yi&&e===Rn.config.name)return"config";if(t===yi&&e===Rn.prompt.name)return"prompt"}function KP(e){let t=e.toLowerCase();return rR.some(r=>Rn[r].name.toLowerCase()===t)}function Gg(e){return Object.fromEntries(e)}function iR(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),Gg(i)}function JP(e){var t,r,n;return iR({dataSources:(t=e.dataSources)!==null&&t!==void 0?t:[],model:e.model,connectorBindings:e.connectorBindings,actionBindings:e.actionBindings},Mj,(r=e.bag)===null||r===void 0?void 0:r.config,(n=e.bag)===null||n===void 0?void 0:n.configKeys)}function QP(e){var t,r;return iR({userMessage:e.firstPrompt,agentMessage:e.firstAgentMessage},Bj,(t=e.bag)===null||t===void 0?void 0:t.prompt,(r=e.bag)===null||r===void 0?void 0:r.promptKeys)}function XP(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=Gg(n)),!0}function YP(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=Gg(n)),!0}function cl(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 Gj=["dataSources","model","connectorBindings","actionBindings","firstPrompt","firstAgentMessage"];function ZP(e){return cl(e)?[]:Gj.filter(t=>e[t]!==void 0).map(t=>(0,me.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 eR(){return(0,me.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 ad(e){return{status:"available",data:(0,sd.utf8ToBase64)(e)}}function ul(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 ld=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){let r=t,n=Pn(r?.project),i=(Array.isArray(r?.files)?r.files:[]).map(v=>{var b,E,C;let N=Pn(v);return{id:String((b=N.uxagentprojectfileid)!==null&&b!==void 0?b:""),name:String((E=N.filename)!==null&&E!==void 0?E:""),fileType:Number((C=N.filetype)!==null&&C!==void 0?C:yi),content:Vj(N.content)}}),a=Array.isArray(r?.conversation)?r.conversation.map(v=>{var b,E;let C=Pn(v);return{sender:Number(C.messagesender)===200000001?"agent":"user",message:String((b=C.message)!==null&&b!==void 0?b:""),createdOn:String((E=C.createdon)!==null&&E!==void 0?E:"")}}):void 0,o=v=>a?{...v,conversation:a}:v,s=new Map,l=[],u=!0;for(let v of i){let b=HP(v.name,v.fileType);b?((s.has(b)||v.name!==Rn[b].name)&&(u=!1),s.set(b,v)):(KP(v.name)&&(u=!1),l.push(v))}if(!u||s.size===0)return o(ul(n,i));let c=ul(n,l),d={rows:{}};for(let[v,b]of s)d.rows[v]=b.id;let p=s.get("source");if(p){let v=nd(p.content);if(v===void 0)return o(ul(n,i));c.source=v}let f=s.get("output");f&&(d.output=f.content);let m=s.get("config");if(m){let v=id(nd(m.content));if(!v||!XP(c,d,v))return o(ul(n,i))}let h=s.get("prompt");if(h){let v=id(nd(h.content));if(!v||!YP(c,d,v))return o(ul(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,b,E;if(r&&!To((i=t.conversation)!==null&&i!==void 0?i:[],(a=r.conversation)!==null&&a!==void 0?a:[]))throw new na.ValidationError("genPage",t.id,[(0,me.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 C=ZP(t);if(C.length>0)throw new na.ValidationError("genPage",t.id,C);let N=[],R=r===void 0,O=R&&t.firstPrompt===void 0&&t.newTurn?{...t,firstPrompt:t.newTurn.prompt,...t.newTurn.agentMessage!==void 0?{firstAgentMessage:t.newTurn.agentMessage}:{}}:t;if(cl(O)){let P=(s=(o=O.bag)===null||o===void 0?void 0:o.rows)!==null&&s!==void 0?s:{},V=Z=>{var ye;return(ye=P[Z])!==null&&ye!==void 0?ye:td(O.id,Z)},q=(Z,ye,xe)=>{N.push({id:V(Z),name:Rn[Z].name,fileType:Rn[Z].fileType,content:ye,unchanged:xe})};if(O.source!==void 0){q("source",ad(O.source),!R&&r?.source===O.source&&P.source!==void 0);let Z=!R&&r?.source===O.source&&To((l=r?.dataSources)!==null&&l!==void 0?l:[],(u=O.dataSources)!==null&&u!==void 0?u:[]),ye=nd((c=O.bag)===null||c===void 0?void 0:c.output);Z&&P.output!==void 0&&(0,zP.isLoadableGenPageOutput)(ye)?q("output",{status:"retain"},!0):q("output",ad(await this.compile(O,O.source,n)),!1)}else{if(P.source!==void 0)throw new na.ValidationError("genPage",O.id,[eR()]);if(P.output!==void 0){if(!R&&!To((d=r?.dataSources)!==null&&d!==void 0?d:[],(p=O.dataSources)!==null&&p!==void 0?p:[]))throw new na.ValidationError("genPage",O.id,[(0,me.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.")]);q("output",{status:"retain"},!0)}}let ze=JP(O),Tt=!R&&r!==void 0&&To(JP(r),ze);(R||P.config!==void 0||!Tt)&&q("config",ad(JSON.stringify(ze)),Tt&&P.config!==void 0);let Be=QP(O),Qe=!R&&r!==void 0&&To(QP(r),Be);(P.prompt!==void 0||Object.keys(Be).length>0&&!Qe)&&q("prompt",ad(JSON.stringify(Be)),Qe&&P.prompt!==void 0)}for(let P of(f=O.files)!==null&&f!==void 0?f:[]){let V=(m=r?.files)===null||m===void 0?void 0:m.find(q=>q.id===P.id);N.push({id:P.id,name:P.name,fileType:P.fileType,content:P.content,unchanged:V!==void 0&&To(V,P)})}let F=[];if(O.newTurn){let P=O.newTurn.id,V=q=>P?{id:qj(P,q)}:{};F.push({...V("user"),sender:"user",message:O.newTurn.prompt}),O.newTurn.agentMessage&&F.push({...V("agent"),sender:"agent",message:O.newTurn.agentMessage})}let k=(v=(h=O.bag)===null||h===void 0?void 0:h.config)!==null&&v!==void 0?v:{};return{name:O.name,files:N,...F.length>0?{messages:F,messageContext:{dataSources:(b=O.dataSources)!==null&&b!==void 0?b:[],model:(E=O.model)!==null&&E!==void 0?E:"",enabledTools:Array.isArray(k.enabledTools)?k.enabledTools:[],configurableTools:Array.isArray(k.configurableTools)?k.configurableTools:[]}}:{}}}committed(t,r,n={intentPending:!1}){let i=this.serverState(t,r);return n.intentPending&&t.newTurn!==void 0?{artifact:{...i,newTurn:rd(t.newTurn)},baseline:i}:{artifact:i,baseline:i}}serverState(t,r){var n,i,a,o,s,l;if(!cl(t)&&!t.newTurn)return t;let u=rd(t);if(delete u.newTurn,!cl(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=rR.find(m=>Rn[m].name===d.name&&Rn[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,sd.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,XP(u,c,(s=id(f))!==null&&s!==void 0?s:{})):p==="prompt"&&(delete c.prompt,delete u.firstPrompt,delete u.firstAgentMessage,YP(u,c,(l=id(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,me.isJsonObject)(r)||typeof r.id=="string"&&WP.test(r.id)?t:{...t,newTurn:{...r,id:(0,od.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,me.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 na.ValidationError("genPage",t.id,s);if(!n?.loadTypeScript)throw new na.ValidationError("genPage",t.id,[(0,me.issue)("/source","genpage-compiler-unavailable","no TypeScript compiler is available to compile the page")]);let l=await n.loadTypeScript(),u=o.length>0?(0,Vg.buildGenPageRuntimeTypes)(o):void 0,c=o.length>0?(0,Vg.buildGenPageLegacyEnums)(o):void 0,d=(0,zP.compileGenPage)(l,r,u,c);if(d.diagnostics.length>0)throw new na.ValidationError("genPage",t.id,d.diagnostics.map(zj));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=jP(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:jP(o.id),name:(s=o.name)!==null&&s!==void 0?s:"index.tsx",fileType:(l=o.fileType)!==null&&l!==void 0?l:yi,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=rd(t.connectorBindings)),t.actionBindings!==void 0&&(a.actionBindings=rd(t.actionBindings)),a.source!==void 0&&(a.bag={rows:{source:td(i,"source"),output:td(i,"output"),config:td(i,"config")}}),a}assignMissingIds(t){if(t==null)return{id:(0,od.newId)()};if(!(0,me.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,od.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,me.issue)(`/${s}`,"genpage-field-type",`${s} must be a string, got ${typeof n[s]}`));if(n.source===void 0&&Pn(Pn(n.bag).rows).source!==void 0&&r.push(eR()),r.push(...ZP(t)),n.newTurn!==void 0){let s=Pn(n.newTurn);(!(0,me.isJsonObject)(n.newTurn)||typeof s.prompt!="string"||s.prompt.trim()==="")&&r.push((0,me.issue)("/newTurn/prompt","genpage-turn-prompt","newTurn needs a non-empty prompt")),s.agentMessage!==void 0&&typeof s.agentMessage!="string"&&r.push((0,me.issue)("/newTurn/agentMessage","genpage-field-type","newTurn.agentMessage must be a string")),s.id!==void 0&&(typeof s.id!="string"||!WP.test(s.id))&&r.push((0,me.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,me.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"||!Vg.TABLE_LOGICAL_NAME.test(l)?r.push((0,me.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,me.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,me.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,me.issue)("/files","files-must-be-array",`files must be an array, got ${typeof i}`)),r;let a=cl(t),o=new Map;return(Array.isArray(i)?i:[]).forEach((s,l)=>{let u=`/files/${l}`,c=Pn(s),d=typeof c.id=="string"?c.id.trim().toLowerCase():"";if(d==="")r.push((0,me.issue)(u,"file-id-required","a generative-page file needs an id"));else{let v=o.get(d);v!==void 0?r.push((0,me.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,me.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&&(KP(p)||HP(p,Number(c.fileType))!==void 0)&&r.push((0,me.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,me.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=Pn(m);h.status==="available"?typeof h.data!="string"&&r.push((0,me.issue)(u+"/content/data","file-content-data-invalid","available content needs base64 `data`")):h.status!=="unavailable"&&r.push((0,me.issue)(u+"/content/status","file-content-status-invalid",`content.status must be 'available' or 'unavailable', got ${String(h.status)}`))}),r}};Po.GenPageAdapter=ld;function zj(e){let t=`line ${e.line}, column ${e.column}`;return e.rule==="genpage-source-syntax"?(0,me.issue)("/source",e.rule,`${t}: ${e.message} (TS${e.code}) \u2014 the page cannot run, so it was not pushed`):(0,me.issue)("/source",e.rule,`${t}: ${e.message}`)}function Wj(){return{adapter:new ld,api:Lj.genPageApi,publish:(e,t)=>(0,kj.publishGenPageById)(e,t),publishScope:e=>({envelope:"uxagentproject",targetIds:[e]}),rebaselineAfterPublish:"snapshot"}}Po.genPageRegistration=Wj});var sR=y(dd=>{"use strict";Object.defineProperty(dd,"__esModule",{value:!0});dd.reconcileBpfSecurityRoles=void 0;var cd=be(),ud=ae(),jj="Global",oR={create:"Create",read:"Read",write:"Write",delete:"Delete"};async function Hj(e,t){var r,n;let i=`/EntityDefinitions(LogicalName='${(0,ud.odataPathLiteral)(t)}')?$select=LogicalName,Privileges`,o=(n=(r=(0,cd.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(oR).forEach(u=>{let c=o.find(d=>d.PrivilegeType===oR[u]);if(c){let d=(0,ud.normalizeGuid)(c.PrivilegeId,"PrivilegeId");s[u]=d,l.add(d)}}),{byAccess:s,all:l}}async function Kj(e,t){var r,n;let i=`/RetrieveRolePrivilegesRole(RoleId=${t})`,o=(n=(r=(0,cd.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,ud.normalizeGuid)(s.PrivilegeId,"PrivilegeId")))}async function Jj(e,t,r){if(r.length===0)return;let n={Privileges:r.map(a=>({Depth:jj,PrivilegeId:a}))},i=`/roles(${t})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;(0,cd.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function Qj(e,t,r){let n={Privilege:{"@odata.type":"Microsoft.Dynamics.CRM.privilege",privilegeid:r}},i=`/roles(${t})/Microsoft.Dynamics.CRM.RemovePrivilegeRole`;(0,cd.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function Xj(e,t,r){var n;if(!r||r.length===0)return;let i=await Hj(e,t.toLowerCase());for(let a of r){let o=(0,ud.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 Kj(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 Jj(e,o,c);for(let p of d)await Qj(e,o,p)}}dd.reconcileBpfSecurityRoles=Xj});var gR=y(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});hd.bpfApi=void 0;var vr=Ai(),Yj=Pt(),yr=te(),It=be(),On=ae(),Zj=sR(),eH={"Content-Type":"application/json",Accept:"application/json"},pd={...eH,Prefer:"return=representation"},tH=new Set([408,502,503,504]),rH=`category eq ${vr.WorkflowCategory.BusinessProcessFlow} and type eq ${vr.WorkflowTypeCode.Definition} and businessprocesstype eq ${vr.BusinessProcessType.BusinessFlow}`,nH="workflowid,name,description,primaryentity,statecode,category,type,businessprocesstype,processorder",iH="workflowid,name,uniquename,description,primaryentity,statecode,statuscode,category,type,businessprocesstype,processorder,xaml,clientdata",aH=["xaml","name","description","processorder"];async function lR(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,Zj.reconcileBpfSecurityRoles)(e,n,t.securityRoles)}async function hR(e,t,r){let n={statecode:vr.StateCode.Activated,statuscode:vr.StatusCode.Activated},i=`/workflows(${t})`,a={...pd};return r&&(a["If-Match"]=r),(0,It.ensureSuccess)(await e.patch(i,n,{headers:a}),e.apiUrl(i))}async function uR(e,t,r){return(0,It.readEtag)(await hR(e,t,r))}function cR(e,t){return new yr.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. `+md(e))}async function fd(e,t){var r;let n=`/workflows(${t})${(0,On.odataQuery)([["$select","statecode"]])}`,i=(0,It.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 yr.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 zg(e,t,r){if(await fd(e,t)!==vr.StateCode.Activated)return{deactivated:!1,etag:null};let n={statecode:vr.StateCode.Draft,statuscode:vr.StatusCode.Draft},i=`/workflows(${t})`,a={...pd};r&&(a["If-Match"]=r);let o;try{o=await e.patch(i,n,{headers:a})}catch(l){return await dR(e,t,l)}if(tH.has(o.status))return await dR(e,t,new yr.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,It.ensureSuccess)(o,e.apiUrl(i));return{deactivated:!0,etag:(0,It.readEtag)(s)}}async function dR(e,t,r){let n;try{n=await fd(e,t)}catch{n=void 0}if(n===vr.StateCode.Draft)return{deactivated:!0,etag:null,uncertainCause:r};if(n===vr.StateCode.Activated)throw r;let i=new yr.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 pR(e,t){let r=(0,On.normalizeGuid)(t,"workflowid");try{return await hR(e,r,null),"restored"}catch{try{let n=await fd(e,r);return n===vr.StateCode.Activated?"restored":n===vr.StateCode.Draft?"disabled":"unknown"}catch{return"unknown"}}}function fR(e,t,r,n){let i=`Original failure: ${n instanceof Error?n.message:String(n)}`,a=r==="disabled"?new yr.SdkError("BPF_LEFT_DEACTIVATED",`Business process flow '${e}' was deactivated ${t}, and it could NOT be reactivated \u2014 it is left DISABLED. ${i}`):new yr.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 oH(e,t){try{return await fd(e,t),"survived"}catch(r){return r instanceof yr.ConnectionError&&r.statusCode===404?"removed":"unknown"}}async function sH(e,t,r){if(r)try{let{deactivated:n,etag:i}=await zg(e,t,r),a=n?i:r;if(a)return await(0,It.deleteRecord)(e,"workflows",t,a),"removed"}catch{}return oH(e,t)}function md(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 mR(e,t){return new yr.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. ${md(e)}`)}function lH(e,t){let r=new yr.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.) ${md(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return r.cause=t,r}function uH(e,t){let r=new yr.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. ${md(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return r.cause=t,r}function cH(e,t){let r=new yr.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 dH(e){let t={};for(let r of aH)e[r]!==void 0&&(t[r]=e[r]);return t}hd.bpfApi={async get(e,t){let n=`/workflows(${(0,On.normalizeGuid)(t,"id")})${(0,On.odataQuery)([["$select",iH]])}`,i=(0,It.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,It.readEtag)(i)}},async list(e,t){let r=[rH];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,On.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,On.odataQuery)([["$select",nH],["$filter",r.join(" and ")]])}`;return(await(0,Yj.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,On.normalizeGuid)(r.record.workflowid,"workflowid"),i="/workflows",a=(0,It.ensureSuccess)(await e.post(i,r.record,{headers:pd}),e.apiUrl(i)),o=(0,It.readEtag)(a);if(!o)throw mR(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 uR(e,n,o)),await lR(e,r)}catch(l){let u=await sH(e,n,s);throw u==="survived"?lH(n,l):u==="unknown"?uH(n,l):l instanceof yr.SdkError&&l.code===It.VERSION_CONFLICT_CODE?cH(n,l):l}if(!s)throw mR(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,On.normalizeGuid)(t,"id"),o=(0,It.requireEtag)(n,"bpf",a),{deactivated:s,etag:l,uncertainCause:u}=await zg(e,a,o);try{if(u!==void 0)throw u;let c=o;if(s){if(!l)throw cR(a,"deactivation");c=l}let d=`/workflows(${a})`,p=(0,It.ensureSuccess)(await e.patch(d,dH(i.record),{headers:{...pd,"If-Match":c}}),e.apiUrl(d)),f=(0,It.readEtag)(p);if(i.status==="Active"){if(!f)throw cR(a,"definition write");f=await uR(e,a,f)}return await lR(e,i),{id:a,etag:f}}catch(c){if(s){let d=await pR(e,a);if(d!=="restored")throw fR(a,"to apply an edit, the edit failed",d,c)}throw c}},async delete(e,t){let r=(0,On.normalizeGuid)(t,"id"),{deactivated:n}=await zg(e,r,null);try{await(0,It.deleteRecord)(e,"workflows",r)}catch(i){if(n){let a=await pR(e,r);if(a!=="restored")throw fR(r,"so it could be deleted, the delete failed",a,i)}throw i}}}});var ZR=y(Oo=>{"use strict";Object.defineProperty(Oo,"__esModule",{value:!0});Oo.bpfRegistration=Oo.BpfAdapter=void 0;var gd=Ai(),pH=gR(),Wg=Kn(),ia=_i(),TR=Qn(),er=Cr(),jt=lt(),sn=te(),fH=100,Hg='<?xml version="1.0" encoding="utf-16"?>',vR=1033,PR="mxswa:Workflow",mH="mxswa:ActivityReference.Properties",hH="mcwo:StepLabel",gH="mcwb:Control",yR="mcwb:Control.ControlDisplayName",RR="mcwb:Control.DataFieldName",OR="DataFieldName",bR="ControlDisplayName",xR="Literal",vd="x:Null",wR="x:String",Kg="x:Key",Jg="DisplayName",bd="Activities",vH="StepLabels",FR="StageId",LR="StageCategory",kR="NextStageId",MR="ProcessStepId",Qg="IsProcessRequired",BR="EntityComposite",UR="StageComposite",$R="StepComposite";function jg(e){return(0,er.isJsonObject)(e)?e:{}}function ln(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 aa(e,t){var r;return(r=ln(e).find(n=>n.tagName===t))!==null&&r!==void 0?r:null}function un(e){return aa(e,mH)}function _t(e,t){var r;return(r=ln(e).find(n=>n.getAttribute(Kg)===t))!==null&&r!==void 0?r:null}function Ro(e,t){var r;return((r=e.getAttribute("AssemblyQualifiedName"))!==null&&r!==void 0?r:"").includes(t)}function Fn(e){var t;return!e||!e.firstChild?"":(t=e.firstChild.nodeValue)!==null&&t!==void 0?t:""}function qR(e,t,r){e.firstChild?e.firstChild.nodeValue=r:e.appendChild(t.createTextNode(r))}function dl(e){var t;let r=(t=e.getAttribute(Jg))!==null&&t!==void 0?t:"",n=r.indexOf(": ");return n>=0?r.slice(n+2):r}function VR(e,t){var r;let n=(r=e.getAttribute(Jg))!==null&&r!==void 0?r:"",i=n.indexOf(": ");e.setAttribute(Jg,i>=0?n.slice(0,i+2)+t:t)}function GR(e,t){let r=_t(e,vH),n=aa(r,hH);n&&n.setAttribute("Description",t)}function yH(e){let t=_t(e,LR);if(!t||t.tagName===vd)return;let r=Fn(t).trim();return r===""?void 0:Number(r)}function bH(e){let t=_t(e,kR);if(!t||t.tagName===vd)return;let r=Fn(t).trim();return r===""?void 0:r}function zR(e){let t=WR(e);if(!t)return;let r=HR(t,OR,RR);return r===""?void 0:r}function Xg(e,t){let r=ln(e);for(;r.length>0;){let n=r.pop();if(n.tagName===t)return n;for(let i of ln(n))r.push(i)}return null}function WR(e){let t=_t(un(e),bd);return t?Xg(t,gH):null}function jR(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 HR(e,t,r){var n;return jR(e,t)?(n=e.getAttribute(t))!==null&&n!==void 0?n:"":SH(e,r)}function AR(e,t,r,n){if(jR(e,t)){e.setAttribute(t,n);return}if(aa(e,r)){wH(e,r,n);return}throw new sn.InvalidArgumentError(`BPF step control exposes neither a '${t}' attribute nor a <${r}> wrapper to bind a column`)}function wH(e,t,r){let n=aa(e,t),i=n?Xg(n,xR):null;i&&i.setAttribute("Value",r)}function KR(e){return dl(e)}function wd(e){let t=aa(e,PR),r=[];for(let n of ln(t).filter(i=>Ro(i,BR))){let i=_t(un(n),bd);for(let a of ln(i).filter(o=>Ro(o,UR)))r.push({el:a,entity:KR(n)})}return r}function Yg(e){let t=_t(un(e),bd);return ln(t).filter(r=>Ro(r,$R))}function AH(e){let t=un(e),r=Fn(_t(t,Qg)).trim().toLowerCase(),n=zR(e),i={id:Fn(_t(t,MR)),name:dl(e)};return n!==void 0&&(i.fieldName=n),r==="true"&&(i.required=!0),i}function EH(e,t){let r=un(e),n=yH(r),i=bH(r),a={id:Fn(_t(r,FR)),name:dl(e),entityLogicalName:t,steps:Yg(e).map(AH)};return n!==void 0&&(a.category=n),i!==void 0&&(a.nextStageId=i),a}function CH(e){return wd(e).map(({el:t,entity:r})=>EH(t,r))}function xn(e){return new sn.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 SH(e,t){var r;let n=aa(e,t),i=n?Xg(n,xR):null;return(r=i?.getAttribute("Value"))!==null&&r!==void 0?r:""}function Zg(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(Zg(e,s)):s.nodeType===3&&n.appendChild(e.createTextNode((r=s.nodeValue)!==null&&r!==void 0?r:""))}return n}function JR(e){return _t(un(e),bd)}function NH(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,jt.newId)(),{body:o}=Ad(e0(i,(0,jt.newId)(),t.id,a));return Zg(e,wd((0,ia.parseXmlRoot)(o,"<Activity/>"))[0].el)}function DH(e,t){let{body:r}=Ad(e0("account",(0,jt.newId)(),(0,jt.newId)(),t.id));return Zg(e,Yg(wd((0,ia.parseXmlRoot)(r,"<Activity/>"))[0].el)[0])}function QR(e,t){for(;e.firstChild;)e.removeChild(e.firstChild);for(let r of t)e.appendChild(r)}function XR(e,t,r,n){let i=_t(e,r);if(!i||!i.parentNode){if(n!==void 0&&n!=="")throw xn(`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!==vd){let s=t.createElement(vd);s.setAttribute(Kg,r),a.replaceChild(s,i)}return}if(i.tagName===wR){Fn(i)!==n&&qR(i,t,n);return}let o=t.createElement(wR);o.setAttribute(Kg,r),o.appendChild(t.createTextNode(n)),a.replaceChild(o,i)}function IH(e,t,r){XR(e,t,LR,r===void 0?void 0:String(r))}function _H(e,t,r){XR(e,t,kR,r)}function YR(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 ER(e){return Fn(_t(un(e),FR))}function CR(e){return Fn(_t(un(e),MR))}function SR(e,t,r){var n,i,a,o;let s=un(e);r.name!==dl(e)&&(VR(e,r.name),GR(s,r.name));let l=Fn(_t(s,Qg)).trim().toLowerCase()==="true";if(((n=r.required)!==null&&n!==void 0?n:!1)!==l){let u=_t(s,Qg);u&&qR(u,t,r.required?"True":"False")}if(((i=r.fieldName)!==null&&i!==void 0?i:"")!==((a=zR(e))!==null&&a!==void 0?a:"")){let u=WR(e);if(!u)throw new sn.InvalidArgumentError("BPF step has no <mcwb:Control> element to bind a column to");let c=(o=r.fieldName)!==null&&o!==void 0?o:"";AR(u,OR,RR,c),c!==""&&HR(u,bR,yR)===""&&AR(u,bR,yR,c)}}function NR(e,t,r,n){var i;let a=un(e);if(!a)throw new sn.InvalidArgumentError("BPF stage composite has no <\u2026ActivityReference.Properties>");if(r.name!==dl(e)&&(VR(e,r.name),GR(a,r.name)),IH(a,t,r.category),_H(a,t,n),r.relationshipName&&r.relationshipName.trim()!=="")throw xn("a stage relationship / table change (multi-table authoring)");if(r.actions&&r.actions.length>0||r.branch)throw xn("stage actions or conditional branching");let o=JR(e);if(!o)throw new sn.InvalidArgumentError("BPF stage has no [Activities] collection");let s=(i=r.steps)!==null&&i!==void 0?i:[];if(s.length===0)throw new sn.InvalidArgumentError(`BPF stage '${r.name}' must have at least one step`);let l=Yg(e);if(YR(l,s.map(d=>d.id),CR)){l.forEach((d,p)=>SR(d,t,s[p]));return}let u=new Map(l.map(d=>[CR(d),d]));if(ln(o).some(d=>!Ro(d,$R)))throw xn("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:DH(t,d)});QR(o,c),c.forEach((d,p)=>SR(d,t,s[p]))}function TH(e,t,r){let n=aa(e,PR);if(!n)throw new sn.InvalidArgumentError("BPF xaml has no <mxswa:Workflow> root activity");if(r.globalActions&&r.globalActions.length>0)throw xn("global (process-completed/abandoned) actions");if(!r.stages||r.stages.length===0)throw new sn.InvalidArgumentError("a BPF must have at least one stage");let i=wd(e),a=i.map(p=>p.el);if(YR(a,r.stages.map(p=>p.id),ER)){i.forEach(({el:p,entity:f},m)=>{let h=r.stages[m];if(h.entityLogicalName&&h.entityLogicalName.trim()!==""&&h.entityLogicalName!==f)throw xn(`changing a stage's table ('${h.entityLogicalName}' vs the process's '${f}')`);NR(p,t,h,h.nextStageId)});return}let o=ln(n).filter(p=>Ro(p,BR));if(o.length!==1)throw xn("adding, removing or reordering stages on a multi-table process");let s=o[0],l=KR(s),u=JR(s);if(!u)throw new sn.InvalidArgumentError("BPF primary entity composite has no [Activities] collection");if(ln(u).some(p=>!Ro(p,UR)))throw xn("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 xn(`a stage on a different table ('${p.entityLogicalName}') than the process primary ('${l}')`);let c=new Map(a.map(p=>[ER(p),p])),d=r.stages.map(p=>{var f;return(f=c.get(p.id))!==null&&f!==void 0?f:NH(t,p,l)});QR(u,d),d.forEach((p,f)=>{let m=f<d.length-1?r.stages[f+1].id:void 0;NR(p,t,r.stages[f],m)})}function Ad(e){let t=e.match(/^<\?xml[^>]*\?>\s*/),r=t?t[0]:"";return{prolog:r,body:e.slice(r.length)}}function PH(e){var t,r,n,i,a,o;(0,TR.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,Wg.mergeAttrs)(s.a,[]),c:(0,Wg.spliceChildren)(s.c,[])};return{root:(0,Wg.rebuildRaw)(f,(0,ia.domEngine)(p),null),prolog:(n=(r=e.bag)===null||r===void 0?void 0:r.xamlProlog)!==null&&n!==void 0?n:Hg,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=e0(e.entityLogicalName,(0,jt.newId)(),l?.id&&l.id.trim()!==""?l.id:(0,jt.newId)(),u?.id&&u.id.trim()!==""?u.id:(0,jt.newId)()),{body:d}=Ad(c);return{root:(0,ia.parseXmlRoot)(d,"<Activity/>"),prolog:Hg,eol:"lf"}}function RH(e){let{root:t,prolog:r,eol:n}=PH(e);TH(t,t.ownerDocument,e);let i=(0,ia.serializeNode)(t);return n==="crlf"&&(i=i.replace(/\n/g,`\r
+`)),r+i}function OH(e){return e.uniqueName&&e.uniqueName.trim()!==""?e.uniqueName:`new_${(e.name||"businessprocessflow").toLowerCase().replace(/[^a-z0-9]/g,"")||"businessprocessflow"}`}var yd=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var r,n;(0,TR.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}=Ad(a),u=(0,ia.parseXmlRoot)(l,"<Activity/>");o.stages=CH(u),o.bag={xaml:(0,ia.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,jt.newId)(),name:t.name,uniquename:OH(t),primaryentity:t.entityLogicalName,xaml:RH(t),category:gd.WorkflowCategory.BusinessProcessFlow,type:gd.WorkflowTypeCode.Definition,businessprocesstype:gd.BusinessProcessType.BusinessFlow,scope:gd.WorkflowScope.Organization,processorder:(r=t.order)!==null&&r!==void 0?r:fH};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 sn.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(IR):[IR({id:(0,jt.newId)(),name:"New Stage",steps:[]})],o={id:t.id&&t.id.trim()!==""?t.id:(0,jt.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=jg(t);(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,jt.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,er.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,er.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=jg(l),p=typeof d.id=="string"?d.id.trim():"";p===""?r.push((0,er.issue)(`${c}/id`,"stage-id-required","a stage needs an id")):o.has(p.toLowerCase())?r.push((0,er.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,er.issue)(`${c}/steps`,"stage-needs-step","a BPF stage must have at least one step")),f.length>30&&r.push((0,er.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 b=`${c}/steps/${v}`,E=typeof jg(h).id=="string"?h.id.trim():"";E===""?r.push((0,er.issue)(`${b}/id`,"step-id-required","a step needs an id")):m.has(E.toLowerCase())?r.push((0,er.issue)(`${b}/id`,"step-id-duplicate",`two steps in this stage share the id '${h.id}'`)):m.set(E.toLowerCase(),v)}),l.branch&&!DR(i,l.branch.nextStageId)&&r.push((0,er.issue)(`${c}/branch/nextStageId`,"branch-target-unknown",`branch nextStageId '${l.branch.nextStageId}' does not match any stage id`)),typeof l.nextStageId=="string"&&l.nextStageId!==""&&!DR(i,l.nextStageId)&&r.push((0,er.issue)(`${c}/nextStageId`,"next-stage-unknown",`nextStageId '${l.nextStageId}' does not match any stage id`))}),a.size>5&&r.push((0,er.issue)("/stages","too-many-tables",`a BPF spans at most 5 tables, got ${a.size}`));let s=xH(i);return s>=0&&r.push((0,er.issue)(`/stages/${s}/nextStageId`,"next-stage-cycle","the stage nextStageId links form a cycle; the flow must be acyclic")),r}};Oo.BpfAdapter=yd;function xH(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 DR(e,t){return e.some(r=>r.id===t)}function IR(e){var t,r;let n=e.steps&&e.steps.length>0?e.steps.map(_R):[_R({id:(0,jt.newId)(),name:"New Step"})],i={id:e.id&&e.id.trim()!==""?e.id:(0,jt.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 _R(e){var t;let r={id:e.id&&e.id.trim()!==""?e.id:(0,jt.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 e0(e,t,r,n){return`${Hg}<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="${vR}" /></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="${vR}" /></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 FH(){return{adapter:new yd,api:pH.bpfApi,languageSensitive:!0}}Oo.bpfRegistration=FH});var eO=y(Ed=>{"use strict";Object.defineProperty(Ed,"__esModule",{value:!0});Ed.buildRegistrations=void 0;var LH=I_(),kH=z_(),MH=d2(),BH=I2(),UH=j2(),$H=dP(),qH=_P(),VH=aR(),GH=ZR();function zH(e){let t=new Map;return t.set("form",(0,LH.formRegistration)(e)),t.set("view",(0,kH.viewRegistration)()),t.set("businessRule",(0,MH.businessRuleRegistration)()),t.set("app",(0,BH.appRegistration)(e)),t.set("command",(0,UH.commandRegistration)()),t.set("chart",(0,$H.chartRegistration)()),t.set("dashboard",(0,qH.dashboardRegistration)(e)),t.set("genPage",(0,VH.genPageRegistration)()),t.set("bpf",(0,GH.bpfRegistration)()),t}Ed.buildRegistrations=zH});var uO=y(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.removeRowSummary=Me.configureRowSummary=Me.buildGptDynamicPrompt=Me.setAppAiFeatures=Me.getAiReadiness=Me.saveSettingValue=Me.retrieveSetting=Me.AI_GATE=void 0;var Lr=be(),Ge=ae(),tO=lt(),Ln=te();Me.AI_GATE={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabled",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"EnableNLGridSearch",nlChart:"NLChartVisualizationSetting",summaries:"EnableFormInsights",m365:"m365copilotmodelappenabled"};var aO={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabledOnByDefault",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"NLGridSearchSetting",nlChart:"NLChartDataVisualizationSetting",m365:"m365copilotmodelappenabled"},WH=new Set(Object.entries(Me.AI_GATE).filter(([e,t])=>aO[e]===t).map(([e])=>e)),jH={formFill:{enabled:"2",disabled:"1"},formFillSuggestions:{enabled:"2",disabled:"1"},formFillSmartPaste:{enabled:"2",disabled:"1"},formFillFiles:{enabled:"2",disabled:"1"}};function t0(e){return jH[e]}var Cd=1e6;function HH(e,t){let r=t0(t),n=()=>{throw new Ln.InvalidArgumentError(`setAppAiFeatures: '${t}' must be a boolean or an integer between 0 and ${Cd} (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>Cd?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(Cd).length||Number(s)>Cd?n():s}}return n()}function KH(e,t){let r=t0(t);return r?e===r.enabled:e!=="0"}async function JH(e,t){var r,n,i;let a=`/appmodules${(0,Ge.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,Ge.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 QH(e,t){var r,n;let i=`/appmodules${(0,Ge.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,Ge.odataLiteral)(t)}'`]])}`,a;try{a=await e.get(i)}catch(l){throw new Ln.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 Ln.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 Ln.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 Ln.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a row with no appmoduleid.`);return s}var rO=new WeakMap;async function XH(e,t){var r,n,i;let a=rO.get(e);if(a||(a=new Map,rO.set(e,a)),a.has(t))return a.get(t);let o=`/settingdefinitions${(0,Ge.odataQuery)([["$select","settingdefinitionid"],["$filter",`uniquename eq '${(0,Ge.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 YH(e,t,r){var n,i;let a=await XH(e,r);if(!t||!a)return;let o=`/appsettings${(0,Ge.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 ZH=4,eK=500,nO=20,iO=3e4;function tK(e){if(e===void 0)return ZH;if(!Number.isFinite(e))throw new Ln.InvalidArgumentError(`setAppAiFeatures: verifyAttempts must be a finite integer between 1 and ${nO}; got ${e}.`);return Math.min(nO,Math.max(1,Math.floor(e)))}function rK(e){if(e===void 0)return eK;if(!Number.isFinite(e))throw new Ln.InvalidArgumentError(`setAppAiFeatures: verifyDelayMs must be a finite number between 0 and ${iO}; got ${e}.`);return Math.min(iO,Math.max(0,Math.floor(e)))}async function nK(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 YH(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 Sd(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 oO(e,t,r){if(t===2)return String(e).toLowerCase()==="true";let n=r?t0(r):void 0;return n?e===n.enabled:e!=null&&e!=="0"&&e!==""}async function Sd(e,t,r={}){var n,i;let a=[`SettingName='${(0,Ge.odataPathLiteral)(t)}'`];r.appUniqueName&&a.push(`AppUniqueName='${(0,Ge.odataPathLiteral)(r.appUniqueName)}'`);let o=`/RetrieveSetting(${a.join(",")})`,l=(i=(n=(0,Lr.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}}Me.retrieveSetting=Sd;async function sO(e,t,r,n={}){let i={SettingName:t,Value:r};n.appUniqueName&&(i.AppUniqueName=n.appUniqueName),n.solutionUniqueName&&(i.SolutionUniqueName=n.solutionUniqueName),(0,Lr.ensureSuccess)(await e.post("/SaveSettingValue",i),e.apiUrl("/SaveSettingValue"))}Me.saveSettingValue=sO;async function iK(e,t={}){let r={};for(let[n,i]of Object.entries(Me.AI_GATE)){let{value:a,dataType:o}=await Sd(e,i,t);r[n]={enabled:oO(a,o,n),setting:i,value:a}}return r}Me.getAiReadiness=iK;async function aK(e,t,r,n={}){var i,a;if(!t||!t.trim())throw new Ln.InvalidArgumentError("setAppAiFeatures: a non-empty appUniqueName is required (an empty value would write the setting at organization scope, affecting every app).");let o=tK(n.verifyAttempts),s=rK(n.verifyDelayMs),l=[];for(let[h,v]of Object.entries(r)){if(v===void 0)continue;let b=aO[h];b&&l.push({feature:h,setting:b,requestedValue:HH(v,h)})}let u=[],c=n.appModuleId?(0,Ge.normalizeGuid)(n.appModuleId,"appModuleId"):void 0;if(c){let h=await QH(e,t);if(h&&(0,Ge.normalizeGuid)(h,"appModuleId")!==c)throw new Ln.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 JH(e,t)),d),f=new Map,m=async h=>{if(WH.has(h))return;let v=Me.AI_GATE[h];if(v){if(!f.has(v))try{let{value:b,dataType:E}=await Sd(e,v);f.set(v,{enabled:oO(b,E,h),setting:v,value:b})}catch{f.set(v,void 0)}return f.get(v)}};for(let{feature:h,setting:v,requestedValue:b}of l)try{await sO(e,v,b,{appUniqueName:t,solutionUniqueName:n.solutionUniqueName});let E=await nK(e,p,t,v,b,o,s),C={feature:h,setting:v,requestedValue:b,effectiveValue:E.effectiveValue,appOverrideExists:E.appOverrideExists};if(E.result==="proven")u.push({...C,status:"applied"});else if(E.result==="absent"){let N=KH(b,h)?await m(h):void 0;N&&!N.enabled?u.push({...C,status:"skipped",reason:`the write was issued and no app-scope override holding '${b}' was observed for '${v}' after ${o} attempt(s); the org readiness gate '${N.setting}' reads '${N.value}', so an environment admin must enable it before this app can turn the feature on`}):u.push({...C,status:"notPersisted",reason:`the write reported success but no app-scope override holding '${b}' was observed for '${v}' after ${o} attempt(s) \u2014 it reads '${(i=E.effectiveValue)!==null&&i!==void 0?i:""}' for this app (Dataverse can accept an app-scope write without storing it)`})}else u.push({...C,status:"unverified",reason:`the write was issued but could not be confirmed: ${(a=E.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(E){u.push({feature:h,setting:v,requestedValue:b,status:"failed",reason:E.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}}Me.setAppAiFeatures=aK;var oK="GptPowerPrompt",sK='{ "consumptionSource": "Api", "partnerSource": "AIBuilder", "consumptionSourceVersion": "GptApiClient"}';function lO(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:""}}Me.buildGptDynamicPrompt=lO;async function lK(e,t){var r,n;let i=`/EntityDefinitions(LogicalName='${(0,Ge.odataPathLiteral)(t)}')${(0,Ge.odataQuery)([["$select","MetadataId"]])}`;return(n=(r=(0,Lr.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||r===void 0?void 0:r.MetadataId)!==null&&n!==void 0?n:""}async function uK(e,t,r={}){var n,i,a,o,s;let l=`ais_RowSummary_${t.entityLogicalName}`,u=`/aiskillconfigs${(0,Ge.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,Ge.odataLiteral)(l)}'`],["$top",1]])}`,c=((i=(n=(0,Lr.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,Ge.odataQuery)([["$select","msdyn_aitemplateid"],["$filter",`msdyn_uniquename eq '${oK}'`],["$top",1]])}`,p=((s=(o=(a=(0,Lr.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,tO.newId)(),m=(0,tO.newId)(),h=JSON.stringify(lO(t)),v={ModelId:f,RunConfigurationId:m,ModelName:`${t.entityLogicalName} row summary`,TemplateId:p,CustomConfiguration:h,Source:sK,RunConfiguration:""};(0,Lr.ensureSuccess)(await e.post("/AIModelPublish",v),e.apiUrl("/AIModelPublish"));try{let b=await lK(e,t.entityLogicalName),E={uniquename:l,description:`${t.entityLogicalName} row summary`,"[email protected]":`/entities(${b})`,"[email protected]":`/msdyn_aimodels(${f})`,aiskill:"RowSummary"},C=(0,Lr.ensureSuccess)(await e.post("/aiskillconfigs",E),e.apiUrl("/aiskillconfigs")),N=(0,Lr.requireCreatedId)(C,"aiskillconfigid","row-summary skill");return{modelId:f,aiSkillConfigId:N}}catch(b){try{await e.delete(`/msdyn_aimodels(${f})`)}catch{}throw b}}Me.configureRowSummary=uK;async function cK(e,t){var r,n;let i=`ais_RowSummary_${t.entityLogicalName}`,a=`/aiskillconfigs${(0,Ge.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,Ge.odataLiteral)(i)}'`],["$top",1]])}`,o=((n=(r=(0,Lr.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=(0,Ge.normalizeGuid)(o.aiskillconfigid,"aiskillconfigid"),l=o._aimodel_value?(0,Ge.normalizeGuid)(o._aimodel_value,"_aimodel_value"):void 0,u=`/aiskillconfigs(${s})`;if((0,Lr.ensureSuccess)(await e.delete(u),e.apiUrl(u)),l){let c=`/msdyn_aimodels(${l})`;(0,Lr.ensureSuccess)(await e.delete(c),e.apiUrl(c))}}Me.removeRowSummary=cK});var pO=y(xo=>{"use strict";Object.defineProperty(xo,"__esModule",{value:!0});xo.findArtifact=xo.resolveArtifact=void 0;var dt=ae(),kn=lu(),dK=gu(),pK=Pt(),fK=be(),cO=te();async function dO(e,t,r){let n="/uxagentprojects"+(0,dt.odataQuery)([["$select","uxagentprojectid,name"],["$filter",`name eq '${(0,dt.odataLiteral)(t)}'`],...r!==void 0?[["$top",String(r)]]:[]]);return(await(0,pK.collectPages)(e,n,"resolveArtifact('genPage')",void 0,{headers:{"MSCRM.IncludeUnpublished":"true"}})).map(a=>({id:String(a.uxagentprojectid),name:String(a.name)}))}async function mK(e,t,r){var n,i,a,o,s,l,u,c,d,p,f,m,h;switch(t){case"app":{let v=(0,dK.unpublishedAppModulesQuery)("appmoduleid,name,appmoduleidunique",`uniquename eq '${(0,dt.odataLiteral)((n=r.uniqueName)!==null&&n!==void 0?n:"")}'`,1),E=(i=(0,fK.ensureSuccess)(await e.get(v),e.apiUrl(v)).body)===null||i===void 0?void 0:i.value,C=E&&E[0];return C?[{id:String(C.appmoduleid),name:String(C.name),appModuleIdUnique:String(C.appmoduleidunique)}]:[]}case"dashboard":return(await(0,kn.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,dt.odataLiteral)((a=r.name)!==null&&a!==void 0?a:"")}' and type eq 0`,top:10})||[]).map(b=>({id:String(b.formid),name:String(b.name)}));case"command":{let v=await(0,kn.queryRecords)(e,"appaction",{select:["appactionid","buttonlabeltext"],filter:`contextvalue eq '${(0,dt.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,kn.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,dt.odataLiteral)((s=r.name)!==null&&s!==void 0?s:"")}' and objecttypecode eq '${(0,dt.odataLiteral)((l=r.entity)!==null&&l!==void 0?l:"")}'`,top:10})||[]).map(b=>({id:String(b.formid),name:String(b.name)}));case"chart":return(await(0,kn.queryRecords)(e,"savedqueryvisualization",{select:["savedqueryvisualizationid","name"],filter:`name eq '${(0,dt.odataLiteral)((u=r.name)!==null&&u!==void 0?u:"")}' and primaryentitytypecode eq '${(0,dt.odataLiteral)((c=r.entity)!==null&&c!==void 0?c:"")}'`,top:10})||[]).map(b=>({id:String(b.savedqueryvisualizationid),name:String(b.name)}));case"view":return(await(0,kn.queryRecords)(e,"savedquery",{select:["savedqueryid","name"],filter:`name eq '${(0,dt.odataLiteral)((d=r.name)!==null&&d!==void 0?d:"")}' and returnedtypecode eq '${(0,dt.odataLiteral)((p=r.entity)!==null&&p!==void 0?p:"")}'`,top:10})||[]).map(b=>({id:String(b.savedqueryid),name:String(b.name)}));case"webResource":return(await(0,kn.queryRecords)(e,"webresource",{select:["webresourceid","name"],filter:`name eq '${(0,dt.odataLiteral)((f=r.name)!==null&&f!==void 0?f:"")}'`,top:1})||[]).map(b=>({id:String(b.webresourceid),name:String(b.name)}));case"solution":return(await(0,kn.queryRecords)(e,"solution",{select:["solutionid","uniquename"],filter:`uniquename eq '${(0,dt.odataLiteral)((m=r.uniqueName)!==null&&m!==void 0?m:"")}'`,top:1})||[]).map(b=>({id:String(b.solutionid),name:String(b.uniquename)}));case"genPage":return dO(e,(h=r.name)!==null&&h!==void 0?h:"");default:return[]}}xo.resolveArtifact=mK;async function hK(e,t,r){var n,i,a,o,s,l,u;let c=(0,dt.odataLiteral)((n=r.name)!==null&&n!==void 0?n:""),d=(0,dt.odataLiteral)((i=r.entity)!==null&&i!==void 0?i:"");if(t==="command"){let v=await(0,kn.queryRecords)(e,"appaction",{select:["appactionid"],filter:`contextvalue eq '${(0,dt.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 dO(e,(o=r.name)!==null&&o!==void 0?o:"",2);if(v.length>1)throw new cO.AmbiguousArtifactError(t,(s=r.name)!==null&&s!==void 0?s:"",v.length);return v.length===1?v[0].id:null}let p=gK(t,c,d,r),f=t!=="app",m=await(0,kn.queryRecords)(e,p.set,{select:[p.idField],filter:p.filter,top:f?2:1});if(f&&m&&m.length>1)throw new cO.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}xo.findArtifact=hK;function gK(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,dt.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 mO=y(Dd=>{"use strict";Object.defineProperty(Dd,"__esModule",{value:!0});Dd.seedRecordGraph=void 0;var fO=lu(),vK=xl(),Nd=ae(),yK=te();async function bK(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,vK.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 O of p.records){let F={...O.body};for(let k of(o=O.binds)!==null&&o!==void 0?o:[]){let P=k.parentEntity.toLowerCase(),V=(s=d(P))===null||s===void 0?void 0:s[k.parentIndex];if(!V)throw new yK.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 q=(0,Nd.assertODataName)(await u(P),`entity set for parent '${k.parentEntity}'`),ze=(0,Nd.normalizeGuid)(V,`parent id for bind '${k.navProperty}'`);F[`${k.navProperty}@odata.bind`]=`/${q}(${ze})`}h.push(F)}let v=m?h.map(O=>{let F=O[m];return F!=null&&F!==""?String(F):null}):h.map(()=>null),b=new Map;if(m){let O=(0,Nd.assertODataName)(m,"RecordGraph matchOn key"),F=[...new Set(v.filter(k=>k!==null))];if(F.length){let k=F.map(V=>`${O} eq '${(0,Nd.odataLiteral)(V)}'`).join(" or "),P=await(0,fO.queryRecords)(e,f,{select:[O,`${f}id`],filter:k,top:5e3});for(let V of P??[]){let q=V[O];q!=null&&b.set(String(q).toLowerCase(),String(V[`${f}id`]))}}}let E=[],C=new Map,N=h.map((O,F)=>{let k=v[F];if(k&&b.has(k.toLowerCase()))return null;if(k){let P=k.toLowerCase(),V=C.get(P);if(V!==void 0)return V;let q=E.push(O)-1;return C.set(P,q),q}return E.push(O)-1}),R=E.length?await(0,fO.createRecordsBulk)(e,f,E):[];c[f]=h.map((O,F)=>{let k=v[F];return k&&b.has(k.toLowerCase())?b.get(k.toLowerCase()):R[N[F]]})}return{createdIds:c}}Dd.seedRecordGraph=bK});var SO=y(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.getEntityPrivileges=bt.addEntityPrivilegesToRole=bt.deleteSecurityRole=bt.createPersonaRole=bt.createSecurityRole=bt.SDK_ROLE_MARKER=void 0;var kr=be(),it=ae(),tr=te(),Id={read:"Read",create:"Create",write:"Write",delete:"Delete",append:"Append",appendTo:"AppendTo",assign:"Assign",share:"Share"},n0={user:"Basic",businessUnit:"Local",parentChild:"Deep",organization:"Global"},hO={user:1,businessUnit:2,parentChild:3,organization:4},r0={user:"CanBeBasic",businessUnit:"CanBeLocal",parentChild:"CanBeDeep",organization:"CanBeGlobal"};bt.SDK_ROLE_MARKER="Authored by @maker-studio/cds-maker-sdk (persona/security role).";function wK(e){return Object.prototype.hasOwnProperty.call(Id,e)?Id[e]:void 0}function AK(e){return Object.prototype.hasOwnProperty.call(n0,e)}var gO=new WeakMap,vO=new WeakMap;async function wO(e,t){var r,n;(0,it.assertODataName)(t,"entity logical name");let i=gO.get(e);i||(i=new Map,gO.set(e,i));let a=i.get(t);if(a)return a;let o=`/EntityDefinitions(LogicalName='${(0,it.odataPathLiteral)(t)}')${(0,it.odataQuery)([["$select","LogicalName,Privileges"]])}`,l=(n=(r=(0,kr.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 tr.InvalidArgumentError(`Entity '${t}' exposes no privileges (unknown or non-securable entity).`);return i.set(t,l),l}async function EK(e){var t,r,n;let i=vO.get(e);if(i)return i;let a=`/businessunits${(0,it.odataQuery)([["$select","businessunitid"],["$filter","_parentbusinessunitid_value eq null"],["$top",1]])}`,l=(n=((r=(t=(0,kr.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 tr.InvalidArgumentError("Could not resolve the root business unit.");let u=(0,it.normalizeGuid)(l,"businessUnitId");return vO.set(e,u),u}async function AO(e,t){var r;let n=new Map;for(let i of t){if(!i.access||i.access.length===0)throw new tr.InvalidArgumentError(`Entity '${i.entity}' privilege request has no access levels.`);let a=(r=i.scope)!==null&&r!==void 0?r:"user";if(!AK(a))throw new tr.InvalidArgumentError(`Unknown privilege scope '${a}' for entity '${i.entity}'.`);let o=await wO(e,i.entity);for(let s of i.access){let l=wK(s);if(!l)throw new tr.InvalidArgumentError(`Unknown access level '${s}' for entity '${i.entity}'.`);let u=o.find(m=>m.PrivilegeType===l);if(!u)throw new tr.InvalidArgumentError(`Entity '${i.entity}' does not support '${s}' access.`);let c=r0[a];if(u[c]===!1)throw new tr.InvalidArgumentError(`Privilege '${u.Name}' on '${i.entity}' does not support the '${a}' scope.`);let d=(0,it.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 tr.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=hO[a]>hO[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 CK(e,t,r,n){if(r.length===0&&!n)return;let i={Privileges:r.map(o=>({Depth:n0[o.scope],PrivilegeId:o.privilegeId}))},a=`/roles(${t})/Microsoft.Dynamics.CRM.ReplacePrivilegesRole`;(0,kr.ensureSuccess)(await e.post(a,i),e.apiUrl(a))}async function yO(e,t,r,n,i){var a,o;let s=`/${t}(${r})/${n}${(0,it.odataQuery)([["$select","roleid"],["$filter",`roleid eq ${i}`]])}`;return((o=(a=(0,kr.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 SK(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,it.normalizeGuid)(l,"teamId");if(!await yO(e,"teams",u,"teamroles_association",t)){let c=`/teams(${u})/teamroles_association/$ref`;(0,kr.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,it.normalizeGuid)(l,"userId");if(!await yO(e,"systemusers",u,"systemuserroles_association",t)){let c=`/systemusers(${u})/systemuserroles_association/$ref`;(0,kr.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}o.push(u)}return{teams:a,users:o}}async function bO(e,t,r){var n,i;let a=`/roles${(0,it.odataQuery)([["$select","roleid,description,ismanaged"],["$filter",`name eq '${(0,it.odataLiteral)(t)}' and _businessunitid_value eq ${r}`]])}`,l=((i=(n=(0,kr.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:"")===bt.SDK_ROLE_MARKER};if(l.some(d=>!u(d)))throw new tr.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 tr.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,it.normalizeGuid)(c,"roleId"):void 0}function NK(e){var t,r;return{teams:((t=e?.teams)!==null&&t!==void 0?t:[]).map(n=>(0,it.normalizeGuid)(n,"teamId")),users:((r=e?.users)!==null&&r!==void 0?r:[]).map(n=>(0,it.normalizeGuid)(n,"userId"))}}function EO(e){return e.map(t=>({entity:t.entity,privilegeName:t.privilegeName,privilegeType:t.privilegeType,scope:t.scope}))}async function CO(e,t){var r,n;let i=(r=t.name)===null||r===void 0?void 0:r.trim();if(!i)throw new tr.InvalidArgumentError("createSecurityRole: a non-empty role name is required.");let a=t.businessUnitId?(0,it.normalizeGuid)(t.businessUnitId,"businessUnitId"):await EK(e),o=await AO(e,(n=t.privileges)!==null&&n!==void 0?n:[]),s=NK(t.assignTo),l=await bO(e,i,a),u=l!==void 0;if(!l){let d="/roles",p={name:i,description:bt.SDK_ROLE_MARKER,"[email protected]":`/businessunits(${a})`};try{let f=(0,kr.ensureSuccess)(await e.post(d,p),e.apiUrl(d));l=(0,it.normalizeGuid)((0,kr.requireCreatedId)(f,"roleid","role"),"roleId")}catch(f){let m;try{m=await bO(e,i,a)}catch{m=void 0}if(!m)throw f;l=m}}await CK(e,l,o,u);let c=await SK(e,l,s);return{roleId:l,name:i,reused:u,appliedPrivileges:EO(o),assignedTeams:c.teams,assignedUsers:c.users}}bt.createSecurityRole=CO;async function DK(e,t){var r,n;let i=(r=t.persona)===null||r===void 0?void 0:r.trim();if(!i)throw new tr.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 CO(e,{name:i,businessUnitId:t.businessUnitId,privileges:a,assignTo:t.assignTo})}bt.createPersonaRole=DK;async function IK(e,t){let n=`/roles(${(0,it.normalizeGuid)(t,"roleId")})`;(0,kr.ensureSuccess)(await e.delete(n),e.apiUrl(n))}bt.deleteSecurityRole=IK;async function _K(e,t,r){let n=(0,it.normalizeGuid)(t,"roleId");if(r.length===0)throw new tr.InvalidArgumentError("addEntityPrivilegesToRole requires at least one entity privilege (an empty grant would be a silent no-op).");let i=await AO(e,r),a={Privileges:i.map(s=>({Depth:n0[s.scope],PrivilegeId:s.privilegeId}))},o=`/roles(${n})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;return(0,kr.ensureSuccess)(await e.post(o,a),e.apiUrl(o)),EO(i)}bt.addEntityPrivilegesToRole=_K;var TK=new Map(Object.keys(Id).map(e=>[Id[e],e]));async function PK(e,t){return(await wO(e,t)).map(n=>{let i=Object.keys(r0).filter(o=>n[r0[o]]!==!1),a=TK.get(n.PrivilegeType);return{name:n.Name,privilegeId:n.PrivilegeId,privilegeType:n.PrivilegeType,...a?{access:a}:{},scopes:i}})}bt.getEntityPrivileges=PK});var PO=y(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.createMakerSdk=rr.MakerSdk=rr.PUSH_NOT_ATTEMPTED_CODE=rr.ALREADY_EXISTS_CODE=void 0;var NO=Xd(),ne=te(),br=ca(),RK=Iv(),Pd=xv(),pl=Uv(),OK=Zd(),xK=ay(),i0=oy(),FK=wy(),at=xl(),DO=of(),Mn=lu(),_d=ow(),Fo=pu(),LK=mu(),wt=fw(),kK=df(),MK=wf(),BK=eO(),Td=lt(),UK=ha(),cn=rg(),bi=rp(),$K=3e5,wr=be(),wi=ae(),Lo=uO(),IO=pO(),qK=mO(),VK=wh(),fl=SO();function GK(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 Pd.WorkspaceManager(zK,e.instanceUrl,(0,OK.assertStorageContract)(t))}rr.ALREADY_EXISTS_CODE="ARTIFACT_ALREADY_EXISTS";rr.PUSH_NOT_ATTEMPTED_CODE="PUSH_NOT_ATTEMPTED";var zK="<injected workspaceStorage>",Rd=class{constructor(t){var r,n;this.artifactLocks=new Map,this.observedGenerations=new Map,this.baselineObserved=new Map,this.languageCode=(r=t.languageCode)!==null&&r!==void 0?r:UK.DEFAULT_LCID,this.cacheStalenessMs=(n=t.cacheStalenessMs)!==null&&n!==void 0?n:$K,this.compiler={load:(0,kK.createGenPageTypeScriptLoader)(t.typescript)},this.workspace=GK(t),this.versions=new pl.VersionManager(this.workspace),this.dataverse=new xK.DataverseClient(t.instanceUrl,t.httpClient,t.solutionUniqueName),this.registrations=(0,BK.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=this.artifactKey(t,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,async()=>{let i=await this.fetchArtifactUnlocked(t,r,n);return await this.acknowledgeRefresh(t,r),i})}async fetchArtifactUnlocked(t,r,n){var i,a,o;let s=this.requireRegistration(t,"fetchArtifact"),{raw:l,etag:u,memberEtags:c,siblingEtags:d}=await s.api.get(this.dataverse,r),p=s.adapter.fromApiResponse(l);if(!n?.overwrite&&await this.versions.isDirty(t,r)){let m=(a=(i=await this.versions.getMeta(t,r))===null||i===void 0?void 0:i.etag)!==null&&a!==void 0?a:null;if(m&&u&&m!==u)throw new ne.LocalEditsWouldBeLostError(t,r,m,u);let h=await this.workspace.readArtifact(t,r);if(h){let v=await this.versions.getMeta(t,r);if(v&&!v.etag&&u){if(!(0,bi.deepEqual)(v.snapshot,p))throw new ne.LocalEditsWouldBeLostError(t,r,m,u);await this.versions.storeMeta(t,r,{...v,etag:u,fetchedAt:(0,wr.nowIso)()})}return(0,cn.cloneJson)(h)}}await this.workspace.writeArtifact(t,r,p);let f=await this.versions.getMeta(t,r);return await this.versions.storeMeta(t,r,{etag:u,languageCode:this.languageCode,projectionVersion:pl.PROJECTION_VERSION,fetchedAt:(0,wr.nowIso)(),snapshot:(0,cn.cloneJson)(p),...c?{memberEtags:c}:{},...d?{siblingEtags:d}:{},...f?.refreshGeneration?{refreshGeneration:f.refreshGeneration,observedGeneration:(o=f.observedGeneration)!==null&&o!==void 0?o:0}:{}}),(0,cn.cloneJson)(p)}async fetchArtifactList(t,r){return this.requireRegistration(t,"fetchArtifactList").api.list(this.dataverse,r)}async fetchSolution(t){var r;let n=await(0,wt.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,wr.nowIso)(),isDirty:!1})}catch(s){a.push({componentId:o.objectId,componentType:o.componentType,workflowCategory:o.workflowCategory,reason:"failed",error:oa(s)})}return await this.workspace.updateManifest({lastSyncAt:(0,wr.nowIso)()}),{summaries:i,skipped:a}}async fetchEntityMetadata(t){let r=await(0,i0.fetchEntityMetadataFromApi)(this.dataverse,t);return await this.workspace.writeEntityMetadata(t,r),r}generateGenPageRuntimeTypes(t,r){return(0,FK.generateGenPageRuntimeTypes)(n=>this.fetchEntityMetadata(n),t,r)}findTables(t,r){return(0,i0.findTables)(this.dataverse,t,r)}findColumns(t,r,n){return(0,i0.findColumns)(this.dataverse,t,r,n)}createTable(t){return(0,at.createTable)(this.dataverse,t)}createColumn(t,r){return(0,at.createColumn)(this.dataverse,t,r)}createColumns(t,r){return(0,at.createColumns)(this.dataverse,t,r)}updateColumn(t,r,n){return(0,at.updateColumn)(this.dataverse,t,r,n)}deleteColumn(t,r){return(0,at.deleteColumn)(this.dataverse,t,r)}setFormSecurityRoles(t,r){return(0,DO.setFormSecurityRoles)(this.dataverse,t,r)}getFormSecurityRoles(t){return(0,DO.getFormSecurityRoles)(this.dataverse,t)}setColumnVisualization(t,r,n){return(0,at.setColumnVisualization)(this.dataverse,t,r,n)}getColumnVisualization(t,r){return(0,at.getColumnVisualization)(this.dataverse,t,r)}createCustomerColumn(t,r){return(0,at.createCustomerColumn)(this.dataverse,t,r)}insertStatusValue(t,r){return(0,at.insertStatusValue)(this.dataverse,t,r)}updateTable(t,r){return(0,at.updateTable)(this.dataverse,t,r)}async setEntityIcon(t,r){if(await(0,at.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,wi.xmlText)(t)}</entity></entities></importexportxml>`;(0,wr.ensureSuccess)(await this.dataverse.post("/PublishXml",{ParameterXml:n}),this.dataverse.apiUrl("/PublishXml"))}}createAlternateKey(t,r){return(0,at.createAlternateKey)(this.dataverse,t,r)}deleteAlternateKey(t,r){return(0,at.deleteAlternateKey)(this.dataverse,t,r)}createRelationship(t){return(0,at.createRelationship)(this.dataverse,t)}deleteRelationship(t){return(0,at.deleteRelationship)(this.dataverse,t)}createGlobalOptionSet(t){return(0,at.createGlobalOptionSet)(this.dataverse,t)}deleteGlobalOptionSet(t){return(0,at.deleteGlobalOptionSet)(this.dataverse,t)}deleteTable(t){return(0,at.deleteTable)(this.dataverse,t)}createSecurityRole(t){return(0,fl.createSecurityRole)(this.dataverse,t)}createPersonaRole(t){return(0,fl.createPersonaRole)(this.dataverse,t)}deleteSecurityRole(t){return(0,fl.deleteSecurityRole)(this.dataverse,t)}addEntityPrivilegesToRole(t,r){return(0,fl.addEntityPrivilegesToRole)(this.dataverse,t,r)}getEntityPrivileges(t){return(0,fl.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,qK.seedRecordGraph)(this.dataverse,t,r)}resolveArtifact(t,r){return(0,IO.resolveArtifact)(this.dataverse,t,r)}findArtifact(t,r){return(0,IO.findArtifact)(this.dataverse,t,r)}async deleteAppCascade(t,r){let n=await(0,MK.deleteAppCascade)(this.dataverse,t,r),i=(0,wi.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,_d.createWebResource)(this.dataverse,t)}updateWebResource(t,r){return(0,_d.updateWebResource)(this.dataverse,t,r)}getWebResource(t){return(0,_d.getWebResource)(this.dataverse,t)}deleteWebResource(t){return(0,_d.deleteWebResource)(this.dataverse,t)}getAppSettings(t){return(0,Fo.readAppSettings)(this.dataverse,t)}setAppSetting(t,r,n){return(0,Fo.setAppSetting)(this.dataverse,t,r,n)}setHeaderAndNavigationRefresh(t,r){if(typeof r!="boolean")throw new ne.ValidationError("app",t,[{pointer:"/headerAndNavigationRefresh",rule:LK.HEADER_NAV_BOOLEAN_RULE,message:`enabled must be a boolean, got ${typeof r}`}]);return(0,Fo.setAppSetting)(this.dataverse,t,Fo.HEADER_AND_NAVIGATION_REFRESH,r?Fo.APP_SETTING_ON:Fo.APP_SETTING_OFF)}getSolution(t){return(0,wt.getSolution)(this.dataverse,t)}createPublisher(t){return(0,wt.createPublisher)(this.dataverse,t)}createSolution(t){return(0,wt.createSolution)(this.dataverse,t)}setSolutionVersion(t,r){return(0,wt.setSolutionVersion)(this.dataverse,t,r)}addSolutionComponent(t){return(0,wt.addSolutionComponent)(this.dataverse,t)}removeSolutionComponent(t,r,n){return(0,wt.removeSolutionComponent)(this.dataverse,t,r,n)}exportSolution(t){return(0,wt.exportSolution)(this.dataverse,t)}importSolution(t){return(0,wt.importSolution)(this.dataverse,t)}deleteSolution(t){return(0,wt.deleteSolution)(this.dataverse,t)}async getArtifact(t,r){return this.withArtifactLock(t,r,async()=>{let n=await this.getArtifactUnlocked(t,r);return await this.acknowledgeRefresh(t,r),n})}async getArtifactUnlocked(t,r){return(0,cn.cloneJson)(await this.readRaw(t,r))}async acknowledgeRefresh(t,r){var n,i,a;let o=this.artifactKey(t,r),s=await this.versions.getMeta(t,r);this.baselineObserved.has(o)||this.baselineObserved.set(o,(n=s?.observedGeneration)!==null&&n!==void 0?n:0);let l=(i=s?.refreshGeneration)!==null&&i!==void 0?i:0;s&&l!==((a=s.observedGeneration)!==null&&a!==void 0?a:0)&&await this.versions.storeMeta(t,r,{...s,observedGeneration:l}),this.observedGenerations.set(o,l)}async observedAtInvocation(t,r,n){var i,a;if(n!==void 0)return n;let o=this.baselineObserved.get(this.artifactKey(t,r));return o!==void 0?o:(a=(i=await this.versions.getMeta(t,r))===null||i===void 0?void 0:i.observedGeneration)!==null&&a!==void 0?a:0}artifactKey(t,r){return`${t}\0${(0,Pd.canonicalArtifactId)(r)}`}async readRaw(t,r){return await this.revalidateIfStale(t,r),this.readLocal(t,r)}async readForMutation(t,r,n,i){var a,o;let s=await this.observedAtInvocation(t,r,i);if(((o=(a=await this.versions.getMeta(t,r))===null||a===void 0?void 0:a.refreshGeneration)!==null&&o!==void 0?o:0)>s)throw new ne.StaleArtifactError(t,r,n,"pushed");if(await this.revalidateIfStale(t,r)==="refreshed-changed")throw new ne.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 ne.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,bi.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=br.JsonPointer.resolve(i,n);if(a===void 0)throw new ne.PathNotFoundError(t,r,n);return n===""&&await this.acknowledgeRefresh(t,r),a})}async findElements(t,r,n){return this.withArtifactLock(t,r,async()=>(0,RK.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 ne.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 ne.PathNotFoundError("entityMetadata",t,r);return i}async updateElement(t,r,n,i){let a=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let o=await this.readForMutation(t,r,n,a),s=br.JsonPointer.resolve(o,n);if(s===void 0)throw new ne.PathNotFoundError(t,r,n);let l=Bn(s)&&Bn(i)?{...s,...i}:i;return br.JsonPointer.set(o,n,(0,cn.cloneJson)(l)),this.assertStructurallyValid(t,r,o,n),await this.workspace.writeArtifact(t,r,o),this.getArtifactUnlocked(t,r)})}async addElement(t,r,n,i,a){let o=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let s=await this.readForMutation(t,r,n,o),l=br.JsonPointer.resolve(s,n);if(l===void 0)throw new ne.PathNotFoundError(t,r,n);if(!Array.isArray(l)){if(!Bn(l)||!Bn(i))throw new ne.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 ne.ValidationError(t,r,n,"position is not supported for an object parent");let d={};for(let p of Object.keys(i)){if(p==="id")throw new ne.ValidationError(t,r,n,"refusing to write 'id' \u2014 that re-keys the node rather than adding a property");let f=(0,cn.cloneJson)(i[p]),m=(0,Td.isValueMapKey)(p)||(0,Td.pointerTouchesValueMap)(n);d[p]=m?f:Array.isArray(f)?f.map(h=>Bn(h)?this.assignMissingIds(t,h):h):Bn(f)?this.assignMissingIds(t,f):f}for(let p of Object.keys(d))br.JsonPointer.set(s,br.JsonPointer.append(n,p),d[p]);return this.assertStructurallyValid(t,r,s,n),await this.workspace.writeArtifact(t,r,s),this.getArtifactUnlocked(t,r)}let u=(0,Td.pointerTouchesValueMap)(n)?(0,cn.cloneJson)(i):this.assignMissingIds(t,(0,cn.cloneJson)(i)),c=jK(l,a?.position);return l.splice(c,0,u),this.assertStructurallyValid(t,r,s,n),await this.workspace.writeArtifact(t,r,s),this.getArtifactUnlocked(t,r)})}async moveElement(t,r,n,i,a){let o=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{var s;let l=await this.readForMutation(t,r,n,o),u=br.JsonPointer.resolve(l,n);if(u===void 0)throw new ne.PathNotFoundError(t,r,n);let c=br.JsonPointer.resolve(l,i);if(c===void 0)throw new ne.PathNotFoundError(t,r,i);if(!Array.isArray(c))throw new ne.ValidationError(t,r,i,"move target must be an array");if(i===n||i.startsWith(`${n}/`))throw new ne.ValidationError(t,r,i,"cannot move an element into its own subtree");br.JsonPointer.remove(l,n);let d=(s=a?.index)!==null&&s!==void 0?s:c.length;c.splice(Math.max(0,Math.min(d,c.length)),0,u),TO(c);let p=br.JsonPointer.resolve(l,_O(n));return Array.isArray(p)&&p!==c&&TO(p),this.assertStructurallyValid(t,r,l,i),await this.workspace.writeArtifact(t,r,l),this.getArtifactUnlocked(t,r)})}async removeElement(t,r,n){let i=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let a=await this.readForMutation(t,r,n,i);if(br.JsonPointer.resolve(a,n)===void 0)throw new ne.PathNotFoundError(t,r,n);return br.JsonPointer.remove(a,n),this.assertStructurallyValid(t,r,a,_O(n)),await this.workspace.writeArtifact(t,r,a),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 ne.ValidationError(t,r,u)}retrieveSetting(t,r){return(0,Lo.retrieveSetting)(this.dataverse,t,r)}saveSettingValue(t,r,n){return(0,Lo.saveSettingValue)(this.dataverse,t,r,n)}getAiReadiness(t){return(0,Lo.getAiReadiness)(this.dataverse,t)}setAppAiFeatures(t,r,n){return(0,Lo.setAppAiFeatures)(this.dataverse,t,r,n)}configureRowSummary(t,r){return(0,Lo.configureRowSummary)(this.dataverse,t,r)}removeRowSummary(t){return(0,Lo.removeRowSummary)(this.dataverse,t)}async enrichDefaultViews(t,r,n={}){let i=await(0,VK.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 ne.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 ne.ValidationError(t,"(new)","/id","created artifact must have an id");return this.withArtifactLock(t,a,async()=>(await this.workspace.writeArtifact(t,a,i),(0,cn.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){let{result:i,siblings:a}=await this.withArtifactLock(t,r,()=>this.publishArtifactUnlocked(t,r,n));for(let o of a)await this.withArtifactLock(o.type,o.id,()=>this.adoptBracket(o));return i}async publishArtifactUnlocked(t,r,n){var i;let a=await this.readRaw(t,r),o=this.registrations.get(t);if(!o?.publish)return{result:{type:t,id:r,shipped:!1,publish:{kind:"notApplicable"}},siblings:[]};let s=(i=o.publishScope)===null||i===void 0?void 0:i.call(o,r,a),l=o.rebaselineAfterPublish==="bracket"?await this.captureBracket(o,t,r):void 0,u=s?await this.captureSiblings(s,t,r):[];try{await o.publish(this.dataverse,r,a)}catch(d){return{result:{type:t,id:r,shipped:!1,publish:{kind:"failed",error:oa(d)},...s?{publishScope:s}:{}},siblings:[]}}if(o.rebaselineAfterPublish==="snapshot"&&await this.rebaselineAfterPublish(o,t,r),l&&await this.adoptBracket(l),!n?.verify)return{result:{type:t,id:r,shipped:!1,publish:{kind:"submitted"},...s?{publishScope:s}:{}},siblings:u};let c=await this.verifyPublished(t,r,a);return{result:{type:t,id:r,shipped:c.kind==="verified",publish:c,...s?{publishScope:s}:{}},siblings:u}}async captureBracket(t,r,n){var i;try{let a=(i=await this.versions.getMeta(r,n))===null||i===void 0?void 0:i.etag;if(!a||!t.api.readToken)return;let{raw:o,etag:s}=await t.api.get(this.dataverse,n);return s!==a||await t.api.readToken(this.dataverse,n)!==a?void 0:{type:r,id:n,reg:t,heldEtag:a,content:this.bracketContent(t,o)}}catch{return}}async captureSiblings(t,r,n){var i,a;let o=t.envelope==="entity"?(i=t.entityLogicalName)===null||i===void 0?void 0:i.toLowerCase():void 0;if(!o)return[];let s=[],l;try{l=await this.workspace.listArtifacts()}catch{return[]}for(let u of l){let c=this.registrations.get(u.type);if(u.type===r&&(0,Pd.canonicalArtifactId)(u.id)===(0,Pd.canonicalArtifactId)(n)||c?.rebaselineAfterPublish!=="bracket"||!c.publishScope)continue;try{let f=await this.workspace.readArtifact(u.type,u.id),m=f?c.publishScope(u.id,f):void 0;if(m?.envelope!=="entity"||((a=m.entityLogicalName)===null||a===void 0?void 0:a.toLowerCase())!==o)continue}catch{continue}let p=await this.captureBracket(c,u.type,u.id);p&&s.push(p)}return s}async adoptBracket(t){try{let r=await this.versions.getMeta(t.type,t.id);if(!r||r.etag!==t.heldEtag)return;let{raw:n,etag:i}=await t.reg.api.get(this.dataverse,t.id);if(!i||i===t.heldEtag||!(0,bi.deepEqual)(this.bracketContent(t.reg,n),t.content))return;await this.versions.storeMeta(t.type,t.id,{...r,etag:i,fetchedAt:(0,wr.nowIso)()})}catch{}}bracketContent(t,r){var n,i,a;let o=t.adapter.fromApiResponse(r);return(a=(i=(n=t.adapter).baselineContent)===null||i===void 0?void 0:i.call(n,o))!==null&&a!==void 0?a:o}adoptReadBack(t,r){try{return{artifact:t.adapter.fromApiResponse(r)}}catch(n){return{warning:`The write was saved, but the record read back after it could not be read into the local copy (${oa(n).message}). The SDK holds no version for it now, so the next push is refused: re-fetch before editing again.`}}}adoptedAsSent(t,r,n,i){try{let a=t.adapter.fromApiResponse({...n,...i});return(0,bi.deepEqual)(r,a)}catch{return!1}}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,bi.deepEqual)(c(i.snapshot),c(u)))return;await this.versions.storeMeta(r,n,{...i,etag:o,fetchedAt:(0,wr.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,wi.normalizeGuid)(r,"id")})${(0,wi.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:oa(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,bi.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,bi.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:oa(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 ne.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,l,u,c;let{type:d,id:p,reg:f,json:m,meta:h,payload:v}=t;try{let b=h?await f.api.update(this.dataverse,p,v,h.etag,h.memberEtags,h.siblingEtags):await this.createWithMintedId(f,d,p,v),E=p;h||(b.serverIdentity&&f.adapter.applyServerIdentity&&f.adapter.applyServerIdentity(m,b.serverIdentity),b.id&&b.id!==p&&(m.id=b.id,await this.workspace.deleteArtifact(d,p),E=b.id));let C=h&&b.readBack!==void 0?this.adoptReadBack(f,b.readBack):void 0,N=C?.artifact?{artifact:C.artifact,baseline:C.artifact}:f.adapter.committed?f.adapter.committed(m,v,{intentPending:b.intentPending===!0}):{artifact:m,baseline:m};(!h||N.artifact!==m)&&await this.workspace.writeArtifact(d,E,N.artifact);let R=C?.artifact!==void 0&&!(0,bi.deepEqual)(C.artifact,m),O=((r=h?.refreshGeneration)!==null&&r!==void 0?r:0)+(R?1:0),F=[...(n=b.warnings)!==null&&n!==void 0?n:[],...C?.warning?[C.warning]:[],...C?.artifact!==void 0&&!this.adoptedAsSent(f,C.artifact,b.readBack,v)?[`Saved, but the server holds something other than what was pushed (the platform rewrites a form on save \u2014 empty labels, column display names \u2014 or another writer saved in between); the local ${d} now holds the server's version. Read it (getArtifact) before the next edit: a mutation whose pointer was derived from the earlier copy is refused (StaleArtifactError).`]:[]];return await this.versions.storeMeta(d,E,{etag:C&&!C.artifact?null:b.etag,...O>0?{refreshGeneration:O,observedGeneration:(i=h?.observedGeneration)!==null&&i!==void 0?i:0}:{},languageCode:this.languageCode,projectionVersion:pl.PROJECTION_VERSION,fetchedAt:(0,wr.nowIso)(),snapshot:(0,cn.cloneJson)(N.baseline),...b.memberEtags?{memberEtags:b.memberEtags}:{},...b.siblingEtags?{siblingEtags:b.siblingEtags}:{}}),{type:d,id:E,saved:!0,shipped:!1,publish:(a=b.publish)!==null&&a!==void 0?a:{kind:"notRequested"},...b.publish&&b.publish.kind!=="notRequested"?(()=>{var k;let P=(k=f.publishScope)===null||k===void 0?void 0:k.call(f,E,m);return P?{publishScope:P}:{}})():{},...R?{refreshed:!0}:{},...F.length>0?{warnings:F}:{}}}catch(b){let E=(0,ne.readPartialTokens)(b);if(E&&h){let C={...(o=h.memberEtags)!==null&&o!==void 0?o:{},...(s=E.memberEtags)!==null&&s!==void 0?s:{}},N={...(l=h.siblingEtags)!==null&&l!==void 0?l:{},...(u=E.siblingEtags)!==null&&u!==void 0?u:{}};await this.versions.storeMeta(d,p,{...h,...Object.keys(C).length>0?{memberEtags:C}:{},...Object.keys(N).length>0?{siblingEtags:N}:{}})}if(b instanceof ne.SdkError&&b.code===rr.ALREADY_EXISTS_CODE)return{type:d,id:p,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:b};if(b instanceof ne.SdkError&&b.code===NO.WFOM_API_UNAVAILABLE_CODE)return{type:d,id:p,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:b};if(b instanceof ne.SdkError&&b.code===NO.BUSINESS_RULE_LEFT_DEACTIVATED_CODE)return{type:d,id:p,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:b};if(b instanceof ne.SdkError&&b.code===wr.VERSION_CONFLICT_CODE)return{type:d,id:p,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:new ne.VersionConflictError(d,p,(c=h?.etag)!==null&&c!==void 0?c:null,null,b.message)};throw b}}assertLanguageMatches(t,r,n,i){if(i?.languageSensitive&&!(n?.languageCode===void 0||n.languageCode===this.languageCode))throw new ne.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!==pl.PROJECTION_VERSION)throw new ne.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 ${pl.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 ne.SdkError)||a.code!==wr.VERSION_CONFLICT_CODE?a:new ne.SdkError(rr.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:oa(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 ne.SdkError(rr.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:oa(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,Td.assignMissingIds)(r)}async resolveComponentType(t){switch(t.componentType){case wt.SolutionComponentType.SavedQuery:return"view";case wt.SolutionComponentType.SavedQueryVisualization:return"chart";case wt.SolutionComponentType.AppModule:return"app";case wt.SolutionComponentType.UxAgentProject:return"genPage";case wt.SolutionComponentType.Workflow:return t.workflowCategory===2?"businessRule":t.workflowCategory===4&&await this.isBusinessFlowWorkflow(t.objectId)?"bpf":void 0;case wt.SolutionComponentType.SystemForm:return await this.isDashboardForm(t.objectId)?"dashboard":"form";default:return}}async isDashboardForm(t){let n=`/systemforms(${(0,wi.normalizeGuid)(t,"formId")})${(0,wi.odataQuery)([["$select","type"]])}`,i=(0,wr.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,wi.normalizeGuid)(t,"workflowId")})${(0,wi.odataQuery)([["$select","businessprocesstype"]])}`,i=(0,wr.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 ne.NotImplementedError(r,`no adapter registered for artifact type '${t}'`);return n}};rr.MakerSdk=Rd;function WK(e){return new Rd(e)}rr.createMakerSdk=WK;function oa(e){return e instanceof Error?e:new Error(String(e))}function Bn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function _O(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function TO(e){e.length===0||!e.every(t=>Bn(t)&&typeof t.order=="number")||e.forEach((t,r)=>{t.order=r})}function jK(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=>Bn(i)&&i.id===t.before);return n<0?e.length:n}let r=e.findIndex(n=>Bn(n)&&n.id===t.after);return r<0?e.length:r+1}});var RO=y(Od=>{"use strict";Object.defineProperty(Od,"__esModule",{value:!0});Od.ARTIFACT_TYPES=void 0;Od.ARTIFACT_TYPES=["form","view","businessRule","app","command","chart","dashboard","genPage","bpf"]});var xO=y(OO=>{"use strict";Object.defineProperty(OO,"__esModule",{value:!0})});var LO=y(FO=>{"use strict";Object.defineProperty(FO,"__esModule",{value:!0})});var MO=y(kO=>{"use strict";Object.defineProperty(kO,"__esModule",{value:!0})});var UO=y(BO=>{"use strict";Object.defineProperty(BO,"__esModule",{value:!0})});var qO=y($O=>{"use strict";Object.defineProperty($O,"__esModule",{value:!0})});var GO=y(VO=>{"use strict";Object.defineProperty(VO,"__esModule",{value:!0})});var WO=y(zO=>{"use strict";Object.defineProperty(zO,"__esModule",{value:!0})});var HO=y(jO=>{"use strict";Object.defineProperty(jO,"__esModule",{value:!0})});var JO=y(KO=>{"use strict";Object.defineProperty(KO,"__esModule",{value:!0})});var XO=y(QO=>{"use strict";Object.defineProperty(QO,"__esModule",{value:!0})});var ZO=y(YO=>{"use strict";Object.defineProperty(YO,"__esModule",{value:!0})});var t1=y(e1=>{"use strict";Object.defineProperty(e1,"__esModule",{value:!0})});var n1=y(r1=>{"use strict";Object.defineProperty(r1,"__esModule",{value:!0})});var a1=y(i1=>{"use strict";Object.defineProperty(i1,"__esModule",{value:!0})});var s1=y(o1=>{"use strict";Object.defineProperty(o1,"__esModule",{value:!0})});var u1=y(l1=>{"use strict";Object.defineProperty(l1,"__esModule",{value:!0})});var d1=y(c1=>{"use strict";Object.defineProperty(c1,"__esModule",{value:!0})});var f1=y(p1=>{"use strict";Object.defineProperty(p1,"__esModule",{value:!0})});var h1=y(m1=>{"use strict";Object.defineProperty(m1,"__esModule",{value:!0})});var v1=y(g1=>{"use strict";Object.defineProperty(g1,"__esModule",{value:!0})});var y1=y(ue=>{"use strict";var HK=ue&&ue.__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]})),Pe=ue&&ue.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&HK(t,e,r)};Object.defineProperty(ue,"__esModule",{value:!0});ue.createMakerSdk=void 0;var KK=PO();Object.defineProperty(ue,"createMakerSdk",{enumerable:!0,get:function(){return KK.createMakerSdk}});Pe(RO(),ue);Pe(xO(),ue);Pe(LO(),ue);Pe(MO(),ue);Pe(UO(),ue);Pe(qO(),ue);Pe(GO(),ue);Pe(WO(),ue);Pe(HO(),ue);Pe(JO(),ue);Pe(XO(),ue);Pe(ZO(),ue);Pe(t1(),ue);Pe(n1(),ue);Pe(mu(),ue);Pe(a1(),ue);Pe(s1(),ue);Pe(u1(),ue);Pe(d1(),ue);Pe(f1(),ue);Pe(h1(),ue);Pe(v1(),ue);Pe(te(),ue)});var o0=y(dn=>{"use strict";var JK=dn&&dn.__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]})),QK=dn&&dn.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),A1=dn&&dn.__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)&&JK(t,e,r);return QK(t,e),t};Object.defineProperty(dn,"__esModule",{value:!0});dn.NodeFileSystemStorage=void 0;var Je=A1(require("fs")),At=A1(require("path")),b1=te(),w1=ep();async function E1(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 E1(At.join(e,r));await Je.promises.rmdir(e)}var a0=class{constructor(t){this.root=t}getRoot(){return this.root}pathFor(t,r=!0){return this.assertWithinRoot(At.join(this.root,...t),r)}realPathThroughNearestAncestor(t){let r=t,n=[];for(;!Je.existsSync(r);){n.unshift(At.basename(r));let i=At.dirname(r);if(i===r)return At.resolve(t);r=i}return At.resolve(Je.realpathSync(r),...n)}assertWithinRoot(t,r){let n=At.resolve(this.root),i=At.resolve(t);if(i!==n&&!i.startsWith(n+At.sep))throw new b1.PathTraversalError(t,this.root);let a=this.realPathThroughNearestAncestor(n),o=r?this.realPathThroughNearestAncestor(i):At.resolve(this.realPathThroughNearestAncestor(At.dirname(i)),At.basename(i));if(o!==a&&!o.startsWith(a+At.sep))throw new b1.PathTraversalError(t,this.root);return i}async readText(t){let r=this.pathFor(t);if(!Je.existsSync(r))return null;try{return await(0,w1.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=At.dirname(n);await Je.promises.mkdir(i,{recursive:!0});let a=At.join(i,`.${At.basename(n)}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);try{await Je.promises.writeFile(a,r,"utf8"),await(0,w1.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 E1(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))}};dn.NodeFileSystemStorage=a0});var C1=y(Ht=>{"use strict";var XK=Ht&&Ht.__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]})),YK=Ht&&Ht.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),ZK=Ht&&Ht.__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)&&XK(t,e,r);return YK(t,e),t};Object.defineProperty(Ht,"__esModule",{value:!0});Ht.loadNodeTypeScript=Ht.createNodeWorkspaceStorage=Ht.NodeFileSystemStorage=void 0;var eJ=o0(),tJ=o0();Object.defineProperty(Ht,"NodeFileSystemStorage",{enumerable:!0,get:function(){return tJ.NodeFileSystemStorage}});function rJ(e){return new eJ.NodeFileSystemStorage(e)}Ht.createNodeWorkspaceStorage=rJ;async function nJ(){return await Promise.resolve().then(()=>ZK(require("typescript")))}Ht.loadNodeTypeScript=nJ});var Un={};module.exports=Mr(Un);qn(Un,ce(y1()),module.exports);qn(Un,ce(C1()),module.exports);
diff --git a/plugins/model-apps/scripts/verify-model-app.js b/plugins/model-apps/scripts/verify-model-app.js
index b5f03cb7a..9f777927c 100644
--- a/plugins/model-apps/scripts/verify-model-app.js
+++ b/plugins/model-apps/scripts/verify-model-app.js
@@ -11,9 +11,10 @@
const fs = require('node:fs');
const path = require('node:path');
const os = require('node:os');
-const { parseArgs, validateFlags, readJsonArg, emitResult } = require('./lib/dataverse-auth.js');
+const { parseArgs, validateFlags, readJsonArg, emitResult, dataverseOrigin } = require('./lib/dataverse-auth.js');
const { createAzHttpClient } = require('./lib/sdk-http-client.js');
const { verifySpec } = require('./lib/verify-spec.js');
+const { readBaseline } = require('./lib/deployed-baseline.js');
const { appUniqueName } = require('./lib/sdk-build.js');
const { validateAppSpec, migrateAppSpec } = require('./lib/app-spec.js');
const { odataLit } = require('./lib/odata.js');
@@ -176,6 +177,15 @@ function readerFor(sdk, appUnique, opts) {
const memoSitemap = () => (sitemapP || (sitemapP = _fetchSitemap(sdk, appUnique)));
// Memoized app TABLE components — one live read per verify run, keyed by the wanted-table set.
const appComponentsP = new Map();
+ // The user running verify, read once: servedMainForms asks the platform what THIS user is served. The id
+ // is interpolated into the function's `User` alias, so only a canonical GUID is accepted.
+ let callerIdP;
+ const callerId = () => (callerIdP || (callerIdP = (async () => {
+ const who = await sdk.dataverse.get('/WhoAmI');
+ const id = who && who.status >= 200 && who.status < 300 && who.body ? String(who.body.UserId || '').replace(/[{}]/g, '').toLowerCase() : '';
+ if (!/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(id)) throw new Error(`WhoAmI returned no user id (HTTP ${who && who.status})`);
+ return id;
+ })()));
// Per-id page code cache. Downloads by specific id on demand rather than pulling all pages at once
// (the old all-pages downloadP). Each id gets its own output dir to avoid directory collision.
@@ -270,6 +280,27 @@ function readerFor(sdk, appUnique, opts) {
const row = rows && rows[0];
return (row && row.formxml) || null;
},
+ // servedMainForms(entity): the Main forms the platform serves the user running verify for a table,
+ // first to last — the order a user without a remembered form opens them in (AB#6736948). The public
+ // RetrieveFilteredForms function is the platform's own answer to "which forms may this user open,
+ // in which order": it applies each form's security roles and <DisplayConditions Order>. It returns
+ // ids only, e.g.
+ // { "value": [ { "@odata.type": "#Microsoft.Dynamics.CRM.systemform", "formid": "<guid>" }, … ] }
+ // so the names come from one systemform read. Each entry is { id, name }. Errors propagate: verify
+ // reports an order it could not read as not verified.
+ // See: https://learn.microsoft.com/power-apps/developer/data-platform/webapi/reference/retrievefilteredforms
+ servedMainForms: async (entity) => {
+ const logical = String(entity).toLowerCase();
+ const userId = await callerId();
+ const res = await sdk.dataverse.get(`/systemforms/Microsoft.Dynamics.CRM.RetrieveFilteredForms(EntityLogicalName=@e,FormType=@t,User=@u)?@e='${odataLit(logical)}'&@t=2&@u={'@odata.id':'systemusers(${userId})'}`);
+ // `dataverse.get` RESOLVES on a non-2xx, so the status is checked explicitly.
+ if (!res || res.status < 200 || res.status >= 300) throw new Error(`RetrieveFilteredForms returned HTTP ${res && res.status}`);
+ const bare = (id) => String(id || '').replace(/[{}]/g, '').toLowerCase();
+ const ids = ((res.body && res.body.value) || []).map((r) => bare(r && r.formid)).filter(Boolean);
+ const rows = await sdk.queryRecords('systemform', { select: ['formid', 'name'], filter: `objecttypecode eq '${odataLit(logical)}' and type eq 2`, top: 250 });
+ const nameOf = new Map((rows || []).map((r) => [bare(r.formid), String(r.name || '')]));
+ return ids.map((id) => ({ id, name: nameOf.get(id) || id }));
+ },
// dashboardComponents(dashboardId): the deployed dashboard's tiles, parsed by the SDK's own
// dashboard deserializer — the path download already reads them through — so verify sees each
// tile's TargetEntityType / ViewId / VisualizationId exactly as a rebuild would, instead of
@@ -462,7 +493,10 @@ async function main() {
const httpClient = createAzHttpClient(env);
const sdk = await makeProvision(env, workspaceDir, httpClient);
const genpageCli = makeGenpageCli(env);
- const r = await verifySpec(spec, readerFor(sdk, appUniqueName(spec), { genpageCli, workspaceDir, isolatedReader: isolatedReaderFor(env, { httpClient }) }));
+ // The spec's baseline for this environment and app, when the workspace has one: an icon the build
+ // kept because it was changed in the designer since then is not a failure (AB#6726727).
+ const baselineSpec = readBaseline(workspaceDir, { environment: dataverseOrigin(env), appUniqueName: appUniqueName(spec) }) || undefined;
+ const r = await verifySpec(spec, readerFor(sdk, appUniqueName(spec), { genpageCli, workspaceDir, isolatedReader: isolatedReaderFor(env, { httpClient }) }), { baselineSpec });
// Show `detail` on a failing check. Without it a READ that failed (throttling, auth expiry, a 5xx)
// is indistinguishable from an artifact that is genuinely absent — verifySpec records the cause
// but the operator saw only "✗ view: Active Orders" and would chase a phantom deployment drift.
diff --git a/plugins/model-apps/skills/app-builder/SKILL.md b/plugins/model-apps/skills/app-builder/SKILL.md
index 54cc4a762..b78bc82d3 100644
--- a/plugins/model-apps/skills/app-builder/SKILL.md
+++ b/plugins/model-apps/skills/app-builder/SKILL.md
@@ -399,8 +399,8 @@ The App Spec field `languageCode` pins the same value across runs. It now covers
data-model labels, and form, dashboard and sitemap labels — the SDK serializers that used to hardcode
1033 take the authoring language as an option.
-Narrate progress as it runs. Transient env errors (429 customization-lock, 503 SQL-timeout,
-concurrent-op guards) are **auto-retried** with backoff on `--apply` (the build is idempotent, so a
+Narrate progress as it runs. Transient env errors (429 customization-lock, 503 SQL-timeout, a SQL
+deadlock, concurrent-op guards) are **auto-retried** with backoff on `--apply` (the build is idempotent, so a
retry reuses what's already created). If the build still **halts** (`BuildHalt`) on an
unrecoverable error, surface it and ask the user how to proceed via `AskUserQuestion` (adjust the
spec / cancel), then re-run. Everything is scoped to a dedicated unmanaged solution; **`--publish`
@@ -509,7 +509,8 @@ Never fails.
**App-level features** (`ai.appFeatures`) — `formFill` (Copilot-assisted form fill), `nlSearch`
(natural-language grid/view search), `nlChart` (NL chart / AI data visualization), `m365` (M365
-Copilot). All default to `true` except `m365`; set any to `false` to opt out.
+Copilot). All default to on except `m365`, which is left at its platform default; `false` writes an
+explicit Off for this app (each setting's values: `references/app-spec-schema.md` → `ai`).
**Per-table row summaries** (`ai.summaries`):
- `default: "auto"` — the skill auto-selects good-candidate tables (skips lookup-only / config /
@@ -659,7 +660,9 @@ child view id. Each step emits `[n/total]`.
(`forms[].quickViews[]`); **per-form security roles** (`forms[].securityRoles` — name the
`personas[]` this form is offered to, or `everyone: true`; applied after the roles exist. A form
with no assignment is visible to **every** role, so this **restricts** a form rather than granting
- it); Choice-column charts; **business rules** (`businessRules[]` — authored as the modern workflow
+ it); **which form a table opens with** (`forms[].isDefault` / `entities[].mainFormOrder` set the
+ table's Main Form Set order, on existing tables too — a user's remembered form still opens first for
+ that user; see app-spec-schema.md); Choice-column charts; **business rules** (`businessRules[]` — authored as the modern workflow
object model and activated; see the environment gate above); **security roles** (`personas[]` — one role per
persona sized from its jobs-to-be-done, with app access so the app opens for non-admins);
**dashboards** (`dashboards[]` — chart/list/iframe/webresource tiles) + **dashboard sitemap