A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
model-apps 2.7.0: close the [AgenticMDA] bug batch — roleGrants[], localized labels, download reporting, auth preflight (#548)
Akshay Maloo8a36dab92613
diff --git a/plugins/model-apps/.claude-plugin/plugin.json b/plugins/model-apps/.claude-plugin/plugin.jsonindex 2f15afb45..747450d4e 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.6.1",+ "version": "2.7.0","description": "Build model-driven Power Apps end to end: /app-builder authors whole apps (tables, relationships, forms, views, charts, security roles, app + sitemap) from a natural-language intent, and /genpage builds generative pages with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI > 2.10.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.","author": {"name": "Microsoft",diff --git a/plugins/model-apps/.plugin/plugin.json b/plugins/model-apps/.plugin/plugin.jsonindex 2f15afb45..747450d4e 100644--- a/plugins/model-apps/.plugin/plugin.json+++ b/plugins/model-apps/.plugin/plugin.json@@ -1,6 +1,6 @@{"name": "model-apps",- "version": "2.6.1",+ "version": "2.7.0","description": "Build model-driven Power Apps end to end: /app-builder authors whole apps (tables, relationships, forms, views, charts, security roles, app + sitemap) from a natural-language intent, and /genpage builds generative pages with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI > 2.10.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.","author": {"name": "Microsoft",diff --git a/plugins/model-apps/AGENTS.md b/plugins/model-apps/AGENTS.mdindex 7fdb8f72a..104b220ac 100644--- a/plugins/model-apps/AGENTS.md+++ b/plugins/model-apps/AGENTS.md@@ -52,6 +52,21 @@ able to tell what moved from the docs alone):Don't duplicate content across these — **cross-link instead** (a second copy only drifts, as the filetree and teardown order both did before).+**Issue references belong in history and in code, never in use-the-plugin reference material.**+`references/*.md` and `skills/*/SKILL.md` are loaded verbatim into an agent's context so it can+*author a spec*. A tracker link there costs tokens, cannot be dereferenced by the reader it is shown+to, and goes stale while the doc lives on — so state the rule and the **why**, and stop. The test is+simple: if deleting the link loses nothing operational, it was provenance, not explanation.++Provenance is welcome in the *other* class of doc — the material that explains **why the code is the+way it is** rather than how to use it: this file, `CHANGELOG.md`, and code comments, where the+repo-root `AGENTS.md` actively asks for one. Its reader is a contributor who can open the link and+act on it. Prefer the bare id (`AB#6686428`, `#537`) over a full URL even there: it carries the same+provenance, costs less, and cannot rot.++A corollary for **error messages**: an error must stand alone. `operator 'X' is not usable — see+<issue url>` sends an author to a tracker to find out what they did wrong; say what is wrong instead.+**This repo is public.** Before adding to any of these docs, re-read the repo-root `AGENTS.md` →*"This Repo Is PUBLIC"*. The docs here have already had to be scrubbed once for internal repo paths,a real Dataverse environment name, review provenance, and indexes into documents an outside reader@@ -118,9 +133,16 @@ the pipeline and delegates each script's **behavioral spec** to the entries beloconverges only Active/Draft **state**, never stage structure — and `bpfFilter` scopes every query inbuild/verify/teardown to the DEFINITION row, excluding both the platform's activated `type 2` copy andsame-named TASK flows (also category 4). v1 is deliberately single-entity and linear: cross-entity- stages, branching, stage actions and `securityRoles` are **rejected at the spec gate** rather than- silently dropped, because the build cannot yet verify them (a BPF's role grants are privileges on the- backing table that ACTIVATION creates, so they belong to the `security` phase). The rejection is an+ stages, branching and stage actions are **rejected at the spec gate** rather than silently dropped,+ because the build cannot yet verify them. `securityRoles` was rejected alongside them and is now+ **supported** (`{ "personas": [...] }`): a BPF's role grants are `create/read/write/delete` privileges+ on the backing table that ACTIVATION creates, so they are applied in the **`security` phase**, after+ both the flow and the personas' roles exist — persona lookup there is **case-insensitive**, since a+ persona is a display name the author repeats by hand across two sections of the spec, and the target+ table is the flow's **deployed `uniquename` read back** from the workflow row rather than derived+ from its display name (a flow authored in Maker, or renamed later, keeps an unrelated unique name). There is no+ `everyone`/`fallbackForm`/`order`: those are `forms[].securityRoles` concepts written into formxml,+ and a privilege has no such equivalent. The rejection is an**allow-list at flow, stage AND step level**, because the SDK's normalizers copy a fixed key set anddiscard the rest — so a `branch` written on a stage (where the SDK actually models it), or the veryplausible `fieldLogicalName` instead of `field` on a step, would otherwise validate clean and deploy@@ -171,7 +193,7 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo`--language-code` → App Spec `languageCode` → the org's base language → 1033. Without this, an orgthat has not provisioned 1033 fails the data-model phase with `The language code 1033 is not a validlanguage for this organization`- ([#447](https://github.com/microsoft/power-platform-skills/issues/447)) — and confusingly only on+ (#447) — and confusingly only on*some* column types, because (observed 2026-08) Dataverse tolerates an unprovisioned LCID on`EntityMetadata` and `PicklistAttributeMetadata` but rejects it on `DateTime`/`Memo`. Every fallbackto 1033 warns, as does an explicitly supplied LCID that had to be discarded.@@ -189,7 +211,7 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo**Scope — this now extends to the `forms`, `dashboards` and `app-shell` phases too.** Those gothrough the vendored SDK's artifact serializers, which used to hardcode `1033` into FormXML(`<label languagecode="1033">`), SiteMap XML (`<Title LCID="1033">`) and dashboard XML with **no- caller override** ([#455](https://github.com/microsoft/power-platform-skills/issues/455)). The SDK+ caller override** (#455). The SDKnow takes the authoring LCID as a **construction-time** option (`MakerSdkOptions.languageCode`),which is why `main()` resolves the language over the transport hatch (`resolveAuthoringLanguage`,`scripts/lib/entity-provision.js`) **before** calling `makeSdk`, and passes the identical value on@@ -203,13 +225,29 @@ the pipeline and delegates each script's **behavioral spec** to the entries belomulti-language labelling is blocked a layer lower anyway, since the SDK's label serializer emits aone-element `LocalizedLabels` array by design. `entities[].languageCode` and`entities[].localizedLabels` are therefore **rejected by validation**- ([#537](https://github.com/microsoft/power-platform-skills/issues/537)) rather than accepted and+ (#537) rather than accepted anddropped: `entities[]` had no allow-list, so both validated clean and were silently ignored, and anauthor asking for one table in a second language got a successful build with the request gone. Anyunknown table key now fails the same way (see `ENTITY_KEYS`, `scripts/lib/app-spec.js`). Note that`references/localization.md` is about generated **page** code, not Dataverse labels.Note the SDK deliberately does **not** language-parameterize BusinessRule: its mapper's languageparameter is the *environment base* language, a different concept.+ **`languageCode` is the language for a PLAIN label, not the only language available.** An+ author-facing name (`entities[].displayName`/`pluralName`, `primaryAttribute.displayName`,+ `columns[].displayName`, `alternateKeys[].displayName`, `relationships[].lookup.displayName`,+ and an **inline** Choice option on `columns[].options[]`) may instead be a **map keyed by LCID**,+ which the SDK's label serializer turns into a multi-entry `LocalizedLabels` array+ (AB#6686428 / #537). ⚠ **`globalChoices[]` is the exception and is REJECTED, not supported** —+ neither its `displayName` nor its `options[]` may be localized, because Dataverse accepts the+ multi-language payload for a global option set and stores only the base language (measured, even+ through a raw `POST` that bypasses the SDK). Listing it here as localizable sent authors into a+ validation error; use an inline Choice on the column when option labels must be localized. The plugin+ passes a supported value through **unflattened** — flattening it here would silently restore the+ English-only behaviour while validation and the design doc still claimed two languages. Everything+ that RENDERS or DERIVES FROM a label must go through `labelText()` (never string-interpolate a+ label), and anything that resolves an author's reference BY label text must go through+ `labelAliases()` so a reference written in any provisioned language matches. Both live in+ `app-spec.js`; `references/localization.md` is about generated **page** code, a separate concern.Guarded by `scripts/tests/lcid-real-bundle.test.js`, which drives the REAL vendored bundle — a mockwould keep passing against a bundle that ignored the option.`--verify` (opt-in) auto-runs the read-only reconcile after a successful apply and exits non-zero on a silent partial build (the same@@ -296,9 +334,20 @@ the pipeline and delegates each script's **behavioral spec** to the entries beloround-trip.** (View hydration was tried and reverted — LIVE-verified that the deployed savedquery setcan't reliably tell app-builder-authored views from Dataverse's auto-generated Active/Inactive/QuickFindsystem views: `isdefault` is TRUE on the authored primary view and FALSE on the system Inactive view, so- no filter isolates author views. Forms/charts/commands need structured reads the SDK doesn't expose.)- All four 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.+ no filter isolates author views. Charts/commands need structured reads the SDK doesn't expose. FORMS are+ a deliberate refusal rather than a missing capability: the SDK does expose `formTypes` on its form+ listing, but the App Spec form shape cannot express everything a deployed `formxml` carries — header/+ footer, business-process control, related-entity nav, control parameters, event libraries — and a LOSSY+ form declared in the spec is *worse* than an absent one, because a rebuild into a fresh environment+ recreates it having silently lost those controls while reporting success.)+ All four survive on the live app (a rebuild into the SAME environment preserves them), but are absent+ from the downloaded spec, so edit them in Maker or a fresh spec.+ **The omission is reported, not silent** (AB#6686423): every deployed form/view/chart is listed in the+ spec's `descriptionInventory`, and each run prints a note naming the counts, the tables and the+ artifacts, plus a `notRoundTripped` block on the JSON result. It is a NOTE, never a gate — every app+ has forms and views, so failing the download would break every download, and the omission is not+ destructive in the environment the app came from. Do not "fix" this by reconstructing `forms[]`+ without also solving the lossy-layout problem above.**Entities are the sitemap's tables UNIONED with the entities owned by the app's VIEW / CHART /FORM components** (`appComponentEntities`) — a maker-built app can include tables reachable only viaa lookup/sub-grid/related view, with no sitemap entry of their own, and reconstructing from the@@ -401,24 +450,35 @@ the pipeline and delegates each script's **behavioral spec** to the entries belohalf-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`notPersisted` on first apply). `applied` is the ONLY success bucket; a feature otherwise lands in- `skipped` (org gate off), `notPersisted` (no override observed for the whole retry budget — Dataverse- can accept an app-scope `SaveSettingValue` with HTTP 204 and store nothing), `unverified` (the write+ `notPersisted` (no override observed for the whole retry budget — Dataverse+ can accept an app-scope `SaveSettingValue` with HTTP 204 and store nothing), `skipped` (the same+ absence, PLUS the feature's org readiness gate reads off, which is offered as the explanation),+ `unverified` (the writewas issued but the proof could not be read) or `failed` (the write threw; the rest of the batch still- reports). The build surfaces **every** non-success bucket as a `⊘` warning plus in the phase detail+ reports). **A gate is never a PRECONDITION** (AB#6688904): the SDK attempts every write and reads a+ gate only afterwards, to explain an absence that actually happened. It used to read the gate first,+ and for four of the seven features that "gate" IS the per-app setting the write is about to set — so+ on a new app its platform-default `0` looked like an admin refusal and the build shipped an app with+ no AI features while reporting success. The build surfaces **every** non-success bucket as a `⊘` warning plus in the phase detail— buckets are read off the result object, so one a future SDK adds is reported verbatim rather thansilently dropped — and `--verify` fails on any of them. **An app-scope setting WRITE is a no-op untilthe app is published** (live-measured: the write reports `notPersisted` and `appsettings` holds no rowat all, while publishing and re-issuing the same call applies every feature). This is not read lag, sore-*proving* after publish cannot fix it — the build **re-issues** the write after publish for anything- the first attempt did not apply. Verification proves the override ROW, keyed by `appmoduleid`, so the+ the first attempt did not apply, `skipped` INCLUDED. On a fresh app nothing persists pre-publish, so+ the gate diagnosis fires for every feature that has one; abandoning those would leave `--verify`+ failing on a row the build declined to write a second time, and a reported customer environment ran a+ working app at `NLGridSearchSetting = 2` with `EnableNLGridSearch` off. Anything still `skipped` after+ the re-issue is reported as an admin action. Verification proves the override ROW, keyed by `appmoduleid`, so thebuild passes the id it already holds rather than have the SDK resolve it by name (an unpublishedappmodule is not readable). See the `ai-features` phase in `scripts/lib/sdk-build.js` for the fullsequence and its bounds.The flag set is resolved ONCE by `scripts/lib/ai-app-settings.js` and shared by the build and theverifier: a spec with an `ai` block but no `ai.appFeatures` still gets defaults written, soreconciling only the DECLARED features left them applied-but-unverified.- All AI features are **admin-gated**: the skill preflights- and skips/warns; it cannot flip admin or tenant switches. `scripts/lib/ai-candidates.js` selects+ All AI features need an environment admin to have enabled them: the skill preflights+ and warns; it cannot flip admin or tenant switches. What it does NOT do is decline to write on the+ strength of that preflight — see the bucket note above. `scripts/lib/ai-candidates.js` selectsgood-candidate tables for auto row-summary mode; `scripts/lib/ai-prompt.js` generates tailored summaryprompts. The `ai` block in the App Spec configures the full set; see[`references/app-spec-schema.md`](references/app-spec-schema.md) → `## ai`.@@ -539,6 +599,7 @@ scripts/spec-shape.js ← shared structural normalization for both authoring gatessurface-resolver.js ← pure: resolve personas[].jobs[].surfaces[] to the spec artifacts that satisfy themrole-privileges.js ← pure: declared persona privileges + subset comparison against a deployed role+ (also the oracle for `roleGrants[]`, which is additive rather than converged)odata.js ← OData literal escaping helpersgenpage-cli.js ← pac model genpage upload/list/download wrapperhydrate-spec.js ← reconstruct an App Spec from a deployed app (edit flow)@@ -816,17 +877,18 @@ Dataverse simply are not in it.| Hatch | Use for | Examples in tree ||---|---|---|| `dataverseRequest()` in `lib/dataverse-auth.js` (and the `dataverse-request.js` CLI) | Dataverse surfaces the SDK does not model at all | `WhoAmI` (`check-auth.js`), `customapis` (`list-custom-apis.js`), `connectionreferences` (`create-connection-reference.js`), solution-component adds (`add-page-to-solution.js`) |-| The raw `httpClient` from `createAzHttpClient` | A surface the SDK *does* touch but whose response it **projects away** | `entityPrivileges` in `verify-model-app.js` — `fetchEntityMetadata` returns `{logicalName, displayName, entitySetName, attributes, relationships}` and drops `Privileges` entirely. The projection's omission is permanent (it is disk-cached and best-effort, the wrong contract for a security read) and pinned by an SDK guardrail test. **Transitional:** the SDK is gaining a dedicated `getEntityPrivileges()`; switch to it and drop this raw read once the vendored bundle carries it |+| The raw `httpClient` from `createAzHttpClient` | A surface the SDK *does* touch but whose response it **projects away** | **No caller today.** The one that existed — `entityPrivileges` in `verify-model-app.js` — is gone: the SDK had no privilege READ at all, and `fetchEntityMetadata` drops `Privileges` permanently by design, so the check composed its own `EntityDefinitions(...)?$select=Privileges` request. The vendored bundle now carries `getEntityPrivileges`, and the reader takes it. The hatch stays documented because the *category* recurs; opening it again needs the same justification |**Prefer `dataverseRequest()` over the raw client.** It already handles the API path, auth, headersand timeouts. Reach for `httpClient` only when you must share the exact client instance the SDK is-using, as the verify reader does.+using — and check first that the SDK has not since grown the method, as it did for entity privileges.When you do go direct, all four of these apply:1. **Comment WHY the SDK cannot serve it** — name the SDK method you would otherwise call and what itdrops or lacks. "Deliberately not `sdk.fetchEntityMetadata`" is the difference between a- documented exception and something a later reader "simplifies" back into a silent bug.+ documented exception and something a later reader "simplifies" back into a silent bug. Say what+ would retire the hatch, so the note is actionable rather than permanent.2. **Absolute URL including `/api/data/v9.2`** when using the raw `httpClient`. It is the transportthe SDK drives, so it takes full request URLs and validates them with `new URL(url)` for itssame-origin guard — a relative path throws there rather than resolving against the org.@@ -835,7 +897,9 @@ When you do go direct, all four of these apply:4. **Test the reader itself, not only an injected stub.** The `entityPrivileges` URL bug shippedbecause every test injected a fake reader into `verifySpec`, so the real one was never executed —and `verify-spec` catches per-entity read failures, so it would have failed silently on every live- run rather than crashing. Drive at least one test through the real client's request seam.+ run rather than crashing. Drive at least one test through the real seam: the client's request path+ for a raw read, or the **real vendored bundle** for one that goes through the SDK. A hand-written+ SDK stub proves only that the mapping is self-consistent with itself.- Keep SKILL.md under 500 lines@@ -906,6 +970,14 @@ Second, "built from master" is not provenance, because master moves; the SHA isreviewer reproduce the artifact. Re-running the build on the same inputs must reproduce the samesha256 — check it.+⚠ **`subject` is the subject of the commit the bundle was BUILT FROM — normally master's HEAD — and+is usually unrelated to the change you are taking up.** It is recorded verbatim from git on purpose+(`sanitize-subject.js` only strips merge-tool prefixes), because editorialising it would break the+one thing provenance is for. So expect it to read like `Revert 'fix: scheduled trigger skips its+first run…'` while the uptake is about AI settings: master simply moved on after the commit that+carried the fix. Do not "correct" it, and do not read it as a description of the uptake — name the+change in `CHANGELOG.md` instead, which is where a reader looks for what actually arrived.+`scripts/tests/sdk-surface-contract.test.js` — the **method-presence** guard. Asserts every SDKmethod the engines call (`SKILL_SDK_SURFACE`, kept in sync with the `provision.*` / `sdk.*` callsites by a source-scan test that also covers `artifact-intent.js`) is a function on the real vendoreddiff --git a/plugins/model-apps/CHANGELOG.md b/plugins/model-apps/CHANGELOG.mdindex db6a0306e..d7c5c8d7c 100644--- a/plugins/model-apps/CHANGELOG.md+++ b/plugins/model-apps/CHANGELOG.md@@ -1,535 +1,532 @@-# Changelog--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.6.1--### Fixed--- **A table key the build cannot honour now fails instead of being dropped** ([#537]). `entities[]`- was the one authorable block with no allow-list, so `entities[].languageCode` and- `entities[].localizedLabels` — the two natural ways to ask for a per-table or multi-language- label — validated clean and were then silently ignored. Asking for one table in Spanish produced a- successful build with the request gone and nothing reporting the loss. Unknown table keys (a- misspelled `pluralname`, too) are now rejected, and the error names what to write instead: the- authoring language is **build-wide**, set by the spec-level `languageCode`. Multi-language labels- remain unsupported — the SDK's serializer emits one label per name by design. The same check runs- on the `/genpage` provisioning input, which is the other entry point that accepts tables; it still- accepts every App Spec table key, so entities copied from an `app-spec.json` keep validating.-- **The `languageCode` error now says what to write.** It named the mistake but not the fix; it now- gives a concrete LCID (`1033`) and rejects a language tag explicitly. A tag is deliberately not- accepted as an alias: `es-ES` is 3082 or 1034 depending on sort order, and guessing wrong would- not fail — it would build every label in the wrong language.-- **A non-string `entities[].schemaName` is an error, not a crash.** The check only tested- truthiness, so `"schemaName": 42` (or `{}`, `[]`, `true`) passed it and the next line called- `.toLowerCase()` on the value — `validateAppSpec` threw a raw `TypeError` and the caller lost- every problem found so far, not just that one. Found while reproducing the review comment on the- message above; pre-existing rather than introduced here, but on the same line and the same class- of "a validator must return problems, not throw them".--[#537]: https://github.com/microsoft/power-platform-skills/issues/537--## [2.6.0]--Business process flows, plus an SDK uptake that changes how business rules fail on an environment-that cannot host them.--### Added--- **`businessProcessFlows[]` — guided, staged processes on a table.** Ordered stages with steps bound- to that table's columns, activated on create (an inactive flow is invisible, not merely inert).- Every step must bind a `field`; the platform refuses one without. v1 is single-entity and linear —- branching, stage actions and role grants ([#513]) are rejected rather than silently dropped.--### Changed--- **A business rule is validated before it is written.** A rule the SDK's compiler cannot understand- used to deploy as an empty rule that never fires. The build now runs the designer's own- completeness validator first and fails with its findings. No rule this spec surface can author is- affected — the whole operator/action/scope matrix was measured clean.--### Fixed--- **A build no longer halts on an environment that cannot host business rules.** The SDK now reports- the preview gate as a returned no-op instead of a thrown error; the build read that as a version- conflict and stopped. Such rules are skipped with a warning again, as documented — which matters- because those environments are the common case.-- **A failed push reports the SDK's own reason.** Any push failure the build had no specific remedy- for was reported as *"the artifact changed in Maker"*, sending you to re-download an app nobody had- touched.-- **Download round-trips `app.newLook` and `app.headerNavigationRefresh`** ([#514]). A downloaded spec- carried neither, so rebuilding it into another environment produced a classic-shell app and nothing- reported the loss.-- **`views[].columns` rejects a non-string entry** ([#525]). An object was accepted by validation and- written into the view's fetchxml as `[object object]`; the build then failed at the platform and- left behind a view row that could not be read or deleted, so every later build failed the same way.-- **A business process flow whose derived unique name is already taken is refused up front.** That- name is a *table* name — activation creates a backing table from it — and the derivation ignores- both the table and your publisher prefix, so a flow named after its own table collided silently and- failed late, mid-build. Now rejected at the plan gate against declared tables, and at build time- against any flow or table already in the environment.-- **A reused business rule rejoins its solution on every build.** Solution membership was reconciled- only on the create path, so a rule that already existed — because an earlier component add failed,- or because it came from a different solution — stayed outside the solution permanently and never- travelled on export/import, with nothing saying so.-- **A push that fails with the SDK's `VERSION_CONFLICT` still tells you to re-download.** Reporting- unrecognised SDK codes verbatim had dropped that remedy from a real 412.-- **A table reference that is not a string is rejected instead of being coerced.** `charts[].entity`,- a subgrid's `childEntity`, a sitemap subarea's `entity` and a dashboard tile's `entity` were- stringified before the check, so a nested array passed validation and then crashed the build with a- raw `TypeError`.--[#513]: https://github.com/microsoft/power-platform-skills/issues/513-[#514]: https://github.com/microsoft/power-platform-skills/issues/514-[#525]: https://github.com/microsoft/power-platform-skills/issues/525--## [2.5.1]--SDK uptake. Adds per-form security roles and three column capabilities; **business rules now require-an environment that supports them**.--### Changed--- **Business rules are environment-gated.** The SDK writes a rule only through the bound- `CreateProcessWithWfomJson` member, and an environment that does not declare it **cannot host- business rules at all** — the common case, not an edge case. Such rules are skipped with a warning;- everything else builds, and `--verify` reports them as *not applicable on this environment*.--### Added--- **Generated pages can report to the customer's Application Insights** — behind the new- default-OFF `custom-telemetry` feature flag. When enabled, `genpage-page-builder` may- instrument a page through an optional `props.appInsights` surface (`trackEvent`,- `trackMetric`, `trackTrace`, `trackException`, `trackDependency`, `startTrack` /- `stopTrack`), with built-in call-site throttling for rapid-fire handlers.-- The flag is permission, not instruction. Even with it on, a page is instrumented **only**- when the maker asked to measure, track, monitor, or diagnose something in their own words —- the default output is still a page with zero telemetry, so nothing changes for existing- prompts. `/genpage` re-probes the flag at Phase 4.7 and passes the verbatim result as- `Telemetry: enabled|disabled` into every page-builder dispatch, the same contract- `Connectors:` already uses; the dispatch value wins over anything else.-- The contract — when to instrument, the API, naming and privacy rules, known-good shapes and- anti-patterns — lives in `references/page-telemetry.md`, read only when both gates pass.- It ships OFF pending the host runtime, authoring control, agent prompt and ECS setting- reaching PROD. Not to be confused with the plugin's own usage telemetry- (`/model-apps:telemetry`), which is unrelated and unchanged.-- **Per-form security roles** — `forms[].securityRoles`: offer a form to named `personas[]` or to- `everyone`. A form with no assignment is visible to **every** role, so this *restricts* a form; undo- with `everyone: true`, not by deleting the block. Takes effect after a publish. (AB#6648526)-- **Boolean `defaultValue`, whole-number `integerFormat`, and per-column `isValidForCreate` /- `isValidForUpdate` / `isValidForRead`** — the last is how you make a column read-only.- ([#495], AB#6648523, AB#6648522, AB#6651276)-- **Twelve more business-rule operators** and **multi-condition rules** (ANDed). Spelling matters:- `IsGreaterThan`, not `GreaterThan` — the SDK silently resolves an unknown operator to `Equals`, so- the spec rejects anything outside its table.-- **A `description` on every artifact that accepts one**, written at create time and omitted when- absent, so a rebuild never blanks text typed in the maker.-- **Per-field form control** — `readOnly`, `hidden` and `after`, via a form-level `fieldOptions` map- or inline on an explicit layout. `prune: false` edits part of a form without re-declaring it.-- **The AI form-fill family is controllable per capability** — assist toolbar, edit-form predictions,- smart paste and file upload, instead of one flag that only governed the toolbar.--### Fixed--- **A `businessRules[]`-only edit is no longer treated as "nothing changed."** The diff driving- `--changed-only` had no entry for that phase, so the run did nothing at all. ([#478] fixed- alongside: the SDK could not deserialize a dashboard it had serialized, so downloads lost tiles.)-- **Descriptions converge on existing views and charts** — previously written only at create, so the- auto-created *"Active <Plural>"* view never got one. ([#496])-- **Downloaded specs preserve deployed descriptions**, listing the rest in a read-only inventory. ([#494])-- **Teardown removes the activated copy of a business rule**, previously stranding an undeletable- row ([#493]), and clears column visualizations for a table the spec keeps (`existing: true`).-- **Existing columns honour an explicit `required` change on rebuild**; an omitted one still leaves- the live column alone.-- **Big Integer columns are no longer auto-placed on forms** — they have no Unified Interface control- and rendered *"Error loading control"* on every record.-- **AI on/off is read with the platform's semantics** — `0` = platform default, `1` = disabled,- `2` = enabled. Treating any non-zero value as "on" reported a disabled feature as enabled.-- **Presence operators** (`ContainsData` / `DoesNotContainData`) deploy; the compiler bug behind the- `HTTP 500 — Error generating UiData` failures went with the compiler. ([#481])-- **The async-surface guard is AST-based** — a regex could not decide the remaining cases. ([#475])-- **`ai.summaries.default: "off"` no longer discards a per-table `enabled: true`**, and a- differently-cased `tables[]` key keeps its `instruction` and `columns`.-- **A row summary an environment cannot license is skipped, not fatal** — and the model row the- refused publish leaves behind is swept, so a rebuild does not fail on a duplicate key.-- **A spec with no `appShell` reports what to add** instead of dying with- `Cannot read properties of undefined (reading 'areas')` after the app was half-created.-- **A malformed `businessRules` is a validation error**, not a raw `TypeError`; duplicate-cleanup- warnings report the real failure instead of asserting a wedged platform row.--[#475]: https://github.com/microsoft/power-platform-skills/issues/475+# Changelog++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.7.0++Multi-language Dataverse labels, granting access on roles this spec does not own, and the+app-builder defects found while rebuilding a real app into a second environment.++### Added++- **Localized Dataverse metadata labels** (AB#6686428, [#537]). Any author-facing name — a table's+ `displayName`/`pluralName`, its primary column's, a column's, a lookup's, an alternate key's, an+ inline Choice option's — may be a map keyed by LCID instead of a string:++ ```jsonc+ "displayName": { "1033": "Project Baseline", "3082": "Línea base del proyecto" }+ ```++ A single-language label stays a plain string, so no existing spec changes shape. Three rules:+ `globalChoices[]` is **rejected** (Dataverse stores only the base language there — use an inline+ Choice on the column); a language **tag** (`"es-ES"`) is rejected rather than guessed; and a+ localized `displayName` requires an explicit `pluralName`, because appending `"s"` is not a plural+ rule outside English. An LCID the organization has not provisioned halts the build.+ See `references/app-spec-schema.md` → *Localized labels*.+- **`roleGrants[]` — extend a security role you did not author** (AB#6686429). Adds privileges to a+ role that already exists, typically the ones an existing solution ships; `personas[]` remains the+ surface for roles the spec owns. **Additive and one-way**: dropping the entry does not revoke, and+ teardown never removes one. An unknown, ambiguous or stale role halts the build rather than+ skipping, because granting on the wrong role is a silent access defect.+- **`businessProcessFlows[].securityRoles` — who may run a flow** ([#513]). Same persona idiom as+ `forms[].securityRoles`. The grant lands on the flow's activation-created backing table, so there+ is no `scope` to author, and `securityRoles` on a **Draft** flow is rejected — the table does not+ exist until activation.++### Fixed++- **AI features are written even when an org readiness gate reads off** (AB#6688904). The gate was a+ precondition, and for four of the seven features that "gate" is the per-app row the write is about+ to set — so a new app looked forbidden and the build reported success having written nothing. Every+ write is now attempted and verified, a gate is read only to explain an absence, and the write is+ re-issued after publish (no app-scope write persists before that).+- **Localized labels were silently discarded on the real build path.** A broad metadata read issued+ immediately before a create makes Dataverse keep only the base-language label, and the request body+ is identical either way, so nothing reported the loss. The three create paths now use narrow reads.+ The column path is the one reached when adding a column to an existing table.+- **A requested row summary that was never created now FAILS verification** (AB#6689110). Build,+ verify and teardown share one selector and one AI opt-in test, so what is verified is exactly what+ was asked for, and a spec with no `ai` block is not checked for summaries at all.+- **Teardown removes a row summary the build created by default.** It planned that removal only for+ an explicit `ai.summaries` block, so for a spec carrying only `ai.appFeatures` the orphaned AI model+ blocked the table delete — teardown finished *with errors* and left the table and its data behind.+- **An SVG in a sitemap subarea's legacy `icon` is flagged** (AB#6688906), naming the `vectorIcon`+ replacement; a raster `icon` beside a vector one stays legal as a deliberate fallback. A sitemap+ attribute you remove from the spec is now removed from the deployed sitemap instead of surviving.+- **A workspace-metadata race no longer halts a multi-form build** (AB#6688905). Wiring form events+ could start before the SDK had persisted that form's metadata file, failing with a bare `UNKNOWN`.+ The read is retried; a persistent failure says it is a local race and that a re-run clears it.+- **`appendTo` no longer reports a false verification failure** — the access token was matched+ case-sensitively against a lower-cased lookup, so a correctly granted role reported it as missing.+- **A download says what it did not bring back** (AB#6686423). `download-model-app` does not+ reconstruct `forms[]`, `views[]`, `charts[]`, `businessRules[]` or `globalChoices[]`, and a spec+ with `"forms": []` was indistinguishable from an app that has none. Runs now name the counts and+ artifacts and return a `notRoundTripped` block. It is a note, not a gate: the loss is real only+ when rebuilding into a *different* environment. Every inventory read that **fails** — a failed+ table-label read, an unreadable business-rule or global-choice list, or a component page that hit+ its cap — is reported as an UNKNOWN class rather than an empty one, so "we could not look" never+ reads as "the app has none".+- **An inactive row-summary model no longer verifies clean.** The AI model row is created before it+ is published, so an environment that does not license the capability leaves a committed but+ unusable row behind; matching on the name alone reported PASS for a summary nobody can run.+- **The Azure CLI identity is checked before any Dataverse read** (AB#6686427). A token from the+ wrong tenant surfaced as an *empty download* — every best-effort read swallowed its 401. A terminal+ 401 now names the identity, tenant and environment (AB#6686424); a re-`az login` is the only fix,+ because `az account get-access-token` is MSAL-cached.+- **Default-form promotion is deterministic** (AB#6686426) — building several Main forms in parallel+ could leave whichever finished last as the default. It now honours `forms[].isDefault`.+- **The complete form-id map is signposted** (AB#6686425): `created.formIds`, keyed+ `entity|type|name`. The ids were never lost — `created.forms` is a Main-form-only convenience map.+- **A download no longer emits a raw Dataverse Label object as a column name**; an unlabelled+ synthetic lookup column is omitted instead of failing the spec's own validation.++### Changed++- **SDK uptake `cds-maker-sdk 331b9f56`** — the platform halves of the bugs above: multi-language+ label serialization, `formTypes` on the form listing, the additive `addEntityPrivilegesToRole`,+ `setAppAiFeatures` no longer pre-empting a write, sitemap attribute removal, and retries around the+ workspace file pair.+- **Two label rules relaxed** after they were measured to break specs that build correctly: a blank+ plain-string label is accepted (every create site falls back to the schema name), and a duplicate+ **plain** option label is a warning. A blank entry inside a localized map, and a cross-language+ collision, still fail.+- **The role-privilege read moved onto the SDK's `getEntityPrivileges`**, retiring the last raw-HTTP+ escape hatch in the app-builder scripts. No behaviour change — an unreadable privilege set still+ fails the check closed.++### Known limitations++- **A single-language label loses its LCID on download.** A table labelled only in, say, 3082 comes+ back as a plain string, and a rebuild applies it at the target build's resolved language — correct+ in the same organization, wrong in one with a different base language. Pin `languageCode` in the+ spec before a cross-organization rebuild.++[#537]: https://github.com/microsoft/power-platform-skills/issues/537+[#513]: https://github.com/microsoft/power-platform-skills/issues/513++## [2.6.1]+### Fixed++- **A table key the build cannot honour now fails instead of being dropped** ([#537]).+ `entities[].languageCode` and `entities[].localizedLabels` validated clean and were then silently+ ignored, so asking for one table in Spanish produced a successful build with the request gone.+ Unknown table keys are now rejected and the error names what to write instead. (2.7.0 adds+ multi-language labels as an LCID map on the label field itself.)+- **The `languageCode` error says what to write** — a concrete LCID, and an explicit rejection of a+ language tag, which would otherwise build every label in the wrong language.+- **A non-string `entities[].schemaName` is an error, not a raw `TypeError`** that discarded every+ other problem found so far.++[#537]: https://github.com/microsoft/power-platform-skills/issues/537++## [2.6.0]++Business process flows, plus an SDK uptake that changes how business rules fail on an environment+that cannot host them.++### Added++- **`businessProcessFlows[]` — guided, staged processes on a table.** Ordered stages with steps bound+ to that table's columns, activated on create. v1 is single-entity and linear — branching, stage+ actions and role grants ([#513]) are rejected rather than silently dropped.++### Changed++- **A business rule is validated before it is written.** A rule the SDK's compiler cannot understand+ used to deploy as an empty rule that never fires; the build now runs the designer's own validator+ and fails with its findings.++### Fixed++- **A build no longer halts on an environment that cannot host business rules** — those rules are+ skipped with a warning again, which matters because such environments are the common case.+- **A failed push reports the SDK's own reason** instead of always blaming a concurrent Maker edit,+ and a `VERSION_CONFLICT` still tells you to re-download.+- **Download round-trips `app.newLook` and `app.headerNavigationRefresh`** ([#514]) — a rebuild+ elsewhere previously produced a classic-shell app with nothing reporting the loss.+- **`views[].columns` rejects a non-string entry** ([#525]). An object reached the view's fetchxml as+ `[object object]` and left behind a view row that could not be read or deleted, so every later+ build failed the same way.+- **A business process flow whose derived unique name is already taken is refused up front** — that+ name becomes a *table* name on activation, so a flow named after its own table collided silently.+- **A reused business rule rejoins its solution on every build**, so it travels on export/import.+- **A non-string table reference is rejected instead of coerced** (`charts[].entity`, a subgrid's+ `childEntity`, a sitemap subarea's `entity`, a dashboard tile's `entity`).++[#513]: https://github.com/microsoft/power-platform-skills/issues/513+[#514]: https://github.com/microsoft/power-platform-skills/issues/514+[#525]: https://github.com/microsoft/power-platform-skills/issues/525++## [2.5.1]++SDK uptake. Adds per-form security roles and three column capabilities; **business rules now require+an environment that supports them**.++### Changed++- **Business rules are environment-gated.** An environment that does not declare the SDK's bound+ `CreateProcessWithWfomJson` member **cannot host business rules at all** — the common case. Such+ rules are skipped with a warning, and `--verify` reports them as *not applicable on this+ environment*.++### Added++- **Generated pages can report to the customer's Application Insights** — behind the new default-OFF+ `custom-telemetry` feature flag, via an optional `props.appInsights` surface. The flag is+ permission, not instruction: even with it on, a page is instrumented only when the maker asked to+ measure something, so existing prompts are unaffected. Ships OFF pending the host runtime,+ authoring control, agent prompt and ECS setting. See `references/page-telemetry.md`. Unrelated to+ the plugin's own usage telemetry (`/model-apps:telemetry`).+- **Per-form security roles** — `forms[].securityRoles`: offer a form to named `personas[]` or to+ `everyone`. A form with no assignment is visible to **every** role, so this *restricts* a form; undo+ with `everyone: true`, not by deleting the block. (AB#6648526)+- **Boolean `defaultValue`, whole-number `integerFormat`, and per-column `isValidForCreate` /+ `isValidForUpdate` / `isValidForRead`** — the last is how you make a column read-only.+ ([#495], AB#6648523, AB#6648522, AB#6651276)+- **Twelve more business-rule operators** and **multi-condition rules** (ANDed). Spelling matters:+ `IsGreaterThan`, not `GreaterThan` — the SDK silently resolves an unknown operator to `Equals`, so+ the spec rejects anything outside its table.+- **A `description` on every artifact that accepts one**, written at create time and omitted when+ absent, so a rebuild never blanks text typed in the maker.+- **Per-field form control** — `readOnly`, `hidden` and `after`, via a form-level `fieldOptions` map+ or inline on an explicit layout. `prune: false` edits part of a form without re-declaring it.+- **The AI form-fill family is controllable per capability** — assist toolbar, edit-form predictions,+ smart paste and file upload, instead of one flag that only governed the toolbar.++### Fixed++- **A `businessRules[]`-only edit is no longer treated as "nothing changed"** under `--changed-only`+ ([#478], which also fixes downloads losing dashboard tiles).+- **Descriptions converge on existing views and charts** — previously written only at create, so the+ auto-created *"Active <Plural>"* view never got one ([#496]); **downloaded specs preserve+ deployed descriptions** ([#494]).+- **Teardown removes the activated copy of a business rule**, previously stranding an undeletable+ row ([#493]), and clears column visualizations for a table the spec keeps.+- **Existing columns honour an explicit `required` change on rebuild**; an omitted one leaves the+ live column alone.+- **Big Integer columns are no longer auto-placed on forms** — they have no Unified Interface control+ and rendered *"Error loading control"* on every record.+- **AI on/off is read with the platform's semantics** — `0` = platform default, `1` = disabled,+ `2` = enabled. Treating any non-zero value as "on" reported a disabled feature as enabled.+- **Presence operators** (`ContainsData` / `DoesNotContainData`) deploy ([#481]).+- **`ai.summaries.default: "off"` no longer discards a per-table `enabled: true`**, and a+ differently-cased `tables[]` key keeps its `instruction` and `columns`.+- **A row summary an environment cannot license is skipped, not fatal** — and the row the refused+ publish leaves behind is swept, so a rebuild does not fail on a duplicate key.+- **A spec with no `appShell` reports what to add** instead of dying after the app was half-created.+- **A malformed `businessRules` is a validation error**, not a raw `TypeError`.+[#478]: https://github.com/microsoft/power-platform-skills/issues/478[#481]: https://github.com/microsoft/power-platform-skills/issues/481[#493]: https://github.com/microsoft/power-platform-skills/issues/493[#494]: https://github.com/microsoft/power-platform-skills/issues/494[#495]: https://github.com/microsoft/power-platform-skills/issues/495-[#496]: https://github.com/microsoft/power-platform-skills/issues/496-[#513]: https://github.com/microsoft/power-platform-skills/issues/513+[#496]: https://github.com/microsoft/power-platform-skills/issues/496++## [2.5.0]++Takes up the current maker SDK, adds modern-shell and navigation controls, labels Dataverse+metadata in the organization's own language instead of a hardcoded 1033, and makes persona roles+and jobs-to-be-done checkable.++### Added++- **`businessRules[]` — declarative form logic, no code.** Show/hide, lock/unlock, set-required and+ set-value, gated on a condition over the record, activated on create. Every field is checked+ against the rule's own entity, because a rule naming a column that does not exist is accepted by+ the platform and then simply never fires. Operators `Equals` · `DoesNotEqual`.+- **Custom grid rendering (preview) — `entities[].columns[].visualization`.** Render a column as a+ radial dial, line chart, heat map or star rating in every grid and view that shows it. Where the+ platform has not provisioned the preview the build skips it and everything else still deploys.+- **`app.newLook` — opt into the modern ("new look") shell**, written as the per-app+ `NewLookAlwaysOn` setting so the result is deterministic rather than a per-user preference.+ Best-effort: a tenant without the definition still gets a working app, with a warning.+- **`app.headerNavigationRefresh` — control the Wave 2 header and navigation refresh.** A separate,+ independent setting from `app.newLook`. The platform default is **ON**, so this exists as much to+ turn the refresh off as on — `false` is written actively rather than treated as "do nothing".+- **Labels honour the authoring language everywhere** ([#447], [#455]) — tables, columns, choices,+ **form, dashboard and sitemap labels**. Previously only the data-model phase respected it, so+ `--language-code 1031` produced German columns and English form labels. Precedence:+ `--language-code` → App Spec `languageCode` → the organization's base language → 1033.+- **An unprovisioned `languageCode` stops the build before any label is written** ([#456]), naming+ the LCID you asked for and the ones the organization has. Dataverse otherwise fails+ *inconsistently* — accepting it on tables and choices, rejecting it on `DateTime` and `Memo` — so+ the build died phases away from the flag that caused it.+- **A hand-pinned `languageCode` survives download.**+- **`directEntry` on `pages[]`.** A page declaring `pageInput` must say what a no-input entry+ renders: `{ "behavior": "selector" }` or `{ "behavior": "emptyState" }`. Every key in+ `pageInput.data` must also be supplied by an incoming `navigatesTo[].data` edge.+- **`verify` proves what a persona security role GRANTS**, not just that the role exists — a subset+ check by design, failing closed on an unreadable role or table.+- **`personas[].jobs[].surfaces[]` is checked, not documentary** — `spec-lint` warns when a surface+ matches nothing, and `verify` reports a failure as the job it broke.+- **Automatic plugin update notice** — a non-blocking preflight when a newer version is available.++### Fixed++- **Command buttons now actually run.** A JS command was created with no on-click parameters, so the+ usual `function doThing(primaryControl)` shape threw on its first property access and the button+ silently did nothing — with the build, the deployed rows and `--verify` all looking correct.+ Buttons now receive the standard parameters for their location, overridable via `parameters`.+- **Business rules no longer mistake the platform's activated copy for a duplicate**, which made the+ build warn about a duplicate that did not exist and teardown fail on it.+- **AI preflight no longer reports a running feature as disabled.** The readiness gate and a+ feature's actual setting are different rows; preflight now resolves the effective value and stops+ emitting an admin action for a feature that is already on.+- **Rebuilds no longer duplicate sub-grids or skip field removals.** The SDK's artifact surface became+ asynchronous upstream, and un-awaited that fails *silently* — a promise is truthy, so guards never+ fired, producing duplicate sub-grids, re-added fields and removals that never landed, all behind+ `2xx` responses and a green build.+- **Dashboard chart tiles no longer fail the `dashboards` phase** — the tile emitted `ChartId` where+ the FormXML schema requires `VisualizationId`.+- **Publish failures are no longer silent**, and **a partially-wrong push no longer reads as a clean+ success** — including the case where an app's system-administrator role assignment fails, which+ yields an app nobody can open.+- **A 412 version conflict could be swallowed**, dropping a concurrent Maker edit with no error.+- **A sitemap subarea targeting a custom web resource round-trips** ([#430]) — `$webresource:<name>`+ was rejected by the URL guard, so **no spec file was written at all**, blocking the whole+ download → edit → rebuild flow over one nav entry.+- **Malformed specs produce validation errors instead of raw `TypeError`s**, naming the exact path,+ and can no longer pass validation and then crash *after* the solution and data model were written.+- **`verify-model-app` reports a missing table as a finding**, not a raw Dataverse HTTP 400.++### Changed++- **An app now requires an image icon.** The SDK's auto-resolve demands an **image** web resource,+ failing with `APP_ICON_UNRESOLVED` rather than falling back to any unmanaged web resource+ (including a **JavaScript** file, which the platform then rejected opaquely). No change for+ `/app-builder`, which always passes one explicitly.+- **The vendored SDK records its provenance.** `scripts/vendor/PROVENANCE.json` carries the upstream+ SHA and the bundle's own sha256, and the bundler **refuses** a stale, dirty or unidentifiable+ source. "Built from master" is not provenance: a previously shipped bundle was built from a stale+ build output several commits behind its nominal source, and nothing could reveal it.+- **Three SDK contract changes are user-visible**: `deleteAppCascade` no longer deletes generative+ pages (they are *referenced* by an app, not owned by one, and are reported in `retained[]`);+ unconditional artifact writes are refused (`ARTIFACT_UPDATE_NO_ETAG`); and `pushArtifact` /+ `publishArtifact` report failure by value instead of throwing.+- **`download-model-app.js --app` accepts a display name**, and fails closed when one matches more+ than one app.++### Known limitations++- **A classic dashboard does not survive `download-model-app.js`** — the vendored SDK throws while+ deserializing the `<parameters>` block it itself serialized, so no tiles are recovered and the+ download fails unless `--allow-lossy-download` is passed. Not a regression from this release's SDK+ uptake; tracked upstream.++[#430]: https://github.com/microsoft/power-platform-skills/issues/430+[#447]: https://github.com/microsoft/power-platform-skills/issues/447+[#455]: https://github.com/microsoft/power-platform-skills/issues/455+[#456]: https://github.com/microsoft/power-platform-skills/issues/456++## [2.4.2]++Fixes a malformed app module: generated apps did not actually contain their tables.++### Fixed++- **Generated apps contained an invalid `entity` table component instead of their real tables**+ (ADO 6612527), which also broke unrelated app-processing paths. Tables are now pinned by OData+ **reference** — the only form that can also express an abstract table such as `activitypointer`.+- **An unresolvable table halts the build, naming it.** One bad component fails the whole+ `AddAppComponents` call, so a silently-skipped table used to empty the app's component list.+- **App components are read back and verified after the write** — the write returned 204 for every+ corrupt app, and `ValidateApp` reported success too.++### Known limitations++- **Download still drops entity components not in the sitemap** (ADO 6603388) — the hidden component+ it describes could not be constructed live, so the download-side fix is unverified.++## 2.4.1++Bug fixes for apps built on **out-of-the-box** tables, and the matching SDK uptake. No change to+any skill's public surface.++### Fixed++- **AI app features had no effect on a newly built app** — an app-scope setting write is a no-op+ until the app is published, so the build wrote nothing while reporting success. **`--verify` passed+ when they were never applied**; it now proves an app-scope override row, because reading the+ setting back falls through to the environment value.+- **`ai.appFeatures` accepts non-boolean values** such as `2` ("on for everyone").+- **Download invented primary-name columns**, **replaced the solution's publisher prefix with+ `new`**, and **dropped tables with no sitemap entry** — all three now read from Dataverse.+- **Teardown could permanently burn an app's unique name** — an app is two rows with no server-side+ cascade, so deleting only the app module stranded the sitemap and reserved its name forever. Both+ rows are now deleted atomically in one OData `$batch`.++### Changed++- Re-vendored `cds-maker-sdk`. An injected `HttpClient` must now implement `postRaw` for the atomic+ `$batch`.+- **model-apps now runs in CI** (ubuntu × windows × macos, Node 20 × 22, plus the offline evals) —+ previously every test workflow was scoped to another plugin, so this suite never ran on a PR.++## 2.4.0++A new **`/app-builder`** skill (Preview) that builds and edits whole model-driven apps, plus+local-dev ergonomics, sample coverage, and an automated eval suite. No breaking changes.++### Added++- **`/app-builder` (Preview)** — natural-language intent → deployed model-driven app: tables,+ columns, relationships, adaptive forms with sub-grids, views, charts, dashboards, generative+ pages, app + sitemap, and sample data, via the headless vendored `cds-maker-sdk`.+- **Jobs-to-be-done drive the design** — authoring starts by asking who uses the app and what each+ of them needs to get done, *before* the data model.+- **Security roles per persona (`personas[]`)** — one role per persona, sized to the privileges its+ jobs declare, associated with the app so it opens for non-admins.+- **`model-app-plan.md`** — a readable, regenerable design document rendered from the spec, plus+ design-gap warnings at the lint gate.+- **Table icons are described before they are drawn** — each table proposes what its glyph will+ *depict* in plain language, shown for approval before any SVG is authored.+- **AI-first features** (`ai` block) — form fill, NL search, NL charts, M365 Copilot and row+ summaries, admin-gated by a preflight.+- **`--changed-only` partial apply (Preview, off by default)** — a page-only `.tsx` edit re-runs just+ the pages phase; anything else falls back to a full build.+- **`scripts/preview-app.js`** to review the whole design before building.++### Changed++- **Edits are first-class**: forms and views update in place, a form edit can *remove* a field, a+ built main form becomes the entity default, and editing an existing app updates the sitemap for+ page-less apps too.+- **Identity is unambiguous** — forms resolve by `(entity, name, type)`, views by `entity|name`, and+ an app round-trips by its real `uniquename`, so a rebuild cannot duplicate or cross-wire.+- **Page generation reuses the `/genpage` worker** through a plan adapter, so an intent page can no+ longer silently fail to become `.tsx`.+- Re-vendored `cds-maker-sdk` (pagination, quick create, idempotent global choice, authored column+ width, shared input-safety boundaries).++### Fixed++- **Teardown removes everything the app owns** — icon and app-icon web resources are removed, cascade+ failures are reported rather than silently orphaning rows, and reused/system tables are skipped+ with a reason. The **publisher** is deliberately left behind: it can own other solutions, so+ removing it is not this app's decision.+- **Exported solutions are self-contained** — the app icon and sitemap are added to the solution.+- **The Dataverse token is never sent to another origin** — the HTTP client refuses any request+ outside the absolute `https` org URL.+- **A lossy download fails instead of reporting success** (`--allow-lossy-download` opts in), and+ **CLI flags fail loudly** — notably `--apply --only` with no phase list used to run a *full* apply.+- Assorted: relationships to system tables, classic dashboard round-trip, AI row summaries, and+ sub-grid `targetEntity`.++### Removed++- Standalone entity/solution scripts, consolidated into `provision-entities.js` and+ `provision-solution.js`.++### Known limitations++- **App EDIT does not re-pin a new chart** as an explicit app component — a chart added to an+ existing app needs a manual pin or a rebuild.++## 2.3.0 — 2026-07-23++Plugin observability and authoring guardrails. No breaking changes.++### Added++- **Anonymous 1DS telemetry** (default-on, ships `disabled` until provisioned) with a local+ diagnostic mirror, a `/model-apps:telemetry on|off|status` control skill, and a CI opt-out via+ `POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT=1`. Fail-closed throughout, and carries **no+ user-level identifier**.+- **PostToolUse validators**, including a `@fluentui/react-icons` allowlist check that blocks a+ hallucinated icon name at write time.+- **PreToolUse write-safety guard** — flags writes outside the cwd during an active genpage session+ only, so a globally-installed plugin never interferes with unrelated work.++### Fixed++- **Generated-page double-fetch / render flash on open.** The webplayer host double-mounts a page and+ `dataApi` is a new reference each render, so a `useEffect` dep on it re-fires forever. Guidance and+ every exemplar now use an in-flight-promise de-dupe plus a window cache; `dataApi` is forbidden in+ any dependency array.+- **Playwright MCP launcher** — exports `launch()` per the `.mcp.json` contract, avoids the npx+ first-run prompt hang, and quotes config paths so Windows paths with spaces work.++## 2.2.0++Local-dev ergonomics, sample coverage, and an automated eval suite. No breaking changes.++### Added++- **Local-dev manifest** — working dirs get `package.json` and `genpage.d.ts`, so `npm install` and+ editor IntelliSense work after generation.+- **Eval suite** — TAP v13 runners for workflow and code assertions, 10 shipping fixtures, and+ `capture-fixture.js` to turn a real `/genpage` run into one.+- **Dialog and overlay guidance** plus samples — portalled Fluent surfaces are confined to the page+ so a modal cannot escape the preview and cover the designer.+- **Feature-flag gate for connectors (default OFF)**, with all connector work owned by a single+ `genpage-connector-builder` agent invoked from both the create and edit flows.++### Fixed++- **`queryTable` returns a `DataTable`, not an array** — 7 samples and fixtures iterated the result+ directly, producing `X.map is not a function` at runtime.+++## 2.1.0 — 2026-05-13++Replaces the Dataverse MCP server + Python SDK fallback with Node.js Web API scripts. Adds solution+selection, prefix discipline, and a consolidated auth pre-flight.++### Breaking+- **Azure CLI (`az`) is now required** for entity creation, with access to the target environment.+- **The Dataverse Skills plugin is no longer required.**++### Added+- Node.js Web API scripts under `scripts/` (auth, request, table/column/relationship/record+ creation with `$batch` bulk, solution management).+- Solution selection with prefix-conflict warnings, and a transactional creation log.++### Fixed+- **Prefix drift is structurally impossible** — the plan stores logical-name suffixes only, and the+ full name is constructed from one source of truth.+- **`pac model create` always passes `--solution`** — the CLI's "active solution" fallback errors+ in practice.++### Performance+- ~27K tokens saved per page-builder run (icon list is no longer loaded upfront; reference docs and+ the opt-in browser-verification flow were extracted or trimmed).++### Added (samples)+- Dashboard with D3 charts, a list page using the window-cache pattern, and its paired detail page+ demonstrating `pageInput` and the formatted-value lookup.++### Migration from 2.0+1. `az login` (use the same identity as `pac auth who`).+2. Uninstall the Dataverse Skills plugin if it was only for `/genpage`.+3. No code or page changes needed; existing pages keep working.++---++## 2.0.0 — 2026-05-12++Major refactor of `/genpage` into an agent-orchestrated architecture.++### Breaking+- **PAC CLI ≥ 2.7.0** required.+- Skill output now lives in a per-invocation working directory.+- Plan-mode approval is mandatory; no skip or auto-accept.++### Added+- Four specialist agents (planner, entity-builder, page-builder, edit-planner).+- Multi-page parallel generation with cross-page navigation via `PAGEREF_<filename>` placeholders.+- A plan schema contract, a verified Fluent icon list, and a 16-eval suite across three tiers.++### Migration from 1.x+1. `dotnet tool update --global Microsoft.PowerApps.CLI.Tool` (to ≥ 2.7.0).+2. Existing deployed pages keep working — only the local workflow and layout changed.++---++## 1.0.6 — earlier in 2026-## [2.5.0]--Takes up the current maker SDK, adds modern-shell and navigation controls, labels Dataverse-metadata in the organization's own language instead of a hardcoded 1033, makes persona roles-and jobs-to-be-done checkable, and fixes a class of failures that were silent.--### Added-- **`businessRules[]` — declarative form logic, no code.** Show/hide, lock/unlock, set-required and- set-value, gated on a condition over the record; compiled to classic workflow XAML and activated on- create. Every field is checked against the rule's own entity, because a rule naming a column that- does not exist is accepted by the platform and then simply never fires. Operators `Equals` ·- `DoesNotEqual`. Additive on rebuild, torn down with the app, and a new `business-rules` build- phase.-- **Custom grid rendering (preview) — `entities[].columns[].visualization`.** Render a column as a- radial dial, line chart, heat map or star rating in every grid and view that shows it. Per-column,- so it is declared once rather than per view. Where the platform has not provisioned the preview the- build skips it and everything else still deploys.-- **`app.newLook` — opt into the modern ("new look") shell.** Writes the per-app- `NewLookAlwaysOn` setting, so the result is deterministic rather than a per-user preference.- Scoped to the app and solution so it travels on export/import. Best-effort: a tenant without- the definition still gets a working app on the classic shell, with a warning.-- **`app.headerNavigationRefresh` — control the Wave 2 header and navigation refresh.** A- **separate, independent** setting from `app.newLook`; enabling one does not enable the other.- The platform default is **ON**, so this exists as much to turn the refresh off as on — `false`- is written actively rather than treated as "do nothing".-- **Labels honour the authoring language everywhere**- ([#447](https://github.com/microsoft/power-platform-skills/issues/447),- [#455](https://github.com/microsoft/power-platform-skills/issues/455)). Tables, columns,- choices, **form, dashboard and sitemap labels** all use one resolved LCID. Previously only the- data-model phase respected it, so `--language-code 1031` produced German columns and English- form labels. Precedence: `--language-code` / `--languageCode` → App Spec `languageCode` → the- organization's base language → 1033. Omit it and behaviour is unchanged.-- **An unprovisioned `languageCode` stops the build before any label is written**- ([#456](https://github.com/microsoft/power-platform-skills/issues/456)), naming the LCID you- asked for and the ones the organization actually has. Dataverse otherwise fails *inconsistently*- here — it accepts an unprovisioned LCID on tables and choices and rejects it on `DateTime` and- `Memo` — so the build died phases away from the flag that caused it.-- **A hand-pinned `languageCode` survives download.** Download still never reads the LCID from- Dataverse (that would make the spec non-portable), but a value you wrote is carried over.-- **`directEntry` on `pages[]`.** Every page is a sitemap subarea, so a **detail** page is- reachable from navigation with no input. A page declaring `pageInput` must now say what happens- then: `{ "behavior": "selector" }` (show a picker) or `{ "behavior": "emptyState" }`. Every key- in `pageInput.data` must also be supplied by an incoming `navigatesTo[].data` edge.-- **`verify` proves what a persona security role GRANTS**, not just that the role exists — every- declared `(entity, access)` is resolved to its Dataverse privilege and checked at **at least**- the declared depth. A subset check by design; fails closed on an unreadable role or table.-- **`personas[].jobs[].surfaces[]` is checked, not documentary.** `spec-lint` warns when a surface- matches nothing in the spec, and `verify` reports a deployed failure as the job it broke- ("persona P can no longer do job J") rather than only "view X is missing".-- **Automatic plugin update notice** — a non-blocking preflight tells you when a newer Model Apps- version is available, with the update command for your host.--### Fixed-- **Command buttons now actually run.** A JS command was created with no on-click parameters, so the- function was invoked with no arguments — the near-universal `function doThing(primaryControl)` shape- threw on its first property access and the button silently did nothing. Nothing server-side showed- it: the build, the deployed rows and `--verify` all looked correct, and the error appeared only in- the browser console. Buttons now receive the standard parameters for their location- (`MainTab` → PrimaryControl; grid/subgrid → SelectedControl), overridable via `parameters`.-- **Business rules no longer mistake the platform's activated copy for a duplicate.** Activating a- rule makes Dataverse create a second `workflows` row (`type 2`, parented to the definition) — normal- for any activated process. Build, verify and teardown queried without `type eq 1`, so the build- tried to delete that copy (which the platform refuses, 405) and warned about a duplicate that did- not exist, teardown failed on it, and verify would have reported every active rule as duplicated.- All three now select definitions only.-- **AI preflight no longer reports a running feature as disabled.** The readiness gate and a- feature's actual setting are different rows, so a gate reading off did not mean the feature was- off — NL search and NL charts were reported as unavailable while both were in effect. Preflight now- resolves the effective value (app override → environment → default), says which scope enabled it,- and stops emitting an admin action for a feature that is already on.-- **Rebuilds no longer duplicate sub-grids or skip field removals.** The vendored SDK's artifact- surface became **asynchronous** upstream (`getArtifact`, `addElement`, `updateElement`,- `removeElement`, `moveElement`, `findElements`, `queryTree`). Un-awaited, that fails *silently*:- a promise is truthy, so guards never fire and the form helpers see a promise instead of a form —- producing duplicate sub-grids and quick-views, re-added fields, and field removals that never- land, all behind `2xx` responses and a green build. All 40 call sites are fixed, and two nets now- guard the class (a source scan, and test mocks that actually yield).-- **Dashboard chart tiles no longer fail the `dashboards` phase.** A tile emitted `ChartId`, which- the platform's FormXML schema rejects; the correct name is `VisualizationId`. Found by a live- build — the mock-based test had asserted the wrong name, so the suite agreed with the bug.-- **Publish failures are no longer silent.** The SDK moved `publishArtifact` from throwing to- reporting by value and all nine call sites discarded the result, so a failed `PublishXml`- produced `ok: true` with nothing logged — and the transient-retry path for 429 / 503 /- customization-lock had become unreachable.-- **A partially-wrong push no longer reads as a clean success.** `PushResult.warnings[]` were- dropped at all eleven sites — including the case where an app's system-administrator role- assignment fails, which yields an app nobody can open.-- **A 412 version conflict could be swallowed.** The SDK renamed `PushResult.success` to `saved`;- the guard still read `success === false` and simply stopped firing, dropping a concurrent Maker- edit with no error. It now reads either spelling and fails closed.-- **A sitemap subarea targeting a custom web resource round-trips**- ([#430](https://github.com/microsoft/power-platform-skills/issues/430)). `$webresource:<name>`- was rejected by the URL guard, so the downloaded spec failed validation and **no spec file was- written at all** — blocking the whole download → edit → rebuild flow over one nav entry.-- **Malformed specs produce validation errors instead of raw `TypeError`s**, and can no longer pass- validation and then crash mid-build *after* the solution and data model were written. Errors name- the exact path (`appShell.areas[0].groups must be an array`).-- **`verify-model-app` reports a missing table as a finding**, not a raw Dataverse HTTP 400, and- prints the failure detail so a failed *read* is distinguishable from a genuinely absent artifact.-- **The live smoke eval asserted an outcome the builder never produces** — it used the one icon- shape the builder deliberately drops, and the offline test hid it by hand-writing the XML it- wanted to see.--### Known limitations-- **A classic dashboard does not survive `download-model-app.js`.** Build and teardown work, but the- vendored SDK's `fetchArtifact('dashboard', …)` throws while deserializing the `<parameters>` block- it itself serialized, so no tiles are recovered and the dashboard's sitemap subarea is dropped —- failing the whole download unless `--allow-lossy-download` is passed. Live-verified, and reproduced- on the previous bundle too, so it is **not** a regression from this release's SDK uptake. Download- now names the cause instead of dropping the subarea silently. Tracked upstream.--### Changed-- **Business rules are authorable — the vendored SDK now compiles them to classic workflow XAML.**- They were unauthorable because the supported bound member faults (`400 0x80040216`) on our tenants;- the SDK now falls back to a plain `workflows` row carrying compiled WWF XAML. The fallback is- narrow on purpose — only that code, or a `404` — so an ambiguous failure can never write the rule- twice. Live-verified end to end, and pinned against the shipped bundle in- `sdk-uptake-contract.test.js`. **The App Spec does not expose business rules yet;** this makes them- possible, not authorable from a spec.--- **Column data visualizations for grids** (`getColumnVisualization` / `setColumnVisualization`)- are available on the vendored SDK (preview). Not yet surfaced in the App Spec.--- **An app now requires an image icon.** `appmodule.webresourceid` is required, and the SDK's- auto-resolve now demands an **image** web resource, failing with `APP_ICON_UNRESOLVED` when the- environment has none — it previously fell back to any unmanaged web resource, including a- **JavaScript** file, which the platform then rejected opaquely. No change for `/app-builder`: it- always generates or resolves an icon and passes it explicitly.--- **Vendored SDK re-taken from its merged `master`, and it now records its provenance.**- `scripts/vendor/PROVENANCE.json` carries the upstream SHA, build mode and the bundle's own- sha256, and the bundler **refuses** a stale, dirty or unidentifiable source. "Built from master"- is not provenance: the previously shipped bundle was built from a stale build output several- commits behind its nominal source, and nothing in the repo could reveal it.-- **Three SDK contract changes are user-visible**: `deleteAppCascade` no longer deletes generative- pages (they are *referenced* by an app, not owned by one, so they are reported in `retained[]`);- unconditional artifact writes are refused (`ARTIFACT_UPDATE_NO_ETAG`); and `pushArtifact` /- `publishArtifact` report failure by value instead of throwing.-- **`download-model-app.js --app` accepts a display name**, not just an id or `uniquename`, and- fails closed when a display name matches more than one app.--### Tests-- ~1600 plugin tests + 159 eval tests; 94% line coverage.-- **The mocks no longer lie about the SDK contract.** Every mock returned plain values while the- real SDK returns promises, so a missing `await` behaved identically under test — leaving ~1500- tests structurally blind to the class above. They are now `async` *and* yield.-- **Rebuild idempotence is asserted.** Reconcile tests started from an *empty* deployed form, where- "re-add everything" and "add only what's missing" produce identical call logs.-- **Concurrency stress against the real bundle**, and contract tests that pin the SDK's async- surface, its serialized sitemap bytes, and the committed bundle against its provenance record.--## [2.4.2]--Fixes a malformed app module: generated apps did not actually contain their tables.--### Fixed-- **Generated apps contained an invalid `entity` table component instead of their real tables**- (ADO 6612527), which also broke unrelated app-processing paths. The documented `@odata.type`- shape returns 204 and then records a component pointing at the metadata table literally named- `entity` (platform defect **AB#39140211**). Tables are now pinned by OData **reference** — the- only form that can also express an abstract table such as `activitypointer`.-- **An unresolvable table halts the build, naming it.** One bad component fails the whole- `AddAppComponents` call, so a silently-skipped table used to empty the app's component list.-- **App components are read back and verified after the write** — `AddAppComponents` returned 204- for every corrupt app, and `ValidateApp` reported success too.--### Changed-- Re-vendored `cds-maker-sdk` with the above.--### Eval harness-- **A value-less or malformed runner flag is rejected** instead of silently changing scope — a bare- `--tier` became "no tier filter", and the run then reported PASS for a scope nobody asked for.- The parser is now shared at `evals/model-apps/lib/eval-args.js`.-- **A malformed fixture names the fixture**, tolerates a UTF-8 BOM, and rejects a non-object spec- up front.--### Known limitations-- **Download still drops entity components not in the sitemap** (ADO 6603388) — the hidden- component it describes could not be constructed live, so the download-side fix is unverified.--## 2.4.1--Bug fixes for apps built on **out-of-the-box** tables, and the matching SDK uptake. No change to-any skill's public surface.--### Fixed-- **AI app features had no effect on a newly built app** — an app-scope setting write is a no-op- until the app is published, so the build wrote nothing while reporting success.-- **`--verify` passed when AI features were never applied** — it now proves an app-scope override- row, because reading the setting back falls through to the environment value.-- **`ai.appFeatures` accepts non-boolean values** such as `2` ("on for everyone").-- **Download invented primary-name columns**, **replaced the solution's publisher prefix with- `new`**, and **dropped tables with no sitemap entry** — all three now read from Dataverse.-- **Teardown could permanently burn an app's unique name** — an app is two rows with no server-side- cascade, so deleting only the app module stranded the sitemap and reserved its name forever. Both- rows are now deleted atomically in one OData `$batch`.--### Changed-- Re-vendored `cds-maker-sdk`. An injected `HttpClient` must now implement `postRaw` for the atomic- `$batch`.--### Tests-- 1266 → 1340 tests; coverage 92.7 → 93.9% line.-- **model-apps now runs in CI** (ubuntu × windows × macos, Node 20 × 22, plus the offline evals) —- previously every test workflow was scoped to another plugin, so this suite never ran on a PR.--## 2.4.0--A new **`/app-builder`** skill (Preview) that builds and edits whole model-driven apps, plus-local-dev ergonomics, sample coverage, and an automated eval suite. No breaking changes.--### Added-- **`/app-builder` (Preview)** — natural-language intent → deployed model-driven app: tables,- columns, relationships, adaptive forms with sub-grids, views, charts, dashboards, generative- pages, app + sitemap, and sample data, via the headless vendored `cds-maker-sdk`.-- **Jobs-to-be-done drive the design** — authoring starts by asking who uses the app and what each- of them needs to get done, *before* the data model, and carries those jobs through to the- surfaces that satisfy them.-- **Security roles per persona (`personas[]`)** — one role per persona, sized to the privileges its- jobs declare, associated with the app so it opens for non-admins.-- **`model-app-plan.md`** — a readable, regenerable design document rendered from the spec, plus- design-gap warnings at the lint gate (a job with no covering surface, an app with no pages).-- **Table icons are described before they are drawn** — each table proposes what its glyph will- *depict* in plain language, shown for approval before any SVG is authored.-- **AI-first features** (`ai` block) — form fill, NL search, NL charts, M365 Copilot and row- summaries, admin-gated by a preflight.-- **`--changed-only` partial apply (Preview, off by default)** — a page-only `.tsx` edit re-runs- just the pages phase; anything else falls back to a full build.-- **`scripts/preview-app.js`** to review the whole design before building, and an offline eval- suite for `/app-builder` alongside the genpage TAP runners.--### Changed-- **Edits are first-class**: forms and views update in place, a form edit can *remove* a field, a- built main form becomes the entity default, and editing an existing app updates the sitemap for- page-less apps too.-- **Identity is unambiguous** — forms resolve by `(entity, name, type)`, views by `entity|name`,- and an app round-trips by its real `uniquename`, so a rebuild cannot duplicate or cross-wire.-- **Page generation reuses the `/genpage` worker** through a plan adapter, so an intent page can no- longer silently fail to become `.tsx`; untrusted spec text cannot forge plan sections.-- Re-vendored `cds-maker-sdk` (pagination, quick create, idempotent global choice, authored column- width, shared input-safety boundaries).--### Fixed-- **Teardown removes everything the app owns** — icon and app-icon web resources are removed, cascade- failures are reported rather than silently orphaning rows, and reused/system tables are skipped- with a reason. Command-bar teardown is fail-closed. The **publisher** is deliberately left behind:- it can own other solutions, so removing it is not this app's decision.-- **Exported solutions are self-contained** — the app icon and sitemap are added to the solution.-- **The Dataverse token is never sent to another origin** — the HTTP client refuses any request- outside the absolute `https` org URL.-- **A lossy download fails instead of reporting success** (`--allow-lossy-download` opts in), and- **CLI flags fail loudly** — notably `--apply --only` with no phase list used to run a *full* apply.-- Assorted: relationships to system tables, classic dashboard round-trip, AI row summaries, and- sub-grid `targetEntity`.--### Removed-- Standalone entity/solution scripts, consolidated into `provision-entities.js` and- `provision-solution.js`.--### Known limitations-- **App EDIT does not re-pin a new chart** as an explicit app component — a chart added to an- existing app needs a manual pin or a rebuild.--## 2.3.0 — 2026-07-23--Plugin observability and authoring guardrails. No breaking changes.--### Added-- **Anonymous 1DS telemetry** (default-on, ships `disabled` until provisioned) with a local- diagnostic mirror, a `/model-apps:telemetry on|off|status` control skill, and a CI opt-out via- `POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT=1`. Fail-closed throughout, and carries **no- user-level identifier**.-- **PostToolUse validators**, including a `@fluentui/react-icons` allowlist check that blocks a- hallucinated icon name at write time.-- **PreToolUse write-safety guard** — flags writes outside the cwd during an active genpage- session only, so a globally-installed plugin never interferes with unrelated work.--### Fixed-- **Generated-page double-fetch / render flash on open.** The webplayer host double-mounts a page,- and `dataApi` is a new reference each render, so a `useEffect` dep on it re-fires forever.- Guidance and every exemplar now use an in-flight-promise de-dupe plus a window cache and a- readiness boolean; `dataApi` is forbidden in any dependency array.-- **Playwright MCP launcher** — exports `launch()` per the `.mcp.json` contract, avoids the npx- first-run prompt hang, and quotes config paths so Windows paths with spaces work.--## 2.2.0--Local-dev ergonomics, sample coverage, and an automated eval suite. No breaking changes.--### Added-- **Local-dev manifest** — working dirs get `package.json` and `genpage.d.ts`, so `npm install` and- editor IntelliSense work after generation.-- **Eval suite** — TAP v13 runners for workflow and code assertions, 10 shipping fixtures, and- `capture-fixture.js` to turn a real `/genpage` run into one.-- **Dialog and overlay guidance** plus samples — portalled Fluent surfaces are confined to the page- so a modal cannot escape the preview and cover the designer.-- **Feature-flag gate for connectors (default OFF)**, with all connector work owned by a single- `genpage-connector-builder` agent invoked from both the create and edit flows.--### Fixed-- **`queryTable` returns a `DataTable`, not an array** — 7 samples and fixtures iterated the result- directly, producing `X.map is not a function` at runtime. A new assertion catches it going forward.--## 2.1.0 — 2026-05-13--Replaces the Dataverse MCP server + Python SDK fallback with Node.js Web API scripts. Adds solution-selection, prefix discipline, and a consolidated auth pre-flight.--### Breaking-- **Azure CLI (`az`) is now required** for entity creation, with access to the target environment.-- **The Dataverse Skills plugin is no longer required.**--### Added-- Node.js Web API scripts under `scripts/` (auth, request, table/column/relationship/record- creation with `$batch` bulk, solution management).-- Solution selection with prefix-conflict warnings, and a transactional creation log.--### Fixed-- **Prefix drift is structurally impossible** — the plan stores logical-name suffixes only, and the- full name is constructed from one source of truth.-- **`pac model create` always passes `--solution`** — the CLI's "active solution" fallback errors- in practice.--### Performance-- ~27K tokens saved per page-builder run (icon list is no longer loaded upfront; reference docs and- the opt-in browser-verification flow were extracted or trimmed).--### Added (samples)-- Dashboard with D3 charts, a list page using the window-cache pattern, and its paired detail page- demonstrating `pageInput` and the formatted-value lookup.--### Migration from 2.0-1. `az login` (use the same identity as `pac auth who`).-2. Uninstall the Dataverse Skills plugin if it was only for `/genpage`.-3. No code or page changes needed; existing pages keep working.-------## 2.0.0 — 2026-05-12--Major refactor of `/genpage` into an agent-orchestrated architecture.--### Breaking-- **PAC CLI ≥ 2.7.0** required.-- Skill output now lives in a per-invocation working directory.-- Plan-mode approval is mandatory; no skip or auto-accept.--### Added-- Four specialist agents (planner, entity-builder, page-builder, edit-planner).-- Multi-page parallel generation with cross-page navigation via `PAGEREF_<filename>` placeholders.-- A plan schema contract, a verified Fluent icon list, and a 16-eval suite across three tiers.--### Migration from 1.x-1. `dotnet tool update --global Microsoft.PowerApps.CLI.Tool` (to ≥ 2.7.0).-2. Existing deployed pages keep working — only the local workflow and layout changed.-------## 1.0.6 — earlier in 2026--PageInput support, FluentProvider flicker fix, lookup `$select` rule, data caching pattern. See git-history for details.+PageInput support, FluentProvider flicker fix, lookup `$select` rule, data caching pattern. See git+history for details.diff --git a/plugins/model-apps/references/app-spec-schema.md b/plugins/model-apps/references/app-spec-schema.mdindex 8787bd3f8..22b376455 100644--- a/plugins/model-apps/references/app-spec-schema.md+++ b/plugins/model-apps/references/app-spec-schema.md@@ -59,6 +59,7 @@ sample data (incl. multi-parent junction links + status reasons), and publish."sampleData": { /* optional, keyed by entity schemaName */ },"ai": { /* optional — AI feature flags + row-summary config */ },"personas": [ /* optional — one security role per persona (see below) */ ],+ "roleGrants": [ /* optional — ADD privileges to a role you did NOT author (see below) */ ],"languageCode": 1031 /* optional — LCID for Dataverse labels; defaults to the org's base language */}```@@ -106,8 +107,7 @@ sample data (incl. multi-parent junction links + status reasons), and publish.- **`languageCode`** *(optional)* — the [LCID](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-lcid/)stamped on the Dataverse labels the build creates: data-model labels (table, column, choice, statusreason, relationship and alternate-key display names) **and** form, dashboard and sitemap labels.- The serializers used to hardcode 1033 with no caller override- ([#455](https://github.com/microsoft/power-platform-skills/issues/455)); they now take the+ The serializers used to hardcode 1033 with no caller override; they now take theauthoring language, so a non-English build no longer produces translated columns next to Englishform labels.**Normally omit it**: the build reads the organization's base language@@ -124,10 +124,11 @@ sample data (incl. multi-parent junction links + status reasons), and publish.discarded value rather than a silent fall-through.**It is build-wide.** One LCID is resolved and applied to every table, column, choice, statusvalue, relationship and alternate key in the spec. There is **no per-table language**: an- `entities[].languageCode` or `entities[].localizedLabels` is **rejected**- ([#537](https://github.com/microsoft/power-platform-skills/issues/537)), because the- build cannot honour either — the SDK takes the language as a construction-time option and its- label serializer emits one label per name by design. Multi-language labelling is not supported.+ `entities[].languageCode` is rejected, because the build cannot honour it — the SDK takes the+ language as a construction-time option. To label something in **several** languages, write the+ field itself as an LCID map (see *Localized labels* below); an `entities[].localizedLabels` block+ is rejected too, because the map belongs beside the name it labels rather than in a parallel+ addressing scheme.**Emitted by `download-model-app.js` only if you pinned it yourself.** It is deliberately neverread from Dataverse: an LCID copied out of the source org would be re-applied verbatim when thespec is rebuilt somewhere else, which is exactly how a spec starts failing in an org that lacks@@ -136,6 +137,74 @@ sample data (incl. multi-parent junction links + status reasons), and publish.pin is not silently lost — losing it would leave newly created columns in the org default whilethe existing ones keep the pinned language, with no error anywhere.+## Localized labels — one name, several languages++`languageCode` above sets the **one** language every plain label is written in. To label something in+**several** languages, write the field as a map keyed by LCID instead of a string:++```jsonc+"displayName": "Project Baseline" // one language+"displayName": { "1033": "Project Baseline", "3082": "Línea base" } // two+```++This works on every author-facing name the SDK can localize. **Measured**, per surface, against an+organization with 1033 and 3082 provisioned — the table is the honest scope of the claim:++| Where | Field | Status |+|---|---|---|+| `entities[]` | `displayName`, `pluralName` | **verified** — stored in both languages |+| `entities[].primaryAttribute` | `displayName` | **verified** |+| `entities[].columns[]` | `displayName` | **verified** |+| `entities[].columns[]` | inline Choice `options[]` | **verified** |+| `relationships[].lookup` | `displayName` | **verified** |+| `entities[].alternateKeys[]` | `displayName` | accepted; not consistently reproducible |+| `globalChoices[]` | `displayName`, `options[]` | **REJECTED at the spec gate** — see below |++**Global choices are the exception, and it is not this plugin's doing.** Measured: a global option set+created with a two-language label stores only the base language — **including through a raw+`POST /GlobalOptionSetDefinitions` that bypasses the SDK entirely** (0/4). Because Dataverse reports+nothing when it drops the language, a localized `globalChoices[]` label is **rejected by validation**+rather than sent: accepting it would produce a green build with the author's second language silently+gone, which is the exact failure this feature exists to end. Use an **inline** Choice on the column+(`columns[].options[]`, verified) when you need localized option labels, or set the global set's+labels in Maker. Plain-string global-choice labels are unaffected.++**Why a map on the field, not a `localizedLabels` block.** The label belongs beside the name it+labels. A table-level block cannot address a Choice **option** or a lookup's display name without+inventing a parallel addressing scheme, and it splits one value across two places that then drift.+An `entities[].localizedLabels` key is therefore **not** a supported shape.++**Rules**+- Keys are **canonical positive integer LCIDs** up to 65535 — `3082`, not `"03082"` and not+ `"es-ES"`. A language tag is rejected rather than guessed: `es-ES` is 3082 *or* 1034 depending on+ sort order, and guessing wrong would not fail — it would label everything in the wrong language.+- Every value must be a non-empty string; an empty map is rejected (the SDK rejects one too).+- `pluralName` becomes **required** beside a localized `displayName`. The English fallback appends+ `"s"`, which is not a plural rule in most languages — so the spec asks rather than inventing+ *"Línea base del proyectos"*.+- Omitting the spec's own `languageCode` from a map is a **warning**, not an error. Dataverse serves+ the base-language label to every user whose UI language has none, so leaving it out usually means+ those users read a schema name — but a deliberately single-non-English label is legal.+- Labels for all languages are written in **one** create call. That matters: a later single-language+ `PUT` can overwrite the base label even with merge semantics.+- **Every LCID you name must be provisioned in the organization, and the build halts if one is not.**+ This is the guard the feature depends on, not a nicety. Live-measured against a 1033-only org:+ `createTable` carrying `{ "1033": …, "3082": … }` returns **success** and stores **only** the 1033+ label — Dataverse does not warn, error, or report the drop anywhere. Without the halt you would get+ a green build with the second language silently gone, which is the exact failure this feature+ exists to end. The check is best-effort in the same way the existing `languageCode` check is: an+ unreadable `RetrieveProvisionedLanguages` leaves the build unchanged, and a spec with only plain+ string labels never pays the round trip.++**Referencing a localized label.** Anywhere the spec names an artifact by its label — `sampleData`+choosing a Choice option, or `personas[].jobs[].surfaces[]` naming a screen — **any** of its+languages resolves to the same artifact. One option, one value, several names.++**Round-trip.** `download-model-app` reconstructs localized labels from Dataverse: a table, plural,+column or option labelled in several languages comes back as a map, and one labelled in a single+language comes back as a plain string (so no existing spec changes shape). The download emits+`pluralName` alongside a localized `displayName`, so its own output re-validates.+## `description` — write one on everything that takes one`description` is optional on every artifact below and **recommended on all of them**. It is written@@ -253,11 +322,11 @@ it exists is accepted by validation, builds green, and does not change the deplo]}```-- **Unknown table keys are REJECTED, not ignored**- ([#537](https://github.com/microsoft/power-platform-skills/issues/537)). A table accepts exactly the keys above+- **Unknown table keys are REJECTED, not ignored.** A table accepts exactly the keys aboveplus `statusReasons` / `alternateKeys`. Anything else — a misspelled `pluralname`, or a- `languageCode` / `localizedLabels` asking for a per-table or second language — fails validation- naming the alternative, rather than validating clean and being dropped from the build.+ `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.- **Column `type`:** `Text · Memo · Choice · MultiChoice · Boolean · Money · DateTime ·Integer · BigInt · Decimal · Double · File · Image · AutoNumber · Customer`.**Lookups are NOT columns** — declare a `OneToMany` relationship instead.@@ -443,8 +512,7 @@ Reference from a column via `"globalChoice": "new_priority"` (built before the c`filters[].attr`. Not `[{ "name": "..." }]` — that is the shape `forms[]` uses for its fields, andit used to be accepted here and stringified into the view's FetchXML as `[object object]`. Thebuild then failed at the platform, mid-run, and left behind a view row that could not be read or- deleted, so every later build failed the same way- ([#525](https://github.com/microsoft/power-platform-skills/issues/525)). It is now rejected up+ deleted, so every later build failed the same way. It is now rejected upfront, naming the view and the offending entry.- `activeOnly` (default `true`) adds `statecode eq 0`. `filters[]` add conditions: `op` is anyFetchXML operator — `eq`/`ne`/`lt`/`le`/`gt`/`ge`/`like`, no-value ops (`eq-userid`, `null`,@@ -1037,9 +1105,13 @@ entirely optional; omitting it leaves every AI feature at its platform default.// 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; a feature whose org gate is off is skipped with a warning and never silently applied.- // ENABLING is gated that way; DISABLING is not — a `false` is written even when the gate is off,- // which is why an incorrect `false` is the more damaging mistake of the two.+ // preflights. The gate is NOT a precondition: every write is attempted and then verified, and a+ // gate is read only to EXPLAIN a write that did not persist (AB#6688904 — for four of these+ // features the "gate" IS this same per-app row, so reading it first made a brand-new app look+ // forbidden and nothing was written at all). A feature whose write does not persist is surfaced+ // with a warning naming the admin action; it is never silently reported as applied.+ // 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)@@ -1179,4 +1251,121 @@ requested access, and the rule that different entities sharing one Dataverse prisame scope.**Not yet supported** (tracked follow-up): column-level (field) security and access teams / hierarchy-security. The security surface today is role-per-persona only.+security. The security surface today is role-per-persona plus `roleGrants[]` (below).++## roleGrants[] (optional — extend a role you did NOT author)++Adds privileges for a table to a security role that **already exists** — typically the roles an+existing solution ships. Use it when you add a table to an app whose access model somebody else owns:+without it the table, its forms and its navigation deploy while every non-admin persona still cannot+open the table, and nothing reports it.++```jsonc+"roleGrants": [+ {+ // Name the EXISTING role. Either `role` (display name) or `roleId` (GUID) — never both.+ "role": "Contoso PM - Project Manager",+ "businessUnitId": "…", // optional; scopes the NAME lookup (defaults to the org root BU)+ "privileges": [+ { "entity": "contoso_projectbaseline",+ "access": ["create", "read", "write", "delete", "append", "appendTo", "assign", "share"],+ "scope": "organization" }+ ]+ },+ { "role": "Contoso PM - Viewer",+ "privileges": [ { "entity": "contoso_projectbaseline", "access": ["read"], "scope": "organization" } ] }+]+```++**How it differs from `personas[]` — and why both exist.** A persona role is **converged**: the build+applies it with `ReplacePrivilegesRole`, so every privilege not in the spec is **removed**. That is+right for a role the spec created and catastrophic for one it did not — pointing a persona at an+existing role to add one table would silently strip everything else that role held. A `roleGrant`+compiles to `AddPrivilegesRole` instead, which is purely **additive**: it re-asserts what you declare+and leaves everything else alone.++| | `personas[]` | `roleGrants[]` |+|---|---|---|+| Owns the role | yes (creates it, SDK-marked) | no — the role already exists |+| Semantics | converges (replace) | adds only |+| Can revoke | yes, by dropping the privilege | **no** — see below |+| Managed role | refused (fail-closed conflict) | allowed |+| Teardown | deletes the role | does nothing |++**A grant is one-way.** Dropping an entry from `roleGrants[]` does **not** revoke the privilege, and+`teardown` never removes one. `AddPrivilegesRole` does not record who added what, so a revoke could not+tell a privilege this spec granted from one the role already held (or one a second spec granted) —+stripping the latter is exactly the outcome this surface exists to avoid. **Revoke in Maker.**++**Field reference**+- `role` **or** `roleId` (**required**, exactly one) — the existing role's display name, or its GUID. Setting both is rejected: they can disagree and only one can be honoured.+- `businessUnitId` (optional GUID) — scopes a lookup by `role` name. Rejected alongside `roleId`, where nothing would consult it.+- `privileges[]` (**required**, ≥1) — identical shape to a persona's: `{ entity, access[], scope? }`. `scope` reaches Dataverse intact as the privilege `Depth`.+- `description` (optional) — a note for readers of the spec; never written to Dataverse.++**Resolution fails closed.** Granting on the wrong role is a silent access-control defect no later+phase would catch, so every ambiguity is a **build halt**, never a skip: a name that matches no role,+a name that matches more than one role in the business unit, a stale pinned `roleId`, or a business+unit that cannot be resolved (a name-only fallback could grant on a same-named role in a *different*+business unit). Unlike the persona path this does **not** require the SDK ownership marker, and a+`ismanaged` role is allowed — extending a solution's shipped roles is the point.++**Validation rules** (`validateAppSpec`): exactly one of `role` / `roleId`; GUID shapes; a non-empty+`privileges[]` with valid `access` / `scope` tokens; **one entry per role** (two entries could request+conflicting depths for a shared Dataverse privilege — the SDK only detects that *within* one call, so+a split would let both writes through and the later would silently win); and a role that is **also a+persona in this spec** is rejected, because the persona pass would converge the grant away on the next+build. The apply-time metadata guards (a table that exposes no such access; two tables sharing one+`prv*` at different depths) surface as a build halt with the SDK's own message.++**Verification.** `verify-model-app` proves the role exists (`role-grant`) and — when the reader+supplies privilege access — that it actually **holds** every granted privilege at at least the declared+depth (`role-grant-privileges`). This matters more here than for a persona: a persona role's existence+implies its content (it was converged), whereas a grant is additive onto a role that existed before and+still exists whether or not the privileges landed. Subset semantics again — the role's other privileges+belong to somebody else and are never a finding.++## businessProcessFlows[].securityRoles — who may run a flow++Same shape and same persona idiom as `forms[].securityRoles`, so there is one thing to learn:++```jsonc+{ "name": "Ticket Handling", "entity": "contoso_ticket", "status": "Active",+ "securityRoles": { "personas": ["Dispatcher"] },+ "stages": [ /* … */ ] }+```++The **mechanic** is different, though, and it explains every rule below. A form's roles live inside+its formxml. A flow's live on a **table**: activating a flow makes the platform create an+organization-owned backing table, and holding privileges on that table is what lets a persona run the+process. Three things measured live before this surface was designed:++- the backing table's logical name is the flow's **deployed `uniquename`**, which the build **reads+ back** rather than deriving. For a flow this build creates the derivation is correct by+ construction, but a flow authored in Maker — or one renamed after creation — keeps a unique name+ unrelated to its display name, and granting on the derivation would target a table that does not+ exist, or an unrelated one that happens to hold that name. The plan can still *name* the derived+ table before the flow exists; the grant uses the value read at build time;+- the table is organization-owned and **every privilege is Global-only** — so there is **no `scope`**+ to author, because the platform accepts no other depth;+- the access granted is fixed at `create`, `read`, `write`, `delete` — a partial set produces a flow a+ user can see but not advance.++**Rejected rather than ignored**+- `everyone`, `fallbackForm`, `order` — formxml concepts with no equivalent here. The error says so+ rather than just listing allowed keys, because an author who wrote them learned them from `forms[]`.+- an **empty** `personas[]` — unlike a form (offered to everyone until restricted), a flow's backing+ table grants to nobody by default, so an empty list is a request that cannot be satisfied.+- `securityRoles` on a **Draft** flow — the backing table is created by *activation*, so there is+ nothing to grant on yet.++Applied in the **security** phase, after `personas[]` roles exist. If the flow was not built in the+same invocation the grant is **skipped with a stated reason**, never applied blind.+`verify-model-app` proves each persona holds the privileges on the backing table (`bpf-roles`) and+fails closed when that table cannot be read — which also catches a flow that never activated.+Teardown plans nothing: measured, the flow (and with it the backing table and its privileges) is+deleted before the roles, and the run completes with 0 failures.+++**Not yet supported** (tracked follow-up): column-level (field) security and access teams / hierarchy+security.diff --git a/plugins/model-apps/references/localization.md b/plugins/model-apps/references/localization.mdindex fdd9da034..d4af80346 100644--- a/plugins/model-apps/references/localization.md+++ b/plugins/model-apps/references/localization.md@@ -2,9 +2,10 @@> **Scope: generated PAGE code, not Dataverse metadata.** This file covers translating the React> pages `/genpage` writes — translation dictionaries, RTL, and user-settings-driven number/date-> formatting. It does **not** cover Dataverse table, column or choice **labels**. Those are written-> in a single build-wide authoring language set by the spec-level `languageCode`; there is no-> per-table language and no multi-language labelling (see `app-spec-schema.md` → `languageCode`).+> formatting. It does **not** cover Dataverse table, column or choice **labels**. Those are set per+> field: a plain string uses the build-wide authoring language (`languageCode`), or write the field+> as an LCID map to label it in several languages at once. There is no per-table language+> (see `app-spec-schema.md` → `languageCode` and *Localized labels*).Read this only when the planner has detected multiple configured languages OR anynon-English language via `pac model list-languages`. English-only environmentsdiff --git a/plugins/model-apps/scripts/build-model-app.js b/plugins/model-apps/scripts/build-model-app.jsindex 84969195e..42a4aa40f 100644--- a/plugins/model-apps/scripts/build-model-app.js+++ b/plugins/model-apps/scripts/build-model-app.js@@ -20,7 +20,7 @@ const { stagePhasesOrResolve, PHASES, STAGES } = require('./lib/stages.js');// 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, readAliasedFlag, readJsonArg, emitResult, dataverseRequest, readProvisionedLanguages } = require('./lib/dataverse-auth.js');+const { parseArgs, readAliasedFlag, readJsonArg, emitResult, dataverseRequest, readProvisionedLanguages, preflightAuth } = require('./lib/dataverse-auth.js');const { openJournal } = require('./lib/build-journal.js');const { diffPhases, summarizeDiff } = require('./lib/phase-diff.js');const { annotateContentHashes } = require('./lib/content-hash.js');@@ -70,11 +70,12 @@ function makeSdk(env, spec, workspaceDir, languageCode) {const cleanup = () => {fs.rmSync(sdkTempDir, { recursive: true, force: true });};- // `httpClient` is returned so the caller can wire verify's role-privilege reader, which needs the- // raw client (and the org URL) to compose an absolute `EntityDefinitions(...)?$select=Privileges`- // request — the SDK's entity metadata projects `Privileges` away. Returning the SAME instance- // rather than constructing a second one keeps token acquisition and retry state shared.- return { sdk, provisionSdk, httpClient, cleanup };+ // Only the two SDK instances and the cleanup are returned. The raw `httpClient` used to come back+ // with them so the caller could wire verify's role-privilege reader — that read had no SDK surface+ // and had to compose an absolute `EntityDefinitions(...)?$select=Privileges` request itself. The+ // vendored bundle now exposes `getEntityPrivileges`, so the reader takes the SDK and the raw client+ // has no caller. Returning it anyway would advertise a bypass this file no longer takes.+ return { sdk, provisionSdk, cleanup };}// Turn engine progress events into a phase-grouped, status-marked build log:@@ -522,6 +523,22 @@ async function main() {// (#456), before the SDK is constructed and before any label is written. That halt is the point:// Dataverse would otherwise accept some labels under the wrong language and reject others// mid-build, phases away from the flag that caused it.+ // AB#6686427 — prove the ambient Azure CLI identity can reach this org BEFORE anything else on an+ // apply. Everything below (the language read, the destructive-apply safety probe, every phase)+ // authenticates through that identity, and when it is wrong they each fail in their own vocabulary+ // — "could not determine the organization's base language", "preflight safety check could not run"+ // — none of which names the actual cause. Dry runs skip it: they perform no writes and need no+ // identity. An INCONCLUSIVE verdict never blocks; see preflightAuth.+ if (opts.apply) {+ const auth = await preflightAuth(env);+ // A single, already-explained failure uses `error`, not `errors: [...]`. `emitResult` reserves+ // the array for a genuine PARTIAL failure and summarises it as a COUNT ("completed with 1+ // error(s); see stdout JSON") — which would replace a message written specifically to tell the+ // operator which identity to sign in as. `download-model-app.js` uses `error` for the identical+ // failure, so the array here also made two sibling CLIs report the same problem differently.+ if (!auth.ok && !auth.inconclusive) { emitResult(false, { ok: false, error: auth.error }); return; }+ if (auth.inconclusive) process.stderr.write(`⚠ ${auth.error}\n`);+ }const authoringLanguageCode = opts.apply? await resolveAuthoringLanguage({ envUrl: env, languageCode, spec, warn: (m) => process.stderr.write(`⚠ ${m}\n`) }): undefined;@@ -531,7 +548,7 @@ async function main() {opts.preResolvedLanguageCode = authoringLanguageCode;// Construct for both dry-run and apply: proves the vendored bundle + adapter wire up// (offline), and apply needs it. A spec validation error short-circuits before any write.- const { sdk, provisionSdk, httpClient, cleanup } = makeSdk(env, spec, workspaceDir, authoringLanguageCode);+ const { sdk, provisionSdk, cleanup } = makeSdk(env, spec, workspaceDir, authoringLanguageCode);// Durable build journal (apply runs only): a per-run record of steps + where a run halted,// written to <workspace>/build-log.jsonl. Resume = re-run the same command (idempotent).const journal = opts.apply@@ -585,13 +602,13 @@ async function main() {log: (m) => process.stderr.write(m + '\n'),warn: (m) => process.stderr.write(`⚠ ${m}\n`),sdk, provisionSdk, journal,- // `httpClient` + `envUrl` are threaded through so the role-privileges check actually RUNS- // here. verify-spec skips it unless BOTH `rolePrivileges` and `entityPrivileges` readers are- // present, and `entityPrivileges` needs the raw client and the org URL to compose an absolute- // EntityDefinitions request. Omitting them degraded silently: `--apply --verify` reported a- // clean PASS having never checked what any persona's role actually grants. Caught live —+ // The role-privileges check must actually RUN here. verify-spec skips it unless BOTH+ // `rolePrivileges` and `entityPrivileges` readers are present, and `entityPrivileges` used to+ // need the raw client plus the org URL — omitting them degraded silently, so `--apply --verify`+ // reported a clean PASS having never checked what any persona's role grants. Caught live:// standalone verify ran 10 checks against the same app where the build's inline verify ran 8.- verify: (s, verifyOpts) => verifySpec(s, readerFor(provisionSdk, appUniqueName(s), { genpageCli: makeGenpageCli(env), workspaceDir, httpClient, envUrl: env }), verifyOpts),+ // The reader now takes its privilege read off the SDK, so there is nothing left to forget.+ verify: (s, verifyOpts) => verifySpec(s, readerFor(provisionSdk, appUniqueName(s), { genpageCli: makeGenpageCli(env), workspaceDir }), verifyOpts),// The set of LCIDs this organization actually has. Injected so the pure lib stays free of// transport, and only consulted for an EXPLICIT `--language-code` / spec `languageCode`.provisionedLanguages: () => readProvisionedLanguages(env),diff --git a/plugins/model-apps/scripts/download-model-app.js b/plugins/model-apps/scripts/download-model-app.jsindex a5580801a..80e01bc44 100644--- a/plugins/model-apps/scripts/download-model-app.js+++ b/plugins/model-apps/scripts/download-model-app.js@@ -9,7 +9,7 @@const fs = require('node:fs');const path = require('node:path');-const { parseArgs, emitResult } = require('./lib/dataverse-auth.js');+const { parseArgs, emitResult, preflightAuth } = require('./lib/dataverse-auth.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');@@ -17,7 +17,7 @@ const { parseManifestBase64, manifestResourceName, reconcilePageIds } = require(const { reverseResolveNavIds } = require('./lib/pageref-resolver.js');const { fetchSitemap, sitemapGenPages } = require('./lib/sitemap-pages.js');const { isRestrictedSolution } = require('./lib/system-solutions.js');-const { isPlatformIconRef, webResourceNameFromRef, validateAppSpec, normalizeLanguageCode } = require('./lib/app-spec.js');+const { isPlatformIconRef, webResourceNameFromRef, validateAppSpec, normalizeLanguageCode, isLocalizedLabelMap } = require('./lib/app-spec.js');const { odataGuid } = require('./lib/ai-app-settings.js');// webresourcetype (int) -> app-spec web-resource type.@@ -189,6 +189,9 @@ const APP_COMPONENT_ENTITY_SOURCES = [{ componentType: 59, set: 'savedqueryvisualization', idField: 'savedqueryvisualizationid', entityField: 'primaryentitytypecode' },{ componentType: 60, set: 'systemform', idField: 'formid', entityField: 'objecttypecode' },];+// Dataverse entity set -> the App Spec artifact class it inventories, so a failed read is reported+// in the author's vocabulary ("forms could not be inventoried") rather than Dataverse's.+const INVENTORY_KIND_BY_SET = { savedquery: 'views', savedqueryvisualization: 'charts', systemform: 'forms' };// Dataverse honors `$top` as a HARD cap and omits `@odata.nextLink`, so this is the point past which// components of one type stop being inspected. Generous for a real app (a 70-table app has ~1000// views), and exceeded only with a warning.@@ -309,48 +312,77 @@ async function readAppShellSettings(sdk, appId) {}async function readDescriptionInventory(sdk, appId, solutionUniqueName) {- const inventory = { views: [], charts: [], forms: [], businessRules: [], globalChoices: [], roleRestrictedForms: [] };+ // `incomplete[]` records an artifact class whose read FAILED. Without it the whole app-component+ // block shared one broad catch, so a 403 on `systemform` left `forms: []` — indistinguishable from+ // an app with no forms, which is EXACTLY the reported bug (AB#6686423) reappearing inside the fix+ // for it. It is a sibling key for the same reason `roleRestrictedForms` is: only the five+ // whitelisted keys reach `app-spec.json`, so this informs the CLI without changing the spec shape.+ const inventory = { views: [], charts: [], forms: [], businessRules: [], globalChoices: [], roleRestrictedForms: [], incomplete: [] };+ const fail = (kind, err) => inventory.incomplete.push({ kind, reason: (err && err.message) ? String(err.message).slice(0, 200) : 'read failed' });try {const appRows = await sdk.queryRecords('appmodule', { select: ['appmoduleidunique'], filter: `appmoduleid eq ${appId}`, top: 1 });const appUniqueId = appRows && appRows[0] && appRows[0].appmoduleidunique;const parent = appUniqueId ? String(appUniqueId).replace(/[{}]/g, '') : null;if (parent) {+ // Caught PER ARTIFACT CLASS, not once around the loop: one failed query must not hide the+ // other two, and the caller has to be told WHICH class it cannot vouch for.for (const src of APP_COMPONENT_ENTITY_SOURCES) {- const rows = await sdk.queryRecords('appmodulecomponent', {- select: ['objectid', 'componenttype'],- filter: `_appmoduleidunique_value eq ${parent} and componenttype eq ${src.componentType}`,- top: COMPONENT_PAGE_CAP,- });- const ids = (rows || []).map((r) => r && r.objectid).filter(Boolean);- if (src.set === 'savedquery') {- inventory.views.push(...await rowsByIds(sdk, 'savedquery', 'savedqueryid', ids, ['savedqueryid', 'name', 'returnedtypecode', 'description'], (r) =>- withDescription({ id: r.savedqueryid, name: r.name, entity: r.returnedtypecode }, r.description)));- } else if (src.set === 'savedqueryvisualization') {- inventory.charts.push(...await rowsByIds(sdk, 'savedqueryvisualization', 'savedqueryvisualizationid', ids, ['savedqueryvisualizationid', 'name', 'primaryentitytypecode', 'description'], (r) =>- withDescription({ id: r.savedqueryvisualizationid, name: r.name, entity: r.primaryentitytypecode }, r.description)));- } else if (src.set === 'systemform') {- // `formxml` is pulled ONLY to detect a role restriction — it is never stored. A form's- // security roles live inside formxml as `<DisplayConditions>` (there is no- // systemform↔role relationship), and `forms[]` is not reconstructed by this download at- // all, so a restricted form would come back as one every role can see. That is a silent- // WIDENING of access on a cross-environment rebuild, which is why it is worth one extra- // column on a query this download already makes.- //- // The flag is kept OFF the form entries and on a sibling key, because- // `sanitizeDescriptionInventory` whitelists exactly five keys — so this reaches the- // download CLI for its warning without leaking a new field into `app-spec.json`.- const rawForms = await rowsByIds(sdk, 'systemform', 'formid', ids, ['formid', 'name', 'objecttypecode', 'description', 'formxml'], (r) => r);- for (const r of rawForms) {- if (!r || !r.objecttypecode || r.objecttypecode === 'none') continue;- inventory.forms.push(withDescription({ id: r.formid, name: r.name, entity: r.objecttypecode }, r.description));- if (isRoleRestrictedFormXml(r.formxml)) {- inventory.roleRestrictedForms.push({ name: r.name, entity: r.objecttypecode });+ try {+ const rows = await sdk.queryRecords('appmodulecomponent', {+ select: ['objectid', 'componenttype'],+ filter: `_appmoduleidunique_value eq ${parent} and componenttype eq ${src.componentType}`,+ top: COMPONENT_PAGE_CAP,+ });+ // A FULL page is indistinguishable from a truncated one, so treat it as truncated. `$top` is+ // a HARD cap and Dataverse omits `@odata.nextLink` when it is honoured, so there is no+ // signal to read afterwards. `appComponentEntities` warns about the same cap on its own+ // query, but THIS list feeds `notRoundTrippedSummary`, which reports a count — so a+ // truncated read there is not merely a missing table, it is a smaller number presented as+ // the whole truth. Marking the class incomplete makes the report say it cannot vouch for+ // the class instead. A false positive at exactly the cap costs one honest+ // "could not be inventoried" line; the alternative is a silent undercount.+ if ((rows || []).length >= COMPONENT_PAGE_CAP) {+ fail(INVENTORY_KIND_BY_SET[src.set] || src.set,+ new Error(`more than ${COMPONENT_PAGE_CAP} app components of this type; the list was truncated, so this class is incomplete`));+ }+ const ids = (rows || []).map((r) => r && r.objectid).filter(Boolean);+ if (src.set === 'savedquery') {+ inventory.views.push(...await rowsByIds(sdk, 'savedquery', 'savedqueryid', ids, ['savedqueryid', 'name', 'returnedtypecode', 'description'], (r) =>+ withDescription({ id: r.savedqueryid, name: r.name, entity: r.returnedtypecode }, r.description)));+ } else if (src.set === 'savedqueryvisualization') {+ inventory.charts.push(...await rowsByIds(sdk, 'savedqueryvisualization', 'savedqueryvisualizationid', ids, ['savedqueryvisualizationid', 'name', 'primaryentitytypecode', 'description'], (r) =>+ withDescription({ id: r.savedqueryvisualizationid, name: r.name, entity: r.primaryentitytypecode }, r.description)));+ } else if (src.set === 'systemform') {+ // `formxml` is pulled ONLY to detect a role restriction — it is never stored. A form's+ // security roles live inside formxml as `<DisplayConditions>` (there is no+ // systemform↔role relationship), and `forms[]` is not reconstructed by this download at+ // all, so a restricted form would come back as one every role can see. That is a silent+ // WIDENING of access on a cross-environment rebuild, which is why it is worth one extra+ // column on a query this download already makes.+ //+ // The flag is kept OFF the form entries and on a sibling key, because+ // `sanitizeDescriptionInventory` whitelists exactly five keys — so this reaches the+ // download CLI for its warning without leaking a new field into `app-spec.json`.+ const rawForms = await rowsByIds(sdk, 'systemform', 'formid', ids, ['formid', 'name', 'objecttypecode', 'description', 'formxml'], (r) => r);+ for (const r of rawForms) {+ if (!r || !r.objecttypecode || r.objecttypecode === 'none') continue;+ inventory.forms.push(withDescription({ id: r.formid, name: r.name, entity: r.objecttypecode }, r.description));+ if (isRoleRestrictedFormXml(r.formxml)) {+ inventory.roleRestrictedForms.push({ name: r.name, entity: r.objecttypecode });+ }}}+ } catch (err) {+ fail(INVENTORY_KIND_BY_SET[src.set] || src.set, err);}}+ } else {+ // No app-component parent means NONE of the three classes could be enumerated.+ for (const src of APP_COMPONENT_ENTITY_SOURCES) fail(INVENTORY_KIND_BY_SET[src.set] || src.set, new Error('the app\'s component list could not be read'));}- } catch { /* inventory is best-effort; structural download still carries the rebuildable app spec */ }+ } catch (err) {+ for (const src of APP_COMPONENT_ENTITY_SOURCES) fail(INVENTORY_KIND_BY_SET[src.set] || src.set, err);+ }try {if (solutionUniqueName && !isRestrictedSolution(solutionUniqueName)) {@@ -379,7 +411,15 @@ async function readDescriptionInventory(sdk, appId, solutionUniqueName) {}}}- } catch { /* business-rule descriptions are an inspection aid, not a rebuild prerequisite */ }+ } catch (err) {+ // FAIL CLOSED, not silent. This used to swallow the error as "an inspection aid, not a rebuild+ // prerequisite", which was defensible while nothing consumed the list. It is not any more:+ // `notRoundTrippedSummary` now reports business rules as a class that does not round-trip, and it+ // reports a class only when it has rows — so a 403 or 500 here leaves the list empty and the+ // report silently asserts the app HAS no business rules. "Unknown" and "none" must never look+ // alike in a report whose entire purpose is naming what was left behind.+ fail('businessRules', err);+ }try {// Global option sets are not app components, but their Description is another Dataverse Label. This@@ -392,11 +432,18 @@ async function readDescriptionInventory(sdk, appId, solutionUniqueName) {// and the catch below would swallow it — leaving this inventory permanently empty while the// download still reported success. Same trap, and same fix, as readEntityWithDescriptions.//- // `dataverse.get` RESOLVES on a non-2xx instead of throwing, so the status is checked explicitly.+ // `dataverse.get` RESOLVES on a non-2xx instead of throwing, so an unsuccessful or malformed+ // response has to be REJECTED explicitly. Coercing it to `[]` (the previous `|| []`) put the+ // failure beyond the catch's reach, so a metadata 403 was indistinguishable from an environment+ // with no global choices — and now that the report consumes this list, that reads as a positive+ // claim rather than an absence of information.const res = await sdk.dataverse.get('/GlobalOptionSetDefinitions?$select=Name,Description');- const rows = (res && res.status >= 200 && res.status < 300 && res.body && res.body.value) || [];- inventory.globalChoices.push(...rows.map((r) => withDescription({ name: r.Name }, r.Description)));- } catch { /* optional inventory */ }+ if (!res || res.status < 200 || res.status >= 300) throw new Error(`HTTP ${res && res.status}`);+ if (!res.body || !Array.isArray(res.body.value)) throw new Error('the response carried no value[] array');+ inventory.globalChoices.push(...res.body.value.map((r) => withDescription({ name: r.Name }, r.Description)));+ } catch (err) {+ fail('globalChoices', err);+ }return Object.fromEntries(Object.entries(inventory).filter(([, value]) => value.length));}@@ -545,6 +592,134 @@ function isRoleRestrictedFormXml(formxml) {return /<Role\b/i.test(block[0]);}+// Which of the app's DEPLOYED artifact classes this download does not reconstruct. AB#6686423.+//+// `forms[]`, `views[]` and `charts[]` are emitted EMPTY by hydrateSpec (see the note there for why+// each is blocked). The artifacts themselves are already captured — `descriptionInventory` in the+// written app-spec.json lists every one of them by id, name and table — but until this reporter+// existed nothing SAID they were missing from the rebuildable part of the spec. The reported+// symptom was exactly that: "it emitted empty forms and views ... with nothing reporting the loss".+//+// This is a REPORT, not a gate. Blocking would be wrong: every app has forms and views, so a+// failure here would break every download, and the omission is not destructive in the environment+// the app was downloaded from — a rebuild there does not delete artifacts the spec omits. The loss+// is real only when rebuilding into a DIFFERENT environment, and the message says so rather than+// stating a blanket "dropped".+//+// Returns null when there is nothing to report, so a caller can skip the warning entirely.+function notRoundTrippedSummary(inventory) {+ // Data-driven, and the set is derived from what `hydrateSpec` actually emits — NOT from what is+ // convenient to format. `hydrateSpec` returns `views: []`, `charts: []`, `forms: []`,+ // `commands: []` and no `businessRules`/`globalChoices` key at all, so all of these are absent+ // from the rebuildable spec. Reporting only forms/views/charts contradicted the report's own+ // purpose and left a business rule — a real cross-environment loss — silent.+ //+ // `entityScoped: false` for global choices because they are ORG-wide: grouping one under a table+ // would invent a relationship the platform does not have.+ //+ // ⚠ `commands[]` is missing from this list for a different reason, and it is a KNOWN gap rather+ // than an oversight: `readDescriptionInventory` never collects commands, so there is no count to+ // report. Adding the class here would emit a permanent "0 commands" that reads as "this app has+ // none" — the exact false reassurance the `incomplete` channel exists to avoid. Inventory them+ // first, then add the class.+ const CLASSES = [+ { key: 'forms', label: 'form', entityScoped: true },+ { key: 'views', label: 'view', entityScoped: true },+ { key: 'charts', label: 'chart', entityScoped: true },+ { key: 'businessRules', label: 'business rule', entityScoped: true },+ { key: 'globalChoices', label: 'global choice', entityScoped: false },+ ];+ const classes = [];+ const orgScoped = []; // [{ key, label, names: [] }] — classes with no owning table+ const byEntity = new Map(); // table logical -> { <classKey>: [names] }+ const blankEntityRow = () => Object.fromEntries(CLASSES.filter((c) => c.entityScoped).map((c) => [c.key, []]));+ for (const { key, label, entityScoped } of CLASSES) {+ const rows = (inventory && Array.isArray(inventory[key]) ? inventory[key] : []).filter((r) => r && r.name);+ if (!rows.length) continue;+ classes.push({ kind: key, count: rows.length, label });+ if (!entityScoped) {+ orgScoped.push({ kind: key, label, names: rows.map((r) => String(r.name)).sort((a, b) => a.localeCompare(b)) });+ continue;+ }+ for (const r of rows) {+ const entity = String(r.entity || 'unknown').toLowerCase();+ if (!byEntity.has(entity)) byEntity.set(entity, blankEntityRow());+ byEntity.get(entity)[key].push(r.name);+ }+ }+ // A class whose read FAILED is reported too, and is the reason this cannot simply return null on an+ // empty inventory: "no forms were found" and "the forms query returned 403" look identical from+ // here, and treating the second as the first is precisely the silent-loss bug being fixed. An+ // UNKNOWN class is worse than a known-omitted one, so it is surfaced even when nothing was read.+ const incomplete = (inventory && Array.isArray(inventory.incomplete) ? inventory.incomplete : [])+ .filter((i) => i && i.kind)+ .map((i) => ({ kind: i.kind, reason: i.reason || 'read failed' }))+ .sort((a, b) => a.kind.localeCompare(b.kind));+ if (!classes.length && !incomplete.length) return null;+ // Sorted at EVERY level, not just the table one. The rows arrive from `queryRecords`, i.e. in+ // whatever order Dataverse returned them, which carries no ordering guarantee — so two downloads+ // of an unchanged app could emit the same artifacts in a different order. This block is written+ // into the operator's output and compared between runs, so an unstable order reads as a change+ // that did not happen, which is the opposite of the point: the report exists to make a real+ // difference visible. `classes` is already deterministic (built from the fixed CLASSES list).+ const entityKeys = CLASSES.filter((c) => c.entityScoped).map((c) => c.key);+ return {+ classes,+ total: classes.reduce((n, c) => n + c.count, 0),+ entities: [...byEntity.entries()]+ .sort(([a], [b]) => a.localeCompare(b))+ .map(([entity, v]) => ({+ entity,+ ...Object.fromEntries(entityKeys.map((k) => [k, [...(v[k] || [])].sort((a, b) => String(a).localeCompare(String(b)))])),+ })),+ ...(orgScoped.length ? { orgScoped } : {}),+ ...(incomplete.length ? { incomplete } : {}),+ };+}++// Render `notRoundTrippedSummary` as the operator-facing warning. Kept separate from the computation+// so the wording is testable without a download, and so the same summary can be emitted as JSON.+function notRoundTrippedWarning(summary) {+ if (!summary) return '';+ const lines = [];+ if (summary.classes.length) {+ const counts = summary.classes.map((c) => `${c.count} ${c.label}${c.count === 1 ? '' : 's'}`).join(', ');+ // The class list is rendered from the summary rather than hardcoded. It used to read+ // "forms[], views[] or charts[]" regardless of what was actually reported, so once business+ // rules and global choices joined the inventory the sentence named the wrong things — a report+ // about silent loss quietly misdescribing its own contents.+ const names = summary.classes.map((c) => (c.kind === 'globalChoices' ? 'globalChoices[]' : `${c.kind}[]`)).join(', ');+ const tables = summary.entities.length;+ lines.push(+ `NOTE: this download does not reconstruct ${names} — ${counts}${tables ? ` on ${tables} table(s)` : ''} are absent from the rebuildable spec.`,+ ' They are NOT lost: every one is listed under `descriptionInventory` in app-spec.json, and they remain on the deployed app.',+ ' Rebuilding into THIS environment leaves them untouched. Rebuilding into a DIFFERENT environment will NOT recreate them —',+ ` re-declare the ones you need in ${names}, or copy them with a solution export.`,+ );+ for (const e of summary.entities) {+ const parts = [];+ for (const c of summary.classes) {+ const list = e[c.kind];+ if (Array.isArray(list) && list.length) parts.push(`${c.kind}: ${list.join(', ')}`);+ }+ if (parts.length) lines.push(` ${e.entity} — ${parts.join('; ')}`);+ }+ // Org-scoped classes are listed separately and WITHOUT a table, because they do not belong to+ // one; filing a global choice under a table would assert a relationship Dataverse does not have.+ for (const o of summary.orgScoped || []) {+ lines.push(` (environment-wide) ${o.kind}: ${o.names.join(', ')}`);+ }+ }+ if (summary.incomplete && summary.incomplete.length) {+ lines.push(+ `WARNING: ${summary.incomplete.length} artifact class(es) could NOT be inventoried, so this download cannot say what it left behind:`,+ );+ for (const i of summary.incomplete) lines.push(` ${i.kind} — ${i.reason}`);+ lines.push(' Treat an empty list for those classes as UNKNOWN, not as "the app has none".');+ }+ return `${lines.join('\n')}\n`;+}+// Columns whose type could not be substantiated, so a `download -> rebuild into a fresh org` round// trip does not silently create them as Text. `type` is absent for a Choice/MultiChoice (above), or// for an attribute whose metadata carried no `attributeType` at all — an attribute with a type that@@ -592,17 +767,51 @@ function entityFromMetadata(meta, logical) {const specType = TYPES_NEEDING_COMPANION_DATA.has(mapped) ? undefined : mapped;return withDescription({schemaName,- ...(a && (a.displayName || a.DisplayName) ? { displayName: descriptionFromDataverse(a.displayName || a.DisplayName) || a.displayName || a.DisplayName } : {}),+ // A column labelled in several languages round-trips as an LCID map; one language stays a+ // plain string (AB#6686428). Resolution order, and every step must yield a STRING or a map —+ // never a raw Dataverse Label object:+ // 1. the RAW `DisplayName` Label merged in by readEntityWithDescriptions (the only source+ // that carries every language),+ // 2. the SDK's own already-flattened `displayName` string,+ // 3. a single-language Label unwrapped by descriptionFromDataverse.+ //+ // Step 2 is not optional tidiness. LIVE-MEASURED: a synthetic lookup `*name` column such as+ // `cfo_customeridname` carries `{"LocalizedLabels":[],"UserLocalizedLabel":null}` — a wholly+ // EMPTY Label. `labelFromDataverse` correctly returns undefined for it, and an `|| a.DisplayName`+ // tail would then emit that raw object as the column's displayName, producing a spec that fails+ // its own validation with "'LocalizedLabels' is not an LCID". Omitting the label entirely is the+ // right answer: Dataverse has none either.+ ...(columnDisplayName(a) !== undefined ? { displayName: columnDisplayName(a) } : {}),...(specType ? { type: specType } : {}),}, a && (a.description !== undefined ? a.description : a.Description));}).filter((c) => c.schemaName);+ // Table label + plural. When the table carries more than one language, BOTH must round-trip and+ // `pluralName` becomes required (validateAppSpec refuses to derive a plural from a label map), so+ // the plural is emitted whenever the display name is localized.+ const displayName = labelFromDataverse(meta && meta.DisplayName);+ const pluralName = labelFromDataverse(meta && meta.DisplayCollectionName);+ // The primary column's own label. It is EXCLUDED from `columns[]` (it is declared separately as+ // `primaryAttribute`), so its label has to be read from the un-filtered attribute list here —+ // otherwise a table whose primary column is called "Order Title" / "Título del pedido" downloads+ // as the hardcoded "Name", and a fresh-environment rebuild loses both the real label and its+ // translations. `'Name'` remains the fallback for a metadata read that carried no label at all.+ const primaryAttr = primaryLower ? attrs.find((a) => String((a && (a.logicalName || a.LogicalName || a.schemaName || a.SchemaName)) || '').toLowerCase() === primaryLower) : null;+ const primaryLabel = columnDisplayName(primaryAttr);return {schemaName: (meta && (meta.schemaName || meta.logicalName)) || logical,- displayName: (meta && meta.displayName) || logical,+ displayName: displayName !== undefined ? displayName : ((meta && meta.displayName) || logical),+ // Emitted when EITHER label is localized, not only when the singular is. `validateAppSpec`+ // requires `pluralName` beside a localized `displayName`, which is why the singular's shape is+ // checked — but a table can carry a single-language `DisplayName` and a multi-language+ // `DisplayCollectionName` (the two are independent in Dataverse, and an unprovisioned language is+ // dropped per-label on read). Keying only off the singular silently discarded those plural+ // translations and a rebuild then derived an English plural. Two PLAIN labels still omit it: a+ // plain plural is derivable and emitting it would add noise to every download.+ ...((isLocalizedLabelMap(displayName) || isLocalizedLabelMap(pluralName)) && pluralName !== undefined ? { pluralName } : {}),...(descriptionFromDataverse(meta && (meta.description !== undefined ? meta.description : meta.Description)) ? { description: descriptionFromDataverse(meta && (meta.description !== undefined ? meta.description : meta.Description)) } : {}),// Never synthesized: a fabricated attribute name yields a spec that references a column Dataverse// does not have, which is exactly the bug this fixes.- primaryAttribute: primary ? { schemaName: primary, displayName: 'Name' } : null,+ primaryAttribute: primary ? { schemaName: primary, displayName: primaryLabel !== undefined ? primaryLabel : 'Name' } : null,columns,// Flag every recovered table as pre-existing so a teardown of THIS downloaded spec never deletes the// table (+ its data). Download cannot prove which tables the app CREATED vs merely REFERENCED, and@@ -638,26 +847,102 @@ async function readEntityWithDescriptions(sdk, logical) {// reintroduce exactly the silence this replaces.const entityPath = `/${metadataEntityPath(logical)}`;try {- const res = await sdk.dataverse.get(`${entityPath}?$select=LogicalName,Description`);- if (res && res.status >= 200 && res.status < 300 && res.body) meta.Description = res.body.Description;- } catch { /* description best-effort — never sink an otherwise usable download */ }+ // DisplayName / DisplayCollectionName are read alongside Description so a table labelled in more+ // than one language round-trips (AB#6686428). The SDK's own `fetchEntityMetadata` projection+ // flattens `displayName` to ONE string, which is enough for identity but silently loses every+ // other language — a rebuild from such a spec would recreate the table English-only.+ const res = await sdk.dataverse.get(`${entityPath}?$select=LogicalName,Description,DisplayName,DisplayCollectionName`);+ if (res && res.status >= 200 && res.status < 300 && res.body) {+ meta.Description = res.body.Description;+ meta.DisplayName = res.body.DisplayName;+ meta.DisplayCollectionName = res.body.DisplayCollectionName;+ } else {+ // A non-2xx is NOT "this table has no extra languages" — it is "we could not look". Recorded so+ // the caller can say so; see the catch below for why silence here is the wrong default.+ meta.labelReadFailed = `HTTP ${res && res.status}`;+ }+ } catch (err) {+ meta.labelReadFailed = (err && err.message) ? String(err.message).slice(0, 200) : 'read failed';+ }try {// Merge onto the SDK's attribute list rather than replacing it: `fetchEntityMetadata` supplies// `targets` (lookup target tables) and `attributeType`, which this projection does not, and// entityFromMetadata/other callers rely on them.- const res = await sdk.dataverse.get(`${entityPath}/Attributes?$select=LogicalName,Description`);- const rows = (res && res.status >= 200 && res.status < 300 && res.body && res.body.value) || null;- if (Array.isArray(rows)) {- const byLogical = new Map(rows.filter((r) => r && r.LogicalName).map((r) => [String(r.LogicalName).toLowerCase(), r.Description]));- meta.attributes = (meta.attributes || []).map((a) => {- const key = String((a && (a.logicalName || a.LogicalName)) || '').toLowerCase();- return byLogical.has(key) ? { ...a, Description: byLogical.get(key) } : a;- });+ //+ // This read carries the SAME weight as the table-level one above: it is the only source of+ // multi-language labels for every non-primary COLUMN and for the primary attribute. Treating it+ // as "column descriptions are best-effort" was right when descriptions were all it fetched, and+ // became wrong the moment labels rode along — a 403 here returns a spec whose columns are+ // single-language, with nothing saying so. Same recording, same reason.+ const res = await sdk.dataverse.get(`${entityPath}/Attributes?$select=LogicalName,Description,DisplayName`);+ if (!res || res.status < 200 || res.status >= 300) throw new Error(`HTTP ${res && res.status}`);+ if (!res.body || !Array.isArray(res.body.value)) throw new Error('the response carried no value[] array');+ const rows = res.body.value;+ const byLogical = new Map(rows.filter((r) => r && r.LogicalName).map((r) => [String(r.LogicalName).toLowerCase(), r]));+ meta.attributes = (meta.attributes || []).map((a) => {+ const key = String((a && (a.logicalName || a.LogicalName)) || '').toLowerCase();+ const row = byLogical.get(key);+ return row ? { ...a, Description: row.Description, DisplayName: row.DisplayName } : a;+ });+ } catch (err) {+ // Recorded, not swallowed — and it does NOT overwrite a table-level failure already recorded+ // above, because the first reason is the more useful one to show and both describe the same+ // outcome for the operator: this table came back single-language.+ if (!meta.labelReadFailed) {+ meta.labelReadFailed = (err && err.message) ? String(err.message).slice(0, 200) : 'read failed';}- } catch { /* column descriptions are best-effort */ }+ }return meta;}+// Reconstruct an App Spec label from a Dataverse Label, preserving EVERY language. AB#6686428.+//+// Shape (see the Label reference linked in hydrate-spec.js):+// { "LocalizedLabels": [{ "Label": "Baseline", "LanguageCode": 1033 },+// { "Label": "Línea base", "LanguageCode": 3082 }],+// "UserLocalizedLabel": { "Label": "Baseline", "LanguageCode": 1033 } }+//+// Returns a plain STRING when the table is labelled in one language, and an LCID map only when there+// are genuinely two or more. That asymmetry is deliberate: emitting `{ "1033": "Baseline" }` for+// every single-language table would change the shape of every spec this tool has ever written, for+// no gain, and would make every download diff noisy. Returns undefined when there is nothing usable,+// so a caller can fall back to the SDK's flattened `displayName` rather than write an empty label.+//+// ⚠ KNOWN LIMITATION, accepted rather than overlooked: the LCID of a SINGLE label is not preserved.+// A table labelled only in 3082 downloads as a plain string, and a rebuild applies it at the target+// build's resolved language — correct when rebuilding into the same organization (its base language+// is the same), wrong when rebuilding into one with a different base, where Spanish text is stored+// as an English label. Fixing it means threading the org's base language into this pure function and+// emitting a one-entry map whenever the two differ, which changes the emitted shape for a case that+// is currently indistinguishable from the common one. `download` also deliberately never pins the+// org's LCID into the spec (that would make the spec non-portable), so there is no existing signal+// to key off. Pin `languageCode` in the spec before a cross-organization rebuild.+function labelFromDataverse(value) {+ if (!value || typeof value !== 'object') return undefined;+ const rows = Array.isArray(value.LocalizedLabels) ? value.LocalizedLabels : [];+ const usable = rows.filter((l) => l && typeof l.Label === 'string' && l.Label.trim() && Number.isInteger(Number(l.LanguageCode)) && Number(l.LanguageCode) > 0);+ if (!usable.length) return undefined;+ if (usable.length === 1) return usable[0].Label;+ const out = {};+ // NOT sorted, deliberately: V8 orders integer-like object keys ASCENDING regardless of insertion+ // order, so `JSON.stringify` of this map is already deterministic and two downloads of the same+ // table produce byte-identical output. A sort here would look like it earned that guarantee and+ // could never be shown to matter — verified: inserting 3082 then 1033 yields keys ["1033","3082"].+ for (const l of usable) out[String(Number(l.LanguageCode))] = l.Label;+ return out;+}++// The App Spec `displayName` for one downloaded column, or undefined when Dataverse has no usable+// label. GUARANTEES a string or an LCID map — never a raw Dataverse Label object, which would emit a+// spec that fails its own validation. See the call site for the live-measured shape that motivated it.+function columnDisplayName(a) {+ const localized = labelFromDataverse(a && a.DisplayName);+ if (localized !== undefined) return localized;+ // The SDK's `fetchEntityMetadata` projection already flattens this one to a string.+ if (typeof (a && a.displayName) === 'string' && a.displayName.trim()) return a.displayName;+ return descriptionFromDataverse(a && a.DisplayName);+}+// Image webresourcetypes (png/jpg/gif/ico/svg) — an icon reference must resolve to one of these to be// re-declared. See WR_TYPE. Guards against re-declaring a non-image WR that a path happens to name.const IMAGE_WR_TYPES = new Set([5, 6, 7, 10, 11]);@@ -969,6 +1254,10 @@ async function runDownload({ sdk, genpageCli, outDir, appId, appUnique, allowLosconst noPrimaryName = []; // sitemap tables — a hard failure (the user asked for these)const droppedComponents = []; // component-only tables — dropped with a warning (best-effort input)const metadataErrors = new Map(); // logical -> error message (the read itself failed)+ // Tables whose LABEL read failed. Distinct from `metadataErrors`: the table itself was recovered+ // and the spec is usable, but only the SDK's flattened single-language `displayName` survived, so+ // a multi-language table silently downloads as English-only. Reported rather than swallowed.+ const labelReadFailures = new Map(); // logical -> reasonfor (const logical of allLogicals) {let e;// A metadata READ failure is not the same as metadata that reports no primary name, and it must@@ -977,7 +1266,9 @@ async function runDownload({ sdk, genpageCli, outDir, appId, appUnique, allowLos// the confusing downstream error the explicit branch below exists to avoid. Bucket it by origin// exactly like the no-primary-name case, so the user is told the table AND the reason.try {- e = entityFromMetadata(await readEntityWithDescriptions(sdk, logical), logical);+ const meta = await readEntityWithDescriptions(sdk, logical);+ if (meta && meta.labelReadFailed) labelReadFailures.set(logical, meta.labelReadFailed);+ e = entityFromMetadata(meta, logical);} catch (err) {metadataErrors.set(logical, (err && err.message) || String(err));(sitemapSet.has(logical) ? noPrimaryName : droppedComponents).push(logical);@@ -1012,6 +1303,15 @@ async function runDownload({ sdk, genpageCli, outDir, appId, appUnique, allowLosif (droppedComponents.length) {process.stderr.write(`WARNING: ${droppedComponents.length} app component table(s) were omitted from the spec because Dataverse reported no primary-name column (${withReason(droppedComponents)}) — they are NOT in the app's navigation, and the deployed app still references them; declare them by hand if a rebuild needs them.\n`);}+ // AB#6686428: the label read is the ONLY source of multi-language labels. When it fails the table+ // is still recovered, so the download succeeds and the spec looks complete — but it carries the+ // SDK's flattened single-language `displayName` and every other language is gone. Silently+ // degrading there is the same shape as the bug this feature fixes, so say so. Not a gate: an+ // English-only spec is still a usable spec, and failing a read-only command over it would be worse.+ if (labelReadFailures.size) {+ const detail = [...labelReadFailures.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([l, r]) => `${l} (${r})`).join(', ');+ process.stderr.write(`WARNING: a label read failed for ${labelReadFailures.size} table(s) (${detail}). The table AND COLUMN labels for those tables fall back to ONE language, so anything labelled in several languages downloads as single-language and a rebuild would recreate it that way. Re-run the download to recover the other languages before rebuilding into a different environment.\n`);+ }// A column whose App Spec type could not be substantiated — a Choice/MultiChoice (whose options// this download does not read) or an attribute type the spec cannot declare. Rebuilding into an// org that ALREADY has the table reuses the column and this is inert; rebuilding into a FRESH org@@ -1121,9 +1421,15 @@ async function runDownload({ sdk, genpageCli, outDir, appId, appUnique, allowLosif (restricted.length) {process.stderr.write(`WARNING: ${restricted.length} form(s) are restricted to specific security roles (${restricted.map((f) => `${f.entity}.${f.name}`).join(', ')}). This download does not reconstruct forms[], so that restriction is NOT carried into the spec — rebuilding into a fresh environment would recreate them visible to EVERY role. Re-declare it with forms[].securityRoles before a cross-environment rebuild.\n`);}+ // AB#6686423: name the artifact classes this download leaves out of the rebuildable spec. The+ // reported failure was not that they are omitted — that is a documented limitation — but that+ // NOTHING said so, so a second session reading the spec could not tell "this app has no views"+ // from "this download does not carry views".+ const notRoundTripped = notRoundTrippedSummary(capturedInventory);+ if (notRoundTripped) process.stderr.write(notRoundTrippedWarning(notRoundTripped));const droppedSubareas = typeof spec.droppedSubareas === 'number' ? spec.droppedSubareas : droppedSubareaCount(app, spec);const droppedSubareaDetails = Array.isArray(spec.droppedSubareaDetails) ? spec.droppedSubareaDetails : [];- return { ok: true, spec, pages, entities, webResources, droppedSubareas, droppedSubareaDetails, dashboardReconstructionError, dashboardWarnings };+ return { ok: true, spec, pages, entities, webResources, droppedSubareas, droppedSubareaDetails, dashboardReconstructionError, dashboardWarnings, notRoundTripped };}async function main() {@@ -1141,6 +1447,18 @@ async function main() {}const outDir = path.resolve(outArg || '.');fs.mkdirSync(outDir, { recursive: true });+ // AB#6686427 — prove the ambient Azure CLI identity can actually reach this org BEFORE any read.+ // Every read below is best-effort by design (a tenant without a setting definition, or a caller+ // without access to one artifact class, must still produce a usable spec), so an auth failure does+ // 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; }+ // 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 = makeProvision(env, path.join(outDir, '.maker-workspace'));const resolved = await resolveAppId(sdk, appArg);if (resolved.error) { emitResult(false, { ok: false, error: resolved.error }); return; }@@ -1159,7 +1477,7 @@ async function main() {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 } = result;+ const { spec, pages, entities, webResources, droppedSubareas, droppedSubareaDetails, dashboardReconstructionError, dashboardWarnings, notRoundTripped } = result;if (droppedSubareas > 0 || dashboardReconstructionError) {const droppedList = (droppedSubareaDetails || []).map((d) => `${d.type}${d.id ? `:${d.id}` : ''}${d.title ? ` (${d.title})` : ''}`)@@ -1201,7 +1519,7 @@ async function main() {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, ...(defaulted.length ? { directEntryDefaulted: defaulted } : {}) });+ emitResult(true, { ok: true, spec: specPath, pages: pages.length, entities: entities.length, webResources: webResources.length, droppedSubareas, ...(notRoundTripped ? { notRoundTripped } : {}), ...(defaulted.length ? { directEntryDefaulted: defaulted } : {}) });}// Carry an AUTHOR-PINNED `languageCode` across a download, and only from the spec already on disk.@@ -1242,4 +1560,4 @@ if (require.main === module) {main().catch((err) => emitResult(false, err));}-module.exports = { untypedColumnNames, isRoleRestrictedFormXml, resolveAppId, collectSitemap, appComponentEntities, parseDownloadedPages, assignPageKeys, missingDownloads, entityFromMetadata, readEntityWithDescriptions, readDescriptionInventory, readAppShellSettings, iconWebResources, readDashboards, droppedSubareaCount, recoverAppSolution, runDownload, preserveAuthoredLanguageCode };+module.exports = { untypedColumnNames, isRoleRestrictedFormXml, notRoundTrippedSummary, notRoundTrippedWarning, labelFromDataverse, columnDisplayName, resolveAppId, collectSitemap, appComponentEntities, parseDownloadedPages, assignPageKeys, missingDownloads, entityFromMetadata, readEntityWithDescriptions, readDescriptionInventory, readAppShellSettings, iconWebResources, readDashboards, droppedSubareaCount, recoverAppSolution, runDownload, preserveAuthoredLanguageCode };diff --git a/plugins/model-apps/scripts/lib/ai-app-settings.js b/plugins/model-apps/scripts/lib/ai-app-settings.jsindex 0ae0de8e0..e0e64a840 100644--- a/plugins/model-apps/scripts/lib/ai-app-settings.js+++ b/plugins/model-apps/scripts/lib/ai-app-settings.js@@ -69,13 +69,35 @@ const AI_FEATURE_MAX_VALUE = 1000000;// than a sensible default.const DEFAULT_APP_FEATURES = { formFill: true, nlSearch: true, nlChart: true, m365: false };+/**+ * Does this spec opt into AI at all?+ *+ * The ONE predicate the build, the verifier and teardown must all use. `selectSummaryTables` does+ * NOT decide this: handed a spec with no `ai` block it reads `summaries` as `{}`, which means+ * "default auto", and returns every entity carrying a descriptive column. That is correct for what+ * it is — a candidate selector — but it is not an opt-in test, and treating it as one has now gone+ * wrong twice in two different files:+ * * teardown gated on `spec.ai.summaries` and planned NOTHING for a spec carrying only+ * `ai.appFeatures`, so the row summary the build created blocked the table delete;+ * * verify gated on nothing at all, so a spec with NO `ai` block failed with+ * "ai.summaries requests a row summary for 'x'" for a summary nobody requested and the build+ * never created — a false FAIL on the build's own exit code, for most specs.+ * Both were the same mistake in opposite directions. Asking here, once, is what stops a third.+ *+ * `null` is treated as opting out alongside `undefined`: it is what a JSON caller produces for+ * "no AI", and the build has always read it that way.+ */+function specOptsIntoAi(spec) {+ return !!spec && spec.ai !== undefined && spec.ai !== null;+}+/*** The EXACT flag set the build writes for a spec — and therefore the exact set verify must* reconcile. Both callers MUST go through this; that equality is the whole point of the module.* Returns null when the spec opts out of `ai` entirely (no features are written, none are checked).*/function resolveAiFlags(spec) {- if (!spec || spec.ai === undefined || spec.ai === null) return null;+ if (!specOptsIntoAi(spec)) return null;const flags = Object.assign({}, DEFAULT_APP_FEATURES, spec.ai.appFeatures || {});// Drop keys the SDK has no setting for: it ignores them, so verifying them would invent a// permanent failure for a spec the validator already reports on.@@ -293,6 +315,7 @@ module.exports = {AI_FEATURE_KEYS,AI_FEATURE_MAX_VALUE,DEFAULT_APP_FEATURES,+ specOptsIntoAi,resolveAiFlags,featureWantValue,sameSettingValue,diff --git a/plugins/model-apps/scripts/lib/ai-prompt.js b/plugins/model-apps/scripts/lib/ai-prompt.jsindex e569c7b8a..63a3d52ec 100644--- a/plugins/model-apps/scripts/lib/ai-prompt.js+++ b/plugins/model-apps/scripts/lib/ai-prompt.js@@ -1,6 +1,7 @@'use strict';// Pure helper: build a PromptSpec for a single entity's AI summary.// No Dataverse / network access — operates entirely on the spec entity object.+const { labelText } = require('./app-spec.js');// Column types preferred over Memo for summary columns.const PREFERRED_TYPES = new Set([@@ -19,6 +20,9 @@ const EXCLUDED_TYPES = new Set(['File', 'Image', 'Lookup', 'AutoNumber']);*/function buildPromptSpec(entity, opts) {const override = (opts && opts.override) || null;+ // Resolve localized labels in the SPEC's authoring language. Without it a Spanish-authoring spec+ // generated an English prompt, because labelText falls back to 1033 when given no language.+ const lang = opts && opts.spec && opts.spec.languageCode;const entityLogicalName = entity.schemaName.toLowerCase();// The record's primary KEY attribute (its id) — e.g. new_ohproject -> new_ohprojectid. The@@ -35,7 +39,7 @@ function buildPromptSpec(entity, opts) {columns = override.columns.map((s) => colMap.get(s.toLowerCase())).filter(Boolean)- .map((c) => ({ logical: c.schemaName.toLowerCase(), display: c.displayName || c.schemaName }));+ .map((c) => ({ logical: c.schemaName.toLowerCase(), display: labelText(c.displayName, lang) || c.schemaName }));} else {// Auto-select: exclude PK, AutoNumber, File, Image, Lookup.const eligible = (entity.columns || []).filter((c) => {@@ -53,7 +57,7 @@ function buildPromptSpec(entity, opts) {const selected = [...preferred, ...memos.slice(0, 1)].slice(0, 6);columns = selected.map((c) => ({logical: c.schemaName.toLowerCase(),- display: c.displayName || c.schemaName,+ display: labelText(c.displayName, lang) || c.schemaName,}));}@@ -62,7 +66,7 @@ function buildPromptSpec(entity, opts) {if (override && override.instruction && override.instruction.trim().length > 0) {instruction = override.instruction;} else {- const recordType = entity.displayName || entity.schemaName;+ const recordType = labelText(entity.displayName, lang) || entity.schemaName;instruction = `Summarize this ${recordType} as a short paragraph highlighting the most important details and any recent activity.`;}diff --git a/plugins/model-apps/scripts/lib/app-preview.js b/plugins/model-apps/scripts/lib/app-preview.jsindex 80ada4e5a..0a6eb41a3 100644--- a/plugins/model-apps/scripts/lib/app-preview.js+++ b/plugins/model-apps/scripts/lib/app-preview.js@@ -4,7 +4,8 @@// form; this renders the whole app — a data-model summary, the appShell sitemap tree, views/charts,// per-form wireframes (reusing form-preview.js), page-INTENTS (purpose/data-sources/navigation), and// the page design contract. Pure (no I/O); the CLI wrapper is preview-app.js. See design §12.-const { renderFormWireframe } = require('./form-preview.js');+const { renderFormWireframe } = require('./form-preview.js');+const { labelText } = require('./app-spec.js');const lc = (s) => String(s || '').toLowerCase();const h = (title) => `\n=== ${title} ===`;@@ -13,7 +14,7 @@ function dataModelSection(spec) {const out = [h('Data model')];if (!(spec.entities || []).length) { out.push(' (no tables)'); }for (const e of spec.entities || []) {- out.push(` • ${e.displayName || e.schemaName} [${lc(e.schemaName)}]${e.hasNotes ? ' (notes/timeline)' : ''}`);+ out.push(` • ${labelText(e.displayName, spec && spec.languageCode) || e.schemaName} [${lc(e.schemaName)}]${e.hasNotes ? ' (notes/timeline)' : ''}`);out.push(` primary: ${e.primaryAttribute ? e.primaryAttribute.schemaName : '(none)'}`);const cols = (e.columns || []).map((c) => `${c.schemaName} (${c.type || 'Text'})`);if (cols.length) out.push(` columns: ${cols.join(', ')}`);diff --git a/plugins/model-apps/scripts/lib/app-spec-doc.js b/plugins/model-apps/scripts/lib/app-spec-doc.jsindex 93ec3d654..520a9bbf1 100644--- a/plugins/model-apps/scripts/lib/app-spec-doc.js+++ b/plugins/model-apps/scripts/lib/app-spec-doc.js@@ -16,6 +16,7 @@// PURE: no I/O. The CLI wrapper (scripts/write-app-spec-doc.js) owns writing the file.const lc = (s) => String(s || '').toLowerCase();+const { labelText } = require('./app-spec.js');// Every collection read below goes through these. The renderer runs against WORK-IN-PROGRESS specs// during authoring — a half-typed `jobs: "x"`, a null entry left by an edit, a `dataSources` written@@ -106,7 +107,7 @@ function dataModel(spec) {if (!entities.length) { out.push('_No tables._', ''); return out; }for (const e of entities) {const reused = e.existing ? ' _(existing table — reused, not created)_' : '';- out.push(`### ${text(e.displayName, e.schemaName)} \`${lc(e.schemaName)}\`${reused}`, '');+ out.push(`### ${text(labelText(e.displayName, spec && spec.languageCode), e.schemaName)} \`${lc(e.schemaName)}\`${reused}`, '');if (e.description) out.push(text(e.description), '');// The nav icon is something the user APPROVES, and at plan time the SVG may not exist yet — so// show what the glyph will DEPICT, not the web-resource name (which tells a reviewer nothing).@@ -116,13 +117,16 @@ function dataModel(spec) {}out.push('| Column | Type | Notes |', '|---|---|---|');const pa = e.primaryAttribute && typeof e.primaryAttribute === 'object' ? e.primaryAttribute : null;- if (pa) out.push(`| ${cell(pa.displayName || pa.schemaName)} | ${cell(pa.type, 'Text')} | primary name${pa.autoNumberFormat ? `, auto-number \`${cell(pa.autoNumberFormat)}\`` : ''} |`);+ if (pa) out.push(`| ${cell(labelText(pa.displayName, spec && spec.languageCode) || pa.schemaName)} | ${cell(pa.type, 'Text')} | primary name${pa.autoNumberFormat ? `, auto-number \`${cell(pa.autoNumberFormat)}\`` : ''} |`);for (const c of objs(e.columns)) {const notes = [];if (c.required) notes.push('required');- if (c.options) notes.push(`choices: ${arr(c.options).map((o) => cell(o && typeof o === 'object' ? o.label : o)).join(', ')}`);+ // `o.label` is the legacy object-option shape. A LOCALIZED option is also an object but has no+ // `label` key, so the legacy branch rendered every one as an empty cell — resolve through+ // labelText first and only then fall back.+ if (c.options) notes.push(`choices: ${arr(c.options).map((o) => cell(labelText(o, spec && spec.languageCode) || (o && typeof o === 'object' ? o.label : o))).join(', ')}`);if (c.globalChoice) notes.push(`global choice \`${cell(c.globalChoice)}\``);- out.push(`| ${cell(c.displayName || c.schemaName)} | ${cell(c.type, 'Text')} | ${notes.join('; ') || '—'} |`);+ out.push(`| ${cell(labelText(c.displayName, spec && spec.languageCode) || c.schemaName)} | ${cell(c.type, 'Text')} | ${notes.join('; ') || '—'} |`);}out.push('');if (e.hasNotes) out.push('Notes/timeline enabled.', '');diff --git a/plugins/model-apps/scripts/lib/app-spec.js b/plugins/model-apps/scripts/lib/app-spec.jsindex 622085f69..5fb357e9d 100644--- a/plugins/model-apps/scripts/lib/app-spec.js+++ b/plugins/model-apps/scripts/lib/app-spec.js@@ -1,2352 +1,2864 @@-// App Spec schema + validator. The App Spec is the reviewable contract between-// the app-builder's LLM proposal and the deterministic builder.--const path = require('node:path');-const { normalizeSpecShape } = require('./spec-shape.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:`-// URL in an app the maker ships would be a script-injection / local-file-exfil vector for whoever opens-// the app. Anything unparseable or non-http(s) is rejected by the validator.-function isSafeHttpUrl(u) {- if (typeof u !== 'string' || !u) return false;- let parsed;- try { parsed = new URL(u); } catch { return false; }- return parsed.protocol === 'http:' || parsed.protocol === 'https:';-}--// Dataverse systemform.type codes. A form NAME is unique only per (entity, TYPE) — a table's auto-created-// Main / Quick View / Card forms are commonly ALL named "Information" — so any code that RESOLVES a form-// (build reconcile, preflight discovery, verify) must scope by type or a name-only match hits multiple-// rows. Shared here (the lowest-level spec module) so build + verify agree. Values per the option set:-// https://learn.microsoft.com/power-apps/developer/data-platform/reference/entities/systemform#type-choicesoptions-const FORM_TYPE_CODE = { Main: 2, QuickView: 6, QuickCreate: 7, Card: 11 };--// A canonical GUID (used to validate an author-pinned forms[].formId, which is interpolated UNQUOTED into-// an Edm.Guid OData filter). Anchored so it can neither over-match nor be an injection seam.-const FORM_GUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;--// Security-authoring enums (personas[]). These mirror the vendored SDK's security surface-// (cds-maker-sdk src/types/security.ts) EXACTLY — the app-spec validator is a lint-time echo of the-// SDK's own guards so an author sees a bad access/scope at author time instead of only on apply.-// AccessLevel -> Dataverse PrivilegeType (read->Read, appendTo->AppendTo, …)-// 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 PRIVILEGE_SCOPES = new Set(['user', 'businessUnit', 'parentChild', 'organization']);--// The exact ownership marker the vendored SDK (cds-maker-sdk SecurityApi) stamps on the `description`-// of every security role it authors. The SDK deletes/reuses ONLY a role carrying this marker (SEC-1);-// the plugin re-implements that guard in teardown (deleteSecurityRole takes a raw id and does not-// re-check ownership) and in verify (a same-name role someone else built is NOT the one we authored),-// so the string lives here as the single source of truth. Keep in lockstep with the SDK — vendor-sdk--// smoke asserts the vendored bundle still contains it.-const SDK_ROLE_MARKER = 'Authored by @maker-studio/cds-maker-sdk (persona/security role).';--// A sitemap icon / vectorIcon VALUE the platform resolves DIRECTLY (as opposed to a locally-declared-// `webResources[]` NAME): a relative WebResources path (`/WebResources/...`, `/_imgs/...`) or a-// `$webresource:` reference. These are exactly what a DOWNLOADED app carries verbatim on its subareas —-// including OOB system icons like `/WebResources/msdyn_OmnichannelBase/_imgs/SitemapIcon/CDSEntity` — and-// what a modern custom nav icon uses (`/WebResources/<pub>/icons/x.svg`). They must ROUND-TRIP: the build-// emits them verbatim (case-preserved) and validation must NOT reject them for not being a declared web-// resource (that rejection broke download→build on every real app).-// The signal is a leading `/` or a `$webresource:` prefix — NOT a file extension: a web-resource NAME-// legitimately ends in an extension (e.g. `new_appicon.png`), so an extension alone can't distinguish a-// path from a declared name. A BARE token (no `/`, no scheme — e.g. a Fluent icon name `Shop`, or even a-// bare `x.svg`) is NOT a platform ref: as an `icon` it is a local web-resource name that must be declared,-// and as an entity-subarea `VectorIcon` it breaks the modern app-designer property pane (build drops it).-// Grounded by a live probe of the vendored SDK: it serializes-// `<SubArea Entity="…" … VectorIcon="/WebResources/<pub>/icons/x.svg">` correctly for a path value.-function isPlatformIconRef(v) {- const s = String(v == null ? '' : v);- return s.startsWith('/') || /^\$webresource:/i.test(s);-}--// `iconDescription` is a DOCUMENTARY field: what the icon's glyph will DEPICT, in plain language-// ("a briefcase", "an outlined clipboard with a checkmark"). It is never written to Dataverse — it-// exists so `model-app-plan.md` can show the user what they are approving BEFORE the SVG is drawn.-//-// Why a Fluent token name is rejected outright: the SVG is authored fresh in this phase, so there is-// no icon library to look a token up in — and a token name the user has never seen ("ClipboardTask")-// tells them nothing about what the glyph will look like, which defeats the entire point of the-// field. Detect a token by SHAPE: a single word (no whitespace) that is either Capitalised the way-// every Fluent name is ("Briefcase", "ClipboardTask") or carries a Fluent style/size suffix-// ("...24Regular"). A single lowercase word ("briefcase") is terse but still a real depiction, so it-// passes — the rule targets library-name pasting, not brevity.-const FLUENT_TOKENISH = /^(?=\S+$)(?:[A-Z].*|.*[a-z0-9][A-Z].*|.*(?:Regular|Filled|Light|Color)\d*$)/;-function validateIconDescription(value, label, errors) {- if (value === undefined) return;- if (typeof value !== 'string' || !value.trim()) {- errors.push(`${label}: iconDescription must be a non-empty string describing what the glyph depicts (e.g. "a briefcase")`);- return;- }- if (FLUENT_TOKENISH.test(value.trim())) {- errors.push(`${label}: iconDescription '${value}' looks like a Fluent icon token, not a description. The SVG is drawn fresh, so describe what the glyph will DEPICT (e.g. "an outlined clipboard with a checkmark") — a token name the user has not seen tells them nothing.`);- }-}--// The web-resource NAME a PLATFORM icon reference points at, or null when it isn't a resolvable-// web-resource reference. Two forms the platform emits:-// `/WebResources/<name>` → <name> (the runtime path a modern nav icon uses)-// `$webresource:<name>` → <name>-// A `<name>` may itself contain `/` (web-resource names are folder-like, e.g. `pub_/icons/x.svg`), so-// strip ONLY the known prefix, verbatim. A non-WebResources path (an OOB static image like-// `/_imgs/TableIconsFluentV9/x.svg`) returns null — not a queryable web resource, so it stays a bare-// reference present on every env.-function webResourceNameFromRef(ref) {- const s = String(ref == null ? '' : ref);- let m = /^\/WebResources\/(.+)$/i.exec(s);- if (m) return m[1];- m = /^\$webresource:(.+)$/i.exec(s);- if (m) return m[1];- return null;-}--// App Spec column type -> { dv: Dataverse attribute type name }. (The SDK build engine-// maps App Spec types to the SDK's own ColumnType in lib/sdk-build.js.)-const TYPE_MAP = {- Text: { dv: 'string' },- Memo: { dv: 'memo' },- Choice: { dv: 'picklist' },- MultiChoice: { dv: 'multiselectpicklist' },- Boolean: { dv: 'boolean' },- Money: { dv: 'money' },- DateTime: { dv: 'datetime' },- Integer: { dv: 'integer' },- BigInt: { dv: 'bigint' },- Decimal: { dv: 'decimal' },- Double: { dv: 'double' },- File: { dv: 'file' },- Image: { dv: 'image' },- AutoNumber: { dv: 'string' },- Customer: { dv: 'lookup' }, // polymorphic account/contact — built via createCustomerColumn- Lookup: { dv: null }, // lookups come from relationships, not a column-};--function columnTypeMap(t) {- return TYPE_MAP[t] || TYPE_MAP.Text;-}--// Map every Choice / MultiChoice column's option LABELS to the integer values the-// builder assigns (value = 100000000 + index — the same convention used for inline-// option sets AND global option sets; see lib/sdk-build.js). Resolves inline `options[]`-// columns AND columns bound to a `globalChoice` (looked up in spec.globalChoices). Pass-// `spec` to resolve global choices; without it, only inline-option columns resolve.-// { columnLogicalName: { "Platinum": 100000000, ... } }.-function choiceValueMap(entity, spec) {- const globalByName = {};- for (const g of (spec && spec.globalChoices) || []) {- const byLabel = {};- (g.options || []).forEach((label, i) => { byLabel[String(label)] = 100000000 + i; });- globalByName[String(g.name).toLowerCase()] = byLabel;- }- const map = {};- for (const c of entity.columns || []) {- if (c.type !== 'Choice' && c.type !== 'MultiChoice') continue;- let byLabel = null;- if (Array.isArray(c.options) && c.options.length) {- byLabel = {};- c.options.forEach((label, i) => { byLabel[String(label)] = 100000000 + i; });- } else if (c.globalChoice && globalByName[String(c.globalChoice).toLowerCase()]) {- byLabel = globalByName[String(c.globalChoice).toLowerCase()];- }- if (byLabel) map[c.schemaName.toLowerCase()] = byLabel;- }- return map;-}--// Shared choice-value linter (#4). Returns [{ field, token }] for each Choice/MultiChoice sample VALUE-// in `record` that is neither a declared option label nor a raw integer option value. Both the hard-// validator (validateAppSpec) and the guardrail linter (spec-lint.js) call this so the two gates never-// diverge. A MultiChoice value is a comma-separated token list; a single Choice is one token — a label-// that legitimately contains a comma is matched WHOLE first (byLabel[val]) so it is never mis-split.-// Raw integer tokens pass through (an author may use the stable option value instead of the label).-function invalidChoiceSampleTokens(spec, entity, record) {- if (!entity || !record || typeof record !== 'object' || Array.isArray(record)) return [];- const byField = choiceValueMap(entity, spec);- const multi = new Set((entity.columns || []).filter((c) => c.type === 'MultiChoice').map((c) => String(c.schemaName).toLowerCase()));- const out = [];- for (const [field, val] of Object.entries(record)) {- if (field.startsWith('$') || field === 'statusReason') continue;- const byLabel = byField[field.toLowerCase()];- if (!byLabel || typeof val !== 'string') continue; // not a choice column, or already an int- if (byLabel[val] !== undefined) continue; // whole value is a known label (incl. labels with commas)- const tokens = multi.has(field.toLowerCase()) ? val.split(',').map((t) => t.trim()).filter(Boolean) : [val];- for (const tok of tokens) {- if (tok === '' || /^-?\d+$/.test(tok)) continue; // blank or a raw option int- if (byLabel[tok] === undefined) out.push({ field, token: tok });- }- }- return out;-}--// The sample records declared for an entity (keyed by schemaName, case-insensitive).-function sampleRecordsFor(spec, entity) {- const sd = spec.sampleData || {};- const key = Object.keys(sd).find((k) => k.toLowerCase() === entity.schemaName.toLowerCase());- return (key && Array.isArray(sd[key]) && sd[key]) || [];-}--// Valid chart types (SDK ChartSeriesType values).-const CHART_TYPES = ['Column', 'Bar', 'Pie', 'Line'];--// Find the OneToMany relationship in the spec whose `referenced` = parentEntity and-// `referencing` = childEntity (case-insensitive on both schema names). Returns the-// relationship object (its `lookup.schemaName` is the @odata.bind nav-property; the-// sub-grid RelationshipName is relationshipSchemaName(rel)), or null when none exists.-function relationshipFor(spec, parentEntity, childEntity) {- const p = String(parentEntity || '').toLowerCase();- const c = String(childEntity || '').toLowerCase();- return (- (spec.relationships || []).find(- (r) =>- r.type === 'OneToMany' &&- String(r.referenced || '').toLowerCase() === p &&- String(r.referencing || '').toLowerCase() === c- ) || null- );-}--// The 1:N lookup columns a relationship places ON `entityLogical` (the referencing/child side).-// These lookups are NOT part of entities[].columns — they come from relationships[] — so form-// auto-layout and default-view enrichment call this to surface the parent links (otherwise the-// parent lookup is invisible on the form/grid). N:N relationships use an intersect table and place-// no lookup column on either side, so they're excluded. Deduped by logical name; declared order-// preserved. Returns [{ logical, displayName }].-function lookupColumnsFor(spec, entityLogical) {- const child = String(entityLogical || '').toLowerCase();- const seen = new Set();- const out = [];- for (const r of spec.relationships || []) {- if (r.type !== 'OneToMany') continue;- if (String(r.referencing || '').toLowerCase() !== child) continue;- const logical = String((r.lookup && r.lookup.schemaName) || '').toLowerCase();- if (!logical || seen.has(logical)) continue;- seen.add(logical);- out.push({ logical, displayName: (r.lookup && r.lookup.displayName) || (r.lookup && r.lookup.schemaName) || logical });- }- return out;-}--// The child relationships to show as sub-grids on `entityLogical`'s (parent) form: every 1:N where-// this entity is the REFERENCED (parent) side, plus every N:N it participates in. Returns the child-// (the "many"/other side) as [{ childEntity }], deduped, declared order preserved. Used by the opt-in-// forms[].autoSubgrids to give a hub table a "list of its children" grid without hand-authoring each.-function childRelationshipsFor(spec, entityLogical) {- const parent = String(entityLogical || '').toLowerCase();- const seen = new Set();- const out = [];- for (const r of spec.relationships || []) {- let child = null;- if (r.type === 'OneToMany' && String(r.referenced || '').toLowerCase() === parent) {- child = String(r.referencing || '').toLowerCase();- } else if (r.type === 'ManyToMany') {- const a = String(r.entity1 || '').toLowerCase();- const b = String(r.entity2 || '').toLowerCase();- if (a === parent) child = b;- else if (b === parent) child = a;- }- if (!child || seen.has(child)) continue;- seen.add(child);- out.push({ childEntity: child });- }- return out;-}--// The 1:N relationship's SCHEMA name (used for entity provisioning and the-// sub-grid RelationshipName). This MUST be distinct from the lookup attribute's-// schema name — Dataverse rejects a relationship whose name collides with the-// lookup column on the referencing table. Defaults to `<referenced>_<referencing>`,-// with the solution's publisher prefix guaranteed at the front (see-// prefixedRelationshipName) so a relationship to a STANDARD/system table (systemuser,-// account, …) — which has no custom prefix — still gets a valid, prefixed name that-// Dataverse accepts. An explicit `rel.schemaName` is honored verbatim.-function relationshipSchemaName(rel, publisherPrefix) {- if (rel && rel.schemaName) {- return rel.schemaName;- }- return prefixedRelationshipName(rel.referenced, rel.referencing, publisherPrefix);-}--// Compose a relationship schema name from two entity schema names, guaranteeing the result starts-// with the solution's publisher prefix. Dataverse REQUIRES a relationship schema name to start with-// the publisher prefix; the naive `<a>_<b>` only satisfies that when `a` is a custom (prefixed)-// table. When `a` is a standard/system table (systemuser, account, …) the composed name starts with-// the table name instead and Dataverse rejects the create with a 400. So when the composed name-// doesn't already start with `<prefix>_`, prepend it (stripping a redundant prefix from `b` so we-// don't double it). With no prefix supplied the legacy `<a>_<b>` is returned unchanged.-function prefixedRelationshipName(a, b, publisherPrefix) {- const first = String(a || '').toLowerCase();- const second = String(b || '').toLowerCase();- const prefix = String(publisherPrefix || '').toLowerCase();- const composed = `${first}_${second}`;- if (!prefix || composed.startsWith(`${prefix}_`)) {- return composed;- }- const secondStripped = second.startsWith(`${prefix}_`) ? second.slice(prefix.length + 1) : second;- return `${prefix}_${first}_${secondStripped}`;-}--// Find the ManyToMany relationship linking two entities (order-independent), or null.-function manyToManyFor(spec, entityA, entityB) {- const a = String(entityA || '').toLowerCase();- const b = String(entityB || '').toLowerCase();- return (- (spec.relationships || []).find((r) => {- if (r.type !== 'ManyToMany') return false;- const e1 = String(r.entity1 || '').toLowerCase();- const e2 = String(r.entity2 || '').toLowerCase();- return (e1 === a && e2 === b) || (e1 === b && e2 === a);- }) || null- );-}--// The N:N relationship's SCHEMA name (the intersect/RelationshipName). #3: an N:N is symmetric, so the-// name is composed from the two entity logical names SORTED ALPHABETICALLY — this makes the name STABLE-// regardless of authoring order (the same pair authored `entity1/entity2` either way yields ONE name,-// fixing the V1/V2 reversal that broke a data-load assuming a fixed order). The publisher prefix is then-// guaranteed at the front (see prefixedRelationshipName). An explicit `schemaName` still wins verbatim.-// NOTE: only N:N sorts — a 1:N name (relationshipSchemaName) keeps its semantic `referenced_referencing`-// (parent_child) order and must NOT be sorted.-function manyToManySchemaName(rel, publisherPrefix) {- if (rel && rel.schemaName) {- return rel.schemaName;- }- const [a, b] = [String(rel.entity1 || '').toLowerCase(), String(rel.entity2 || '').toLowerCase()].sort();- return prefixedRelationshipName(a, b, publisherPrefix);-}--// Turn author-friendly sample records into Web-API bodies: Choice / MultiChoice values-// written as labels ("Platinum", or "Low,High" for multi-select) are resolved to their-// option ints — for inline-option AND global-choice columns (pass `spec` so global-// choices resolve). Everything else passes through unchanged (raw ints, strings,-// booleans, ISO dates, and unknown tokens all still work).-function resolveSampleRecords(entity, records, spec) {- const choices = choiceValueMap(entity, spec);- const multi = new Set((entity.columns || []).filter((c) => c.type === 'MultiChoice').map((c) => c.schemaName.toLowerCase()));- return (records || []).map((rec) => {- const out = {};- for (const [k, v] of Object.entries(rec)) {- const byLabel = choices[k.toLowerCase()];- out[k] = byLabel ? resolveChoiceValue(byLabel, v, multi.has(k.toLowerCase())) : v;- }- return out;- });-}--// Resolve one sample value against a column's { label -> int } map.-// - single-select Choice: a known label becomes its integer value (Edm.Int32);-// - MultiChoice (multi-select picklist): the Web API expects a COMMA-SEPARATED STRING of-// option ints *even for a single value* — so every token is resolved and re-joined as a-// string (a bare Int32 is rejected: "Cannot convert '100000002' (Int32) to Edm.String").-// Unknown tokens and non-strings pass through unchanged (raw ints still work for single-select).-function resolveChoiceValue(byLabel, v, isMulti) {- if (typeof v !== 'string') return v;- if (isMulti) {- return v.split(',').map((t) => {- const tok = t.trim();- return byLabel[tok] !== undefined ? String(byLabel[tok]) : tok;- }).join(',');- }- return byLabel[v] !== undefined ? byLabel[v] : v;-}--// Valid validation profiles. `deploy` (default) is the strictest — every page must be implemented-// (a real .tsx). `design`/`plan` allow intent-only pages (author designs pages before generate-pages-// writes their .tsx). `structural` ignores page implementation (teardown/cleanup only cares about refs).-// See docs/app-builder-design.md §7.1.-const VALIDATION_PROFILES = ['design', 'plan', 'deploy', 'structural'];--// What a page does when a user opens it straight from the app navigation with no caller input.-// Every page is sitemap-placed, so this state is always reachable for a page that declares-// `pageInput`; these are the two honest answers.-// selector — render a picker/list so the user can choose the record the page needs.-// emptyState — render an explanatory empty state ("open a row from X to see its detail").-const DIRECT_ENTRY_BEHAVIORS = ['selector', 'emptyState'];--// Per-column grid data visualization (PREVIEW). MIRRORS the vendored SDK's `ColumnVisualizationType`-// (types/schema.ts) exactly — widening here without widening there produces a mid-build throw.-//-// Semantics are per COLUMN, not per view: the platform renders the graphic in EVERY grid and view-// that shows the column, which is why this lives on `entities[].columns[]` rather than on `views[]`.-// Persisted as a `controlconfiguration` row bound to the attribute.-//-// `None` is the platform default (plain text) and is accepted so a spec can explicitly CLEAR a-// visualization set by an earlier build or by a maker in the portal. OMITTING the field is NOT the-// same as `None`: an omitted column is left exactly as deployed, because converging every undeclared-// column to "plain text" would cost one extra read per column on every build to find out whether-// there was anything to clear.-const COLUMN_VISUALIZATIONS = ['None', 'RadialDial', 'LineChart', 'HeatMap', 'StarRating'];--// Whole Number display Format (AB#6648522). MIRRORS the vendored SDK's `integerFormat` union-// (types/schema.ts) exactly, same reasoning as COLUMN_VISUALIZATIONS above — widening one without-// the other produces a mid-build InvalidArgumentError instead of a spec-gate rejection.-//-// 'None' is the platform default (plain integer). It is accepted here, same as visualization's-// 'None', so a spec can explicitly clear a Format set by an earlier build or a maker in the portal.-// Unlike visualization, this is Integer-type-only — the SDK throws InvalidArgumentError for any-// other numeric type (BigInt/Decimal/Double/Money), so validated below alongside the enum check.-const INTEGER_FORMATS = ['None', 'Duration', 'TimeZone', 'Language', 'Locale'];--// Business rules. These MIRROR the vendored SDK's supported slice.-//-// The list is the SDK's operator TABLE, not a subset of it, and that table is the authority for a-// sharp reason: the serializer resolves an operator with-// `Uf[operator] ?? WorkflowConditionOperator.Equal`, so an operator it does not know becomes-// **Equals**. `IsGreaterThan` is in the table; `GreaterThan` is not — writing the latter silently-// deploys an equality test. That is a wrong rule behind a green build, which is exactly what this-// gate exists to prevent, so `business-rules.test.js` pins this list against the bundle's own table.-//-// The list was four entries long for a long time. That was never a platform limit: the SDK used to-// fall back to a client-side workflow-XAML compiler that could only express those four, and the-// restriction outlived it. The compiler has been deleted upstream, so the JSON path's full table is-// available.-const BUSINESS_RULE_OPERATORS = [- 'Equals', 'DoesNotEqual',- 'IsGreaterThan', 'IsGreaterThanEqualTo', 'IsLessThan', 'IsLessThanEqualTo',- 'Contains', 'DoesNotContain',- 'BeginsWith', 'DoesNotBeginWith', 'EndsWith', 'DoesNotEndWith',- 'On', 'NotOn',- 'ContainsData', 'DoesNotContainData',-];-// Nothing is blocked at present. Kept (empty) so a future platform-side breakage can be re-declared-// here with an explanation, rather than being folded into "unknown operator".-const BUSINESS_RULE_BLOCKED_OPERATORS = new Set();-// Operators that take NO value: they test presence, so a `value` would be meaningless. Measured —-// the serializer emits an EMPTY right-hand operand list for exactly these two.-const BUSINESS_RULE_VALUELESS_OPERATORS = new Set(['ContainsData', 'DoesNotContainData']);-// action type -> the field carrying its payload. `null` = no payload (none currently).-//-// The SDK models seven action types (adding `SetDefaultValue`, `ShowErrorMessage` and-// `Recommendation`), and all seven were measured serializing correctly through the real bundle.-// They are deliberately NOT exposed yet: each needs new mapping in `businessRuleDef`, and business-// rules cannot be exercised end to end on an environment that does not declare-// `CreateProcessWithWfomJson` — which is the environment this was developed against. Shipping-// mapping code that has never round-tripped against the platform is how a rule deploys and quietly-// does the wrong thing. Expose them from an environment where they can be live-verified.-const BUSINESS_RULE_ACTIONS = { SetVisibility: 'visible', LockUnlock: 'lock', SetBusinessRequired: 'required', SetFieldValue: 'value' };-const BUSINESS_RULE_ACTION_TYPES = Object.keys(BUSINESS_RULE_ACTIONS);-// Boolean-payload actions, so a string "false" (truthy in JS) is rejected rather than silently-// inverting the author's intent — the same trap `app.newLook` validation exists to close.-const BUSINESS_RULE_BOOLEAN_ACTIONS = new Set(['SetVisibility', 'LockUnlock', 'SetBusinessRequired']);-// `valueWorkflowType` in SDK terms: how the platform should interpret the literal. Named `dataType`-// in the App Spec because `valueType` in the SDK means something else (Value vs Field vs Lookup),-// and only `Value` is supported — so exposing that name would invite a distinction authors cannot use.-//-// This list has NO counterpart in the bundle any more, and nothing pins it. It used to mirror the-// XAML compiler's literal-type map, which this SDK uptake deleted along with the compiler.-//-// MEASURED against the replacement JSON path: `dataType` is IGNORED. Across all ten tokens below —-// and a made-up one — on both the condition path and the SetFieldValue action path, the serializer-// emits WorkflowAttributeType String ("14") every time:-// let r = valueType==='Lookup' ? … : valueType==='Clear' ? (valueWorkflowType ?? String)-// : WorkflowAttributeType.String-// So this is a curated closed set kept for two reasons only: it catches a typo at the spec gate, and-// it keeps the surface forward-compatible if the SDK starts honouring the field. Do NOT add a token-// on the assumption a test will validate it against the SDK — no such test can exist while there is-// nothing to validate against. `business-rules.test.js` instead pins the measured no-op.-const BUSINESS_RULE_DATA_TYPES = ['String', 'Memo', 'Picklist', 'State', 'Status', 'Boolean', 'Integer', 'Double', 'Decimal', 'Money'];-// Only entity scope is supported. A form-scoped rule needs `processtriggerscope 1` plus a form id,-// which cannot be resolved before the forms phase has run.-const BUSINESS_RULE_SCOPES = ['Entity'];--// --- Business process flows (BPF) ----------------------------------------------------------------//-// A BPF is a `workflows` row (category 4 / type 1 / businessprocesstype 0) whose XAML the platform-// reads to materialize the read-only `processstage` rows. The vendored SDK owns that serialization;-// the plugin owns the judgment below.-//-// v1 is deliberately a SINGLE-ENTITY, linear flow: ordered stages, each with ordered steps bound to-// columns of that same entity. The SDK's artifact additionally models `category`, `nextStageId`,-// `relationshipName`, `branch`, stage `actions` and `securityRoles`, and those are NOT exposed here:-// * cross-entity stages / branching change what the flow MEANS and need live verification per-// shape before being offered;-// * `securityRoles` needs role IDs (the SDK grants CRUD privileges on the backing table that-// ACTIVATION creates, via `reconcileBpfSecurityRoles({ roleId, access })`) — that is the-// `security` phase's job, not this one, and is tracked as a follow-up.-// Offering a knob the build cannot verify is how a spec deploys something the author did not mean.-const BPF_STATUSES = ['Active', 'Draft'];--// Mirror of the vendored SDK's BPF `uniquename` derivation:-// uniqueName || `new_${name.toLowerCase().replace(/[^a-z0-9]/g, '') || 'businessprocessflow'}`-// Two properties of it drive the collision check below, and both are easy to get wrong:-// * it IGNORES the entity, so two flows on DIFFERENT tables can derive one unique name; and-// * it strips case and punctuation, so "Ticket Handling" and "ticket-handling" derive the same one.-// The plugin does not supply an explicit `uniqueName` (bpfDef leaves it to the SDK), so an author has-// no way to disambiguate. This is not merely a name clash: ACTIVATION creates an org-owned backing-// TABLE named after the derived value, so the second flow cannot deploy at all.-function bpfUniqueName(name) {- const normalized = String(name === undefined || name === null ? '' : name).toLowerCase().replace(/[^a-z0-9]/g, '');- return `new_${normalized || 'businessprocessflow'}`;-}--// The keys a stage / step may carry. Everything else is REJECTED rather than dropped: the SDK's own-// normalizers copy a fixed key set (stage: id/name/entityLogicalName/steps + category/nextStageId/-// relationshipName/actions/branch; step: id/name/fieldName/required) and discard the rest, so an-// unmapped key an author wrote — a stage `branch`, or the very plausible `fieldLogicalName` instead of-// `field` — would otherwise validate clean and deploy as if it had never been written.-const BPF_STAGE_KEYS = new Set(['name', 'entity', 'steps']);-const BPF_STEP_KEYS = new Set(['name', 'field', 'required']);-// Hard ceilings the vendored SDK enforces on a BPF. Pinned here so an over-large flow is a spec-// error, not a throw from inside the bundle in a late build phase.-const BPF_MAX_STAGES = 30;-const BPF_MAX_STEPS = 30;--// The keys an `entities[]` table may carry. Everything else is REJECTED rather than dropped.-//-// Entities were the one authorable block with NO allow-list, and the gap was not theoretical: the-// two most natural ways to ask for a second language — `entities[].languageCode` and-// `entities[].localizedLabels` — both validated clean and were then silently ignored, so an author-// asking for one table in Spanish got a SUCCESSFUL build with the request dropped and nothing-// reporting the loss (#537). Neither key is read anywhere in scripts/ or scripts/lib/.-//-// They cannot be honoured today, which is precisely why they must fail loudly rather than validate-// clean. The authoring language is BUILD-WIDE: provisionDataModel resolves ONE LCID and passes it to-// every createTable / createColumn / createGlobalOptionSet / insertStatusValue / createRelationship /-// createAlternateKey call, and the SDK takes it as a CONSTRUCTION-TIME option (the App/Form/Dashboard-// adapters bake it in), so a per-table language would need a second SDK instance. Multi-language-// labelling is blocked a layer lower still — the SDK's label serializer emits a ONE-element-// LocalizedLabels array by design, and pushing an artifact read under a different LCID throws-// ARTIFACT_LANGUAGE_MISMATCH.-//-// This list is the set the build actually READS. Adding a key here without a reader would re-open-// the very silent-drop hole it exists to close.-const ENTITY_KEYS = new Set([- 'schemaName', 'displayName', 'pluralName', 'description', 'primaryAttribute', 'columns',- 'hasNotes', 'quickCreate', 'existing', 'enrichDefaultViews',- 'vectorIcon', 'iconDescription', 'icon',- 'statusReasons', 'alternateKeys',-]);--// What to write INSTEAD, for the keys an author is most likely to reach for. A bare "unknown key"-// names the mistake but not the fix, and for these two the fix is not guessable from the schema.-//-// Prototype-less on purpose: the lookup key comes from the SPEC, so a table carrying `constructor`-// or `toString` would otherwise inherit a value from Object.prototype and splice-// "function Object() { [native code] }" into the error message.-const ENTITY_KEY_HINTS = Object.assign(Object.create(null), {- languageCode: ' — the authoring language is build-wide, not per-table: set the spec-level `languageCode`, which applies to every table',- localizedLabels: ' — multi-language labels are not supported: the build writes ONE label per name, in the spec-level `languageCode` language',-});--// 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).-//-// Shared by the business-rule and BPF validators — they ask the identical question, and an answer-// that drifts between them would let one accept a field the other rejects.-function declaredColumnLogicals(spec, entitySchemaName) {- const ent = (spec.entities || []).find((e) => e && e.schemaName === entitySchemaName);- const cols = new Set();- if (!ent) return cols;- if (ent.primaryAttribute && ent.primaryAttribute.schemaName) cols.add(String(ent.primaryAttribute.schemaName).toLowerCase());- for (const c of ent.columns || []) if (c && c.schemaName) cols.add(String(c.schemaName).toLowerCase());- for (const rel of spec.relationships || []) {- if (rel && rel.referencing === entitySchemaName && rel.lookup && rel.lookup.schemaName) {- cols.add(String(rel.lookup.schemaName).toLowerCase());- }- }- return cols;-}--// Normalize a Dataverse language identifier (LCID) to a positive integer, or null if it is not one.-//-// This is the SINGLE definition used by all three entry points an LCID can arrive from, so they can-// never disagree about what is valid: the `--language-code` CLI flag (always a string), the App Spec-// `languageCode` field (JSON, so nominally a number but in practice anything), and a programmatic-// caller of resolveLanguageCode().-//-// It deliberately does NOT use a bare `Number(value)` cast, which is far too lenient for a value that-// is sent straight to Dataverse as a label LanguageCode:-// Number(true) === 1 -> `"languageCode": true` would build every label with LCID 1-// Number([1033]) === 1033 -> a one-element array would silently "work"-// Number('1e3') === 1000 -> exponent notation is never a real LCID-// Each of those passes a naive positive-integer check and then fails deep inside the data-model phase-// with an opaque Dataverse 400, instead of a clear spec/CLI error up front. Accept only a real number-// or an all-digits string, and bound it: an LCID is a 16-bit value, so anything above 0xFFFF cannot be-// one and would fail the same opaque way (65536, 1e20 and MAX_SAFE_INTEGER all cleared an unbounded-// positive-integer check).-// LCID reference: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-lcid/-const MAX_LCID = 0xFFFF;-function normalizeLanguageCode(value) {- const ok = (n) => (n > 0 && n <= MAX_LCID ? n : null);- if (typeof value === 'number') return Number.isInteger(value) ? ok(value) : null;- if (typeof value === 'string' && /^\d+$/.test(value.trim())) return ok(Number(value.trim()));- return null;-}--// Describe a rejected value for an error message WITHOUT being able to throw doing it.-// `JSON.stringify` throws on a BigInt and on a getter that throws, which would turn a structured-// validation error into a raw crash — the exact outcome this validator exists to prevent.-// The FALLBACK is guarded too: `Object.prototype.toString` itself throws on a revoked Proxy, so an-// unguarded fallback would reintroduce the crash it exists to avoid.-// Module-level so checks that run BEFORE validateAppSpec's local helpers are initialised can use it-// too (a `const` arrow declared later in the function is in the temporal dead zone until then).-function describeSpecValue(v) {- try { return JSON.stringify(v); } catch { /* fall through */ }- try { return Object.prototype.toString.call(v); } catch { return '<unprintable>'; }-}--// The single wording for a rejected LCID, shared by every entry point that accepts one.-//-// It is a function rather than a constant because the offending value is quoted back: the most-// common wrong input is a BCP-47 language TAG ("es-ES", "de-DE") — the thing a person naturally-// writes — and "must be a positive integer LCID" is true but leaves that author with nothing to act-// on. Shared for the same reason `ENTITY_KEYS` is: two entry points that disagree about what a bad-// LCID *is* teach the author two different rules for one field.-// LCID reference: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-lcid/-function invalidLanguageCodeMessage(value) {- return `languageCode must be a positive integer LCID up to ${MAX_LCID} — e.g. 1033 (en-US) or 1031 (de-DE), `- + `not a language tag like "de-DE" (got ${describeSpecValue(value)})`;-}--// Normalize a page's implementation source into a discriminated shape:-// { kind: 'tsx', codeFile } | { kind: 'intent' } | null-// A legacy top-level `codeFile` (schemaVersion < 2) is treated as an implemented tsx page. `null`-// means the page declares neither a source nor a codeFile. Whitespace-only codeFile values are-// treated as absent (codeFile trimmed to undefined) so a blank value fails the structural check-// rather than silently being treated as an implemented page.-function normalizePageSource(page) {- if (page && page.source && typeof page.source === 'object') {- if (page.source.kind === 'intent') return { kind: 'intent' };- if (page.source.kind === 'tsx') {- // Trim so ' ' is treated identically to undefined — blank is not an implemented codeFile.- const codeFile = typeof page.source.codeFile === 'string' ? page.source.codeFile.trim() || undefined : page.source.codeFile;- return { kind: 'tsx', codeFile };- }- return { kind: page.source.kind }; // malformed — surfaced by the validator below- }- // Treat a whitespace-only legacy codeFile as absent so it fails the implemented check.- if (page && typeof page.codeFile === 'string' && page.codeFile.trim()) {- return { kind: 'tsx', codeFile: page.codeFile.trim() };- }- return null;-}--// Whether the build should enable "Allow quick create" (`IsQuickCreateEnabled`) on a table.-// TWO triggers, both author-controlled:-// 1. explicit `entities[].quickCreate === true`, OR-// 2. the spec authors a `formType: 'QuickCreate'` form for that entity — enabling the flag then-// just makes the form the author already declared actually reachable (the inline "+ New" from a-// lookup / sub-grid). Authoring a Quick Create form but leaving the table flag OFF is a footgun:-// the form exists but the platform never surfaces it, so we treat the authored QC form as intent.-// PURE: both the build engine (entity-provision.js) and the eval fact extractor (schema-facts.js) call-// this so the eval grades the EXACT rule the engine applies (DRY — never a naive spec echo).-function quickCreateEnabledFor(spec, entity) {- if (!entity) return false;- if (entity.quickCreate === true) return true;- const logical = String(entity.schemaName || '').toLowerCase();- if (!logical) return false;- return (spec && spec.forms || []).some(- (f) => f && f.formType === 'QuickCreate' && String(f.entity || '').toLowerCase() === logical,- );-}--// A maker-facing `description`, supported on every artifact whose SDK create surface accepts one-// (table, column, view, chart, form, dashboard, business rule, app, web resource).-//-// Deliberately a soft contract: descriptions are OPTIONAL, because making them mandatory would fail-// every spec authored before they existed. What is validated is only that a supplied value is usable-// — a number or an object here means the author meant something else, and silently stringifying it-// would write "[object Object]" into Dataverse.-//-// 2000 is the Dataverse ceiling for a description Label; the platform truncates past it rather than-// erroring, so catching it here is the only place the author finds out.-// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/entity-attribute-metadata-const DESCRIPTION_MAX = 2000;-function validateDescription(value, label, errors, opts = {}) {- if (value === undefined || value === null) return;- if (typeof value !== 'string') {- errors.push(`${label}: description must be a string`);- return;- }- // `app.description` predates this contract and countless existing specs (and every spec emitted by- // `download-model-app`) carry it as `""`. Rejecting that would fail specs that are otherwise fine,- // so emptiness is tolerated exactly where it is already established — never for a NEW surface,- // where an empty string is the one value that could blank a maker's text on rebuild.- if (!value.trim()) {- if (opts.allowEmpty) return;- errors.push(`${label}: description must not be blank — omit the field instead of setting an empty string`);- return;- }- if (value.length > DESCRIPTION_MAX) {- errors.push(`${label}: description is ${value.length} characters (max ${DESCRIPTION_MAX})`);- }-}--// Per-control form-field options: `readOnly`, `hidden`, `after`.-//-// Reachable two ways — inline on an EXPLICIT layout's `sections[].fields[]` entry, or via the-// form-level `fieldOptions` map (the only route under an AUTO layout, which has no field list).-//-// Only the ENABLED state is written by the build (`isReadOnly: true` / `visible: false`); `false` is-// a no-op rather than an un-set, so it is rejected here instead of being accepted and quietly-// ignored — an author who writes `readOnly: false` expecting it to clear an existing lock would-// otherwise get a green build and no change.-// `forms[].securityRoles` — who a form is offered to. AB#6648526.-//-// Direction matters and is easy to get backwards: a form with NO assignment is offered to EVERY-// role, so declaring this RESTRICTS the form. That makes every failure mode here access-relevant —-// a typo'd persona or an empty list narrows a form to nobody — so each is a hard error rather than-// a warning, and the build additionally halts on an unresolvable persona.-//-// `everyone` and `roleIds` are mutually exclusive in the PLATFORM's model (`<Everyone />` replaces-// the `<Role>` list rather than adding to it), not merely in this validator; the SDK rejects the-// combination with INVALID_ARGUMENT, so catching it here just names the form.-function validateFormSecurityRoles(f, spec, errors) {- const sr = f.securityRoles;- if (sr === undefined) return;- const label = `form '${f.name || f.entity}'`;- if (!sr || typeof sr !== 'object' || Array.isArray(sr)) {- errors.push(`${label}: securityRoles must be an object like { "personas": ["Dispatcher"] } or { "everyone": true }`);- return;- }- const known = new Set(['personas', 'everyone', 'fallbackForm', 'order']);- for (const k of Object.keys(sr)) {- if (!known.has(k)) errors.push(`${label}: securityRoles has unknown key '${k}' — expected ${[...known].join(', ')}`);- }-- const hasEveryone = sr.everyone !== undefined;- if (hasEveryone && typeof sr.everyone !== 'boolean') {- errors.push(`${label}: securityRoles.everyone must be a boolean`);- }- // `everyone: false` is not "restrict to nobody" — it is an author reaching for a switch that does- // not exist.- if (sr.everyone === false) {- errors.push(`${label}: securityRoles.everyone: false does nothing — use "everyone": true to make the form available to every role again, or list personas to restrict it`);- }-- if (sr.personas !== undefined) {- if (!Array.isArray(sr.personas) || sr.personas.some((p) => typeof p !== 'string' || !p.trim())) {- errors.push(`${label}: securityRoles.personas must be an array of persona names`);- } else if (!sr.personas.length) {- errors.push(`${label}: securityRoles.personas is empty — that would offer the form to NO role. List at least one persona, or use "everyone": true.`);- } else {- // Resolved against `personas[]` at author time so a typo is a spec error naming the form,- // rather than a build halt two minutes into a run.- const declared = new Set((spec.personas || []).map((p) => String(canonicalPersonaName(p) || '').toLowerCase()));- for (const p of sr.personas) {- if (!declared.has(String(p).trim().toLowerCase())) {- errors.push(`${label}: securityRoles names persona '${p}', which is not declared in personas[]`);- }- }- const dupes = sr.personas.map((p) => String(p).trim().toLowerCase()).filter((p, i, a) => a.indexOf(p) !== i);- if (dupes.length) errors.push(`${label}: securityRoles lists persona '${dupes[0]}' more than once`);- }- }-- if (sr.everyone === true && sr.personas !== undefined) {- errors.push(`${label}: securityRoles cannot set both 'everyone' and 'personas' — the platform models <Everyone /> as a replacement for the role list, not an addition to it`);- }- if (!hasEveryone && sr.personas === undefined) {- errors.push(`${label}: securityRoles must say who the form is for — set 'personas' or 'everyone': true`);- }-- if (sr.fallbackForm !== undefined && typeof sr.fallbackForm !== 'boolean') {- errors.push(`${label}: securityRoles.fallbackForm must be a boolean`);- }- if (sr.order !== undefined && (!Number.isInteger(sr.order) || sr.order < 0)) {- errors.push(`${label}: securityRoles.order must be a non-negative integer (got ${JSON.stringify(sr.order)})`);- }-- // The build addresses this form by (entity, formType, name) — `created.forms` is keyed by entity- // and holds only the Main form, so a later phase cannot reach a sibling any other way. Duplicate- // (entity, formType, name) is otherwise LEGAL here: only QuickView forms are checked for a unique- // (entity, name), because Main and Card may both be called "Information" harmlessly.- //- // Harmless, that is, until one of them declares securityRoles: the map would keep whichever was- // built last, and the restriction would land on the wrong form while every structural check passed- // and the build reported success. Reject the ambiguity instead of picking a winner.- const twin = (spec.forms || []).filter((o) => o- && String(o.entity || '').toLowerCase() === String(f.entity || '').toLowerCase()- && (o.formType || 'Main') === (f.formType || 'Main')- && String(o.name || '') === String(f.name || ''));- if (twin.length > 1) {- errors.push(`${label}: securityRoles needs a form this spec can identify unambiguously, but ${twin.length} forms share (entity ${f.entity}, type ${f.formType || 'Main'}, name '${f.name || ''}') — rename one, or move the assignment to the form you meant`);- }-}--function validateFormFieldOptions(f, entityByLower, errors, warnings) {- const label = `form '${f.name || f.entity}'`;- const entity = entityByLower.get(String(f.entity || '').toLowerCase());- const columnType = (logical) => {- if (!entity) return undefined;- const c = (entity.columns || []).find((x) => x && x.schemaName && x.schemaName.toLowerCase() === logical);- return c && (c.type || 'Text');- };- const explicit = Array.isArray(f.tabs) || f.layout === 'explicit';- // Every field this form declares an option for, from either route, so the checks below run once- // per (field, source) pair with a source-accurate message.- const seen = [];- // Fields the EXPLICIT layout lists by position. An `after` anchor for one of these — from either- // route — would give the form two competing orderings.- const listedByLayout = new Set();-- for (const t of (Array.isArray(f.tabs) ? f.tabs : [])) {- for (const s of ((t && t.sections) || [])) {- if (s && s.fields !== undefined && !Array.isArray(s.fields)) {- // Guard the compiler, which does `(s.fields || []).map(...)`. A string is ITERABLE and every- // character of it IS a string, so a `fields: "new_name"` typo would pass a naive per-entry- // check and then throw a raw TypeError at compile time instead of producing a finding. A- // non-iterable value (`{}`, `3`) would throw right here. Note `spec-shape.js` does not model- // `fields`, so `normalizeSpecShape` does not coerce it — this check is load-bearing.- errors.push(`${label}: a section's fields must be an array of column logical names`);- continue;- }- for (const entry of ((s && s.fields) || [])) {- if (entry && typeof entry === 'object' && !Array.isArray(entry)) {- if (!entry.name || typeof entry.name !== 'string') {- errors.push(`${label}: a field entry object is missing a string 'name'`);- continue;- }- listedByLayout.add(String(entry.name).toLowerCase());- seen.push({ name: String(entry.name).toLowerCase(), opt: entry, where: `field '${entry.name}'`, inline: true });- } else if (typeof entry === 'string') {- listedByLayout.add(entry.toLowerCase());- } else {- errors.push(`${label}: a field entry must be a column logical name or an object { name, readOnly?, hidden?, after? }`);- }- }- }- }-- if (f.fieldOptions !== undefined) {- if (!f.fieldOptions || typeof f.fieldOptions !== 'object' || Array.isArray(f.fieldOptions)) {- errors.push(`${label}: fieldOptions must be an object keyed by column logical name`);- } else {- for (const key of Object.keys(f.fieldOptions)) {- const v = f.fieldOptions[key];- if (!v || typeof v !== 'object' || Array.isArray(v)) {- errors.push(`${label}: fieldOptions['${key}'] must be an object { readOnly?, hidden?, after? }`);- continue;- }- seen.push({ name: String(key).toLowerCase(), opt: v, where: `fieldOptions['${key}']`, inline: false });- }- }- }-- for (const { name, opt, where, inline } of seen) {- for (const flag of ['readOnly', 'hidden']) {- if (opt[flag] === undefined) continue;- if (typeof opt[flag] !== 'boolean') {- errors.push(`${label}: ${where} ${flag} must be a boolean`);- } else if (opt[flag] === false) {- errors.push(`${label}: ${where} sets ${flag}: false, which the build cannot apply — it only ever writes the ENABLED state, so a maker's existing setting is never silently cleared. Omit the flag, or clear it in the form designer.`);- }- }- if (opt.after !== undefined) {- if (typeof opt.after !== 'string' || !opt.after.trim()) {- errors.push(`${label}: ${where} after must be the logical name of another field on this form`);- } else if (String(opt.after).toLowerCase() === name) {- errors.push(`${label}: ${where} anchors '${name}' after itself`);- } else if (inline || listedByLayout.has(name)) {- // An explicit layout already expresses order by listing position, so honouring `after` for a- // listed field would give the form two competing orderings — and they would DISAGREE: the- // create path follows the authored list, while the reconcile applies the anchor, so the same- // spec would produce one order on a new form and another on the first rebuild.- // A form-level anchor for a field the layout does NOT list stays legal: that is the- // `prune: false` case, where the point is to position a control on a deployed form without- // re-declaring the rest of it.- errors.push(`${label}: ${where} cannot use 'after' for a field an explicit tabs layout already lists — the listed order positions it. Move it in the list instead, or drop it from the list if you mean to position it against fields this layout does not declare.`);- }- }- // A BigInt has no Unified Interface control, so a form placement renders "Error loading control".- // Auto layout skips them outright; an explicit layout still honours the author, but declaring- // per-control options for one is almost certainly a mistake worth surfacing.- if (columnType(name) === 'BigInt') {- warnings.push(`${label}: ${where} targets '${name}', a BigInt column — Big Integer has no Unified Interface form control, so it renders "Error loading control" wherever it is placed`);- }- }-- // Two contradictory anchor shapes. Both are silently unstable rather than wrong-but-stable: the- // reconcile moves each field to its anchor on every build and they undo each other, so the form- // never converges and a rebuild issues writes forever. Neither can be resolved automatically —- // "immediately after X" cannot be true of two fields at once, and a cycle has no valid order — so- // they are rejected at author time instead of being papered over by the placement code.- const anchorOf = new Map();- for (const { name, opt } of seen) {- if (opt.after && typeof opt.after === 'string') anchorOf.set(name, String(opt.after).toLowerCase());- }- const claimants = new Map();- for (const [name, anchor] of anchorOf) {- if (!claimants.has(anchor)) claimants.set(anchor, []);- claimants.get(anchor).push(name);- }- for (const [anchor, names] of claimants) {- if (names.length > 1) {- errors.push(`${label}: ${names.map((n) => `'${n}'`).join(' and ')} are both anchored after '${anchor}' — only one field can sit immediately after another. Chain them instead (anchor the second one after the first).`);- }- }- for (const start of anchorOf.keys()) {- const seenInWalk = new Set([start]);- let cur = anchorOf.get(start);- while (cur !== undefined) {- if (seenInWalk.has(cur)) {- if (cur === start) errors.push(`${label}: the 'after' anchors form a cycle through '${start}' — there is no order that satisfies them all.`);- break;- }- seenInWalk.add(cur);- cur = anchorOf.get(cur);- }- }-- if (f.prune !== undefined) {- if (typeof f.prune !== 'boolean') {- errors.push(`${label}: prune must be a boolean`);- } else if (f.prune === false && !explicit) {- warnings.push(`${label}: prune: false has no effect on an auto layout — an auto layout is already additive and never removes a field`);- }- }-- // An explicit layout that names a BigInt column produces a broken control on a live record. It is a- // warning, not an error: the author asked for it by name and may be pairing it with a custom control.- if (explicit) {- for (const t of (Array.isArray(f.tabs) ? f.tabs : [])) {- for (const s of ((t && t.sections) || [])) {- // Re-guard: the array check in the first loop `continue`s that loop only. Without repeating- // it here a non-iterable `fields` (e.g. `{}` or `3`) throws a raw TypeError out of- // validateAppSpec — discarding the correct finding the first loop already pushed.- if (!Array.isArray(s && s.fields)) continue;- for (const entry of s.fields) {- const nm = String((entry && typeof entry === 'object' ? entry.name : entry) || '').toLowerCase();- if (nm && columnType(nm) === 'BigInt') {- warnings.push(`${label}: field '${nm}' is a BigInt column — Big Integer has no Unified Interface form control, so it will render "Error loading control" on every record. Keep it off the form (it stays readable through the API).`);- }- }- }- }- }-}--function validateAppSpec(spec, opts = {}) {- const profile = opts.profile || 'deploy';- const errors = [];- // Non-blocking advisories (e.g. a PRE-EXISTING duplicate page name the current run did not create).- // Additive to the return shape — callers that only read { ok, errors } are unaffected.- const warnings = [];- if (!VALIDATION_PROFILES.includes(profile)) {- return { ok: false, errors: [`unknown validation profile '${profile}' (valid: ${VALIDATION_PROFILES.join(', ')})`], warnings };- }- if (!spec || typeof spec !== 'object') {- return { ok: false, errors: ['spec is not an object'], warnings };- }- // Structural normalization (shared with lintAppSpec) so a half-typed collection produces findings- // rather than a raw TypeError. Covers NESTED collections too — `entity.columns: {}` and- // `appShell.areas: {}` are realistic mid-edit states that reach `for...of` and throw.- const shape = normalizeSpecShape(spec);- errors.push(...shape.errors);- spec = shape.spec;- if (!spec.solution || !spec.solution.uniqueName) {- errors.push('solution.uniqueName is required');- }- if (!spec.solution || !spec.solution.publisherPrefix) {- errors.push('solution.publisherPrefix is required');- }- if (!spec.app || !spec.app.name) {- errors.push('app.name is required');- }- validateDescription(spec.solution && spec.solution.description, 'solution', errors);- // allowEmpty: `app.description: ""` is the established shape (download-model-app emits it).- validateDescription(spec.app && spec.app.description, 'app', errors, { allowEmpty: true });- for (const gc of spec.globalChoices || []) {- validateDescription(gc && gc.description, `globalChoice '${(gc && gc.name) || '(unnamed)'}'`, errors);- }- // The modern ("new look") shell is an opt-in per-app SETTING, not an appmodule column —- // `navigationtype` only selects Single/Multi session and is unrelated. Boolean-only: a string- // "false" is truthy in JS and would silently turn the new look ON for an author who meant to- // disable it.- if (spec.app && spec.app.newLook !== undefined && typeof spec.app.newLook !== 'boolean') {- errors.push('app.newLook must be a boolean');- }- // The Wave 2 header/navigation refresh is a SEPARATE public-preview setting from the new look;- // enabling one does not enable the other. Boolean-only for the same reason as newLook — a string- // "false" is truthy and would silently turn the feature ON for an author who meant to disable it.- if (spec.app && spec.app.headerNavigationRefresh !== undefined && typeof spec.app.headerNavigationRefresh !== 'boolean') {- errors.push('app.headerNavigationRefresh must be a boolean');- }- if (spec.languageCode !== undefined && normalizeLanguageCode(spec.languageCode) === null) {- // Keep the leading clause stable — the CLI flag and two test suites match on it. The appended- // guidance exists because the bare message named the mistake without naming the fix, and a- // language TAG is the most likely thing an author reaches for.- //- // A tag is NOT accepted as an alias, deliberately: the mapping is genuinely ambiguous where it- // matters (es-ES is 3082 with the international sort and 1034 with the traditional one), and a- // wrong guess would not fail — it would build every label in the wrong language, which is the- // same silent-corruption class this validator exists to prevent. Naming the LCID is safe;- // inferring one is not.- errors.push(invalidLanguageCodeMessage(spec.languageCode));- }- const entityNames = new Set();- const entityByLower = new Map(); // logical (lowercased schemaName) -> entity- // Describe a rejected value for an error message WITHOUT being able to throw doing it.- // See describeSpecValue above for why a bare JSON.stringify is unsafe here.- const describeValue = describeSpecValue;- // A table reference an author writes becomes a Dataverse METADATA NAME, so it has to be a string- // BEFORE it is compared. `String([["new_ticket"]])` is `"new_ticket"`, so a nested array passes an- // entity-membership check and then throws a raw TypeError deep in the build, where the engine- // calls `.toLowerCase()` on the array itself. It is the same trap as `views[].columns` (#525):- // coercing during validation makes the validator agree with a value the builder cannot use.- // Returns true when it reported a problem, so callers can `continue`.- const badEntityRef = (value, where) => {- if (typeof value === 'string' && value.trim()) return false;- errors.push(`${where}: entity must be a table name (a string), got ${describeValue(value)}`);- return true;- };- for (const e of spec.entities || []) {- // Reject unknown keys (#537). A key with no reader is otherwise accepted and dropped, so an- // explicit authoring instruction disappears into a successful build.- //- // Guarded to plain objects: a malformed entity already fails the schemaName check below, and- // `Object.keys('x')` would turn one bad value into a bogus "unknown key '0'".- //- // The enumeration itself is guarded because the object comes from the CALLER: a programmatic- // caller can pass a Proxy whose `ownKeys` trap throws, and this validator's contract is to- // RETURN problems, not to throw them.- if (e && typeof e === 'object' && !Array.isArray(e)) {- // The label is resolved BEFORE `schemaName` is validated, and reading it can itself fail (a- // getter that throws). Without a fallback a malformed entity reported `entity undefined:- // unknown key ...` next to the real `entity.schemaName is required` — two errors for one- // problem, one of them naming a table that does not exist.- let label;- try {- label = typeof e.schemaName === 'string' && e.schemaName.trim() ? `entity ${e.schemaName}` : 'an entity with no schemaName';- } catch {- label = 'an entity whose schemaName could not be read';- }- let keys;- try {- keys = Object.keys(e);- } catch {- keys = null;- errors.push('an entity could not be inspected: enumerating its keys threw');- }- for (const k of keys || []) {- if (ENTITY_KEYS.has(k)) continue;- errors.push(`${label}: unknown key '${k}'${ENTITY_KEY_HINTS[k] || ''} (allowed: ${[...ENTITY_KEYS].join(', ')})`);- }- }- // `schemaName` must be a non-empty STRING, and the check says so rather than only testing- // truthiness. `!e.schemaName` let `42`, `{}` and `[]` through, and the very next line called- // `.toLowerCase()` on them — so a spec carrying `"schemaName": 42` CRASHED the validator with a- // raw TypeError instead of being told what was wrong. That is the one outcome this function must- // never produce: its whole contract is to turn bad input into structured errors, and a caller- // that gets a TypeError loses every finding collected so far, not just this one. Reachable from- // any hand- or model-authored JSON file, which is how every spec arrives.- //- // The read itself is wrapped only because it is cheap to do so. A getter or Proxy trap that- // throws is NOT comprehensively defended against in this validator — several later passes- // interpolate `e.schemaName` directly — and no attempt is made to pretend otherwise; that shape- // cannot come from `JSON.parse`, only from a programmatic caller.- let schemaNameValue;- let schemaNameReadable = true;- try { schemaNameValue = e.schemaName; } catch { schemaNameReadable = false; }- if (!schemaNameReadable) {- errors.push('entity.schemaName could not be read');- } else if (typeof schemaNameValue !== 'string' || !schemaNameValue.trim()) {- // `undefined`/`null`/`""` keep the original wording: it is the overwhelmingly common case and- // "is required" is the right thing to say about an absent value. A present-but-wrong value- // gets its own message, quoting what was found, because "required" would be actively- // misleading to someone who did supply one.- errors.push(schemaNameValue === undefined || schemaNameValue === null || schemaNameValue === ''- ? 'entity.schemaName is required'- : `entity.schemaName must be a non-empty string (got ${describeSpecValue(schemaNameValue)})`);- } else {- entityNames.add(schemaNameValue);- entityByLower.set(schemaNameValue.toLowerCase(), e);- }- if (!e.primaryAttribute || !e.primaryAttribute.schemaName) {- errors.push(`entity ${e.schemaName}: primaryAttribute.schemaName required`);- }- if (e.quickCreate !== undefined && typeof e.quickCreate !== 'boolean') {- errors.push(`entity ${e.schemaName}: quickCreate must be a boolean`);- }- validateDescription(e.description, `entity ${e.schemaName}`, errors);- for (const c of e.columns || []) {- if (!c.schemaName) {- errors.push(`entity ${e.schemaName}: a column is missing schemaName`);- }- validateDescription(c.description, `entity ${e.schemaName}: column ${c.schemaName}`, errors);- // A Customer column is created through `createCustomerColumn`, whose payload is only- // { Lookup, OneToManyRelationships } — the SDK has nowhere to put a description, so one- // authored here is silently discarded. Warn rather than error: the spec is still valid and- // still builds; the author just needs to know the value will not appear in Dataverse.- if (c.type === 'Customer' && c.description) {- warnings.push(`entity ${e.schemaName}: column ${c.schemaName} is a Customer column — the SDK's createCustomerColumn accepts no description, so this one will NOT be written to Dataverse`);- }- if (c.type && !TYPE_MAP[c.type]) {- errors.push(`entity ${e.schemaName}: column ${c.schemaName} has unknown type '${c.type}'`);- }- if ((c.type === 'Choice' || c.type === 'MultiChoice') && !(Array.isArray(c.options) && c.options.length) && !c.globalChoice) {- errors.push(`column ${c.schemaName}: ${c.type} needs options[] or a globalChoice reference`);- }- // Grid data visualization (preview). Only the enum is enforced. Column-TYPE compatibility is- // deliberately NOT enforced: the SDK does not constrain it either, and the sensible pairings- // are not a clean "numeric only" rule (LineChart is documented for a TEXT column holding- // comma-separated numbers). Guessing a constraint the platform does not have would reject- // valid specs, so type guidance lives in the schema doc instead.- if (c.visualization !== undefined && !COLUMN_VISUALIZATIONS.includes(c.visualization)) {- errors.push(`entity ${e.schemaName}: column ${c.schemaName} has unknown visualization '${c.visualization}' — must be one of ${COLUMN_VISUALIZATIONS.join('|')}`);- }- // AB#6648523: Boolean default value. The SDK used to hardcode `DefaultValue: false`; the- // vendored bundle now honours an explicit value on create AND update (measured against- // cds-maker-sdk.cjs). Boolean-only for the same reason as the form-event flags below — a- // truthy-but-non-boolean value (e.g. the string "false") must be rejected, not coerced — and- // type-gated to the exact 'Boolean' column: the SDK itself throws InvalidArgumentError for- // defaultValue on any other type, so this just moves that same failure to the spec gate and- // names the column instead of surfacing mid-build.- if (c.defaultValue !== undefined) {- if (typeof c.defaultValue !== 'boolean') {- errors.push(`entity ${e.schemaName}: column ${c.schemaName} defaultValue must be a boolean (got ${JSON.stringify(c.defaultValue)})`);- } else if (c.type !== 'Boolean') {- errors.push(`entity ${e.schemaName}: column ${c.schemaName} defaultValue is only valid on a Boolean column (this one is '${c.type || 'Text'}')`);- }- }- // AB#6648522: Whole Number display Format (e.g. render a raw integer count of minutes as a- // Duration picker in the maker UI). Restricted to the exact 'Integer' App Spec type, NOT the- // wider Integer/BigInt/Decimal/Double/Money switch case columnOptions() shares for min/max/- // precision — the SDK's Format option is Integer-only, so a spec targeting Decimal would- // otherwise pass this gate and hit the SDK's own InvalidArgumentError deep inside the- // data-model phase instead of here.- if (c.integerFormat !== undefined) {- if (!INTEGER_FORMATS.includes(c.integerFormat)) {- errors.push(`entity ${e.schemaName}: column ${c.schemaName} has unknown integerFormat '${c.integerFormat}' — must be one of ${INTEGER_FORMATS.join('|')}`);- } else if (c.type !== 'Integer') {- errors.push(`entity ${e.schemaName}: column ${c.schemaName} integerFormat is only valid on an Integer column (this one is '${c.type || 'Text'}')`);- }- }- // AB#6651276: per-verb write/read permissions (e.g. isValidForUpdate:false makes a column- // write-once after creation — the entire point of the feature, so `false` must validate and- // build identically to `true`). Boolean-only, same reasoning as the form-event flags below.- // Type-agnostic per the SDK — every buildable column type accepts these on BOTH create and- // update (measured) — EXCEPT Customer, which is created through createCustomerColumn, a- // wholly separate SDK call whose options carry no such fields. Warned rather than rejected- // there, matching the Customer + description precedent above: the spec stays valid and still- // builds, the author just needs to know the flag will not reach Dataverse.- let hasValidForFlag = false;- for (const flag of ['isValidForCreate', 'isValidForUpdate', 'isValidForRead']) {- if (c[flag] === undefined) continue;- hasValidForFlag = true;- if (typeof c[flag] !== 'boolean') {- errors.push(`entity ${e.schemaName}: column ${c.schemaName} ${flag} must be a boolean (got ${JSON.stringify(c[flag])})`);- }- }- if (hasValidForFlag && c.type === 'Customer') {- warnings.push(`entity ${e.schemaName}: column ${c.schemaName} is a Customer column — the SDK's createCustomerColumn accepts no isValidForCreate/isValidForUpdate/isValidForRead, so these will NOT be written to Dataverse`);- }- }- }- if (!entityNames.size) {- errors.push('at least one entity is required');- }- // Web resources (optional — JS/HTML/CSS shipped for form logic).- const WEB_RESOURCE_KINDS = new Set(['js', 'html', 'css', 'xml', 'png', 'jpg', 'gif', 'xsl', 'ico', 'svg', 'resx']);- const FORM_EVENTS = new Set(['onload', 'onsave', 'onchange']);- const webResourceNames = new Set();- const IMAGE_WR_TYPES = new Set(['png', 'jpg', 'gif', 'svg', 'ico']);- const imageWebResourceNames = new Set();- const svgWebResourceNames = new Set(); // SVG only — valid for a table's vector icon- const rasterWebResourceNames = new Set(); // png/jpg/gif/ico — valid for a table's raster icon- for (const wr of spec.webResources || []) {- if (!wr || !wr.name) { errors.push('a webResource is missing a name'); continue; }- validateDescription(wr.description, `webResource '${wr.name}'`, errors);- webResourceNames.add(wr.name.toLowerCase());- const wrType = String(wr.type || '').toLowerCase();- if (IMAGE_WR_TYPES.has(wrType)) imageWebResourceNames.add(wr.name.toLowerCase());- if (wrType === 'svg') svgWebResourceNames.add(wr.name.toLowerCase());- else if (IMAGE_WR_TYPES.has(wrType)) rasterWebResourceNames.add(wr.name.toLowerCase());- if (!WEB_RESOURCE_KINDS.has(String(wr.type || 'js').toLowerCase())) {- errors.push(`webResource ${wr.name}: type must be one of ${[...WEB_RESOURCE_KINDS].join('|')}`);- }- if (wr.content === undefined && wr.contentBase64 === undefined && !wr.contentPath) {- errors.push(`webResource ${wr.name}: needs content, contentBase64, or contentPath`);- }- }- // #6: a Main form that sets deactivateOtherMainForms must be the ONLY Main form declared for its- // entity. Rationale: forms build concurrently and every Main form on an OWN custom table is promoted- // to isdefault. If a flagged form shares its entity with ANOTHER Main form (flagged or not), the- // sibling can win the isdefault race and then be deactivated by the flagged form's pass — leaving the- // entity's default form INACTIVE (a bricked form experience). Requiring the flagged form to stand- // alone removes the race entirely: the only other active main form is then the stock "Information"- // form (which the build never promotes), so deactivating it is safe.- const mainFormsByEntity = {};- const flaggedByEntity = {};- for (const f of spec.forms || []) {- if (!f || (f.formType !== undefined && f.formType !== 'Main')) continue;- const key = String(f.entity || '').toLowerCase();- mainFormsByEntity[key] = (mainFormsByEntity[key] || 0) + 1;- if (f.deactivateOtherMainForms === true) flaggedByEntity[key] = (flaggedByEntity[key] || 0) + 1;- }- for (const [ent, n] of Object.entries(flaggedByEntity)) {- if (n > 1) {- errors.push(`entity '${ent}': ${n} Main forms set deactivateOtherMainForms — at most one may (two would deactivate each other)`);- } else if ((mainFormsByEntity[ent] || 0) > 1) {- errors.push(`entity '${ent}': a Main form sets deactivateOtherMainForms but the entity declares ${mainFormsByEntity[ent]} Main forms — a flagged form must be the ONLY Main form for its entity (a concurrent build would nondeterministically deactivate the sibling and could leave the default form inactive)`);- }- }- for (const f of spec.forms || []) {- validateDescription(f.description, `form '${f.name || f.entity}'`, errors);- if (!entityNames.has(f.entity)) {- errors.push(`form references unknown entity '${f.entity}'`);- }- if (f.layout !== undefined && f.layout !== 'auto' && f.layout !== 'explicit') {- errors.push(`form ${f.entity}: layout must be 'auto' or 'explicit'`);- }- const formType = f.formType === undefined ? 'Main' : f.formType;- if (!['Main', 'QuickCreate', 'QuickView'].includes(formType)) {- errors.push(`form ${f.entity}: formType must be one of Main|QuickCreate|QuickView`);- }- // Optional author-pinned target: a GUID that reconciles an EXACT existing form when a table has two- // forms of the same (entity, type, name) that type-scoped resolution can't disambiguate. Validated- // here because the build interpolates it UNQUOTED into an Edm.Guid OData filter (a non-GUID would both- // break the query and be an injection seam).- if (f.formId !== undefined && !FORM_GUID_RE.test(String(f.formId))) {- errors.push(`form ${f.entity}: formId '${f.formId}' is not a valid GUID`);- }- if (formType !== 'Main' && Array.isArray(f.subgrids) && f.subgrids.length) {- errors.push(`form ${f.entity}: ${formType} forms can't host sub-grids (Main forms only)`);- }- if (formType === 'QuickView' && Array.isArray(f.events) && f.events.length) {- errors.push(`form ${f.entity}: QuickView forms are read-only and can't have event handlers`);- }- for (const ev of f.events || []) {- if (!ev || !FORM_EVENTS.has(ev.event)) { errors.push(`form ${f.entity}: event must be one of ${[...FORM_EVENTS].join('|')}`); continue; }- if (!ev.library) errors.push(`form ${f.entity}: ${ev.event} handler is missing a library (web-resource name)`);- else if (!webResourceNames.has(String(ev.library).toLowerCase())) errors.push(`form ${f.entity}: ${ev.event} handler references undeclared web resource '${ev.library}'`);- if (!ev.function) errors.push(`form ${f.entity}: ${ev.event} handler is missing a function name`);- if (ev.event === 'onchange' && !ev.attribute) errors.push(`form ${f.entity}: onchange handler requires an attribute (column logical name)`);- // These three are documented as optional with defaults, and are now actually honoured by the- // build (they used to be hardcoded and the authored value discarded). Validate the types so a- // string "false" — which is truthy in JS and would silently enable a handler the author meant- // to disable — is rejected rather than coerced.- for (const flagKey of ['enabled', 'passExecutionContext']) {- if (ev[flagKey] !== undefined && typeof ev[flagKey] !== 'boolean') {- errors.push(`form ${f.entity}: ${ev.event} handler ${flagKey} must be a boolean (got ${JSON.stringify(ev[flagKey])})`);- }- }- if (ev.parameters !== undefined && typeof ev.parameters !== 'string') {- errors.push(`form ${f.entity}: ${ev.event} handler parameters must be a string (a comma-separated argument list)`);- }- }- for (const qv of f.quickViews || []) {- if (!qv || !qv.lookup) { errors.push(`form ${f.entity}: a quickView is missing lookup (the lookup column logical name on this form)`); continue; }- if (!qv.targetEntity || !entityByLower.has(String(qv.targetEntity).toLowerCase())) errors.push(`form ${f.entity}: quickView references unknown targetEntity '${qv.targetEntity}'`);- if (!qv.form) { errors.push(`form ${f.entity}: quickView is missing form (the name of a QuickView form in forms[])`); continue; }- // Resolve by (name, targetEntity) AND prefer the QuickView — a same-named Main on the target entity- // must not shadow the intended QuickView (order-dependent otherwise). The build keys the- // quick-view lookup by (entity, QuickView, name) too.- const qvCandidates = (spec.forms || []).filter((x) => x.name === qv.form && String(x.entity).toLowerCase() === String(qv.targetEntity || '').toLowerCase());- const qf = qvCandidates.find((x) => (x.formType || 'Main') === 'QuickView') || qvCandidates[0];- if (!qf) errors.push(`form ${f.entity}: quickView references form '${qv.form}' (a QuickView on '${qv.targetEntity}') not found in forms[]`);- else if ((qf.formType || 'Main') !== 'QuickView') errors.push(`form ${f.entity}: quickView form '${qv.form}' must have formType: "QuickView"`);- }- if (f.subgrids !== undefined) {- if (!Array.isArray(f.subgrids)) {- errors.push(`form ${f.entity}: subgrids must be an array`);- } else {- for (const sg of f.subgrids) {- if (!sg || !sg.childEntity) {- errors.push(`form ${f.entity}: a subgrid is missing childEntity`);- continue;- }- if (badEntityRef(sg.childEntity, `form ${f.entity}: subgrid childEntity`)) continue;- if (!entityByLower.has(String(sg.childEntity).toLowerCase())) {- errors.push(`form ${f.entity}: subgrid references unknown childEntity '${sg.childEntity}'`);- continue;- }- if (!relationshipFor(spec, f.entity, sg.childEntity) && !manyToManyFor(spec, f.entity, sg.childEntity)) {- errors.push(- `form ${f.entity}: no OneToMany or ManyToMany relationship between '${f.entity}' and subgrid childEntity '${sg.childEntity}'`- );- }- }- }- }- validateFormFieldOptions(f, entityByLower, errors, warnings);- validateFormSecurityRoles(f, spec, errors);- // `layout: 'explicit'` with no `tabs[]` is a spec that asks for one thing and builds another.- // `compileFormIntent` takes the explicit path only when `tabs` is an ARRAY, so this combination- // silently compiles an AUTO layout — while `prune` and the field-positioning rules read as- // explicit-layout behaviour to the author. Rejected rather than warned: the two layouts differ in- // whether a rebuild REMOVES deployed fields, so guessing wrong is destructive.- if (f && f.layout === 'explicit' && !Array.isArray(f.tabs)) {- errors.push(`form '${f.name || f.entity}': layout is 'explicit' but no tabs[] were authored — an explicit layout IS its tabs. Author tabs[], or drop layout: 'explicit' to use the auto layout.`);- }- }- // Two QuickView forms sharing (entity, name) make a quick-view reference — which resolves a QuickView by- // (targetEntity, name) — ambiguous (the build map keeps only one, order-dependently). Reject the- // ambiguity at author time. Main/Card share the "Information" name harmlessly (they're not- // quick-view targets), so this is scoped to QuickView.- const qvIdentity = new Set();- for (const f of spec.forms || []) {- if (!f || (f.formType || 'Main') !== 'QuickView' || !f.name) continue;- const key = `${String(f.entity).toLowerCase()}|${String(f.name).toLowerCase()}`;- if (qvIdentity.has(key)) errors.push(`form ${f.entity}: duplicate QuickView form '${f.name}' — two QuickView forms on one table can't share a name (a quick-view reference resolves a QuickView by name)`);- qvIdentity.add(key);- }- for (const ch of spec.charts || []) {- validateDescription(ch && ch.description, `chart '${(ch && (ch.name || ch.entity)) || '(unnamed)'}'`, errors);- if (!ch || badEntityRef(ch.entity, `chart '${(ch && (ch.name || ch.entity)) || '(unnamed)'}'`)) continue;- if (!ch.entity || !entityByLower.has(String(ch.entity).toLowerCase())) {- errors.push(`chart references unknown entity '${ch && ch.entity}'`);- continue;- }- if (!ch.name) {- errors.push(`chart on '${ch.entity}': name is required`);- }- if (!CHART_TYPES.includes(ch.chartType)) {- errors.push(`chart '${ch.name || ch.entity}': chartType must be one of ${CHART_TYPES.join('|')}`);- }- const entity = entityByLower.get(String(ch.entity).toLowerCase());- const choiceCol =- entity &&- (entity.columns || []).find(- (c) => c.type === 'Choice' && c.schemaName.toLowerCase() === String(ch.groupBy || '').toLowerCase()- );- if (!choiceCol) {- errors.push(`chart '${ch.name || ch.entity}': groupBy '${ch.groupBy}' is not a Choice column on '${ch.entity}'`);- }- }- for (const v of spec.views || []) {- const vlabel = `view '${(v && (v.name || v.entity)) || '(unnamed)'}'`;- validateDescription(v && v.description, vlabel, errors);- if (!entityNames.has(v.entity)) {- errors.push(`view references unknown entity '${v.entity}'`);- }- // A column/attribute reference is STRINGIFIED downstream, never type-checked: `viewDef` maps- // every one of them with `String(x).toLowerCase()`. So a non-string is not rejected — it is- // silently turned into text, and an object becomes the literal `[object object]`, which lands- // in the view's fetchxml. Dataverse refuses it with an opaque metadata error ("entity doesn't- // contain attribute with Name = '[object object]'") mid-build, after the solution, tables and- // columns already exist.- //- // The damage outlives that run. The savedquery row is created holding the bad fetchxml, so- // every later READ of it also 400s and the next build dies at the same step; Dataverse reports- // the row as system-defined and refuses to delete it, so recovery means tearing the table down.- // https://github.com/microsoft/power-platform-skills/issues/525- //- // `{ "name": "..." }` is not an exotic mistake: it is exactly the shape `forms[]` uses for its- // fields, so an author moving between the two surfaces writes it naturally.- const attrRef = (value, where) => {- if (typeof value !== 'string' || !value.trim()) {- errors.push(`${vlabel}: ${where} must be a non-empty column name (a string), got ${describeValue(value)}`);- }- };- if (v && v.columns !== undefined) {- if (!Array.isArray(v.columns)) errors.push(`${vlabel}: columns must be an array of column names`);- else v.columns.forEach((c, i) => attrRef(c, `columns[${i}]`));- }- if (v && v.sort !== undefined) {- if (!Array.isArray(v.sort)) errors.push(`${vlabel}: sort must be an array`);- else v.sort.forEach((s, i) => attrRef(s && s.attr, `sort[${i}].attr`));- }- if (v && v.filters !== undefined) {- if (!Array.isArray(v.filters)) errors.push(`${vlabel}: filters must be an array`);- else v.filters.forEach((f, i) => attrRef(f && f.attr, `filters[${i}].attr`));- }- }- // Commands (modern command-bar buttons). A functional button needs a JS library + function;- // the library must be a declared web resource (the on-click binds to it).- const COMMAND_LOCATIONS = new Set(['MainTab', 'HomeTab', 'ContextualTab']);- const COMMAND_TYPES = new Set(['Button', 'FlyoutAnchor', 'SplitButton']);- // A leaf button (top-level or a flyout child) needs a JS library + function; the library must be- // a declared web resource (the on-click binds to it).- const checkCmdAction = (where, library, fn) => {- if (!library) errors.push(`${where}: library (web-resource name) is required`);- else if (!webResourceNames.has(String(library).toLowerCase())) errors.push(`${where}: library '${library}' is not a declared webResources[] name`);- if (!fn) errors.push(`${where}: function (JS function name) is required`);- };- for (const c of spec.commands || []) {- if (!c || !c.entity || !entityNames.has(c.entity)) { errors.push(`command references unknown entity '${c && c.entity}'`); continue; }- // The SDK's command surface drops `description` (the artifact it returns carries only- // commandBars/entityLogicalName/id), so one authored here never reaches Dataverse. Warn rather- // than error — the spec is otherwise valid — but do not let it pass silently.- if (c.description) {- warnings.push(`command '${c.label || c.entity}': the SDK's command surface accepts no description, so this one will NOT be written to Dataverse`);- }- if (!c.label) errors.push(`command on ${c.entity}: label is required`);- if (c.location && !COMMAND_LOCATIONS.has(c.location)) errors.push(`command '${c.label}' on ${c.entity}: location must be MainTab|HomeTab|ContextualTab`);- const type = c.type || 'Button';- if (!COMMAND_TYPES.has(type)) errors.push(`command '${c.label}' on ${c.entity}: type must be Button|FlyoutAnchor|SplitButton`);- if (type === 'FlyoutAnchor' || type === 'SplitButton') {- // A flyout/split container holds child buttons; it has no on-click of its own.- if (!Array.isArray(c.children) || !c.children.length) errors.push(`command '${c.label}' on ${c.entity}: a ${type} needs children[] (its menu buttons)`);- for (const ch of c.children || []) {- if (!ch || !ch.label) { errors.push(`command '${c.label}' on ${c.entity}: a child button is missing a label`); continue; }- checkCmdAction(`command '${c.label}' child '${ch.label}' on ${c.entity}`, ch.library, ch.function);- }- } else {- checkCmdAction(`command '${c.label}' on ${c.entity}`, c.library, c.function);- }- }- // Business rules. Every reference is checked against the spec's own columns, because a rule that- // names a column the app does not create is authored against nothing — and the platform accepts it- // silently (the rule just never fires), so nothing downstream would catch it.- for (const r of spec.businessRules || []) {- const label = `business rule '${(r && r.name) || '(unnamed)'}'`;- if (!r || typeof r !== 'object' || Array.isArray(r)) { errors.push('businessRules[] entries must be objects'); continue; }- validateDescription(r.description, label, errors);- if (!r.name) errors.push(`${label}: name is required`);- if (!r.entity || !entityNames.has(r.entity)) { errors.push(`${label}: references unknown entity '${r.entity}'`); continue; }- if (r.scope !== undefined && !BUSINESS_RULE_SCOPES.includes(r.scope)) {- errors.push(`${label}: scope must be ${BUSINESS_RULE_SCOPES.join('|')} (a form-scoped rule needs a form id that does not exist until the forms phase runs)`);- }- if (r.status !== undefined && !['Active', 'Draft'].includes(r.status)) {- errors.push(`${label}: status must be Active|Draft`);- }-- // Columns the rule may reference: the entity's own declared columns plus its primary name.- const cols = declaredColumnLogicals(spec, r.entity);- const checkField = (field, what) => {- if (!field) { errors.push(`${label}: ${what} needs a field`); return; }- if (cols.size && !cols.has(String(field).toLowerCase())) {- errors.push(`${label}: ${what} references '${field}', which is not a column on ${r.entity}`);- }- };-- if (!Array.isArray(r.conditions) || !r.conditions.length) {- errors.push(`${label}: conditions[] is required (a rule with no condition would apply unconditionally, which the SDK serializes as an empty rule that silently never fires)`);- }- for (const c of r.conditions || []) {- if (!c || typeof c !== 'object') { errors.push(`${label}: each condition must be an object`); continue; }- checkField(c.field, 'condition');- if (!BUSINESS_RULE_OPERATORS.includes(c.operator)) {- // Name the platform failure rather than pretending the operator is unrecognised: an author- // who reaches for a blocked operator has written something reasonable that we cannot deploy.- if (BUSINESS_RULE_BLOCKED_OPERATORS.has(c.operator)) {- errors.push(`${label}: operator '${c.operator}' is not usable — see https://github.com/microsoft/power-platform-skills/issues/481`);- } else {- // The near-misses matter more than the nonsense here. `GreaterThan` is a natural thing to- // write and is NOT in the SDK's table, and the serializer resolves an unknown operator to- // Equals — so without this gate that spec would deploy an equality test. Name the closest- // legal spelling so the fix is obvious.- const near = BUSINESS_RULE_OPERATORS.find((o) => o.toLowerCase() === `is${String(c.operator).toLowerCase()}`- || o.toLowerCase().replace(/^is/, '') === String(c.operator).toLowerCase()- || o.toLowerCase() === String(c.operator).toLowerCase());- errors.push(`${label}: condition operator must be one of ${BUSINESS_RULE_OPERATORS.join('|')} (got '${c.operator}')${near ? ` — did you mean '${near}'?` : ''}`);- }- continue;- }- const valueless = BUSINESS_RULE_VALUELESS_OPERATORS.has(c.operator);- if (valueless && c.value !== undefined) {- errors.push(`${label}: '${c.operator}' tests presence, so it must not carry a value`);- }- if (!valueless && (c.value === undefined || c.value === null || c.value === '')) {- errors.push(`${label}: '${c.operator}' needs a value`);- }- if (c.dataType !== undefined && !BUSINESS_RULE_DATA_TYPES.includes(c.dataType)) {- // Name the offending value: this is a curated closed set with no bundle counterpart, and the- // most likely mistake is a plausible-but-absent type (DateTime is the classic one), so- // echoing what was written is what makes the message actionable.- errors.push(`${label}: condition dataType '${c.dataType}' is not supported — must be one of ${BUSINESS_RULE_DATA_TYPES.join('|')}`);- }- }-- if (!Array.isArray(r.actions) || !r.actions.length) {- errors.push(`${label}: actions[] is required (a rule that does nothing is not worth deploying)`);- }- for (const a of r.actions || []) {- if (!a || typeof a !== 'object') { errors.push(`${label}: each action must be an object`); continue; }- if (!BUSINESS_RULE_ACTION_TYPES.includes(a.type)) {- errors.push(`${label}: action type must be one of ${BUSINESS_RULE_ACTION_TYPES.join('|')} (got '${a.type}')`);- continue;- }- checkField(a.field, `action '${a.type}'`);- const payload = BUSINESS_RULE_ACTIONS[a.type];- if (a[payload] === undefined) {- errors.push(`${label}: action '${a.type}' needs '${payload}'`);- } else if (BUSINESS_RULE_BOOLEAN_ACTIONS.has(a.type) && typeof a[payload] !== 'boolean') {- // A string "false" is truthy, so coercing here would invert the author's intent silently.- errors.push(`${label}: action '${a.type}'.${payload} must be a boolean`);- }- if (a.type === 'SetFieldValue' && a.dataType !== undefined && !BUSINESS_RULE_DATA_TYPES.includes(a.dataType)) {- errors.push(`${label}: action dataType must be one of ${BUSINESS_RULE_DATA_TYPES.join('|')}`);- }- }- }- // Business process flows. Same discipline as business rules and for the same reason: the platform- // accepts a BPF whose step names a column that does not exist, materializes its stages, and then- // simply renders a step bound to nothing — no error at deploy time, and nothing downstream to- // catch it. So every field is checked against the flow's own entity here.- const bpfUniques = new Map();- for (const p of spec.businessProcessFlows || []) {- const label = `business process flow '${(p && p.name) || '(unnamed)'}'`;- if (!p || typeof p !== 'object' || Array.isArray(p)) { errors.push('businessProcessFlows[] entries must be objects'); continue; }- if (!p.name) errors.push(`${label}: name is required`);- else if (typeof p.name !== 'string' || !p.name.trim()) {- // The SDK derives the server unique name by lower-casing this value, so a non-string reaches- // `.toLowerCase()` and dies with a TypeError inside the bundle rather than a spec error here.- errors.push(`${label}: name must be a non-empty string`);- } else {- // Keyed on the DERIVED unique name, not on (entity, name). The build identifies a flow by- // (entity, name) for reuse, but the SERVER identity the SDK derives ignores the entity and- // strips case/punctuation — so an (entity, name) key would let two flows through that cannot- // both exist. See bpfUniqueName.- const unique = bpfUniqueName(p.name);- const clash = bpfUniques.get(unique);- if (clash !== undefined) {- errors.push(`${label}: collides with '${clash}' — both derive the Dataverse unique name '${unique}' (the derivation lower-cases the name, strips punctuation, and ignores the table). Activation creates a backing table with that name, so the second flow cannot deploy. Rename one, e.g. "${p.name} (Cases)".`);- } else {- bpfUniques.set(unique, p.name);- }- // The derived name is a TABLE name, so it collides with tables too — not only with other- // flows. Activation creates an org-owned backing table called `unique`, and a table with that- // logical name cannot be created twice.- //- // This axis is easy to hit precisely because the derivation ignores the solution's publisher- // prefix and always emits `new_`: on a spec using the default `new` prefix, a flow named after- // its own table ("Ticket" on `new_ticket`) derives exactly that table's logical name. Without- // this check it validates clean and then fails in the business-process-flows phase — after the- // solution, tables, columns, views, forms and the app already exist — with a platform error- // naming a table the author never meant to create.- //- // `existing: true` tables are included deliberately: the build does not create them, but they- // are still in the org, so the backing table clashes just the same.- const tableClash = entityByLower.get(unique);- if (tableClash) {- errors.push(`${label}: derives the Dataverse unique name '${unique}', which is already the logical name of the table '${tableClash.schemaName}' in this spec. Activating a flow creates a backing table with that name (the derivation lower-cases the name, strips punctuation, and always uses the 'new_' prefix regardless of your publisher prefix), so the flow cannot deploy. Rename the flow, e.g. "${p.name} Process".`);- }- }- if (!p.entity || !entityNames.has(p.entity)) { errors.push(`${label}: references unknown entity '${p.entity}'`); continue; }- if (p.status !== undefined && !BPF_STATUSES.includes(p.status)) {- errors.push(`${label}: status must be ${BPF_STATUSES.join('|')}`);- }- if (p.order !== undefined && (!Number.isInteger(p.order) || p.order < 1)) {- errors.push(`${label}: order must be a positive integer (it becomes the workflow's processorder)`);- }- // Allow-list the flow's own keys for the same reason as the stage/step ones below: naming only the- // three knobs we knew about left others (the SDK also models `globalActions`) neither mapped nor- // rejected — silently dropped, which is the failure this guard exists to prevent.- const BPF_FLOW_KEYS = new Set(['name', 'entity', 'description', 'status', 'order', 'stages']);- for (const k of Object.keys(p)) {- if (!BPF_FLOW_KEYS.has(k)) {- errors.push(`${label}: unsupported key '${k}' (allowed: ${[...BPF_FLOW_KEYS].join(', ')}). Security-role grants, branching and process actions are modelled by the SDK but cannot be verified by this build, so they are rejected rather than silently dropped — configure them in Maker after the flow deploys.`);- }- }- const cols = declaredColumnLogicals(spec, p.entity);- validateDescription(p.description, label, errors);- if (!Array.isArray(p.stages) || !p.stages.length) {- errors.push(`${label}: stages[] is required (a flow with no stage is not a process)`);- continue;- }- // The SDK enforces a hard ceiling of 30 stages per flow and 30 steps per stage. Without these- // the spec validates, the build runs, and the SDK throws in a late phase with the earlier- // artifacts already created — the same half-built-app failure the step-field rule above exists- // to prevent.- if (p.stages.length > BPF_MAX_STAGES) {- errors.push(`${label}: ${p.stages.length} stages — the platform allows at most ${BPF_MAX_STAGES}`);- }- const stageNames = new Set();- for (const st of p.stages) {- if (!st || typeof st !== 'object' || Array.isArray(st)) { errors.push(`${label}: each stage must be an object`); continue; }- if (!st.name) { errors.push(`${label}: every stage needs a name`); continue; }- if (stageNames.has(st.name)) errors.push(`${label}: duplicate stage name '${st.name}'`);- stageNames.add(st.name);- // Reject an unmapped stage key rather than dropping it. `branch`, `actions`, `nextStageId`,- // `category` and `relationshipName` are STAGE-level in the SDK's model — which is exactly where- // an author would write them — and bpfDef maps only name/entity/steps, so without this they- // would vanish silently.- for (const k of Object.keys(st)) {- if (!BPF_STAGE_KEYS.has(k)) {- errors.push(`${label}: stage '${st.name}' has unsupported key '${k}' (allowed: ${[...BPF_STAGE_KEYS].join(', ')}). Branching, stage actions and cross-entity flow are modelled by the SDK but cannot be verified by this build, so they are rejected rather than silently dropped — configure them in Maker.`);- }- }- // v1 is single-entity: a stage on another table is a cross-entity flow, which changes what the- // process means (it spans records) and is rejected rather than silently retargeted.- if (st.entity !== undefined && st.entity !== p.entity) {- errors.push(`${label}: stage '${st.name}' targets '${st.entity}' — cross-entity flows are not supported; every stage must be on ${p.entity}`);- }- if (st.steps !== undefined && !Array.isArray(st.steps)) {- errors.push(`${label}: stage '${st.name}': steps must be an array`);- continue;- }- // A stage MUST carry at least one step. The SDK's createDefault substitutes a placeholder step- // literally named "New Step" when a stage has none, so an empty stage deploys a step the author- // never wrote (and the SDK's own `stage-needs-step` rule never fires, because the placeholder is- // injected before it looks).- if (!(st.steps || []).length) {- errors.push(`${label}: stage '${st.name}' has no steps — a stage with none deploys a placeholder step named "New Step" that you did not author`);- }- if ((st.steps || []).length > BPF_MAX_STEPS) {- errors.push(`${label}: stage '${st.name}' has ${st.steps.length} steps — the platform allows at most ${BPF_MAX_STEPS} per stage`);- }- const stepNames = new Set();- for (const step of st.steps || []) {- if (!step || typeof step !== 'object' || Array.isArray(step)) { errors.push(`${label}: stage '${st.name}': each step must be an object`); continue; }- if (!step.name) { errors.push(`${label}: stage '${st.name}': every step needs a name`); continue; }- if (stepNames.has(step.name)) errors.push(`${label}: stage '${st.name}': duplicate step name '${step.name}'`);- stepNames.add(step.name);- // Same reason as the stage allow-list, and the likeliest instance of it: a step written with- // `fieldLogicalName` (the name used elsewhere in the SDK's own artifact shapes) is dropped by- // the step normalizer and deploys bound to nothing.- for (const k of Object.keys(step)) {- if (!BPF_STEP_KEYS.has(k)) {- errors.push(`${label}: stage '${st.name}' step '${step.name}' has unsupported key '${k}' (allowed: ${[...BPF_STEP_KEYS].join(', ')}${k === 'fieldLogicalName' ? " — the column key is 'field'" : ''})`);- }- }- // `field` is REQUIRED on every step. This was originally modelled as optional — a step with- // no field was documented as a "checklist item" — but the platform rejects it outright:- //- // HTTP 400 from .../api/data/v9.0/workflows(<id>)- // Attribute - datafieldname of ControlStep cannot be null or empty- //- // MEASURED live, and isolated by A/B: the identical flow with every step bound to a column- // deploys and activates cleanly. Because the push happens in a late phase, accepting the- // shape here meant the build HALTED after the solution, table, columns, views and forms were- // already created — the author got a half-built app and a platform error naming an internal- // XAML element they never wrote. So it is rejected up front, where it is actionable.- //- // `null` and a blank/whitespace string are the SAME defect as `undefined` and must give the- // same message. Treating only `undefined` as missing let them fall through to the column- // check, which reported `references ''` — or, worse, `references 'null'` from stringifying- // the value — instead of saying what was actually wrong.- const fieldGiven = step.field !== undefined && step.field !== null && String(step.field).trim() !== '';- if (!fieldGiven) {- errors.push(`${label}: stage '${st.name}' step '${step.name}' binds no field — every step must set 'field' (the platform rejects a step with no column: "datafieldname of ControlStep cannot be null or empty"). For a manual check-off, bind a Boolean column such as a "Confirmed" flag.`);- } else if (cols.size && !cols.has(String(step.field).toLowerCase())) {- errors.push(`${label}: stage '${st.name}' step '${step.name}' references '${step.field}', which is not a column on ${p.entity}`);- }- if (step.required !== undefined && typeof step.required !== 'boolean') {- errors.push(`${label}: stage '${st.name}' step '${step.name}': required must be a boolean`);- }- }- }- }- // Dashboards: chart/list tiles reference a declared chart/view; iframe needs a url; webresource a- // declared web resource.- const DASH_TILE_TYPES = new Set(['chart', 'list', 'iframe', 'webresource']);- const viewNamesSet = new Set((spec.views || []).map((v) => v.name));- const chartNamesSet = new Set((spec.charts || []).map((c) => c.name));- for (const d of spec.dashboards || []) {- if (!d || !d.name) { errors.push('a dashboard is missing a name'); continue; }- validateDescription(d.description, `dashboard '${d.name}'`, errors);- if (!Array.isArray(d.tiles) || !d.tiles.length) { errors.push(`dashboard '${d.name}': needs tiles[]`); continue; }- for (const t of d.tiles) {- if (!t || !DASH_TILE_TYPES.has(t.type)) { errors.push(`dashboard '${d.name}': tile type must be chart|list|iframe|webresource`); continue; }- // ID-passthrough tiles (from a round-tripped/downloaded app) carry the deployed view/chart ids- // + entity directly instead of names — they bind to existing artifacts, so skip the name checks.- const byId = t.viewId || t.visualizationId;- if (t.type === 'chart') {- if (byId) {- if (!t.viewId) errors.push(`dashboard '${d.name}': chart tile with visualizationId also needs viewId`);- if (!t.entity) errors.push(`dashboard '${d.name}': id-based chart tile needs entity`);- else badEntityRef(t.entity, `dashboard '${d.name}': chart tile`);- } else {- if (!t.chart || !chartNamesSet.has(t.chart)) errors.push(`dashboard '${d.name}': chart tile references unknown chart '${t.chart}'`);- if (!t.view || !viewNamesSet.has(t.view)) errors.push(`dashboard '${d.name}': chart tile needs a declared view for its data — '${t.view}' not found`);- }- } else if (t.type === 'list') {- if (byId) {- if (!t.entity) errors.push(`dashboard '${d.name}': id-based list tile needs entity`);- else badEntityRef(t.entity, `dashboard '${d.name}': list tile`);- } else if (!t.view || !viewNamesSet.has(t.view)) {- errors.push(`dashboard '${d.name}': list tile references unknown view '${t.view}'`);- }- } else if (t.type === 'iframe') {- if (!t.url) errors.push(`dashboard '${d.name}': iframe tile needs a url`);- else if (!isSafeHttpUrl(t.url)) errors.push(`dashboard '${d.name}': iframe tile url must be an http(s) URL (got '${t.url}')`);- if (!t.name) errors.push(`dashboard '${d.name}': iframe tile needs a name`);- } else if (t.type === 'webresource') {- if (!t.webResource || !webResourceNames.has(String(t.webResource).toLowerCase())) errors.push(`dashboard '${d.name}': webresource tile references undeclared web resource '${t.webResource}'`);- if (!t.name) errors.push(`dashboard '${d.name}': webresource tile needs a name`);- }- }- }- const dashNamesSet = new Set((spec.dashboards || []).map((d) => d && d.name).filter(Boolean));- // Generative pages. Each needs a name. Implementation state is a discriminated `source`- // (`intent` | `tsx`+codeFile); a legacy top-level `codeFile` is accepted as an implemented tsx.- // The `deploy` profile requires every page implemented; `design`/`plan` allow intent (the page's- // .tsx is produced by generate-pages after approval); `structural` ignores implementation.- // isV2/pageKeysSet are declared here — before the page loop — so the appShell subarea loop that- // follows can also reference them (both loops live in the same function scope). pageNamesSet is- // kept for legacy (schemaVersion < 2) appShell page refs; pageRefSet selects the right set.- const isV2 = (spec.schemaVersion || 0) >= 2;- const pageKeysSet = new Set();- const pageNamesSet = new Set();- // Stable-key grammar (schemaVersion 2): lowercase slug — alphanumerics + internal single hyphens,- // no leading/trailing hyphen, no underscores/spaces/uppercase. migrateAppSpec mints keys via- // slugify (:686) which always conforms; a hand-authored v2 key must too, since the key is the- // cross-reference identity (navigatesTo.targetKey, PAGEREF_<key>, appShell page subareas).- const PAGE_KEY_GRAMMAR = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;- // GUID pattern for pages[].pageId — a 36-char hyphenated hex UUID as minted by Dataverse / PAC CLI.- // A spec page carrying this field is an EDIT-SNAPSHOT (env-specific, downloaded from a live app);- // a portable fresh-authored spec omits it. When present it must be exactly this shape so- // reconcilePageIds can use it as the highest identity authority without silently accepting garbage- // (e.g. a cross-env GUID that happens to match an unrelated page). Addenda Task 4 / C3.- const PAGE_ID_GUID = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;- const pageCodeFilesNorm = new Set(); // implemented-page normalized codeFile uniqueness (Critical 4)- // A codeFile must resolve INSIDE the working directory. Use path.normalize to canonicalize before- // checking — this catches aliases like 'pages/./x.tsx' and 'pages/../pages/x.tsx' that resolve to- // the same file but evade a naive string-split check (addendum Crit 4). path.isAbsolute is- // platform-specific (on POSIX it does NOT flag a Windows drive-letter path like 'C:/x'), so we ALSO- // match a drive-letter prefix explicitly — a spec authored on Windows must be rejected the same way- // on a Linux CI runner. After normalization, a path starting with '..' has escaped the workspace- // root. sdk-build resolves codeFile with path.resolve(appDir, codeFile) at :1037-1041, so an- // unconfined path reaches the filesystem outside the app folder — reject it here, before any write. Design §7.2.- const codeFileConfined = (codeFile) => {- const cf = String(codeFile);- // Drive-letter guard (/^[a-zA-Z]:[/\\]/) catches 'C:\x'/'C:/x' on POSIX where path.isAbsolute misses it.- if (path.isAbsolute(cf) || /^[a-zA-Z]:[/\\]/.test(cf)) return false;- const normalized = path.normalize(cf);- // normalized === '..' means the codeFile IS the parent directory.- // normalized.startsWith('..' + path.sep) means it is a path beneath the parent directory.- return normalized !== '..' && !normalized.startsWith('..' + path.sep);- };- for (const p of spec.pages || []) {- if (!p || !p.name) { errors.push('a page is missing a name'); continue; }- pageNamesSet.add(p.name);- // NOTE: case-insensitive page-name uniqueness is enforced in a dedicated pass AFTER this loop- // (see "page-name uniqueness" below) so it can distinguish a NEW page from a PRE-EXISTING one.- // A page MAY carry its own deployed `pageId` (edit-snapshot marker). A portable fresh-authored spec- // omits it — absence is never an error. When present it MUST be a valid 36-char GUID: the- // reconcilePageIds authority logic (addenda Task 4 / C3) consumes it as the HIGHEST identity source,- // so silently accepting a malformed / empty value would cause reconcile to bind the wrong page.- if (p.pageId !== undefined && !PAGE_ID_GUID.test(String(p.pageId))) {- errors.push(`page '${p.key || p.name}': pageId must be a 36-char GUID`);- }- const src = normalizePageSource(p);- // Track whether a structural source error was emitted so the profile check below doesn't- // double-report (e.g. source:{kind:'tsx'} with no codeFile should get ONE error, not two).- let structuralSourceOk = true;- if (src && src.kind !== 'intent' && src.kind !== 'tsx') {- errors.push(`page '${p.key || p.name}': source.kind must be 'intent' or 'tsx'`);- structuralSourceOk = false;- } else if (src && src.kind === 'tsx' && (typeof src.codeFile !== 'string' || !src.codeFile)) {- errors.push(`page '${p.key || p.name}': source.kind 'tsx' needs a codeFile (path to the .tsx)`);- structuralSourceOk = false;- }- if (structuralSourceOk) {- if (profile === 'deploy') {- if (!(src && src.kind === 'tsx' && typeof src.codeFile === 'string' && src.codeFile)) {- errors.push(`page '${p.key || p.name}': must be implemented (source.kind 'tsx' with a codeFile) for a deploy build — run generate-pages`);- }- } else if (profile !== 'structural' && src === null) {- // design/plan still require SOME declared source (intent or tsx) — a page with neither is a- // spec error, not a valid design.- errors.push(`page '${p.key || p.name}': needs a source ({ kind: 'intent' } or { kind: 'tsx', codeFile })`);- }- }- // codeFile confinement + path-uniqueness (Critical 4). Only checked for implemented tsx pages- // (intent pages have no codeFile; the codeFile presence was already validated above). Normalize- // the path before checking so that 'pages/./x.tsx' and 'pages/../pages/x.tsx' are detected as- // duplicates of 'pages/x.tsx' (addendum Crit 4). Replace backslashes with forward slashes before- // lowercasing for cross-platform-safe comparison in the set.- if (src && src.kind === 'tsx' && typeof src.codeFile === 'string' && src.codeFile) {- if (!codeFileConfined(src.codeFile)) {- errors.push(`page '${p.key || p.name}': codeFile '${src.codeFile}' must be a workspace-confined relative path (no '..' escape, no absolute path)`);- }- const cfNorm = path.normalize(src.codeFile).replace(/\\/g, '/').toLowerCase();- if (pageCodeFilesNorm.has(cfNorm)) errors.push(`page '${p.key || p.name}': duplicate codeFile '${src.codeFile}' (another page already uses this path)`);- else pageCodeFilesNorm.add(cfNorm);- }- // schemaVersion 2 adds a required, unique stable key per page so pages can be referenced by an- // identity that survives renames. The key is also what navigatesTo.targetKey and appShell page- // subareas use (key-based refs replace name-based refs for v2 specs).- if (isV2) {- if (!p.key || typeof p.key !== 'string') errors.push(`page '${p.name}': needs a stable key (schemaVersion 2)`);- else if (!PAGE_KEY_GRAMMAR.test(p.key)) errors.push(`page '${p.name}': key '${p.key}' has an invalid key grammar (lowercase slug: ^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$)`);- else if (pageKeysSet.has(p.key)) errors.push(`duplicate page key '${p.key}'`);- else pageKeysSet.add(p.key);- }- }- // Page-name uniqueness (case-insensitive) — SCOPED to what the current run authors. Two pages that- // share a name (e.g. 'Overview' vs 'overview') are confusing in the app navigation. BUT a downloaded- // edit-snapshot can legitimately carry a PRE-EXISTING duplicate the run did NOT create (two pages- // authored by different people/tools), and blocking every build — even an unrelated form edit that- // never touches pages — on a dupe the run is not changing is wrong (the pages phase matches by id/key,- // never by name: genpage-cli.js enumerateEnv is id-keyed, and download's assignPageKeys de-dups keys- // with a -N suffix, so distinct-id same-name pages build fine). Signal: a page carrying a deployed- // `pageId` is PRE-EXISTING (an edit-snapshot marker); a page WITHOUT one is NEW (authored this run).- // - collision involving a NEW page → ERROR (prevent authoring/adding a duplicate)- // - collision purely among PRE-EXISTING pages → WARNING (tolerate; rename one in Maker to fix nav)- const nameGroups = new Map(); // nameLower -> { display, count, anyNew }- for (const p of spec.pages || []) {- if (!p || !p.name) continue;- const nl = String(p.name).toLowerCase();- const g = nameGroups.get(nl) || { display: p.name, count: 0, anyNew: false };- g.count += 1;- if (!p.pageId) g.anyNew = true; // no deployed id ⇒ this page is being created/authored by this run- nameGroups.set(nl, g);- }- for (const g of nameGroups.values()) {- if (g.count <= 1) continue;- if (g.anyNew) errors.push(`duplicate page name '${g.display}' (page names must be unique, case-insensitive)`);- else warnings.push(`pre-existing duplicate page name '${g.display}' — ${g.count} deployed pages share this name (case-insensitive); tolerated because this build does not create them, but the app navigation is ambiguous. Rename one in Maker (or a fresh spec) to disambiguate.`);- }- // Navigation graph (v2 only — these fields don't exist in hand-authored legacy specs):- // every navigatesTo.targetKey must resolve to a known page key. pageInput shape is validated- // here too (object, not array/null).- if (isV2) {- for (const p of spec.pages || []) {- for (const nav of p.navigatesTo || []) {- if (!nav || typeof nav.targetKey !== 'string') { errors.push(`page '${p.key || p.name}': navigatesTo entry needs a targetKey`); continue; }- if (!pageKeysSet.has(nav.targetKey)) errors.push(`page '${p.key || p.name}': navigatesTo target '${nav.targetKey}' is not a known page key`);- if (nav.data !== undefined && (typeof nav.data !== 'object' || nav.data === null || Array.isArray(nav.data))) errors.push(`page '${p.key || p.name}': navigatesTo.data must be an object`);- }- if (p.pageInput !== undefined) {- if (typeof p.pageInput !== 'object' || p.pageInput === null || Array.isArray(p.pageInput)) errors.push(`page '${p.key || p.name}': pageInput must be an object`);- }- }- // INPUT CONTRACT. These two rules together resolve a policy conflict that was previously left- // implicit, and that a page author had no way to satisfy:- //- // - Every page MUST be sitemap-placed (the MEMBERSHIP invariant above): the sitemap is the- // download's only membership oracle, so a page reached only by navigation is invisible to- // download and gets re-created as a duplicate on the next build.- // - But a DETAIL page declares `pageInput` (e.g. `{ data: { orderId: 'string' } }`) because it- // is opened from a list with a row id.- //- // Being sitemap-placed means the page is ALSO reachable straight from the app's navigation, with- // NO input at all. That is a real, user-reachable state — it is what a user gets by clicking the- // nav entry — and previously nothing made the author account for it, so the generated page would- // render against `undefined` context. Rather than weaken the membership invariant (which would- // reintroduce duplicate pages on every rebuild), require the author to say what direct entry- // does. `directEntry` is that answer, and page-plan feeds it to the generator.- for (const p of spec.pages || []) {- const key = p.key || p.name;- const inputKeys = Object.keys((p.pageInput && p.pageInput.data) || {});- if (!inputKeys.length) continue;-- if (p.directEntry === undefined) {- errors.push(`page '${key}' declares pageInput (${inputKeys.join(', ')}) but no directEntry — every page is sitemap-placed, so a user can open it from the app navigation with no input. Declare directEntry: { "behavior": "selector" | "emptyState", "note": "…" } to say what that shows.`);- } else if (typeof p.directEntry !== 'object' || p.directEntry === null || Array.isArray(p.directEntry)) {- errors.push(`page '${key}': directEntry must be an object`);- } else if (!DIRECT_ENTRY_BEHAVIORS.includes(p.directEntry.behavior)) {- errors.push(`page '${key}': directEntry.behavior must be one of ${DIRECT_ENTRY_BEHAVIORS.join('|')}`);- }-- // Trace each declared input back to a navigation edge that actually produces it. An input no- // caller supplies is either a typo or a page that can ONLY ever be entered directly — both are- // worth failing on, because the generated page would read a key nothing ever sets.- //- // EXCEPT when the spec was RECONSTRUCTED from a deployed app (`opts.reconstructed`, set by- // download). This is an authoring rule: it gates what you are about to create. A reconstruction- // describes an app that ALREADY EXISTS, and download validates before it writes — so treating- // it as fatal there produces no spec file at all and strands the author with nothing to edit,- // which is the #430 failure this release exists to fix. A page whose manifest predates the rule- // (input supplied externally, or from its own .tsx) hits exactly that. Reported as a warning- // instead: the author gets the file, the finding, and the chance to fix it.- const produced = new Set();- for (const other of spec.pages || []) {- for (const nav of other.navigatesTo || []) {- if (nav && nav.targetKey === key) for (const k of Object.keys((nav.data) || {})) produced.add(k);- }- }- const orphaned = inputKeys.filter((k) => !produced.has(k));- if (orphaned.length) {- const msg = `page '${key}': pageInput declares ${orphaned.map((k) => `'${k}'`).join(', ')} but no page navigates to it with that data — add it to the producing page's navigatesTo[].data, or drop it from pageInput.`;- if (opts.reconstructed) warnings.push(msg);- else errors.push(msg);- }- }- }- // Icons are chrome, not a target. An `icon` that is a **platform reference** (a path or- // `$webresource:` — see isPlatformIconRef) is a live/OOB value a downloaded app carries and is valid- // AS-IS (rejecting it broke the download→build round-trip on real apps). Only a BARE NAME is treated- // as a local web-resource reference and must be a declared IMAGE web resource. `vectorIcon` handling- // is per-subarea below (entity vs non-entity differ).- const checkIcon = (icon, label) => {- if (!icon) return;- if (isPlatformIconRef(icon)) return; // live/OOB platform reference — pass through- const ic = String(icon).toLowerCase();- if (!webResourceNames.has(ic)) errors.push(`${label}: icon '${icon}' is not a declared web resource`);- else if (!imageWebResourceNames.has(ic)) errors.push(`${label}: icon '${icon}' must be an image web resource (png/jpg/gif/svg/ico)`);- };- // Portability advisory: a platform icon/vectorIcon that references THIS app's OWN custom web resource- // (by the solution publisher prefix) but does NOT declare it in webResources[] will render only on an- // env that already has that web resource — on a fresh/other env it dangles (a broken icon). A DOWNLOADED- // spec re-declares its OWN-prefix UNMANAGED image icon web resources automatically (download-model-app- // collectSitemap + iconWebResources), so this normally fires only for a hand-authored spec (a rare- // exception: an own-prefix MANAGED icon WR, which download can't recreate and so leaves undeclared). An- // OOB/system reference (a different prefix, or a non-WebResources `/_imgs/...` path) is assumed present on- // every env → not flagged.- const pubPrefix = (spec.solution && spec.solution.publisherPrefix) ? String(spec.solution.publisherPrefix).toLowerCase() : '';- const checkPortableIconRef = (val, label) => {- if (!val || !isPlatformIconRef(val)) return;- const wrName = webResourceNameFromRef(val);- if (!wrName || !pubPrefix) return;- const lc = wrName.toLowerCase();- if (lc.startsWith(pubPrefix + '_') && !webResourceNames.has(lc)) {- 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.`);- }- };- for (const a of (spec.appShell && spec.appShell.areas) || []) {- checkIcon(a.icon, `sitemap area "${a.label || ''}"`);- checkPortableIconRef(a.icon, `sitemap area "${a.label || ''}"`);- checkPortableIconRef(a.vectorIcon, `sitemap area "${a.label || ''}"`);- validateIconDescription(a.iconDescription, `sitemap area "${a.label || ''}"`, errors);- for (const g of a.groups || []) {- validateIconDescription(g && g.iconDescription, `sitemap group "${(g && g.label) || ''}"`, errors);- for (const sa of g.subAreas || []) {- const targets = ['entity', 'dashboard', 'url', 'page'].filter((k) => sa[k]);- if (targets.length === 0) errors.push(`sitemap subArea "${sa.title || ''}" needs an entity, dashboard, url, or page`);- else if (targets.length > 1) errors.push(`sitemap subArea "${sa.title || ''}" sets multiple targets (${targets.join(', ')}) — pick one`);- // Case-insensitive: Dataverse logical names are lower-case while `schemaName` is cased- // (`Account`), and a sitemap subarea's `entity` comes from the deployed sitemap XML as a- // LOGICAL name. A downloaded spec therefore legitimately pairs `schemaName: "Account"` with- // `entity: "account"`. Matches the chart check above, which already uses `entityByLower`.- if (sa.entity && !badEntityRef(sa.entity, 'sitemap subArea') && !entityByLower.has(String(sa.entity).toLowerCase())) errors.push(`sitemap subArea references unknown entity '${sa.entity}'`);- if (sa.dashboard && !dashNamesSet.has(sa.dashboard)) errors.push(`sitemap subArea references unknown dashboard '${sa.dashboard}' (declare it in dashboards[])`);- // A sitemap URL subarea is EITHER a real link OR a web-resource reference —- // `$webresource:<name>` (what 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, exactly like a platform icon ref above,- // and for the same reason recorded there: it is a live/OOB value a downloaded app carries,- // and rejecting it broke the download→build round-trip on real apps. Requiring it to be- // DECLARED would re-make that mistake in a new place — the referenced resource is often- // managed or owned by another publisher, which download deliberately leaves as a bare- // reference (it exists in the target env; re-creating a foreign prefix would hard-fail a- // fresh build). Download still captures the CONTENT when it can safely do so, so an- // own-prefix unmanaged page travels with the app.- //- // This does not weaken the http(s) guard, which exists to stop an ARBITRARY scheme- // (`javascript:`, `file:`) becoming a nav entry in a shipped app. A web-resource reference- // is not arbitrary: it names a resource inside Dataverse, not a script or a local file.- if (sa.url && !webResourceNameFromRef(sa.url) && !isSafeHttpUrl(sa.url)) {- errors.push(`sitemap subArea "${sa.title || ''}" url must be an http(s) URL or a $webresource:<name> reference (got '${sa.url}')`);- }- // schemaVersion 2 references pages by stable KEY; legacy specs still reference by name.- const pageRefSet = isV2 ? pageKeysSet : pageNamesSet;- if (sa.page && !pageRefSet.has(sa.page)) errors.push(`sitemap subArea references unknown page '${sa.page}' (declare it in pages[])`);- checkIcon(sa.icon, `sitemap subArea "${sa.title || ''}"`);- checkPortableIconRef(sa.icon, `sitemap subArea "${sa.title || ''}"`);- checkPortableIconRef(sa.vectorIcon, `sitemap subArea "${sa.title || ''}"`);- validateIconDescription(sa.iconDescription, `sitemap subArea "${sa.title || ''}"`, errors);- // Ask 3: don't SILENTLY drop an entity-subarea vectorIcon. A valid platform ref round-trips- // (emitted by the build); a BARE token can't be emitted on an entity subarea (it breaks the- // modern app-designer), so surface it as a warning at author time rather than a silent drop.- if (sa.entity && sa.vectorIcon && !isPlatformIconRef(sa.vectorIcon)) {- warnings.push(`sitemap subArea "${sa.title || ''}": vectorIcon '${sa.vectorIcon}' is a bare token — on an entity subarea a bare Fluent token breaks the app designer and is DROPPED from the sitemap. Use an SVG path (e.g. /WebResources/<pub>/icons/x.svg) or a $webresource:<name>.svg reference, or set entities[].vectorIcon (the table icon) for a custom nav glyph.`);- }- }- }- }- // MEMBERSHIP invariant (Plan 5 v2 / Task 3): every generative page MUST appear as a sitemap subarea.- // A model-driven app's membership IS sitemap presence — there is no hidden-but-navigable subarea.- // A page that is only a navigatesTo target (no subarea) is NOT owned by the app's navigation: build- // will create it, but download enumeration (membership = sitemap) and verify (membership check) will- // both miss it, and the next build from a downloaded spec will then re-create it as a duplicate.- // Enforced for specs that will be BUILT: deploy / plan / design. The `structural` profile is shape-- // only (used by the eval harness and teardown / cleanup) and is explicitly excluded.- if (isV2 && profile !== 'structural') {- const sitemappedPageKeys = new Set();- for (const a of (spec.appShell && spec.appShell.areas) || [])- for (const g of a.groups || [])- for (const sa of g.subAreas || []) if (sa && sa.page) sitemappedPageKeys.add(sa.page);- for (const p of spec.pages || []) {- const key = p.key || p.name;- if (!sitemappedPageKeys.has(key)) {- errors.push(`page '${key}' is not placed in the sitemap — every page must be an appShell subarea (a page reached only by navigation is not owned by the app; add a subarea for it)`);- }- }- }- // Table (entity) icons — these set the table's OWN icon (what the modern app designer and app- // nav render for the table). Unlike a sitemap subarea's `vectorIcon` (a free-form Fluent token),- // a TABLE's icon must be a declared, buildable web resource: `vectorIcon` an SVG web resource- // (Dataverse IconVectorName), `icon` a raster PNG/JPG/GIF/ICO web resource (IconMediumName). An- // unresolvable value is exactly what leaves the designer's property pane stuck on a glimmer, so- // this is a hard error, not a lint warning.- for (const e of spec.entities || []) {- const label = `entity ${e.schemaName || ''}`;- if (e.vectorIcon) {- const v = String(e.vectorIcon).toLowerCase();- if (!webResourceNames.has(v)) errors.push(`${label}: vectorIcon '${e.vectorIcon}' is not a declared web resource (a table's vectorIcon must be an SVG web resource — declare it in webResources[])`);- else if (!svgWebResourceNames.has(v)) errors.push(`${label}: vectorIcon '${e.vectorIcon}' must be an SVG web resource (type "svg")`);- }- if (e.icon) {- const ic = String(e.icon).toLowerCase();- if (!webResourceNames.has(ic)) errors.push(`${label}: icon '${e.icon}' is not a declared web resource`);- else if (!rasterWebResourceNames.has(ic)) errors.push(`${label}: icon '${e.icon}' must be a raster image web resource (png/jpg/gif/ico); use vectorIcon for an SVG`);- }- validateIconDescription(e.iconDescription, label, errors);- }- // App tile icon (optional). When set it must be a declared IMAGE web resource so the app is- // self-contained on export/import; when omitted, the build generates a default icon in-solution.- if (spec.app && spec.app.icon) {- const ai = String(spec.app.icon).toLowerCase();- if (!webResourceNames.has(ai)) errors.push(`app.icon '${spec.app.icon}' is not a declared web resource`);- else if (!imageWebResourceNames.has(ai)) errors.push(`app.icon '${spec.app.icon}' must be an image web resource (png/jpg/gif/svg/ico)`);- }- if (spec.sampleData !== undefined) {- if (typeof spec.sampleData !== 'object' || spec.sampleData === null || Array.isArray(spec.sampleData)) {- errors.push('sampleData must be an object keyed by entity schemaName');- } else {- const lower = new Set([...entityNames].map((n) => n.toLowerCase()));- for (const [k, v] of Object.entries(spec.sampleData)) {- if (!lower.has(k.toLowerCase())) {- errors.push(`sampleData references unknown entity '${k}'`);- }- if (!Array.isArray(v)) {- errors.push(`sampleData['${k}'] must be an array of records`);- continue;- }- // #4: catch Choice/MultiChoice sample values that are NOT a declared option label. Unknown- // labels otherwise pass through resolveChoiceValue() unchanged and reach Dataverse as a raw- // string, which either 400s late in the build or (for a MultiChoice) is silently wrong — a- // typo like 'Urgnet' should fail here, not the live deploy. Uses the shared token linter so- // this hard gate and spec-lint's guardrail apply identical rules. Built once per entity.- const ent = lower.has(k.toLowerCase())- ? (spec.entities || []).find((e) => String(e.schemaName).toLowerCase() === k.toLowerCase())- : null;- for (const rec of v) {- for (const { field, token } of invalidChoiceSampleTokens(spec, ent, rec)) {- errors.push(`sampleData['${k}']: value '${token}' for choice column '${field}' is not a declared option label`);- }- if (!rec || typeof rec !== 'object') {- continue;- }- // #1: validate the parent bind(s) — one `$parent` (singular) and/or many `$parents` (a- // junction row binding multiple sides). Each must name a known parent entity, carry a- // non-empty match, have an existing OneToMany relationship, AND a match that resolves to- // EXACTLY ONE parent sample record. Zero matches silently drops the bind (child created with- // the lookup UNSET); more than one is ambiguous and the seeder would silently pick the first- // (a mis-bind) — both fail loud here at lint time instead of shipping a wrong/half-linked row.- if (rec.$parents !== undefined && !Array.isArray(rec.$parents)) {- // A non-array $parents is silently ignored by the array-guarded map below but IS processed- // by the seeder ([].concat(..., nonArray) keeps it as one element), so validation must- // reject it rather than diverge from runtime.- errors.push(`sampleData['${k}']: $parents must be an array of { entity, match } binds`);- }- const parentBinds = [].concat(- rec.$parent !== undefined ? [{ p: rec.$parent, key: '$parent' }] : [],- Array.isArray(rec.$parents) ? rec.$parents.map((pp) => ({ p: pp, key: '$parents' })) : []- );- for (const { p, key } of parentBinds) {- if (!p || typeof p !== 'object' || Array.isArray(p) || !p.entity || !lower.has(String(p.entity).toLowerCase())) {- errors.push(`sampleData['${k}']: ${key}.entity '${p && p.entity}' is unknown`);- continue;- }- if (!p.match || typeof p.match !== 'object' || Array.isArray(p.match) || !Object.keys(p.match).length) {- errors.push(`sampleData['${k}']: ${key}.match must be a non-empty object`);- continue;- }- if (!relationshipFor(spec, p.entity, k)) {- errors.push(`sampleData['${k}']: no OneToMany relationship from ${key} '${p.entity}' to '${k}'`);- continue;- }- // The match must resolve to EXACTLY ONE parent sample record.- const pKey = Object.keys(spec.sampleData).find((kk) => kk.toLowerCase() === String(p.entity).toLowerCase());- const parentRecs = (pKey && Array.isArray(spec.sampleData[pKey])) ? spec.sampleData[pKey] : [];- const matchCount = parentRecs.filter((pr) => pr && typeof pr === 'object' && Object.entries(p.match).every(([mk, mv]) => {- const rk = Object.keys(pr).find((x) => x.toLowerCase() === mk.toLowerCase());- return rk !== undefined && pr[rk] === mv;- })).length;- if (matchCount === 0) {- errors.push(`sampleData['${k}']: ${key}.match ${JSON.stringify(p.match)} matched no '${String(p.entity).toLowerCase()}' sample record — the lookup would be left unset`);- } else if (matchCount > 1) {- errors.push(`sampleData['${k}']: ${key}.match ${JSON.stringify(p.match)} is ambiguous — it matches ${matchCount} '${String(p.entity).toLowerCase()}' sample records; tighten the match to select exactly one`);- }- }- }- }- }- }- // ai block (optional) — validates appFeatures flags and summaries table references.- if (spec.ai !== undefined) {- if (!spec.ai || typeof spec.ai !== 'object' || Array.isArray(spec.ai)) {- errors.push('ai must be an object');- } else {- const AI_FEATURE_KEYS_LIST = [...AI_FEATURE_KEYS].join(', ');- if (spec.ai.appFeatures !== undefined) {- if (!spec.ai.appFeatures || typeof spec.ai.appFeatures !== 'object' || Array.isArray(spec.ai.appFeatures)) {- errors.push('ai.appFeatures must be an object');- } else {- 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).- // Accept a boolean or a non-negative integer; reject anything else (a string like '2'- // would silently bypass the range check downstream).- //- // The upper bound MIRRORS the SDK's `MAX_SETTING_VALUE` in api/AiApi.ts. The SDK THROWS- // an InvalidArgumentError for an out-of-range value, so without this bound a spec would- // validate cleanly and then abort the build half-applied — validation must reject it up- // 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")`);- }- }- }- }- if (spec.ai.summaries !== undefined) {- if (!spec.ai.summaries || typeof spec.ai.summaries !== 'object' || Array.isArray(spec.ai.summaries)) {- errors.push('ai.summaries must be an object');- } else {- if (spec.ai.summaries.default !== undefined && !['auto', 'off'].includes(spec.ai.summaries.default)) {- errors.push(`ai.summaries.default must be 'auto' or 'off'`);- }- if (spec.ai.summaries.tables !== undefined) {- if (!spec.ai.summaries.tables || typeof spec.ai.summaries.tables !== 'object' || Array.isArray(spec.ai.summaries.tables)) {- errors.push('ai.summaries.tables must be an object');- } else {- for (const [k, v] of Object.entries(spec.ai.summaries.tables)) {- const ent = entityByLower.get(k.toLowerCase());- if (!ent) {- errors.push(`ai.summaries.tables: unknown table '${k}'`);- continue;- }- if (!v || typeof v !== 'object' || Array.isArray(v)) {- errors.push(`ai.summaries.tables['${k}']: must be an object`);- continue;- }- if (v.enabled !== undefined && typeof v.enabled !== 'boolean') errors.push(`ai.summaries.tables['${k}'].enabled: must be a boolean`);- if (v.instruction !== undefined && typeof v.instruction !== 'string') errors.push(`ai.summaries.tables['${k}'].instruction: must be a string`);- if (v.columns !== undefined) {- if (!Array.isArray(v.columns)) {- errors.push(`ai.summaries.tables['${k}'].columns: must be an array`);- } else {- const entCols = new Set([- ...(ent.columns || []).map((c) => c.schemaName.toLowerCase()),- ...(ent.primaryAttribute && ent.primaryAttribute.schemaName ? [ent.primaryAttribute.schemaName.toLowerCase()] : []),- ]);- for (const c of v.columns) {- if (typeof c !== 'string') {- errors.push(`ai.summaries.tables['${k}'].columns: each entry must be a string`);- } else if (!entCols.has(c.toLowerCase())) {- errors.push(`ai.summaries.tables['${k}'].columns: unknown column '${c}'`);- }- }- }- }- }- }- }- }- }- }- }- // Page design contract (optional, v2 only). Shape-only in this plan; the token→Fluent mapping- // and generated-page validation land in the Pages plan. Reject unknown keys so typos fail early.- // Gated on isV2 so a hand-authored legacy spec is not rejected for a v2-only field.- if (isV2 && spec.design !== undefined) {- if (typeof spec.design !== 'object' || spec.design === null || Array.isArray(spec.design)) {- errors.push('design must be an object');- } else {- const allowed = new Set(['accentColor', 'density', 'cornerRadius', 'darkMode', 'layout']);- for (const k of Object.keys(spec.design)) if (!allowed.has(k)) errors.push(`design: unknown key '${k}' (allowed: ${[...allowed].join(', ')})`);- }- }- // Security personas (optional; additive — validated on v1 and v2 specs). Each persona authors ONE- // security role (role name = persona) whose privilege set is the UNION of the entity access every- // one of its jobs-to-be-done declares (the SDK unions them, max scope wins per entity+access). The- // planner DECLARES the access each job needs — the engine never infers it — so this validator only- // checks the declared SHAPE: valid Dataverse access/scope tokens and well-formed GUIDs. Two guards- // are intentionally deferred to apply time because they need live entity metadata the lint pass does- // not have: (1) whether an entity actually supports a requested access, and (2) the SDK's shared-- // privilege rule (entities that alias to the same prv* must request one scope). Those surface as a- // clean BuildHalt from the security phase, not here. Entity NAMES are likewise resolved against live- // metadata by the SDK (a persona legitimately grants access to standard tables like `account` that- // this spec does not author), so we validate only that `entity` is a non-empty string.- if (spec.personas !== undefined) {- if (!Array.isArray(spec.personas)) {- errors.push('personas must be an array');- } else {- const personaNames = new Set();- // Reject unknown keys so a typo fails loudly at author time instead of silently taking a default.- // WHY this matters for security: `appAcces:false` (typo) would leave the REAL `appAccess` absent →- // defaulting to true → the persona wrongly gets app-module read + the app association. Same pattern- // the `design` block uses. Allowlists mirror the vendored SDK's PersonaRoleSpec/JobToBeDone/- // EntityPrivilege shapes exactly.- const PERSONA_KEYS = new Set(['persona', 'jobs', 'additionalPrivileges', 'appAccess', 'businessUnitId', 'assignTo']);- const JOB_KEYS = new Set(['name', 'description', 'privileges', 'surfaces']);- const PRIVILEGE_KEYS = new Set(['entity', 'access', 'scope']);- const rejectUnknown = (obj, allowed, ctx) => {- for (const k of Object.keys(obj)) if (!allowed.has(k)) errors.push(`${ctx}: unknown key '${k}' (allowed: ${[...allowed].join(', ')})`);- };- // Validate a persona/JTBD EntityPrivilege[] (shape + enum only — see the deferral note above).- const validatePrivileges = (privs, ctx, { allowEmpty = false } = {}) => {- if (privs === undefined) {- if (!allowEmpty) errors.push(`${ctx}: privileges[] is required`);- return;- }- if (!Array.isArray(privs) || (!allowEmpty && !privs.length)) {- errors.push(`${ctx}: privileges must be a non-empty array`);- return;- }- for (const pr of privs) {- if (!pr || typeof pr !== 'object' || Array.isArray(pr)) { errors.push(`${ctx}: each privilege must be an object`); continue; }- rejectUnknown(pr, PRIVILEGE_KEYS, `${ctx}: privilege`);- if (!pr.entity || typeof pr.entity !== 'string') errors.push(`${ctx}: privilege.entity (a table logical name) is required`);- if (!Array.isArray(pr.access) || !pr.access.length) {- errors.push(`${ctx}: privilege on '${pr.entity || '?'}' needs a non-empty access[]`);- } else {- for (const a of pr.access) if (!ACCESS_LEVELS.has(a)) errors.push(`${ctx}: unknown access '${a}' on '${pr.entity}' (valid: ${[...ACCESS_LEVELS].join(', ')})`);- }- if (pr.scope !== undefined && !PRIVILEGE_SCOPES.has(pr.scope)) errors.push(`${ctx}: unknown scope '${pr.scope}' on '${pr.entity}' (valid: ${[...PRIVILEGE_SCOPES].join(', ')})`);- }- };- for (const p of spec.personas) {- if (!p || typeof p !== 'object' || Array.isArray(p)) { errors.push('personas[]: each persona must be an object'); continue; }- rejectUnknown(p, PERSONA_KEYS, 'persona');- // The SDK TRIMS the role name before its (name, business-unit) lookup, so validate + dedup on the- // TRIMMED name — otherwise "Agent" and " Agent " pass as distinct here but collapse onto one role- // (the second silently REPLACES the first's privileges), and teardown/verify would query the wrong- // (untrimmed) name and miss the role.- const pname = typeof p.persona === 'string' ? p.persona.trim() : p.persona;- if (!pname || typeof pname !== 'string') {- errors.push('persona: persona (the role name) is required and cannot be blank/whitespace-only');- } else {- const key = pname.toLowerCase();- if (personaNames.has(key)) errors.push(`persona "${pname}": duplicate persona name (each persona authors one role — names must be unique after trimming)`);- personaNames.add(key);- }- const label = pname || '?';- if (p.appAccess !== undefined && typeof p.appAccess !== 'boolean') errors.push(`persona "${label}": appAccess must be a boolean`);- if (p.businessUnitId !== undefined && (typeof p.businessUnitId !== 'string' || !FORM_GUID_RE.test(p.businessUnitId))) errors.push(`persona "${label}": businessUnitId must be a GUID`);- if (!Array.isArray(p.jobs) || !p.jobs.length) {- errors.push(`persona "${label}": at least one job (jobs[]) is required`);- } else {- for (const j of p.jobs) {- if (!j || typeof j !== 'object' || Array.isArray(j)) { errors.push(`persona "${label}": each job must be an object`); continue; }- rejectUnknown(j, JOB_KEYS, `persona "${label}" job`);- if (!j.name || typeof j.name !== 'string') errors.push(`persona "${label}": a job is missing name`);- // surfaces[]: the view/form/page names (or page keys) that let this persona DO the job.- // Purely documentary — it drives the design doc's traceability table and the "job with no- // surface" lint warning, and is never applied to Dataverse. Shape-only validation, because- // a surface may legitimately name an artifact this spec doesn't author (a stock view).- if (j.surfaces !== undefined) {- if (!Array.isArray(j.surfaces)) errors.push(`persona "${label}" job "${j.name || '?'}": surfaces must be an array of strings`);- else for (const s of j.surfaces) if (typeof s !== 'string' || !s.trim()) errors.push(`persona "${label}" job "${j.name || '?'}": each surfaces[] entry must be a non-empty string`);- }- validatePrivileges(j.privileges, `persona "${label}" job "${(j && j.name) || '?'}"`);- }- }- if (p.additionalPrivileges !== undefined) validatePrivileges(p.additionalPrivileges, `persona "${label}" additionalPrivileges`, { allowEmpty: true });- // assignTo (optional, grant-only). Team/user ids are Dataverse GUIDs — validate the shape so a- // typo'd id fails at author time rather than as an opaque SDK GUID-normalization error on apply.- if (p.assignTo !== undefined) {- if (typeof p.assignTo !== 'object' || p.assignTo === null || Array.isArray(p.assignTo)) {- errors.push(`persona "${label}": assignTo must be an object with teams[]/users[]`);- } else {- for (const k of Object.keys(p.assignTo)) if (k !== 'teams' && k !== 'users') errors.push(`persona "${label}": assignTo unknown key '${k}' (allowed: teams, users)`);- for (const k of ['teams', 'users']) {- if (p.assignTo[k] === undefined) continue;- if (!Array.isArray(p.assignTo[k])) { errors.push(`persona "${label}": assignTo.${k} must be an array of GUIDs`); continue; }- for (const id of p.assignTo[k]) if (typeof id !== 'string' || !FORM_GUID_RE.test(id)) errors.push(`persona "${label}": assignTo.${k} contains a non-GUID value`);- }- }- }- }- }- }- return { ok: errors.length === 0, errors, warnings };-}--// Slugify a page name into a stable key candidate: lowercase, non-alphanumerics -> '-', trimmed.-// "Sales Overview" -> "sales-overview"-// "KPI / Analytics" -> "kpi-analytics"-function slugify(name) {- return String(name || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'page';-}--// The canonical role name for a persona: the TRIMMED `persona` string. The vendored SDK trims the name-// before its (name, business-unit) role lookup/create, so every plugin site that identifies the role —-// the create mapper (personaRoleSpecFor), teardown, and verify — MUST use this same trimmed form or they-// will disagree on the role's identity (create "Agent" but tear down / verify " Agent ").-function canonicalPersonaName(persona) {- const n = persona && persona.persona;- return typeof n === 'string' ? n.trim() : n;-}--// Upgrade a legacy App Spec to schemaVersion 2 in one pure pass (no I/O; returns a deep copy):-// - mint a stable, unique `key` per page (slug of name, de-duplicated with a -N suffix)-// - wrap a legacy top-level `codeFile` into `source: { kind: 'tsx', codeFile }`-// - rewrite name-based references (appShell page subareas + navigatesTo.targetKey) to keys-// Idempotent: a spec already at schemaVersion >= 2 is returned as-is. Runs on load before validate,-// so downstream code only ever sees the v2 shape. See docs/app-builder-design.md §7.3.-//-// Two-pass design: pass 1 mints ALL keys first so nameToKey is fully populated before any-// rewrite. A single rewrite pass (pass 2) then replaces every name-ref exactly once, preventing-// the double-rewrite bug that occurred when a minted key collided with another page's name-// (e.g. pages "Detail" → key "detail" and "detail" → key "detail-2": the old two-pass code-// would rewrite a "Detail" name-ref to "detail" in pass 1, then re-apply nameToKey in pass 2-// and wrongly map "detail" (now a key, but also the name of the second page) to "detail-2").-function migrateAppSpec(spec) {- if (!spec || typeof spec !== 'object' || (spec.schemaVersion || 0) >= 2) return spec;- const out = JSON.parse(JSON.stringify(spec));- out.schemaVersion = 2;- const nameToKey = new Map();- const used = new Set();- // Migration runs BEFORE validateAppSpec at every CLI entry point (build/preview/verify/teardown- // all migrate the file they just read, then validate), so a malformed collection reached these- // loops and threw a raw TypeError before the gate that is supposed to report it ever ran. Iterate- // defensively — but do NOT rewrite the value, or validateAppSpec would see a repaired spec and- // report nothing. The shape error stays for the gate to find.- const arr = (v) => (Array.isArray(v) ? v : []);- // Pass 1: mint every key and wrap legacy codeFile→source. nameToKey is fully populated- // after this loop so the rewrite pass below needs only a single scan (no forward-ref gaps).- for (const p of arr(out.pages)) {- if (!p || typeof p !== 'object') continue;- let key = slugify(p.name);- let n = 1;- while (used.has(key)) { n += 1; key = `${slugify(p.name)}-${n}`; }- used.add(key);- p.key = key;- nameToKey.set(p.name, key);- if (!p.source && typeof p.codeFile === 'string') { p.source = { kind: 'tsx', codeFile: p.codeFile }; delete p.codeFile; }- }- // Pass 2: rewrite name-refs to keys exactly once. Because nameToKey is complete, forward refs- // (a page referencing a later-declared page) resolve correctly without a repeated second pass.- for (const p of arr(out.pages)) {- if (!p || typeof p !== 'object') continue;- for (const nav of arr(p.navigatesTo)) { if (nav && nameToKey.has(nav.targetKey)) nav.targetKey = nameToKey.get(nav.targetKey); }- }- for (const a of arr(out.appShell && out.appShell.areas)) {- if (!a || typeof a !== 'object') continue;- for (const g of arr(a.groups)) {- if (!g || typeof g !== 'object') continue;- for (const sa of arr(g.subAreas)) { if (sa && sa.page && nameToKey.has(sa.page)) sa.page = nameToKey.get(sa.page); }- }- }- return out;-}--module.exports = {- validateAppSpec,- normalizePageSource,- normalizeLanguageCode,- quickCreateEnabledFor,- isPlatformIconRef,- webResourceNameFromRef,- FORM_TYPE_CODE,- FORM_GUID_RE,- ACCESS_LEVELS,- PRIVILEGE_SCOPES,- SDK_ROLE_MARKER,- canonicalPersonaName,- VALIDATION_PROFILES,- ENTITY_KEYS,- invalidLanguageCodeMessage,- ENTITY_KEY_HINTS,- DIRECT_ENTRY_BEHAVIORS,- COLUMN_VISUALIZATIONS,- INTEGER_FORMATS,- BUSINESS_RULE_OPERATORS,- BUSINESS_RULE_VALUELESS_OPERATORS,- BUSINESS_RULE_ACTIONS,- BUSINESS_RULE_ACTION_TYPES,- BUSINESS_RULE_DATA_TYPES,- BPF_STATUSES,- bpfUniqueName,- declaredColumnLogicals,- BUSINESS_RULE_SCOPES,- migrateAppSpec,- columnTypeMap,- TYPE_MAP,- choiceValueMap,- invalidChoiceSampleTokens,- sampleRecordsFor,- resolveSampleRecords,- relationshipFor,- lookupColumnsFor,- childRelationshipsFor,- relationshipSchemaName,- prefixedRelationshipName,- manyToManyFor,- manyToManySchemaName,- isSafeHttpUrl,- CHART_TYPES,-};+// App Spec schema + validator. The App Spec is the reviewable contract between+// the app-builder's LLM proposal and the deterministic builder.++const path = require('node:path');+const { normalizeSpecShape } = require('./spec-shape.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:`+// URL in an app the maker ships would be a script-injection / local-file-exfil vector for whoever opens+// the app. Anything unparseable or non-http(s) is rejected by the validator.+function isSafeHttpUrl(u) {+ if (typeof u !== 'string' || !u) return false;+ let parsed;+ try { parsed = new URL(u); } catch { return false; }+ return parsed.protocol === 'http:' || parsed.protocol === 'https:';+}++// Dataverse systemform.type codes. A form NAME is unique only per (entity, TYPE) — a table's auto-created+// Main / Quick View / Card forms are commonly ALL named "Information" — so any code that RESOLVES a form+// (build reconcile, preflight discovery, verify) must scope by type or a name-only match hits multiple+// rows. Shared here (the lowest-level spec module) so build + verify agree. Values per the option set:+// https://learn.microsoft.com/power-apps/developer/data-platform/reference/entities/systemform#type-choicesoptions+const FORM_TYPE_CODE = { Main: 2, QuickView: 6, QuickCreate: 7, Card: 11 };++// A canonical GUID (used to validate an author-pinned forms[].formId, which is interpolated UNQUOTED into+// an Edm.Guid OData filter). Anchored so it can neither over-match nor be an injection seam.+const FORM_GUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++// Security-authoring enums (personas[]). These mirror the vendored SDK's security surface+// (cds-maker-sdk src/types/security.ts) EXACTLY — the app-spec validator is a lint-time echo of the+// SDK's own guards so an author sees a bad access/scope at author time instead of only on apply.+// AccessLevel -> Dataverse PrivilegeType (read->Read, appendTo->AppendTo, …)+// 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 PRIVILEGE_SCOPES = new Set(['user', 'businessUnit', 'parentChild', 'organization']);++// The exact ownership marker the vendored SDK (cds-maker-sdk SecurityApi) stamps on the `description`+// of every security role it authors. The SDK deletes/reuses ONLY a role carrying this marker (SEC-1);+// the plugin re-implements that guard in teardown (deleteSecurityRole takes a raw id and does not+// re-check ownership) and in verify (a same-name role someone else built is NOT the one we authored),+// so the string lives here as the single source of truth. Keep in lockstep with the SDK — vendor-sdk-+// smoke asserts the vendored bundle still contains it.+const SDK_ROLE_MARKER = 'Authored by @maker-studio/cds-maker-sdk (persona/security role).';++// A sitemap icon / vectorIcon VALUE the platform resolves DIRECTLY (as opposed to a locally-declared+// `webResources[]` NAME): a relative WebResources path (`/WebResources/...`, `/_imgs/...`) or a+// `$webresource:` reference. These are exactly what a DOWNLOADED app carries verbatim on its subareas —+// including OOB system icons like `/WebResources/msdyn_OmnichannelBase/_imgs/SitemapIcon/CDSEntity` — and+// what a modern custom nav icon uses (`/WebResources/<pub>/icons/x.svg`). They must ROUND-TRIP: the build+// emits them verbatim (case-preserved) and validation must NOT reject them for not being a declared web+// resource (that rejection broke download→build on every real app).+// The signal is a leading `/` or a `$webresource:` prefix — NOT a file extension: a web-resource NAME+// legitimately ends in an extension (e.g. `new_appicon.png`), so an extension alone can't distinguish a+// path from a declared name. A BARE token (no `/`, no scheme — e.g. a Fluent icon name `Shop`, or even a+// bare `x.svg`) is NOT a platform ref: as an `icon` it is a local web-resource name that must be declared,+// and as an entity-subarea `VectorIcon` it breaks the modern app-designer property pane (build drops it).+// Grounded by a live probe of the vendored SDK: it serializes+// `<SubArea Entity="…" … VectorIcon="/WebResources/<pub>/icons/x.svg">` correctly for a path value.+function isPlatformIconRef(v) {+ const s = String(v == null ? '' : v);+ return s.startsWith('/') || /^\$webresource:/i.test(s);+}++// `iconDescription` is a DOCUMENTARY field: what the icon's glyph will DEPICT, in plain language+// ("a briefcase", "an outlined clipboard with a checkmark"). It is never written to Dataverse — it+// exists so `model-app-plan.md` can show the user what they are approving BEFORE the SVG is drawn.+//+// Why a Fluent token name is rejected outright: the SVG is authored fresh in this phase, so there is+// no icon library to look a token up in — and a token name the user has never seen ("ClipboardTask")+// tells them nothing about what the glyph will look like, which defeats the entire point of the+// field. Detect a token by SHAPE: a single word (no whitespace) that is either Capitalised the way+// every Fluent name is ("Briefcase", "ClipboardTask") or carries a Fluent style/size suffix+// ("...24Regular"). A single lowercase word ("briefcase") is terse but still a real depiction, so it+// passes — the rule targets library-name pasting, not brevity.+const FLUENT_TOKENISH = /^(?=\S+$)(?:[A-Z].*|.*[a-z0-9][A-Z].*|.*(?:Regular|Filled|Light|Color)\d*$)/;+function validateIconDescription(value, label, errors) {+ if (value === undefined) return;+ if (typeof value !== 'string' || !value.trim()) {+ errors.push(`${label}: iconDescription must be a non-empty string describing what the glyph depicts (e.g. "a briefcase")`);+ return;+ }+ if (FLUENT_TOKENISH.test(value.trim())) {+ errors.push(`${label}: iconDescription '${value}' looks like a Fluent icon token, not a description. The SVG is drawn fresh, so describe what the glyph will DEPICT (e.g. "an outlined clipboard with a checkmark") — a token name the user has not seen tells them nothing.`);+ }+}++// The web-resource NAME a PLATFORM icon reference points at, or null when it isn't a resolvable+// web-resource reference. Two forms the platform emits:+// `/WebResources/<name>` → <name> (the runtime path a modern nav icon uses)+// `$webresource:<name>` → <name>+// A `<name>` may itself contain `/` (web-resource names are folder-like, e.g. `pub_/icons/x.svg`), so+// strip ONLY the known prefix, verbatim. A non-WebResources path (an OOB static image like+// `/_imgs/TableIconsFluentV9/x.svg`) returns null — not a queryable web resource, so it stays a bare+// reference present on every env.+function webResourceNameFromRef(ref) {+ const s = String(ref == null ? '' : ref);+ let m = /^\/WebResources\/(.+)$/i.exec(s);+ if (m) return m[1];+ m = /^\$webresource:(.+)$/i.exec(s);+ if (m) return m[1];+ return null;+}++// App Spec column type -> { dv: Dataverse attribute type name }. (The SDK build engine+// maps App Spec types to the SDK's own ColumnType in lib/sdk-build.js.)+const TYPE_MAP = {+ Text: { dv: 'string' },+ Memo: { dv: 'memo' },+ Choice: { dv: 'picklist' },+ MultiChoice: { dv: 'multiselectpicklist' },+ Boolean: { dv: 'boolean' },+ Money: { dv: 'money' },+ DateTime: { dv: 'datetime' },+ Integer: { dv: 'integer' },+ BigInt: { dv: 'bigint' },+ Decimal: { dv: 'decimal' },+ Double: { dv: 'double' },+ File: { dv: 'file' },+ Image: { dv: 'image' },+ AutoNumber: { dv: 'string' },+ Customer: { dv: 'lookup' }, // polymorphic account/contact — built via createCustomerColumn+ Lookup: { dv: null }, // lookups come from relationships, not a column+};++function columnTypeMap(t) {+ return TYPE_MAP[t] || TYPE_MAP.Text;+}++// Map every Choice / MultiChoice column's option LABELS to the integer values the+// builder assigns (value = 100000000 + index — the same convention used for inline+// option sets AND global option sets; see lib/sdk-build.js). Resolves inline `options[]`+// columns AND columns bound to a `globalChoice` (looked up in spec.globalChoices). Pass+// `spec` to resolve global choices; without it, only inline-option columns resolve.+// { columnLogicalName: { "Platinum": 100000000, ... } }.+function choiceValueMap(entity, spec) {+ // Index each option under EVERY string it can be named by — the label itself when plain, or each+ // per-language string when localized (AB#6686428). A localized option has ONE value and N labels,+ // so `sampleData` written in either language must resolve to the same value; keying on+ // `String(label)` alone would turn a label map into the literal key "[object Object]".+ //+ // FIRST alias wins on collision, and `invalidChoiceSampleTokens` rejects an ambiguous alias+ // outright. Last-wins was the original and is silently wrong: given+ // [ { "1033": "Open", "3082": "Abierto" },+ // { "1033": "Abierto", "3082": "Cerrado" } ]+ // the alias "Abierto" belongs to BOTH options, and last-wins resolved a sample record's "Abierto"+ // to the SECOND option — the English label of a different choice quietly beating the Spanish label+ // of the one the author meant.+ // Every dictionary here is keyed by an AUTHOR-CONTROLLED string — an option label, a global-choice+ // name, a column schema name — so all three are `Object.create(null)`. On a plain `{}` the label+ // "__proto__" is not merely unwritable (the write hits the prototype SETTER and is dropped): the+ // READ `byLabel['__proto__']` returns `Object.prototype`, which is `!== undefined`. That made+ // `invalidChoiceSampleTokens` accept "__proto__" as a known label and `resolveSampleRecords`+ // resolve it to `Object.prototype`, which serializes into the Web API body as `{}` — a silently+ // corrupted record that passed every gate. Measured: a Choice with options ["__proto__", "Open"]+ // validated clean and produced `{"new_state": {}}`.+ const indexOptions = (options) => {+ const byLabel = Object.create(null);+ (options || []).forEach((label, i) => {+ for (const alias of labelAliases(label)) {+ if (!Object.prototype.hasOwnProperty.call(byLabel, alias)) byLabel[alias] = 100000000 + i;+ }+ });+ return byLabel;+ };+ const globalByName = Object.create(null);+ for (const g of (spec && spec.globalChoices) || []) {+ globalByName[String(g.name).toLowerCase()] = indexOptions(g.options);+ }+ const map = Object.create(null);+ for (const c of entity.columns || []) {+ if (c.type !== 'Choice' && c.type !== 'MultiChoice') continue;+ let byLabel = null;+ if (Array.isArray(c.options) && c.options.length) {+ byLabel = indexOptions(c.options);+ } else if (c.globalChoice && globalByName[String(c.globalChoice).toLowerCase()]) {+ byLabel = globalByName[String(c.globalChoice).toLowerCase()];+ }+ if (byLabel) map[c.schemaName.toLowerCase()] = byLabel;+ }+ return map;+}++// Shared choice-value linter (#4). Returns [{ field, token }] for each Choice/MultiChoice sample VALUE+// in `record` that is neither a declared option label nor a raw integer option value. Both the hard+// validator (validateAppSpec) and the guardrail linter (spec-lint.js) call this so the two gates never+// diverge. A MultiChoice value is a comma-separated token list; a single Choice is one token — a label+// that legitimately contains a comma is matched WHOLE first (byLabel[val]) so it is never mis-split.+// Raw integer tokens pass through (an author may use the stable option value instead of the label).+function invalidChoiceSampleTokens(spec, entity, record) {+ if (!entity || !record || typeof record !== 'object' || Array.isArray(record)) return [];+ const byField = choiceValueMap(entity, spec);+ const multi = new Set((entity.columns || []).filter((c) => c.type === 'MultiChoice').map((c) => String(c.schemaName).toLowerCase()));+ const out = [];+ for (const [field, val] of Object.entries(record)) {+ if (field.startsWith('$') || field === 'statusReason') continue;+ const byLabel = byField[field.toLowerCase()];+ if (!byLabel || typeof val !== 'string') continue; // not a choice column, or already an int+ if (byLabel[val] !== undefined) continue; // whole value is a known label (incl. labels with commas)+ const tokens = multi.has(field.toLowerCase()) ? val.split(',').map((t) => t.trim()).filter(Boolean) : [val];+ for (const tok of tokens) {+ if (tok === '' || /^-?\d+$/.test(tok)) continue; // blank or a raw option int+ if (byLabel[tok] === undefined) out.push({ field, token: tok });+ }+ }+ return out;+}++// The sample records declared for an entity (keyed by schemaName, case-insensitive).+function sampleRecordsFor(spec, entity) {+ const sd = spec.sampleData || {};+ const key = Object.keys(sd).find((k) => k.toLowerCase() === entity.schemaName.toLowerCase());+ return (key && Array.isArray(sd[key]) && sd[key]) || [];+}++// Valid chart types (SDK ChartSeriesType values).+const CHART_TYPES = ['Column', 'Bar', 'Pie', 'Line'];++// Find the OneToMany relationship in the spec whose `referenced` = parentEntity and+// `referencing` = childEntity (case-insensitive on both schema names). Returns the+// relationship object (its `lookup.schemaName` is the @odata.bind nav-property; the+// sub-grid RelationshipName is relationshipSchemaName(rel)), or null when none exists.+function relationshipFor(spec, parentEntity, childEntity) {+ const p = String(parentEntity || '').toLowerCase();+ const c = String(childEntity || '').toLowerCase();+ return (+ (spec.relationships || []).find(+ (r) =>+ r.type === 'OneToMany' &&+ String(r.referenced || '').toLowerCase() === p &&+ String(r.referencing || '').toLowerCase() === c+ ) || null+ );+}++// The 1:N lookup columns a relationship places ON `entityLogical` (the referencing/child side).+// These lookups are NOT part of entities[].columns — they come from relationships[] — so form+// auto-layout and default-view enrichment call this to surface the parent links (otherwise the+// parent lookup is invisible on the form/grid). N:N relationships use an intersect table and place+// no lookup column on either side, so they're excluded. Deduped by logical name; declared order+// preserved. Returns [{ logical, displayName }].+function lookupColumnsFor(spec, entityLogical) {+ const child = String(entityLogical || '').toLowerCase();+ const seen = new Set();+ const out = [];+ for (const r of spec.relationships || []) {+ if (r.type !== 'OneToMany') continue;+ if (String(r.referencing || '').toLowerCase() !== child) continue;+ const logical = String((r.lookup && r.lookup.schemaName) || '').toLowerCase();+ if (!logical || seen.has(logical)) continue;+ seen.add(logical);+ out.push({ logical, displayName: labelText((r.lookup && r.lookup.displayName), spec && spec.languageCode) || (r.lookup && r.lookup.schemaName) || logical });+ }+ return out;+}++// The child relationships to show as sub-grids on `entityLogical`'s (parent) form: every 1:N where+// this entity is the REFERENCED (parent) side, plus every N:N it participates in. Returns the child+// (the "many"/other side) as [{ childEntity }], deduped, declared order preserved. Used by the opt-in+// forms[].autoSubgrids to give a hub table a "list of its children" grid without hand-authoring each.+function childRelationshipsFor(spec, entityLogical) {+ const parent = String(entityLogical || '').toLowerCase();+ const seen = new Set();+ const out = [];+ for (const r of spec.relationships || []) {+ let child = null;+ if (r.type === 'OneToMany' && String(r.referenced || '').toLowerCase() === parent) {+ child = String(r.referencing || '').toLowerCase();+ } else if (r.type === 'ManyToMany') {+ const a = String(r.entity1 || '').toLowerCase();+ const b = String(r.entity2 || '').toLowerCase();+ if (a === parent) child = b;+ else if (b === parent) child = a;+ }+ if (!child || seen.has(child)) continue;+ seen.add(child);+ out.push({ childEntity: child });+ }+ return out;+}++// The 1:N relationship's SCHEMA name (used for entity provisioning and the+// sub-grid RelationshipName). This MUST be distinct from the lookup attribute's+// schema name — Dataverse rejects a relationship whose name collides with the+// lookup column on the referencing table. Defaults to `<referenced>_<referencing>`,+// with the solution's publisher prefix guaranteed at the front (see+// prefixedRelationshipName) so a relationship to a STANDARD/system table (systemuser,+// account, …) — which has no custom prefix — still gets a valid, prefixed name that+// Dataverse accepts. An explicit `rel.schemaName` is honored verbatim.+function relationshipSchemaName(rel, publisherPrefix) {+ if (rel && rel.schemaName) {+ return rel.schemaName;+ }+ return prefixedRelationshipName(rel.referenced, rel.referencing, publisherPrefix);+}++// Compose a relationship schema name from two entity schema names, guaranteeing the result starts+// with the solution's publisher prefix. Dataverse REQUIRES a relationship schema name to start with+// the publisher prefix; the naive `<a>_<b>` only satisfies that when `a` is a custom (prefixed)+// table. When `a` is a standard/system table (systemuser, account, …) the composed name starts with+// the table name instead and Dataverse rejects the create with a 400. So when the composed name+// doesn't already start with `<prefix>_`, prepend it (stripping a redundant prefix from `b` so we+// don't double it). With no prefix supplied the legacy `<a>_<b>` is returned unchanged.+function prefixedRelationshipName(a, b, publisherPrefix) {+ const first = String(a || '').toLowerCase();+ const second = String(b || '').toLowerCase();+ const prefix = String(publisherPrefix || '').toLowerCase();+ const composed = `${first}_${second}`;+ if (!prefix || composed.startsWith(`${prefix}_`)) {+ return composed;+ }+ const secondStripped = second.startsWith(`${prefix}_`) ? second.slice(prefix.length + 1) : second;+ return `${prefix}_${first}_${secondStripped}`;+}++// Find the ManyToMany relationship linking two entities (order-independent), or null.+function manyToManyFor(spec, entityA, entityB) {+ const a = String(entityA || '').toLowerCase();+ const b = String(entityB || '').toLowerCase();+ return (+ (spec.relationships || []).find((r) => {+ if (r.type !== 'ManyToMany') return false;+ const e1 = String(r.entity1 || '').toLowerCase();+ const e2 = String(r.entity2 || '').toLowerCase();+ return (e1 === a && e2 === b) || (e1 === b && e2 === a);+ }) || null+ );+}++// The N:N relationship's SCHEMA name (the intersect/RelationshipName). #3: an N:N is symmetric, so the+// name is composed from the two entity logical names SORTED ALPHABETICALLY — this makes the name STABLE+// regardless of authoring order (the same pair authored `entity1/entity2` either way yields ONE name,+// fixing the V1/V2 reversal that broke a data-load assuming a fixed order). The publisher prefix is then+// guaranteed at the front (see prefixedRelationshipName). An explicit `schemaName` still wins verbatim.+// NOTE: only N:N sorts — a 1:N name (relationshipSchemaName) keeps its semantic `referenced_referencing`+// (parent_child) order and must NOT be sorted.+function manyToManySchemaName(rel, publisherPrefix) {+ if (rel && rel.schemaName) {+ return rel.schemaName;+ }+ const [a, b] = [String(rel.entity1 || '').toLowerCase(), String(rel.entity2 || '').toLowerCase()].sort();+ return prefixedRelationshipName(a, b, publisherPrefix);+}++// Turn author-friendly sample records into Web-API bodies: Choice / MultiChoice values+// written as labels ("Platinum", or "Low,High" for multi-select) are resolved to their+// option ints — for inline-option AND global-choice columns (pass `spec` so global+// choices resolve). Everything else passes through unchanged (raw ints, strings,+// booleans, ISO dates, and unknown tokens all still work).+function resolveSampleRecords(entity, records, spec) {+ const choices = choiceValueMap(entity, spec);+ const multi = new Set((entity.columns || []).filter((c) => c.type === 'MultiChoice').map((c) => c.schemaName.toLowerCase()));+ return (records || []).map((rec) => {+ const out = {};+ for (const [k, v] of Object.entries(rec)) {+ const byLabel = choices[k.toLowerCase()];+ out[k] = byLabel ? resolveChoiceValue(byLabel, v, multi.has(k.toLowerCase())) : v;+ }+ return out;+ });+}++// Resolve one sample value against a column's { label -> int } map.+// - single-select Choice: a known label becomes its integer value (Edm.Int32);+// - MultiChoice (multi-select picklist): the Web API expects a COMMA-SEPARATED STRING of+// option ints *even for a single value* — so every token is resolved and re-joined as a+// string (a bare Int32 is rejected: "Cannot convert '100000002' (Int32) to Edm.String").+// Unknown tokens and non-strings pass through unchanged (raw ints still work for single-select).+function resolveChoiceValue(byLabel, v, isMulti) {+ if (typeof v !== 'string') return v;+ if (isMulti) {+ return v.split(',').map((t) => {+ const tok = t.trim();+ return byLabel[tok] !== undefined ? String(byLabel[tok]) : tok;+ }).join(',');+ }+ return byLabel[v] !== undefined ? byLabel[v] : v;+}++// Valid validation profiles. `deploy` (default) is the strictest — every page must be implemented+// (a real .tsx). `design`/`plan` allow intent-only pages (author designs pages before generate-pages+// writes their .tsx). `structural` ignores page implementation (teardown/cleanup only cares about refs).+// See docs/app-builder-design.md §7.1.+const VALIDATION_PROFILES = ['design', 'plan', 'deploy', 'structural'];++// What a page does when a user opens it straight from the app navigation with no caller input.+// Every page is sitemap-placed, so this state is always reachable for a page that declares+// `pageInput`; these are the two honest answers.+// selector — render a picker/list so the user can choose the record the page needs.+// emptyState — render an explanatory empty state ("open a row from X to see its detail").+const DIRECT_ENTRY_BEHAVIORS = ['selector', 'emptyState'];++// Per-column grid data visualization (PREVIEW). MIRRORS the vendored SDK's `ColumnVisualizationType`+// (types/schema.ts) exactly — widening here without widening there produces a mid-build throw.+//+// Semantics are per COLUMN, not per view: the platform renders the graphic in EVERY grid and view+// that shows the column, which is why this lives on `entities[].columns[]` rather than on `views[]`.+// Persisted as a `controlconfiguration` row bound to the attribute.+//+// `None` is the platform default (plain text) and is accepted so a spec can explicitly CLEAR a+// visualization set by an earlier build or by a maker in the portal. OMITTING the field is NOT the+// same as `None`: an omitted column is left exactly as deployed, because converging every undeclared+// column to "plain text" would cost one extra read per column on every build to find out whether+// there was anything to clear.+const COLUMN_VISUALIZATIONS = ['None', 'RadialDial', 'LineChart', 'HeatMap', 'StarRating'];++// Whole Number display Format (AB#6648522). MIRRORS the vendored SDK's `integerFormat` union+// (types/schema.ts) exactly, same reasoning as COLUMN_VISUALIZATIONS above — widening one without+// the other produces a mid-build InvalidArgumentError instead of a spec-gate rejection.+//+// 'None' is the platform default (plain integer). It is accepted here, same as visualization's+// 'None', so a spec can explicitly clear a Format set by an earlier build or a maker in the portal.+// Unlike visualization, this is Integer-type-only — the SDK throws InvalidArgumentError for any+// other numeric type (BigInt/Decimal/Double/Money), so validated below alongside the enum check.+const INTEGER_FORMATS = ['None', 'Duration', 'TimeZone', 'Language', 'Locale'];++// Business rules. These MIRROR the vendored SDK's supported slice.+//+// The list is the SDK's operator TABLE, not a subset of it, and that table is the authority for a+// sharp reason: the serializer resolves an operator with+// `Uf[operator] ?? WorkflowConditionOperator.Equal`, so an operator it does not know becomes+// **Equals**. `IsGreaterThan` is in the table; `GreaterThan` is not — writing the latter silently+// deploys an equality test. That is a wrong rule behind a green build, which is exactly what this+// gate exists to prevent, so `business-rules.test.js` pins this list against the bundle's own table.+//+// The list was four entries long for a long time. That was never a platform limit: the SDK used to+// fall back to a client-side workflow-XAML compiler that could only express those four, and the+// restriction outlived it. The compiler has been deleted upstream, so the JSON path's full table is+// available.+const BUSINESS_RULE_OPERATORS = [+ 'Equals', 'DoesNotEqual',+ 'IsGreaterThan', 'IsGreaterThanEqualTo', 'IsLessThan', 'IsLessThanEqualTo',+ 'Contains', 'DoesNotContain',+ 'BeginsWith', 'DoesNotBeginWith', 'EndsWith', 'DoesNotEndWith',+ 'On', 'NotOn',+ 'ContainsData', 'DoesNotContainData',+];+// Nothing is blocked at present. Kept (empty) so a future platform-side breakage can be re-declared+// here with an explanation, rather than being folded into "unknown operator".+const BUSINESS_RULE_BLOCKED_OPERATORS = new Set();+// Operators that take NO value: they test presence, so a `value` would be meaningless. Measured —+// the serializer emits an EMPTY right-hand operand list for exactly these two.+const BUSINESS_RULE_VALUELESS_OPERATORS = new Set(['ContainsData', 'DoesNotContainData']);+// action type -> the field carrying its payload. `null` = no payload (none currently).+//+// The SDK models seven action types (adding `SetDefaultValue`, `ShowErrorMessage` and+// `Recommendation`), and all seven were measured serializing correctly through the real bundle.+// They are deliberately NOT exposed yet: each needs new mapping in `businessRuleDef`, and business+// rules cannot be exercised end to end on an environment that does not declare+// `CreateProcessWithWfomJson` — which is the environment this was developed against. Shipping+// mapping code that has never round-tripped against the platform is how a rule deploys and quietly+// does the wrong thing. Expose them from an environment where they can be live-verified.+const BUSINESS_RULE_ACTIONS = { SetVisibility: 'visible', LockUnlock: 'lock', SetBusinessRequired: 'required', SetFieldValue: 'value' };+const BUSINESS_RULE_ACTION_TYPES = Object.keys(BUSINESS_RULE_ACTIONS);+// Boolean-payload actions, so a string "false" (truthy in JS) is rejected rather than silently+// inverting the author's intent — the same trap `app.newLook` validation exists to close.+const BUSINESS_RULE_BOOLEAN_ACTIONS = new Set(['SetVisibility', 'LockUnlock', 'SetBusinessRequired']);+// `valueWorkflowType` in SDK terms: how the platform should interpret the literal. Named `dataType`+// in the App Spec because `valueType` in the SDK means something else (Value vs Field vs Lookup),+// and only `Value` is supported — so exposing that name would invite a distinction authors cannot use.+//+// This list has NO counterpart in the bundle any more, and nothing pins it. It used to mirror the+// XAML compiler's literal-type map, which this SDK uptake deleted along with the compiler.+//+// MEASURED against the replacement JSON path: `dataType` is IGNORED. Across all ten tokens below —+// and a made-up one — on both the condition path and the SetFieldValue action path, the serializer+// emits WorkflowAttributeType String ("14") every time:+// let r = valueType==='Lookup' ? … : valueType==='Clear' ? (valueWorkflowType ?? String)+// : WorkflowAttributeType.String+// So this is a curated closed set kept for two reasons only: it catches a typo at the spec gate, and+// it keeps the surface forward-compatible if the SDK starts honouring the field. Do NOT add a token+// on the assumption a test will validate it against the SDK — no such test can exist while there is+// nothing to validate against. `business-rules.test.js` instead pins the measured no-op.+const BUSINESS_RULE_DATA_TYPES = ['String', 'Memo', 'Picklist', 'State', 'Status', 'Boolean', 'Integer', 'Double', 'Decimal', 'Money'];+// Only entity scope is supported. A form-scoped rule needs `processtriggerscope 1` plus a form id,+// which cannot be resolved before the forms phase has run.+const BUSINESS_RULE_SCOPES = ['Entity'];++// --- Business process flows (BPF) ---------------------------------------------------------------+//+// A BPF is a `workflows` row (category 4 / type 1 / businessprocesstype 0) whose XAML the platform+// reads to materialize the read-only `processstage` rows. The vendored SDK owns that serialization;+// the plugin owns the judgment below.+//+// v1 is deliberately a SINGLE-ENTITY, linear flow: ordered stages, each with ordered steps bound to+// columns of that same entity. The SDK's artifact additionally models `category`, `nextStageId`,+// `relationshipName`, `branch`, stage `actions` and `securityRoles`, and those are NOT exposed here:+// * cross-entity stages / branching change what the flow MEANS and need live verification per+// shape before being offered;+// * `securityRoles` needs role IDs (the SDK grants CRUD privileges on the backing table that+// ACTIVATION creates, via `reconcileBpfSecurityRoles({ roleId, access })`) — that is the+// `security` phase's job, not this one, and is tracked as a follow-up.+// Offering a knob the build cannot verify is how a spec deploys something the author did not mean.+const BPF_STATUSES = ['Active', 'Draft'];++// `businessProcessFlows[].securityRoles` — who may run a flow. #513.+//+// The mechanic is NOT the one `forms[].securityRoles` uses. A form's roles live inside its formxml;+// a flow's live on a TABLE. Activating a flow makes the platform create an org-owned backing table,+// and holding privileges on that table is what lets a persona run the process.+//+// Three things measured live against a real environment before this surface was designed, because+// #513 asked for exactly that — and two of them contradict what the issue assumed:+//+// 1. The backing table's logical name is EXACTLY `bpfUniqueName(flow.name)`, the derivation this+// file already duplicates for its collision check. The issue expected it to need resolving from+// the deployed workflow's `uniquename`; measured, `uniquename` IS the derived value, so nothing+// has to be read back and the grant can be planned before the flow exists.+// 2. The table is ORGANIZATION-OWNED and every privilege it exposes reports+// `CanBeGlobal: true, CanBeLocal: false, CanBeDeep: false, CanBeBasic: false`. So there is no+// `scope` to author — Global is the only depth the platform will accept, and requesting any+// other is rejected by the SDK. (This is also why the SDK's own internal BPF role helper+// hardcodes `Depth: "Global"`: a platform constraint, not a shortcut.)+// 3. The exposed privileges are Create, Read, Write, Delete, Append and AppendTo — no Assign or+// Share, which org-owned tables do not have.+//+// So the surface is deliberately just `{ personas: [...] }`: the same key name and the same persona+// idiom as forms, minus every knob that would be a lie here. `everyone`, `fallbackForm` and `order`+// are formxml concepts and are rejected by name rather than ignored.+const BPF_SECURITY_ROLE_KEYS = new Set(['personas']);+// The access a persona needs on the backing table to run the flow. Fixed, not authorable: these are+// the four the platform's own BPF role reconciliation grants, and a partial set produces a flow a+// user can see but not advance — a worse outcome than not granting at all.+const BPF_ROLE_ACCESS = ['create', 'read', 'write', 'delete'];++function validateBpfSecurityRoles(flow, spec, label, errors) {+ const sr = flow && flow.securityRoles;+ if (sr === undefined) return;+ if (!sr || typeof sr !== 'object' || Array.isArray(sr)) {+ errors.push(`${label}: securityRoles must be an object like { "personas": ["Dispatcher"] }`);+ return;+ }+ for (const k of Object.keys(sr)) {+ if (BPF_SECURITY_ROLE_KEYS.has(k)) continue;+ const formOnly = k === 'everyone' || k === 'fallbackForm' || k === 'order';+ errors.push(`${label}: securityRoles has unknown key '${k}'`+ + (formOnly+ ? ` — that is a forms[].securityRoles concept written into formxml. A flow's access is a PRIVILEGE on its backing table, so there is no <Everyone /> equivalent and no ordering; list the personas that may run it.`+ : ` (allowed: ${[...BPF_SECURITY_ROLE_KEYS].join(', ')})`));+ }+ if (!Array.isArray(sr.personas) || sr.personas.some((p) => typeof p !== 'string' || !p.trim())) {+ errors.push(`${label}: securityRoles.personas must be an array of persona names`);+ return;+ }+ if (!sr.personas.length) {+ // Unlike a form — which is offered to everyone until it is restricted — a flow is reachable by+ // NOBODY until a privilege is granted, so an empty list is not a no-op, it is a request that+ // cannot be satisfied. Say so rather than silently granting nothing.+ errors.push(`${label}: securityRoles.personas is empty — a flow's backing table grants access to nobody by default, so an empty list would leave the flow unusable. List at least one persona, or omit securityRoles and grant access in Maker.`);+ return;+ }+ const declared = new Set((spec.personas || []).map((p) => String(canonicalPersonaName(p) || '').toLowerCase()));+ for (const p of sr.personas) {+ if (!declared.has(String(p).trim().toLowerCase())) {+ errors.push(`${label}: securityRoles names persona '${p}', which is not declared in personas[]`);+ }+ }+ const dupes = sr.personas.map((p) => String(p).trim().toLowerCase()).filter((p, i, a) => a.indexOf(p) !== i);+ if (dupes.length) errors.push(`${label}: securityRoles lists persona '${dupes[0]}' more than once`);+ // A DRAFT flow has no backing table: the table is created by ACTIVATION (measured). Granting on it+ // would fail against a table that does not exist, so this is an authoring error, not a runtime one.+ if (flow.status === 'Draft') {+ errors.push(`${label}: securityRoles cannot be applied to a Draft flow — the backing table that carries the privileges is created by ACTIVATION, so there is nothing to grant on yet. Set status "Active", or drop securityRoles.`);+ }+}++// Mirror of the vendored SDK's BPF `uniquename` derivation:+// uniqueName || `new_${name.toLowerCase().replace(/[^a-z0-9]/g, '') || 'businessprocessflow'}`+// Two properties of it drive the collision check below, and both are easy to get wrong:+// * it IGNORES the entity, so two flows on DIFFERENT tables can derive one unique name; and+// * it strips case and punctuation, so "Ticket Handling" and "ticket-handling" derive the same one.+// The plugin does not supply an explicit `uniqueName` (bpfDef leaves it to the SDK), so an author has+// no way to disambiguate. This is not merely a name clash: ACTIVATION creates an org-owned backing+// TABLE named after the derived value, so the second flow cannot deploy at all.+function bpfUniqueName(name) {+ const normalized = String(name === undefined || name === null ? '' : name).toLowerCase().replace(/[^a-z0-9]/g, '');+ return `new_${normalized || 'businessprocessflow'}`;+}++// The keys a stage / step may carry. Everything else is REJECTED rather than dropped: the SDK's own+// normalizers copy a fixed key set (stage: id/name/entityLogicalName/steps + category/nextStageId/+// relationshipName/actions/branch; step: id/name/fieldName/required) and discard the rest, so an+// unmapped key an author wrote — a stage `branch`, or the very plausible `fieldLogicalName` instead of+// `field` — would otherwise validate clean and deploy as if it had never been written.+const BPF_STAGE_KEYS = new Set(['name', 'entity', 'steps']);+const BPF_STEP_KEYS = new Set(['name', 'field', 'required']);+// Hard ceilings the vendored SDK enforces on a BPF. Pinned here so an over-large flow is a spec+// error, not a throw from inside the bundle in a late build phase.+const BPF_MAX_STAGES = 30;+const BPF_MAX_STEPS = 30;++// The keys an `entities[]` table may carry. Everything else is REJECTED rather than dropped.+//+// Entities were the one authorable block with NO allow-list, and the gap was not theoretical: the+// two most natural ways to ask for a second language — `entities[].languageCode` and+// `entities[].localizedLabels` — both validated clean and were then silently ignored, so an author+// asking for one table in Spanish got a SUCCESSFUL build with the request dropped and nothing+// reporting the loss (#537). Neither key is read anywhere in scripts/ or scripts/lib/.+//+// They cannot be honoured today, which is precisely why they must fail loudly rather than validate+// clean. The authoring language is BUILD-WIDE: provisionDataModel resolves ONE LCID and passes it to+// every createTable / createColumn / createGlobalOptionSet / insertStatusValue / createRelationship /+// createAlternateKey call, and the SDK takes it as a CONSTRUCTION-TIME option (the App/Form/Dashboard+// adapters bake it in), so a per-table language would need a second SDK instance. Multi-language+// labelling is blocked a layer lower still — the SDK's label serializer emits a ONE-element+// LocalizedLabels array by design, and pushing an artifact read under a different LCID throws+// ARTIFACT_LANGUAGE_MISMATCH.+//+// This list is the set the build actually READS. Adding a key here without a reader would re-open+// the very silent-drop hole it exists to close.+const ENTITY_KEYS = new Set([+ 'schemaName', 'displayName', 'pluralName', 'description', 'primaryAttribute', 'columns',+ 'hasNotes', 'quickCreate', 'existing', 'enrichDefaultViews',+ 'vectorIcon', 'iconDescription', 'icon',+ 'statusReasons', 'alternateKeys',+]);++// What to write INSTEAD, for the keys an author is most likely to reach for. A bare "unknown key"+// names the mistake but not the fix, and for these two the fix is not guessable from the schema.+//+// Prototype-less on purpose: the lookup key comes from the SPEC, so a table carrying `constructor`+// or `toString` would otherwise inherit a value from Object.prototype and splice+// "function Object() { [native code] }" into the error message.+const ENTITY_KEY_HINTS = Object.assign(Object.create(null), {+ languageCode: ' — the authoring language is build-wide, not per-table: set the spec-level `languageCode`, which applies to every table',+ 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 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).+//+// Shared by the business-rule and BPF validators — they ask the identical question, and an answer+// that drifts between them would let one accept a field the other rejects.+function declaredColumnLogicals(spec, entitySchemaName) {+ const ent = (spec.entities || []).find((e) => e && e.schemaName === entitySchemaName);+ const cols = new Set();+ if (!ent) return cols;+ if (ent.primaryAttribute && ent.primaryAttribute.schemaName) cols.add(String(ent.primaryAttribute.schemaName).toLowerCase());+ for (const c of ent.columns || []) if (c && c.schemaName) cols.add(String(c.schemaName).toLowerCase());+ for (const rel of spec.relationships || []) {+ if (rel && rel.referencing === entitySchemaName && rel.lookup && rel.lookup.schemaName) {+ cols.add(String(rel.lookup.schemaName).toLowerCase());+ }+ }+ return cols;+}++// Normalize a Dataverse language identifier (LCID) to a positive integer, or null if it is not one.+//+// This is the SINGLE definition used by all three entry points an LCID can arrive from, so they can+// never disagree about what is valid: the `--language-code` CLI flag (always a string), the App Spec+// `languageCode` field (JSON, so nominally a number but in practice anything), and a programmatic+// caller of resolveLanguageCode().+//+// It deliberately does NOT use a bare `Number(value)` cast, which is far too lenient for a value that+// is sent straight to Dataverse as a label LanguageCode:+// Number(true) === 1 -> `"languageCode": true` would build every label with LCID 1+// Number([1033]) === 1033 -> a one-element array would silently "work"+// Number('1e3') === 1000 -> exponent notation is never a real LCID+// Each of those passes a naive positive-integer check and then fails deep inside the data-model phase+// with an opaque Dataverse 400, instead of a clear spec/CLI error up front. Accept only a real number+// or an all-digits string, and bound it: an LCID is a 16-bit value, so anything above 0xFFFF cannot be+// one and would fail the same opaque way (65536, 1e20 and MAX_SAFE_INTEGER all cleared an unbounded+// positive-integer check).+// LCID reference: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-lcid/+const MAX_LCID = 0xFFFF;+function normalizeLanguageCode(value) {+ const ok = (n) => (n > 0 && n <= MAX_LCID ? n : null);+ if (typeof value === 'number') return Number.isInteger(value) ? ok(value) : null;+ if (typeof value === 'string' && /^\d+$/.test(value.trim())) return ok(Number(value.trim()));+ return null;+}++// --- localized Dataverse metadata labels (AB#6686428) --------------------------------------------+//+// Every author-facing NAME in the spec — a table's `displayName`/`pluralName`, its primary column's,+// a column's, a lookup's, a Choice option's, an alternate key's — may be EITHER a plain string or a+// map keyed by LCID:+//+// "displayName": "Project Baseline"+// "displayName": { "1033": "Project Baseline", "3082": "Línea base del proyecto" }+//+// The map form is the vendored SDK's own label shape (measured on the wire: each of createTable,+// createColumn, createGlobalOptionSet, createRelationship and createAlternateKey serializes a map+// into a multi-entry `LocalizedLabels` array), so the spec passes it straight through rather than+// pre-flattening it. A string still emits exactly one label at the build's `languageCode`, so every+// existing spec is byte-identical.+//+// WHY a map on the field rather than a sibling `localizedLabels` block: the label belongs next to+// the name it labels. A table-level block cannot address a Choice OPTION or a lookup's display name+// without inventing a parallel addressing scheme, and it separates the two halves of one value so+// they drift.+//+// The reported workaround is instructive about the failure mode: labels must be written for ALL+// languages in one request, "because a single-language PUT can overwrite 1033 even with merge+// labels". That is why an author who supplies a map omitting the build's base language gets a+// warning — the base label is what everyone without a matching UI language sees.+// Label shape: https://learn.microsoft.com/power-apps/developer/data-platform/webapi/reference/label+function isLocalizedLabelMap(value) {+ return !!value && typeof value === 'object' && !Array.isArray(value);+}++// Is a label ABSENT for the purpose of a required-label check?+//+// `undefined` alone is not enough. `null` is what a JSON author writes for "nothing", and a blank or+// whitespace-only string is the same statement typed differently — yet all three would satisfy an+// `=== undefined` test while meaning the opposite. That gap shipped once: the "a localized+// displayName needs an explicit pluralName" guard checked only `undefined`, so `pluralName: null`,+// `""` and `" "` all passed validation and the build then derived an ENGLISH plural for a+// bilingual table (or wrote the whitespace through as the label), silently discarding the very+// thing the guard exists to demand. A localized MAP is always present — `validateLabel` checks what+// is inside it separately.+function labelIsMissing(value) {+ if (value === undefined || value === null) return true;+ return typeof value === 'string' && value.trim() === '';+}++// The LCIDs a localized label declares, in ASCENDING numeric order. That is not a choice: V8+// enumerates integer-like object keys ascending regardless of how they were written, so this can+// never reflect the author's write order. Returns [] for a string or a non-canonical key.+function localizedLabelLcids(value) {+ if (!isLocalizedLabelMap(value)) return [];+ return Object.keys(value).filter((k) => /^[1-9]\d*$/.test(k)).map(Number);+}++// Resolve a label to ONE display string, for everything that must render or derive from it (the+// design doc, the app preview, eval facts, surface resolution, lint messages).+//+// Preference: the requested language (normally the spec's build-wide `languageCode`), then 1033,+// then the LOWEST declared LCID. The 1033 step is load-bearing and not merely a tidy default: V8+// orders integer-like object keys ASCENDING regardless of how they were written, so the last step+// picks the numerically smallest LCID — for `{ 1031: "…", 1033: "…" }` that would be German. 1033 is+// also the platform's own fallback for a user whose UI language has no label, so preferring it+// keeps a document and Dataverse telling the same story.+function labelText(value, languageCode) {+ if (typeof value === 'string') return value;+ if (!isLocalizedLabelMap(value)) return '';+ const wanted = normalizeLanguageCode(languageCode);+ const pick = (lcid) => (lcid != null && typeof value[String(lcid)] === 'string' ? value[String(lcid)] : undefined);+ const first = localizedLabelLcids(value)[0];+ const hit = pick(wanted) ?? pick(1033) ?? pick(first);+ return typeof hit === 'string' ? hit : '';+}++// Every string a label can legitimately be NAMED by: a plain label is itself; a localized label is+// each of its per-language strings. Used wherever an author may reference a label by text — Choice+// option → value resolution for `sampleData`, and `personas[].jobs[].surfaces[]` — so a reference+// written in ANY provisioned language resolves to the same artifact. Ordered by ascending LCID+// (V8's own ordering for integer-like keys), which is stable but is NOT the author's write order.+function labelAliases(value) {+ if (typeof value === 'string') return value.trim() ? [value] : [];+ if (!isLocalizedLabelMap(value)) return [];+ return Object.values(value).filter((v) => typeof v === 'string' && v.trim());+}++// Reject a Choice option list in which one LABEL STRING names more than one option. AB#6686428.+//+// Only reachable once options may be localized: with plain string labels a duplicate is already+// obviously wrong, but across languages it hides. Given+// [ { "1033": "Open", "3082": "Abierto" }, { "1033": "Abierto", "3082": "Cerrado" } ]+// the string "Abierto" names option 0 in Spanish and option 1 in English. Any resolution rule is+// then a coin flip that silently picks one — so the SPEC is what must be fixed, not the tie-break.+// Returns the offending aliases so the error can name them, each flagged `hidden` when at least one+// side is a LOCALIZED label — that is the case the author cannot see by reading the line, and the+// only one severe enough to fail a spec that provisioned correctly before this rule existed.+function ambiguousChoiceAliases(options) {+ const seen = new Map(); // alias -> { index, localized }+ const clashes = [];+ (options || []).forEach((label, i) => {+ const localized = isLocalizedLabelMap(label);+ for (const alias of labelAliases(label)) {+ const prior = seen.get(alias);+ if (prior && prior.index !== i) clashes.push({ alias, first: prior.index, second: i, hidden: localized || prior.localized });+ else if (!prior) seen.set(alias, { index: i, localized });+ }+ });+ return clashes;+}++// Reject a LOCALIZED label on a global choice. AB#6686428.+//+// Not a validation nicety: Dataverse ACCEPTS the multi-language payload and stores only the base+// language, reporting nothing. Measured 0/4 on an org with 1033 and 3082 provisioned — including+// through a raw `POST /GlobalOptionSetDefinitions` that bypasses the SDK entirely, so this is a+// platform limitation rather than a serialization bug we could fix. Every other localized surface+// verified 4/4 on the same org in the same session.+//+// Accepting it would reproduce the exact defect this feature exists to end: a green build with the+// author's request silently gone. Rejecting is loud, happens BEFORE any write, and has a working+// workaround — an inline Choice on the column, which is verified. Plain-string labels are untouched;+// only a map is rejected.+function rejectLocalizedGlobalChoice(gc, label, errors) {+ if (!gc || typeof gc !== 'object') return;+ const WHY = 'Dataverse accepts the multi-language payload for a global option set and stores ONLY the base '+ + 'language, reporting nothing (measured, including through a raw POST that bypasses the SDK). Use an inline '+ + 'Choice on the column — `columns[].options[]` localizes correctly — or set this option set\'s labels in Maker.';+ if (isLocalizedLabelMap(gc.displayName)) {+ errors.push(`${label}: displayName cannot be localized. ${WHY}`);+ }+ (Array.isArray(gc.options) ? gc.options : []).forEach((o, i) => {+ if (isLocalizedLabelMap(o)) errors.push(`${label}: options[${i}] cannot be localized. ${WHY}`);+ });+}++function validateChoiceOptionLabels(options, label, errors, opts = {}) {+ if (!Array.isArray(options)) return;+ options.forEach((o, i) => validateLabel(o, `${label}: options[${i}]`, errors, opts));+ for (const c of ambiguousChoiceAliases(options)) {+ const msg = `${label}: the label '${c.alias}' names BOTH options[${c.first}] and options[${c.second}] — one string cannot select two values, so a sample record or view filter using it resolves to options[${c.first}].`;+ if (c.hidden) {+ // At least one side is localized, so the collision is INVISIBLE on the page: the author reads+ // two different Spanish labels and cannot see that one matches the other option's English.+ errors.push(`${msg} It is not visible on the line because at least one of them is a localized label. Rename one.`);+ } else if (Array.isArray(opts.warnings)) {+ // Both sides are plain strings, so the duplicate is visible on the line — and Dataverse allows+ // it, so specs written before this rule existed provisioned fine. Failing them would break+ // working input to restate something the author can already see; warn instead.+ opts.warnings.push(`${msg} Rename one if they were meant to be different.`);+ }+ }+}++// Validate a label that may be localized. `errors` gets a message per problem; `warnings` (optional)+// gets the base-language advisory, which is guidance rather than a rule — a spec that deliberately+// labels a table only in Spanish is legal, just probably not what the author meant.+function validateLabel(value, label, errors, opts = {}) {+ const { required = false, warnings = null, baseLanguageCode = null } = opts;+ if (value === undefined || value === null) {+ if (required) errors.push(`${label} is required`);+ return;+ }+ if (typeof value === 'string') {+ // A blank PLAIN-STRING label is treated exactly as an absent one, because that is precisely what+ // the runtime does with it: every create site falls back with `x.displayName || x.schemaName`+ // (entity-provision.js:204, :737, :804, :960), so "" and undefined are indistinguishable by the+ // time they reach Dataverse. Rejecting "" while accepting undefined would fail specs that build+ // correctly today for no behavioural gain — the same reasoning already applied to+ // `validateDescription`'s `allowEmpty`. A blank entry INSIDE a localized map is a different+ // matter and is still rejected below: a non-empty map is truthy, so the `||` fallback never+ // fires and the blank per-language label reaches the platform.+ if (required && !value.trim()) errors.push(`${label} is required`);+ return;+ }+ if (!isLocalizedLabelMap(value)) {+ errors.push(`${label} must be a string, or a localized label keyed by LCID like { "1033": "Baseline", "3082": "Línea base" } (got ${typeof value})`);+ return;+ }+ let keys;+ try {+ keys = Object.keys(value);+ } catch {+ // A Proxy whose ownKeys trap throws would otherwise take down the whole validation pass.+ errors.push(`${label} could not be read as a localized label`);+ return;+ }+ if (!keys.length) {+ errors.push(`${label} is an empty localized label — give it at least one LCID, e.g. { "1033": "Baseline" } (the SDK rejects an empty label)`);+ return;+ }+ for (const k of keys) {+ // Canonical positive integers only, mirroring the SDK's own key check. "01033" and "en-US" are+ // rejected rather than coerced: a tag is ambiguous (es-ES is 3082 or 1034 depending on sort+ // order) and guessing wrong would not fail — it would label everything in the wrong language.+ if (!/^[1-9]\d*$/.test(k)) {+ errors.push(`${label}: '${k}' is not an LCID — use a canonical positive integer like 1033 (en-US) or 3082 (es-ES), not a language tag`);+ continue;+ }+ if (Number(k) > MAX_LCID) {+ errors.push(`${label}: LCID ${k} is out of range (max ${MAX_LCID})`);+ continue;+ }+ if (typeof value[k] !== 'string' || !value[k].trim()) {+ errors.push(`${label}: the label for LCID ${k} must be a non-empty string`);+ }+ }+ // Advisory, not an error. Dataverse serves the base-language label to every user whose UI language+ // has none, so a localized label that omits it leaves those users reading a schema name.+ const base = normalizeLanguageCode(baseLanguageCode);+ if (warnings && base && keys.length && !keys.includes(String(base))) {+ warnings.push(`${label}: no label for the spec's languageCode ${base} — that is the label users without a matching UI language will see. Add "${base}" alongside ${keys.filter((k) => /^[1-9]\d*$/.test(k)).join(', ')}.`);+ }+}+// Describe a rejected value for an error message WITHOUT being able to throw doing it.+// `JSON.stringify` throws on a BigInt and on a getter that throws, which would turn a structured+// validation error into a raw crash — the exact outcome this validator exists to prevent.+// The FALLBACK is guarded too: `Object.prototype.toString` itself throws on a revoked Proxy, so an+// unguarded fallback would reintroduce the crash it exists to avoid.+// Module-level so checks that run BEFORE validateAppSpec's local helpers are initialised can use it+// too (a `const` arrow declared later in the function is in the temporal dead zone until then).+function describeSpecValue(v) {+ try { return JSON.stringify(v); } catch { /* fall through */ }+ try { return Object.prototype.toString.call(v); } catch { return '<unprintable>'; }+}++// The single wording for a rejected LCID, shared by every entry point that accepts one.+//+// It is a function rather than a constant because the offending value is quoted back: the most+// common wrong input is a BCP-47 language TAG ("es-ES", "de-DE") — the thing a person naturally+// writes — and "must be a positive integer LCID" is true but leaves that author with nothing to act+// on. Shared for the same reason `ENTITY_KEYS` is: two entry points that disagree about what a bad+// LCID *is* teach the author two different rules for one field.+// LCID reference: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-lcid/+function invalidLanguageCodeMessage(value) {+ return `languageCode must be a positive integer LCID up to ${MAX_LCID} — e.g. 1033 (en-US) or 1031 (de-DE), `+ + `not a language tag like "de-DE" (got ${describeSpecValue(value)})`;+}++// Normalize a page's implementation source into a discriminated shape:+// { kind: 'tsx', codeFile } | { kind: 'intent' } | null+// A legacy top-level `codeFile` (schemaVersion < 2) is treated as an implemented tsx page. `null`+// means the page declares neither a source nor a codeFile. Whitespace-only codeFile values are+// treated as absent (codeFile trimmed to undefined) so a blank value fails the structural check+// rather than silently being treated as an implemented page.+function normalizePageSource(page) {+ if (page && page.source && typeof page.source === 'object') {+ if (page.source.kind === 'intent') return { kind: 'intent' };+ if (page.source.kind === 'tsx') {+ // Trim so ' ' is treated identically to undefined — blank is not an implemented codeFile.+ const codeFile = typeof page.source.codeFile === 'string' ? page.source.codeFile.trim() || undefined : page.source.codeFile;+ return { kind: 'tsx', codeFile };+ }+ return { kind: page.source.kind }; // malformed — surfaced by the validator below+ }+ // Treat a whitespace-only legacy codeFile as absent so it fails the implemented check.+ if (page && typeof page.codeFile === 'string' && page.codeFile.trim()) {+ return { kind: 'tsx', codeFile: page.codeFile.trim() };+ }+ return null;+}++// Whether the build should enable "Allow quick create" (`IsQuickCreateEnabled`) on a table.+// TWO triggers, both author-controlled:+// 1. explicit `entities[].quickCreate === true`, OR+// 2. the spec authors a `formType: 'QuickCreate'` form for that entity — enabling the flag then+// just makes the form the author already declared actually reachable (the inline "+ New" from a+// lookup / sub-grid). Authoring a Quick Create form but leaving the table flag OFF is a footgun:+// the form exists but the platform never surfaces it, so we treat the authored QC form as intent.+// PURE: both the build engine (entity-provision.js) and the eval fact extractor (schema-facts.js) call+// this so the eval grades the EXACT rule the engine applies (DRY — never a naive spec echo).+function quickCreateEnabledFor(spec, entity) {+ if (!entity) return false;+ if (entity.quickCreate === true) return true;+ const logical = String(entity.schemaName || '').toLowerCase();+ if (!logical) return false;+ return (spec && spec.forms || []).some(+ (f) => f && f.formType === 'QuickCreate' && String(f.entity || '').toLowerCase() === logical,+ );+}++// A maker-facing `description`, supported on every artifact whose SDK create surface accepts one+// (table, column, view, chart, form, dashboard, business rule, app, web resource).+//+// Deliberately a soft contract: descriptions are OPTIONAL, because making them mandatory would fail+// every spec authored before they existed. What is validated is only that a supplied value is usable+// — a number or an object here means the author meant something else, and silently stringifying it+// would write "[object Object]" into Dataverse.+//+// 2000 is the Dataverse ceiling for a description Label; the platform truncates past it rather than+// erroring, so catching it here is the only place the author finds out.+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/entity-attribute-metadata+const DESCRIPTION_MAX = 2000;+function validateDescription(value, label, errors, opts = {}) {+ if (value === undefined || value === null) return;+ if (typeof value !== 'string') {+ errors.push(`${label}: description must be a string`);+ return;+ }+ // `app.description` predates this contract and countless existing specs (and every spec emitted by+ // `download-model-app`) carry it as `""`. Rejecting that would fail specs that are otherwise fine,+ // so emptiness is tolerated exactly where it is already established — never for a NEW surface,+ // where an empty string is the one value that could blank a maker's text on rebuild.+ if (!value.trim()) {+ if (opts.allowEmpty) return;+ errors.push(`${label}: description must not be blank — omit the field instead of setting an empty string`);+ return;+ }+ if (value.length > DESCRIPTION_MAX) {+ errors.push(`${label}: description is ${value.length} characters (max ${DESCRIPTION_MAX})`);+ }+}++// Per-control form-field options: `readOnly`, `hidden`, `after`.+//+// Reachable two ways — inline on an EXPLICIT layout's `sections[].fields[]` entry, or via the+// form-level `fieldOptions` map (the only route under an AUTO layout, which has no field list).+//+// Only the ENABLED state is written by the build (`isReadOnly: true` / `visible: false`); `false` is+// a no-op rather than an un-set, so it is rejected here instead of being accepted and quietly+// ignored — an author who writes `readOnly: false` expecting it to clear an existing lock would+// otherwise get a green build and no change.+// `forms[].securityRoles` — who a form is offered to. AB#6648526.+//+// Direction matters and is easy to get backwards: a form with NO assignment is offered to EVERY+// role, so declaring this RESTRICTS the form. That makes every failure mode here access-relevant —+// a typo'd persona or an empty list narrows a form to nobody — so each is a hard error rather than+// a warning, and the build additionally halts on an unresolvable persona.+//+// `everyone` and `roleIds` are mutually exclusive in the PLATFORM's model (`<Everyone />` replaces+// the `<Role>` list rather than adding to it), not merely in this validator; the SDK rejects the+// combination with INVALID_ARGUMENT, so catching it here just names the form.+function validateFormSecurityRoles(f, spec, errors) {+ const sr = f.securityRoles;+ if (sr === undefined) return;+ const label = `form '${f.name || f.entity}'`;+ if (!sr || typeof sr !== 'object' || Array.isArray(sr)) {+ errors.push(`${label}: securityRoles must be an object like { "personas": ["Dispatcher"] } or { "everyone": true }`);+ return;+ }+ const known = new Set(['personas', 'everyone', 'fallbackForm', 'order']);+ for (const k of Object.keys(sr)) {+ if (!known.has(k)) errors.push(`${label}: securityRoles has unknown key '${k}' — expected ${[...known].join(', ')}`);+ }++ const hasEveryone = sr.everyone !== undefined;+ if (hasEveryone && typeof sr.everyone !== 'boolean') {+ errors.push(`${label}: securityRoles.everyone must be a boolean`);+ }+ // `everyone: false` is not "restrict to nobody" — it is an author reaching for a switch that does+ // not exist.+ if (sr.everyone === false) {+ errors.push(`${label}: securityRoles.everyone: false does nothing — use "everyone": true to make the form available to every role again, or list personas to restrict it`);+ }++ if (sr.personas !== undefined) {+ if (!Array.isArray(sr.personas) || sr.personas.some((p) => typeof p !== 'string' || !p.trim())) {+ errors.push(`${label}: securityRoles.personas must be an array of persona names`);+ } else if (!sr.personas.length) {+ errors.push(`${label}: securityRoles.personas is empty — that would offer the form to NO role. List at least one persona, or use "everyone": true.`);+ } else {+ // Resolved against `personas[]` at author time so a typo is a spec error naming the form,+ // rather than a build halt two minutes into a run.+ const declared = new Set((spec.personas || []).map((p) => String(canonicalPersonaName(p) || '').toLowerCase()));+ for (const p of sr.personas) {+ if (!declared.has(String(p).trim().toLowerCase())) {+ errors.push(`${label}: securityRoles names persona '${p}', which is not declared in personas[]`);+ }+ }+ const dupes = sr.personas.map((p) => String(p).trim().toLowerCase()).filter((p, i, a) => a.indexOf(p) !== i);+ if (dupes.length) errors.push(`${label}: securityRoles lists persona '${dupes[0]}' more than once`);+ }+ }++ if (sr.everyone === true && sr.personas !== undefined) {+ errors.push(`${label}: securityRoles cannot set both 'everyone' and 'personas' — the platform models <Everyone /> as a replacement for the role list, not an addition to it`);+ }+ if (!hasEveryone && sr.personas === undefined) {+ errors.push(`${label}: securityRoles must say who the form is for — set 'personas' or 'everyone': true`);+ }++ if (sr.fallbackForm !== undefined && typeof sr.fallbackForm !== 'boolean') {+ errors.push(`${label}: securityRoles.fallbackForm must be a boolean`);+ }+ if (sr.order !== undefined && (!Number.isInteger(sr.order) || sr.order < 0)) {+ errors.push(`${label}: securityRoles.order must be a non-negative integer (got ${JSON.stringify(sr.order)})`);+ }++ // The build addresses this form by (entity, formType, name) — `created.forms` is keyed by entity+ // and holds only the Main form, so a later phase cannot reach a sibling any other way. Duplicate+ // (entity, formType, name) is otherwise LEGAL here: only QuickView forms are checked for a unique+ // (entity, name), because Main and Card may both be called "Information" harmlessly.+ //+ // Harmless, that is, until one of them declares securityRoles: the map would keep whichever was+ // built last, and the restriction would land on the wrong form while every structural check passed+ // and the build reported success. Reject the ambiguity instead of picking a winner.+ const twin = (spec.forms || []).filter((o) => o+ && String(o.entity || '').toLowerCase() === String(f.entity || '').toLowerCase()+ && (o.formType || 'Main') === (f.formType || 'Main')+ && String(o.name || '') === String(f.name || ''));+ if (twin.length > 1) {+ errors.push(`${label}: securityRoles needs a form this spec can identify unambiguously, but ${twin.length} forms share (entity ${f.entity}, type ${f.formType || 'Main'}, name '${f.name || ''}') — rename one, or move the assignment to the form you meant`);+ }+}++function validateFormFieldOptions(f, entityByLower, errors, warnings) {+ const label = `form '${f.name || f.entity}'`;+ const entity = entityByLower.get(String(f.entity || '').toLowerCase());+ const columnType = (logical) => {+ if (!entity) return undefined;+ const c = (entity.columns || []).find((x) => x && x.schemaName && x.schemaName.toLowerCase() === logical);+ return c && (c.type || 'Text');+ };+ const explicit = Array.isArray(f.tabs) || f.layout === 'explicit';+ // Every field this form declares an option for, from either route, so the checks below run once+ // per (field, source) pair with a source-accurate message.+ const seen = [];+ // Fields the EXPLICIT layout lists by position. An `after` anchor for one of these — from either+ // route — would give the form two competing orderings.+ const listedByLayout = new Set();++ for (const t of (Array.isArray(f.tabs) ? f.tabs : [])) {+ for (const s of ((t && t.sections) || [])) {+ if (s && s.fields !== undefined && !Array.isArray(s.fields)) {+ // Guard the compiler, which does `(s.fields || []).map(...)`. A string is ITERABLE and every+ // character of it IS a string, so a `fields: "new_name"` typo would pass a naive per-entry+ // check and then throw a raw TypeError at compile time instead of producing a finding. A+ // non-iterable value (`{}`, `3`) would throw right here. Note `spec-shape.js` does not model+ // `fields`, so `normalizeSpecShape` does not coerce it — this check is load-bearing.+ errors.push(`${label}: a section's fields must be an array of column logical names`);+ continue;+ }+ for (const entry of ((s && s.fields) || [])) {+ if (entry && typeof entry === 'object' && !Array.isArray(entry)) {+ if (!entry.name || typeof entry.name !== 'string') {+ errors.push(`${label}: a field entry object is missing a string 'name'`);+ continue;+ }+ listedByLayout.add(String(entry.name).toLowerCase());+ seen.push({ name: String(entry.name).toLowerCase(), opt: entry, where: `field '${entry.name}'`, inline: true });+ } else if (typeof entry === 'string') {+ listedByLayout.add(entry.toLowerCase());+ } else {+ errors.push(`${label}: a field entry must be a column logical name or an object { name, readOnly?, hidden?, after? }`);+ }+ }+ }+ }++ if (f.fieldOptions !== undefined) {+ if (!f.fieldOptions || typeof f.fieldOptions !== 'object' || Array.isArray(f.fieldOptions)) {+ errors.push(`${label}: fieldOptions must be an object keyed by column logical name`);+ } else {+ for (const key of Object.keys(f.fieldOptions)) {+ const v = f.fieldOptions[key];+ if (!v || typeof v !== 'object' || Array.isArray(v)) {+ errors.push(`${label}: fieldOptions['${key}'] must be an object { readOnly?, hidden?, after? }`);+ continue;+ }+ seen.push({ name: String(key).toLowerCase(), opt: v, where: `fieldOptions['${key}']`, inline: false });+ }+ }+ }++ for (const { name, opt, where, inline } of seen) {+ for (const flag of ['readOnly', 'hidden']) {+ if (opt[flag] === undefined) continue;+ if (typeof opt[flag] !== 'boolean') {+ errors.push(`${label}: ${where} ${flag} must be a boolean`);+ } else if (opt[flag] === false) {+ errors.push(`${label}: ${where} sets ${flag}: false, which the build cannot apply — it only ever writes the ENABLED state, so a maker's existing setting is never silently cleared. Omit the flag, or clear it in the form designer.`);+ }+ }+ if (opt.after !== undefined) {+ if (typeof opt.after !== 'string' || !opt.after.trim()) {+ errors.push(`${label}: ${where} after must be the logical name of another field on this form`);+ } else if (String(opt.after).toLowerCase() === name) {+ errors.push(`${label}: ${where} anchors '${name}' after itself`);+ } else if (inline || listedByLayout.has(name)) {+ // An explicit layout already expresses order by listing position, so honouring `after` for a+ // listed field would give the form two competing orderings — and they would DISAGREE: the+ // create path follows the authored list, while the reconcile applies the anchor, so the same+ // spec would produce one order on a new form and another on the first rebuild.+ // A form-level anchor for a field the layout does NOT list stays legal: that is the+ // `prune: false` case, where the point is to position a control on a deployed form without+ // re-declaring the rest of it.+ errors.push(`${label}: ${where} cannot use 'after' for a field an explicit tabs layout already lists — the listed order positions it. Move it in the list instead, or drop it from the list if you mean to position it against fields this layout does not declare.`);+ }+ }+ // A BigInt has no Unified Interface control, so a form placement renders "Error loading control".+ // Auto layout skips them outright; an explicit layout still honours the author, but declaring+ // per-control options for one is almost certainly a mistake worth surfacing.+ if (columnType(name) === 'BigInt') {+ warnings.push(`${label}: ${where} targets '${name}', a BigInt column — Big Integer has no Unified Interface form control, so it renders "Error loading control" wherever it is placed`);+ }+ }++ // Two contradictory anchor shapes. Both are silently unstable rather than wrong-but-stable: the+ // reconcile moves each field to its anchor on every build and they undo each other, so the form+ // never converges and a rebuild issues writes forever. Neither can be resolved automatically —+ // "immediately after X" cannot be true of two fields at once, and a cycle has no valid order — so+ // they are rejected at author time instead of being papered over by the placement code.+ const anchorOf = new Map();+ for (const { name, opt } of seen) {+ if (opt.after && typeof opt.after === 'string') anchorOf.set(name, String(opt.after).toLowerCase());+ }+ const claimants = new Map();+ for (const [name, anchor] of anchorOf) {+ if (!claimants.has(anchor)) claimants.set(anchor, []);+ claimants.get(anchor).push(name);+ }+ for (const [anchor, names] of claimants) {+ if (names.length > 1) {+ errors.push(`${label}: ${names.map((n) => `'${n}'`).join(' and ')} are both anchored after '${anchor}' — only one field can sit immediately after another. Chain them instead (anchor the second one after the first).`);+ }+ }+ for (const start of anchorOf.keys()) {+ const seenInWalk = new Set([start]);+ let cur = anchorOf.get(start);+ while (cur !== undefined) {+ if (seenInWalk.has(cur)) {+ if (cur === start) errors.push(`${label}: the 'after' anchors form a cycle through '${start}' — there is no order that satisfies them all.`);+ break;+ }+ seenInWalk.add(cur);+ cur = anchorOf.get(cur);+ }+ }++ if (f.prune !== undefined) {+ if (typeof f.prune !== 'boolean') {+ errors.push(`${label}: prune must be a boolean`);+ } else if (f.prune === false && !explicit) {+ warnings.push(`${label}: prune: false has no effect on an auto layout — an auto layout is already additive and never removes a field`);+ }+ }++ // An explicit layout that names a BigInt column produces a broken control on a live record. It is a+ // warning, not an error: the author asked for it by name and may be pairing it with a custom control.+ if (explicit) {+ for (const t of (Array.isArray(f.tabs) ? f.tabs : [])) {+ for (const s of ((t && t.sections) || [])) {+ // Re-guard: the array check in the first loop `continue`s that loop only. Without repeating+ // it here a non-iterable `fields` (e.g. `{}` or `3`) throws a raw TypeError out of+ // validateAppSpec — discarding the correct finding the first loop already pushed.+ if (!Array.isArray(s && s.fields)) continue;+ for (const entry of s.fields) {+ const nm = String((entry && typeof entry === 'object' ? entry.name : entry) || '').toLowerCase();+ if (nm && columnType(nm) === 'BigInt') {+ warnings.push(`${label}: field '${nm}' is a BigInt column — Big Integer has no Unified Interface form control, so it will render "Error loading control" on every record. Keep it off the form (it stays readable through the API).`);+ }+ }+ }+ }+ }+}++function validateAppSpec(spec, opts = {}) {+ const profile = opts.profile || 'deploy';+ const errors = [];+ // Non-blocking advisories (e.g. a PRE-EXISTING duplicate page name the current run did not create).+ // Additive to the return shape — callers that only read { ok, errors } are unaffected.+ const warnings = [];+ if (!VALIDATION_PROFILES.includes(profile)) {+ return { ok: false, errors: [`unknown validation profile '${profile}' (valid: ${VALIDATION_PROFILES.join(', ')})`], warnings };+ }+ if (!spec || typeof spec !== 'object') {+ return { ok: false, errors: ['spec is not an object'], warnings };+ }+ // Structural normalization (shared with lintAppSpec) so a half-typed collection produces findings+ // rather than a raw TypeError. Covers NESTED collections too — `entity.columns: {}` and+ // `appShell.areas: {}` are realistic mid-edit states that reach `for...of` and throw.+ const shape = normalizeSpecShape(spec);+ errors.push(...shape.errors);+ spec = shape.spec;+ if (!spec.solution || !spec.solution.uniqueName) {+ errors.push('solution.uniqueName is required');+ }+ if (!spec.solution || !spec.solution.publisherPrefix) {+ errors.push('solution.publisherPrefix is required');+ }+ if (!spec.app || !spec.app.name) {+ errors.push('app.name is required');+ }+ validateDescription(spec.solution && spec.solution.description, 'solution', errors);+ // allowEmpty: `app.description: ""` is the established shape (download-model-app emits it).+ validateDescription(spec.app && spec.app.description, 'app', errors, { allowEmpty: true });+ for (const gc of spec.globalChoices || []) {+ validateDescription(gc && gc.description, `globalChoice '${(gc && gc.name) || '(unnamed)'}'`, errors);+ // Choice labels may be localized (AB#6686428). The SDK serializes an LCID map into a multi-entry+ // LocalizedLabels array on BOTH the option-set display name and each option's label.+ const gcLabel = `globalChoice '${(gc && gc.name) || '(unnamed)'}'`;+ validateLabel(gc && gc.displayName, `${gcLabel}: displayName`, errors, { warnings, baseLanguageCode: spec.languageCode });+ validateChoiceOptionLabels(gc && gc.options, gcLabel, errors, { warnings, baseLanguageCode: spec.languageCode });+ rejectLocalizedGlobalChoice(gc, gcLabel, errors);+ }+ // The modern ("new look") shell is an opt-in per-app SETTING, not an appmodule column —+ // `navigationtype` only selects Single/Multi session and is unrelated. Boolean-only: a string+ // "false" is truthy in JS and would silently turn the new look ON for an author who meant to+ // disable it.+ if (spec.app && spec.app.newLook !== undefined && typeof spec.app.newLook !== 'boolean') {+ errors.push('app.newLook must be a boolean');+ }+ // The Wave 2 header/navigation refresh is a SEPARATE public-preview setting from the new look;+ // enabling one does not enable the other. Boolean-only for the same reason as newLook — a string+ // "false" is truthy and would silently turn the feature ON for an author who meant to disable it.+ if (spec.app && spec.app.headerNavigationRefresh !== undefined && typeof spec.app.headerNavigationRefresh !== 'boolean') {+ errors.push('app.headerNavigationRefresh must be a boolean');+ }+ if (spec.languageCode !== undefined && normalizeLanguageCode(spec.languageCode) === null) {+ // Keep the leading clause stable — the CLI flag and two test suites match on it. The appended+ // guidance exists because the bare message named the mistake without naming the fix, and a+ // language TAG is the most likely thing an author reaches for.+ //+ // A tag is NOT accepted as an alias, deliberately: the mapping is genuinely ambiguous where it+ // matters (es-ES is 3082 with the international sort and 1034 with the traditional one), and a+ // wrong guess would not fail — it would build every label in the wrong language, which is the+ // same silent-corruption class this validator exists to prevent. Naming the LCID is safe;+ // inferring one is not.+ errors.push(invalidLanguageCodeMessage(spec.languageCode));+ }+ const entityNames = new Set();+ const entityByLower = new Map(); // logical (lowercased schemaName) -> entity+ // Describe a rejected value for an error message WITHOUT being able to throw doing it.+ // See describeSpecValue above for why a bare JSON.stringify is unsafe here.+ const describeValue = describeSpecValue;+ // A table reference an author writes becomes a Dataverse METADATA NAME, so it has to be a string+ // BEFORE it is compared. `String([["new_ticket"]])` is `"new_ticket"`, so a nested array passes an+ // entity-membership check and then throws a raw TypeError deep in the build, where the engine+ // calls `.toLowerCase()` on the array itself. It is the same trap as `views[].columns` (#525):+ // coercing during validation makes the validator agree with a value the builder cannot use.+ // Returns true when it reported a problem, so callers can `continue`.+ const badEntityRef = (value, where) => {+ if (typeof value === 'string' && value.trim()) return false;+ errors.push(`${where}: entity must be a table name (a string), got ${describeValue(value)}`);+ return true;+ };+ for (const e of spec.entities || []) {+ // Reject unknown keys (#537). A key with no reader is otherwise accepted and dropped, so an+ // explicit authoring instruction disappears into a successful build.+ //+ // Guarded to plain objects: a malformed entity already fails the schemaName check below, and+ // `Object.keys('x')` would turn one bad value into a bogus "unknown key '0'".+ //+ // The enumeration itself is guarded because the object comes from the CALLER: a programmatic+ // caller can pass a Proxy whose `ownKeys` trap throws, and this validator's contract is to+ // RETURN problems, not to throw them.+ if (e && typeof e === 'object' && !Array.isArray(e)) {+ // The label is resolved BEFORE `schemaName` is validated, and reading it can itself fail (a+ // getter that throws). Without a fallback a malformed entity reported `entity undefined:+ // unknown key ...` next to the real `entity.schemaName is required` — two errors for one+ // problem, one of them naming a table that does not exist.+ let label;+ try {+ label = typeof e.schemaName === 'string' && e.schemaName.trim() ? `entity ${e.schemaName}` : 'an entity with no schemaName';+ } catch {+ label = 'an entity whose schemaName could not be read';+ }+ let keys;+ try {+ keys = Object.keys(e);+ } catch {+ keys = null;+ errors.push('an entity could not be inspected: enumerating its keys threw');+ }+ for (const k of keys || []) {+ if (ENTITY_KEYS.has(k)) continue;+ errors.push(`${label}: unknown key '${k}'${ENTITY_KEY_HINTS[k] || ''} (allowed: ${[...ENTITY_KEYS].join(', ')})`);+ }+ }+ // `schemaName` must be a non-empty STRING, and the check says so rather than only testing+ // truthiness. `!e.schemaName` let `42`, `{}` and `[]` through, and the very next line called+ // `.toLowerCase()` on them — so a spec carrying `"schemaName": 42` CRASHED the validator with a+ // raw TypeError instead of being told what was wrong. That is the one outcome this function must+ // never produce: its whole contract is to turn bad input into structured errors, and a caller+ // that gets a TypeError loses every finding collected so far, not just this one. Reachable from+ // any hand- or model-authored JSON file, which is how every spec arrives.+ //+ // The read itself is wrapped only because it is cheap to do so. A getter or Proxy trap that+ // throws is NOT comprehensively defended against in this validator — several later passes+ // interpolate `e.schemaName` directly — and no attempt is made to pretend otherwise; that shape+ // cannot come from `JSON.parse`, only from a programmatic caller.+ let schemaNameValue;+ let schemaNameReadable = true;+ try { schemaNameValue = e.schemaName; } catch { schemaNameReadable = false; }+ if (!schemaNameReadable) {+ errors.push('entity.schemaName could not be read');+ } else if (typeof schemaNameValue !== 'string' || !schemaNameValue.trim()) {+ // `undefined`/`null`/`""` keep the original wording: it is the overwhelmingly common case and+ // "is required" is the right thing to say about an absent value. A present-but-wrong value+ // gets its own message, quoting what was found, because "required" would be actively+ // misleading to someone who did supply one.+ errors.push(schemaNameValue === undefined || schemaNameValue === null || schemaNameValue === ''+ ? 'entity.schemaName is required'+ : `entity.schemaName must be a non-empty string (got ${describeSpecValue(schemaNameValue)})`);+ } else {+ entityNames.add(schemaNameValue);+ entityByLower.set(schemaNameValue.toLowerCase(), e);+ }+ if (!e.primaryAttribute || !e.primaryAttribute.schemaName) {+ errors.push(`entity ${e.schemaName}: primaryAttribute.schemaName required`);+ }+ if (e.quickCreate !== undefined && typeof e.quickCreate !== 'boolean') {+ errors.push(`entity ${e.schemaName}: quickCreate must be a boolean`);+ }+ // Table + primary-column labels may be localized (AB#6686428).+ validateLabel(e.displayName, `entity ${e.schemaName}: displayName`, errors, { warnings, baseLanguageCode: spec.languageCode });+ validateLabel(e.pluralName, `entity ${e.schemaName}: pluralName`, errors, { warnings, baseLanguageCode: spec.languageCode });+ if (e.primaryAttribute) validateLabel(e.primaryAttribute.displayName, `entity ${e.schemaName}: primaryAttribute.displayName`, errors, { warnings, baseLanguageCode: spec.languageCode });+ // A LOCALIZED displayName cannot derive a plural. The English fallback appends "s"+ // (`${displayName}s`), which is wrong in most languages and meaningless for a label map — so+ // rather than write "Línea base del proyectos" into Dataverse, require the author to say it.+ // `labelIsMissing` rather than `=== undefined`: `null`, `""` and `" "` are the same statement+ // and all three used to slip through into that English derivation.+ if (isLocalizedLabelMap(e.displayName) && labelIsMissing(e.pluralName)) {+ errors.push(`entity ${e.schemaName}: pluralName is required when displayName is a localized label — the plural cannot be derived by appending "s" in every language`);+ }+ validateDescription(e.description, `entity ${e.schemaName}`, errors);+ for (const c of e.columns || []) {+ if (!c.schemaName) {+ errors.push(`entity ${e.schemaName}: a column is missing schemaName`);+ }+ validateDescription(c.description, `entity ${e.schemaName}: column ${c.schemaName}`, errors);+ validateLabel(c.displayName, `entity ${e.schemaName}: column ${c.schemaName} displayName`, errors, { warnings, baseLanguageCode: spec.languageCode });+ // Local (per-column) Choice options carry labels too, and take the same localized shape.+ validateChoiceOptionLabels(c.options, `entity ${e.schemaName}: column ${c.schemaName}`, errors, { warnings, baseLanguageCode: spec.languageCode });+ // A Customer column is created through `createCustomerColumn`, whose payload is only+ // { Lookup, OneToManyRelationships } — the SDK has nowhere to put a description, so one+ // authored here is silently discarded. Warn rather than error: the spec is still valid and+ // still builds; the author just needs to know the value will not appear in Dataverse.+ if (c.type === 'Customer' && c.description) {+ warnings.push(`entity ${e.schemaName}: column ${c.schemaName} is a Customer column — the SDK's createCustomerColumn accepts no description, so this one will NOT be written to Dataverse`);+ }+ if (c.type && !TYPE_MAP[c.type]) {+ errors.push(`entity ${e.schemaName}: column ${c.schemaName} has unknown type '${c.type}'`);+ }+ if ((c.type === 'Choice' || c.type === 'MultiChoice') && !(Array.isArray(c.options) && c.options.length) && !c.globalChoice) {+ errors.push(`column ${c.schemaName}: ${c.type} needs options[] or a globalChoice reference`);+ }+ // Grid data visualization (preview). Only the enum is enforced. Column-TYPE compatibility is+ // deliberately NOT enforced: the SDK does not constrain it either, and the sensible pairings+ // are not a clean "numeric only" rule (LineChart is documented for a TEXT column holding+ // comma-separated numbers). Guessing a constraint the platform does not have would reject+ // valid specs, so type guidance lives in the schema doc instead.+ if (c.visualization !== undefined && !COLUMN_VISUALIZATIONS.includes(c.visualization)) {+ errors.push(`entity ${e.schemaName}: column ${c.schemaName} has unknown visualization '${c.visualization}' — must be one of ${COLUMN_VISUALIZATIONS.join('|')}`);+ }+ // AB#6648523: Boolean default value. The SDK used to hardcode `DefaultValue: false`; the+ // vendored bundle now honours an explicit value on create AND update (measured against+ // cds-maker-sdk.cjs). Boolean-only for the same reason as the form-event flags below — a+ // truthy-but-non-boolean value (e.g. the string "false") must be rejected, not coerced — and+ // type-gated to the exact 'Boolean' column: the SDK itself throws InvalidArgumentError for+ // defaultValue on any other type, so this just moves that same failure to the spec gate and+ // names the column instead of surfacing mid-build.+ if (c.defaultValue !== undefined) {+ if (typeof c.defaultValue !== 'boolean') {+ errors.push(`entity ${e.schemaName}: column ${c.schemaName} defaultValue must be a boolean (got ${JSON.stringify(c.defaultValue)})`);+ } else if (c.type !== 'Boolean') {+ errors.push(`entity ${e.schemaName}: column ${c.schemaName} defaultValue is only valid on a Boolean column (this one is '${c.type || 'Text'}')`);+ }+ }+ // AB#6648522: Whole Number display Format (e.g. render a raw integer count of minutes as a+ // Duration picker in the maker UI). Restricted to the exact 'Integer' App Spec type, NOT the+ // wider Integer/BigInt/Decimal/Double/Money switch case columnOptions() shares for min/max/+ // precision — the SDK's Format option is Integer-only, so a spec targeting Decimal would+ // otherwise pass this gate and hit the SDK's own InvalidArgumentError deep inside the+ // data-model phase instead of here.+ if (c.integerFormat !== undefined) {+ if (!INTEGER_FORMATS.includes(c.integerFormat)) {+ errors.push(`entity ${e.schemaName}: column ${c.schemaName} has unknown integerFormat '${c.integerFormat}' — must be one of ${INTEGER_FORMATS.join('|')}`);+ } else if (c.type !== 'Integer') {+ errors.push(`entity ${e.schemaName}: column ${c.schemaName} integerFormat is only valid on an Integer column (this one is '${c.type || 'Text'}')`);+ }+ }+ // AB#6651276: per-verb write/read permissions (e.g. isValidForUpdate:false makes a column+ // write-once after creation — the entire point of the feature, so `false` must validate and+ // build identically to `true`). Boolean-only, same reasoning as the form-event flags below.+ // Type-agnostic per the SDK — every buildable column type accepts these on BOTH create and+ // update (measured) — EXCEPT Customer, which is created through createCustomerColumn, a+ // wholly separate SDK call whose options carry no such fields. Warned rather than rejected+ // there, matching the Customer + description precedent above: the spec stays valid and still+ // builds, the author just needs to know the flag will not reach Dataverse.+ let hasValidForFlag = false;+ for (const flag of ['isValidForCreate', 'isValidForUpdate', 'isValidForRead']) {+ if (c[flag] === undefined) continue;+ hasValidForFlag = true;+ if (typeof c[flag] !== 'boolean') {+ errors.push(`entity ${e.schemaName}: column ${c.schemaName} ${flag} must be a boolean (got ${JSON.stringify(c[flag])})`);+ }+ }+ if (hasValidForFlag && c.type === 'Customer') {+ warnings.push(`entity ${e.schemaName}: column ${c.schemaName} is a Customer column — the SDK's createCustomerColumn accepts no isValidForCreate/isValidForUpdate/isValidForRead, so these will NOT be written to Dataverse`);+ }+ }+ }+ if (!entityNames.size) {+ errors.push('at least one entity is required');+ }+ // Web resources (optional — JS/HTML/CSS shipped for form logic).+ const WEB_RESOURCE_KINDS = new Set(['js', 'html', 'css', 'xml', 'png', 'jpg', 'gif', 'xsl', 'ico', 'svg', 'resx']);+ const FORM_EVENTS = new Set(['onload', 'onsave', 'onchange']);+ const webResourceNames = new Set();+ const IMAGE_WR_TYPES = new Set(['png', 'jpg', 'gif', 'svg', 'ico']);+ const imageWebResourceNames = new Set();+ const svgWebResourceNames = new Set(); // SVG only — valid for a table's vector icon+ const rasterWebResourceNames = new Set(); // png/jpg/gif/ico — valid for a table's raster icon+ for (const wr of spec.webResources || []) {+ if (!wr || !wr.name) { errors.push('a webResource is missing a name'); continue; }+ validateDescription(wr.description, `webResource '${wr.name}'`, errors);+ webResourceNames.add(wr.name.toLowerCase());+ const wrType = String(wr.type || '').toLowerCase();+ if (IMAGE_WR_TYPES.has(wrType)) imageWebResourceNames.add(wr.name.toLowerCase());+ if (wrType === 'svg') svgWebResourceNames.add(wr.name.toLowerCase());+ else if (IMAGE_WR_TYPES.has(wrType)) rasterWebResourceNames.add(wr.name.toLowerCase());+ if (!WEB_RESOURCE_KINDS.has(String(wr.type || 'js').toLowerCase())) {+ errors.push(`webResource ${wr.name}: type must be one of ${[...WEB_RESOURCE_KINDS].join('|')}`);+ }+ if (wr.content === undefined && wr.contentBase64 === undefined && !wr.contentPath) {+ errors.push(`webResource ${wr.name}: needs content, contentBase64, or contentPath`);+ }+ }+ // AB#6686426: `isDefault` picks which Main form a table opens with. Explicit beats the fallback+ // (first Main form in spec order), and both are order-independent — which is the property the old+ // behaviour lacked, when every Main form promoted itself from inside a concurrent loop and the last+ // to finish won.+ const defaultByEntity = {};+ for (const f of spec.forms || []) {+ if (!f) continue;+ if (f.isDefault !== undefined && typeof f.isDefault !== 'boolean') {+ errors.push(`form '${f.name || f.entity}': isDefault must be a boolean (got ${describeValue(f.isDefault)})`);+ continue;+ }+ if (f.isDefault !== true) continue;+ if (f.formType !== undefined && f.formType !== 'Main') {+ errors.push(`form '${f.name || f.entity}': isDefault is only meaningful on a Main form (this one is '${f.formType}') — only Main forms are promoted`);+ continue;+ }+ const key = String(f.entity || '').toLowerCase();+ (defaultByEntity[key] = defaultByEntity[key] || []).push(f.name || '(unnamed)');+ }+ for (const [ent, names] of Object.entries(defaultByEntity)) {+ if (names.length > 1) {+ errors.push(`entity '${ent}': ${names.length} Main forms set isDefault (${names.join(', ')}) — exactly one form can be the table's default`);+ }+ }++ // #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+ // pass after all forms exist (AB#6686426). The rule is kept anyway on the surviving, independent+ // ground: deactivating every other Main form is a DESTRUCTIVE, entity-wide act, and a spec that+ // declares a sibling Main form alongside a flagged one is asking for that sibling to be built and+ // then immediately deactivated — almost certainly not what the author meant.+ const mainFormsByEntity = {};+ const flaggedByEntity = {};+ for (const f of spec.forms || []) {+ if (!f || (f.formType !== undefined && f.formType !== 'Main')) continue;+ const key = String(f.entity || '').toLowerCase();+ mainFormsByEntity[key] = (mainFormsByEntity[key] || 0) + 1;+ if (f.deactivateOtherMainForms === true) flaggedByEntity[key] = (flaggedByEntity[key] || 0) + 1;+ }+ for (const [ent, n] of Object.entries(flaggedByEntity)) {+ if (n > 1) {+ errors.push(`entity '${ent}': ${n} Main forms set deactivateOtherMainForms — at most one may (two would deactivate each other)`);+ } else if ((mainFormsByEntity[ent] || 0) > 1) {+ errors.push(`entity '${ent}': a Main form sets deactivateOtherMainForms but the entity declares ${mainFormsByEntity[ent]} Main forms — a flagged form must be the ONLY Main form for its entity (a concurrent build would nondeterministically deactivate the sibling and could leave the default form inactive)`);+ }+ }+ for (const f of spec.forms || []) {+ validateDescription(f.description, `form '${f.name || f.entity}'`, errors);+ if (!entityNames.has(f.entity)) {+ errors.push(`form references unknown entity '${f.entity}'`);+ }+ if (f.layout !== undefined && f.layout !== 'auto' && f.layout !== 'explicit') {+ errors.push(`form ${f.entity}: layout must be 'auto' or 'explicit'`);+ }+ const formType = f.formType === undefined ? 'Main' : f.formType;+ if (!['Main', 'QuickCreate', 'QuickView'].includes(formType)) {+ errors.push(`form ${f.entity}: formType must be one of Main|QuickCreate|QuickView`);+ }+ // Optional author-pinned target: a GUID that reconciles an EXACT existing form when a table has two+ // forms of the same (entity, type, name) that type-scoped resolution can't disambiguate. Validated+ // here because the build interpolates it UNQUOTED into an Edm.Guid OData filter (a non-GUID would both+ // break the query and be an injection seam).+ if (f.formId !== undefined && !FORM_GUID_RE.test(String(f.formId))) {+ errors.push(`form ${f.entity}: formId '${f.formId}' is not a valid GUID`);+ }+ if (formType !== 'Main' && Array.isArray(f.subgrids) && f.subgrids.length) {+ errors.push(`form ${f.entity}: ${formType} forms can't host sub-grids (Main forms only)`);+ }+ if (formType === 'QuickView' && Array.isArray(f.events) && f.events.length) {+ errors.push(`form ${f.entity}: QuickView forms are read-only and can't have event handlers`);+ }+ for (const ev of f.events || []) {+ if (!ev || !FORM_EVENTS.has(ev.event)) { errors.push(`form ${f.entity}: event must be one of ${[...FORM_EVENTS].join('|')}`); continue; }+ if (!ev.library) errors.push(`form ${f.entity}: ${ev.event} handler is missing a library (web-resource name)`);+ else if (!webResourceNames.has(String(ev.library).toLowerCase())) errors.push(`form ${f.entity}: ${ev.event} handler references undeclared web resource '${ev.library}'`);+ if (!ev.function) errors.push(`form ${f.entity}: ${ev.event} handler is missing a function name`);+ if (ev.event === 'onchange' && !ev.attribute) errors.push(`form ${f.entity}: onchange handler requires an attribute (column logical name)`);+ // These three are documented as optional with defaults, and are now actually honoured by the+ // build (they used to be hardcoded and the authored value discarded). Validate the types so a+ // string "false" — which is truthy in JS and would silently enable a handler the author meant+ // to disable — is rejected rather than coerced.+ for (const flagKey of ['enabled', 'passExecutionContext']) {+ if (ev[flagKey] !== undefined && typeof ev[flagKey] !== 'boolean') {+ errors.push(`form ${f.entity}: ${ev.event} handler ${flagKey} must be a boolean (got ${JSON.stringify(ev[flagKey])})`);+ }+ }+ if (ev.parameters !== undefined && typeof ev.parameters !== 'string') {+ errors.push(`form ${f.entity}: ${ev.event} handler parameters must be a string (a comma-separated argument list)`);+ }+ }+ for (const qv of f.quickViews || []) {+ if (!qv || !qv.lookup) { errors.push(`form ${f.entity}: a quickView is missing lookup (the lookup column logical name on this form)`); continue; }+ if (!qv.targetEntity || !entityByLower.has(String(qv.targetEntity).toLowerCase())) errors.push(`form ${f.entity}: quickView references unknown targetEntity '${qv.targetEntity}'`);+ if (!qv.form) { errors.push(`form ${f.entity}: quickView is missing form (the name of a QuickView form in forms[])`); continue; }+ // Resolve by (name, targetEntity) AND prefer the QuickView — a same-named Main on the target entity+ // must not shadow the intended QuickView (order-dependent otherwise). The build keys the+ // quick-view lookup by (entity, QuickView, name) too.+ const qvCandidates = (spec.forms || []).filter((x) => x.name === qv.form && String(x.entity).toLowerCase() === String(qv.targetEntity || '').toLowerCase());+ const qf = qvCandidates.find((x) => (x.formType || 'Main') === 'QuickView') || qvCandidates[0];+ if (!qf) errors.push(`form ${f.entity}: quickView references form '${qv.form}' (a QuickView on '${qv.targetEntity}') not found in forms[]`);+ else if ((qf.formType || 'Main') !== 'QuickView') errors.push(`form ${f.entity}: quickView form '${qv.form}' must have formType: "QuickView"`);+ }+ if (f.subgrids !== undefined) {+ if (!Array.isArray(f.subgrids)) {+ errors.push(`form ${f.entity}: subgrids must be an array`);+ } else {+ for (const sg of f.subgrids) {+ if (!sg || !sg.childEntity) {+ errors.push(`form ${f.entity}: a subgrid is missing childEntity`);+ continue;+ }+ if (badEntityRef(sg.childEntity, `form ${f.entity}: subgrid childEntity`)) continue;+ if (!entityByLower.has(String(sg.childEntity).toLowerCase())) {+ errors.push(`form ${f.entity}: subgrid references unknown childEntity '${sg.childEntity}'`);+ continue;+ }+ if (!relationshipFor(spec, f.entity, sg.childEntity) && !manyToManyFor(spec, f.entity, sg.childEntity)) {+ errors.push(+ `form ${f.entity}: no OneToMany or ManyToMany relationship between '${f.entity}' and subgrid childEntity '${sg.childEntity}'`+ );+ }+ }+ }+ }+ validateFormFieldOptions(f, entityByLower, errors, warnings);+ validateFormSecurityRoles(f, spec, errors);+ // `layout: 'explicit'` with no `tabs[]` is a spec that asks for one thing and builds another.+ // `compileFormIntent` takes the explicit path only when `tabs` is an ARRAY, so this combination+ // silently compiles an AUTO layout — while `prune` and the field-positioning rules read as+ // explicit-layout behaviour to the author. Rejected rather than warned: the two layouts differ in+ // whether a rebuild REMOVES deployed fields, so guessing wrong is destructive.+ if (f && f.layout === 'explicit' && !Array.isArray(f.tabs)) {+ errors.push(`form '${f.name || f.entity}': layout is 'explicit' but no tabs[] were authored — an explicit layout IS its tabs. Author tabs[], or drop layout: 'explicit' to use the auto layout.`);+ }+ }+ // Two QuickView forms sharing (entity, name) make a quick-view reference — which resolves a QuickView by+ // (targetEntity, name) — ambiguous (the build map keeps only one, order-dependently). Reject the+ // ambiguity at author time. Main/Card share the "Information" name harmlessly (they're not+ // quick-view targets), so this is scoped to QuickView.+ const qvIdentity = new Set();+ for (const f of spec.forms || []) {+ if (!f || (f.formType || 'Main') !== 'QuickView' || !f.name) continue;+ const key = `${String(f.entity).toLowerCase()}|${String(f.name).toLowerCase()}`;+ if (qvIdentity.has(key)) errors.push(`form ${f.entity}: duplicate QuickView form '${f.name}' — two QuickView forms on one table can't share a name (a quick-view reference resolves a QuickView by name)`);+ qvIdentity.add(key);+ }+ for (const ch of spec.charts || []) {+ validateDescription(ch && ch.description, `chart '${(ch && (ch.name || ch.entity)) || '(unnamed)'}'`, errors);+ if (!ch || badEntityRef(ch.entity, `chart '${(ch && (ch.name || ch.entity)) || '(unnamed)'}'`)) continue;+ if (!ch.entity || !entityByLower.has(String(ch.entity).toLowerCase())) {+ errors.push(`chart references unknown entity '${ch && ch.entity}'`);+ continue;+ }+ if (!ch.name) {+ errors.push(`chart on '${ch.entity}': name is required`);+ }+ if (!CHART_TYPES.includes(ch.chartType)) {+ errors.push(`chart '${ch.name || ch.entity}': chartType must be one of ${CHART_TYPES.join('|')}`);+ }+ const entity = entityByLower.get(String(ch.entity).toLowerCase());+ const choiceCol =+ entity &&+ (entity.columns || []).find(+ (c) => c.type === 'Choice' && c.schemaName.toLowerCase() === String(ch.groupBy || '').toLowerCase()+ );+ if (!choiceCol) {+ errors.push(`chart '${ch.name || ch.entity}': groupBy '${ch.groupBy}' is not a Choice column on '${ch.entity}'`);+ }+ }+ for (const v of spec.views || []) {+ const vlabel = `view '${(v && (v.name || v.entity)) || '(unnamed)'}'`;+ validateDescription(v && v.description, vlabel, errors);+ if (!entityNames.has(v.entity)) {+ errors.push(`view references unknown entity '${v.entity}'`);+ }+ // A column/attribute reference is STRINGIFIED downstream, never type-checked: `viewDef` maps+ // every one of them with `String(x).toLowerCase()`. So a non-string is not rejected — it is+ // silently turned into text, and an object becomes the literal `[object object]`, which lands+ // in the view's fetchxml. Dataverse refuses it with an opaque metadata error ("entity doesn't+ // contain attribute with Name = '[object object]'") mid-build, after the solution, tables and+ // columns already exist.+ //+ // The damage outlives that run. The savedquery row is created holding the bad fetchxml, so+ // every later READ of it also 400s and the next build dies at the same step; Dataverse reports+ // the row as system-defined and refuses to delete it, so recovery means tearing the table down.+ // https://github.com/microsoft/power-platform-skills/issues/525+ //+ // `{ "name": "..." }` is not an exotic mistake: it is exactly the shape `forms[]` uses for its+ // fields, so an author moving between the two surfaces writes it naturally.+ const attrRef = (value, where) => {+ if (typeof value !== 'string' || !value.trim()) {+ errors.push(`${vlabel}: ${where} must be a non-empty column name (a string), got ${describeValue(value)}`);+ }+ };+ if (v && v.columns !== undefined) {+ if (!Array.isArray(v.columns)) errors.push(`${vlabel}: columns must be an array of column names`);+ else v.columns.forEach((c, i) => attrRef(c, `columns[${i}]`));+ }+ if (v && v.sort !== undefined) {+ if (!Array.isArray(v.sort)) errors.push(`${vlabel}: sort must be an array`);+ else v.sort.forEach((s, i) => attrRef(s && s.attr, `sort[${i}].attr`));+ }+ if (v && v.filters !== undefined) {+ if (!Array.isArray(v.filters)) errors.push(`${vlabel}: filters must be an array`);+ else v.filters.forEach((f, i) => attrRef(f && f.attr, `filters[${i}].attr`));+ }+ }+ // Commands (modern command-bar buttons). A functional button needs a JS library + function;+ // the library must be a declared web resource (the on-click binds to it).+ const COMMAND_LOCATIONS = new Set(['MainTab', 'HomeTab', 'ContextualTab']);+ const COMMAND_TYPES = new Set(['Button', 'FlyoutAnchor', 'SplitButton']);+ // A leaf button (top-level or a flyout child) needs a JS library + function; the library must be+ // a declared web resource (the on-click binds to it).+ const checkCmdAction = (where, library, fn) => {+ if (!library) errors.push(`${where}: library (web-resource name) is required`);+ else if (!webResourceNames.has(String(library).toLowerCase())) errors.push(`${where}: library '${library}' is not a declared webResources[] name`);+ if (!fn) errors.push(`${where}: function (JS function name) is required`);+ };+ for (const c of spec.commands || []) {+ if (!c || !c.entity || !entityNames.has(c.entity)) { errors.push(`command references unknown entity '${c && c.entity}'`); continue; }+ // The SDK's command surface drops `description` (the artifact it returns carries only+ // commandBars/entityLogicalName/id), so one authored here never reaches Dataverse. Warn rather+ // than error — the spec is otherwise valid — but do not let it pass silently.+ if (c.description) {+ warnings.push(`command '${c.label || c.entity}': the SDK's command surface accepts no description, so this one will NOT be written to Dataverse`);+ }+ if (!c.label) errors.push(`command on ${c.entity}: label is required`);+ if (c.location && !COMMAND_LOCATIONS.has(c.location)) errors.push(`command '${c.label}' on ${c.entity}: location must be MainTab|HomeTab|ContextualTab`);+ const type = c.type || 'Button';+ if (!COMMAND_TYPES.has(type)) errors.push(`command '${c.label}' on ${c.entity}: type must be Button|FlyoutAnchor|SplitButton`);+ if (type === 'FlyoutAnchor' || type === 'SplitButton') {+ // A flyout/split container holds child buttons; it has no on-click of its own.+ if (!Array.isArray(c.children) || !c.children.length) errors.push(`command '${c.label}' on ${c.entity}: a ${type} needs children[] (its menu buttons)`);+ for (const ch of c.children || []) {+ if (!ch || !ch.label) { errors.push(`command '${c.label}' on ${c.entity}: a child button is missing a label`); continue; }+ checkCmdAction(`command '${c.label}' child '${ch.label}' on ${c.entity}`, ch.library, ch.function);+ }+ } else {+ checkCmdAction(`command '${c.label}' on ${c.entity}`, c.library, c.function);+ }+ }+ // Business rules. Every reference is checked against the spec's own columns, because a rule that+ // names a column the app does not create is authored against nothing — and the platform accepts it+ // silently (the rule just never fires), so nothing downstream would catch it.+ for (const r of spec.businessRules || []) {+ const label = `business rule '${(r && r.name) || '(unnamed)'}'`;+ if (!r || typeof r !== 'object' || Array.isArray(r)) { errors.push('businessRules[] entries must be objects'); continue; }+ validateDescription(r.description, label, errors);+ if (!r.name) errors.push(`${label}: name is required`);+ if (!r.entity || !entityNames.has(r.entity)) { errors.push(`${label}: references unknown entity '${r.entity}'`); continue; }+ if (r.scope !== undefined && !BUSINESS_RULE_SCOPES.includes(r.scope)) {+ errors.push(`${label}: scope must be ${BUSINESS_RULE_SCOPES.join('|')} (a form-scoped rule needs a form id that does not exist until the forms phase runs)`);+ }+ if (r.status !== undefined && !['Active', 'Draft'].includes(r.status)) {+ errors.push(`${label}: status must be Active|Draft`);+ }++ // Columns the rule may reference: the entity's own declared columns plus its primary name.+ const cols = declaredColumnLogicals(spec, r.entity);+ const checkField = (field, what) => {+ if (!field) { errors.push(`${label}: ${what} needs a field`); return; }+ if (cols.size && !cols.has(String(field).toLowerCase())) {+ errors.push(`${label}: ${what} references '${field}', which is not a column on ${r.entity}`);+ }+ };++ if (!Array.isArray(r.conditions) || !r.conditions.length) {+ errors.push(`${label}: conditions[] is required (a rule with no condition would apply unconditionally, which the SDK serializes as an empty rule that silently never fires)`);+ }+ for (const c of r.conditions || []) {+ if (!c || typeof c !== 'object') { errors.push(`${label}: each condition must be an object`); continue; }+ checkField(c.field, 'condition');+ if (!BUSINESS_RULE_OPERATORS.includes(c.operator)) {+ // Name the platform failure rather than pretending the operator is unrecognised: an author+ // who reaches for a blocked operator has written something reasonable that we cannot deploy.+ if (BUSINESS_RULE_BLOCKED_OPERATORS.has(c.operator)) {+ errors.push(`${label}: operator '${c.operator}' is not usable — see https://github.com/microsoft/power-platform-skills/issues/481`);+ } else {+ // The near-misses matter more than the nonsense here. `GreaterThan` is a natural thing to+ // write and is NOT in the SDK's table, and the serializer resolves an unknown operator to+ // Equals — so without this gate that spec would deploy an equality test. Name the closest+ // legal spelling so the fix is obvious.+ const near = BUSINESS_RULE_OPERATORS.find((o) => o.toLowerCase() === `is${String(c.operator).toLowerCase()}`+ || o.toLowerCase().replace(/^is/, '') === String(c.operator).toLowerCase()+ || o.toLowerCase() === String(c.operator).toLowerCase());+ errors.push(`${label}: condition operator must be one of ${BUSINESS_RULE_OPERATORS.join('|')} (got '${c.operator}')${near ? ` — did you mean '${near}'?` : ''}`);+ }+ continue;+ }+ const valueless = BUSINESS_RULE_VALUELESS_OPERATORS.has(c.operator);+ if (valueless && c.value !== undefined) {+ errors.push(`${label}: '${c.operator}' tests presence, so it must not carry a value`);+ }+ if (!valueless && (c.value === undefined || c.value === null || c.value === '')) {+ errors.push(`${label}: '${c.operator}' needs a value`);+ }+ if (c.dataType !== undefined && !BUSINESS_RULE_DATA_TYPES.includes(c.dataType)) {+ // Name the offending value: this is a curated closed set with no bundle counterpart, and the+ // most likely mistake is a plausible-but-absent type (DateTime is the classic one), so+ // echoing what was written is what makes the message actionable.+ errors.push(`${label}: condition dataType '${c.dataType}' is not supported — must be one of ${BUSINESS_RULE_DATA_TYPES.join('|')}`);+ }+ }++ if (!Array.isArray(r.actions) || !r.actions.length) {+ errors.push(`${label}: actions[] is required (a rule that does nothing is not worth deploying)`);+ }+ for (const a of r.actions || []) {+ if (!a || typeof a !== 'object') { errors.push(`${label}: each action must be an object`); continue; }+ if (!BUSINESS_RULE_ACTION_TYPES.includes(a.type)) {+ errors.push(`${label}: action type must be one of ${BUSINESS_RULE_ACTION_TYPES.join('|')} (got '${a.type}')`);+ continue;+ }+ checkField(a.field, `action '${a.type}'`);+ const payload = BUSINESS_RULE_ACTIONS[a.type];+ if (a[payload] === undefined) {+ errors.push(`${label}: action '${a.type}' needs '${payload}'`);+ } else if (BUSINESS_RULE_BOOLEAN_ACTIONS.has(a.type) && typeof a[payload] !== 'boolean') {+ // A string "false" is truthy, so coercing here would invert the author's intent silently.+ errors.push(`${label}: action '${a.type}'.${payload} must be a boolean`);+ }+ if (a.type === 'SetFieldValue' && a.dataType !== undefined && !BUSINESS_RULE_DATA_TYPES.includes(a.dataType)) {+ errors.push(`${label}: action dataType must be one of ${BUSINESS_RULE_DATA_TYPES.join('|')}`);+ }+ }+ }+ // Business process flows. Same discipline as business rules and for the same reason: the platform+ // accepts a BPF whose step names a column that does not exist, materializes its stages, and then+ // simply renders a step bound to nothing — no error at deploy time, and nothing downstream to+ // catch it. So every field is checked against the flow's own entity here.+ const bpfUniques = new Map();+ for (const p of spec.businessProcessFlows || []) {+ const label = `business process flow '${(p && p.name) || '(unnamed)'}'`;+ if (!p || typeof p !== 'object' || Array.isArray(p)) { errors.push('businessProcessFlows[] entries must be objects'); continue; }+ if (!p.name) errors.push(`${label}: name is required`);+ else if (typeof p.name !== 'string' || !p.name.trim()) {+ // The SDK derives the server unique name by lower-casing this value, so a non-string reaches+ // `.toLowerCase()` and dies with a TypeError inside the bundle rather than a spec error here.+ errors.push(`${label}: name must be a non-empty string`);+ } else {+ // Keyed on the DERIVED unique name, not on (entity, name). The build identifies a flow by+ // (entity, name) for reuse, but the SERVER identity the SDK derives ignores the entity and+ // strips case/punctuation — so an (entity, name) key would let two flows through that cannot+ // both exist. See bpfUniqueName.+ const unique = bpfUniqueName(p.name);+ const clash = bpfUniques.get(unique);+ if (clash !== undefined) {+ errors.push(`${label}: collides with '${clash}' — both derive the Dataverse unique name '${unique}' (the derivation lower-cases the name, strips punctuation, and ignores the table). Activation creates a backing table with that name, so the second flow cannot deploy. Rename one, e.g. "${p.name} (Cases)".`);+ } else {+ bpfUniques.set(unique, p.name);+ }+ // The derived name is a TABLE name, so it collides with tables too — not only with other+ // flows. Activation creates an org-owned backing table called `unique`, and a table with that+ // logical name cannot be created twice.+ //+ // This axis is easy to hit precisely because the derivation ignores the solution's publisher+ // prefix and always emits `new_`: on a spec using the default `new` prefix, a flow named after+ // its own table ("Ticket" on `new_ticket`) derives exactly that table's logical name. Without+ // this check it validates clean and then fails in the business-process-flows phase — after the+ // solution, tables, columns, views, forms and the app already exist — with a platform error+ // naming a table the author never meant to create.+ //+ // `existing: true` tables are included deliberately: the build does not create them, but they+ // are still in the org, so the backing table clashes just the same.+ const tableClash = entityByLower.get(unique);+ if (tableClash) {+ errors.push(`${label}: derives the Dataverse unique name '${unique}', which is already the logical name of the table '${tableClash.schemaName}' in this spec. Activating a flow creates a backing table with that name (the derivation lower-cases the name, strips punctuation, and always uses the 'new_' prefix regardless of your publisher prefix), so the flow cannot deploy. Rename the flow, e.g. "${p.name} Process".`);+ }+ }+ if (!p.entity || !entityNames.has(p.entity)) { errors.push(`${label}: references unknown entity '${p.entity}'`); continue; }+ if (p.status !== undefined && !BPF_STATUSES.includes(p.status)) {+ errors.push(`${label}: status must be ${BPF_STATUSES.join('|')}`);+ }+ if (p.order !== undefined && (!Number.isInteger(p.order) || p.order < 1)) {+ errors.push(`${label}: order must be a positive integer (it becomes the workflow's processorder)`);+ }+ // Allow-list the flow's own keys for the same reason as the stage/step ones below: naming only the+ // three knobs we knew about left others (the SDK also models `globalActions`) neither mapped nor+ // rejected — silently dropped, which is the failure this guard exists to prevent.+ const BPF_FLOW_KEYS = new Set(['name', 'entity', 'description', 'status', 'order', 'stages', 'securityRoles']);+ for (const k of Object.keys(p)) {+ if (!BPF_FLOW_KEYS.has(k)) {+ errors.push(`${label}: unsupported key '${k}' (allowed: ${[...BPF_FLOW_KEYS].join(', ')}). Branching and process actions are modelled by the SDK but cannot be verified by this build, so they are rejected rather than silently dropped — configure them in Maker after the flow deploys.`);+ }+ }+ validateBpfSecurityRoles(p, spec, label, errors);+ const cols = declaredColumnLogicals(spec, p.entity);+ validateDescription(p.description, label, errors);+ if (!Array.isArray(p.stages) || !p.stages.length) {+ errors.push(`${label}: stages[] is required (a flow with no stage is not a process)`);+ continue;+ }+ // The SDK enforces a hard ceiling of 30 stages per flow and 30 steps per stage. Without these+ // the spec validates, the build runs, and the SDK throws in a late phase with the earlier+ // artifacts already created — the same half-built-app failure the step-field rule above exists+ // to prevent.+ if (p.stages.length > BPF_MAX_STAGES) {+ errors.push(`${label}: ${p.stages.length} stages — the platform allows at most ${BPF_MAX_STAGES}`);+ }+ const stageNames = new Set();+ for (const st of p.stages) {+ if (!st || typeof st !== 'object' || Array.isArray(st)) { errors.push(`${label}: each stage must be an object`); continue; }+ if (!st.name) { errors.push(`${label}: every stage needs a name`); continue; }+ if (stageNames.has(st.name)) errors.push(`${label}: duplicate stage name '${st.name}'`);+ stageNames.add(st.name);+ // Reject an unmapped stage key rather than dropping it. `branch`, `actions`, `nextStageId`,+ // `category` and `relationshipName` are STAGE-level in the SDK's model — which is exactly where+ // an author would write them — and bpfDef maps only name/entity/steps, so without this they+ // would vanish silently.+ for (const k of Object.keys(st)) {+ if (!BPF_STAGE_KEYS.has(k)) {+ errors.push(`${label}: stage '${st.name}' has unsupported key '${k}' (allowed: ${[...BPF_STAGE_KEYS].join(', ')}). Branching, stage actions and cross-entity flow are modelled by the SDK but cannot be verified by this build, so they are rejected rather than silently dropped — configure them in Maker.`);+ }+ }+ // v1 is single-entity: a stage on another table is a cross-entity flow, which changes what the+ // process means (it spans records) and is rejected rather than silently retargeted.+ if (st.entity !== undefined && st.entity !== p.entity) {+ errors.push(`${label}: stage '${st.name}' targets '${st.entity}' — cross-entity flows are not supported; every stage must be on ${p.entity}`);+ }+ if (st.steps !== undefined && !Array.isArray(st.steps)) {+ errors.push(`${label}: stage '${st.name}': steps must be an array`);+ continue;+ }+ // A stage MUST carry at least one step. The SDK's createDefault substitutes a placeholder step+ // literally named "New Step" when a stage has none, so an empty stage deploys a step the author+ // never wrote (and the SDK's own `stage-needs-step` rule never fires, because the placeholder is+ // injected before it looks).+ if (!(st.steps || []).length) {+ errors.push(`${label}: stage '${st.name}' has no steps — a stage with none deploys a placeholder step named "New Step" that you did not author`);+ }+ if ((st.steps || []).length > BPF_MAX_STEPS) {+ errors.push(`${label}: stage '${st.name}' has ${st.steps.length} steps — the platform allows at most ${BPF_MAX_STEPS} per stage`);+ }+ const stepNames = new Set();+ for (const step of st.steps || []) {+ if (!step || typeof step !== 'object' || Array.isArray(step)) { errors.push(`${label}: stage '${st.name}': each step must be an object`); continue; }+ if (!step.name) { errors.push(`${label}: stage '${st.name}': every step needs a name`); continue; }+ if (stepNames.has(step.name)) errors.push(`${label}: stage '${st.name}': duplicate step name '${step.name}'`);+ stepNames.add(step.name);+ // Same reason as the stage allow-list, and the likeliest instance of it: a step written with+ // `fieldLogicalName` (the name used elsewhere in the SDK's own artifact shapes) is dropped by+ // the step normalizer and deploys bound to nothing.+ for (const k of Object.keys(step)) {+ if (!BPF_STEP_KEYS.has(k)) {+ errors.push(`${label}: stage '${st.name}' step '${step.name}' has unsupported key '${k}' (allowed: ${[...BPF_STEP_KEYS].join(', ')}${k === 'fieldLogicalName' ? " — the column key is 'field'" : ''})`);+ }+ }+ // `field` is REQUIRED on every step. This was originally modelled as optional — a step with+ // no field was documented as a "checklist item" — but the platform rejects it outright:+ //+ // HTTP 400 from .../api/data/v9.0/workflows(<id>)+ // Attribute - datafieldname of ControlStep cannot be null or empty+ //+ // MEASURED live, and isolated by A/B: the identical flow with every step bound to a column+ // deploys and activates cleanly. Because the push happens in a late phase, accepting the+ // shape here meant the build HALTED after the solution, table, columns, views and forms were+ // already created — the author got a half-built app and a platform error naming an internal+ // XAML element they never wrote. So it is rejected up front, where it is actionable.+ //+ // `null` and a blank/whitespace string are the SAME defect as `undefined` and must give the+ // same message. Treating only `undefined` as missing let them fall through to the column+ // check, which reported `references ''` — or, worse, `references 'null'` from stringifying+ // the value — instead of saying what was actually wrong.+ const fieldGiven = step.field !== undefined && step.field !== null && String(step.field).trim() !== '';+ if (!fieldGiven) {+ errors.push(`${label}: stage '${st.name}' step '${step.name}' binds no field — every step must set 'field' (the platform rejects a step with no column: "datafieldname of ControlStep cannot be null or empty"). For a manual check-off, bind a Boolean column such as a "Confirmed" flag.`);+ } else if (cols.size && !cols.has(String(step.field).toLowerCase())) {+ errors.push(`${label}: stage '${st.name}' step '${step.name}' references '${step.field}', which is not a column on ${p.entity}`);+ }+ if (step.required !== undefined && typeof step.required !== 'boolean') {+ errors.push(`${label}: stage '${st.name}' step '${step.name}': required must be a boolean`);+ }+ }+ }+ }+ // Dashboards: chart/list tiles reference a declared chart/view; iframe needs a url; webresource a+ // declared web resource.+ const DASH_TILE_TYPES = new Set(['chart', 'list', 'iframe', 'webresource']);+ const viewNamesSet = new Set((spec.views || []).map((v) => v.name));+ const chartNamesSet = new Set((spec.charts || []).map((c) => c.name));+ for (const d of spec.dashboards || []) {+ if (!d || !d.name) { errors.push('a dashboard is missing a name'); continue; }+ validateDescription(d.description, `dashboard '${d.name}'`, errors);+ if (!Array.isArray(d.tiles) || !d.tiles.length) { errors.push(`dashboard '${d.name}': needs tiles[]`); continue; }+ for (const t of d.tiles) {+ if (!t || !DASH_TILE_TYPES.has(t.type)) { errors.push(`dashboard '${d.name}': tile type must be chart|list|iframe|webresource`); continue; }+ // ID-passthrough tiles (from a round-tripped/downloaded app) carry the deployed view/chart ids+ // + entity directly instead of names — they bind to existing artifacts, so skip the name checks.+ const byId = t.viewId || t.visualizationId;+ if (t.type === 'chart') {+ if (byId) {+ if (!t.viewId) errors.push(`dashboard '${d.name}': chart tile with visualizationId also needs viewId`);+ if (!t.entity) errors.push(`dashboard '${d.name}': id-based chart tile needs entity`);+ else badEntityRef(t.entity, `dashboard '${d.name}': chart tile`);+ } else {+ if (!t.chart || !chartNamesSet.has(t.chart)) errors.push(`dashboard '${d.name}': chart tile references unknown chart '${t.chart}'`);+ if (!t.view || !viewNamesSet.has(t.view)) errors.push(`dashboard '${d.name}': chart tile needs a declared view for its data — '${t.view}' not found`);+ }+ } else if (t.type === 'list') {+ if (byId) {+ if (!t.entity) errors.push(`dashboard '${d.name}': id-based list tile needs entity`);+ else badEntityRef(t.entity, `dashboard '${d.name}': list tile`);+ } else if (!t.view || !viewNamesSet.has(t.view)) {+ errors.push(`dashboard '${d.name}': list tile references unknown view '${t.view}'`);+ }+ } else if (t.type === 'iframe') {+ if (!t.url) errors.push(`dashboard '${d.name}': iframe tile needs a url`);+ else if (!isSafeHttpUrl(t.url)) errors.push(`dashboard '${d.name}': iframe tile url must be an http(s) URL (got '${t.url}')`);+ if (!t.name) errors.push(`dashboard '${d.name}': iframe tile needs a name`);+ } else if (t.type === 'webresource') {+ if (!t.webResource || !webResourceNames.has(String(t.webResource).toLowerCase())) errors.push(`dashboard '${d.name}': webresource tile references undeclared web resource '${t.webResource}'`);+ if (!t.name) errors.push(`dashboard '${d.name}': webresource tile needs a name`);+ }+ }+ }+ const dashNamesSet = new Set((spec.dashboards || []).map((d) => d && d.name).filter(Boolean));+ // Generative pages. Each needs a name. Implementation state is a discriminated `source`+ // (`intent` | `tsx`+codeFile); a legacy top-level `codeFile` is accepted as an implemented tsx.+ // The `deploy` profile requires every page implemented; `design`/`plan` allow intent (the page's+ // .tsx is produced by generate-pages after approval); `structural` ignores implementation.+ // isV2/pageKeysSet are declared here — before the page loop — so the appShell subarea loop that+ // follows can also reference them (both loops live in the same function scope). pageNamesSet is+ // kept for legacy (schemaVersion < 2) appShell page refs; pageRefSet selects the right set.+ const isV2 = (spec.schemaVersion || 0) >= 2;+ const pageKeysSet = new Set();+ const pageNamesSet = new Set();+ // Stable-key grammar (schemaVersion 2): lowercase slug — alphanumerics + internal single hyphens,+ // no leading/trailing hyphen, no underscores/spaces/uppercase. migrateAppSpec mints keys via+ // slugify (:686) which always conforms; a hand-authored v2 key must too, since the key is the+ // cross-reference identity (navigatesTo.targetKey, PAGEREF_<key>, appShell page subareas).+ const PAGE_KEY_GRAMMAR = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;+ // GUID pattern for pages[].pageId — a 36-char hyphenated hex UUID as minted by Dataverse / PAC CLI.+ // A spec page carrying this field is an EDIT-SNAPSHOT (env-specific, downloaded from a live app);+ // a portable fresh-authored spec omits it. When present it must be exactly this shape so+ // reconcilePageIds can use it as the highest identity authority without silently accepting garbage+ // (e.g. a cross-env GUID that happens to match an unrelated page). Addenda Task 4 / C3.+ const PAGE_ID_GUID = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;+ const pageCodeFilesNorm = new Set(); // implemented-page normalized codeFile uniqueness (Critical 4)+ // A codeFile must resolve INSIDE the working directory. Use path.normalize to canonicalize before+ // checking — this catches aliases like 'pages/./x.tsx' and 'pages/../pages/x.tsx' that resolve to+ // the same file but evade a naive string-split check (addendum Crit 4). path.isAbsolute is+ // platform-specific (on POSIX it does NOT flag a Windows drive-letter path like 'C:/x'), so we ALSO+ // match a drive-letter prefix explicitly — a spec authored on Windows must be rejected the same way+ // on a Linux CI runner. After normalization, a path starting with '..' has escaped the workspace+ // root. sdk-build resolves codeFile with path.resolve(appDir, codeFile) at :1037-1041, so an+ // unconfined path reaches the filesystem outside the app folder — reject it here, before any write. Design §7.2.+ const codeFileConfined = (codeFile) => {+ const cf = String(codeFile);+ // Drive-letter guard (/^[a-zA-Z]:[/\\]/) catches 'C:\x'/'C:/x' on POSIX where path.isAbsolute misses it.+ if (path.isAbsolute(cf) || /^[a-zA-Z]:[/\\]/.test(cf)) return false;+ const normalized = path.normalize(cf);+ // normalized === '..' means the codeFile IS the parent directory.+ // normalized.startsWith('..' + path.sep) means it is a path beneath the parent directory.+ return normalized !== '..' && !normalized.startsWith('..' + path.sep);+ };+ for (const p of spec.pages || []) {+ if (!p || !p.name) { errors.push('a page is missing a name'); continue; }+ pageNamesSet.add(p.name);+ // NOTE: case-insensitive page-name uniqueness is enforced in a dedicated pass AFTER this loop+ // (see "page-name uniqueness" below) so it can distinguish a NEW page from a PRE-EXISTING one.+ // A page MAY carry its own deployed `pageId` (edit-snapshot marker). A portable fresh-authored spec+ // omits it — absence is never an error. When present it MUST be a valid 36-char GUID: the+ // reconcilePageIds authority logic (addenda Task 4 / C3) consumes it as the HIGHEST identity source,+ // so silently accepting a malformed / empty value would cause reconcile to bind the wrong page.+ if (p.pageId !== undefined && !PAGE_ID_GUID.test(String(p.pageId))) {+ errors.push(`page '${p.key || p.name}': pageId must be a 36-char GUID`);+ }+ const src = normalizePageSource(p);+ // Track whether a structural source error was emitted so the profile check below doesn't+ // double-report (e.g. source:{kind:'tsx'} with no codeFile should get ONE error, not two).+ let structuralSourceOk = true;+ if (src && src.kind !== 'intent' && src.kind !== 'tsx') {+ errors.push(`page '${p.key || p.name}': source.kind must be 'intent' or 'tsx'`);+ structuralSourceOk = false;+ } else if (src && src.kind === 'tsx' && (typeof src.codeFile !== 'string' || !src.codeFile)) {+ errors.push(`page '${p.key || p.name}': source.kind 'tsx' needs a codeFile (path to the .tsx)`);+ structuralSourceOk = false;+ }+ if (structuralSourceOk) {+ if (profile === 'deploy') {+ if (!(src && src.kind === 'tsx' && typeof src.codeFile === 'string' && src.codeFile)) {+ errors.push(`page '${p.key || p.name}': must be implemented (source.kind 'tsx' with a codeFile) for a deploy build — run generate-pages`);+ }+ } else if (profile !== 'structural' && src === null) {+ // design/plan still require SOME declared source (intent or tsx) — a page with neither is a+ // spec error, not a valid design.+ errors.push(`page '${p.key || p.name}': needs a source ({ kind: 'intent' } or { kind: 'tsx', codeFile })`);+ }+ }+ // codeFile confinement + path-uniqueness (Critical 4). Only checked for implemented tsx pages+ // (intent pages have no codeFile; the codeFile presence was already validated above). Normalize+ // the path before checking so that 'pages/./x.tsx' and 'pages/../pages/x.tsx' are detected as+ // duplicates of 'pages/x.tsx' (addendum Crit 4). Replace backslashes with forward slashes before+ // lowercasing for cross-platform-safe comparison in the set.+ if (src && src.kind === 'tsx' && typeof src.codeFile === 'string' && src.codeFile) {+ if (!codeFileConfined(src.codeFile)) {+ errors.push(`page '${p.key || p.name}': codeFile '${src.codeFile}' must be a workspace-confined relative path (no '..' escape, no absolute path)`);+ }+ const cfNorm = path.normalize(src.codeFile).replace(/\\/g, '/').toLowerCase();+ if (pageCodeFilesNorm.has(cfNorm)) errors.push(`page '${p.key || p.name}': duplicate codeFile '${src.codeFile}' (another page already uses this path)`);+ else pageCodeFilesNorm.add(cfNorm);+ }+ // schemaVersion 2 adds a required, unique stable key per page so pages can be referenced by an+ // identity that survives renames. The key is also what navigatesTo.targetKey and appShell page+ // subareas use (key-based refs replace name-based refs for v2 specs).+ if (isV2) {+ if (!p.key || typeof p.key !== 'string') errors.push(`page '${p.name}': needs a stable key (schemaVersion 2)`);+ else if (!PAGE_KEY_GRAMMAR.test(p.key)) errors.push(`page '${p.name}': key '${p.key}' has an invalid key grammar (lowercase slug: ^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$)`);+ else if (pageKeysSet.has(p.key)) errors.push(`duplicate page key '${p.key}'`);+ else pageKeysSet.add(p.key);+ }+ }+ // Page-name uniqueness (case-insensitive) — SCOPED to what the current run authors. Two pages that+ // share a name (e.g. 'Overview' vs 'overview') are confusing in the app navigation. BUT a downloaded+ // edit-snapshot can legitimately carry a PRE-EXISTING duplicate the run did NOT create (two pages+ // authored by different people/tools), and blocking every build — even an unrelated form edit that+ // never touches pages — on a dupe the run is not changing is wrong (the pages phase matches by id/key,+ // never by name: genpage-cli.js enumerateEnv is id-keyed, and download's assignPageKeys de-dups keys+ // with a -N suffix, so distinct-id same-name pages build fine). Signal: a page carrying a deployed+ // `pageId` is PRE-EXISTING (an edit-snapshot marker); a page WITHOUT one is NEW (authored this run).+ // - collision involving a NEW page → ERROR (prevent authoring/adding a duplicate)+ // - collision purely among PRE-EXISTING pages → WARNING (tolerate; rename one in Maker to fix nav)+ const nameGroups = new Map(); // nameLower -> { display, count, anyNew }+ for (const p of spec.pages || []) {+ if (!p || !p.name) continue;+ const nl = String(p.name).toLowerCase();+ const g = nameGroups.get(nl) || { display: p.name, count: 0, anyNew: false };+ g.count += 1;+ if (!p.pageId) g.anyNew = true; // no deployed id ⇒ this page is being created/authored by this run+ nameGroups.set(nl, g);+ }+ for (const g of nameGroups.values()) {+ if (g.count <= 1) continue;+ if (g.anyNew) errors.push(`duplicate page name '${g.display}' (page names must be unique, case-insensitive)`);+ else warnings.push(`pre-existing duplicate page name '${g.display}' — ${g.count} deployed pages share this name (case-insensitive); tolerated because this build does not create them, but the app navigation is ambiguous. Rename one in Maker (or a fresh spec) to disambiguate.`);+ }+ // Navigation graph (v2 only — these fields don't exist in hand-authored legacy specs):+ // every navigatesTo.targetKey must resolve to a known page key. pageInput shape is validated+ // here too (object, not array/null).+ if (isV2) {+ for (const p of spec.pages || []) {+ for (const nav of p.navigatesTo || []) {+ if (!nav || typeof nav.targetKey !== 'string') { errors.push(`page '${p.key || p.name}': navigatesTo entry needs a targetKey`); continue; }+ if (!pageKeysSet.has(nav.targetKey)) errors.push(`page '${p.key || p.name}': navigatesTo target '${nav.targetKey}' is not a known page key`);+ if (nav.data !== undefined && (typeof nav.data !== 'object' || nav.data === null || Array.isArray(nav.data))) errors.push(`page '${p.key || p.name}': navigatesTo.data must be an object`);+ }+ if (p.pageInput !== undefined) {+ if (typeof p.pageInput !== 'object' || p.pageInput === null || Array.isArray(p.pageInput)) errors.push(`page '${p.key || p.name}': pageInput must be an object`);+ }+ }+ // INPUT CONTRACT. These two rules together resolve a policy conflict that was previously left+ // implicit, and that a page author had no way to satisfy:+ //+ // - Every page MUST be sitemap-placed (the MEMBERSHIP invariant above): the sitemap is the+ // download's only membership oracle, so a page reached only by navigation is invisible to+ // download and gets re-created as a duplicate on the next build.+ // - But a DETAIL page declares `pageInput` (e.g. `{ data: { orderId: 'string' } }`) because it+ // is opened from a list with a row id.+ //+ // Being sitemap-placed means the page is ALSO reachable straight from the app's navigation, with+ // NO input at all. That is a real, user-reachable state — it is what a user gets by clicking the+ // nav entry — and previously nothing made the author account for it, so the generated page would+ // render against `undefined` context. Rather than weaken the membership invariant (which would+ // reintroduce duplicate pages on every rebuild), require the author to say what direct entry+ // does. `directEntry` is that answer, and page-plan feeds it to the generator.+ for (const p of spec.pages || []) {+ const key = p.key || p.name;+ const inputKeys = Object.keys((p.pageInput && p.pageInput.data) || {});+ if (!inputKeys.length) continue;++ if (p.directEntry === undefined) {+ errors.push(`page '${key}' declares pageInput (${inputKeys.join(', ')}) but no directEntry — every page is sitemap-placed, so a user can open it from the app navigation with no input. Declare directEntry: { "behavior": "selector" | "emptyState", "note": "…" } to say what that shows.`);+ } else if (typeof p.directEntry !== 'object' || p.directEntry === null || Array.isArray(p.directEntry)) {+ errors.push(`page '${key}': directEntry must be an object`);+ } else if (!DIRECT_ENTRY_BEHAVIORS.includes(p.directEntry.behavior)) {+ errors.push(`page '${key}': directEntry.behavior must be one of ${DIRECT_ENTRY_BEHAVIORS.join('|')}`);+ }++ // Trace each declared input back to a navigation edge that actually produces it. An input no+ // caller supplies is either a typo or a page that can ONLY ever be entered directly — both are+ // worth failing on, because the generated page would read a key nothing ever sets.+ //+ // EXCEPT when the spec was RECONSTRUCTED from a deployed app (`opts.reconstructed`, set by+ // download). This is an authoring rule: it gates what you are about to create. A reconstruction+ // describes an app that ALREADY EXISTS, and download validates before it writes — so treating+ // it as fatal there produces no spec file at all and strands the author with nothing to edit,+ // which is the #430 failure this release exists to fix. A page whose manifest predates the rule+ // (input supplied externally, or from its own .tsx) hits exactly that. Reported as a warning+ // instead: the author gets the file, the finding, and the chance to fix it.+ const produced = new Set();+ for (const other of spec.pages || []) {+ for (const nav of other.navigatesTo || []) {+ if (nav && nav.targetKey === key) for (const k of Object.keys((nav.data) || {})) produced.add(k);+ }+ }+ const orphaned = inputKeys.filter((k) => !produced.has(k));+ if (orphaned.length) {+ const msg = `page '${key}': pageInput declares ${orphaned.map((k) => `'${k}'`).join(', ')} but no page navigates to it with that data — add it to the producing page's navigatesTo[].data, or drop it from pageInput.`;+ if (opts.reconstructed) warnings.push(msg);+ else errors.push(msg);+ }+ }+ }+ // Icons are chrome, not a target. An `icon` that is a **platform reference** (a path or+ // `$webresource:` — see isPlatformIconRef) is a live/OOB value a downloaded app carries and is valid+ // AS-IS (rejecting it broke the download→build round-trip on real apps). Only a BARE NAME is treated+ // as a local web-resource reference and must be a declared IMAGE web resource. `vectorIcon` handling+ // is per-subarea below (entity vs non-entity differ).+ const checkIcon = (icon, label) => {+ if (!icon) return;+ if (isPlatformIconRef(icon)) return; // live/OOB platform reference — pass through+ const ic = String(icon).toLowerCase();+ if (!webResourceNames.has(ic)) errors.push(`${label}: icon '${icon}' is not a declared web resource`);+ else if (!imageWebResourceNames.has(ic)) errors.push(`${label}: icon '${icon}' must be an image web resource (png/jpg/gif/svg/ico)`);+ };+ // Portability advisory: a platform icon/vectorIcon that references THIS app's OWN custom web resource+ // (by the solution publisher prefix) but does NOT declare it in webResources[] will render only on an+ // env that already has that web resource — on a fresh/other env it dangles (a broken icon). A DOWNLOADED+ // spec re-declares its OWN-prefix UNMANAGED image icon web resources automatically (download-model-app+ // collectSitemap + iconWebResources), so this normally fires only for a hand-authored spec (a rare+ // exception: an own-prefix MANAGED icon WR, which download can't recreate and so leaves undeclared). An+ // OOB/system reference (a different prefix, or a non-WebResources `/_imgs/...` path) is assumed present on+ // every env → not flagged.+ const pubPrefix = (spec.solution && spec.solution.publisherPrefix) ? String(spec.solution.publisherPrefix).toLowerCase() : '';+ const checkPortableIconRef = (val, label) => {+ if (!val || !isPlatformIconRef(val)) return;+ const wrName = webResourceNameFromRef(val);+ if (!wrName || !pubPrefix) return;+ const lc = wrName.toLowerCase();+ if (lc.startsWith(pubPrefix + '_') && !webResourceNames.has(lc)) {+ 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.`);+ }+ };+ for (const a of (spec.appShell && spec.appShell.areas) || []) {+ checkIcon(a.icon, `sitemap area "${a.label || ''}"`);+ checkPortableIconRef(a.icon, `sitemap area "${a.label || ''}"`);+ checkPortableIconRef(a.vectorIcon, `sitemap area "${a.label || ''}"`);+ validateIconDescription(a.iconDescription, `sitemap area "${a.label || ''}"`, errors);+ for (const g of a.groups || []) {+ validateIconDescription(g && g.iconDescription, `sitemap group "${(g && g.label) || ''}"`, errors);+ for (const sa of g.subAreas || []) {+ const targets = ['entity', 'dashboard', 'url', 'page'].filter((k) => sa[k]);+ if (targets.length === 0) errors.push(`sitemap subArea "${sa.title || ''}" needs an entity, dashboard, url, or page`);+ else if (targets.length > 1) errors.push(`sitemap subArea "${sa.title || ''}" sets multiple targets (${targets.join(', ')}) — pick one`);+ // Case-insensitive: Dataverse logical names are lower-case while `schemaName` is cased+ // (`Account`), and a sitemap subarea's `entity` comes from the deployed sitemap XML as a+ // LOGICAL name. A downloaded spec therefore legitimately pairs `schemaName: "Account"` with+ // `entity: "account"`. Matches the chart check above, which already uses `entityByLower`.+ if (sa.entity && !badEntityRef(sa.entity, 'sitemap subArea') && !entityByLower.has(String(sa.entity).toLowerCase())) errors.push(`sitemap subArea references unknown entity '${sa.entity}'`);+ if (sa.dashboard && !dashNamesSet.has(sa.dashboard)) errors.push(`sitemap subArea references unknown dashboard '${sa.dashboard}' (declare it in dashboards[])`);+ // A sitemap URL subarea is EITHER a real link OR a web-resource reference —+ // `$webresource:<name>` (what 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, exactly like a platform icon ref above,+ // and for the same reason recorded there: it is a live/OOB value a downloaded app carries,+ // and rejecting it broke the download→build round-trip on real apps. Requiring it to be+ // DECLARED would re-make that mistake in a new place — the referenced resource is often+ // managed or owned by another publisher, which download deliberately leaves as a bare+ // reference (it exists in the target env; re-creating a foreign prefix would hard-fail a+ // fresh build). Download still captures the CONTENT when it can safely do so, so an+ // own-prefix unmanaged page travels with the app.+ //+ // This does not weaken the http(s) guard, which exists to stop an ARBITRARY scheme+ // (`javascript:`, `file:`) becoming a nav entry in a shipped app. A web-resource reference+ // is not arbitrary: it names a resource inside Dataverse, not a script or a local file.+ if (sa.url && !webResourceNameFromRef(sa.url) && !isSafeHttpUrl(sa.url)) {+ errors.push(`sitemap subArea "${sa.title || ''}" url must be an http(s) URL or a $webresource:<name> reference (got '${sa.url}')`);+ }+ // schemaVersion 2 references pages by stable KEY; legacy specs still reference by name.+ const pageRefSet = isV2 ? pageKeysSet : pageNamesSet;+ if (sa.page && !pageRefSet.has(sa.page)) errors.push(`sitemap subArea references unknown page '${sa.page}' (declare it in pages[])`);+ checkIcon(sa.icon, `sitemap subArea "${sa.title || ''}"`);+ checkPortableIconRef(sa.icon, `sitemap subArea "${sa.title || ''}"`);+ checkPortableIconRef(sa.vectorIcon, `sitemap subArea "${sa.title || ''}"`);+ validateIconDescription(sa.iconDescription, `sitemap subArea "${sa.title || ''}"`, errors);+ // Ask 3: don't SILENTLY drop an entity-subarea vectorIcon. A valid platform ref round-trips+ // (emitted by the build); a BARE token can't be emitted on an entity subarea (it breaks the+ // modern app-designer), so surface it as a warning at author time rather than a silent drop.+ if (sa.entity && sa.vectorIcon && !isPlatformIconRef(sa.vectorIcon)) {+ warnings.push(`sitemap subArea "${sa.title || ''}": vectorIcon '${sa.vectorIcon}' is a bare token — on an entity subarea a bare Fluent token breaks the app designer and is DROPPED from the sitemap. Use an SVG path (e.g. /WebResources/<pub>/icons/x.svg) or a $webresource:<name>.svg reference, or set entities[].vectorIcon (the table icon) for a custom nav glyph.`);+ }+ // `icon` on a subarea is the LEGACY RASTER slot; `vectorIcon` is the modern SVG one. Putting+ // an SVG in `icon` is accepted by Dataverse and then renders as a placeholder — which is the+ // first half of AB#6688906: the author sees a broken glyph, switches to `vectorIcon`, and is+ // then left with both attributes deployed because the SDK's sitemap reconcile MERGES the new+ // attribute list onto the deployed node instead of replacing it, so the dropped `Icon`+ // survives in the XML.+ //+ // Only the authoring half is fixable here, so only that is claimed. Declaring BOTH is left+ // legal on purpose — a raster `icon` alongside a vector `vectorIcon` is a legitimate+ // legacy-fallback pair, and the shipped smoke spec uses exactly that.+ if (typeof sa.icon === 'string' && /\.svg$/i.test(sa.icon.trim()) && !isPlatformIconRef(sa.icon)) {+ warnings.push(`sitemap subArea "${sa.title || ''}": icon '${sa.icon}' is an SVG, but 'icon' is the legacy RASTER slot — the modern navigation renders a placeholder for it. Use vectorIcon: "$webresource:${sa.icon.trim()}" instead. If this subarea was already deployed with the icon, note that dropping it from the spec does NOT currently remove the Icon attribute from the deployed sitemap (the reconcile merges attributes rather than replacing them), so clear it once in the sitemap.`);+ }+ }+ }+ }+ // MEMBERSHIP invariant (Plan 5 v2 / Task 3): every generative page MUST appear as a sitemap subarea.+ // A model-driven app's membership IS sitemap presence — there is no hidden-but-navigable subarea.+ // A page that is only a navigatesTo target (no subarea) is NOT owned by the app's navigation: build+ // will create it, but download enumeration (membership = sitemap) and verify (membership check) will+ // both miss it, and the next build from a downloaded spec will then re-create it as a duplicate.+ // Enforced for specs that will be BUILT: deploy / plan / design. The `structural` profile is shape-+ // only (used by the eval harness and teardown / cleanup) and is explicitly excluded.+ if (isV2 && profile !== 'structural') {+ const sitemappedPageKeys = new Set();+ for (const a of (spec.appShell && spec.appShell.areas) || [])+ for (const g of a.groups || [])+ for (const sa of g.subAreas || []) if (sa && sa.page) sitemappedPageKeys.add(sa.page);+ for (const p of spec.pages || []) {+ const key = p.key || p.name;+ if (!sitemappedPageKeys.has(key)) {+ errors.push(`page '${key}' is not placed in the sitemap — every page must be an appShell subarea (a page reached only by navigation is not owned by the app; add a subarea for it)`);+ }+ }+ }+ // Table (entity) icons — these set the table's OWN icon (what the modern app designer and app+ // nav render for the table). Unlike a sitemap subarea's `vectorIcon` (a free-form Fluent token),+ // a TABLE's icon must be a declared, buildable web resource: `vectorIcon` an SVG web resource+ // (Dataverse IconVectorName), `icon` a raster PNG/JPG/GIF/ICO web resource (IconMediumName). An+ // unresolvable value is exactly what leaves the designer's property pane stuck on a glimmer, so+ // this is a hard error, not a lint warning.+ for (const e of spec.entities || []) {+ const label = `entity ${e.schemaName || ''}`;+ if (e.vectorIcon) {+ const v = String(e.vectorIcon).toLowerCase();+ if (!webResourceNames.has(v)) errors.push(`${label}: vectorIcon '${e.vectorIcon}' is not a declared web resource (a table's vectorIcon must be an SVG web resource — declare it in webResources[])`);+ else if (!svgWebResourceNames.has(v)) errors.push(`${label}: vectorIcon '${e.vectorIcon}' must be an SVG web resource (type "svg")`);+ }+ if (e.icon) {+ const ic = String(e.icon).toLowerCase();+ if (!webResourceNames.has(ic)) errors.push(`${label}: icon '${e.icon}' is not a declared web resource`);+ else if (!rasterWebResourceNames.has(ic)) errors.push(`${label}: icon '${e.icon}' must be a raster image web resource (png/jpg/gif/ico); use vectorIcon for an SVG`);+ }+ validateIconDescription(e.iconDescription, label, errors);+ }+ // App tile icon (optional). When set it must be a declared IMAGE web resource so the app is+ // self-contained on export/import; when omitted, the build generates a default icon in-solution.+ if (spec.app && spec.app.icon) {+ const ai = String(spec.app.icon).toLowerCase();+ if (!webResourceNames.has(ai)) errors.push(`app.icon '${spec.app.icon}' is not a declared web resource`);+ else if (!imageWebResourceNames.has(ai)) errors.push(`app.icon '${spec.app.icon}' must be an image web resource (png/jpg/gif/svg/ico)`);+ }+ if (spec.sampleData !== undefined) {+ if (typeof spec.sampleData !== 'object' || spec.sampleData === null || Array.isArray(spec.sampleData)) {+ errors.push('sampleData must be an object keyed by entity schemaName');+ } else {+ const lower = new Set([...entityNames].map((n) => n.toLowerCase()));+ for (const [k, v] of Object.entries(spec.sampleData)) {+ if (!lower.has(k.toLowerCase())) {+ errors.push(`sampleData references unknown entity '${k}'`);+ }+ if (!Array.isArray(v)) {+ errors.push(`sampleData['${k}'] must be an array of records`);+ continue;+ }+ // #4: catch Choice/MultiChoice sample values that are NOT a declared option label. Unknown+ // labels otherwise pass through resolveChoiceValue() unchanged and reach Dataverse as a raw+ // string, which either 400s late in the build or (for a MultiChoice) is silently wrong — a+ // typo like 'Urgnet' should fail here, not the live deploy. Uses the shared token linter so+ // this hard gate and spec-lint's guardrail apply identical rules. Built once per entity.+ const ent = lower.has(k.toLowerCase())+ ? (spec.entities || []).find((e) => String(e.schemaName).toLowerCase() === k.toLowerCase())+ : null;+ for (const rec of v) {+ for (const { field, token } of invalidChoiceSampleTokens(spec, ent, rec)) {+ errors.push(`sampleData['${k}']: value '${token}' for choice column '${field}' is not a declared option label`);+ }+ if (!rec || typeof rec !== 'object') {+ continue;+ }+ // #1: validate the parent bind(s) — one `$parent` (singular) and/or many `$parents` (a+ // junction row binding multiple sides). Each must name a known parent entity, carry a+ // non-empty match, have an existing OneToMany relationship, AND a match that resolves to+ // EXACTLY ONE parent sample record. Zero matches silently drops the bind (child created with+ // the lookup UNSET); more than one is ambiguous and the seeder would silently pick the first+ // (a mis-bind) — both fail loud here at lint time instead of shipping a wrong/half-linked row.+ if (rec.$parents !== undefined && !Array.isArray(rec.$parents)) {+ // A non-array $parents is silently ignored by the array-guarded map below but IS processed+ // by the seeder ([].concat(..., nonArray) keeps it as one element), so validation must+ // reject it rather than diverge from runtime.+ errors.push(`sampleData['${k}']: $parents must be an array of { entity, match } binds`);+ }+ const parentBinds = [].concat(+ rec.$parent !== undefined ? [{ p: rec.$parent, key: '$parent' }] : [],+ Array.isArray(rec.$parents) ? rec.$parents.map((pp) => ({ p: pp, key: '$parents' })) : []+ );+ for (const { p, key } of parentBinds) {+ if (!p || typeof p !== 'object' || Array.isArray(p) || !p.entity || !lower.has(String(p.entity).toLowerCase())) {+ errors.push(`sampleData['${k}']: ${key}.entity '${p && p.entity}' is unknown`);+ continue;+ }+ if (!p.match || typeof p.match !== 'object' || Array.isArray(p.match) || !Object.keys(p.match).length) {+ errors.push(`sampleData['${k}']: ${key}.match must be a non-empty object`);+ continue;+ }+ if (!relationshipFor(spec, p.entity, k)) {+ errors.push(`sampleData['${k}']: no OneToMany relationship from ${key} '${p.entity}' to '${k}'`);+ continue;+ }+ // The match must resolve to EXACTLY ONE parent sample record.+ const pKey = Object.keys(spec.sampleData).find((kk) => kk.toLowerCase() === String(p.entity).toLowerCase());+ const parentRecs = (pKey && Array.isArray(spec.sampleData[pKey])) ? spec.sampleData[pKey] : [];+ const matchCount = parentRecs.filter((pr) => pr && typeof pr === 'object' && Object.entries(p.match).every(([mk, mv]) => {+ const rk = Object.keys(pr).find((x) => x.toLowerCase() === mk.toLowerCase());+ return rk !== undefined && pr[rk] === mv;+ })).length;+ if (matchCount === 0) {+ errors.push(`sampleData['${k}']: ${key}.match ${JSON.stringify(p.match)} matched no '${String(p.entity).toLowerCase()}' sample record — the lookup would be left unset`);+ } else if (matchCount > 1) {+ errors.push(`sampleData['${k}']: ${key}.match ${JSON.stringify(p.match)} is ambiguous — it matches ${matchCount} '${String(p.entity).toLowerCase()}' sample records; tighten the match to select exactly one`);+ }+ }+ }+ }+ }+ }+ // ai block (optional) — validates appFeatures flags and summaries table references.+ if (spec.ai !== undefined) {+ if (!spec.ai || typeof spec.ai !== 'object' || Array.isArray(spec.ai)) {+ errors.push('ai must be an object');+ } else {+ const AI_FEATURE_KEYS_LIST = [...AI_FEATURE_KEYS].join(', ');+ if (spec.ai.appFeatures !== undefined) {+ if (!spec.ai.appFeatures || typeof spec.ai.appFeatures !== 'object' || Array.isArray(spec.ai.appFeatures)) {+ errors.push('ai.appFeatures must be an object');+ } else {+ 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).+ // Accept a boolean or a non-negative integer; reject anything else (a string like '2'+ // would silently bypass the range check downstream).+ //+ // The upper bound MIRRORS the SDK's `MAX_SETTING_VALUE` in api/AiApi.ts. The SDK THROWS+ // an InvalidArgumentError for an out-of-range value, so without this bound a spec would+ // validate cleanly and then abort the build half-applied — validation must reject it up+ // 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")`);+ }+ }+ }+ }+ if (spec.ai.summaries !== undefined) {+ if (!spec.ai.summaries || typeof spec.ai.summaries !== 'object' || Array.isArray(spec.ai.summaries)) {+ errors.push('ai.summaries must be an object');+ } else {+ if (spec.ai.summaries.default !== undefined && !['auto', 'off'].includes(spec.ai.summaries.default)) {+ errors.push(`ai.summaries.default must be 'auto' or 'off'`);+ }+ if (spec.ai.summaries.tables !== undefined) {+ if (!spec.ai.summaries.tables || typeof spec.ai.summaries.tables !== 'object' || Array.isArray(spec.ai.summaries.tables)) {+ errors.push('ai.summaries.tables must be an object');+ } else {+ for (const [k, v] of Object.entries(spec.ai.summaries.tables)) {+ const ent = entityByLower.get(k.toLowerCase());+ if (!ent) {+ errors.push(`ai.summaries.tables: unknown table '${k}'`);+ continue;+ }+ if (!v || typeof v !== 'object' || Array.isArray(v)) {+ errors.push(`ai.summaries.tables['${k}']: must be an object`);+ continue;+ }+ if (v.enabled !== undefined && typeof v.enabled !== 'boolean') errors.push(`ai.summaries.tables['${k}'].enabled: must be a boolean`);+ if (v.instruction !== undefined && typeof v.instruction !== 'string') errors.push(`ai.summaries.tables['${k}'].instruction: must be a string`);+ if (v.columns !== undefined) {+ if (!Array.isArray(v.columns)) {+ errors.push(`ai.summaries.tables['${k}'].columns: must be an array`);+ } else {+ const entCols = new Set([+ ...(ent.columns || []).map((c) => c.schemaName.toLowerCase()),+ ...(ent.primaryAttribute && ent.primaryAttribute.schemaName ? [ent.primaryAttribute.schemaName.toLowerCase()] : []),+ ]);+ for (const c of v.columns) {+ if (typeof c !== 'string') {+ errors.push(`ai.summaries.tables['${k}'].columns: each entry must be a string`);+ } else if (!entCols.has(c.toLowerCase())) {+ errors.push(`ai.summaries.tables['${k}'].columns: unknown column '${c}'`);+ }+ }+ }+ }+ }+ }+ }+ }+ }+ }+ }+ // Page design contract (optional, v2 only). Shape-only in this plan; the token→Fluent mapping+ // and generated-page validation land in the Pages plan. Reject unknown keys so typos fail early.+ // Gated on isV2 so a hand-authored legacy spec is not rejected for a v2-only field.+ if (isV2 && spec.design !== undefined) {+ if (typeof spec.design !== 'object' || spec.design === null || Array.isArray(spec.design)) {+ errors.push('design must be an object');+ } else {+ const allowed = new Set(['accentColor', 'density', 'cornerRadius', 'darkMode', 'layout']);+ for (const k of Object.keys(spec.design)) if (!allowed.has(k)) errors.push(`design: unknown key '${k}' (allowed: ${[...allowed].join(', ')})`);+ }+ }+ // Security personas (optional; additive — validated on v1 and v2 specs). Each persona authors ONE+ // security role (role name = persona) whose privilege set is the UNION of the entity access every+ // one of its jobs-to-be-done declares (the SDK unions them, max scope wins per entity+access). The+ // planner DECLARES the access each job needs — the engine never infers it — so this validator only+ // checks the declared SHAPE: valid Dataverse access/scope tokens and well-formed GUIDs. Two guards+ // are intentionally deferred to apply time because they need live entity metadata the lint pass does+ // not have: (1) whether an entity actually supports a requested access, and (2) the SDK's shared-+ // privilege rule (entities that alias to the same prv* must request one scope). Those surface as a+ // clean BuildHalt from the security phase, not here. Entity NAMES are likewise resolved against live+ // metadata by the SDK (a persona legitimately grants access to standard tables like `account` that+ // this spec does not author), so we validate only that `entity` is a non-empty string.+ if (spec.personas !== undefined) {+ if (!Array.isArray(spec.personas)) {+ errors.push('personas must be an array');+ } else {+ const personaNames = new Set();+ // Reject unknown keys so a typo fails loudly at author time instead of silently taking a default.+ // WHY this matters for security: `appAcces:false` (typo) would leave the REAL `appAccess` absent →+ // defaulting to true → the persona wrongly gets app-module read + the app association. Same pattern+ // the `design` block uses. Allowlists mirror the vendored SDK's PersonaRoleSpec/JobToBeDone/+ // EntityPrivilege shapes exactly.+ const PERSONA_KEYS = new Set(['persona', 'jobs', 'additionalPrivileges', 'appAccess', 'businessUnitId', 'assignTo']);+ const JOB_KEYS = new Set(['name', 'description', 'privileges', 'surfaces']);+ const PRIVILEGE_KEYS = new Set(['entity', 'access', 'scope']);+ const rejectUnknown = (obj, allowed, ctx) => {+ for (const k of Object.keys(obj)) if (!allowed.has(k)) errors.push(`${ctx}: unknown key '${k}' (allowed: ${[...allowed].join(', ')})`);+ };+ // Validate a persona/JTBD EntityPrivilege[] (shape + enum only — see the deferral note above).+ const validatePrivileges = (privs, ctx, { allowEmpty = false } = {}) => {+ if (privs === undefined) {+ if (!allowEmpty) errors.push(`${ctx}: privileges[] is required`);+ return;+ }+ if (!Array.isArray(privs) || (!allowEmpty && !privs.length)) {+ errors.push(`${ctx}: privileges must be a non-empty array`);+ return;+ }+ for (const pr of privs) {+ if (!pr || typeof pr !== 'object' || Array.isArray(pr)) { errors.push(`${ctx}: each privilege must be an object`); continue; }+ rejectUnknown(pr, PRIVILEGE_KEYS, `${ctx}: privilege`);+ if (!pr.entity || typeof pr.entity !== 'string') errors.push(`${ctx}: privilege.entity (a table logical name) is required`);+ if (!Array.isArray(pr.access) || !pr.access.length) {+ errors.push(`${ctx}: privilege on '${pr.entity || '?'}' needs a non-empty access[]`);+ } else {+ for (const a of pr.access) if (!ACCESS_LEVELS.has(a)) errors.push(`${ctx}: unknown access '${a}' on '${pr.entity}' (valid: ${[...ACCESS_LEVELS].join(', ')})`);+ }+ if (pr.scope !== undefined && !PRIVILEGE_SCOPES.has(pr.scope)) errors.push(`${ctx}: unknown scope '${pr.scope}' on '${pr.entity}' (valid: ${[...PRIVILEGE_SCOPES].join(', ')})`);+ }+ };+ for (const p of spec.personas) {+ if (!p || typeof p !== 'object' || Array.isArray(p)) { errors.push('personas[]: each persona must be an object'); continue; }+ rejectUnknown(p, PERSONA_KEYS, 'persona');+ // The SDK TRIMS the role name before its (name, business-unit) lookup, so validate + dedup on the+ // TRIMMED name — otherwise "Agent" and " Agent " pass as distinct here but collapse onto one role+ // (the second silently REPLACES the first's privileges), and teardown/verify would query the wrong+ // (untrimmed) name and miss the role.+ const pname = typeof p.persona === 'string' ? p.persona.trim() : p.persona;+ if (!pname || typeof pname !== 'string') {+ errors.push('persona: persona (the role name) is required and cannot be blank/whitespace-only');+ } else {+ const key = pname.toLowerCase();+ if (personaNames.has(key)) errors.push(`persona "${pname}": duplicate persona name (each persona authors one role — names must be unique after trimming)`);+ personaNames.add(key);+ }+ const label = pname || '?';+ if (p.appAccess !== undefined && typeof p.appAccess !== 'boolean') errors.push(`persona "${label}": appAccess must be a boolean`);+ if (p.businessUnitId !== undefined && (typeof p.businessUnitId !== 'string' || !FORM_GUID_RE.test(p.businessUnitId))) errors.push(`persona "${label}": businessUnitId must be a GUID`);+ if (!Array.isArray(p.jobs) || !p.jobs.length) {+ errors.push(`persona "${label}": at least one job (jobs[]) is required`);+ } else {+ for (const j of p.jobs) {+ if (!j || typeof j !== 'object' || Array.isArray(j)) { errors.push(`persona "${label}": each job must be an object`); continue; }+ rejectUnknown(j, JOB_KEYS, `persona "${label}" job`);+ if (!j.name || typeof j.name !== 'string') errors.push(`persona "${label}": a job is missing name`);+ // surfaces[]: the view/form/page names (or page keys) that let this persona DO the job.+ // Purely documentary — it drives the design doc's traceability table and the "job with no+ // surface" lint warning, and is never applied to Dataverse. Shape-only validation, because+ // a surface may legitimately name an artifact this spec doesn't author (a stock view).+ if (j.surfaces !== undefined) {+ if (!Array.isArray(j.surfaces)) errors.push(`persona "${label}" job "${j.name || '?'}": surfaces must be an array of strings`);+ else for (const s of j.surfaces) if (typeof s !== 'string' || !s.trim()) errors.push(`persona "${label}" job "${j.name || '?'}": each surfaces[] entry must be a non-empty string`);+ }+ validatePrivileges(j.privileges, `persona "${label}" job "${(j && j.name) || '?'}"`);+ }+ }+ if (p.additionalPrivileges !== undefined) validatePrivileges(p.additionalPrivileges, `persona "${label}" additionalPrivileges`, { allowEmpty: true });+ // assignTo (optional, grant-only). Team/user ids are Dataverse GUIDs — validate the shape so a+ // typo'd id fails at author time rather than as an opaque SDK GUID-normalization error on apply.+ if (p.assignTo !== undefined) {+ if (typeof p.assignTo !== 'object' || p.assignTo === null || Array.isArray(p.assignTo)) {+ errors.push(`persona "${label}": assignTo must be an object with teams[]/users[]`);+ } else {+ for (const k of Object.keys(p.assignTo)) if (k !== 'teams' && k !== 'users') errors.push(`persona "${label}": assignTo unknown key '${k}' (allowed: teams, users)`);+ for (const k of ['teams', 'users']) {+ if (p.assignTo[k] === undefined) continue;+ if (!Array.isArray(p.assignTo[k])) { errors.push(`persona "${label}": assignTo.${k} must be an array of GUIDs`); continue; }+ for (const id of p.assignTo[k]) if (typeof id !== 'string' || !FORM_GUID_RE.test(id)) errors.push(`persona "${label}": assignTo.${k} contains a non-GUID value`);+ }+ }+ }+ }+ }+ }+ // Lookup + alternate-key labels may be localized too (AB#6686428). Validated in one pass here+ // rather than inside the entities loop, because relationships[] is a top-level block and an+ // entity's alternateKeys[] have no other label check.+ (spec.relationships || []).forEach((r, i) => {+ if (r && r.lookup) validateLabel(r.lookup.displayName, `relationships[${i}] (${r.lookup.schemaName || '?'}): lookup.displayName`, errors, { warnings, baseLanguageCode: spec.languageCode });+ });+ for (const e of spec.entities || []) {+ (e && Array.isArray(e.alternateKeys) ? e.alternateKeys : []).forEach((k, i) => {+ if (k) validateLabel(k.displayName, `entity ${e.schemaName}: alternateKeys[${i}] displayName`, errors, { warnings, baseLanguageCode: spec.languageCode });+ });+ }+ validateRoleGrants(spec, errors);+ return { ok: errors.length === 0, errors, warnings };+}++// Slugify a page name into a stable key candidate: lowercase, non-alphanumerics -> '-', trimmed.+// "Sales Overview" -> "sales-overview"+// "KPI / Analytics" -> "kpi-analytics"+function slugify(name) {+ return String(name || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'page';+}++// The canonical role name for a persona: the TRIMMED `persona` string. The vendored SDK trims the name+// before its (name, business-unit) role lookup/create, so every plugin site that identifies the role —+// the create mapper (personaRoleSpecFor), teardown, and verify — MUST use this same trimmed form or they+// will disagree on the role's identity (create "Agent" but tear down / verify " Agent ").+function canonicalPersonaName(persona) {+ const n = persona && persona.persona;+ return typeof n === 'string' ? n.trim() : n;+}++// `roleGrants[]` — ADD privileges for a table to a security role this spec did NOT author. AB#6686429.+//+// WHY a separate block rather than another persona. `personas[]` OWNS its role: the SDK writes it with+// `ReplacePrivilegesRole`, which CONVERGES the role onto exactly the declared set — every privilege not+// in the spec is REMOVED. That is the right semantics for a role the spec created, and the wrong one for+// a role that already exists: pointing a persona at "Contoso PM — Project Manager" to add one table's+// privileges would silently strip every OTHER privilege that role held. `roleGrants[]` therefore compiles+// to `AddPrivilegesRole` (`sdk.addEntityPrivilegesToRole`), which is purely ADDITIVE — it never removes.+//+// The consequence the author must understand, and which the docs state: a roleGrant cannot REVOKE. To+// take a privilege away, edit the role in Maker. Dropping the entry from the spec leaves the grant in+// place; that is deliberate (a grant-only surface cannot know whether it put the privilege there) and it+// is what makes teardown safe — see sdk-teardown.js, which deletes only SDK-marked persona roles.+//+// Depth is honoured, not fixed: the SDK maps scope → Depth with the SAME table this plugin uses+// ({ user: Basic, businessUnit: Local, parentChild: Deep, organization: Global } — verified against the+// vendored bundle), so a declared `scope` reaches Dataverse intact.+// https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/addprivilegesrole+const ROLE_GRANT_KEYS = new Set(['role', 'roleId', 'businessUnitId', 'privileges', 'description']);++function validateRoleGrants(spec, errors) {+ const grants = spec && spec.roleGrants;+ if (grants === undefined) return;+ if (!Array.isArray(grants)) {+ errors.push('roleGrants must be an array of { role | roleId, privileges[] } entries');+ return;+ }+ const describeValue = (v) => { try { return JSON.stringify(v); } catch { return Object.prototype.toString.call(v); } };+ // A role's identity is (trimmed+folded NAME, business unit) — the same key the SDK uses. Two roles+ // may legitimately share a name in different business units, so the BU must be part of the key or+ // that valid pair is rejected; an absent BU means "the org root", which is one specific BU.+ //+ // The BU half is a TEXTUAL comparison, and cannot be otherwise here: the root business unit's GUID+ // is an environment fact, and nothing in this file may read the environment. So an implicit root+ // (`businessUnitId` absent -> "root") and an EXPLICIT root (`businessUnitId` set to the root's+ // GUID) key differently even though they name one business unit, and an overlap spanning that pair+ // is invisible to this check. It is caught at apply time on the RESOLVED role id, which is the+ // identity that actually matters — and since the apply path resolves and guards every grant before+ // writing any of them, nothing is granted before it halts.+ const personaKey = (name, businessUnitId) => `${String(name || '').trim().toLowerCase()}@${String(businessUnitId || 'root').trim().toLowerCase()}`;+ const personaNames = new Set(+ (Array.isArray(spec.personas) ? spec.personas : [])+ .filter((p) => p && typeof canonicalPersonaName(p) === 'string' && canonicalPersonaName(p).trim())+ .map((p) => personaKey(canonicalPersonaName(p), p.businessUnitId)),+ );+ const seenTargets = new Set();+ grants.forEach((g, i) => {+ if (!g || typeof g !== 'object' || Array.isArray(g)) { errors.push(`roleGrants[${i}]: each entry must be an object`); return; }+ for (const k of Object.keys(g)) {+ if (!ROLE_GRANT_KEYS.has(k)) errors.push(`roleGrants[${i}]: unknown key '${k}' (allowed: ${[...ROLE_GRANT_KEYS].join(', ')})`);+ }+ const roleName = typeof g.role === 'string' ? g.role.trim() : g.role;+ const label = `roleGrants[${i}]${roleName ? ` (role "${roleName}")` : g.roleId ? ` (roleId ${g.roleId})` : ''}`;+ // Exactly one identity. Accepting both would let them disagree, and the apply path can only follow+ // one — resolving the id and ignoring a mismatched name would grant on a role the author did not name.+ const hasName = g.role !== undefined;+ const hasId = g.roleId !== undefined;+ if (hasName && hasId) {+ errors.push(`${label}: set either 'role' (the existing role's display name) or 'roleId' (its GUID), not both — they can disagree and only one can be honoured`);+ } else if (!hasName && !hasId) {+ errors.push(`${label}: name the existing role to extend — set 'role' (display name) or 'roleId' (GUID)`);+ }+ if (hasName && (typeof roleName !== 'string' || !roleName)) {+ errors.push(`${label}: role must be the non-empty display name of an EXISTING security role (got ${describeValue(g.role)})`);+ }+ if (hasId && (typeof g.roleId !== 'string' || !FORM_GUID_RE.test(g.roleId))) {+ errors.push(`${label}: roleId must be a GUID (got ${describeValue(g.roleId)})`);+ }+ if (g.businessUnitId !== undefined && (typeof g.businessUnitId !== 'string' || !FORM_GUID_RE.test(g.businessUnitId))) {+ errors.push(`${label}: businessUnitId must be a GUID`);+ }+ // A name lookup is scoped to a business unit; an id already IS the identity, so a BU alongside it is+ // dead configuration that reads as if it constrains the lookup. Reject rather than ignore.+ if (hasId && g.businessUnitId !== undefined) {+ errors.push(`${label}: businessUnitId only scopes a lookup by 'role' name — remove it, or target the role by name instead of roleId`);+ }+ validateDescription(g.description, label, errors);+ // Extending a role this SAME spec authors is self-defeating: the security phase runs personas first+ // and `ReplacePrivilegesRole` converges that role onto the persona's declared set, so the grant would+ // be added, then removed on the next build's persona pass, then re-added — churn that reads as an+ // intermittent access bug. Declare the privileges on the persona's job instead, where they converge.+ //+ // This is a NAME check only, and cannot be otherwise: a persona role is identified by (name, BU) and+ // does not exist yet at lint time, so a `roleId` pinned at the same role is invisible here. The apply+ // path therefore re-checks on the RESOLVED role id, which is the identity that actually matters.+ if (roleName && personaNames.has(personaKey(roleName, g.businessUnitId))) {+ errors.push(`${label}: '${roleName}' is a persona in this spec, whose role the build CONVERGES (privileges not declared on the persona are removed) — declare these privileges on that persona's job instead of as a roleGrant`);+ }+ if (roleName || g.roleId) {+ // One grant per role. Two grants on the same role are not additive-safe to validate: the SDK+ // detects the "entities sharing one Dataverse privilege must request one depth" conflict only+ // WITHIN a single call, so splitting a role's privileges across entries would let a conflicting+ // pair through to two separate writes, where the second silently wins.+ //+ // Keyed on (name, BU) rather than name alone, because a role is identified by BOTH: two roles+ // legitimately share a name in different business units, and rejecting that pair was wrong.+ // A `roleId` keys on itself. A name and an id can still ALIAS the same role, which no static+ // check can see — the apply path catches that on the resolved id.+ const key = g.roleId ? `id:${String(g.roleId).trim().toLowerCase()}` : `name:${personaKey(roleName, g.businessUnitId)}`;+ if (seenTargets.has(key)) errors.push(`${label}: duplicate roleGrant for the same role — merge the privileges into one entry (two entries can request conflicting depths for one shared Dataverse privilege, and the later write would silently win)`);+ seenTargets.add(key);+ }+ // Privilege shape: identical to a persona's, and validated the same way — enum-only here, because+ // whether a table actually EXPOSES an access, and the shared-privilege depth rule, both need live+ // metadata. Those surface as a BuildHalt from the security phase.+ if (!Array.isArray(g.privileges) || !g.privileges.length) {+ errors.push(`${label}: privileges must be a non-empty array — a roleGrant with nothing to grant is a no-op the SDK rejects`);+ return;+ }+ for (const pr of g.privileges) {+ if (!pr || typeof pr !== 'object' || Array.isArray(pr)) { errors.push(`${label}: each privilege must be an object`); continue; }+ for (const k of Object.keys(pr)) if (k !== 'entity' && k !== 'access' && k !== 'scope') errors.push(`${label}: privilege unknown key '${k}' (allowed: entity, access, scope)`);+ if (!pr.entity || typeof pr.entity !== 'string') errors.push(`${label}: privilege.entity (a table logical name) is required`);+ if (!Array.isArray(pr.access) || !pr.access.length) {+ errors.push(`${label}: privilege on '${pr.entity || '?'}' needs a non-empty access[]`);+ } else {+ for (const a of pr.access) if (!ACCESS_LEVELS.has(a)) errors.push(`${label}: unknown access '${a}' on '${pr.entity}' (valid: ${[...ACCESS_LEVELS].join(', ')})`);+ }+ if (pr.scope !== undefined && !PRIVILEGE_SCOPES.has(pr.scope)) errors.push(`${label}: unknown scope '${pr.scope}' on '${pr.entity}' (valid: ${[...PRIVILEGE_SCOPES].join(', ')})`);+ }+ });+}++// Upgrade a legacy App Spec to schemaVersion 2 in one pure pass (no I/O; returns a deep copy):+// - mint a stable, unique `key` per page (slug of name, de-duplicated with a -N suffix)+// - wrap a legacy top-level `codeFile` into `source: { kind: 'tsx', codeFile }`+// - rewrite name-based references (appShell page subareas + navigatesTo.targetKey) to keys+// Idempotent: a spec already at schemaVersion >= 2 is returned as-is. Runs on load before validate,+// so downstream code only ever sees the v2 shape. See docs/app-builder-design.md §7.3.+//+// Two-pass design: pass 1 mints ALL keys first so nameToKey is fully populated before any+// rewrite. A single rewrite pass (pass 2) then replaces every name-ref exactly once, preventing+// the double-rewrite bug that occurred when a minted key collided with another page's name+// (e.g. pages "Detail" → key "detail" and "detail" → key "detail-2": the old two-pass code+// would rewrite a "Detail" name-ref to "detail" in pass 1, then re-apply nameToKey in pass 2+// and wrongly map "detail" (now a key, but also the name of the second page) to "detail-2").+function migrateAppSpec(spec) {+ if (!spec || typeof spec !== 'object' || (spec.schemaVersion || 0) >= 2) return spec;+ const out = JSON.parse(JSON.stringify(spec));+ out.schemaVersion = 2;+ const nameToKey = new Map();+ const used = new Set();+ // Migration runs BEFORE validateAppSpec at every CLI entry point (build/preview/verify/teardown+ // all migrate the file they just read, then validate), so a malformed collection reached these+ // loops and threw a raw TypeError before the gate that is supposed to report it ever ran. Iterate+ // defensively — but do NOT rewrite the value, or validateAppSpec would see a repaired spec and+ // report nothing. The shape error stays for the gate to find.+ const arr = (v) => (Array.isArray(v) ? v : []);+ // Pass 1: mint every key and wrap legacy codeFile→source. nameToKey is fully populated+ // after this loop so the rewrite pass below needs only a single scan (no forward-ref gaps).+ for (const p of arr(out.pages)) {+ if (!p || typeof p !== 'object') continue;+ let key = slugify(p.name);+ let n = 1;+ while (used.has(key)) { n += 1; key = `${slugify(p.name)}-${n}`; }+ used.add(key);+ p.key = key;+ nameToKey.set(p.name, key);+ if (!p.source && typeof p.codeFile === 'string') { p.source = { kind: 'tsx', codeFile: p.codeFile }; delete p.codeFile; }+ }+ // Pass 2: rewrite name-refs to keys exactly once. Because nameToKey is complete, forward refs+ // (a page referencing a later-declared page) resolve correctly without a repeated second pass.+ for (const p of arr(out.pages)) {+ if (!p || typeof p !== 'object') continue;+ for (const nav of arr(p.navigatesTo)) { if (nav && nameToKey.has(nav.targetKey)) nav.targetKey = nameToKey.get(nav.targetKey); }+ }+ for (const a of arr(out.appShell && out.appShell.areas)) {+ if (!a || typeof a !== 'object') continue;+ for (const g of arr(a.groups)) {+ if (!g || typeof g !== 'object') continue;+ for (const sa of arr(g.subAreas)) { if (sa && sa.page && nameToKey.has(sa.page)) sa.page = nameToKey.get(sa.page); }+ }+ }+ return out;+}++module.exports = {+ rejectLocalizedGlobalChoice,+ validateAppSpec,+ normalizePageSource,+ normalizeLanguageCode,+ validateChoiceOptionLabels,+ labelText,+ labelAliases,+ isLocalizedLabelMap,+ labelIsMissing,+ localizedLabelLcids,+ validateLabel,+ quickCreateEnabledFor,+ isPlatformIconRef,+ webResourceNameFromRef,+ FORM_TYPE_CODE,+ FORM_GUID_RE,+ ACCESS_LEVELS,+ PRIVILEGE_SCOPES,+ ROLE_GRANT_KEYS,+ SDK_ROLE_MARKER,+ canonicalPersonaName,+ VALIDATION_PROFILES,+ ENTITY_KEYS,+ invalidLanguageCodeMessage,+ ENTITY_KEY_HINTS,+ DIRECT_ENTRY_BEHAVIORS,+ COLUMN_VISUALIZATIONS,+ INTEGER_FORMATS,+ BUSINESS_RULE_OPERATORS,+ BUSINESS_RULE_VALUELESS_OPERATORS,+ BUSINESS_RULE_ACTIONS,+ BUSINESS_RULE_ACTION_TYPES,+ BUSINESS_RULE_DATA_TYPES,+ BPF_STATUSES,+ BPF_ROLE_ACCESS,+ BPF_SECURITY_ROLE_KEYS,+ bpfUniqueName,+ declaredColumnLogicals,+ BUSINESS_RULE_SCOPES,+ migrateAppSpec,+ columnTypeMap,+ TYPE_MAP,+ choiceValueMap,+ invalidChoiceSampleTokens,+ sampleRecordsFor,+ resolveSampleRecords,+ relationshipFor,+ lookupColumnsFor,+ childRelationshipsFor,+ relationshipSchemaName,+ prefixedRelationshipName,+ manyToManyFor,+ manyToManySchemaName,+ isSafeHttpUrl,+ CHART_TYPES,+};diff --git a/plugins/model-apps/scripts/lib/classify-changes.js b/plugins/model-apps/scripts/lib/classify-changes.jsindex 95ad19879..957f4427c 100644--- a/plugins/model-apps/scripts/lib/classify-changes.js+++ b/plugins/model-apps/scripts/lib/classify-changes.js@@ -168,8 +168,11 @@ function classifyAdditive(cur, prior, phase, type, arrKey, opts = {}) {for (const c of common) {if (stableStringify(c.cur) !== stableStringify(c.prior)) {const onlyConverged = convergedKeys.length && equalExcept(c.cur, c.prior, convergedKeys);+ // Name only the keys that actually differ. "status/securityRoles changed" when just one did is+ // the kind of small inaccuracy that makes a reader stop trusting the whole report.+ const changed = convergedKeys.filter((k) => stableStringify(c.cur && c.cur[k]) !== stableStringify(c.prior && c.prior[k]));out.full.push(onlyConverged- ? `${phase}: ${type} '${c.id}' ${convergedKeys.join('/')} changed — reconciled by a full build`+ ? `${phase}: ${type} '${c.id}' ${(changed.length ? changed : convergedKeys).join('/')} changed — reconciled by a full build`: `${phase}: ${type} '${c.id}' edited — the additive build engine skips edits to an existing ${type}`);if (!onlyConverged) out.debt.push({ artifactType: type, identity: c.id, reason: `${type}-edit-not-convergent` });}@@ -231,7 +234,12 @@ function classifyChanges(current, prior) {// is real debt. The ONE exception is `status`: both reuse branches converge statecode in both// directions, so a status-only change is applied by a rebuild and is not debt.case 'business-rules': merge(classifyAdditive(cur, prior, 'business-rules', 'businessRule', 'businessRules', { convergedKeys: ['status'] })); break;- case 'business-process-flows': merge(classifyAdditive(cur, prior, 'business-process-flows', 'businessProcessFlow', 'businessProcessFlows', { convergedKeys: ['status'] })); break;+ // `securityRoles` converges too, and for a stronger reason than `status`: a BPF grant always+ // targets a PERSONA role, which the security phase applies with `ReplacePrivilegesRole` — so a+ // rebuild both ADDS a newly-declared persona and REMOVES one that was dropped. Filing it as+ // permanent debt disabled every later fast apply over a divergence that a full build erases.+ // (`roleGrants[]` would NOT qualify: it is additive and cannot revoke.)+ case 'business-process-flows': merge(classifyAdditive(cur, prior, 'business-process-flows', 'businessProcessFlow', 'businessProcessFlows', { convergedKeys: ['status', 'securityRoles'] })); break;default:// An unrecognized changed phase must never silently pass as fast (fail-closed).fullReasons.push(`${phase}: changed — no fast-path shape recognized`);diff --git a/plugins/model-apps/scripts/lib/dataverse-auth.js b/plugins/model-apps/scripts/lib/dataverse-auth.jsindex e640217ca..6038237ad 100644--- a/plugins/model-apps/scripts/lib/dataverse-auth.js+++ b/plugins/model-apps/scripts/lib/dataverse-auth.js@@ -28,6 +28,180 @@ function getAuthToken(envUrl) {}}+/**+ * Reads the Azure CLI identity that will supply the Dataverse token. Best-effort and never throws —+ * it exists to make a failure explicable, so it must not become a failure of its own.+ * @returns {{user: string, tenantId: string}|null}+ */+function azIdentity() {+ try {+ const out = execFileSync(+ 'az',+ ['account', 'show', '--query', '{user:user.name,tenantId:tenantId}', '-o', 'json'],+ { encoding: 'utf8', timeout: 30000, stdio: ['ignore', 'pipe', 'pipe'], shell: process.platform === 'win32' }+ );+ const parsed = JSON.parse(out);+ return parsed && parsed.user ? { user: parsed.user, tenantId: parsed.tenantId || '(unknown)' } : null;+ } catch {+ return null;+ }+}++/**+ * AB#6686427 — prove, before any real work, that the ambient Azure CLI context can actually talk to+ * the requested org.+ *+ * The skill flow selects a PAC profile, but every script here authenticates through the+ * INDEPENDENTLY active `az` account. In a normal multi-tenant workflow `pac auth` and `az login`+ * legitimately point at different tenants: `pac org who` succeeds, `az` mints a token for the wrong+ * tenant, and Dataverse answers 401. That reads as a permission problem, so the user goes looking at+ * security roles and PAC profiles instead of at `az account show`.+ *+ * `WhoAmI` is the probe because it is the cheapest authenticated call and needs no privilege beyond+ * being a valid user of the org — so a 401 here is about IDENTITY, not about what that identity may+ * do. That distinction is the whole value: a 403 or a 5xx is deliberately NOT blamed on the tenant,+ * because misattributing those would send the user down exactly the wrong path, which is the bug+ * this fixes, mirrored.+ *+ * Dependencies are injected for tests. Returns `{ ok: true, identity }` or `{ ok: false, error }`+ * and never throws — it is a diagnostic.+ * WhoAmI: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/whoami+ */+/**+ * Reject anything that is not an absolute HTTPS origin BEFORE a token is acquired or sent.+ *+ * This is STRICTER than `createAzHttpClient`, deliberately, and the difference matters. That client+ * requires an absolute `https:` org URL and refuses to send its token to a different ORIGIN — but it+ * compares origins, so a path-bearing `--env` passes construction untouched. This gate additionally+ * rejects a path, query or fragment, because the preflight runs earlier and goes through+ * `dataverseRequest`, whose transport picks plain `http` for any non-HTTPS scheme+ * (`u.protocol === 'https:' ? https : http`). Without it a malformed `--env` could put a bearer token+ * on the wire in clear text before the client's fail-closed validation ever ran — the preflight would+ * have become a hole in the credential boundary it sits in front of.+ * @returns {string|null} the normalized origin, or null when the value is unusable+ */+function httpsOriginOrNull(envUrl) {+ try {+ const raw = String(envUrl == null ? '' : envUrl).trim();+ if (!raw) return null;+ const u = new URL(raw);+ if (u.protocol !== 'https:') return null;+ // An ORIGIN, strictly. A value carrying a path, query or fragment is REJECTED rather than+ // silently trimmed to its origin: `dataverseRequest` appends `/api/data/...` to whatever it is+ // given, so `https://org.crm.dynamics.com/some/path` would produce `.../some/path/api/data/...`+ // and the preflight would report a misleading result about a URL nobody asked for. Rejecting is+ // also the tighter credential boundary — this function's whole job is to decide where a bearer+ // token may be sent, so "close enough" is the wrong disposition.+ if ((u.pathname && u.pathname !== '/') || u.search || u.hash) return null;+ return u.origin;+ } catch {+ return null;+ }+}++async function preflightAuth(envUrl, deps = {}) {+ const getToken = deps.getToken || getAuthToken;+ const request = deps.request || dataverseRequest;+ const readIdentity = deps.azIdentity || azIdentity;++ // Memoized, because reading it costs an `az` subprocess and BOTH the success path (to report which+ // identity was accepted) and the 401 path (to name the one that was rejected) want it. Without the+ // cache the 401 path could read it twice.+ let identityRead = false;+ let cachedIdentity = null;+ const who = () => {+ if (!identityRead) {+ identityRead = true;+ try { cachedIdentity = readIdentity(); } catch { cachedIdentity = null; }+ }+ return cachedIdentity;+ };++ // Normalize to the validated ORIGIN and use it from here on. Validating one string and then+ // requesting with another is how a check becomes decorative.+ const origin = httpsOriginOrNull(envUrl);+ if (!origin) {+ return {+ ok: false,+ error: `refusing to authenticate against '${envUrl}': the environment must be an absolute https:// ORIGIN `+ + '(scheme + host only, no path, query or fragment). A bearer token is attached to this request, so a '+ + 'non-HTTPS, path-bearing or malformed target is rejected before any token is acquired.',+ };+ }++ let token = null;+ try { token = getToken(origin); } catch { token = null; }+ if (!token) {+ return {+ ok: false,+ error: `no Azure CLI access token could be obtained for ${origin}. This is a sign-in problem, not a `+ + `permissions one — run \`az login\` (add \`--tenant <id>\` if this org lives in another tenant), then retry.`,+ };+ }++ let res;+ try {+ // Headers are requested because a 401's `WWW-Authenticate` is the only thing that distinguishes a+ // Conditional Access / CAE claims challenge from a plain wrong-identity rejection.+ // The token acquired above is HANDED OVER rather than re-fetched: `dataverseRequest` would+ // otherwise shell out to `az account get-access-token` a second time for the same origin, and+ // that call cold-starts the Azure CLI runtime — seconds, on the path a user is waiting on.+ res = await request(origin, 'GET', 'WhoAmI', null, { includeHeaders: true, token });+ } catch (e) {+ // A transport failure says nothing about identity, so it must not be reported as one — and must+ // not BLOCK. See the `inconclusive` contract below.+ return { ok: false, inconclusive: true, error: `the identity check could not reach ${origin}: ${(e && e.message) || e}` };+ }++ const status = res && (res.status !== undefined ? res.status : res.statusCode);+ if (status >= 200 && status < 300) {+ return { ok: true, identity: who() || { user: '(unknown)', tenantId: '(unknown)' }, userId: res.data && (res.data.UserId || res.data.userId) };+ }++ if (status === 401) {+ // A 401 is NOT proof of tenant divergence. Conditional Access and Continuous Access Evaluation+ // return 401 with `WWW-Authenticate: ... error="insufficient_claims"`, and a revoked token or a+ // disabled user land here too — none of which `az login --tenant` fixes. Naming tenant divergence+ // as a certainty would be the same misattribution this bug is about, pointed somewhere new.+ // See: https://learn.microsoft.com/en-us/entra/identity-platform/claims-challenge+ const authenticate = String((res.headers && (res.headers['www-authenticate'] || res.headers['WWW-Authenticate'])) || '');+ if (/insufficient_claims|claims=/i.test(authenticate)) {+ return {+ ok: false,+ error: `Dataverse returned a CLAIMS CHALLENGE for ${origin} (401 with \`${authenticate.slice(0, 160)}\`). This is a `+ + 'Conditional Access / CAE requirement, not a wrong-tenant problem — re-authenticate so the requested claims '+ + 'are satisfied (for example an interactive `az login`); switching tenant will not help.',+ };+ }+ const id = who();+ const whoText = id+ ? `The token is being issued to '${id.user}' in tenant ${id.tenantId}.`+ : 'The active Azure CLI identity could not be read, so the token source is unknown.';+ return {+ ok: false,+ error: `Dataverse rejected the Azure CLI token for ${origin} (WhoAmI returned 401). ${whoText} `+ + 'The most likely cause is that these scripts authenticate through the ACTIVE Azure CLI account rather than '+ + `the selected PAC profile, so \`pac org who\` can succeed while this fails — run \`az login --tenant <the `+ + `tenant that owns ${origin}>\` and retry. A revoked token or a disabled account would also land here.`,+ };+ }++ // INCONCLUSIVE, never blocking. This probe goes through `dataverseRequest`, which retries fewer+ // statuses and fewer times than the `createAzHttpClient` the real work uses (that one also retries+ // 504 and backs off longer). So a transient 429/5xx the caller's own client would ride out can fail+ // HERE — and turning that into a hard stop would make a diagnostic the reason a previously working+ // download fails. Report it, do not block: only a definitive verdict (bad URL, no token, or a 401)+ // is worth refusing to start over. The server's own message is preserved because a 403 usually+ // explains itself (IP firewall, licensing, missing role) and discarding it hides the real cause.+ const serverMsg = res && res.data && (res.data.error?.message || (typeof res.data === 'string' ? res.data : null));+ return {+ ok: false,+ inconclusive: true,+ error: `the identity check against ${envUrl} returned HTTP ${status}${serverMsg ? ` — ${serverMsg}` : ''}, which is not an `+ + 'authentication failure — proceeding anyway; if the run then fails, investigate that response rather than the Azure CLI tenant.',+ };+}+/*** Makes a raw HTTPS request and resolves with `{ statusCode, body, headers? }` or `{ error }`.* @param {object} options@@ -91,9 +265,20 @@ async function dataverseRequest(envUrl, method, apiPath, body = null, opts = {})const cleanUrl = envUrl.replace(/\/+$/, '');const url = `${cleanUrl}/api/data/v9.2/${apiPath}`;const bodyStr = body == null ? null : typeof body === 'string' ? body : JSON.stringify(body);- const { includeHeaders = false, extraHeaders = {}, timeout = 60000 } = opts;+ const { includeHeaders = false, extraHeaders = {}, timeout = 60000, token: presetToken = null } = opts;+ // Test seams, matching `preflightAuth`'s injection style. Without them the token-reuse behaviour+ // below could only be exercised against a live Azure CLI and a real org.+ const acquireToken = opts.getToken || getAuthToken;+ const send = opts.request || makeRequest;- let token = getAuthToken(cleanUrl);+ // `token` lets a caller that has ALREADY acquired one hand it over instead of paying for a second+ // `az account get-access-token`, which cold-starts the Azure CLI's Python runtime (seconds, not+ // milliseconds, on Windows). `preflightAuth` is the case that matters: it deliberately fetches a+ // token first so it can tell "not signed in" apart from "signed in but rejected" — two genuinely+ // different diagnoses — and would otherwise fetch the very same token twice in a row.+ // The 401 refresh path below still re-acquires from the CLI, because a preset token that has just+ // been rejected is exactly the thing that must not be retried.+ let token = presetToken || acquireToken(cleanUrl);if (!token) {throw new Error(`Failed to get Azure CLI token for ${cleanUrl}. Run 'az login' first.`);}@@ -109,7 +294,7 @@ async function dataverseRequest(envUrl, method, apiPath, body = null, opts = {})};if (bodyStr) headers['Content-Type'] = 'application/json; charset=utf-8';- const res = await makeRequest({ url, method, headers, body: bodyStr, includeHeaders, timeout });+ const res = await send({ url, method, headers, body: bodyStr, includeHeaders, timeout });if (res.error) {if (attempt < maxRetries) continue;@@ -117,7 +302,7 @@ async function dataverseRequest(envUrl, method, apiPath, body = null, opts = {})}if (res.statusCode === 401 && attempt < maxRetries) {- token = getAuthToken(cleanUrl);+ token = acquireToken(cleanUrl);if (!token) throw new Error("Token refresh failed. Run 'az login' again.");continue;}@@ -141,10 +326,38 @@ async function dataverseRequest(envUrl, method, apiPath, body = null, opts = {})/*** Throws if the response is not 2xx. Returns the response untouched on success.* Pulls Dataverse's structured error message out of `data.error.message` when present.+ *+ * AB#6686424 — a surviving 401 names the identity whose token was refused. Both auth paths already+ * retry a 401 once, and that retry is NOT the gap: measured, `az account get-access-token` serves+ * from the MSAL cache, so an immediate re-call returns a byte-identical token. A retry therefore+ * cannot fix a token rejected for WHO it belongs to — only one that expired in a narrow window. The+ * reporter's own workaround was `az login`, i.e. AB#6686427's cause. So what a terminal 401 needs is+ * not another attempt but an explanation, or the reader goes looking at Dataverse security roles.+ *+ * Scoped to 401 only. A 403 is a genuine privilege problem and a 4xx/5xx is something else entirely;+ * attaching identity advice to those would send the reader to `az login` for something it cannot fix.+ * The identity is read lazily so a successful call never shells out to `az`.*/-function ensureOk(res, context) {+function ensureOk(res, context, deps = {}) {if (res.status >= 200 && res.status < 300) return res;- const msg = res?.data?.error?.message || (typeof res.data === 'string' ? res.data : JSON.stringify(res.data));+ // A 401 from Dataverse frequently carries NO body at all, so `data` is null and interpolating it+ // yields the literal "HTTP 401 — null". Found by live verification; the unit fixtures all supplied+ // a message, so nothing caught it.+ const raw = res?.data?.error?.message || (typeof res.data === 'string' ? res.data : (res.data == null ? null : JSON.stringify(res.data)));+ const msg = raw || '(no response body)';+ if (res.status === 401) {+ const readIdentity = deps.azIdentity || azIdentity;+ let id = null;+ try { id = readIdentity(); } catch { id = null; }+ const whoText = id+ ? `The token was issued to '${id.user}' in tenant ${id.tenantId}.`+ : 'The active Azure CLI identity could not be read.';+ throw new Error(+ `${context} failed: HTTP 401 — ${msg}. ${whoText} These scripts authenticate through the ACTIVE `+ + 'Azure CLI account, not the selected PAC profile, so this is an identity problem rather than a '+ + 'Dataverse privilege issue — run `az login --tenant <the tenant that owns this org>` and retry.'+ );+ }throw new Error(`${context} failed: HTTP ${res.status} — ${msg}`);}@@ -367,12 +580,23 @@ function emitResult(ok, payload) {if (payload instanceof Error) {process.stderr.write(payload.message + '\n');} else if (payload !== null && typeof payload === 'object') {- // Partial failure (e.g., bulk insert with some errors). Emit the structured- // payload to stdout so callers can parse `errors`, and exit 1 so shells+ // Structured failure. Emit the payload to stdout so callers can parse it, and exit 1 so shells// still treat it as a failure.process.stdout.write(JSON.stringify(payload) + '\n');- const n = Array.isArray(payload.errors) ? payload.errors.length : 'unknown';- process.stderr.write(`Operation completed with ${n} error(s); see stdout JSON\n`);+ if (Array.isArray(payload.errors)) {+ // A genuine PARTIAL failure (bulk insert with some rows rejected): the count is the useful+ // summary and the detail is per-row on stdout.+ process.stderr.write(`Operation completed with ${payload.errors.length} error(s); see stdout JSON\n`);+ } else if (typeof payload.error === 'string' && payload.error.trim()) {+ // A single, already-explained failure — an auth preflight rejection, an unresolvable app id.+ // These carry a message written specifically to tell the operator what to DO, so print IT.+ // The old branch printed "completed with unknown error(s)" for every one of them, burying the+ // diagnostic under boilerplate that is both less informative and actively misleading: nothing+ // "completed", and the error is not unknown.+ process.stderr.write(payload.error.trim() + '\n');+ } else {+ process.stderr.write('Operation failed with an unstructured error; see stdout JSON\n');+ }} else {process.stderr.write(String(payload) + '\n');}@@ -380,6 +604,8 @@ function emitResult(ok, payload) {}module.exports = {+ preflightAuth,+ azIdentity,getAuthToken,makeRequest,dataverseRequest,diff --git a/plugins/model-apps/scripts/lib/entity-provision.js b/plugins/model-apps/scripts/lib/entity-provision.jsindex 4509583dd..4c7f10c10 100644--- a/plugins/model-apps/scripts/lib/entity-provision.js+++ b/plugins/model-apps/scripts/lib/entity-provision.js@@ -13,6 +13,9 @@ const {manyToManySchemaName,quickCreateEnabledFor,normalizeLanguageCode,+ labelText,+ isLocalizedLabelMap,+ localizedLabelLcids,} = require('./app-spec.js');const { topoOrderEntities, entityByLogical } = require('./_graph.js');// OData string-literal escaping for spec-controlled values interpolated into $filter (a solution@@ -79,6 +82,70 @@ async function checkProvisioned(lcid, source, provisionedLanguages) {);}+// Every LCID the spec's LOCALIZED labels ask for, deduped and sorted, with an example of where each+// was declared so the halt below can name one. AB#6686428.+function localizedLabelLcidsInSpec(spec) {+ const byLcid = new Map(); // lcid -> a human-readable "where" for the first site that used it+ const note = (value, where) => {+ for (const lcid of localizedLabelLcids(value)) if (!byLcid.has(lcid)) byLcid.set(lcid, where);+ };+ for (const e of (spec && spec.entities) || []) {+ const at = `entity ${e && e.schemaName}`;+ note(e && e.displayName, `${at} displayName`);+ note(e && e.pluralName, `${at} pluralName`);+ note(e && e.primaryAttribute && e.primaryAttribute.displayName, `${at} primaryAttribute.displayName`);+ for (const c of (e && e.columns) || []) {+ note(c && c.displayName, `${at} column ${c && c.schemaName} displayName`);+ for (const o of (c && c.options) || []) note(o, `${at} column ${c && c.schemaName} option`);+ }+ for (const k of (e && e.alternateKeys) || []) note(k && k.displayName, `${at} alternate key ${k && k.schemaName}`);+ }+ for (const r of (spec && spec.relationships) || []) note(r && r.lookup && r.lookup.displayName, `relationship lookup ${r && r.lookup && r.lookup.schemaName}`);+ for (const g of (spec && spec.globalChoices) || []) {+ note(g && g.displayName, `globalChoice ${g && g.name} displayName`);+ for (const o of (g && g.options) || []) note(o, `globalChoice ${g && g.name} option`);+ }+ return [...byLcid.entries()].sort(([a], [b]) => a - b).map(([lcid, where]) => ({ lcid, where }));+}++// Halt when a LOCALIZED label names a language the organization has not provisioned. AB#6686428.+//+// This is NOT a validation nicety — it is the difference between the feature working and the feature+// re-creating the exact bug it fixes. LIVE-MEASURED against a 1033-only organization: `createTable`+// with `DisplayName: { 1033, 3082 }` returns SUCCESS and stores ONLY the 1033 label. Dataverse does+// not warn, error, or report the drop anywhere. So without this check an author labels a table in+// Spanish, gets a green build, and the Spanish is simply gone — "a successful build with the request+// gone and nothing reporting the loss", which is the failure this whole feature exists to end.+//+// Distinct from `checkProvisioned` above, which guards the single build-wide authoring language: that+// one can also fail LOUDLY later (a DateTime/Memo column is rejected outright), whereas a dropped+// localized label has no downstream symptom at all.+//+// Best-effort in exactly the same way: an unreadable probe leaves the build unchanged, because a+// diagnostic that cannot answer must not block work that would otherwise succeed.+async function checkLocalizedLabelLanguages(spec, provisionedLanguages) {+ const wanted = localizedLabelLcidsInSpec(spec);+ if (!wanted.length || typeof provisionedLanguages !== 'function') return;+ let list;+ try {+ list = await provisionedLanguages();+ } catch {+ return;+ }+ if (!Array.isArray(list) || !list.length) return;+ const missing = wanted.filter((w) => !list.includes(w.lcid));+ if (!missing.length) return;+ throw new BuildHalt(+ `${missing.length} localized label language(s) are not provisioned in this organization: `+ + `${missing.map((m) => `${m.lcid} (first used by ${m.where})`).join('; ')}. `+ + 'Dataverse would ACCEPT those labels and silently store only the provisioned one — live-measured: '+ + 'a create carrying an unprovisioned LCID returns success and the label is simply absent afterwards, '+ + 'with nothing reporting the loss. Provisioned languages: '+ + `${list.join(', ')}. Provision the language in the organization first, or drop it from the labels.`,+ { phase: 'data-model', code: 'localized-label-language-not-provisioned', recoverable: false }+ );+}+// Dataverse label payloads must use an LCID the org actually has provisioned. Resolve an explicit// CLI override first, then an App Spec override, then the org's base `organization.languagecode`,// and only fall back to 1033 if discovery itself fails so an unrelated read error does not block@@ -292,6 +359,103 @@ function columnRequiredLevel(c) {return requiredLevelValue(c.RequiredLevel) || requiredLevelValue(c.requiredLevel);}+// The columns a table already has, as `[{ logicalName, RequiredLevel }]`.+//+// Same reason as `findExistingTable` above, and the same measurement: calling the SDK's+// `findColumns` immediately before `createColumn` makes Dataverse store ONLY the base-language+// label of a multi-language column name. Order-controlled, 8 columns, sequence C,F,F,C,C,F,F,C:+// `createColumn` alone kept both languages 4/4; `findColumns` then `createColumn` kept both 0/4.+//+// This path matters MORE than the table one, not less: it is the table-REUSE branch, i.e. adding a+// column to a table that already exists — which is exactly the scenario AB#6686428 was reported+// against ("adding a table to an existing app"). A fresh-table build never reaches it, which is why+// the first round of this fix missed it and why the end-to-end verification did not catch it.+//+// The projection deliberately matches `readAttributeRequiredLevels` below, so the rows still answer+// `columnRequiredLevel`.+//+// ON THE FAILURE PATH, and this is the subtle part: when the raw client is PRESENT but the read+// fails or returns a non-2xx, we return `[]` rather than falling back to `findColumns`. Falling back+// would re-introduce the exact poisoning this function exists to remove, silently, on the very+// branch it targets — `createColumn` is guaranteed to run here for every column that looks new. An+// empty list instead makes every column look new, and `createColumn`'s `skipIf: isAlreadyExists`+// de-duplicates the ones that already exist WITHOUT a poisoning pre-read. The cost is that the+// required/capability reconcile degrades to best-effort for this table, which is the same+// degradation a `readAttributeRequiredLevels` failure already produces — and it is warned about,+// because a silent degradation is what this whole line of fixes is about.+//+// `findColumns` is therefore reserved for the one case where it cannot poison anything: no raw+// client at all, which in practice means a unit-test double.+async function findExistingColumns(provision, logical, warn) {+ const raw = provision && provision.dataverse;+ if (raw && typeof raw.get === 'function') {+ let res = null;+ let err = null;+ try {+ res = await raw.get(`/EntityDefinitions(LogicalName='${odataLit(logical)}')/Attributes?$select=LogicalName,RequiredLevel`);+ } catch (e) { err = e; }+ if (res && res.status >= 200 && res.status < 300 && res.body && Array.isArray(res.body.value)) {+ return res.body.value.map((a) => ({ logicalName: String(a.LogicalName || '').toLowerCase(), RequiredLevel: a.RequiredLevel }));+ }+ const why = err ? ((err && err.message) || String(err)) : `HTTP ${res && res.status}`;+ if (typeof warn === 'function') {+ warn(`could not read existing columns for ${logical} (${why}) — treating every declared column as new. `+ + 'Existing ones are de-duplicated by the create\'s already-exists handling; required-level reconciliation '+ + 'is skipped for this table this run.');+ }+ return [];+ }+ if (typeof (provision && provision.findColumns) !== 'function') return [];+ return (await provision.findColumns(logical)) || [];+}++// Does a relationship with this schema name already exist on the entity?+//+// A NARROW relationship read, for the third time and the same measured reason: the plugin used to+// answer this with `provision.fetchEntityMetadata(...)`, and any broad metadata read immediately+// before a labelled create makes Dataverse store ONLY the base-language label. Order-controlled+// (C,F,F,C): `createRelationship` alone kept a bilingual `lookupDisplayName` 2/2;+// `fetchEntityMetadata` then `createRelationship` kept it 0/2.+//+// `$select=SchemaName` on the relationship collection is the smallest question that answers this.+// Falls back to `fetchEntityMetadata` when the raw client is unavailable (unit-test doubles).+//+// Returns `true`/`false`, or `null` when it genuinely could not tell — the caller treats null the+// way the old `catch {}` did (assume absent and let the create's own already-exists handling deal+// with it), because a table created moments ago legitimately 404s here.+//+// `hasLocalizedLabels` closes the same hole `findExistingTable` documents, for the same reason and+// with the same rule. `fetchEntityMetadata` → `createRelationship` is one of the three broad-read →+// create pairs that makes Dataverse keep ONLY the base-language label (AB#6686428), so falling back+// to it after an inconclusive narrow probe would silently reintroduce the bug on a transient 5xx —+// invisibly, because the request body is byte-identical either way and the relationship is still+// created. For a localized lookup label the fallback is therefore skipped and `null` is returned:+// "assume absent" costs at most a redundant create that already-exists handling absorbs, whereas the+// poisoning read costs a label nobody can see is wrong until a user switches language.+// A relationship with a plain-string label keeps the fallback exactly as before.+async function relationshipExists(provision, entityLogical, schemaName, type, { hasLocalizedLabels = false } = {}) {+ const collection = type === 'ManyToMany' ? 'ManyToManyRelationships' : 'OneToManyRelationships';+ const raw = provision && provision.dataverse;+ if (raw && typeof raw.get === 'function') {+ try {+ const res = await raw.get(`/EntityDefinitions(LogicalName='${odataLit(entityLogical)}')/${collection}?$select=SchemaName`);+ if (res && res.status >= 200 && res.status < 300 && res.body && Array.isArray(res.body.value)) {+ return res.body.value.some((r) => String(r.SchemaName || '').toLowerCase() === String(schemaName).toLowerCase());+ }+ if (res && res.status === 404) return false;+ } catch { /* fall through */ }+ // Inconclusive AND localized: never resolve it with the broad read.+ if (hasLocalizedLabels) return null;+ }+ if (typeof (provision && provision.fetchEntityMetadata) !== 'function') return null;+ try {+ const meta = await provision.fetchEntityMetadata(entityLogical);+ return ((meta && meta.relationships) || []).some((r) => String(r.schemaName || '').toLowerCase() === String(schemaName).toLowerCase());+ } catch {+ return null;+ }+}+async function readAttributeRequiredLevels({ sdk, provision, logical }) {const client = (provision && provision.dataverse) || (sdk && sdk.dataverse);if (!client || typeof client.get !== 'function') return new Map();@@ -516,6 +680,72 @@ async function resolveAuthoringLanguage({ envUrl, languageCode, spec, warn, read// Discover-then-create global choices, tables, columns, status reasons, alternate keys,// and relationships (idempotent). Returns captured maps used by sample data + later phases.+// Does this table already exist? Returns { logicalName, entitySetName } or null.+//+// Deliberately a NARROW `EntityDefinitions(LogicalName=…)` read rather than the SDK's `findTables`,+// and this is a correctness requirement rather than an optimisation. LIVE-MEASURED, order-controlled+// (8 tables, sequence C,F,F,C,C,F,F,C so each arm appears early and late): calling `findTables`+// before `createTable` makes Dataverse store ONLY the base-language label of a multi-language name —+// `create only` kept both languages 4/4, `findTables + create` kept both 0/4. The outgoing+// EntityDefinitions body is byte-identical in both cases, so the loss is caused by the preceding+// unfiltered metadata read, not by the create payload.+//+// Without this the localized-label feature silently degrades to English-only on the real build path+// while every unit test (which never issues the preceding read) passes — the exact silent-drop class+// of failure AB#6686428 exists to end.+//+// `dataverse.get` RESOLVES with `{ status }` on a 404 instead of throwing, so the status is checked+// explicitly. Falls back to `findTables` when the raw client is unavailable (older callers and+// unit-test doubles) or when the narrow read is INCONCLUSIVE — with one exception, below.+//+// `hasLocalizedLabels` closes the gap that fallback would otherwise leave open. `findTables` can+// safely prove PRESENCE (a hit means we reuse the table and no create follows, so nothing is+// poisoned), but a MISS is followed immediately by `createTable` — with the poisoning read already+// on the wire. So for an entity whose labels ARE localized, an inconclusive probe is never resolved+// by `findTables`: the narrow read is retried, and if it stays inconclusive the build HALTS rather+// than silently shipping an English-only table. Same fail-closed rule as the unprovisioned-language+// check above, and for the same reason: by the time a warning is read the table already exists, and+// fixing a label after the fact is a manual job.+async function findExistingTable(provision, schemaName, { hasLocalizedLabels = false, attempts = 3 } = {}) {+ const logical = String(schemaName).toLowerCase();+ const raw = provision && provision.dataverse;+ if (raw && typeof raw.get === 'function') {+ const escaped = logical.replace(/'/g, "''");+ const url = `/EntityDefinitions(LogicalName='${escaped}')?$select=LogicalName,EntitySetName`;+ // Retried only for a LOCALIZED entity, where the alternative to a conclusive answer is a halt.+ // For everything else one attempt then `findTables` is both cheaper and exactly the old+ // behaviour.+ const tries = hasLocalizedLabels ? Math.max(1, attempts) : 1;+ let lastWhy = 'unknown';+ for (let i = 0; i < tries; i += 1) {+ // Wrapped like its `findExistingColumns` sibling. The client resolves `{status}` for a 404 and+ // even a persistent 5xx, and throws only on a persistent TRANSPORT error; letting that+ // propagate here would abort the build on a blip the fallback might well survive.+ let res = null;+ try { res = await raw.get(url); } catch (err) { res = null; lastWhy = (err && err.message) || String(err); }+ if (res && res.status >= 200 && res.status < 300 && res.body && res.body.LogicalName) {+ return { logicalName: String(res.body.LogicalName).toLowerCase(), entitySetName: res.body.EntitySetName };+ }+ if (res && res.status === 404) return null;+ if (res) lastWhy = `HTTP ${res.status}${res.body && res.body.LogicalName === undefined && res.status < 300 ? ' with no LogicalName in the body' : ''}`;+ }+ if (hasLocalizedLabels) {+ throw new BuildHalt(+ `could not determine whether table '${logical}' already exists (${lastWhy}), and its labels are localized. `+ + 'Resolving this by the broad metadata read the build normally falls back to is what makes Dataverse store '+ + 'ONLY the base-language label (live-measured, 0/4 vs 4/4), so the build stops here instead of silently '+ + 'creating an English-only table. Re-run once the environment answers metadata reads.',+ { phase: 'data-model', code: 'table-probe-inconclusive', recoverable: true },+ );+ }+ // Any other status is inconclusive — fall through to findTables rather than assume "absent",+ // because assuming absent turns a transient read failure into a duplicate-create attempt.+ }+ if (typeof (provision && provision.findTables) !== 'function') return null;+ const hits = await provision.findTables(schemaName, { top: 50 });+ return (hits || []).find((t) => t.logicalName === logical) || null;+}+async function provisionDataModel({ sdk, provision, runner, spec, apply, languageCode, warn, provisionedLanguages, preResolvedLanguageCode }) {const result = { entities: {}, globalChoiceIds: {}, statusReasonValues: {}, columns: {}, relationships: [] };// The CLI resolves the authoring LCID BEFORE constructing the SDK, because@@ -527,6 +757,11 @@ async function provisionDataModel({ sdk, provision, runner, spec, apply, languagconst resolvedLanguageCode = preResolvedLanguageCode|| await resolveLanguageCode({ provision, spec, languageCode, warn, provisionedLanguages });+ // Before any write: refuse a localized label naming a language this org has not provisioned.+ // Dataverse would accept it and silently keep only the provisioned label (live-measured), so this+ // must run ahead of the first createTable rather than as a post-hoc verify.+ await checkLocalizedLabelLanguages(spec, provisionedLanguages);+const globalChoiceIds = result.globalChoiceIds;const statusReasonValues = result.statusReasonValues;@@ -547,18 +782,41 @@ async function provisionDataModel({ sdk, provision, runner, spec, apply, languag// 2b. Tables -> columns (all types + customer) -> status reasons -> alternate keys.for (const e of spec.entities) {const logical = e.schemaName.toLowerCase();- const hits = await provision.findTables(e.schemaName, { top: 50 });- const existingTable = (hits || []).find((t) => t.logicalName === logical);+ // Whether THIS entity carries any localized label. It decides whether an inconclusive existence+ // probe may be resolved by the broad `findTables` read — safe for a plain-label entity, poisoning+ // for a localized one. See findExistingTable.+ const entityIsLocalized = localizedLabelLcidsInSpec({ entities: [e] }).length > 0;+ const hits = await findExistingTable(provision, e.schemaName, { hasLocalizedLabels: entityIsLocalized });+ const existingTable = hits;let existingCols = new Set();let existingColRows = [];if (existingTable) {runner.skip('data-model', `table ${e.schemaName} (exists — reuse)`);result.entities[e.schemaName] = { logicalName: logical, entitySetName: existingTable.entitySetName };- existingColRows = (await provision.findColumns(logical)) || [];+ existingColRows = await findExistingColumns(provision, logical, warn);existingCols = new Set(existingColRows.map((c) => String(c.logicalName || c.schemaName || '').toLowerCase()));} else {await runner.run('data-model', `table ${e.schemaName}`, async () => {- const createOpts = { schemaName: e.schemaName, displayName: e.displayName, pluralName: e.pluralName || `${e.displayName}s`,+ // `displayName` / `pluralName` / `primaryColumnDisplayName` are passed THROUGH unflattened: a+ // plain string emits one label at `resolvedLanguageCode`, and an LCID map emits one per+ // language (AB#6686428 — measured on the wire against the vendored bundle). The English+ // plural fallback is only reachable for a STRING displayName; validateAppSpec requires an+ // explicit `pluralName` beside a localized one, because appending "s" is not a plural rule+ // outside English and would write "Línea base del proyectos" into Dataverse.+ //+ // The schema-name fallback is NOT cosmetic. `displayName` is optional in the App Spec — the+ // validator accepts an omitted or blank one, exactly as it does for a column — and every+ // other create site here already falls back (`c.displayName || c.schemaName` for columns,+ // customer columns and alternate keys). The table was the one that did not, and handing the+ // SDK `undefined` throws inside its label builder with `Cannot convert undefined or null to+ // object` BEFORE any request is issued — an opaque failure with nothing naming the table or+ // the field. MEASURED against the real vendored bundle; `''` gets past it but would label the+ // table blank. A localized MAP must pass through untouched, so it is never routed through+ // `labelText`, which would flatten it to one language.+ const tableDisplayName = isLocalizedLabelMap(e.displayName)+ ? e.displayName+ : (labelText(e.displayName, resolvedLanguageCode) || e.schemaName);+ const createOpts = { schemaName: e.schemaName, displayName: tableDisplayName, pluralName: e.pluralName || `${labelText(tableDisplayName, resolvedLanguageCode) || e.schemaName}s`,primaryColumnSchemaName: e.primaryAttribute.schemaName, primaryColumnDisplayName: e.primaryAttribute.displayName || 'Name', hasNotes: e.hasNotes === true, languageCode: resolvedLanguageCode };// AutoNumber the primary/title column when requested (the order number IS the identity).if (e.primaryAttribute.autoNumberFormat) createOpts.primaryColumnAutoNumberFormat = e.primaryAttribute.autoNumberFormat;@@ -571,9 +829,9 @@ async function provisionDataModel({ sdk, provision, runner, spec, apply, languag} catch (err) {if (!isAlreadyExists(err)) throw err;// First POST likely succeeded server-side; a transient-network retry hit "already exists".- // Rediscover to capture entitySetName (required by later phases).- const rehits = await provision.findTables(e.schemaName, { top: 50 });- const found = (rehits || []).find((x) => x.logicalName === logical);+ // Rediscover to capture entitySetName (required by later phases). No poisoning concern+ // here whatever the labels are — the table now EXISTS, so no create follows this read.+ const found = await findExistingTable(provision, e.schemaName);if (!found) throw err;result.entities[e.schemaName] = { logicalName: logical, entitySetName: found.entitySetName };}@@ -769,9 +1027,13 @@ async function provisionDataModel({ sdk, provision, runner, spec, apply, languagfor (const rel of spec.relationships || []) {if (rel.type === 'OneToMany') {const schema = relationshipSchemaName(rel, publisherPrefix);- let exists = false;- try { exists = ((await provision.fetchEntityMetadata(rel.referenced.toLowerCase())).relationships || []).some((r) => r.schemaName.toLowerCase() === schema.toLowerCase()); } catch { /* just created */ }- if (exists) { runner.skip('data-model', `relationship ${schema} (exists)`); continue; }+ // `null` (could not tell) is treated as absent, exactly as the previous `catch {}` did: a table+ // created moments earlier legitimately 404s here, and the create's own already-exists handling+ // covers the race. A localized lookup label suppresses the broad-read fallback inside the+ // probe — see relationshipExists.+ const exists = await relationshipExists(provision, rel.referenced.toLowerCase(), schema, 'OneToMany',+ { hasLocalizedLabels: localizedLabelLcids(rel.lookup && rel.lookup.displayName).length > 0 });+ if (exists === true) { runner.skip('data-model', `relationship ${schema} (exists)`); continue; }await runner.run('data-model', `relationship 1:N ${rel.referenced}->${rel.referencing}`, async () => {const res = await sdk.createRelationship({ type: 'OneToMany', schemaName: schema, referencedEntity: rel.referenced.toLowerCase(), referencingEntity: rel.referencing.toLowerCase(), lookupSchemaName: rel.lookup.schemaName, lookupDisplayName: rel.lookup.displayName, languageCode: resolvedLanguageCode });result.relationships.push({@@ -783,9 +1045,8 @@ async function provisionDataModel({ sdk, provision, runner, spec, apply, languag}, { skipIf: isAlreadyExists });} else if (rel.type === 'ManyToMany') {const schema = manyToManySchemaName(rel, publisherPrefix);- let exists = false;- try { exists = ((await provision.fetchEntityMetadata(rel.entity1.toLowerCase())).relationships || []).some((r) => r.schemaName.toLowerCase() === schema.toLowerCase()); } catch { /* just created */ }- if (exists) { runner.skip('data-model', `relationship ${schema} (exists)`); continue; }+ const exists = await relationshipExists(provision, rel.entity1.toLowerCase(), schema, 'ManyToMany');+ if (exists === true) { runner.skip('data-model', `relationship ${schema} (exists)`); continue; }await runner.run('data-model', `relationship N:N ${rel.entity1}<->${rel.entity2}`, async () => {const res = await sdk.createRelationship({ type: 'ManyToMany', schemaName: schema, entity1: rel.entity1.toLowerCase(), entity2: rel.entity2.toLowerCase(), intersectEntityName: rel.intersectEntityName, languageCode: resolvedLanguageCode });result.relationships.push({@@ -932,4 +1193,4 @@ async function provisionSampleData({ sdk, provision, runner, spec, dataModel })return { records: result.records, entitySetFor };}-module.exports = { makeRunner, requireSuccessfulPush, reportPartialPush, errorCodeChain, makeEntitySetResolver, resolveLanguageCode, resolveAuthoringLanguage, provisionSolution, provisionDataModel, provisionSampleData, buildSeedGroup, BuildHalt, SDK_COLUMN_TYPE, isVisualizationUnsupported };+module.exports = { makeRunner, requireSuccessfulPush, reportPartialPush, errorCodeChain, makeEntitySetResolver, resolveLanguageCode, resolveAuthoringLanguage, provisionSolution, provisionDataModel, provisionSampleData, buildSeedGroup, BuildHalt, SDK_COLUMN_TYPE, isVisualizationUnsupported, localizedLabelLcidsInSpec, checkLocalizedLabelLanguages };diff --git a/plugins/model-apps/scripts/lib/form-preview.js b/plugins/model-apps/scripts/lib/form-preview.jsindex ec7a1daf5..193c7517f 100644--- a/plugins/model-apps/scripts/lib/form-preview.js+++ b/plugins/model-apps/scripts/lib/form-preview.js@@ -5,6 +5,7 @@// interactive authoring turn before approving it. Pure (no I/O); the CLI is preview-form.js.const { compileFormIntent } = require('./artifact-intent.js');const { entityByLogical } = require('./_graph.js');+const { labelText } = require('./app-spec.js');const INNER = 63; // content width inside the box borders@@ -63,19 +64,19 @@ const BOTTOM = `└${'─'.repeat(INNER + 2)}┘`;// Display label for a field logical name. compileFormIntent emits push-ready cells that OMIT the// label (the SDK adapter derives it from attribute metadata at push, per T4), so the preview// resolves the display name itself from the spec entity (falling back to the logical name).-function labelFor(entity, fn) {+function labelFor(entity, fn, lang) {if (!entity) return fn;- if (entity.primaryAttribute && entity.primaryAttribute.schemaName.toLowerCase() === fn) return entity.primaryAttribute.displayName || 'Name';+ if (entity.primaryAttribute && entity.primaryAttribute.schemaName.toLowerCase() === fn) return labelText(entity.primaryAttribute.displayName, lang) || 'Name';const c = (entity.columns || []).find((x) => x.schemaName.toLowerCase() === fn);- return (c && (c.displayName || c.schemaName)) || fn;+ return (c && (labelText(c.displayName, lang) || c.schemaName)) || fn;}// "Label * [widget]" for one field cell.-function fieldLabel(entity, cell) {+function fieldLabel(entity, cell, lang) {const fn = cell.control.fieldName;const req = cell.control.isRequired ? ' *' : '';const widget = WIDGET[fieldType(entity, fn)] || WIDGET.Text;- return `${cell.control.label || labelFor(entity, fn)}${req} ${widget}`;+ return `${cell.control.label || labelFor(entity, fn, lang)}${req} ${widget}`;}// Render one form to an ASCII wireframe string.@@ -111,7 +112,7 @@ function renderFormWireframe(spec, f) {const cells = (r.cells || []).filter((c) => c.control && c.control.fieldName);if (!cells.length) continue;const colW = Math.floor((INNER - 3) / Math.max(1, cells.length));- const parts = cells.map((c) => vpad(clip(` ${fieldLabel(entity, c)}`, colW), colW));+ const parts = cells.map((c) => vpad(clip(` ${fieldLabel(entity, c, spec && spec.languageCode)}`, colW), colW));lines.push(row(parts.join('')));}}diff --git a/plugins/model-apps/scripts/lib/hydrate-spec.js b/plugins/model-apps/scripts/lib/hydrate-spec.jsindex 86eb8540f..c1a86375f 100644--- a/plugins/model-apps/scripts/lib/hydrate-spec.js+++ b/plugins/model-apps/scripts/lib/hydrate-spec.js@@ -208,14 +208,24 @@ async function hydrateSpec(read) {entities,webResources,views: [],- // NOT yet round-tripped (documented limitation): views, charts, forms, and commands. VIEWS were+ // NOT reconstructed (documented limitation): views, charts, forms, and commands. VIEWS were// tried (F3) but reverted — the deployed savedquery set can't reliably distinguish app-builder-// authored views from Dataverse's auto-generated Active/Inactive/QuickFind/Lookup/AdvancedFind// system views (LIVE-verified: `isdefault` marks the AUTHORED primary "Active" view TRUE and the// SYSTEM "Inactive" view FALSE, so no `isdefault`/`querytype` filter isolates author views — it// grabbed the wrong one). Charts/forms/commands also need structured reads the SDK doesn't expose.- // All four 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. See download docs / app-builder-capabilities.+ //+ // FORMS specifically stay out even though the SDK now exposes `formTypes` on its form listing:+ // listing them was never the blocker. The App Spec form shape cannot express everything a+ // deployed `formxml` carries (header/footer, business-process control, related-entity nav,+ // control parameters, event libraries), so a reconstruction would be lossy — and a lossy form+ // declared in the spec is worse than an absent one, because rebuilding into a FRESH environment+ // would recreate a form that silently lost those controls while reporting success.+ //+ // All four survive on the live app — a rebuild into the SAME environment preserves them — but are+ // absent from the downloaded spec, so edit them in Maker or a fresh spec. This is no longer+ // silent: every deployed form/view/chart is listed in `descriptionInventory` below, and+ // `download-model-app` reports the omission by class and table on every run (AB#6686423).charts: [],forms: [],commands: [],diff --git a/plugins/model-apps/scripts/lib/phase-diff.js b/plugins/model-apps/scripts/lib/phase-diff.jsindex 774f1427a..e050c9820 100644--- a/plugins/model-apps/scripts/lib/phase-diff.js+++ b/plugins/model-apps/scripts/lib/phase-diff.js@@ -38,10 +38,13 @@ const PHASE_SLICES = {'app-shell': (s) => ({ app: s.app, appShell: s.appShell }),pages: (s) => s.pages,'ai-features': (s) => s.ai,- // security consumes personas[]. It has no safe partial-apply path yet (a persona change must- // re-author roles + reconcile app associations), so a change here forces a FULL build via+ // security consumes personas[] AND roleGrants[]. Both must be here: with only `personas`, a spec+ // whose ONLY change was adding a roleGrant diffed as "nothing changed", so `--changed-only`+ // reported "deployed app already matches the spec" and never called AddPrivilegesRole — the table+ // deployed and the role still had no access to it, which is the exact bug roleGrants[] fixes.+ // Neither has a safe partial-apply path yet, so a change here forces a FULL build via// FULL_BUILD_PHASES in classify-changes.js — never a silent changed-only no-op.- security: (s) => s.personas,+ security: (s) => ({ personas: s.personas, roleGrants: s.roleGrants }),};// Deterministic, key-order-independent JSON so a reordered-but-equal slice compares equal. Arrays keepdiff --git a/plugins/model-apps/scripts/lib/provision-input.js b/plugins/model-apps/scripts/lib/provision-input.jsindex fa4afaea0..235ddad52 100644--- a/plugins/model-apps/scripts/lib/provision-input.js+++ b/plugins/model-apps/scripts/lib/provision-input.js@@ -5,7 +5,7 @@// App-Spec subset: { solution, entities, relationships, globalChoices?, sampleData? }.// Entities carry FULL schema names (e.g. cr_candidate), not bare suffixes.-const { TYPE_MAP, normalizeLanguageCode, ENTITY_KEYS, ENTITY_KEY_HINTS, invalidLanguageCodeMessage } = require('./app-spec.js');+const { TYPE_MAP, normalizeLanguageCode, validateLabel, validateChoiceOptionLabels, isLocalizedLabelMap, labelIsMissing, rejectLocalizedGlobalChoice, ENTITY_KEYS, ENTITY_KEY_HINTS, invalidLanguageCodeMessage } = require('./app-spec.js');// Validates provision-entities input. Returns { ok, errors }.function validateProvisionInput(input) {@@ -109,6 +109,23 @@ function validateProvisionInput(input) {entityByLower.set(e.schemaName.toLowerCase(), e);+ // Localized labels are validated HERE too, with the SHARED validator, not only in+ // `validateAppSpec`. This input is a documented App Spec subset and `provision-entities.js` is a+ // SEPARATE entry point whose only gate is this function — so without these lines a per-LCID label+ // with a language tag key, or a localized displayName with no pluralName, returned ok:true and+ // reached `createTable`, where the tag key throws mid-build and the missing plural is derived by+ // appending "s" to one language. The solution is provisioned BEFORE the data model, so the+ // failure would land after a write. Same reasoning as sharing ENTITY_KEYS: two entry points that+ // disagree about what a label IS teach the author two different rules for one field.+ validateLabel(e.displayName, `entity '${e.schemaName}': displayName`, errors, { baseLanguageCode: input.languageCode });+ validateLabel(e.pluralName, `entity '${e.schemaName}': pluralName`, errors, { baseLanguageCode: input.languageCode });+ if (isLocalizedLabelMap(e.displayName) && labelIsMissing(e.pluralName)) {+ errors.push(`entity '${e.schemaName}': pluralName is required when displayName is a localized label — the plural cannot be derived by appending "s" in every language`);+ }+ if (e.primaryAttribute && typeof e.primaryAttribute === 'object') {+ validateLabel(e.primaryAttribute.displayName, `entity '${e.schemaName}': primaryAttribute.displayName`, errors, { baseLanguageCode: input.languageCode });+ }+// Validate primaryAttributeif (!e.primaryAttribute || typeof e.primaryAttribute !== 'object') {errors.push(`entity '${e.schemaName}': primaryAttribute is required and must be an object`);@@ -136,8 +153,21 @@ function validateProvisionInput(input) {if ((c.type === 'Choice' || c.type === 'MultiChoice') && !(Array.isArray(c.options) && c.options.length) && !c.globalChoice) {errors.push(`entity '${e.schemaName}': column '${c.schemaName}' (${c.type}) needs options[] or a globalChoice reference`);}+ validateLabel(c.displayName, `entity '${e.schemaName}': column '${c.schemaName || ''}' displayName`, errors, { baseLanguageCode: input.languageCode });+ validateChoiceOptionLabels(c.options, `entity '${e.schemaName}': column '${c.schemaName || ''}'`, errors, { baseLanguageCode: input.languageCode });}}++ // `alternateKeys[].displayName` is a label too, and it reaches `createAlternateKey` from THIS+ // entry point. Omitting it here left `{"es-ES": "Clave"}` returning ok:true and throwing+ // "localized label key 'es-ES' is not an LCID" mid-provision — after the solution and tables are+ // already written. `validateAppSpec` has always covered it; the two gates must not disagree.+ if (Array.isArray(e.alternateKeys)) {+ e.alternateKeys.forEach((k, i) => {+ if (!k || typeof k !== 'object') return;+ validateLabel(k.displayName, `entity '${e.schemaName}': alternateKeys[${i}] displayName`, errors, { baseLanguageCode: input.languageCode });+ });+ }}// Relationships validation@@ -176,6 +206,12 @@ function validateProvisionInput(input) {} else if (!r.lookup.schemaName || typeof r.lookup.schemaName !== 'string') {errors.push('OneToMany relationship: lookup.schemaName is required');}+ // The lookup COLUMN's label, same reasoning as the alternate-key label above: it is passed+ // straight to `createRelationship` from this entry point, and a language-tag key throws+ // there rather than here.+ if (r.lookup && typeof r.lookup === 'object') {+ validateLabel(r.lookup.displayName, `OneToMany relationship (${r.lookup.schemaName || '?'}): lookup.displayName`, errors, { baseLanguageCode: input.languageCode });+ }}// Validate ManyToMany relationships@@ -213,6 +249,12 @@ function validateProvisionInput(input) {if (!Array.isArray(g.options) || g.options.length === 0) {errors.push(`globalChoice '${g.name || ''}': options must be a non-empty array`);}+ validateLabel(g.displayName, `globalChoice '${g.name || ''}': displayName`, errors, { baseLanguageCode: input.languageCode });+ validateChoiceOptionLabels(g.options, `globalChoice '${g.name || ''}'`, errors, { baseLanguageCode: input.languageCode });+ // Same rejection as validateAppSpec, from the same shared helper: Dataverse stores only the+ // base language for a global option set and reports nothing. Two entry points that disagree+ // about what a label IS is the whole reason these gates share their validators.+ rejectLocalizedGlobalChoice(g, `globalChoice '${g.name || ''}'`, errors);}}}diff --git a/plugins/model-apps/scripts/lib/role-privileges.js b/plugins/model-apps/scripts/lib/role-privileges.jsindex f5584dc72..549548eb0 100644--- a/plugins/model-apps/scripts/lib/role-privileges.js+++ b/plugins/model-apps/scripts/lib/role-privileges.js@@ -25,7 +25,12 @@const SCOPE_DEPTH = { user: 'Basic', businessUnit: 'Local', parentChild: 'Deep', organization: 'Global' };const DEPTH_RANK = { basic: 1, local: 2, deep: 3, global: 4 };// App Spec access token -> Dataverse PrivilegeType, again mirroring the SDK.-const ACCESS_TYPE = { read: 'Read', create: 'Create', write: 'Write', delete: 'Delete', append: 'Append', appendTo: 'AppendTo', assign: 'Assign', share: 'Share' };+// KEYS ARE LOWERCASE because the lookup lowercases (`ACCESS_TYPE[d.access.toLowerCase()]`). The+// camelCase `appendTo` spelling the App Spec uses therefore has to appear here as `appendto`; keying+// it `appendTo` made the lookup return undefined and reported every declared appendTo privilege as+// "'<entity>' exposes no 'appendTo' privilege" — a false failure on a correctly granted role, which+// is the cry-wolf outcome this whole check exists to avoid.+const ACCESS_TYPE = { read: 'Read', create: 'Create', write: 'Write', delete: 'Delete', append: 'Append', appendto: 'AppendTo', assign: 'Assign', share: 'Share' };const rankOf = (depth) => DEPTH_RANK[String(depth == null ? '' : depth).trim().toLowerCase()] || 0;diff --git a/plugins/model-apps/scripts/lib/schema-facts.js b/plugins/model-apps/scripts/lib/schema-facts.jsindex 6b8cead65..c4f80c6e7 100644--- a/plugins/model-apps/scripts/lib/schema-facts.js+++ b/plugins/model-apps/scripts/lib/schema-facts.js@@ -6,7 +6,7 @@// offline eval harness diffs per build. Pure (no I/O, no SDK): it derives everything deterministically// from the App Spec, reusing the SAME naming/value rules the engine uses, so a fact equals what WOULD// be provisioned — not a naive spec echo. See docs/app-builder-design.md §13.2, §14.-const { columnTypeMap, choiceValueMap, relationshipSchemaName, manyToManySchemaName, quickCreateEnabledFor } = require('./app-spec.js');+const { columnTypeMap, choiceValueMap, relationshipSchemaName, manyToManySchemaName, quickCreateEnabledFor, labelText } = require('./app-spec.js');const lc = (s) => String(s || '').toLowerCase();const byKey = (k) => (a, b) => (a[k] < b[k] ? -1 : a[k] > b[k] ? 1 : 0);@@ -21,11 +21,23 @@ function isBuildableColumn(c) {// Choice/MultiChoice { value, label } pairs via the engine's shared rule (value = 100000000 + index;// inline options AND globalChoice refs) so the fact carries the exact values the build assigns-// (app-spec.js choiceValueMap:35-55). Sorted by value (its natural, stable order).+// (app-spec.js choiceValueMap). Sorted by value (its natural, stable order).+//+// `choiceValueMap` indexes a LOCALIZED option under every language it declares (so sample data in+// either language resolves), which means several keys can share one value. An eval fact must carry+// ONE label per value, so collapse to the FIRST alias seen.+//+// That resolves to the lowest-LCID label — but NOT because of V8's integer-key ordering, which does+// not apply here: this map is keyed by label STRINGS, so it enumerates in INSERTION order. The+// ascending-LCID property comes from `labelAliases`, which emits a localized label's values in LCID+// order (that is where the integer-key rule applies), combined with `choiceValueMap` being+// first-wins. Change either of those and the winning label changes.function choiceFacts(entity, spec, columnLogical) {const map = choiceValueMap(entity, spec)[columnLogical];if (!map) return undefined;- return Object.entries(map).map(([label, value]) => ({ value, label })).sort((a, b) => a.value - b.value);+ const byValue = new Map();+ for (const [label, value] of Object.entries(map)) if (!byValue.has(value)) byValue.set(value, label);+ return [...byValue.entries()].map(([value, label]) => ({ value, label })).sort((a, b) => a.value - b.value);}function tableFacts(spec, e) {@@ -39,13 +51,13 @@ function tableFacts(spec, e) {}).sort(byKey('logicalName'));return {logicalName: lc(e.schemaName),- displayName: e.displayName || '',+ displayName: labelText(e.displayName, spec && spec.languageCode) || '',hasNotes: e.hasNotes === true,// Whether the build enables "Allow quick create" (IsQuickCreateEnabled) on this table — the EXACT// engine rule (explicit entities[].quickCreate OR an authored QuickCreate form), so the eval grades// provisioned intent, not a naive spec echo. See entity-provision.js updateTable step.quickCreate: quickCreateEnabledFor(spec, e),- primary: { logicalName: lc(primary.schemaName), displayName: primary.displayName || '', autoNumber: !!primary.autoNumberFormat },+ primary: { logicalName: lc(primary.schemaName), displayName: labelText(primary.displayName, spec && spec.languageCode) || '', autoNumber: !!primary.autoNumberFormat },columns,statusReasons: (e.statusReasons || []).map((sr) => ({ label: sr.label, state: sr.state || 'Active' })).sort(byKey('label')),alternateKeys: (e.alternateKeys || []).map((k) => ({ logicalName: lc(k.schemaName), columns: (k.columns || []).map(lc).sort() })).sort(byKey('logicalName')),@@ -58,7 +70,7 @@ function relationshipFacts(spec) {for (const r of spec.relationships || []) {if (r.type === 'OneToMany') {rels.push({ kind: '1:n', schemaName: lc(relationshipSchemaName(r, prefix)), referenced: lc(r.referenced), referencing: lc(r.referencing),- lookup: { logicalName: lc(r.lookup && r.lookup.schemaName), displayName: (r.lookup && r.lookup.displayName) || '' } });+ lookup: { logicalName: lc(r.lookup && r.lookup.schemaName), displayName: labelText(r.lookup && r.lookup.displayName, spec && spec.languageCode) || '' } });} else if (r.type === 'ManyToMany') {const fact = { kind: 'n:n', schemaName: lc(manyToManySchemaName(r, prefix)), entity1: lc(r.entity1), entity2: lc(r.entity2) };if (r.intersectEntityName) fact.intersect = lc(r.intersectEntityName);@@ -73,7 +85,7 @@ function relationshipFacts(spec) {function schemaFacts(spec) {const s = spec || {};return {- globalChoices: (s.globalChoices || []).map((g) => ({ name: lc(g.name), options: (g.options || []).map((label, i) => ({ value: 100000000 + i, label })) })).sort(byKey('name')),+ globalChoices: (s.globalChoices || []).map((g) => ({ name: lc(g.name), options: (g.options || []).map((label, i) => ({ value: 100000000 + i, label: labelText(label, s.languageCode) || '' })) })).sort(byKey('name')),tables: (s.entities || []).map((e) => tableFacts(s, e)).sort(byKey('logicalName')),relationships: relationshipFacts(s),};diff --git a/plugins/model-apps/scripts/lib/sdk-build.js b/plugins/model-apps/scripts/lib/sdk-build.jsindex 93eab4090..267205e0f 100644--- a/plugins/model-apps/scripts/lib/sdk-build.js+++ b/plugins/model-apps/scripts/lib/sdk-build.js@@ -35,6 +35,9 @@ const {canonicalPersonaName,BUSINESS_RULE_VALUELESS_OPERATORS,bpfUniqueName,+ labelText,+ choiceValueMap,+ BPF_ROLE_ACCESS,} = require('./app-spec.js');const { PHASES } = require('./stages.js');const { topoOrderEntities, entityByLogical } = require('./_graph.js');@@ -74,7 +77,7 @@ 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, featureWantValue, sameSettingValue, resolveAppModuleId, proveAppOverride } = require('./ai-app-settings.js');+const { AI_APP_SETTING, resolveAiFlags, specOptsIntoAi, featureWantValue, sameSettingValue, resolveAppModuleId, proveAppOverride } = require('./ai-app-settings.js');const { buildPromptSpec } = require('./ai-prompt.js');const { odataLit } = require('./odata.js');@@ -294,15 +297,21 @@ function resolvePhases({ only, skip, from, to } = {}) {// Resolve a view-filter value: a Choice/MultiChoice label becomes its option int; everything// else (raw ints, strings, ISO dates) passes through. No-value operators omit the value entirely.+//+// Resolution goes through `choiceValueMap`, the SHARED rule, rather than `options.indexOf(val)`.+// Two reasons, and the first is a real defect the naive version had: a LOCALIZED option is an+// object (`{ "1033": "Open", "3082": "Abierto" }`), so `indexOf("Abierto")` returns -1 and the+// LABEL was sent as the value of a numeric picklist condition — an invalid or silently ineffective+// view filter. The second is that `choiceValueMap` also resolves a column bound to a `globalChoice`,+// which the inline-only lookup never did.function resolveFilterValue(spec, entityLogical, attr, val) {if (typeof val !== 'string') return val;const e = entityByLogical(spec, entityLogical);const c = e && (e.columns || []).find((x) => x.schemaName.toLowerCase() === String(attr).toLowerCase());- if (c && (c.type === 'Choice' || c.type === 'MultiChoice') && Array.isArray(c.options)) {- const i = c.options.indexOf(val);- if (i >= 0) return 100000000 + i;- }- return val;+ if (!c || (c.type !== 'Choice' && c.type !== 'MultiChoice')) return val;+ const byLabel = choiceValueMap(e, spec)[String(c.schemaName).toLowerCase()];+ const hit = byLabel && byLabel[val];+ return typeof hit === 'number' ? hit : val;}function primaryNameOf(spec, logical) {@@ -331,7 +340,12 @@ function planFor(spec, opts) {if (has('data-model')) {for (const gc of spec.globalChoices || []) items.push({ phase: 'data-model', label: `global choice ${gc.name}` });for (const e of spec.entities) {- items.push({ phase: 'data-model', label: `table ${e.schemaName} ("${e.displayName}")` });+ // `labelText` returns "" for an absent displayName, or for a localized map with nothing usable+ // — which rendered a dry-run line as `table new_order ("")`, an empty quoted string the reader+ // has to decode. Fall back to the schema name, which is what the CREATE itself falls back to+ // (`displayName || schemaName`), so the plan says what the build will actually do.+ const shown = labelText(e.displayName, spec && spec.languageCode) || e.schemaName;+ items.push({ phase: 'data-model', label: `table ${e.schemaName} ("${shown}")` });if (quickCreateEnabledFor(spec, e)) items.push({ phase: 'data-model', label: `enable quick create on ${e.schemaName.toLowerCase()}` });for (const c of e.columns || []) {if (SDK_COLUMN_TYPE[c.type || 'Text'] || c.type === 'Customer') items.push({ phase: 'data-model', label: `column ${e.schemaName}.${c.schemaName} (${c.type || 'Text'})` });@@ -372,7 +386,7 @@ function planFor(spec, opts) {if (has('pages') && (spec.pages || []).length && appHasCrossPageNav(spec)) items.push({ phase: 'pages', label: 'resolve cross-page navigation' });if (has('pages') && (spec.pages || []).length) items.push({ phase: 'pages', label: `page manifest ${appUniqueName(spec)}_pagemanifest` });if (has('pages') && (spec.pages || []).length && appHasPageSubareas(spec)) items.push({ phase: 'pages', label: 'finalize sitemap (genpage subareas)' });- if (has('ai-features') && spec.ai !== undefined && spec.ai !== null) {+ if (has('ai-features') && specOptsIntoAi(spec)) {items.push({ phase: 'ai-features', label: 'enable app AI features' });// Do NOT short-circuit on `summaries.default === 'off'`. `selectSummaryTables` already implements// the documented semantics — `default` is the app-level DEFAULT and `tables[x].enabled: true` is@@ -386,11 +400,22 @@ function planFor(spec, opts) {const n = (p.jobs || []).length;items.push({ phase: 'security', label: `security role "${p.persona}" (${n} job${n === 1 ? '' : 's'})` });}+ // Role grants are planned after personas because they run after them (a grant on a role this spec+ // also authors is rejected at validation, but the ORDER still matters for reading the plan).+ if (has('security')) for (const g of spec.roleGrants || []) {+ const n = (g.privileges || []).length;+ items.push({ phase: 'security', label: `grant privileges on ${n} table${n === 1 ? '' : 's'} to existing role ${roleGrantLabel(g)}` });+ }// Form role assignment is planned under `security` (not `forms`) because it can only run once the// roles exist — see the 7b block in the engine for why.if (has('security')) for (const f of spec.forms || []) {if (f && f.securityRoles) items.push({ phase: 'security', label: `form roles for ${f.name || f.formType || 'Main'} on ${f.entity}` });}+ // Flow role grants are planned under `security` for the same reason form ones are: they target the+ // backing table ACTIVATION creates, and they need persona roles that do not exist until this phase.+ if (has('security')) for (const f of spec.businessProcessFlows || []) {+ if (f && f.securityRoles) items.push({ phase: 'security', label: `flow roles for ${f.name} (backing table ${bpfUniqueName(f.name)})` });+ }if (has('publish') && opts.publish) items.push({ phase: 'publish', label: 'publish customizations' });return items;}@@ -491,7 +516,11 @@ function defaultViewColumns(spec, entity, opts = {}) {function subgridLabel(spec, sg) {if (sg.label) return sg.label;const child = entityByLogical(spec, String(sg.childEntity || '').toLowerCase());- return (child && (child.pluralName || child.displayName)) || sg.childEntity;+ // Resolved through labelText: a LOCALIZED plural/display name is an object, and returning it here+ // put "[object Object]" into the form's section and control labels — and, because the form+ // projection stringifies for change detection, made two DIFFERENT localized labels hash the same.+ const lang = spec && spec.languageCode;+ return labelText(child && child.pluralName, lang) || labelText(child && child.displayName, lang) || sg.childEntity;}// True when a table has enough declared columns to make enriching its default views worthwhile// (opt out per-entity with enrichDefaultViews:false).@@ -1079,9 +1108,12 @@ async function ensureAppNotAvailableToRole(sdk, appId, roleId) {// Resolve the business unit a persona's role lives in, so role QUERIES (teardown, verify) scope to the// SAME (name, BU) identity the SDK uses on create (createPersonaRole keys a role by name WITHIN a BU).// Returns the explicit `businessUnitId`, else the org ROOT business unit (the SDK's own default — a BU-// with no parent), else null when it can't be resolved (caller then falls back to a name-only match:-// best-effort, so a transient BU-lookup failure never blocks teardown/verify). `q` is a queryRecords fn-// (the teardown `sdk` or the verify `read`); `cache` memoizes the root-BU lookup for the run.+// with no parent), else NULL when it cannot be resolved. Every current caller treats null as FAIL+// CLOSED and reports the role as missing rather than matching on name alone (teardown+// sdk-teardown.js, verify verify-spec.js, and the roleGrant apply path) — a name-only match could+// touch a same-named role in a DIFFERENT business unit, which for a grant is privilege escalation.+// `q` is a queryRecords fn (the teardown `sdk` or the verify `read`); `cache` memoizes the root-BU+// lookup for the run.async function resolveRoleBusinessUnit(q, businessUnitId, cache = {}) {if (businessUnitId && FORM_GUID_RE.test(businessUnitId)) return businessUnitId;if (Object.prototype.hasOwnProperty.call(cache, 'rootBu')) return cache.rootBu;@@ -1098,12 +1130,59 @@ async function resolveRoleBusinessUnit(q, businessUnitId, cache = {}) {}// The `_businessunitid_value eq <guid>` OData clause (Edm.Guid is UNQUOTED) that scopes a role query to a-// business unit. Empty string when the BU is unknown (name-only fallback). `bu` is GUID-validated by+// business unit. Empty string when the BU is unknown — but no caller reaches that today: every one+// treats an unresolved BU as fail-closed before calling this. `bu` is GUID-validated by// resolveRoleBusinessUnit, so interpolation is injection-safe.function roleBuClause(bu) {return bu && FORM_GUID_RE.test(String(bu)) ? ` and _businessunitid_value eq ${bu}` : '';}+// A stable, human-readable name for a `roleGrants[]` entry, used in plan lines, progress labels and+// errors. Prefers the display name the author wrote; falls back to the pinned id.+function roleGrantLabel(g) {+ const name = g && typeof g.role === 'string' ? g.role.trim() : '';+ return name ? `"${name}"` : `${(g && g.roleId) || '?'}`;+}++// Resolve the EXISTING role a `roleGrants[]` entry extends. AB#6686429.+//+// Fail-closed on every ambiguity, because the write is a privilege grant: granting on the wrong role is+// a silent access-control defect that no later phase would catch.+// - `roleId` pinned → confirm the row EXISTS (an absent id is a stale pin, not a create trigger — this+// surface never creates a role) and report its name so the build log names what was actually changed.+// - `role` name → exact-match within the resolved business unit (explicit `businessUnitId`, else the org+// ROOT BU — the same identity `createPersonaRole`, teardown and verify use). 0 matches and >1 match+// are BOTH errors; ">1" happens when the same role name exists in several BUs and the author must+// disambiguate.+//+// Unlike the persona path this deliberately does NOT require the SDK ownership marker: the whole point is+// to extend a role somebody else built. `ismanaged` is not a blocker either — Dataverse permits+// AddPrivilegesRole on a managed role, and refusing would block the bug's actual scenario (a solution's+// shipped roles). It IS surfaced in the returned detail so the log says what was touched.+async function resolveRoleGrantTarget(provision, grant, buCache) {+ if (grant.roleId) {+ const rows = await provision.queryRecords('role', { select: ['roleid', 'name', 'ismanaged'], filter: `roleid eq ${grant.roleId}`, top: 1 });+ const row = rows && rows[0];+ if (!row) throw new Error(`roleGrant: pinned roleId ${grant.roleId} does not exist on this environment — correct the id, or target the role by name`);+ return { roleId: String(row.roleid), name: row.name || '', managed: row.ismanaged === true };+ }+ const name = String(grant.role).trim();+ const bu = await resolveRoleBusinessUnit((e, o) => provision.queryRecords(e, o), grant.businessUnitId, buCache);+ // FAIL CLOSED when the BU cannot be resolved. Teardown/verify fall back to a name-only match because a+ // false negative there is merely noisy; here a name-only match could grant privileges on a same-named+ // role in a DIFFERENT business unit, which is a real privilege escalation.+ if (!bu) throw new Error(`roleGrant "${name}": could not resolve the business unit to scope the role lookup — pin the role with 'roleId' instead`);+ const rows = await provision.queryRecords('role', {+ select: ['roleid', 'name', 'ismanaged'],+ filter: `name eq '${String(name).replace(/'/g, "''")}'${roleBuClause(bu)}`,+ top: 5,+ });+ const matches = (rows || []).filter((r) => r && r.roleid);+ if (!matches.length) throw new Error(`roleGrant "${name}": no security role with that name exists in business unit ${bu} — check the spelling (the name must match EXACTLY), or pin the role with 'roleId'`);+ if (matches.length > 1) throw new Error(`roleGrant "${name}": ${matches.length} roles share that name in business unit ${bu} — pin the one you mean with 'roleId'`);+ return { roleId: String(matches[0].roleid), name: matches[0].name || name, managed: matches[0].ismanaged === true };+}+// --- orchestrator ----------------------------------------------------------------------async function runSdkBuild(spec, opts = {}) {@@ -1124,7 +1203,7 @@ async function runSdkBuild(spec, opts = {}) {return { ok: true, dryRun: true, plan: plan.map((p) => p.label) };}- const result = { ok: true, created: { entities: {}, relationships: {}, records: {}, webResources: {}, views: {}, charts: {}, forms: {}, formIds: {}, businessRules: {}, businessProcessFlows: {}, commands: {}, dashboards: {}, pages: {}, pageDeployedShas: {}, ai: { appFeatures: null, summaries: {} }, roles: {}, app: null }, skipped: { businessRules: [], aiSummaries: [] } };+ const result = { ok: true, created: { entities: {}, relationships: {}, records: {}, webResources: {}, views: {}, charts: {}, forms: {}, formIds: {}, businessRules: {}, businessProcessFlows: {}, bpfBackingTables: {}, commands: {}, dashboards: {}, pages: {}, pageDeployedShas: {}, ai: { appFeatures: null, summaries: {} }, roles: {}, roleGrants: {}, bpfRoleGrants: {}, app: null }, skipped: { businessRules: [], aiSummaries: [] } };// #changed-only (pages-only fast apply): seed the LIVE app id (discovered by unique name upstream) so the// pages phase's `pages-requires-app` guard passes WITHOUT running the app-shell phase in this invocation.// The full-build path never sets opts.changedOnly, so result.created.app stays null and app-shell@@ -1295,6 +1374,57 @@ async function runSdkBuild(spec, opts = {}) {return added;};+ // Fetch a just-created form before wiring its event handlers, tolerating the workspace-metadata+ // race. AB#6688905.+ //+ // `buildArtifact` resolves once the form ROW exists, but the SDK persists the workspace copy as two+ // files — `.maker-workspace/forms/<id>.json` and `.maker-workspace/.metadata/forms/<id>.meta.json`+ // — and `fetchArtifact` reads the metadata one. Under `mapLimit` several forms are written+ // concurrently, and the reporter hit the window between them:+ // UNKNOWN: unknown error, open '...\.maker-workspace\.metadata\forms\<id>.meta.json'+ // with the sibling `.json` already on disk. `UNKNOWN` (not ENOENT) is what Windows reports for a+ // concurrent-access/sharing violation, which is why this matches on the PATH rather than the code+ // — matching only ENOENT would miss the shape that was actually observed.+ //+ // A retry is the correct remedy rather than a workaround: the reporter's second identical run+ // succeeded, so the state is transient by construction, and the build is idempotent. Bounded and+ // narrow on purpose — a form whose metadata never lands still fails, with a message that names the+ // race instead of the bare `UNKNOWN` the operator could do nothing with.+ //+ // ⚠ THE SDK NOW RETRIES TOO, and this is deliberately kept as a SECOND layer rather than deleted.+ // The vendored `WorkspaceManager` retries `EPERM`/`EACCES`/`EBUSY`/`UNKNOWN` on its own and treats a+ // file deleted between its `exists` probe and its open as absent. Two reasons this outer retry still+ // earns its place: the SDK's authors explicitly decline to call that fix MEASURED (a two-process+ // harness never reproduced the failure, so the trigger is environmental — an AV scanner or indexer+ // holding a handle), and an exhausted SDK budget rethrows the bare `UNKNOWN` unchanged, which is the+ // message the operator could do nothing with. The layering costs nothing on the happy path. Delete+ // this only against evidence that the SDK's budget is sufficient, not merely because it exists.+ const isWorkspaceMetadataRace = (err) => {+ const msg = (err && err.message) || String(err || '');+ return /[\\/]\.metadata[\\/]/.test(msg) && /\.meta\.json/.test(msg);+ };+ const fetchFormForWiring = async (id, f) => {+ const attempts = 4;+ let last;+ for (let i = 0; i < attempts; i += 1) {+ try {+ return await provision.fetchArtifact('form', id);+ } catch (err) {+ last = err;+ if (!isWorkspaceMetadataRace(err) || i === attempts - 1) break;+ // Linear, not exponential: the writer is a local file flush, so the wait needed is+ // milliseconds — a doubling backoff would spend seconds waiting for something already done.+ await new Promise((r) => setTimeout(r, 150 * (i + 1)));+ }+ }+ if (isWorkspaceMetadataRace(last)) {+ throw new Error(`form ${f && (f.name || f.entity)}: the workspace metadata for this form was still not readable after ${attempts} attempts `+ + `(${(last && last.message) || last}). The form row itself was created — this is a local workspace write race, not a Dataverse failure. `+ + 'Re-run the same command: the build is idempotent and the metadata will exist on the next run.');+ }+ throw last;+ };+// Reconcile an EXISTING form to the spec: fetch it, ADD any spec field/sub-grid not already placed// (semantic identity = bound fieldName / relationship, so a rebuild never duplicates), PRUNE fields// an explicit layout dropped, then push (halt on a 412 conflict), publish, and ensure it's a@@ -1746,21 +1876,10 @@ async function runSdkBuild(spec, opts = {}) {}));const ids = await runner.mapLimit(defs, concurrency, async (d) => {const id = await buildArtifact('form', d.def);- // Gap 2: make our main form the entity's default so the app opens it, not the blank stock form.- // Guarded to a table THIS build OWNS — a custom, publisher-prefixed table that isn't flagged- // `existing`. A system/reused table (account, systemuser, or anything without our prefix) must- // never have its default form re-pointed: that's a shared, environment-wide side effect.- if ((d.f.formType || 'Main') === 'Main') {- const entSpec = entityByLogical(spec, d.f.entity.toLowerCase());- const prefix = spec.solution && spec.solution.publisherPrefix;- const isOwnCustomTable = !!(entSpec && entSpec.existing !== true && prefix &&- String(entSpec.schemaName).toLowerCase().startsWith(String(prefix).toLowerCase() + '_'));- if (isOwnCustomTable) await promoteDefaultForm(id, d.f.entity.toLowerCase(), d.f.deactivateOtherMainForms === true);- }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 () => {- await provision.fetchArtifact('form', id);+ await fetchFormForWiring(id, d.f);// Merge into the root-bag <events> region (idempotent — a rebuild only pushes if a NEW// handler was appended, so re-runs don't duplicate a handler or a second <events> root).if (await wireFormEvents(id, wantedEvents)) {@@ -1773,7 +1892,77 @@ async function runSdkBuild(spec, opts = {}) {});// Key the entity's MAIN form by entity (the app wires one form per entity below); quick-create// / quick-view forms are still built + added to the solution, just not the entity's app form.- defs.forEach((d, i) => { if ((d.f.formType || 'Main') === 'Main') result.created.forms[d.f.entity.toLowerCase()] = ids[i]; });+ //+ // AB#6686426 — default-form promotion, ONCE per entity, AFTER every form exists.+ //+ // This used to run inside the concurrent per-form build above, so on a table with several Main+ // forms every one of them promoted itself and the LAST to finish won. Which form a table opened+ // 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.+ const promotedEntities = new Set();+ const mainByEntity = new Map(); // entity -> { id, f } chosen for promotion+ defs.forEach((d, i) => {+ if ((d.f.formType || 'Main') !== 'Main') return;+ const key = d.f.entity.toLowerCase();+ 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;+ // Serialized deliberately: two promotions racing is the bug being fixed.+ await promoteDefaultForm(chosen.id, entityLogical, chosen.f.deactivateOtherMainForms === true);+ promotedEntities.add(entityLogical);+ }+ if (promotedEntities.size) result.created.defaultForms = Object.fromEntries(+ [...mainByEntity].filter(([k]) => promotedEntities.has(k)).map(([k, v]) => [k, v.id])+ );++ // 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,+ // name) triple and normally holds them all.+ //+ // The warning deliberately does NOT promise that `formIds` is complete: `formIdentityKey` omits+ // `formId`, which the App Spec supports precisely so two forms can share an entity, type and+ // name. Two such pinned forms collide in `formIds` as well, and claiming otherwise would send+ // the reader to a map that cannot answer them either.+ const mainFormSeen = new Map(); // entity -> { shownName, identityKey } for the first Main form, in spec order+ defs.forEach((d, i) => {+ if ((d.f.formType || 'Main') !== 'Main') return;+ const key = d.f.entity.toLowerCase();+ // `name` is optional on a form and is compiled to "<entity> form"; using the raw spec value+ // here would print "undefined" for exactly the forms the author did not name.+ const shownName = d.f.name || (d.def && d.def.name) || `${key} form`;+ if (!mainFormSeen.has(key)) {+ mainFormSeen.set(key, { shownName, identityKey: formIdentityKey(d.f) });+ } else if (typeof opts.warn === 'function') {+ const first = mainFormSeen.get(key);+ // Compared on the stored IDENTITY KEY of the earlier form, not on a key rebuilt from its+ // DISPLAY name. Those differ for an UNNAMED form: `formIdentityKey` uses `f.name || ''`+ // while `shownName` falls back to "<entity> form", so rebuilding from the display name made+ // two unnamed Main forms look distinct when they actually collide in `created.formIds` —+ // and the warning then pointed the reader at a map that could not separate them either.+ const distinct = formIdentityKey(d.f) !== first.identityKey;+ opts.warn(`entity ${key} has more than one Main form ("${first.shownName}" and "${shownName}"); `+ + `created.forms keeps ONE id per entity for the app shell, so it now reports "${shownName}". `+ + (distinct+ ? 'The other ids are in created.formIds, keyed "entity|formType|name" — read that map rather than re-querying systemform.'+ : 'These two share an entity, type and name, so created.formIds cannot separate them either — give them distinct names.'));+ }+ result.created.forms[key] = ids[i];+ });// Every form, addressable individually. `created.forms` is keyed by ENTITY and holds only the// Main form, which is all the app shell needs — but `forms[].securityRoles` is applied in the// SECURITY phase (roles do not exist until then), by which time the forms phase is long over and@@ -2081,7 +2270,14 @@ async function runSdkBuild(spec, opts = {}) {const entityLogical = String(flow.entity).toLowerCase();const key = `${entityLogical}|${flow.name}`;const existing = await provision.queryRecords('workflow', {- select: ['workflowid', 'statecode', 'createdon'],+ // `uniquename` is selected, not derived. Activation creates the flow's backing TABLE with+ // exactly this name, and the security phase grants privileges on that table. For a flow this+ // build created, `bpfUniqueName(flow.name)` IS the deployed value — but a REUSED flow may+ // have been authored in Maker or by another tool under any unique name at all, and a+ // later display-name rename does not follow it. Deriving instead of reading would then grant+ // on a table that either does not exist or, worse, belongs to something else entirely.+ // See https://learn.microsoft.com/en-us/power-automate/developer/business-process-flows-code+ select: ['workflowid', 'statecode', 'createdon', 'uniquename'],// Definition rows only, and BusinessFlow only — see bpfFilter.filter: bpfFilter(flow.name, entityLogical),// Ordered and > 1 for the same reason as business rules: `top: 1` unordered adopts an@@ -2118,6 +2314,10 @@ async function runSdkBuild(spec, opts = {}) {runner.skip('business-process-flows', `business process flow "${flow.name}" on ${flow.entity} (exists — reuse; stage edits aren't applied on rebuild, recreate to change)`);}result.created.businessProcessFlows[key] = existingId;+ // The DEPLOYED backing-table name, read back rather than derived (see the select above). A+ // row with no `uniquename` (an older projection, or a double that does not model the field)+ // falls back to the derivation, which is still the right answer for anything this tool made.+ result.created.bpfBackingTables[key] = String(existing[0].uniquename || bpfUniqueName(flow.name)).toLowerCase();// Reconcile solution membership on the REUSE path too. `addSolutionComponent` is otherwise// only reached by the create branch, so a run where the flow was created but the component// add failed (or a flow created by an earlier build of a different solution) would be reused@@ -2188,6 +2388,11 @@ async function runSdkBuild(spec, opts = {}) {const art = provision.createArtifact('bpf', bpfDef(flow));const pushed = requireSuccessfulPush(await provision.pushArtifact('bpf', art.id), `business process flow ${flow.name}`, opts.warn);result.created.businessProcessFlows[key] = pushed.id;+ // On the CREATE path the derivation is authoritative: the build supplied `flow.name`, the+ // adapter derived `uniquename` from it, and `unique` above is that same derivation — already+ // proven collision-free by the clash checks. Recorded explicitly so the security phase reads+ // ONE map regardless of which branch produced the flow.+ result.created.bpfBackingTables[key] = unique;// componentType 29 (workflow) — a BPF is a workflow row, so it ships in the solution the same// way a business rule does. Without this the process is left out of the solution and does not// travel on export/import.@@ -2663,14 +2868,13 @@ async function runSdkBuild(spec, opts = {}) {}}- // 7c. AI features (opt-in via spec.ai). Enable app-level agents (gated on admin settings) +- // configure per-table row summaries. All AI writes are best-effort-gated: setAppAiFeatures- // skips features whose admin gate is off; it never throws.- // Features the SDK did not put in `applied`, deferred for a post-publish re-proof (see inside the+ // 7c. AI features (opt-in via spec.ai). Enable app-level agents + configure per-table row+ // summaries. `setAppAiFeatures` never throws — every outcome arrives as data in a bucket.+ // Features the SDK did not put in `applied`, deferred for a post-publish re-issue (see inside the// ai-features phase for why the verdict cannot honestly be decided at write time).const pendingAiReconfirm = [];- if (has('ai-features') && spec.ai !== undefined && spec.ai !== null) {+ if (has('ai-features') && specOptsIntoAi(spec)) {const solutionUniqueName = spec.solution && spec.solution.uniqueName;const appUnique = appUniqueName(spec);const flags = resolveAiFlags(spec);@@ -2708,10 +2912,15 @@ async function runSdkBuild(spec, opts = {}) {// false-PASS half of ADO 6603383 (features were pushed onto `applied` while writing nothing):// notPersisted — the write returned 204 but no override was observed for the whole retry// budget; Dataverse can accept an app-scope write and store nothing.+ // skipped — as notPersisted, PLUS the feature's org readiness gate reads off, which is+ // 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.// 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 (or its org-gate read) threw. The SDK keeps going so the rest- // of the batch still reports, so this arrives as data, never as an exception.+ // failed — the write threw. The SDK keeps going so the rest of the batch still+ // reports, so this arrives as data, never as an exception.//// RE-CONFIRMATION (safety net): with `appModuleId` supplied above, the SDK can prove the// override row here, pre-publish, so the normal path decides the verdict in this phase. The@@ -2722,10 +2931,20 @@ async function runSdkBuild(spec, opts = {}) {// `reconfirmAiFeatures` below) against the identical override-row oracle the verifier uses.// The re-proof can only ever UPGRADE a feature, never hide a real failure.//+ // `skipped` is deferred WITH the rest, and that is the plugin half of AB#6688904. On a freshly+ // created app NO app-scope write persists until the app is published, so the SDK's post-write+ // gate read fires for every feature — and for the ones that happen to have a distinct org gate+ // (`nlSearch`, `nlChart`, `formFillSmartPaste`) an org-wide `false` then labels them `skipped`.+ // Treating that as a final answer would abandon them before the one sequence measured to work,+ // and `--verify` would then fail on an override row the build gave up on writing. The reported+ // environment ran a working app at `NLGridSearchSetting = 2` with `EnableNLGridSearch` off, so+ // a gate reading off is not proof the app-scope write cannot land — only the retry can settle+ // it. Anything still `skipped` after the retry is reported as an admin action, not a defect.+ //// Derive the non-success buckets from the RESULT, not a fixed list: a bucket added by a future// SDK revision is then reported verbatim rather than silently dropped (which is the very bug// class this phase exists to remove). `outcomes` is per-feature detail, not a bucket.- const problemKeys = Object.keys(r || {}).filter((k) => k !== 'applied' && k !== 'skipped' && k !== 'outcomes' && Array.isArray(r[k]) && r[k].length);+ const problemKeys = Object.keys(r || {}).filter((k) => k !== 'applied' && k !== 'outcomes' && Array.isArray(r[k]) && r[k].length);for (const key of problemKeys) {for (const feature of r[key]) {const outcome = (r.outcomes || []).find((o) => o && o.feature === feature);@@ -2734,9 +2953,8 @@ async function runSdkBuild(spec, opts = {}) {}const parts = [];if (r.applied && r.applied.length) parts.push(`applied: ${r.applied.join(', ')}`);- if (r.skipped && r.skipped.length) parts.push(`skipped (admin gate off): ${r.skipped.join(', ')}`);if (pendingAiReconfirm.length) parts.push(`retrying after publish: ${pendingAiReconfirm.map((p) => p.feature).join(', ')}`);- return parts.length ? parts.join('; ') : '(none \u2014 admin gate off)';+ return parts.length ? parts.join('; ') : '(none)';});// Same rule as the plan: `selectSummaryTables` owns the default-vs-override decision, so calling// it unconditionally is what lets `default: 'off'` + `tables[x].enabled: true` opt a single table@@ -2908,6 +3126,165 @@ async function runSdkBuild(spec, opts = {}) {});}+ // 7a-bis. Role grants (`roleGrants[]`) — ADD privileges for a table to a PRE-EXISTING role. AB#6686429.+ //+ // The scenario this exists for: a table is added to an app whose solution already ships four data+ // roles. Before this, the table, its forms and its nav deployed while every non-admin persona still+ // had no access to it, and nothing said so.+ //+ // ADDITIVE, never converging. `addEntityPrivilegesToRole` compiles to `AddPrivilegesRole`, so a+ // privilege the role already holds is re-asserted and every privilege the spec does NOT mention is+ // left alone. That is what makes it safe to point at a role somebody else owns — and it is also why+ // this surface cannot REVOKE (documented in references/app-spec-schema.md).+ //+ // Idempotency comes from Dataverse, not from a read-compare here: re-POSTing a grant the role already+ // holds at the same depth succeeds and changes nothing. Re-POSTing at a HIGHER depth raises it. We do+ // not pre-read the role's privileges, because a read-then-write would be racy and the write is+ // already the converged operation.+ //+ // Runs AFTER the persona loop so that, if a future change ever allowed both to touch one role, the+ // additive grant lands last rather than being converged away. Today validation rejects that overlap+ // outright (see validateRoleGrants).+ const roleGrantBuCache = {}; // memoize the root-BU lookup across grants in this build+ // Resolved-id guards. The static validator can only compare NAMES, so a `roleId` pinned at a role+ // a persona also authors, or a name-and-id pair aliasing one role, both slip past it. Both are+ // caught here on the identity that actually matters — the resolved Dataverse role id:+ // * persona overlap would let ReplacePrivilegesRole converge the grant away on the next build,+ // and a failure BETWEEN the two passes leaves the access removed;+ // * two grants on one role split a depth conflict across two SDK calls, where the SDK's+ // "entities sharing one privilege must request one depth" check cannot see it and the later+ // write silently wins.+ const personaRoleIds = new Map(); // lowercased roleId -> persona name, from the loop above+ for (const [name, rr] of Object.entries(result.created.roles || {})) {+ if (rr && rr.roleId) personaRoleIds.set(String(rr.roleId).toLowerCase(), name);+ }+ const grantedRoleIds = new Map(); // lowercased roleId -> the label of the grant that claimed it+ // TWO PASSES, deliberately. Resolving and guarding EVERY grant before applying ANY is what makes+ // the identity guards below worth having: with resolve-guard-apply interleaved per grant, a spec+ // whose second entry aliases the first applied grant #1 and only then halted, leaving one role+ // changed and one not, with nothing in the output saying which. Every guard here rejects a spec+ // that is wrong independently of the environment, so it costs nothing to learn that first.+ const resolvedGrants = [];+ for (const grant of spec.roleGrants || []) {+ const label = roleGrantLabel(grant);+ let target;+ try {+ target = await resolveRoleGrantTarget(provision, grant, roleGrantBuCache);+ } catch (err) {+ // Fail-closed: an unresolvable or ambiguous role means we do not know what we would be granting+ // on. Halting is better than skipping, because a skipped grant reads as a successful build whose+ // users still cannot open the table — the exact failure this feature was filed for.+ throw new BuildHalt(`roleGrant ${label} could not be resolved: ${err && err.message ? err.message : err}`, { phase: 'security', code: 'role-grant-unresolved', recoverable: false });+ }+ const idKey = String(target.roleId).toLowerCase();+ if (personaRoleIds.has(idKey)) {+ throw new BuildHalt(+ `roleGrant ${label} resolves to role ${target.roleId}, which is also persona "${personaRoleIds.get(idKey)}" in this spec. `+ + 'The build CONVERGES a persona\'s role (privileges not declared on the persona are removed), so this grant would be '+ + 'undone on the next build — declare these privileges on that persona\'s job instead.',+ { phase: 'security', code: 'role-grant-persona-overlap', recoverable: false },+ );+ }+ if (grantedRoleIds.has(idKey)) {+ throw new BuildHalt(+ `roleGrant ${label} resolves to role ${target.roleId}, which roleGrant ${grantedRoleIds.get(idKey)} already targets. `+ + 'Merge them into one entry: two entries can request conflicting depths for one shared Dataverse privilege, and the '+ + 'SDK only detects that within a single call, so the later write would silently win.',+ { phase: 'security', code: 'role-grant-duplicate-target', recoverable: false },+ );+ }+ grantedRoleIds.set(idKey, label);+ resolvedGrants.push({ grant, label, target });+ }+ for (const { grant, label, target } of resolvedGrants) {+ await runner.run('security', `grant privileges to existing role ${label}`, async () => {+ let applied;+ try {+ applied = await provision.addEntityPrivilegesToRole(target.roleId, grant.privileges);+ } catch (err) {+ // Apply-time metadata guards live here: a table that exposes no such access, and the SDK's+ // shared-privilege rule (two tables aliasing to one prv* must request one depth). Both are+ // author errors that only live metadata can detect, so they surface with the SDK's own message.+ throw new BuildHalt(`roleGrant ${label} could not be applied: ${err && err.message ? err.message : err}`, { phase: 'security', code: 'role-grant-failed', recoverable: false });+ }+ const n = Array.isArray(applied) ? applied.length : 0;+ // Keyed on the resolved ROLE ID, with the display name carried in the value. Keying on+ // `target.name` collapsed two DIFFERENT roles that share a display name — which the spec+ // gate deliberately allows, because a role is identified by (name, business unit) and the+ // same name in two BUs is two roles. The second grant then overwrote the first in this map,+ // so `--json` consumers saw one grant where two were applied. The id is the identity the+ // apply itself guards on, so it cannot collide.+ result.created.roleGrants[target.roleId] = { roleId: target.roleId, name: target.name, managed: target.managed, privileges: applied || [] };+ // The role is NOT added to the app's solution. A persona role is ours to place; a pre-existing role+ // already lives wherever its owner put it, and adding a foreign (possibly managed) role to this+ // solution would take an ownership decision the author did not ask for. If the role is already a+ // component of this solution, its updated privileges export with it either way.+ return `${n} privilege${n === 1 ? '' : 's'} granted on ${target.name || target.roleId}${target.managed ? ' (managed role)' : ''}`;+ });+ }++ // 7b-bis. Business process flow role grants (`businessProcessFlows[].securityRoles`). #513.+ //+ // Runs in SECURITY, not in the flow phase, for the same reason `forms[].securityRoles` does: a+ // persona's role does not exist until the loop above has run.+ //+ // The target is the flow's BACKING TABLE, not the flow row. Activating a flow makes the platform+ // create an org-owned table, and holding privileges on THAT is what lets a persona run the+ // process. Two things were measured live before this was written (see validateBpfSecurityRoles):+ // the table is organization-owned and every privilege is Global-only, so there is no scope to+ // author; and the public `addEntityPrivilegesToRole` grants on it (the SDK's internal BPF role+ // helper is not on its public surface).+ //+ // The table NAME is taken from `created.bpfBackingTables`, which the flow phase read back from+ // the deployed `workflow.uniquename`. It is only DERIVED from the display name as a last resort:+ // a flow authored elsewhere, or renamed after creation, keeps its original unique name, and+ // granting on the derivation would target a table that does not exist — or one that belongs to+ // something else. The fallback still covers the doubles and older projections that do not carry+ // the field, where the derivation is the correct answer anyway.+ const flowsWithRoles = (spec.businessProcessFlows || []).filter((f) => f && f.securityRoles);+ for (const f of flowsWithRoles) {+ const flowKey = `${String(f.entity).toLowerCase()}|${f.name}`;+ const backingTable = result.created.bpfBackingTables[flowKey] || bpfUniqueName(f.name);+ const label = `flow "${f.name}" (backing table ${backingTable})`;+ // The flow must have been built in THIS invocation, or its backing table may not exist —+ // ACTIVATION is what creates it. Checked BEFORE runner.run and reported through runner.skip,+ // because a value returned from runner.run is not emitted: a silent skip would report a clean+ // build in which nobody can run the process, which is the failure #513 exists to fix.+ // The key mirrors the flow phase's own `${entityLogical}|${flow.name}`.+ const built = result.created.businessProcessFlows[flowKey];+ if (!built) {+ runner.skip('security', `flow roles for ${f.name} (the business-process-flows phase did not run in this invocation, so the backing table may not exist yet)`);+ continue;+ }+ await runner.run('security', `flow roles for ${f.name}`, async () => {+ const personas = (f.securityRoles.personas || []);+ // Case-INSENSITIVE, exactly like the form path immediately below — and for the same reason.+ // `validateBpfSecurityRoles` resolves the persona reference against a LOWERCASED set, so a+ // spec naming "dispatcher" for a persona declared as "Dispatcher" validates clean. A+ // case-sensitive lookup here would then halt at the near-last phase, with a message claiming+ // the persona "has no role in this build" — which is false; it was declared and its role was+ // created. Late halt, wrong diagnosis, half-built app.+ const roleByLower = new Map(Object.entries(result.created.roles || {})+ .map(([name, rr]) => [String(name).trim().toLowerCase(), rr]));+ const roleIds = personas.map((p) => {+ const rr = roleByLower.get(String(canonicalPersonaName({ persona: p }) || '').toLowerCase());+ if (!rr || !rr.roleId) throw new BuildHalt(`${label}: persona '${p}' has no role in this build`, { phase: 'security', code: 'bpf-role-unresolved', recoverable: false });+ return { persona: p, roleId: rr.roleId };+ });+ for (const { persona, roleId } of roleIds) {+ try {+ // Organization scope is not a choice: the backing table is org-owned and its privileges+ // report CanBeGlobal only, so any other depth is rejected by the platform.+ await provision.addEntityPrivilegesToRole(roleId, [{ entity: backingTable, access: BPF_ROLE_ACCESS, scope: 'organization' }]);+ } catch (err) {+ throw new BuildHalt(`${label}: could not grant to persona '${persona}': ${err && err.message ? err.message : err}`, { phase: 'security', code: 'bpf-role-grant-failed', recoverable: false });+ }+ }+ result.created.bpfRoleGrants[f.name] = { backingTable, personas };+ return `${roleIds.length} persona(s) granted ${BPF_ROLE_ACCESS.join('/')} on ${backingTable}`;+ });+ }+// 7b. Offer forms to specific security roles (`forms[].securityRoles`). AB#6648526.//// This runs in the SECURITY phase, not the forms phase, because a persona's role does not exist@@ -3020,8 +3397,13 @@ async function runSdkBuild(spec, opts = {}) {const appUnique = appUniqueName(spec);const BUCKET_LABELS = {notPersisted: ['NOT PERSISTED', 'Dataverse accepted the write but no app-scope override holding the requested value was observed'],+ // Distinct wording from NOT PERSISTED on purpose: both mean the override row is absent, but+ // `skipped` carries a diagnosis the operator can ACT on — an environment admin has to turn the+ // feature on before any app can. The SDK's own per-feature `reason` names the gate and its+ // value, and it is preferred over this text wherever it is present.+ skipped: ['ADMIN GATE OFF', 'the write was issued, no app-scope override appeared, and the feature\u2019s org readiness gate reads off \u2014 an environment admin must enable it first'],unverified: ['UNVERIFIED', 'the write was issued but could not be confirmed \u2014 verify manually before relying on it'],- failed: ['FAILED', 'the write or its org-gate read threw'],+ failed: ['FAILED', 'the write threw'],};// Replicate the sequence proven to work live, in order: fetch the app (so the workspace holds the// server's copy), publish it, then write. Each step is best-effort — a failure here must not fail@@ -3075,7 +3457,12 @@ async function runSdkBuild(spec, opts = {}) {const af = result.created.ai && result.created.ai.appFeatures;if (af && reproven.length) {af.applied = [...(af.applied || []), ...reproven];- for (const key of Object.keys(af)) if (Array.isArray(af[key]) && key !== 'applied' && key !== 'skipped') af[key] = af[key].filter((f) => !reproven.includes(f));+ // `skipped` is cleaned up like every other non-success bucket. It used to be exempt, back when+ // the SDK pre-empted a gated write and `skipped` therefore meant "never attempted" — a state+ // no retry could change. Since AB#6688904 the write IS attempted, so a feature can genuinely+ // move from `skipped` to `applied`, and leaving it listed in both would make+ // `created.ai.appFeatures` contradict itself for any `--json` consumer.+ for (const key of Object.keys(af)) if (Array.isArray(af[key]) && key !== 'applied' && key !== 'outcomes') af[key] = af[key].filter((f) => !reproven.includes(f));for (const o of af.outcomes || []) if (reproven.includes(o.feature)) { o.status = 'applied'; o.appOverrideExists = true; o.reason = reprovenBy.get(o.feature); }}// `runner.skip` renders as `⊘ <label>` — the closest thing the narrator has to a warning — and@@ -3091,4 +3478,4 @@ async function runSdkBuild(spec, opts = {}) {return result;}-module.exports = { runSdkBuild, planFor, resolvePhases, PHASES, BuildHalt, SDK_COLUMN_TYPE, viewDef, defaultViewColumns, subgridLabel, enrichesDefaultViews, artifactIdentityQuery, resolveExistingFormId, FORM_TYPE_CODE, chartDef, dashboardTileOpts, dashboardComponent, compileFormIntent, formFieldLogicals, appDef, appUniqueName, commandsByEntity, commandDef, businessRuleDef, businessRuleFilter, bpfDef, bpfFilter, webResourceOpts, WEB_RESOURCE_KINDS, FORM_EVENTS, acquireAppPagesLease, personaRoleSpecFor, resolveRoleBusinessUnit, roleBuClause };+module.exports = { runSdkBuild, planFor, resolvePhases, PHASES, BuildHalt, SDK_COLUMN_TYPE, viewDef, defaultViewColumns, subgridLabel, enrichesDefaultViews, artifactIdentityQuery, resolveExistingFormId, FORM_TYPE_CODE, chartDef, dashboardTileOpts, dashboardComponent, compileFormIntent, formFieldLogicals, appDef, appUniqueName, 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-teardown.js b/plugins/model-apps/scripts/lib/sdk-teardown.jsindex 5fc1a28a4..0a3a93fbf 100644--- a/plugins/model-apps/scripts/lib/sdk-teardown.js+++ b/plugins/model-apps/scripts/lib/sdk-teardown.js@@ -57,6 +57,7 @@ const { appUniqueName, commandsByEntity, defaultViewColumns, resolveExistingFormconst { 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');+const { specOptsIntoAi } = require('./ai-app-settings.js');const { isRestrictedSolution } = require('./system-solutions.js');// OData v4 string-literal escaping lives in ./odata.js. `odataStr` is kept as a backward-compatible@@ -791,6 +792,18 @@ function planTeardown(spec) {if (!name) continue;steps.push({ kind: 'role', phase: 'security', label: `security role "${name}"`, target: { name, businessUnitId: p.businessUnitId } });}+ // `roleGrants[]` are deliberately NOT torn down. AB#6686429 asks for "safe teardown semantics that+ // do not remove pre-existing grants", and the safe semantics are to do nothing at all:+ //+ // * the ROLE belongs to someone else — deleting it is out of the question, and the marker gate+ // above already refuses (a foreign role carries no SDK_ROLE_MARKER), so no step is needed for that;+ // * the PRIVILEGES cannot be revoked safely either. `AddPrivilegesRole` is additive and does not+ // record who added what, so a teardown could not tell a privilege this spec granted from one the+ // role already held — or one a second spec granted. Removing "what the spec declares" would strip+ // access that predates us, which is precisely the outcome the bug asks to avoid, and is worse+ // than leaving a stale grant (extra access on a role its owner still administers in Maker).+ //+ // Consequence, stated in references/app-spec-schema.md: a roleGrant is one-way. Revoke in Maker.for (const c of spec.charts || []) {steps.push({ kind: 'chart', phase: 'charts', label: `chart "${c.name}" (${c.entity})`, target: { name: c.name, entity: String(c.entity).toLowerCase() } });}@@ -811,8 +824,21 @@ function planTeardown(spec) {steps.push({ kind: 'relationship', phase: 'relationships', label: `relationship ${schema}`, target: { schemaName: schema } });}// AI row-summary records must be removed BEFORE tables: the summary record references the- // table and would block its delete. Reuses selectSummaryTables to respect default:'off' + overrides.- if (spec.ai && spec.ai.summaries) {+ // table and would block its delete.+ //+ // Gated on the SHARED opt-in predicate, deliberately — NOT on `spec.ai.summaries`, and not on+ // `selectSummaryTables` alone. `selectSummaryTables` owns the default-vs-override decision but is a+ // CANDIDATE selector, not an opt-in test: handed a spec with no `ai` block at all it returns every+ // entity with a descriptive column. The BUILD creates a summary per eligible table whenever the+ // spec opts into `ai`, so a spec carrying only `ai.appFeatures` still gets one.+ // Short-circuiting on `spec.ai.summaries` here meant teardown planned NOTHING for exactly that+ // spec, and the orphaned `msdyn_aimodel` then blocked the table delete:+ // ✗ table new_uptakeorder — HTTP 400 … cannot be deleted because it is referenced by 1 other+ // components+ // MEASURED live on a spec with `ai.appFeatures` and no `summaries` block. The failure is worse+ // than a leaked record: teardown reports errors and leaves the TABLE — and any data in it —+ // behind, on the one operation whose job is to remove them.+ if (specOptsIntoAi(spec)) {for (const schema of selectSummaryTables(spec)) {const logical = String(schema).toLowerCase();steps.push({ kind: 'aiSummary', phase: 'ai-summaries', label: `row summary ${logical}`, target: { entityLogicalName: logical } });diff --git a/plugins/model-apps/scripts/lib/spec-lint.js b/plugins/model-apps/scripts/lib/spec-lint.jsindex 12ac7e73a..b459862fa 100644--- a/plugins/model-apps/scripts/lib/spec-lint.js+++ b/plugins/model-apps/scripts/lib/spec-lint.js@@ -2,7 +2,7 @@// Pure App Spec guardrail. Returns { ok, errors, warnings }. errors block the plan// gate; warnings teach. Bakes in the modeling lessons hit live — notably the// relationship schema-name vs lookup-name collision Dataverse rejects.-const { relationshipSchemaName, relationshipFor, invalidChoiceSampleTokens, isPlatformIconRef } = require('./app-spec.js');+const { relationshipSchemaName, relationshipFor, invalidChoiceSampleTokens, isPlatformIconRef, labelText } = require('./app-spec.js');const { normalizeSpecShape } = require('./spec-shape.js');const { resolveSurfaces, unresolvedSurfaceMessage } = require('./surface-resolver.js');@@ -286,7 +286,7 @@ function lintAppSpec(spec) {// author picks a distinct name (or knowingly customizes the stock default).const ve = (spec.entities || []).find((x) => lc(x.schemaName) === lc(v.entity));if (ve && v.name) {- const plural = ve.pluralName || `${ve.displayName || ve.schemaName}s`;+ const plural = labelText(ve.pluralName, spec && spec.languageCode) || `${labelText(ve.displayName, spec && spec.languageCode) || ve.schemaName}s`;if (lc(v.name) === `active ${lc(plural)}` || lc(v.name) === `inactive ${lc(plural)}`) {W(`View '${v.name}' has the same name as ${ve.schemaName}'s stock default view — it will MERGE onto that default (columns are unioned and the stock "Created On" is kept, but its filters/sort are ignored). Use a distinct name to author a separate view.`);}diff --git a/plugins/model-apps/scripts/lib/surface-resolver.js b/plugins/model-apps/scripts/lib/surface-resolver.jsindex 16e60dc86..6ba71f046 100644--- a/plugins/model-apps/scripts/lib/surface-resolver.js+++ b/plugins/model-apps/scripts/lib/surface-resolver.js@@ -16,6 +16,7 @@'use strict';const norm = (s) => String(s == null ? '' : s).trim().toLowerCase();+const { labelText, labelAliases } = require('./app-spec.js');// Every artifact kind a surface may legitimately name, with the field(s) a human would write.// Sitemap subareas are included because an author frequently names the NAV ENTRY ("Work Orders")@@ -45,8 +46,14 @@ function buildIndex(spec) {for (const e of spec.entities || []) {// A table itself is a surface when the app exposes it as a nav entry (grid + form). Accept the// display name and the schema name.- add(e && e.displayName, { kind: 'entity', name: e.displayName || e.schemaName, entity: e.schemaName });- add(e && e.schemaName, { kind: 'entity', name: e.displayName || e.schemaName, entity: e.schemaName });+ //+ // A LOCALIZED display name (an LCID map) is indexed under EVERY language it declares, not just+ // the resolved one: a `surfaces[]` entry naming the Spanish label is as legitimate an answer to+ // "what lets them do this job" as one naming the English label, and matching only the resolved+ // language would report a real surface as unresolved on a bilingual spec (AB#6686428).+ const resolved = labelText(e && e.displayName, spec && spec.languageCode) || (e && e.schemaName);+ for (const alias of labelAliases(e && e.displayName)) add(alias, { kind: 'entity', name: resolved, entity: e.schemaName });+ add(e && e.schemaName, { kind: 'entity', name: resolved, entity: e.schemaName });}for (const a of (spec.appShell && spec.appShell.areas) || []) {for (const g of (a && a.groups) || []) {diff --git a/plugins/model-apps/scripts/lib/verify-spec.js b/plugins/model-apps/scripts/lib/verify-spec.jsindex 3f5976a56..a77d7aead 100644--- a/plugins/model-apps/scripts/lib/verify-spec.js+++ b/plugins/model-apps/scripts/lib/verify-spec.js@@ -5,12 +5,13 @@// { ok, checks:[{kind,name,present,detail}], missing:[…] }.const { odataLit } = require('./odata.js');-const { normalizePageSource, relationshipSchemaName, manyToManySchemaName, SDK_ROLE_MARKER, canonicalPersonaName } = require('./app-spec.js');+const { normalizePageSource, relationshipSchemaName, manyToManySchemaName, SDK_ROLE_MARKER, canonicalPersonaName, bpfUniqueName, BPF_ROLE_ACCESS } = require('./app-spec.js');const { resolveExistingFormId, resolveRoleBusinessUnit, roleBuClause, appUniqueName, businessRuleFilter, bpfFilter } = require('./sdk-build.js');const { extractNavTargets } = require('./pageref-resolver.js');-const { AI_APP_SETTING, resolveAiFlags, featureWantValue, sameSettingValue, resolveAppModuleId, proveAppOverride } = require('./ai-app-settings.js');+const { AI_APP_SETTING, resolveAiFlags, specOptsIntoAi, featureWantValue, sameSettingValue, resolveAppModuleId, proveAppOverride } = require('./ai-app-settings.js');const { declaredPrivileges, compareRolePrivileges } = require('./role-privileges.js');const { resolveSurfaces } = require('./surface-resolver.js');+const { selectSummaryTables } = require('./ai-candidates.js');const { isVisualizationUnsupported } = require('./entity-provision.js');// The PER-APP setting each AI feature writes now lives in ./ai-app-settings.js, together with the@@ -466,6 +467,143 @@ async function verifySpec(spec, read, opts = {}) {}}+ // Role grants (`roleGrants[]`) — privileges ADDED to a pre-existing role. AB#6686429.+ //+ // Verified with the SAME subset comparison as personas, and for a stronger reason: unlike a persona+ // role (converged by ReplacePrivilegesRole, so existence implies content), a grant is ADDITIVE onto a+ // role we do not own. Nothing else proves the grant landed — the role existed before and still exists+ // whether or not the privileges were added. A subset check is exactly right here: every privilege the+ // role holds beyond the declared set is somebody else's and must never be a finding.+ //+ // Deliberately NOT checked: the SDK ownership marker. The role belongs to someone else by definition.+ for (const g of spec.roleGrants || []) {+ const declaredName = typeof g.role === 'string' ? g.role.trim() : '';+ const label = declaredName || String(g.roleId || '?');+ let row;+ try {+ if (g.roleId) {+ const rows = await read.queryRecords('role', { select: ['roleid', 'name'], filter: `roleid eq ${g.roleId}`, top: 1 });+ row = (rows || [])[0];+ } else {+ // Same fail-closed BU scoping as the apply path: a name-only fallback could verify against a+ // same-named role in another business unit and report a grant that never happened as held.+ const bu = await resolveRoleBusinessUnit((e, o) => read.queryRecords(e, o), g.businessUnitId, roleBuCache);+ if (bu) {+ const rows = await read.queryRecords('role', { select: ['roleid', 'name'], filter: `name eq '${odataLit(declaredName)}'${roleBuClause(bu)}`, top: 5 });+ row = (rows || []).length === 1 ? rows[0] : undefined; // ambiguity is not proof+ }+ }+ } catch { row = undefined; }+ add('role-grant', label, row, row ? '' : 'the role named by this roleGrant was not found (or its business unit could not be resolved, or the name is ambiguous)');+ if (!row || typeof read.rolePrivileges !== 'function' || typeof read.entityPrivileges !== 'function') continue;+ // `declaredPrivileges` folds in an `appmodule` read for a persona; a roleGrant grants exactly what it+ // declares and must not imply app access, so the triples are flattened here instead of reusing it.+ const declared = [];+ for (const pr of g.privileges || []) {+ for (const a of pr.access || []) declared.push({ entity: String(pr.entity || '').toLowerCase(), access: String(a), scope: pr.scope || 'user' });+ }+ let actual = null;+ try {+ actual = await read.rolePrivileges(row.roleid);+ } catch { actual = null; }+ if (!Array.isArray(actual)) {+ add('role-grant-privileges', label, false, 'could not read the role\'s privileges');+ continue;+ }+ const actualByPrivilegeId = new Map(actual.map((a) => [String((a && a.privilegeId) || '').trim().toLowerCase(), a && a.depth]));+ const entityPrivileges = new Map();+ for (const entity of new Set(declared.map((d) => d.entity))) {+ try {+ const privs = await read.entityPrivileges(entity);+ if (Array.isArray(privs)) entityPrivileges.set(entity, privs);+ } catch { /* left absent → reported as a finding by compareRolePrivileges */ }+ }+ const cmp = compareRolePrivileges(declared, entityPrivileges, actualByPrivilegeId);+ add('role-grant-privileges', label, cmp.ok, cmp.ok+ ? `${declared.length} granted privilege(s) held`+ : cmp.missing.map((m) => `${m.entity}.${m.access}: ${m.reason}`).join('; '));+ }++ // Business process flow role grants (`businessProcessFlows[].securityRoles`). #513.+ //+ // Verified on the flow's BACKING TABLE, not on the flow row: activation creates an org-owned table+ // named `bpfUniqueName(flow.name)` (live-measured), and holding privileges on it is what lets a+ // persona run the process. Subset semantics as everywhere else — a persona legitimately holds far+ // more than this one grant.+ for (const f of spec.businessProcessFlows || []) {+ if (!f || !f.securityRoles || !Array.isArray(f.securityRoles.personas)) continue;+ if (typeof read.rolePrivileges !== 'function' || typeof read.entityPrivileges !== 'function') continue;+ // READ the deployed unique name, do not derive it. A flow authored in Maker, or one renamed+ // after creation, keeps a `uniquename` unrelated to its display name — and that name IS the+ // backing table. Verifying against the derivation would report a real grant as missing, or (if+ // an unrelated table happens to hold the derived name) PASS while the actual flow is ungranted,+ // which is the worse of the two. Falls back to the derivation only when the row cannot be read,+ // where it remains correct for anything this tool created.+ // See https://learn.microsoft.com/en-us/power-automate/developer/business-process-flows-code+ //+ // Three outcomes, kept apart because two of them used to collapse into one. A successful query+ // returning NO ROWS means the flow does not exist — it was never created, or never activated —+ // and the derivation must NOT be used then: `bpfUniqueName(f.name)` could coincide with an+ // unrelated table, whose privileges would verify clean and report a PASS for a flow that is+ // absent. That is the one direction this check exists to prevent. A read that THREW is different:+ // we could not look, so the derivation stands and the privilege read below fails closed anyway.+ let backingTable = bpfUniqueName(f.name);+ let flowMissing = false;+ try {+ const rows = await read.queryRecords('workflow', {+ select: ['workflowid', 'uniquename'],+ filter: bpfFilter(f.name, String(f.entity).toLowerCase()),+ orderBy: 'createdon asc',+ top: 5,+ });+ const row = rows && rows[0];+ if (!row) flowMissing = true;+ else if (row.uniquename) backingTable = String(row.uniquename).toLowerCase();+ // A row WITHOUT a uniquename keeps the derivation: the flow demonstrably exists, so the+ // derived name is the best available answer for anything this tool created.+ } catch { /* could not look — keep the derivation; the privilege read below fails closed */ }+ if (flowMissing) {+ add('bpf-roles', f.name, false,+ `no business process flow named '${f.name}' exists on '${String(f.entity).toLowerCase()}', so its backing table cannot be identified and no role grant on it can be verified`);+ continue;+ }+ let privs = null;+ try {+ privs = await read.entityPrivileges(backingTable);+ } catch { privs = null; }+ if (!Array.isArray(privs)) {+ // Fail CLOSED: an unreadable backing table is not proof the grant landed. It also catches the+ // realistic case that the flow never activated, so the table does not exist at all.+ add('bpf-roles', f.name, false, `could not read privileges for the flow's backing table '${backingTable}' — it is created by ACTIVATION, so this also means the flow may not be active`);+ continue;+ }+ for (const personaName of f.securityRoles.personas) {+ // Resolve the reference to the persona's CANONICAL name, case-insensitively — the validator+ // accepts a case-mismatched reference, and the deployed role carries the persona's own casing.+ // Querying `name eq '<as written>'` would miss it and report a real grant as missing.+ const declaredPersona = (spec.personas || []).find((p) => String(canonicalPersonaName(p) || '').toLowerCase() === String(personaName).trim().toLowerCase());+ const roleName = String((declaredPersona && canonicalPersonaName(declaredPersona)) || personaName).trim();+ let row;+ try {+ const bu = await resolveRoleBusinessUnit((e, o) => read.queryRecords(e, o), declaredPersona && declaredPersona.businessUnitId, roleBuCache);+ if (bu) {+ const rows = await read.queryRecords('role', { select: ['roleid', 'description', 'ismanaged'], filter: `name eq '${odataLit(roleName)}'${roleBuClause(bu)}`, top: 5 });+ row = (rows || []).find((r) => r.ismanaged !== true && (r.description || '') === SDK_ROLE_MARKER);+ }+ } catch { row = undefined; }+ if (!row) { add('bpf-roles', `${f.name} / ${roleName}`, false, 'persona role not found'); continue; }+ let actual = null;+ try { actual = await read.rolePrivileges(row.roleid); } catch { actual = null; }+ if (!Array.isArray(actual)) { add('bpf-roles', `${f.name} / ${roleName}`, false, "could not read the role's privileges"); continue; }+ const actualByPrivilegeId = new Map(actual.map((a) => [String((a && a.privilegeId) || '').trim().toLowerCase(), a && a.depth]));+ const declared = BPF_ROLE_ACCESS.map((access) => ({ entity: backingTable, access, scope: 'organization' }));+ const cmp = compareRolePrivileges(declared, new Map([[backingTable, privs]]), actualByPrivilegeId);+ add('bpf-roles', `${f.name} / ${roleName}`, cmp.ok, cmp.ok+ ? `${declared.length} privilege(s) held on ${backingTable}`+ : cmp.missing.map((m) => `${m.access}: ${m.reason}`).join('; '));+ }+ }+// AI app features. The verifier previously had NO awareness of `spec.ai` at all, so a build whose// every requested AI feature was skipped (admin gate off) or silently not persisted still reported a// clean PASS — a false success signal for automation (ADO 6603383).@@ -484,9 +622,11 @@ async function verifySpec(spec, read, opts = {}) {// with three features written and ZERO verified: a clean PASS for features the platform may never// have stored. One resolver, both callers.//- // A feature the org gate SKIPPED therefore fails here, which is intended: the spec asked for it and- // it is not configured on the app. The effective value is still read, but only as context in the- // failure message ("in effect as X by environment fallback").+ // A feature whose write did not persist therefore FAILS here, which is intended: the spec asked for+ // it and it is not configured on the app. That includes one the SDK bucketed as `skipped` — since+ // AB#6688904 that means "attempted, absent, and an org gate reads off", i.e. an admin action is+ // outstanding, not that the request was withdrawn. The effective value is still read, but only as+ // context in the failure message ("in effect as X by environment fallback").//// Reader-gated like the other content checks: this needs BOTH `retrieveSetting` (context) and// `queryRecords` (the proof), so an existence-only reader skips it entirely rather than falling@@ -536,6 +676,77 @@ async function verifySpec(spec, read, opts = {}) {}}+ // AI row summaries (`ai.summaries`). AB#6689110.+ //+ // Without this a spec that REQUESTS a row summary verified clean when none was created: the build+ // legitimately degrades to a skip when the environment does not license AI Builder (see the+ // ai-features phase), but nothing downstream re-asserted the request, so a licensed-environment+ // failure and an unlicensed skip both ended in a green `PASS`. The reporter saw `PASS, 45/45` with+ // the requested summary absent — a build that reports success while a declared artifact does not+ // exist is the one outcome verification exists to prevent.+ //+ // `selectSummaryTables` is the SAME selector the build uses, so the set verified is exactly the set+ // requested — including the `default: 'off'` + per-table `enabled: true` opt-in the reporter used.+ // Duplicating the default-vs-override rule here would let the two drift, which is how a verifier+ // starts proving something other than what was built.+ //+ // The oracle is the `msdyn_aimodel` row the SDK creates, named `<entity> row summary` — the same+ // name the build's own orphan sweep matches, and the name the platform quotes back in its+ // duplicate-key error, so it is the stored value rather than a guess.+ //+ // Reader-gated: `queryRecords` only. A reader without it skips rather than guessing.+ //+ // AI-OPT-IN gated FIRST, via the shared predicate. `selectSummaryTables` is a candidate selector,+ // not an opt-in test: handed a spec with no `ai` block it reads `summaries` as `{}` — "default+ // auto" — and returns every entity with a descriptive column. Calling it ungated made verify FAIL+ // a spec that never mentioned AI, reporting "ai.summaries requests a row summary for 'x'" for a+ // summary nobody requested and the build never created. That is a false failure on the build's own+ // `--verify` exit code, and it hits most specs, since almost every table has a text column.+ const summaryTables = specOptsIntoAi(spec) ? selectSummaryTables(spec) : [];+ if (summaryTables.length && typeof read.queryRecords === 'function') {+ for (const logical of summaryTables) {+ const modelName = `${String(logical).toLowerCase()} row summary`;+ let rows = null;+ let readError = null;+ try {+ rows = await read.queryRecords('msdyn_aimodel', {+ select: ['msdyn_aimodelid', 'msdyn_name', 'statecode'],+ filter: `msdyn_name eq '${odataLit(modelName)}'`,+ top: 5,+ });+ } catch (e) { readError = (e && e.message) || String(e); }+ // Fail CLOSED. `msdyn_aimodel` is readable by any role that can run the build, so an+ // unreadable list is not evidence of absence — and reporting PASS on a read we could not make+ // is the same false confidence this check exists to remove.+ if (!Array.isArray(rows)) {+ add('ai-summary', logical, false,+ `could not read the AI model list to prove the requested row summary exists${readError ? `: ${readError}` : ''}`);+ continue;+ }+ const active = rows.filter((r) => Number(r && r.statecode) === 1);+ const present = active.length > 0;+ // `statecode` was selected but not USED — existence alone was the test. That is a reachable+ // false PASS rather than a theoretical one: on an environment that does not license the+ // row-summary capability the SDK CREATES the `msdyn_aimodel` row and only then fails to+ // publish it, leaving a committed but unusable row behind (the same orphan the build's own+ // sweep tries to remove, and deliberately leaves in place when it cannot). Verify then found a+ // row with the right name and reported PASS for a summary nobody can use.+ //+ // The encoding is MEASURED from the environment's own metadata, not assumed:+ // EntityDefinitions(LogicalName='msdyn_aimodel')/Attributes(LogicalName='statecode') →+ // 0 = Inactive (defaultStatus 0), 1 = Active (defaultStatus 1)+ // See https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities+ add('ai-summary', logical, present, present ? `'${modelName}' exists and is active` :+ rows.length+ ? `ai.summaries requests a row summary for '${logical}', and an AI model named '${modelName}' exists but is INACTIVE `+ + `(statecode ${rows.map((r) => Number(r && r.statecode)).join(', ')}). The model row is created before it is published, so an `+ + 'environment that does not license the row-summary (AI Builder) capability leaves exactly this behind — the summary will not run.'+ : `ai.summaries requests a row summary for '${logical}', but no AI model named '${modelName}' exists in this environment. `+ + 'The build reports this as a skip when the environment does not license the row-summary (AI Builder) capability — '+ + 'run against a licensed environment, or set the table to enabled:false so the spec stops requesting it.');+ }+ }+// JTBD rollup — translates a technical failure into the business impact it caused. Every other// check answers "is this artifact deployed?"; this one answers "can this persona still do this// job?".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.jsindex 70a73ea95..b44688279 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@@ -20,9 +20,10 @@ const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');const APP = 'co_supportdesk';const APP_ID = '11111111-1111-1111-1111-111111111111';-// The PER-APP setting for formFill. Note it doubles as its own org gate in the SDK's AI_GATE map,-// which is why the gate is deliberately read at ORG scope (an app-scope 0 must not look like "the-// environment forbids this" and permanently block re-enabling).+// The PER-APP setting for formFill. It doubles as its own "gate" in the SDK's AI_GATE map — which is+// precisely why the SDK no longer reads it as one (AB#6688904): the row it would consult is the row+// the write is about to set, so on a new app the platform default `0` read as "the environment+// forbids this" and pre-empted every write.const SETTING = 'FormFillBarUXEnabled';const DEF_ID = '22222222-2222-2222-2222-222222222222';@@ -118,11 +119,10 @@ test('REAL BUNDLE: a write that becomes visible late is retried and reported apptest('REAL BUNDLE: an unreadable override row is `unverified`, never applied and never notPersisted', async () => {// The ORG GATE and the PER-APP setting use different encodings, which is easy to conflate: the- // per-app form-fill value is 0=platform default / 1=disabled / 2=enabled, but the gate- // short-circuits only on '0'. MEASURED by mutating this fixture: '0' makes both this test and the- // next FAIL (the SDK skips before it writes or proves), while '1' and '2' both reach the path and- // pass identically. '2' is used here purely so a fixture for a `formFill: true` request does not- // read as "disabled".+ // per-app form-fill value is 0=platform default / 1=disabled / 2=enabled. The gate value no longer+ // decides whether this path is reached at all — since AB#6688904 the write and the proof always+ // run — so `gate` here is inert and `'2'` is used purely so a fixture for a `formFill: true`+ // request does not read as "disabled".const { sdk } = freshSdk({ gate: '2', effective: '2', failProof: true });const r = await sdk.setAppAiFeatures(APP, { formFill: true }, FAST);assert.deepStrictEqual(r.unverified, ['formFill']);@@ -138,11 +138,36 @@ test('REAL BUNDLE: a throwing write lands in `failed` and does not abort the batassert.match(r.outcomes[0].reason, /boom from SaveSettingValue/);});-test('REAL BUNDLE: an org gate that is off yields `skipped` and issues no write', async () => {+// AB#6688904 rewrote this contract, and the two tests below are the new pinning pair. The OLD+// behaviour — "an org gate that is off yields `skipped` and issues NO write" — is exactly the defect:+// the gate was read as a PRECONDITION, and for four of the seven features that "gate" is the very row+// the write is about to set, so a brand-new app (value `0`, the platform default) looked forbidden and+// the build shipped an app with no AI features while reporting success.+//+// The new contract is: always write, then verify, and read a gate only to EXPLAIN an absence. So the+// bucket now depends on whether the feature HAS an independent gate, which is what these two separate.+test('REAL BUNDLE: a gate that is off no longer pre-empts the write — it is issued, then explained as `skipped`', async () => {+ // `nlSearch` has a genuinely distinct gate (`EnableNLGridSearch`) from its per-app setting+ // (`NLGridSearchSetting`), so a gate-off diagnosis is meaningful for it.+ const { sdk, calls } = freshSdk({ gate: '0', effective: '0', overrideRows: [] });+ const r = await sdk.setAppAiFeatures(APP, { nlSearch: true }, FAST);+ assert.deepStrictEqual(r.skipped, ['nlSearch'], 'an absent override plus a gate reading off is `skipped`');+ const writes = calls.filter((c) => c.method === 'POST' && c.url.includes('SaveSettingValue'));+ assert.strictEqual(writes.length, 1, 'the write MUST be attempted — pre-empting it was the bug');+ // The engine defers `skipped` to its post-publish re-issue on the strength of this: the outcome is+ // evidence about one attempt, not a verdict that the app can never hold the setting.+ assert.strictEqual(r.outcomes[0].appOverrideExists, false, 'skipped now carries a real verification result');+});++test('REAL BUNDLE: a SELF-GATED feature has no gate to blame — an absent override is notPersisted, never skipped', async () => {+ // `formFill` reads `FormFillBarUXEnabled` for BOTH its gate and its per-app value. `0` there is the+ // platform default on a new app, not an admin saying no, so there is nothing to diagnose with and+ // the honest bucket is `notPersisted`. Reporting `skipped` here would re-tell the AB#6688904 story.const { sdk, calls } = freshSdk({ gate: '0', effective: '0', overrideRows: [] });const r = await sdk.setAppAiFeatures(APP, { formFill: true }, FAST);- assert.deepStrictEqual(r.skipped, ['formFill']);- assert.strictEqual(calls.filter((c) => c.method === 'POST' && c.url.includes('SaveSettingValue')).length, 0);+ assert.deepStrictEqual(r.skipped, [], 'a self-gated feature can never be `skipped`');+ assert.deepStrictEqual(r.notPersisted, ['formFill']);+ assert.strictEqual(calls.filter((c) => c.method === 'POST' && c.url.includes('SaveSettingValue')).length, 1);});test('REAL BUNDLE: disabling is never gated — it writes even when the org gate is off', async () => {diff --git a/plugins/model-apps/scripts/tests/app-spec-keys.test.js b/plugins/model-apps/scripts/tests/app-spec-keys.test.jsindex d45bbb90d..611ad40c1 100644--- a/plugins/model-apps/scripts/tests/app-spec-keys.test.js+++ b/plugins/model-apps/scripts/tests/app-spec-keys.test.js@@ -220,16 +220,29 @@ test('#537: entities[].languageCode is rejected and names the spec-level languag}});-test('#537: entities[].localizedLabels is rejected and says multi-language is unsupported', () => {- for (const profile of ['plan', 'deploy']) {- const s = base();- s.entities[0].localizedLabels = { 3082: 'Cliente', 1033: 'Customer' };- const r = validateAppSpec(s, { profile });- const hit = (r.errors || []).find((e) => /unknown key 'localizedLabels'/.test(e));- assert.ok(hit, `${profile}: ` + JSON.stringify(r.errors));- assert.match(hit, /multi-language labels are not supported/);- }-});+test('#537: entities[].localizedLabels is rejected, and names the shape that DOES work', () => {+ // The key stays rejected after 2.7.0 added multi-language labels — but for a different reason, and+ // the message had to change with it. A localized label is an LCID map on the label FIELD; a+ // separate per-table block cannot address a Choice OPTION or a lookup's display name without+ // inventing a parallel addressing scheme. So "not supported" became "write it here instead",+ // which is the whole point of rejecting a key rather than dropping it.+ for (const profile of ['plan', 'deploy']) {+ const s = base();+ s.entities[0].localizedLabels = { 3082: 'Cliente', 1033: 'Customer' };+ const r = validateAppSpec(s, { profile });+ const hit = (r.errors || []).find((e) => /unknown key 'localizedLabels'/.test(e));+ assert.ok(hit, `${profile}: ` + JSON.stringify(r.errors));+ assert.match(hit, /LCID map on the label FIELD/, hit);+ assert.doesNotMatch(hit, /not supported/, `2.7.0 supports multi-language labels; the hint must not deny it: ${hit}`);+ }++ // And the shape it points at must actually validate, or the error sends the author into a wall.+ const ok = base();+ ok.entities[0].displayName = { 1033: 'Customer', 3082: 'Cliente' };+ ok.entities[0].pluralName = { 1033: 'Customers', 3082: 'Clientes' };+ assert.strictEqual(validateAppSpec(ok, { profile: 'plan' }).ok, true,+ JSON.stringify(validateAppSpec(ok, { profile: 'plan' }).errors));+});test('#537: a misspelled entity key fails loudly instead of being dropped', () => {const s = base();diff --git a/plugins/model-apps/scripts/tests/app-spec.test.js b/plugins/model-apps/scripts/tests/app-spec.test.jsindex cdefcbc8a..40ceb9cc7 100644--- a/plugins/model-apps/scripts/tests/app-spec.test.js+++ b/plugins/model-apps/scripts/tests/app-spec.test.js@@ -1176,3 +1176,40 @@ test('the value describer cannot itself throw (BigInt / a throwing getter)', ()assert.strictEqual(res.ok, false, `${label} must still be rejected`);}});++// --- AB#6686426: default-form selection must be deterministic --------------------------------------+//+// Promotion used to run INSIDE the concurrent per-form build, so every Main form on an owned custom+// table promoted itself and the LAST to finish won. Which form a table opened with therefore depended+// on completion order — an alternate read-only or OnSave-blocked form could silently become the+// default. Promotion is now ONE serialized pass after every form exists, choosing an explicit+// `isDefault` first and otherwise the first Main form in spec order.++const deskWithForms = (forms) => { const s = cloneDesk(); s.forms = forms; return s; };+const mainForm = (name, over = {}) => ({+ entity: desk.entities[0].schemaName, name, formType: 'Main',+ sections: [{ label: 'General', columns: [desk.entities[0].primaryAttribute.schemaName] }], ...over,+});++test('AB#6686426: isDefault must be a boolean', () => {+ const r = validateAppSpec(deskWithForms([mainForm('A', { isDefault: 'yes' })]), { profile: 'plan' });+ assert.strictEqual(r.ok, false);+ assert.match((r.errors || []).join(' | '), /isDefault must be a boolean/);+});++test('AB#6686426: two Main forms cannot both claim isDefault', () => {+ const r = validateAppSpec(deskWithForms([mainForm('A', { isDefault: true }), mainForm('B', { isDefault: true })]), { profile: 'plan' });+ assert.strictEqual(r.ok, false);+ assert.match((r.errors || []).join(' | '), /exactly one form can be the table's default/);+});++test('AB#6686426: isDefault on a NON-Main form is rejected — only Main forms are promoted', () => {+ const r = validateAppSpec(deskWithForms([mainForm('QC', { formType: 'QuickCreate', isDefault: true })]), { profile: 'plan' });+ assert.strictEqual(r.ok, false);+ assert.match((r.errors || []).join(' | '), /only meaningful on a Main form/);+});++test('AB#6686426: one isDefault among several Main forms is valid', () => {+ const r = validateAppSpec(deskWithForms([mainForm('A'), mainForm('B', { isDefault: true }), mainForm('C')]), { profile: 'plan' });+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));+});diff --git a/plugins/model-apps/scripts/tests/bpf-security-roles.test.js b/plugins/model-apps/scripts/tests/bpf-security-roles.test.jsnew file mode 100644index 000000000..3d360587c--- /dev/null+++ b/plugins/model-apps/scripts/tests/bpf-security-roles.test.js@@ -0,0 +1,627 @@+'use strict';+// Two things that came out of the same live-verification session, kept together because the second+// is what made the first testable:+//+// 1. #513 — Business Process Flow security-role grants.+// 2. The table existence probe defect (AB#6686428): the plugin's `findTables` idempotency probe+// silently dropped every non-base-language label on the real build path. See the dedicated+// section below; the localized-label surface itself is tested in localized-labels.test.js.+//+// The issue asked for live measurement BEFORE designing the surface ("assume the role path has its+// own such surprise"). It had two, and both shaped what is implemented:+//+// 1. The backing table's logical name is EXACTLY `bpfUniqueName(flow.name)` — the derivation this+// repo already duplicates for its collision check. The issue expected it to need resolving from+// the deployed workflow's `uniquename`; measured, they are the same string, so the grant needs+// no id plumbing and can be planned before the flow exists.+// 2. The backing table is ORGANIZATION-OWNED and every privilege reports CanBeGlobal only+// (Local/Deep/Basic all false). So there is no `scope` to author.+//+// Measured on a live org, on a flow named "Probe Flow 217190":+// backing table new_probeflow217190 ownership=OrganizationOwned isCustom=true+// privileges Create(G) Read(G) Write(G) Delete(G) Append(G) AppendTo(G)+// addEntityPrivilegesToRole(...) -> role held prvReadnew_probeflow217190 afterwards (was false)+const { test } = require('node:test');+const assert = require('node:assert');+const { validateAppSpec, bpfUniqueName, BPF_ROLE_ACCESS, SDK_ROLE_MARKER } = require('../lib/app-spec.js');+const { planFor, runSdkBuild } = require('../lib/sdk-build.js');++const PERSONA = { persona: 'Dispatcher', jobs: [{ name: 'Dispatch', privileges: [{ entity: 'contoso_ticket', access: ['read'] }] }] };+const FLOW = {+ name: 'Ticket Handling',+ entity: 'contoso_ticket',+ status: 'Active',+ stages: [{ name: 'Triage', steps: [{ name: 'Notes', field: 'contoso_notes' }] }],+};++function base(flowExtra = {}) {+ return {+ schemaVersion: 2,+ solution: { uniqueName: 'contoso', publisherPrefix: 'contoso' },+ app: { name: 'Contoso' },+ entities: [{ schemaName: 'contoso_ticket', displayName: 'Ticket', primaryAttribute: { schemaName: 'contoso_name' }, columns: [{ schemaName: 'contoso_notes', type: 'Text' }] }],+ personas: [PERSONA],+ businessProcessFlows: [{ ...FLOW, ...flowExtra }],+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'Main', subAreas: [] }] }] },+ };+}+const errorsFor = (flowExtra) => validateAppSpec(base(flowExtra), { profile: 'plan' }).errors || [];++// --- shape ----------------------------------------------------------------------------------------++test('#513 a flow may name the personas that can run it', () => {+ const s = base({ securityRoles: { personas: ['Dispatcher'] } });+ const r = validateAppSpec(s, { profile: 'deploy' });+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));+});++test('#513 absent stays valid — the block is optional', () => {+ assert.strictEqual(validateAppSpec(base(), { profile: 'deploy' }).ok, true);+});++test('#513 an unknown persona is rejected, like forms[].securityRoles', () => {+ assert.ok(errorsFor({ securityRoles: { personas: ['Nobody'] } }).some((e) => /is not declared in personas\[\]/.test(e)));+});++test('#513 a duplicate persona is rejected', () => {+ assert.ok(errorsFor({ securityRoles: { personas: ['Dispatcher', 'dispatcher'] } }).some((e) => /more than once/.test(e)));+});++test('#513 the FORM-only knobs are rejected BY NAME, explaining why', () => {+ // `everyone` / `fallbackForm` / `order` are formxml concepts. A flow's access is a privilege on a+ // table, so there is no <Everyone /> equivalent and no ordering — saying so is the whole point,+ // because the author reasonably expects one idiom to work everywhere.+ for (const k of ['everyone', 'fallbackForm', 'order']) {+ const errs = errorsFor({ securityRoles: { personas: ['Dispatcher'], [k]: true } });+ const hit = errs.find((e) => new RegExp(`securityRoles has unknown key '${k}'`).test(e));+ assert.ok(hit, `${k}: ${JSON.stringify(errs)}`);+ assert.match(hit, /PRIVILEGE on its backing table/);+ }+});++test('#513 an EMPTY personas[] is rejected — unlike a form, a flow defaults to nobody', () => {+ // A form with no assignment is offered to EVERY role, so an empty list there is a narrowing. A+ // flow's backing table grants to nobody by default, so an empty list is a request that cannot be+ // satisfied — silently granting nothing would leave the flow unusable with a green build.+ const errs = errorsFor({ securityRoles: { personas: [] } });+ const hit = errs.find((e) => /securityRoles.personas is empty/.test(e));+ assert.ok(hit, JSON.stringify(errs));+ assert.match(hit, /grants access to nobody by default/);+});++test('#513 securityRoles on a DRAFT flow is rejected — activation creates the table', () => {+ // Measured: the backing table is created by ACTIVATION. A Draft flow has none, so the grant would+ // target a table that does not exist. That is an authoring error, catchable before any write.+ const errs = errorsFor({ status: 'Draft', securityRoles: { personas: ['Dispatcher'] } });+ const hit = errs.find((e) => /cannot be applied to a Draft flow/.test(e));+ assert.ok(hit, JSON.stringify(errs));+ assert.match(hit, /created by ACTIVATION/);+});++test('#513 there is no scope knob, because the platform allows only one depth', () => {+ // The backing table is organization-owned and its privileges report CanBeGlobal only. Offering a+ // `scope` the platform rejects would be a knob that cannot work.+ assert.deepStrictEqual(BPF_ROLE_ACCESS, ['create', 'read', 'write', 'delete']);+ const errs = errorsFor({ securityRoles: { personas: ['Dispatcher'], scope: 'user' } });+ assert.ok(errs.some((e) => /securityRoles has unknown key 'scope'/.test(e)), JSON.stringify(errs));+});++// --- plan -----------------------------------------------------------------------------------------++test('#513 the plan names the flow AND its backing table', () => {+ // The backing table is the thing actually granted on, and its name is derived rather than written+ // by the author — so a dry run has to show it, or the author cannot tell what will be touched.+ const labels = planFor(base({ securityRoles: { personas: ['Dispatcher'] } }), {}).map((p) => p.label);+ assert.ok(labels.some((l) => /flow roles for Ticket Handling \(backing table new_tickethandling\)/.test(l)), labels.join(' | '));+ assert.strictEqual(bpfUniqueName('Ticket Handling'), 'new_tickethandling');+});++// --- the label-loss defect found while live-verifying (AB#6686428) --------------------------------++test('the table existence probe is a NARROW metadata read, not findTables', async () => {+ // FOUND BY LIVE VERIFICATION, and it made the whole localized-label feature a no-op on the real+ // build path while every unit test passed. Order-controlled measurement, 8 tables in the sequence+ // C,F,F,C,C,F,F,C so each arm appears early and late:+ //+ // create only kept both languages 4/4+ // findTables + create kept both languages 0/4+ //+ // The outgoing EntityDefinitions body is byte-identical either way, so the loss is caused by the+ // preceding unfiltered `EntityDefinitions?$select=...DisplayName...` read that `findTables` issues,+ // not by the create payload. Switching the probe to a narrow single-table read took the plugin+ // path from 0/4 to 4/4 against the same org.+ //+ // This test pins the MECHANISM (which read is issued), because the consequence is only observable+ // against an org with two languages provisioned.+ const { provisionDataModel } = require('../lib/entity-provision.js');+ const gets = [];+ const runner = {+ run: async (p, l, fn, o = {}) => { try { return await fn(); } catch (e) { if (o.skipIf && o.skipIf(e)) return undefined; throw e; } },+ skip: () => {},+ mapLimit: async (items, _n, fn) => { const out = []; for (const it of items) out.push(await fn(it)); return out; },+ };+ const created = [];+ const sdk = {+ createTable: async (o) => { created.push(o); return { logicalName: o.schemaName.toLowerCase(), entitySetName: `${o.schemaName.toLowerCase()}s` }; },+ createColumn: async (e, o) => ({ logicalName: o.schemaName.toLowerCase() }),+ updateTable: async () => undefined,+ };+ const provision = {+ dataverse: { get: async (url) => { gets.push(url); return { status: 404, headers: {}, body: {} }; } },+ findTables: async () => { throw new Error('findTables must NOT be used before createTable — it drops non-base-language labels'); },+ findColumns: async () => [],+ fetchEntityMetadata: async (l) => ({ logicalName: l, entitySetName: `${l}s`, relationships: [] }),+ queryRecords: async () => [],+ };+ const spec = {+ solution: { uniqueName: 'contoso', publisherPrefix: 'contoso' },+ languageCode: 1033,+ entities: [{ schemaName: 'contoso_probe', displayName: { 1033: 'Probe', 3082: 'Sonda' }, pluralName: { 1033: 'Probes', 3082: 'Sondas' }, primaryAttribute: { schemaName: 'contoso_name' }, columns: [] }],+ relationships: [],+ };+ await provisionDataModel({ spec, sdk, provision, runner, preResolvedLanguageCode: 1033 });+ assert.strictEqual(gets.length, 1, JSON.stringify(gets));+ assert.match(gets[0], /^\/EntityDefinitions\(LogicalName='contoso_probe'\)\?\$select=LogicalName,EntitySetName$/, gets[0]);+ // ...and the create still carried BOTH languages, unflattened.+ assert.deepStrictEqual(created[0].displayName, { 1033: 'Probe', 3082: 'Sonda' });+});++test('a 404 from the narrow probe means "absent", and a 200 means "reuse"', async () => {+ const { provisionDataModel } = require('../lib/entity-provision.js');+ const runner = {+ run: async (p, l, fn, o = {}) => { try { return await fn(); } catch (e) { if (o.skipIf && o.skipIf(e)) return undefined; throw e; } },+ skip: () => {},+ mapLimit: async (items, _n, fn) => { const out = []; for (const it of items) out.push(await fn(it)); return out; },+ };+ const mk = (status, body) => {+ const created = [];+ return {+ created,+ sdk: { createTable: async (o) => { created.push(o); return { logicalName: o.schemaName.toLowerCase(), entitySetName: 'xs' }; }, createColumn: async (e, o) => ({ logicalName: o.schemaName }), updateTable: async () => undefined },+ provision: {+ dataverse: { get: async () => ({ status, headers: {}, body }) },+ findColumns: async () => [],+ fetchEntityMetadata: async (l) => ({ logicalName: l, entitySetName: 'xs', relationships: [] }),+ queryRecords: async () => [],+ },+ };+ };+ const spec = () => ({+ solution: { uniqueName: 'contoso', publisherPrefix: 'contoso' },+ languageCode: 1033,+ entities: [{ schemaName: 'contoso_probe', displayName: 'Probe', primaryAttribute: { schemaName: 'contoso_name' }, columns: [] }],+ relationships: [],+ });++ const absent = mk(404, {});+ await provisionDataModel({ spec: spec(), sdk: absent.sdk, provision: absent.provision, runner, preResolvedLanguageCode: 1033 });+ assert.strictEqual(absent.created.length, 1, 'a 404 must take the create path');++ const present = mk(200, { LogicalName: 'contoso_probe', EntitySetName: 'contoso_probes' });+ await provisionDataModel({ spec: spec(), sdk: present.sdk, provision: present.provision, runner, preResolvedLanguageCode: 1033 });+ assert.strictEqual(present.created.length, 0, 'a 200 must take the reuse path, not create a duplicate');+});++test('an INCONCLUSIVE probe falls back to findTables rather than assuming absent', async () => {+ // Assuming "absent" on a 500 would turn a transient read failure into a duplicate-create attempt.+ const { provisionDataModel } = require('../lib/entity-provision.js');+ const runner = {+ run: async (p, l, fn, o = {}) => { try { return await fn(); } catch (e) { if (o.skipIf && o.skipIf(e)) return undefined; throw e; } },+ skip: () => {},+ mapLimit: async (items, _n, fn) => { const out = []; for (const it of items) out.push(await fn(it)); return out; },+ };+ let findTablesCalled = 0;+ const created = [];+ await provisionDataModel({+ spec: {+ solution: { uniqueName: 'contoso', publisherPrefix: 'contoso' },+ languageCode: 1033,+ entities: [{ schemaName: 'contoso_probe', displayName: 'Probe', primaryAttribute: { schemaName: 'contoso_name' }, columns: [] }],+ relationships: [],+ },+ sdk: { createTable: async (o) => { created.push(o); return { logicalName: 'contoso_probe', entitySetName: 'xs' }; }, createColumn: async () => ({}), updateTable: async () => undefined },+ provision: {+ dataverse: { get: async () => ({ status: 503, headers: {}, body: {} }) },+ findTables: async () => { findTablesCalled += 1; return [{ logicalName: 'contoso_probe', entitySetName: 'contoso_probes' }]; },+ findColumns: async () => [],+ fetchEntityMetadata: async (l) => ({ logicalName: l, entitySetName: 'xs', relationships: [] }),+ queryRecords: async () => [],+ },+ runner,+ preResolvedLanguageCode: 1033,+ });+ assert.strictEqual(findTablesCalled, 1, 'an inconclusive status must fall back');+ assert.strictEqual(created.length, 0, 'and the fallback found it, so no duplicate create');+});++test('the COLUMN existence probe is a narrow read too — the reuse path was missed first time', async () => {+ // The table probe fix above was INCOMPLETE. `findColumns` poisons `createColumn` identically, and+ // it is called on the table-REUSE branch — i.e. adding a column to a table that already exists,+ // which is exactly the scenario AB#6686428 was reported against. A fresh-table build never reaches+ // it, which is why both the first fix and the end-to-end verification missed it.+ //+ // Order-controlled, 8 columns, C,F,F,C,C,F,F,C:+ // createColumn only kept both languages 4/4+ // findColumns + createColumn kept both languages 0/4+ // After the fix, the plugin's reuse path measured 4/4 against the same org.+ const { provisionDataModel } = require('../lib/entity-provision.js');+ const gets = [];+ const runner = {+ run: async (p, l, fn, o = {}) => { try { return await fn(); } catch (e) { if (o.skipIf && o.skipIf(e)) return undefined; throw e; } },+ skip: () => {},+ mapLimit: async (items, _n, fn) => { const out = []; for (const it of items) out.push(await fn(it)); return out; },+ };+ const createdColumns = [];+ const sdk = {+ createTable: async () => { throw new Error('the table exists — the reuse branch must not create it'); },+ createColumn: async (e, o) => { createdColumns.push(o); return { logicalName: o.schemaName.toLowerCase() }; },+ updateTable: async () => undefined,+ updateColumn: async () => undefined,+ };+ const provision = {+ dataverse: {+ get: async (url) => {+ gets.push(url);+ if (/^\/EntityDefinitions\(LogicalName='contoso_probe'\)\?/.test(url)) {+ return { status: 200, headers: {}, body: { LogicalName: 'contoso_probe', EntitySetName: 'contoso_probes' } };+ }+ if (/\/Attributes\?/.test(url)) {+ return { status: 200, headers: {}, body: { value: [{ LogicalName: 'contoso_name', RequiredLevel: { Value: 'ApplicationRequired' } }] } };+ }+ return { status: 404, headers: {}, body: {} };+ },+ },+ findColumns: async () => { throw new Error('findColumns must NOT be used before createColumn — it drops non-base-language labels'); },+ findTables: async () => { throw new Error('findTables must NOT be used before a create'); },+ fetchEntityMetadata: async (l) => ({ logicalName: l, entitySetName: 'contoso_probes', relationships: [] }),+ queryRecords: async () => [],+ };+ await provisionDataModel({+ spec: {+ solution: { uniqueName: 'contoso', publisherPrefix: 'contoso' },+ languageCode: 1033,+ entities: [{ schemaName: 'contoso_probe', displayName: 'Probe', primaryAttribute: { schemaName: 'contoso_name' }, columns: [{ schemaName: 'contoso_note', type: 'Text', displayName: { 1033: 'Note', 3082: 'Nota' } }] }],+ relationships: [],+ },+ sdk, provision, runner, preResolvedLanguageCode: 1033,+ });+ assert.ok(gets.some((u) => /^\/EntityDefinitions\(LogicalName='contoso_probe'\)\/Attributes\?\$select=LogicalName,RequiredLevel$/.test(u)), JSON.stringify(gets));+ const note = createdColumns.find((c) => c.schemaName === 'contoso_note');+ assert.ok(note, JSON.stringify(createdColumns));+ assert.deepStrictEqual(note.displayName, { 1033: 'Note', 3082: 'Nota' });+});++test('an unreadable column list does NOT fall back to findColumns — that would re-poison the labels', async () => {+ // The obvious fallback is exactly the bug. `findColumns` is the poisoning read this function+ // exists to avoid, and this branch is the one where `createColumn` is guaranteed to run next, so+ // falling back would silently restore the defect on the very path it targets. Instead: warn, treat+ // every column as new, and let the create's already-exists handling de-duplicate.+ const { provisionDataModel } = require('../lib/entity-provision.js');+ let findColumnsCalled = 0;+ const createdColumns = [];+ const warnings = [];+ const runner = {+ run: async (p, l, fn, o = {}) => { try { return await fn(); } catch (e) { if (o.skipIf && o.skipIf(e)) return undefined; throw e; } },+ skip: () => {},+ mapLimit: async (items, _n, fn) => { const out = []; for (const it of items) out.push(await fn(it)); return out; },+ };+ await provisionDataModel({+ spec: {+ solution: { uniqueName: 'contoso', publisherPrefix: 'contoso' },+ languageCode: 1033,+ entities: [{ schemaName: 'contoso_probe', displayName: 'Probe', primaryAttribute: { schemaName: 'contoso_name' }, columns: [{ schemaName: 'contoso_note', type: 'Text', displayName: 'Note' }] }],+ relationships: [],+ },+ sdk: { createColumn: async (e, o) => { createdColumns.push(o); return { logicalName: o.schemaName }; }, updateTable: async () => undefined, updateColumn: async () => undefined },+ provision: {+ dataverse: {+ get: async (url) => {+ if (/^\/EntityDefinitions\(LogicalName='contoso_probe'\)\?/.test(url)) return { status: 200, headers: {}, body: { LogicalName: 'contoso_probe', EntitySetName: 'contoso_probes' } };+ return { status: 503, headers: {}, body: {} };+ },+ },+ findColumns: async () => { findColumnsCalled += 1; return [{ logicalName: 'contoso_note' }]; },+ fetchEntityMetadata: async (l) => ({ logicalName: l, entitySetName: 'contoso_probes', relationships: [] }),+ queryRecords: async () => [],+ },+ runner,+ warn: (m) => warnings.push(String(m)),+ preResolvedLanguageCode: 1033,+ });+ assert.strictEqual(findColumnsCalled, 0, 'the poisoning fallback must NOT run when a raw client is present');+ assert.strictEqual(createdColumns.length, 1, 'every column looks new, and create de-duplicates the existing one');+ assert.ok(+ warnings.some((w) => /could not read existing columns for contoso_probe/.test(w) && /503/.test(w)),+ `the degradation must be warned about, not silent — got ${JSON.stringify(warnings)}`,+ );+});++test('a raw read that THROWS is handled too — the client throws only on a persistent transport error', async () => {+ // `findExistingTable` and `findExistingColumns` must behave identically here. The az-backed client+ // resolves `{status}` for 404s and even persistent 5xx, and throws only when the transport itself+ // never produced a response; letting that propagate would abort a build over a blip that the+ // documented fallbacks are designed to survive.+ const { provisionDataModel } = require('../lib/entity-provision.js');+ const createdColumns = [];+ const warnings = [];+ let findTablesCalled = 0;+ const runner = {+ run: async (p, l, fn, o = {}) => { try { return await fn(); } catch (e) { if (o.skipIf && o.skipIf(e)) return undefined; throw e; } },+ skip: () => {},+ mapLimit: async (items, _n, fn) => { const out = []; for (const it of items) out.push(await fn(it)); return out; },+ };+ await provisionDataModel({+ spec: {+ solution: { uniqueName: 'contoso', publisherPrefix: 'contoso' },+ languageCode: 1033,+ entities: [{ schemaName: 'contoso_probe', displayName: 'Probe', primaryAttribute: { schemaName: 'contoso_name' }, columns: [{ schemaName: 'contoso_note', type: 'Text', displayName: 'Note' }] }],+ relationships: [],+ },+ sdk: {+ createTable: async () => ({ logicalName: 'contoso_probe', entitySetName: 'contoso_probes' }),+ createColumn: async (e, o) => { createdColumns.push(o); return { logicalName: o.schemaName }; },+ updateTable: async () => undefined,+ updateColumn: async () => undefined,+ },+ provision: {+ dataverse: { get: async () => { throw new Error('ECONNRESET'); } },+ findTables: async () => { findTablesCalled += 1; return []; },+ fetchEntityMetadata: async (l) => ({ logicalName: l, entitySetName: 'contoso_probes', relationships: [] }),+ queryRecords: async () => [],+ },+ runner,+ warn: (m) => warnings.push(String(m)),+ preResolvedLanguageCode: 1033,+ });+ // The table probe threw, so it fell back to findTables (which cannot poison a table that is about+ // to be CREATED — the poisoning is read-then-create on the SAME object, and this table is absent).+ assert.strictEqual(findTablesCalled, 1, 'a thrown table probe must fall back rather than abort the build');+ assert.strictEqual(createdColumns.length, 1, 'and the build proceeded to create the column');+});++function securitySdk(over = {}) {+ const calls = { addEntityPrivilegesToRole: [] };+ return {+ calls,+ queryRecords: async (entity) => {+ if (entity === 'businessunit') return [{ businessunitid: '44444444-4444-4444-4444-444444444444' }];+ return [];+ },+ createPersonaRole: async (s) => ({ roleId: '55555555-5555-5555-5555-555555555555', name: s.name, reused: false, appliedPrivileges: [] }),+ addEntityPrivilegesToRole: async (roleId, privileges) => { calls.addEntityPrivilegesToRole.push({ roleId, privileges }); return []; },+ addSolutionComponent: async () => ({}),+ associateRecords: async () => ({}),+ disassociateRecords: async () => ({}),+ ...over,+ };+}++async function applySecurity(spec, sdk, seedFlow = true) {+ return runSdkBuild(spec, {+ sdk, provisionSdk: sdk, apply: true, phases: ['security'],+ // The security phase reads `created.businessProcessFlows`, which the flow phase fills. Seed it+ // the way a full build would, so this exercises the grant rather than the skip path.+ ...(seedFlow ? { changedOnly: undefined } : {}),+ });+}++test('#513 apply grants the fixed access set on the BACKING TABLE at organization scope', async () => {+ // Runs the flow phase too, so `created.businessProcessFlows` is populated the way a real build+ // does — otherwise this would only ever exercise the skip path below.+ const s = base({ securityRoles: { personas: ['Dispatcher'] } });+ const sdk = securitySdk({+ queryRecords: async (entity) => {+ if (entity === 'businessunit') return [{ businessunitid: '44444444-4444-4444-4444-444444444444' }];+ if (entity === 'workflow') return []; // no existing flow -> create path+ return [];+ },+ createArtifact: (type, def) => ({ id: '66666666-6666-6666-6666-666666666666', type, def }),+ pushArtifact: async (type, id) => ({ ok: true, id }),+ activateArtifact: async () => ({ ok: true }),+ updateRecord: async () => ({}),+ });+ const r = await runSdkBuild(s, {+ sdk, provisionSdk: sdk, apply: true,+ phases: ['business-process-flows', 'security'], emit: () => undefined,+ });+ assert.strictEqual(r.ok, true, JSON.stringify(r).slice(0, 400));+ assert.strictEqual(sdk.calls.addEntityPrivilegesToRole.length, 1, JSON.stringify(sdk.calls.addEntityPrivilegesToRole));+ const call = sdk.calls.addEntityPrivilegesToRole[0];+ assert.strictEqual(call.roleId, '55555555-5555-5555-5555-555555555555');+ // The DERIVED backing table, not the flow name and not the flow's own entity.+ assert.deepStrictEqual(call.privileges, [{ entity: 'new_tickethandling', access: ['create', 'read', 'write', 'delete'], scope: 'organization' }]);+ assert.deepStrictEqual(r.created.bpfRoleGrants['Ticket Handling'], { backingTable: 'new_tickethandling', personas: ['Dispatcher'] });+});++test('#513 a persona is matched CASE-INSENSITIVELY — the author types the display name twice', async () => {+ // A persona is a DISPLAY name repeated by hand in two unrelated sections of the spec+ // (`personas[].persona` and `businessProcessFlows[].securityRoles.personas[]`). An exact-case+ // Map lookup made "dispatcher" vs "Dispatcher" silently grant nothing while the build reported+ // success — the worst failure mode for a security feature. The SPEC GATE also accepts the+ // mismatch, so a case-sensitive apply would contradict its own validator.+ const s = base({ securityRoles: { personas: ['dispatcher'] } }); // persona is declared as 'Dispatcher'+ assert.deepStrictEqual(validateAppSpec(s, { profile: 'plan' }).errors || [], [], 'the gate must accept it too');+ const sdk = securitySdk({+ queryRecords: async (entity) => {+ if (entity === 'businessunit') return [{ businessunitid: '44444444-4444-4444-4444-444444444444' }];+ if (entity === 'workflow') return [];+ return [];+ },+ createArtifact: (type, def) => ({ id: '66666666-6666-6666-6666-666666666666', type, def }),+ pushArtifact: async (type, id) => ({ ok: true, id }),+ activateArtifact: async () => ({ ok: true }),+ updateRecord: async () => ({}),+ });+ const r = await runSdkBuild(s, {+ sdk, provisionSdk: sdk, apply: true,+ phases: ['business-process-flows', 'security'], emit: () => undefined,+ });+ assert.strictEqual(r.ok, true, JSON.stringify(r).slice(0, 400));+ assert.strictEqual(sdk.calls.addEntityPrivilegesToRole.length, 1, 'the case-differing persona must still be granted');+ assert.deepStrictEqual(+ sdk.calls.addEntityPrivilegesToRole[0].privileges,+ [{ entity: 'new_tickethandling', access: ['create', 'read', 'write', 'delete'], scope: 'organization' }],+ );+});++test('#513 verify resolves the persona case-insensitively too, or it would report a false failure', async () => {+ // build and verify must agree. If build grants a case-differing persona but verify queries+ // `role` by the AS-WRITTEN casing, verify reports a missing grant that is actually present —+ // which is worse than no check, because it trains the operator to ignore the check.+ const { verifySpec } = require('../lib/verify-spec.js');+ const BACKING = 'new_tickethandling';+ const privs = BPF_ROLE_ACCESS.map((a) => ({+ Name: `prv${a[0].toUpperCase()}${a.slice(1)}${BACKING}`, PrivilegeId: `bpf-${a}`, PrivilegeType: a[0].toUpperCase() + a.slice(1),+ }));+ const queried = [];+ const read = {+ findTable: async () => null,+ findColumns: async () => [],+ sitemapXml: async () => '',+ queryRecords: async (set, o) => {+ if (set === 'businessunit') return [{ businessunitid: '44444444-4444-4444-4444-444444444444' }];+ if (set === 'role') {+ queried.push((o && o.filter) || '');+ // The DEPLOYED role carries the persona's own casing, and OData `eq` on a string is+ // case-INsensitive in Dataverse — but the row is only returned for the canonical name here,+ // so this asserts the resolver picked it rather than relying on server-side collation.+ return /'Dispatcher'/.test((o && o.filter) || '') ? [{ roleid: 'role-1', name: 'Dispatcher', description: SDK_ROLE_MARKER }] : [];+ }+ if (set === 'workflow') return [{ workflowid: 'w1', statecode: 1 }];+ return [];+ },+ entityPrivileges: async (t) => (t === BACKING ? privs : []),+ rolePrivileges: async () => BPF_ROLE_ACCESS.map((a) => ({ privilegeId: `bpf-${a}`, depth: 'Global' })),+ };+ const s = base({ securityRoles: { personas: ['DISPATCHER'] } });+ const r = await verifySpec(s, read);+ const c = r.checks.find((x) => x.kind === 'bpf-roles');+ assert.ok(c && c.present, `expected a passing bpf-roles check; filters=${JSON.stringify(queried)} check=${JSON.stringify(c)}`);+});++test('#513 verify FAILS when the flow does not exist, instead of probing a derived table name', async () => {+ // The fail-open this closes: with no workflow row, `deployed` was falsy and the DERIVED backing+ // name (`bpfUniqueName(flow.name)`) stayed in place. If an unrelated table happened to hold that+ // name and the persona happened to hold privileges on it, verify reported PASS for a business+ // process flow that does not exist at all. A successful query returning NO ROWS is positive+ // evidence of absence — quite different from a read that threw, where the derivation still stands+ // and the privilege read fails closed on its own.+ const { verifySpec } = require('../lib/verify-spec.js');+ const asked = [];+ const read = {+ findTable: async () => null,+ findColumns: async () => [],+ sitemapXml: async () => '',+ queryRecords: async (set) => {+ if (set === 'businessunit') return [{ businessunitid: '44444444-4444-4444-4444-444444444444' }];+ if (set === 'role') return [{ roleid: 'role-1', name: 'Dispatcher', description: SDK_ROLE_MARKER }];+ if (set === 'workflow') return []; // the flow was never created+ return [];+ },+ // The trap: a DIFFERENT table happens to carry the derived name and grants everything.+ entityPrivileges: async (t) => {+ asked.push(t);+ return BPF_ROLE_ACCESS.map((a) => ({ Name: `prv${a}`, PrivilegeId: `bpf-${a}`, PrivilegeType: a[0].toUpperCase() + a.slice(1) }));+ },+ rolePrivileges: async () => BPF_ROLE_ACCESS.map((a) => ({ privilegeId: `bpf-${a}`, depth: 'Global' })),+ };+ const r = await verifySpec(base({ securityRoles: { personas: ['Dispatcher'] } }), read);+ const c = r.checks.find((x) => x.kind === 'bpf-roles');+ assert.ok(c, 'a bpf-roles check must still be recorded');+ assert.strictEqual(c.present, false, `an absent flow must FAIL: ${JSON.stringify(c)}`);+ assert.match(c.detail, /no business process flow named/, c.detail);+ // Scoped to the DERIVED backing-table name. The persona role-privileges check legitimately reads+ // privileges for the spec's own entities, so asserting "nothing was asked" would fail for an+ // unrelated reason and prove nothing about this fix.+ const derived = require('../lib/app-spec.js').bpfUniqueName(FLOW.name);+ assert.ok(!asked.includes(derived),+ `it must not read privileges on '${derived}' — a name it could not confirm belongs to the flow; asked=${JSON.stringify(asked)}`);+});++test('#513 a flow the phase did not build is SKIPPED with a reason, never granted blind', async () => {+ // The backing table only exists once the flow is activated. Granting anyway would fail against a+ // missing table; skipping SILENTLY would report success while nobody can run the process.+ const s = base({ securityRoles: { personas: ['Dispatcher'] } });+ const sdk = securitySdk();+ const emitted = [];+ await runSdkBuild(s, { sdk, provisionSdk: sdk, apply: true, phases: ['security'], emit: (e) => emitted.push(e) });+ assert.strictEqual(sdk.calls.addEntityPrivilegesToRole.length, 0, 'must not grant when the flow was not built in this run');+ // The REASON has to reach the operator. runner.run does not emit a returned value, so this is+ // reported as a labelled SKIP — assert on that, not on a message that never leaves the closure.+ const skipped = emitted.find((e) => e.status === 'skip' && /flow roles for Ticket Handling/.test(e.label || ''));+ assert.ok(skipped, JSON.stringify(emitted.map((e) => `${e.status} ${e.label}`)));+ assert.match(skipped.label, /did not run in this invocation/);+});+// --- the backing table is READ BACK, not derived -------------------------------------------------++test('#513 a REUSED flow grants on its DEPLOYED uniquename, not the derivation', async () => {+ // A flow authored in Maker (or renamed after creation) keeps a `uniquename` unrelated to its+ // display name -- and that name IS the backing table. Deriving would grant on a table that does+ // not exist, or on an unrelated one that happens to hold the derived name.+ const s = base({ securityRoles: { personas: ['Dispatcher'] } });+ const sdk = securitySdk({+ queryRecords: async (entity) => {+ if (entity === 'businessunit') return [{ businessunitid: '44444444-4444-4444-4444-444444444444' }];+ if (entity === 'workflow') return [{ workflowid: 'w-existing', statecode: 1, createdon: '2020-01-01', uniquename: 'contoso_ticketprocess' }];+ return [];+ },+ updateRecord: async () => ({}),+ });+ const r = await runSdkBuild(s, {+ sdk, provisionSdk: sdk, apply: true,+ phases: ['business-process-flows', 'security'], emit: () => undefined, warn: () => undefined,+ });+ assert.strictEqual(r.ok, true, JSON.stringify(r).slice(0, 400));+ assert.strictEqual(sdk.calls.addEntityPrivilegesToRole.length, 1, JSON.stringify(sdk.calls.addEntityPrivilegesToRole));+ assert.strictEqual(sdk.calls.addEntityPrivilegesToRole[0].privileges[0].entity, 'contoso_ticketprocess',+ 'the DEPLOYED unique name, not bpfUniqueName("Ticket Handling")');+ assert.notStrictEqual(sdk.calls.addEntityPrivilegesToRole[0].privileges[0].entity, bpfUniqueName('Ticket Handling'),+ 'and the derivation really is different here, so this asserts something');+ assert.strictEqual(r.created.bpfRoleGrants['Ticket Handling'].backingTable, 'contoso_ticketprocess');+});++test('#513 a row with no uniquename falls back to the derivation rather than granting on undefined', async () => {+ // Older projections and test doubles do not model the field. The derivation is the right answer+ // for anything this tool created, so the fallback must stay -- but it must be a FALLBACK.+ const s = base({ securityRoles: { personas: ['Dispatcher'] } });+ const sdk = securitySdk({+ queryRecords: async (entity) => {+ if (entity === 'businessunit') return [{ businessunitid: '44444444-4444-4444-4444-444444444444' }];+ if (entity === 'workflow') return [{ workflowid: 'w-existing', statecode: 1, createdon: '2020-01-01' }];+ return [];+ },+ updateRecord: async () => ({}),+ });+ const r = await runSdkBuild(s, {+ sdk, provisionSdk: sdk, apply: true,+ phases: ['business-process-flows', 'security'], emit: () => undefined, warn: () => undefined,+ });+ assert.strictEqual(sdk.calls.addEntityPrivilegesToRole[0].privileges[0].entity, bpfUniqueName('Ticket Handling'));+});++test('#513 verify reads the deployed uniquename too, or build and verify disagree', async () => {+ const { verifySpec } = require('../lib/verify-spec.js');+ const DEPLOYED = 'contoso_ticketprocess';+ const privs = BPF_ROLE_ACCESS.map((a) => ({+ Name: `prv${a[0].toUpperCase()}${a.slice(1)}${DEPLOYED}`, PrivilegeId: `bpf-${a}`, PrivilegeType: a[0].toUpperCase() + a.slice(1),+ }));+ const asked = [];+ const read = {+ findTable: async () => null,+ findColumns: async () => [],+ sitemapXml: async () => '',+ queryRecords: async (set) => {+ if (set === 'businessunit') return [{ businessunitid: '44444444-4444-4444-4444-444444444444' }];+ if (set === 'role') return [{ roleid: 'role-1', name: 'Dispatcher', description: SDK_ROLE_MARKER }];+ if (set === 'workflow') return [{ workflowid: 'w1', statecode: 1, uniquename: DEPLOYED }];+ return [];+ },+ entityPrivileges: async (t) => { asked.push(t); return t === DEPLOYED ? privs : []; },+ rolePrivileges: async () => BPF_ROLE_ACCESS.map((a) => ({ privilegeId: `bpf-${a}`, depth: 'Global' })),+ };+ const r = await verifySpec(base({ securityRoles: { personas: ['Dispatcher'] } }), read);+ const c = r.checks.find((x) => x.kind === 'bpf-roles');+ assert.ok(c && c.present, `asked for: ${JSON.stringify(asked)}; check=${JSON.stringify(c)}`);+ assert.ok(asked.includes(DEPLOYED), 'verify must ask about the DEPLOYED table');+ assert.strictEqual(asked.includes(bpfUniqueName('Ticket Handling')), false, 'and never about the derivation');+});diff --git a/plugins/model-apps/scripts/tests/build-model-app.test.js b/plugins/model-apps/scripts/tests/build-model-app.test.jsindex 11ed97269..370f124bc 100644--- a/plugins/model-apps/scripts/tests/build-model-app.test.js+++ b/plugins/model-apps/scripts/tests/build-model-app.test.js@@ -555,13 +555,19 @@ test('unableToRun is propagated from verifySpec into r.verify (RECONCILIATION 1)});// -- verify wiring ------------------------------------------------------------------------------// Asserted against SOURCE because the wiring lives inside main(), which is not exported, and the-// failure mode is SILENT: verify-spec skips role-privileges unless BOTH readers are present, so-// omitting httpClient/envUrl made --apply --verify report a clean PASS having never checked what-// any persona role actually grants. Found live -- the standalone verifier ran 10 checks against the-// same app where the build inline verify ran 8. A behavioural test would need a live SDK; this pins-// the exact regression at zero cost.-test('build --verify wires the role-privilege readers (httpClient + envUrl)', () => {+// The failure mode being guarded is SILENT: verify-spec skips the role-privileges check unless BOTH+// `rolePrivileges` and `entityPrivileges` readers are present, so a build that under-wires them+// reports a clean `--apply --verify` PASS having never checked what any persona role actually grants.+// Found live — the standalone verifier ran 10 checks against the same app where the build's inline+// verify ran 8.+//+// This used to assert that the wiring line mentioned `httpClient` and `envUrl`, which the+// `entityPrivileges` reader needed to compose its own absolute `EntityDefinitions(...)` request. That+// read now goes through the SDK's `getEntityPrivileges`, so those two arguments are gone — and a test+// pinned to them would have failed for a change that STRENGTHENED what it guards. The assertions+// below are re-pointed at the invariant rather than the mechanism: build the reader from the exact+// options the build passes and check that neither privilege reader is missing.+test('build --verify wires readers that verify-spec will NOT skip role-privileges over', () => {const src = fs.readFileSync(path.join(__dirname, '..', 'build-model-app.js'), 'utf8');// Matched on the wiring, not the exact arity: the deps.verify lambda gained a second parameter so// the build can hand verify the artifacts this ENVIRONMENT could not host (an environment-gated@@ -569,20 +575,48 @@ test('build --verify wires the role-privilege readers (httpClient + envUrl)', ()// for a change that did not touch what it is actually guarding.const call = src.split(/\r?\n/).find((l) => /verify: \([^)]*\) => verifySpec/.test(l));assert.ok(call, 'expected the deps.verify wiring line');- assert.match(call, /httpClient/, 'entityPrivileges needs the raw client');- assert.match(call, /envUrl: env/, 'entityPrivileges needs the org url to build an absolute request');- // And the second argument must actually be forwarded, or the environment-skip list is silently+ assert.match(call, /readerFor\(provisionSdk,/, 'verify must read through the provisioning SDK');+ // The second argument must actually be forwarded, or the environment-skip list is silently// dropped and verify keeps failing on rules the build already reported it could not create.assert.match(call, /verifySpec\(\s*s\s*,[\s\S]*\)\s*,\s*verifyOpts\s*\)/,'the caller-supplied verify options must reach verifySpec');++ // The substantive half: the option bag on that line, fed to the real `readerFor`, must yield BOTH+ // privilege readers. A source match alone would keep passing if `entityPrivileges` were made+ // conditional again on something the build does not supply.+ const optsSrc = /readerFor\(provisionSdk,[^,]+,\s*(\{[^}]*\})\s*\)/.exec(call);+ assert.ok(optsSrc, `could not extract the readerFor options from: ${call}`);+ // Shorthand-aware: `{ genpageCli: makeGenpageCli(env), workspaceDir }` carries one `key:` and one+ // SHORTHAND key. A colon-only pattern silently saw just `genpageCli`, which made the assertion+ // below weaker than it looks — it would have kept passing for an option bag that had lost+ // `workspaceDir` entirely. Match a name followed by `:`, `,` or `}`.+ const optKeys = [...optsSrc[1].matchAll(/([A-Za-z_$][\w$]*)\s*(?::|[,}])/g)].map((m) => m[1]);+ assert.ok(optKeys.includes('workspaceDir') && optKeys.includes('genpageCli'),+ `expected both readerFor options to be extracted, got ${JSON.stringify(optKeys)}`);+ const { readerFor } = require('../verify-model-app.js');+ // A bare object is enough: every base reader is a lazy closure, so this asserts PRESENCE, which is+ // exactly what verify-spec's method-presence gate tests.+ const reader = readerFor({}, 'contoso_app', Object.fromEntries(optKeys.map((k) => [k, k === 'workspaceDir' ? __dirname : {}])));+ for (const name of ['rolePrivileges', 'entityPrivileges']) {+ assert.strictEqual(typeof reader[name], 'function',+ `verify-spec silently skips role-privileges without '${name}'; the build's options are ${JSON.stringify(optKeys)}`);+ }});-test('makeSdk returns the httpClient so the caller can wire verify', () => {- // Returning the SAME instance rather than constructing a second one keeps token acquisition and- // retry state shared; a second client would re-acquire a token per verify run.+test('makeSdk\u2019s return shape and main\u2019s destructure stay in agreement', () => {+ // A mismatch here is silent: destructuring a key the factory stopped returning yields `undefined`,+ // and the first symptom is a TypeError deep in an apply run. Compared as SETS rather than pinned to+ // a specific key list, so this keeps guarding the invariant as the shape legitimately changes — it+ // previously asserted the literal `{ sdk, provisionSdk, httpClient, cleanup }`, and `httpClient` was+ // removed when the raw-client escape hatch was retired in favour of `sdk.getEntityPrivileges`.const src = fs.readFileSync(path.join(__dirname, '..', 'build-model-app.js'), 'utf8');- assert.match(src, /return \{ sdk, provisionSdk, httpClient, cleanup \}/, 'makeSdk must expose httpClient');- assert.match(src, /const \{ sdk, provisionSdk, httpClient, cleanup \} = makeSdk\(/, 'main must destructure it');+ const returned = /return \{ ([^}]*) \};/.exec(src.slice(src.indexOf('function makeSdk')));+ assert.ok(returned, 'expected makeSdk to return an object literal');+ const destructured = /const \{ ([^}]*) \} = makeSdk\(/.exec(src);+ assert.ok(destructured, 'expected main to destructure makeSdk()');+ const names = (s) => s.split(',').map((x) => x.trim()).filter(Boolean).sort();+ assert.deepStrictEqual(names(destructured[1]), names(returned[1]),+ 'main destructures keys makeSdk does not return (or ignores ones it does)');});// #447 follow-up: an LCID reaches Dataverse as a label LanguageCode, so a value that merely SURVIVESdiff --git a/plugins/model-apps/scripts/tests/business-process-flows.test.js b/plugins/model-apps/scripts/tests/business-process-flows.test.jsindex 5a6e7fa6a..038a0f85b 100644--- a/plugins/model-apps/scripts/tests/business-process-flows.test.js+++ b/plugins/model-apps/scripts/tests/business-process-flows.test.js@@ -205,10 +205,16 @@ test('a cross-entity stage is rejected rather than silently retargeted', () => {test('a knob the build cannot verify is REJECTED, not ignored — at flow, stage AND step level', () => {// Silently dropping a key the author wrote is how a spec "deploys" something it does not: they// would see the stages appear and reasonably assume the rest applied.- for (const key of ['securityRoles', 'branch', 'actions', 'globalActions']) {- const errs = errorsFor([{ ...FLOW, [key]: key === 'securityRoles' ? ['Salesperson'] : [{}] }]);+ //+ // `securityRoles` is NO LONGER in this list: it is supported since #513 (see the dedicated tests+ // below). It stays rejected as an ARRAY though — the shape here — because the supported form is+ // an object, so the old spelling still fails rather than being read as something else.+ for (const key of ['branch', 'actions', 'globalActions']) {+ const errs = errorsFor([{ ...FLOW, [key]: [{}] }]);assert.ok(errs.some((e) => new RegExp(`unsupported key '${key}'`).test(e)), `${key}: ${JSON.stringify(errs)}`);}+ const arrayRoles = errorsFor([{ ...FLOW, securityRoles: ['Salesperson'] }]);+ assert.ok(arrayRoles.some((e) => /securityRoles must be an object like \{ "personas"/.test(e)), JSON.stringify(arrayRoles));// STAGE level is where an author would naturally write branching/actions — the SDK models them// there, and bpfDef maps only name/entity/steps, so an unguarded key vanishes without a word.for (const key of ['branch', 'actions', 'nextStageId', 'category', 'relationshipName']) {@@ -787,11 +793,35 @@ test('REGRESSION: a status-only edit is a full build but NOT permanent debt', ()assert.ok(statusOnly.changedPhases.includes('business-process-flows'), 'it still needs a full build');assert.ok(statusOnly.fullReasons.some((r) => /status changed — reconciled/.test(r)), JSON.stringify(statusOnly.fullReasons));- // A stage edit is NOT converged and must still be debt.- const restaged = specWith([{ ...FLOW, stages: [{ name: 'Only', steps: [{ name: 'S', field: 'new_notes' }] }] }]);- const stageEdit = classifyChanges(restaged, draft);- assert.ok(stageEdit.debt.some((d) => /edit-not-convergent/.test(d.reason)), `a stage edit is real debt; got ${JSON.stringify(stageEdit.debt)}`);-});+ // A stage edit is NOT converged and must still be debt.+ const restaged = specWith([{ ...FLOW, stages: [{ name: 'Only', steps: [{ name: 'S', field: 'new_notes' }] }] }]);+ const stageEdit = classifyChanges(restaged, draft);+ assert.ok(stageEdit.debt.some((d) => /edit-not-convergent/.test(d.reason)), `a stage edit is real debt; got ${JSON.stringify(stageEdit.debt)}`);+});++test('REGRESSION: a securityRoles-only edit is a full build but NOT permanent debt either (#513)', () => {+ // Stronger than the `status` case above. A BPF grant always targets a PERSONA role, and the+ // security phase applies persona roles with `ReplacePrivilegesRole` — so a rebuild both ADDS a+ // newly-declared persona and REMOVES one that was dropped. Filing permanent debt disabled every+ // later fast apply over a divergence a full build erases. (`roleGrants[]` would NOT qualify: it is+ // additive and cannot revoke.)+ const { classifyChanges } = require('../lib/classify-changes.js');+ const withPersonas = (personas) => {+ const s = specWith([personas ? { ...FLOW, securityRoles: { personas } } : { ...FLOW }]);+ s.personas = [{ persona: 'Dispatcher', jobs: [{ name: 'J', privileges: [{ entity: 'new_ticket', access: ['read'] }] }] }];+ return s;+ };+ const none = withPersonas(null);+ const granted = withPersonas(['Dispatcher']);++ for (const [label, cur, prior] of [['added', granted, none], ['removed', none, granted]]) {+ const r = classifyChanges(cur, prior);+ assert.deepStrictEqual(r.debt, [], `securityRoles ${label} is reconciled; got ${JSON.stringify(r.debt)}`);+ assert.ok(r.changedPhases.includes('business-process-flows'), `${label}: it still needs a full build`);+ assert.ok(r.fullReasons.some((x) => /securityRoles changed — reconciled/.test(x)),+ `${label}: and the reason must name the field that changed, not the whole converged list: ${JSON.stringify(r.fullReasons)}`);+ }+});test('REGRESSION: the same status-only rule applies to business rules', () => {// Business rules converge status in their reuse branch too, so they shared the bug and the fix.diff --git a/plugins/model-apps/scripts/tests/business-rules.test.js b/plugins/model-apps/scripts/tests/business-rules.test.jsindex 1c71a2bb6..39325080b 100644--- a/plugins/model-apps/scripts/tests/business-rules.test.js+++ b/plugins/model-apps/scripts/tests/business-rules.test.js@@ -906,10 +906,16 @@ test('REAL BUNDLE: every spec operator EXISTS in the SDK table, and none silentl//// Pinned against the bundle's own table so a re-vendor that renames or drops an operator fails// here rather than in production.+ //+ // The module alias in front of `WorkflowConditionOperator` is MINIFIER-ASSIGNED and changes on+ // every re-vendor — it was `z` when this was written and became `G` on the next bundle, which made+ // this test fail with "got 0" for a table that was fully intact. Match the alias as a wildcard, not+ // a literal: hardcoding a minified identifier is the same rebuild-unstable-string trap the build+ // engine documents for `err.name`, and here it costs a false failure rather than a silent pass.const bundle = fs.readFileSync(BUNDLE, 'utf8');const m = bundle.match(/\b[A-Za-z_$][\w$]*=\{Equals:[^}]*\}/);assert.ok(m, 'the operator table must be present in the vendored bundle');- const sdkOperators = [...m[0].matchAll(/(\w+):z\.WorkflowConditionOperator\./g)].map((x) => x[1]);+ const sdkOperators = [...m[0].matchAll(/(\w+):\s*[A-Za-z_$][\w$]*\.WorkflowConditionOperator\./g)].map((x) => x[1]);assert.ok(sdkOperators.length >= 16, `expected the full table, got ${sdkOperators.length}: ${sdkOperators}`);const { BUSINESS_RULE_OPERATORS } = require('../lib/app-spec.js');diff --git a/plugins/model-apps/scripts/tests/dataverse-auth.test.js b/plugins/model-apps/scripts/tests/dataverse-auth.test.jsindex 27ce802f8..386d6bc9b 100644--- a/plugins/model-apps/scripts/tests/dataverse-auth.test.js+++ b/plugins/model-apps/scripts/tests/dataverse-auth.test.js@@ -114,3 +114,345 @@ test('emitResult: partial-failure object writes JSON to stdout (not [object Objeassert.equal(parsed.errors[0].message, 'bad row');assert.match(res.stderr, /Operation completed with 1 error/);});++// --- AB#6686427: auth preflight — az tenant divergence from the selected PAC environment ---------+//+// The skill flow validates and selects a PAC profile, but every script authenticates through the+// INDEPENDENTLY active Azure CLI account. In a normal multi-tenant workflow `pac auth` and+// `az login` legitimately point at different tenants, and the result is an HTTP 401 that reads as a+// Dataverse permission problem — so the user troubleshoots roles and PAC profiles while the actual+// cause is the ambient az context. Worse, download's best-effort catches turn that 401 into a+// silently EMPTY spec (AB#6686423), so the failure does not even surface as an error.+//+// The preflight names the identity that will actually supply the token, before any real work.++const { preflightAuth } = require('../lib/dataverse-auth.js');++test('AB#6686427: preflight passes and reports the identity when WhoAmI succeeds', async () => {+ const r = await preflightAuth('https://contoso.crm.dynamics.com', {+ getToken: () => 'token',+ request: async () => ({ status: 200, data: { UserId: '00000000-0000-0000-0000-000000000001' } }),+ azIdentity: () => ({ user: '[email protected]', tenantId: 'aaaaaaaa-0000-0000-0000-000000000000' }),+ });+ assert.strictEqual(r.ok, true, JSON.stringify(r));+ assert.match(r.identity.user, /maker@contoso\.com/);+});++test('dataverseRequest USES a preset token and skips the CLI entirely', async () => {+ // The receiving half of the preflight optimisation. Passing the token is pointless if this side+ // fetches its own anyway, and that is invisible from the caller.+ const { dataverseRequest } = require('../lib/dataverse-auth.js');+ let cliCalls = 0;+ let sentAuth;+ const res = await dataverseRequest('https://contoso.crm.dynamics.com', 'GET', 'WhoAmI', null, {+ token: 'tok-abc',+ getToken: () => { cliCalls += 1; return 'tok-from-cli'; },+ request: async ({ headers }) => { sentAuth = headers.Authorization; return { statusCode: 200, body: '{}' }; },+ });+ assert.strictEqual(cliCalls, 0, 'a preset token must skip `az account get-access-token` altogether');+ assert.strictEqual(sentAuth, 'Bearer tok-abc');+ assert.strictEqual(res.status, 200);++ // Counterfactual: with no preset token it still acquires one, or the seam would have broken the+ // normal path while looking green.+ cliCalls = 0;+ await dataverseRequest('https://contoso.crm.dynamics.com', 'GET', 'WhoAmI', null, {+ getToken: () => { cliCalls += 1; return 'tok-from-cli'; },+ request: async ({ headers }) => { sentAuth = headers.Authorization; return { statusCode: 200, body: '{}' }; },+ });+ assert.strictEqual(cliCalls, 1);+ assert.strictEqual(sentAuth, 'Bearer tok-from-cli');+});++test('a path-bearing or query-bearing env is refused, not silently trimmed to its origin', async () => {+ // `dataverseRequest` appends `/api/data/...` to whatever it is given, so a trimmed+ // `https://org.crm.dynamics.com/some/path` would probe `.../some/path/api/data/...` and report a+ // result about a URL nobody asked for. This function decides where a bearer token may be sent, so+ // "close enough" is the wrong disposition.+ for (const bad of [+ 'https://contoso.crm.dynamics.com/some/path',+ 'https://contoso.crm.dynamics.com/?q=1',+ 'https://contoso.crm.dynamics.com/#frag',+ ]) {+ let tokenAsked = 0;+ let requested = 0;+ const r = await preflightAuth(bad, {+ getToken: () => { tokenAsked += 1; return 'token'; },+ request: async () => { requested += 1; return { status: 200, data: {} }; },+ azIdentity: () => ({ user: '[email protected]', tenantId: 't' }),+ });+ assert.strictEqual(r.ok, false, `${bad} must be refused: ${JSON.stringify(r)}`);+ assert.match(r.error, /ORIGIN/, r.error);+ assert.strictEqual(tokenAsked, 0, `${bad}: no token may be acquired for a rejected target`);+ assert.strictEqual(requested, 0, `${bad}: and nothing may be sent`);+ }+ // Counterfactual: a bare origin, and an origin with only a trailing slash, are both fine.+ for (const good of ['https://contoso.crm.dynamics.com', 'https://contoso.crm.dynamics.com/']) {+ const r = await preflightAuth(good, {+ getToken: () => 'token',+ request: async () => ({ status: 200, data: { UserId: 'u' } }),+ azIdentity: () => ({ user: '[email protected]', tenantId: 't' }),+ });+ assert.strictEqual(r.ok, true, `${good} must be accepted: ${JSON.stringify(r)}`);+ }+});++// --- emitResult: a single explained failure must not be dressed as a partial one -----------------+test('both CLIs report an auth-preflight failure with the SAME payload shape', () => {+ // `emitResult` reserves `errors: [...]` for a genuine PARTIAL failure and summarises it as a COUNT.+ // `build-model-app.js` wrapped its single preflight message in that array while+ // `download-model-app.js` passed it as `error`, so the two sibling CLIs printed different things+ // for the identical failure — and the one users hit on an apply printed the count, replacing a+ // message written specifically to say which identity to sign in as.+ //+ // Asserted on the SOURCE because the alternative is spawning both CLIs against a live tenant.+ const fs = require('node:fs');+ const path = require('node:path');+ for (const cli of ['build-model-app.js', 'download-model-app.js']) {+ const src = fs.readFileSync(path.join(__dirname, '..', cli), 'utf8');+ const line = src.split('\n').find((l) => /emitResult\(false,.*auth\.error/.test(l));+ assert.ok(line, `${cli}: expected an emitResult call carrying auth.error`);+ assert.match(line, /error:\s*auth\.error/, `${cli}: a single explained failure must use \`error\`: ${line.trim()}`);+ assert.doesNotMatch(line, /errors:\s*\[/, `${cli}: \`errors: [...]\` is for PARTIAL failures and prints only a count: ${line.trim()}`);+ }+});++test('emitResult prints a single error message instead of "unknown error(s)"', () => {+ // The auth preflight, the app-id resolver and friends all fail with { ok:false, error:"<what to+ // do>" } and no `errors` array. The old branch printed "Operation completed with unknown error(s)"+ // for every one of them — burying a message written specifically to tell the operator what to do,+ // under boilerplate that is also untrue: nothing completed, and it is not unknown.+ const { emitResult } = require('../lib/dataverse-auth.js');+ const run = (payload) => {+ const out = [];+ const err = [];+ const so = process.stdout.write;+ const se = process.stderr.write;+ const ex = process.exit;+ process.stdout.write = (s) => { out.push(String(s)); return true; };+ process.stderr.write = (s) => { err.push(String(s)); return true; };+ // `emitResult` ends the process by contract, so the exit is turned into a throw and swallowed.+ process.exit = () => { throw new Error('__exit__'); };+ try { emitResult(false, payload); } catch (e) { if (e.message !== '__exit__') throw e; } finally {+ process.stdout.write = so; process.stderr.write = se; process.exit = ex;+ }+ return { out: out.join(''), err: err.join('') };+ };++ const single = run({ ok: false, error: 'no Azure CLI access token could be obtained; run az login' });+ assert.match(single.err, /run az login/, 'the actionable message must reach stderr');+ assert.doesNotMatch(single.err, /unknown error/, 'and must not be replaced by boilerplate');+ assert.match(single.out, /"ok":false/, 'the structured payload still goes to stdout for callers');++ // The genuine PARTIAL-failure contract is unchanged: a count, with the detail on stdout.+ const partial = run({ ok: false, errors: [{ row: 1 }, { row: 2 }] });+ assert.match(partial.err, /completed with 2 error\(s\)/, partial.err);++ // Neither shape: say so honestly rather than claiming a count we do not have.+ const opaque = run({ ok: false });+ assert.match(opaque.err, /unstructured error/, opaque.err);+ assert.doesNotMatch(opaque.err, /completed with/, 'nothing completed');+});++test('AB#6686427: the preflight HANDS its token to the request instead of fetching a second one', async () => {+ // `preflightAuth` deliberately acquires a token itself so it can tell "not signed in" apart from+ // "signed in but rejected" — two different diagnoses with two different fixes. Without passing it+ // on, `dataverseRequest` shells out to `az account get-access-token` again for the same origin,+ // and that call cold-starts the Azure CLI's Python runtime: seconds, on a path a user waits on.+ let tokenCalls = 0;+ let sawToken;+ const r = await preflightAuth('https://contoso.crm.dynamics.com', {+ getToken: () => { tokenCalls += 1; return 'tok-abc'; },+ request: async (_url, _m, _p, _b, opts) => { sawToken = opts && opts.token; return { status: 200, data: { UserId: 'u' } }; },+ azIdentity: () => ({ user: '[email protected]', tenantId: 'aaaaaaaa-0000-0000-0000-000000000000' }),+ });+ assert.strictEqual(r.ok, true, JSON.stringify(r));+ assert.strictEqual(tokenCalls, 1, 'exactly one token acquisition');+ assert.strictEqual(sawToken, 'tok-abc', 'and the SAME token must reach the request');+});++test('AB#6686427: a 401 names the ACTIVE az identity, the target org, and the remediation', async () => {+ const r = await preflightAuth('https://contoso.crm.dynamics.com', {+ getToken: () => 'token',+ request: async () => ({ status: 401, data: {} }),+ azIdentity: () => ({ user: '[email protected]', tenantId: 'bbbbbbbb-0000-0000-0000-000000000000' }),+ });+ assert.strictEqual(r.ok, false);+ // Naming only the status repeats the failure the user already saw; the point is to name the CAUSE.+ assert.match(r.error, /other@fabrikam\.onmicrosoft\.com/, 'must name the active az identity');+ assert.match(r.error, /bbbbbbbb-0000-0000-0000-000000000000/, 'must name the tenant supplying the token');+ assert.match(r.error, /contoso\.crm\.dynamics\.com/, 'must name the target org');+ assert.match(r.error, /az login/, 'must name the remediation');+});++test('AB#6686427: no token at all is reported as a sign-in problem, not a permission one', async () => {+ const r = await preflightAuth('https://contoso.crm.dynamics.com', {+ getToken: () => null,+ request: async () => { throw new Error('should not be called'); },+ azIdentity: () => null,+ });+ assert.strictEqual(r.ok, false);+ assert.match(r.error, /az login/);+ // Assert the CLAIM, not the vocabulary: the message may legitimately use the word "permissions"+ // to rule it OUT, which an over-crude /permission/ ban would fail. What must not happen is the+ // failure being ATTRIBUTED to privileges, sending the user to security roles.+ assert.match(r.error, /sign-in problem/, 'must name the real cause');+ assert.doesNotMatch(r.error, /insufficient|lacks? (the )?privilege|missing privilege|security role/i,+ 'must not attribute a missing token to privileges');+});++test('AB#6686427: the preflight is a diagnostic and never throws', async () => {+ for (const opts of [+ { getToken: () => { throw new Error('az exploded'); }, request: async () => ({ status: 200, data: {} }), azIdentity: () => null },+ { getToken: () => 't', request: async () => { throw new Error('socket hang up'); }, azIdentity: () => null },+ { getToken: () => 't', request: async () => ({ status: 200, data: {} }), azIdentity: () => { throw new Error('az show failed'); } },+ ]) {+ let r;+ await assert.doesNotReject(async () => { r = await preflightAuth('https://contoso.crm.dynamics.com', opts); });+ assert.ok(typeof r.ok === 'boolean', 'always returns a structured verdict');+ }+});++test('AB#6686427: a non-401 failure is INCONCLUSIVE, not a block and not a tenant mismatch', async () => {+ // A 403 is a real privilege problem and a 500 is the service; blaming the az tenant for either+ // would send the user down exactly the wrong path — the mirror of the bug being fixed.+ //+ // They must also NOT BLOCK. This probe goes through `dataverseRequest`, which retries fewer+ // statuses and fewer times than the `createAzHttpClient` the real download uses (that one also+ // retries 504). A transient 5xx the download would have ridden out must not be turned into a hard+ // failure by a diagnostic sitting in front of it. Found in review.+ for (const status of [403, 429, 500, 504]) {+ const r = await preflightAuth('https://contoso.crm.dynamics.com', {+ getToken: () => 'token',+ request: async () => ({ status, data: { error: { message: 'upstream detail' } } }),+ azIdentity: () => ({ user: '[email protected]', tenantId: 'aaaa' }),+ });+ assert.strictEqual(r.ok, false);+ assert.strictEqual(r.inconclusive, true, `${status} must be inconclusive, never blocking`);+ assert.doesNotMatch(r.error, /az login --tenant/, `${status} must not be blamed on the az tenant`);+ assert.match(r.error, /upstream detail/, 'the server message explains a 403 and must survive');+ }+});++test('AB#6686427: a non-HTTPS or malformed env is refused BEFORE any token is acquired', async () => {+ // The preflight runs ahead of createAzHttpClient's credential boundary and goes through+ // dataverseRequest, whose transport falls back to plain `http` for a non-HTTPS scheme. Without+ // this gate a malformed --env could put a bearer token on the wire in clear text. Found in review.+ for (const bad of ['http://contoso.crm.dynamics.com', 'not-a-url', 'ftp://x/y', '']) {+ let tokenAsked = 0;+ const r = await preflightAuth(bad, {+ getToken: () => { tokenAsked++; return 'token'; },+ request: async () => { throw new Error('must not reach the wire'); },+ azIdentity: () => null,+ });+ assert.strictEqual(r.ok, false, `${bad} must be refused`);+ assert.strictEqual(r.inconclusive, undefined, 'a bad target is definitive, not inconclusive');+ assert.strictEqual(tokenAsked, 0, `no token may be acquired for ${bad}`);+ assert.match(r.error, /https/i);+ }+});++test('AB#6686427: a CLAIMS CHALLENGE 401 is not blamed on the tenant', async () => {+ // Conditional Access / CAE answer 401 with `WWW-Authenticate: ... error="insufficient_claims"`,+ // and `az login --tenant` does not fix it. Asserting tenant divergence as a certainty would be the+ // same misattribution this bug is about, pointed somewhere new. Found in review.+ const r = await preflightAuth('https://contoso.crm.dynamics.com', {+ getToken: () => 'token',+ request: async () => ({ status: 401, data: null, headers: { 'www-authenticate': 'Bearer error="insufficient_claims", claims="eyJ..."' } }),+ azIdentity: () => ({ user: '[email protected]', tenantId: 'aaaa' }),+ });+ assert.strictEqual(r.ok, false);+ assert.match(r.error, /claims/i);+ assert.doesNotMatch(r.error, /az login --tenant/, 'a claims challenge is not a tenant problem');+});++test('AB#6686427: the happy path does not shell out to az for an identity nobody asked for', async () => {+ // The caller only reads `auth.ok`; paying for an `az account show` subprocess on every successful+ // run is pure cost. Found in review.+ let idReads = 0;+ const r = await preflightAuth('https://contoso.crm.dynamics.com', {+ getToken: () => 'token',+ request: async () => ({ status: 200, data: { UserId: 'u' } }),+ azIdentity: () => { idReads++; return { user: '[email protected]', tenantId: 'aaaa' }; },+ });+ assert.strictEqual(r.ok, true);+ assert.ok(idReads <= 1, `identity read at most once on success, got ${idReads}`);+});++// --- AB#6686424: a terminal 401 must explain itself ----------------------------------------------+//+// Both auth paths already retry a 401 once (dataverse-auth's loop, and sdk-http-client.js:130). The+// retry is not the gap: MEASURED, `az account get-access-token` serves from the MSAL cache, so an+// immediate re-call returns a byte-identical token (same sha256). A retry therefore cannot fix a+// token that is rejected for WHO it belongs to — only one that expired in a very narrow window.+//+// The reporter's own workaround was "refresh Azure CLI login and retry" — an `az login`, which is+// AB#6686427's cause. So what a surviving 401 needs is not another attempt, it is to say whose+// token was refused, so the reader stops looking at Dataverse roles.++test('AB#6686424: a terminal 401 names the identity whose token was refused', () => {+ const { ensureOk } = require('../lib/dataverse-auth.js');+ assert.throws(+ () => ensureOk({ status: 401, data: { error: { message: 'Unauthorized' } } }, 'read EntityDefinitions',+ { azIdentity: () => ({ user: '[email protected]', tenantId: 'bbbb-tenant' }) }),+ (e) => {+ assert.match(e.message, /other@fabrikam\.onmicrosoft\.com/, 'names the account');+ assert.match(e.message, /bbbb-tenant/, 'names the tenant');+ assert.match(e.message, /az login/, 'names the remediation');+ return true;+ }+ );+});++test('AB#6686424: a NON-401 error is left exactly as it was', () => {+ // A 403 is a real privilege problem and a 400 is a bad request; attaching identity advice to+ // either would send the reader to `az login` for something az cannot fix.+ const { ensureOk } = require('../lib/dataverse-auth.js');+ for (const status of [400, 403, 404, 500]) {+ assert.throws(+ () => ensureOk({ status, data: { error: { message: 'boom' } } }, 'ctx', { azIdentity: () => ({ user: 'x', tenantId: 'y' }) }),+ (e) => {+ assert.doesNotMatch(e.message, /az login/, `${status} must not be blamed on the az identity`);+ assert.match(e.message, /boom/);+ return true;+ }+ );+ }+});++test('AB#6686424: an unreadable identity still produces a useful 401, never a crash', () => {+ const { ensureOk } = require('../lib/dataverse-auth.js');+ assert.throws(+ () => ensureOk({ status: 401, data: {} }, 'ctx', { azIdentity: () => { throw new Error('az gone'); } }),+ (e) => {+ assert.match(e.message, /401/);+ assert.match(e.message, /az login/);+ return true;+ }+ );+});++test('AB#6686424: a 2xx is returned untouched (no identity read on the happy path)', () => {+ const { ensureOk } = require('../lib/dataverse-auth.js');+ let called = 0;+ const res = { status: 200, data: { ok: 1 } };+ assert.strictEqual(ensureOk(res, 'ctx', { azIdentity: () => { called++; return null; } }), res);+ assert.strictEqual(called, 0, 'must not shell out to az on every successful call');+});++test('AB#6686424: a bodyless error does not print "null" as the server message', () => {+ // Found by LIVE verification, not by the unit fixtures: a real Dataverse 401 often carries no body+ // at all, so `data` is null and the message read "HTTP 401 — null". Every unit fixture supplied a+ // message, so nothing caught it.+ const { ensureOk } = require('../lib/dataverse-auth.js');+ for (const [status, data] of [[401, null], [500, null], [404, undefined]]) {+ assert.throws(+ () => ensureOk({ status, data }, 'ctx', { azIdentity: () => null }),+ (e) => {+ assert.doesNotMatch(e.message, /— null|— undefined/, `${status} must not print a bare null: ${e.message}`);+ assert.match(e.message, /no response body/);+ return true;+ }+ );+ }+});diff --git a/plugins/model-apps/scripts/tests/download-model-app.test.js b/plugins/model-apps/scripts/tests/download-model-app.test.jsindex f7c83c127..baa79a620 100644--- a/plugins/model-apps/scripts/tests/download-model-app.test.js+++ b/plugins/model-apps/scripts/tests/download-model-app.test.js@@ -246,8 +246,10 @@ test('readEntityWithDescriptions reads descriptions through the RAW dataverse clconst meta = await readEntityWithDescriptions(sdk, 'new_order');const e = entityFromMetadata(meta, 'new_order');- assert.ok(gets.some((u) => /^\/EntityDefinitions\(LogicalName='new_order'\)\?\$select=LogicalName,Description$/.test(u)), `table read URL wrong: ${gets.join(' | ')}`);- assert.ok(gets.some((u) => /^\/EntityDefinitions\(LogicalName='new_order'\)\/Attributes\?\$select=LogicalName,Description$/.test(u)), `attribute read URL wrong: ${gets.join(' | ')}`);+ // The $select also carries the DISPLAY labels now, so a table/column labelled in more than one+ // language round-trips (AB#6686428). The SDK's flattened `displayName` keeps only one.+ assert.ok(gets.some((u) => /^\/EntityDefinitions\(LogicalName='new_order'\)\?\$select=LogicalName,Description,DisplayName,DisplayCollectionName$/.test(u)), `table read URL wrong: ${gets.join(' | ')}`);+ assert.ok(gets.some((u) => /^\/EntityDefinitions\(LogicalName='new_order'\)\/Attributes\?\$select=LogicalName,Description,DisplayName$/.test(u)), `attribute read URL wrong: ${gets.join(' | ')}`);assert.strictEqual(e.description, 'Order table purpose.');const status = e.columns.find((c) => c.schemaName === 'new_status');assert.strictEqual(status.description, 'State shown to dispatchers.');@@ -1324,11 +1326,35 @@ test('runDownload WARNS on stderr about a role-restricted form, naming it', asynassert.strictEqual(res.ok, true, `the download itself must succeed; got ${res.error || ''}`);const text = written.join('');- assert.match(text, /form\(s\) are restricted to specific security roles/, 'the warning must fire');- assert.match(text, /new_order\.Dispatcher Form/, 'and must NAME the restricted form');- assert.doesNotMatch(text, /Everyone Form/,+ // Scoped to the RESTRICTION warning's own line. The download also emits a separate+ // not-round-tripped note (AB#6686423) that lists every deployed form by name — including the+ // unrestricted one — so scanning all of stderr would now assert the wrong thing. The intent of+ // this check has always been "the restriction warning must not name an unrestricted form".+ const restrictionLine = text.split('\n').find((l) => /are restricted to specific security roles/.test(l)) || '';+ assert.ok(restrictionLine, 'the warning must fire');+ assert.match(restrictionLine, /new_order\.Dispatcher Form/, 'and must NAME the restricted form');+ assert.doesNotMatch(restrictionLine, /Everyone Form/,'the <Everyone /> form is the unrestricted DEFAULT — warning on it would make the warning noise');- assert.match(text, /forms\[\]\.securityRoles/, 'and must say how to carry the restriction forward');+ assert.match(restrictionLine, /forms\[\]\.securityRoles/, 'and must say how to carry the restriction forward');++ // AB#6686423 — BEHAVIOURAL: the same run must also report the artifact classes it did not+ // reconstruct, and carry that report in the RESULT so `--json` consumers see it too. The unit+ // tests in download-not-round-tripped.test.js pin the wording; this pins that it is actually+ // reached from a real download, which a source-shape assertion could not.+ //+ // This app has only forms, and the sentence now names only the classes actually reported — it used+ // to read "forms[], views[] or charts[]" regardless, telling the operator two things were missing+ // that were never there.+ assert.match(text, /NOTE: this download does not reconstruct forms\[\] —/);+ assert.doesNotMatch(text, /does not reconstruct[^\n]*views\[\]/, 'no views were found, so none may be claimed');+ assert.ok(res.notRoundTripped, 'the summary must ride on the runDownload result, not only on stderr');+ assert.strictEqual(res.notRoundTripped.total, 2, JSON.stringify(res.notRoundTripped));+ // SORTED, not in the order the mock returned them. `notRoundTripped` is compared between runs, so+ // it sorts at every level; `descriptionInventory` below is the raw read and keeps Dataverse's+ // order, which is why the two lists differ here.+ assert.deepStrictEqual(res.notRoundTripped.entities, [{ entity: 'new_order', forms: ['Dispatcher Form', 'Everyone Form'], views: [], charts: [], businessRules: [] }]);+ // The spec on disk still carries them under descriptionInventory — the note's claim must be true.+ assert.deepStrictEqual((res.spec.descriptionInventory.forms || []).map((f) => f.name), ['Everyone Form', 'Dispatcher Form']);});test('runDownload stays SILENT when no form is role-restricted', async () => {diff --git a/plugins/model-apps/scripts/tests/download-not-round-tripped.test.js b/plugins/model-apps/scripts/tests/download-not-round-tripped.test.jsnew file mode 100644index 000000000..3f485034d--- /dev/null+++ b/plugins/model-apps/scripts/tests/download-not-round-tripped.test.js@@ -0,0 +1,256 @@+'use strict';+// AB#6686423 — download-model-app reported an app as fully downloaded while emitting empty+// `forms[]`, `views[]` and `charts[]`, "with nothing reporting the loss".+//+// Four of the five reported defects (missing columns, missing relationships, guessed+// `contoso_name` primary attributes, absent entity metadata) turned out to be one upstream cause —+// an Azure CLI token from the wrong tenant, whose 401 every best-effort read swallowed — and are+// fixed by the AB#6686427 preflight on this same branch. What genuinely remains is the artifact+// classes hydrateSpec deliberately does not reconstruct, and the fact that nothing said so.+//+// These tests pin the REPORT, not a reconstruction. Reconstructing forms was reconsidered and+// rejected: the App Spec form shape cannot express everything a deployed `formxml` carries, and a+// lossy form DECLARED in the spec is worse than an absent one, because a rebuild into a fresh+// environment would recreate it having silently lost controls while reporting success.+const { test } = require('node:test');+const assert = require('node:assert');+const { notRoundTrippedSummary, notRoundTrippedWarning } = require('../download-model-app.js');++const inventory = (over = {}) => ({+ forms: [{ id: 'f1', name: 'Project', entity: 'contoso_project' }, { id: 'f2', name: 'Baseline', entity: 'contoso_projectbaseline' }],+ views: [{ id: 'v1', name: 'Active Projects', entity: 'contoso_project' }],+ charts: [{ id: 'c1', name: 'By Status', entity: 'contoso_project' }],+ businessRules: [],+ globalChoices: [],+ roleRestrictedForms: [],+ ...over,+});++test('notRoundTrippedSummary counts every omitted class and groups by table', () => {+ const s = notRoundTrippedSummary(inventory());+ assert.strictEqual(s.total, 4);+ assert.deepStrictEqual(s.classes.map((c) => [c.kind, c.count]), [['forms', 2], ['views', 1], ['charts', 1]]);+ // Sorted by table so two runs against the same app produce the same report.+ assert.deepStrictEqual(s.entities.map((e) => e.entity), ['contoso_project', 'contoso_projectbaseline']);+ assert.deepStrictEqual(s.entities[0], { entity: 'contoso_project', forms: ['Project'], views: ['Active Projects'], charts: ['By Status'], businessRules: [] });+});++test('notRoundTrippedSummary returns null when there is nothing to report', () => {+ // A note that fires when there is nothing to say is a note nobody reads. An app with no forms,+ // views or charts is unusual but legal (a pages-only app).+ assert.strictEqual(notRoundTrippedSummary({ forms: [], views: [], charts: [] }), null);+ assert.strictEqual(notRoundTrippedSummary({}), null);+ assert.strictEqual(notRoundTrippedSummary(null), null);+});++test('notRoundTrippedSummary omits a class that has no rows rather than reporting a zero', () => {+ const s = notRoundTrippedSummary(inventory({ charts: [], views: [] }));+ assert.deepStrictEqual(s.classes.map((c) => c.kind), ['forms']);+ assert.strictEqual(s.total, 2);+});++test('notRoundTrippedSummary skips nameless rows instead of printing blanks', () => {+ // A row with no `name` came back from a partial read; naming it "" in the report would be noise+ // that reads like a real artifact called nothing.+ const s = notRoundTrippedSummary(inventory({ forms: [{ id: 'f1', entity: 'contoso_project' }, { id: 'f2', name: 'Real', entity: 'contoso_project' }] }));+ assert.deepStrictEqual(s.entities.find((e) => e.entity === 'contoso_project').forms, ['Real']);+});++test('notRoundTrippedSummary buckets a row with no table under "unknown" rather than dropping it', () => {+ const s = notRoundTrippedSummary({ forms: [{ id: 'f1', name: 'Orphan' }] });+ assert.deepStrictEqual(s.entities, [{ entity: 'unknown', forms: ['Orphan'], views: [], charts: [], businessRules: [] }]);+});++// --- the classes actually reported ---------------------------------------------------------------+// `hydrateSpec` reconstructs neither BUSINESS RULES nor GLOBAL CHOICES, and both are inventoried, so+// both belong in a report whose whole purpose is naming what did not round-trip. Leaving them out+// made the report quietly incomplete about a real cross-environment loss.++test('a business rule is reported, grouped by its table like any other artifact', () => {+ const s = notRoundTrippedSummary(inventory({ businessRules: [{ id: 'br1', name: 'Require close reason', entity: 'contoso_project' }] }));+ assert.ok(s.classes.some((c) => c.kind === 'businessRules' && c.count === 1), JSON.stringify(s.classes));+ assert.deepStrictEqual(s.entities.find((e) => e.entity === 'contoso_project').businessRules, ['Require close reason']);+ assert.match(notRoundTrippedWarning(s), /businessRules: Require close reason/);+});++test('a global choice is reported WITHOUT a table, because it does not belong to one', () => {+ // Filing an org-wide option set under a table would assert a relationship Dataverse does not have.+ const s = notRoundTrippedSummary(inventory({ globalChoices: [{ id: 'gc1', name: 'contoso_status' }] }));+ assert.ok(s.classes.some((c) => c.kind === 'globalChoices' && c.count === 1));+ assert.deepStrictEqual(s.orgScoped, [{ kind: 'globalChoices', label: 'global choice', names: ['contoso_status'] }]);+ assert.ok(!s.entities.some((e) => e.entity === 'unknown'), 'it must not be bucketed under a fake table');+ assert.match(notRoundTrippedWarning(s), /\(environment-wide\) globalChoices: contoso_status/);+});++// --- the wording, which is the whole point of the fix -------------------------------------------++test('the warning distinguishes "absent from the spec" from "deleted from the app"', () => {+ // THE correction this fix makes. The reporter concluded the download had LOST the artifacts. It+ // had not — they are on the deployed app and in `descriptionInventory` — so a message that said+ // "dropped" would trade one wrong belief for another. Both halves must be stated.+ const w = notRoundTrippedWarning(notRoundTrippedSummary(inventory()));+ assert.match(w, /NOT lost/);+ assert.match(w, /descriptionInventory/, 'must point at where they ARE recorded');+ assert.match(w, /THIS environment leaves them untouched/, 'must say a same-environment rebuild is safe');+ assert.match(w, /DIFFERENT environment will NOT recreate them/, 'must say where the loss is real');+});++test('the warning names the counts, the tables and the artifacts', () => {+ const w = notRoundTrippedWarning(notRoundTrippedSummary(inventory()));+ assert.match(w, /2 forms, 1 view, 1 chart/, 'counts must be singularised correctly');+ assert.match(w, /on 2 table\(s\)/);+ assert.match(w, /contoso_project — forms: Project; views: Active Projects; charts: By Status/);+ assert.match(w, /contoso_projectbaseline — forms: Baseline/);+});++test('the warning says what to DO about it', () => {+ // A report with no remedy just relocates the problem.+ const w = notRoundTrippedWarning(notRoundTrippedSummary(inventory()));+ assert.match(w, /re-declare the ones you need in forms\[\], views\[\], charts\[\]/);+ assert.match(w, /solution export/);+});++test('the class list in the wording FOLLOWS the content — it is not a fixed sentence', () => {+ // It used to read "forms[], views[] or charts[]" no matter what was reported, so a download with+ // only forms told the operator views and charts were missing too, and adding business rules to the+ // report left the sentence naming the wrong classes. The remedy line has to name the same set.+ const onlyForms = notRoundTrippedWarning(notRoundTrippedSummary(inventory({ views: [], charts: [] })));+ assert.match(onlyForms, /does not reconstruct forms\[\] —/);+ assert.doesNotMatch(onlyForms, /views\[\]/, 'must not claim views were omitted when none were found');+ assert.doesNotMatch(onlyForms, /charts\[\]/);++ const withRules = notRoundTrippedWarning(notRoundTrippedSummary(inventory({ businessRules: [{ id: 'b', name: 'R', entity: 'contoso_project' }] })));+ assert.match(withRules, /does not reconstruct forms\[\], views\[\], charts\[\], businessRules\[\] —/);+ assert.match(withRules, /re-declare the ones you need in forms\[\], views\[\], charts\[\], businessRules\[\]/);+});++test('notRoundTrippedWarning is empty for an empty summary, so nothing is printed', () => {+ assert.strictEqual(notRoundTrippedWarning(null), '');+});++test("the note's promise is TRUE: a downloaded spec plans no form/view/chart mutation", () => {+ // The note tells an operator "Rebuilding into THIS environment leaves them untouched." That is a+ // promise about the BUILD, made by the DOWNLOAD, so nothing else would catch it going stale — and+ // a wrong promise here is worse than the silence it replaced, because the operator would act on it.+ //+ // Two mechanisms could break it and both are checked: the forms phase prunes fields for a form+ // whose spec declares an EXPLICIT layout (unreachable with `forms: []`), and the views phase+ // enriches a table's stock Active/Inactive views (skipped because download flags every recovered+ // table `existing: true`).+ const { planFor, enrichesDefaultViews } = require('../lib/sdk-build.js');+ const downloaded = {+ solution: { uniqueName: 's', publisherPrefix: 'p' },+ app: { name: 'A' },+ entities: [{ schemaName: 'contoso_order', existing: true, displayName: 'Order', primaryAttribute: { schemaName: 'contoso_name' }, columns: [] }],+ views: [], charts: [], forms: [], commands: [], dashboards: [], pages: [], webResources: [],+ appShell: { areas: [] },+ };+ assert.strictEqual(enrichesDefaultViews(downloaded, downloaded.entities[0]), false,+ 'download flags recovered tables existing:true precisely so the stock views are left alone');+ const labels = planFor(downloaded, {}).map((p) => p.label);+ const risky = labels.filter((l) => /\b(form|view|chart)\b|delete|prune|deactivate|enrich/i.test(l));+ assert.deepStrictEqual(risky, [], `a downloaded spec planned work against a deployed artifact: ${risky.join(' | ')}`);+});++// --- determinism -----------------------------------------------------------------------------------++test('the report is stable whatever order Dataverse returns rows in', () => {+ // The rows come from `queryRecords`, which carries no ordering guarantee. This block is written+ // into the operator's output and compared BETWEEN runs, so an unstable order reads as a change+ // that did not happen -- the opposite of the point, which is to make a real difference visible.+ // Tables were already sorted; the per-table artifact NAME lists were not, so it was half stable.+ const build = (formNames, incompleteOrder) => notRoundTrippedSummary({+ forms: formNames.map((n) => ({ entity: 'b_table', name: n })).concat([+ { entity: 'a_table', name: 'Zulu' }, { entity: 'a_table', name: 'Alpha' },+ ]),+ views: [], charts: [],+ incomplete: incompleteOrder.map((k) => ({ kind: k, reason: 'HTTP 403' })),+ });++ const one = build(['Zeta', 'Alpha', 'Mid'], ['views', 'charts']);+ const two = build(['Mid', 'Zeta', 'Alpha'], ['charts', 'views']);+ assert.deepStrictEqual(one, two, 'two orderings of the same data must produce an identical report');++ // Assert the ordering itself, not just that the two agree -- both could be equally wrong.+ assert.deepStrictEqual(one.entities.map((e) => e.entity), ['a_table', 'b_table']);+ assert.deepStrictEqual(one.entities[0].forms, ['Alpha', 'Zulu']);+ assert.deepStrictEqual(one.entities[1].forms, ['Alpha', 'Mid', 'Zeta']);+ assert.deepStrictEqual(one.incomplete.map((i) => i.kind), ['charts', 'views']);+});+++// --- AB#6686428: a failed LABEL read must not degrade silently -----------------------------------+// The table-label read is the ONLY source of multi-language labels. When it fails the table is still+// recovered, so the download SUCCEEDS and the spec looks complete while carrying the SDK's flattened+// single-language `displayName` — every other language gone. That is the same silent-loss shape the+// localized-label feature exists to end, so the failure is recorded and reported.+const { readEntityWithDescriptions, entityFromMetadata } = require('../download-model-app.js');++const labelSdk = (get) => ({+ fetchEntityMetadata: async (l) => ({ logicalName: l, displayName: 'Ticket', primaryNameAttribute: 'new_name', attributes: [] }),+ // `readEntityWithDescriptions` makes TWO metadata reads — the table labels and the column labels —+ // and BOTH now record a failure. A stub that answers one response for both made the+ // success case fail on the Attributes read, so route by URL and keep the column read healthy;+ // the column read has its own tests below.+ dataverse: { get: async (url) => (/\/Attributes\?/.test(url) ? { status: 200, headers: {}, body: { value: [] } } : get(url)) },+});++test('a non-2xx label read is RECORDED, not read as "this table has no other languages"', async () => {+ const meta = await readEntityWithDescriptions(labelSdk(async () => ({ status: 403, body: {} })), 'new_t');+ assert.strictEqual(meta.labelReadFailed, 'HTTP 403');+});++test('a THROWN label read is recorded with its reason', async () => {+ const meta = await readEntityWithDescriptions(labelSdk(async () => { throw new Error('socket hang up'); }), 'new_t');+ assert.match(meta.labelReadFailed, /socket hang up/);+});++test('a SUCCESSFUL label read records no failure', async () => {+ const meta = await readEntityWithDescriptions(labelSdk(async () => ({ status: 200, body: { DisplayName: { LocalizedLabels: [{ Label: 'T', LanguageCode: 1033 }] } } })), 'new_t');+ assert.strictEqual(meta.labelReadFailed, undefined);+});++test('the failure marker never reaches the emitted spec', async () => {+ // `entityFromMetadata` builds an explicit literal, so the marker is dropped — asserted rather than+ // assumed, because a stray key here would be written into app-spec.json and fail its validation+ // (the same class as the raw Dataverse Label object that used to leak through as a column name).+ const meta = await readEntityWithDescriptions(labelSdk(async () => ({ status: 500, body: {} })), 'new_t');+ assert.ok(meta.labelReadFailed, 'precondition: the marker is set');+ assert.ok(!Object.keys(entityFromMetadata(meta, 'new_t')).includes('labelReadFailed'));+});+// The COLUMN-label read is a second source of the same loss, and was fixed one commit later than the+// table one — it is the only source of multi-language labels for every non-primary column and for the+// primary attribute, and it was still coercing a non-2xx to null and swallowing a throw.+const twoReadSdk = (tableGet, attrGet) => ({+ fetchEntityMetadata: async (l) => ({ logicalName: l, displayName: 'Ticket', primaryNameAttribute: 'new_name', attributes: [{ logicalName: 'new_name' }] }),+ dataverse: { get: async (url) => (/\/Attributes\?/.test(url) ? attrGet(url) : tableGet(url)) },+});+const OK_TABLE = async () => ({ status: 200, headers: {}, body: { DisplayName: { LocalizedLabels: [{ Label: 'T', LanguageCode: 1033 }] } } });+const OK_ATTRS = async () => ({ status: 200, headers: {}, body: { value: [{ LogicalName: 'new_name', DisplayName: { LocalizedLabels: [{ Label: 'N', LanguageCode: 1033 }] } }] } });++test('a non-2xx COLUMN-label read is recorded, not silently coerced to "no columns"', async () => {+ const meta = await readEntityWithDescriptions(twoReadSdk(OK_TABLE, async () => ({ status: 403, headers: {}, body: {} })), 'new_t');+ assert.strictEqual(meta.labelReadFailed, 'HTTP 403');+});++test('a THROWN column-label read is recorded', async () => {+ const meta = await readEntityWithDescriptions(twoReadSdk(OK_TABLE, async () => { throw new Error('socket hang up'); }), 'new_t');+ assert.match(meta.labelReadFailed, /socket hang up/);+});++test('a malformed column-label body is recorded rather than merged as nothing', async () => {+ const meta = await readEntityWithDescriptions(twoReadSdk(OK_TABLE, async () => ({ status: 200, headers: {}, body: { notValue: 1 } })), 'new_t');+ assert.match(meta.labelReadFailed, /value\[\] array/);+});++test('both reads succeeding records no failure, and the column labels are merged', async () => {+ const meta = await readEntityWithDescriptions(twoReadSdk(OK_TABLE, OK_ATTRS), 'new_t');+ assert.strictEqual(meta.labelReadFailed, undefined);+ assert.ok(meta.attributes[0].DisplayName, 'the column label must actually be merged onto the attribute');+});++test('a TABLE-level failure is not overwritten by a later column failure', async () => {+ // The first reason is the more useful one to show, and both describe the same outcome.+ const meta = await readEntityWithDescriptions(twoReadSdk(async () => ({ status: 401, headers: {}, body: {} }), async () => { throw new Error('later'); }), 'new_t');+ assert.strictEqual(meta.labelReadFailed, 'HTTP 401');+});\ No newline at end of filediff --git a/plugins/model-apps/scripts/tests/entity-provision.test.js b/plugins/model-apps/scripts/tests/entity-provision.test.jsindex f76d6a0a5..66eda47db 100644--- a/plugins/model-apps/scripts/tests/entity-provision.test.js+++ b/plugins/model-apps/scripts/tests/entity-provision.test.js@@ -913,3 +913,44 @@ test('requireSuccessfulPush keeps the re-download remedy for the SDK\u0027s own});});+++// ── AB#6686428: the relationship existence probe must not fall back to the POISONING broad read ──+// `fetchEntityMetadata` -> `createRelationship` is one of the three broad-read -> create pairs that+// makes Dataverse keep only the base-language label. The narrow probe exists to avoid it; an+// inconclusive narrow probe falling through to the broad read silently reintroduces the bug, and+// invisibly, because the create's request body is byte-identical either way.+const relSpec = (lookupDisplayName) => ({+ solution: { uniqueName: 'S', publisherPrefix: 'new' },+ entities: [],+ relationships: [{ type: 'OneToMany', referenced: 'new_a', referencing: 'new_b', lookup: { schemaName: 'new_aid', displayName: lookupDisplayName } }],+});+// A raw client whose narrow probe is INCONCLUSIVE (a transient 5xx), which is the trigger.+const inconclusiveRaw = () => ({ get: async () => ({ status: 503, headers: {}, body: {} }) });++test('AB#6686428: an inconclusive probe for a LOCALIZED lookup label skips the broad metadata read', async () => {+ const m = mockSdk();+ const broadReads = [];+ m.provision.dataverse = inconclusiveRaw();+ m.provision.fetchEntityMetadata = async (l) => { broadReads.push(l); return { logicalName: l, entitySetName: l + 's', relationships: [] }; };+ const runner = makeRunner({ emit: () => {}, total: 4 });+ await provisionDataModel({ sdk: m.sdk, provision: m.provision, runner, spec: relSpec({ 1033: 'Account', 3082: 'Cuenta' }), apply: true });++ assert.deepStrictEqual(broadReads, [],+ 'the broad read must NOT run for a localized label -- it is what strips every non-base language');+ assert.ok(m.calls.some((c) => c[0] === 'createRelationship'),+ 'and the relationship is still created: "could not tell" is treated as absent, as it always was');+});++test('AB#6686428: a PLAIN lookup label keeps the broad-read fallback unchanged', async () => {+ // The narrowing must not cost the existence check for the common case. Nothing is at risk there:+ // a plain string has one label, so the broad read cannot strip anything.+ const m = mockSdk();+ const broadReads = [];+ m.provision.dataverse = inconclusiveRaw();+ m.provision.fetchEntityMetadata = async (l) => { broadReads.push(l); return { logicalName: l, entitySetName: l + 's', relationships: [] }; };+ const runner = makeRunner({ emit: () => {}, total: 4 });+ await provisionDataModel({ sdk: m.sdk, provision: m.provision, runner, spec: relSpec('Account'), apply: true });++ assert.deepStrictEqual(broadReads, ['new_a'], 'the fallback still runs when no label can be poisoned');+});\ No newline at end of filediff --git a/plugins/model-apps/scripts/tests/fixed-issues-coverage.test.js b/plugins/model-apps/scripts/tests/fixed-issues-coverage.test.jsindex 6dde2e39e..5214815a2 100644--- a/plugins/model-apps/scripts/tests/fixed-issues-coverage.test.js+++ b/plugins/model-apps/scripts/tests/fixed-issues-coverage.test.js@@ -49,8 +49,27 @@ const MANIFEST = {function walk(dir) {if (!fs.existsSync(dir)) return [];const out = [];- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {+ let entries;+ // The scan races other test files. Several CLI tests create a scratch fixture directory UNDER+ // `evals/model-apps/**` and delete it when they finish, so a directory listed a moment ago can be+ // gone by the time it is descended into — which used to crash this whole file with ENOENT, but+ // only when the suite ran together, making it look like an unreproducible flake.+ //+ // Narrowed to the race it exists for. A blanket catch would let EACCES/EPERM/ENOTDIR silently+ // shrink the corpus this guard scans, so the guard would PASS by looking at less — which is the+ // exact failure mode it was written to prevent. Anything that is not "it vanished" is a real+ // environment problem and must fail loudly.+ try {+ entries = fs.readdirSync(dir, { withFileTypes: true });+ } catch (err) {+ if (err && err.code === 'ENOENT') return out;+ throw err;+ }+ for (const entry of entries) {const p = path.join(dir, entry.name);+ // Scratch output from another test is never a citation source, so skip it outright rather than+ // race it. The suffix is a timestamp, hence the loose match.+ if (entry.isDirectory() && /-cli-test-\d+$/.test(entry.name)) continue;if (entry.isDirectory()) out.push(...walk(p));else if (/\.(test\.js|md)$/.test(entry.name)) out.push(p);}@@ -62,7 +81,19 @@ const FILES = [...walk(TESTS_DIR), ...walk(EVALS_DIR)]// Exclude this file: it names every id by construction, so counting it would make the guard// trivially self-satisfying — the exact failure mode it exists to prevent..filter((f) => path.resolve(f) !== path.resolve(__filename))- .map((f) => ({ file: path.basename(f), body: fs.readFileSync(f, 'utf8') }));+ // Same race as `walk`, one level down: a file can vanish between the listing and the read. A file+ // that no longer exists cannot be anyone's citation, so dropping it is correct as well as safe —+ // but only for ENOENT. A permissions error means the corpus is incomplete for a reason nobody+ // intended, and a guard that quietly scans fewer files is a guard that passes for the wrong reason.+ .map((f) => {+ try {+ return { file: path.basename(f), body: fs.readFileSync(f, 'utf8') };+ } catch (err) {+ if (err && err.code === 'ENOENT') return null;+ throw err;+ }+ })+ .filter(Boolean);function citingFiles(id) {// `#478` must not match `#4780`, and `AB#6648526` is matched with optional space after the hash sodiff --git a/plugins/model-apps/scripts/tests/form-security-roles.test.js b/plugins/model-apps/scripts/tests/form-security-roles.test.jsindex 20819760a..8acecb3e1 100644--- a/plugins/model-apps/scripts/tests/form-security-roles.test.js+++ b/plugins/model-apps/scripts/tests/form-security-roles.test.js@@ -78,17 +78,62 @@ function provisionForRoles({ failSet } = {}) {}// Drive forms THEN security so the form id exists, exactly as a real build does.-async function build(spec, { failSet } = {}) {+async function build(spec, { failSet, warn } = {}) {const { sdk } = makeSimpleMockSdk();const { provision, calls } = provisionForRoles({ failSet });const events = [];const res = await runSdkBuild(spec, {sdk, provisionSdk: provision, apply: true,- phases: ['forms', 'security'], emit: (e) => events.push(e), warn: () => {},+ phases: ['forms', 'security'], emit: (e) => events.push(e), warn: warn || (() => {}),});return { res, calls, events };}+// --- the multi-Main-form warning ------------------------------------------------------------------+//+// `created.forms` keeps ONE id per entity, so a second Main form silently replaces the first there.+// The warning exists so the reader is not left believing the id was lost — and it must be HONEST+// about whether `created.formIds` can actually separate the two, because it sends the reader there.++test('two DISTINCTLY NAMED Main forms are warned about, and pointed at created.formIds', async () => {+ const spec = specWithFormRoles(null);+ spec.forms = [+ { entity: 'new_ticket', name: 'Standard', formType: 'Main' },+ { entity: 'new_ticket', name: 'Expanded', formType: 'Main' },+ ];+ const warnings = [];+ const { res } = await build(spec, { warn: (m) => warnings.push(String(m)) });+ const w = warnings.find((m) => /more than one Main form/.test(m));+ assert.ok(w, JSON.stringify(warnings));+ assert.match(w, /The other ids are in created\.formIds/);+ assert.notStrictEqual(res.created.formIds['new_ticket|Main|Standard'], undefined);+ assert.notStrictEqual(res.created.formIds['new_ticket|Main|Expanded'], undefined);+ assert.notStrictEqual(res.created.formIds['new_ticket|Main|Standard'], res.created.formIds['new_ticket|Main|Expanded'],+ 'distinct names really do separate them, which is what the warning promises');+});++test('two UNNAMED Main forms are told the truth: formIds cannot separate them either', async () => {+ // The defect: `distinct` was computed by rebuilding an identity key from the earlier form's+ // DISPLAY name ("new_ticket form"), while `formIdentityKey` uses the RAW name (""). Two unnamed+ // forms therefore looked distinct and the warning sent the reader to `created.formIds` — where+ // both collide on the SAME key and the first id is genuinely gone. The warning must instead say+ // "give them distinct names".+ const spec = specWithFormRoles(null);+ spec.forms = [+ { entity: 'new_ticket', formType: 'Main' },+ { entity: 'new_ticket', formType: 'Main' },+ ];+ const warnings = [];+ const { res } = await build(spec, { warn: (m) => warnings.push(String(m)) });+ const w = warnings.find((m) => /more than one Main form/.test(m));+ assert.ok(w, JSON.stringify(warnings));+ assert.match(w, /created\.formIds cannot separate them either/);+ assert.doesNotMatch(w, /The other ids are in created\.formIds/,+ 'promising a map that cannot answer the question is the bug');+ assert.strictEqual(Object.keys(res.created.formIds).filter((k) => k.startsWith('new_ticket|Main|')).length, 1,+ 'and the collision is real: both unnamed forms land on one key');+});+test('a form offered to two personas resolves them to the roles this build created', async () => {const { res, calls } = await build(specWithFormRoles({ personas: ['Dispatcher', 'Technician'] }));assert.strictEqual(res.ok, true);diff --git a/plugins/model-apps/scripts/tests/localized-labels.test.js b/plugins/model-apps/scripts/tests/localized-labels.test.jsnew file mode 100644index 000000000..b265004f4--- /dev/null+++ b/plugins/model-apps/scripts/tests/localized-labels.test.js@@ -0,0 +1,667 @@+'use strict';+// AB#6686428 / #537(b) — localized Dataverse metadata labels.+//+// The reported gap: "the whole-app App Spec cannot express multiple Dataverse metadata labels for+// tables, plural names, primary fields, columns, lookups, or Choice options. Download also does not+// round-trip existing localized labels." The build created English labels only; the Spanish UI+// therefore fell back to English, and every create/edit needed a manual metadata patch afterwards.+//+// The shape is an LCID map ON THE FIELD, not a sibling `localizedLabels` block:+//+// "displayName": { "1033": "Project Baseline", "3082": "Línea base del proyecto" }+//+// That is the vendored SDK's own label shape (measured on the wire: createTable, createColumn,+// createGlobalOptionSet, createRelationship and createAlternateKey each serialize a map into a+// multi-entry LocalizedLabels array), so the spec passes it through instead of pre-flattening. It+// also keeps the label beside the name it labels, which a table-level block could not do for a+// Choice OPTION or a lookup's display name without inventing a parallel addressing scheme.+const { test } = require('node:test');+const assert = require('node:assert');+const { validateAppSpec, labelText, labelAliases, isLocalizedLabelMap, localizedLabelLcids, validateLabel, choiceValueMap } = require('../lib/app-spec.js');+const { labelFromDataverse, columnDisplayName, entityFromMetadata } = require('../download-model-app.js');++const ES = { 1033: 'Project Baseline', 3082: 'Línea base del proyecto' };++function base() {+ return {+ schemaVersion: 2,+ solution: { uniqueName: 'contoso', publisherPrefix: 'contoso' },+ app: { name: 'Contoso' },+ languageCode: 1033,+ entities: [{+ schemaName: 'contoso_projectbaseline',+ displayName: 'Project Baseline',+ primaryAttribute: { schemaName: 'contoso_title', displayName: 'Title' },+ columns: [],+ }],+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'Main', subAreas: [] }] }] },+ };+}++const errorsFor = (mutate, profile = 'plan') => { const s = base(); mutate(s); return validateAppSpec(s, { profile }).errors || []; };+const warningsFor = (mutate) => { const s = base(); mutate(s); return validateAppSpec(s, { profile: 'plan' }).warnings || []; };++// --- labelText ------------------------------------------------------------------------------------++test('labelText returns a plain string unchanged', () => {+ assert.strictEqual(labelText('Baseline'), 'Baseline');+});++test('labelText prefers the requested language, then 1033, then the lowest declared LCID', () => {+ assert.strictEqual(labelText(ES, 3082), 'Línea base del proyecto');+ // No requested language -> 1033. This step is load-bearing, not decorative: V8 orders+ // integer-like keys ASCENDING, so without it a { 1031, 1033 } label would resolve to GERMAN.+ assert.strictEqual(labelText({ 1031: 'Projektbasislinie', 1033: 'Project Baseline' }), 'Project Baseline');+ assert.strictEqual(labelText({ 3082: 'Línea base', 1033: 'Baseline' }), 'Baseline');+ // Neither the requested language nor 1033 exists -> the lowest declared, rather than an empty cell.+ assert.strictEqual(labelText({ 3082: 'Línea base' }, 1031), 'Línea base');+ assert.strictEqual(labelText({ 3082: 'Línea base', 1031: 'Basislinie' }, 1049), 'Basislinie');+});++test('labelText returns "" for nothing usable, so callers can fall back to a schema name', () => {+ for (const v of [undefined, null, {}, [], 42, { 'en-US': 'x' }]) assert.strictEqual(labelText(v), '', JSON.stringify(v));+});++test('localizedLabelLcids reports only canonical LCID keys', () => {+ assert.deepStrictEqual(localizedLabelLcids(ES), [1033, 3082]);+ assert.deepStrictEqual(localizedLabelLcids({ '01033': 'x', 'en-US': 'y' }), []);+ assert.deepStrictEqual(localizedLabelLcids('Baseline'), []);+ assert.strictEqual(isLocalizedLabelMap('Baseline'), false);+ assert.strictEqual(isLocalizedLabelMap([]), false);+});++// --- validation: the shape ------------------------------------------------------------------------++test('a localized label on every VERIFIED surface validates', () => {+ // The exact list the bug asks for, minus global choices: table, plural, primary field, column,+ // lookup, alternate key, and INLINE Choice options. `globalChoices[]` is covered by its own test+ // below — it is rejected, because Dataverse silently stores only the base language there.+ const s = base();+ s.entities[0].displayName = ES;+ s.entities[0].pluralName = { 1033: 'Project Baselines', 3082: 'Líneas base del proyecto' };+ s.entities[0].primaryAttribute.displayName = { 1033: 'Title', 3082: 'Título' };+ s.entities[0].columns = [+ { schemaName: 'contoso_note', type: 'Text', displayName: { 1033: 'Note', 3082: 'Nota' } },+ { schemaName: 'contoso_status', type: 'Choice', displayName: { 1033: 'Status', 3082: 'Estado' }, options: [{ 1033: 'Open', 3082: 'Abierto' }, { 1033: 'Closed', 3082: 'Cerrado' }] },+ ];+ s.entities[0].alternateKeys = [{ schemaName: 'contoso_key', columns: ['contoso_title'], displayName: { 1033: 'Key', 3082: 'Clave' } }];+ s.entities.push({ schemaName: 'contoso_project', displayName: 'Project', primaryAttribute: { schemaName: 'contoso_name' }, columns: [] });+ s.relationships = [{ type: 'OneToMany', referenced: 'contoso_project', referencing: 'contoso_projectbaseline', lookup: { schemaName: 'contoso_projectid', displayName: { 1033: 'Project', 3082: 'Proyecto' } } }];+ const r = validateAppSpec(s, { profile: 'deploy' });+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));+});++test('a LOCALIZED global choice is REJECTED — the platform silently drops it', () => {+ // Measured 0/4 on an org with 1033 and 3082 provisioned, INCLUDING through a raw+ // `POST /GlobalOptionSetDefinitions` that bypasses the SDK — so this is a platform limitation, not+ // a serialization bug. Accepting it would reproduce the exact defect this feature exists to end:+ // a green build with the author's second language silently gone. Rejecting is loud, lands BEFORE+ // any write, and the message names the verified workaround.+ const forDisplayName = errorsFor((s) => {+ s.globalChoices = [{ name: 'contoso_status', displayName: { 1033: 'Status', 3082: 'Estado' }, options: ['Open'] }];+ });+ assert.ok(forDisplayName.some((e) => /displayName cannot be localized/.test(e)), JSON.stringify(forDisplayName));+ assert.ok(forDisplayName.some((e) => /inline\s+Choice/i.test(e)), 'the error must name the workaround');++ const forOption = errorsFor((s) => {+ s.globalChoices = [{ name: 'contoso_status', displayName: 'Status', options: [{ 1033: 'Open', 3082: 'Abierto' }] }];+ });+ assert.ok(forOption.some((e) => /options\[0\] cannot be localized/.test(e)), JSON.stringify(forOption));++ // Counterfactual: a PLAIN global choice is untouched, and so is an INLINE localized Choice —+ // rejecting either would break the verified path and the workaround the message recommends.+ assert.deepStrictEqual(errorsFor((s) => {+ s.globalChoices = [{ name: 'contoso_status', displayName: 'Status', options: ['Open', 'Closed'] }];+ s.entities[0].columns = [{ schemaName: 'contoso_p', type: 'Choice', displayName: { 1033: 'P', 3082: 'P' }, options: [{ 1033: 'High', 3082: 'Alta' }] }];+ }), []);+});++test('the second entry point rejects a localized global choice identically', () => {+ // `provision-entities.js` has its own gate. Two gates that disagree about what a label IS teach+ // the author two different rules for one field.+ const { validateProvisionInput } = require('../lib/provision-input.js');+ const r = validateProvisionInput({+ solution: { uniqueName: 'S', publisherPrefix: 'new' }, languageCode: 1033, entities: [], relationships: [],+ globalChoices: [{ name: 'new_p', displayName: { 1033: 'P', 3082: 'Pr' }, options: ['High'] }],+ });+ assert.strictEqual(r.ok, false, JSON.stringify(r));+ assert.ok(r.errors.some((e) => /cannot be localized/.test(e)), JSON.stringify(r.errors));+});++test('a plain-string label still validates — every existing spec is unaffected', () => {+ assert.strictEqual(validateAppSpec(base(), { profile: 'deploy' }).ok, true);+});++test('a language TAG is rejected rather than guessed', () => {+ // es-ES is 3082 or 1034 depending on sort order. Guessing wrong would not fail — it would label+ // everything in the wrong language, which is far worse than a validation error.+ const errs = errorsFor((s) => { s.entities[0].displayName = { 'es-ES': 'Línea base' }; });+ const hit = errs.find((e) => /is not an LCID/.test(e));+ assert.ok(hit, JSON.stringify(errs));+ assert.match(hit, /not a language tag/);+});++test('a non-canonical integer key is rejected', () => {+ // "01033" is not what Dataverse round-trips, and accepting it would produce two spec keys that+ // mean one language.+ assert.ok(errorsFor((s) => { s.entities[0].displayName = { '01033': 'x' }; }).some((e) => /is not an LCID/.test(e)));+});++test('an out-of-range LCID is rejected', () => {+ assert.ok(errorsFor((s) => { s.entities[0].displayName = { 70000: 'x' }; }).some((e) => /out of range/.test(e)));+});++test('an EMPTY localized label is rejected — the SDK rejects it too', () => {+ const errs = errorsFor((s) => { s.entities[0].displayName = {}; });+ assert.ok(errs.some((e) => /empty localized label/.test(e)), JSON.stringify(errs));+});++test('a blank or non-string label value is rejected per LCID', () => {+ for (const bad of ['', ' ', 42, null]) {+ const errs = errorsFor((s) => { s.entities[0].displayName = { 1033: 'Baseline', 3082: bad }; });+ assert.ok(errs.some((e) => /label for LCID 3082 must be a non-empty string/.test(e)), `${JSON.stringify(bad)}: ${JSON.stringify(errs)}`);+ }+});++test('an array is rejected — it is not a label of either shape', () => {+ assert.ok(errorsFor((s) => { s.entities[0].displayName = ['Baseline']; }).some((e) => /must be a string, or a localized label keyed by LCID/.test(e)));+});++test('validateLabel survives a value whose keys cannot be read', () => {+ // A validator that CRASHES on a hostile spec is worse than one that rejects it: the author gets a+ // stack trace instead of the list of everything else wrong with their spec.+ const errors = [];+ validateLabel(new Proxy({}, { ownKeys() { throw new Error('trap'); } }), 'entity x: displayName', errors);+ assert.deepStrictEqual(errors, ['entity x: displayName could not be read as a localized label']);+});++// --- the plural rule ------------------------------------------------------------------------------++test('a localized displayName REQUIRES an explicit pluralName', () => {+ // The fallback appends "s" (`${displayName}s`). That is not a plural rule outside English, and on+ // a label map it would produce "[object Object]s". Refusing is the only honest option.+ const errs = errorsFor((s) => { s.entities[0].displayName = ES; });+ const hit = errs.find((e) => /pluralName is required when displayName is a localized label/.test(e));+ assert.ok(hit, JSON.stringify(errs));+ assert.match(hit, /cannot be derived by appending "s"/);+});++test('a plain displayName still derives its plural, unchanged', () => {+ assert.strictEqual(validateAppSpec(base(), { profile: 'deploy' }).ok, true);+});++// --- the base-language advisory -------------------------------------------------------------------++test('a localized label omitting the base language WARNS but does not fail', () => {+ // The reporter's own workaround note says both labels must be sent "because a single-language PUT+ // can overwrite 1033". The base label is what every user without a matching UI language sees, so+ // omitting it is nearly always a mistake — but a deliberately Spanish-only table is legal.+ const s = base();+ s.languageCode = 1033;+ s.entities[0].displayName = { 3082: 'Línea base del proyecto' };+ s.entities[0].pluralName = { 3082: 'Líneas base' };+ const r = validateAppSpec(s, { profile: 'deploy' });+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));+ const hit = (r.warnings || []).find((w) => /no label for the spec's languageCode 1033/.test(w));+ assert.ok(hit, JSON.stringify(r.warnings));+ assert.match(hit, /Add "1033" alongside 3082/, 'the warning must say what to add');+});++test('no base-language warning when the base language IS present', () => {+ // A warning that fires on every correct spec is a warning nobody reads.+ const ws = warningsFor((s) => { s.entities[0].displayName = ES; s.entities[0].pluralName = { 1033: 'Baselines', 3082: 'Líneas base' }; });+ assert.deepStrictEqual(ws.filter((w) => /no label for the spec's languageCode/.test(w)), []);+});++// --- render + derive sites ------------------------------------------------------------------------++test('a localized label never reaches a rendered document as [object Object]', () => {+ const { renderAppSpecDoc } = require('../lib/app-spec-doc.js');+ const { renderAppPreview } = require('../lib/app-preview.js');+ const s = base();+ s.languageCode = 3082;+ s.entities[0].displayName = ES;+ s.entities[0].pluralName = { 1033: 'Project Baselines', 3082: 'Líneas base del proyecto' };+ s.entities[0].primaryAttribute.displayName = { 1033: 'Title', 3082: 'Título' };+ s.entities[0].columns = [{ schemaName: 'contoso_note', type: 'Text', displayName: { 1033: 'Note', 3082: 'Nota' } }];+ for (const [name, text, expect] of [+ ['plan doc', renderAppSpecDoc(s), /Título/],+ // The console preview renders table names but shows the primary column by SCHEMA name, so the+ // table label is the assertion that fits it.+ ['app preview', renderAppPreview(s), /Línea base del proyecto/],+ ]) {+ assert.doesNotMatch(text, /\[object Object\]/, `${name} rendered a raw label object`);+ assert.match(text, expect, `${name} did not resolve the label to languageCode 3082`);+ }+});++test('eval schema facts resolve a localized table label to a string', () => {+ const { schemaFacts } = require('../lib/schema-facts.js');+ const s = base();+ s.entities[0].displayName = ES;+ s.entities[0].pluralName = { 1033: 'Project Baselines', 3082: 'Líneas base' };+ const facts = schemaFacts(s);+ const e = (facts.tables || facts.entities || [])[0] || {};+ assert.strictEqual(typeof e.displayName, 'string', JSON.stringify(facts).slice(0, 400));+ assert.strictEqual(e.displayName, 'Project Baseline');+ assert.strictEqual(JSON.stringify(facts).includes('[object Object]'), false);+});++test('eval choice facts carry ONE label per value, not one per language', () => {+ // choiceValueMap indexes a localized option under every language so sample data resolves in+ // either. An eval fact compares against Dataverse, where the option has ONE value — emitting a+ // duplicate fact per language would make every bilingual choice look like twice as many options.+ const { schemaFacts } = require('../lib/schema-facts.js');+ const s = base();+ s.entities[0].columns = [{ schemaName: 'contoso_status', type: 'Choice', options: [{ 1033: 'Open', 3082: 'Abierto' }, { 1033: 'Closed', 3082: 'Cerrado' }] }];+ const facts = schemaFacts(s);+ const table = (facts.tables || facts.entities || [])[0] || {};+ const col = ((table.columns || []).find((c) => /contoso_status/i.test(c.logicalName || c.schemaName || ''))) || {};+ const opts = col.choices || col.options || [];+ assert.strictEqual(opts.length, 2, JSON.stringify(col));+ assert.deepStrictEqual(opts.map((o) => o.value), [100000000, 100000001]);+ assert.deepStrictEqual(opts.map((o) => o.label), ['Open', 'Closed'], 'the first-declared language must win');+});++test('a localized Choice option resolves from EITHER language for sampleData', () => {+ // THE regression this guards: `choiceValueMap` used to key on `String(label)`, which turns a label+ // map into the literal key "[object Object]" — so every sample record referencing a localized+ // option would fail to resolve, silently, at build time.+ const entity = { schemaName: 'contoso_projectbaseline', columns: [{ schemaName: 'contoso_status', type: 'Choice', options: [{ 1033: 'Open', 3082: 'Abierto' }, { 1033: 'Closed', 3082: 'Cerrado' }] }] };+ const map = choiceValueMap(entity, {})['contoso_status'];+ assert.strictEqual(map.Open, 100000000);+ assert.strictEqual(map.Abierto, 100000000, 'the Spanish label must resolve to the SAME value');+ assert.strictEqual(map.Closed, 100000001);+ assert.strictEqual(map.Cerrado, 100000001);+ assert.strictEqual('[object Object]' in map, false);+});++test('labelAliases is the one rule both sample data and surfaces use', () => {+ // DRY: two different resolvers disagreeing about what a label can be CALLED would mean a spec that+ // validates for sample data and not for surfaces, or vice versa.+ assert.deepStrictEqual(labelAliases('Open'), ['Open']);+ assert.deepStrictEqual(labelAliases({ 1033: 'Open', 3082: 'Abierto' }), ['Open', 'Abierto']);+ assert.deepStrictEqual(labelAliases(' '), []);+ assert.deepStrictEqual(labelAliases(undefined), []);+});++test('a surface named in EITHER language resolves', () => {+ // `surfaces[]` is the machine-readable claim that a job is satisfied by these screens. On a+ // bilingual spec, naming the Spanish label is as legitimate as naming the English one — matching+ // only the resolved language would report a real surface as unresolved.+ const { resolveSurfaces } = require('../lib/surface-resolver.js');+ const mk = (surface) => {+ const s = base();+ s.entities[0].displayName = ES;+ s.entities[0].pluralName = { 1033: 'Project Baselines', 3082: 'Líneas base' };+ s.personas = [{ persona: 'Manager', jobs: [{ name: 'Manage', surfaces: [surface], privileges: [{ entity: 'contoso_projectbaseline', access: ['read'] }] }] }];+ return resolveSurfaces(s);+ };+ for (const name of ['Project Baseline', 'Línea base del proyecto', 'contoso_projectbaseline']) {+ const res = mk(name);+ const unresolved = (res.unresolved || res.filter?.((r) => !r.resolved) || []).length;+ assert.strictEqual(unresolved, 0, `'${name}' did not resolve: ${JSON.stringify(res).slice(0, 300)}`);+ }+});++// --- download round-trip --------------------------------------------------------------------------++const dvLabel = (pairs) => ({ LocalizedLabels: pairs.map(([LanguageCode, Label]) => ({ Label, LanguageCode })) });++test('labelFromDataverse returns a STRING for one language and a MAP for several', () => {+ // The asymmetry is deliberate: emitting { "1033": "Order" } for every single-language table would+ // change the shape of every spec this tool has ever written, and make every download diff noisy.+ assert.strictEqual(labelFromDataverse(dvLabel([[1033, 'Order']])), 'Order');+ assert.deepStrictEqual(labelFromDataverse(dvLabel([[1033, 'Order'], [3082, 'Pedido']])), { 1033: 'Order', 3082: 'Pedido' });+});++test('labelFromDataverse emits deterministic key order without needing a sort', () => {+ // V8 orders integer-like object keys ASCENDING regardless of insertion order, so two downloads of+ // the same table serialize identically with no sort step. Pinned because the alternative — a sort+ // that can never be shown to matter — reads as if it earned the guarantee.+ assert.strictEqual(JSON.stringify(labelFromDataverse(dvLabel([[3082, 'Pedido'], [1033, 'Order']]))), '{"1033":"Order","3082":"Pedido"}');+ assert.strictEqual(JSON.stringify(labelFromDataverse(dvLabel([[1033, 'Order'], [3082, 'Pedido']]))), '{"1033":"Order","3082":"Pedido"}');+});++test('labelAliases order follows ascending LCID, not the author write order', () => {+ // Pinned because `choiceFacts` collapses a multi-alias option to its FIRST alias, so the eval fact+ // it emits depends on this ordering being predictable.+ assert.deepStrictEqual(labelAliases({ 3082: 'Abierto', 1033: 'Open' }), ['Open', 'Abierto']);+});++test('labelFromDataverse returns undefined for nothing usable, so a caller can fall back', () => {+ for (const v of [undefined, null, 'Order', {}, dvLabel([]), { LocalizedLabels: [{ Label: ' ', LanguageCode: 1033 }] }]) {+ assert.strictEqual(labelFromDataverse(v), undefined, JSON.stringify(v));+ }+ // A row with a junk LanguageCode is skipped rather than keyed under NaN.+ assert.strictEqual(labelFromDataverse({ LocalizedLabels: [{ Label: 'x', LanguageCode: 'en-US' }] }), undefined);+});++test('entityFromMetadata round-trips a bilingual table, plural and column', () => {+ const meta = {+ logicalName: 'contoso_projectbaseline', schemaName: 'contoso_projectbaseline',+ displayName: 'Project Baseline', primaryNameAttribute: 'contoso_title',+ DisplayName: dvLabel([[1033, 'Project Baseline'], [3082, 'Línea base del proyecto']]),+ DisplayCollectionName: dvLabel([[1033, 'Project Baselines'], [3082, 'Líneas base del proyecto']]),+ attributes: [{ logicalName: 'contoso_note', schemaName: 'contoso_note', attributeType: 'String', isCustomAttribute: true, DisplayName: dvLabel([[1033, 'Note'], [3082, 'Nota']]) }],+ };+ const e = entityFromMetadata(meta, 'contoso_projectbaseline');+ assert.deepStrictEqual(e.displayName, { 1033: 'Project Baseline', 3082: 'Línea base del proyecto' });+ // The plural is emitted BECAUSE the display name is localized — validateAppSpec then requires it.+ assert.deepStrictEqual(e.pluralName, { 1033: 'Project Baselines', 3082: 'Líneas base del proyecto' });+ assert.deepStrictEqual(e.columns[0].displayName, { 1033: 'Note', 3082: 'Nota' });+});++test('a downloaded bilingual entity VALIDATES — the round trip closes', () => {+ // The whole point: download -> rebuild must not fail on its own output. Without the pluralName+ // emission above, this spec would be rejected by the localized-plural rule.+ const meta = {+ logicalName: 'contoso_projectbaseline', schemaName: 'contoso_projectbaseline',+ displayName: 'Project Baseline', primaryNameAttribute: 'contoso_title',+ DisplayName: dvLabel([[1033, 'Project Baseline'], [3082, 'Línea base del proyecto']]),+ DisplayCollectionName: dvLabel([[1033, 'Project Baselines'], [3082, 'Líneas base del proyecto']]),+ attributes: [],+ };+ const s = base();+ s.entities = [entityFromMetadata(meta, 'contoso_projectbaseline')];+ const r = validateAppSpec(s, { profile: 'plan', reconstructed: true });+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));+});++test('a single-language table still downloads as a plain string', () => {+ const meta = {+ logicalName: 'new_order', schemaName: 'new_order', displayName: 'Order', primaryNameAttribute: 'new_name',+ DisplayName: dvLabel([[1033, 'Order']]), DisplayCollectionName: dvLabel([[1033, 'Orders']]), attributes: [],+ };+ const e = entityFromMetadata(meta, 'new_order');+ assert.strictEqual(e.displayName, 'Order');+ // No plural is emitted for a plain label — it was never in the spec before and adding it would+ // change every existing download.+ assert.strictEqual('pluralName' in e, false, JSON.stringify(e));+});++test('a metadata read that returned no labels falls back to the SDK display name', () => {+ // The raw metadata read is best-effort (it is wrapped in a catch). Losing it must degrade to the+ // previous behaviour, not to an empty label.+ const e = entityFromMetadata({ logicalName: 'new_order', schemaName: 'new_order', displayName: 'Order', primaryNameAttribute: 'new_name', attributes: [] }, 'new_order');+ assert.strictEqual(e.displayName, 'Order');+});++// --- the regression LIVE testing caught that the unit tests above did not --------------------------++test('an EMPTY Dataverse Label never emits the raw object as a column displayName', () => {+ // FOUND BY RUNNING A REAL DOWNLOAD, not by review. A synthetic lookup `*name` column carries+ // EXACTLY this shape — measured on a live org for cfo_customeridname / cfo_billtoname:+ //+ // {"LocalizedLabels":[],"UserLocalizedLabel":null}+ //+ // Merging the raw `DisplayName` into the attribute list (which this change does, to carry every+ // language) made that object reachable by the pre-existing `|| a.DisplayName` fallback, so the+ // download emitted it verbatim and the spec failed its OWN validation with+ // "'LocalizedLabels' is not an LCID". A download that cannot write a valid spec is worse than one+ // that loses a label, so this is the load-bearing case.+ const EMPTY = { LocalizedLabels: [], UserLocalizedLabel: null };+ assert.strictEqual(labelFromDataverse(EMPTY), undefined);+ assert.strictEqual(columnDisplayName({ logicalName: 'cfo_customeridname', DisplayName: EMPTY }), undefined,+ 'an unlabelled column must be OMITTED, not labelled with the raw Label object');++ const e = entityFromMetadata({+ logicalName: 'cfo_workorder', schemaName: 'cfo_workorder', displayName: 'Work Order', primaryNameAttribute: 'cfo_title',+ attributes: [+ { logicalName: 'cfo_customeridname', schemaName: 'cfo_customeridname', attributeType: 'String', isCustomAttribute: true, DisplayName: EMPTY },+ { logicalName: 'cfo_title2', schemaName: 'cfo_title2', attributeType: 'String', isCustomAttribute: true, displayName: 'Title 2', DisplayName: EMPTY },+ ],+ }, 'cfo_workorder');+ const unlabelled = e.columns.find((c) => c.schemaName === 'cfo_customeridname');+ assert.strictEqual('displayName' in unlabelled, false, JSON.stringify(unlabelled));+ // ...but the SDK's own flattened string is still used when it has one.+ assert.strictEqual(e.columns.find((c) => c.schemaName === 'cfo_title2').displayName, 'Title 2');++ // And the whole spec must validate — the property the live run actually broke.+ const s = base();+ s.entities = [e];+ const r = validateAppSpec(s, { profile: 'plan', reconstructed: true });+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));+});++test('columnDisplayName never returns a raw Label object for any shape', () => {+ // Exhaustive over the shapes a live metadata read can produce, because ONE leak fails the download.+ const shapes = [+ { DisplayName: { LocalizedLabels: [], UserLocalizedLabel: null } },+ { DisplayName: { LocalizedLabels: [{ Label: ' ', LanguageCode: 1033 }] } },+ { DisplayName: { LocalizedLabels: [{ Label: 'x', LanguageCode: 'en-US' }] } },+ { DisplayName: {} },+ { DisplayName: null },+ {},+ { displayName: '', DisplayName: { LocalizedLabels: [] } },+ { displayName: ' ', DisplayName: { LocalizedLabels: [] } },+ ];+ for (const a of shapes) {+ const got = columnDisplayName(a);+ assert.ok(got === undefined || typeof got === 'string' || isLocalizedLabelMap(got), `${JSON.stringify(a)} -> ${JSON.stringify(got)}`);+ if (isLocalizedLabelMap(got)) assert.deepStrictEqual(localizedLabelLcids(got).length > 0, true);+ }+ // A UserLocalizedLabel with no LocalizedLabels is still a real label and must survive.+ assert.strictEqual(columnDisplayName({ DisplayName: { LocalizedLabels: [], UserLocalizedLabel: { Label: 'Owner', LanguageCode: 1033 } } }), 'Owner');+});++// --- the unprovisioned-language guard -------------------------------------------------------------+//+// THE most important test in this file. LIVE-MEASURED against a 1033-only organization: `createTable`+// carrying `DisplayName: { 1033, 3082 }` returns SUCCESS and stores ONLY the 1033 label. Dataverse+// does not warn, error or report the drop anywhere. Without this guard the feature would recreate the+// exact bug it was built to fix — a green build with the request silently gone.++test('a localized label naming an UNPROVISIONED language HALTS before any write', async () => {+ const { provisionDataModel, BuildHalt } = require('../lib/entity-provision.js');+ const writes = [];+ const s = base();+ s.entities[0].displayName = ES; // asks for 3082+ s.entities[0].pluralName = { 1033: 'Project Baselines', 3082: 'Líneas base' };+ const sdk = { createTable: async (o) => { writes.push(o); return { logicalName: 'x', entitySetName: 'xs' }; } };+ const runner = { run: async (p, l, fn) => fn(), skip: () => {}, mapLimit: async (i, n, fn) => Promise.all(i.map(fn)) };+ await assert.rejects(+ () => provisionDataModel({+ spec: s, sdk, provision: { findTables: async () => [], findColumns: async () => [], queryRecords: async () => [] },+ runner, preResolvedLanguageCode: 1033, provisionedLanguages: async () => [1033],+ }),+ (err) => {+ assert.ok(err instanceof BuildHalt, `expected a BuildHalt, got ${err && err.name}`);+ assert.strictEqual(err.code, 'localized-label-language-not-provisioned');+ assert.match(err.message, /3082 \(first used by entity contoso_projectbaseline displayName\)/, err.message);+ // The message must state WHY silence is the danger, or the reader assumes a warning would suffice.+ assert.match(err.message, /silently store only the provisioned one/);+ assert.match(err.message, /Provisioned languages: 1033/);+ return true;+ },+ );+ // BEFORE any write, not as a post-hoc verify: a partial data model is the outcome being avoided.+ assert.deepStrictEqual(writes, [], 'the build wrote a table before checking the label languages');+});++test('the guard names EVERY unprovisioned language, sorted, with where each came from', async () => {+ const { localizedLabelLcidsInSpec, checkLocalizedLabelLanguages } = require('../lib/entity-provision.js');+ const s = base();+ s.entities[0].displayName = { 1033: 'Baseline', 3082: 'Línea base' };+ s.entities[0].pluralName = { 1033: 'Baselines', 1031: 'Basislinien' };+ s.entities[0].columns = [+ // A column DISPLAY NAME and a Choice OPTION carry different unprovisioned LCIDs, so a guard that+ // walks only one of the two is caught. (1040 = it-IT on the column, 1036 = fr-FR on the option.)+ { schemaName: 'contoso_note', type: 'Text', displayName: { 1033: 'Note', 1040: 'Nota' } },+ { schemaName: 'contoso_status', type: 'Choice', options: [{ 1033: 'Open', 1036: 'Ouvert' }] },+ ];+ s.entities[0].alternateKeys = [{ schemaName: 'contoso_key', columns: ['contoso_title'], displayName: { 1033: 'Key', 1043: 'Sleutel' } }];+ s.entities.push({ schemaName: 'contoso_project', displayName: 'Project', primaryAttribute: { schemaName: 'contoso_name' }, columns: [] });+ s.relationships = [{ type: 'OneToMany', referenced: 'contoso_project', referencing: 'contoso_projectbaseline', lookup: { schemaName: 'contoso_projectid', displayName: { 1033: 'Project', 1053: 'Projekt' } } }];+ s.globalChoices = [{ name: 'contoso_p', displayName: { 1033: 'P', 3082: 'P' }, options: [{ 1033: 'High', 1045: 'Wysoki' }] }];+ // Every authorable label site must be walked, or a spec passes the guard and still loses a language.+ assert.deepStrictEqual(localizedLabelLcidsInSpec(s).map((w) => w.lcid), [1031, 1033, 1036, 1040, 1043, 1045, 1053, 3082]);+ await assert.rejects(+ () => checkLocalizedLabelLanguages(s, async () => [1033]),+ (err) => {+ for (const lcid of [1031, 1036, 1040, 1043, 1045, 1053, 3082]) assert.match(err.message, new RegExp(String(lcid)), `${lcid} missing from: ${err.message}`);+ assert.match(err.message, /1031 \(first used by entity contoso_projectbaseline pluralName\)/);+ assert.match(err.message, /1036 \(first used by entity contoso_projectbaseline column contoso_status option\)/);+ assert.match(err.message, /1040 \(first used by entity contoso_projectbaseline column contoso_note displayName\)/);+ assert.match(err.message, /1043 \(first used by entity contoso_projectbaseline alternate key contoso_key\)/);+ assert.match(err.message, /1045 \(first used by globalChoice contoso_p option\)/);+ assert.match(err.message, /1053 \(first used by relationship lookup contoso_projectid\)/);+ return true;+ },+ );+});++test('the guard passes when every requested language IS provisioned', async () => {+ const { checkLocalizedLabelLanguages } = require('../lib/entity-provision.js');+ const s = base();+ s.entities[0].displayName = ES;+ s.entities[0].pluralName = { 1033: 'Baselines', 3082: 'Líneas base' };+ await checkLocalizedLabelLanguages(s, async () => [1033, 3082]); // must not throw+});++test('the guard is best-effort: an unreadable probe leaves the build unchanged', async () => {+ // Identical policy to the existing `checkProvisioned`: a diagnostic that cannot answer must never+ // block work that would otherwise succeed.+ const { checkLocalizedLabelLanguages } = require('../lib/entity-provision.js');+ const s = base();+ s.entities[0].displayName = ES;+ s.entities[0].pluralName = { 1033: 'Baselines', 3082: 'Líneas base' };+ for (const probe of [undefined, async () => { throw new Error('403'); }, async () => [], async () => null]) {+ await checkLocalizedLabelLanguages(s, probe); // must not throw+ }+});++test('the guard costs nothing for a spec with only plain labels', async () => {+ // No localized labels -> the probe is never even called, so an all-string spec pays no round trip.+ const { checkLocalizedLabelLanguages } = require('../lib/entity-provision.js');+ let called = 0;+ await checkLocalizedLabelLanguages(base(), async () => { called += 1; return [1033]; });+ assert.strictEqual(called, 0);+});++test('the localized label reaches the SDK UNFLATTENED', async () => {+ // The plugin must not pre-flatten: the SDK's serializer is what turns a map into a multi-entry+ // LocalizedLabels array. Flattening here would silently restore the English-only behaviour while+ // every validation and document still claimed two languages.+ const { provisionDataModel } = require('../lib/entity-provision.js');+ const calls = [];+ const s = base();+ s.entities[0].displayName = ES;+ s.entities[0].pluralName = { 1033: 'Project Baselines', 3082: 'Líneas base' };+ s.entities[0].primaryAttribute.displayName = { 1033: 'Title', 3082: 'Título' };+ const sdk = {+ createTable: async (o) => { calls.push(o); return { logicalName: o.schemaName.toLowerCase(), entitySetName: `${o.schemaName.toLowerCase()}s` }; },+ createColumn: async (e, o) => ({ logicalName: o.schemaName.toLowerCase() }),+ updateTable: async () => undefined,+ };+ const provision = {+ findTables: async () => [],+ findColumns: async () => [],+ fetchEntityMetadata: async (l) => ({ logicalName: l, entitySetName: `${l}s`, relationships: [] }),+ queryRecords: async () => [],+ };+ const runner = {+ run: async (phase, label, fn, o = {}) => { try { return await fn(); } catch (err) { if (o.skipIf && o.skipIf(err)) return undefined; throw err; } },+ skip: () => {},+ mapLimit: async (items, _n, fn) => { const out = []; for (const it of items) out.push(await fn(it)); return out; },+ };+ await provisionDataModel({ spec: s, sdk, provision, runner, preResolvedLanguageCode: 1033 });+ const t = calls[0];+ assert.ok(t, 'createTable was never called');+ assert.deepStrictEqual(t.displayName, ES, 'displayName was flattened before reaching the SDK');+ assert.deepStrictEqual(t.pluralName, { 1033: 'Project Baselines', 3082: 'Líneas base' });+ assert.deepStrictEqual(t.primaryColumnDisplayName, { 1033: 'Title', 3082: 'Título' });+});++test('a localized COLUMN, lookup, alternate key and Choice label all reach the SDK unflattened', async () => {+ const { provisionDataModel } = require('../lib/entity-provision.js');+ const seen = { column: null, relationship: null, key: null, choice: null };+ const s = base();+ s.entities[0].columns = [{ schemaName: 'contoso_note', type: 'Text', displayName: { 1033: 'Note', 3082: 'Nota' } }];+ s.entities[0].alternateKeys = [{ schemaName: 'contoso_key', columns: ['contoso_title'], displayName: { 1033: 'Key', 3082: 'Clave' } }];+ s.entities.push({ schemaName: 'contoso_project', displayName: 'Project', primaryAttribute: { schemaName: 'contoso_name' }, columns: [] });+ s.relationships = [{ type: 'OneToMany', referenced: 'contoso_project', referencing: 'contoso_projectbaseline', lookup: { schemaName: 'contoso_projectid', displayName: { 1033: 'Project', 3082: 'Proyecto' } } }];+ s.globalChoices = [{ name: 'contoso_priority', displayName: { 1033: 'Priority', 3082: 'Prioridad' }, options: [{ 1033: 'High', 3082: 'Alta' }] }];+ const sdk = {+ createTable: async (o) => ({ logicalName: o.schemaName.toLowerCase(), entitySetName: `${o.schemaName.toLowerCase()}s` }),+ createColumn: async (e, o) => { if (o.schemaName === 'contoso_note') seen.column = o; return { logicalName: o.schemaName.toLowerCase() }; },+ createRelationship: async (o) => { seen.relationship = o; return { schemaName: o.schemaName }; },+ createAlternateKey: async (e, o) => { seen.key = o; return { logicalName: o.schemaName.toLowerCase() }; },+ createGlobalOptionSet: async (o) => { seen.choice = o; return { name: o.name, metadataId: 'gc-1' }; },+ updateTable: async () => undefined,+ };+ const provision = {+ findTables: async () => [],+ findColumns: async () => [],+ fetchEntityMetadata: async (l) => ({ logicalName: l, entitySetName: `${l}s`, relationships: [] }),+ queryRecords: async () => [],+ };+ const runner = {+ run: async (phase, label, fn, o = {}) => { try { return await fn(); } catch (err) { if (o.skipIf && o.skipIf(err)) return undefined; throw err; } },+ skip: () => {},+ mapLimit: async (items, _n, fn) => { const out = []; for (const it of items) out.push(await fn(it)); return out; },+ };+ await provisionDataModel({ spec: s, sdk, provision, runner, preResolvedLanguageCode: 1033 });+ assert.deepStrictEqual(seen.column && seen.column.displayName, { 1033: 'Note', 3082: 'Nota' }, JSON.stringify(seen.column));+ assert.deepStrictEqual(seen.relationship && seen.relationship.lookupDisplayName, { 1033: 'Project', 3082: 'Proyecto' }, JSON.stringify(seen.relationship));+ assert.deepStrictEqual(seen.key && seen.key.displayName, { 1033: 'Key', 3082: 'Clave' }, JSON.stringify(seen.key));+ assert.deepStrictEqual(seen.choice && seen.choice.displayName, { 1033: 'Priority', 3082: 'Prioridad' }, JSON.stringify(seen.choice));+ assert.deepStrictEqual(seen.choice && seen.choice.options, [{ value: 100000000, label: { 1033: 'High', 3082: 'Alta' } }], JSON.stringify(seen.choice));+});+// --- the poisoning-read hazard: the probe must never be resolved by a broad read ------------------+//+// The rest of this class of test lives in bpf-security-roles.test.js (the narrow-probe tests landed+// there while that file was the active workspace). They belong together; see+// "the table existence probe is a NARROW metadata read" there.++test('an INCONCLUSIVE existence probe HALTS a localized table rather than falling back', async () => {+ // `findTables` can safely prove PRESENCE, but a MISS is followed immediately by `createTable` --+ // with the poisoning read already on the wire. So for a localized entity an unresolved probe must+ // stop the build, not be answered by the very read that loses the label. Fail-closed for the same+ // reason as the unprovisioned-language halt: once the table exists, a lost label is a manual fix.+ const { provisionDataModel } = require('../lib/entity-provision.js');+ let findTablesCalled = 0;+ const args = (displayName) => ({+ spec: {+ solution: { uniqueName: 'c', publisherPrefix: 'c' },+ languageCode: 1033,+ entities: [{ schemaName: 'c_t', displayName, pluralName: displayName, primaryAttribute: { schemaName: 'c_n' }, columns: [] }],+ relationships: [],+ },+ sdk: { createTable: async () => ({ logicalName: 'c_t', entitySetName: 'c_ts' }), updateTable: async () => undefined, updateColumn: async () => undefined },+ provision: {+ dataverse: { get: async () => ({ status: 503, headers: {}, body: {} }) },+ findTables: async () => { findTablesCalled += 1; return []; },+ findColumns: async () => [],+ fetchEntityMetadata: async (l) => ({ logicalName: l, entitySetName: 'c_ts', relationships: [] }),+ queryRecords: async () => [],+ },+ runner: {+ run: async (ph, l, fn, o = {}) => { try { return await fn(); } catch (e) { if (o.skipIf && o.skipIf(e)) return undefined; throw e; } },+ skip: () => {},+ mapLimit: async (items, _n, fn) => { const out = []; for (const it of items) out.push(await fn(it)); return out; },+ },+ warn: () => {},+ preResolvedLanguageCode: 1033,+ });++ await assert.rejects(+ () => provisionDataModel(args({ 1033: 'Table', 3082: 'Tabla' })),+ (err) => err.code === 'table-probe-inconclusive' && /localized/.test(err.message),+ 'a localized entity must halt on an unresolved probe');+ assert.strictEqual(findTablesCalled, 0, 'and it must NOT have issued the poisoning read to get there');++ // The halt must name a REAL phase. `stages.js` is the single source of truth for the 16 phase+ // names, and a halt tagged with one that is not in it makes the error report and the logs+ // disagree with every other halt in the file — which both use `data-model`.+ const { PHASES } = require('../lib/stages.js');+ let halted;+ await provisionDataModel(args({ 1033: 'Table', 3082: 'Tabla' })).catch((e) => { halted = e; });+ assert.ok(PHASES.includes(halted.phase), `phase '${halted.phase}' is not one of ${JSON.stringify(PHASES)}`);+ assert.strictEqual(halted.phase, 'data-model');++ // The counterfactual: a PLAIN label has nothing to lose, so the old fallback still applies and the+ // build proceeds. Tightening this path too would fail builds that are entirely correct.+ await provisionDataModel(args('Table'));+ assert.strictEqual(findTablesCalled, 1, 'a plain-label entity still falls back rather than halting');+});diff --git a/plugins/model-apps/scripts/tests/review-findings.test.js b/plugins/model-apps/scripts/tests/review-findings.test.jsnew file mode 100644index 000000000..fcfb4cb82--- /dev/null+++ b/plugins/model-apps/scripts/tests/review-findings.test.js@@ -0,0 +1,612 @@+'use strict';+// Regression tests for the ten defects an adversarial peer review found in the AB#6686423 /+// AB#6686428 / AB#6686429 changes. Every one was a real bug in code I had already tested, mutation-+// tested and (for roleGrants) live-verified — so each is pinned here by the PROPERTY it broke, not+// by the shape of the fix.+const { test } = require('node:test');+const assert = require('node:assert');+const { validateAppSpec, choiceValueMap, labelText, resolveSampleRecords } = require('../lib/app-spec.js');+const { validateProvisionInput } = require('../lib/provision-input.js');+const { phaseInputs } = (() => { const m = require('../lib/phase-diff.js'); return { phaseInputs: m.PHASE_INPUTS || m.phaseInputs }; })();+const { runSdkBuild, subgridLabel, viewDef } = require('../lib/sdk-build.js');+const { notRoundTrippedSummary, notRoundTrippedWarning } = require('../download-model-app.js');++function base() {+ return {+ schemaVersion: 2,+ solution: { uniqueName: 'contoso', publisherPrefix: 'contoso' },+ app: { name: 'Contoso' },+ languageCode: 1033,+ entities: [{ schemaName: 'contoso_order', displayName: 'Order', primaryAttribute: { schemaName: 'contoso_name' }, columns: [] }],+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'Main', subAreas: [] }] }] },+ };+}+const errorsFor = (mutate) => { const s = base(); mutate(s); return validateAppSpec(s, { profile: 'plan' }).errors || []; };++// --- Finding 1: roleGrants were invisible to --changed-only ---------------------------------------++test('#1 a roleGrant-only change is VISIBLE to the changed-only phase diff', async () => {+ // The security slice was `s.personas` alone, so a spec whose ONLY change was adding a roleGrant+ // diffed as "nothing changed": --changed-only reported "deployed app already matches the spec" and+ // never called AddPrivilegesRole. The table deployed and the role still had no access to it —+ // which IS the bug roleGrants[] exists to fix, reintroduced through the fast path.+ const { diffPhases } = require('../lib/phase-diff.js');+ const before = base();+ const after = base();+ after.roleGrants = [{ role: 'Viewer', privileges: [{ entity: 'contoso_order', access: ['read'], scope: 'organization' }] }];+ assert.ok(diffPhases(after, before).includes('security'), `security not in ${JSON.stringify(diffPhases(after, before))}`);+ // ...and EDITING an existing grant is a change too, not just adding the first one.+ const edited = JSON.parse(JSON.stringify(after));+ edited.roleGrants[0].privileges[0].access = ['read', 'write'];+ assert.ok(diffPhases(edited, after).includes('security'));+ // An untouched spec must still diff clean, or every build becomes a full build.+ assert.ok(!diffPhases(after, JSON.parse(JSON.stringify(after))).includes('security'));+});++// --- Finding 2: the role identity guard could be bypassed -----------------------------------------++const roleRow = (over = {}) => ({ roleid: '33333333-3333-3333-3333-333333333333', name: 'Shared', ismanaged: false, ...over });++function securitySdk(over = {}) {+ const calls = { addEntityPrivilegesToRole: [] };+ return {+ calls,+ queryRecords: async (entity) => {+ if (entity === 'businessunit') return [{ businessunitid: '44444444-4444-4444-4444-444444444444' }];+ if (entity === 'role') return [roleRow()];+ return [];+ },+ createPersonaRole: async (spec) => ({ roleId: '33333333-3333-3333-3333-333333333333', name: spec.name, reused: false, appliedPrivileges: [] }),+ addEntityPrivilegesToRole: async (roleId, privileges) => { calls.addEntityPrivilegesToRole.push({ roleId, privileges }); return []; },+ addSolutionComponent: async () => ({}),+ associateRecords: async () => ({}),+ disassociateRecords: async () => ({}),+ ...over,+ };+}+const applySecurity = (spec, sdk) => runSdkBuild(spec, { sdk, provisionSdk: sdk, apply: true, phases: ['security'] });++test('#2a a roleGrant pinned by roleId at a PERSONA role halts on the resolved id', async () => {+ // The static check compares NAMES, and a persona role does not exist at lint time, so a pinned id+ // aiming at the same role slipped through. The build then ran ReplacePrivilegesRole (removing+ // everything not on the persona) and AddPrivilegesRole against ONE role — and a failure between+ // the two leaves the access removed.+ const s = base();+ s.personas = [{ persona: 'Shared', jobs: [{ name: 'j', privileges: [{ entity: 'contoso_order', access: ['read'] }] }] }];+ s.roleGrants = [{ roleId: '33333333-3333-3333-3333-333333333333', privileges: [{ entity: 'contoso_order', access: ['write'], scope: 'organization' }] }];+ assert.strictEqual(validateAppSpec(s, { profile: 'plan' }).ok, true, 'a static check cannot see this — the apply path must');+ const sdk = securitySdk();+ await assert.rejects(() => applySecurity(s, sdk), (err) => {+ assert.strictEqual(err.code, 'role-grant-persona-overlap');+ assert.match(err.message, /also persona "Shared"/);+ return true;+ });+ assert.strictEqual(sdk.calls.addEntityPrivilegesToRole.length, 0, 'nothing may be granted once the overlap is known');+});++test('#2b a NAME and a roleId aliasing ONE role halt on the resolved id', async () => {+ // Two entries the static dedup could not see as one role. Splitting them across two SDK calls+ // hides the "entities sharing one privilege must request one depth" conflict, which the SDK+ // detects only WITHIN a call — so the later write silently wins.+ const s = base();+ s.roleGrants = [+ { role: 'Shared', privileges: [{ entity: 'contoso_order', access: ['read'], scope: 'user' }] },+ { roleId: '33333333-3333-3333-3333-333333333333', privileges: [{ entity: 'contoso_order', access: ['read'], scope: 'organization' }] },+ ];+ assert.strictEqual(validateAppSpec(s, { profile: 'plan' }).ok, true);+ const aliasSdk = securitySdk();+ await assert.rejects(() => applySecurity(s, aliasSdk), (err) => {+ assert.strictEqual(err.code, 'role-grant-duplicate-target');+ assert.match(err.message, /already targets/);+ return true;+ });+ // And NOTHING was granted. The guards run in a resolve-and-check pass over EVERY grant before the+ // first apply: interleaved, the first entry was written and only the second halted, leaving one+ // role changed and one not with nothing in the output saying which.+ assert.strictEqual(aliasSdk.calls.addEntityPrivilegesToRole.length, 0,+ `no grant may be applied once any later one is known to be invalid; got ${JSON.stringify(aliasSdk.calls.addEntityPrivilegesToRole)}`);+});++test('#2b-bis a VALID grant preceding an invalid one is not applied either', async () => {+ // The counterfactual that makes the assertion above mean something: here the first grant targets a+ // completely different, legitimate role, so under the old interleaved order it was applied+ // successfully before the second halted. Nothing about the first entry is wrong — it must still not+ // land, because a build that halts must not leave a partial security state behind.+ const s = base();+ s.roleGrants = [+ { role: 'Other', privileges: [{ entity: 'contoso_order', access: ['read'], scope: 'organization' }] },+ { role: 'Shared', privileges: [{ entity: 'contoso_order', access: ['read'], scope: 'user' }] },+ { roleId: '33333333-3333-3333-3333-333333333333', privileges: [{ entity: 'contoso_order', access: ['write'], scope: 'organization' }] },+ ];+ assert.strictEqual(validateAppSpec(s, { profile: 'plan' }).ok, true);+ const sdk = securitySdk();+ await assert.rejects(() => applySecurity(s, sdk), (err) => err.code === 'role-grant-duplicate-target');+ assert.strictEqual(sdk.calls.addEntityPrivilegesToRole.length, 0,+ `the leading VALID grant must not have been applied; got ${JSON.stringify(sdk.calls.addEntityPrivilegesToRole)}`);+});++test('#2c two same-named roles in DIFFERENT business units are allowed', async () => {+ // The old dedup keyed on the bare name, so this valid pair was rejected. A role is identified by+ // (name, business unit) — that is the identity the SDK itself uses.+ const errs = errorsFor((s) => {+ s.roleGrants = [+ { role: 'Viewer', businessUnitId: '11111111-1111-1111-1111-111111111111', privileges: [{ entity: 'contoso_order', access: ['read'] }] },+ { role: 'Viewer', businessUnitId: '22222222-2222-2222-2222-222222222222', privileges: [{ entity: 'contoso_order', access: ['read'] }] },+ ];+ });+ assert.deepStrictEqual(errs.filter((e) => /duplicate roleGrant/.test(e)), [], JSON.stringify(errs));+ // ...but the SAME business unit (or both defaulting to root) is still a duplicate.+ assert.ok(errorsFor((s) => {+ s.roleGrants = [+ { role: 'Viewer', privileges: [{ entity: 'contoso_order', access: ['read'] }] },+ { role: 'viewer', privileges: [{ entity: 'contoso_order', access: ['write'] }] },+ ];+ }).some((e) => /duplicate roleGrant/.test(e)));+});++test('#2d the persona overlap check is business-unit aware', async () => {+ // A persona in BU-1 and a grant on a same-named role in BU-2 are DIFFERENT roles; rejecting that+ // pair was over-strict for the same reason #2c was.+ const errs = errorsFor((s) => {+ s.personas = [{ persona: 'Viewer', businessUnitId: '11111111-1111-1111-1111-111111111111', jobs: [{ name: 'j', privileges: [{ entity: 'contoso_order', access: ['read'] }] }] }];+ s.roleGrants = [{ role: 'Viewer', businessUnitId: '22222222-2222-2222-2222-222222222222', privileges: [{ entity: 'contoso_order', access: ['read'] }] }];+ });+ assert.deepStrictEqual(errs.filter((e) => /is a persona in this spec/.test(e)), [], JSON.stringify(errs));+ // Same BU (both root) is still caught statically.+ assert.ok(errorsFor((s) => {+ s.personas = [{ persona: 'Viewer', jobs: [{ name: 'j', privileges: [{ entity: 'contoso_order', access: ['read'] }] }] }];+ s.roleGrants = [{ role: 'Viewer', privileges: [{ entity: 'contoso_order', access: ['read'] }] }];+ }).some((e) => /is a persona in this spec/.test(e)));+ // And an EXPLICIT matching BU on both sides is caught too — a bug the name-only key hid, because+ // it could not tell "same BU, explicitly written" from "different BU".+ assert.ok(errorsFor((s) => {+ s.personas = [{ persona: 'Viewer', businessUnitId: '11111111-1111-1111-1111-111111111111', jobs: [{ name: 'j', privileges: [{ entity: 'contoso_order', access: ['read'] }] }] }];+ s.roleGrants = [{ role: 'Viewer', businessUnitId: '11111111-1111-1111-1111-111111111111', privileges: [{ entity: 'contoso_order', access: ['read'] }] }];+ }).some((e) => /is a persona in this spec/.test(e)), 'an explicit same-BU overlap must still be rejected');+});++// --- Finding 3: provision-entities bypassed localized-label validation ----------------------------++const provisionBase = (entityExtra) => ({+ solution: { uniqueName: 'contoso', publisherPrefix: 'contoso' },+ entities: [{ schemaName: 'contoso_order', primaryAttribute: { schemaName: 'contoso_name' }, columns: [], ...entityExtra }],+ relationships: [],+});++test('#3 the provision-entities input rejects a language TAG, like the App Spec does', () => {+ // `provision-entities.js` is a SEPARATE entry point whose only gate is validateProvisionInput, and+ // it provisions the SOLUTION before the data model — so a label that fails only inside createTable+ // fails AFTER a write. Two entry points that disagree about what a label is teach two rules.+ const r = validateProvisionInput(provisionBase({ displayName: { 'es-ES': 'Pedido' } }));+ assert.strictEqual(r.ok, false, JSON.stringify(r.errors));+ assert.ok((r.errors || []).some((e) => /is not an LCID/.test(e)), JSON.stringify(r.errors));+});++test('#3b the provision-entities input enforces the localized-plural rule', () => {+ const r = validateProvisionInput(provisionBase({ displayName: { 1033: 'Order', 3082: 'Pedido' } }));+ assert.strictEqual(r.ok, false);+ assert.ok((r.errors || []).some((e) => /pluralName is required when displayName is a localized label/.test(e)), JSON.stringify(r.errors));+ // With the plural supplied it passes — the rule is about derivability, not about forbidding maps.+ assert.strictEqual(validateProvisionInput(provisionBase({ displayName: { 1033: 'Order', 3082: 'Pedido' }, pluralName: { 1033: 'Orders', 3082: 'Pedidos' } })).ok, true);+});++test('#3c a plain-string provision input is unaffected', () => {+ assert.strictEqual(validateProvisionInput(provisionBase({ displayName: 'Order' })).ok, true);+});++// --- Finding 4: localized Choice labels did not resolve in view filters ---------------------------++test('#4 a view filter naming a localized Choice option resolves to its option value', () => {+ // `options.indexOf(val)` returns -1 for an object option, so the LABEL was sent as the value of a+ // numeric picklist condition — an invalid or silently ineffective view filter.+ const s = base();+ s.entities[0].columns = [{ schemaName: 'contoso_status', type: 'Choice', options: [{ 1033: 'Open', 3082: 'Abierto' }, { 1033: 'Closed', 3082: 'Cerrado' }] }];+ s.views = [{ name: 'Open', entity: 'contoso_order', columns: ['contoso_name'], filters: [{ attr: 'contoso_status', op: 'eq', value: 'Abierto' }] }];+ const def = viewDef(s, s.views[0]);+ const json = JSON.stringify(def);+ assert.match(json, /100000000/, `the Spanish label did not resolve: ${json}`);+ assert.doesNotMatch(json, /"Abierto"/, 'the raw label must not reach a numeric picklist condition');+});++test('#4b a view filter on a GLOBAL choice resolves too', () => {+ // The inline-only lookup never resolved a column bound to a globalChoice at all.+ const s = base();+ s.globalChoices = [{ name: 'contoso_status', displayName: 'Status', options: ['Open', 'Closed'] }];+ s.entities[0].columns = [{ schemaName: 'contoso_status', type: 'Choice', globalChoice: 'contoso_status' }];+ s.views = [{ name: 'Closed', entity: 'contoso_order', columns: ['contoso_name'], filters: [{ attr: 'contoso_status', op: 'eq', value: 'Closed' }] }];+ assert.match(JSON.stringify(viewDef(s, s.views[0])), /100000001/);+});++// --- Finding 5: an ambiguous cross-language alias silently picked the wrong option ------------------++test('#5 a label string naming TWO options is rejected, not tie-broken', () => {+ // "Abierto" is option 0 in Spanish and option 1 in English. Any resolution rule is a coin flip, so+ // the SPEC is what must be fixed. Last-wins silently resolved it to the second option.+ const errs = errorsFor((s) => {+ s.entities[0].columns = [{ schemaName: 'contoso_status', type: 'Choice', options: [{ 1033: 'Open', 3082: 'Abierto' }, { 1033: 'Abierto', 3082: 'Cerrado' }] }];+ });+ const hit = errs.find((e) => /names BOTH options/.test(e));+ assert.ok(hit, JSON.stringify(errs));+ assert.match(hit, /'Abierto'/);+ assert.match(hit, /Rename one/);+});++test('#5b a duplicate PLAIN label warns rather than failing — it is visible, and Dataverse allows it', () => {+ // Deliberately NOT an error. A plain duplicate sits on the same line, so the author can already+ // see it, and specs written before this rule existed provisioned fine with one; failing them+ // would break working input to restate something obvious. The invisible cross-language case+ // above is the one that fails. Both are still DETECTED — only the severity differs.+ const spec = base();+ spec.globalChoices = [{ name: 'contoso_p', displayName: 'P', options: ['Open', 'Open'] }];+ const r = validateAppSpec(spec, { profile: 'plan' });+ assert.strictEqual((r.errors || []).some((e) => /names BOTH options/.test(e)), false,+ `a visible duplicate must not fail the spec: ${JSON.stringify(r.errors)}`);+ const w = (r.warnings || []).find((x) => /names BOTH options/.test(x));+ assert.ok(w, `but it must still be reported: ${JSON.stringify(r.warnings)}`);+ assert.match(w, /resolves to options\[0\]/, 'and the warning must state which one wins');+});++test('#5c the alias index is first-wins, so resolution is deterministic', () => {+ // Belt and braces: the validator rejects ambiguity, but a spec that bypassed validation must still+ // resolve predictably rather than to whichever option happened to be last.+ const entity = { schemaName: 'e', columns: [{ schemaName: 'c', type: 'Choice', options: [{ 1033: 'Open', 3082: 'Abierto' }, { 1033: 'Abierto', 3082: 'Cerrado' }] }] };+ assert.strictEqual(choiceValueMap(entity, {}).c.Abierto, 100000000);+});++// --- Finding 6: the not-round-tripped report failed open on an inventory read failure --------------++test('#6 a FAILED inventory read is reported as UNKNOWN, not as "the app has none"', () => {+ // The whole app-component block shared one broad catch, so a 403 on systemform produced+ // `forms: []` and `notRoundTripped: null` — an empty spec with nothing reporting why, which is+ // AB#6686423 reappearing inside its own fix.+ const s = notRoundTrippedSummary({ forms: [], views: [], charts: [], incomplete: [{ kind: 'forms', reason: 'HTTP 403' }] });+ assert.ok(s, 'a failed read must not summarise as null');+ assert.deepStrictEqual(s.incomplete, [{ kind: 'forms', reason: 'HTTP 403' }]);+ const w = notRoundTrippedWarning(s);+ assert.match(w, /could NOT be inventoried/);+ assert.match(w, /forms — HTTP 403/);+ assert.match(w, /UNKNOWN, not as "the app has none"/);+});++test('#6a readDescriptionInventory RECORDS a per-class read failure', async () => {+ // BEHAVIOURAL, through the real reader. The unit test above proves the summary reports an+ // `incomplete` entry; only this proves one is ever PRODUCED. It also pins the per-class catch: a+ // failing `systemform` query must not hide the views and charts that were read successfully.+ const { readDescriptionInventory } = require('../download-model-app.js');+ const APP = '11111111-1111-1111-1111-111111111111';+ const sdk = {+ queryRecords: async (logical, opts) => {+ const filter = (opts && opts.filter) || '';+ if (logical === 'appmodule') return [{ appmoduleidunique: APP }];+ if (logical === 'appmodulecomponent') {+ if (/componenttype eq 60/.test(filter)) throw new Error('HTTP 403 forbidden');+ if (/componenttype eq 26/.test(filter)) return [{ objectid: 'v-1', componenttype: 26 }];+ return [];+ }+ if (logical === 'savedquery') return [{ savedqueryid: 'v-1', name: 'Active Orders', returnedtypecode: 'contoso_order' }];+ return [];+ },+ dataverse: { get: async () => ({ status: 404, headers: {}, body: {} }) },+ };+ const inv = await readDescriptionInventory(sdk, APP, null);+ // `globalChoices` is now reported too: the stub answers that metadata read with a 404, and a+ // non-2xx is no longer coerced to an empty list. Before, it read as "this environment has no+ // global choices" — a positive claim made from a failed read.+ assert.deepStrictEqual((inv.incomplete || []).map((i) => i.kind).sort(), ['forms', 'globalChoices'], JSON.stringify(inv.incomplete));+ assert.match(inv.incomplete.find((i) => i.kind === 'forms').reason, /403/);+ // The class that DID read is still present — one failed query must not blank the others.+ assert.deepStrictEqual(inv.views.map((v) => v.name), ['Active Orders']);+ // ...and the summary built from it reports both halves.+ const w = notRoundTrippedWarning(notRoundTrippedSummary(inv));+ assert.match(w, /1 view on 1 table\(s\)/);+ assert.match(w, /forms — HTTP 403/);+});++test('#6a3 a non-2xx global-choice read is UNKNOWN, not "this environment has none"', async () => {+ // `sdk.dataverse.get` resolves a non-2xx as a VALUE, so the old `|| []` put the failure beyond the+ // catch's reach and the class simply vanished from the report. That mattered the moment+ // `notRoundTrippedSummary` started reporting global choices: a class it omits reads as absent.+ const { readDescriptionInventory } = require('../download-model-app.js');+ const base = { queryRecords: async () => [] };+ for (const [label, get] of [+ ['non-2xx', async () => ({ status: 403, headers: {}, body: {} })],+ ['malformed body', async () => ({ status: 200, headers: {}, body: { notValue: 1 } })],+ ['throws', async () => { throw new Error('socket hang up'); }],+ ]) {+ const inv = await readDescriptionInventory({ ...base, dataverse: { get } }, null, null);+ assert.ok((inv.incomplete || []).some((i) => i.kind === 'globalChoices'),+ `${label}: expected globalChoices to be recorded as unknown, got ${JSON.stringify(inv.incomplete)}`);+ }+ // And a GOOD read records nothing.+ const ok = await readDescriptionInventory({ ...base, dataverse: { get: async () => ({ status: 200, headers: {}, body: { value: [{ Name: 'contoso_status' }] } }) } }, null, null);+ assert.ok(!(ok.incomplete || []).some((i) => i.kind === 'globalChoices'));+ assert.deepStrictEqual((ok.globalChoices || []).map((g) => g.name), ['contoso_status']);+});++test('#6a4 a failed BUSINESS-RULE read is UNKNOWN, not "this app has no business rules"', async () => {+ // This path needs a solutionUniqueName, which the fixtures above pass as null — so the guard was+ // shipped untested until a mutation run showed removing it changed nothing. It matters for the+ // same reason as the others: `notRoundTrippedSummary` reports a class only when it has rows, so a+ // 403 on the solution/workflow read made the report assert the app HAS no business rules.+ const { readDescriptionInventory } = require('../download-model-app.js');+ const noop = { dataverse: { get: async () => ({ status: 200, headers: {}, body: { value: [] } }) } };++ const throwing = await readDescriptionInventory({+ ...noop,+ queryRecords: async (logical) => { if (logical === 'solution') throw new Error('HTTP 403 on solution'); return []; },+ }, null, 'contoso_sln');+ assert.ok((throwing.incomplete || []).some((i) => i.kind === 'businessRules' && /403/.test(i.reason)),+ `expected businessRules recorded as unknown, got ${JSON.stringify(throwing.incomplete)}`);++ // A SUCCESSFUL read that genuinely finds none records nothing — otherwise the warning would cry+ // wolf on every app without business rules.+ const clean = await readDescriptionInventory({+ ...noop,+ queryRecords: async (logical) => (logical === 'solution' ? [{ solutionid: 's1' }] : []),+ }, null, 'contoso_sln');+ assert.ok(!(clean.incomplete || []).some((i) => i.kind === 'businessRules'), JSON.stringify(clean.incomplete));+});++test('#6a5 a TRUNCATED component page marks the class incomplete, not undercounted', async () => {+ // `$top` is a hard cap and Dataverse omits `@odata.nextLink` when it is honoured, so a full page is+ // indistinguishable from a truncated one and there is no signal to read afterwards. This list feeds+ // `notRoundTrippedSummary`, which reports a COUNT — so a truncated read there is not merely a+ // missing artifact, it is a smaller number presented as the whole truth.+ //+ // Written after a mutation run showed the guard was shipped untested: disabling it changed no test.+ const { readDescriptionInventory } = require('../download-model-app.js');+ const APP = '11111111-1111-1111-1111-111111111111';+ const CAP = 1000; // COMPONENT_PAGE_CAP — module-private, so pinned here deliberately.+ const full = Array.from({ length: CAP }, (_, i) => ({ objectid: `v-${i}`, componenttype: 26 }));+ const sdk = (rows) => ({+ dataverse: { get: async () => ({ status: 200, headers: {}, body: { value: [] } }) },+ queryRecords: async (logical, opts) => {+ if (logical === 'appmodule') return [{ appmoduleidunique: APP }];+ // Only the VIEW class (componenttype 26) is saturated; the others return a short page.+ if (logical === 'appmodulecomponent') return /componenttype eq 26/.test((opts && opts.filter) || '') ? rows : [];+ if (logical === 'savedquery') return [];+ return [];+ },+ });++ const truncated = await readDescriptionInventory(sdk(full), APP, null);+ const v = (truncated.incomplete || []).find((i) => i.kind === 'views');+ assert.ok(v, `views must be marked incomplete at the cap, got ${JSON.stringify(truncated.incomplete)}`);+ assert.match(v.reason, /truncated/i, v.reason);+ // Scoped: the classes that read a SHORT page are not tarred with it.+ assert.ok(!(truncated.incomplete || []).some((i) => i.kind === 'charts'), JSON.stringify(truncated.incomplete));++ // One row under the cap is a complete read and must stay silent, or the warning cries wolf.+ const under = await readDescriptionInventory(sdk(full.slice(0, CAP - 1)), APP, null);+ assert.ok(!(under.incomplete || []).some((i) => i.kind === 'views'), JSON.stringify(under.incomplete));+});++test('#6a2 an unreadable app-component list marks EVERY class unknown', async () => {+ // If the parent lookup itself fails, nothing was enumerated — reporting "no forms, no views, no+ // charts" would be three lies at once.+ const { readDescriptionInventory } = require('../download-model-app.js');+ const sdk = {+ queryRecords: async () => { throw new Error('HTTP 500'); },+ dataverse: { get: async () => ({ status: 500, headers: {}, body: {} }) },+ };+ const inv = await readDescriptionInventory(sdk, '11111111-1111-1111-1111-111111111111', null);+ assert.deepStrictEqual((inv.incomplete || []).map((i) => i.kind).sort(), ['charts', 'forms', 'globalChoices', 'views']);+});++test('#6b a partial failure reports BOTH what was found and what is unknown', () => {+ const s = notRoundTrippedSummary({+ forms: [{ name: 'Main', entity: 'contoso_order' }], views: [], charts: [],+ incomplete: [{ kind: 'views', reason: 'HTTP 500' }],+ });+ const w = notRoundTrippedWarning(s);+ assert.match(w, /1 form on 1 table\(s\)/);+ assert.match(w, /views — HTTP 500/);+});++test('#6c a clean read with nothing to report still summarises as null', () => {+ assert.strictEqual(notRoundTrippedSummary({ forms: [], views: [], charts: [], incomplete: [] }), null);+});++// --- Finding 7: the download discarded the localized primary-attribute label -----------------------++test('#7 the primary attribute keeps its real (and localized) label', () => {+ // It is excluded from columns[], so its label was hardcoded to 'Name' — a fresh-environment+ // rebuild lost both the real label and its translations, contradicting "the round trip closes".+ const { entityFromMetadata } = require('../download-model-app.js');+ const dv = (pairs) => ({ LocalizedLabels: pairs.map(([LanguageCode, Label]) => ({ Label, LanguageCode })) });+ const e = entityFromMetadata({+ logicalName: 'contoso_order', schemaName: 'contoso_order', displayName: 'Order', primaryNameAttribute: 'contoso_title',+ attributes: [{ logicalName: 'contoso_title', schemaName: 'contoso_title', attributeType: 'String', isCustomAttribute: true, DisplayName: dv([[1033, 'Order Title'], [3082, 'Título del pedido']]) }],+ }, 'contoso_order');+ assert.deepStrictEqual(e.primaryAttribute.displayName, { 1033: 'Order Title', 3082: 'Título del pedido' });+ // The primary column must still be kept OUT of columns[] — it is declared separately.+ assert.deepStrictEqual(e.columns.map((c) => c.schemaName), []);+ // A single-language primary stays a plain string.+ const single = entityFromMetadata({+ logicalName: 'new_order', schemaName: 'new_order', displayName: 'Order', primaryNameAttribute: 'new_title',+ attributes: [{ logicalName: 'new_title', schemaName: 'new_title', attributeType: 'String', isCustomAttribute: true, DisplayName: dv([[1033, 'Order Title']]) }],+ }, 'new_order');+ assert.strictEqual(single.primaryAttribute.displayName, 'Order Title');+ // And an UNLABELLED primary still falls back to 'Name' rather than to undefined.+ const none = entityFromMetadata({ logicalName: 'new_order', schemaName: 'new_order', displayName: 'Order', primaryNameAttribute: 'new_title', attributes: [] }, 'new_order');+ assert.strictEqual(none.primaryAttribute.displayName, 'Name');+});++// --- Finding 8: a localized child label reached form change detection as [object Object] ------------++test('#8 a sub-grid title resolves a localized child label instead of stringifying it', () => {+ // subgridLabel fed the form intent, which the projection stringifies for change detection — so two+ // DIFFERENT localized labels both became "[object Object]" and hashed identically.+ const s = base();+ s.languageCode = 3082;+ s.entities.push({ schemaName: 'contoso_line', displayName: { 1033: 'Line', 3082: 'Línea' }, pluralName: { 1033: 'Lines', 3082: 'Líneas' }, primaryAttribute: { schemaName: 'contoso_name' }, columns: [] });+ assert.strictEqual(subgridLabel(s, { childEntity: 'contoso_line' }), 'Líneas');+ // Falls through to the singular when there is no plural, and to the logical name when neither.+ s.entities[1].pluralName = undefined;+ assert.strictEqual(subgridLabel(s, { childEntity: 'contoso_line' }), 'Línea');+ assert.strictEqual(subgridLabel(s, { childEntity: 'contoso_missing' }), 'contoso_missing');+ // An explicit label always wins.+ assert.strictEqual(subgridLabel(s, { childEntity: 'contoso_line', label: 'Mine' }), 'Mine');+});++// --- Finding 9: several derive sites ignored the spec's authoring language -------------------------++test('#9 the AI prompt, design doc and schema facts all resolve in the SPEC language', () => {+ const s = base();+ s.languageCode = 3082;+ s.entities[0].displayName = { 1033: 'Order', 3082: 'Pedido' };+ s.entities[0].pluralName = { 1033: 'Orders', 3082: 'Pedidos' };+ s.entities[0].primaryAttribute.displayName = { 1033: 'Name', 3082: 'Nombre' };+ s.entities[0].columns = [{ schemaName: 'contoso_note', type: 'Text', displayName: { 1033: 'Note', 3082: 'Nota' } }];++ const { buildPromptSpec } = require('../lib/ai-prompt.js');+ const p = buildPromptSpec(s.entities[0], { spec: s });+ assert.match(p.instruction, /Pedido/, `AI prompt used the wrong language: ${p.instruction}`);+ assert.deepStrictEqual(p.columns.map((c) => c.display), ['Nota']);++ const { schemaFacts } = require('../lib/schema-facts.js');+ const facts = schemaFacts(s);+ const t = (facts.tables || facts.entities || [])[0];+ assert.strictEqual(t.displayName, 'Pedido');+ assert.strictEqual(t.primary.displayName, 'Nombre');++ const { renderAppSpecDoc } = require('../lib/app-spec-doc.js');+ assert.match(renderAppSpecDoc(s), /Nota/);+});++test('#9b a localized Choice option renders in the design doc instead of an empty cell', () => {+ // The doc treated any object option as the legacy `{label}` shape, so a localized option — an+ // object with no `label` key — rendered as "choices: —, —".+ const { renderAppSpecDoc } = require('../lib/app-spec-doc.js');+ const s = base();+ s.entities[0].columns = [{ schemaName: 'contoso_status', type: 'Choice', options: [{ 1033: 'Open', 3082: 'Abierto' }, { 1033: 'Closed', 3082: 'Cerrado' }] }];+ const doc = renderAppSpecDoc(s);+ assert.match(doc, /choices: Open, Closed/, doc.split('\n').filter((l) => /choices/.test(l)).join(' | '));+});++test('#9c a localized lookup label reaches relationship facts as a STRING', () => {+ const { schemaFacts } = require('../lib/schema-facts.js');+ const s = base();+ s.entities.push({ schemaName: 'contoso_line', displayName: 'Line', primaryAttribute: { schemaName: 'contoso_name' }, columns: [] });+ s.relationships = [{ type: 'OneToMany', referenced: 'contoso_order', referencing: 'contoso_line', lookup: { schemaName: 'contoso_orderid', displayName: { 1033: 'Order', 3082: 'Pedido' } } }];+ const rels = schemaFacts(s).relationships || [];+ assert.strictEqual(typeof rels[0].lookup.displayName, 'string', JSON.stringify(rels[0]));+ assert.strictEqual(rels[0].lookup.displayName, 'Order');+ assert.strictEqual(JSON.stringify(schemaFacts(s)).includes('[object Object]'), false);+});++test('#9d a form wireframe renders localized field labels in the spec language', () => {+ const { renderFormWireframe } = require('../lib/form-preview.js');+ const s = base();+ s.languageCode = 3082;+ s.entities[0].primaryAttribute.displayName = { 1033: 'Name', 3082: 'Nombre' };+ s.entities[0].columns = [{ schemaName: 'contoso_note', type: 'Text', displayName: { 1033: 'Note', 3082: 'Nota' } }];+ s.forms = [{ entity: 'contoso_order', name: 'Main', formType: 'Main', tabs: [{ label: 'General', sections: [{ label: 'Details', fields: ['contoso_name', 'contoso_note'] }] }] }];+ const w = renderFormWireframe(s, s.forms[0]);+ assert.doesNotMatch(w, /\[object Object\]/);+ assert.match(w, /Nombre/);+ assert.match(w, /Nota/);+});+// --- Second review round: prototype keys, and the two label gates that still disagreed -----------++test('an option label of "__proto__" resolves to its own value, not Object.prototype', () => {+ // `choiceValueMap` is a dictionary keyed by an AUTHOR-CONTROLLED string. On a plain {} the READ+ // `byLabel['__proto__']` returns Object.prototype, which is `!== undefined` -- so the validator+ // accepted "__proto__" as a known label and `resolveSampleRecords` resolved it to Object.prototype,+ // which serializes into the Web API body as {}. A silently corrupted record that passed every gate.+ const entity = { schemaName: 'e', columns: [{ schemaName: 'c', type: 'Choice', options: ['__proto__', 'Open'] }] };+ const map = choiceValueMap(entity, {});+ assert.strictEqual(map.c.__proto__, 100000000, 'the label must own its slot');+ const out = resolveSampleRecords(entity, [{ c: '__proto__' }, { c: 'Open' }], {});+ assert.deepStrictEqual(out, [{ c: 100000000 }, { c: 100000001 }]);+});++test('an inherited Object.prototype key is not mistaken for a declared option', () => {+ // The same defect with a nastier value: `byLabel['constructor']` returned the Object FUNCTION, so+ // an undeclared "constructor" validated clean and resolved to a function.+ const s = base();+ s.entities[0].columns = [{ schemaName: 'contoso_status', type: 'Choice', displayName: 'S', options: ['Open', 'Closed'] }];+ s.sampleData = { contoso_order: [{ contoso_name: 'n', contoso_status: 'constructor' }] };+ const errs = validateAppSpec(s, { profile: 'plan' }).errors || [];+ assert.ok(errs.some((e) => /'constructor'.*is not a declared option label/.test(e)), JSON.stringify(errs));+ const out = resolveSampleRecords(s.entities[0], [{ contoso_status: 'toString' }], s);+ assert.strictEqual(typeof out[0].contoso_status, 'string', 'an inherited method must never become the value');+});++test('provision-input validates alternateKeys[].displayName, like the full validator', () => {+ // `provision-entities.js` is a SEPARATE entry point whose only gate is this function. The label+ // reaches `createAlternateKey` unchecked, where a language-tag key throws mid-provision -- AFTER+ // the solution and tables are written. Two gates that disagree teach one field two rules.+ const bad = {+ solution: { uniqueName: 'S', publisherPrefix: 'new' }, languageCode: 1033, relationships: [],+ entities: [{ schemaName: 'new_t', displayName: 'T', primaryAttribute: { schemaName: 'new_n' }, columns: [],+ alternateKeys: [{ schemaName: 'new_key', displayName: { 'es-ES': 'Clave' }, columns: ['new_n'] }] }],+ };+ const r = validateProvisionInput(bad);+ assert.strictEqual(r.ok, false, JSON.stringify(r));+ assert.ok(r.errors.some((e) => /alternateKeys\[0\] displayName.*not an LCID/.test(e)), JSON.stringify(r.errors));+ // Counterfactual: a CORRECT localized label must still pass, or the gate is just a blocker.+ bad.entities[0].alternateKeys[0].displayName = { 3082: 'Clave', 1033: 'Key' };+ assert.strictEqual(validateProvisionInput(bad).ok, true, JSON.stringify(validateProvisionInput(bad)));+});++test('a BLANK plain-string label is accepted — the runtime already treats it as absent', () => {+ // Not a loosening for its own sake. Every create site falls back with `x.displayName ||+ // x.schemaName`, so "" and undefined are indistinguishable by the time they reach Dataverse.+ // Rejecting "" while accepting undefined failed specs that build correctly, which is a worse+ // outcome than the typo it was catching. Both entry points must agree.+ const s = base();+ s.entities[0].columns = [{ schemaName: 'contoso_note', type: 'Text', displayName: '' }];+ s.globalChoices = [{ name: 'contoso_p', displayName: '', options: ['Open'] }];+ const errs = validateAppSpec(s, { profile: 'plan' }).errors || [];+ assert.strictEqual(errs.some((e) => /must not be blank/.test(e)), false, JSON.stringify(errs));++ const pi = validateProvisionInput({+ solution: { uniqueName: 'S', publisherPrefix: 'new' }, languageCode: 1033, relationships: [],+ entities: [{ schemaName: 'new_t', displayName: 'T', primaryAttribute: { schemaName: 'new_n' }, columns: [{ schemaName: 'new_c', type: 'Text', displayName: '' }] }],+ });+ assert.strictEqual(pi.ok, true, JSON.stringify(pi.errors));++ // A blank inside a LOCALIZED map is still rejected: a non-empty map is truthy, so the `||`+ // fallback never fires and the blank per-language label reaches the platform.+ const inMap = errorsFor((x) => {+ x.entities[0].columns = [{ schemaName: 'contoso_note', type: 'Text', displayName: { 1033: '', 3082: 'Nota' } }];+ });+ assert.ok(inMap.some((e) => /label for LCID 1033 must be a non-empty string/.test(e)), JSON.stringify(inMap));+});++test('provision-input validates relationships[].lookup.displayName too', () => {+ const bad = {+ solution: { uniqueName: 'S', publisherPrefix: 'new' }, languageCode: 1033,+ entities: [{ schemaName: 'new_t', displayName: 'T', primaryAttribute: { schemaName: 'new_n' }, columns: [] }],+ relationships: [{ type: 'OneToMany', referenced: 'new_t', referencing: 'new_t', lookup: { schemaName: 'new_p', displayName: { 'es-ES': 'Padre' } } }],+ };+ const r = validateProvisionInput(bad);+ assert.strictEqual(r.ok, false, JSON.stringify(r));+ assert.ok(r.errors.some((e) => /lookup\.displayName.*not an LCID/.test(e)), JSON.stringify(r.errors));+ bad.relationships[0].lookup.displayName = { 3082: 'Padre', 1033: 'Parent' };+ assert.strictEqual(validateProvisionInput(bad).ok, true, JSON.stringify(validateProvisionInput(bad)));+});++test('the dry-run plan never shows a table as an empty quoted label', () => {+ // `labelText` returns "" for an absent displayName, so the plan line read `table new_order ("")`+ // -- an empty string the reader has to decode. The CREATE falls back to the schema name+ // (`displayName || schemaName`), so the plan must say the same thing the build will do.+ const mk = (displayName) => {+ const s = base();+ if (displayName === undefined) delete s.entities[0].displayName;+ else s.entities[0].displayName = displayName;+ return s;+ };+ const tableLine = (s) => {+ const { planFor } = require('../lib/sdk-build.js');+ return (planFor(s, {}) || []).map((x) => x.label).find((l) => /^table /.test(l));+ };+ for (const absent of [undefined, '', { 9999: '' }]) {+ const line = tableLine(mk(absent));+ assert.doesNotMatch(line, /\(""\)/, `an unresolvable label must not render as an empty string: ${line}`);+ assert.match(line, /contoso_order/, line);+ }+ // A resolvable label is still shown, so the fallback did not swallow the real one.+ assert.match(tableLine(mk('Order')), /\("Order"\)/);+});diff --git a/plugins/model-apps/scripts/tests/role-grants.test.js b/plugins/model-apps/scripts/tests/role-grants.test.jsnew file mode 100644index 000000000..dd2c7dacf--- /dev/null+++ b/plugins/model-apps/scripts/tests/role-grants.test.js@@ -0,0 +1,475 @@+// `roleGrants[]` — extend a PRE-EXISTING security role with privileges for a table. AB#6686429.+//+// The reported failure: a table, its forms and its nav deployed into an app whose solution already+// shipped four data roles, and NONE of those roles received privileges on the new table. Every+// non-admin persona could be assigned the app and still not open the table, and nothing said so.+//+// These tests pin the three properties that make the fix safe rather than merely present:+// 1. it is ADDITIVE — it compiles to AddPrivilegesRole, never ReplacePrivilegesRole,+// 2. it FAILS CLOSED on any ambiguity about WHICH role it would grant on, and+// 3. it refuses the one authoring shape that silently self-destructs (extending a role the same+// spec also authors as a persona, whose privileges the build converges).+'use strict';+const test = require('node:test');+const assert = require('node:assert');+const { validateAppSpec } = require('../lib/app-spec.js');+const { planFor, runSdkBuild, roleGrantLabel, resolveRoleGrantTarget } = require('../lib/sdk-build.js');++function base() {+ return {+ schemaVersion: 2,+ solution: { uniqueName: 'contoso', publisherPrefix: 'contoso' },+ app: { name: 'Contoso' },+ entities: [{ schemaName: 'contoso_order', primaryAttribute: { schemaName: 'contoso_name' }, columns: [] }],+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'Main', subAreas: [] }] }] },+ };+}++const grant = (extra = {}) => ({ role: 'Contoso PM - Project Manager', privileges: [{ entity: 'contoso_order', access: ['read', 'write'], scope: 'organization' }], ...extra });++const errorsFor = (mutate, profile = 'plan') => {+ const s = base();+ mutate(s);+ return validateAppSpec(s, { profile }).errors || [];+};++// --- shape -------------------------------------------------------------------------------------++test('roleGrants: a well-formed grant validates on both profiles', () => {+ for (const profile of ['plan', 'deploy']) {+ const s = base();+ s.roleGrants = [grant()];+ const r = validateAppSpec(s, { profile });+ assert.strictEqual(r.ok, true, `${profile}: ${JSON.stringify(r.errors)}`);+ }+});++test('roleGrants: absent stays valid — the block is optional and additive', () => {+ assert.strictEqual(validateAppSpec(base(), { profile: 'deploy' }).ok, true);+});++test('roleGrants: must be an array', () => {+ const errs = errorsFor((s) => { s.roleGrants = { role: 'X' }; });+ assert.ok(errs.some((e) => /roleGrants must be an array/.test(e)), JSON.stringify(errs));+});++test('roleGrants: unknown keys are rejected, not silently dropped', () => {+ // The same silent-drop failure class as #537: a misspelled key that validates clean means the+ // author asked for something and got a green build with the request gone.+ const errs = errorsFor((s) => { s.roleGrants = [grant({ privilege: [] })]; });+ assert.ok(errs.some((e) => /unknown key 'privilege'/.test(e)), JSON.stringify(errs));+});++// --- identity: fail closed on WHICH role ---------------------------------------------------------++test('roleGrants: naming no role at all is rejected', () => {+ const errs = errorsFor((s) => { s.roleGrants = [{ privileges: [{ entity: 'contoso_order', access: ['read'] }] }]; });+ assert.ok(errs.some((e) => /name the existing role to extend/.test(e)), JSON.stringify(errs));+});++test('roleGrants: role and roleId together are rejected — they can disagree', () => {+ const errs = errorsFor((s) => { s.roleGrants = [grant({ roleId: '11111111-1111-1111-1111-111111111111' })]; });+ assert.ok(errs.some((e) => /not both/.test(e)), JSON.stringify(errs));+});++test('roleGrants: roleId must be a GUID', () => {+ const errs = errorsFor((s) => { s.roleGrants = [{ roleId: 'Project Manager', privileges: [{ entity: 'contoso_order', access: ['read'] }] }]; });+ assert.ok(errs.some((e) => /roleId must be a GUID/.test(e)), JSON.stringify(errs));+});++test('roleGrants: a blank role name is rejected rather than trimmed to nothing', () => {+ const errs = errorsFor((s) => { s.roleGrants = [grant({ role: ' ' })]; });+ assert.ok(errs.some((e) => /non-empty display name of an EXISTING security role/.test(e)), JSON.stringify(errs));+});++test('roleGrants: businessUnitId alongside roleId is rejected as dead configuration', () => {+ // It reads as if it constrains the lookup, but an id IS the identity — nothing would consult it.+ const errs = errorsFor((s) => {+ s.roleGrants = [{ roleId: '11111111-1111-1111-1111-111111111111', businessUnitId: '22222222-2222-2222-2222-222222222222', privileges: [{ entity: 'contoso_order', access: ['read'] }] }];+ });+ assert.ok(errs.some((e) => /businessUnitId only scopes a lookup by 'role' name/.test(e)), JSON.stringify(errs));+});++test('roleGrants: two grants on the same role are rejected — a split can hide a depth conflict', () => {+ // The SDK detects "these entities share one Dataverse privilege so they must request one depth"+ // only WITHIN a single call. Split across two entries, both writes succeed and the later wins.+ const errs = errorsFor((s) => { s.roleGrants = [grant(), grant({ privileges: [{ entity: 'contoso_order', access: ['delete'] }] })]; });+ assert.ok(errs.some((e) => /duplicate roleGrant for the same role/.test(e)), JSON.stringify(errs));+});++test('roleGrants: the duplicate check matches on the SDK role identity (trimmed, case-insensitive)', () => {+ const errs = errorsFor((s) => { s.roleGrants = [grant({ role: 'Project Manager' }), grant({ role: ' project manager ' })]; });+ assert.ok(errs.some((e) => /duplicate roleGrant for the same role/.test(e)), JSON.stringify(errs));+});++// --- the self-destructing shape ------------------------------------------------------------------++test('roleGrants: extending a role this SAME spec authors as a persona is rejected', () => {+ // `personas[]` converges its role with ReplacePrivilegesRole, so a grant on it is added, removed by+ // the next build's persona pass, and re-added — churn that reads as an intermittent access bug.+ const errs = errorsFor((s) => {+ s.personas = [{ persona: 'Dispatcher', jobs: [{ name: 'Dispatch', privileges: [{ entity: 'contoso_order', access: ['read'] }] }] }];+ s.roleGrants = [grant({ role: 'Dispatcher' })];+ });+ const hit = errs.find((e) => /is a persona in this spec/.test(e));+ assert.ok(hit, JSON.stringify(errs));+ // The error must name the alternative, or the author has nowhere to go.+ assert.match(hit, /declare these privileges on that persona's job instead/);+});++test('roleGrants: the persona overlap check uses the trimmed, case-folded role identity', () => {+ // " Dispatcher " and "dispatcher" are ONE role to the SDK, so they must be one role to this check —+ // otherwise the guard is trivially bypassed by whitespace and the convergence churn returns.+ const errs = errorsFor((s) => {+ s.personas = [{ persona: ' Dispatcher ', jobs: [{ name: 'Dispatch', privileges: [{ entity: 'contoso_order', access: ['read'] }] }] }];+ s.roleGrants = [grant({ role: 'dispatcher' })];+ });+ assert.ok(errs.some((e) => /is a persona in this spec/.test(e)), JSON.stringify(errs));+});++// --- privileges ----------------------------------------------------------------------------------++test('roleGrants: an empty privileges[] is rejected — the SDK rejects an empty grant too', () => {+ for (const privileges of [undefined, []]) {+ const errs = errorsFor((s) => { s.roleGrants = [grant({ privileges })]; });+ assert.ok(errs.some((e) => /privileges must be a non-empty array/.test(e)), `${JSON.stringify(privileges)}: ${JSON.stringify(errs)}`);+ }+});++test('roleGrants: access and scope tokens are validated against the Dataverse enums', () => {+ const bad = errorsFor((s) => { s.roleGrants = [grant({ privileges: [{ entity: 'contoso_order', access: ['reed'], scope: 'org' }] })]; });+ assert.ok(bad.some((e) => /unknown access 'reed'/.test(e)), JSON.stringify(bad));+ assert.ok(bad.some((e) => /unknown scope 'org'/.test(e)), JSON.stringify(bad));+});++test('roleGrants: every Dataverse access token the bug asked for is accepted', () => {+ // The reported matrix: Create, Read, Write, Delete, Append, AppendTo, Assign, Share at Organization.+ const s = base();+ s.roleGrants = [grant({ privileges: [{ entity: 'contoso_order', access: ['create', 'read', 'write', 'delete', 'append', 'appendTo', 'assign', 'share'], scope: 'organization' }] })];+ const r = validateAppSpec(s, { profile: 'deploy' });+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));+});++// --- plan ----------------------------------------------------------------------------------------++test('roleGrants: the plan names the role, so a dry run shows what would be granted', () => {+ const s = base();+ s.roleGrants = [grant()];+ const labels = planFor(s, {}).map((p) => p.label);+ assert.ok(labels.some((l) => /grant privileges on 1 table to existing role "Contoso PM - Project Manager"/.test(l)), labels.join(' | '));+});++test('roleGrantLabel falls back to the pinned id when there is no name', () => {+ assert.strictEqual(roleGrantLabel({ role: ' PM ' }), '"PM"');+ assert.strictEqual(roleGrantLabel({ roleId: 'abc' }), 'abc');+});++// --- resolution: fail closed ---------------------------------------------------------------------++const roleRow = (over = {}) => ({ roleid: '33333333-3333-3333-3333-333333333333', name: 'Contoso PM - Project Manager', ismanaged: false, ...over });++function fakeProvision(handlers) {+ return { queryRecords: async (entity, opts) => (handlers[entity] ? handlers[entity](opts) : []) };+}++test('resolveRoleGrantTarget: a name resolves within the root business unit', async () => {+ const seen = [];+ const p = fakeProvision({+ businessunit: () => [{ businessunitid: '44444444-4444-4444-4444-444444444444' }],+ role: (o) => { seen.push(o.filter); return [roleRow()]; },+ });+ const t = await resolveRoleGrantTarget(p, grant(), {});+ assert.strictEqual(t.roleId, '33333333-3333-3333-3333-333333333333');+ // The BU clause must be present, or a same-named role in another BU could be picked.+ assert.match(seen[0], /_businessunitid_value eq 44444444-4444-4444-4444-444444444444/);+});++test('resolveRoleGrantTarget: an unresolvable business unit FAILS rather than matching on name alone', async () => {+ // Teardown/verify fall back to a name-only match because a false negative there is only noisy.+ // Here a name-only match could grant privileges on a same-named role in a DIFFERENT business unit.+ const p = fakeProvision({ businessunit: () => [], role: () => [roleRow()] });+ await assert.rejects(() => resolveRoleGrantTarget(p, grant(), {}), /could not resolve the business unit/);+});++test('resolveRoleGrantTarget: no match and an ambiguous match are both errors', async () => {+ const bu = { businessunit: () => [{ businessunitid: '44444444-4444-4444-4444-444444444444' }] };+ await assert.rejects(+ () => resolveRoleGrantTarget(fakeProvision({ ...bu, role: () => [] }), grant(), {}),+ /no security role with that name exists/,+ );+ await assert.rejects(+ () => resolveRoleGrantTarget(fakeProvision({ ...bu, role: () => [roleRow(), roleRow({ roleid: '55555555-5555-5555-5555-555555555555' })] }), grant(), {}),+ /2 roles share that name/,+ );+});++test('resolveRoleGrantTarget: a stale pinned roleId is an error, never a create trigger', async () => {+ const p = fakeProvision({ role: () => [] });+ await assert.rejects(+ () => resolveRoleGrantTarget(p, { roleId: '11111111-1111-1111-1111-111111111111', privileges: [] }, {}),+ /does not exist on this environment/,+ );+});++test('resolveRoleGrantTarget: a MANAGED role resolves — extending a shipped role is the point', async () => {+ const p = fakeProvision({ role: () => [roleRow({ ismanaged: true })] });+ const t = await resolveRoleGrantTarget(p, { roleId: '33333333-3333-3333-3333-333333333333', privileges: [] }, {});+ assert.strictEqual(t.managed, true);+});++// --- apply: additive, and it halts rather than skipping ------------------------------------------++function buildSdk(over = {}) {+ const calls = { addEntityPrivilegesToRole: [], addSolutionComponent: [] };+ const sdk = {+ calls,+ queryRecords: async (entity) => {+ if (entity === 'businessunit') return [{ businessunitid: '44444444-4444-4444-4444-444444444444' }];+ if (entity === 'role') return [roleRow()];+ return [];+ },+ addEntityPrivilegesToRole: async (roleId, privileges) => {+ calls.addEntityPrivilegesToRole.push({ roleId, privileges });+ return [{ privilegeName: 'prvReadcontoso_order', scope: 'organization' }];+ },+ addSolutionComponent: async (o) => { calls.addSolutionComponent.push(o); },+ ...over,+ };+ return sdk;+}++async function applySecurity(spec, sdk) {+ return runSdkBuild(spec, { sdk, provisionSdk: sdk, apply: true, phases: ['security'] });+}++test('roleGrants: apply calls the ADDITIVE SDK surface, with the declared scope intact', async () => {+ const s = base();+ s.roleGrants = [grant()];+ const sdk = buildSdk();+ const r = await applySecurity(s, sdk);+ assert.strictEqual(r.ok, true, JSON.stringify(r));+ assert.strictEqual(sdk.calls.addEntityPrivilegesToRole.length, 1);+ const call = sdk.calls.addEntityPrivilegesToRole[0];+ assert.strictEqual(call.roleId, '33333333-3333-3333-3333-333333333333');+ // The scope must survive the trip: the SDK maps it to Depth, and a dropped scope would silently+ // grant at Basic (user-owned records only) instead of the Organization access the author declared.+ assert.deepStrictEqual(call.privileges, [{ entity: 'contoso_order', access: ['read', 'write'], scope: 'organization' }]);+ // Keyed by the resolved ROLE ID, not the display name — see the collision test below. The name is+ // carried in the value, so nothing readable is lost.+ const recorded = r.created.roleGrants['33333333-3333-3333-3333-333333333333'];+ assert.ok(recorded, JSON.stringify(r.created.roleGrants));+ assert.strictEqual(recorded.name, 'Contoso PM - Project Manager');+});++test('roleGrants: two roles sharing a display name are BOTH recorded, not collapsed', async () => {+ // The spec gate deliberately allows this: a role is identified by (name, business unit), so the+ // same name in two BUs is two different roles. Keying the result map on the display name silently+ // dropped the first grant from the emitted output — the apply did both, but `--json` reported one,+ // which is the reporting half of exactly the defect roleGrants[] exists to fix.+ const s = base();+ s.roleGrants = [+ { role: 'Shared', businessUnitId: '11111111-1111-1111-1111-111111111111', privileges: [{ entity: 'contoso_order', access: ['read'], scope: 'organization' }] },+ { role: 'Shared', businessUnitId: '22222222-2222-2222-2222-222222222222', privileges: [{ entity: 'contoso_order', access: ['write'], scope: 'organization' }] },+ ];+ assert.strictEqual(validateAppSpec(s, { profile: 'plan' }).ok, true, 'the gate allows same-name roles in different BUs');++ // Resolve each BU to its own role id, which is what makes them two distinct targets.+ const byBu = {+ '11111111-1111-1111-1111-111111111111': { roleid: 'aaaaaaaa-0000-0000-0000-000000000001', name: 'Shared' },+ '22222222-2222-2222-2222-222222222222': { roleid: 'bbbbbbbb-0000-0000-0000-000000000002', name: 'Shared' },+ };+ const sdk = buildSdk();+ sdk.queryRecords = async (set, o = {}) => {+ if (set === 'businessunit') return [{ businessunitid: '44444444-4444-4444-4444-444444444444' }];+ if (set === 'role') {+ const bu = Object.keys(byBu).find((id) => String(o.filter || '').includes(id));+ return bu ? [byBu[bu]] : [];+ }+ return [];+ };+ const r = await applySecurity(s, sdk);+ assert.strictEqual(r.ok, true, JSON.stringify(r).slice(0, 300));+ assert.strictEqual(sdk.calls.addEntityPrivilegesToRole.length, 2, 'both grants must be applied');+ assert.deepStrictEqual(+ Object.keys(r.created.roleGrants).sort(),+ ['aaaaaaaa-0000-0000-0000-000000000001', 'bbbbbbbb-0000-0000-0000-000000000002'],+ `both must be RECORDED, not collapsed onto one name: ${JSON.stringify(r.created.roleGrants)}`,+ );+});++test('roleGrants: a foreign role is NOT added to this app solution', async () => {+ // A persona role is ours to place. A pre-existing (possibly managed) role already lives wherever+ // its owner put it, and moving it would be an ownership decision the author never asked for.+ const s = base();+ s.roleGrants = [grant()];+ const sdk = buildSdk();+ await applySecurity(s, sdk);+ assert.strictEqual(sdk.calls.addSolutionComponent.filter((c) => c.componentType === 20).length, 0, JSON.stringify(sdk.calls.addSolutionComponent));+});++test('roleGrants: an unresolvable role HALTS the build instead of skipping', async () => {+ // Skipping would report a successful build whose users still cannot open the table — the exact+ // failure this feature was filed for. A BuildHalt THROWS out of runSdkBuild; asserting on a+ // returned `ok:false` would pass even if the grant had been quietly swallowed.+ const s = base();+ s.roleGrants = [grant()];+ const sdk = buildSdk({ queryRecords: async (entity) => (entity === 'businessunit' ? [{ businessunitid: '44444444-4444-4444-4444-444444444444' }] : []) });+ await assert.rejects(() => applySecurity(s, sdk), (err) => {+ assert.strictEqual(err.code, 'role-grant-unresolved');+ assert.match(err.message, /no security role with that name exists/);+ return true;+ });+ // Nothing was granted — a failed resolution must not reach the write.+ assert.strictEqual(sdk.calls.addEntityPrivilegesToRole.length, 0);+});++test('roleGrants: an SDK apply failure HALTS and surfaces the SDK message', async () => {+ // The live-metadata guards (a table that exposes no such access; two tables sharing one prv* at+ // different depths) can only fire here, so their message has to reach the author verbatim.+ const s = base();+ s.roleGrants = [grant()];+ const sdk = buildSdk({ addEntityPrivilegesToRole: async () => { throw new Error("Entity 'contoso_order' does not support 'share' access."); } });+ await assert.rejects(() => applySecurity(s, sdk), (err) => {+ assert.strictEqual(err.code, 'role-grant-failed');+ assert.match(err.message, /does not support 'share' access/);+ return true;+ });+});++// --- verify --------------------------------------------------------------------------------------+//+// Verification matters MORE here than for a persona role. A persona role is converged by+// ReplacePrivilegesRole, so proving the row exists proves its content. A grant is additive onto a role+// that already existed and still exists whether or not the privileges landed — so without a privilege+// read, a grant that silently failed verifies clean.++const { verifySpec } = require('../lib/verify-spec.js');++const ORDER_PRIVS = [+ { Name: 'prvReadcontoso_order', PrivilegeId: 'ord-read', PrivilegeType: 'Read' },+ { Name: 'prvWritecontoso_order', PrivilegeId: 'ord-write', PrivilegeType: 'Write' },+];++function verifyReader({ role, rolePrivileges, entityPrivileges } = {}) {+ const r = {+ findTable: async () => null,+ findColumns: async () => [],+ sitemapXml: async () => '',+ queryRecords: async (set) => {+ if (set === 'businessunit') return [{ businessunitid: '44444444-4444-4444-4444-444444444444' }];+ if (set === 'role') return role === undefined ? [{ roleid: 'role-1', name: 'Contoso PM - Project Manager' }] : role;+ return [];+ },+ };+ if (rolePrivileges) r.rolePrivileges = rolePrivileges;+ if (entityPrivileges) r.entityPrivileges = entityPrivileges;+ return r;+}++const verifiableSpec = () => ({ solution: { uniqueName: 'S' }, app: { name: 'A' }, entities: [], views: [], charts: [], forms: [], appShell: { areas: [] }, roleGrants: [grant()] });++test('verifySpec PASSES a roleGrant whose privileges the role actually holds', async () => {+ const r = await verifySpec(verifiableSpec(), verifyReader({+ rolePrivileges: async () => [{ privilegeId: 'ord-read', depth: 'Global' }, { privilegeId: 'ord-write', depth: 'Global' }],+ entityPrivileges: async () => ORDER_PRIVS,+ }));+ const c = r.checks.find((x) => x.kind === 'role-grant-privileges');+ assert.ok(c && c.present, JSON.stringify(c));+});++test('verifySpec FAILS a roleGrant whose privileges never landed', async () => {+ // THE regression this check exists for: the grant silently failed, the role still exists, and+ // without a privilege read the build reports success while users still cannot open the table.+ const r = await verifySpec(verifiableSpec(), verifyReader({+ rolePrivileges: async () => [{ privilegeId: 'ord-read', depth: 'Global' }],+ entityPrivileges: async () => ORDER_PRIVS,+ }));+ const c = r.checks.find((x) => x.kind === 'role-grant-privileges');+ assert.ok(c && !c.present, JSON.stringify(c));+ assert.match(c.detail, /contoso_order\.write/);+ assert.strictEqual(r.ok, false);+});++test('verifySpec: a grant held at too SHALLOW a depth fails', async () => {+ // Declared `organization` (Global). Basic would restrict the persona to their own records — a real+ // access defect that an existence-only check reports as fine.+ const r = await verifySpec(verifiableSpec(), verifyReader({+ rolePrivileges: async () => [{ privilegeId: 'ord-read', depth: 'Basic' }, { privilegeId: 'ord-write', depth: 'Global' }],+ entityPrivileges: async () => ORDER_PRIVS,+ }));+ const c = r.checks.find((x) => x.kind === 'role-grant-privileges');+ assert.ok(c && !c.present);+ assert.match(c.detail, /at Basic, below the declared Global/);+});++test('verifySpec: privileges the role holds beyond the grant are NOT a finding', async () => {+ // Subset semantics are load-bearing here: every OTHER privilege on a foreign role belongs to+ // somebody else, and reporting them would make the check unusable on exactly its target scenario.+ const r = await verifySpec(verifiableSpec(), verifyReader({+ rolePrivileges: async () => [+ { privilegeId: 'ord-read', depth: 'Global' }, { privilegeId: 'ord-write', depth: 'Global' },+ { privilegeId: 'somebody-elses-privilege', depth: 'Global' },+ ],+ entityPrivileges: async () => ORDER_PRIVS,+ }));+ const c = r.checks.find((x) => x.kind === 'role-grant-privileges');+ assert.ok(c && c.present, JSON.stringify(c));+});++test('verifySpec: a roleGrant does NOT imply appmodule read', async () => {+ // `declaredPrivileges` folds an appmodule read into a PERSONA (without it the role exists but the+ // app does not open). A grant declares exactly what it declares; implying app access here would+ // fail every grant on a role that legitimately has none.+ const r = await verifySpec(verifiableSpec(), verifyReader({+ rolePrivileges: async () => [{ privilegeId: 'ord-read', depth: 'Global' }, { privilegeId: 'ord-write', depth: 'Global' }],+ entityPrivileges: async (e) => { assert.notStrictEqual(e, 'appmodule', 'a roleGrant must not read appmodule privileges'); return ORDER_PRIVS; },+ }));+ assert.ok(r.checks.find((x) => x.kind === 'role-grant-privileges').present);+});++test('verifySpec: an ambiguous role name is NOT proof — the grant check fails', async () => {+ // Two same-named roles in one BU: we cannot know which one was granted on, so "found" would be a lie.+ const r = await verifySpec(verifiableSpec(), verifyReader({+ role: [{ roleid: 'role-1', name: 'X' }, { roleid: 'role-2', name: 'X' }],+ rolePrivileges: async () => [],+ entityPrivileges: async () => ORDER_PRIVS,+ }));+ const c = r.checks.find((x) => x.kind === 'role-grant');+ assert.ok(c && !c.present, JSON.stringify(c));+});++test('verifySpec fails CLOSED when a granted role\'s privileges cannot be read', async () => {+ const r = await verifySpec(verifiableSpec(), verifyReader({+ rolePrivileges: async () => { throw new Error('429 throttled'); },+ entityPrivileges: async () => ORDER_PRIVS,+ }));+ const c = r.checks.find((x) => x.kind === 'role-grant-privileges');+ assert.ok(c && !c.present);+ assert.match(c.detail, /could not read/);+});++test('verifySpec: an existence-only reader emits no roleGrant privilege check', async () => {+ // Reader-gated, exactly like the persona check — an old reader must behave as it did before.+ const r = await verifySpec(verifiableSpec(), verifyReader());+ assert.ok(r.checks.some((c) => c.kind === 'role-grant'), 'the existence check still runs');+ assert.ok(!r.checks.some((c) => c.kind === 'role-grant-privileges'));+});++// --- teardown ------------------------------------------------------------------------------------++test('teardown plans NOTHING for a roleGrant — a grant is one-way by design', async () => {+ // The bug asks for "safe teardown semantics that do not remove pre-existing grants". AddPrivilegesRole+ // does not record WHO added a privilege, so a revoke could not distinguish a privilege this spec+ // granted from one the role already held — and stripping the latter is the outcome being guarded+ // against. This test exists so that adding a revoke step later is a deliberate, visible decision.+ const { planTeardown } = require('../lib/sdk-teardown.js');+ const s = base();+ s.roleGrants = [grant()];+ const steps = planTeardown(s, { allowDestructive: true });+ const list = Array.isArray(steps) ? steps : (steps && steps.steps) || [];+ const touching = list.filter((st) => /roleGrant|grant/i.test(`${st.kind} ${st.label}`));+ assert.deepStrictEqual(touching, [], `teardown must not plan any roleGrant step: ${JSON.stringify(touching)}`);+ // And it must not have planned a role deletion for the foreign role either.+ const roleSteps = list.filter((st) => st.kind === 'role');+ assert.deepStrictEqual(roleSteps, [], `a roleGrant target is not ours to delete: ${JSON.stringify(roleSteps)}`);+});diff --git a/plugins/model-apps/scripts/tests/role-privileges.test.js b/plugins/model-apps/scripts/tests/role-privileges.test.jsindex 5bbdfacc7..93b39bfa7 100644--- a/plugins/model-apps/scripts/tests/role-privileges.test.js+++ b/plugins/model-apps/scripts/tests/role-privileges.test.js@@ -58,6 +58,29 @@ test('a role holding every declared privilege at the declared depth passes', ()assert.deepStrictEqual(r, { ok: true, missing: [] });});+// The structural version of the bug this catches. `appendTo` was keyed in ACCESS_TYPE with its+// camelCase App Spec spelling while the lookup lowercases, so it resolved to `undefined` and every+// declared appendTo privilege was reported as "the table exposes no such privilege" — a FALSE+// FAILURE on a correctly granted role, which is worse than no check at all.+//+// Driven from the validator's OWN allow-list rather than a hand-written list: any access token the+// App Spec starts accepting is covered automatically, so the next multi-word token cannot repeat+// this. A hand-listed test would have had to be remembered, and this one was not.+test('EVERY access token the App Spec accepts resolves through ACCESS_TYPE (casing included)', () => {+ const { ACCESS_LEVELS } = require('../lib/app-spec.js');+ const tokens = [...ACCESS_LEVELS];+ assert.ok(tokens.length >= 8, `expected the full access-level set, got ${tokens.length}`);+ // One table exposing one privilege per access token, with the PrivilegeType spelling Dataverse+ // returns — which is the capitalized token, i.e. exactly what ACCESS_TYPE must map to.+ const typeFor = (t) => t.charAt(0).toUpperCase() + t.slice(1);+ const privileges = new Map([['msdyn_workorder', tokens.map((t) => ({ Name: `prv${typeFor(t)}Workorder`, PrivilegeId: `wo-${t.toLowerCase()}`, PrivilegeType: typeFor(t) }))]]);+ const held = new Map(tokens.map((t) => [`wo-${t.toLowerCase()}`, 'Global']));+ const declared = tokens.map((t) => ({ entity: 'msdyn_workorder', access: t, scope: 'organization' }));+ const r = compareRolePrivileges(declared, privileges, held);+ assert.deepStrictEqual(r, { ok: true, missing: [] },+ `these tokens did not resolve: ${r.missing.map((m) => m.access).join(', ')}`);+});+// SUBSET semantics: a deeper grant satisfies a shallower declaration. Equality would false-fail on// the builder's own max-scope union and on shared Dataverse privileges.test('a DEEPER grant than declared still passes', () => {diff --git a/plugins/model-apps/scripts/tests/sdk-build.test.js b/plugins/model-apps/scripts/tests/sdk-build.test.jsindex 19bbd6ca8..e3376c09b 100644--- a/plugins/model-apps/scripts/tests/sdk-build.test.js+++ b/plugins/model-apps/scripts/tests/sdk-build.test.js@@ -2625,6 +2625,70 @@ test('ai-features phase: a result missing the newer buckets does not throw (oldeassert.strictEqual(events.filter((e) => e.phase === 'ai-features' && e.status === 'error').length, 0, 'no error events');});+// ── AB#6688904: `skipped` is now a RETRYABLE outcome, not a final one ─────────────────────────+// The SDK used to pre-empt a write when an org readiness gate read off, so `skipped` meant "never+// attempted" and no retry could change it — correctly excluded from the post-publish re-issue. Since+// AB#6688904 the write IS attempted and `skipped` means "attempted, absent, and a gate explains it".+// That matters because NO app-scope write persists before the app is published, so on a fresh app+// the gate diagnosis fires for every gate-bearing feature (`nlSearch`, `nlChart`,+// `formFillSmartPaste`) and abandoning them leaves `--verify` failing on override rows the build+// declined to write a second time.+//+// Driven through the mock rather than the real bundle deliberately: the bundle's own behaviour is+// pinned by ai-app-features-real-bundle.test.js, whereas what is under test here is the ENGINE's+// choice of which buckets to defer — which no bundle-level test can see.+const aiRetrySpec = () => makeSpec({ ai: { appFeatures: { nlSearch: true }, summaries: { default: 'off' } } });+const withAiResults = (results) => {+ const { sdk, calls } = mockSdk();+ let n = 0;+ sdk.setAppAiFeatures = async (appUnique, flags, opts) => {+ calls.push({ name: 'setAppAiFeatures', args: [appUnique, flags, opts] });+ return results[Math.min(n++, results.length - 1)];+ };+ return { sdk, calls };+};+const skippedResult = () => ({+ applied: [], skipped: ['nlSearch'], notPersisted: [], unverified: [], failed: [],+ outcomes: [{ feature: 'nlSearch', setting: 'NLGridSearchSetting', status: 'skipped', appOverrideExists: false, reason: "the org readiness gate 'EnableNLGridSearch' reads 'false'" }],+});++test('ai-features phase: a `skipped` feature is RE-ISSUED after publish and reported applied', async () => {+ const { sdk, calls } = withAiResults([+ skippedResult(),+ { applied: ['nlSearch'], skipped: [], notPersisted: [], unverified: [], failed: [], outcomes: [{ feature: 'nlSearch', status: 'applied' }] },+ ]);+ const events = [];+ const r = await runSdkBuild(aiRetrySpec(), { sdk, apply: true, phases: ['app-shell', 'ai-features'], emit: (e) => events.push(e) });++ assert.strictEqual(find(calls, 'setAppAiFeatures').length, 2, 'the gate-explained failure must be re-issued after publish');+ const af = r.created.ai.appFeatures;+ assert.ok(af.applied.includes('nlSearch'), `expected nlSearch applied, got ${JSON.stringify(af.applied)}`);+ assert.ok(!af.skipped.includes('nlSearch'),+ 'it must also be REMOVED from `skipped`, or created.ai.appFeatures contradicts itself for a --json consumer');+ const outcome = (af.outcomes || []).find((o) => o.feature === 'nlSearch');+ assert.strictEqual(outcome.status, 'applied');+ assert.strictEqual(outcome.appOverrideExists, true);+ assert.strictEqual(events.filter((e) => e.phase === 'ai-features' && e.status === 'skip').length, 0,+ 'a recovered feature must not also be reported as a problem');+});++test('ai-features phase: a `skipped` feature the re-issue cannot recover is reported as ADMIN GATE OFF', async () => {+ // The honest other half: when the gate really is blocking, the re-issue changes nothing and the+ // operator gets an actionable message rather than a silent success — and the SDK's own per-feature+ // reason (which names the gate and its value) is preferred over the canned bucket text.+ const { sdk, calls } = withAiResults([skippedResult()]);+ const events = [];+ const r = await runSdkBuild(aiRetrySpec(), { sdk, apply: true, phases: ['app-shell', 'ai-features'], emit: (e) => events.push(e) });++ assert.strictEqual(find(calls, 'setAppAiFeatures').length, 2, 'it is still re-issued — only the outcome differs');+ const warnings = events.filter((e) => e.phase === 'ai-features' && e.status === 'skip');+ assert.ok(warnings.some((e) => /ADMIN GATE OFF: nlSearch/.test(e.label)),+ `expected an ADMIN GATE OFF warning, got ${JSON.stringify(warnings.map((e) => e.label))}`);+ assert.ok(warnings.some((e) => /EnableNLGridSearch/.test(e.label)),+ 'the SDK reason names the gate, which is the actionable part');+ assert.ok(!r.created.ai.appFeatures.applied.includes('nlSearch'), 'and it is NOT claimed as applied');+});+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 thediff --git a/plugins/model-apps/scripts/tests/sdk-surface-contract.test.js b/plugins/model-apps/scripts/tests/sdk-surface-contract.test.jsindex 4ae28b6d4..b6105fd34 100644--- a/plugins/model-apps/scripts/tests/sdk-surface-contract.test.js+++ b/plugins/model-apps/scripts/tests/sdk-surface-contract.test.js@@ -33,6 +33,7 @@ const SCRIPTS_DIR = path.resolve(__dirname, '..');// this list is the living contract of what a re-vendored bundle MUST keep exposing.const SKILL_SDK_SURFACE = ['addElement',+ 'addEntityPrivilegesToRole','addSolutionComponent','associateRecords','configureRowSummary',@@ -66,6 +67,7 @@ const SKILL_SDK_SURFACE = ['getAiReadiness','getArtifact','getColumnVisualization',+ 'getEntityPrivileges','getSolution','initWorkspace','insertStatusValue',diff --git a/plugins/model-apps/scripts/tests/sdk-teardown.test.js b/plugins/model-apps/scripts/tests/sdk-teardown.test.jsindex f18a90e09..d8b548dbb 100644--- a/plugins/model-apps/scripts/tests/sdk-teardown.test.js+++ b/plugins/model-apps/scripts/tests/sdk-teardown.test.js@@ -1006,9 +1006,46 @@ test('teardown plans an ai-summaries step (before tables) for each candidate andassert.ok(removeCalls.some((c) => c.entityLogicalName === 'new_memo'), 'removeRowSummary called for the candidate table');});-test('planTeardown omits ai-summaries steps when spec.ai.summaries is absent', () => {+test('planTeardown omits ai-summaries steps when the spec has no `ai` block at all', () => {const steps = planTeardown(fullSpec()); // no spec.ai- assert.ok(!steps.some((s) => s.kind === 'aiSummary'), 'no aiSummary steps when spec has no ai.summaries');+ assert.ok(!steps.some((s) => s.kind === 'aiSummary'), 'no aiSummary steps when the spec opts out of ai entirely');+});++// The regression this section now guards, found by a LIVE teardown rather than by review.+//+// The build calls `selectSummaryTables` UNCONDITIONALLY whenever `spec.ai` exists, so a spec that+// carries only `ai.appFeatures` still gets a row summary per eligible table. Teardown used to plan+// its removal only `if (spec.ai && spec.ai.summaries)`, so for exactly that spec it planned nothing —+// and the orphaned `msdyn_aimodel` references the table, so Dataverse then REFUSED the table delete:+// ✗ table new_uptakeorder — HTTP 400 … referenced by 1 other components+// Teardown finished "with errors" having left the table and everything in it behind.+//+// Asserted as build/teardown SYMMETRY rather than as "an aiSummary step exists": the two must plan+// over the identical set, which is the property that was violated, and a one-off existence check+// would not catch the next divergence (`default: 'off'` plus a per-table opt-in, say).+test('teardown plans a row-summary removal for a spec with ai.appFeatures and NO summaries block', () => {+ const { selectSummaryTables } = require(path.join(__dirname, '..', 'lib', 'ai-candidates.js'));+ const spec = {+ solution: { uniqueName: 'AiTest', publisherPrefix: 'new' },+ app: { name: 'AiApp' },+ entities: [+ { schemaName: 'new_memo', displayName: 'Memo', primaryAttribute: { schemaName: 'new_name' }, columns: [{ schemaName: 'new_body', displayName: 'Body', type: 'Memo' }] },+ ],+ relationships: [],+ ai: { appFeatures: { formFill: true } }, // no `summaries` — the shape that regressed+ };++ const built = selectSummaryTables(spec).map((s) => String(s).toLowerCase());+ assert.deepStrictEqual(built, ['new_memo'], 'precondition: the BUILD would create a summary here');++ const plan = planTeardown(spec);+ const planned = plan.filter((s) => s.kind === 'aiSummary').map((s) => s.target.entityLogicalName);+ assert.deepStrictEqual(planned, built, 'teardown must plan exactly the set the build creates');++ const aiIdx = plan.findIndex((s) => s.kind === 'aiSummary');+ const tableIdx = plan.findIndex((s) => s.kind === 'table');+ assert.ok(tableIdx === -1 || aiIdx < tableIdx,+ 'the summary must be removed BEFORE the table, or Dataverse refuses the table delete');});test('planTeardown omits ai-summaries steps when default is off and no overrides', () => {diff --git a/plugins/model-apps/scripts/tests/second-app-bugs.test.js b/plugins/model-apps/scripts/tests/second-app-bugs.test.jsnew file mode 100644index 000000000..94b850053--- /dev/null+++ b/plugins/model-apps/scripts/tests/second-app-bugs.test.js@@ -0,0 +1,298 @@+// Second-app bug batch (AB#6689110, AB#6688905, AB#6688906) — the three halves that belong to THIS+// plugin. The root causes of 6688904, and of 6688905/6688906's deployed symptoms, live in the+// vendored SDK and are reported separately; what is covered here is what the plugin itself owns.+//+// Written against the reporters' actual inputs rather than a paraphrase: an `ai.summaries` block with+// `default: "off"` plus one explicitly-enabled table, an SVG placed in the legacy `icon` slot, and a+// workspace `.meta.json` that is not readable at the moment the event-wiring step runs.++const test = require('node:test');+const assert = require('node:assert');++const { validateAppSpec } = require('../lib/app-spec.js');+const { verifySpec } = require('../lib/verify-spec.js');++// --- AB#6689110: a requested row summary must not verify clean when it does not exist ------------++const summarySpec = () => ({+ solution: { uniqueName: 'S' },+ app: { name: 'A' },+ entities: [{ schemaName: 'contoso_workitem', displayName: 'Work Item', primaryAttribute: { schemaName: 'contoso_title' }, columns: [] }],+ views: [], charts: [], forms: [], appShell: { areas: [] },+ // The reporter's exact shape: default OFF, one table explicitly opted back in.+ ai: { summaries: { default: 'off', tables: { contoso_workitem: { enabled: true, instruction: 'Summarize execution status.', columns: ['contoso_title'] } } } },+});++const summaryReader = ({ rows = [], throws = false } = {}) => ({+ findTable: async () => ({ logicalName: 'contoso_workitem', entitySetName: 'contoso_workitems' }),+ findColumns: async () => [{ logicalName: 'contoso_title' }],+ sitemapXml: async () => '<SiteMap/>',+ queryRecords: async (set) => {+ if (set !== 'msdyn_aimodel') return [];+ if (throws) throw new Error('HTTP 403 from msdyn_aimodels');+ return rows;+ },+});++test('AB#6689110: a requested row summary that does not exist FAILS verification', async () => {+ // The reported symptom: `PASS, 45/45` with the requested Work Item summary absent. Verification+ // covered `ai.appFeatures` but had no check for `ai.summaries` at all, so the one artifact the+ // maker asked for was the one thing nothing looked at.+ const r = await verifySpec(summarySpec(), summaryReader({ rows: [] }));+ const c = r.checks.find((x) => x.kind === 'ai-summary');+ assert.ok(c, `an ai-summary check must exist: ${JSON.stringify(r.checks.map((x) => x.kind))}`);+ assert.strictEqual(c.present, false);+ assert.strictEqual(r.ok, false, 'and it must fail the whole verification, not just annotate it');+ assert.match(c.detail, /contoso_workitem row summary/, c.detail);+ assert.match(c.detail, /licens/i, 'the message must name the usual cause so the operator can act');+});++test('AB#6689110: a row summary that DOES exist AND is active passes', async () => {+ // The counterfactual. Without it the check could pass the test above by failing unconditionally,+ // which would make every licensed environment fail verification instead.+ const r = await verifySpec(summarySpec(), summaryReader({ rows: [{ msdyn_aimodelid: 'm1', msdyn_name: 'contoso_workitem row summary', statecode: 1 }] }));+ const c = r.checks.find((x) => x.kind === 'ai-summary');+ assert.strictEqual(c.present, true, JSON.stringify(c));+ assert.strictEqual(r.ok, true, JSON.stringify(r.checks.filter((x) => !x.present)));+});++test('AB#6689110: an INACTIVE row-summary model FAILS — existence alone is not enough', async () => {+ // A reachable false PASS, not a theoretical one. On an environment that does not license the+ // row-summary capability the SDK CREATES the `msdyn_aimodel` row and only then fails to publish+ // it, leaving a committed but unusable row behind — the same orphan the build's own sweep tries to+ // remove and deliberately leaves when it cannot. Matching on the name alone reported PASS for a+ // summary nobody can use.+ //+ // `statecode` 0 = Inactive / 1 = Active is MEASURED from the environment's own+ // `msdyn_aimodel` statecode option set, not assumed.+ const r = await verifySpec(summarySpec(), summaryReader({ rows: [{ msdyn_aimodelid: 'm1', msdyn_name: 'contoso_workitem row summary', statecode: 0 }] }));+ const c = r.checks.find((x) => x.kind === 'ai-summary');+ assert.strictEqual(c.present, false, JSON.stringify(c));+ assert.match(c.detail, /INACTIVE/, c.detail);+ assert.match(c.detail, /statecode 0/, 'the observed state must reach the operator');+ assert.strictEqual(r.ok, false);+});++test('AB#6689110: a row with NO statecode is not assumed active', async () => {+ // Fail closed on a reader that did not supply the column, rather than treating an unknown state as+ // a working summary.+ const r = await verifySpec(summarySpec(), summaryReader({ rows: [{ msdyn_aimodelid: 'm1', msdyn_name: 'contoso_workitem row summary' }] }));+ assert.strictEqual(r.checks.find((x) => x.kind === 'ai-summary').present, false);+});++test('AB#6689110: an unreadable AI model list fails CLOSED, it does not pass', async () => {+ // "Could not look" is not "it is there". Reporting PASS on a read that failed is the same false+ // confidence this check was added to remove.+ const r = await verifySpec(summarySpec(), summaryReader({ throws: true }));+ const c = r.checks.find((x) => x.kind === 'ai-summary');+ assert.strictEqual(c.present, false);+ assert.match(c.detail, /could not read/i, c.detail);+ assert.match(c.detail, /403/, 'the underlying cause must survive into the message');+});++test('AB#6689110: verification uses the SAME table selector as the build', async () => {+ // `default: "off"` with NO per-table opt-in requests nothing, so nothing must be checked —+ // otherwise every spec that merely mentions `ai` fails. The selector is shared with the build+ // (`selectSummaryTables`) precisely so the set verified is the set built; duplicating the+ // default-vs-override rule here is how a verifier starts proving something else.+ const s = summarySpec();+ s.ai.summaries.tables.contoso_workitem.enabled = false;+ const r = await verifySpec(s, summaryReader({ rows: [] }));+ assert.strictEqual(r.checks.some((x) => x.kind === 'ai-summary'), false,+ 'a table nobody asked for must not be verified');+ assert.strictEqual(r.ok, true);+});++// The gap that test did NOT close, found by review after the fact. It pins that a spec which asks+// for nothing is checked for nothing — but only within a spec that HAS an `ai` block. A spec with no+// `ai` block at all took a different path: `selectSummaryTables` was called ungated, and with no+// `summaries` key it reads `{}` as "default auto" and returns every entity carrying a descriptive+// column. Verify then FAILED, claiming "ai.summaries requests a row summary for 'x'" for a summary+// nobody requested and the build never created.+//+// That is a false failure on `--verify`'s exit code, and it hits the common case rather than an edge+// one: almost every table has a text column, and most specs never mention AI. `columns: []` in+// `summarySpec` is exactly why the existing coverage missed it — an entity with no columns is never+// an auto-candidate, so the only table it ever exercised was the explicit opt-in.+test('AB#6689110 follow-up: a spec with NO `ai` block is not checked for row summaries at all', async () => {+ const s = summarySpec();+ delete s.ai;+ // A descriptive column is what makes the entity an auto-candidate — without one this test would+ // pass against the broken code too, which is the trap the original fixture fell into.+ s.entities[0].columns = [{ schemaName: 'contoso_notes', displayName: 'Notes', type: 'Memo' }];+ const { selectSummaryTables } = require('../lib/ai-candidates.js');+ assert.deepStrictEqual(selectSummaryTables(s), ['contoso_workitem'],+ 'precondition: the candidate selector DOES return this table — the gate is the only thing stopping it');++ const r = await verifySpec(s, { ...summaryReader({ rows: [] }), findColumns: async () => [{ logicalName: 'contoso_notes' }] });+ assert.strictEqual(r.checks.some((x) => x.kind === 'ai-summary'), false,+ `a spec that never mentions ai must not be verified for row summaries: ${JSON.stringify(r.checks.filter((x) => x.kind === 'ai-summary'))}`);+ assert.strictEqual(r.ok, true, 'and it must not fail verification');+});++test('AB#6689110 follow-up: build, verify and teardown share ONE ai opt-in predicate', async () => {+ // The instance above was the second time a caller treated `selectSummaryTables` as an opt-in test+ // rather than a candidate selector (teardown gated on `spec.ai.summaries` and planned no removal+ // for an `appFeatures`-only spec, stranding a row summary that then blocked the table delete).+ // Pin the predicate itself so the next caller cannot invent a third spelling.+ const { specOptsIntoAi } = require('../lib/ai-app-settings.js');+ assert.strictEqual(specOptsIntoAi({ ai: { appFeatures: { formFill: true } } }), true);+ assert.strictEqual(specOptsIntoAi({ ai: {} }), true, 'an empty ai block is still an opt-in');+ assert.strictEqual(specOptsIntoAi({}), false);+ assert.strictEqual(specOptsIntoAi({ ai: null }), false, 'null is what a JSON caller writes for "no AI"');+ assert.strictEqual(specOptsIntoAi(undefined), false);++ // And that teardown agrees with the build for the shape that regressed: `appFeatures` only.+ const { planTeardown } = require('../lib/sdk-teardown.js');+ const spec = {+ solution: { uniqueName: 'S', publisherPrefix: 'new' },+ app: { name: 'A' },+ entities: [{ schemaName: 'new_memo', primaryAttribute: { schemaName: 'new_name' }, columns: [{ schemaName: 'new_body', type: 'Memo' }] }],+ relationships: [],+ ai: { appFeatures: { formFill: true } },+ };+ assert.deepStrictEqual(+ planTeardown(spec).filter((s) => s.kind === 'aiSummary').map((s) => s.target.entityLogicalName),+ selectSummaryTablesFor(spec),+ 'teardown must plan exactly the set the build creates');+ // …and plans nothing when the spec opts out entirely.+ assert.deepStrictEqual(planTeardown({ ...spec, ai: undefined }).filter((s) => s.kind === 'aiSummary'), []);+});+const selectSummaryTablesFor = (s) => require('../lib/ai-candidates.js').selectSummaryTables(s).map((x) => String(x).toLowerCase());++// --- AB#6688906: an SVG in the legacy raster `icon` slot -----------------------------------------++const iconSpec = (subArea) => ({+ solution: { uniqueName: 'S', publisherPrefix: 'contoso' },+ app: { name: 'A' },+ entities: [{ schemaName: 'contoso_t', displayName: 'T', primaryAttribute: { schemaName: 'contoso_n' }, columns: [] }],+ webResources: [{ name: 'contoso_myactivework.svg', type: 'svg', content: '<svg/>' }],+ views: [], charts: [], forms: [],+ appShell: { areas: [{ label: 'A', groups: [{ label: 'G', subAreas: [subArea] }] }] },+});+const iconWarnings = (spec) => (validateAppSpec(spec, { profile: 'plan' }).warnings || []).filter((w) => /legacy RASTER slot/.test(w));++test('AB#6688906: an SVG in the legacy `icon` slot is flagged, naming the vectorIcon fix', () => {+ // Step 2 of the report: the author writes the SVG into `icon`, Dataverse accepts it, and the nav+ // renders a placeholder. Everything after that in the report — the switch to `vectorIcon`, the+ // stale `Icon` left behind — follows from this first wrong turn, which is the only half the+ // plugin can prevent.+ const w = iconWarnings(iconSpec({ url: 'https://contoso.example/x', title: 'My Active Work Items', icon: 'contoso_myactivework.svg' }));+ assert.strictEqual(w.length, 1, JSON.stringify(w));+ assert.match(w[0], /vectorIcon: "\$webresource:contoso_myactivework\.svg"/, 'it must name the exact replacement');+});++test('AB#6688906: the CORRECTED spec is silent', () => {+ // Step 4. A rule that still complains after the author has fixed it teaches them to ignore it.+ assert.deepStrictEqual(+ iconWarnings(iconSpec({ url: 'https://contoso.example/x', title: 'My Active Work Items', vectorIcon: '$webresource:contoso_myactivework.svg' })),+ [],+ );+});++test('AB#6688906: a raster icon beside a vector one stays legal', () => {+ // Deliberately NOT rejected. `Icon` + `VectorIcon` together is a legitimate legacy-fallback pair —+ // the shipped smoke spec uses exactly that shape, and an earlier draft of this rule broke it.+ assert.deepStrictEqual(+ iconWarnings(iconSpec({ url: 'https://contoso.example/x', title: 'T', icon: 'contoso_icon.png', vectorIcon: '/WebResources/contoso_v.svg' })),+ [],+ );+});++test('AB#6688906: a platform icon PATH ending .svg is not flagged', () => {+ // An OOB/WebResources path is resolved by the platform and is valid in the legacy slot; flagging+ // it would fire on every downloaded app that round-trips one.+ assert.deepStrictEqual(+ iconWarnings(iconSpec({ url: 'https://contoso.example/x', title: 'T', icon: '/WebResources/contoso_myactivework.svg' })),+ [],+ );+});++// --- AB#6688905: the workspace-metadata race must retry, not halt UNKNOWN ------------------------++const { runSdkBuild } = require('../lib/sdk-build.js');+const { makeSimpleMockSdk } = require('./helpers/mock-sdk.js');++const eventSpec = () => ({+ solution: { uniqueName: 'S', displayName: 'S', publisherPrefix: 'new' },+ app: { name: 'A', description: 'd' },+ entities: [{ schemaName: 'new_ticket', displayName: 'Ticket', pluralName: 'Tickets',+ primaryAttribute: { schemaName: 'new_subject', displayName: 'Subject' }, columns: [] }],+ webResources: [{ name: 'new_lib.js', type: 'js', content: 'function f(){}' }],+ forms: [{ entity: 'new_ticket', name: 'Main', formType: 'Main',+ events: [{ event: 'onload', library: 'new_lib.js', function: 'f' }] }],+ views: [], charts: [],+ appShell: { areas: [{ label: 'M', groups: [{ label: 'R', subAreas: [{ entity: 'new_ticket', title: 'Tickets' }] }] }] },+});++// The exact error Node raises for the observed race: a Windows sharing/partial-write violation on+// the workspace metadata sibling, reported as UNKNOWN rather than ENOENT.+const raceError = (id) => new Error(+ String.raw`UNKNOWN: unknown error, open 'C:\\w\\.maker-workspace\\.metadata\\forms\\` + id + String.raw`.meta.json'`);++async function buildWithFlakyFetch(failures) {+ const { sdk } = makeSimpleMockSdk();+ const provision = Object.create(sdk);+ provision.queryRecords = async (entity) => {+ if (entity === 'solution' || entity === 'systemform') return [];+ return [{ publisherid: 'pub-1' }];+ };+ let attempts = 0;+ provision.fetchArtifact = async (type, id) => {+ if (type === 'form') {+ attempts += 1;+ if (attempts <= failures) throw raceError(id);+ }+ return sdk.fetchArtifact(type, id);+ };+ const res = await runSdkBuild(eventSpec(), {+ sdk, provisionSdk: provision, apply: true, phases: ['forms'],+ emit: () => undefined, warn: () => undefined,+ });+ return { res, attempts };+}++test('AB#6688905: a transient workspace-metadata failure is RETRIED, not halted', async () => {+ // The reporter's second identical run succeeded, which is the proof the state is transient: the+ // form ROW was already created and only the local workspace sibling had not landed. Halting a+ // multi-form build on that -- with a bare `UNKNOWN` the operator can do nothing with -- costs the+ // whole app-shell, AI and publish phases for a file flush that finishes microseconds later.+ const { res, attempts } = await buildWithFlakyFetch(2);+ assert.strictEqual(res.ok, true, JSON.stringify(res).slice(0, 400));+ assert.ok(attempts >= 3, `it must actually have retried; attempts=${attempts}`);+});++test('AB#6688905: a PERSISTENT metadata failure still fails, naming the race', async () => {+ // The retry must be bounded. A form whose metadata never lands is a real failure -- but the+ // message has to say it is a LOCAL workspace race and that a re-run fixes it, rather than the+ // bare `UNKNOWN: unknown error, open ...` the report quoted.+ await assert.rejects(+ () => buildWithFlakyFetch(Number.MAX_SAFE_INTEGER),+ (err) => {+ const m = String(err && err.message);+ assert.match(m, /workspace metadata/i, m);+ assert.match(m, /not a Dataverse failure/i, 'it must not send the operator to the server');+ assert.match(m, /idempotent/i, 'and must name the remedy: re-run');+ return true;+ });+});++test('AB#6688905: an UNRELATED fetch failure is NOT retried or reworded', async () => {+ // Narrow on purpose. Retrying a genuine Dataverse error would turn one clear failure into four+ // slow ones, and rewording it would hide the real cause.+ const { sdk } = makeSimpleMockSdk();+ const provision = Object.create(sdk);+ provision.queryRecords = async (entity) => {+ if (entity === 'solution' || entity === 'systemform') return [];+ return [{ publisherid: 'pub-1' }];+ };+ let attempts = 0;+ provision.fetchArtifact = async (type) => {+ if (type === 'form') { attempts += 1; throw new Error('HTTP 403 from systemforms: principal lacks prvReadSystemForm'); }+ return undefined;+ };+ await assert.rejects(+ () => runSdkBuild(eventSpec(), { sdk, provisionSdk: provision, apply: true, phases: ['forms'], emit: () => undefined, warn: () => undefined }),+ (err) => { assert.match(String(err.message), /403/, String(err.message)); return true; });+ assert.strictEqual(attempts, 1, 'a non-race error must be surfaced on the FIRST attempt');+});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.jsnew file mode 100644index 000000000..6eebf3903--- /dev/null+++ b/plugins/model-apps/scripts/tests/sitemap-icon-real-bundle.test.js@@ -0,0 +1,152 @@+'use strict';+// REAL-BUNDLE contract tests for sitemap chrome removal (AB#6688906).+//+// The report was "sitemap reconciliation retains obsolete Icon when switching to VectorIcon". The SDK+// 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.+//+// IN-PLACE MUTATE (what the SDK's own reproduction does, and what any future in-place reconcile would)+// 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).+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 APP_ID = '11111111-1111-1111-1111-111111111111';+const APP_UNIQUE = 'new_probeapp';+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';++// A DEPLOYED sitemap carrying the legacy raster `Icon` plus chrome the plugin never emits+// (`Contoso.*` resource ids). The chrome is what makes "was the bag carried forward?" observable+// independently of the icon, so a test cannot pass for the wrong reason.+const DEPLOYED_SITEMAP_XML =+ '<SiteMap IntroducedVersion="7.0.0.0">'+ + '<Area Id="Area1" Icon="/WebResources/contoso_area.png" ShowGroups="true" ResourceId="Contoso.AreaRes">'+ + '<Titles><Title LCID="1033" Title="Main" /></Titles>'+ + '<Group Id="Group1" ResourceId="Contoso.GroupRes"><Titles><Title LCID="1033" Title="Main" /></Titles>'+ + '<SubArea Id="Sub1" Entity="new_torder" Icon="contoso_legacy.png" ResourceId="Contoso.SubRes" ToolTipResourseId="Contoso.Tip" Client="All" Sku="All">'+ + '<Titles><Title LCID="1033" Title="Orders" /></Titles>'+ + '</SubArea></Group></Area></SiteMap>';++const VECTOR_REF = '$webresource:contoso_vec.svg';++const tempDirs = [];+test.after(() => { for (const d of tempDirs) fs.rmSync(d, { recursive: true, force: true }); });++/** A real SDK over a fake Dataverse holding {@link DEPLOYED_SITEMAP_XML}. */+function freshSdk() {+ const { createMakerSdk } = require(BUNDLE);+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sitemap-icon-'));+ tempDirs.push(dir);+ const posted = [];+ const appRow = () => ({ appmoduleid: APP_ID, appmoduleidunique: APP_IDUNIQUE, name: 'Probe', uniquename: APP_UNIQUE, description: '' });+ const sitemapRow = () => ({ sitemapid: SITEMAP_ID, sitemapnameunique: APP_UNIQUE, sitemapxml: DEPLOYED_SITEMAP_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)) {+ // componenttype 62 is the SITEMAP component; 1 is a table. The filter arrives URL-encoded+ // (`componenttype%20eq%2062`), so accept either spacing.+ 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 }] } };+ }+ // A collection read (`/sitemaps?$filter=…` or the RetrieveUnpublishedMultiple function) answers+ // with `{ value: [...] }`; a by-id read answers with the row itself.+ 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) posted.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) posted.push(String(body.sitemapxml));+ return { status: 204, headers: {}, body: {} };+ },+ delete: async () => ({ status: 204, headers: {}, body: {} }),+ put: async () => ({ status: 204, headers: {}, body: {} }),+ };+ const sdk = createMakerSdk({ workspacePath: dir, instanceUrl: 'https://example.crm.dynamics.com', httpClient });+ sdk.initWorkspace();+ return { sdk, lastSitemapXml: () => posted[posted.length - 1] || '' };+}++/** 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 () => {+ const { sdk, lastSitemapXml } = 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 }] }] }],+ });+ 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');+});++test('REAL BUNDLE: an IN-PLACE reconcile drops a removed Icon while keeping the rest of the bag', async () => {+ // The shape that actually regressed. Before the fix this serialized BOTH `Icon="contoso_legacy.png"`+ // and the new `VectorIcon`, and the deployed app went on rendering the stale raster — MEASURED+ // against the pre-uptake bundle, which fails this test.+ const { sdk, lastSitemapXml } = freshSdk();+ const art = await sdk.fetchArtifact('app', APP_ID);+ const sub = art.siteMap.areas[0].groups[0].subAreas[0];+ delete sub.icon;+ sub.vectorIcon = VECTOR_REF;++ await sdk.updateElement('app', APP_ID, '/siteMap', art.siteMap);+ await sdk.pushArtifact('app', APP_ID);++ const tag = subAreaTag(lastSitemapXml());+ assert.match(tag, /VectorIcon="\$webresource:contoso_vec\.svg"/);+ assert.doesNotMatch(tag, /\sIcon="/, 'the dropped icon must be REMOVED, not merged forward');+ // Removal is per-node and per-key. Everything else the deployed sitemap carried still rides through,+ // which is what distinguishes a removal from a rebuild — and is the guarantee an in-place reconcile+ // exists to provide.+ assert.match(tag, /ResourceId="Contoso\.SubRes"/, 'unrelated bagged chrome survives');+ assert.match(tag, /ToolTipResourseId="Contoso\.Tip"/);+ // Scoped to the node the caller changed: the Area still has its own icon.+ assert.match(lastSitemapXml(), /Icon="\/WebResources\/contoso_area\.png"/, 'the Area icon is untouched');+});diff --git a/plugins/model-apps/scripts/tests/verify-model-app.test.js b/plugins/model-apps/scripts/tests/verify-model-app.test.jsindex 7b60f5d06..7d1fb1821 100644--- a/plugins/model-apps/scripts/tests/verify-model-app.test.js+++ b/plugins/model-apps/scripts/tests/verify-model-app.test.js@@ -410,77 +410,94 @@ test('verify CLI entrypoint converts SDK startup errors into emitResult failures// ── entityPrivileges reader ──────────────────────────────────────────────────────────────────────// These tests exist because the original role-privileges tests injected a FAKE `entityPrivileges`-// into verifySpec, which meant the real reader was never executed by any test. It shipped building a-// RELATIVE url (`/EntityDefinitions(...)`). `createAzHttpClient` is the raw transport the SDK drives,-// so it takes FULL request urls and validates them with `new URL(url)` for its same-origin guard — a-// relative path throws there. verify-spec catches that per entity, so the failure was silent: every-// entity would have reported "privileges unreadable" and the check would have failed on every live-// run. A reader is only as tested as its narrowest untested seam.--test('entityPrivileges builds an ABSOLUTE url with the /api/data prefix', async () => {+// into verifySpec, which meant the real reader was never executed by any test. That is how it shipped+// building a RELATIVE url against a transport that requires absolute ones — a failure verify-spec+// catches per entity, so every entity would silently have reported "privileges unreadable". A reader+// is only as tested as its narrowest untested seam, which is why the last test here drives the REAL+// vendored bundle rather than a hand-written SDK stub.+//+// The reader now goes through the SDK's `getEntityPrivileges` instead of a raw Web API call, so the+// url-shape tests that used to live here are gone with the url they tested. What replaces them is the+// SHAPE ADAPTATION and the fail-closed behaviour, which is what verify-spec actually depends on.++test('entityPrivileges maps the SDK camelCase rows onto the PascalCase shape the comparison reads', async () => {+ // lib/role-privileges.js speaks Dataverse's wire vocabulary (`PrivilegeType`), which is also what+ // the role WRITE payload uses. The SDK returns its own camelCase view. If this mapping were+ // dropped, `ACCESS_TYPE[...] === x.PrivilegeType` would compare against undefined for every row and+ // report every declared privilege as missing — a total, silent false failure.const seen = [];- const httpClient = { get: async (url) => { seen.push(url); return { status: 200, body: { Privileges: [{ PrivilegeId: 'p1', Name: 'prvReadAccount' }] } }; } };- const read = readerFor(stubSdk(), 'app', { httpClient, envUrl: 'https://contoso.crm.dynamics.com' });-- const privs = await read.entityPrivileges('Account');-- assert.strictEqual(seen.length, 1);- assert.strictEqual(- seen[0],- "https://contoso.crm.dynamics.com/api/data/v9.2/EntityDefinitions(LogicalName='account')?$select=LogicalName,Privileges",- );- assert.deepStrictEqual(privs, [{ PrivilegeId: 'p1', Name: 'prvReadAccount' }]);-});--test('entityPrivileges survives the REAL createAzHttpClient same-origin guard', async () => {- // The regression test that matters: drive the reader through the actual transport rather than a- // hand-written stub, so the url has to satisfy the same guard it failed in production.- const { createAzHttpClient } = require('../lib/sdk-http-client.js');- const requests = [];- const request = async (o) => {- requests.push(o);- return { statusCode: 200, headers: {}, body: JSON.stringify({ Privileges: [{ PrivilegeId: 'p9' }] }) };+ const sdk = stubSdk();+ sdk.getEntityPrivileges = async (logical) => {+ seen.push(logical);+ return [{ name: 'prvReadAccount', privilegeId: 'p1', privilegeType: 'Read', access: 'read', scopes: ['user', 'organization'] }];};- const httpClient = createAzHttpClient('https://contoso.crm.dynamics.com', { getToken: () => 'TOK', request });- const read = readerFor(stubSdk(), 'app', { httpClient, envUrl: 'https://contoso.crm.dynamics.com' });+ const read = readerFor(sdk, 'app', {});- const privs = await read.entityPrivileges('co_ticket');+ const privs = await read.entityPrivileges('Account');- assert.deepStrictEqual(privs, [{ PrivilegeId: 'p9' }]);- assert.strictEqual(requests.length, 1, 'the request must reach the transport, not be rejected by the guard');+ assert.deepStrictEqual(seen, ['account'], 'the logical name is lower-cased, as Dataverse stores it');+ assert.deepStrictEqual(privs, [{ Name: 'prvReadAccount', PrivilegeId: 'p1', PrivilegeType: 'Read' }]);});-test('entityPrivileges tolerates a trailing slash on the org url', async () => {- const seen = [];- const httpClient = { get: async (url) => { seen.push(url); return { status: 200, body: { Privileges: [] } }; } };- const read = readerFor(stubSdk(), 'app', { httpClient, envUrl: 'https://contoso.crm.dynamics.com/' });- await read.entityPrivileges('account');- assert.ok(!seen[0].includes('.com//api'), `double slash in ${seen[0]}`);-});--test('entityPrivileges escapes a quote in the logical name', async () => {- // odataLit doubles a single quote; without it the OData path literal would be malformed.- const seen = [];- const httpClient = { get: async (url) => { seen.push(url); return { status: 200, body: { Privileges: [] } }; } };- const read = readerFor(stubSdk(), 'app', { httpClient, envUrl: 'https://contoso.crm.dynamics.com' });- await read.entityPrivileges("o'brien");- assert.match(seen[0], /LogicalName='o''brien'/);+test('entityPrivileges PROPAGATES a throw rather than returning an empty grant', async () => {+ // The SDK throws for a table that exposes no privileges (unknown or non-securable). Swallowing that+ // into `[]` would read as "this table exposes nothing", which passes the subset comparison+ // vacuously — the exact false PASS the check exists to prevent. verify-spec wraps each call in a+ // try/catch and leaves the entity ABSENT from its map, which `compareRolePrivileges` reports as a+ // finding. So the fail-closed behaviour depends on this throw reaching it.+ const sdk = stubSdk();+ sdk.getEntityPrivileges = async () => { throw new Error('no privileges for co_missing'); };+ const read = readerFor(sdk, 'app', {});+ await assert.rejects(read.entityPrivileges('co_missing'), /no privileges for co_missing/);});-test('entityPrivileges returns null on a non-2xx rather than an empty grant', async () => {- // null is the fail-closed signal: verify-spec reports it as a finding. An empty array would read- // as "this table exposes no privileges" and could pass the subset comparison vacuously.- const httpClient = { get: async () => ({ status: 404, body: {} }) };- const read = readerFor(stubSdk(), 'app', { httpClient, envUrl: 'https://contoso.crm.dynamics.com' });- assert.strictEqual(await read.entityPrivileges('account'), null);+test('entityPrivileges is ALWAYS wired now that the SDK carries the read', async () => {+ // It used to be conditional on a raw httpClient + org url, and ABSENT when either was missing, so+ // verify-spec skipped the role-privileges check entirely. With the read on the SDK there is no such+ // condition left: the reader exists whenever the SDK does. Asserted so a future refactor cannot+ // quietly reintroduce a silent skip — an absent reader disables a security check without saying so.+ assert.strictEqual(typeof readerFor(stubSdk(), 'app', {}).entityPrivileges, 'function');});-test('entityPrivileges is ABSENT (not broken) when the client or org url is missing', async () => {- // verify-spec skips role-privileges unless both readers are functions, so an unwired reader must- // not exist at all. A present-but-throwing reader would report a false failure on every entity.- assert.strictEqual(typeof readerFor(stubSdk(), 'app', {}).entityPrivileges, 'undefined');- assert.strictEqual(typeof readerFor(stubSdk(), 'app', { httpClient: { get: async () => ({}) } }).entityPrivileges, 'undefined');- assert.strictEqual(typeof readerFor(stubSdk(), 'app', { envUrl: 'https://contoso.crm.dynamics.com' }).entityPrivileges, 'undefined');+test('entityPrivileges REAL BUNDLE: the SDK method exists and returns the shape the mapping expects', async () => {+ // The seam that matters. A hand-written SDK stub proves only that the mapping is self-consistent;+ // it would stay green if `getEntityPrivileges` were renamed or dropped by a re-vendor, or if it+ // returned a different shape. Drive the actual bundle over a fake Dataverse instead.+ const { createMakerSdk } = require(path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs'));+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'entpriv-real-'));+ const urls = [];+ const httpClient = {+ get: async (url) => {+ urls.push(url);+ return {+ status: 200,+ headers: {},+ body: {+ LogicalName: 'co_ticket',+ Privileges: [+ { Name: 'prvReadco_ticket', PrivilegeId: 'p9', PrivilegeType: 'Read', CanBeBasic: true, CanBeGlobal: true },+ { Name: 'prvCreateco_ticket', PrivilegeId: 'p10', PrivilegeType: 'Create', CanBeBasic: false, CanBeGlobal: true },+ ],+ },+ };+ },+ post: async () => ({ status: 204, headers: {}, body: {} }),+ patch: async () => ({ status: 204, headers: {}, body: {} }),+ delete: async () => ({ status: 204, headers: {}, body: {} }),+ put: async () => ({ status: 204, headers: {}, body: {} }),+ };+ const sdk = createMakerSdk({ workspacePath: dir, instanceUrl: 'https://contoso.crm.dynamics.com', httpClient });+ sdk.initWorkspace();++ const privs = await readerFor(sdk, 'app', {}).entityPrivileges('CO_Ticket');++ assert.deepStrictEqual(privs, [+ { Name: 'prvReadco_ticket', PrivilegeId: 'p9', PrivilegeType: 'Read' },+ { Name: 'prvCreateco_ticket', PrivilegeId: 'p10', PrivilegeType: 'Create' },+ ], 'the bundle must still return { name, privilegeId, privilegeType } rows');+ assert.ok(urls.some((u) => /EntityDefinitions\(LogicalName='co_ticket'\)/.test(u)),+ `the SDK must query the entity by logical name; saw ${JSON.stringify(urls)}`);+ fs.rmSync(dir, { recursive: true, force: true });});test('rolePrivileges paginates and never caps with top', async () => {@@ -493,7 +510,7 @@ test('rolePrivileges paginates and never caps with top', async () => {const calls = [];const sdk = stubSdk();sdk.queryRecords = async (set, options) => { calls.push({ set, options }); return []; };- const read = readerFor(sdk, 'app', { httpClient: { get: async () => ({ status: 200, body: {} }) }, envUrl: 'https://contoso.crm.dynamics.com' });+ const read = readerFor(sdk, 'app', {});await read.rolePrivileges('00000000-0000-0000-0000-000000000001');diff --git a/plugins/model-apps/scripts/vendor/PROVENANCE.json b/plugins/model-apps/scripts/vendor/PROVENANCE.jsonindex 2f114265d..5d1dcc61b 100644--- a/plugins/model-apps/scripts/vendor/PROVENANCE.json+++ b/plugins/model-apps/scripts/vendor/PROVENANCE.json@@ -1,14 +1,14 @@{- "commit": "e7e8e601a5587ebed523bf9de0043130eafa7888",- "subject": "Fix PPAPI licensing recommendation pagination",+ "commit": "331b9f56705b8f5887f73bd40a1cceddc9fbf2e1",+ "subject": "Revert 'fix: scheduled trigger skips its first run when the start time is in the future'","dirtySdkPackage": 0,- "libBuiltAt": "2026-09-04T21:32:20.419Z",- "newestSrcAt": "2026-09-04T21:24:55.321Z",+ "libBuiltAt": "2026-09-11T02:08:20.161Z",+ "newestSrcAt": "2026-09-11T02:03:26.756Z","libIsStale": false,"nostub": false,"esbuildVersion": "0.28.1","nodeVersion": "v22.13.1",- "builtAt": "2026-09-04T21:43:31.252Z",- "bundleSha256": "dabef5c4e76ce646d613834d1114f32e89c013a6a16b91e1fb83c7f4ee4494ed",- "bundleBytes": 692039+ "builtAt": "2026-09-11T02:08:49.251Z",+ "bundleSha256": "e51103ce286d9b7749b1c542e5313d837374978c3584184c47f48d2886d9e248",+ "bundleBytes": 695310}diff --git a/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs b/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjsindex 9d9c25921..951079cfc 100644--- a/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs+++ b/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs@@ -25,37 +25,37 @@}globalThis.document=globalThis.document||globalThis.window.document;})();-"use strict";var aP=Object.create;var us=Object.defineProperty;var oP=Object.getOwnPropertyDescriptor;var sP=Object.getOwnPropertyNames;var lP=Object.getPrototypeOf,uP=Object.prototype.hasOwnProperty;var I=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var g=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},Rr=(e,t)=>{for(var r in t)us(e,r,{get:t[r],enumerable:!0})},ih=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of sP(t))!uP.call(e,i)&&i!==r&&us(e,i,{get:()=>t[i],enumerable:!(n=oP(t,i))||n.enumerable});return e};var se=(e,t,r)=>(r=e!=null?aP(lP(e)):{},ih(t||!e||!e.__esModule?us(r,"default",{value:e,enumerable:!0}):r,e)),Fr=e=>ih(us({},"__esModule",{value:!0}),e);var Mn=g(C=>{"use strict";Object.defineProperty(C,"__esModule",{value:!0});C.DateTimeBehavior=C.PrecisionSource=C.StringFormatName=C.SourceType=C.ImeMode=C.SolutionEntityTypeCodeExtToComponentTypeCode=C.SolutionComponentTypeCodeToEntityTypeCodeExt=C.SolutionComponentVirtualAttributeSubtype=C.EntityTypeCode=C.SolutionComponentTypeCodeExt=C.RootComponentBehavior=C.SolutionComponentTypeCode=C.EntityKeyIndexStatus=C.ViewStateCode=C.ViewStatusCode=C.RelationshipSecurityTypes=C.CascadeType=C.RelationshipTypeExt=C.RelationshipType=C.AppSubType=C.BusinessProcessType=C.WorkflowCategory=C.WorkflowScope=C.WorkflowTypeCode=C.StatusCodeEnabledDisabled=C.StateCodeEnabledDisabled=C.StatusCode=C.StateCode=C.OptionSetType=C.AttributeTypeCodeNum=C.AttributeFormatName=C.AttributeFormatCode=C.AttributeTypeName=C.AttributeTypeCode=C.PluginSourceType=C.AuthType=C.PluginIsolationMode=C.ComponentState=C.ChartType=C.ChartsType=C.ViewType=C.AttributeType=C.ActivationState=C.FormPresentation=C.FormType=C.TableTypeCode=C.TableTypes=C.ActivityTypeMask=C.PrincipalType=C.OwnershipTypes=void 0;C.QueryType=C.KnownCustomSolutionComponentEntitySetName=C.TeamTypeEnum=C.EnvironmentVariableDefinitionTypeEnum=C.ConnectorTypeEnum=C.RoleInheritance=C.DefaultRoleTemplates=C.DeleteDependencyErrorCode=C.ServiceEndpointConnectionMode=C.ServiceEndpointContract=C.ServiceNamespaceFormat=C.ConnectionRoleCategory=C.ReportTypeCode=C.SdkMessageProcessingMode=C.SupportedDeployment=C.SdkMessageProcessingStage=C.WebResourceTypeCode=C.IntegerFormat=C.DateTimeFormat=void 0;var ah;(function(e){e.None="None",e.UserOwned="UserOwned",e.TeamOwned="TeamOwned",e.BusinessOwned="BusinessOwned",e.OrganizationOwned="OrganizationOwned",e.BusinessParented="BusinessParented",e.Filtered="Filtered"})(ah||(C.OwnershipTypes=ah={}));var oh;(function(e){e.User="Microsoft.Dynamics.CRM.systemuser",e.Team="Microsoft.Dynamics.CRM.team"})(oh||(C.PrincipalType=oh={}));var sh;(function(e){e[e.DoNotDisplayInActivityMenus=0]="DoNotDisplayInActivityMenus",e[e.DisplayInActivityMenus=1]="DisplayInActivityMenus"})(sh||(C.ActivityTypeMask=sh={}));var lh;(function(e){e.Activity="Activity",e.Virtual="Virtual",e.Standard="Standard",e.Elastic="Elastic"})(lh||(C.TableTypes=lh={}));var uh;(function(e){e.Standard="Standard",e.Virtual="Virtual",e.Elastic="Elastic"})(uh||(C.TableTypeCode=uh={}));var ch;(function(e){e[e.Dashboard=0]="Dashboard",e[e.AppointmentBook=1]="AppointmentBook",e[e.Main=2]="Main",e[e.MiniCampaignBO=3]="MiniCampaignBO",e[e.Preview=4]="Preview",e[e.MobileExpress=5]="MobileExpress",e[e.QuickViewForm=6]="QuickViewForm",e[e.QuickCreate=7]="QuickCreate",e[e.Dialog=8]="Dialog",e[e.TaskFlowForm=9]="TaskFlowForm",e[e.InteractionCentricDashboard=10]="InteractionCentricDashboard",e[e.Card=11]="Card",e[e.MainInteractiveExperience=12]="MainInteractiveExperience",e[e.Other=100]="Other",e[e.MainBackup=101]="MainBackup",e[e.AppointmentBookBackup=102]="AppointmentBookBackup",e[e.PowerBIDashboard=103]="PowerBIDashboard"})(ch||(C.FormType=ch={}));var dh;(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(dh||(C.FormPresentation=dh={}));var ph;(function(e){e[e.Inactive=0]="Inactive",e[e.Active=1]="Active"})(ph||(C.ActivationState=ph={}));var fh;(function(e){e[e.String=0]="String",e[e.Number=1]="Number",e[e.Picklist=2]="Picklist"})(fh||(C.AttributeType=fh={}));var mh;(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"})(mh||(C.ViewType=mh={}));var hh;(function(e){e[e.ASPChart=0]="ASPChart",e[e.PowerBI=1]="PowerBI"})(hh||(C.ChartsType=hh={}));var gh;(function(e){e[e.DataAndInteractionCentric=0]="DataAndInteractionCentric",e[e.InteractionCentric=1]="InteractionCentric"})(gh||(C.ChartType=gh={}));var vh;(function(e){e[e.Published=0]="Published",e[e.Unpublished=1]="Unpublished",e[e.Deleted=2]="Deleted",e[e.DeletedUnpublished=3]="DeletedUnpublished"})(vh||(C.ComponentState=vh={}));var yh;(function(e){e[e.None=1]="None",e[e.Sandbox=2]="Sandbox",e[e.External=3]="External"})(yh||(C.PluginIsolationMode=yh={}));var bh;(function(e){e[e.BasicAuth=0]="BasicAuth"})(bh||(C.AuthType=bh={}));var wh;(function(e){e[e.Database=0]="Database",e[e.Disk=1]="Disk",e[e.Normal=2]="Normal",e[e.AzureWebApp=3]="AzureWebApp"})(wh||(C.PluginSourceType=wh={}));var Ah;(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"})(Ah||(C.AttributeTypeCode=Ah={}));var Ch;(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"})(Ch||(C.AttributeTypeName=Ch={}));var Sh;(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"})(Sh||(C.AttributeFormatCode=Sh={}));var Eh;(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"})(Eh||(C.AttributeFormatName=Eh={}));var Nh;(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"})(Nh||(C.AttributeTypeCodeNum=Nh={}));var Dh;(function(e){e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean"})(Dh||(C.OptionSetType=Dh={}));var Ih;(function(e){e[e.Draft=0]="Draft",e[e.Activated=1]="Activated"})(Ih||(C.StateCode=Ih={}));var _h;(function(e){e[e.Draft=1]="Draft",e[e.Activated=2]="Activated"})(_h||(C.StatusCode=_h={}));var Ph;(function(e){e[e.Enabled=0]="Enabled",e[e.Disabled=1]="Disabled"})(Ph||(C.StateCodeEnabledDisabled=Ph={}));var Th;(function(e){e[e.Enabled=1]="Enabled",e[e.Disabled=2]="Disabled"})(Th||(C.StatusCodeEnabledDisabled=Th={}));var Oh;(function(e){e[e.Definition=1]="Definition",e[e.Activation=2]="Activation",e[e.Template=3]="Template"})(Oh||(C.WorkflowTypeCode=Oh={}));var Rh;(function(e){e[e.User=1]="User",e[e.BusinessUnit=2]="BusinessUnit",e[e.ParentChildBusinessUnit=3]="ParentChildBusinessUnit",e[e.Organization=4]="Organization"})(Rh||(C.WorkflowScope=Rh={}));var Fh;(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"})(Fh||(C.WorkflowCategory=Fh={}));var xh;(function(e){e[e.None=-1]="None",e[e.BusinessFlow=0]="BusinessFlow",e[e.TaskFlow=1]="TaskFlow"})(xh||(C.BusinessProcessType=xh={}));var Lh;(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"})(Lh||(C.AppSubType=Lh={}));var kh;(function(e){e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(kh||(C.RelationshipType=kh={}));var Mh;(function(e){e.ManyToOneRelationship="ManyToOneRelationship",e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(Mh||(C.RelationshipTypeExt=Mh={}));var Uh;(function(e){e.NoCascade="NoCascade",e.Cascade="Cascade",e.Active="Active",e.UserOwned="UserOwned",e.RemoveLink="RemoveLink",e.Restrict="Restrict"})(Uh||(C.CascadeType=Uh={}));var Bh;(function(e){e.None="None",e.Append="Append",e.ParentChild="ParentChild",e.Pointer="Pointer",e.Inheritance="Inheritance"})(Bh||(C.RelationshipSecurityTypes=Bh={}));var $h;(function(e){e[e.Active=1]="Active",e[e.Inactive=2]="Inactive"})($h||(C.ViewStatusCode=$h={}));var qh;(function(e){e[e.Active=0]="Active",e[e.Inactive=1]="Inactive"})(qh||(C.ViewStateCode=qh={}));var Vh;(function(e){e.Active="Active",e.Failed="Failed",e.InProgress="InProgress",e.Pending="Pending"})(Vh||(C.EntityKeyIndexStatus=Vh={}));var Gh;(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"})(Gh||(C.SolutionComponentTypeCode=Gh={}));var zh;(function(e){e[e.IncludeSubcomponents=0]="IncludeSubcomponents",e[e.DoNotIncludeSubcomponents=1]="DoNotIncludeSubcomponents",e[e.IncludeAsShellOnly=2]="IncludeAsShellOnly"})(zh||(C.RootComponentBehavior=zh={}));var cs;(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"})(cs||(C.SolutionComponentTypeCodeExt=cs={}));var ds;(function(e){e[e.Entity=9801]="Entity",e[e.Attribute=9802]="Attribute",e[e.OptionSet=9804]="OptionSet",e[e.EntityRelationship=9805]="EntityRelationship",e[e.EntityKey=9812]="EntityKey",e[e.Role=1036]="Role",e[e.DisplayString=4102]="DisplayString",e[e.SavedQuery=1039]="SavedQuery",e[e.Workflow=4703]="Workflow",e[e.Report=9100]="Report",e[e.Template=2010]="Template",e[e.ContractTemplate=2011]="ContractTemplate",e[e.KbArticleTemplate=1016]="KbArticleTemplate",e[e.MailMergeTemplate=9106]="MailMergeTemplate",e[e.SavedQueryVisualization=1111]="SavedQueryVisualization",e[e.SystemForm=1030]="SystemForm",e[e.WebResource=9333]="WebResource",e[e.SiteMap=4709]="SiteMap",e[e.ConnectionRole=3231]="ConnectionRole",e[e.HierarchyRule=8840]="HierarchyRule",e[e.CustomControl=9753]="CustomControl",e[e.FieldSecurityProfile=1200]="FieldSecurityProfile",e[e.AppModule=9006]="AppModule",e[e.PluginAssembly=4605]="PluginAssembly",e[e.SdkMessageProcessingStep=4608]="SdkMessageProcessingStep",e[e.ServiceEndpoint=4618]="ServiceEndpoint",e[e.RoutingRule=8181]="RoutingRule",e[e.SLA=9750]="SLA",e[e.ConvertRule=9300]="ConvertRule",e[e.MobileOfflineProfile=9866]="MobileOfflineProfile",e[e.EntityDataSource=85]="EntityDataSource",e[e.SdkMessage=4606]="SdkMessage",e[e.RibbonCustomization=1120]="RibbonCustomization",e[e.EntityDataProvider=181]="EntityDataProvider",e[e.CanvasApp=300]="CanvasApp",e[e.Connector=372]="Connector",e[e.MaskingRule=373]="MaskingRule",e[e.AttributeMaskingRule=374]="AttributeMaskingRule",e[e.EnvironmentVariableDefinition=380]="EnvironmentVariableDefinition",e[e.EnvironmentVariableValue=381]="EnvironmentVariableValue",e[e.AIModel=401]="AIModel",e[e.Plan=10283]="Plan",e[e.Dataflow=418]="Dataflow",e[e.DataflowEntities=419]="DataflowEntities",e[e.DualWriteEntityMap=500]="DualWriteEntityMap",e[e.DataIntegrationConnection=501]="DataIntegrationConnection",e[e.ExportToDataLakeConfig=510]="ExportToDataLakeConfig",e[e.TeamTemplate=511]="TeamTemplate",e[e.DataWorkspace=10282]="DataWorkspace",e[e.Dashboard=1030]="Dashboard",e[e.InteractionCentricDashboard=1032]="InteractionCentricDashboard",e[e.PowerBIDashboard=1034]="PowerBIDashboard",e[e.Dialog=1030]="Dialog",e[e.WebResourceImage=9333]="WebResourceImage",e[e.WebResourceSilverlight=9333]="WebResourceSilverlight",e[e.WebResourceCode=9333]="WebResourceCode",e[e.WebResourceData=9333]="WebResourceData",e[e.BusinessRule=4703]="BusinessRule",e[e.ActionDefinition=4703]="ActionDefinition",e[e.ActionTemplate=4703]="ActionTemplate",e[e.DialogDefinition=4703]="DialogDefinition",e[e.DialogTemplate=4703]="DialogTemplate",e[e.WorkflowDefinition=4703]="WorkflowDefinition",e[e.WorkflowTemplate=4703]="WorkflowTemplate",e[e.ProcessFlow=4703]="ProcessFlow",e[e.Flow=4703]="Flow",e[e.UIFlow=4703]="UIFlow",e[e.ProcessNoFlow=4703]="ProcessNoFlow",e[e.ProcessNoFlowNoUIFlowNoBusinessRule=4703]="ProcessNoFlowNoUIFlowNoBusinessRule",e[e.AllDashboards=1030]="AllDashboards",e[e.FormsOnly=1030]="FormsOnly",e[e.ComponentLibrary=300]="ComponentLibrary",e[e.CanvasAppsOnly=300]="CanvasAppsOnly",e[e.CustomCanvasPage=300]="CustomCanvasPage",e[e.CodeApp=300]="CodeApp",e[e.MobileApp=300]="MobileApp",e[e.Chatbot=10030]="Chatbot",e[e.Card=10276]="Card"})(ds||(C.EntityTypeCode=ds={}));var Wh;(function(e){e.MultiSelectPicklist="MultiSelectPicklist",e.File="File",e.Image="Image"})(Wh||(C.SolutionComponentVirtualAttributeSubtype=Wh={}));function cP(e){let t=cs[e];return ds[t]}C.SolutionComponentTypeCodeToEntityTypeCodeExt=cP;function dP(e){let t=ds[e];return cs[t]}C.SolutionEntityTypeCodeExtToComponentTypeCode=dP;var jh;(function(e){e.Active="Active",e.Auto="Auto",e.Disabled="Disabled",e.Inactive="Inactive"})(jh||(C.ImeMode=jh={}));var Hh;(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"})(Hh||(C.SourceType=Hh={}));var Jh;(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"})(Jh||(C.StringFormatName=Jh={}));var Qh;(function(e){e[e.PrecisionProperty=0]="PrecisionProperty",e[e.Organization=1]="Organization",e[e.TransactionCurrency=2]="TransactionCurrency"})(Qh||(C.PrecisionSource=Qh={}));var Xh;(function(e){e.UserLocal="UserLocal",e.DateOnly="DateOnly",e.TimeZoneIndependent="TimeZoneIndependent"})(Xh||(C.DateTimeBehavior=Xh={}));var Kh;(function(e){e.DateOnly="DateOnly",e.DateAndTime="DateAndTime"})(Kh||(C.DateTimeFormat=Kh={}));var Yh;(function(e){e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale"})(Yh||(C.IntegerFormat=Yh={}));var Zh;(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"})(Zh||(C.WebResourceTypeCode=Zh={}));var eg;(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"})(eg||(C.SdkMessageProcessingStage=eg={}));var tg;(function(e){e[e.ServerOnly=0]="ServerOnly",e[e.OutlookClientOnly=1]="OutlookClientOnly",e[e.Both=2]="Both"})(tg||(C.SupportedDeployment=tg={}));var rg;(function(e){e[e.Synchronous=0]="Synchronous",e[e.Asynchronous=1]="Asynchronous"})(rg||(C.SdkMessageProcessingMode=rg={}));var ng;(function(e){e[e.ReportingServicesReport=1]="ReportingServicesReport",e[e.OtherReport=2]="OtherReport",e[e.LinkedReport=3]="LinkedReport"})(ng||(C.ReportTypeCode=ng={}));var ig;(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"})(ig||(C.ConnectionRoleCategory=ig={}));var ag;(function(e){e[e.Name=1]="Name",e[e.Address=2]="Address"})(ag||(C.ServiceNamespaceFormat=ag={}));var og;(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"})(og||(C.ServiceEndpointContract=og={}));var sg;(function(e){e[e.Normal=1]="Normal",e[e.Federated=2]="Federated"})(sg||(C.ServiceEndpointConnectionMode=sg={}));var lg;(function(e){e.CannotDeleteInUseComponent="0x8004f01f",e.CannotDeleteInUseAttribute="0x80048418",e.CannotDeleteInUseOptionSet="0x80048417",e.CannotDeleteInUseEntity="0x80048420",e.CannotUninstallWithDependencies="0x8004F01D"})(lg||(C.DeleteDependencyErrorCode=lg={}));var ug;(function(e){e.SystemAdministrator="627090FF-40A3-4053-8790-584EDC5BE201",e.SystemCustomizer="119F245C-3CC8-4B62-B31C-D1A046CED15D"})(ug||(C.DefaultRoleTemplates=ug={}));var cg;(function(e){e[e.DefaultTeamPrivilege=0]="DefaultTeamPrivilege",e[e.DirectUserAndTeamPrivilege=1]="DirectUserAndTeamPrivilege"})(cg||(C.RoleInheritance=cg={}));var dg;(function(e){e[e.NotSpecified=0]="NotSpecified",e[e.CustomConnector=1]="CustomConnector"})(dg||(C.ConnectorTypeEnum=dg={}));var pg;(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"})(pg||(C.EnvironmentVariableDefinitionTypeEnum=pg={}));var fg;(function(e){e[e.Owner=0]="Owner",e[e.Access=1]="Access",e[e.AADSecurityGroup=2]="AADSecurityGroup",e[e.AADOfficeGroup=3]="AADOfficeGroup"})(fg||(C.TeamTypeEnum=fg={}));var mg;(function(e){e.Bots="bots"})(mg||(C.KnownCustomSolutionComponentEntitySetName=mg={}));var hg;(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"})(hg||(C.QueryType=hg={}))});var ie=g(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.IncompatibleWorkspaceError=Y.PathTraversalError=Y.AmbiguousArtifactError=Y.JsonPointerError=Y.NotImplementedError=Y.WorkspaceNotInitializedError=Y.ConnectionError=Y.VersionConflictError=Y.LocalEditsWouldBeLostError=Y.StaleArtifactError=Y.InvalidArgumentError=Y.ValidationError=Y.PathNotFoundError=Y.ArtifactNotFoundError=Y.readPartialTokens=Y.withPartialTokens=Y.SdkError=void 0;var Ye=class extends Error{constructor(t,r){super(r),this.code=t,Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}};Y.SdkError=Ye;var gg=Symbol.for("cds-maker-sdk.partialWriteTokens");function pP(e,t){return typeof e=="object"&&e!==null&&(e[gg]=t),e}Y.withPartialTokens=pP;function fP(e){let t=e;for(let r=0;t&&typeof t=="object"&&r<8;r++){let n=t[gg];if(n&&typeof n=="object")return n;t=t.cause}}Y.readPartialTokens=fP;var sc=class extends Ye{constructor(t,r){super("ARTIFACT_NOT_FOUND",`Artifact ${t}/${r} not found in workspace`),this.type=t,this.id=r}};Y.ArtifactNotFoundError=sc;var lc=class extends Ye{constructor(t,r,n){super("PATH_NOT_FOUND",`Path ${n} not found in ${t}/${r}`),this.type=t,this.id=r,this.pointer=n}};Y.PathNotFoundError=lc;var uc=class extends Ye{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}:+"use strict";var hP=Object.create;var ds=Object.defineProperty;var gP=Object.getOwnPropertyDescriptor;var vP=Object.getOwnPropertyNames;var yP=Object.getPrototypeOf,bP=Object.prototype.hasOwnProperty;var I=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var g=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},Rr=(e,t)=>{for(var r in t)ds(e,r,{get:t[r],enumerable:!0})},uh=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of vP(t))!bP.call(e,i)&&i!==r&&ds(e,i,{get:()=>t[i],enumerable:!(n=gP(t,i))||n.enumerable});return e};var se=(e,t,r)=>(r=e!=null?hP(yP(e)):{},uh(t||!e||!e.__esModule?ds(r,"default",{value:e,enumerable:!0}):r,e)),Fr=e=>uh(ds({},"__esModule",{value:!0}),e);var Mn=g(C=>{"use strict";Object.defineProperty(C,"__esModule",{value:!0});C.DateTimeBehavior=C.PrecisionSource=C.StringFormatName=C.SourceType=C.ImeMode=C.SolutionEntityTypeCodeExtToComponentTypeCode=C.SolutionComponentTypeCodeToEntityTypeCodeExt=C.SolutionComponentVirtualAttributeSubtype=C.EntityTypeCode=C.SolutionComponentTypeCodeExt=C.RootComponentBehavior=C.SolutionComponentTypeCode=C.EntityKeyIndexStatus=C.ViewStateCode=C.ViewStatusCode=C.RelationshipSecurityTypes=C.CascadeType=C.RelationshipTypeExt=C.RelationshipType=C.AppSubType=C.BusinessProcessType=C.WorkflowCategory=C.WorkflowScope=C.WorkflowTypeCode=C.StatusCodeEnabledDisabled=C.StateCodeEnabledDisabled=C.StatusCode=C.StateCode=C.OptionSetType=C.AttributeTypeCodeNum=C.AttributeFormatName=C.AttributeFormatCode=C.AttributeTypeName=C.AttributeTypeCode=C.PluginSourceType=C.AuthType=C.PluginIsolationMode=C.ComponentState=C.ChartType=C.ChartsType=C.ViewType=C.AttributeType=C.ActivationState=C.FormPresentation=C.FormType=C.TableTypeCode=C.TableTypes=C.ActivityTypeMask=C.PrincipalType=C.OwnershipTypes=void 0;C.QueryType=C.KnownCustomSolutionComponentEntitySetName=C.TeamTypeEnum=C.EnvironmentVariableDefinitionTypeEnum=C.ConnectorTypeEnum=C.RoleInheritance=C.DefaultRoleTemplates=C.DeleteDependencyErrorCode=C.ServiceEndpointConnectionMode=C.ServiceEndpointContract=C.ServiceNamespaceFormat=C.ConnectionRoleCategory=C.ReportTypeCode=C.SdkMessageProcessingMode=C.SupportedDeployment=C.SdkMessageProcessingStage=C.WebResourceTypeCode=C.IntegerFormat=C.DateTimeFormat=void 0;var ch;(function(e){e.None="None",e.UserOwned="UserOwned",e.TeamOwned="TeamOwned",e.BusinessOwned="BusinessOwned",e.OrganizationOwned="OrganizationOwned",e.BusinessParented="BusinessParented",e.Filtered="Filtered"})(ch||(C.OwnershipTypes=ch={}));var dh;(function(e){e.User="Microsoft.Dynamics.CRM.systemuser",e.Team="Microsoft.Dynamics.CRM.team"})(dh||(C.PrincipalType=dh={}));var ph;(function(e){e[e.DoNotDisplayInActivityMenus=0]="DoNotDisplayInActivityMenus",e[e.DisplayInActivityMenus=1]="DisplayInActivityMenus"})(ph||(C.ActivityTypeMask=ph={}));var fh;(function(e){e.Activity="Activity",e.Virtual="Virtual",e.Standard="Standard",e.Elastic="Elastic"})(fh||(C.TableTypes=fh={}));var mh;(function(e){e.Standard="Standard",e.Virtual="Virtual",e.Elastic="Elastic"})(mh||(C.TableTypeCode=mh={}));var hh;(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"})(hh||(C.FormType=hh={}));var gh;(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(gh||(C.FormPresentation=gh={}));var vh;(function(e){e[e.Inactive=0]="Inactive",e[e.Active=1]="Active"})(vh||(C.ActivationState=vh={}));var yh;(function(e){e[e.String=0]="String",e[e.Number=1]="Number",e[e.Picklist=2]="Picklist"})(yh||(C.AttributeType=yh={}));var bh;(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"})(bh||(C.ViewType=bh={}));var wh;(function(e){e[e.ASPChart=0]="ASPChart",e[e.PowerBI=1]="PowerBI"})(wh||(C.ChartsType=wh={}));var Ah;(function(e){e[e.DataAndInteractionCentric=0]="DataAndInteractionCentric",e[e.InteractionCentric=1]="InteractionCentric"})(Ah||(C.ChartType=Ah={}));var Ch;(function(e){e[e.Published=0]="Published",e[e.Unpublished=1]="Unpublished",e[e.Deleted=2]="Deleted",e[e.DeletedUnpublished=3]="DeletedUnpublished"})(Ch||(C.ComponentState=Ch={}));var Sh;(function(e){e[e.None=1]="None",e[e.Sandbox=2]="Sandbox",e[e.External=3]="External"})(Sh||(C.PluginIsolationMode=Sh={}));var Eh;(function(e){e[e.BasicAuth=0]="BasicAuth"})(Eh||(C.AuthType=Eh={}));var Nh;(function(e){e[e.Database=0]="Database",e[e.Disk=1]="Disk",e[e.Normal=2]="Normal",e[e.AzureWebApp=3]="AzureWebApp"})(Nh||(C.PluginSourceType=Nh={}));var Dh;(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"})(Dh||(C.AttributeTypeCode=Dh={}));var Ih;(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"})(Ih||(C.AttributeTypeName=Ih={}));var _h;(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"})(_h||(C.AttributeFormatCode=_h={}));var Ph;(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"})(Ph||(C.AttributeFormatName=Ph={}));var Th;(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"})(Th||(C.AttributeTypeCodeNum=Th={}));var Oh;(function(e){e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean"})(Oh||(C.OptionSetType=Oh={}));var Rh;(function(e){e[e.Draft=0]="Draft",e[e.Activated=1]="Activated"})(Rh||(C.StateCode=Rh={}));var Fh;(function(e){e[e.Draft=1]="Draft",e[e.Activated=2]="Activated"})(Fh||(C.StatusCode=Fh={}));var xh;(function(e){e[e.Enabled=0]="Enabled",e[e.Disabled=1]="Disabled"})(xh||(C.StateCodeEnabledDisabled=xh={}));var Lh;(function(e){e[e.Enabled=1]="Enabled",e[e.Disabled=2]="Disabled"})(Lh||(C.StatusCodeEnabledDisabled=Lh={}));var kh;(function(e){e[e.Definition=1]="Definition",e[e.Activation=2]="Activation",e[e.Template=3]="Template"})(kh||(C.WorkflowTypeCode=kh={}));var Mh;(function(e){e[e.User=1]="User",e[e.BusinessUnit=2]="BusinessUnit",e[e.ParentChildBusinessUnit=3]="ParentChildBusinessUnit",e[e.Organization=4]="Organization"})(Mh||(C.WorkflowScope=Mh={}));var Uh;(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"})(Uh||(C.WorkflowCategory=Uh={}));var Bh;(function(e){e[e.None=-1]="None",e[e.BusinessFlow=0]="BusinessFlow",e[e.TaskFlow=1]="TaskFlow"})(Bh||(C.BusinessProcessType=Bh={}));var $h;(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"})($h||(C.AppSubType=$h={}));var qh;(function(e){e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(qh||(C.RelationshipType=qh={}));var Vh;(function(e){e.ManyToOneRelationship="ManyToOneRelationship",e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(Vh||(C.RelationshipTypeExt=Vh={}));var Gh;(function(e){e.NoCascade="NoCascade",e.Cascade="Cascade",e.Active="Active",e.UserOwned="UserOwned",e.RemoveLink="RemoveLink",e.Restrict="Restrict"})(Gh||(C.CascadeType=Gh={}));var zh;(function(e){e.None="None",e.Append="Append",e.ParentChild="ParentChild",e.Pointer="Pointer",e.Inheritance="Inheritance"})(zh||(C.RelationshipSecurityTypes=zh={}));var Wh;(function(e){e[e.Active=1]="Active",e[e.Inactive=2]="Inactive"})(Wh||(C.ViewStatusCode=Wh={}));var jh;(function(e){e[e.Active=0]="Active",e[e.Inactive=1]="Inactive"})(jh||(C.ViewStateCode=jh={}));var Hh;(function(e){e.Active="Active",e.Failed="Failed",e.InProgress="InProgress",e.Pending="Pending"})(Hh||(C.EntityKeyIndexStatus=Hh={}));var Qh;(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"})(Qh||(C.SolutionComponentTypeCode=Qh={}));var Jh;(function(e){e[e.IncludeSubcomponents=0]="IncludeSubcomponents",e[e.DoNotIncludeSubcomponents=1]="DoNotIncludeSubcomponents",e[e.IncludeAsShellOnly=2]="IncludeAsShellOnly"})(Jh||(C.RootComponentBehavior=Jh={}));var ps;(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"})(ps||(C.SolutionComponentTypeCodeExt=ps={}));var fs;(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"})(fs||(C.EntityTypeCode=fs={}));var Xh;(function(e){e.MultiSelectPicklist="MultiSelectPicklist",e.File="File",e.Image="Image"})(Xh||(C.SolutionComponentVirtualAttributeSubtype=Xh={}));function wP(e){let t=ps[e];return fs[t]}C.SolutionComponentTypeCodeToEntityTypeCodeExt=wP;function AP(e){let t=fs[e];return ps[t]}C.SolutionEntityTypeCodeExtToComponentTypeCode=AP;var Kh;(function(e){e.Active="Active",e.Auto="Auto",e.Disabled="Disabled",e.Inactive="Inactive"})(Kh||(C.ImeMode=Kh={}));var Yh;(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"})(Yh||(C.SourceType=Yh={}));var Zh;(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"})(Zh||(C.StringFormatName=Zh={}));var eg;(function(e){e[e.PrecisionProperty=0]="PrecisionProperty",e[e.Organization=1]="Organization",e[e.TransactionCurrency=2]="TransactionCurrency"})(eg||(C.PrecisionSource=eg={}));var tg;(function(e){e.UserLocal="UserLocal",e.DateOnly="DateOnly",e.TimeZoneIndependent="TimeZoneIndependent"})(tg||(C.DateTimeBehavior=tg={}));var rg;(function(e){e.DateOnly="DateOnly",e.DateAndTime="DateAndTime"})(rg||(C.DateTimeFormat=rg={}));var ng;(function(e){e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale"})(ng||(C.IntegerFormat=ng={}));var ig;(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"})(ig||(C.WebResourceTypeCode=ig={}));var ag;(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"})(ag||(C.SdkMessageProcessingStage=ag={}));var og;(function(e){e[e.ServerOnly=0]="ServerOnly",e[e.OutlookClientOnly=1]="OutlookClientOnly",e[e.Both=2]="Both"})(og||(C.SupportedDeployment=og={}));var sg;(function(e){e[e.Synchronous=0]="Synchronous",e[e.Asynchronous=1]="Asynchronous"})(sg||(C.SdkMessageProcessingMode=sg={}));var lg;(function(e){e[e.ReportingServicesReport=1]="ReportingServicesReport",e[e.OtherReport=2]="OtherReport",e[e.LinkedReport=3]="LinkedReport"})(lg||(C.ReportTypeCode=lg={}));var ug;(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"})(ug||(C.ConnectionRoleCategory=ug={}));var cg;(function(e){e[e.Name=1]="Name",e[e.Address=2]="Address"})(cg||(C.ServiceNamespaceFormat=cg={}));var dg;(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"})(dg||(C.ServiceEndpointContract=dg={}));var pg;(function(e){e[e.Normal=1]="Normal",e[e.Federated=2]="Federated"})(pg||(C.ServiceEndpointConnectionMode=pg={}));var fg;(function(e){e.CannotDeleteInUseComponent="0x8004f01f",e.CannotDeleteInUseAttribute="0x80048418",e.CannotDeleteInUseOptionSet="0x80048417",e.CannotDeleteInUseEntity="0x80048420",e.CannotUninstallWithDependencies="0x8004F01D"})(fg||(C.DeleteDependencyErrorCode=fg={}));var mg;(function(e){e.SystemAdministrator="627090FF-40A3-4053-8790-584EDC5BE201",e.SystemCustomizer="119F245C-3CC8-4B62-B31C-D1A046CED15D"})(mg||(C.DefaultRoleTemplates=mg={}));var hg;(function(e){e[e.DefaultTeamPrivilege=0]="DefaultTeamPrivilege",e[e.DirectUserAndTeamPrivilege=1]="DirectUserAndTeamPrivilege"})(hg||(C.RoleInheritance=hg={}));var gg;(function(e){e[e.NotSpecified=0]="NotSpecified",e[e.CustomConnector=1]="CustomConnector"})(gg||(C.ConnectorTypeEnum=gg={}));var vg;(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"})(vg||(C.EnvironmentVariableDefinitionTypeEnum=vg={}));var yg;(function(e){e[e.Owner=0]="Owner",e[e.Access=1]="Access",e[e.AADSecurityGroup=2]="AADSecurityGroup",e[e.AADOfficeGroup=3]="AADOfficeGroup"})(yg||(C.TeamTypeEnum=yg={}));var bg;(function(e){e.Bots="bots"})(bg||(C.KnownCustomSolutionComponentEntitySetName=bg={}));var wg;(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"})(wg||(C.QueryType=wg={}))});var ie=g(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.IncompatibleWorkspaceError=Y.PathTraversalError=Y.AmbiguousArtifactError=Y.JsonPointerError=Y.NotImplementedError=Y.WorkspaceNotInitializedError=Y.ConnectionError=Y.VersionConflictError=Y.LocalEditsWouldBeLostError=Y.StaleArtifactError=Y.InvalidArgumentError=Y.ValidationError=Y.PathNotFoundError=Y.ArtifactNotFoundError=Y.readPartialTokens=Y.withPartialTokens=Y.SdkError=void 0;var et=class extends Error{constructor(t,r){super(r),this.code=t,Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}};Y.SdkError=et;var Ag=Symbol.for("cds-maker-sdk.partialWriteTokens");function CP(e,t){return typeof e=="object"&&e!==null&&(e[Ag]=t),e}Y.withPartialTokens=CP;function SP(e){let t=e;for(let r=0;t&&typeof t=="object"&&r<8;r++){let n=t[Ag];if(n&&typeof n=="object")return n;t=t.cause}}Y.readPartialTokens=SP;var uc=class extends et{constructor(t,r){super("ARTIFACT_NOT_FOUND",`Artifact ${t}/${r} not found in workspace`),this.type=t,this.id=r}};Y.ArtifactNotFoundError=uc;var cc=class extends et{constructor(t,r,n){super("PATH_NOT_FOUND",`Path ${n} not found in ${t}/${r}`),this.type=t,this.id=r,this.pointer=n}};Y.PathNotFoundError=cc;var dc=class extends et{constructor(t,r,n,i){var a,o,s,l;let u=Array.isArray(n)?n:[{pointer:n,rule:i??"invalid",message:i??"invalid"}];super("VALIDATION_ERROR",`Validation failed for ${t}/${r}:`+u.map(c=>` \u2022 ${c.pointer}: ${c.message} [${c.rule}]`).join(`-`)),this.type=t,this.id=r,this.issues=u,this.pointer=(o=(a=u[0])===null||a===void 0?void 0:a.pointer)!==null&&o!==void 0?o:"",this.rule=(l=(s=u[0])===null||s===void 0?void 0:s.rule)!==null&&l!==void 0?l:"invalid"}};Y.ValidationError=uc;var cc=class extends Ye{constructor(t){super("INVALID_ARGUMENT",t)}};Y.InvalidArgumentError=cc;var dc=class extends Ye{constructor(t,r,n){super("STALE_ARTIFACT",`Cannot apply the edit at ${n} to ${t}/${r}: the cached copy was stale and the server copy has since changed, so any pointer derived from the old copy may now identify a different node. The local copy has been refreshed \u2014 re-read the artifact, re-derive the pointer, and retry.`),this.type=t,this.id=r,this.pointer=n}};Y.StaleArtifactError=dc;var pc=class extends Ye{constructor(t,r,n,i){super("LOCAL_EDITS_WOULD_BE_LOST",`Refusing to fetch ${t}/${r}: the local copy has unpushed edits AND the server has moved since it was fetched (local=${n??"(none)"}, server=${i??"(none)"}). Overwriting now would discard your edits and replace them with another writer's changes. Push or discard your edits first, or pass { overwrite: true } to deliberately reset the local copy to the server version.`),this.type=t,this.id=r,this.localEtag=n,this.serverEtag=i}};Y.LocalEditsWouldBeLostError=pc;var fc=class extends Ye{constructor(t,r,n,i,a){super("VERSION_CONFLICT",`Version conflict for ${t}/${r}: local=${n??"(none)"}, server=${i??"(none)"}. Re-fetch and reapply changes.${a?` ${a}`:""}`),this.type=t,this.id=r,this.localEtag=n,this.serverEtag=i,this.detail=a}};Y.VersionConflictError=fc;var mc=class extends Ye{constructor(t,r,n,i){super("CONNECTION_ERROR",r>0?`HTTP ${r} from ${t}: ${n}`:`Transport failure reaching ${t}: ${n}`),this.url=t,this.statusCode=r,this.cause=i}};Y.ConnectionError=mc;var hc=class extends Ye{constructor(t){super("WORKSPACE_NOT_INITIALIZED",`Workspace not initialized at ${t}. Call initWorkspace() first.`),this.workspacePath=t}};Y.WorkspaceNotInitializedError=hc;var gc=class extends Ye{constructor(t,r){super("NOT_IMPLEMENTED",`Operation '${t}' is not implemented yet${r?`: ${r}`:""}.`),this.operation=t}};Y.NotImplementedError=gc;var vc=class extends Ye{constructor(t,r){super("INVALID_JSON_POINTER",`Invalid JSON Pointer '${t}': ${r}`),this.pointer=t}};Y.JsonPointerError=vc;var yc=class extends Ye{constructor(t,r,n){super("AMBIGUOUS_ARTIFACT",`Found ${n} ${t} rows matching '${r}'; a name is not a unique key. Resolve by id / alternate key instead of relying on name-based idempotency.`),this.kind=t,this.identity=r,this.matchCount=n}};Y.AmbiguousArtifactError=yc;var bc=class extends Ye{constructor(t,r){super("PATH_TRAVERSAL",`Refusing to resolve a path outside the workspace root: '${t}' is not within '${r}'.`),this.target=t,this.root=r}};Y.PathTraversalError=bc;var wc=class extends Ye{constructor(t,r){super("INCOMPATIBLE_WORKSPACE",`Workspace schema version ${t} is newer than this SDK supports (v${r}). Upgrade the SDK, or re-create the workspace with this version.`),this.workspaceVersion=t,this.supportedVersion=r}};Y.IncompatibleWorkspaceError=wc});var ee=g(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.odataQuery=Oe.normalizeGuid=Oe.createSafeXmlElement=Oe.assertNoControlChars=Oe.assertODataName=Oe.assertXmlName=Oe.xmlText=Oe.odataPathLiteral=Oe.odataLiteral=void 0;var ps=ie();function vg(e){return String(e??"").replace(/'/g,"''")}Oe.odataLiteral=vg;function mP(e){return encodeURIComponent(vg(e))}Oe.odataPathLiteral=mP;function hP(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}Oe.xmlText=hP;function yg(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 ps.InvalidArgumentError(`${t} must be a valid XML element name (got '${e}')`);return e}Oe.assertXmlName=yg;function gP(e,t){let r=String(e??"");if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw new ps.InvalidArgumentError(`${t} must be a valid OData identifier (letters, digits, underscore): got '${e}'`);return e}Oe.assertODataName=gP;function vP(e,t){if(/[\u0000-\u001F\u007F]/.test(String(e??"")))throw new ps.InvalidArgumentError(`${t} must not contain control characters (including CR/LF): they would inject additional lines into the request`);return e}Oe.assertNoControlChars=vP;function yP(e,t,r){return e.createElement(yg(t,r))}Oe.createSafeXmlElement=yP;var bP=/^[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 wP(e,t){let r=String(e??""),n=r.length===38&&r.startsWith("{")&&r.endsWith("}")?r.slice(1,-1):r;if(!bP.test(n))throw new ps.InvalidArgumentError(`${t} must be a valid GUID (got '${e}')`);return n.toLowerCase()}Oe.normalizeGuid=wP;function AP(e){let t=[];for(let[r,n]of e)n!=null&&n!==""&&t.push(`${r}=${encodeURIComponent(String(n))}`);return t.length>0?`?${t.join("&")}`:""}Oe.odataQuery=AP});var ye=g(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.nowIso=te.isAlreadyDeleted=te.deleteRecord=te.ensureSuccess=te.resolveCreatedId=te.requireCreatedId=te.withClientMintedId=te.readCreatedId=te.readEtag=te.requireEtag=te.echoWrite=te.UPDATE_NO_ETAG_CODE=te.VERSION_CONFLICT_CODE=void 0;var pi=ie(),Fa=ee();te.VERSION_CONFLICT_CODE="VERSION_CONFLICT";te.UPDATE_NO_ETAG_CODE="ARTIFACT_UPDATE_NO_ETAG";function CP(e,t){return{query:`?$select=${encodeURIComponent(e)}`,options:{headers:{...t??{},Prefer:"return=representation"}}}}te.echoWrite=CP;function SP(e,t,r){if(!e)throw new pi.SdkError(te.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}te.requireEtag=SP;function EP(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}te.readEtag=EP;function Ac(e,t){var r;let n=e.body;if(n&&typeof n[t]=="string")return(0,Fa.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,Fa.normalizeGuid)(o[1],t)}return null}te.readCreatedId=Ac;function NP(e,t,r){return r?{...e,[t]:(0,Fa.normalizeGuid)(r,t)}:e}te.withClientMintedId=NP;function DP(e,t,r){let n=Ac(e,t);if(!n)throw new pi.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`);return n}te.requireCreatedId=DP;function IP(e,t,r,n){let i=Ac(e,t);if(i)return i;if(n)return(0,Fa.normalizeGuid)(n,t);throw new pi.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`)}te.resolveCreatedId=IP;function bg(e,t){if(e.status===412)throw new pi.SdkError(te.VERSION_CONFLICT_CODE,`Version conflict (412) from ${t}`);if(e.status<200||e.status>=300)throw new pi.ConnectionError(t,e.status,_P(e.body),e.body);return e}te.ensureSuccess=bg;function _P(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 PP(e,t,r,n){let i=(0,Fa.normalizeGuid)(r,"id"),a=`/${t}(${i})`;bg(await e.delete(a,n?{headers:{"If-Match":n}}:void 0),e.apiUrl(a))}te.deleteRecord=PP;function TP(e){return e instanceof pi.ConnectionError&&e.statusCode===404}te.isAlreadyDeleted=TP;function OP(){return new Date().toISOString()}te.nowIso=OP});var Kt=g(fi=>{"use strict";Object.defineProperty(fi,"__esModule",{value:!0});fi.describeMalformedValue=fi.collectPages=void 0;var wg=ye(),Cc=ie();async function RP(e,t,r){let n=[],i=new Set,a=e.apiUrl(t),o=(0,wg.ensureSuccess)(await e.get(t),a);for(;;){let s=o.body,l=s?.value;if(!Array.isArray(l))throw new Cc.ConnectionError(a,o.status,`${r}: paginated read returned a malformed page \u2014 expected an OData 'value' array but got ${Sc(l)}; refusing to return partial results.`);for(let c of l)n.push(c);let u=s?.["@odata.nextLink"];if(u==null)break;if(typeof u!="string"||u.length===0)throw new Cc.ConnectionError(a,o.status,`${r}: paginated read returned a malformed @odata.nextLink (${Sc(u)}); cannot follow it, and refusing to return partial results.`);if(i.has(u))throw new Cc.InvalidArgumentError(`${r}: aborting pagination \u2014 the server returned a repeated @odata.nextLink ('${u}'), which would loop indefinitely.`);i.add(u),a=u,o=(0,wg.ensureSuccess)(await e.getAbsolute(u),u)}return n}fi.collectPages=RP;function Sc(e){return e===null?"null":e===void 0?"undefined (missing)":`a ${typeof e}`}fi.describeMalformedValue=Sc});var Ec=g(lr=>{"use strict";Object.defineProperty(lr,"__esModule",{value:!0});lr.businessRuleApi=lr.BUSINESS_RULE_LEFT_DEACTIVATED_CODE=lr.WFOM_API_UNAVAILABLE_CODE=void 0;var xr=Mn(),FP=Kt(),Ze=ye(),an=ee(),ms=ie();lr.WFOM_API_UNAVAILABLE_CODE="BUSINESS_RULE_API_UNAVAILABLE";lr.BUSINESS_RULE_LEFT_DEACTIVATED_CODE="BUSINESS_RULE_LEFT_DEACTIVATED";async function Ag(e,t,r,n){let i=`/workflows(${kP})/Microsoft.Dynamics.CRM.${t}`;try{return(0,Ze.ensureSuccess)(await e.post(i,{Entity:r.Entity,WfomJson:r.WfomJson},{headers:n}),e.apiUrl(i))}catch(a){throw a?.statusCode!==404?a:new ms.SdkError(lr.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 xP(e,t){let r=`/workflows(${t})${(0,an.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,Ze.readEtag)(n),statecode:typeof i?.statecode=="number"?i.statecode:null,statuscode:typeof i?.statuscode=="number"?i.statuscode:null}}catch{return null}}async function LP(e,t,r){let n=await xP(e,t);if(n===null||n.etag===null)throw new ms.SdkError(Ze.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 ms.SdkError(Ze.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 kP="00000000-0000-0000-0000-000000000000",fs={"Content-Type":"application/json",Accept:"application/json","OData-Version":"4.0","OData-MaxVersion":"4.0"},MP="workflowid,name,description,primaryentity,statecode,category,type",UP="category eq 2 and type eq 1";async function Cg(e,t,r){var n;if(r==="Draft")return null;let i=(0,an.normalizeGuid)(t,"workflowid"),a=r==="Active",o={statecode:a?xr.StateCode.Activated:xr.StateCode.Draft,statuscode:a?xr.StatusCode.Activated:xr.StatusCode.Draft},s=`/workflows(${i})`,l=(0,Ze.ensureSuccess)(await e.patch(s,o,{headers:fs}),e.apiUrl(s));return(n=(0,Ze.readEtag)(l))!==null&&n!==void 0?n:await xa(e,i)}async function xa(e,t){let r=`/workflows(${t})${(0,an.odataQuery)([["$select","workflowid"]])}`;try{let n=await e.get(r);return n.status>=200&&n.status<300?(0,Ze.readEtag)(n):null}catch{return null}}async function BP(e,t,r){let n=await xa(e,t),i=await r(),a=(0,Ze.readEtag)(i);if(a)return{response:i,etag:a};let o=await xa(e,t);return{response:i,etag:n!==null&&n===o?o:null}}lr.businessRuleApi={async get(e,t){let r=(0,an.normalizeGuid)(t,"id"),n=`/workflows(${r})/Microsoft.Dynamics.CRM.RetrieveProcessWithWfomJson`,{response:i,etag:a}=await BP(e,r,async()=>(0,Ze.ensureSuccess)(await e.get(n),e.apiUrl(n)));return{raw:i.body,etag:a}},async list(e,t){let r=[UP];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,an.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,an.odataQuery)([["$select",MP],["$filter",r.join(" and ")]])}`;return(await(0,FP.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,an.normalizeGuid)(n.Entity.workflowid,"workflowid"),a=await Ag(e,"CreateProcessWithWfomJson",n,fs),o=(0,Ze.resolveCreatedId)(a,"workflowid","business rule",i),s=null;try{s=await Cg(e,o,n.status)}catch(l){try{await(0,Ze.deleteRecord)(e,"workflows",o)}catch{}throw l}return{id:o,etag:(r=s??(0,Ze.readEtag)(a))!==null&&r!==void 0?r:await xa(e,o)}},async update(e,t,r,n){var i,a;let o=r,s=(0,an.normalizeGuid)(t,"id"),l=`/workflows(${s})`,u={...fs,"If-Match":(0,Ze.requireEtag)(n,"business rule",s)},c=await LP(e,s,u["If-Match"]),d=c.statecode===xr.StateCode.Activated;d&&(0,Ze.ensureSuccess)(await e.patch(l,{statecode:xr.StateCode.Draft,statuscode:xr.StatusCode.Draft},{headers:u}),e.apiUrl(l));let p;try{p=await Ag(e,"UpdateProcessWithWfomJson",o,u)}catch(h){if(d)try{(0,Ze.ensureSuccess)(await e.patch(l,{statecode:xr.StateCode.Activated,statuscode:(i=c.statuscode)!==null&&i!==void 0?i:xr.StatusCode.Activated},{headers:fs}),e.apiUrl(l))}catch(w){throw new ms.SdkError(lr.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: ${h instanceof Error?h.message:String(h)}. Restore failure: ${w instanceof Error?w.message:String(w)}`)}throw h}let m=await Cg(e,s,o.status);return{id:s,etag:(a=m??(0,Ze.readEtag)(p))!==null&&a!==void 0?a:await xa(e,s)}},delete(e,t){return(0,Ze.deleteRecord)(e,"workflows",t)}}});var Sg=g(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});Nc.default="ffffffff-ffff-ffff-ffff-ffffffffffff"});var Eg=g(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});Dc.default="00000000-0000-0000-0000-000000000000"});var Ng=g(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});Ic.default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i});var La=g(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});var $P=Ng();function qP(e){return typeof e=="string"&&$P.default.test(e)}_c.default=qP});var ka=g(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});var VP=La();function GP(e){if(!(0,VP.default)(e))throw TypeError("Invalid UUID");let t;return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,t&255,(t=parseInt(e.slice(9,13),16))>>>8,t&255,(t=parseInt(e.slice(14,18),16))>>>8,t&255,(t=parseInt(e.slice(19,23),16))>>>8,t&255,(t=parseInt(e.slice(24,36),16))/1099511627776&255,t/4294967296&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255)}Pc.default=GP});var Lr=g(Ma=>{"use strict";Object.defineProperty(Ma,"__esModule",{value:!0});Ma.unsafeStringify=void 0;var zP=La(),et=[];for(let e=0;e<256;++e)et.push((e+256).toString(16).slice(1));function Dg(e,t=0){return(et[e[t+0]]+et[e[t+1]]+et[e[t+2]]+et[e[t+3]]+"-"+et[e[t+4]]+et[e[t+5]]+"-"+et[e[t+6]]+et[e[t+7]]+"-"+et[e[t+8]]+et[e[t+9]]+"-"+et[e[t+10]]+et[e[t+11]]+et[e[t+12]]+et[e[t+13]]+et[e[t+14]]+et[e[t+15]]).toLowerCase()}Ma.unsafeStringify=Dg;function WP(e,t=0){let r=Dg(e,t);if(!(0,zP.default)(r))throw TypeError("Stringified UUID is invalid");return r}Ma.default=WP});var vs=g(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});var jP=require("crypto"),gs=new Uint8Array(256),hs=gs.length;function HP(){return hs>gs.length-16&&((0,jP.randomFillSync)(gs),hs=0),gs.slice(hs,hs+=16)}Tc.default=HP});var Oc=g(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});Ba.updateV1State=void 0;var Ig=vs(),JP=Lr(),Ua={};function QP(e,t,r){let n,i=e?._v6??!1;if(e){let a=Object.keys(e);a.length===1&&a[0]==="_v6"&&(e=void 0)}if(e)n=_g(e.random??e.rng?.()??(0,Ig.default)(),e.msecs,e.nsecs,e.clockseq,e.node,t,r);else{let a=Date.now(),o=(0,Ig.default)();Pg(Ua,a,o),n=_g(o,Ua.msecs,Ua.nsecs,i?void 0:Ua.clockseq,i?void 0:Ua.node,t,r)}return t??(0,JP.unsafeStringify)(n)}function Pg(e,t,r){return e.msecs??=-1/0,e.nsecs??=0,t===e.msecs?(e.nsecs++,e.nsecs>=1e4&&(e.node=void 0,e.nsecs=0)):t>e.msecs?e.nsecs=0:t<e.msecs&&(e.node=void 0),e.node||(e.node=r.slice(10,16),e.node[0]|=1,e.clockseq=(r[8]<<8|r[9])&16383),e.msecs=t,e}Ba.updateV1State=Pg;function _g(e,t,r,n,i,a,o=0){if(e.length<16)throw new Error("Random bytes length must be >= 16");if(!a)a=new Uint8Array(16),o=0;else if(o<0||o+16>a.length)throw new RangeError(`UUID byte range ${o}:${o+15} is out of buffer bounds`);t??=Date.now(),r??=0,n??=(e[8]<<8|e[9])&16383,i??=e.slice(10,16),t+=122192928e5;let s=((t&268435455)*1e4+r)%4294967296;a[o++]=s>>>24&255,a[o++]=s>>>16&255,a[o++]=s>>>8&255,a[o++]=s&255;let l=t/4294967296*1e4&268435455;a[o++]=l>>>8&255,a[o++]=l&255,a[o++]=l>>>24&15|16,a[o++]=l>>>16&255,a[o++]=n>>>8|128,a[o++]=n&255;for(let u=0;u<6;++u)a[o++]=i[u];return a}Ba.default=QP});var Fc=g(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});var XP=ka(),KP=Lr();function YP(e){let t=typeof e=="string"?(0,XP.default)(e):e,r=ZP(t);return typeof e=="string"?(0,KP.unsafeStringify)(r):r}Rc.default=YP;function ZP(e){return Uint8Array.of((e[6]&15)<<4|e[7]>>4&15,(e[7]&15)<<4|(e[4]&240)>>4,(e[4]&15)<<4|(e[5]&240)>>4,(e[5]&15)<<4|(e[0]&240)>>4,(e[0]&15)<<4|(e[1]&240)>>4,(e[1]&15)<<4|(e[2]&240)>>4,96|e[2]&15,e[3],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}});var Tg=g(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});var eT=require("crypto");function tT(e){return Array.isArray(e)?e=Buffer.from(e):typeof e=="string"&&(e=Buffer.from(e,"utf8")),(0,eT.createHash)("md5").update(e).digest()}xc.default=tT});var $a=g(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});kr.URL=kr.DNS=kr.stringToBytes=void 0;var Og=ka(),rT=Lr();function Rg(e){e=unescape(encodeURIComponent(e));let t=new Uint8Array(e.length);for(let r=0;r<e.length;++r)t[r]=e.charCodeAt(r);return t}kr.stringToBytes=Rg;kr.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8";kr.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function nT(e,t,r,n,i,a){let o=typeof r=="string"?Rg(r):r,s=typeof n=="string"?(0,Og.default)(n):n;if(typeof n=="string"&&(n=(0,Og.default)(n)),n?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let l=new Uint8Array(16+o.length);if(l.set(s),l.set(o,s.length),l=t(l),l[6]=l[6]&15|e,l[8]=l[8]&63|128,i){if(a=a||0,a<0||a+16>i.length)throw new RangeError(`UUID byte range ${a}:${a+15} is out of buffer bounds`);for(let u=0;u<16;++u)i[a+u]=l[u];return i}return(0,rT.unsafeStringify)(l)}kr.default=nT});var xg=g(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.URL=Un.DNS=void 0;var iT=Tg(),Lc=$a(),Fg=$a();Object.defineProperty(Un,"DNS",{enumerable:!0,get:function(){return Fg.DNS}});Object.defineProperty(Un,"URL",{enumerable:!0,get:function(){return Fg.URL}});function kc(e,t,r,n){return(0,Lc.default)(48,iT.default,e,t,r,n)}kc.DNS=Lc.DNS;kc.URL=Lc.URL;Un.default=kc});var Lg=g(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});var aT=require("crypto");Mc.default={randomUUID:aT.randomUUID}});var Mg=g(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});var kg=Lg(),oT=vs(),sT=Lr();function lT(e,t,r){if(kg.default.randomUUID&&!t&&!e)return kg.default.randomUUID();e=e||{};let n=e.random??e.rng?.()??(0,oT.default)();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(0,sT.unsafeStringify)(n)}Uc.default=lT});var Ug=g(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});var uT=require("crypto");function cT(e){return Array.isArray(e)?e=Buffer.from(e):typeof e=="string"&&(e=Buffer.from(e,"utf8")),(0,uT.createHash)("sha1").update(e).digest()}Bc.default=cT});var $g=g(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.URL=Bn.DNS=void 0;var dT=Ug(),$c=$a(),Bg=$a();Object.defineProperty(Bn,"DNS",{enumerable:!0,get:function(){return Bg.DNS}});Object.defineProperty(Bn,"URL",{enumerable:!0,get:function(){return Bg.URL}});function qc(e,t,r,n){return(0,$c.default)(80,dT.default,e,t,r,n)}qc.DNS=$c.DNS;qc.URL=$c.URL;Bn.default=qc});var qg=g(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});var pT=Lr(),fT=Oc(),mT=Fc();function hT(e,t,r){e??={},r??=0;let n=(0,fT.default)({...e,_v6:!0},new Uint8Array(16));if(n=(0,mT.default)(n),t){if(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(0,pT.unsafeStringify)(n)}Vc.default=hT});var Vg=g(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});var gT=ka(),vT=Lr();function yT(e){let t=typeof e=="string"?(0,gT.default)(e):e,r=bT(t);return typeof e=="string"?(0,vT.unsafeStringify)(r):r}Gc.default=yT;function bT(e){return Uint8Array.of((e[3]&15)<<4|e[4]>>4&15,(e[4]&15)<<4|(e[5]&240)>>4,(e[5]&15)<<4|e[6]&15,e[7],(e[1]&15)<<4|(e[2]&240)>>4,(e[2]&15)<<4|(e[3]&240)>>4,16|(e[0]&240)>>4,(e[0]&15)<<4|(e[1]&240)>>4,e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}});var jg=g(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});qa.updateV7State=void 0;var Gg=vs(),wT=Lr(),zc={};function AT(e,t,r){let n;if(e)n=zg(e.random??e.rng?.()??(0,Gg.default)(),e.msecs,e.seq,t,r);else{let i=Date.now(),a=(0,Gg.default)();Wg(zc,i,a),n=zg(a,zc.msecs,zc.seq,t,r)}return t??(0,wT.unsafeStringify)(n)}function Wg(e,t,r){return e.msecs??=-1/0,e.seq??=0,t>e.msecs?(e.seq=r[6]<<23|r[7]<<16|r[8]<<8|r[9],e.msecs=t):(e.seq=e.seq+1|0,e.seq===0&&e.msecs++),e}qa.updateV7State=Wg;function zg(e,t,r,n,i=0){if(e.length<16)throw new Error("Random bytes length must be >= 16");if(!n)n=new Uint8Array(16),i=0;else if(i<0||i+16>n.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);return t??=Date.now(),r??=e[6]*127<<24|e[7]<<16|e[8]<<8|e[9],n[i++]=t/1099511627776&255,n[i++]=t/4294967296&255,n[i++]=t/16777216&255,n[i++]=t/65536&255,n[i++]=t/256&255,n[i++]=t&255,n[i++]=112|r>>>28&15,n[i++]=r>>>20&255,n[i++]=128|r>>>14&63,n[i++]=r>>>6&255,n[i++]=r<<2&255|e[10]&3,n[i++]=e[11],n[i++]=e[12],n[i++]=e[13],n[i++]=e[14],n[i++]=e[15],n}qa.default=AT});var Hg=g(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});var CT=La();function ST(e){if(!(0,CT.default)(e))throw TypeError("Invalid UUID");return parseInt(e.slice(14,15),16)}Wc.default=ST});var ys=g(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.version=re.validate=re.v7=re.v6ToV1=re.v6=re.v5=re.v4=re.v3=re.v1ToV6=re.v1=re.stringify=re.parse=re.NIL=re.MAX=void 0;var ET=Sg();Object.defineProperty(re,"MAX",{enumerable:!0,get:function(){return ET.default}});var NT=Eg();Object.defineProperty(re,"NIL",{enumerable:!0,get:function(){return NT.default}});var DT=ka();Object.defineProperty(re,"parse",{enumerable:!0,get:function(){return DT.default}});var IT=Lr();Object.defineProperty(re,"stringify",{enumerable:!0,get:function(){return IT.default}});var _T=Oc();Object.defineProperty(re,"v1",{enumerable:!0,get:function(){return _T.default}});var PT=Fc();Object.defineProperty(re,"v1ToV6",{enumerable:!0,get:function(){return PT.default}});var TT=xg();Object.defineProperty(re,"v3",{enumerable:!0,get:function(){return TT.default}});var OT=Mg();Object.defineProperty(re,"v4",{enumerable:!0,get:function(){return OT.default}});var RT=$g();Object.defineProperty(re,"v5",{enumerable:!0,get:function(){return RT.default}});var FT=qg();Object.defineProperty(re,"v6",{enumerable:!0,get:function(){return FT.default}});var xT=Vg();Object.defineProperty(re,"v6ToV1",{enumerable:!0,get:function(){return xT.default}});var LT=jg();Object.defineProperty(re,"v7",{enumerable:!0,get:function(){return LT.default}});var kT=La();Object.defineProperty(re,"validate",{enumerable:!0,get:function(){return kT.default}});var MT=Hg();Object.defineProperty(re,"version",{enumerable:!0,get:function(){return MT.default}})});function bs(e,t){return e==="SetFieldValue"&&t!==void 0&&UT.has(t.attributeType)&&(t.requiredLevel==="None"||t.requiredLevel==="Recommended")}var UT,jc=I(()=>{"use strict";UT=new Set(["Integer","Double","Decimal","Money","String","Memo","DateTime","Picklist","Lookup"])});function Jg(e){return e!=="Entity"&&e!=="AllForms"&&typeof e=="string"&&e.trim()!==""}function Hc(e){return Jg(e)?1:2}function Jc(e){return Jg(e)?e:void 0}function Qg(e,t){let r=Jc(e.scope);return{"@odata.type":"#Microsoft.Dynamics.CRM.workflow",name:e.name,description:e.description,workflowid:t,ondemand:!1,subprocess:!1,triggeroncreate:!1,triggerondelete:!1,category:mi.WorkflowCategory.BusinessRule,type:mi.WorkflowTypeCode.Definition,mode:1,scope:mi.WorkflowScope.Organization,primaryentity:e.entityLogicalName,iscrmuiworkflow:!0,processtriggerscope:Hc(e.scope),...r!==void 0?{processtriggerformid:r}:{}}}var mi,Xg=I(()=>{"use strict";mi=se(Mn());});function Kg(e,t=0){return(tt[e[t+0]]+tt[e[t+1]]+tt[e[t+2]]+tt[e[t+3]]+"-"+tt[e[t+4]]+tt[e[t+5]]+"-"+tt[e[t+6]]+tt[e[t+7]]+"-"+tt[e[t+8]]+tt[e[t+9]]+"-"+tt[e[t+10]]+tt[e[t+11]]+tt[e[t+12]]+tt[e[t+13]]+tt[e[t+14]]+tt[e[t+15]]).toLowerCase()}var tt,Yg=I(()=>{tt=[];for(let e=0;e<256;++e)tt.push((e+256).toString(16).slice(1))});function Qc(){return ws>As.length-16&&((0,Zg.randomFillSync)(As),ws=0),As.slice(ws,ws+=16)}var Zg,As,ws,e0=I(()=>{Zg=require("crypto"),As=new Uint8Array(256),ws=As.length});var t0,Xc,r0=I(()=>{t0=require("crypto"),Xc={randomUUID:t0.randomUUID}});function BT(e,t,r){if(Xc.randomUUID&&!t&&!e)return Xc.randomUUID();e=e||{};let n=e.random??e.rng?.()??Qc();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 Kg(n)}var ct,n0=I(()=>{r0();e0();Yg();ct=BT});var Kc=I(()=>{n0()});var i0=I(()=>{"use strict";});var Yc=g(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.WorkflowConditionOperator=xt.WorkflowAttributeType=xt.SystemStep=xt.FieldRequiredLevelTypes=xt.AttributeDateTimeBehavior=void 0;xt.AttributeDateTimeBehavior={None:0,Dynamic:1,DateOnly:2,StaticTimeZoneInvariant:3,UserLocal:4};xt.FieldRequiredLevelTypes={None:"0",Required:"1",Recommended:"2"};xt.SystemStep={IdentifyContact:"IdentifyContact",IdentifyAccount:"IdentifyAccount",IdentifyCustomer:"IdentifyCustomer",IdentifyCase:"IdentifyCase",Solution:"Solution",Resolve:"Resolve"};xt.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"};xt.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 l0(e){switch(e){case"Boolean":return pe.WorkflowAttributeType.Boolean;case"Customer":return pe.WorkflowAttributeType.Customer;case"DateTime":return pe.WorkflowAttributeType.DateTime;case"Decimal":return pe.WorkflowAttributeType.Decimal;case"Double":return pe.WorkflowAttributeType.Float;case"Integer":return pe.WorkflowAttributeType.Integer;case"Lookup":return pe.WorkflowAttributeType.Lookup;case"Money":return pe.WorkflowAttributeType.Money;case"Owner":return pe.WorkflowAttributeType.Owner;case"Picklist":return pe.WorkflowAttributeType.Picklist;case"State":return pe.WorkflowAttributeType.State;case"Status":return pe.WorkflowAttributeType.Status;case"Uniqueidentifier":case"UniqueIdentifier":return pe.WorkflowAttributeType.UniqueIdentifier;case"BigInt":return pe.WorkflowAttributeType.BigType;default:return pe.WorkflowAttributeType.String}}function h0(e){return e&&e!==pe.WorkflowAttributeType.String?e:void 0}function VT(e){return{__class:m0,parameterName:"primaryEntity",entityName:e}}function a0(e){return{__class:ed,type:Zc,typeSet:!1,behavior:pe.AttributeDateTimeBehavior.None,method:u0,parameters:[e]}}function o0(e,t,r=pe.WorkflowAttributeType.String){return{__class:d0,type:r,behavior:pe.AttributeDateTimeBehavior.None,typeSet:!1,entity:VT(t),attributeName:e}}function GT(e,t=pe.WorkflowAttributeType.String){return{__class:p0,type:t,behavior:pe.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function zT(e){return{__class:f0,type:Zc,typeSet:!1,behavior:pe.AttributeDateTimeBehavior.None,days:e,hours:"0",minutes:"0",months:"0",years:"0"}}function g0(e,t){let r=$T[e.operator],n=a0(o0(e.leftField,t,e.leftWorkflowType)),i;e.dateArithmetic?i=zT(e.right.value??"0"):e.right.kind==="field"?i=o0(e.right.field??"",t,e.right.workflowType):i=GT(e.right.value??"",e.right.workflowType??e.leftWorkflowType);let a=a0(i);return{__class:ed,type:Zc,typeSet:!1,behavior:pe.AttributeDateTimeBehavior.None,method:c0,parameters:[r,n,a]}}function v0(e){return typeof e=="object"&&e.__class===ed}function WT(e){return typeof e=="object"&&e.__class===f0}function Cs(e){return v0(e)&&e.method===u0&&e.parameters.length>0?Cs(e.parameters[0]):e}function s0(e){if(typeof e!="object"||e.__class!==d0)return null;let t=e.entity;if(t&&t.__class&&t.__class!==m0)return null;let r=e.attributeName;return r?{field:r,workflowType:h0(e.type)}:null}function y0(e){if(!e)return null;let t=Cs(e);if(!v0(t)||t.method!==c0||t.parameters.length!==3)return null;let r=t.parameters[0],n=qT[String(r)];if(!n)return null;let i=s0(Cs(t.parameters[1]));if(!i)return null;let a=Cs(t.parameters[2]);if(WT(a))return n!=="+"&&n!=="-"?null:{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:String(a.days??"")},dateArithmetic:!0};let o=s0(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===p0){let s=a.primitiveValue;return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:s!=null?String(s):"",workflowType:h0(a.type)}}}return null}function hi(e){return!e||!e.leftField?!1:e.right.kind==="field"?!!(e.right.field&&e.right.field.trim()):!!(e.right.value&&e.right.value.trim())}var pe,u0,c0,Zc,d0,p0,ed,f0,m0,$T,qT,Ss=I(()=>{"use strict";pe=se(Yc());u0="0",c0="3",Zc="0",d0="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",p0="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",ed="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",f0="TimeSpanExpression:#Microsoft.Crm.Workflow.Expressions",m0="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions";$T={"+":0,"-":1,"*":2,"/":3},qT={0:"+",1:"-",2:"*",3:"/"}});function b0(e){return e.__class==="BinaryExpression:#Microsoft.Crm.Workflow.Expressions"}function jT(e){return e.__class==="ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel"}function Va(){return{list:[]}}function w0(e,t,r){return e&&e.list.length>0?{list:[{...e.list[0],description:t},...e.list.slice(1)]}:{list:[{labelId:ct(),languageCode:r,description:t}]}}function id(e){return{__class:"PrimaryEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:"primaryEntity",entityName:e}}function ad(e,t,r){return{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,entity:id(t),attributeName:e}}function Ga(e,t){return{__class:"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",type:t,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function I0(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:Ga(e.id.replace(/[{}]/g,""),z.WorkflowAttributeType.UniqueIdentifier)}}function A0(e,t){let r=e.valueType==="Lookup"?e.lookupValue?.workflowType??z.WorkflowAttributeType.Lookup:e.valueType==="Clear"?e.valueWorkflowType??z.WorkflowAttributeType.String:z.WorkflowAttributeType.String,n=nd[e.operator]??z.WorkflowConditionOperator.Equal,i=ad(e.field,t,r),a;if(e.operator==="ContainsData"||e.operator==="DoesNotContainData")a=[];else if(e.valueType==="Field"&&e.valueField)a=[ad(e.valueField,t,r)];else if(e.valueType==="Lookup"){if(!e.lookupValue)throw new Error("Lookup condition is missing its record value.");a=[I0(e.lookupValue)]}else e.valueType==="Clear"?a=[Ga(null,r)]:e.valueType==="Expression"?a=[Ns(e.valueType,e.value,e.valueField,t,e.expression,e.rawExpression)]:a=[Ga(e.value??"",r)];return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:i,right:a}}function HT(e,t,r){if(e.length===0)return null;if(e.length===1)return A0(e[0],r);let n=t==="AND"?z.WorkflowConditionOperator.LogicalAnd:z.WorkflowConditionOperator.LogicalOr,[i,...a]=e.map(o=>A0(o,r));return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.String,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:i,right:a}}function Es(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=y0(e);return t?{valueType:"Expression",expression:t}:{valueType:"Expression",rawExpression:e}}return{valueType:"Value",value:""}}function td(e){let t=D0[e.conditionOperatoroperator]??"Equals",r=e.left.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions"?e.left.attributeName:"",i=t==="ContainsData"||t==="DoesNotContainData"?{valueType:"Value"}:Es(e.right[0]);return{id:ct(),field:r,fieldDisplayName:r,operator:t,...i}}function C0(e){if(!e||e.__class!=="BinaryExpression:#Microsoft.Crm.Workflow.Expressions")return{clauses:[],logic:"AND"};let t=e.conditionOperatoroperator;if(t===z.WorkflowConditionOperator.LogicalAnd||t===z.WorkflowConditionOperator.LogicalOr){let r=t===z.WorkflowConditionOperator.LogicalAnd?"AND":"OR";return{clauses:[...b0(e.left)?[td(e.left)]:[],...e.right.filter(b0).map(td)],logic:r}}return{clauses:[td(e)],logic:"AND"}}function Ns(e,t,r,n,i,a,o,s){if(e==="Field"&&r)return ad(r,n,z.WorkflowAttributeType.String);if(e==="Expression"){if(i)return g0(i,n);if(a!=null)return a}return e==="Lookup"&&o?I0(o):e==="Clear"?Ga(null,s??z.WorkflowAttributeType.String):Ga(t??"",z.WorkflowAttributeType.String)}function rd(e,t){return{propertyName:e,propertyValueExpr:t}}function gi(e){return`Step_${e.value++}`}function Lt(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 S0(e,t,r){return e&&!r.used.has(e)?(r.used.add(e),e):Lt(t,r)}function JT(e){return e===N0.StateCode.Activated?"Active":"Draft"}function QT(e,t){let r=e.processtriggerscope,n=e.processtriggerformid;return r===1&&n?n:r===2?"Entity":t??"Entity"}function _0(e,t=1033){return new vi({languageCode:t}).serialize(e)}function P0(e){return new vi().deserialize(e)}var N0,z,nd,D0,od,vi,sd=I(()=>{"use strict";Kc();N0=se(Mn());i0();Ss();z=se(Yc());nd={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},D0={};for(let e of Object.keys(nd))D0[nd[e]]=e;od={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"};vi=class{resolveLabel;languageCode;entityName="";stepCounter={value:0};idCounter={counts:{},used:new Set};constructor(t={}){this.resolveLabel=t.resolveLabel??(r=>od[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={__class:"WorkflowStep:#Microsoft.Crm.Workflow.ObjectModel",id:r?.id??t.ruleId??ct(),name:r?.name??"Step_0",description:r!==void 0?r.description:t.description||null,stepLabels:Va(),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:Lt("SetAttributeValueStep",this.idCounter),description:t.displayName||"New Action",name:t.stepName??gi(this.stepCounter),stepLabels:{list:[]},specification:rd(t.field,Ns(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType)),entity:id(this.entityName)}}makeRecommendationActionStep(t,r,n){let i=r.map(l=>this.makeApplyActionStep(l)),a=t??"",o=n?.stepLabels,s=w0(o,a,this.languageCode);return{__class:"ActionStep:#Microsoft.Crm.Workflow.ObjectModel",id:S0(n?.id,"ActionStep",this.idCounter),name:n?.name??gi(this.stepCounter),description:n?.description??"Action step",stepLabels:s,steps:{list:i},actionId:null,actionType:n?.actionType??"4",processId:n?.processId??ct(),uniqueName:n?.uniqueName??`id_${ct().replace(/-/g,"")}ActionStep`}}serializeAction(t){let r=id(this.entityName),n=t.stepName??gi(this.stepCounter),i=t.stepLabels??Va(),a={name:n,stepLabels:i,description:t.displayName},o=t.type;switch(o){case"SetFieldValue":return{...a,id:Lt("SetAttributeValueStep",this.idCounter),__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:rd(t.field,Ns(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"SetDefaultValue":return{...a,id:Lt("SetDefaultValueStep",this.idCounter),__class:"SetDefaultValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:rd(t.field,Ns(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"LockUnlock":return{...a,id:Lt("SetDisplayModeStep",this.idCounter),__class:"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isReadOnly:t.lock,entity:r};case"SetBusinessRequired":return{...a,id:Lt("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:Lt("SetVisibilityStep",this.idCounter),__class:"SetVisibilityStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isVisible:t.visible,entity:r};case"ShowErrorMessage":{let s=t.errorMessage||t.displayName,l=t.stepLabels&&t.stepLabels.list.length>0?t.stepLabels:{list:[{labelId:ct(),languageCode:this.languageCode,description:s}]};return{...a,id:Lt("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=w0(t.stepLabels,s,this.languageCode),u={list:[this.makeRecommendationActionStep(t.acceptanceText,t.applyActions??[],t.recommendationActionStepMeta)]};return{...a,id:Lt("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??gi(this.stepCounter),n=Lt("ConditionStep",this.idCounter),i=[],a=t,o=!0;for(;a;){let s=HT(a.clauses,a.logic,this.entityName),l=o?a.branchName??gi(this.stepCounter):gi(this.stepCounter),c={__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:o?S0(a.branchId,"ConditionBranchStep",this.idCounter):Lt("ConditionBranchStep",this.idCounter),name:l,description:a.displayName,stepLabels:Va(),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:Va(),containsElsebranch:i.length>1,steps:{list:i}}}makeTerminalElseBranch(t){return{__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:Lt("ConditionBranchStep",this.idCounter),name:"Else",description:null,stepLabels:Va(),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??ct():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};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:QT(r,i?.formId),status:JT(t.statecode),rootCondition:n,wfomRoot:i}}deserializeConditionStep(t){let r=(t.steps?.list??[]).filter(jT);return this.buildConditionNodeFromBranches(r,t,!0)}buildConditionNodeFromBranches(t,r,n){let[i,...a]=t,{clauses:o,logic:s}=C0(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)??ct(),displayName:c,clauses:o,logic:s,trueBranch:l,falseBranch:u,isCollapsed:!1,stepName:n?r.name:void 0,branchId:n?i?.id:void 0,branchName:n?i?.name:void 0}}deserializeElseChain(t,r){if(t.length===0)return[];let[n]=t,{clauses:i}=C0(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||ct(),field:u?.propertyName??"",stepName:l.name??void 0,displayName:l.description??void 0,...Es(u?.propertyValueExpr)}}),meta:i,acceptanceText:o}}deserializeAction(t){switch(t.__class){case"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=Es(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=Es(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}}}});function on(e){return!XT.has(e)}function F0(e){return nO.has(e)}function Ds(e){return O0.has(e)?KT:tO.has(e)?YT:R0.has(e)?ZT:eO}function x0(e){return Ds(e)[0]}function L0(e,t){return Ds(t).includes(e)}function T0(e){return O0.has(e)?"string":e==="Money"?"money":e==="Integer"||e==="BigInt"?"integer":e==="Decimal"||e==="Double"?"decimal":R0.has(e)?"date":rO.has(e)?"boolean":"other"}function Is(e,t){let r=T0(e),n=T0(t);return r==="other"||n==="other"?e===t:r===n}var XT,KT,YT,ZT,eO,O0,tO,R0,rO,nO,ld=I(()=>{"use strict";XT=new Set(["ContainsData","DoesNotContainData"]);KT=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],YT=["Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],ZT=["On","NotOn","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],eO=["Equals","DoesNotEqual","ContainsData","DoesNotContainData"],O0=new Set(["String","Memo","EntityName"]),tO=new Set(["Integer","BigInt","Money","Decimal","Double"]),R0=new Set(["DateTime"]),rO=new Set(["Boolean"]),nO=new Set(["Equals","DoesNotEqual"])});function cd(e){return iO.has(e.type)}function ud(e,t,r,n,i,a,o){let s=i.get(r);!s||!aO.has(s.attributeType)||n!=="Value"||o?.operator&&!F0(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 k0(e,t,r,n,i,a,o,s){if(i!=="Clear")return;let l=a.get(n);bs(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 Ps(e){if(!e)return!1;for(let t of[...e.trueBranch,...e.falseBranch])if(t.kind==="action"){if(cd(t))return!0}else if(Ps(t))return!0;return!1}function dd(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=dd(r,t);if(n)return n}}return null}function yi(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=yi(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=yi(n,t);if(i)return i}}return null}function pd(e,t){return{...e,trueBranch:M0(e.trueBranch,t),falseBranch:M0(e.falseBranch,t)}}function M0(e,t){return e.filter(r=>r.id!==t).map(r=>r.kind==="condition"?pd(r,t):r)}function sn(e,t,r){return e.id===t?r(e):{...e,trueBranch:e.trueBranch.map(n=>n.kind==="condition"?sn(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="condition"?sn(n,t,r):n)}}function _s(e,t,r){return{...e,trueBranch:e.trueBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?_s(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?_s(n,t,r):n)}}function U0(e,t,r,n){return sn(e,t,i=>({...i,trueBranch:r==="true"?[...i.trueBranch,n]:i.trueBranch,falseBranch:r==="false"?[...i.falseBranch,n]:i.falseBranch}))}function oO(e){return e.length===1&&e[0].kind==="condition"}function B0(e,t,r){return sn(e,t,n=>$0(n,r))}function $0(e,t){if(oO(e.falseBranch))return{...e,falseBranch:[$0(e.falseBranch[0],t)]};let r=fd(t);return r.falseBranch=e.falseBranch,{...e,falseBranch:[r]}}function q0(e,t){let r=yi(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 sn(e,r.node.id,a=>({...a,falseBranch:i}))}function V0(e,t,r){let n=yi(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 sn(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 fd(e){return{kind:"condition",id:ct(),displayName:e??"New Condition",clauses:[],logic:"AND",trueBranch:[],falseBranch:[],isCollapsed:!1}}function G0(e,t){let r={kind:"action",id:ct(),type:e,displayName:t??`New ${e}`};switch(e){case"Recommendation":return{...r,type:"Recommendation",field:"",recommendationTitle:"",messageText:"",applyActions:[{id:ct(),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 z0(e){if(!e)return[];let t=[];return W0(e,t),[...new Set(t)]}function W0(e,t){e.clauses.forEach(r=>{r.field&&t.push(r.field)}),[...e.trueBranch,...e.falseBranch].forEach(r=>{r.kind==="condition"?W0(r,t):"field"in r&&r.field&&t.push(r.field)})}function j0(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 H0(e,r,n),Ps(e)||r.push({nodeId:"root",kind:"NO_ACTION",message:"A business rule must include at least one action step.",target:"node"}),r}function H0(e,t,r){e.clauses.length===0&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Add at least one clause to this condition.",target:"node",messageKey:"Validation.AddClause"}),e.clauses.forEach(n=>{if(!n.field)t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Please select a field for this clause.",target:"clauseField",itemId:n.id});else if(on(n.operator)&&n.valueType==="Value"&&!n.value)t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause.",target:"clauseValue",itemId:n.id});else if(on(n.operator)&&n.valueType==="Value"&&n.value){let i=r.get(n.field);i?.maxLength&&n.value.length>i.maxLength&&t.push({nodeId:e.id,kind:"CLAUSE_VALUE_TOO_LONG",message:`Value exceeds the field's maximum length of ${i.maxLength} characters.`,target:"clauseValue",itemId:n.id,messageParams:{maxLength:i.maxLength}})}else on(n.operator)&&n.valueType==="Expression"&&!n.rawExpression&&!hi(n.expression)&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please complete the formula for this clause.",target:"clauseValue",itemId:n.id,messageKey:"Validation.CompleteClauseFormula"});on(n.operator)&&n.valueType==="Lookup"&&(!n.lookupValue?.entityType||!n.lookupValue.id||!n.lookupValue.label)&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please select a lookup record for this clause.",target:"clauseValue",itemId:n.id,messageKey:"Validation.EmptyClauseLookupValue"}),on(n.operator)&&ud(e.id,"Condition",n.field,n.valueType,r,t,{operator:n.operator,target:"clauseValue",itemId:n.id})}),[...e.trueBranch,...e.falseBranch].forEach(n=>{if(n.kind==="condition")H0(n,t,r);else{if(!("field"in n)||!n.field)t.push({nodeId:n.id,kind:"EMPTY_ACTION_FIELD",message:`${n.type}: a target field is required.`,target:"actionField",messageParams:{actionType:n.type}});else if((n.type==="SetFieldValue"||n.type==="SetDefaultValue")&&(n.valueType??"Value")==="Value"&&!n.value?.trim())t.push({nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:`${n.type}: please provide a value.`,target:"actionValue",messageParams:{actionType:n.type}});else if((n.type==="SetFieldValue"||n.type==="SetDefaultValue")&&n.valueType==="Value"&&n.value){let i=r.get(n.field);i?.maxLength&&n.value.length>i.maxLength&&t.push({nodeId:n.id,kind:"ACTION_VALUE_TOO_LONG",message:`${n.type}: value exceeds the field's maximum length of ${i.maxLength} characters.`,target:"actionValue",messageParams:{actionType:n.type,maxLength:i.maxLength}})}else if((n.type==="SetFieldValue"||n.type==="SetDefaultValue")&&n.valueType==="Field"){if(!n.valueField)t.push({nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:`${n.type}: please select a field to copy from.`,target:"actionValue",messageKey:"Validation.SelectActionSourceField",messageParams:{actionType:n.type}});else if(r.size>0){let i=r.get(n.field),a=r.get(n.valueField);i&&a&&!Is(i.attributeType,a.attributeType)&&t.push({nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:`${n.type}: the source field's type is not compatible with the target field.`,target:"actionValue",messageKey:"Validation.IncompatibleActionSourceField",messageParams:{actionType:n.type}})}}else(n.type==="SetFieldValue"||n.type==="SetDefaultValue")&&n.valueType==="Expression"?!n.rawExpression&&!hi(n.expression)&&t.push({nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:`${n.type}: please complete the formula.`,target:"actionValue",messageKey:"Validation.CompleteActionFormula",messageParams:{actionType:n.type}}):(n.type==="SetFieldValue"||n.type==="SetDefaultValue")&&n.valueType==="Lookup"&&(!n.lookupValue?.entityType||!n.lookupValue.id||!n.lookupValue.label)&&t.push({nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:`${n.type}: please complete the lookup record.`,target:"actionValue",messageKey:"Validation.EmptyActionLookupValue",messageParams:{actionType:n.type}});if((n.type==="SetFieldValue"||n.type==="SetDefaultValue")&&n.field&&(ud(n.id,n.type,n.field,n.valueType,r,t,{target:"actionValue"}),k0(n.id,n.type,n.type,n.field,n.valueType,r,t,{target:"actionValue"})),n.type==="ShowErrorMessage"&&!n.errorMessage?.trim()&&t.push({nodeId:n.id,kind:"EMPTY_ACTION_MESSAGE",message:"Show error message: please enter an error message.",target:"actionMessage"}),n.type==="Recommendation"){let i=n.applyActions??[];n.recommendationTitle?.trim()||t.push({nodeId:n.id,kind:"EMPTY_RECOMMENDATION_TITLE",message:"Recommendation: please enter a recommendation title.",target:"recommendationTitle"}),n.messageText?.trim()||t.push({nodeId:n.id,kind:"EMPTY_RECOMMENDATION_MESSAGE",message:"Recommendation: please enter a recommendation message.",target:"recommendationMessage"}),i.length===0&&t.push({nodeId:n.id,kind:"RECOMMENDATION_NO_APPLY_ACTION",message:"Recommendation: add at least one action to apply.",target:"node"}),i.forEach(a=>{a.field?a.valueType==="Field"?a.valueField||t.push({nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please select a field to copy from.",target:"applyActionValue",itemId:a.id,messageKey:"Validation.RecommendationApplySourceField"}):a.valueType==="Expression"?!a.rawExpression&&!hi(a.expression)&&t.push({nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the formula.",target:"applyActionValue",itemId:a.id,messageKey:"Validation.RecommendationApplyFormula"}):a.valueType==="Lookup"?(!a.lookupValue?.entityType||!a.lookupValue.id||!a.lookupValue.label)&&t.push({nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the lookup record.",target:"applyActionValue",itemId:a.id,messageKey:"Validation.RecommendationApplyLookupValue"}):a.valueType==="Clear"||a.value?.trim()||t.push({nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please enter a value for each action to apply.",target:"applyActionValue",itemId:a.id,messageKey:"Validation.RecommendationApplyValue"}):t.push({nodeId:n.id,kind:"EMPTY_ACTION_FIELD",message:"Recommendation: a target field is required for each action to apply.",target:"applyActionField",itemId:a.id,messageKey:"Validation.RecommendationApplyField"}),a.field&&(ud(n.id,"Recommendation",a.field,a.valueType,r,t,{target:"applyActionValue",itemId:a.id}),k0(n.id,"Recommendation","SetFieldValue",a.field,a.valueType,r,t,{target:"applyActionValue",itemId:a.id}))})}}})}var iO,aO,md=I(()=>{"use strict";Kc();jc();ld();Ss();iO=new Set(["LockUnlock","ShowErrorMessage","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]);aO=new Set(["Lookup","Customer","Owner"])});var J0={};Rr(J0,{DEFAULT_DESERIALIZE_LABELS:()=>od,WorkflowJsonMapper:()=>vi,addElseIfInTree:()=>B0,appendToBranch:()=>U0,areFieldKindsCompatible:()=>Is,attributeTypeToWorkflowType:()=>l0,buildWorkflowEntity:()=>Qg,collectUsedFields:()=>z0,createEmptyAction:()=>G0,createEmptyCondition:()=>fd,deserializeWorkflowJson:()=>P0,findNode:()=>dd,findParent:()=>yi,getDefaultOperatorForFieldType:()=>x0,getOperatorsForFieldType:()=>Ds,hasAnyTriggerGeneratingAction:()=>Ps,isExpressionModelComplete:()=>hi,isOperatorCompatible:()=>L0,isTriggerGeneratingAction:()=>cd,moveBranchItemInTree:()=>V0,operatorNeedsValue:()=>on,processTriggerFormIdFromScope:()=>Jc,processTriggerScopeFromScope:()=>Hc,removeElseIfInTree:()=>q0,removeNodeFromTree:()=>pd,serializeToWorkflowJson:()=>_0,supportsClearForActionType:()=>bs,updateActionInTree:()=>_s,updateConditionInTree:()=>sn,validateBusinessRule:()=>j0});var Q0=I(()=>{"use strict";jc();Xg();sd();sd();md();md();ld();Ss();});var Yt=g(Ge=>{"use strict";Object.defineProperty(Ge,"__esModule",{value:!0});Ge.publishBoundEntity=Ge.boundEntityPublishScope=Ge.publishGenPageById=Ge.publishDashboardById=Ge.publishWebResourceById=Ge.publishEntity=Ge.publishAppModule=Ge.publishXml=void 0;var sO=ye(),za=ee(),X0="/PublishXml";async function bi(e,t){(0,sO.ensureSuccess)(await e.post(X0,{ParameterXml:t}),e.apiUrl(X0))}Ge.publishXml=bi;function lO(e,t){return bi(e,`<importexportxml><appmodules><appmodule>${(0,za.xmlText)(t)}</appmodule></appmodules></importexportxml>`)}Ge.publishAppModule=lO;function K0(e,t){return bi(e,`<importexportxml><entities><entity>${(0,za.xmlText)(t)}</entity></entities></importexportxml>`)}Ge.publishEntity=K0;function uO(e,t){return bi(e,`<importexportxml><webresources><webresource>${(0,za.xmlText)(t)}</webresource></webresources></importexportxml>`)}Ge.publishWebResourceById=uO;function cO(e,t){return bi(e,`<importexportxml><dashboards><dashboard>${(0,za.xmlText)(t)}</dashboard></dashboards></importexportxml>`)}Ge.publishDashboardById=cO;function dO(e,t){return bi(e,`<importexportxml><uxagentprojects><uxagentproject>${(0,za.xmlText)(t)}</uxagentproject></uxagentprojects></importexportxml>`)}Ge.publishGenPageById=dO;function pO(e){let t=e?.entityLogicalName;return t?{envelope:"entity",entityLogicalName:t,blastRadiusWarning:"ENTITY_ENVELOPE_ALSO_SHIPS_UNRELATED_UNPUBLISHED_CHANGES"}:{envelope:"entity"}}Ge.boundEntityPublishScope=pO;function fO(e,t){let r=t?.entityLogicalName;return r?K0(e,r):Promise.resolve()}Ge.publishBoundEntity=fO});var hd=g(Ts=>{"use strict";Object.defineProperty(Ts,"__esModule",{value:!0});Ts.cloneJson=void 0;function mO(e){return JSON.parse(JSON.stringify(e))}Ts.cloneJson=mO});var ur=g(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.childObjects=vt.optionalGuidId=vt.optionalEnum=vt.eachObject=vt.issue=vt.isJsonObject=void 0;function Y0(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}vt.isJsonObject=Y0;function Wa(e,t,r,n){return n?{pointer:e,rule:t,message:r,fatal:n}:{pointer:e,rule:t,message:r}}vt.issue=Wa;function Z0(e,t,r,n){if(!Array.isArray(e))return[];let i=[];return e.forEach((a,o)=>{Y0(a)?i.push({node:a,index:o}):n.push(Wa(`${t}/${o}`,`${r}-must-be-object`,`a ${r} must be a JSON object, got ${a===null?"null":typeof a}`))}),i}vt.eachObject=Z0;function hO(e,t,r,n,i,a){let o=e[t];o!==void 0&&(typeof o!="string"||!r.includes(o))&&a.push(Wa(`${n}/${t}`,i,`${t} must be one of ${r.map(s=>`'${s}'`).join(", ")}, got ${JSON.stringify(o)}`))}vt.optionalEnum=hO;var gO=/^(?:\{[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 vO(e,t,r,n,i){let a=e[t];typeof a=="string"&&a!==""&&!gO.test(a)&&i.push(Wa(`${r}/${t}`,n,`${t} must be a GUID or empty, got '${a}'`))}vt.optionalGuidId=vO;function yO(e,t,r,n,i){let a=e[t],o=`${r}/${t}`;return a===void 0?[]:Array.isArray(a)?Z0(a,o,n,i):(i.push(Wa(o,`${n}-list-must-be-array`,`${t} must be an array when present, got ${typeof a}`)),[])}vt.childObjects=yO});var yt=g(wi=>{"use strict";Object.defineProperty(wi,"__esModule",{value:!0});wi.assignMissingIds=wi.newId=void 0;var bO=ys();function ev(){return(0,bO.v4)()}wi.newId=ev;function wO(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var AO=new Set(["parameters","bag","expression","rawExpression","lookupValue","stepLabels"]);function CO(e){return gd(e),e}wi.assignMissingIds=CO;function gd(e){if(Array.isArray(e)){e.forEach(t=>gd(t));return}if(wO(e)){(typeof e.id!="string"||e.id.length===0)&&(e.id=ev());for(let t of Object.keys(e))t==="id"||AO.has(t)||gd(e[t])}}});var yd=g(ln=>{"use strict";Object.defineProperty(ln,"__esModule",{value:!0});ln.BUSINESS_RULE_NULL_GUID=ln.businessRuleRegistration=ln.BusinessRuleAdapter=void 0;var tv=ys(),ja=(Q0(),Fr(J0)),rv=Yt(),nv=ie(),SO=hd(),cr=ur(),EO=Ec(),NO=yt();function DO(e){return sv((0,SO.cloneJson)(e))}function sv(e){var t,r;let n=i=>(i??[]).map(a=>IO(a)?sv(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 IO(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 _O(e){var t;if(e===null||typeof e!="object"||Array.isArray(e))throw new nv.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 nv.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 PO="00000000-0000-0000-0000-000000000000";ln.BUSINESS_RULE_NULL_GUID=PO;var TO=new Set(["Recommendation","LockUnlock","ShowErrorMessage","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]),OO=["ruleId","name","description","entityLogicalName","scope","status","rootCondition"],RO=["kind","id","displayName","logic","clauses","trueBranch","falseBranch"],FO=["id","field","fieldDisplayName","operator","valueType","value","valueField","lookupValue","expression","rawExpression","valueWorkflowType"];function Zt(e,t){return e===void 0?t:{...e,...t}}var $n=["kind","id","type","displayName","field","stepName","stepLabels"],iv=["valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression"],xO={Recommendation:[...$n,"recommendationTitle","messageText","acceptanceText","applyActions","recommendationActionStepMeta"],LockUnlock:[...$n,"lock"],ShowErrorMessage:[...$n,"errorMessage","messageLevel","messageActionSteps"],SetFieldValue:[...$n,...iv],SetDefaultValue:[...$n,...iv],SetBusinessRequired:[...$n,"required"],SetVisibility:[...$n,"visible"]};function j(e,t){return t===void 0?{}:{[e]:t}}function lv(e){var t;return e===void 0?void 0:{...e,label:(t=e.label)!==null&&t!==void 0?t:""}}function vd(e){return{valueType:e.valueType,...j("valueWorkflowType",e.valueWorkflowType),...j("value",e.value),...j("valueField",e.valueField),...j("lookupValue",lv(e.lookupValue)),...j("expression",e.expression),...j("rawExpression",e.rawExpression)}}function uv(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 LO=["id","field","valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression","stepName","displayName"];function kO(e){return Zt(e.bag,{id:e.id,field:e.field,...vd(e),...j("stepName",e.stepName),...j("displayName",e.displayName)})}function MO(e){let t=uv(e,LO);return{id:e.id,field:e.field,valueType:e.valueType,...j("valueWorkflowType",e.valueWorkflowType),...j("value",e.value),...j("valueField",e.valueField),...j("lookupValue",e.lookupValue),...j("expression",e.expression),...j("rawExpression",e.rawExpression),...j("stepName",e.stepName),...j("displayName",e.displayName),...j("bag",t)}}function av(e){return{valueType:e.valueType,...j("valueWorkflowType",e.valueWorkflowType),...j("value",e.value),...j("valueField",e.valueField),...j("lookupValue",e.lookupValue),...j("expression",e.expression),...j("rawExpression",e.rawExpression)}}function ov(e){throw new Error(`Unsupported business-rule action type: ${e.type}`)}var UO=new Set(["INVALID_CLEAR_FOR_FIELD","INVALID_VALUE_TYPE_FOR_FIELD","CLAUSE_VALUE_TOO_LONG","ACTION_VALUE_TOO_LONG"]),BO=new Set;function $O(e){let t=n=>{var i;return(0,cr.isJsonObject)(n)&&(n.label===""||n.label===void 0)?{...n,label:String((i=n.id)!==null&&i!==void 0?i:"")}:n},r=n=>{if(!(0,cr.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 Os=class{toArtifact(t){let r=this.residualBag(t,OO),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 Zt(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,ja.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,ja.serializeToWorkflowJson)(n),a=(r=n.ruleId)!==null&&r!==void 0?r:(0,tv.v4)();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,ja.createEmptyCondition)():t.rootCondition===null?null:this.conditionFromJson(DO(_O(t.rootCondition)))},u=this.toArtifact(l);return u.id||(u.id=(0,tv.v4)()),u}assignMissingIds(t){return(0,NO.assignMissingIds)(t)}validate(t){let r=[],n=t.rootCondition;return n==null?r:(0,cr.isJsonObject)(n)?(cv(n,"/rootCondition",r),r):(r.push((0,cr.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,cr.issue)("/rootCondition","rule-not-representable",o instanceof Error?o.message:String(o))]}let i=n.rootCondition===null?null:$O(n.rootCondition),a=r.length===0?UO:BO;return(0,ja.validateBusinessRule)(i,r).filter(o=>!a.has(o.kind)).map(o=>(0,cr.issue)(`/rootCondition (${o.nodeId})`,`business-rule-${o.kind}`,o.message))}residualBag(t,r){return uv(t,r)}buildWorkflowEntity(t,r){return(0,ja.buildWorkflowEntity)(t,r)}conditionToJson(t){let r=this.residualBag(t,RO),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,FO),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,xO[t.type]),n={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...j("stepName",t.stepName),...j("stepLabels",t.stepLabels),...j("bag",r)};switch(t.type){case"Recommendation":return{...n,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...j("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(MO),...j("recommendationActionStepMeta",t.recommendationActionStepMeta)};case"LockUnlock":return{...n,type:"LockUnlock",lock:t.lock};case"ShowErrorMessage":return{...n,type:"ShowErrorMessage",errorMessage:t.errorMessage,...j("messageLevel",t.messageLevel),...j("messageActionSteps",t.messageActionSteps)};case"SetFieldValue":return{...n,type:"SetFieldValue",...av(t)};case"SetDefaultValue":return{...n,type:"SetDefaultValue",...av(t)};case"SetBusinessRequired":return{...n,type:"SetBusinessRequired",required:t.required};case"SetVisibility":return{...n,type:"SetVisibility",visible:t.visible};default:return ov(t)}}conditionFromJson(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:{};return Zt(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 Zt(t.bag,{id:t.id,field:t.field,fieldDisplayName:(r=t.fieldDisplayName)!==null&&r!==void 0?r:t.field,operator:t.operator,valueType:t.valueType,...j("value",t.value),...j("valueField",t.valueField),...j("lookupValue",lv(t.lookupValue)),...j("expression",t.expression),...j("rawExpression",t.rawExpression),...j("valueWorkflowType",t.valueWorkflowType)})}branchItemFromJson(t){return this.isConditionJson(t)?this.conditionFromJson(t):this.actionFromJson(t)}actionFromJson(t){if(!TO.has(t.type))throw new Error(`Unsupported business-rule action type: ${t.type}`);VO(t);let r={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...j("stepName",t.stepName),...j("stepLabels",t.stepLabels)};switch(t.type){case"Recommendation":return Zt(t.bag,{...r,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...j("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(kO),...j("recommendationActionStepMeta",t.recommendationActionStepMeta)});case"LockUnlock":return Zt(t.bag,{...r,type:"LockUnlock",lock:t.lock});case"ShowErrorMessage":return Zt(t.bag,{...r,type:"ShowErrorMessage",errorMessage:t.errorMessage,...j("messageLevel",t.messageLevel),...j("messageActionSteps",t.messageActionSteps)});case"SetFieldValue":return Zt(t.bag,{...r,type:"SetFieldValue",...vd(t)});case"SetDefaultValue":return Zt(t.bag,{...r,type:"SetDefaultValue",...vd(t)});case"SetBusinessRequired":return Zt(t.bag,{...r,type:"SetBusinessRequired",required:t.required});case"SetVisibility":return Zt(t.bag,{...r,type:"SetVisibility",visible:t.visible});default:return ov(t)}}isConditionJson(t){return Object.prototype.hasOwnProperty.call(t,"clauses")&&Object.prototype.hasOwnProperty.call(t,"logic")&&!Object.prototype.hasOwnProperty.call(t,"type")}};ln.BusinessRuleAdapter=Os;function cv(e,t,r){(0,cr.optionalEnum)(e,"logic",["AND","OR"],t,"condition-logic-invalid",r),(0,cr.childObjects)(e,"clauses",t,"clause",r);for(let n of["trueBranch","falseBranch"])(0,cr.childObjects)(e,n,t,"branchItem",r).forEach(({node:a,index:o})=>{"clauses"in a||"trueBranch"in a||"falseBranch"in a?cv(a,`${t}/${n}/${o}`,r):qO(a,`${t}/${n}/${o}`,r)})}function qO(e,t,r){e.type==="SetDefaultValue"&&e.valueType==="Clear"&&r.push((0,cr.issue)(`${t}/valueType`,"clear-only-set-field-value","Clear is only supported for SetFieldValue actions."))}function VO(e){if(e.type==="SetDefaultValue"&&e.valueType==="Clear")throw new Error("Clear is only supported for SetFieldValue actions.")}function GO(){return{adapter:new Os,api:EO.businessRuleApi,publish:(e,t,r)=>(0,rv.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,rv.boundEntityPublishScope)(t)}}ln.businessRuleRegistration=GO});var xs=g(Fs=>{"use strict";Object.defineProperty(Fs,"__esModule",{value:!0});Fs.JsonPointer=void 0;var Tt=ie(),Rs=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 Tt.JsonPointerError(t,'non-empty pointers must start with "/"');return t.substring(1).split("/").map(r=>{if(/~(?![01])/.test(r))throw new Tt.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 Tt.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 Tt.JsonPointerError(r,`'${o}' is not a valid array index`);if(s>a.length)throw new Tt.JsonPointerError(r,`array index '${o}' is out of range`);a[s]=n}else{if(e.isReservedToken(o))throw new Tt.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 Tt.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 Tt.JsonPointerError(r,`array index '${a}' is out of range`);i.splice(o,1)}else{if(e.isReservedToken(a))throw new Tt.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 Tt.JsonPointerError(r,"add target must be an array");u.push(n);return}let o=e.resolve(t,r);if(!Array.isArray(o))throw new Tt.JsonPointerError(r,"add target must be an array");let s=i===void 0?o.length:i;if(s<0||s>o.length)throw new Tt.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 Tt.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)}};Fs.JsonPointer=Rs;Rs.RESERVED_TOKENS=new Set(["__proto__","prototype","constructor"])});var pv=g(Ls=>{"use strict";Object.defineProperty(Ls,"__esModule",{value:!0});Ls.findElements=void 0;var dv=xs();function zO(e,t){let r=[];return bd(e,"",t,r),r}Ls.findElements=zO;function bd(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)=>{bd(i,dv.JsonPointer.append(t,a),r,n)});else for(let i of Object.keys(e))bd(e[i],dv.JsonPointer.append(t,i),r,n)}});var hv=g(rt=>{"use strict";var WO=rt&&rt.__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]})),jO=rt&&rt.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),mv=rt&&rt.__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)&&WO(t,e,r);return jO(t,e),t};Object.defineProperty(rt,"__esModule",{value:!0});rt.canonicalArtifactId=rt.WorkspaceManager=rt.WORKSPACE_SCHEMA_VERSION=void 0;var _e=mv(require("fs")),Re=mv(require("path")),Ai=ie();rt.WORKSPACE_SCHEMA_VERSION=1;var ks={form:"forms",view:"views",businessRule:"business-rules",app:"apps",command:"commands",chart:"charts",dashboard:"dashboards",genPage:"gen-pages",bpf:"business-process-flows"},HO="manifest.json",Ms=".metadata",fv="entities",wd=class{constructor(t,r){this.workspacePath=t,this.instanceUrl=r}getRoot(){return this.workspacePath}getArtifactDir(t){return Re.join(this.workspacePath,ks[t])}getArtifactFilePath(t,r){return this.assertSafeId(r),this.assertWithinRoot(Re.join(this.getArtifactDir(t),`${Ha(r)}.json`))}getMetaFilePath(t,r){return this.assertSafeId(r),this.assertWithinRoot(Re.join(this.workspacePath,Ms,ks[t],`${Ha(r)}.meta.json`))}getEntityMetaFilePath(t){return this.assertSafeId(t),this.assertWithinRoot(Re.join(this.workspacePath,Ms,fv,`${t}.json`))}assertSafeId(t){if(typeof t!="string"||t.length===0||/[\u0000-\u001f]/.test(t)||t.includes("/")||t.includes("\\")||t.includes(":")||t==="."||t===".."||t.includes("..")||Re.basename(t)!==t)throw new Ai.PathTraversalError(String(t),this.workspacePath)}assertWithinRoot(t){let r=Re.resolve(this.workspacePath),n=Re.resolve(t);if(n!==r&&!n.startsWith(r+Re.sep))throw new Ai.PathTraversalError(t,this.workspacePath);let i=_e.existsSync(r)?_e.realpathSync(r):r,a=n,o=[];for(;!_e.existsSync(a);){o.unshift(Re.basename(a));let l=Re.dirname(a);if(l===a)break;a=l}let s=Re.resolve(_e.realpathSync(a),...o);if(s!==i&&!s.startsWith(i+Re.sep))throw new Ai.PathTraversalError(t,this.workspacePath);return n}get manifestPath(){return Re.join(this.workspacePath,HO)}init(){for(let t of Object.keys(ks))_e.mkdirSync(this.getArtifactDir(t),{recursive:!0}),_e.mkdirSync(Re.dirname(this.getMetaFilePath(t,"x")),{recursive:!0});if(_e.mkdirSync(Re.join(this.workspacePath,Ms,fv),{recursive:!0}),!this.exists(this.manifestPath)){let t={instanceUrl:this.instanceUrl,createdAt:new Date().toISOString(),artifacts:[]};this.writeManifest(t)}}isInitialized(){return this.exists(this.manifestPath)}ensureInitialized(){if(!this.isInitialized())throw new Ai.WorkspaceNotInitializedError(this.workspacePath)}clean(){for(let r of Object.keys(ks))Ad(this.getArtifactDir(r));Ad(Re.join(this.workspacePath,Ms));let t=this.getManifest();t.artifacts=[],t.lastSyncAt=void 0,this.init(),this.writeManifest(t)}readArtifact(t,r){return this.ensureInitialized(),this.readJson(this.getArtifactFilePath(t,r))}writeArtifact(t,r,n){this.ensureInitialized(),this.writeJson(this.getArtifactFilePath(t,r),n),this.upsertManifestEntry(t,r,n)}deleteArtifact(t,r){this.ensureInitialized(),this.removeFile(this.getArtifactFilePath(t,r)),this.removeFile(this.getMetaFilePath(t,r));let n=Ha(r),i=this.getManifest();i.artifacts=i.artifacts.filter(a=>!(a.type===t&&a.id===n)),this.writeManifest(i)}listArtifacts(t,r){return this.ensureInitialized(),this.getManifest().artifacts.filter(n=>!(t&&n.type!==t||r?.entityLogicalName&&n.entityLogicalName!==r.entityLogicalName))}readEntityMetadata(t){this.ensureInitialized();let r=this.readJson(this.getEntityMetaFilePath(t));return!r||typeof r.schemaName!="string"||typeof r.primaryNameAttribute!="string"||typeof r.primaryIdAttribute!="string"||typeof r.isCustomEntity!="boolean"?null:r}writeEntityMetadata(t,r){this.ensureInitialized(),this.writeJson(this.getEntityMetaFilePath(t),r)}getManifest(){this.ensureInitialized();let t=this.readJson(this.manifestPath);if(!t)throw new Ai.WorkspaceNotInitializedError(this.workspacePath);if(t.schemaVersion!==void 0&&t.schemaVersion>rt.WORKSPACE_SCHEMA_VERSION)throw new Ai.IncompatibleWorkspaceError(t.schemaVersion,rt.WORKSPACE_SCHEMA_VERSION);return t}writeManifest(t){this.writeJson(this.manifestPath,{...t,schemaVersion:rt.WORKSPACE_SCHEMA_VERSION})}updateManifest(t){let r=this.getManifest();this.writeManifest({...r,...t})}upsertManifestEntry(t,r,n){let i=this.getManifest(),a=Ha(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}),this.writeManifest(i)}readJson(t){return this.exists(t)?JSON.parse(_e.readFileSync(t,"utf8")):null}writeJson(t,r){let n=Re.dirname(t);_e.mkdirSync(n,{recursive:!0});let i=Re.join(n,`.${Re.basename(t)}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);try{_e.writeFileSync(i,`${JSON.stringify(r,null,2)}-`,"utf8"),_e.renameSync(i,t)}catch(a){try{_e.existsSync(i)&&_e.unlinkSync(i)}catch{}throw a}}removeFile(t){this.exists(t)&&_e.unlinkSync(t)}exists(t){return _e.existsSync(t)}};rt.WorkspaceManager=wd;function Ha(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()}rt.canonicalArtifactId=Ha;function Ad(e){let t;try{t=_e.lstatSync(e)}catch{return}if(t.isSymbolicLink()){try{_e.unlinkSync(e)}catch{_e.rmdirSync(e)}return}if(!t.isDirectory()){_e.unlinkSync(e);return}for(let r of _e.readdirSync(e))Ad(Re.join(e,r));_e.rmdirSync(e)}});var Cd=g(Ci=>{"use strict";Object.defineProperty(Ci,"__esModule",{value:!0});Ci.deepEqual=Ci.deepDiff=void 0;var JO=xs();function QO(e,t){let r=[];return vv(e,t,"",r,0),r}Ci.deepDiff=QO;var Us=Symbol("missing"),Bs=512;function vv(e,t,r,n,i){if(e===t)return;if(i>Bs)throw new RangeError(`deepDiff exceeded the maximum supported depth of ${Bs}`);let a=$s(e),o=$s(t);if(a&&o&&Array.isArray(e)===Array.isArray(t)){let s=XO(e,t);for(let l of s){let u=gv(e,l),c=gv(t,l),d=JO.JsonPointer.append(r,l);u===Us?n.push({pointer:d,type:"added",newValue:c}):c===Us?n.push({pointer:d,type:"removed",oldValue:u}):vv(u,c,d,n,i+1)}return}yv(e,t)||n.push({pointer:r,type:"modified",oldValue:e,newValue:t})}function $s(e){return e!==null&&typeof e=="object"}function XO(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 gv(e,t){if(Array.isArray(e)){let r=Number(t);return r<e.length?e[r]:Us}return t in e?e[t]:Us}function yv(e,t){return bv(e,t,0)}Ci.deepEqual=yv;function bv(e,t,r){if(e===t)return!0;if(r>Bs)throw new RangeError(`deepEqual exceeded the maximum supported depth of ${Bs}`);if(!$s(e)||!$s(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&&bv(e[a],t[a],r+1))}});var Av=g(qs=>{"use strict";Object.defineProperty(qs,"__esModule",{value:!0});qs.VersionManager=void 0;var wv=Cd(),Sd=class{constructor(t){this.workspace=t}storeMeta(t,r,n){this.workspace.writeJson(this.workspace.getMetaFilePath(t,r),n)}getMeta(t,r){return this.workspace.readJson(this.workspace.getMetaFilePath(t,r))}isDirty(t,r){let n=this.workspace.readArtifact(t,r);if(n===null)return!1;let i=this.getMeta(t,r);return i?!(0,wv.deepEqual)(i.snapshot,n):!0}diff(t,r){let n=this.workspace.readArtifact(t,r),i=this.getMeta(t,r),a;return n===null?a=i?[{pointer:"",type:"removed",oldValue:i.snapshot}]:[]:i?a=(0,wv.deepDiff)(i.snapshot,n):a=[{pointer:"",type:"added",newValue:n}],{artifactType:t,artifactId:r,changes:a}}checkConflict(t,r,n){let i=this.getMeta(t,r);return!i||i.etag===null?!1:i.etag!==n}};qs.VersionManager=Sd});var Sv=g((Ed,Cv)=>{(function(e,t){typeof define=="function"&&define.amd?define([],t):typeof Ed=="object"?Cv.exports=t():e.compareVersions=t()})(Ed,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 m=l[l.length-1],h=u[u.length-1];if(m&&h){var w=m.split(".").map(n),b=h.split(".").map(n);for(c=0;c<Math.max(w.length,b.length);c++){if(w[c]===void 0||typeof b[c]=="string"&&typeof w[c]=="number")return-1;if(b[c]===void 0||typeof w[c]=="string"&&typeof b[c]=="number"||w[c]>b[c])return 1;if(b[c]>w[c])return-1}}else if(m||h)return m?-1:1;return 0}})});var _v=g(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.EnvironmentFlowHostingType=Ee.EnvironmentDisableReasonCode=Ee.EnvironmentMigrationConstants=Ee.EnvironmentProvisioningStates=Ee.EnvironmentLocations=Ee.EnvironmentCreationTypeConstants=Ee.EnvironmentType=Ee.EnvironmentSkuConstants=Ee.environmentPermissions=Ee.DatabaseType=void 0;var Ev;(function(e){e.CommonDataService="CommonDataService",e.None="None"})(Ev||(Ee.DatabaseType=Ev={}));Ee.environmentPermissions={CreatePowerApp:"CreatePowerApp",ReadEnvironment:"ReadEnvironment",GenerateResourceStorage:"GenerateResourceStorage",CreateGateway:"CreateGateway",CreateFlow:"CreateFlow",CreateCustomApi:"CreateCustomApi",AdminReadEnvironment:"AdminReadEnvironment",UpdateEnvironment:"UpdateEnvironment",DeleteEnvironment:"DeleteEnvironment",ExportEnvironmentPackage:"ExportEnvironmentPackage",SetDLPPolicy:"SetDLPPolicy",ListAnyPowerApp:"ListAnyPowerApp",ListAnyFlow:"ListAnyFlow",DeleteAnyPowerApp:"DeleteAnyPowerApp",DeleteAnyFlow:"DeleteAnyFlow",AddEnvironmentRoleAssignment:"AddEnvironmentRoleAssignment",ReadEnvironmentRoleInformation:"ReadEnvironmentRoleInformation",RemoveEnvironmentRoleAssignment:"RemoveEnvironmentRoleAssignment",ModifyDatabaseRoleAssignments:"ModifyDatabaseRoleAssignments",CreateDatabase:"CreateDatabase",ListDatabaseEntities:"ListDatabaseEntities",CreateDatabaseEntities:"CreateDatabaseEntities",UpdateDatabaseEntities:"UpdateDatabaseEntities",DeleteDatabaseEntities:"DeleteDatabaseEntities"};Ee.EnvironmentSkuConstants={NotSpecified:"NotSpecified",Standard:"Standard",Premium:"Premium",Developer:"Developer",Basic:"Basic",Production:"Production",Sandbox:"Sandbox",Trial:"Trial",Default:"Default",Teams:"Teams",Platform:"Platform"};var Nv;(function(e){e[e.CDS2=0]="CDS2",e[e.CDS1=1]="CDS1",e[e.Empty=2]="Empty"})(Nv||(Ee.EnvironmentType=Nv={}));Ee.EnvironmentCreationTypeConstants={NotSpecified:"NotSpecified",Legacy:"Legacy",DefaultTenant:"DefaultTenant",User:"User",CommonDataModelLegacy:"CommonDataModelLegacy"};Ee.EnvironmentLocations={global:"global",unitedStates:"unitedstates",southamerica:"southamerica",europe:"europe",canada:"canada",preview:"unitedstatesfirstrelease",asia:"asia",japan:"japan",australia:"australia",india:"india",unitedkingdom:"unitedkingdom",france:"france",germany:"germany",brazil:"brazil",usgov:"usgov",usgovhigh:"usgovhigh",uae:"unitedarabemirates",switzerland:"switzerland",mooncake:"china",korea:"korea",norway:"norway",southafrica:"southafrica",dod:"usdod",singapore:"singapore",sweden:"sweden",italy:"italy",poland:"poland"};Ee.EnvironmentProvisioningStates={NotSpecified:"NotSpecified",Succeeded:"Succeeded",Deleting:"Deleting",Deleted:"Deleted",FailedDeleting:"FailedDeleting",LinkedDatabaseProvisioning:"LinkedDatabaseProvisioning",LinkedDatabaseFailedProvisioning:"LinkedDatabaseFailedProvisioning",LinkedDatabaseFailedConfiguring:"LinkedDatabaseFailedConfiguring",LinkedDatabaseUnavailable:"LinkedDatabaseUnavailable",Creating:"Creating"};Ee.EnvironmentMigrationConstants={phases:{completed:"Completed"}};var Dv;(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"})(Dv||(Ee.EnvironmentDisableReasonCode=Dv={}));var Iv;(function(e){e.LogicApps="LogicApps",e.SelfHostSingleTenant="SelfHostSingleTenant",e.SelfHostMultiTenant="SelfHostMultiTenant"})(Iv||(Ee.EnvironmentFlowHostingType=Iv={}))});var kv=g(A=>{"use strict";var KO=A&&A.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(A,"__esModule",{value:!0});A.hasCommonDataServiceDatabase=A.getEnvironmentDiscoveryUrl=A.getEnvironmentWebApiUrl=A.getEnvironmentInstanceApiUrl=A.getEnvironmentLanguageCode=A.getEnvironmentUpdateCadence=A.checkVersions=A.isCds2EnvironmentVersionAtLeast=A.getSecurityOrConnectedGroupId=A.hasSecurityGroupId=A.doesCds2VersionSupportApiVersion9_1=A.doesCds2EnvironmentSupportApiVersion9_1=A.cdsVersionSupportingOSColorEdit=A.getEnvironmentDisplayName=A.getEnvironmentName=A.isEnvironmentInFirstReleaseCluster=A.isEnvironmentInPreprodCluster=A.isEnvironmentInTestCluster=A.isLiteEnvironmentUpgrading=A.isEnvironmentExpired=A.isEnvironmentInDeletedState=A.isEnvironmentInCreatingState=A.isDatabaseInProvisioningState=A.canUserCreateDatabase=A.isDisabledEnvironment=A.isDefaultEnvironment=A.isTrialEnvironment=A.isPlatformEnvironment=A.isTeamsEnvironment=A.isSandboxEnvironment=A.isProdEnvironment=A.isDevEnvironment=A.getEnvironmentType=A.getCrmInstanceName=A.getCrmInstanceUrl=A.getCrmAppDesignerUrl=A.getDevResourcesUrl=A.isEnvironmentInSuccessfulState=A.getAllThemesUrl=A.getAllPublishersUrl=A.getAllSolutionsUrl=A.getSecurityRolesUrl=A.getSecurityUsersUrl=A.environmentHasCds2Database=A.DEFAULT_SOLUTION_UNIQUE_NAME=A.DEFAULT_SOLUTION_ID=A.crmBapSolutionId=A.doesUserHavePermission=A.getLinkedEnvironmentMetadata=A.getCrmVersion=void 0;A.doesUserHaveFlowRunOnlyPermission=A.isUserPautoMakerWithoutDataAccess=A.isUserPautoMakerWithDataAccess=A.doesUserHaveCreateFlowPermission=A.equalsIgnoreCase=A.doesUserHaveCreateDatabasePermission=A.doesUserHaveDatabaseTablePermissions=A.isUserMakerWithoutDataAccess=A.isUserMakerWithDataAccess=A.doesUserHaveCreateAppPermission=A.doesUserHaveAdminPermission=void 0;var YO=KO(Sv()),le=_v(),Ja=Dd();function ZO(e){let t=Ur(e);return t&&t.version}A.getCrmVersion=ZO;function Ur(e){return e&&e.properties&&e.properties.linkedEnvironmentMetadata}A.getLinkedEnvironmentMetadata=Ur;function Mr(e,t){return e?!!e[t]:!1}A.doesUserHavePermission=Mr;A.crmBapSolutionId="00000001-0000-0000-0001-00000000009b";A.DEFAULT_SOLUTION_ID="fd140aaf-4df4-11dd-bd17-0019b9312238";A.DEFAULT_SOLUTION_UNIQUE_NAME="Default";function qn(e){return!!Ur(e)&&Pv(e)}A.environmentHasCds2Database=qn;function eR(e){if(e&&qn(e)){let t=un(e);return(0,Ja.getCrmAdminSecurityRolesUrl)(t)}return""}A.getSecurityUsersUrl=eR;function tR(e){if(e&&qn(e)){let t=un(e);return(0,Ja.getCrmAdminSecurityUsersUrl)(t)}return""}A.getSecurityRolesUrl=tR;function rR(e){if(e&&qn(e)){let t=un(e);(0,Ja.getCrmAllSolutionsUrl)(t)}return""}A.getAllSolutionsUrl=rR;function nR(e){if(e&&qn(e)){let t=un(e);return(0,Ja.getCrmAllPublishersUrl)(t)}return""}A.getAllPublishersUrl=nR;function iR(e){return e&&qn(e)?un(e):""}A.getAllThemesUrl=iR;function Pv(e){return!!e&&e.properties&&!!e.properties.provisioningState&&e.properties.provisioningState.toUpperCase()===le.EnvironmentProvisioningStates.Succeeded.toUpperCase()}A.isEnvironmentInSuccessfulState=Pv;function aR(e){if(e&&qn(e)){let t=un(e);return(0,Ja.getCrmDevResourcesUrl)(t)}return""}A.getDevResourcesUrl=aR;function oR(e){return`${e}designer/app/{${A.crmBapSolutionId}}/CreateNewApp}}`}A.getCrmAppDesignerUrl=oR;function un(e){let t=Ur(e);if(t){let r=t.instanceUrl;return r?r.endsWith("/")?r:r+"/":""}return""}A.getCrmInstanceUrl=un;function sR(e){let t=Ur(e);return t?t.uniqueName:""}A.getCrmInstanceName=sR;function lR(e){return Ur(e)?le.EnvironmentType.CDS2:e&&e.properties&&e.properties.namespace?le.EnvironmentType.CDS1:le.EnvironmentType.Empty}A.getEnvironmentType=lR;function uR(e){return e&&e.properties&&e.properties.environmentSku===le.EnvironmentSkuConstants.Developer}A.isDevEnvironment=uR;function cR(e){return e&&e.properties&&e.properties.environmentSku===le.EnvironmentSkuConstants.Production}A.isProdEnvironment=cR;function dR(e){return e&&e.properties&&e.properties.environmentSku===le.EnvironmentSkuConstants.Sandbox}A.isSandboxEnvironment=dR;function Qa(e){return e&&e.properties&&e.properties.environmentSku===le.EnvironmentSkuConstants.Teams}A.isTeamsEnvironment=Qa;function pR(e){return e&&e.properties&&e.properties.environmentSku===le.EnvironmentSkuConstants.Platform}A.isPlatformEnvironment=pR;var fR=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.environmentSku)===le.EnvironmentSkuConstants.Trial};A.isTrialEnvironment=fR;function mR(e){return e&&e.properties&&(e.properties.isDefault||e.properties.creationType===le.EnvironmentCreationTypeConstants.DefaultTenant)}A.isDefaultEnvironment=mR;function hR(e){return e&&e.properties&&!!e.properties.states&&!!e.properties.states.runtime&&e.properties.states.runtime.id==="Disabled"}A.isDisabledEnvironment=hR;function gR(e){return e&&e.properties&&Mr(e.properties.permissions,le.environmentPermissions.CreateDatabase)}A.canUserCreateDatabase=gR;function vR(e){return!!(e&&e.properties&&e.properties.provisioningState&&Lv(e.properties.provisioningState,le.EnvironmentProvisioningStates.LinkedDatabaseProvisioning))}A.isDatabaseInProvisioningState=vR;function yR(e){return!!e&&!!e.properties&&e.properties.provisioningState===le.EnvironmentProvisioningStates.Creating}A.isEnvironmentInCreatingState=yR;function bR(e){return e&&e.properties&&(e.properties.provisioningState===le.EnvironmentProvisioningStates.Deleted||e.properties.provisioningState===le.EnvironmentProvisioningStates.Deleting||e.properties.provisioningState===le.EnvironmentProvisioningStates.FailedDeleting)}A.isEnvironmentInDeletedState=bR;function wR(e){return!!e&&!!e.properties&&!!e.properties.expirationTime&&Date.parse(e.properties.expirationTime)<Date.now()}A.isEnvironmentExpired=wR;function AR(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"}A.isLiteEnvironmentUpgrading=AR;function CR(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Test"}A.isEnvironmentInTestCluster=CR;function SR(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Preprod"}A.isEnvironmentInPreprodCluster=SR;function ER(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="FirstRelease"}A.isEnvironmentInFirstReleaseCluster=ER;function NR(e){return e&&e.name||""}A.getEnvironmentName=NR;function DR(e){return e&&e.properties&&e.properties.displayName||""}A.getEnvironmentDisplayName=DR;var Tv="9.1.0.8202";A.cdsVersionSupportingOSColorEdit="9.1.0000.20708";function IR(e){return Fv(e,Tv)}A.doesCds2EnvironmentSupportApiVersion9_1=IR;function _R(e){return Nd(e,Tv)}A.doesCds2VersionSupportApiVersion9_1=_R;function Ov(e){let t=Ur(e);if(t)return t.securityGroupId}function Rv(e){return e&&e.properties&&e.properties.connectedGroups}function PR(e,t){let r=Rv(e);return!!r&&!!r.find(n=>n.id===t)||Ov(e)===t}A.hasSecurityGroupId=PR;function TR(e){let t=Rv(e);return t&&t.length>0&&t[0].id?t[0].id:Ov(e)}A.getSecurityOrConnectedGroupId=TR;function Fv(e,t){let r=e.version;return r?Nd(r,t):!1}A.isCds2EnvironmentVersionAtLeast=Fv;function Nd(e,t){return t?e?(0,YO.default)(e,t)>=0:!1:!0}A.checkVersions=Nd;function OR(e){return e&&e.properties&&e.properties.updateCadence&&e.properties.updateCadence.id||"NotSpecified"}A.getEnvironmentUpdateCadence=OR;function RR(e){let t=Ur(e);return t?Number(t.baseLanguage):0}A.getEnvironmentLanguageCode=RR;function xv(e){let t=Ur(e);return t?t.instanceApiUrl:void 0}A.getEnvironmentInstanceApiUrl=xv;function FR(e){let t=xv(e);return t?t+"/api/data/v9.2":""}A.getEnvironmentWebApiUrl=FR;function xR(e){let t=un(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"}A.getEnvironmentDiscoveryUrl=xR;var LR=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.databaseType)===le.DatabaseType.CommonDataService};A.hasCommonDataServiceDatabase=LR;var kR=e=>{var t;return Mr((t=e.properties)===null||t===void 0?void 0:t.permissions,le.environmentPermissions.AdminReadEnvironment)};A.doesUserHaveAdminPermission=kR;var MR=e=>{var t;return Mr((t=e.properties)===null||t===void 0?void 0:t.permissions,le.environmentPermissions.CreatePowerApp)};A.doesUserHaveCreateAppPermission=MR;var UR=e=>(0,A.doesUserHaveAdminPermission)(e)&&(0,A.hasCommonDataServiceDatabase)(e)?!0:(0,A.doesUserHaveCreateAppPermission)(e)?Qa(e)||(0,A.doesUserHaveDatabaseTablePermissions)(e):!1;A.isUserMakerWithDataAccess=UR;var BR=e=>(0,A.doesUserHaveCreateAppPermission)(e)&&!Qa(e)&&!(0,A.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,A.doesUserHaveAdminPermission)(e)||!(0,A.hasCommonDataServiceDatabase)(e));A.isUserMakerWithoutDataAccess=BR;var $R=e=>[le.environmentPermissions.CreateDatabaseEntities,le.environmentPermissions.ListDatabaseEntities,le.environmentPermissions.UpdateDatabaseEntities,le.environmentPermissions.DeleteDatabaseEntities].every(t=>{var r;return Mr((r=e.properties)===null||r===void 0?void 0:r.permissions,t)});A.doesUserHaveDatabaseTablePermissions=$R;var qR=e=>{var t;return Mr((t=e.properties)===null||t===void 0?void 0:t.permissions,le.environmentPermissions.CreateDatabase)};A.doesUserHaveCreateDatabasePermission=qR;function Lv(e,t){return!e&&!t?!0:!e||!t?!1:e.toUpperCase()===t.toUpperCase()}A.equalsIgnoreCase=Lv;var VR=e=>{var t;return Mr((t=e.properties)===null||t===void 0?void 0:t.permissions,le.environmentPermissions.CreateFlow)};A.doesUserHaveCreateFlowPermission=VR;var GR=e=>(0,A.doesUserHaveAdminPermission)(e)&&(0,A.hasCommonDataServiceDatabase)(e)?!0:(0,A.doesUserHaveCreateFlowPermission)(e)?Qa(e)||(0,A.doesUserHaveDatabaseTablePermissions)(e):!1;A.isUserPautoMakerWithDataAccess=GR;var zR=e=>(0,A.doesUserHaveCreateFlowPermission)(e)&&!Qa(e)&&!(0,A.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,A.doesUserHaveAdminPermission)(e)||!(0,A.hasCommonDataServiceDatabase)(e));A.isUserPautoMakerWithoutDataAccess=zR;var WR=e=>{var t,r;return!Mr((t=e.properties)===null||t===void 0?void 0:t.permissions,le.environmentPermissions.CreateFlow)&&Mr((r=e.properties)===null||r===void 0?void 0:r.permissions,le.environmentPermissions.ReadEnvironment)};A.doesUserHaveFlowRunOnlyPermission=WR});var Dd=g(y=>{"use strict";Object.defineProperty(y,"__esModule",{value:!0});y.getRequiredComponentsQueryUrl=y.solutionComponentCountSummariesQueryUrl=y.solutionComponentSummariesQueryUrl=y.solutionComponentConfigurationsQueryUrl=y.chartsQueryUrl=y.workflowsQueryUrl=y.entityDefinitionsQueryUrl=y.solutionComponentDefinitionsQueryUrl=y.getCreateNewArticleTemplateUrl=y.getCreateNewPublisherUrl=y.getEnableSecurityRolesUrl=y.getArticleTemplateUrl=y.getFieldSecurityProfileDesignerUrl=y.getSecurityRoleDesignerUrl=y.getMailMergeTemplateDesignerUrl=y.getEmailTemplateDesignerUrl=y.getConnectionRoleDesignerUrl=y.getSiteMapDesignerUrl=y.getWebResourceFileUrl=y.getWebResourceDesignerUrl=y.getReportDesignerUrl=y.getBusinessProcessFlowDesignerUrl=y.getProcessShareUrl=y.getProcessDesignerUrl=y.getChartDesignerUrl=y.getOpenModernEntityDashboardUrl=y.getNewModernEntityDashboardUrl=y.getNewModernDashboardUrl=y.getOpenModernDashboardUrl=y.getDashboardDesignerUrl=y.getAppModuleDesignerUrl=y.privilegesQueryUrls=y.xrmApiUrl=y.getPlayAppModuleUrl=y.getCrmAdminSecurityUsersUrl=y.getCrmAdminSecurityRolesUrl=y.getCrmMyAppsUrl=y.getCrmAppDesignerUrl=y.getCrmDevResourcesUrl=y.getCrmAllPublishersUrl=y.getCrmAllSolutionsUrl=y.getSolutionPublisherUrl=y.getExportTranslationFileName=y.getExportSolutionTranslationUrl=y.getImportSolutionTranslationUrl=y.getShowSolutionDependenciesUrl=y.getShowComponentDependenciesUrl=y.cdsServiceUrl=y.ODATA_NEXT_LINK=y.ODATA_MAX_PAGE_SIZE=void 0;y.retrieveOrganizationResources=y.getUCIEntityRecordEditUrl=y.getUCIEntityRecordBaseUrl=y.getBusinessRuleDesignerUri=y.retrieveUnpublishedSuffix=y.getSavePowerSettingUri=y.getPowerSettingUri=y.getPowerSettingsUri=y.RetrievePlatform=y.getAppSettingOverrideUri=y.AppSettingOverrideName=y.getOrgSettingOverrideUri=y.OrgSettingOverrideName=y.getSettingDefinitionsUri=y.retrieveFeatureControlSettingsByNamespaceUrl=y.retrieveDeploymentPipelineConfigAppUrl=y.SPNPrincipalIdUrl=y.retrieveDeploymentEnvironmentInfoUrl=y.devSolutionInfoUrl=y.deployOperationStatusUrl=y.getAIGeneratedDeploymentNotesUrl=y.deploymentStageRunUrl=y.validatePackageAsyncUrl=y.deployPackageAsyncUrl=y.updateDeploymentStageRunUrl=y.createDeploymentStageRunUrl=y.retrieveDeploymentStagesUrl=y.retrievePipelinesUrl=y.retrieveDeploymentPipelineInfoUrl=y.getDeploymentStageRunsUrl=y.appDeploymentUrls=y.getProvisionLanguageUrl=y.getSolutionQueryUrl=y.getSolutionsByUniqueNameQueryUrl=y.solutionsQueryUrl=y.getDependentComponentsWithMetadataQueryUrl=void 0;var Mv=kv();y.ODATA_MAX_PAGE_SIZE="odata.maxpagesize";y.ODATA_NEXT_LINK="@odata.nextLink";y.cdsServiceUrl="https://cds-org/";var Ka;(function(e){e.AllSolutions="11",e.AllPublishers="10",e.DevResources="05"})(Ka||(Ka={}));function jR(e,t,r,n){return`${e}tools/dependency/dependencyviewdialog.aspx?appSolutionId=%7b${t}%7d&dType=1&objectid=%7b${r}%7d&objecttype=${n}&operationtype=showdependency`}y.getShowComponentDependenciesUrl=jR;function HR(e,t){let r=`dType=1&isproactivecheck=true&objecttype=7100&operationtype=dependenciesforuninstall&objectid=${t}`;return`${e}tools/dependency/dependencyviewdialog.aspx?${r}`}y.getShowSolutionDependenciesUrl=HR;function JR(e,t){return`${e}tools/muiProvisioning/Dialogs/LangTranslationsImport.aspx?dType=1&appSolutionId=${t}`}y.getImportSolutionTranslationUrl=JR;function QR(e,t){return`${e}_grid/cmds/dlg_exportsolution.aspx?command=exporttranslation&appSolutionId=${t}`}y.getExportSolutionTranslationUrl=QR;function XR(e,t){return e!==void 0&&t!==void 0&&`CrmTranslations_${e}_${t.replace(/[.]/g,"_")}.zip`||""}y.getExportTranslationFileName=XR;function KR(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`}y.getSolutionPublisherUrl=KR;function Id(e,t){return`${e}tools/systemcustomization/systemCustomization.aspx?pid=${t}`}function YR(e){return Id(e,Ka.AllSolutions)}y.getCrmAllSolutionsUrl=YR;function ZR(e){return Id(e,Ka.AllPublishers)}y.getCrmAllPublishersUrl=ZR;function eF(e){return Id(e,Ka.DevResources)}y.getCrmDevResourcesUrl=eF;function tF(e,t=Mv.crmBapSolutionId){return`${e}designer/app/${t}#/CreateNewApp`}y.getCrmAppDesignerUrl=tF;function rF(e){return`${e}apps`}y.getCrmMyAppsUrl=rF;function nF(e){return Uv(e,"role")+"&forceUCI=0"}y.getCrmAdminSecurityRolesUrl=nF;function iF(e){return`${Uv(e,"systemuser")}&forceclassic=1`}y.getCrmAdminSecurityUsersUrl=iF;function Uv(e,t){return`${e}main.aspx?pagetype=entitylist&etn=${t}`}function aF(e,t){return`${e}main.aspx?appid=${t}`}y.getPlayAppModuleUrl=aF;y.xrmApiUrl="api/data/v9.0";y.privilegesQueryUrls={systemUserInfo:e=>`${e}${y.xrmApiUrl}/WhoAmI`,userPrivileges:(e,t)=>`${e}${y.xrmApiUrl}/systemusers(${t})/Microsoft.Dynamics.CRM.RetrieveUserPrivileges`,systemPrivileges:e=>`${e}${y.xrmApiUrl}/privileges/Microsoft.Dynamics.CRM.RetrievePrivilegeSet`};function oF(e,t,r=Mv.crmBapSolutionId){return`${e}designer/app/${r}/${t}/AppDesignerCanvas/${t}`}y.getAppModuleDesignerUrl=oF;function sF(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${r}%7d&extraqs=%26formId%3d%7b${t}%7d%26dashboardType%3d1030&pagetype=${`${n?"ic":""}dashboardeditor`}`}y.getDashboardDesignerUrl=sF;function lF(e,t,r){return`/e/${e}/s/${t}/dashboard/${r}`}y.getOpenModernDashboardUrl=lF;function uF(e,t,r){let n=r!==void 0?r.toString():void 0;return`/e/${e}/s/${t}/dashboard/new${n?`/${n}`:""}`}y.getNewModernDashboardUrl=uF;function cF(e,t,r,n){let i=n!==void 0?n.toString():void 0;return`/e/${e}/s/${t}/n/${r}/dashboard/new${i?`/${i}`:""}`}y.getNewModernEntityDashboardUrl=cF;function dF(e,t,r,n){return`/e/${e}/s/${t}/n/${r}/dashboard/${n}`}y.getOpenModernEntityDashboardUrl=dF;function pF(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${t}%7d&extraqs=etc=${r||""}`+(n?`%26id=${n}`:"")+"&pagetype=vizdesigner"}y.getChartDesignerUrl=pF;function fF(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}y.getProcessDesignerUrl=fF;function mF(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}y.getProcessShareUrl=mF;function hF(e,t){return`${e}Tools/ProcessControl/UnifiedProcessDesigner.aspx?id=${t}`}y.getBusinessProcessFlowDesignerUrl=hF;function gF(e,t,r){return`${e}CRMReports/reportproperty.aspx?appSolutionId=%7b${r}%7d&disablePersonal=true&id=%7b${t}%7d`}y.getReportDesignerUrl=gF;function vF(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`}y.getWebResourceDesignerUrl=vF;function yF(e,t){return`${e}WebResources/${t}`}y.getWebResourceFileUrl=yF;function bF(e,t,r){return`${e}designer/sitemap/${r}/${t}/SiteMapHome/${t}`}y.getSiteMapDesignerUrl=bF;function wF(e,t,r){return`${e}connections/connectionroles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}y.getConnectionRoleDesignerUrl=wF;function AF(e,t,r){return`${e}tools/emailtemplateeditor/emailtemplateeditor.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}y.getEmailTemplateDesignerUrl=AF;function CF(e,t,r){return`${e}tools/mailmerge/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}y.getMailMergeTemplateDesignerUrl=CF;function SF(e,t,r){return`${e}biz/roles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}y.getSecurityRoleDesignerUrl=SF;function EF(e,t,r){return`${e}biz/fieldsecurityprofiles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}y.getFieldSecurityProfileDesignerUrl=EF;function NF(e,t,r){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?_CreateFromId=%7b${t}%7d&_CreateFromType=7100&appSolutionId=%7b${t}%7d&id=%7b${r}%7d`}y.getArticleTemplateUrl=NF;function DF(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}`}y.getEnableSecurityRolesUrl=DF;function IF(e){return`${e}tools/publisher/edit.aspx`}y.getCreateNewPublisherUrl=IF;function _F(e,t){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?appSolutionId=${t}`}y.getCreateNewArticleTemplateUrl=_F;y.solutionComponentDefinitionsQueryUrl="api/data/v9.0/solutioncomponentdefinitions";y.entityDefinitionsQueryUrl="api/data/v9.0/EntityDefinitions?$select=EntitySetName,DisplayName,LogicalName&$filter=";y.workflowsQueryUrl="api/data/v9.0/workflows";y.chartsQueryUrl="/api/data/v9.0/savedqueryvisualizations";y.solutionComponentConfigurationsQueryUrl="/api/data/v9.1/solutioncomponentconfigurations?$filter=isdisplayable eq true&$select=name";y.solutionComponentSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentsummaries";y.solutionComponentCountSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentcountsummaries";function PF(e,t){return`${y.xrmApiUrl}/RetrieveRequiredComponents(ObjectId=${e},ComponentType=${t})`}y.getRequiredComponentsQueryUrl=PF;function TF(e,t){return`${y.cdsServiceUrl}${y.xrmApiUrl}/RetrieveDependentComponentsWithMetadata(ObjectId=${e},ComponentType=${t})`}y.getDependentComponentsWithMetadataQueryUrl=TF;y.solutionsQueryUrl="/api/data/v9.0/solutions?$expand=publisherid&$filter=(isvisible eq true)";function OF(e){return`/api/data/v9.0/solutions?$expand=publisherid&$filter=(uniquename eq '${e}')`}y.getSolutionsByUniqueNameQueryUrl=OF;function RF(e){return`/api/data/v9.0/solutions(${e})?$expand=publisherid`}y.getSolutionQueryUrl=RF;function FF(e){return`${e}api/data/v9.1/ProvisionLanguageForUser`}y.getProvisionLanguageUrl=FF;y.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 xF(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"}};Y.ValidationError=dc;var pc=class extends et{constructor(t){super("INVALID_ARGUMENT",t)}};Y.InvalidArgumentError=pc;var fc=class extends et{constructor(t,r,n){super("STALE_ARTIFACT",`Cannot apply the edit at ${n} to ${t}/${r}: the cached copy was stale and the server copy has since changed, so any pointer derived from the old copy may now identify a different node. The local copy has been refreshed \u2014 re-read the artifact, re-derive the pointer, and retry.`),this.type=t,this.id=r,this.pointer=n}};Y.StaleArtifactError=fc;var mc=class extends et{constructor(t,r,n,i){super("LOCAL_EDITS_WOULD_BE_LOST",`Refusing to fetch ${t}/${r}: the local copy has unpushed edits AND the server has moved since it was fetched (local=${n??"(none)"}, server=${i??"(none)"}). Overwriting now would discard your edits and replace them with another writer's changes. Push or discard your edits first, or pass { overwrite: true } to deliberately reset the local copy to the server version.`),this.type=t,this.id=r,this.localEtag=n,this.serverEtag=i}};Y.LocalEditsWouldBeLostError=mc;var hc=class extends et{constructor(t,r,n,i,a){super("VERSION_CONFLICT",`Version conflict for ${t}/${r}: local=${n??"(none)"}, server=${i??"(none)"}. Re-fetch and reapply changes.${a?` ${a}`:""}`),this.type=t,this.id=r,this.localEtag=n,this.serverEtag=i,this.detail=a}};Y.VersionConflictError=hc;var gc=class extends et{constructor(t,r,n,i){super("CONNECTION_ERROR",r>0?`HTTP ${r} from ${t}: ${n}`:`Transport failure reaching ${t}: ${n}`),this.url=t,this.statusCode=r,this.cause=i}};Y.ConnectionError=gc;var vc=class extends et{constructor(t){super("WORKSPACE_NOT_INITIALIZED",`Workspace not initialized at ${t}. Call initWorkspace() first.`),this.workspacePath=t}};Y.WorkspaceNotInitializedError=vc;var yc=class extends et{constructor(t,r){super("NOT_IMPLEMENTED",`Operation '${t}' is not implemented yet${r?`: ${r}`:""}.`),this.operation=t}};Y.NotImplementedError=yc;var bc=class extends et{constructor(t,r){super("INVALID_JSON_POINTER",`Invalid JSON Pointer '${t}': ${r}`),this.pointer=t}};Y.JsonPointerError=bc;var wc=class extends et{constructor(t,r,n){super("AMBIGUOUS_ARTIFACT",`Found ${n} ${t} rows matching '${r}'; a name is not a unique key. Resolve by id / alternate key instead of relying on name-based idempotency.`),this.kind=t,this.identity=r,this.matchCount=n}};Y.AmbiguousArtifactError=wc;var Ac=class extends et{constructor(t,r){super("PATH_TRAVERSAL",`Refusing to resolve a path outside the workspace root: '${t}' is not within '${r}'.`),this.target=t,this.root=r}};Y.PathTraversalError=Ac;var Cc=class extends et{constructor(t,r){super("INCOMPATIBLE_WORKSPACE",`Workspace schema version ${t} is newer than this SDK supports (v${r}). Upgrade the SDK, or re-create the workspace with this version.`),this.workspaceVersion=t,this.supportedVersion=r}};Y.IncompatibleWorkspaceError=Cc});var ee=g(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.odataQuery=Fe.normalizeGuid=Fe.createSafeXmlElement=Fe.assertNoControlChars=Fe.assertODataName=Fe.assertXmlName=Fe.xmlText=Fe.odataPathLiteral=Fe.odataLiteral=void 0;var ms=ie();function Cg(e){return String(e??"").replace(/'/g,"''")}Fe.odataLiteral=Cg;function EP(e){return encodeURIComponent(Cg(e))}Fe.odataPathLiteral=EP;function NP(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}Fe.xmlText=NP;function Sg(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 ms.InvalidArgumentError(`${t} must be a valid XML element name (got '${e}')`);return e}Fe.assertXmlName=Sg;function DP(e,t){let r=String(e??"");if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw new ms.InvalidArgumentError(`${t} must be a valid OData identifier (letters, digits, underscore): got '${e}'`);return e}Fe.assertODataName=DP;function IP(e,t){if(/[\u0000-\u001F\u007F]/.test(String(e??"")))throw new ms.InvalidArgumentError(`${t} must not contain control characters (including CR/LF): they would inject additional lines into the request`);return e}Fe.assertNoControlChars=IP;function _P(e,t,r){return e.createElement(Sg(t,r))}Fe.createSafeXmlElement=_P;var PP=/^[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 TP(e,t){let r=String(e??""),n=r.length===38&&r.startsWith("{")&&r.endsWith("}")?r.slice(1,-1):r;if(!PP.test(n))throw new ms.InvalidArgumentError(`${t} must be a valid GUID (got '${e}')`);return n.toLowerCase()}Fe.normalizeGuid=TP;function OP(e){let t=[];for(let[r,n]of e)n!=null&&n!==""&&t.push(`${r}=${encodeURIComponent(String(n))}`);return t.length>0?`?${t.join("&")}`:""}Fe.odataQuery=OP});var be=g(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.nowIso=te.isAlreadyDeleted=te.deleteRecord=te.ensureSuccess=te.resolveCreatedId=te.requireCreatedId=te.withClientMintedId=te.readCreatedId=te.readEtag=te.requireEtag=te.echoWrite=te.UPDATE_NO_ETAG_CODE=te.VERSION_CONFLICT_CODE=void 0;var pi=ie(),xa=ee();te.VERSION_CONFLICT_CODE="VERSION_CONFLICT";te.UPDATE_NO_ETAG_CODE="ARTIFACT_UPDATE_NO_ETAG";function RP(e,t){return{query:`?$select=${encodeURIComponent(e)}`,options:{headers:{...t??{},Prefer:"return=representation"}}}}te.echoWrite=RP;function FP(e,t,r){if(!e)throw new pi.SdkError(te.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}te.requireEtag=FP;function xP(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}te.readEtag=xP;function Sc(e,t){var r;let n=e.body;if(n&&typeof n[t]=="string")return(0,xa.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,xa.normalizeGuid)(o[1],t)}return null}te.readCreatedId=Sc;function LP(e,t,r){return r?{...e,[t]:(0,xa.normalizeGuid)(r,t)}:e}te.withClientMintedId=LP;function kP(e,t,r){let n=Sc(e,t);if(!n)throw new pi.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`);return n}te.requireCreatedId=kP;function MP(e,t,r,n){let i=Sc(e,t);if(i)return i;if(n)return(0,xa.normalizeGuid)(n,t);throw new pi.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`)}te.resolveCreatedId=MP;function Eg(e,t){if(e.status===412)throw new pi.SdkError(te.VERSION_CONFLICT_CODE,`Version conflict (412) from ${t}`);if(e.status<200||e.status>=300)throw new pi.ConnectionError(t,e.status,UP(e.body),e.body);return e}te.ensureSuccess=Eg;function UP(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 BP(e,t,r,n){let i=(0,xa.normalizeGuid)(r,"id"),a=`/${t}(${i})`;Eg(await e.delete(a,n?{headers:{"If-Match":n}}:void 0),e.apiUrl(a))}te.deleteRecord=BP;function $P(e){return e instanceof pi.ConnectionError&&e.statusCode===404}te.isAlreadyDeleted=$P;function qP(){return new Date().toISOString()}te.nowIso=qP});var Kt=g(fi=>{"use strict";Object.defineProperty(fi,"__esModule",{value:!0});fi.describeMalformedValue=fi.collectPages=void 0;var Ng=be(),Ec=ie();async function VP(e,t,r){let n=[],i=new Set,a=e.apiUrl(t),o=(0,Ng.ensureSuccess)(await e.get(t),a);for(;;){let s=o.body,l=s?.value;if(!Array.isArray(l))throw new Ec.ConnectionError(a,o.status,`${r}: paginated read returned a malformed page \u2014 expected an OData 'value' array but got ${Nc(l)}; refusing to return partial results.`);for(let c of l)n.push(c);let u=s?.["@odata.nextLink"];if(u==null)break;if(typeof u!="string"||u.length===0)throw new Ec.ConnectionError(a,o.status,`${r}: paginated read returned a malformed @odata.nextLink (${Nc(u)}); cannot follow it, and refusing to return partial results.`);if(i.has(u))throw new Ec.InvalidArgumentError(`${r}: aborting pagination \u2014 the server returned a repeated @odata.nextLink ('${u}'), which would loop indefinitely.`);i.add(u),a=u,o=(0,Ng.ensureSuccess)(await e.getAbsolute(u),u)}return n}fi.collectPages=VP;function Nc(e){return e===null?"null":e===void 0?"undefined (missing)":`a ${typeof e}`}fi.describeMalformedValue=Nc});var Dc=g(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.businessRuleApi=ur.BUSINESS_RULE_LEFT_DEACTIVATED_CODE=ur.WFOM_API_UNAVAILABLE_CODE=void 0;var xr=Mn(),GP=Kt(),tt=be(),an=ee(),gs=ie();ur.WFOM_API_UNAVAILABLE_CODE="BUSINESS_RULE_API_UNAVAILABLE";ur.BUSINESS_RULE_LEFT_DEACTIVATED_CODE="BUSINESS_RULE_LEFT_DEACTIVATED";async function Dg(e,t,r,n){let i=`/workflows(${jP})/Microsoft.Dynamics.CRM.${t}`;try{return(0,tt.ensureSuccess)(await e.post(i,{Entity:r.Entity,WfomJson:r.WfomJson},{headers:n}),e.apiUrl(i))}catch(a){throw a?.statusCode!==404?a:new gs.SdkError(ur.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 zP(e,t){let r=`/workflows(${t})${(0,an.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,tt.readEtag)(n),statecode:typeof i?.statecode=="number"?i.statecode:null,statuscode:typeof i?.statuscode=="number"?i.statuscode:null}}catch{return null}}async function WP(e,t,r){let n=await zP(e,t);if(n===null||n.etag===null)throw new gs.SdkError(tt.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 gs.SdkError(tt.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 jP="00000000-0000-0000-0000-000000000000",hs={"Content-Type":"application/json",Accept:"application/json","OData-Version":"4.0","OData-MaxVersion":"4.0"},HP="workflowid,name,description,primaryentity,statecode,category,type",QP="category eq 2 and type eq 1";async function Ig(e,t,r){var n;if(r==="Draft")return null;let i=(0,an.normalizeGuid)(t,"workflowid"),a=r==="Active",o={statecode:a?xr.StateCode.Activated:xr.StateCode.Draft,statuscode:a?xr.StatusCode.Activated:xr.StatusCode.Draft},s=`/workflows(${i})`,l=(0,tt.ensureSuccess)(await e.patch(s,o,{headers:hs}),e.apiUrl(s));return(n=(0,tt.readEtag)(l))!==null&&n!==void 0?n:await La(e,i)}async function La(e,t){let r=`/workflows(${t})${(0,an.odataQuery)([["$select","workflowid"]])}`;try{let n=await e.get(r);return n.status>=200&&n.status<300?(0,tt.readEtag)(n):null}catch{return null}}async function JP(e,t,r){let n=await La(e,t),i=await r(),a=(0,tt.readEtag)(i);if(a)return{response:i,etag:a};let o=await La(e,t);return{response:i,etag:n!==null&&n===o?o:null}}ur.businessRuleApi={async get(e,t){let r=(0,an.normalizeGuid)(t,"id"),n=`/workflows(${r})/Microsoft.Dynamics.CRM.RetrieveProcessWithWfomJson`,{response:i,etag:a}=await JP(e,r,async()=>(0,tt.ensureSuccess)(await e.get(n),e.apiUrl(n)));return{raw:i.body,etag:a}},async list(e,t){let r=[QP];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,an.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,an.odataQuery)([["$select",HP],["$filter",r.join(" and ")]])}`;return(await(0,GP.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,an.normalizeGuid)(n.Entity.workflowid,"workflowid"),a=await Dg(e,"CreateProcessWithWfomJson",n,hs),o=(0,tt.resolveCreatedId)(a,"workflowid","business rule",i),s=null;try{s=await Ig(e,o,n.status)}catch(l){try{await(0,tt.deleteRecord)(e,"workflows",o)}catch{}throw l}return{id:o,etag:(r=s??(0,tt.readEtag)(a))!==null&&r!==void 0?r:await La(e,o)}},async update(e,t,r,n){var i,a;let o=r,s=(0,an.normalizeGuid)(t,"id"),l=`/workflows(${s})`,u={...hs,"If-Match":(0,tt.requireEtag)(n,"business rule",s)},c=await WP(e,s,u["If-Match"]),d=c.statecode===xr.StateCode.Activated;d&&(0,tt.ensureSuccess)(await e.patch(l,{statecode:xr.StateCode.Draft,statuscode:xr.StatusCode.Draft},{headers:u}),e.apiUrl(l));let p;try{p=await Dg(e,"UpdateProcessWithWfomJson",o,u)}catch(h){if(d)try{(0,tt.ensureSuccess)(await e.patch(l,{statecode:xr.StateCode.Activated,statuscode:(i=c.statuscode)!==null&&i!==void 0?i:xr.StatusCode.Activated},{headers:hs}),e.apiUrl(l))}catch(y){throw new gs.SdkError(ur.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: ${h instanceof Error?h.message:String(h)}. Restore failure: ${y instanceof Error?y.message:String(y)}`)}throw h}let f=await Ig(e,s,o.status);return{id:s,etag:(a=f??(0,tt.readEtag)(p))!==null&&a!==void 0?a:await La(e,s)}},delete(e,t){return(0,tt.deleteRecord)(e,"workflows",t)}}});var _g=g(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});Ic.default="ffffffff-ffff-ffff-ffff-ffffffffffff"});var Pg=g(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});_c.default="00000000-0000-0000-0000-000000000000"});var Tg=g(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});Pc.default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i});var ka=g(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});var XP=Tg();function KP(e){return typeof e=="string"&&XP.default.test(e)}Tc.default=KP});var Ma=g(Oc=>{"use strict";Object.defineProperty(Oc,"__esModule",{value:!0});var YP=ka();function ZP(e){if(!(0,YP.default)(e))throw TypeError("Invalid UUID");let t;return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,t&255,(t=parseInt(e.slice(9,13),16))>>>8,t&255,(t=parseInt(e.slice(14,18),16))>>>8,t&255,(t=parseInt(e.slice(19,23),16))>>>8,t&255,(t=parseInt(e.slice(24,36),16))/1099511627776&255,t/4294967296&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255)}Oc.default=ZP});var Lr=g(Ua=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});Ua.unsafeStringify=void 0;var eT=ka(),rt=[];for(let e=0;e<256;++e)rt.push((e+256).toString(16).slice(1));function Og(e,t=0){return(rt[e[t+0]]+rt[e[t+1]]+rt[e[t+2]]+rt[e[t+3]]+"-"+rt[e[t+4]]+rt[e[t+5]]+"-"+rt[e[t+6]]+rt[e[t+7]]+"-"+rt[e[t+8]]+rt[e[t+9]]+"-"+rt[e[t+10]]+rt[e[t+11]]+rt[e[t+12]]+rt[e[t+13]]+rt[e[t+14]]+rt[e[t+15]]).toLowerCase()}Ua.unsafeStringify=Og;function tT(e,t=0){let r=Og(e,t);if(!(0,eT.default)(r))throw TypeError("Stringified UUID is invalid");return r}Ua.default=tT});var bs=g(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});var rT=require("crypto"),ys=new Uint8Array(256),vs=ys.length;function nT(){return vs>ys.length-16&&((0,rT.randomFillSync)(ys),vs=0),ys.slice(vs,vs+=16)}Rc.default=nT});var Fc=g($a=>{"use strict";Object.defineProperty($a,"__esModule",{value:!0});$a.updateV1State=void 0;var Rg=bs(),iT=Lr(),Ba={};function aT(e,t,r){let n,i=e?._v6??!1;if(e){let a=Object.keys(e);a.length===1&&a[0]==="_v6"&&(e=void 0)}if(e)n=Fg(e.random??e.rng?.()??(0,Rg.default)(),e.msecs,e.nsecs,e.clockseq,e.node,t,r);else{let a=Date.now(),o=(0,Rg.default)();xg(Ba,a,o),n=Fg(o,Ba.msecs,Ba.nsecs,i?void 0:Ba.clockseq,i?void 0:Ba.node,t,r)}return t??(0,iT.unsafeStringify)(n)}function xg(e,t,r){return e.msecs??=-1/0,e.nsecs??=0,t===e.msecs?(e.nsecs++,e.nsecs>=1e4&&(e.node=void 0,e.nsecs=0)):t>e.msecs?e.nsecs=0:t<e.msecs&&(e.node=void 0),e.node||(e.node=r.slice(10,16),e.node[0]|=1,e.clockseq=(r[8]<<8|r[9])&16383),e.msecs=t,e}$a.updateV1State=xg;function Fg(e,t,r,n,i,a,o=0){if(e.length<16)throw new Error("Random bytes length must be >= 16");if(!a)a=new Uint8Array(16),o=0;else if(o<0||o+16>a.length)throw new RangeError(`UUID byte range ${o}:${o+15} is out of buffer bounds`);t??=Date.now(),r??=0,n??=(e[8]<<8|e[9])&16383,i??=e.slice(10,16),t+=122192928e5;let s=((t&268435455)*1e4+r)%4294967296;a[o++]=s>>>24&255,a[o++]=s>>>16&255,a[o++]=s>>>8&255,a[o++]=s&255;let l=t/4294967296*1e4&268435455;a[o++]=l>>>8&255,a[o++]=l&255,a[o++]=l>>>24&15|16,a[o++]=l>>>16&255,a[o++]=n>>>8|128,a[o++]=n&255;for(let u=0;u<6;++u)a[o++]=i[u];return a}$a.default=aT});var Lc=g(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});var oT=Ma(),sT=Lr();function lT(e){let t=typeof e=="string"?(0,oT.default)(e):e,r=uT(t);return typeof e=="string"?(0,sT.unsafeStringify)(r):r}xc.default=lT;function uT(e){return Uint8Array.of((e[6]&15)<<4|e[7]>>4&15,(e[7]&15)<<4|(e[4]&240)>>4,(e[4]&15)<<4|(e[5]&240)>>4,(e[5]&15)<<4|(e[0]&240)>>4,(e[0]&15)<<4|(e[1]&240)>>4,(e[1]&15)<<4|(e[2]&240)>>4,96|e[2]&15,e[3],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}});var Lg=g(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});var cT=require("crypto");function dT(e){return Array.isArray(e)?e=Buffer.from(e):typeof e=="string"&&(e=Buffer.from(e,"utf8")),(0,cT.createHash)("md5").update(e).digest()}kc.default=dT});var qa=g(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});kr.URL=kr.DNS=kr.stringToBytes=void 0;var kg=Ma(),pT=Lr();function Mg(e){e=unescape(encodeURIComponent(e));let t=new Uint8Array(e.length);for(let r=0;r<e.length;++r)t[r]=e.charCodeAt(r);return t}kr.stringToBytes=Mg;kr.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8";kr.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function fT(e,t,r,n,i,a){let o=typeof r=="string"?Mg(r):r,s=typeof n=="string"?(0,kg.default)(n):n;if(typeof n=="string"&&(n=(0,kg.default)(n)),n?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let l=new Uint8Array(16+o.length);if(l.set(s),l.set(o,s.length),l=t(l),l[6]=l[6]&15|e,l[8]=l[8]&63|128,i){if(a=a||0,a<0||a+16>i.length)throw new RangeError(`UUID byte range ${a}:${a+15} is out of buffer bounds`);for(let u=0;u<16;++u)i[a+u]=l[u];return i}return(0,pT.unsafeStringify)(l)}kr.default=fT});var Bg=g(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.URL=Un.DNS=void 0;var mT=Lg(),Mc=qa(),Ug=qa();Object.defineProperty(Un,"DNS",{enumerable:!0,get:function(){return Ug.DNS}});Object.defineProperty(Un,"URL",{enumerable:!0,get:function(){return Ug.URL}});function Uc(e,t,r,n){return(0,Mc.default)(48,mT.default,e,t,r,n)}Uc.DNS=Mc.DNS;Uc.URL=Mc.URL;Un.default=Uc});var $g=g(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});var hT=require("crypto");Bc.default={randomUUID:hT.randomUUID}});var Vg=g($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});var qg=$g(),gT=bs(),vT=Lr();function yT(e,t,r){if(qg.default.randomUUID&&!t&&!e)return qg.default.randomUUID();e=e||{};let n=e.random??e.rng?.()??(0,gT.default)();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(0,vT.unsafeStringify)(n)}$c.default=yT});var Gg=g(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});var bT=require("crypto");function wT(e){return Array.isArray(e)?e=Buffer.from(e):typeof e=="string"&&(e=Buffer.from(e,"utf8")),(0,bT.createHash)("sha1").update(e).digest()}qc.default=wT});var Wg=g(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.URL=Bn.DNS=void 0;var AT=Gg(),Vc=qa(),zg=qa();Object.defineProperty(Bn,"DNS",{enumerable:!0,get:function(){return zg.DNS}});Object.defineProperty(Bn,"URL",{enumerable:!0,get:function(){return zg.URL}});function Gc(e,t,r,n){return(0,Vc.default)(80,AT.default,e,t,r,n)}Gc.DNS=Vc.DNS;Gc.URL=Vc.URL;Bn.default=Gc});var jg=g(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});var CT=Lr(),ST=Fc(),ET=Lc();function NT(e,t,r){e??={},r??=0;let n=(0,ST.default)({...e,_v6:!0},new Uint8Array(16));if(n=(0,ET.default)(n),t){if(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(0,CT.unsafeStringify)(n)}zc.default=NT});var Hg=g(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});var DT=Ma(),IT=Lr();function _T(e){let t=typeof e=="string"?(0,DT.default)(e):e,r=PT(t);return typeof e=="string"?(0,IT.unsafeStringify)(r):r}Wc.default=_T;function PT(e){return Uint8Array.of((e[3]&15)<<4|e[4]>>4&15,(e[4]&15)<<4|(e[5]&240)>>4,(e[5]&15)<<4|e[6]&15,e[7],(e[1]&15)<<4|(e[2]&240)>>4,(e[2]&15)<<4|(e[3]&240)>>4,16|(e[0]&240)>>4,(e[0]&15)<<4|(e[1]&240)>>4,e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}});var Kg=g(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});Va.updateV7State=void 0;var Qg=bs(),TT=Lr(),jc={};function OT(e,t,r){let n;if(e)n=Jg(e.random??e.rng?.()??(0,Qg.default)(),e.msecs,e.seq,t,r);else{let i=Date.now(),a=(0,Qg.default)();Xg(jc,i,a),n=Jg(a,jc.msecs,jc.seq,t,r)}return t??(0,TT.unsafeStringify)(n)}function Xg(e,t,r){return e.msecs??=-1/0,e.seq??=0,t>e.msecs?(e.seq=r[6]<<23|r[7]<<16|r[8]<<8|r[9],e.msecs=t):(e.seq=e.seq+1|0,e.seq===0&&e.msecs++),e}Va.updateV7State=Xg;function Jg(e,t,r,n,i=0){if(e.length<16)throw new Error("Random bytes length must be >= 16");if(!n)n=new Uint8Array(16),i=0;else if(i<0||i+16>n.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);return t??=Date.now(),r??=e[6]*127<<24|e[7]<<16|e[8]<<8|e[9],n[i++]=t/1099511627776&255,n[i++]=t/4294967296&255,n[i++]=t/16777216&255,n[i++]=t/65536&255,n[i++]=t/256&255,n[i++]=t&255,n[i++]=112|r>>>28&15,n[i++]=r>>>20&255,n[i++]=128|r>>>14&63,n[i++]=r>>>6&255,n[i++]=r<<2&255|e[10]&3,n[i++]=e[11],n[i++]=e[12],n[i++]=e[13],n[i++]=e[14],n[i++]=e[15],n}Va.default=OT});var Yg=g(Hc=>{"use strict";Object.defineProperty(Hc,"__esModule",{value:!0});var RT=ka();function FT(e){if(!(0,RT.default)(e))throw TypeError("Invalid UUID");return parseInt(e.slice(14,15),16)}Hc.default=FT});var ws=g(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.version=re.validate=re.v7=re.v6ToV1=re.v6=re.v5=re.v4=re.v3=re.v1ToV6=re.v1=re.stringify=re.parse=re.NIL=re.MAX=void 0;var xT=_g();Object.defineProperty(re,"MAX",{enumerable:!0,get:function(){return xT.default}});var LT=Pg();Object.defineProperty(re,"NIL",{enumerable:!0,get:function(){return LT.default}});var kT=Ma();Object.defineProperty(re,"parse",{enumerable:!0,get:function(){return kT.default}});var MT=Lr();Object.defineProperty(re,"stringify",{enumerable:!0,get:function(){return MT.default}});var UT=Fc();Object.defineProperty(re,"v1",{enumerable:!0,get:function(){return UT.default}});var BT=Lc();Object.defineProperty(re,"v1ToV6",{enumerable:!0,get:function(){return BT.default}});var $T=Bg();Object.defineProperty(re,"v3",{enumerable:!0,get:function(){return $T.default}});var qT=Vg();Object.defineProperty(re,"v4",{enumerable:!0,get:function(){return qT.default}});var VT=Wg();Object.defineProperty(re,"v5",{enumerable:!0,get:function(){return VT.default}});var GT=jg();Object.defineProperty(re,"v6",{enumerable:!0,get:function(){return GT.default}});var zT=Hg();Object.defineProperty(re,"v6ToV1",{enumerable:!0,get:function(){return zT.default}});var WT=Kg();Object.defineProperty(re,"v7",{enumerable:!0,get:function(){return WT.default}});var jT=ka();Object.defineProperty(re,"validate",{enumerable:!0,get:function(){return jT.default}});var HT=Yg();Object.defineProperty(re,"version",{enumerable:!0,get:function(){return HT.default}})});function As(e,t){return e==="SetFieldValue"&&t!==void 0&&QT.has(t.attributeType)&&(t.requiredLevel==="None"||t.requiredLevel==="Recommended")}var QT,Qc=I(()=>{"use strict";QT=new Set(["Integer","Double","Decimal","Money","String","Memo","DateTime","Picklist","Lookup"])});function Zg(e){return e!=="Entity"&&e!=="AllForms"&&typeof e=="string"&&e.trim()!==""}function Jc(e){return Zg(e)?1:2}function Xc(e){return Zg(e)?e:void 0}function e0(e,t){let r=Xc(e.scope);return{"@odata.type":"#Microsoft.Dynamics.CRM.workflow",name:e.name,description:e.description,workflowid:t,ondemand:!1,subprocess:!1,triggeroncreate:!1,triggerondelete:!1,category:mi.WorkflowCategory.BusinessRule,type:mi.WorkflowTypeCode.Definition,mode:1,scope:mi.WorkflowScope.Organization,primaryentity:e.entityLogicalName,iscrmuiworkflow:!0,processtriggerscope:Jc(e.scope),...r!==void 0?{processtriggerformid:r}:{}}}var mi,t0=I(()=>{"use strict";mi=se(Mn());});function r0(e,t=0){return(nt[e[t+0]]+nt[e[t+1]]+nt[e[t+2]]+nt[e[t+3]]+"-"+nt[e[t+4]]+nt[e[t+5]]+"-"+nt[e[t+6]]+nt[e[t+7]]+"-"+nt[e[t+8]]+nt[e[t+9]]+"-"+nt[e[t+10]]+nt[e[t+11]]+nt[e[t+12]]+nt[e[t+13]]+nt[e[t+14]]+nt[e[t+15]]).toLowerCase()}var nt,n0=I(()=>{nt=[];for(let e=0;e<256;++e)nt.push((e+256).toString(16).slice(1))});function Kc(){return Cs>Ss.length-16&&((0,i0.randomFillSync)(Ss),Cs=0),Ss.slice(Cs,Cs+=16)}var i0,Ss,Cs,a0=I(()=>{i0=require("crypto"),Ss=new Uint8Array(256),Cs=Ss.length});var o0,Yc,s0=I(()=>{o0=require("crypto"),Yc={randomUUID:o0.randomUUID}});function JT(e,t,r){if(Yc.randomUUID&&!t&&!e)return Yc.randomUUID();e=e||{};let n=e.random??e.rng?.()??Kc();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 r0(n)}var dt,l0=I(()=>{s0();a0();n0();dt=JT});var Zc=I(()=>{l0()});var u0=I(()=>{"use strict";});var ed=g(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.WorkflowConditionOperator=Lt.WorkflowAttributeType=Lt.SystemStep=Lt.FieldRequiredLevelTypes=Lt.AttributeDateTimeBehavior=void 0;Lt.AttributeDateTimeBehavior={None:0,Dynamic:1,DateOnly:2,StaticTimeZoneInvariant:3,UserLocal:4};Lt.FieldRequiredLevelTypes={None:"0",Required:"1",Recommended:"2"};Lt.SystemStep={IdentifyContact:"IdentifyContact",IdentifyAccount:"IdentifyAccount",IdentifyCustomer:"IdentifyCustomer",IdentifyCase:"IdentifyCase",Solution:"Solution",Resolve:"Resolve"};Lt.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"};Lt.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 f0(e){switch(e){case"Boolean":return fe.WorkflowAttributeType.Boolean;case"Customer":return fe.WorkflowAttributeType.Customer;case"DateTime":return fe.WorkflowAttributeType.DateTime;case"Decimal":return fe.WorkflowAttributeType.Decimal;case"Double":return fe.WorkflowAttributeType.Float;case"Integer":return fe.WorkflowAttributeType.Integer;case"Lookup":return fe.WorkflowAttributeType.Lookup;case"Money":return fe.WorkflowAttributeType.Money;case"Owner":return fe.WorkflowAttributeType.Owner;case"Picklist":return fe.WorkflowAttributeType.Picklist;case"State":return fe.WorkflowAttributeType.State;case"Status":return fe.WorkflowAttributeType.Status;case"Uniqueidentifier":case"UniqueIdentifier":return fe.WorkflowAttributeType.UniqueIdentifier;case"BigInt":return fe.WorkflowAttributeType.BigType;default:return fe.WorkflowAttributeType.String}}function w0(e){return e&&e!==fe.WorkflowAttributeType.String?e:void 0}function YT(e){return{__class:b0,parameterName:"primaryEntity",entityName:e}}function c0(e){return{__class:rd,type:td,typeSet:!1,behavior:fe.AttributeDateTimeBehavior.None,method:m0,parameters:[e]}}function d0(e,t,r=fe.WorkflowAttributeType.String){return{__class:g0,type:r,behavior:fe.AttributeDateTimeBehavior.None,typeSet:!1,entity:YT(t),attributeName:e}}function ZT(e,t=fe.WorkflowAttributeType.String){return{__class:v0,type:t,behavior:fe.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function eO(e){return{__class:y0,type:td,typeSet:!1,behavior:fe.AttributeDateTimeBehavior.None,days:e,hours:"0",minutes:"0",months:"0",years:"0"}}function A0(e,t){let r=XT[e.operator],n=c0(d0(e.leftField,t,e.leftWorkflowType)),i;e.dateArithmetic?i=eO(e.right.value??"0"):e.right.kind==="field"?i=d0(e.right.field??"",t,e.right.workflowType):i=ZT(e.right.value??"",e.right.workflowType??e.leftWorkflowType);let a=c0(i);return{__class:rd,type:td,typeSet:!1,behavior:fe.AttributeDateTimeBehavior.None,method:h0,parameters:[r,n,a]}}function C0(e){return typeof e=="object"&&e.__class===rd}function tO(e){return typeof e=="object"&&e.__class===y0}function Es(e){return C0(e)&&e.method===m0&&e.parameters.length>0?Es(e.parameters[0]):e}function p0(e){if(typeof e!="object"||e.__class!==g0)return null;let t=e.entity;if(t&&t.__class&&t.__class!==b0)return null;let r=e.attributeName;return r?{field:r,workflowType:w0(e.type)}:null}function S0(e){if(!e)return null;let t=Es(e);if(!C0(t)||t.method!==h0||t.parameters.length!==3)return null;let r=t.parameters[0],n=KT[String(r)];if(!n)return null;let i=p0(Es(t.parameters[1]));if(!i)return null;let a=Es(t.parameters[2]);if(tO(a))return n!=="+"&&n!=="-"?null:{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:String(a.days??"")},dateArithmetic:!0};let o=p0(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===v0){let s=a.primitiveValue;return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:s!=null?String(s):"",workflowType:w0(a.type)}}}return null}function hi(e){return!e||!e.leftField?!1:e.right.kind==="field"?!!(e.right.field&&e.right.field.trim()):!!(e.right.value&&e.right.value.trim())}var fe,m0,h0,td,g0,v0,rd,y0,b0,XT,KT,Ns=I(()=>{"use strict";fe=se(ed());m0="0",h0="3",td="0",g0="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",v0="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",rd="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",y0="TimeSpanExpression:#Microsoft.Crm.Workflow.Expressions",b0="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions";XT={"+":0,"-":1,"*":2,"/":3},KT={0:"+",1:"-",2:"*",3:"/"}});function E0(e){return e.__class==="BinaryExpression:#Microsoft.Crm.Workflow.Expressions"}function rO(e){return e.__class==="ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel"}function Ga(){return{list:[]}}function N0(e,t,r){return e&&e.list.length>0?{list:[{...e.list[0],description:t},...e.list.slice(1)]}:{list:[{labelId:dt(),languageCode:r,description:t}]}}function od(e){return{__class:"PrimaryEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:"primaryEntity",entityName:e}}function sd(e,t,r){return{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:G.AttributeDateTimeBehavior.None,typeSet:!1,entity:od(t),attributeName:e}}function za(e,t){return{__class:"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",type:t,behavior:G.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function R0(e){return{__class:"LookupExpression:#Microsoft.Crm.Workflow.Expressions",type:e.workflowType??G.WorkflowAttributeType.Lookup,behavior:G.AttributeDateTimeBehavior.None,typeSet:!1,entityType:e.entityType,label:e.label,staticValue:za(e.id.replace(/[{}]/g,""),G.WorkflowAttributeType.UniqueIdentifier)}}function D0(e,t){let r=e.valueType==="Lookup"?e.lookupValue?.workflowType??G.WorkflowAttributeType.Lookup:e.valueType==="Clear"?e.valueWorkflowType??G.WorkflowAttributeType.String:G.WorkflowAttributeType.String,n=ad[e.operator]??G.WorkflowConditionOperator.Equal,i=sd(e.field,t,r),a;if(e.operator==="ContainsData"||e.operator==="DoesNotContainData")a=[];else if(e.valueType==="Field"&&e.valueField)a=[sd(e.valueField,t,r)];else if(e.valueType==="Lookup"){if(!e.lookupValue)throw new Error("Lookup condition is missing its record value.");a=[R0(e.lookupValue)]}else e.valueType==="Clear"?a=[za(null,r)]:e.valueType==="Expression"?a=[Is(e.valueType,e.value,e.valueField,t,e.expression,e.rawExpression)]:a=[za(e.value??"",r)];return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:G.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:i,right:a}}function nO(e,t,r){if(e.length===0)return null;if(e.length===1)return D0(e[0],r);let n=t==="AND"?G.WorkflowConditionOperator.LogicalAnd:G.WorkflowConditionOperator.LogicalOr,[i,...a]=e.map(o=>D0(o,r));return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:G.WorkflowAttributeType.String,behavior:G.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:i,right:a}}function Ds(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!==G.WorkflowAttributeType.Lookup?{workflowType:e.type}:{}}}}if(e.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"){let t=S0(e);return t?{valueType:"Expression",expression:t}:{valueType:"Expression",rawExpression:e}}return{valueType:"Value",value:""}}function nd(e){let t=O0[e.conditionOperatoroperator]??"Equals",r=e.left.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions"?e.left.attributeName:"",i=t==="ContainsData"||t==="DoesNotContainData"?{valueType:"Value"}:Ds(e.right[0]);return{id:dt(),field:r,fieldDisplayName:r,operator:t,...i}}function I0(e){if(!e||e.__class!=="BinaryExpression:#Microsoft.Crm.Workflow.Expressions")return{clauses:[],logic:"AND"};let t=e.conditionOperatoroperator;if(t===G.WorkflowConditionOperator.LogicalAnd||t===G.WorkflowConditionOperator.LogicalOr){let r=t===G.WorkflowConditionOperator.LogicalAnd?"AND":"OR";return{clauses:[...E0(e.left)?[nd(e.left)]:[],...e.right.filter(E0).map(nd)],logic:r}}return{clauses:[nd(e)],logic:"AND"}}function Is(e,t,r,n,i,a,o,s){if(e==="Field"&&r)return sd(r,n,G.WorkflowAttributeType.String);if(e==="Expression"){if(i)return A0(i,n);if(a!=null)return a}return e==="Lookup"&&o?R0(o):e==="Clear"?za(null,s??G.WorkflowAttributeType.String):za(t??"",G.WorkflowAttributeType.String)}function id(e,t){return{propertyName:e,propertyValueExpr:t}}function gi(e){return`Step_${e.value++}`}function kt(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 _0(e,t,r){return e&&!r.used.has(e)?(r.used.add(e),e):kt(t,r)}function iO(e){return e===T0.StateCode.Activated?"Active":"Draft"}function aO(e,t){let r=e.processtriggerscope,n=e.processtriggerformid;return r===1&&n?n:r===2?"Entity":t??"Entity"}function F0(e,t=1033){return new vi({languageCode:t}).serialize(e)}function x0(e){return new vi().deserialize(e)}var T0,G,ad,O0,ld,vi,ud=I(()=>{"use strict";Zc();T0=se(Mn());u0();Ns();G=se(ed());ad={Equals:G.WorkflowConditionOperator.Equal,DoesNotEqual:G.WorkflowConditionOperator.NotEqual,IsGreaterThan:G.WorkflowConditionOperator.GreaterThan,IsLessThan:G.WorkflowConditionOperator.LessThan,IsGreaterThanEqualTo:G.WorkflowConditionOperator.GreaterThanOrEqual,IsLessThanEqualTo:G.WorkflowConditionOperator.LessThanOrEqual,Contains:G.WorkflowConditionOperator.Contains,DoesNotContain:G.WorkflowConditionOperator.DoesNotContain,BeginsWith:G.WorkflowConditionOperator.BeginsWith,DoesNotBeginWith:G.WorkflowConditionOperator.DoesNotBeginWith,EndsWith:G.WorkflowConditionOperator.EndsWith,DoesNotEndWith:G.WorkflowConditionOperator.DoesNotEndWith,On:G.WorkflowConditionOperator.On,NotOn:G.WorkflowConditionOperator.NotOn,ContainsData:G.WorkflowConditionOperator.NotNull,DoesNotContainData:G.WorkflowConditionOperator.IsNull},O0={};for(let e of Object.keys(ad))O0[ad[e]]=e;ld={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"};vi=class{resolveLabel;languageCode;entityName="";stepCounter={value:0};idCounter={counts:{},used:new Set};constructor(t={}){this.resolveLabel=t.resolveLabel??(r=>ld[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={__class:"WorkflowStep:#Microsoft.Crm.Workflow.ObjectModel",id:r?.id??t.ruleId??dt(),name:r?.name??"Step_0",description:r!==void 0?r.description:t.description||null,stepLabels:Ga(),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:kt("SetAttributeValueStep",this.idCounter),description:t.displayName||"New Action",name:t.stepName??gi(this.stepCounter),stepLabels:{list:[]},specification:id(t.field,Is(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType)),entity:od(this.entityName)}}makeRecommendationActionStep(t,r,n){let i=r.map(l=>this.makeApplyActionStep(l)),a=t??"",o=n?.stepLabels,s=N0(o,a,this.languageCode);return{__class:"ActionStep:#Microsoft.Crm.Workflow.ObjectModel",id:_0(n?.id,"ActionStep",this.idCounter),name:n?.name??gi(this.stepCounter),description:n?.description??"Action step",stepLabels:s,steps:{list:i},actionId:null,actionType:n?.actionType??"4",processId:n?.processId??dt(),uniqueName:n?.uniqueName??`id_${dt().replace(/-/g,"")}ActionStep`}}serializeAction(t){let r=od(this.entityName),n=t.stepName??gi(this.stepCounter),i=t.stepLabels??Ga(),a={name:n,stepLabels:i,description:t.displayName},o=t.type;switch(o){case"SetFieldValue":return{...a,id:kt("SetAttributeValueStep",this.idCounter),__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:id(t.field,Is(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"SetDefaultValue":return{...a,id:kt("SetDefaultValueStep",this.idCounter),__class:"SetDefaultValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:id(t.field,Is(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"LockUnlock":return{...a,id:kt("SetDisplayModeStep",this.idCounter),__class:"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isReadOnly:t.lock,entity:r};case"SetBusinessRequired":return{...a,id:kt("SetFieldRequiredLevelStep",this.idCounter),__class:"SetFieldRequiredLevelStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",requiredLevel:t.required?G.FieldRequiredLevelTypes.Required:G.FieldRequiredLevelTypes.None,entity:r};case"SetVisibility":return{...a,id:kt("SetVisibilityStep",this.idCounter),__class:"SetVisibilityStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isVisible:t.visible,entity:r};case"ShowErrorMessage":{let s=t.errorMessage||t.displayName,l=t.stepLabels&&t.stepLabels.list.length>0?t.stepLabels:{list:[{labelId:dt(),languageCode:this.languageCode,description:s}]};return{...a,id:kt("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=N0(t.stepLabels,s,this.languageCode),u={list:[this.makeRecommendationActionStep(t.acceptanceText,t.applyActions??[],t.recommendationActionStepMeta)]};return{...a,id:kt("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??gi(this.stepCounter),n=kt("ConditionStep",this.idCounter),i=[],a=t,o=!0;for(;a;){let s=nO(a.clauses,a.logic,this.entityName),l=o?a.branchName??gi(this.stepCounter):gi(this.stepCounter),c={__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:o?_0(a.branchId,"ConditionBranchStep",this.idCounter):kt("ConditionBranchStep",this.idCounter),name:l,description:a.displayName,stepLabels:Ga(),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:Ga(),containsElsebranch:i.length>1,steps:{list:i}}}makeTerminalElseBranch(t){return{__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:kt("ConditionBranchStep",this.idCounter),name:"Else",description:null,stepLabels:Ga(),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??dt():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};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:aO(r,i?.formId),status:iO(t.statecode),rootCondition:n,wfomRoot:i}}deserializeConditionStep(t){let r=(t.steps?.list??[]).filter(rO);return this.buildConditionNodeFromBranches(r,t,!0)}buildConditionNodeFromBranches(t,r,n){let[i,...a]=t,{clauses:o,logic:s}=I0(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)??dt(),displayName:c,clauses:o,logic:s,trueBranch:l,falseBranch:u,isCollapsed:!1,stepName:n?r.name:void 0,branchId:n?i?.id:void 0,branchName:n?i?.name:void 0}}deserializeElseChain(t,r){if(t.length===0)return[];let[n]=t,{clauses:i}=I0(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||dt(),field:u?.propertyName??"",stepName:l.name??void 0,displayName:l.description??void 0,...Ds(u?.propertyValueExpr)}}),meta:i,acceptanceText:o}}deserializeAction(t){switch(t.__class){case"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=Ds(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=Ds(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!==G.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}}}});function on(e){return!oO.has(e)}function U0(e){return fO.has(e)}function _s(e){return k0.has(e)?sO:dO.has(e)?lO:M0.has(e)?uO:cO}function B0(e){return _s(e)[0]}function $0(e,t){return _s(t).includes(e)}function L0(e){return k0.has(e)?"string":e==="Money"?"money":e==="Integer"||e==="BigInt"?"integer":e==="Decimal"||e==="Double"?"decimal":M0.has(e)?"date":pO.has(e)?"boolean":"other"}function Ps(e,t){let r=L0(e),n=L0(t);return r==="other"||n==="other"?e===t:r===n}var oO,sO,lO,uO,cO,k0,dO,M0,pO,fO,cd=I(()=>{"use strict";oO=new Set(["ContainsData","DoesNotContainData"]);sO=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],lO=["Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],uO=["On","NotOn","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],cO=["Equals","DoesNotEqual","ContainsData","DoesNotContainData"],k0=new Set(["String","Memo","EntityName"]),dO=new Set(["Integer","BigInt","Money","Decimal","Double"]),M0=new Set(["DateTime"]),pO=new Set(["Boolean"]),fO=new Set(["Equals","DoesNotEqual"])});function pd(e){return mO.has(e.type)}function dd(e,t,r,n,i,a,o){let s=i.get(r);!s||!hO.has(s.attributeType)||n!=="Value"||o?.operator&&!U0(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 q0(e,t,r,n,i,a,o,s){if(i!=="Clear")return;let l=a.get(n);As(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 Os(e){if(!e)return!1;for(let t of[...e.trueBranch,...e.falseBranch])if(t.kind==="action"){if(pd(t))return!0}else if(Os(t))return!0;return!1}function fd(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=fd(r,t);if(n)return n}}return null}function yi(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=yi(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=yi(n,t);if(i)return i}}return null}function md(e,t){return{...e,trueBranch:V0(e.trueBranch,t),falseBranch:V0(e.falseBranch,t)}}function V0(e,t){return e.filter(r=>r.id!==t).map(r=>r.kind==="condition"?md(r,t):r)}function sn(e,t,r){return e.id===t?r(e):{...e,trueBranch:e.trueBranch.map(n=>n.kind==="condition"?sn(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="condition"?sn(n,t,r):n)}}function Ts(e,t,r){return{...e,trueBranch:e.trueBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?Ts(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?Ts(n,t,r):n)}}function G0(e,t,r,n){return sn(e,t,i=>({...i,trueBranch:r==="true"?[...i.trueBranch,n]:i.trueBranch,falseBranch:r==="false"?[...i.falseBranch,n]:i.falseBranch}))}function gO(e){return e.length===1&&e[0].kind==="condition"}function z0(e,t,r){return sn(e,t,n=>W0(n,r))}function W0(e,t){if(gO(e.falseBranch))return{...e,falseBranch:[W0(e.falseBranch[0],t)]};let r=hd(t);return r.falseBranch=e.falseBranch,{...e,falseBranch:[r]}}function j0(e,t){let r=yi(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 sn(e,r.node.id,a=>({...a,falseBranch:i}))}function H0(e,t,r){let n=yi(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 sn(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 hd(e){return{kind:"condition",id:dt(),displayName:e??"New Condition",clauses:[],logic:"AND",trueBranch:[],falseBranch:[],isCollapsed:!1}}function Q0(e,t){let r={kind:"action",id:dt(),type:e,displayName:t??`New ${e}`};switch(e){case"Recommendation":return{...r,type:"Recommendation",field:"",recommendationTitle:"",messageText:"",applyActions:[{id:dt(),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 J0(e){if(!e)return[];let t=[];return X0(e,t),[...new Set(t)]}function X0(e,t){e.clauses.forEach(r=>{r.field&&t.push(r.field)}),[...e.trueBranch,...e.falseBranch].forEach(r=>{r.kind==="condition"?X0(r,t):"field"in r&&r.field&&t.push(r.field)})}function K0(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 Y0(e,r,n),Os(e)||r.push({nodeId:"root",kind:"NO_ACTION",message:"A business rule must include at least one action step.",target:"node"}),r}function Y0(e,t,r){e.clauses.length===0&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Add at least one clause to this condition.",target:"node",messageKey:"Validation.AddClause"}),e.clauses.forEach(n=>{if(!n.field)t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Please select a field for this clause.",target:"clauseField",itemId:n.id});else if(on(n.operator)&&n.valueType==="Value"&&!n.value)t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause.",target:"clauseValue",itemId:n.id});else if(on(n.operator)&&n.valueType==="Value"&&n.value){let i=r.get(n.field);i?.maxLength&&n.value.length>i.maxLength&&t.push({nodeId:e.id,kind:"CLAUSE_VALUE_TOO_LONG",message:`Value exceeds the field's maximum length of ${i.maxLength} characters.`,target:"clauseValue",itemId:n.id,messageParams:{maxLength:i.maxLength}})}else on(n.operator)&&n.valueType==="Expression"&&!n.rawExpression&&!hi(n.expression)&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please complete the formula for this clause.",target:"clauseValue",itemId:n.id,messageKey:"Validation.CompleteClauseFormula"});on(n.operator)&&n.valueType==="Lookup"&&(!n.lookupValue?.entityType||!n.lookupValue.id||!n.lookupValue.label)&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please select a lookup record for this clause.",target:"clauseValue",itemId:n.id,messageKey:"Validation.EmptyClauseLookupValue"}),on(n.operator)&&dd(e.id,"Condition",n.field,n.valueType,r,t,{operator:n.operator,target:"clauseValue",itemId:n.id})}),[...e.trueBranch,...e.falseBranch].forEach(n=>{if(n.kind==="condition")Y0(n,t,r);else{if(!("field"in n)||!n.field)t.push({nodeId:n.id,kind:"EMPTY_ACTION_FIELD",message:`${n.type}: a target field is required.`,target:"actionField",messageParams:{actionType:n.type}});else if((n.type==="SetFieldValue"||n.type==="SetDefaultValue")&&(n.valueType??"Value")==="Value"&&!n.value?.trim())t.push({nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:`${n.type}: please provide a value.`,target:"actionValue",messageParams:{actionType:n.type}});else if((n.type==="SetFieldValue"||n.type==="SetDefaultValue")&&n.valueType==="Value"&&n.value){let i=r.get(n.field);i?.maxLength&&n.value.length>i.maxLength&&t.push({nodeId:n.id,kind:"ACTION_VALUE_TOO_LONG",message:`${n.type}: value exceeds the field's maximum length of ${i.maxLength} characters.`,target:"actionValue",messageParams:{actionType:n.type,maxLength:i.maxLength}})}else if((n.type==="SetFieldValue"||n.type==="SetDefaultValue")&&n.valueType==="Field"){if(!n.valueField)t.push({nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:`${n.type}: please select a field to copy from.`,target:"actionValue",messageKey:"Validation.SelectActionSourceField",messageParams:{actionType:n.type}});else if(r.size>0){let i=r.get(n.field),a=r.get(n.valueField);i&&a&&!Ps(i.attributeType,a.attributeType)&&t.push({nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:`${n.type}: the source field's type is not compatible with the target field.`,target:"actionValue",messageKey:"Validation.IncompatibleActionSourceField",messageParams:{actionType:n.type}})}}else(n.type==="SetFieldValue"||n.type==="SetDefaultValue")&&n.valueType==="Expression"?!n.rawExpression&&!hi(n.expression)&&t.push({nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:`${n.type}: please complete the formula.`,target:"actionValue",messageKey:"Validation.CompleteActionFormula",messageParams:{actionType:n.type}}):(n.type==="SetFieldValue"||n.type==="SetDefaultValue")&&n.valueType==="Lookup"&&(!n.lookupValue?.entityType||!n.lookupValue.id||!n.lookupValue.label)&&t.push({nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:`${n.type}: please complete the lookup record.`,target:"actionValue",messageKey:"Validation.EmptyActionLookupValue",messageParams:{actionType:n.type}});if((n.type==="SetFieldValue"||n.type==="SetDefaultValue")&&n.field&&(dd(n.id,n.type,n.field,n.valueType,r,t,{target:"actionValue"}),q0(n.id,n.type,n.type,n.field,n.valueType,r,t,{target:"actionValue"})),n.type==="ShowErrorMessage"&&!n.errorMessage?.trim()&&t.push({nodeId:n.id,kind:"EMPTY_ACTION_MESSAGE",message:"Show error message: please enter an error message.",target:"actionMessage"}),n.type==="Recommendation"){let i=n.applyActions??[];n.recommendationTitle?.trim()||t.push({nodeId:n.id,kind:"EMPTY_RECOMMENDATION_TITLE",message:"Recommendation: please enter a recommendation title.",target:"recommendationTitle"}),n.messageText?.trim()||t.push({nodeId:n.id,kind:"EMPTY_RECOMMENDATION_MESSAGE",message:"Recommendation: please enter a recommendation message.",target:"recommendationMessage"}),i.length===0&&t.push({nodeId:n.id,kind:"RECOMMENDATION_NO_APPLY_ACTION",message:"Recommendation: add at least one action to apply.",target:"node"}),i.forEach(a=>{a.field?a.valueType==="Field"?a.valueField||t.push({nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please select a field to copy from.",target:"applyActionValue",itemId:a.id,messageKey:"Validation.RecommendationApplySourceField"}):a.valueType==="Expression"?!a.rawExpression&&!hi(a.expression)&&t.push({nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the formula.",target:"applyActionValue",itemId:a.id,messageKey:"Validation.RecommendationApplyFormula"}):a.valueType==="Lookup"?(!a.lookupValue?.entityType||!a.lookupValue.id||!a.lookupValue.label)&&t.push({nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the lookup record.",target:"applyActionValue",itemId:a.id,messageKey:"Validation.RecommendationApplyLookupValue"}):a.valueType==="Clear"||a.value?.trim()||t.push({nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please enter a value for each action to apply.",target:"applyActionValue",itemId:a.id,messageKey:"Validation.RecommendationApplyValue"}):t.push({nodeId:n.id,kind:"EMPTY_ACTION_FIELD",message:"Recommendation: a target field is required for each action to apply.",target:"applyActionField",itemId:a.id,messageKey:"Validation.RecommendationApplyField"}),a.field&&(dd(n.id,"Recommendation",a.field,a.valueType,r,t,{target:"applyActionValue",itemId:a.id}),q0(n.id,"Recommendation","SetFieldValue",a.field,a.valueType,r,t,{target:"applyActionValue",itemId:a.id}))})}}})}var mO,hO,gd=I(()=>{"use strict";Zc();Qc();cd();Ns();mO=new Set(["LockUnlock","ShowErrorMessage","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]);hO=new Set(["Lookup","Customer","Owner"])});var Z0={};Rr(Z0,{DEFAULT_DESERIALIZE_LABELS:()=>ld,WorkflowJsonMapper:()=>vi,addElseIfInTree:()=>z0,appendToBranch:()=>G0,areFieldKindsCompatible:()=>Ps,attributeTypeToWorkflowType:()=>f0,buildWorkflowEntity:()=>e0,collectUsedFields:()=>J0,createEmptyAction:()=>Q0,createEmptyCondition:()=>hd,deserializeWorkflowJson:()=>x0,findNode:()=>fd,findParent:()=>yi,getDefaultOperatorForFieldType:()=>B0,getOperatorsForFieldType:()=>_s,hasAnyTriggerGeneratingAction:()=>Os,isExpressionModelComplete:()=>hi,isOperatorCompatible:()=>$0,isTriggerGeneratingAction:()=>pd,moveBranchItemInTree:()=>H0,operatorNeedsValue:()=>on,processTriggerFormIdFromScope:()=>Xc,processTriggerScopeFromScope:()=>Jc,removeElseIfInTree:()=>j0,removeNodeFromTree:()=>md,serializeToWorkflowJson:()=>F0,supportsClearForActionType:()=>As,updateActionInTree:()=>Ts,updateConditionInTree:()=>sn,validateBusinessRule:()=>K0});var ev=I(()=>{"use strict";Qc();t0();ud();ud();gd();gd();cd();Ns();});var Yt=g(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 vO=be(),Wa=ee(),tv="/PublishXml";async function bi(e,t){(0,vO.ensureSuccess)(await e.post(tv,{ParameterXml:t}),e.apiUrl(tv))}ze.publishXml=bi;function yO(e,t){return bi(e,`<importexportxml><appmodules><appmodule>${(0,Wa.xmlText)(t)}</appmodule></appmodules></importexportxml>`)}ze.publishAppModule=yO;function rv(e,t){return bi(e,`<importexportxml><entities><entity>${(0,Wa.xmlText)(t)}</entity></entities></importexportxml>`)}ze.publishEntity=rv;function bO(e,t){return bi(e,`<importexportxml><webresources><webresource>${(0,Wa.xmlText)(t)}</webresource></webresources></importexportxml>`)}ze.publishWebResourceById=bO;function wO(e,t){return bi(e,`<importexportxml><dashboards><dashboard>${(0,Wa.xmlText)(t)}</dashboard></dashboards></importexportxml>`)}ze.publishDashboardById=wO;function AO(e,t){return bi(e,`<importexportxml><uxagentprojects><uxagentproject>${(0,Wa.xmlText)(t)}</uxagentproject></uxagentprojects></importexportxml>`)}ze.publishGenPageById=AO;function CO(e){let t=e?.entityLogicalName;return t?{envelope:"entity",entityLogicalName:t,blastRadiusWarning:"ENTITY_ENVELOPE_ALSO_SHIPS_UNRELATED_UNPUBLISHED_CHANGES"}:{envelope:"entity"}}ze.boundEntityPublishScope=CO;function SO(e,t){let r=t?.entityLogicalName;return r?rv(e,r):Promise.resolve()}ze.publishBoundEntity=SO});var vd=g(Rs=>{"use strict";Object.defineProperty(Rs,"__esModule",{value:!0});Rs.cloneJson=void 0;function EO(e){return JSON.parse(JSON.stringify(e))}Rs.cloneJson=EO});var cr=g(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.childObjects=yt.optionalGuidId=yt.optionalEnum=yt.eachObject=yt.issue=yt.isJsonObject=void 0;function nv(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}yt.isJsonObject=nv;function ja(e,t,r,n){return n?{pointer:e,rule:t,message:r,fatal:n}:{pointer:e,rule:t,message:r}}yt.issue=ja;function iv(e,t,r,n){if(!Array.isArray(e))return[];let i=[];return e.forEach((a,o)=>{nv(a)?i.push({node:a,index:o}):n.push(ja(`${t}/${o}`,`${r}-must-be-object`,`a ${r} must be a JSON object, got ${a===null?"null":typeof a}`))}),i}yt.eachObject=iv;function NO(e,t,r,n,i,a){let o=e[t];o!==void 0&&(typeof o!="string"||!r.includes(o))&&a.push(ja(`${n}/${t}`,i,`${t} must be one of ${r.map(s=>`'${s}'`).join(", ")}, got ${JSON.stringify(o)}`))}yt.optionalEnum=NO;var DO=/^(?:\{[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 IO(e,t,r,n,i){let a=e[t];typeof a=="string"&&a!==""&&!DO.test(a)&&i.push(ja(`${r}/${t}`,n,`${t} must be a GUID or empty, got '${a}'`))}yt.optionalGuidId=IO;function _O(e,t,r,n,i){let a=e[t],o=`${r}/${t}`;return a===void 0?[]:Array.isArray(a)?iv(a,o,n,i):(i.push(ja(o,`${n}-list-must-be-array`,`${t} must be an array when present, got ${typeof a}`)),[])}yt.childObjects=_O});var bt=g(wi=>{"use strict";Object.defineProperty(wi,"__esModule",{value:!0});wi.assignMissingIds=wi.newId=void 0;var PO=ws();function av(){return(0,PO.v4)()}wi.newId=av;function TO(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var OO=new Set(["parameters","bag","expression","rawExpression","lookupValue","stepLabels"]);function RO(e){return yd(e),e}wi.assignMissingIds=RO;function yd(e){if(Array.isArray(e)){e.forEach(t=>yd(t));return}if(TO(e)){(typeof e.id!="string"||e.id.length===0)&&(e.id=av());for(let t of Object.keys(e))t==="id"||OO.has(t)||yd(e[t])}}});var wd=g(ln=>{"use strict";Object.defineProperty(ln,"__esModule",{value:!0});ln.BUSINESS_RULE_NULL_GUID=ln.businessRuleRegistration=ln.BusinessRuleAdapter=void 0;var ov=ws(),Ha=(ev(),Fr(Z0)),sv=Yt(),lv=ie(),FO=vd(),dr=cr(),xO=Dc(),LO=bt();function kO(e){return pv((0,FO.cloneJson)(e))}function pv(e){var t,r;let n=i=>(i??[]).map(a=>MO(a)?pv(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 MO(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 UO(e){var t;if(e===null||typeof e!="object"||Array.isArray(e))throw new lv.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 lv.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 BO="00000000-0000-0000-0000-000000000000";ln.BUSINESS_RULE_NULL_GUID=BO;var $O=new Set(["Recommendation","LockUnlock","ShowErrorMessage","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]),qO=["ruleId","name","description","entityLogicalName","scope","status","rootCondition"],VO=["kind","id","displayName","logic","clauses","trueBranch","falseBranch"],GO=["id","field","fieldDisplayName","operator","valueType","value","valueField","lookupValue","expression","rawExpression","valueWorkflowType"];function Zt(e,t){return e===void 0?t:{...e,...t}}var $n=["kind","id","type","displayName","field","stepName","stepLabels"],uv=["valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression"],zO={Recommendation:[...$n,"recommendationTitle","messageText","acceptanceText","applyActions","recommendationActionStepMeta"],LockUnlock:[...$n,"lock"],ShowErrorMessage:[...$n,"errorMessage","messageLevel","messageActionSteps"],SetFieldValue:[...$n,...uv],SetDefaultValue:[...$n,...uv],SetBusinessRequired:[...$n,"required"],SetVisibility:[...$n,"visible"]};function W(e,t){return t===void 0?{}:{[e]:t}}function fv(e){var t;return e===void 0?void 0:{...e,label:(t=e.label)!==null&&t!==void 0?t:""}}function bd(e){return{valueType:e.valueType,...W("valueWorkflowType",e.valueWorkflowType),...W("value",e.value),...W("valueField",e.valueField),...W("lookupValue",fv(e.lookupValue)),...W("expression",e.expression),...W("rawExpression",e.rawExpression)}}function mv(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 WO=["id","field","valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression","stepName","displayName"];function jO(e){return Zt(e.bag,{id:e.id,field:e.field,...bd(e),...W("stepName",e.stepName),...W("displayName",e.displayName)})}function HO(e){let t=mv(e,WO);return{id:e.id,field:e.field,valueType:e.valueType,...W("valueWorkflowType",e.valueWorkflowType),...W("value",e.value),...W("valueField",e.valueField),...W("lookupValue",e.lookupValue),...W("expression",e.expression),...W("rawExpression",e.rawExpression),...W("stepName",e.stepName),...W("displayName",e.displayName),...W("bag",t)}}function cv(e){return{valueType:e.valueType,...W("valueWorkflowType",e.valueWorkflowType),...W("value",e.value),...W("valueField",e.valueField),...W("lookupValue",e.lookupValue),...W("expression",e.expression),...W("rawExpression",e.rawExpression)}}function dv(e){throw new Error(`Unsupported business-rule action type: ${e.type}`)}var QO=new Set(["INVALID_CLEAR_FOR_FIELD","INVALID_VALUE_TYPE_FOR_FIELD","CLAUSE_VALUE_TOO_LONG","ACTION_VALUE_TOO_LONG"]),JO=new Set;function XO(e){let t=n=>{var i;return(0,dr.isJsonObject)(n)&&(n.label===""||n.label===void 0)?{...n,label:String((i=n.id)!==null&&i!==void 0?i:"")}:n},r=n=>{if(!(0,dr.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 Fs=class{toArtifact(t){let r=this.residualBag(t,qO),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 Zt(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,Ha.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,Ha.serializeToWorkflowJson)(n),a=(r=n.ruleId)!==null&&r!==void 0?r:(0,ov.v4)();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,Ha.createEmptyCondition)():t.rootCondition===null?null:this.conditionFromJson(kO(UO(t.rootCondition)))},u=this.toArtifact(l);return u.id||(u.id=(0,ov.v4)()),u}assignMissingIds(t){return(0,LO.assignMissingIds)(t)}validate(t){let r=[],n=t.rootCondition;return n==null?r:(0,dr.isJsonObject)(n)?(hv(n,"/rootCondition",r),r):(r.push((0,dr.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,dr.issue)("/rootCondition","rule-not-representable",o instanceof Error?o.message:String(o))]}let i=n.rootCondition===null?null:XO(n.rootCondition),a=r.length===0?QO:JO;return(0,Ha.validateBusinessRule)(i,r).filter(o=>!a.has(o.kind)).map(o=>(0,dr.issue)(`/rootCondition (${o.nodeId})`,`business-rule-${o.kind}`,o.message))}residualBag(t,r){return mv(t,r)}buildWorkflowEntity(t,r){return(0,Ha.buildWorkflowEntity)(t,r)}conditionToJson(t){let r=this.residualBag(t,VO),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,GO),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,zO[t.type]),n={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...W("stepName",t.stepName),...W("stepLabels",t.stepLabels),...W("bag",r)};switch(t.type){case"Recommendation":return{...n,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...W("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(HO),...W("recommendationActionStepMeta",t.recommendationActionStepMeta)};case"LockUnlock":return{...n,type:"LockUnlock",lock:t.lock};case"ShowErrorMessage":return{...n,type:"ShowErrorMessage",errorMessage:t.errorMessage,...W("messageLevel",t.messageLevel),...W("messageActionSteps",t.messageActionSteps)};case"SetFieldValue":return{...n,type:"SetFieldValue",...cv(t)};case"SetDefaultValue":return{...n,type:"SetDefaultValue",...cv(t)};case"SetBusinessRequired":return{...n,type:"SetBusinessRequired",required:t.required};case"SetVisibility":return{...n,type:"SetVisibility",visible:t.visible};default:return dv(t)}}conditionFromJson(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:{};return Zt(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 Zt(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,...W("value",t.value),...W("valueField",t.valueField),...W("lookupValue",fv(t.lookupValue)),...W("expression",t.expression),...W("rawExpression",t.rawExpression),...W("valueWorkflowType",t.valueWorkflowType)})}branchItemFromJson(t){return this.isConditionJson(t)?this.conditionFromJson(t):this.actionFromJson(t)}actionFromJson(t){if(!$O.has(t.type))throw new Error(`Unsupported business-rule action type: ${t.type}`);YO(t);let r={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...W("stepName",t.stepName),...W("stepLabels",t.stepLabels)};switch(t.type){case"Recommendation":return Zt(t.bag,{...r,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...W("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(jO),...W("recommendationActionStepMeta",t.recommendationActionStepMeta)});case"LockUnlock":return Zt(t.bag,{...r,type:"LockUnlock",lock:t.lock});case"ShowErrorMessage":return Zt(t.bag,{...r,type:"ShowErrorMessage",errorMessage:t.errorMessage,...W("messageLevel",t.messageLevel),...W("messageActionSteps",t.messageActionSteps)});case"SetFieldValue":return Zt(t.bag,{...r,type:"SetFieldValue",...bd(t)});case"SetDefaultValue":return Zt(t.bag,{...r,type:"SetDefaultValue",...bd(t)});case"SetBusinessRequired":return Zt(t.bag,{...r,type:"SetBusinessRequired",required:t.required});case"SetVisibility":return Zt(t.bag,{...r,type:"SetVisibility",visible:t.visible});default:return dv(t)}}isConditionJson(t){return Object.prototype.hasOwnProperty.call(t,"clauses")&&Object.prototype.hasOwnProperty.call(t,"logic")&&!Object.prototype.hasOwnProperty.call(t,"type")}};ln.BusinessRuleAdapter=Fs;function hv(e,t,r){(0,dr.optionalEnum)(e,"logic",["AND","OR"],t,"condition-logic-invalid",r),(0,dr.childObjects)(e,"clauses",t,"clause",r);for(let n of["trueBranch","falseBranch"])(0,dr.childObjects)(e,n,t,"branchItem",r).forEach(({node:a,index:o})=>{"clauses"in a||"trueBranch"in a||"falseBranch"in a?hv(a,`${t}/${n}/${o}`,r):KO(a,`${t}/${n}/${o}`,r)})}function KO(e,t,r){e.type==="SetDefaultValue"&&e.valueType==="Clear"&&r.push((0,dr.issue)(`${t}/valueType`,"clear-only-set-field-value","Clear is only supported for SetFieldValue actions."))}function YO(e){if(e.type==="SetDefaultValue"&&e.valueType==="Clear")throw new Error("Clear is only supported for SetFieldValue actions.")}function ZO(){return{adapter:new Fs,api:xO.businessRuleApi,publish:(e,t,r)=>(0,sv.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,sv.boundEntityPublishScope)(t)}}ln.businessRuleRegistration=ZO});var ks=g(Ls=>{"use strict";Object.defineProperty(Ls,"__esModule",{value:!0});Ls.JsonPointer=void 0;var Tt=ie(),xs=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 Tt.JsonPointerError(t,'non-empty pointers must start with "/"');return t.substring(1).split("/").map(r=>{if(/~(?![01])/.test(r))throw new Tt.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 Tt.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 Tt.JsonPointerError(r,`'${o}' is not a valid array index`);if(s>a.length)throw new Tt.JsonPointerError(r,`array index '${o}' is out of range`);a[s]=n}else{if(e.isReservedToken(o))throw new Tt.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 Tt.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 Tt.JsonPointerError(r,`array index '${a}' is out of range`);i.splice(o,1)}else{if(e.isReservedToken(a))throw new Tt.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 Tt.JsonPointerError(r,"add target must be an array");u.push(n);return}let o=e.resolve(t,r);if(!Array.isArray(o))throw new Tt.JsonPointerError(r,"add target must be an array");let s=i===void 0?o.length:i;if(s<0||s>o.length)throw new Tt.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 Tt.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)}};Ls.JsonPointer=xs;xs.RESERVED_TOKENS=new Set(["__proto__","prototype","constructor"])});var vv=g(Ms=>{"use strict";Object.defineProperty(Ms,"__esModule",{value:!0});Ms.findElements=void 0;var gv=ks();function eR(e,t){let r=[];return Ad(e,"",t,r),r}Ms.findElements=eR;function Ad(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)=>{Ad(i,gv.JsonPointer.append(t,a),r,n)});else for(let i of Object.keys(e))Ad(e[i],gv.JsonPointer.append(t,i),r,n)}});var wv=g(Me=>{"use strict";var tR=Me&&Me.__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]})),rR=Me&&Me.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),bv=Me&&Me.__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)&&tR(t,e,r);return rR(t,e),t};Object.defineProperty(Me,"__esModule",{value:!0});Me.canonicalArtifactId=Me.retryTransientIo=Me.WorkspaceManager=Me.WORKSPACE_SCHEMA_VERSION=void 0;var Pe=bv(require("fs")),xe=bv(require("path")),Ai=ie();Me.WORKSPACE_SCHEMA_VERSION=1;var Us={form:"forms",view:"views",businessRule:"business-rules",app:"apps",command:"commands",chart:"charts",dashboard:"dashboards",genPage:"gen-pages",bpf:"business-process-flows"},nR="manifest.json",Bs=".metadata",yv="entities",Cd=class{constructor(t,r){this.workspacePath=t,this.instanceUrl=r}getRoot(){return this.workspacePath}getArtifactDir(t){return xe.join(this.workspacePath,Us[t])}getArtifactFilePath(t,r){return this.assertSafeId(r),this.assertWithinRoot(xe.join(this.getArtifactDir(t),`${Qa(r)}.json`))}getMetaFilePath(t,r){return this.assertSafeId(r),this.assertWithinRoot(xe.join(this.workspacePath,Bs,Us[t],`${Qa(r)}.meta.json`))}getEntityMetaFilePath(t){return this.assertSafeId(t),this.assertWithinRoot(xe.join(this.workspacePath,Bs,yv,`${t}.json`))}assertSafeId(t){if(typeof t!="string"||t.length===0||/[\u0000-\u001f]/.test(t)||t.includes("/")||t.includes("\\")||t.includes(":")||t==="."||t===".."||t.includes("..")||xe.basename(t)!==t)throw new Ai.PathTraversalError(String(t),this.workspacePath)}assertWithinRoot(t){let r=xe.resolve(this.workspacePath),n=xe.resolve(t);if(n!==r&&!n.startsWith(r+xe.sep))throw new Ai.PathTraversalError(t,this.workspacePath);let i=Pe.existsSync(r)?Pe.realpathSync(r):r,a=n,o=[];for(;!Pe.existsSync(a);){o.unshift(xe.basename(a));let l=xe.dirname(a);if(l===a)break;a=l}let s=xe.resolve(Pe.realpathSync(a),...o);if(s!==i&&!s.startsWith(i+xe.sep))throw new Ai.PathTraversalError(t,this.workspacePath);return n}get manifestPath(){return xe.join(this.workspacePath,nR)}init(){for(let t of Object.keys(Us))Pe.mkdirSync(this.getArtifactDir(t),{recursive:!0}),Pe.mkdirSync(xe.dirname(this.getMetaFilePath(t,"x")),{recursive:!0});if(Pe.mkdirSync(xe.join(this.workspacePath,Bs,yv),{recursive:!0}),!this.exists(this.manifestPath)){let t={instanceUrl:this.instanceUrl,createdAt:new Date().toISOString(),artifacts:[]};this.writeManifest(t)}}isInitialized(){return this.exists(this.manifestPath)}ensureInitialized(){if(!this.isInitialized())throw new Ai.WorkspaceNotInitializedError(this.workspacePath)}clean(){for(let r of Object.keys(Us))Ed(this.getArtifactDir(r));Ed(xe.join(this.workspacePath,Bs));let t=this.getManifest();t.artifacts=[],t.lastSyncAt=void 0,this.init(),this.writeManifest(t)}readArtifact(t,r){return this.ensureInitialized(),this.readJson(this.getArtifactFilePath(t,r))}writeArtifact(t,r,n){this.ensureInitialized(),this.writeJson(this.getArtifactFilePath(t,r),n),this.upsertManifestEntry(t,r,n)}deleteArtifact(t,r){this.ensureInitialized(),this.removeFile(this.getArtifactFilePath(t,r)),this.removeFile(this.getMetaFilePath(t,r));let n=Qa(r),i=this.getManifest();i.artifacts=i.artifacts.filter(a=>!(a.type===t&&a.id===n)),this.writeManifest(i)}listArtifacts(t,r){return this.ensureInitialized(),this.getManifest().artifacts.filter(n=>!(t&&n.type!==t||r?.entityLogicalName&&n.entityLogicalName!==r.entityLogicalName))}readEntityMetadata(t){this.ensureInitialized();let r=this.readJson(this.getEntityMetaFilePath(t));return!r||typeof r.schemaName!="string"||typeof r.primaryNameAttribute!="string"||typeof r.primaryIdAttribute!="string"||typeof r.isCustomEntity!="boolean"?null:r}writeEntityMetadata(t,r){this.ensureInitialized(),this.writeJson(this.getEntityMetaFilePath(t),r)}getManifest(){this.ensureInitialized();let t=this.readJson(this.manifestPath);if(!t)throw new Ai.WorkspaceNotInitializedError(this.workspacePath);if(t.schemaVersion!==void 0&&t.schemaVersion>Me.WORKSPACE_SCHEMA_VERSION)throw new Ai.IncompatibleWorkspaceError(t.schemaVersion,Me.WORKSPACE_SCHEMA_VERSION);return t}writeManifest(t){this.writeJson(this.manifestPath,{...t,schemaVersion:Me.WORKSPACE_SCHEMA_VERSION})}updateManifest(t){let r=this.getManifest();this.writeManifest({...r,...t})}upsertManifestEntry(t,r,n){let i=this.getManifest(),a=Qa(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}),this.writeManifest(i)}readJson(t){if(!this.exists(t))return null;let r;try{r=Sd(()=>Pe.readFileSync(t,"utf8"))}catch(n){if(n.code==="ENOENT")return null;throw n}return JSON.parse(r)}writeJson(t,r){let n=xe.dirname(t);Pe.mkdirSync(n,{recursive:!0});let i=xe.join(n,`.${xe.basename(t)}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);try{Pe.writeFileSync(i,`${JSON.stringify(r,null,2)}+`,"utf8"),Sd(()=>Pe.renameSync(i,t))}catch(a){try{Pe.existsSync(i)&&Pe.unlinkSync(i)}catch{}throw a}}removeFile(t){this.exists(t)&&Pe.unlinkSync(t)}exists(t){return Pe.existsSync(t)}};Me.WorkspaceManager=Cd;var iR=new Set(["EPERM","EACCES","EBUSY","UNKNOWN"]),aR=5,oR=10;function Sd(e){for(let t=1;;t+=1)try{return e()}catch(r){let n=r.code;if(t>=aR||!n||!iR.has(n))throw r;sR(oR*t)}}Me.retryTransientIo=Sd;function sR(e){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}catch{let t=Date.now()+e;for(;Date.now()<t;);}}function Qa(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()}Me.canonicalArtifactId=Qa;function Ed(e){let t;try{t=Pe.lstatSync(e)}catch{return}if(t.isSymbolicLink()){try{Pe.unlinkSync(e)}catch{Pe.rmdirSync(e)}return}if(!t.isDirectory()){Pe.unlinkSync(e);return}for(let r of Pe.readdirSync(e))Ed(xe.join(e,r));Pe.rmdirSync(e)}});var Nd=g(Ci=>{"use strict";Object.defineProperty(Ci,"__esModule",{value:!0});Ci.deepEqual=Ci.deepDiff=void 0;var lR=ks();function uR(e,t){let r=[];return Cv(e,t,"",r,0),r}Ci.deepDiff=uR;var $s=Symbol("missing"),qs=512;function Cv(e,t,r,n,i){if(e===t)return;if(i>qs)throw new RangeError(`deepDiff exceeded the maximum supported depth of ${qs}`);let a=Vs(e),o=Vs(t);if(a&&o&&Array.isArray(e)===Array.isArray(t)){let s=cR(e,t);for(let l of s){let u=Av(e,l),c=Av(t,l),d=lR.JsonPointer.append(r,l);u===$s?n.push({pointer:d,type:"added",newValue:c}):c===$s?n.push({pointer:d,type:"removed",oldValue:u}):Cv(u,c,d,n,i+1)}return}Sv(e,t)||n.push({pointer:r,type:"modified",oldValue:e,newValue:t})}function Vs(e){return e!==null&&typeof e=="object"}function cR(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 Av(e,t){if(Array.isArray(e)){let r=Number(t);return r<e.length?e[r]:$s}return t in e?e[t]:$s}function Sv(e,t){return Ev(e,t,0)}Ci.deepEqual=Sv;function Ev(e,t,r){if(e===t)return!0;if(r>qs)throw new RangeError(`deepEqual exceeded the maximum supported depth of ${qs}`);if(!Vs(e)||!Vs(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&&Ev(e[a],t[a],r+1))}});var Dv=g(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});Gs.VersionManager=void 0;var Nv=Nd(),Dd=class{constructor(t){this.workspace=t}storeMeta(t,r,n){this.workspace.writeJson(this.workspace.getMetaFilePath(t,r),n)}getMeta(t,r){return this.workspace.readJson(this.workspace.getMetaFilePath(t,r))}isDirty(t,r){let n=this.workspace.readArtifact(t,r);if(n===null)return!1;let i=this.getMeta(t,r);return i?!(0,Nv.deepEqual)(i.snapshot,n):!0}diff(t,r){let n=this.workspace.readArtifact(t,r),i=this.getMeta(t,r),a;return n===null?a=i?[{pointer:"",type:"removed",oldValue:i.snapshot}]:[]:i?a=(0,Nv.deepDiff)(i.snapshot,n):a=[{pointer:"",type:"added",newValue:n}],{artifactType:t,artifactId:r,changes:a}}checkConflict(t,r,n){let i=this.getMeta(t,r);return!i||i.etag===null?!1:i.etag!==n}};Gs.VersionManager=Dd});var _v=g((Id,Iv)=>{(function(e,t){typeof define=="function"&&define.amd?define([],t):typeof Id=="object"?Iv.exports=t():e.compareVersions=t()})(Id,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],h=u[u.length-1];if(f&&h){var y=f.split(".").map(n),w=h.split(".").map(n);for(c=0;c<Math.max(y.length,w.length);c++){if(y[c]===void 0||typeof w[c]=="string"&&typeof y[c]=="number")return-1;if(w[c]===void 0||typeof y[c]=="string"&&typeof w[c]=="number"||y[c]>w[c])return 1;if(w[c]>y[c])return-1}}else if(f||h)return f?-1:1;return 0}})});var Fv=g(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.EnvironmentFlowHostingType=Ne.EnvironmentDisableReasonCode=Ne.EnvironmentMigrationConstants=Ne.EnvironmentProvisioningStates=Ne.EnvironmentLocations=Ne.EnvironmentCreationTypeConstants=Ne.EnvironmentType=Ne.EnvironmentSkuConstants=Ne.environmentPermissions=Ne.DatabaseType=void 0;var Pv;(function(e){e.CommonDataService="CommonDataService",e.None="None"})(Pv||(Ne.DatabaseType=Pv={}));Ne.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"};Ne.EnvironmentSkuConstants={NotSpecified:"NotSpecified",Standard:"Standard",Premium:"Premium",Developer:"Developer",Basic:"Basic",Production:"Production",Sandbox:"Sandbox",Trial:"Trial",Default:"Default",Teams:"Teams",Platform:"Platform"};var Tv;(function(e){e[e.CDS2=0]="CDS2",e[e.CDS1=1]="CDS1",e[e.Empty=2]="Empty"})(Tv||(Ne.EnvironmentType=Tv={}));Ne.EnvironmentCreationTypeConstants={NotSpecified:"NotSpecified",Legacy:"Legacy",DefaultTenant:"DefaultTenant",User:"User",CommonDataModelLegacy:"CommonDataModelLegacy"};Ne.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"};Ne.EnvironmentProvisioningStates={NotSpecified:"NotSpecified",Succeeded:"Succeeded",Deleting:"Deleting",Deleted:"Deleted",FailedDeleting:"FailedDeleting",LinkedDatabaseProvisioning:"LinkedDatabaseProvisioning",LinkedDatabaseFailedProvisioning:"LinkedDatabaseFailedProvisioning",LinkedDatabaseFailedConfiguring:"LinkedDatabaseFailedConfiguring",LinkedDatabaseUnavailable:"LinkedDatabaseUnavailable",Creating:"Creating"};Ne.EnvironmentMigrationConstants={phases:{completed:"Completed"}};var Ov;(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"})(Ov||(Ne.EnvironmentDisableReasonCode=Ov={}));var Rv;(function(e){e.LogicApps="LogicApps",e.SelfHostSingleTenant="SelfHostSingleTenant",e.SelfHostMultiTenant="SelfHostMultiTenant"})(Rv||(Ne.EnvironmentFlowHostingType=Rv={}))});var qv=g(A=>{"use strict";var dR=A&&A.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(A,"__esModule",{value:!0});A.hasCommonDataServiceDatabase=A.getEnvironmentDiscoveryUrl=A.getEnvironmentWebApiUrl=A.getEnvironmentInstanceApiUrl=A.getEnvironmentLanguageCode=A.getEnvironmentUpdateCadence=A.checkVersions=A.isCds2EnvironmentVersionAtLeast=A.getSecurityOrConnectedGroupId=A.hasSecurityGroupId=A.doesCds2VersionSupportApiVersion9_1=A.doesCds2EnvironmentSupportApiVersion9_1=A.cdsVersionSupportingOSColorEdit=A.getEnvironmentDisplayName=A.getEnvironmentName=A.isEnvironmentInFirstReleaseCluster=A.isEnvironmentInPreprodCluster=A.isEnvironmentInTestCluster=A.isLiteEnvironmentUpgrading=A.isEnvironmentExpired=A.isEnvironmentInDeletedState=A.isEnvironmentInCreatingState=A.isDatabaseInProvisioningState=A.canUserCreateDatabase=A.isDisabledEnvironment=A.isDefaultEnvironment=A.isTrialEnvironment=A.isPlatformEnvironment=A.isTeamsEnvironment=A.isSandboxEnvironment=A.isProdEnvironment=A.isDevEnvironment=A.getEnvironmentType=A.getCrmInstanceName=A.getCrmInstanceUrl=A.getCrmAppDesignerUrl=A.getDevResourcesUrl=A.isEnvironmentInSuccessfulState=A.getAllThemesUrl=A.getAllPublishersUrl=A.getAllSolutionsUrl=A.getSecurityRolesUrl=A.getSecurityUsersUrl=A.environmentHasCds2Database=A.DEFAULT_SOLUTION_UNIQUE_NAME=A.DEFAULT_SOLUTION_ID=A.crmBapSolutionId=A.doesUserHavePermission=A.getLinkedEnvironmentMetadata=A.getCrmVersion=void 0;A.doesUserHaveFlowRunOnlyPermission=A.isUserPautoMakerWithoutDataAccess=A.isUserPautoMakerWithDataAccess=A.doesUserHaveCreateFlowPermission=A.equalsIgnoreCase=A.doesUserHaveCreateDatabasePermission=A.doesUserHaveDatabaseTablePermissions=A.isUserMakerWithoutDataAccess=A.isUserMakerWithDataAccess=A.doesUserHaveCreateAppPermission=A.doesUserHaveAdminPermission=void 0;var pR=dR(_v()),le=Fv(),Ja=Pd();function fR(e){let t=Ur(e);return t&&t.version}A.getCrmVersion=fR;function Ur(e){return e&&e.properties&&e.properties.linkedEnvironmentMetadata}A.getLinkedEnvironmentMetadata=Ur;function Mr(e,t){return e?!!e[t]:!1}A.doesUserHavePermission=Mr;A.crmBapSolutionId="00000001-0000-0000-0001-00000000009b";A.DEFAULT_SOLUTION_ID="fd140aaf-4df4-11dd-bd17-0019b9312238";A.DEFAULT_SOLUTION_UNIQUE_NAME="Default";function qn(e){return!!Ur(e)&&xv(e)}A.environmentHasCds2Database=qn;function mR(e){if(e&&qn(e)){let t=un(e);return(0,Ja.getCrmAdminSecurityRolesUrl)(t)}return""}A.getSecurityUsersUrl=mR;function hR(e){if(e&&qn(e)){let t=un(e);return(0,Ja.getCrmAdminSecurityUsersUrl)(t)}return""}A.getSecurityRolesUrl=hR;function gR(e){if(e&&qn(e)){let t=un(e);(0,Ja.getCrmAllSolutionsUrl)(t)}return""}A.getAllSolutionsUrl=gR;function vR(e){if(e&&qn(e)){let t=un(e);return(0,Ja.getCrmAllPublishersUrl)(t)}return""}A.getAllPublishersUrl=vR;function yR(e){return e&&qn(e)?un(e):""}A.getAllThemesUrl=yR;function xv(e){return!!e&&e.properties&&!!e.properties.provisioningState&&e.properties.provisioningState.toUpperCase()===le.EnvironmentProvisioningStates.Succeeded.toUpperCase()}A.isEnvironmentInSuccessfulState=xv;function bR(e){if(e&&qn(e)){let t=un(e);return(0,Ja.getCrmDevResourcesUrl)(t)}return""}A.getDevResourcesUrl=bR;function wR(e){return`${e}designer/app/{${A.crmBapSolutionId}}/CreateNewApp}}`}A.getCrmAppDesignerUrl=wR;function un(e){let t=Ur(e);if(t){let r=t.instanceUrl;return r?r.endsWith("/")?r:r+"/":""}return""}A.getCrmInstanceUrl=un;function AR(e){let t=Ur(e);return t?t.uniqueName:""}A.getCrmInstanceName=AR;function CR(e){return Ur(e)?le.EnvironmentType.CDS2:e&&e.properties&&e.properties.namespace?le.EnvironmentType.CDS1:le.EnvironmentType.Empty}A.getEnvironmentType=CR;function SR(e){return e&&e.properties&&e.properties.environmentSku===le.EnvironmentSkuConstants.Developer}A.isDevEnvironment=SR;function ER(e){return e&&e.properties&&e.properties.environmentSku===le.EnvironmentSkuConstants.Production}A.isProdEnvironment=ER;function NR(e){return e&&e.properties&&e.properties.environmentSku===le.EnvironmentSkuConstants.Sandbox}A.isSandboxEnvironment=NR;function Xa(e){return e&&e.properties&&e.properties.environmentSku===le.EnvironmentSkuConstants.Teams}A.isTeamsEnvironment=Xa;function DR(e){return e&&e.properties&&e.properties.environmentSku===le.EnvironmentSkuConstants.Platform}A.isPlatformEnvironment=DR;var IR=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.environmentSku)===le.EnvironmentSkuConstants.Trial};A.isTrialEnvironment=IR;function _R(e){return e&&e.properties&&(e.properties.isDefault||e.properties.creationType===le.EnvironmentCreationTypeConstants.DefaultTenant)}A.isDefaultEnvironment=_R;function PR(e){return e&&e.properties&&!!e.properties.states&&!!e.properties.states.runtime&&e.properties.states.runtime.id==="Disabled"}A.isDisabledEnvironment=PR;function TR(e){return e&&e.properties&&Mr(e.properties.permissions,le.environmentPermissions.CreateDatabase)}A.canUserCreateDatabase=TR;function OR(e){return!!(e&&e.properties&&e.properties.provisioningState&&$v(e.properties.provisioningState,le.EnvironmentProvisioningStates.LinkedDatabaseProvisioning))}A.isDatabaseInProvisioningState=OR;function RR(e){return!!e&&!!e.properties&&e.properties.provisioningState===le.EnvironmentProvisioningStates.Creating}A.isEnvironmentInCreatingState=RR;function FR(e){return e&&e.properties&&(e.properties.provisioningState===le.EnvironmentProvisioningStates.Deleted||e.properties.provisioningState===le.EnvironmentProvisioningStates.Deleting||e.properties.provisioningState===le.EnvironmentProvisioningStates.FailedDeleting)}A.isEnvironmentInDeletedState=FR;function xR(e){return!!e&&!!e.properties&&!!e.properties.expirationTime&&Date.parse(e.properties.expirationTime)<Date.now()}A.isEnvironmentExpired=xR;function LR(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"}A.isLiteEnvironmentUpgrading=LR;function kR(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Test"}A.isEnvironmentInTestCluster=kR;function MR(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Preprod"}A.isEnvironmentInPreprodCluster=MR;function UR(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="FirstRelease"}A.isEnvironmentInFirstReleaseCluster=UR;function BR(e){return e&&e.name||""}A.getEnvironmentName=BR;function $R(e){return e&&e.properties&&e.properties.displayName||""}A.getEnvironmentDisplayName=$R;var Lv="9.1.0.8202";A.cdsVersionSupportingOSColorEdit="9.1.0000.20708";function qR(e){return Uv(e,Lv)}A.doesCds2EnvironmentSupportApiVersion9_1=qR;function VR(e){return _d(e,Lv)}A.doesCds2VersionSupportApiVersion9_1=VR;function kv(e){let t=Ur(e);if(t)return t.securityGroupId}function Mv(e){return e&&e.properties&&e.properties.connectedGroups}function GR(e,t){let r=Mv(e);return!!r&&!!r.find(n=>n.id===t)||kv(e)===t}A.hasSecurityGroupId=GR;function zR(e){let t=Mv(e);return t&&t.length>0&&t[0].id?t[0].id:kv(e)}A.getSecurityOrConnectedGroupId=zR;function Uv(e,t){let r=e.version;return r?_d(r,t):!1}A.isCds2EnvironmentVersionAtLeast=Uv;function _d(e,t){return t?e?(0,pR.default)(e,t)>=0:!1:!0}A.checkVersions=_d;function WR(e){return e&&e.properties&&e.properties.updateCadence&&e.properties.updateCadence.id||"NotSpecified"}A.getEnvironmentUpdateCadence=WR;function jR(e){let t=Ur(e);return t?Number(t.baseLanguage):0}A.getEnvironmentLanguageCode=jR;function Bv(e){let t=Ur(e);return t?t.instanceApiUrl:void 0}A.getEnvironmentInstanceApiUrl=Bv;function HR(e){let t=Bv(e);return t?t+"/api/data/v9.2":""}A.getEnvironmentWebApiUrl=HR;function QR(e){let t=un(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"}A.getEnvironmentDiscoveryUrl=QR;var JR=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.databaseType)===le.DatabaseType.CommonDataService};A.hasCommonDataServiceDatabase=JR;var XR=e=>{var t;return Mr((t=e.properties)===null||t===void 0?void 0:t.permissions,le.environmentPermissions.AdminReadEnvironment)};A.doesUserHaveAdminPermission=XR;var KR=e=>{var t;return Mr((t=e.properties)===null||t===void 0?void 0:t.permissions,le.environmentPermissions.CreatePowerApp)};A.doesUserHaveCreateAppPermission=KR;var YR=e=>(0,A.doesUserHaveAdminPermission)(e)&&(0,A.hasCommonDataServiceDatabase)(e)?!0:(0,A.doesUserHaveCreateAppPermission)(e)?Xa(e)||(0,A.doesUserHaveDatabaseTablePermissions)(e):!1;A.isUserMakerWithDataAccess=YR;var ZR=e=>(0,A.doesUserHaveCreateAppPermission)(e)&&!Xa(e)&&!(0,A.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,A.doesUserHaveAdminPermission)(e)||!(0,A.hasCommonDataServiceDatabase)(e));A.isUserMakerWithoutDataAccess=ZR;var eF=e=>[le.environmentPermissions.CreateDatabaseEntities,le.environmentPermissions.ListDatabaseEntities,le.environmentPermissions.UpdateDatabaseEntities,le.environmentPermissions.DeleteDatabaseEntities].every(t=>{var r;return Mr((r=e.properties)===null||r===void 0?void 0:r.permissions,t)});A.doesUserHaveDatabaseTablePermissions=eF;var tF=e=>{var t;return Mr((t=e.properties)===null||t===void 0?void 0:t.permissions,le.environmentPermissions.CreateDatabase)};A.doesUserHaveCreateDatabasePermission=tF;function $v(e,t){return!e&&!t?!0:!e||!t?!1:e.toUpperCase()===t.toUpperCase()}A.equalsIgnoreCase=$v;var rF=e=>{var t;return Mr((t=e.properties)===null||t===void 0?void 0:t.permissions,le.environmentPermissions.CreateFlow)};A.doesUserHaveCreateFlowPermission=rF;var nF=e=>(0,A.doesUserHaveAdminPermission)(e)&&(0,A.hasCommonDataServiceDatabase)(e)?!0:(0,A.doesUserHaveCreateFlowPermission)(e)?Xa(e)||(0,A.doesUserHaveDatabaseTablePermissions)(e):!1;A.isUserPautoMakerWithDataAccess=nF;var iF=e=>(0,A.doesUserHaveCreateFlowPermission)(e)&&!Xa(e)&&!(0,A.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,A.doesUserHaveAdminPermission)(e)||!(0,A.hasCommonDataServiceDatabase)(e));A.isUserPautoMakerWithoutDataAccess=iF;var aF=e=>{var t,r;return!Mr((t=e.properties)===null||t===void 0?void 0:t.permissions,le.environmentPermissions.CreateFlow)&&Mr((r=e.properties)===null||r===void 0?void 0:r.permissions,le.environmentPermissions.ReadEnvironment)};A.doesUserHaveFlowRunOnlyPermission=aF});var Pd=g(b=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});b.getRequiredComponentsQueryUrl=b.solutionComponentCountSummariesQueryUrl=b.solutionComponentSummariesQueryUrl=b.solutionComponentConfigurationsQueryUrl=b.chartsQueryUrl=b.workflowsQueryUrl=b.entityDefinitionsQueryUrl=b.solutionComponentDefinitionsQueryUrl=b.getCreateNewArticleTemplateUrl=b.getCreateNewPublisherUrl=b.getEnableSecurityRolesUrl=b.getArticleTemplateUrl=b.getFieldSecurityProfileDesignerUrl=b.getSecurityRoleDesignerUrl=b.getMailMergeTemplateDesignerUrl=b.getEmailTemplateDesignerUrl=b.getConnectionRoleDesignerUrl=b.getSiteMapDesignerUrl=b.getWebResourceFileUrl=b.getWebResourceDesignerUrl=b.getReportDesignerUrl=b.getBusinessProcessFlowDesignerUrl=b.getProcessShareUrl=b.getProcessDesignerUrl=b.getChartDesignerUrl=b.getOpenModernEntityDashboardUrl=b.getNewModernEntityDashboardUrl=b.getNewModernDashboardUrl=b.getOpenModernDashboardUrl=b.getDashboardDesignerUrl=b.getAppModuleDesignerUrl=b.privilegesQueryUrls=b.xrmApiUrl=b.getPlayAppModuleUrl=b.getCrmAdminSecurityUsersUrl=b.getCrmAdminSecurityRolesUrl=b.getCrmMyAppsUrl=b.getCrmAppDesignerUrl=b.getCrmDevResourcesUrl=b.getCrmAllPublishersUrl=b.getCrmAllSolutionsUrl=b.getSolutionPublisherUrl=b.getExportTranslationFileName=b.getExportSolutionTranslationUrl=b.getImportSolutionTranslationUrl=b.getShowSolutionDependenciesUrl=b.getShowComponentDependenciesUrl=b.cdsServiceUrl=b.ODATA_NEXT_LINK=b.ODATA_MAX_PAGE_SIZE=void 0;b.retrieveOrganizationResources=b.getUCIEntityRecordEditUrl=b.getUCIEntityRecordBaseUrl=b.getBusinessRuleDesignerUri=b.retrieveUnpublishedSuffix=b.getSavePowerSettingUri=b.getPowerSettingUri=b.getPowerSettingsUri=b.RetrievePlatform=b.getAppSettingOverrideUri=b.AppSettingOverrideName=b.getOrgSettingOverrideUri=b.OrgSettingOverrideName=b.getSettingDefinitionsUri=b.retrieveFeatureControlSettingsByNamespaceUrl=b.retrieveDeploymentPipelineConfigAppUrl=b.SPNPrincipalIdUrl=b.retrieveDeploymentEnvironmentInfoUrl=b.devSolutionInfoUrl=b.deployOperationStatusUrl=b.getAIGeneratedDeploymentNotesUrl=b.deploymentStageRunUrl=b.validatePackageAsyncUrl=b.deployPackageAsyncUrl=b.updateDeploymentStageRunUrl=b.createDeploymentStageRunUrl=b.retrieveDeploymentStagesUrl=b.retrievePipelinesUrl=b.retrieveDeploymentPipelineInfoUrl=b.getDeploymentStageRunsUrl=b.appDeploymentUrls=b.getProvisionLanguageUrl=b.getSolutionQueryUrl=b.getSolutionsByUniqueNameQueryUrl=b.solutionsQueryUrl=b.getDependentComponentsWithMetadataQueryUrl=void 0;var Vv=qv();b.ODATA_MAX_PAGE_SIZE="odata.maxpagesize";b.ODATA_NEXT_LINK="@odata.nextLink";b.cdsServiceUrl="https://cds-org/";var Ya;(function(e){e.AllSolutions="11",e.AllPublishers="10",e.DevResources="05"})(Ya||(Ya={}));function oF(e,t,r,n){return`${e}tools/dependency/dependencyviewdialog.aspx?appSolutionId=%7b${t}%7d&dType=1&objectid=%7b${r}%7d&objecttype=${n}&operationtype=showdependency`}b.getShowComponentDependenciesUrl=oF;function sF(e,t){let r=`dType=1&isproactivecheck=true&objecttype=7100&operationtype=dependenciesforuninstall&objectid=${t}`;return`${e}tools/dependency/dependencyviewdialog.aspx?${r}`}b.getShowSolutionDependenciesUrl=sF;function lF(e,t){return`${e}tools/muiProvisioning/Dialogs/LangTranslationsImport.aspx?dType=1&appSolutionId=${t}`}b.getImportSolutionTranslationUrl=lF;function uF(e,t){return`${e}_grid/cmds/dlg_exportsolution.aspx?command=exporttranslation&appSolutionId=${t}`}b.getExportSolutionTranslationUrl=uF;function cF(e,t){return e!==void 0&&t!==void 0&&`CrmTranslations_${e}_${t.replace(/[.]/g,"_")}.zip`||""}b.getExportTranslationFileName=cF;function dF(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`}b.getSolutionPublisherUrl=dF;function Td(e,t){return`${e}tools/systemcustomization/systemCustomization.aspx?pid=${t}`}function pF(e){return Td(e,Ya.AllSolutions)}b.getCrmAllSolutionsUrl=pF;function fF(e){return Td(e,Ya.AllPublishers)}b.getCrmAllPublishersUrl=fF;function mF(e){return Td(e,Ya.DevResources)}b.getCrmDevResourcesUrl=mF;function hF(e,t=Vv.crmBapSolutionId){return`${e}designer/app/${t}#/CreateNewApp`}b.getCrmAppDesignerUrl=hF;function gF(e){return`${e}apps`}b.getCrmMyAppsUrl=gF;function vF(e){return Gv(e,"role")+"&forceUCI=0"}b.getCrmAdminSecurityRolesUrl=vF;function yF(e){return`${Gv(e,"systemuser")}&forceclassic=1`}b.getCrmAdminSecurityUsersUrl=yF;function Gv(e,t){return`${e}main.aspx?pagetype=entitylist&etn=${t}`}function bF(e,t){return`${e}main.aspx?appid=${t}`}b.getPlayAppModuleUrl=bF;b.xrmApiUrl="api/data/v9.0";b.privilegesQueryUrls={systemUserInfo:e=>`${e}${b.xrmApiUrl}/WhoAmI`,userPrivileges:(e,t)=>`${e}${b.xrmApiUrl}/systemusers(${t})/Microsoft.Dynamics.CRM.RetrieveUserPrivileges`,systemPrivileges:e=>`${e}${b.xrmApiUrl}/privileges/Microsoft.Dynamics.CRM.RetrievePrivilegeSet`};function wF(e,t,r=Vv.crmBapSolutionId){return`${e}designer/app/${r}/${t}/AppDesignerCanvas/${t}`}b.getAppModuleDesignerUrl=wF;function AF(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${r}%7d&extraqs=%26formId%3d%7b${t}%7d%26dashboardType%3d1030&pagetype=${`${n?"ic":""}dashboardeditor`}`}b.getDashboardDesignerUrl=AF;function CF(e,t,r){return`/e/${e}/s/${t}/dashboard/${r}`}b.getOpenModernDashboardUrl=CF;function SF(e,t,r){let n=r!==void 0?r.toString():void 0;return`/e/${e}/s/${t}/dashboard/new${n?`/${n}`:""}`}b.getNewModernDashboardUrl=SF;function EF(e,t,r,n){let i=n!==void 0?n.toString():void 0;return`/e/${e}/s/${t}/n/${r}/dashboard/new${i?`/${i}`:""}`}b.getNewModernEntityDashboardUrl=EF;function NF(e,t,r,n){return`/e/${e}/s/${t}/n/${r}/dashboard/${n}`}b.getOpenModernEntityDashboardUrl=NF;function DF(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${t}%7d&extraqs=etc=${r||""}`+(n?`%26id=${n}`:"")+"&pagetype=vizdesigner"}b.getChartDesignerUrl=DF;function IF(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}b.getProcessDesignerUrl=IF;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`}b.getProcessShareUrl=_F;function PF(e,t){return`${e}Tools/ProcessControl/UnifiedProcessDesigner.aspx?id=${t}`}b.getBusinessProcessFlowDesignerUrl=PF;function TF(e,t,r){return`${e}CRMReports/reportproperty.aspx?appSolutionId=%7b${r}%7d&disablePersonal=true&id=%7b${t}%7d`}b.getReportDesignerUrl=TF;function OF(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`}b.getWebResourceDesignerUrl=OF;function RF(e,t){return`${e}WebResources/${t}`}b.getWebResourceFileUrl=RF;function FF(e,t,r){return`${e}designer/sitemap/${r}/${t}/SiteMapHome/${t}`}b.getSiteMapDesignerUrl=FF;function xF(e,t,r){return`${e}connections/connectionroles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}b.getConnectionRoleDesignerUrl=xF;function LF(e,t,r){return`${e}tools/emailtemplateeditor/emailtemplateeditor.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}b.getEmailTemplateDesignerUrl=LF;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`}b.getMailMergeTemplateDesignerUrl=kF;function MF(e,t,r){return`${e}biz/roles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}b.getSecurityRoleDesignerUrl=MF;function UF(e,t,r){return`${e}biz/fieldsecurityprofiles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}b.getFieldSecurityProfileDesignerUrl=UF;function BF(e,t,r){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?_CreateFromId=%7b${t}%7d&_CreateFromType=7100&appSolutionId=%7b${t}%7d&id=%7b${r}%7d`}b.getArticleTemplateUrl=BF;function $F(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}`}b.getEnableSecurityRolesUrl=$F;function qF(e){return`${e}tools/publisher/edit.aspx`}b.getCreateNewPublisherUrl=qF;function VF(e,t){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?appSolutionId=${t}`}b.getCreateNewArticleTemplateUrl=VF;b.solutionComponentDefinitionsQueryUrl="api/data/v9.0/solutioncomponentdefinitions";b.entityDefinitionsQueryUrl="api/data/v9.0/EntityDefinitions?$select=EntitySetName,DisplayName,LogicalName&$filter=";b.workflowsQueryUrl="api/data/v9.0/workflows";b.chartsQueryUrl="/api/data/v9.0/savedqueryvisualizations";b.solutionComponentConfigurationsQueryUrl="/api/data/v9.1/solutioncomponentconfigurations?$filter=isdisplayable eq true&$select=name";b.solutionComponentSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentsummaries";b.solutionComponentCountSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentcountsummaries";function GF(e,t){return`${b.xrmApiUrl}/RetrieveRequiredComponents(ObjectId=${e},ComponentType=${t})`}b.getRequiredComponentsQueryUrl=GF;function zF(e,t){return`${b.cdsServiceUrl}${b.xrmApiUrl}/RetrieveDependentComponentsWithMetadata(ObjectId=${e},ComponentType=${t})`}b.getDependentComponentsWithMetadataQueryUrl=zF;b.solutionsQueryUrl="/api/data/v9.0/solutions?$expand=publisherid&$filter=(isvisible eq true)";function WF(e){return`/api/data/v9.0/solutions?$expand=publisherid&$filter=(uniquename eq '${e}')`}b.getSolutionsByUniqueNameQueryUrl=WF;function jF(e){return`/api/data/v9.0/solutions(${e})?$expand=publisherid`}b.getSolutionQueryUrl=jF;function HF(e){return`${e}api/data/v9.1/ProvisionLanguageForUser`}b.getProvisionLanguageUrl=HF;b.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 QF(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`}y.getDeploymentStageRunsUrl=xF;function LF(e,t,r){return`/api/data/v9.1/RetrieveDeploymentPipelineInfo(DeploymentPipelineId=${e},SourceEnvironmentId='${t}',ArtifactName='${r}')`}y.retrieveDeploymentPipelineInfoUrl=LF;function kF(e){return`/api/data/v9.0/deploymentenvironments+ &$orderby=starttime desc`}b.getDeploymentStageRunsUrl=QF;function JF(e,t,r){return`/api/data/v9.1/RetrieveDeploymentPipelineInfo(DeploymentPipelineId=${e},SourceEnvironmentId='${t}',ArtifactName='${r}')`}b.retrieveDeploymentPipelineInfoUrl=JF;function XF(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}')`}y.retrievePipelinesUrl=kF;function MF(e){return`/api/data/v9.0/deploymentstages+ &$filter=(environmentid eq '${e}')`}b.retrievePipelinesUrl=XF;function KF(e){return`/api/data/v9.0/deploymentstages?$filter=(_deploymentpipelineid_value eq ${e})&$select=name,description,deploymentstageid,_previousdeploymentstageid_value- &$expand=targetdeploymentenvironmentid($select=deploymentenvironmentid,environmentid,name)`}y.retrieveDeploymentStagesUrl=MF;function UF(){return"/api/data/v9.0/deploymentstageruns?$select=deploymentstagerunid"}y.createDeploymentStageRunUrl=UF;function BF(e){return`/api/data/v9.0/deploymentstageruns(${e})`}y.updateDeploymentStageRunUrl=BF;function $F(){return"/api/data/v9.0/DeployPackageAsync"}y.deployPackageAsyncUrl=$F;function qF(){return"/api/data/v9.0/ValidatePackageAsync"}y.validatePackageAsyncUrl=qF;function VF(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)":""}`}y.deploymentStageRunUrl=VF;function GF(e){return`/api/data/v9.0/deploymentstageruns(${e})- ?$select=aigenerateddeploymentnotes,deploymentstagerunid`}y.getAIGeneratedDeploymentNotesUrl=GF;function zF(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)`}b.retrieveDeploymentStagesUrl=KF;function YF(){return"/api/data/v9.0/deploymentstageruns?$select=deploymentstagerunid"}b.createDeploymentStageRunUrl=YF;function ZF(e){return`/api/data/v9.0/deploymentstageruns(${e})`}b.updateDeploymentStageRunUrl=ZF;function ex(){return"/api/data/v9.0/DeployPackageAsync"}b.deployPackageAsyncUrl=ex;function tx(){return"/api/data/v9.0/ValidatePackageAsync"}b.validatePackageAsyncUrl=tx;function rx(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)":""}`}b.deploymentStageRunUrl=rx;function nx(e){return`/api/data/v9.0/deploymentstageruns(${e})+ ?$select=aigenerateddeploymentnotes,deploymentstagerunid`}b.getAIGeneratedDeploymentNotesUrl=nx;function ix(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`}y.deployOperationStatusUrl=zF;function WF(e){return`/api/data/v9.0/solutions(${e})- ?$select=solutionid,uniquename,version`}y.devSolutionInfoUrl=WF;function jF(e){return`/api/data/v9.0/deploymentenvironments+ &$select=_deploymentstageid_value,deploymentstagerunid,stagerunstatus,operation,operationstatus,suboperation,artifactname`}b.deployOperationStatusUrl=ix;function ax(e){return`/api/data/v9.0/solutions(${e})+ ?$select=solutionid,uniquename,version`}b.devSolutionInfoUrl=ax;function ox(e){return`/api/data/v9.0/deploymentenvironments?$select=deploymentenvironmentid,environmentid,environmenttype,name- &$filter=(environmentid eq '${e}')`}y.retrieveDeploymentEnvironmentInfoUrl=jF;var HF=e=>`/api/data/v9.0/systemusers+ &$filter=(environmentid eq '${e}')`}b.retrieveDeploymentEnvironmentInfoUrl=ox;var sx=e=>`/api/data/v9.0/systemusers?$select=azureactivedirectoryobjectid- &$filter=(applicationid eq '${e}')`;y.SPNPrincipalIdUrl=HF;function JF(){return"/api/data/v9.0/appmodules?$filter=(uniquename eq 'AppDeploymentConfiguration')"}y.retrieveDeploymentPipelineConfigAppUrl=JF;y.retrieveFeatureControlSettingsByNamespaceUrl="/api/data/v9.1/RetrieveFeatureControlSettingsByNamespace";function QF(e){return`/api/data/v9.0/settingdefinitions${e}`}y.getSettingDefinitionsUri=QF;y.OrgSettingOverrideName="organizationsettings";function XF(e,t=!1){let r=`/api/data/v9.0/${y.OrgSettingOverrideName}${e}`;return t?`${y.cdsServiceUrl}${r}`:r}y.getOrgSettingOverrideUri=XF;y.AppSettingOverrideName="appsettings";function KF(e,t=!1){let r=`/api/data/v9.0/${y.AppSettingOverrideName}${e}`;return t?`${y.cdsServiceUrl.replace("/$","")}${r}`:r}y.getAppSettingOverrideUri=KF;var Xa;(function(e){e[e.All=0]="All",e[e.IsPlatformOnly=1]="IsPlatformOnly",e[e.NotPlatformOnly=2]="NotPlatformOnly"})(Xa||(y.RetrievePlatform=Xa={}));function YF(e,t,r,n=Xa.All,i=!1){let a=[];e&&a.push(`AppUniqueName='${e}'`),t!=null&&a.push(`ReleaseLevel=${t}`),r&&a.push(`RetrieveHiddenSettings=${r}`),n!==Xa.All&&a.push(`RetrievePlatformSettings=${n===Xa.IsPlatformOnly?1:0}`);let o="/api/data/v9.0/RetrieveUnpublishedOverridableSettingsInfo";return a.length&&(o=`${o}(${a.join(",")})`),i?`${y.cdsServiceUrl}${o}`:o}y.getPowerSettingsUri=YF;function ZF(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?`${y.cdsServiceUrl}${a}`:a}y.getPowerSettingUri=ZF;function ex(e=!1){let t="/api/data/v9.0/SaveSettingValue()";return e?`${y.cdsServiceUrl}${t}`:t}y.getSavePowerSettingUri=ex;y.retrieveUnpublishedSuffix="Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()";function tx(e){return`tools/systemcustomization/businessrules/businessRulesDesigner.aspx?BRlaunchpoint=BRGrid&appSolutionId={${e}}`}y.getBusinessRuleDesignerUri=tx;function Bv({environmentInstanceUrl:e,entityLogicalName:t}){return e&&t?`${e}main.aspx?cmdbar=true&forceUCI=1&navbar=off&newWindow=true&pageType=entityRecord&etn=${t}`:void 0}y.getUCIEntityRecordBaseUrl=Bv;function rx({baseUrl:e,environmentInstanceUrl:t,entityLogicalName:r,recordId:n}){let i=e||Bv({environmentInstanceUrl:t,entityLogicalName:r});return i&&n?`${i}&id=${n}`:void 0}y.getUCIEntityRecordEditUrl=rx;y.retrieveOrganizationResources=`${y.cdsServiceUrl}api/data/v9.0/RetrieveOrganizationResources`});var $v=g(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});Vs.DataverseClient=void 0;var nx=Dd(),Vn=ie(),_d=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}/${nx.xrmApiUrl}${n}`}async send(t,r){try{return await r()}catch(n){throw n instanceof Vn.SdkError?n:new Vn.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 Vn.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${t}'`)}if(r.protocol!==n.protocol||r.host!==n.host)throw new Vn.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 Vn.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 Vn.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 Vn.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)))}};Vs.DataverseClient=_d});var qv=g(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.findColumns=dn.findTables=dn.fetchEntityMetadataFromApi=void 0;var Pd=ye(),dr=ee();function Ya(e){var t,r;return(r=(t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)!==null&&r!==void 0?r:""}async function Si(e,t){var r,n;let i=await e.get(t);return i.status<200||i.status>=300?[]:(n=(r=i.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[]}function cn(e){return`/EntityDefinitions(LogicalName='${(0,dr.odataLiteral)(e)}')`}async function ix(e,t,r){let n=await Si(e,`${cn(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata${(0,dr.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 ax(e,t,r){var n;let i=await Si(e,`${cn(t)}/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata${(0,dr.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:Ya(s.Label)}}))}}async function ox(e,t,r){let n=await Si(e,`${cn(t)}/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata${(0,dr.odataQuery)([["$select","LogicalName,Targets"]])}`);for(let i of n){let a=r.get(i.LogicalName);a&&i.Targets&&(a.targets=i.Targets)}}async function sx(e,t){var r,n,i,a;let o=[],s=await Si(e,`${cn(t)}/OneToManyRelationships${(0,dr.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 Si(e,`${cn(t)}/ManyToOneRelationships${(0,dr.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 Si(e,`${cn(t)}/ManyToManyRelationships${(0,dr.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 lx(e,t){var r,n,i,a,o;let s=`${cn(t)}`+(0,dr.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,EntitySetName,IsCustomEntity,PrimaryNameAttribute,PrimaryIdAttribute"],["$expand","Attributes($select=LogicalName,DisplayName,AttributeType,IsCustomAttribute)"]]),u=(0,Pd.ensureSuccess)(await e.get(s),e.apiUrl(s)).body,c=((r=u.Attributes)!==null&&r!==void 0?r:[]).map(m=>{var h;return{logicalName:m.LogicalName,displayName:Ya(m.DisplayName),attributeType:(h=m.AttributeType)!==null&&h!==void 0?h:"Unknown",isCustomAttribute:!!m.IsCustomAttribute}}),d=new Map(c.map(m=>[m.logicalName,m])),[,,,p]=await Promise.all([ix(e,t,d),ax(e,t,d),ox(e,t,d),sx(e,t)]);return{logicalName:u.LogicalName,schemaName:(n=u.SchemaName)!==null&&n!==void 0?n:u.LogicalName,displayName:Ya(u.DisplayName),entitySetName:(i=u.EntitySetName)!==null&&i!==void 0?i:"",primaryNameAttribute:(a=u.PrimaryNameAttribute)!==null&&a!==void 0?a:"",primaryIdAttribute:(o=u.PrimaryIdAttribute)!==null&&o!==void 0?o:"",isCustomEntity:!!u.IsCustomEntity,attributes:c,relationships:p}}dn.fetchEntityMetadataFromApi=lx;async function ux(e,t,r){var n,i;let a=`/EntityDefinitions${(0,dr.odataQuery)([["$select","LogicalName,SchemaName,EntitySetName,DisplayName,IsCustomEntity"]])}`,s=(i=(n=(0,Pd.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:Ya(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}dn.findTables=ux;async function cx(e,t,r,n){var i,a;let o=`${cn(t)}/Attributes`+(0,dr.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute"]]),l=(a=(i=(0,Pd.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,m;return{logicalName:d.LogicalName,schemaName:(p=d.SchemaName)!==null&&p!==void 0?p:d.LogicalName,displayName:Ya(d.DisplayName),attributeType:(m=d.AttributeType)!==null&&m!==void 0?m:"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}dn.findColumns=cx});var Ei=g(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});Gs.DEFAULT_LCID=void 0;Gs.DEFAULT_LCID=1033});var Td=g(pn=>{"use strict";Object.defineProperty(pn,"__esModule",{value:!0});pn.postChangeSet=pn.parseChangeSetStatuses=pn.renderChangeSet=void 0;var zs=ie(),dx=ye(),Vv=yt(),Gv=ee();function zv(e,t){let r=`batch_${(0,Vv.newId)()}`,n=`changeset_${(0,Vv.newId)()}`,i=t.map((s,l)=>String(l+1)),a=t.map((s,l)=>{let u=s.body===void 0?void 0:JSON.stringify(s.body);return(0,Gv.assertNoControlChars)(s.path,"batch operation path"),s.etag&&(0,Gv.assertNoControlChars)(s.etag,"batch operation etag"),[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${i[l]}`,"",`${s.method} ${e.apiUrl(s.path)} HTTP/1.1`,...u===void 0?[]:["Content-Type: application/json;type=entry"],...e.solutionName?[`MSCRM.SolutionUniqueName: ${e.solutionName}`]:[],...s.etag?[`If-Match: ${s.etag}`]:[],"",...u===void 0?[]:[u]].join(`\r+ &$filter=(applicationid eq '${e}')`;b.SPNPrincipalIdUrl=sx;function lx(){return"/api/data/v9.0/appmodules?$filter=(uniquename eq 'AppDeploymentConfiguration')"}b.retrieveDeploymentPipelineConfigAppUrl=lx;b.retrieveFeatureControlSettingsByNamespaceUrl="/api/data/v9.1/RetrieveFeatureControlSettingsByNamespace";function ux(e){return`/api/data/v9.0/settingdefinitions${e}`}b.getSettingDefinitionsUri=ux;b.OrgSettingOverrideName="organizationsettings";function cx(e,t=!1){let r=`/api/data/v9.0/${b.OrgSettingOverrideName}${e}`;return t?`${b.cdsServiceUrl}${r}`:r}b.getOrgSettingOverrideUri=cx;b.AppSettingOverrideName="appsettings";function dx(e,t=!1){let r=`/api/data/v9.0/${b.AppSettingOverrideName}${e}`;return t?`${b.cdsServiceUrl.replace("/$","")}${r}`:r}b.getAppSettingOverrideUri=dx;var Ka;(function(e){e[e.All=0]="All",e[e.IsPlatformOnly=1]="IsPlatformOnly",e[e.NotPlatformOnly=2]="NotPlatformOnly"})(Ka||(b.RetrievePlatform=Ka={}));function px(e,t,r,n=Ka.All,i=!1){let a=[];e&&a.push(`AppUniqueName='${e}'`),t!=null&&a.push(`ReleaseLevel=${t}`),r&&a.push(`RetrieveHiddenSettings=${r}`),n!==Ka.All&&a.push(`RetrievePlatformSettings=${n===Ka.IsPlatformOnly?1:0}`);let o="/api/data/v9.0/RetrieveUnpublishedOverridableSettingsInfo";return a.length&&(o=`${o}(${a.join(",")})`),i?`${b.cdsServiceUrl}${o}`:o}b.getPowerSettingsUri=px;function fx(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?`${b.cdsServiceUrl}${a}`:a}b.getPowerSettingUri=fx;function mx(e=!1){let t="/api/data/v9.0/SaveSettingValue()";return e?`${b.cdsServiceUrl}${t}`:t}b.getSavePowerSettingUri=mx;b.retrieveUnpublishedSuffix="Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()";function hx(e){return`tools/systemcustomization/businessrules/businessRulesDesigner.aspx?BRlaunchpoint=BRGrid&appSolutionId={${e}}`}b.getBusinessRuleDesignerUri=hx;function zv({environmentInstanceUrl:e,entityLogicalName:t}){return e&&t?`${e}main.aspx?cmdbar=true&forceUCI=1&navbar=off&newWindow=true&pageType=entityRecord&etn=${t}`:void 0}b.getUCIEntityRecordBaseUrl=zv;function gx({baseUrl:e,environmentInstanceUrl:t,entityLogicalName:r,recordId:n}){let i=e||zv({environmentInstanceUrl:t,entityLogicalName:r});return i&&n?`${i}&id=${n}`:void 0}b.getUCIEntityRecordEditUrl=gx;b.retrieveOrganizationResources=`${b.cdsServiceUrl}api/data/v9.0/RetrieveOrganizationResources`});var Wv=g(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});zs.DataverseClient=void 0;var vx=Pd(),Vn=ie(),Od=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}/${vx.xrmApiUrl}${n}`}async send(t,r){try{return await r()}catch(n){throw n instanceof Vn.SdkError?n:new Vn.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 Vn.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${t}'`)}if(r.protocol!==n.protocol||r.host!==n.host)throw new Vn.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 Vn.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 Vn.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 Vn.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)))}};zs.DataverseClient=Od});var jv=g(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.findColumns=dn.findTables=dn.fetchEntityMetadataFromApi=void 0;var Rd=be(),pr=ee();function Za(e){var t,r;return(r=(t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)!==null&&r!==void 0?r:""}function Si(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 Ei(e,t){var r,n;let i=await e.get(t);return i.status<200||i.status>=300?[]:(n=(r=i.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[]}function cn(e){return`/EntityDefinitions(LogicalName='${(0,pr.odataLiteral)(e)}')`}async function yx(e,t,r){let n=await Ei(e,`${cn(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata${(0,pr.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 bx(e,t,r){var n;let i=await Ei(e,`${cn(t)}/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata${(0,pr.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:Za(s.Label),...Si(s.Label)?{localizedLabel:Si(s.Label)}:{}}}))}}async function wx(e,t,r){let n=await Ei(e,`${cn(t)}/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata${(0,pr.odataQuery)([["$select","LogicalName,Targets"]])}`);for(let i of n){let a=r.get(i.LogicalName);a&&i.Targets&&(a.targets=i.Targets)}}async function Ax(e,t){var r,n,i,a;let o=[],s=await Ei(e,`${cn(t)}/OneToManyRelationships${(0,pr.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 Ei(e,`${cn(t)}/ManyToOneRelationships${(0,pr.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 Ei(e,`${cn(t)}/ManyToManyRelationships${(0,pr.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 Cx(e,t){var r,n,i,a,o;let s=`${cn(t)}`+(0,pr.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,EntitySetName,IsCustomEntity,PrimaryNameAttribute,PrimaryIdAttribute"],["$expand","Attributes($select=LogicalName,DisplayName,AttributeType,IsCustomAttribute)"]]),u=(0,Rd.ensureSuccess)(await e.get(s),e.apiUrl(s)).body,c=((r=u.Attributes)!==null&&r!==void 0?r:[]).map(f=>{var h;return{logicalName:f.LogicalName,displayName:Za(f.DisplayName),...Si(f.DisplayName)?{localizedDisplayName:Si(f.DisplayName)}:{},attributeType:(h=f.AttributeType)!==null&&h!==void 0?h:"Unknown",isCustomAttribute:!!f.IsCustomAttribute}}),d=new Map(c.map(f=>[f.logicalName,f])),[,,,p]=await Promise.all([yx(e,t,d),bx(e,t,d),wx(e,t,d),Ax(e,t)]);return{logicalName:u.LogicalName,schemaName:(n=u.SchemaName)!==null&&n!==void 0?n:u.LogicalName,displayName:Za(u.DisplayName),...Si(u.DisplayName)?{localizedDisplayName:Si(u.DisplayName)}:{},entitySetName:(i=u.EntitySetName)!==null&&i!==void 0?i:"",primaryNameAttribute:(a=u.PrimaryNameAttribute)!==null&&a!==void 0?a:"",primaryIdAttribute:(o=u.PrimaryIdAttribute)!==null&&o!==void 0?o:"",isCustomEntity:!!u.IsCustomEntity,attributes:c,relationships:p}}dn.fetchEntityMetadataFromApi=Cx;async function Sx(e,t,r){var n,i;let a=`/EntityDefinitions${(0,pr.odataQuery)([["$select","LogicalName,SchemaName,EntitySetName,DisplayName,IsCustomEntity"]])}`,s=(i=(n=(0,Rd.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:Za(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}dn.findTables=Sx;async function Ex(e,t,r,n){var i,a;let o=`${cn(t)}/Attributes`+(0,pr.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute"]]),l=(a=(i=(0,Rd.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:Za(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}dn.findColumns=Ex});var Ni=g(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});Ws.DEFAULT_LCID=void 0;Ws.DEFAULT_LCID=1033});var Fd=g(pn=>{"use strict";Object.defineProperty(pn,"__esModule",{value:!0});pn.postChangeSet=pn.parseChangeSetStatuses=pn.renderChangeSet=void 0;var js=ie(),Nx=be(),Hv=bt(),Qv=ee();function Jv(e,t){let r=`batch_${(0,Hv.newId)()}`,n=`changeset_${(0,Hv.newId)()}`,i=t.map((s,l)=>String(l+1)),a=t.map((s,l)=>{let u=s.body===void 0?void 0:JSON.stringify(s.body);return(0,Qv.assertNoControlChars)(s.path,"batch operation path"),s.etag&&(0,Qv.assertNoControlChars)(s.etag,"batch operation etag"),[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${i[l]}`,"",`${s.method} ${e.apiUrl(s.path)} HTTP/1.1`,...u===void 0?[]:["Content-Type: application/json;type=entry"],...e.solutionName?[`MSCRM.SolutionUniqueName: ${e.solutionName}`]:[],...s.etag?[`If-Match: ${s.etag}`]:[],"",...u===void 0?[]:[u]].join(`\r`)});return{body:[`--${r}`,`Content-Type: multipart/mixed;boundary=${n}`,"",...a,`--${n}--`,`--${r}--`,""].join(`\r-`),batchId:r,contentIds:i}}pn.renderChangeSet=zv;function Wv(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 m=p.indexOf(`\r+`),batchId:r,contentIds:i}}pn.renderChangeSet=Jv;function Xv(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(m===-1)return;let h=p.slice(0,m),w=p.slice(m+4);if(!/^Content-Type:\s*application\/http\b/im.test(h))return;let b=/^HTTP\/1\.[01] (\d{3})\b/.exec(w);if(!b||((i=w.match(/^HTTP\/1\.[01] \d{3}\b/gm))!==null&&i!==void 0?i:[]).length!==1)return;let E=(a=/^Content-ID:\s*(\S+)/im.exec(h))===null||a===void 0?void 0:a[1];if(E===void 0||d.has(E)||!u.has(E))return;d.add(E),c.push(Number(b[1]))}return c.length===0?void 0:c}pn.parseChangeSetStatuses=Wv;async function px(e,t,r){if(t.length===0)return;let{body:n,batchId:i,contentIds:a}=zv(e,t),o=await e.postBatch(n,i),s=e.apiUrl("/$batch");if((0,dx.ensureSuccess)(o,s),typeof o.body!="string"||o.body.length===0)throw new zs.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=Wv(o.body,a);if(l===void 0)throw new zs.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 zs.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 zs.ConnectionError(s,u,`atomic write of ${r} was rolled back: the change set reported HTTP ${u}`)}pn.postChangeSet=px});var Ws=g(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=void 0;var ne=ye(),J=ee(),pr=Ei(),Fe=ie(),fx=Td(),mx={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 Pe(e,t){return{"@odata.type":"Microsoft.Dynamics.CRM.Label",LocalizedLabels:[{"@odata.type":"Microsoft.Dynamics.CRM.LocalizedLabel",Label:e,LanguageCode:t}]}}function Za(e){return{Value:e,CanBeChanged:!0,ManagedPropertyLogicalName:"canmodifyrequirementlevelsettings"}}function Fd(e){let t=e.indexOf("_");return t>0?e.slice(0,t):e}function jv(e,t,r){let n=e[t];n&&typeof n=="object"?n.Value=r:e[t]={Value:r}}function eo(e){let t=(0,ne.readCreatedId)(e,"MetadataId");if(!t)throw new Fe.InvalidArgumentError("Dataverse did not return a MetadataId for the created metadata component");return t}function hx(e,t,r){var n,i,a,o,s,l,u,c,d,p,m,h,w,b,E,D,F,x,q,G,M,U,B,W;if(t.defaultValue!==void 0&&e!=="boolean")throw new Fe.InvalidArgumentError(`createColumn: 'defaultValue' applies to boolean columns, but '${t.schemaName}' is of type '${e}'.`);if(t.integerFormat!==void 0&&e!=="integer")throw new Fe.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:(m=t.minValue)!==null&&m!==void 0?m:-1e11,MaxValue:(h=t.maxValue)!==null&&h!==void 0?h:1e11};case"money":return{"@odata.type":"Microsoft.Dynamics.CRM.MoneyAttributeMetadata",AttributeType:"Money",AttributeTypeName:{Value:"MoneyType"},Precision:(w=t.precision)!==null&&w!==void 0?w:2,PrecisionSource:2,MinValue:(b=t.minValue)!==null&&b!==void 0?b:0,MaxValue:(E=t.maxValue)!==null&&E!==void 0?E:1e9};case"boolean":return{"@odata.type":"Microsoft.Dynamics.CRM.BooleanAttributeMetadata",AttributeType:"Boolean",AttributeTypeName:{Value:"BooleanType"},DefaultValue:(D=t.defaultValue)!==null&&D!==void 0?D:!1,OptionSet:{"@odata.type":"Microsoft.Dynamics.CRM.BooleanOptionSetMetadata",TrueOption:{Value:1,Label:Pe((F=t.trueLabel)!==null&&F!==void 0?F:"Yes",r)},FalseOption:{Value:0,Label:Pe((x=t.falseLabel)!==null&&x!==void 0?x:"No",r)}}};case"dateTime":return{"@odata.type":"Microsoft.Dynamics.CRM.DateTimeAttributeMetadata",AttributeType:"DateTime",AttributeTypeName:{Value:"DateTimeType"},Format:(q=t.dateFormat)!==null&&q!==void 0?q:"DateAndTime"};case"choice":return Hv(t,r,!1);case"multiChoice":return Hv(t,r,!0);case"file":return{"@odata.type":"Microsoft.Dynamics.CRM.FileAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"FileType"},MaxSizeInKB:(G=t.maxSizeKb)!==null&&G!==void 0?G:10240};case"image":return{"@odata.type":"Microsoft.Dynamics.CRM.ImageAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"ImageType"},IsPrimaryImage:(M=t.isPrimaryImage)!==null&&M!==void 0?M:!1,MaxSizeInKB:(U=t.maxSizeKb)!==null&&U!==void 0?U:10240};case"autonumber":return{"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},FormatName:{Value:"Text"},MaxLength:(B=t.maxLength)!==null&&B!==void 0?B:100,AutoNumberFormat:(W=t.autoNumberFormat)!==null&&W!==void 0?W:""};default:throw new Fe.InvalidArgumentError(`unsupported column type '${String(e)}'`)}}function Hv(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 Fe.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:Pe(a.label,t)}))},i}var Od=new WeakMap;async function gx(e,t){var r,n;let i=(r=Od.get(e))===null||r===void 0?void 0:r.get(t);if(i)return i;let a=`/EntityDefinitions(LogicalName='${(0,J.odataLiteral)(t)}')${(0,J.odataQuery)([["$select","EntitySetName"]])}`,s=(n=(0,ne.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.EntitySetName;if(!s)throw new Fe.InvalidArgumentError(`could not resolve EntitySetName for '${t}'`);(0,J.assertODataName)(s,`server-derived EntitySetName for '${t}'`);let l=Od.get(e);return l||(l=new Map,Od.set(e,l)),l.set(t,s),s}X.resolveEntitySetName=gx;async function vx(e,t){var r,n,i,a,o,s,l,u,c,d,p,m,h,w,b;let E=(r=t.languageCode)!==null&&r!==void 0?r:pr.DEFAULT_LCID,D=Fd(t.schemaName),F=(n=t.primaryColumnSchemaName)!==null&&n!==void 0?n:`${D}_Name`,x={"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},SchemaName:F,RequiredLevel:Za("None"),MaxLength:(i=t.primaryColumnMaxLength)!==null&&i!==void 0?i:100,FormatName:{Value:"Text"},DisplayName:Pe((a=t.primaryColumnDisplayName)!==null&&a!==void 0?a:"Name",E),IsPrimaryName:!0};t.primaryColumnAutoNumberFormat&&(x.AutoNumberFormat=t.primaryColumnAutoNumberFormat),t.columns&&Kv(t.columns,"createTable");let q={"@odata.type":"Microsoft.Dynamics.CRM.EntityMetadata",SchemaName:t.schemaName,DisplayName:Pe(t.displayName,E),DisplayCollectionName:Pe((o=t.pluralName)!==null&&o!==void 0?o:`${t.displayName}s`,E),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:[x,...((c=t.columns)!==null&&c!==void 0?c:[]).map(Ve=>xd(Ve,E))]};t.description&&(q.Description=Pe(t.description,E));let G="/EntityDefinitions",M=(0,ne.ensureSuccess)(await e.post(G,q),e.apiUrl(G)),U=eo(M),B=`/EntityDefinitions(${U})`+(0,J.odataQuery)([["$select","LogicalName,EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute"]]),W=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),Se;for(let Ve=1;Ve<=W;Ve+=1){let Ke=await e.get(B);if(Ke.status>=200&&Ke.status<300){Se=Ke;break}Ke.status!==404&&(0,ne.ensureSuccess)(Ke,e.apiUrl(B)),Ve<W&&$>0&&await new Promise(de=>setTimeout(de,$))}if(!Se)throw new Fe.SdkError("TABLE_METADATA_NOT_VISIBLE",`Table '${t.schemaName}' WAS CREATED (MetadataId ${U}) but its metadata was still not readable after ${W} attempt(s). Do NOT re-run the create \u2014 it will collide on the schema name. Re-read /EntityDefinitions(${U}) once the environment catches up, or raise 'readBackAttempts'.`);let ve=Se.body;return{logicalName:(m=ve.LogicalName)!==null&&m!==void 0?m:t.schemaName.toLowerCase(),metadataId:U,entitySetName:(h=ve.EntitySetName)!==null&&h!==void 0?h:"",primaryIdAttribute:(w=ve.PrimaryIdAttribute)!==null&&w!==void 0?w:`${t.schemaName.toLowerCase()}id`,primaryNameAttribute:(b=ve.PrimaryNameAttribute)!==null&&b!==void 0?b:F.toLowerCase()}}X.createTable=vx;function xd(e,t){var r,n;let i=(r=e.languageCode)!==null&&r!==void 0?r:t,a={...hx(e.type,e,i),SchemaName:e.schemaName,RequiredLevel:Za((n=e.required)!==null&&n!==void 0?n:"None"),DisplayName:Pe(e.displayName,i)};return e.description&&(a.Description=Pe(e.description,i)),e.sourceType&&e.sourceType!=="Simple"&&(a.SourceType=e.sourceType==="Rollup"?2:1,e.formulaDefinition&&(a.FormulaDefinition=e.formulaDefinition)),Qv(a,e),a}function Qv(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 yx(e,t,r){var n;let i=xd(r,(n=r.languageCode)!==null&&n!==void 0?n:pr.DEFAULT_LCID),a=`/EntityDefinitions(LogicalName='${(0,J.odataLiteral)(t)}')/Attributes`,o=(0,ne.ensureSuccess)(await e.post(a,i),e.apiUrl(a)),s={logicalName:r.schemaName.toLowerCase(),metadataId:eo(o)};if(r.visualization&&r.visualization!=="None")try{await ey(e,t,s.logicalName,s.metadataId,r.visualization)}catch(l){let u=new Fe.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=yx;var Ni="/controlconfigurations",Xv="CustomRenderersConfiguration",Rd={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 Kv(e,t){let r=e.find(n=>n.visualization&&n.visualization!=="None");if(r)throw new Fe.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 Yv(e){return JSON.stringify({type:Rd[e]})}function bx(e){if(!e)return"None";let t;try{t=JSON.parse(e)}catch{return"None"}let r=t?.type,n=Object.keys(Rd).find(i=>Rd[i]===r);return n??"None"}async function Zv(e,t,r){var n,i;let a=`entitylogicalname eq '${(0,J.odataLiteral)(t)}' and Attribute/logicalname eq '${(0,J.odataLiteral)(r)}'`,o=`${Ni}${(0,J.odataQuery)([["$select","name,uniquename,metadatajson"],["$expand","Attribute($select=name,logicalname)"],["$filter",a]])}`,l=(i=(n=(0,ne.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 wx(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,J.odataLiteral)(t)}')/Attributes(LogicalName='${(0,J.odataLiteral)(r)}')${(0,J.odataQuery)([["$select","MetadataId"]])}`,o=(n=(0,ne.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||n===void 0?void 0:n.MetadataId;if(!o)throw new Fe.InvalidArgumentError(`cannot resolve column '${r}' on '${t}' to set its visualization`);return(0,J.normalizeGuid)(o,"MetadataId")}async function ey(e,t,r,n,i){let a={name:Xv,uniquename:`msdyn_${t}_${r}_customrenderers`,metadatajson:Yv(i),"[email protected]":`/attributes(${(0,J.normalizeGuid)(n,"MetadataId")})`,entitylogicalname:t};(0,ne.ensureSuccess)(await e.post(Ni,a),e.apiUrl(Ni))}async function Ax(e,t,r){var n;let i=await Zv(e,t,r);return bx((n=i[0])===null||n===void 0?void 0:n.metadatajson)}X.getColumnVisualization=Ax;async function Cx(e,t,r,n){let a=(await Zv(e,t,r)).map(u=>u.controlconfigurationid).filter(u=>!!u);if(n==="None"){for(let u of a){let c=`${Ni}(${(0,J.normalizeGuid)(u,"controlconfigurationid")})`;(0,ne.ensureSuccess)(await e.delete(c),e.apiUrl(c))}return}let[o,...s]=a,l=await wx(e,t,r);if(o){let u=`${Ni}(${(0,J.normalizeGuid)(o,"controlconfigurationid")})`,c={name:Xv,metadatajson:Yv(n),"[email protected]":`/attributes(${l})`,entitylogicalname:t};(0,ne.ensureSuccess)(await e.patch(u,c),e.apiUrl(u))}else await ey(e,t,r,l,n);for(let u of s){let c=`${Ni}(${(0,J.normalizeGuid)(u,"controlconfigurationid")})`;(0,ne.ensureSuccess)(await e.delete(c),e.apiUrl(c))}}X.setColumnVisualization=Cx;async function Sx(e,t,r){if(r.length===0)return;if(Kv(r,"createColumns"),!e.supportsAtomicBatch)throw new Fe.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.odataLiteral)(t)}')/Attributes`;await(0,fx.postChangeSet)(e,r.map(i=>{var a;return{method:"POST",path:n,body:xd(i,(a=i.languageCode)!==null&&a!==void 0?a:pr.DEFAULT_LCID)}}),`${r.length} column(s) on '${t}'`)}X.createColumns=Sx;async function Ex(e,t,r){var n,i,a,o;let s=(n=r.languageCode)!==null&&n!==void 0?n:pr.DEFAULT_LCID,l=Fd(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:Pe(r.displayName,s),RequiredLevel:Za((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,ne.ensureSuccess)(await e.post("/CreateCustomerRelationships",d),e.apiUrl("/CreateCustomerRelationships")),{logicalName:r.schemaName.toLowerCase(),metadataId:""}}X.createCustomerColumn=Ex;async function Nx(e,t,r){var n,i,a,o,s;let l=(n=r.languageCode)!==null&&n!==void 0?n:pr.DEFAULT_LCID,u={EntityLogicalName:t,AttributeLogicalName:"statuscode",Label:Pe(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,ne.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=Nx;async function Dx(e,t){var r,n,i,a,o;let s=(r=t.languageCode)!==null&&r!==void 0?r:pr.DEFAULT_LCID,l,u;if(t.type==="OneToMany"){if(!t.referencedEntity||!t.referencingEntity)throw new Fe.InvalidArgumentError("OneToMany relationship requires referencedEntity and referencingEntity");let p=(n=t.lookupSchemaName)!==null&&n!==void 0?n:`${Fd(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:Za((i=t.lookupRequired)!==null&&i!==void 0?i:"None"),DisplayName:Pe((a=t.lookupDisplayName)!==null&&a!==void 0?a:t.referencedEntity,s)}}}else{if(!t.entity1||!t.entity2)throw new Fe.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,ne.ensureSuccess)(await e.post(c,l),e.apiUrl(c));return{schemaName:t.schemaName,metadataId:eo(d),lookupLogicalName:u}}X.createRelationship=Dx;async function Ix(e,t){let r=`/EntityDefinitions(LogicalName='${(0,J.odataLiteral)(t)}')`;(0,ne.ensureSuccess)(await e.delete(r),e.apiUrl(r))}X.deleteTable=Ix;async function _x(e,t,r,n){var i,a;let o=(i=n.languageCode)!==null&&i!==void 0?i:pr.DEFAULT_LCID,s=`/EntityDefinitions(LogicalName='${(0,J.odataLiteral)(t)}')/Attributes`,l=`${s}(LogicalName='${(0,J.odataLiteral)(r)}')${(0,J.odataQuery)([["$select","MetadataId,AttributeType"]])}`,c=(0,ne.ensureSuccess)(await e.get(l),e.apiUrl(l)).body,d=mx[(a=c.AttributeType)!==null&&a!==void 0?a:""];if(!c.MetadataId||!d)throw new Fe.InvalidArgumentError(`cannot update column '${r}' on '${t}' (type '${c.AttributeType}' not supported)`);let p=(0,J.normalizeGuid)(c.MetadataId,"MetadataId"),m=`${s}(${p})/${d}`,h=(0,ne.ensureSuccess)(await e.get(m),e.apiUrl(m)).body;for(let b of Object.keys(h))b.startsWith("@odata.")&&delete h[b];if(h["@odata.type"]=d,n.displayName!==void 0&&(h.DisplayName=Pe(n.displayName,o)),n.description!==void 0&&(h.Description=Pe(n.description,o)),n.required!==void 0&&(h.RequiredLevel=Za(n.required)),n.maxLength!==void 0&&(h.MaxLength=n.maxLength),n.autoNumberFormat!==void 0&&(h.AutoNumberFormat=n.autoNumberFormat),n.defaultValue!==void 0&&c.AttributeType!=="Boolean")throw new Fe.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 Fe.InvalidArgumentError(`updateColumn: 'integerFormat' applies to Integer columns, but '${r}' on '${t}' is of type '${c.AttributeType}'.`);n.defaultValue!==void 0&&(h.DefaultValue=n.defaultValue),n.integerFormat!==void 0&&(h.Format=n.integerFormat),Qv(h,n);let w=`${s}(${p})`;(0,ne.ensureSuccess)(await e.put(w,h,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(w))}X.updateColumn=_x;async function Px(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,J.odataLiteral)(t)}')/Attributes`,a=`${i}(LogicalName='${(0,J.odataLiteral)(r)}')${(0,J.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,ne.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new Fe.InvalidArgumentError(`column '${r}' not found on '${t}'`);let l=`${i}(${(0,J.normalizeGuid)(s,"MetadataId")})`;(0,ne.ensureSuccess)(await e.delete(l),e.apiUrl(l))}X.deleteColumn=Px;async function Tx(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,ne.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 Fe.InvalidArgumentError(`relationship '${t}' not found`);let l=`/RelationshipDefinitions(${(0,J.normalizeGuid)(s,"MetadataId")})`;(0,ne.ensureSuccess)(await e.delete(l),e.apiUrl(l))}X.deleteRelationship=Tx;async function Jv(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,ne.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 Ox(e,t){var r;let n=t.name.toLowerCase(),i=await Jv(e,n);if(i)return{name:n,metadataId:i};let a=(r=t.languageCode)!==null&&r!==void 0?r:pr.DEFAULT_LCID,o={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",Name:n,DisplayName:Pe(t.displayName,a),IsGlobal:!0,OptionSetType:"Picklist",Options:t.options.map(l=>({Value:l.value,Label:Pe(l.label,a)}))};t.description&&(o.Description=Pe(t.description,a));let s="/GlobalOptionSetDefinitions";try{let l=(0,ne.ensureSuccess)(await e.post(s,o),e.apiUrl(s));return{name:n,metadataId:eo(l)}}catch(l){let u;try{u=await Jv(e,n)}catch{u=void 0}if(u)return{name:n,metadataId:u};throw l}}X.createGlobalOptionSet=Ox;async function Rx(e,t){let r=`/GlobalOptionSetDefinitions(Name='${(0,J.odataLiteral)(t.toLowerCase())}')`;(0,ne.ensureSuccess)(await e.delete(r),e.apiUrl(r))}X.deleteGlobalOptionSet=Rx;async function Fx(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:pr.DEFAULT_LCID,a={"@odata.type":"Microsoft.Dynamics.CRM.EntityKeyMetadata",SchemaName:r.schemaName,DisplayName:Pe(r.displayName,i),KeyAttributes:r.keyAttributes},o=`/EntityDefinitions(LogicalName='${(0,J.odataLiteral)(t)}')/Keys`,s=(0,ne.ensureSuccess)(await e.post(o,a),e.apiUrl(o));return{logicalName:r.schemaName.toLowerCase(),metadataId:eo(s)}}X.createAlternateKey=Fx;async function xx(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,J.odataLiteral)(t)}')/Keys`,a=`${i}(LogicalName='${(0,J.odataLiteral)(r.toLowerCase())}')${(0,J.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,ne.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new Fe.InvalidArgumentError(`alternate key '${r}' not found on '${t}'`);let l=`${i}(${(0,J.normalizeGuid)(s,"MetadataId")})`;(0,ne.ensureSuccess)(await e.delete(l),e.apiUrl(l))}X.deleteAlternateKey=xx;async function Lx(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:pr.DEFAULT_LCID,a=`/EntityDefinitions(LogicalName='${(0,J.odataLiteral)(t)}')`,s=(0,ne.ensureSuccess)(await e.get(a),e.apiUrl(a)).body,l=s.MetadataId;if(!l)throw new Fe.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=Pe(r.displayName,i)),r.pluralName!==void 0&&(s.DisplayCollectionName=Pe(r.pluralName,i)),r.description!==void 0&&(s.Description=Pe(r.description,i)),r.auditEnabled!==void 0&&jv(s,"IsAuditEnabled",r.auditEnabled),r.duplicateDetectionEnabled!==void 0&&jv(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,ne.ensureSuccess)(await e.put(c,s,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(c))}X.updateTable=Lx});var mn=g(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.rebuildRaw=bt.assembleChildren=bt.spliceChildren=bt.mergeAttrs=bt.rawFromNode=bt.emptyBag=void 0;var fn=ie(),ty=1e6,Hs=512;function kx(){return{a:[],c:[]}}bt.emptyBag=kx;function ry(e,t=0){if(t>Hs)throw new fn.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${Hs}`);return{n:e.getNodeName(),a:e.getAllProperties().map(r=>[r.key,r.value]),c:e.getAllChildren().map(r=>ry(r,t+1))}}bt.rawFromNode=ry;function Mx(e,t){let r=new Map;for(let[a,o]of t)r.set(a,o);let n=new Set,i=[];for(let[a,o]of e)r.has(a)?i.push([a,r.get(a)]):i.push([a,o]),n.add(a);for(let[a,o]of t)n.has(a)||(i.push([a,o]),n.add(a));return i}bt.mergeAttrs=Mx;function js(e,t){let r=new Set;for(let s of e){let l=s.i;if(!Number.isInteger(l)||l<0||l>ty)throw new fn.InvalidArgumentError(`Bag child index must be an integer in [0, ${ty}] (got ${String(l)})`);if(r.has(l))throw new fn.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}bt.spliceChildren=js;function Ux(e,t){if(e.w){let r={n:e.w.n,a:e.w.a.map(n=>[n[0],n[1]]),c:js(e.w.c,t)};return js(e.c,[r])}return js(e.c,t)}bt.assembleChildren=Ux;function ny(e,t,r,n=0){if(n>Hs)throw new fn.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${Hs}`);Bx(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,ny(a,t,i,n+1));return i}bt.rebuildRaw=ny;function Bx(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new fn.InvalidArgumentError(`Malformed hybrid node at depth ${t}: expected a JSON object`);let r=e;if(typeof r.n!="string")throw new fn.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 fn.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 fn.InvalidArgumentError(`Malformed hybrid node '${r.n}': each attribute must be a [string, string] pair`)}});var Gn=g(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.projectElementBag=Te.serializeNode=Te.domEngine=Te.nodeLikeFromDom=Te.parseXmlRoot=Te.EMPTY_FORM_SENTINEL=Te.TEXT_SENTINEL=void 0;var $x=mn(),to=ie();Te.TEXT_SENTINEL="#text";Te.EMPTY_FORM_SENTINEL="#empty";var Qs=new WeakSet;function qx(e,t){let r=e&&e.trim()!==""?e:t,i=new DOMParser().parseFromString(r,"text/xml").documentElement;if(!i)throw new to.InvalidArgumentError("XML source has no root element (empty or malformed input)");return Gx(i),zx(i),Hx(i,r),i}Te.parseXmlRoot=qx;var Vx=new Set([1,3]);function Gx(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(!Vx.has(a.nodeType))throw new to.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 zx(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 to.InvalidArgumentError(`Unsupported document-level XML node (type ${o.nodeType}: declaration / comment / processing-instruction outside the root element) cannot be round-tripped`)}}function Wx(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 jx(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 ay(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 Hx(e,t){let r=Wx(t),n=jx(e),i=Math.min(r.length,n.length);for(let a=0;a<i;a+=1){if(r[a])continue;let o=n[a];ay(o)||Qs.add(o)}}function Ld(e){let t=e.nodeType===3;return{getNodeName:()=>t?Te.TEXT_SENTINEL:e.tagName,getAllProperties:()=>{var r;if(t)return[{key:Te.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 Qs.has(e)&&!ay(e)&&i.push({key:Te.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(Ld(a))}return r}}}Te.nodeLikeFromDom=Ld;function Jx(e){return{make:t=>t===Te.TEXT_SENTINEL?e.createTextNode(""):e.createElement(t),setProp:(t,r,n)=>{t.nodeType===3?t.nodeValue=n:r===Te.EMPTY_FORM_SENTINEL?Qs.add(t):t.setAttribute(r,n)},addChild:(t,r)=>{t.appendChild(r)}}}Te.domEngine=Jx;function oy(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 Js(r);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))throw Js(r);t+=1;continue}if(r>=56320&&r<=57343)throw Js(r)}}function Js(e){let t=e.toString(16).toUpperCase().padStart(4,"0");return new to.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 Qx(e){return oy(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/\r/g,"
").replace(/\n/g,"
").replace(/\t/g,"	")}function Xx(e){return oy(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function Kx(e){return sy(e,0)}Te.serializeNode=Kx;var iy=512;function sy(e,t){var r;if(t>iy)throw new to.InvalidArgumentError(`XML nesting exceeds the maximum supported depth of ${iy}`);if(e.nodeType===3)return Xx((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+'="'+Qx(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 Qs.has(n)?i+"></"+n.tagName+">":i+" />";i+=">";for(let l of o)i+=sy(l,t+1);return i+"</"+n.tagName+">"}function Yx(e){let t=Ld(e);return{a:t.getAllProperties().map(r=>[r.key,r.value]),c:t.getAllChildren().map((r,n)=>({i:n,node:(0,$x.rawFromNode)(r)}))}}Te.projectElementBag=Yx});var Ud=g(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.getFormSecurityRoles=hn.setFormSecurityRoles=hn.formApi=void 0;var Zx=Kt(),fe=ye(),kt=ee(),Di=ie(),kd=Gn(),eL="formid,formxml,name,type,objecttypecode,formpresentation,formactivationstate,uniquename,description,versionnumber",tL="formid,name,type,objecttypecode",rL=2;hn.formApi={async get(e,t){let n=`/systemforms(${(0,kt.normalizeGuid)(t,"id")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,kt.odataQuery)([["$select",eL]]),i=(0,fe.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,fe.readEtag)(i)}},async list(e,t){let r=[`type eq ${rL}`];t?.entityLogicalName&&r.push(`objecttypecode eq '${(0,kt.odataLiteral)(t.entityLogicalName)}'`);let n=`/systemforms${(0,kt.odataQuery)([["$select",tL],["$filter",r.join(" and ")]])}`;return(await(0,Zx.collectPages)(e,n,"listArtifacts('form')")).map(a=>{var o,s;return{type:"form",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=(0,fe.echoWrite)("formid"),i=`/systemforms${n.query}`,a=(0,fe.ensureSuccess)(await e.post(i,(0,fe.withClientMintedId)(t,"formid",r),n.options),e.apiUrl(i));return{id:(0,fe.resolveCreatedId)(a,"formid","form",r),etag:(0,fe.readEtag)(a)}},async update(e,t,r,n){let i=(0,kt.normalizeGuid)(t,"id");await cy(e,i,uy(i),n);let a=await ly(e,i),o=(0,fe.echoWrite)("formid",{"If-Match":(0,fe.requireEtag)(a,"form",i)}),s=`/systemforms(${i})${o.query}`;return(0,fe.ensureSuccess)(await e.patch(s,r,o.options),e.apiUrl(s)),{id:i,etag:await iL(e,i)}},delete(e,t){return(0,fe.deleteRecord)(e,"systemforms",t)}};var Md="DisplayConditions";async function nL(e,t,r){var n,i,a,o,s;if(r.everyone&&r.roleIds&&r.roleIds.length>0)throw new Di.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 l=(0,kt.normalizeGuid)(t,"formId"),u=`/systemforms(${l})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,kt.odataQuery)([["$select","formid,formxml"]]),c=(0,fe.ensureSuccess)(await e.get(u),e.apiUrl(u)),d=(0,fe.readEtag)(c),p=c.body,m=p?.formxml;if(!m)throw new Di.InvalidArgumentError(`form '${l}' returned no formxml, so its roles cannot be set`);let h=(0,kd.parseXmlRoot)(m,"<form/>"),w=h.ownerDocument;if(!w)throw new Di.InvalidArgumentError(`form '${l}' produced no owner document`);let b=dy(h,Md),E=(n=b?.getAttribute("Order"))!==null&&n!==void 0?n:void 0,D=(i=b?.getAttribute("FallbackForm"))!==null&&i!==void 0?i:void 0;b&&h.removeChild(b);let F=!!r.everyone||((o=(a=r.roleIds)===null||a===void 0?void 0:a.length)!==null&&o!==void 0?o:0)>0;if(!F&&(r.order!==void 0||r.fallbackForm!==void 0)){if(!b)throw new Di.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&&b.setAttribute("Order",String(r.order)),r.fallbackForm!==void 0&&b.setAttribute("FallbackForm",String(r.fallbackForm)),h.appendChild(b)}else if(F){let U=w.createElement(Md),B=r.order!==void 0?String(r.order):E;B!==void 0&&U.setAttribute("Order",B);let W=r.fallbackForm!==void 0?String(r.fallbackForm):D??"false";if(U.setAttribute("FallbackForm",W),r.everyone)U.appendChild(w.createElement("Everyone"));else for(let $ of(s=r.roleIds)!==null&&s!==void 0?s:[]){let Se=w.createElement("Role");Se.setAttribute("Id",`{${(0,kt.normalizeGuid)($,"roleId")}}`),U.appendChild(Se)}h.appendChild(U)}let q=(0,kd.serializeNode)(h);await cy(e,l,u,d);let G=await ly(e,l),M=`/systemforms(${l})`;(0,fe.ensureSuccess)(await e.patch(M,{formxml:q},{headers:{"Content-Type":"application/json","If-Match":(0,fe.requireEtag)(G,"form",l)}}),e.apiUrl(M))}hn.setFormSecurityRoles=nL;async function ly(e,t){let r=`/systemforms(${t})${(0,kt.odataQuery)([["$select","formid"]])}`;return(0,fe.readEtag)((0,fe.ensureSuccess)(await e.get(r),e.apiUrl(r)))}function uy(e){return`/systemforms(${e})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,kt.odataQuery)([["$select","formid"]])}async function iL(e,t){let r=uy(t);return(0,fe.readEtag)((0,fe.ensureSuccess)(await e.get(r),e.apiUrl(r)))}async function cy(e,t,r,n){(0,fe.requireEtag)(n,"form",t);let i=(0,fe.readEtag)((0,fe.ensureSuccess)(await e.get(r),e.apiUrl(r)));if(i===null)throw new Di.SdkError(fe.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 Di.SdkError(fe.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 dy(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 aL(e,t){var r,n;let a=`/systemforms(${(0,kt.normalizeGuid)(t,"formId")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,kt.odataQuery)([["$select","formid,formxml"]]),s=(r=(0,fe.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||r===void 0?void 0:r.formxml;if(!s)return;let l=(0,kd.parseXmlRoot)(s,"<form/>"),u=dy(l,Md);if(!u)return;let c=[],d=!1,p=u.childNodes;for(let h=0;h<p.length;h+=1){let w=p[h];if(w.nodeType!==1)continue;let b=w;if(b.tagName==="Everyone")d=!0;else if(b.tagName==="Role"){let E=(n=b.getAttribute("Id"))!==null&&n!==void 0?n:"";E&&c.push(E.replace(/[{}]/g,"").toLowerCase())}}let m=u.getAttribute("Order");return{...d?{everyone:!0}:{},...c.length>0?{roleIds:c}:{},fallbackForm:u.getAttribute("FallbackForm")==="true",...m!==null&&m!==""?{order:Number(m)}:{}}}hn.getFormSecurityRoles=aL});var Ys=g(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.disassociateRecords=Ne.associateRecords=Ne.createRecordsBulk=Ne.upsertRecord=Ne.queryAllRecords=Ne.queryRecords=Ne.getRecord=Ne.deleteRecord=Ne.updateRecord=Ne.createRecord=void 0;var oL=Kt(),er=ye(),it=ee(),Xs=ie(),fr=Ws();function Ks(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 sL(e,t,r){let i=`/${await(0,fr.resolveEntitySetName)(e,t)}`,a=(0,er.ensureSuccess)(await e.post(i,Ks(r)),e.apiUrl(i)),o=(0,er.readCreatedId)(a,`${t}id`);if(!o)throw new Xs.InvalidArgumentError(`Dataverse did not return an id for the created '${t}' row`);return{id:o,entityType:t}}Ne.createRecord=sL;async function lL(e,t,r,n){let i=(0,it.normalizeGuid)(r,"id"),o=`/${await(0,fr.resolveEntitySetName)(e,t)}(${i})`;(0,er.ensureSuccess)(await e.patch(o,Ks(n)),e.apiUrl(o))}Ne.updateRecord=lL;async function uL(e,t,r){let n=(0,it.normalizeGuid)(r,"id"),a=`/${await(0,fr.resolveEntitySetName)(e,t)}(${n})`;(0,er.ensureSuccess)(await e.delete(a),e.apiUrl(a))}Ne.deleteRecord=uL;async function cL(e,t,r,n){var i;let a=(0,it.normalizeGuid)(r,"id"),o=await(0,fr.resolveEntitySetName)(e,t),s=(0,it.odataQuery)([["$select",n&&n.length>0?n.join(","):void 0]]),l=`/${o}(${a})${s}`;return(i=(0,er.ensureSuccess)(await e.get(l),e.apiUrl(l)).body)!==null&&i!==void 0?i:{}}Ne.getRecord=cL;function dL(e){return e?.fetchXml?(0,it.odataQuery)([["fetchXml",e.fetchXml]]):(0,it.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 py(e,t,r){var n,i;if(r?.paginate){if(r.top!==void 0)throw new Xs.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 Xs.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,fr.resolveEntitySetName)(e,t)}${dL(r)}`;return r?.paginate?(0,oL.collectPages)(e,o,"queryRecords"):(i=(n=(0,er.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]}Ne.queryRecords=py;async function pL(e,t,r){return py(e,t,{...r,paginate:!0})}Ne.queryAllRecords=pL;function fL(e){if("id"in e)return`(${(0,it.normalizeGuid)(e.id,"id")})`;let t=typeof e.value=="string"?`'${(0,it.odataPathLiteral)(e.value)}'`:e.value;return`(${(0,it.assertODataName)(e.key,"alternate key name")}=${t})`}async function mL(e,t,r,n){let i=fL(r),o=`/${await(0,fr.resolveEntitySetName)(e,t)}${i}`,s=(0,er.ensureSuccess)(await e.patch(o,Ks(n)),e.apiUrl(o)),l=s.status===201,u=(0,er.readCreatedId)(s,`${t}id`);return{id:u??("id"in r?(0,it.normalizeGuid)(r.id,"id"):""),created:l}}Ne.upsertRecord=mL;async function hL(e,t,r){var n,i;if(r.length===0)return[];let a=await(0,fr.resolveEntitySetName)(e,t),o=r.map(c=>({"@odata.type":`Microsoft.Dynamics.CRM.${t}`,...Ks(c)})),s=`/${a}/Microsoft.Dynamics.CRM.CreateMultiple`,u=(i=(n=(0,er.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 Xs.InvalidArgumentError(`CreateMultiple on '${t}' returned ${u.length} id(s) for ${r.length} row(s)`);return u}Ne.createRecordsBulk=hL;async function gL(e,t,r,n){let i=(0,it.normalizeGuid)(r,"id"),a=(0,it.normalizeGuid)(n.targetId,"targetId"),o=await(0,fr.resolveEntitySetName)(e,t),s=await(0,fr.resolveEntitySetName)(e,n.targetEntity),l=(0,it.assertODataName)(n.relationshipName,"relationshipName"),u=`/${o}(${i})/${l}/$ref`,c={"@odata.id":e.apiUrl(`/${s}(${a})`)};(0,er.ensureSuccess)(await e.post(u,c),e.apiUrl(u))}Ne.associateRecords=gL;async function vL(e,t,r,n,i){let a=(0,it.normalizeGuid)(r,"id"),o=(0,it.normalizeGuid)(i,"targetId"),s=await(0,fr.resolveEntitySetName)(e,t),l=(0,it.assertODataName)(n,"relationshipName"),u=`/${s}(${a})/${l}(${o})/$ref`;(0,er.ensureSuccess)(await e.delete(u),e.apiUrl(u))}Ne.disassociateRecords=vL});var hy=g(mr=>{"use strict";Object.defineProperty(mr,"__esModule",{value:!0});mr.deleteWebResource=mr.getWebResource=mr.updateWebResource=mr.createWebResource=void 0;var yL=Yt(),ro=ye(),Zs=ee(),Bd=ie(),bL={html:1,css:2,js:3,xml:4,png:5,jpg:6,gif:7,xsl:9,ico:10,svg:11,resx:12};function wL(e){let t=globalThis;if(t.Buffer)return t.Buffer.from(e,"utf8").toString("base64");if(t.btoa){let r=globalThis.TextEncoder;if(r){let n=new r().encode(e),i="",a=32768;for(let o=0;o<n.length;o+=a)i+=String.fromCharCode(...n.subarray(o,o+a));return t.btoa(i)}return t.btoa(e)}throw new Bd.InvalidArgumentError("no base64 encoder available; pass contentBase64 instead of content")}function fy(e){if(e.contentBase64!==void 0)return e.contentBase64;if(e.content!==void 0)return wL(e.content)}async function my(e,t){return(0,yL.publishWebResourceById)(e,t)}async function AL(e,t){var r;let n=fy(t);if(n===void 0)throw new Bd.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:bL[t.type],content:n};t.description&&(i.description=t.description);let a=(0,ro.ensureSuccess)(await e.post("/webresourceset",i),e.apiUrl("/webresourceset")),o=(0,ro.readCreatedId)(a,"webresourceid");if(!o)throw new Bd.InvalidArgumentError(`Dataverse did not return an id for web resource '${t.name}'`);return t.publish!==!1&&await my(e,o),{id:o,name:t.name}}mr.createWebResource=AL;async function CL(e,t,r){let n=(0,Zs.normalizeGuid)(t,"id"),i={},a=fy(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,ro.ensureSuccess)(await e.patch(o,i),e.apiUrl(o)),r.publish!==!1&&await my(e,n)}mr.updateWebResource=CL;async function SL(e,t){var r;let i=`/webresourceset(${(0,Zs.normalizeGuid)(t,"id")})${(0,Zs.odataQuery)([["$select","name,displayname,webresourcetype,content,description"]])}`;return(r=(0,ro.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)!==null&&r!==void 0?r:{}}mr.getWebResource=SL;async function EL(e,t){let n=`/webresourceset(${(0,Zs.normalizeGuid)(t,"id")})`;(0,ro.ensureSuccess)(await e.delete(n),e.apiUrl(n))}mr.deleteWebResource=EL});var el=g(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.applyAppSettings=ze.setAppSetting=ze.readAppSettings=ze.resolveSettingDefinitions=ze.APP_SETTING_UNSET=ze.APP_SETTING_OFF=ze.APP_SETTING_ON=ze.HEADER_AND_NAVIGATION_REFRESH=void 0;var Ii=ye(),Br=ee();ze.HEADER_AND_NAVIGATION_REFRESH="HeaderAndNavigationRefresh";ze.APP_SETTING_ON="2";ze.APP_SETTING_OFF="1";ze.APP_SETTING_UNSET="0";function yy(e,t){return"/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Br.odataQuery)([["$select",e],["$filter",t]])}async function by(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,Br.odataLiteral)(c)}'`).join(" or "),s=`/settingdefinitions${(0,Br.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",o]])}`,u=((n=(r=(0,Ii.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[]).filter(Boolean);for(let c of u)c.uniquename&&a.set(c.uniquename,c);return a}ze.resolveSettingDefinitions=by;async function NL(e,t){var r,n,i,a;let o=(0,Br.normalizeGuid)(t,"App id"),s=yy("appsettingid,value,_settingdefinitionid_value",`_parentappmoduleid_value eq ${o}`),u=((n=(r=(0,Ii.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(w=>`settingdefinitionid eq ${(0,Br.normalizeGuid)(w,"Setting definition id")}`).join(" or "),m=`/settingdefinitions${(0,Br.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",p]])}`,h=(0,Ii.ensureSuccess)(await e.get(m),e.apiUrl(m));for(let w of((a=(i=h.body)===null||i===void 0?void 0:i.value)!==null&&a!==void 0?a:[]).filter(Boolean))w.settingdefinitionid&&d.set(w.settingdefinitionid.toLowerCase(),w)}return u.map(p=>{var m,h,w,b,E;let D=d.get(((m=p._settingdefinitionid_value)!==null&&m!==void 0?m:"").toLowerCase());return{id:(h=p.appsettingid)!==null&&h!==void 0?h:"",name:(b=(w=D?.uniquename)!==null&&w!==void 0?w:p._settingdefinitionid_value)!==null&&b!==void 0?b:"",value:(E=p.value)!==null&&E!==void 0?E:"",...D?.displayname?{displayName:D.displayname}:{}}})}ze.readAppSettings=NL;async function gy(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,Ii.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 wy(e,t,r,n){let i=(0,Br.normalizeGuid)(t,"App id"),o=(await by(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,Br.normalizeGuid)(s,"Setting definition id"),u=await gy(e,i,l);if(u)return vy(e,u,n);let c="/appsettings",d={"[email protected]":`/appmodules(${i})`,"[email protected]":`/settingdefinitions(${l})`,value:n},p,m;try{if(p=await e.post(c,d),p.status>=200&&p.status<300)return"created"}catch(w){m=w}let h;try{h=await gy(e,i,l)}catch{h=void 0}if(h)return vy(e,h,n);throw p&&(0,Ii.ensureSuccess)(p,e.apiUrl(c)),m}ze.setAppSetting=wy;async function vy(e,t,r){if(t.value===r)return"unchanged";let n=`/appsettings(${(0,Br.normalizeGuid)(t.id,"App setting id")})`;return(0,Ii.ensureSuccess)(await e.patch(n,{value:r}),e.apiUrl(n)),"updated"}async function DL(e,t,r){var n;let i=[];for(let[a,o]of Object.entries(r??{}))try{await wy(e,t,a,o)}catch(s){i.push(`App setting '${a}' was not applied: ${(n=s?.message)!==null&&n!==void 0?n:String(s)} The app was created; set it later with setAppSetting().`)}return i}ze.applyAppSettings=DL});var rl=g(tl=>{"use strict";Object.defineProperty(tl,"__esModule",{value:!0});tl.HEADER_NAV_BOOLEAN_RULE=void 0;tl.HEADER_NAV_BOOLEAN_RULE="headerAndNavigationRefresh-must-be-boolean"});var Cy=g(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.deleteSolution=Z.importSolution=Z.exportSolution=Z.removeSolutionComponent=Z.addSolutionComponent=Z.setSolutionVersion=Z.createSolution=Z.createPublisher=Z.getSolution=Z.fetchSolutionComponents=Z.SolutionComponentType=void 0;var Ay=Kt(),tr=ye(),wt=ee(),zn=ie();Z.SolutionComponentType={SavedQuery:26,Workflow:29,SavedQueryVisualization:59,SystemForm:60,AppModule:80,UxAgentProject:10372};var IL=[Z.SolutionComponentType.SavedQuery,Z.SolutionComponentType.Workflow,Z.SolutionComponentType.SavedQueryVisualization,Z.SolutionComponentType.SystemForm,Z.SolutionComponentType.AppModule,Z.SolutionComponentType.UxAgentProject];async function _L(e,t){let r=(0,wt.normalizeGuid)(t,"solutionId"),n=IL.map(s=>`msdyn_componenttype eq ${s}`).join(" or "),i=`/msdyn_solutioncomponentsummaries${(0,wt.odataQuery)([["$select","msdyn_objectid,msdyn_componenttype,msdyn_workflowcategory,msdyn_displayname,msdyn_name"],["$filter",`msdyn_solutionid eq ${r} and (${n})`]])}`,o=(await(0,Ay.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 PL(e,r,o)]}Z.fetchSolutionComponents=_L;async function PL(e,t,r){let n=new Set(r.map(s=>s.objectId.toLowerCase())),i=`/solutioncomponents${(0,wt.odataQuery)([["$select","objectid,componenttype"],["$filter",`_solutionid_value eq ${t} and componenttype eq ${Z.SolutionComponentType.UxAgentProject}`]])}`,a=await(0,Ay.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:Z.SolutionComponentType.UxAgentProject}))}return o}function TL(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 OL(e,t){var r,n,i,a,o,s,l,u,c,d;let p=String(t??"").trim();if(!p)throw new zn.InvalidArgumentError("getSolution: a solution unique name or id is required.");let m=TL(p)?`solutionid eq ${(0,wt.normalizeGuid)(p,"solutionId")}`:`uniquename eq '${(0,wt.odataLiteral)(p)}'`,h=`/solutions${(0,wt.odataQuery)([["$select","solutionid,uniquename,friendlyname,version,ismanaged"],["$expand","publisherid($select=publisherid,uniquename,customizationprefix,customizationoptionvalueprefix)"],["$filter",m]])}`,E=((n=(r=(0,tr.ensureSuccess)(await e.get(h),e.apiUrl(h)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0];if(!E?.solutionid)throw new zn.InvalidArgumentError(`No solution found for '${t}'.`);let D=E.publisherid;if(!D?.publisherid)throw new zn.InvalidArgumentError(`Solution '${(i=E.uniquename)!==null&&i!==void 0?i:t}' returned no owning publisher, so its customization prefix cannot be determined; refusing to report an empty prefix that could be mistaken for "no prefix".`);if(!("customizationprefix"in D))throw new zn.InvalidArgumentError(`Solution '${(a=E.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,wt.normalizeGuid)(E.solutionid,"solutionId"),uniqueName:(o=E.uniquename)!==null&&o!==void 0?o:"",friendlyName:(s=E.friendlyname)!==null&&s!==void 0?s:"",version:(l=E.version)!==null&&l!==void 0?l:"",isManaged:!!E.ismanaged,publisherId:(0,wt.normalizeGuid)(D.publisherid,"publisherId"),publisherUniqueName:(u=D.uniquename)!==null&&u!==void 0?u:"",publisherPrefix:(c=D.customizationprefix)!==null&&c!==void 0?c:"",publisherOptionValuePrefix:(d=D.customizationoptionvalueprefix)!==null&&d!==void 0?d:0}}Z.getSolution=OL;async function RL(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,tr.ensureSuccess)(await e.post("/publishers",n),e.apiUrl("/publishers")),a=(0,tr.readCreatedId)(i,"publisherid");if(!a)throw new zn.InvalidArgumentError(`Dataverse did not return an id for publisher '${t.uniqueName}'`);return{id:a,uniqueName:t.uniqueName}}Z.createPublisher=RL;async function FL(e,t){var r;let n=(0,wt.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,tr.ensureSuccess)(await e.post("/solutions",i),e.apiUrl("/solutions")),o=(0,tr.readCreatedId)(a,"solutionid");if(!o)throw new zn.InvalidArgumentError(`Dataverse did not return an id for solution '${t.uniqueName}'`);return{id:o,uniqueName:t.uniqueName}}Z.createSolution=FL;async function xL(e,t,r){let i=`/solutions(${(0,wt.normalizeGuid)(t,"solutionId")})`;(0,tr.ensureSuccess)(await e.patch(i,{version:r}),e.apiUrl(i))}Z.setSolutionVersion=xL;async function LL(e,t){var r;let i={ComponentId:(0,wt.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,tr.ensureSuccess)(await e.post("/AddSolutionComponent",i),e.apiUrl("/AddSolutionComponent"))}Z.addSolutionComponent=LL;async function kL(e,t,r,n){let a={SolutionComponent:{"@odata.type":"Microsoft.Dynamics.CRM.solutioncomponent",solutioncomponentid:(0,wt.normalizeGuid)(t,"componentId")},ComponentType:r,SolutionUniqueName:n};(0,tr.ensureSuccess)(await e.post("/RemoveSolutionComponent",a),e.apiUrl("/RemoveSolutionComponent"))}Z.removeSolutionComponent=kL;async function ML(e,t){var r,n;let i={SolutionName:t.solutionName,Managed:(r=t.managed)!==null&&r!==void 0?r:!1},o=(n=(0,tr.ensureSuccess)(await e.post("/ExportSolution",i),e.apiUrl("/ExportSolution")).body)===null||n===void 0?void 0:n.ExportSolutionFile;if(!o)throw new zn.InvalidArgumentError(`ExportSolution returned no file for '${t.solutionName}'`);return{base64:o}}Z.exportSolution=ML;async function UL(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,wt.normalizeGuid)(t.importJobId,"importJobId")),(0,tr.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution"))}Z.importSolution=UL;async function BL(e,t){let n=`/solutions(${(0,wt.normalizeGuid)(t,"solutionId")})`;(0,tr.ensureSuccess)(await e.delete(n),e.apiUrl(n))}Z.deleteSolution=BL});var al=g(gn=>{"use strict";Object.defineProperty(gn,"__esModule",{value:!0});gn.appApi=gn.deleteAppResolvingOnce=gn.unpublishedAppModulesQuery=void 0;var Wd=Kt(),$L=Hd(),Sy=Yt(),qL=el(),we=ye(),ae=ee(),zd=yt(),VL=Td(),me=ie(),GL=(0,ae.odataQuery)([["$select","appmoduleid,name,uniquename,description"]]),$d="appmoduleid,name,uniquename,description";function Ty(e,t,r){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,ae.odataQuery)([["$select",e],["$filter",t],["$top",r]])}gn.unpublishedAppModulesQuery=Ty;function qd(e,t){return Ty(e,t?`appmoduleid eq ${t}`:void 0,t?1:void 0)}function il(e,t){return"/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,ae.odataQuery)([["$select",t],["$filter",`sitemapid eq ${e}`],["$top",1]])}function _i(e){var t;let r=(t=e.body)===null||t===void 0?void 0:t.value;if(Array.isArray(r))return r[0]}function nl(e){let t=e?.["@odata.etag"];return typeof t=="string"?t:null}function no(e){let t=new Set,r=[];for(let n of e??[])n&&!t.has(n)&&(t.add(n),r.push(n));return r}function zL(e){return`cdsapp_${(e||"").replace(/[^a-zA-Z0-9]/g,"")||"app"}`}async function Oy(e,t){var r,n;let i=u=>{throw new me.SdkError("APP_SITEMAP_UNRESOLVED",`The sitemap lookup for app uniquename '${t??""}' ${u}, so it cannot be determined whether this app has a sitemap. Retry; if the app is newly created, publish it first (an unpublished app is not readable).`)};if(!t)return i("cannot run because the app record carried no uniquename");let a=`/sitemaps${(0,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 WL(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 jd(e){return e instanceof Error?e.message:String(e)}async function jL(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,we.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,we.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 (${jd(a)}); it will not be visible or playable until a role is granted access to it.`}}async function HL(e,t){let r=[];async function n(s,l,u){try{return(await(0,Wd.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}' (${jd(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 Ey=new WeakMap;async function JL(e,t){let r=Ey.get(e);r||(r=new Map,Ey.set(e,r));let n=r.get(t);if(n!==void 0)return n;let i=await QL(e,t);return i&&r.set(t,i),i}async function Ny(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 QL(e,t){let r=`/EntityDefinitions(LogicalName='${(0,ae.odataLiteral)(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 Dy(e,t){let r=[],n=no(t.entities),i=4,a=await Ny(n,i,m=>JL(e,m)),o=n.filter((m,h)=>!a[h]);if(o.length>0)throw new me.SdkError("APP_ENTITY_COMPONENT_UNRESOLVED",`Refusing to build app components: table(s) ${o.map(m=>`'${m}'`).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(m=>!!m);for(let m of s)r.push({"@odata.id":`${m.entitySetName}(${m.metadataId})`});for(let m of no(t.components.forms))r.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:m});for(let m of no(t.components.views))r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:m});for(let m of no(t.components.charts))r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:m});for(let m of no(t.components.dashboards))r.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:m});let l=new Set(t.components.forms),u=new Set(t.components.views),c=new Set(t.components.charts),d=await Ny(n,i,m=>HL(e,m)),p=d.flatMap(m=>m.warnings);for(let m of d){for(let h of m.forms)l.has(h)||(l.add(h),r.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:h}));for(let h of m.views)u.has(h)||(u.add(h),r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:h}));for(let h of m.charts)c.has(h)||(c.add(h),r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:h}))}return{components:r,tables:s,warnings:p}}async function Iy(e,t,r){if(r.length===0)return;let n="/AddAppComponents";(0,we.ensureSuccess)(await e.post(n,{AppId:t,Components:r}),e.apiUrl(n))}function XL(e){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,ae.odataQuery)([["$select","appmoduleid,appmoduleidunique"],["$filter",`appmoduleid eq ${e}`],["$top",1]])}async function _y(e,t,r){var n;if(r.length===0)return;let i=XL(t),a=await e.get(i);if(a.status<200||a.status>=300)throw new me.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its components were written but could not be verified \u2014 the unpublished-aware read returned HTTP ${a.status}. Re-push to retry.`);let o=_i(a),s=o?.appmoduleidunique;if(typeof s!="string"||!s)throw new me.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its components were written but could not be verified \u2014 the app did not return an 'appmoduleidunique' to file components under. Re-push to retry.`);let l=`/appmodulecomponents${(0,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 me.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its table components were written but could not be verified \u2014 reading them back returned HTTP ${u.status}. Re-push to retry.`);let c=(n=u.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(c))throw new me.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its table components were written but could not be verified \u2014 the read-back returned no readable result set. Re-push to retry.`);let d=new Set(c.map(m=>m.objectid).filter(m=>typeof m=="string").map(m=>m.toLowerCase())),p=r.filter(m=>!d.has(m.metadataId.toLowerCase()));if(p.length>0)throw new me.SdkError("APP_COMPONENTS_NOT_PERSISTED",`App '${t}': ${p.length} declared table(s) are NOT components of the app after AddAppComponents reported success \u2014 ${p.map(m=>`'${m.logicalName}' (expected objectid ${m.metadataId})`).join(", ")}. The app's navigation would reference content the app does not contain.`)}async function KL(e,t,r){let n=`/appmodules(${t})`,i=`/sitemaps(${r.sitemapId})`;try{if(!await YL(e,r.sitemapId)){r.serverRefusedSitemap&&(0,we.ensureSuccess)(await e.delete(n),e.apiUrl(n));return}e.supportsAtomicBatch&&await Fy(e,[{path:n,etag:r.appEtag},{path:i,etag:r.sitemapEtag}])}catch{}}async function YL(e,t){var r;let n=il(t,"sitemapid"),i=await e.get(n);if(i.status<200||i.status>=300)throw new me.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned HTTP ${i.status}, so it cannot be determined whether the row exists.`);let a=(r=i.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a))throw new me.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned no readable result set, so it cannot be determined whether the row exists.`);return a.length>0}async function Ry(e,t){var r;let n=(0,ae.normalizeGuid)(t,"id"),i=h=>{throw new me.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})${GL}`,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 Oy(e,s);if(!l)return{uniquename:s,appEtag:(0,we.readEtag)(o)};let u=(0,ae.normalizeGuid)(l,"sitemapId"),c=il(u,"sitemapid,sitemapnameunique,sitemapxml"),d;try{d=await e.get(c)}catch(h){return i(`reading sitemap '${u}' failed (${h.message}).`)}if(d.status<200||d.status>=300)return i(`reading sitemap '${u}' returned HTTP ${d.status}.`);let p=_i(d);if(!p)return i(`sitemap '${u}' was not returned by the unpublished-aware read.`);if(p.sitemapnameunique!==s)return i(`sitemap '${u}' now carries sitemapnameunique '${String(p.sitemapnameunique)}', not '${s}', so it is no longer this app's sitemap.`);let m=p.sitemapxml;return typeof m!="string"?i(`sitemap '${u}' returned no sitemapxml.`):{sitemapId:u,uniquename:s,sitemapXml:m,appEtag:(0,we.readEtag)(o),sitemapEtag:nl(p)}}async function ZL(e,t,r){let n=(0,ae.normalizeGuid)(t,"id"),i=await Ry(e,n);await r?.(i.sitemapXml),await xy(e,n,i)}gn.deleteAppResolvingOnce=ZL;async function Fy(e,t){let r=`batch_${(0,zd.newId)()}`,n=`changeset_${(0,zd.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+`);if(f===-1)return;let h=p.slice(0,f),y=p.slice(f+4);if(!/^Content-Type:\s*application\/http\b/im.test(h))return;let w=/^HTTP\/1\.[01] (\d{3})\b/.exec(y);if(!w||((i=y.match(/^HTTP\/1\.[01] \d{3}\b/gm))!==null&&i!==void 0?i:[]).length!==1)return;let N=(a=/^Content-ID:\s*(\S+)/im.exec(h))===null||a===void 0?void 0:a[1];if(N===void 0||d.has(N)||!u.has(N))return;d.add(N),c.push(Number(w[1]))}return c.length===0?void 0:c}pn.parseChangeSetStatuses=Xv;async function Dx(e,t,r){if(t.length===0)return;let{body:n,batchId:i,contentIds:a}=Jv(e,t),o=await e.postBatch(n,i),s=e.apiUrl("/$batch");if((0,Nx.ensureSuccess)(o,s),typeof o.body!="string"||o.body.length===0)throw new js.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=Xv(o.body,a);if(l===void 0)throw new js.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 js.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 js.ConnectionError(s,u,`atomic write of ${r} was rolled back: the change set reported HTTP ${u}`)}pn.postChangeSet=Dx});var Hs=g(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.updateTable=Q.deleteAlternateKey=Q.createAlternateKey=Q.deleteGlobalOptionSet=Q.createGlobalOptionSet=Q.deleteRelationship=Q.deleteColumn=Q.updateColumn=Q.deleteTable=Q.createRelationship=Q.insertStatusValue=Q.createCustomerColumn=Q.createColumns=Q.setColumnVisualization=Q.getColumnVisualization=Q.createColumn=Q.createTable=Q.resolveEntitySetName=Q.pluralFallback=void 0;var ne=be(),H=ee(),fr=Ni(),de=ie(),Ix=Fd(),_x={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 Te(e,t){return{"@odata.type":"Microsoft.Dynamics.CRM.Label",LocalizedLabels:Px(e,t)}}var Kv=65535;function Px(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 de.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 de.InvalidArgumentError(`localized label key '${a}' is not an LCID (expected a canonical positive integer, e.g. 1033)`);let s=Number(a);if(s>Kv)throw new de.InvalidArgumentError(`localized label LCID ${s} is out of range (1-${Kv})`);if(i.has(s))throw new de.InvalidArgumentError(`localized label LCID ${s} is specified more than once`);if(i.add(s),typeof o!="string")throw new de.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 de.InvalidArgumentError(`localized label for LCID ${t} must be a string`);return[t,`${r}s`]}))}Q.pluralFallback=ty;function eo(e){return{Value:e,CanBeChanged:!0,ManagedPropertyLogicalName:"canmodifyrequirementlevelsettings"}}function kd(e){let t=e.indexOf("_");return t>0?e.slice(0,t):e}function Yv(e,t,r){let n=e[t];n&&typeof n=="object"?n.Value=r:e[t]={Value:r}}function to(e){let t=(0,ne.readCreatedId)(e,"MetadataId");if(!t)throw new de.InvalidArgumentError("Dataverse did not return a MetadataId for the created metadata component");return t}function Tx(e,t,r){var n,i,a,o,s,l,u,c,d,p,f,h,y,w,N,D,x,F,X,V,M,U,B,z;if(t.defaultValue!==void 0&&e!=="boolean")throw new de.InvalidArgumentError(`createColumn: 'defaultValue' applies to boolean columns, but '${t.schemaName}' is of type '${e}'.`);if(t.integerFormat!==void 0&&e!=="integer")throw new de.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:(h=t.maxValue)!==null&&h!==void 0?h:1e11};case"money":return{"@odata.type":"Microsoft.Dynamics.CRM.MoneyAttributeMetadata",AttributeType:"Money",AttributeTypeName:{Value:"MoneyType"},Precision:(y=t.precision)!==null&&y!==void 0?y:2,PrecisionSource:2,MinValue:(w=t.minValue)!==null&&w!==void 0?w:0,MaxValue:(N=t.maxValue)!==null&&N!==void 0?N:1e9};case"boolean":return{"@odata.type":"Microsoft.Dynamics.CRM.BooleanAttributeMetadata",AttributeType:"Boolean",AttributeTypeName:{Value:"BooleanType"},DefaultValue:(D=t.defaultValue)!==null&&D!==void 0?D:!1,OptionSet:{"@odata.type":"Microsoft.Dynamics.CRM.BooleanOptionSetMetadata",TrueOption:{Value:1,Label:Te((x=t.trueLabel)!==null&&x!==void 0?x:"Yes",r)},FalseOption:{Value:0,Label:Te((F=t.falseLabel)!==null&&F!==void 0?F:"No",r)}}};case"dateTime":return{"@odata.type":"Microsoft.Dynamics.CRM.DateTimeAttributeMetadata",AttributeType:"DateTime",AttributeTypeName:{Value:"DateTimeType"},Format:(X=t.dateFormat)!==null&&X!==void 0?X:"DateAndTime"};case"choice":return Zv(t,r,!1);case"multiChoice":return Zv(t,r,!0);case"file":return{"@odata.type":"Microsoft.Dynamics.CRM.FileAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"FileType"},MaxSizeInKB:(V=t.maxSizeKb)!==null&&V!==void 0?V:10240};case"image":return{"@odata.type":"Microsoft.Dynamics.CRM.ImageAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"ImageType"},IsPrimaryImage:(M=t.isPrimaryImage)!==null&&M!==void 0?M:!1,MaxSizeInKB:(U=t.maxSizeKb)!==null&&U!==void 0?U:10240};case"autonumber":return{"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},FormatName:{Value:"Text"},MaxLength:(B=t.maxLength)!==null&&B!==void 0?B:100,AutoNumberFormat:(z=t.autoNumberFormat)!==null&&z!==void 0?z:""};default:throw new de.InvalidArgumentError(`unsupported column type '${String(e)}'`)}}function Zv(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,H.normalizeGuid)(e.globalChoiceMetadataId,"globalChoiceMetadataId")})`,i;if(!e.options||e.options.length===0)throw new de.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:Te(a.label,t)}))},i}var xd=new WeakMap;async function Ox(e,t){var r,n;let i=(r=xd.get(e))===null||r===void 0?void 0:r.get(t);if(i)return i;let a=`/EntityDefinitions(LogicalName='${(0,H.odataLiteral)(t)}')${(0,H.odataQuery)([["$select","EntitySetName"]])}`,s=(n=(0,ne.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.EntitySetName;if(!s)throw new de.InvalidArgumentError(`could not resolve EntitySetName for '${t}'`);(0,H.assertODataName)(s,`server-derived EntitySetName for '${t}'`);let l=xd.get(e);return l||(l=new Map,xd.set(e,l)),l.set(t,s),s}Q.resolveEntitySetName=Ox;async function Rx(e,t){var r,n,i,a,o,s,l,u,c,d,p,f,h,y,w;let N=(r=t.languageCode)!==null&&r!==void 0?r:fr.DEFAULT_LCID,D=kd(t.schemaName),x=(n=t.primaryColumnSchemaName)!==null&&n!==void 0?n:`${D}_Name`,F={"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},SchemaName:x,RequiredLevel:eo("None"),MaxLength:(i=t.primaryColumnMaxLength)!==null&&i!==void 0?i:100,FormatName:{Value:"Text"},DisplayName:Te((a=t.primaryColumnDisplayName)!==null&&a!==void 0?a:"Name",N),IsPrimaryName:!0};t.primaryColumnAutoNumberFormat&&(F.AutoNumberFormat=t.primaryColumnAutoNumberFormat),t.columns&&iy(t.columns,"createTable");let X={"@odata.type":"Microsoft.Dynamics.CRM.EntityMetadata",SchemaName:t.schemaName,DisplayName:Te(t.displayName,N),DisplayCollectionName:Te((o=t.pluralName)!==null&&o!==void 0?o:ty(t.displayName),N),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:[F,...((c=t.columns)!==null&&c!==void 0?c:[]).map(Ge=>Md(Ge,N))]};t.description&&(X.Description=Te(t.description,N));let V="/EntityDefinitions",M=(0,ne.ensureSuccess)(await e.post(V,X),e.apiUrl(V)),U=to(M),B=`/EntityDefinitions(${U})`+(0,H.odataQuery)([["$select","LogicalName,EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute"]]),z=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),Ee;for(let Ge=1;Ge<=z;Ge+=1){let Ze=await e.get(B);if(Ze.status>=200&&Ze.status<300){Ee=Ze;break}Ze.status!==404&&(0,ne.ensureSuccess)(Ze,e.apiUrl(B)),Ge<z&&$>0&&await new Promise(pe=>setTimeout(pe,$))}if(!Ee)throw new de.SdkError("TABLE_METADATA_NOT_VISIBLE",`Table '${t.schemaName}' WAS CREATED (MetadataId ${U}) but its metadata was still not readable after ${z} attempt(s). Do NOT re-run the create \u2014 it will collide on the schema name. Re-read /EntityDefinitions(${U}) once the environment catches up, or raise 'readBackAttempts'.`);let ye=Ee.body;return{logicalName:(f=ye.LogicalName)!==null&&f!==void 0?f:t.schemaName.toLowerCase(),metadataId:U,entitySetName:(h=ye.EntitySetName)!==null&&h!==void 0?h:"",primaryIdAttribute:(y=ye.PrimaryIdAttribute)!==null&&y!==void 0?y:`${t.schemaName.toLowerCase()}id`,primaryNameAttribute:(w=ye.PrimaryNameAttribute)!==null&&w!==void 0?w:x.toLowerCase()}}Q.createTable=Rx;function Md(e,t){var r,n;let i=(r=e.languageCode)!==null&&r!==void 0?r:t,a={...Tx(e.type,e,i),SchemaName:e.schemaName,RequiredLevel:eo((n=e.required)!==null&&n!==void 0?n:"None"),DisplayName:Te(e.displayName,i)};return e.description&&(a.Description=Te(e.description,i)),e.sourceType&&e.sourceType!=="Simple"&&(a.SourceType=e.sourceType==="Rollup"?2:1,e.formulaDefinition&&(a.FormulaDefinition=e.formulaDefinition)),ry(a,e),a}function ry(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 Fx(e,t,r){var n;let i=Md(r,(n=r.languageCode)!==null&&n!==void 0?n:fr.DEFAULT_LCID),a=`/EntityDefinitions(LogicalName='${(0,H.odataLiteral)(t)}')/Attributes`,o=(0,ne.ensureSuccess)(await e.post(a,i),e.apiUrl(a)),s={logicalName:r.schemaName.toLowerCase(),metadataId:to(o)};if(r.visualization&&r.visualization!=="None")try{await sy(e,t,s.logicalName,s.metadataId,r.visualization)}catch(l){let u=new de.SdkError("COLUMN_VISUALIZATION_BIND_FAILED",`Column '${s.logicalName}' on '${t}' was created, but binding its '${r.visualization}' grid visualization failed; the column exists WITHOUT a visualization. Retry with setColumnVisualization('${t}', '${s.logicalName}', '${r.visualization}'). Cause: ${l instanceof Error?l.message:String(l)}`);throw u.cause=l,u}return s}Q.createColumn=Fx;var Di="/controlconfigurations",ny="CustomRenderersConfiguration",Ld={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 iy(e,t){let r=e.find(n=>n.visualization&&n.visualization!=="None");if(r)throw new de.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 ay(e){return JSON.stringify({type:Ld[e]})}function xx(e){if(!e)return"None";let t;try{t=JSON.parse(e)}catch{return"None"}let r=t?.type,n=Object.keys(Ld).find(i=>Ld[i]===r);return n??"None"}async function oy(e,t,r){var n,i;let a=`entitylogicalname eq '${(0,H.odataLiteral)(t)}' and Attribute/logicalname eq '${(0,H.odataLiteral)(r)}'`,o=`${Di}${(0,H.odataQuery)([["$select","name,uniquename,metadatajson"],["$expand","Attribute($select=name,logicalname)"],["$filter",a]])}`,l=(i=(n=(0,ne.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 Lx(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,H.odataLiteral)(t)}')/Attributes(LogicalName='${(0,H.odataLiteral)(r)}')${(0,H.odataQuery)([["$select","MetadataId"]])}`,o=(n=(0,ne.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||n===void 0?void 0:n.MetadataId;if(!o)throw new de.InvalidArgumentError(`cannot resolve column '${r}' on '${t}' to set its visualization`);return(0,H.normalizeGuid)(o,"MetadataId")}async function sy(e,t,r,n,i){let a={name:ny,uniquename:`msdyn_${t}_${r}_customrenderers`,metadatajson:ay(i),"[email protected]":`/attributes(${(0,H.normalizeGuid)(n,"MetadataId")})`,entitylogicalname:t};(0,ne.ensureSuccess)(await e.post(Di,a),e.apiUrl(Di))}async function kx(e,t,r){var n;let i=await oy(e,t,r);return xx((n=i[0])===null||n===void 0?void 0:n.metadatajson)}Q.getColumnVisualization=kx;async function Mx(e,t,r,n){let a=(await oy(e,t,r)).map(u=>u.controlconfigurationid).filter(u=>!!u);if(n==="None"){for(let u of a){let c=`${Di}(${(0,H.normalizeGuid)(u,"controlconfigurationid")})`;(0,ne.ensureSuccess)(await e.delete(c),e.apiUrl(c))}return}let[o,...s]=a,l=await Lx(e,t,r);if(o){let u=`${Di}(${(0,H.normalizeGuid)(o,"controlconfigurationid")})`,c={name:ny,metadatajson:ay(n),"[email protected]":`/attributes(${l})`,entitylogicalname:t};(0,ne.ensureSuccess)(await e.patch(u,c),e.apiUrl(u))}else await sy(e,t,r,l,n);for(let u of s){let c=`${Di}(${(0,H.normalizeGuid)(u,"controlconfigurationid")})`;(0,ne.ensureSuccess)(await e.delete(c),e.apiUrl(c))}}Q.setColumnVisualization=Mx;async function Ux(e,t,r){if(r.length===0)return;if(iy(r,"createColumns"),!e.supportsAtomicBatch)throw new de.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,H.odataLiteral)(t)}')/Attributes`;await(0,Ix.postChangeSet)(e,r.map(i=>{var a;return{method:"POST",path:n,body:Md(i,(a=i.languageCode)!==null&&a!==void 0?a:fr.DEFAULT_LCID)}}),`${r.length} column(s) on '${t}'`)}Q.createColumns=Ux;async function Bx(e,t,r){var n,i,a,o;let s=(n=r.languageCode)!==null&&n!==void 0?n:fr.DEFAULT_LCID,l=kd(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:Te(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,ne.ensureSuccess)(await e.post("/CreateCustomerRelationships",d),e.apiUrl("/CreateCustomerRelationships")),{logicalName:r.schemaName.toLowerCase(),metadataId:""}}Q.createCustomerColumn=Bx;async function $x(e,t,r){var n,i,a,o,s;let l=(n=r.languageCode)!==null&&n!==void 0?n:fr.DEFAULT_LCID,u={EntityLogicalName:t,AttributeLogicalName:"statuscode",Label:Te(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,ne.ensureSuccess)(await e.post("/InsertStatusValue",u),e.apiUrl("/InsertStatusValue"));return Number((s=(o=(a=c.body)===null||a===void 0?void 0:a.NewOptionValue)!==null&&o!==void 0?o:r.value)!==null&&s!==void 0?s:0)}Q.insertStatusValue=$x;async function qx(e,t){var r,n,i,a,o;let s=(r=t.languageCode)!==null&&r!==void 0?r:fr.DEFAULT_LCID,l,u;if(t.type==="OneToMany"){if(!t.referencedEntity||!t.referencingEntity)throw new de.InvalidArgumentError("OneToMany relationship requires referencedEntity and referencingEntity");let p=(n=t.lookupSchemaName)!==null&&n!==void 0?n:`${kd(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:Te((a=t.lookupDisplayName)!==null&&a!==void 0?a:t.referencedEntity,s)}}}else{if(!t.entity1||!t.entity2)throw new de.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,ne.ensureSuccess)(await e.post(c,l),e.apiUrl(c));return{schemaName:t.schemaName,metadataId:to(d),lookupLogicalName:u}}Q.createRelationship=qx;async function Vx(e,t){let r=`/EntityDefinitions(LogicalName='${(0,H.odataLiteral)(t)}')`;(0,ne.ensureSuccess)(await e.delete(r),e.apiUrl(r))}Q.deleteTable=Vx;async function Gx(e,t,r,n){var i,a;let o=(i=n.languageCode)!==null&&i!==void 0?i:fr.DEFAULT_LCID,s=`/EntityDefinitions(LogicalName='${(0,H.odataLiteral)(t)}')/Attributes`,l=`${s}(LogicalName='${(0,H.odataLiteral)(r)}')${(0,H.odataQuery)([["$select","MetadataId,AttributeType"]])}`,c=(0,ne.ensureSuccess)(await e.get(l),e.apiUrl(l)).body,d=_x[(a=c.AttributeType)!==null&&a!==void 0?a:""];if(!c.MetadataId||!d)throw new de.InvalidArgumentError(`cannot update column '${r}' on '${t}' (type '${c.AttributeType}' not supported)`);let p=(0,H.normalizeGuid)(c.MetadataId,"MetadataId"),f=`${s}(${p})/${d}`,h=(0,ne.ensureSuccess)(await e.get(f),e.apiUrl(f)).body;for(let w of Object.keys(h))w.startsWith("@odata.")&&delete h[w];if(h["@odata.type"]=d,n.displayName!==void 0&&(h.DisplayName=Te(n.displayName,o)),n.description!==void 0&&(h.Description=Te(n.description,o)),n.required!==void 0&&(h.RequiredLevel=eo(n.required)),n.maxLength!==void 0&&(h.MaxLength=n.maxLength),n.autoNumberFormat!==void 0&&(h.AutoNumberFormat=n.autoNumberFormat),n.defaultValue!==void 0&&c.AttributeType!=="Boolean")throw new de.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 de.InvalidArgumentError(`updateColumn: 'integerFormat' applies to Integer columns, but '${r}' on '${t}' is of type '${c.AttributeType}'.`);n.defaultValue!==void 0&&(h.DefaultValue=n.defaultValue),n.integerFormat!==void 0&&(h.Format=n.integerFormat),ry(h,n);let y=`${s}(${p})`;(0,ne.ensureSuccess)(await e.put(y,h,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(y))}Q.updateColumn=Gx;async function zx(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,H.odataLiteral)(t)}')/Attributes`,a=`${i}(LogicalName='${(0,H.odataLiteral)(r)}')${(0,H.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,ne.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new de.InvalidArgumentError(`column '${r}' not found on '${t}'`);let l=`${i}(${(0,H.normalizeGuid)(s,"MetadataId")})`;(0,ne.ensureSuccess)(await e.delete(l),e.apiUrl(l))}Q.deleteColumn=zx;async function Wx(e,t){var r,n,i;let a=`/RelationshipDefinitions${(0,H.odataQuery)([["$filter",`SchemaName eq '${(0,H.odataLiteral)(t)}'`],["$select","MetadataId"]])}`,s=(i=(n=(r=(0,ne.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 de.InvalidArgumentError(`relationship '${t}' not found`);let l=`/RelationshipDefinitions(${(0,H.normalizeGuid)(s,"MetadataId")})`;(0,ne.ensureSuccess)(await e.delete(l),e.apiUrl(l))}Q.deleteRelationship=Wx;async function ey(e,t){var r;let n=`/GlobalOptionSetDefinitions(Name='${(0,H.odataPathLiteral)(t)}')${(0,H.odataQuery)([["$select","MetadataId"]])}`,i=await e.get(n);if(i.status===404)return;let o=(r=(0,ne.ensureSuccess)(i,e.apiUrl(n)).body)===null||r===void 0?void 0:r.MetadataId;return o?(0,H.normalizeGuid)(o,"MetadataId"):void 0}async function jx(e,t){var r;let n=t.name.toLowerCase(),i=await ey(e,n);if(i)return{name:n,metadataId:i};let a=(r=t.languageCode)!==null&&r!==void 0?r:fr.DEFAULT_LCID,o={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",Name:n,DisplayName:Te(t.displayName,a),IsGlobal:!0,OptionSetType:"Picklist",Options:t.options.map(l=>({Value:l.value,Label:Te(l.label,a)}))};t.description&&(o.Description=Te(t.description,a));let s="/GlobalOptionSetDefinitions";try{let l=(0,ne.ensureSuccess)(await e.post(s,o),e.apiUrl(s));return{name:n,metadataId:to(l)}}catch(l){let u;try{u=await ey(e,n)}catch{u=void 0}if(u)return{name:n,metadataId:u};throw l}}Q.createGlobalOptionSet=jx;async function Hx(e,t){let r=`/GlobalOptionSetDefinitions(Name='${(0,H.odataLiteral)(t.toLowerCase())}')`;(0,ne.ensureSuccess)(await e.delete(r),e.apiUrl(r))}Q.deleteGlobalOptionSet=Hx;async function Qx(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:fr.DEFAULT_LCID,a={"@odata.type":"Microsoft.Dynamics.CRM.EntityKeyMetadata",SchemaName:r.schemaName,DisplayName:Te(r.displayName,i),KeyAttributes:r.keyAttributes},o=`/EntityDefinitions(LogicalName='${(0,H.odataLiteral)(t)}')/Keys`,s=(0,ne.ensureSuccess)(await e.post(o,a),e.apiUrl(o));return{logicalName:r.schemaName.toLowerCase(),metadataId:to(s)}}Q.createAlternateKey=Qx;async function Jx(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,H.odataLiteral)(t)}')/Keys`,a=`${i}(LogicalName='${(0,H.odataLiteral)(r.toLowerCase())}')${(0,H.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,ne.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new de.InvalidArgumentError(`alternate key '${r}' not found on '${t}'`);let l=`${i}(${(0,H.normalizeGuid)(s,"MetadataId")})`;(0,ne.ensureSuccess)(await e.delete(l),e.apiUrl(l))}Q.deleteAlternateKey=Jx;async function Xx(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:fr.DEFAULT_LCID,a=`/EntityDefinitions(LogicalName='${(0,H.odataLiteral)(t)}')`,s=(0,ne.ensureSuccess)(await e.get(a),e.apiUrl(a)).body,l=s.MetadataId;if(!l)throw new de.InvalidArgumentError(`table '${t}' not found`);let u=(0,H.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=Te(r.displayName,i)),r.pluralName!==void 0&&(s.DisplayCollectionName=Te(r.pluralName,i)),r.description!==void 0&&(s.Description=Te(r.description,i)),r.auditEnabled!==void 0&&Yv(s,"IsAuditEnabled",r.auditEnabled),r.duplicateDetectionEnabled!==void 0&&Yv(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,ne.ensureSuccess)(await e.put(c,s,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(c))}Q.updateTable=Xx});var mn=g(wt=>{"use strict";Object.defineProperty(wt,"__esModule",{value:!0});wt.rebuildRaw=wt.assembleChildren=wt.spliceChildren=wt.mergeAttrs=wt.rawFromNode=wt.emptyBag=void 0;var fn=ie(),ly=1e6,Js=512;function Kx(){return{a:[],c:[]}}wt.emptyBag=Kx;function uy(e,t=0){if(t>Js)throw new fn.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${Js}`);return{n:e.getNodeName(),a:e.getAllProperties().map(r=>[r.key,r.value]),c:e.getAllChildren().map(r=>uy(r,t+1))}}wt.rawFromNode=uy;function Yx(e,t,r=[]){let n=new Map;for(let[s,l]of t)n.set(s,l);let i=new Set(r.filter(s=>!n.has(s))),a=new Set,o=[];for(let[s,l]of e)i.has(s)||(n.has(s)?o.push([s,n.get(s)]):o.push([s,l]),a.add(s));for(let[s,l]of t)a.has(s)||(o.push([s,l]),a.add(s));return o}wt.mergeAttrs=Yx;function Qs(e,t){let r=new Set;for(let s of e){let l=s.i;if(!Number.isInteger(l)||l<0||l>ly)throw new fn.InvalidArgumentError(`Bag child index must be an integer in [0, ${ly}] (got ${String(l)})`);if(r.has(l))throw new fn.InvalidArgumentError(`Duplicate bag child index ${l}`);r.add(l)}let n=[...e].sort((s,l)=>s.i-l.i),i=[],a=0,o=0;for(let s of n){for(;o<s.i&&a<t.length;)i.push(t[a]),a+=1,o+=1;o<s.i&&(o=s.i),i.push(s.node),o+=1}for(;a<t.length;)i.push(t[a]),a+=1;return i}wt.spliceChildren=Qs;function Zx(e,t){if(e.w){let r={n:e.w.n,a:e.w.a.map(n=>[n[0],n[1]]),c:Qs(e.w.c,t)};return Qs(e.c,[r])}return Qs(e.c,t)}wt.assembleChildren=Zx;function cy(e,t,r,n=0){if(n>Js)throw new fn.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${Js}`);eL(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,cy(a,t,i,n+1));return i}wt.rebuildRaw=cy;function eL(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new fn.InvalidArgumentError(`Malformed hybrid node at depth ${t}: expected a JSON object`);let r=e;if(typeof r.n!="string")throw new fn.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 fn.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 fn.InvalidArgumentError(`Malformed hybrid node '${r.n}': each attribute must be a [string, string] pair`)}});var Gn=g(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.projectElementBag=Oe.serializeNode=Oe.domEngine=Oe.nodeLikeFromDom=Oe.parseXmlRoot=Oe.EMPTY_FORM_SENTINEL=Oe.TEXT_SENTINEL=void 0;var tL=mn(),ro=ie();Oe.TEXT_SENTINEL="#text";Oe.EMPTY_FORM_SENTINEL="#empty";var Ks=new WeakSet;function rL(e,t){let r=e&&e.trim()!==""?e:t,i=new DOMParser().parseFromString(r,"text/xml").documentElement;if(!i)throw new ro.InvalidArgumentError("XML source has no root element (empty or malformed input)");return iL(i),aL(i),lL(i,r),i}Oe.parseXmlRoot=rL;var nL=new Set([1,3]);function iL(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(!nL.has(a.nodeType))throw new ro.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 aL(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 ro.InvalidArgumentError(`Unsupported document-level XML node (type ${o.nodeType}: declaration / comment / processing-instruction outside the root element) cannot be round-tripped`)}}function oL(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 sL(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 py(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 lL(e,t){let r=oL(t),n=sL(e),i=Math.min(r.length,n.length);for(let a=0;a<i;a+=1){if(r[a])continue;let o=n[a];py(o)||Ks.add(o)}}function Ud(e){let t=e.nodeType===3;return{getNodeName:()=>t?Oe.TEXT_SENTINEL:e.tagName,getAllProperties:()=>{var r;if(t)return[{key:Oe.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 Ks.has(e)&&!py(e)&&i.push({key:Oe.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(Ud(a))}return r}}}Oe.nodeLikeFromDom=Ud;function uL(e){return{make:t=>t===Oe.TEXT_SENTINEL?e.createTextNode(""):e.createElement(t),setProp:(t,r,n)=>{t.nodeType===3?t.nodeValue=n:r===Oe.EMPTY_FORM_SENTINEL?Ks.add(t):t.setAttribute(r,n)},addChild:(t,r)=>{t.appendChild(r)}}}Oe.domEngine=uL;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 Xs(r);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))throw Xs(r);t+=1;continue}if(r>=56320&&r<=57343)throw Xs(r)}}function Xs(e){let t=e.toString(16).toUpperCase().padStart(4,"0");return new ro.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 cL(e){return fy(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/\r/g,"
").replace(/\n/g,"
").replace(/\t/g,"	")}function dL(e){return fy(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function pL(e){return my(e,0)}Oe.serializeNode=pL;var dy=512;function my(e,t){var r;if(t>dy)throw new ro.InvalidArgumentError(`XML nesting exceeds the maximum supported depth of ${dy}`);if(e.nodeType===3)return dL((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+'="'+cL(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 Ks.has(n)?i+"></"+n.tagName+">":i+" />";i+=">";for(let l of o)i+=my(l,t+1);return i+"</"+n.tagName+">"}function fL(e){let t=Ud(e);return{a:t.getAllProperties().map(r=>[r.key,r.value]),c:t.getAllChildren().map((r,n)=>({i:n,node:(0,tL.rawFromNode)(r)}))}}Oe.projectElementBag=fL});var qd=g(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.getFormSecurityRoles=hn.setFormSecurityRoles=hn.formApi=void 0;var mL=Kt(),me=be(),Mt=ee(),Ii=ie(),Bd=Gn(),hL="formid,formxml,name,type,objecttypecode,formpresentation,formactivationstate,uniquename,description,versionnumber",gL="formid,name,type,objecttypecode",vL=2,yL={Main:vL,QuickView:6,QuickCreate:7,Card:11};hn.formApi={async get(e,t){let n=`/systemforms(${(0,Mt.normalizeGuid)(t,"id")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Mt.odataQuery)([["$select",hL]]),i=(0,me.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,me.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=>yL[u]))],o=[i.length===1?`type eq ${i[0]}`:`(${i.map(u=>`type eq ${u}`).join(" or ")})`];t?.entityLogicalName&&o.push(`objecttypecode eq '${(0,Mt.odataLiteral)(t.entityLogicalName)}'`);let s=`/systemforms${(0,Mt.odataQuery)([["$select",gL],["$filter",o.join(" and ")]])}`;return(await(0,mL.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,me.echoWrite)("formid"),i=`/systemforms${n.query}`,a=(0,me.ensureSuccess)(await e.post(i,(0,me.withClientMintedId)(t,"formid",r),n.options),e.apiUrl(i));return{id:(0,me.resolveCreatedId)(a,"formid","form",r),etag:(0,me.readEtag)(a)}},async update(e,t,r,n){let i=(0,Mt.normalizeGuid)(t,"id");await vy(e,i,gy(i),n);let a=await hy(e,i),o=(0,me.echoWrite)("formid",{"If-Match":(0,me.requireEtag)(a,"form",i)}),s=`/systemforms(${i})${o.query}`;return(0,me.ensureSuccess)(await e.patch(s,r,o.options),e.apiUrl(s)),{id:i,etag:await wL(e,i)}},delete(e,t){return(0,me.deleteRecord)(e,"systemforms",t)}};var $d="DisplayConditions";async function bL(e,t,r){var n,i,a,o,s;if(r.everyone&&r.roleIds&&r.roleIds.length>0)throw new Ii.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 l=(0,Mt.normalizeGuid)(t,"formId"),u=`/systemforms(${l})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Mt.odataQuery)([["$select","formid,formxml"]]),c=(0,me.ensureSuccess)(await e.get(u),e.apiUrl(u)),d=(0,me.readEtag)(c),p=c.body,f=p?.formxml;if(!f)throw new Ii.InvalidArgumentError(`form '${l}' returned no formxml, so its roles cannot be set`);let h=(0,Bd.parseXmlRoot)(f,"<form/>"),y=h.ownerDocument;if(!y)throw new Ii.InvalidArgumentError(`form '${l}' produced no owner document`);let w=yy(h,$d),N=(n=w?.getAttribute("Order"))!==null&&n!==void 0?n:void 0,D=(i=w?.getAttribute("FallbackForm"))!==null&&i!==void 0?i:void 0;w&&h.removeChild(w);let x=!!r.everyone||((o=(a=r.roleIds)===null||a===void 0?void 0:a.length)!==null&&o!==void 0?o:0)>0;if(!x&&(r.order!==void 0||r.fallbackForm!==void 0)){if(!w)throw new Ii.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&&w.setAttribute("Order",String(r.order)),r.fallbackForm!==void 0&&w.setAttribute("FallbackForm",String(r.fallbackForm)),h.appendChild(w)}else if(x){let U=y.createElement($d),B=r.order!==void 0?String(r.order):N;B!==void 0&&U.setAttribute("Order",B);let z=r.fallbackForm!==void 0?String(r.fallbackForm):D??"false";if(U.setAttribute("FallbackForm",z),r.everyone)U.appendChild(y.createElement("Everyone"));else for(let $ of(s=r.roleIds)!==null&&s!==void 0?s:[]){let Ee=y.createElement("Role");Ee.setAttribute("Id",`{${(0,Mt.normalizeGuid)($,"roleId")}}`),U.appendChild(Ee)}h.appendChild(U)}let X=(0,Bd.serializeNode)(h);await vy(e,l,u,d);let V=await hy(e,l),M=`/systemforms(${l})`;(0,me.ensureSuccess)(await e.patch(M,{formxml:X},{headers:{"Content-Type":"application/json","If-Match":(0,me.requireEtag)(V,"form",l)}}),e.apiUrl(M))}hn.setFormSecurityRoles=bL;async function hy(e,t){let r=`/systemforms(${t})${(0,Mt.odataQuery)([["$select","formid"]])}`;return(0,me.readEtag)((0,me.ensureSuccess)(await e.get(r),e.apiUrl(r)))}function gy(e){return`/systemforms(${e})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Mt.odataQuery)([["$select","formid"]])}async function wL(e,t){let r=gy(t);return(0,me.readEtag)((0,me.ensureSuccess)(await e.get(r),e.apiUrl(r)))}async function vy(e,t,r,n){(0,me.requireEtag)(n,"form",t);let i=(0,me.readEtag)((0,me.ensureSuccess)(await e.get(r),e.apiUrl(r)));if(i===null)throw new Ii.SdkError(me.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 Ii.SdkError(me.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 yy(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 AL(e,t){var r,n;let a=`/systemforms(${(0,Mt.normalizeGuid)(t,"formId")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Mt.odataQuery)([["$select","formid,formxml"]]),s=(r=(0,me.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||r===void 0?void 0:r.formxml;if(!s)return;let l=(0,Bd.parseXmlRoot)(s,"<form/>"),u=yy(l,$d);if(!u)return;let c=[],d=!1,p=u.childNodes;for(let h=0;h<p.length;h+=1){let y=p[h];if(y.nodeType!==1)continue;let w=y;if(w.tagName==="Everyone")d=!0;else if(w.tagName==="Role"){let N=(n=w.getAttribute("Id"))!==null&&n!==void 0?n:"";N&&c.push(N.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)}:{}}}hn.getFormSecurityRoles=AL});var el=g(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.disassociateRecords=De.associateRecords=De.createRecordsBulk=De.upsertRecord=De.queryAllRecords=De.queryRecords=De.getRecord=De.deleteRecord=De.updateRecord=De.createRecord=void 0;var CL=Kt(),er=be(),it=ee(),Ys=ie(),mr=Hs();function Zs(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 SL(e,t,r){let i=`/${await(0,mr.resolveEntitySetName)(e,t)}`,a=(0,er.ensureSuccess)(await e.post(i,Zs(r)),e.apiUrl(i)),o=(0,er.readCreatedId)(a,`${t}id`);if(!o)throw new Ys.InvalidArgumentError(`Dataverse did not return an id for the created '${t}' row`);return{id:o,entityType:t}}De.createRecord=SL;async function EL(e,t,r,n){let i=(0,it.normalizeGuid)(r,"id"),o=`/${await(0,mr.resolveEntitySetName)(e,t)}(${i})`;(0,er.ensureSuccess)(await e.patch(o,Zs(n)),e.apiUrl(o))}De.updateRecord=EL;async function NL(e,t,r){let n=(0,it.normalizeGuid)(r,"id"),a=`/${await(0,mr.resolveEntitySetName)(e,t)}(${n})`;(0,er.ensureSuccess)(await e.delete(a),e.apiUrl(a))}De.deleteRecord=NL;async function DL(e,t,r,n){var i;let a=(0,it.normalizeGuid)(r,"id"),o=await(0,mr.resolveEntitySetName)(e,t),s=(0,it.odataQuery)([["$select",n&&n.length>0?n.join(","):void 0]]),l=`/${o}(${a})${s}`;return(i=(0,er.ensureSuccess)(await e.get(l),e.apiUrl(l)).body)!==null&&i!==void 0?i:{}}De.getRecord=DL;function IL(e){return e?.fetchXml?(0,it.odataQuery)([["fetchXml",e.fetchXml]]):(0,it.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 by(e,t,r){var n,i;if(r?.paginate){if(r.top!==void 0)throw new Ys.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 Ys.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,mr.resolveEntitySetName)(e,t)}${IL(r)}`;return r?.paginate?(0,CL.collectPages)(e,o,"queryRecords"):(i=(n=(0,er.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]}De.queryRecords=by;async function _L(e,t,r){return by(e,t,{...r,paginate:!0})}De.queryAllRecords=_L;function PL(e){if("id"in e)return`(${(0,it.normalizeGuid)(e.id,"id")})`;let t=typeof e.value=="string"?`'${(0,it.odataPathLiteral)(e.value)}'`:e.value;return`(${(0,it.assertODataName)(e.key,"alternate key name")}=${t})`}async function TL(e,t,r,n){let i=PL(r),o=`/${await(0,mr.resolveEntitySetName)(e,t)}${i}`,s=(0,er.ensureSuccess)(await e.patch(o,Zs(n)),e.apiUrl(o)),l=s.status===201,u=(0,er.readCreatedId)(s,`${t}id`);return{id:u??("id"in r?(0,it.normalizeGuid)(r.id,"id"):""),created:l}}De.upsertRecord=TL;async function OL(e,t,r){var n,i;if(r.length===0)return[];let a=await(0,mr.resolveEntitySetName)(e,t),o=r.map(c=>({"@odata.type":`Microsoft.Dynamics.CRM.${t}`,...Zs(c)})),s=`/${a}/Microsoft.Dynamics.CRM.CreateMultiple`,u=(i=(n=(0,er.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 Ys.InvalidArgumentError(`CreateMultiple on '${t}' returned ${u.length} id(s) for ${r.length} row(s)`);return u}De.createRecordsBulk=OL;async function RL(e,t,r,n){let i=(0,it.normalizeGuid)(r,"id"),a=(0,it.normalizeGuid)(n.targetId,"targetId"),o=await(0,mr.resolveEntitySetName)(e,t),s=await(0,mr.resolveEntitySetName)(e,n.targetEntity),l=(0,it.assertODataName)(n.relationshipName,"relationshipName"),u=`/${o}(${i})/${l}/$ref`,c={"@odata.id":e.apiUrl(`/${s}(${a})`)};(0,er.ensureSuccess)(await e.post(u,c),e.apiUrl(u))}De.associateRecords=RL;async function FL(e,t,r,n,i){let a=(0,it.normalizeGuid)(r,"id"),o=(0,it.normalizeGuid)(i,"targetId"),s=await(0,mr.resolveEntitySetName)(e,t),l=(0,it.assertODataName)(n,"relationshipName"),u=`/${s}(${a})/${l}(${o})/$ref`;(0,er.ensureSuccess)(await e.delete(u),e.apiUrl(u))}De.disassociateRecords=FL});var Cy=g(hr=>{"use strict";Object.defineProperty(hr,"__esModule",{value:!0});hr.deleteWebResource=hr.getWebResource=hr.updateWebResource=hr.createWebResource=void 0;var xL=Yt(),no=be(),tl=ee(),Vd=ie(),LL={html:1,css:2,js:3,xml:4,png:5,jpg:6,gif:7,xsl:9,ico:10,svg:11,resx:12};function kL(e){let t=globalThis;if(t.Buffer)return t.Buffer.from(e,"utf8").toString("base64");if(t.btoa){let r=globalThis.TextEncoder;if(r){let n=new r().encode(e),i="",a=32768;for(let o=0;o<n.length;o+=a)i+=String.fromCharCode(...n.subarray(o,o+a));return t.btoa(i)}return t.btoa(e)}throw new Vd.InvalidArgumentError("no base64 encoder available; pass contentBase64 instead of content")}function wy(e){if(e.contentBase64!==void 0)return e.contentBase64;if(e.content!==void 0)return kL(e.content)}async function Ay(e,t){return(0,xL.publishWebResourceById)(e,t)}async function ML(e,t){var r;let n=wy(t);if(n===void 0)throw new Vd.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:LL[t.type],content:n};t.description&&(i.description=t.description);let a=(0,no.ensureSuccess)(await e.post("/webresourceset",i),e.apiUrl("/webresourceset")),o=(0,no.readCreatedId)(a,"webresourceid");if(!o)throw new Vd.InvalidArgumentError(`Dataverse did not return an id for web resource '${t.name}'`);return t.publish!==!1&&await Ay(e,o),{id:o,name:t.name}}hr.createWebResource=ML;async function UL(e,t,r){let n=(0,tl.normalizeGuid)(t,"id"),i={},a=wy(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,no.ensureSuccess)(await e.patch(o,i),e.apiUrl(o)),r.publish!==!1&&await Ay(e,n)}hr.updateWebResource=UL;async function BL(e,t){var r;let i=`/webresourceset(${(0,tl.normalizeGuid)(t,"id")})${(0,tl.odataQuery)([["$select","name,displayname,webresourcetype,content,description"]])}`;return(r=(0,no.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)!==null&&r!==void 0?r:{}}hr.getWebResource=BL;async function $L(e,t){let n=`/webresourceset(${(0,tl.normalizeGuid)(t,"id")})`;(0,no.ensureSuccess)(await e.delete(n),e.apiUrl(n))}hr.deleteWebResource=$L});var rl=g(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.applyAppSettings=We.setAppSetting=We.readAppSettings=We.resolveSettingDefinitions=We.APP_SETTING_UNSET=We.APP_SETTING_OFF=We.APP_SETTING_ON=We.HEADER_AND_NAVIGATION_REFRESH=void 0;var _i=be(),Br=ee();We.HEADER_AND_NAVIGATION_REFRESH="HeaderAndNavigationRefresh";We.APP_SETTING_ON="2";We.APP_SETTING_OFF="1";We.APP_SETTING_UNSET="0";function Ny(e,t){return"/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Br.odataQuery)([["$select",e],["$filter",t]])}async function Dy(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,Br.odataLiteral)(c)}'`).join(" or "),s=`/settingdefinitions${(0,Br.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",o]])}`,u=((n=(r=(0,_i.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}We.resolveSettingDefinitions=Dy;async function qL(e,t){var r,n,i,a;let o=(0,Br.normalizeGuid)(t,"App id"),s=Ny("appsettingid,value,_settingdefinitionid_value",`_parentappmoduleid_value eq ${o}`),u=((n=(r=(0,_i.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(y=>`settingdefinitionid eq ${(0,Br.normalizeGuid)(y,"Setting definition id")}`).join(" or "),f=`/settingdefinitions${(0,Br.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",p]])}`,h=(0,_i.ensureSuccess)(await e.get(f),e.apiUrl(f));for(let y of((a=(i=h.body)===null||i===void 0?void 0:i.value)!==null&&a!==void 0?a:[]).filter(Boolean))y.settingdefinitionid&&d.set(y.settingdefinitionid.toLowerCase(),y)}return u.map(p=>{var f,h,y,w,N;let D=d.get(((f=p._settingdefinitionid_value)!==null&&f!==void 0?f:"").toLowerCase());return{id:(h=p.appsettingid)!==null&&h!==void 0?h:"",name:(w=(y=D?.uniquename)!==null&&y!==void 0?y:p._settingdefinitionid_value)!==null&&w!==void 0?w:"",value:(N=p.value)!==null&&N!==void 0?N:"",...D?.displayname?{displayName:D.displayname}:{}}})}We.readAppSettings=qL;async function Sy(e,t,r){var n,i,a;let o=Ny("appsettingid,value",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${r}`),l=((i=(n=(0,_i.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 Iy(e,t,r,n){let i=(0,Br.normalizeGuid)(t,"App id"),o=(await Dy(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,Br.normalizeGuid)(s,"Setting definition id"),u=await Sy(e,i,l);if(u)return Ey(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(y){f=y}let h;try{h=await Sy(e,i,l)}catch{h=void 0}if(h)return Ey(e,h,n);throw p&&(0,_i.ensureSuccess)(p,e.apiUrl(c)),f}We.setAppSetting=Iy;async function Ey(e,t,r){if(t.value===r)return"unchanged";let n=`/appsettings(${(0,Br.normalizeGuid)(t.id,"App setting id")})`;return(0,_i.ensureSuccess)(await e.patch(n,{value:r}),e.apiUrl(n)),"updated"}async function VL(e,t,r){var n;let i=[];for(let[a,o]of Object.entries(r??{}))try{await Iy(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}We.applyAppSettings=VL});var il=g(nl=>{"use strict";Object.defineProperty(nl,"__esModule",{value:!0});nl.HEADER_NAV_BOOLEAN_RULE=void 0;nl.HEADER_NAV_BOOLEAN_RULE="headerAndNavigationRefresh-must-be-boolean"});var Py=g(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.deleteSolution=Z.importSolution=Z.exportSolution=Z.removeSolutionComponent=Z.addSolutionComponent=Z.setSolutionVersion=Z.createSolution=Z.createPublisher=Z.getSolution=Z.fetchSolutionComponents=Z.SolutionComponentType=void 0;var _y=Kt(),tr=be(),At=ee(),zn=ie();Z.SolutionComponentType={SavedQuery:26,Workflow:29,SavedQueryVisualization:59,SystemForm:60,AppModule:80,UxAgentProject:10372};var GL=[Z.SolutionComponentType.SavedQuery,Z.SolutionComponentType.Workflow,Z.SolutionComponentType.SavedQueryVisualization,Z.SolutionComponentType.SystemForm,Z.SolutionComponentType.AppModule,Z.SolutionComponentType.UxAgentProject];async function zL(e,t){let r=(0,At.normalizeGuid)(t,"solutionId"),n=GL.map(s=>`msdyn_componenttype eq ${s}`).join(" or "),i=`/msdyn_solutioncomponentsummaries${(0,At.odataQuery)([["$select","msdyn_objectid,msdyn_componenttype,msdyn_workflowcategory,msdyn_displayname,msdyn_name"],["$filter",`msdyn_solutionid eq ${r} and (${n})`]])}`,o=(await(0,_y.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 WL(e,r,o)]}Z.fetchSolutionComponents=zL;async function WL(e,t,r){let n=new Set(r.map(s=>s.objectId.toLowerCase())),i=`/solutioncomponents${(0,At.odataQuery)([["$select","objectid,componenttype"],["$filter",`_solutionid_value eq ${t} and componenttype eq ${Z.SolutionComponentType.UxAgentProject}`]])}`,a=await(0,_y.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:Z.SolutionComponentType.UxAgentProject}))}return o}function jL(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 HL(e,t){var r,n,i,a,o,s,l,u,c,d;let p=String(t??"").trim();if(!p)throw new zn.InvalidArgumentError("getSolution: a solution unique name or id is required.");let f=jL(p)?`solutionid eq ${(0,At.normalizeGuid)(p,"solutionId")}`:`uniquename eq '${(0,At.odataLiteral)(p)}'`,h=`/solutions${(0,At.odataQuery)([["$select","solutionid,uniquename,friendlyname,version,ismanaged"],["$expand","publisherid($select=publisherid,uniquename,customizationprefix,customizationoptionvalueprefix)"],["$filter",f]])}`,N=((n=(r=(0,tr.ensureSuccess)(await e.get(h),e.apiUrl(h)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0];if(!N?.solutionid)throw new zn.InvalidArgumentError(`No solution found for '${t}'.`);let D=N.publisherid;if(!D?.publisherid)throw new zn.InvalidArgumentError(`Solution '${(i=N.uniquename)!==null&&i!==void 0?i:t}' returned no owning publisher, so its customization prefix cannot be determined; refusing to report an empty prefix that could be mistaken for "no prefix".`);if(!("customizationprefix"in D))throw new zn.InvalidArgumentError(`Solution '${(a=N.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,At.normalizeGuid)(N.solutionid,"solutionId"),uniqueName:(o=N.uniquename)!==null&&o!==void 0?o:"",friendlyName:(s=N.friendlyname)!==null&&s!==void 0?s:"",version:(l=N.version)!==null&&l!==void 0?l:"",isManaged:!!N.ismanaged,publisherId:(0,At.normalizeGuid)(D.publisherid,"publisherId"),publisherUniqueName:(u=D.uniquename)!==null&&u!==void 0?u:"",publisherPrefix:(c=D.customizationprefix)!==null&&c!==void 0?c:"",publisherOptionValuePrefix:(d=D.customizationoptionvalueprefix)!==null&&d!==void 0?d:0}}Z.getSolution=HL;async function QL(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,tr.ensureSuccess)(await e.post("/publishers",n),e.apiUrl("/publishers")),a=(0,tr.readCreatedId)(i,"publisherid");if(!a)throw new zn.InvalidArgumentError(`Dataverse did not return an id for publisher '${t.uniqueName}'`);return{id:a,uniqueName:t.uniqueName}}Z.createPublisher=QL;async function JL(e,t){var r;let n=(0,At.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,tr.ensureSuccess)(await e.post("/solutions",i),e.apiUrl("/solutions")),o=(0,tr.readCreatedId)(a,"solutionid");if(!o)throw new zn.InvalidArgumentError(`Dataverse did not return an id for solution '${t.uniqueName}'`);return{id:o,uniqueName:t.uniqueName}}Z.createSolution=JL;async function XL(e,t,r){let i=`/solutions(${(0,At.normalizeGuid)(t,"solutionId")})`;(0,tr.ensureSuccess)(await e.patch(i,{version:r}),e.apiUrl(i))}Z.setSolutionVersion=XL;async function KL(e,t){var r;let i={ComponentId:(0,At.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,tr.ensureSuccess)(await e.post("/AddSolutionComponent",i),e.apiUrl("/AddSolutionComponent"))}Z.addSolutionComponent=KL;async function YL(e,t,r,n){let a={SolutionComponent:{"@odata.type":"Microsoft.Dynamics.CRM.solutioncomponent",solutioncomponentid:(0,At.normalizeGuid)(t,"componentId")},ComponentType:r,SolutionUniqueName:n};(0,tr.ensureSuccess)(await e.post("/RemoveSolutionComponent",a),e.apiUrl("/RemoveSolutionComponent"))}Z.removeSolutionComponent=YL;async function ZL(e,t){var r,n;let i={SolutionName:t.solutionName,Managed:(r=t.managed)!==null&&r!==void 0?r:!1},o=(n=(0,tr.ensureSuccess)(await e.post("/ExportSolution",i),e.apiUrl("/ExportSolution")).body)===null||n===void 0?void 0:n.ExportSolutionFile;if(!o)throw new zn.InvalidArgumentError(`ExportSolution returned no file for '${t.solutionName}'`);return{base64:o}}Z.exportSolution=ZL;async function ek(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,At.normalizeGuid)(t.importJobId,"importJobId")),(0,tr.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution"))}Z.importSolution=ek;async function tk(e,t){let n=`/solutions(${(0,At.normalizeGuid)(t,"solutionId")})`;(0,tr.ensureSuccess)(await e.delete(n),e.apiUrl(n))}Z.deleteSolution=tk});var sl=g(gn=>{"use strict";Object.defineProperty(gn,"__esModule",{value:!0});gn.appApi=gn.deleteAppResolvingOnce=gn.unpublishedAppModulesQuery=void 0;var Qd=Kt(),rk=Xd(),Ty=Yt(),nk=rl(),Ae=be(),ae=ee(),Hd=bt(),ik=Fd(),he=ie(),ak=(0,ae.odataQuery)([["$select","appmoduleid,name,uniquename,description"]]),Gd="appmoduleid,name,uniquename,description";function My(e,t,r){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,ae.odataQuery)([["$select",e],["$filter",t],["$top",r]])}gn.unpublishedAppModulesQuery=My;function zd(e,t){return My(e,t?`appmoduleid eq ${t}`:void 0,t?1:void 0)}function ol(e,t){return"/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,ae.odataQuery)([["$select",t],["$filter",`sitemapid eq ${e}`],["$top",1]])}function Pi(e){var t;let r=(t=e.body)===null||t===void 0?void 0:t.value;if(Array.isArray(r))return r[0]}function al(e){let t=e?.["@odata.etag"];return typeof t=="string"?t:null}function io(e){let t=new Set,r=[];for(let n of e??[])n&&!t.has(n)&&(t.add(n),r.push(n));return r}function ok(e){return`cdsapp_${(e||"").replace(/[^a-zA-Z0-9]/g,"")||"app"}`}async function Uy(e,t){var r,n;let i=u=>{throw new he.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 sk(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 Jd(e){return e instanceof Error?e.message:String(e)}async function lk(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,Ae.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,Ae.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 (${Jd(a)}); it will not be visible or playable until a role is granted access to it.`}}async function uk(e,t){let r=[];async function n(s,l,u){try{return(await(0,Qd.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}' (${Jd(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 Oy=new WeakMap;async function ck(e,t){let r=Oy.get(e);r||(r=new Map,Oy.set(e,r));let n=r.get(t);if(n!==void 0)return n;let i=await dk(e,t);return i&&r.set(t,i),i}async function Ry(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 dk(e,t){let r=`/EntityDefinitions(LogicalName='${(0,ae.odataLiteral)(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 Fy(e,t){let r=[],n=io(t.entities),i=4,a=await Ry(n,i,f=>ck(e,f)),o=n.filter((f,h)=>!a[h]);if(o.length>0)throw new he.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 io(t.components.forms))r.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:f});for(let f of io(t.components.views))r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:f});for(let f of io(t.components.charts))r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:f});for(let f of io(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 Ry(n,i,f=>uk(e,f)),p=d.flatMap(f=>f.warnings);for(let f of d){for(let h of f.forms)l.has(h)||(l.add(h),r.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:h}));for(let h of f.views)u.has(h)||(u.add(h),r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:h}));for(let h of f.charts)c.has(h)||(c.add(h),r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:h}))}return{components:r,tables:s,warnings:p}}async function xy(e,t,r){if(r.length===0)return;let n="/AddAppComponents";(0,Ae.ensureSuccess)(await e.post(n,{AppId:t,Components:r}),e.apiUrl(n))}function pk(e){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,ae.odataQuery)([["$select","appmoduleid,appmoduleidunique"],["$filter",`appmoduleid eq ${e}`],["$top",1]])}async function Ly(e,t,r){var n;if(r.length===0)return;let i=pk(t),a=await e.get(i);if(a.status<200||a.status>=300)throw new he.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=Pi(a),s=o?.appmoduleidunique;if(typeof s!="string"||!s)throw new he.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 he.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 he.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 he.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 fk(e,t,r){let n=`/appmodules(${t})`,i=`/sitemaps(${r.sitemapId})`;try{if(!await mk(e,r.sitemapId)){r.serverRefusedSitemap&&(0,Ae.ensureSuccess)(await e.delete(n),e.apiUrl(n));return}e.supportsAtomicBatch&&await $y(e,[{path:n,etag:r.appEtag},{path:i,etag:r.sitemapEtag}])}catch{}}async function mk(e,t){var r;let n=ol(t,"sitemapid"),i=await e.get(n);if(i.status<200||i.status>=300)throw new he.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned HTTP ${i.status}, so it cannot be determined whether the row exists.`);let a=(r=i.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a))throw new he.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 a.length>0}async function By(e,t){var r;let n=(0,ae.normalizeGuid)(t,"id"),i=h=>{throw new he.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})${ak}`,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 Uy(e,s);if(!l)return{uniquename:s,appEtag:(0,Ae.readEtag)(o)};let u=(0,ae.normalizeGuid)(l,"sitemapId"),c=ol(u,"sitemapid,sitemapnameunique,sitemapxml"),d;try{d=await e.get(c)}catch(h){return i(`reading sitemap '${u}' failed (${h.message}).`)}if(d.status<200||d.status>=300)return i(`reading sitemap '${u}' returned HTTP ${d.status}.`);let p=Pi(d);if(!p)return i(`sitemap '${u}' was not returned by the unpublished-aware read.`);if(p.sitemapnameunique!==s)return i(`sitemap '${u}' now carries sitemapnameunique '${String(p.sitemapnameunique)}', not '${s}', so it is no longer this app's sitemap.`);let f=p.sitemapxml;return typeof f!="string"?i(`sitemap '${u}' returned no sitemapxml.`):{sitemapId:u,uniquename:s,sitemapXml:f,appEtag:(0,Ae.readEtag)(o),sitemapEtag:al(p)}}async function hk(e,t,r){let n=(0,ae.normalizeGuid)(t,"id"),i=await By(e,n);await r?.(i.sitemapXml),await qy(e,n,i)}gn.deleteAppResolvingOnce=hk;async function $y(e,t){let r=`batch_${(0,Hd.newId)()}`,n=`changeset_${(0,Hd.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,we.ensureSuccess)(o,s);let l=`app '${t[0].path}'`;if(typeof o.body!="string"||o.body.length===0)throw new me.ConnectionError(s,o.status,`atomic delete of ${l} cannot be confirmed: the $batch response had no readable body, so the change set's outcome is unknown`);let u=(0,VL.parseChangeSetStatuses)(o.body,i.map((d,p)=>String(p+1)));if(u===void 0)throw new me.ConnectionError(s,o.status,`atomic delete of ${l} cannot be confirmed: the $batch response could not be parsed as a change set, so the outcome is unknown`);let c=u.find(d=>d<200||d>=300);if(c!==void 0)throw new me.ConnectionError(s,c,`atomic delete of ${l} was rolled back: the change set reported HTTP ${c}`);if(u.length!==i.length)throw new me.ConnectionError(s,o.status,`atomic delete of ${l} cannot be confirmed: the $batch response reported ${u.length} operation result(s), expected exactly ${i.length}`)}async function Vd(e,t){try{let r=il(t,"sitemapid"),n=await e.get(r);return n.status<200||n.status>=300?null:nl(_i(n))}catch{return null}}function ek(e){return e>=400&&e<500&&e!==408&&e!==429}function Gd(e,t,r){if(!e)throw new me.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to delete app '${t}': the ${r} read returned no ETag, so the delete cannot be made conditional on the row that was actually inspected. Without that condition a row renamed or re-pointed between the read and the delete would be destroyed. Retry.`);return e}async function xy(e,t,r){let n=`/appmodules(${t})`;if(!r.sitemapId){await tk(e,n,Gd(r.appEtag,t,"app"));return}if(!e.supportsAtomicBatch)throw new me.SdkError("APP_DELETE_NOT_ATOMIC",`Refusing to delete app '${t}': it owns a sitemap, and the injected HttpClient cannot send a raw body, so the two rows would have to be deleted as separate requests. A failure between them strands the sitemap and permanently reserves the app's unique name. Implement HttpClient.postRaw so the SDK can delete them atomically.`);await Fy(e,[{path:n,etag:Gd(r.appEtag,t,"app")},{path:`/sitemaps(${r.sitemapId})`,etag:Gd(r.sitemapEtag,t,"sitemap")}])}async function tk(e,t,r){(0,we.ensureSuccess)(await e.delete(t,{headers:{"If-Match":r}}),e.apiUrl(t))}async function Py(e,t){if(!/GenPageId/i.test(t))return;let r;try{r=[...new Set((0,$L.collectGenPageIds)(t))]}catch(o){throw new me.SdkError("SITEMAP_TARGET_UNVERIFIABLE",`Refusing to push the app: its sitemap xml could not be parsed, so the generative pages it navigates to cannot be verified (${jd(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,Wd.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 me.SdkError("SITEMAP_TARGET_NOT_FOUND",`Refusing to push the app: its sitemap navigates to generative page(s) ${a.map(o=>`'${o}'`).join(", ")} that do not exist in this environment. Push the page before the app that links to it.`)}function rk(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")}gn.appApi={async get(e,t){var r;let n=(0,ae.normalizeGuid)(t,"id"),i=qd($d,n),a=(0,we.ensureSuccess)(await e.get(i),e.apiUrl(i)),o=(r=_i(a))!==null&&r!==void 0?r:{};if(!o.appmoduleid)throw new me.SdkError("APP_NOT_FOUND",`App '${n}' was not found (checked the unpublished-aware projection, which includes drafts).`);let s=await Oy(e,o.uniquename),l=s?(0,ae.normalizeGuid)(s,"sitemapId"):void 0,u=null;if(l){let d=il(l,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"),p=(0,we.ensureSuccess)(await e.get(d),e.apiUrl(d)),m=_i(p);if(m&&m.sitemapnameunique!==o.uniquename)throw new me.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${n}': sitemap '${l}' now carries sitemapnameunique '${String(m.sitemapnameunique)}', not '${String(o.uniquename)}', so it is no longer this app's sitemap. Retry.`);o.$sitemap=m??{},u=nl(m)}let c=nl(o);return{raw:o,etag:u,...o.appmoduleid?{siblingEtags:{[(0,ae.normalizeGuid)(o.appmoduleid,"appmoduleid")]:c}}:{}}},async list(e,t){let r=qd($d);return(await(0,Wd.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 Py(e,n.sitemapxml);let i=n.iconWebResourceId?void 0:await WL(e),a=n.iconWebResourceId||i?.id;if(!a)throw new me.SdkError("APP_ICON_UNRESOLVED",`Cannot create app '${n.appModuleName}': its icon (\`appmodule.webresourceid\`) is a REQUIRED attribute and this environment has no image web resource to use. Pass \`iconWebResourceId\` explicitly, or add an image (PNG/JPG/GIF/ICO/SVG) web resource to the environment.`);let o=null;i?.managed&&(o=`No unmanaged image web resource was available, so the app icon resolved to a MANAGED one (${i.id}). That creates a cross-solution dependency which can fail to import into an environment without the owning managed solution. Pass \`iconWebResourceId\` with an in-solution image to avoid it.`);let s=n.appModuleUniqueName||zL(n.appModuleId),l={name:n.appModuleName,uniquename:s,clienttype:4,formfactor:1,navigationtype:0};n.appModuleDescription&&(l.description=n.appModuleDescription),a&&(l.webresourceid=a);let u="/appmodules",c=(0,we.ensureSuccess)(await e.post(u,(0,we.withClientMintedId)(l,"appmoduleid",r)),e.apiUrl(u)),d=(0,we.resolveCreatedId)(c,"appmoduleid","app module",r),p=null,m=[];o&&m.push(o);let h={kind:"notRequested"},w=(0,zd.newId)(),b=!1;try{let D="/sitemaps",F=await e.post(D,{sitemapid:w,sitemapnameunique:s,sitemapname:n.sitemapname,sitemapxml:n.sitemapxml});b=ek(F.status);let x=(0,we.ensureSuccess)(F,e.apiUrl(D));p=(0,we.readEtag)(x),p||(p=await Vd(e,w));let q=await Dy(e,n);m.push(...q.warnings);let G=q.components;G.unshift({"@odata.type":"Microsoft.Dynamics.CRM.sitemap",sitemapid:w}),await Iy(e,d,G),await _y(e,d,q.tables);let M=await jL(e,d);M&&m.push(M),n.appSettings&&Object.keys(n.appSettings).length>0&&m.push(...await(0,qL.applyAppSettings)(e,d,n.appSettings)),n.published!==!1&&(await(0,Sy.publishAppModule)(e,d),h={kind:"submitted"})}catch(D){throw await KL(e,d,{sitemapId:w,serverRefusedSitemap:b,appEtag:(0,we.readEtag)(c),sitemapEtag:p}),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,we.readEtag)(D))}catch{}return{id:d,etag:p,serverIdentity:{sitemapId:w},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;let m=r,h=(0,ae.normalizeGuid)(t,"id");if(await Py(e,m.sitemapxml),!m.sitemapId)throw new me.ValidationError("app",h,"/sitemapId","missing sitemap identity \u2014 re-fetch the app before pushing edits");let w=(0,ae.normalizeGuid)(m.sitemapId,"sitemapId");if(!n)throw new me.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${h}': 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 b=await Dy(e,m),E=`/appmodules(${h})`,D=(o=a?.[h])!==null&&o!==void 0?o:null,F=!0,x=!1;try{let ve=qd($d,h),Ve=await e.get(ve);if(Ve.status>=200&&Ve.status<300){let Ke=(s=_i(Ve))!==null&&s!==void 0?s:{};x=!0,F=String((l=Ke.name)!==null&&l!==void 0?l:"")!==String((u=m.appModuleName)!==null&&u!==void 0?u:"")||String((c=Ke.description)!==null&&c!==void 0?c:"")!==String((d=m.appModuleDescription)!==null&&d!==void 0?d:"")}}catch{}let q=D;if(F){let ve=x?D:null,Ve=ve?(0,we.echoWrite)("appmoduleid",{"If-Match":ve}):{query:"",options:void 0},Ke=await e.patch(`${E}${Ve.query}`,{name:m.appModuleName,description:m.appModuleDescription},Ve.options);if(rk(Ke))throw new me.SdkError("APP_DRAFT_HEADER_NOT_WRITABLE",`Refusing to update app '${h}': 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,we.ensureSuccess)(Ke,e.apiUrl(E)),q=(0,we.readEtag)(Ke)}let G={"If-Match":n},M=`/sitemaps(${w})`,U;try{U=(0,we.ensureSuccess)(await e.patch(M,{sitemapxml:m.sitemapxml,sitemapname:m.sitemapname},G?{headers:G}:void 0),e.apiUrl(M))}catch(ve){throw(0,me.withPartialTokens)(ve,{siblingEtags:{[h]:q}})}let B=[...b.warnings];try{await Iy(e,h,b.components),await _y(e,h,b.tables)}catch(ve){B.push(`App '${h}': one or more components were not pinned (${ve.message}). Navigation may reference content not included in the app; re-push to retry.`)}let W={kind:"notRequested"},$=q,Se=(0,we.readEtag)(U);if(m.published===!0){try{await(0,Sy.publishAppModule)(e,h),W={kind:"submitted"}}catch(ve){W={kind:"failed",error:ve},B.push(`App '${h}': saved, but publishing failed (${ve.message}). The app remains unpublished; re-push to retry.`)}if(W.kind==="submitted"){$=null;try{let ve=await e.get(`/appmodules(${h})?$select=appmoduleid`);ve.status>=200&&ve.status<300&&($=(0,we.readEtag)(ve)),Se=(p=await Vd(e,w))!==null&&p!==void 0?p:Se}catch{}}}return{id:h,etag:Se??await Vd(e,w),siblingEtags:{[h]:$},publish:W,...B.length>0?{warnings:B}:{}}},async delete(e,t){let r=(0,ae.normalizeGuid)(t,"id");await xy(e,r,await Ry(e,r))}}});var io=g(Pi=>{"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 Jd(e,t){return t===void 0&&(t=Object),t&&typeof t.freeze=="function"?t.freeze(e):e}function ik(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 Ly=Jd({HTML:"text/html",isHTML:function(e){return e===Ly.HTML},XML_APPLICATION:"application/xml",XML_TEXT:"text/xml",XML_XHTML_APPLICATION:"application/xhtml+xml",XML_SVG_IMAGE:"image/svg+xml"}),ky=Jd({HTML:"http://www.w3.org/1999/xhtml",isHTML:function(e){return e===ky.HTML},SVG:"http://www.w3.org/2000/svg",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"});Pi.assign=ik;Pi.find=nk;Pi.freeze=Jd;Pi.MIME_TYPE=Ly;Pi.NAMESPACE=ky});var op=g(Gr=>{var zy=io(),hr=zy.find,ao=zy.NAMESPACE;function ak(e){return e!==""}function ok(e){return e?e.split(/[\t\n\f\r ]+/).filter(ak):[]}function sk(e,t){return e.hasOwnProperty(t)||(e[t]=!0),e}function My(e){if(!e)return[];var t=ok(e);return Object.keys(t.reduce(sk,{}))}function lk(e){return function(t){return e&&e.indexOf(t)!==-1}}function so(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function Ct(e,t){var r=e.prototype;if(!(r instanceof t)){let i=function(){};var n=i;i.prototype=t.prototype,i=new i,so(r,i),e.prototype=r=i}r.constructor!=e&&(typeof e!="function"&&console.error("unknown Class:"+e),r.constructor=e)}var St={},Mt=St.ELEMENT_NODE=1,Oi=St.ATTRIBUTE_NODE=2,sl=St.TEXT_NODE=3,Wy=St.CDATA_SECTION_NODE=4,jy=St.ENTITY_REFERENCE_NODE=5,uk=St.ENTITY_NODE=6,Qd=St.PROCESSING_INSTRUCTION_NODE=7,Xd=St.COMMENT_NODE=8,Hy=St.DOCUMENT_NODE=9,Jy=St.DOCUMENT_TYPE_NODE=10,$r=St.DOCUMENT_FRAGMENT_NODE=11,ck=St.NOTATION_NODE=12,at={},je={},aj=at.INDEX_SIZE_ERR=(je[1]="Index size error",1),oj=at.DOMSTRING_SIZE_ERR=(je[2]="DOMString size error",2),At=at.HIERARCHY_REQUEST_ERR=(je[3]="Hierarchy request error",3),sj=at.WRONG_DOCUMENT_ERR=(je[4]="Wrong document",4),dk=at.INVALID_CHARACTER_ERR=(je[5]="Invalid character",5),lj=at.NO_DATA_ALLOWED_ERR=(je[6]="No data allowed",6),uj=at.NO_MODIFICATION_ALLOWED_ERR=(je[7]="No modification allowed",7),Qy=at.NOT_FOUND_ERR=(je[8]="Not found",8),cj=at.NOT_SUPPORTED_ERR=(je[9]="Not supported",9),Uy=at.INUSE_ATTRIBUTE_ERR=(je[10]="Attribute in use",10),Ti=at.INVALID_STATE_ERR=(je[11]="Invalid state",11),dj=at.SYNTAX_ERR=(je[12]="Syntax error",12),pj=at.INVALID_MODIFICATION_ERR=(je[13]="Invalid modification",13),fj=at.NAMESPACE_ERR=(je[14]="Invalid namespace",14),mj=at.INVALID_ACCESS_ERR=(je[15]="Invalid access",15);function ue(e,t){if(t instanceof Error)var r=t;else r=this,Error.call(this,je[e]),this.message=je[e],Error.captureStackTrace&&Error.captureStackTrace(this,ue);return r.code=e,t&&(this.message=this.message+": "+t),r}ue.prototype=Error.prototype;so(at,ue);function qr(){}qr.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++)ap(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 Ri(e,t){this._node=e,this._refresh=t,Kd(this)}function Kd(e){var t=e._node._inc||e._node.ownerDocument._inc;if(e._inc!==t){var r=e._refresh(e._node);if(sb(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];so(r,e),e._inc=t}}Ri.prototype.item=function(e){return Kd(this),this[e]||null};Ct(Ri,qr);function ll(){}function Xy(e,t){for(var r=e.length;r--;)if(e[r]===t)return r}function By(e,t,r,n){if(n?t[Xy(t,n)]=r:t[t.length++]=r,e){r.ownerElement=e;var i=e.ownerDocument;i&&(n&&Zy(i,e,n),pk(i,e,r))}}function $y(e,t,r){var n=Xy(t,r);if(n>=0){for(var i=t.length-1;n<i;)t[n]=t[++n];if(t.length=i,e){var a=e.ownerDocument;a&&(Zy(a,e,r),r.ownerElement=null)}}else throw new ue(Qy,new Error(e.tagName+"@"+r))}ll.prototype={length:0,item:qr.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 ue(Uy);var r=this.getNamedItem(e.nodeName);return By(this._ownerElement,this,e,r),r},setNamedItemNS:function(e){var t=e.ownerElement,r;if(t&&t!=this._ownerElement)throw new ue(Uy);return r=this.getNamedItemNS(e.namespaceURI,e.localName),By(this._ownerElement,this,e,r),r},removeNamedItem:function(e){var t=this.getNamedItem(e);return $y(this._ownerElement,this,t),t},removeNamedItemNS:function(e,t){var r=this.getNamedItemNS(e,t);return $y(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 Ky(){}Ky.prototype={hasFeature:function(e,t){return!0},createDocument:function(e,t,r){var n=new lo;if(n.implementation=this,n.childNodes=new qr,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 pl;return n.name=e,n.nodeName=e,n.publicId=t||"",n.systemId=r||"",n}};function oe(){}oe.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 cl(this,e,t)},replaceChild:function(e,t){cl(this,e,t,tb),t&&this.removeChild(t)},removeChild:function(e){return eb(this,e)},appendChild:function(e){return this.insertBefore(e,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(e){return ob(this.ownerDocument||this,this,e)},normalize:function(){We(this,null,{enter:function(e){for(var t=e.firstChild;t;){var r=t.nextSibling;r!==null&&r.nodeType===sl&&t.nodeType===sl?(e.removeChild(r),t.appendData(r.data)):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==Oi?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==Oi?t.ownerDocument:t.parentNode}return null},isDefaultNamespace:function(e){var t=this.lookupPrefix(e);return t==null}};function Yy(e){return e=="<"&&"<"||e==">"&&">"||e=="&"&&"&"||e=='"'&&"""||"&#"+e.charCodeAt()+";"}so(St,oe);so(St,oe.prototype);function ul(e,t){return We(e,null,{enter:function(r){return t(r)?We.STOP:!0}})===We.STOP}function We(e,t,r){for(var n=[{node:e,context:t,phase:We.ENTER}];n.length>0;){var i=n.pop();if(i.phase===We.ENTER){var a=r.enter(i.node,i.context);if(a===We.STOP)return We.STOP;if(n.push({node:i.node,context:a,phase:We.EXIT}),a==null)continue;for(var o=i.node.lastChild;o;)n.push({node:o,context:a,phase:We.ENTER}),o=o.previousSibling}else r.exit&&r.exit(i.node,i.context)}}We.STOP=Symbol("walkDOM.STOP");We.ENTER=0;We.EXIT=1;function lo(){this.ownerDocument=this}function pk(e,t,r){e&&e._inc++;var n=r.namespaceURI;n===ao.XMLNS&&(t._nsMap[r.prefix?r.localName:""]=r.value)}function Zy(e,t,r,n){e&&e._inc++;var i=r.namespaceURI;i===ao.XMLNS&&delete t._nsMap[r.prefix?r.localName:""]}function Yd(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 eb(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,Yd(e.ownerDocument,e),t}function fk(e){return e&&(e.nodeType===oe.DOCUMENT_NODE||e.nodeType===oe.DOCUMENT_FRAGMENT_NODE||e.nodeType===oe.ELEMENT_NODE)}function mk(e){return e&&(gr(e)||Zd(e)||Vr(e)||e.nodeType===oe.DOCUMENT_FRAGMENT_NODE||e.nodeType===oe.COMMENT_NODE||e.nodeType===oe.PROCESSING_INSTRUCTION_NODE)}function Vr(e){return e&&e.nodeType===oe.DOCUMENT_TYPE_NODE}function gr(e){return e&&e.nodeType===oe.ELEMENT_NODE}function Zd(e){return e&&e.nodeType===oe.TEXT_NODE}function qy(e,t){var r=e.childNodes||[];if(hr(r,gr)||Vr(t))return!1;var n=hr(r,Vr);return!(t&&n&&r.indexOf(n)>r.indexOf(t))}function Vy(e,t){var r=e.childNodes||[];function n(a){return gr(a)&&a!==t}if(hr(r,n))return!1;var i=hr(r,Vr);return!(t&&i&&r.indexOf(i)>r.indexOf(t))}function hk(e,t,r){if(!fk(e))throw new ue(At,"Unexpected parent node type "+e.nodeType);if(r&&r.parentNode!==e)throw new ue(Qy,"child not in parent");if(!mk(t)||Vr(t)&&e.nodeType!==oe.DOCUMENT_NODE)throw new ue(At,"Unexpected node type "+t.nodeType+" for parent node type "+e.nodeType)}function gk(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===oe.DOCUMENT_FRAGMENT_NODE){var a=i.filter(gr);if(a.length>1||hr(i,Zd))throw new ue(At,"More than one element or text in fragment");if(a.length===1&&!qy(e,r))throw new ue(At,"Element in fragment can not be inserted before doctype")}if(gr(t)&&!qy(e,r))throw new ue(At,"Only one element can be added and only after doctype");if(Vr(t)){if(hr(n,Vr))throw new ue(At,"Only one doctype is allowed");var o=hr(n,gr);if(r&&n.indexOf(o)<n.indexOf(r))throw new ue(At,"Doctype can only be inserted before an element");if(!r&&o)throw new ue(At,"Doctype can not be appended since element is present")}}function tb(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===oe.DOCUMENT_FRAGMENT_NODE){var a=i.filter(gr);if(a.length>1||hr(i,Zd))throw new ue(At,"More than one element or text in fragment");if(a.length===1&&!Vy(e,r))throw new ue(At,"Element in fragment can not be inserted before doctype")}if(gr(t)&&!Vy(e,r))throw new ue(At,"Only one element can be added and only after doctype");if(Vr(t)){let l=function(u){return Vr(u)&&u!==r};var s=l;if(hr(n,l))throw new ue(At,"Only one doctype is allowed");var o=hr(n,gr);if(r&&n.indexOf(o)<n.indexOf(r))throw new ue(At,"Doctype can only be inserted before an element")}}function cl(e,t,r,n){hk(e,t,r),e.nodeType===oe.DOCUMENT_NODE&&(n||gk)(e,t,r);var i=t.parentNode;if(i&&i.removeChild(t),t.nodeType===$r){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;oo(a,l)}while(a!==o&&(a=a.nextSibling));return Yd(e.ownerDocument||e,e),t.nodeType==$r&&(t.firstChild=t.lastChild=null),t}function oo(e,t){if(e.ownerDocument!==t){if(e.ownerDocument=t,e.nodeType===Mt&&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;)oo(i,t),i=i.nextSibling}}function vk(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,Yd(e.ownerDocument,e,t);var r=e.ownerDocument||e;return oo(t,r),t}lo.prototype={nodeName:"#document",nodeType:Hy,doctype:null,documentElement:null,_inc:1,insertBefore:function(e,t){if(e.nodeType==$r){for(var r=e.firstChild;r;){var n=r.nextSibling;this.insertBefore(r,t),r=n}return e}return cl(this,e,t),oo(e,this),this.documentElement===null&&e.nodeType===Mt&&(this.documentElement=e),e},removeChild:function(e){return this.documentElement==e&&(this.documentElement=null),eb(this,e)},replaceChild:function(e,t){cl(this,e,t,tb),oo(e,this),t&&this.removeChild(t),gr(e)&&(this.documentElement=e)},importNode:function(e,t){return yk(this,e,t)},getElementById:function(e){var t=null;return ul(this.documentElement,function(r){if(r.nodeType==Mt&&r.getAttribute("id")==e)return t=r,!0}),t},getElementsByClassName:function(e){var t=My(e);return new Ri(this,function(r){var n=[];return t.length>0&&ul(r.documentElement,function(i){if(i!==r&&i.nodeType===Mt){var a=i.getAttribute("class");if(a){var o=e===a;if(!o){var s=My(a);o=t.every(lk(s))}o&&n.push(i)}}}),n})},createElement:function(e){var t=new Wn;t.ownerDocument=this,t.nodeName=e,t.tagName=e,t.localName=e,t.childNodes=new qr;var r=t.attributes=new ll;return r._ownerElement=t,t},createDocumentFragment:function(){var e=new fl;return e.ownerDocument=this,e.childNodes=new qr,e},createTextNode:function(e){var t=new ep;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 ue(dk,'data contains "]]>"');var t=new rp;return t.ownerDocument=this,t.appendData(e),t},createProcessingInstruction:function(e,t){var r=new ip;return r.ownerDocument=this,r.tagName=r.nodeName=r.target=e,r.nodeValue=r.data=t,r},createAttribute:function(e){var t=new dl;return t.ownerDocument=this,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},createEntityReference:function(e){var t=new np;return t.ownerDocument=this,t.nodeName=e,t},createElementNS:function(e,t){var r=new Wn,n=t.split(":"),i=r.attributes=new ll;return r.childNodes=new qr,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 dl,n=t.split(":");return r.ownerDocument=this,r.nodeName=t,r.name=t,r.namespaceURI=e,r.specified=!0,n.length==2?(r.prefix=n[0],r.localName=n[1]):r.localName=t,r}};Ct(lo,oe);function Wn(){this._nsMap={}}Wn.prototype={nodeType:Mt,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===$r?this.insertBefore(e,null):vk(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 Ri(this,function(t){var r=[];return ul(t,function(n){n!==t&&n.nodeType==Mt&&(e==="*"||n.tagName==e)&&r.push(n)}),r})},getElementsByTagNameNS:function(e,t){return new Ri(this,function(r){var n=[];return ul(r,function(i){i!==r&&i.nodeType===Mt&&(e==="*"||i.namespaceURI===e)&&(t==="*"||i.localName==t)&&n.push(i)}),n})}};lo.prototype.getElementsByTagName=Wn.prototype.getElementsByTagName;lo.prototype.getElementsByTagNameNS=Wn.prototype.getElementsByTagNameNS;Ct(Wn,oe);function dl(){}dl.prototype.nodeType=Oi;Ct(dl,oe);function uo(){}uo.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(je[At])},deleteData:function(e,t){this.replaceData(e,t,"")},replaceData:function(e,t,r){var n=this.data.substring(0,e),i=this.data.substring(e+t);r=n+r+i,this.nodeValue=this.data=r,this.length=r.length}};Ct(uo,oe);function ep(){}ep.prototype={nodeName:"#text",nodeType:sl,splitText:function(e){var t=this.data,r=t.substring(e);t=t.substring(0,e),this.data=this.nodeValue=t,this.length=t.length;var n=this.ownerDocument.createTextNode(r);return this.parentNode&&this.parentNode.insertBefore(n,this.nextSibling),n}};Ct(ep,uo);function tp(){}tp.prototype={nodeName:"#comment",nodeType:Xd};Ct(tp,uo);function rp(){}rp.prototype={nodeName:"#cdata-section",nodeType:Wy};Ct(rp,uo);function pl(){}pl.prototype.nodeType=Jy;Ct(pl,oe);function rb(){}rb.prototype.nodeType=ck;Ct(rb,oe);function nb(){}nb.prototype.nodeType=uk;Ct(nb,oe);function np(){}np.prototype.nodeType=jy;Ct(np,oe);function fl(){}fl.prototype.nodeName="#document-fragment";fl.prototype.nodeType=$r;Ct(fl,oe);function ip(){}ip.prototype.nodeType=Qd;Ct(ip,oe);function ib(){}ib.prototype.serializeToString=function(e,t,r,n){return ab.call(e,t,r,n)};oe.prototype.toString=ab;function ab(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 ap(this,i,e,t,l,n),i.join("")}function Gy(e,t,r){var n=e.prefix||"",i=e.namespaceURI;if(!i||n==="xml"&&i===ao.XML||i===ao.XMLNS)return!1;for(var a=r.length;a--;){var o=r[a];if(o.prefix===n)return o.namespace!==i}return!0}function ol(e,t,r){e.push(" ",t,'="',r.replace(/[<>&"\t\n\r]/g,Yy),'"')}function ap(e,t,r,n,i,a){i||(i=[]),We(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 Mt:var c=o.attributes,d=c.length,p=o.tagName;u=ao.isHTML(o.namespaceURI)||u;var m=p;if(!u&&!o.prefix&&o.namespaceURI){for(var h,w=0;w<c.length;w++)if(c.item(w).name==="xmlns"){h=c.item(w).value;break}if(!h)for(var b=l.length-1;b>=0;b--){var E=l[b];if(E.prefix===""&&E.namespace===o.namespaceURI){h=E.namespace;break}}if(h!==o.namespaceURI)for(var b=l.length-1;b>=0;b--){var E=l[b];if(E.namespace===o.namespaceURI){E.prefix&&(m=E.prefix+":"+p);break}}}t.push("<",m);for(var D=l.slice(),F=0;F<d;F++){var x=c.item(F);x.prefix=="xmlns"?D.push({prefix:x.localName,namespace:x.value}):x.nodeName=="xmlns"&&D.push({prefix:"",namespace:x.value})}for(var F=0;F<d;F++){var x=c.item(F);if(Gy(x,u,D)){var q=x.prefix||"",G=x.namespaceURI;ol(t,q?"xmlns:"+q:"xmlns",G),D.push({prefix:q,namespace:G})}var M=n?n(x):x;M&&(typeof M=="string"?t.push(M):ol(t,M.name,M.value))}if(p===m&&Gy(o,u,D)){var U=o.prefix||"",G=o.namespaceURI;ol(t,U?"xmlns:"+U:"xmlns",G),D.push({prefix:U,namespace:G})}var B=o.firstChild;if(B||u&&!/^(?:meta|link|img|br|hr|input)$/i.test(p)){if(t.push(">"),u&&/^script$/i.test(p)){for(;B;)B.data?t.push(B.data):ap(B,t,u,n,D.slice(),a),B=B.nextSibling;return t.push("</",p,">"),null}return{ns:D,isHTML:u,tag:m}}else return t.push("/>"),null;case Hy:case $r:return{ns:l.slice(),isHTML:u,tag:null};case Oi:return ol(t,o.name,o.value),null;case sl:return t.push(o.data.replace(/[<&>]/g,Yy)),null;case Wy:if(a&&o.data.indexOf("]]>")!==-1)throw new ue(Ti,'The CDATASection data contains "]]>"');return t.push("<![CDATA[",o.data.replace(/]]>/g,"]]]]><![CDATA[>"),"]]>"),null;case Xd:if(a&&o.data.indexOf("-->")!==-1)throw new ue(Ti,'The comment node data contains "-->"');return t.push("<!--",o.data,"-->"),null;case Jy:if(a){if(o.publicId&&!/^("[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%']*"|'[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%'"]*')$/.test(o.publicId))throw new ue(Ti,"DocumentType publicId is not a valid PubidLiteral");if(o.systemId&&!/^("[^"]*"|'[^']*')$/.test(o.systemId))throw new ue(Ti,"DocumentType systemId is not a valid SystemLiteral");if(o.internalSubset&&o.internalSubset.indexOf("]>")!==-1)throw new ue(Ti,'DocumentType internalSubset contains "]>"')}var W=o.publicId,$=o.systemId;if(t.push("<!DOCTYPE ",o.name),W)t.push(" PUBLIC ",W),$&&$!="."&&t.push(" ",$),t.push(">");else if($&&$!=".")t.push(" SYSTEM ",$,">");else{var Se=o.internalSubset;Se&&t.push(" [",Se,"]"),t.push(">")}return null;case Qd:if(a&&o.data.indexOf("?>")!==-1)throw new ue(Ti,'The ProcessingInstruction data contains "?>"');return t.push("<?",o.target," ",o.data,"?>"),null;case jy: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 yk(e,t,r){var n;return We(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===Oi||r;return s?o:null}}),n}function ob(e,t,r){var n;return We(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 qr),o.ownerDocument=e;var u=r;switch(o.nodeType){case Mt:var c=i.attributes,d=o.attributes=new ll,p=c.length;d._ownerElement=o;for(var m=0;m<p;m++)o.setAttributeNode(ob(e,c.item(m),!0));break;case Oi:u=!0}return a!==null?a.appendChild(o):n=o,u?o:null}}),n}function sb(e,t,r){e[t]=r}try{Object.defineProperty&&(Object.defineProperty(Ri.prototype,"length",{get:function(){return Kd(this),this.$$length}}),Object.defineProperty(oe.prototype,"textContent",{get:function(){if(this.nodeType===Mt||this.nodeType===$r){var e=[];return We(this,null,{enter:function(t){if(t.nodeType===Mt||t.nodeType===$r)return!0;if(t.nodeType===Qd||t.nodeType===Xd)return null;e.push(t.nodeValue)}}),e.join("")}return this.nodeValue},set:function(e){switch(this.nodeType){case Mt:case $r: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}}}),sb=function(e,t,r){e["$$"+t]=r})}catch{}Gr.DocumentType=pl;Gr.DOMException=ue;Gr.DOMImplementation=Ky;Gr.Element=Wn;Gr.Node=oe;Gr.NodeList=qr;Gr.walkDOM=We;Gr.XMLSerializer=ib});var ub=g(co=>{"use strict";var lb=io().freeze;co.XML_ENTITIES=lb({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'});co.HTML_ENTITIES=lb({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"});co.entityMap=co.HTML_ENTITIES});var vb=g(lp=>{var ho=io().NAMESPACE,sp=/[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]/,cb=new RegExp("[\\-\\.0-9"+sp.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),db=new RegExp("^"+sp.source+cb.source+"*(?::"+sp.source+cb.source+"*)?$"),po=0,vn=1,Fi=2,fo=3,xi=4,Li=5,mo=6,ml=7;function ki(e,t){this.message=e,this.locator=t,Error.captureStackTrace&&Error.captureStackTrace(this,ki)}ki.prototype=new Error;ki.prototype.name=ki.name;function mb(){}mb.prototype={parse:function(e,t,r){var n=this.domBuilder;n.startDocument(),hb(t,t={}),bk(e,t,r,n,this.errorHandler),n.endDocument()}};function bk(e,t,r,n,i){function a(de){if(de>65535){de-=65536;var gt=55296+(de>>10),oc=56320+(de&1023);return String.fromCharCode(gt,oc)}else return String.fromCharCode(de)}function o(de){var gt=de.slice(1,-1);return Object.hasOwnProperty.call(r,gt)?r[gt]:gt.charAt(0)==="#"?a(parseInt(gt.substr(1).replace("x","0x"))):(i.error("entity not found:"+de),de)}function s(de){if(de>w){var gt=e.substring(w,de).replace(/&#?\w+;/g,o);p&&l(w),n.characters(gt,0,de-w),w=de}}function l(de,gt){for(;de>=c&&(gt=d.exec(e));)u=gt.index,c=u+gt[0].length,p.lineNumber++;p.columnNumber=de-u+1}for(var u=0,c=0,d=/.*(?:\r\n?|\n)|.*$/g,p=n.locator,m=[{currentNSMap:t}],h={},w=0;;){try{var b=e.indexOf("<",w);if(b<0){if(!e.substr(w).match(/^\s*$/)){var E=n.doc,D=E.createTextNode(e.substr(w));E.appendChild(D),n.currentElement=D}return}switch(b>w&&s(b),e.charAt(b+1)){case"/":var $=e.indexOf(">",b+3),F=e.substring(b+2,$).replace(/[ \t\n\r]+$/g,""),x=m.pop();$<0?(F=e.substring(b+2).replace(/[\s<].*/,""),i.error("end tag name: "+F+" is not complete:"+x.tagName),$=b+1+F.length):F.match(/\s</)&&(F=F.replace(/[\s<].*/,""),i.error("end tag name: "+F+" maybe not complete"),$=b+1+F.length);var q=x.localNSMap,G=x.tagName==F,M=G||x.tagName&&x.tagName.toLowerCase()==F.toLowerCase();if(M){if(n.endElement(x.uri,x.localName,F),q)for(var U in q)Object.prototype.hasOwnProperty.call(q,U)&&n.endPrefixMapping(U);G||i.fatalError("end tag name: "+F+" is not match the current start tagName:"+x.tagName)}else m.push(x);$++;break;case"?":p&&l(b),$=Ek(e,b,n);break;case"!":p&&l(b),$=Sk(e,b,n,i);break;default:p&&l(b);var B=new gb,W=m[m.length-1].currentNSMap,$=wk(e,b,B,W,o,i),Se=B.length;if(!B.closed&&Ck(e,$,B.tagName,h)&&(B.closed=!0,r.nbsp||i.warning("unclosed xml attribute")),p&&Se){for(var ve=pb(p,{}),Ve=0;Ve<Se;Ve++){var Ke=B[Ve];l(Ke.offset),Ke.locator=pb(p,{})}n.locator=ve,fb(B,n,W)&&m.push(B),n.locator=p}else fb(B,n,W)&&m.push(B);ho.isHTML(B.uri)&&!B.closed?$=Ak(e,$,B.tagName,o,n):$++}}catch(de){if(de instanceof ki)throw de;i.error("element parse error: "+de),$=-1}$>w?w=$:s(Math.max(b,w)+1)}}function pb(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}function wk(e,t,r,n,i,a){function o(m,h,w){r.attributeNames.hasOwnProperty(m)&&a.fatalError("Attribute "+m+" redefined"),r.addValue(m,h.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,i),w)}for(var s,l,u=++t,c=po;;){var d=e.charAt(u);switch(d){case"=":if(c===vn)s=e.slice(t,u),c=fo;else if(c===Fi)c=fo;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(c===fo||c===vn)if(c===vn&&(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=Li;else throw new Error("attribute value no end '"+d+"' match");else if(c==xi)l=e.slice(t,u),o(s,l,t),a.warning('attribute "'+s+'" missed start quot('+d+")!!"),t=u+1,c=Li;else throw new Error('attribute value must after "="');break;case"/":switch(c){case po:r.setTagName(e.slice(t,u));case Li:case mo:case ml:c=ml,r.closed=!0;case xi:case vn:break;case Fi:r.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return a.error("unexpected end of input"),c==po&&r.setTagName(e.slice(t,u)),u;case">":switch(c){case po:r.setTagName(e.slice(t,u));case Li:case mo:case ml:break;case xi:case vn:l=e.slice(t,u),l.slice(-1)==="/"&&(r.closed=!0,l=l.slice(0,-1));case Fi:c===Fi&&(l=s),c==xi?(a.warning('attribute "'+l+'" missed quot(")!'),o(s,l,t)):((!ho.isHTML(n[""])||!l.match(/^(?:disabled|checked|selected)$/i))&&a.warning('attribute "'+l+'" missed value!! "'+l+'" instead!!'),o(l,l,t));break;case fo:throw new Error("attribute value missed!!")}return u;case"\x80":d=" ";default:if(d<=" ")switch(c){case po:r.setTagName(e.slice(t,u)),c=mo;break;case vn:s=e.slice(t,u),c=Fi;break;case xi:var l=e.slice(t,u);a.warning('attribute "'+l+'" missed quot(")!!'),o(s,l,t);case Li:c=mo;break}else switch(c){case Fi:var p=r.tagName;(!ho.isHTML(n[""])||!s.match(/^(?:disabled|checked|selected)$/i))&&a.warning('attribute "'+s+'" missed value!! "'+s+'" instead2!!'),o(s,s,t),t=u,c=vn;break;case Li:a.warning('attribute space is required"'+s+'"!!');case mo:c=vn,t=u;break;case fo:c=xi,t=u;break;case ml:throw new Error("elements closed character '/' and '>' must be connected to")}}u++}}function fb(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={},hb(r,r={})),r[c]=i[c]=s,a.uri=ho.XMLNS,t.startPrefixMapping(c,s))}for(var d=e.length;d--;){a=e[d];var l=a.prefix;l&&(l==="xml"&&(a.uri=ho.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 m=e.uri=r[l||""];if(t.startElement(m,u,n,e),e.closed){if(t.endElement(m,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 Ak(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 Ck(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 hb(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function Sk(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=Nk(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 Ek(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 gb(){this.attributeNames={}}gb.prototype={setTagName:function(e){if(!db.test(e))throw new Error("invalid tagName:"+e);this.tagName=e},addValue:function(e,t,r){if(!db.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 Nk(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}lp.XMLReader=mb;lp.ParseError=ki});var Eb=g(gl=>{var Dk=io(),Ik=op(),yb=ub(),Ab=vb(),_k=Ik.DOMImplementation,bb=Dk.NAMESPACE,Pk=Ab.ParseError,Tk=Ab.XMLReader;function Cb(e){return e.replace(/\r[\n\u0085]/g,`+`),o=await e.postBatch(a,r),s=e.apiUrl("/$batch");(0,Ae.ensureSuccess)(o,s);let l=`app '${t[0].path}'`;if(typeof o.body!="string"||o.body.length===0)throw new he.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,ik.parseChangeSetStatuses)(o.body,i.map((d,p)=>String(p+1)));if(u===void 0)throw new he.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 he.ConnectionError(s,c,`atomic delete of ${l} was rolled back: the change set reported HTTP ${c}`);if(u.length!==i.length)throw new he.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 Wd(e,t){try{let r=ol(t,"sitemapid"),n=await e.get(r);return n.status<200||n.status>=300?null:al(Pi(n))}catch{return null}}function gk(e){return e>=400&&e<500&&e!==408&&e!==429}function jd(e,t,r){if(!e)throw new he.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 qy(e,t,r){let n=`/appmodules(${t})`;if(!r.sitemapId){await vk(e,n,jd(r.appEtag,t,"app"));return}if(!e.supportsAtomicBatch)throw new he.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 $y(e,[{path:n,etag:jd(r.appEtag,t,"app")},{path:`/sitemaps(${r.sitemapId})`,etag:jd(r.sitemapEtag,t,"sitemap")}])}async function vk(e,t,r){(0,Ae.ensureSuccess)(await e.delete(t,{headers:{"If-Match":r}}),e.apiUrl(t))}async function ky(e,t){if(!/GenPageId/i.test(t))return;let r;try{r=[...new Set((0,rk.collectGenPageIds)(t))]}catch(o){throw new he.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 (${Jd(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,Qd.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 he.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 yk(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")}gn.appApi={async get(e,t){var r;let n=(0,ae.normalizeGuid)(t,"id"),i=zd(Gd,n),a=(0,Ae.ensureSuccess)(await e.get(i),e.apiUrl(i)),o=(r=Pi(a))!==null&&r!==void 0?r:{};if(!o.appmoduleid)throw new he.SdkError("APP_NOT_FOUND",`App '${n}' was not found (checked the unpublished-aware projection, which includes drafts).`);let s=await Uy(e,o.uniquename),l=s?(0,ae.normalizeGuid)(s,"sitemapId"):void 0,u=null;if(l){let d=ol(l,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"),p=(0,Ae.ensureSuccess)(await e.get(d),e.apiUrl(d)),f=Pi(p);if(f&&f.sitemapnameunique!==o.uniquename)throw new he.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.`);o.$sitemap=f??{},u=al(f)}let c=al(o);return{raw:o,etag:u,...o.appmoduleid?{siblingEtags:{[(0,ae.normalizeGuid)(o.appmoduleid,"appmoduleid")]:c}}:{}}},async list(e,t){let r=zd(Gd);return(await(0,Qd.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 ky(e,n.sitemapxml);let i=n.iconWebResourceId?void 0:await sk(e),a=n.iconWebResourceId||i?.id;if(!a)throw new he.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||ok(n.appModuleId),l={name:n.appModuleName,uniquename:s,clienttype:4,formfactor:1,navigationtype:0};n.appModuleDescription&&(l.description=n.appModuleDescription),a&&(l.webresourceid=a);let u="/appmodules",c=(0,Ae.ensureSuccess)(await e.post(u,(0,Ae.withClientMintedId)(l,"appmoduleid",r)),e.apiUrl(u)),d=(0,Ae.resolveCreatedId)(c,"appmoduleid","app module",r),p=null,f=[];o&&f.push(o);let h={kind:"notRequested"},y=(0,Hd.newId)(),w=!1;try{let D="/sitemaps",x=await e.post(D,{sitemapid:y,sitemapnameunique:s,sitemapname:n.sitemapname,sitemapxml:n.sitemapxml});w=gk(x.status);let F=(0,Ae.ensureSuccess)(x,e.apiUrl(D));p=(0,Ae.readEtag)(F),p||(p=await Wd(e,y));let X=await Fy(e,n);f.push(...X.warnings);let V=X.components;V.unshift({"@odata.type":"Microsoft.Dynamics.CRM.sitemap",sitemapid:y}),await xy(e,d,V),await Ly(e,d,X.tables);let M=await lk(e,d);M&&f.push(M),n.appSettings&&Object.keys(n.appSettings).length>0&&f.push(...await(0,nk.applyAppSettings)(e,d,n.appSettings)),n.published!==!1&&(await(0,Ty.publishAppModule)(e,d),h={kind:"submitted"})}catch(D){throw await fk(e,d,{sitemapId:y,serverRefusedSitemap:w,appEtag:(0,Ae.readEtag)(c),sitemapEtag:p}),D}let N=null;if(h.kind==="submitted")try{let D=await e.get(`/appmodules(${d})?$select=appmoduleid`);D.status>=200&&D.status<300&&(N=(0,Ae.readEtag)(D))}catch{}return{id:d,etag:p,serverIdentity:{sitemapId:y},siblingEtags:{[d]:N},publish:h,...f.length>0?{warnings:f}:{}}},async update(e,t,r,n,i,a){var o,s,l,u,c,d,p;let f=r,h=(0,ae.normalizeGuid)(t,"id");if(await ky(e,f.sitemapxml),!f.sitemapId)throw new he.ValidationError("app",h,"/sitemapId","missing sitemap identity \u2014 re-fetch the app before pushing edits");let y=(0,ae.normalizeGuid)(f.sitemapId,"sitemapId");if(!n)throw new he.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${h}': 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 w=await Fy(e,f),N=`/appmodules(${h})`,D=(o=a?.[h])!==null&&o!==void 0?o:null,x=!0,F=!1;try{let ye=zd(Gd,h),Ge=await e.get(ye);if(Ge.status>=200&&Ge.status<300){let Ze=(s=Pi(Ge))!==null&&s!==void 0?s:{};F=!0,x=String((l=Ze.name)!==null&&l!==void 0?l:"")!==String((u=f.appModuleName)!==null&&u!==void 0?u:"")||String((c=Ze.description)!==null&&c!==void 0?c:"")!==String((d=f.appModuleDescription)!==null&&d!==void 0?d:"")}}catch{}let X=D;if(x){let ye=F?D:null,Ge=ye?(0,Ae.echoWrite)("appmoduleid",{"If-Match":ye}):{query:"",options:void 0},Ze=await e.patch(`${N}${Ge.query}`,{name:f.appModuleName,description:f.appModuleDescription},Ge.options);if(yk(Ze))throw new he.SdkError("APP_DRAFT_HEADER_NOT_WRITABLE",`Refusing to update app '${h}': 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,Ae.ensureSuccess)(Ze,e.apiUrl(N)),X=(0,Ae.readEtag)(Ze)}let V={"If-Match":n},M=`/sitemaps(${y})`,U;try{U=(0,Ae.ensureSuccess)(await e.patch(M,{sitemapxml:f.sitemapxml,sitemapname:f.sitemapname},V?{headers:V}:void 0),e.apiUrl(M))}catch(ye){throw(0,he.withPartialTokens)(ye,{siblingEtags:{[h]:X}})}let B=[...w.warnings];try{await xy(e,h,w.components),await Ly(e,h,w.tables)}catch(ye){B.push(`App '${h}': one or more components were not pinned (${ye.message}). Navigation may reference content not included in the app; re-push to retry.`)}let z={kind:"notRequested"},$=X,Ee=(0,Ae.readEtag)(U);if(f.published===!0){try{await(0,Ty.publishAppModule)(e,h),z={kind:"submitted"}}catch(ye){z={kind:"failed",error:ye},B.push(`App '${h}': saved, but publishing failed (${ye.message}). The app remains unpublished; re-push to retry.`)}if(z.kind==="submitted"){$=null;try{let ye=await e.get(`/appmodules(${h})?$select=appmoduleid`);ye.status>=200&&ye.status<300&&($=(0,Ae.readEtag)(ye)),Ee=(p=await Wd(e,y))!==null&&p!==void 0?p:Ee}catch{}}}return{id:h,etag:Ee??await Wd(e,y),siblingEtags:{[h]:$},publish:z,...B.length>0?{warnings:B}:{}}},async delete(e,t){let r=(0,ae.normalizeGuid)(t,"id");await qy(e,r,await By(e,r))}}});var ao=g(Ti=>{"use strict";function bk(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 Kd(e,t){return t===void 0&&(t=Object),t&&typeof t.freeze=="function"?t.freeze(e):e}function wk(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 Vy=Kd({HTML:"text/html",isHTML:function(e){return e===Vy.HTML},XML_APPLICATION:"application/xml",XML_TEXT:"text/xml",XML_XHTML_APPLICATION:"application/xhtml+xml",XML_SVG_IMAGE:"image/svg+xml"}),Gy=Kd({HTML:"http://www.w3.org/1999/xhtml",isHTML:function(e){return e===Gy.HTML},SVG:"http://www.w3.org/2000/svg",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"});Ti.assign=wk;Ti.find=bk;Ti.freeze=Kd;Ti.MIME_TYPE=Vy;Ti.NAMESPACE=Gy});var up=g(Gr=>{var Ky=ao(),gr=Ky.find,oo=Ky.NAMESPACE;function Ak(e){return e!==""}function Ck(e){return e?e.split(/[\t\n\f\r ]+/).filter(Ak):[]}function Sk(e,t){return e.hasOwnProperty(t)||(e[t]=!0),e}function zy(e){if(!e)return[];var t=Ck(e);return Object.keys(t.reduce(Sk,{}))}function Ek(e){return function(t){return e&&e.indexOf(t)!==-1}}function lo(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function St(e,t){var r=e.prototype;if(!(r instanceof t)){let i=function(){};var n=i;i.prototype=t.prototype,i=new i,lo(r,i),e.prototype=r=i}r.constructor!=e&&(typeof e!="function"&&console.error("unknown Class:"+e),r.constructor=e)}var Et={},Ut=Et.ELEMENT_NODE=1,Ri=Et.ATTRIBUTE_NODE=2,ul=Et.TEXT_NODE=3,Yy=Et.CDATA_SECTION_NODE=4,Zy=Et.ENTITY_REFERENCE_NODE=5,Nk=Et.ENTITY_NODE=6,Yd=Et.PROCESSING_INSTRUCTION_NODE=7,Zd=Et.COMMENT_NODE=8,eb=Et.DOCUMENT_NODE=9,tb=Et.DOCUMENT_TYPE_NODE=10,$r=Et.DOCUMENT_FRAGMENT_NODE=11,Dk=Et.NOTATION_NODE=12,at={},He={},yj=at.INDEX_SIZE_ERR=(He[1]="Index size error",1),bj=at.DOMSTRING_SIZE_ERR=(He[2]="DOMString size error",2),Ct=at.HIERARCHY_REQUEST_ERR=(He[3]="Hierarchy request error",3),wj=at.WRONG_DOCUMENT_ERR=(He[4]="Wrong document",4),Ik=at.INVALID_CHARACTER_ERR=(He[5]="Invalid character",5),Aj=at.NO_DATA_ALLOWED_ERR=(He[6]="No data allowed",6),Cj=at.NO_MODIFICATION_ALLOWED_ERR=(He[7]="No modification allowed",7),rb=at.NOT_FOUND_ERR=(He[8]="Not found",8),Sj=at.NOT_SUPPORTED_ERR=(He[9]="Not supported",9),Wy=at.INUSE_ATTRIBUTE_ERR=(He[10]="Attribute in use",10),Oi=at.INVALID_STATE_ERR=(He[11]="Invalid state",11),Ej=at.SYNTAX_ERR=(He[12]="Syntax error",12),Nj=at.INVALID_MODIFICATION_ERR=(He[13]="Invalid modification",13),Dj=at.NAMESPACE_ERR=(He[14]="Invalid namespace",14),Ij=at.INVALID_ACCESS_ERR=(He[15]="Invalid access",15);function ue(e,t){if(t instanceof Error)var r=t;else r=this,Error.call(this,He[e]),this.message=He[e],Error.captureStackTrace&&Error.captureStackTrace(this,ue);return r.code=e,t&&(this.message=this.message+": "+t),r}ue.prototype=Error.prototype;lo(at,ue);function qr(){}qr.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++)lp(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 Fi(e,t){this._node=e,this._refresh=t,ep(this)}function ep(e){var t=e._node._inc||e._node.ownerDocument._inc;if(e._inc!==t){var r=e._refresh(e._node);if(mb(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];lo(r,e),e._inc=t}}Fi.prototype.item=function(e){return ep(this),this[e]||null};St(Fi,qr);function cl(){}function nb(e,t){for(var r=e.length;r--;)if(e[r]===t)return r}function jy(e,t,r,n){if(n?t[nb(t,n)]=r:t[t.length++]=r,e){r.ownerElement=e;var i=e.ownerDocument;i&&(n&&ob(i,e,n),_k(i,e,r))}}function Hy(e,t,r){var n=nb(t,r);if(n>=0){for(var i=t.length-1;n<i;)t[n]=t[++n];if(t.length=i,e){var a=e.ownerDocument;a&&(ob(a,e,r),r.ownerElement=null)}}else throw new ue(rb,new Error(e.tagName+"@"+r))}cl.prototype={length:0,item:qr.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 ue(Wy);var r=this.getNamedItem(e.nodeName);return jy(this._ownerElement,this,e,r),r},setNamedItemNS:function(e){var t=e.ownerElement,r;if(t&&t!=this._ownerElement)throw new ue(Wy);return r=this.getNamedItemNS(e.namespaceURI,e.localName),jy(this._ownerElement,this,e,r),r},removeNamedItem:function(e){var t=this.getNamedItem(e);return Hy(this._ownerElement,this,t),t},removeNamedItemNS:function(e,t){var r=this.getNamedItemNS(e,t);return Hy(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 ib(){}ib.prototype={hasFeature:function(e,t){return!0},createDocument:function(e,t,r){var n=new uo;if(n.implementation=this,n.childNodes=new qr,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 ml;return n.name=e,n.nodeName=e,n.publicId=t||"",n.systemId=r||"",n}};function oe(){}oe.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 pl(this,e,t)},replaceChild:function(e,t){pl(this,e,t,lb),t&&this.removeChild(t)},removeChild:function(e){return sb(this,e)},appendChild:function(e){return this.insertBefore(e,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(e){return fb(this.ownerDocument||this,this,e)},normalize:function(){je(this,null,{enter:function(e){for(var t=e.firstChild;t;){var r=t.nextSibling;r!==null&&r.nodeType===ul&&t.nodeType===ul?(e.removeChild(r),t.appendData(r.data)):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==Ri?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==Ri?t.ownerDocument:t.parentNode}return null},isDefaultNamespace:function(e){var t=this.lookupPrefix(e);return t==null}};function ab(e){return e=="<"&&"<"||e==">"&&">"||e=="&"&&"&"||e=='"'&&"""||"&#"+e.charCodeAt()+";"}lo(Et,oe);lo(Et,oe.prototype);function dl(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 uo(){this.ownerDocument=this}function _k(e,t,r){e&&e._inc++;var n=r.namespaceURI;n===oo.XMLNS&&(t._nsMap[r.prefix?r.localName:""]=r.value)}function ob(e,t,r,n){e&&e._inc++;var i=r.namespaceURI;i===oo.XMLNS&&delete t._nsMap[r.prefix?r.localName:""]}function tp(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 sb(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,tp(e.ownerDocument,e),t}function Pk(e){return e&&(e.nodeType===oe.DOCUMENT_NODE||e.nodeType===oe.DOCUMENT_FRAGMENT_NODE||e.nodeType===oe.ELEMENT_NODE)}function Tk(e){return e&&(vr(e)||rp(e)||Vr(e)||e.nodeType===oe.DOCUMENT_FRAGMENT_NODE||e.nodeType===oe.COMMENT_NODE||e.nodeType===oe.PROCESSING_INSTRUCTION_NODE)}function Vr(e){return e&&e.nodeType===oe.DOCUMENT_TYPE_NODE}function vr(e){return e&&e.nodeType===oe.ELEMENT_NODE}function rp(e){return e&&e.nodeType===oe.TEXT_NODE}function Qy(e,t){var r=e.childNodes||[];if(gr(r,vr)||Vr(t))return!1;var n=gr(r,Vr);return!(t&&n&&r.indexOf(n)>r.indexOf(t))}function Jy(e,t){var r=e.childNodes||[];function n(a){return vr(a)&&a!==t}if(gr(r,n))return!1;var i=gr(r,Vr);return!(t&&i&&r.indexOf(i)>r.indexOf(t))}function Ok(e,t,r){if(!Pk(e))throw new ue(Ct,"Unexpected parent node type "+e.nodeType);if(r&&r.parentNode!==e)throw new ue(rb,"child not in parent");if(!Tk(t)||Vr(t)&&e.nodeType!==oe.DOCUMENT_NODE)throw new ue(Ct,"Unexpected node type "+t.nodeType+" for parent node type "+e.nodeType)}function Rk(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===oe.DOCUMENT_FRAGMENT_NODE){var a=i.filter(vr);if(a.length>1||gr(i,rp))throw new ue(Ct,"More than one element or text in fragment");if(a.length===1&&!Qy(e,r))throw new ue(Ct,"Element in fragment can not be inserted before doctype")}if(vr(t)&&!Qy(e,r))throw new ue(Ct,"Only one element can be added and only after doctype");if(Vr(t)){if(gr(n,Vr))throw new ue(Ct,"Only one doctype is allowed");var o=gr(n,vr);if(r&&n.indexOf(o)<n.indexOf(r))throw new ue(Ct,"Doctype can only be inserted before an element");if(!r&&o)throw new ue(Ct,"Doctype can not be appended since element is present")}}function lb(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===oe.DOCUMENT_FRAGMENT_NODE){var a=i.filter(vr);if(a.length>1||gr(i,rp))throw new ue(Ct,"More than one element or text in fragment");if(a.length===1&&!Jy(e,r))throw new ue(Ct,"Element in fragment can not be inserted before doctype")}if(vr(t)&&!Jy(e,r))throw new ue(Ct,"Only one element can be added and only after doctype");if(Vr(t)){let l=function(u){return Vr(u)&&u!==r};var s=l;if(gr(n,l))throw new ue(Ct,"Only one doctype is allowed");var o=gr(n,vr);if(r&&n.indexOf(o)<n.indexOf(r))throw new ue(Ct,"Doctype can only be inserted before an element")}}function pl(e,t,r,n){Ok(e,t,r),e.nodeType===oe.DOCUMENT_NODE&&(n||Rk)(e,t,r);var i=t.parentNode;if(i&&i.removeChild(t),t.nodeType===$r){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;so(a,l)}while(a!==o&&(a=a.nextSibling));return tp(e.ownerDocument||e,e),t.nodeType==$r&&(t.firstChild=t.lastChild=null),t}function so(e,t){if(e.ownerDocument!==t){if(e.ownerDocument=t,e.nodeType===Ut&&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;)so(i,t),i=i.nextSibling}}function Fk(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,tp(e.ownerDocument,e,t);var r=e.ownerDocument||e;return so(t,r),t}uo.prototype={nodeName:"#document",nodeType:eb,doctype:null,documentElement:null,_inc:1,insertBefore:function(e,t){if(e.nodeType==$r){for(var r=e.firstChild;r;){var n=r.nextSibling;this.insertBefore(r,t),r=n}return e}return pl(this,e,t),so(e,this),this.documentElement===null&&e.nodeType===Ut&&(this.documentElement=e),e},removeChild:function(e){return this.documentElement==e&&(this.documentElement=null),sb(this,e)},replaceChild:function(e,t){pl(this,e,t,lb),so(e,this),t&&this.removeChild(t),vr(e)&&(this.documentElement=e)},importNode:function(e,t){return xk(this,e,t)},getElementById:function(e){var t=null;return dl(this.documentElement,function(r){if(r.nodeType==Ut&&r.getAttribute("id")==e)return t=r,!0}),t},getElementsByClassName:function(e){var t=zy(e);return new Fi(this,function(r){var n=[];return t.length>0&&dl(r.documentElement,function(i){if(i!==r&&i.nodeType===Ut){var a=i.getAttribute("class");if(a){var o=e===a;if(!o){var s=zy(a);o=t.every(Ek(s))}o&&n.push(i)}}}),n})},createElement:function(e){var t=new Wn;t.ownerDocument=this,t.nodeName=e,t.tagName=e,t.localName=e,t.childNodes=new qr;var r=t.attributes=new cl;return r._ownerElement=t,t},createDocumentFragment:function(){var e=new hl;return e.ownerDocument=this,e.childNodes=new qr,e},createTextNode:function(e){var t=new np;return t.ownerDocument=this,t.appendData(e),t},createComment:function(e){var t=new ip;return t.ownerDocument=this,t.appendData(e),t},createCDATASection:function(e){if(e.indexOf("]]>")!==-1)throw new ue(Ik,'data contains "]]>"');var t=new ap;return t.ownerDocument=this,t.appendData(e),t},createProcessingInstruction:function(e,t){var r=new sp;return r.ownerDocument=this,r.tagName=r.nodeName=r.target=e,r.nodeValue=r.data=t,r},createAttribute:function(e){var t=new fl;return t.ownerDocument=this,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},createEntityReference:function(e){var t=new op;return t.ownerDocument=this,t.nodeName=e,t},createElementNS:function(e,t){var r=new Wn,n=t.split(":"),i=r.attributes=new cl;return r.childNodes=new qr,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 fl,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}};St(uo,oe);function Wn(){this._nsMap={}}Wn.prototype={nodeType:Ut,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===$r?this.insertBefore(e,null):Fk(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 Fi(this,function(t){var r=[];return dl(t,function(n){n!==t&&n.nodeType==Ut&&(e==="*"||n.tagName==e)&&r.push(n)}),r})},getElementsByTagNameNS:function(e,t){return new Fi(this,function(r){var n=[];return dl(r,function(i){i!==r&&i.nodeType===Ut&&(e==="*"||i.namespaceURI===e)&&(t==="*"||i.localName==t)&&n.push(i)}),n})}};uo.prototype.getElementsByTagName=Wn.prototype.getElementsByTagName;uo.prototype.getElementsByTagNameNS=Wn.prototype.getElementsByTagNameNS;St(Wn,oe);function fl(){}fl.prototype.nodeType=Ri;St(fl,oe);function co(){}co.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(He[Ct])},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}};St(co,oe);function np(){}np.prototype={nodeName:"#text",nodeType:ul,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}};St(np,co);function ip(){}ip.prototype={nodeName:"#comment",nodeType:Zd};St(ip,co);function ap(){}ap.prototype={nodeName:"#cdata-section",nodeType:Yy};St(ap,co);function ml(){}ml.prototype.nodeType=tb;St(ml,oe);function ub(){}ub.prototype.nodeType=Dk;St(ub,oe);function cb(){}cb.prototype.nodeType=Nk;St(cb,oe);function op(){}op.prototype.nodeType=Zy;St(op,oe);function hl(){}hl.prototype.nodeName="#document-fragment";hl.prototype.nodeType=$r;St(hl,oe);function sp(){}sp.prototype.nodeType=Yd;St(sp,oe);function db(){}db.prototype.serializeToString=function(e,t,r,n){return pb.call(e,t,r,n)};oe.prototype.toString=pb;function pb(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 lp(this,i,e,t,l,n),i.join("")}function Xy(e,t,r){var n=e.prefix||"",i=e.namespaceURI;if(!i||n==="xml"&&i===oo.XML||i===oo.XMLNS)return!1;for(var a=r.length;a--;){var o=r[a];if(o.prefix===n)return o.namespace!==i}return!0}function ll(e,t,r){e.push(" ",t,'="',r.replace(/[<>&"\t\n\r]/g,ab),'"')}function lp(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 Ut:var c=o.attributes,d=c.length,p=o.tagName;u=oo.isHTML(o.namespaceURI)||u;var f=p;if(!u&&!o.prefix&&o.namespaceURI){for(var h,y=0;y<c.length;y++)if(c.item(y).name==="xmlns"){h=c.item(y).value;break}if(!h)for(var w=l.length-1;w>=0;w--){var N=l[w];if(N.prefix===""&&N.namespace===o.namespaceURI){h=N.namespace;break}}if(h!==o.namespaceURI)for(var w=l.length-1;w>=0;w--){var N=l[w];if(N.namespace===o.namespaceURI){N.prefix&&(f=N.prefix+":"+p);break}}}t.push("<",f);for(var D=l.slice(),x=0;x<d;x++){var F=c.item(x);F.prefix=="xmlns"?D.push({prefix:F.localName,namespace:F.value}):F.nodeName=="xmlns"&&D.push({prefix:"",namespace:F.value})}for(var x=0;x<d;x++){var F=c.item(x);if(Xy(F,u,D)){var X=F.prefix||"",V=F.namespaceURI;ll(t,X?"xmlns:"+X:"xmlns",V),D.push({prefix:X,namespace:V})}var M=n?n(F):F;M&&(typeof M=="string"?t.push(M):ll(t,M.name,M.value))}if(p===f&&Xy(o,u,D)){var U=o.prefix||"",V=o.namespaceURI;ll(t,U?"xmlns:"+U:"xmlns",V),D.push({prefix:U,namespace:V})}var B=o.firstChild;if(B||u&&!/^(?:meta|link|img|br|hr|input)$/i.test(p)){if(t.push(">"),u&&/^script$/i.test(p)){for(;B;)B.data?t.push(B.data):lp(B,t,u,n,D.slice(),a),B=B.nextSibling;return t.push("</",p,">"),null}return{ns:D,isHTML:u,tag:f}}else return t.push("/>"),null;case eb:case $r:return{ns:l.slice(),isHTML:u,tag:null};case Ri:return ll(t,o.name,o.value),null;case ul:return t.push(o.data.replace(/[<&>]/g,ab)),null;case Yy:if(a&&o.data.indexOf("]]>")!==-1)throw new ue(Oi,'The CDATASection data contains "]]>"');return t.push("<![CDATA[",o.data.replace(/]]>/g,"]]]]><![CDATA[>"),"]]>"),null;case Zd:if(a&&o.data.indexOf("-->")!==-1)throw new ue(Oi,'The comment node data contains "-->"');return t.push("<!--",o.data,"-->"),null;case tb:if(a){if(o.publicId&&!/^("[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%']*"|'[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%'"]*')$/.test(o.publicId))throw new ue(Oi,"DocumentType publicId is not a valid PubidLiteral");if(o.systemId&&!/^("[^"]*"|'[^']*')$/.test(o.systemId))throw new ue(Oi,"DocumentType systemId is not a valid SystemLiteral");if(o.internalSubset&&o.internalSubset.indexOf("]>")!==-1)throw new ue(Oi,'DocumentType internalSubset contains "]>"')}var z=o.publicId,$=o.systemId;if(t.push("<!DOCTYPE ",o.name),z)t.push(" PUBLIC ",z),$&&$!="."&&t.push(" ",$),t.push(">");else if($&&$!=".")t.push(" SYSTEM ",$,">");else{var Ee=o.internalSubset;Ee&&t.push(" [",Ee,"]"),t.push(">")}return null;case Yd:if(a&&o.data.indexOf("?>")!==-1)throw new ue(Oi,'The ProcessingInstruction data contains "?>"');return t.push("<?",o.target," ",o.data,"?>"),null;case Zy: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 xk(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===Ri||r;return s?o:null}}),n}function fb(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 qr),o.ownerDocument=e;var u=r;switch(o.nodeType){case Ut:var c=i.attributes,d=o.attributes=new cl,p=c.length;d._ownerElement=o;for(var f=0;f<p;f++)o.setAttributeNode(fb(e,c.item(f),!0));break;case Ri:u=!0}return a!==null?a.appendChild(o):n=o,u?o:null}}),n}function mb(e,t,r){e[t]=r}try{Object.defineProperty&&(Object.defineProperty(Fi.prototype,"length",{get:function(){return ep(this),this.$$length}}),Object.defineProperty(oe.prototype,"textContent",{get:function(){if(this.nodeType===Ut||this.nodeType===$r){var e=[];return je(this,null,{enter:function(t){if(t.nodeType===Ut||t.nodeType===$r)return!0;if(t.nodeType===Yd||t.nodeType===Zd)return null;e.push(t.nodeValue)}}),e.join("")}return this.nodeValue},set:function(e){switch(this.nodeType){case Ut:case $r: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}}}),mb=function(e,t,r){e["$$"+t]=r})}catch{}Gr.DocumentType=ml;Gr.DOMException=ue;Gr.DOMImplementation=ib;Gr.Element=Wn;Gr.Node=oe;Gr.NodeList=qr;Gr.walkDOM=je;Gr.XMLSerializer=db});var gb=g(po=>{"use strict";var hb=ao().freeze;po.XML_ENTITIES=hb({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'});po.HTML_ENTITIES=hb({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"});po.entityMap=po.HTML_ENTITIES});var Eb=g(dp=>{var go=ao().NAMESPACE,cp=/[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]/,vb=new RegExp("[\\-\\.0-9"+cp.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),yb=new RegExp("^"+cp.source+vb.source+"*(?::"+cp.source+vb.source+"*)?$"),fo=0,vn=1,xi=2,mo=3,Li=4,ki=5,ho=6,gl=7;function Mi(e,t){this.message=e,this.locator=t,Error.captureStackTrace&&Error.captureStackTrace(this,Mi)}Mi.prototype=new Error;Mi.prototype.name=Mi.name;function Ab(){}Ab.prototype={parse:function(e,t,r){var n=this.domBuilder;n.startDocument(),Cb(t,t={}),Lk(e,t,r,n,this.errorHandler),n.endDocument()}};function Lk(e,t,r,n,i){function a(pe){if(pe>65535){pe-=65536;var vt=55296+(pe>>10),lc=56320+(pe&1023);return String.fromCharCode(vt,lc)}else return String.fromCharCode(pe)}function o(pe){var vt=pe.slice(1,-1);return Object.hasOwnProperty.call(r,vt)?r[vt]:vt.charAt(0)==="#"?a(parseInt(vt.substr(1).replace("x","0x"))):(i.error("entity not found:"+pe),pe)}function s(pe){if(pe>y){var vt=e.substring(y,pe).replace(/&#?\w+;/g,o);p&&l(y),n.characters(vt,0,pe-y),y=pe}}function l(pe,vt){for(;pe>=c&&(vt=d.exec(e));)u=vt.index,c=u+vt[0].length,p.lineNumber++;p.columnNumber=pe-u+1}for(var u=0,c=0,d=/.*(?:\r\n?|\n)|.*$/g,p=n.locator,f=[{currentNSMap:t}],h={},y=0;;){try{var w=e.indexOf("<",y);if(w<0){if(!e.substr(y).match(/^\s*$/)){var N=n.doc,D=N.createTextNode(e.substr(y));N.appendChild(D),n.currentElement=D}return}switch(w>y&&s(w),e.charAt(w+1)){case"/":var $=e.indexOf(">",w+3),x=e.substring(w+2,$).replace(/[ \t\n\r]+$/g,""),F=f.pop();$<0?(x=e.substring(w+2).replace(/[\s<].*/,""),i.error("end tag name: "+x+" is not complete:"+F.tagName),$=w+1+x.length):x.match(/\s</)&&(x=x.replace(/[\s<].*/,""),i.error("end tag name: "+x+" maybe not complete"),$=w+1+x.length);var X=F.localNSMap,V=F.tagName==x,M=V||F.tagName&&F.tagName.toLowerCase()==x.toLowerCase();if(M){if(n.endElement(F.uri,F.localName,x),X)for(var U in X)Object.prototype.hasOwnProperty.call(X,U)&&n.endPrefixMapping(U);V||i.fatalError("end tag name: "+x+" is not match the current start tagName:"+F.tagName)}else f.push(F);$++;break;case"?":p&&l(w),$=$k(e,w,n);break;case"!":p&&l(w),$=Bk(e,w,n,i);break;default:p&&l(w);var B=new Sb,z=f[f.length-1].currentNSMap,$=kk(e,w,B,z,o,i),Ee=B.length;if(!B.closed&&Uk(e,$,B.tagName,h)&&(B.closed=!0,r.nbsp||i.warning("unclosed xml attribute")),p&&Ee){for(var ye=bb(p,{}),Ge=0;Ge<Ee;Ge++){var Ze=B[Ge];l(Ze.offset),Ze.locator=bb(p,{})}n.locator=ye,wb(B,n,z)&&f.push(B),n.locator=p}else wb(B,n,z)&&f.push(B);go.isHTML(B.uri)&&!B.closed?$=Mk(e,$,B.tagName,o,n):$++}}catch(pe){if(pe instanceof Mi)throw pe;i.error("element parse error: "+pe),$=-1}$>y?y=$:s(Math.max(w,y)+1)}}function bb(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}function kk(e,t,r,n,i,a){function o(f,h,y){r.attributeNames.hasOwnProperty(f)&&a.fatalError("Attribute "+f+" redefined"),r.addValue(f,h.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,i),y)}for(var s,l,u=++t,c=fo;;){var d=e.charAt(u);switch(d){case"=":if(c===vn)s=e.slice(t,u),c=mo;else if(c===xi)c=mo;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(c===mo||c===vn)if(c===vn&&(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=ki;else throw new Error("attribute value no end '"+d+"' match");else if(c==Li)l=e.slice(t,u),o(s,l,t),a.warning('attribute "'+s+'" missed start quot('+d+")!!"),t=u+1,c=ki;else throw new Error('attribute value must after "="');break;case"/":switch(c){case fo:r.setTagName(e.slice(t,u));case ki:case ho:case gl:c=gl,r.closed=!0;case Li:case vn:break;case xi:r.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return a.error("unexpected end of input"),c==fo&&r.setTagName(e.slice(t,u)),u;case">":switch(c){case fo:r.setTagName(e.slice(t,u));case ki:case ho:case gl:break;case Li:case vn:l=e.slice(t,u),l.slice(-1)==="/"&&(r.closed=!0,l=l.slice(0,-1));case xi:c===xi&&(l=s),c==Li?(a.warning('attribute "'+l+'" missed quot(")!'),o(s,l,t)):((!go.isHTML(n[""])||!l.match(/^(?:disabled|checked|selected)$/i))&&a.warning('attribute "'+l+'" missed value!! "'+l+'" instead!!'),o(l,l,t));break;case mo:throw new Error("attribute value missed!!")}return u;case"\x80":d=" ";default:if(d<=" ")switch(c){case fo:r.setTagName(e.slice(t,u)),c=ho;break;case vn:s=e.slice(t,u),c=xi;break;case Li:var l=e.slice(t,u);a.warning('attribute "'+l+'" missed quot(")!!'),o(s,l,t);case ki:c=ho;break}else switch(c){case xi:var p=r.tagName;(!go.isHTML(n[""])||!s.match(/^(?:disabled|checked|selected)$/i))&&a.warning('attribute "'+s+'" missed value!! "'+s+'" instead2!!'),o(s,s,t),t=u,c=vn;break;case ki:a.warning('attribute space is required"'+s+'"!!');case ho:c=vn,t=u;break;case mo:c=Li,t=u;break;case gl:throw new Error("elements closed character '/' and '>' must be connected to")}}u++}}function wb(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={},Cb(r,r={})),r[c]=i[c]=s,a.uri=go.XMLNS,t.startPrefixMapping(c,s))}for(var d=e.length;d--;){a=e[d];var l=a.prefix;l&&(l==="xml"&&(a.uri=go.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 Mk(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 Uk(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 Cb(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function Bk(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=qk(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 $k(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 Sb(){this.attributeNames={}}Sb.prototype={setTagName:function(e){if(!yb.test(e))throw new Error("invalid tagName:"+e);this.tagName=e},addValue:function(e,t,r){if(!yb.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 qk(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}dp.XMLReader=Ab;dp.ParseError=Mi});var Ob=g(yl=>{var Vk=ao(),Gk=up(),Nb=gb(),_b=Eb(),zk=Gk.DOMImplementation,Db=Vk.NAMESPACE,Wk=_b.ParseError,jk=_b.XMLReader;function Pb(e){return e.replace(/\r[\n\u0085]/g,``).replace(/[\r\u0085\u2028]/g,`-`)}function Sb(e){this.options=e||{locator:{}}}Sb.prototype.parseFromString=function(e,t){var r=this.options,n=new Tk,i=r.domBuilder||new go,a=r.errorHandler,o=r.locator,s=r.xmlns||{},l=/\/x?html?$/.test(t),u=l?yb.HTML_ENTITIES:yb.XML_ENTITIES;o&&i.setDocumentLocator(o),n.errorHandler=Ok(a,i,o),n.domBuilder=r.domBuilder||i,l&&(s[""]=bb.HTML),s.xml=s.xml||bb.XML;var c=r.normalizeLineEndings||Cb;return e&&typeof e=="string"?n.parse(c(e),s,u):n.errorHandler.error("invalid doc source"),i.doc};function Ok(e,t,r){if(!e){if(t instanceof go)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+up(r))}||function(){}}return a("warning"),a("error"),a("fatalError"),n}function go(){this.cdata=!1}function Mi(e,t){t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber}go.prototype={startDocument:function(){this.doc=new _k().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;hl(this,a),this.currentElement=a,this.locator&&Mi(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&&Mi(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&&Mi(this.locator,r),hl(this,r)},ignorableWhitespace:function(e,t,r){},characters:function(e,t,r){if(e=wb.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&&Mi(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=wb.apply(this,arguments);var n=this.doc.createComment(e);this.locator&&Mi(this.locator,n),hl(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&&Mi(this.locator,i),hl(this,i),this.doc.doctype=i}},warning:function(e){console.warn("[xmldom warning] "+e,up(this.locator))},error:function(e){console.error("[xmldom error] "+e,up(this.locator))},fatalError:function(e){throw new Pk(e,this.locator)}};function up(e){if(e)return`-@`+(e.systemId||"")+"#[line:"+e.lineNumber+",col:"+e.columnNumber+"]"}function wb(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){go.prototype[e]=function(){return null}});function hl(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}gl.__DOMHandler=go;gl.normalizeLineEndings=Cb;gl.DOMParser=Sb});var yl=g(vl=>{var Nb=op();vl.DOMImplementation=Nb.DOMImplementation;vl.XMLSerializer=Nb.XMLSerializer;vl.DOMParser=Eb().DOMParser});var Hd=g(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.deleteAppCascade=Ui.collectGenPageIds=void 0;var Rk=al(),Fk=ie(),cp=ee(),xk=yl();function Db(e){let t=[],r=s=>l=>t.push(`${s}: ${l}`),i=new xk.DOMParser({errorHandler:{warning:r("warning"),error:r("error"),fatalError:r("fatalError")}}).parseFromString(e,"text/xml").documentElement;if(!i||t.length>0)throw new Fk.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,cp.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}Ui.collectGenPageIds=Db;async function Lk(e,t,r){let n=(0,cp.normalizeGuid)(t,"appModuleId");(0,cp.normalizeGuid)(r,"appModuleIdUnique");let i=[],a=[],o=[];await(0,Rk.deleteAppResolvingOnce)(e,n,l=>{l!==void 0&&o.push(...Db(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}}Ui.deleteAppCascade=Lk});var Ib={};Rr(Ib,{Guid:()=>P});var P,Me=I(()=>{"use strict";P=class e{guidString;guid;static get EmptyGuid(){return new e("00000000-0000-0000-0000-000000000000")}static NewGuid(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var r=Math.random()*16|0,n=t=="x"?r:r&3|8;return n.toString(16)})}constructor(t,r=!1){this.guidString=t;let n=new RegExp("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$");(r||n.test(t))&&(this.guid=t)}ToString(){return this.guid}}});var T,ot=I(()=>{"use strict";xe();T=class e{static get EmptyString(){return""}static IsTrue(t){let r=!1;return r=t&&(this.IsStrictTrue(t)||this.IsYes(t)),r}static IsStrictTrue(t){let r=!1;return t&&(r=t.toLowerCase()==="true"),r}static IsYes(t){return t.toLowerCase()==="yes"||t.toLowerCase()==="y"}static get WhiteSpace(){return/ /g}static get EnglishAndNumericCharacters(){return/([a-z0-9A-Z]+)/g}static get ValidIdExpression(){return/([a-z0-9A-Z_]+)/g}static IsNullOrEmpty(t){return t==null||t==null||t==""}static Format(t,r){return e.IsNullOrEmpty(t)?t:t.replace(/\{\{|\}\}|\{(\d+)\}/g,function(n,i){return n=="{{"?"{":n=="}}"?"}":r[i]})}static EndsWithString(t,r){return t.indexOf(r,t.length-r.length)!==-1}static IsBlankString(t){return t.replace(/\s/g,"").length==0}static EscapeXml(t,r){let n=t;return this.IsNullOrEmpty(n)||(n=n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),r&&(n=n.replace(/"/g,""").replace(/'/g,"'"))),n}static EscapeDomId(t){return t.replace(".","\\.")}static ToSnakeCase(t){let r=e.EmptyString;for(let n=0;n<t.length;n++)n!==0&&t[n]==t[n].toUpperCase()&&(r+="-"),r+=t[n].toLowerCase();return r}static GetSnakeCaseMarkup(t,r){let n="<"+this.ToSnakeCase(t);if(!N.IsNullOrUndefined(r))for(let i of r.getKeys())n+=" "+this.ToSnakeCase(i)+'="'+r.getValue(i)+'"';return n+">"}static StripBraces(t){return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?t.substr(1,t.length-2):t}static AddBraces(t){return N.IsNullOrUndefined(t)||t.charAt(0)==="{"||t.charAt(t.length-1)==="}"?t:`{${t}}`}static GuidStringEquals(t,r){return t===r?!0:!t||!r?!1:e.StripBraces(t).toUpperCase()===e.StripBraces(r).toUpperCase()}static AddBracesToArrayValues(t){return t.length>0?t.map(n=>(n.charAt(0)!=="{"&&(n="{"+n),n.charAt(n.length-1)!=="}"&&(n=n+"}"),n)):t}static StripBracesOnArrayValues(t){return t.length>0?t.map(n=>{let i;return n.charAt(0)==="{"&&(i=n.substr(1,n.length-1)),n.charAt(n.length-1)==="}"&&(i=i.substr(0,n.length-2)),i}):t}}});var _b={};Rr(_b,{ScriptUtilities:()=>N});var N,xe=I(()=>{"use strict";Me();ot();N=class e{static IsNullOrUndefined(t){return t==null||t===void 0}static IsMacMachine(){return navigator.platform.indexOf("Mac")!==-1}static IsNullOrEmptyGuid(t){return T.IsNullOrEmpty(t.ToString())?!0:P.EmptyGuid.ToString()===t.ToString()}static IsNullOrUndefinedNested(t,r){return r.split(".").every(i=>typeof t!="object"||t==null||!(i in t)||t[i]==null?!1:(t=t[i],!0))}static ParseXml(t){return new DOMParser().parseFromString(t,"text/xml")}static IsWellFormedXml(t){return!e.ParseXml(t).querySelector("parsererror")}static getNamedItemValue(t,r){let n=t.getNamedItem(r);return e.IsNullOrUndefined(n)?null:n.value}static getBooleanValue(t,r){let n=e.getNamedItemValue(t,r);return e.IsNullOrUndefined(n)?null:T.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 bl,wl,jn,Al,dp,Cl,pp=I(()=>{"use strict";(function(e){e[e.FormElementNodeChange=0]="FormElementNodeChange",e[e.FormElementAttributeChange=1]="FormElementAttributeChange"})(bl||(bl={}));wl=class{type;targetNode;constructor(t,r){this.type=t,this.targetNode=r}},jn=class extends wl{key;oldValue;newValue;constructor(t,r,n,i){super(bl.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)}},Al=class extends wl{property;oldValue;newValue;constructor(t,r,n,i){super(bl.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()})}},Cl=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 Pb={};Rr(Pb,{ChartGridMode:()=>Ut,ColumnLayoutWidths:()=>$k,ComponentCategory:()=>El,ComponentType:()=>fp,ControlLayoutTypes:()=>wp,DisplayConditionsInfo:()=>Uk,ElementNames:()=>v,ElementProperties:()=>f,ElementType:()=>hp,EntityAttributeProperty:()=>gp,EventType:()=>vo,FormActivationState:()=>bp,FormCanvasServiceScope:()=>Yk,FormDesignerSideBarTab:()=>mp,FormPresentation:()=>vp,FormState:()=>Sl,FormType:()=>Ue,HeaderDensityType:()=>yn,LookUpTable:()=>vr,MORE_TAB_PREFIX:()=>Vk,NavBarChildElementType:()=>yp,PREVIEW_ID_HEADER_FLYOUT:()=>jk,PREVIEW_ID_HEADER_OVERFLOW_BUTTON:()=>Jk,PREVIEW_ID_NAVIGATION_AREA:()=>zk,PREVIEW_ID_QUICKCREATE_ROOT:()=>Xk,PREVIEW_ID_TAB:()=>Qk,PREVIEW_ID_TAB_LIST:()=>Hk,PREVIEW_ID_TAB_PANEL:()=>Wk,PropertyModelKeys:()=>Sp,PropertyModelSectionKeys:()=>qk,RELATED_TAB_ID:()=>Ep,RELATED_TAB_PREFIX:()=>Gk,SectionDefaultProperties:()=>Bk,SectionLayoutTypes:()=>Ce,TabContentType:()=>Ap,TabDefaultProperties:()=>bn,TabLayoutTypes:()=>Ae,TelemetryPropertyNames:()=>Kk,UnboundControlPropertyKeys:()=>Cp,compositeAddressFields:()=>Mk,compositeFieldNames:()=>Ot,compositeFields:()=>kk});var Ue,fp,mp,v,f,hp,Ot,kk,Mk,gp,vr,Sl,yn,vp,Uk,yp,bp,Ae,Bk,bn,Ce,wp,Ap,$k,Cp,Sp,qk,vo,Ut,Ep,Vk,Gk,zk,Wk,jk,Hk,Jk,Qk,Xk,Kk,El,Yk,K=I(()=>{"use strict";(function(e){e[e.Dashboard=0]="Dashboard",e[e.AppointmentBook=1]="AppointmentBook",e[e.Main=2]="Main",e[e.MiniCampaignBO=3]="MiniCampaignBO",e[e.Preview=4]="Preview",e[e.MobileExpress=5]="MobileExpress",e[e.QuickViewForm=6]="QuickViewForm",e[e.QuickCreate=7]="QuickCreate",e[e.Dialog=8]="Dialog",e[e.TaskFlowForm=9]="TaskFlowForm",e[e.InteractionCentricDashboard=10]="InteractionCentricDashboard",e[e.Card=11]="Card",e[e.MainInteractiveExperience=12]="MainInteractiveExperience",e[e.Other=100]="Other",e[e.MainBackup=101]="MainBackup",e[e.AppointmentBookBackup=102]="AppointmentBookBackup",e[e.PowerBIDashboard=103]="PowerBIDashboard"})(Ue||(Ue={}));(function(e){e[e.Form=0]="Form",e[e.Dialog=1]="Dialog"})(fp||(fp={}));(function(e){e[e.Components=0]="Components",e[e.Properties=1]="Properties",e[e.Relationship=2]="Relationship",e[e.BusinessRules=3]="BusinessRules"})(mp||(mp={}));(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"})(v||(v={}));f={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"})(hp||(hp={}));Ot={fullname:"fullname",yomifullname:"yomifullname",address1_composite:"address1_composite",address2_composite:"address2_composite",address3_composite:"address3_composite",billto:"billto_composite",shipto:"shipto_composite"},kk=[Ot.fullname,Ot.yomifullname,Ot.address1_composite,Ot.address2_composite,Ot.address3_composite,Ot.billto,Ot.shipto],Mk=[Ot.address1_composite,Ot.address2_composite,Ot.address3_composite,Ot.billto,Ot.shipto];(function(e){e[e.IsValidForForm=0]="IsValidForForm",e[e.IsValidForCreate=1]="IsValidForCreate"})(gp||(gp={}));(function(e){e[e.DependencyFieldTable=0]="DependencyFieldTable",e[e.LockedFieldTable=1]="LockedFieldTable"})(vr||(vr={}));(function(e){e[e.Published=0]="Published",e[e.Draft=1]="Draft",e[e.New=2]="New",e[e.SaveAs=3]="SaveAs"})(Sl||(Sl={}));(function(e){e.Low="Low",e.HighReadOnlyValues="HighReadOnlyValues",e.HighWithControls="HighWithControls"})(yn||(yn={}));(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(vp||(vp={}));Uk={TopOrderFormId:"topOrderFormId",NextDisplayOrder:"nextDisplayOrder"};(function(e){e[e.NavBarRelationShipItem=0]="NavBarRelationShipItem",e[e.NavBarItem=1]="NavBarItem"})(yp||(yp={}));(function(e){e[e.InActive=0]="InActive",e[e.Active=1]="Active"})(bp||(bp={}));(function(e){e[e.ONE_COLUMN=0]="ONE_COLUMN",e[e.TWO_COLUMN_EQUAL=1]="TWO_COLUMN_EQUAL",e[e.TWO_COLUMN_WIDER_LEFT=2]="TWO_COLUMN_WIDER_LEFT",e[e.TWO_COLUMN_WIDER_RIGHT=3]="TWO_COLUMN_WIDER_RIGHT",e[e.TWO_COLUMN_CUSTOM_LAYOUT=4]="TWO_COLUMN_CUSTOM_LAYOUT",e[e.THREE_COLUMN_EQUAL=5]="THREE_COLUMN_EQUAL",e[e.THREE_COLUMN_WIDER_MID=6]="THREE_COLUMN_WIDER_MID",e[e.THREE_COLUMN_CUSTOM_LAYOUT=7]="THREE_COLUMN_CUSTOM_LAYOUT"})(Ae||(Ae={}));Bk={ShowLabel:"false",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_"},bn={namePrefix:"tab_",ShowLabel:"true",LockLevel:"0",IsUserDefined:"0"};(function(e){e[e.ONE_COLUMN=0]="ONE_COLUMN",e[e.TWO_COLUMN=1]="TWO_COLUMN",e[e.THREE_COLUMN=2]="THREE_COLUMN",e[e.FOUR_COLUMN=3]="FOUR_COLUMN",e[e.REFERENCE_PANEL=4]="REFERENCE_PANEL"})(Ce||(Ce={}));(function(e){e[e.SUBGRID=0]="SUBGRID",e[e.SPACER=1]="SPACER",e[e.QUICK_VIEW=2]="QUICK_VIEW",e[e.WEB_RESOURCE=3]="WEB_RESOURCE",e[e.IFRAME=4]="IFRAME",e[e.BING_MAPS=5]="BING_MAPS",e[e.TIMER=6]="TIMER",e[e.TIMELINE=7]="TIMELINE",e[e.NOTES=8]="NOTES",e[e.SOCIAL_INSIGHTS=9]="SOCIAL_INSIGHTS",e[e.KB_SEARCH=10]="KB_SEARCH",e[e.INTERACTION_WALL=11]="INTERACTION_WALL",e[e.ACI_CONTROL=12]="ACI_CONTROL",e[e.RELATIONSHIP_ASSISTANT=13]="RELATIONSHIP_ASSISTANT",e[e.REFERENCE_PANEL=14]="REFERENCE_PANEL",e[e.REF_PANEL_QUICKVIEW=15]="REF_PANEL_QUICKVIEW",e[e.REF_PANEL_SUBGRID=16]="REF_PANEL_SUBGRID",e[e.REF_PANEL_KBSEARCH=17]="REF_PANEL_KBSEARCH",e[e.WEB_RESOURCE_HTML=18]="WEB_RESOURCE_HTML",e[e.PRED_LEAD_SCORING=19]="PRED_LEAD_SCORING"})(wp||(wp={}));(function(e){e.cardSections="cardSections",e.singleComponent="singleComponent",e.default="default",e.expandAvailableSpace="expandAvailableSpace"})(Ap||(Ap={}));$k={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"})(Cp||(Cp={}));(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"})(Sp||(Sp={}));qk={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"})(vo||(vo={}));(function(e){e.All="All",e.Chart="Chart",e.Grid="Grid"})(Ut||(Ut={}));Ep="tab_related3b554255-7717-4d17-bb7f-9936fb1e75ca",Vk="more_tab_",Gk="related_tab_",zk="preview_id_navigation_area",Wk="tab-section",jk="headerFieldsFlyout",Hk="tablist",Jk="header_overflowButton",Qk="tab",Xk="quickCreateRoot",Kk={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"})(El||(El={}));Yk="CellCanvasServiceScope"});var Tb={};Rr(Tb,{Attribute:()=>Nl,FormElementNode:()=>H});var Nl,H,He=I(()=>{"use strict";xe();ot();pp();K();Me();Nl=class{key;value;constructor(t,r){this.key=t,this.value=r}},H=class e{nodeName;properties;childrenNodes;parentNode;nodeId;isTransient;constructor(t,r){this.nodeName=t,this.properties=[],this.childrenNodes=[],this.parentNode=r,this.isTransient=!1,this.nodeId=`nodeId-${P.NewGuid()}`}getProperty(t){for(let r of this.properties)if(r.key===t)return r.value;return null}getNodeId(){return this.nodeId}getNodeName(){return this.nodeName}setNodeName(t){this.trackObjectPropertyChange("nodeName",t)}get NodeName(){return this.getNodeName()}getAllProperties(){return this.properties}replaceAttributeValue(t,r){this.properties.find(n=>n===t)&&(t.value=r)}replaceObjectPropertyValue(t,r){this[t]=r}getAllChildren(){return this.childrenNodes}getParentNode(){return this.parentNode}visit(t){let r=!1;if(t){r=!!t(this);let n=this.childrenNodes;if(!r&&n)for(let i=0;!r&&i<n.length;i++)r=n[i].visit(t)}return r}findAll(t){let r=[];return t&&this.visit(n=>{t(n)&&r.push(n)}),r}findFirst(t){let r=null;return t&&this.visit(n=>{if(t(n))return r=n,!0}),r}raiseMetadataChange(t){let r=this.getAncestor(v.form);r&&r.raiseMetadataChange(t)}trackPropertyAddition(t,r){this.trackPropertyCollectionChange(()=>{this.properties.push(new Nl(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 jn(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 jn(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 jn(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 Al(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 jn(this,t,i,r))}else this[t]=r}setProperty(t,r){if(!t)throw new Error("Invalid property key");let n=this.properties.find(i=>i.key===t);n?this.trackAttributeValueChange(n,r):this.addProperty(t,r)}addProperty(t,r){if(!t)throw new Error("Invalid property key");this.trackPropertyAddition(t,r)}removeProperty(t){this.trackPropertyDeletion(t)}addChild(t){t.trackParentNodeChange(()=>{t.parentNode=this}),this.trackChildrenCollectionChange(()=>{this.childrenNodes.push(t)})}insertChildAtIndex(t,r){N.IsNullOrUndefined(t)||(t.trackParentNodeChange(()=>{t.parentNode=this}),this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(r,0,t)}))}moveChild(t,r){let n=this.childrenNodes.indexOf(t);if(n<0)return!1;let i=Math.min(Math.max(0,n+r),this.childrenNodes.length-1);return n!==i&&this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(i,0,this.childrenNodes.splice(n,1)[0])}),!0}getChildren(t){let r=[];for(let n of this.childrenNodes)n.nodeName===t&&r.push(n);return r}getFirstChild(t){for(let r of this.childrenNodes)if(r.nodeName===t)return r;return null}getAllGrandChildren(t){let r=this.getChildren(t),n=null;return r.length===0?new Array:(n=r[0],n.childrenNodes)}deleteChild(t){if(N.IsNullOrUndefined(t))return-1;for(let r=0;r<this.childrenNodes.length;r++)if(this.childrenNodes[r]===t)return this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(r,1)}),r;return-1}deleteAllChildren(){this.trackChildrenCollectionChange(()=>{this.childrenNodes=[]})}getParent(){return this.parentNode}getParentType(){return this.parentNode?this.parentNode.nodeName:T.EmptyString}updateChild(t,r){let n=this.childrenNodes.indexOf(t);return n>-1?(r.trackParentNodeChange(()=>{r.parentNode=this}),this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(n,1,r)}),!0):!1}getAncestor(t){let r=this.getParent(),n=this.getParentType();for(;r;){if(n===t)return r;n=r.getParentType(),r=r.getParent()}return null}deleteFirstGrandChildOfName(t,r){return this.getChildren(t)[0].deleteChild(r)}deleteChildren(t,r){r=N.IsNullOrUndefined(r)?this.childrenNodes.length:r,this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(t,r)})}deleteGrandChildren(t,r,n){this.getChildren(t)[0].deleteChildren(r,n)}addGrandChild(t,r){let n=this.getChildren(t),i=null;n.length===0?(i=new e(t,this),this.addChild(i)):i=n[0],i.addChild(r)}addGrandChildAtIndex(t,r,n){let i=this.getChildren(t),a=null;i.length===0?(a=new e(t,this),this.addChild(a)):a=i[0],a.insertChildAtIndex(r,n)}GetPropertyByParameter(t){return this.getProperty(t)}getSemanticParent(){switch(this.getNodeName()){case v.formCell:let t=this.getAncestor(v.formSection);return t||(t=this.getAncestor(v.formHeader),t)||(t=this.getAncestor(v.formFooter),t)?t:null;case v.formSection:return this.getAncestor(v.formTab);case v.formTab:return this.getAncestor(v.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(v.form);return t?t.changeTracker():null}}});var Ob={};Rr(Ob,{ControlClassId:()=>S,ControlNamePrefixes:()=>Dl,getControlDisplayNames:()=>Zk});function Zk(e){return{[S.AccessPrivilegeControl]:e("controls.controlNames.accessPrivilege"),[S.AccessTeamTablePickerControl]:e("controls.controlNames.accessTeamTablePicker"),[S.ACIControl]:e("controls.controlNames.aci"),[S.ActivitiesContainerControl]:e("controls.controlNames.activitiesContainer"),[S.ActivitiesWallControl]:e("controls.controlNames.activitiesWall"),[S.AppliedFiltersControl]:e("controls.controlNames.appliedFilters"),[S.ArticleContentControl]:e("controls.controlNames.articleContent"),[S.BooleanControl]:e("controls.controlNames.twoOption"),[S.ButtonControl]:e("controls.controlNames.button"),[S.CheckboxControl]:e("controls.controlNames.checkbox"),[S.CompositionLinkControl]:e("controls.controlNames.compositionLink"),[S.ConnectionControl]:e("controls.controlNames.connection"),[S.ConnectionRoleObjectTypeListControl]:e("controls.controlNames.connectionRoleObjectTypeList"),[S.CoverageChoiceControl]:e("controls.controlNames.coverageChoice"),[S.DashboardControl]:e("controls.controlNames.dashboard"),[S.DynamicPropertyListControl]:e("controls.controlNames.dynamicPropertyList"),[S.EditFilterControl]:e("controls.controlNames.editFilter"),[S.ErrorStatusControl]:e("controls.controlNames.errorStatus"),[S.GlobalFilterControl]:e("controls.controlNames.globalFilter"),[S.HiddenInputControl]:e("controls.controlNames.hiddenInput"),[S.KBViewerControl]:e("controls.controlNames.kbViewer"),[S.LabelControl]:e("controls.controlNames.label"),[S.MailMergeLanguagePickerControl]:e("controls.controlNames.mailMergeLanguagePicker"),[S.MapLinkControl]:e("controls.controlNames.mapLink"),[S.OrgInsightsControl]:e("controls.controlNames.orgInsights"),[S.ChoiceLookupControl]:e("controls.controlNames.choiceLookup"),[S.PowerBIControl]:e("controls.controlNames.powerBI"),[S.ProcessControl]:e("controls.controlNames.process"),[S.RelatedInformationControl]:e("controls.controlNames.relatedInformation"),[S.RelationshipRoleChoiceControl]:e("controls.controlNames.relationshipRoleChoice"),[S.ReportControl]:e("controls.controlNames.report"),[S.StreamsControl]:e("controls.controlNames.streams"),[S.WebResourceSilverlightControl]:e("controls.controlNames.webResourceSilverlight"),[S.CurrencyControl]:e("controls.controlNames.currency"),[S.DateTimeControl]:e("controls.controlNames.dateAndTime"),[S.DecimalControl]:e("controls.controlNames.decimal"),[S.DurationControl]:e("controls.controlNames.duration"),[S.EmailAddressControl]:e("controls.controlNames.email"),[S.FileControl]:e("controls.controlNames.file"),[S.FloatingNumberControl]:e("controls.controlNames.floatingNumber"),[S.IframeControl]:e("controls.controlNames.iframe"),[S.ImageControl]:e("controls.controlNames.image"),[S.LookupControl]:e("controls.controlNames.lookup"),[S.MapsControl]:e("controls.controlNames.maps"),[S.PhoneNumberControl]:e("controls.controlNames.phoneNumber"),[S.ChoiceControl]:e("controls.controlNames.choice"),[S.QuickViewControl]:e("controls.controlNames.quickView"),[S.QuickFormControl]:e("controls.controlNames.quickForm"),[S.CustomControl]:e("controls.controlNames.customControl"),[S.SearchWidgetControl]:e("controls.controlNames.searchWidget"),[S.SocialInsightsControl]:e("controls.controlNames.socialInsights"),[S.SubgridControl]:e("controls.controlNames.subgrid"),[S.TextAreaControl]:e("controls.controlNames.textArea"),[S.TextboxControl]:e("controls.controlNames.textBox"),[S.TickerControl]:e("controls.controlNames.ticker"),[S.UrlControl]:e("controls.controlNames.url"),[S.WebResourceHTMLControl]:e("controls.controlNames.webResourceHTML"),[S.WebResourceImageControl]:e("controls.controlNames.webResourceImage"),[S.IntegerControl]:e("controls.controlNames.integer"),[S.TimerControl]:e("controls.controlNames.timer"),[S.TimelineControl]:e("controls.controlNames.timeline"),[S.EmailBodyControl]:e("controls.controlNames.emailBody"),[S.PartyListControl]:e("controls.controlNames.partyList"),[S.TimezoneControl]:e("controls.controlNames.timezone"),[S.LanguageControl]:e("controls.controlNames.language"),[S.ChoiceStatusControl]:e("controls.controlNames.choiceStatus"),[S.ChoicesControl]:e("controls.controlNames.choices"),[S.RegardingControl]:e("controls.controlNames.regarding"),[S.EmailEngagementActionsControl]:e("controls.controlNames.emailEngagementActions"),[S.EmailRecipientActivityControl]:e("controls.controlNames.emailRecipientActivity"),[S.ReferencePanelSearchWidgetControl]:e("controls.controlNames.referencePanelSearchWidget"),[S.ReferencePanelQuickViewControl]:e("controls.controlNames.referencePanelQuickView"),[S.ReferencePanelSubgridControl]:e("controls.controlNames.referencePanelSubgrid"),[S.KBEditorControl]:e("controls.controlNames.KBEditor"),[S.LinkControl]:e("controls.controlNames.link")}}var S,Dl,Hn=I(()=>{"use strict";(function(e){e.AccessPrivilegeControl="F93A31B2-99AC-4084-8EC2-D4027C31369A",e.AccessTeamTablePickerControl="3f4e2a56-f102-4b4d-ab9c-f1574ca5bfda",e.ACIControl="C8BFBBEF-6851-4401-A0CC-7450062FE085",e.ActivitiesContainerControl="C72511AB-84E5-4FB7-A543-25B4FC01E83E",e.ActivitiesWallControl="6636847D-B74D-4994-B55A-A6FAF97ECEA2",e.AppliedFiltersControl="9C310A73-A360-42C5-8943-47A06F1B51EA",e.ArticleContentControl="F02EF977-2564-4B9A-B2F0-DF083D8A019B",e.BooleanControl="67FAC785-CD58-4F9F-ABB3-4B7DDC6ED5ED",e.ButtonControl="00AD73DA-BD4D-49C6-88A8-2F4F4CAD4A20",e.CheckboxControl="B0C6723A-8503-4FD7-BB28-C8A06AC933C2",e.CompositionLinkControl="DB1284EF-9FFC-4E99-B382-0CC082FE2364",e.ConnectionControl="3246F906-1F71-45F7-B11F-D7BE0F9D04C9",e.ConnectionRoleObjectTypeListControl="821ACF1A-7E46-4A0C-965D-FE14A57D78C7",e.CoverageChoiceControl="4168A05C-D857-46AF-8457-5BB47EB04EA1",e.DashboardControl="D2561F53-B292-42D9-B222-478E40FFE29F",e.DynamicPropertyListControl="6896F004-B17A-4202-861E-8B7EA2080E0B",e.EditFilterControl="1479835F-F852-4679-B864-C6892A2844C9",e.ErrorStatusControl="F4C16ECA-CA81-4E39-9448-834B8378721E",e.GlobalFilterControl="FFF0E632-9D7B-4F21-BBC1-05D1567AD144",e.HiddenInputControl="5546E6CD-394C-4BEE-94A8-4425E17EF6C6",e.KBViewerControl="A62B6FA9-169E-406C-B1AA-EAB828CB6026",e.LabelControl="39354E4A-5015-4D74-8031-EA9EB73A1322",e.MailMergeLanguagePickerControl="B634828E-C390-444A-AFE6-E07315D9D970",e.MapLinkControl="91DC0675-C8B9-4421-B1E0-261CEBF02BAC",e.OrgInsightsControl="76b9e25e-695e-4fef-ac69-f05cfa96739c",e.ChoiceLookupControl="2305e33a-bad3-4022-9e15-1856cf218333",e.PowerBIControl="8C54228C-1B25-4909-A12A-F2B968BB0D62",e.ProcessControl="06E9F7AF-1F54-4681-8EEC-1E21A1CEB465",e.RelatedInformationControl="163B90A6-EB64-49D2-9DF8-3C84A4F0A0F8",e.RelationshipRoleChoiceControl="5F986642-5961-4D9F-AB5E-643D71E231E9",e.ReportControl="A28F441B-916C-4865-87FD-0C5D53BD59C9",e.StreamsControl="EE9078C8-6946-4E2C-B8F8-35E65F4BE6A8",e.WebResourceSilverlightControl="080677DB-86EC-4544-AC42-F927E74B491F",e.CurrencyControl="533B9E00-756B-4312-95A0-DC888637AC78",e.CustomControl="F9A8A302-114E-466A-B582-6771B2AE0D92",e.DateTimeControl="5B773807-9FB2-42DB-97C3-7A91EFF8ADFF",e.DecimalControl="C3EFE0C3-0EC6-42BE-8349-CBD9079DFD8E",e.DurationControl="AA987274-CE4E-4271-A803-66164311A958",e.EmailAddressControl="ADA2203E-B4CD-49BE-9DDF-234642B43B52",e.EmailBodyControl="6F3FB987-393B-4D2D-859F-9D0F0349B6AD",e.EmailEngagementActionsControl="F454228D-1D25-4319-E12F-D27968BC0234",e.EmailRecipientActivityControl="26E9760F-7454-40DE-BB07-F6DCCCB82040",e.FileControl="0A7FF475-B016-4687-9CE5-042BFDBD6519",e.FloatingNumberControl="0D2C745A-E5A8-4C8F-BA63-C6D3BB604660",e.IframeControl="FD2A7985-3187-444E-908D-6624B21F69C0",e.ImageControl="7E548B0D-209C-477B-9DCD-F0F44472381D",e.LanguageControl="671A9387-CA5A-4D1E-8AB7-06E39DDCF6B5",e.LookupControl="270BD3DB-D9AF-4782-9025-509E298DEC0A",e.MapsControl="62B0DF79-0464-470F-8AF7-4483CFEA0C7D",e.ChoicesControl="4AA28AB7-9C13-4F57-A73D-AD894D048B5F",e.IntegerControl="C6D124CA-7EDA-4A60-AEA9-7FB8D318B68F",e.PartyListControl="CBFB742C-14E7-4A17-96BB-1A13F7F64AA2",e.PhoneNumberControl="8C10015A-B339-4982-9474-A95FE05631A5",e.ChoiceControl="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE",e.ChoiceStatusControl="5D68B988-0661-4DB2-BC3E-17598AD3BE6C",e.QuickViewControl="5C5600E0-1D6E-4205-A272-BE80DA87FD42",e.QuickFormControl="69AF7DCA-2E3B-4EE7-9201-0DA731DD2413",e.RegardingControl="F3015350-44A2-4AA0-97B5-00166532B5E9",e.SearchWidgetControl="E616A57F-20E0-4534-8662-A101B5DDF4E0",e.SocialInsightsControl="86B9E25E-695E-4FEF-AC69-F05CFA96739C",e.SubgridControl="E7A81278-8635-4D9E-8D4D-59480B391C5B",e.TextAreaControl="E0DECE4B-6FC8-4A8F-A065-082708572369",e.TextboxControl="4273EDBD-AC1D-40D3-9FB2-095C621B552D",e.TickerControl="1E1FC551-F7A8-43AF-AC34-A8DC35C7B6D4",e.TimerControl="9C5CA0A1-AB4D-4781-BE7E-8DFBE867B87E",e.TimelineControl="06375649-C143-495E-A496-C962E5B4488E",e.TimezoneControl="7C624A0B-F59E-493D-9583-638D34759266",e.UrlControl="71716B6C-711E-476C-8AB8-5D11542BFB47",e.WebResourceHTMLControl="9FDF5F91-88B1-47F4-AD53-C11EFC01A01D",e.WebResourceImageControl="587CDF98-C1D5-4BDE-8473-14A0BC7644A7",e.ReferencePanelSearchWidgetControl="7CCD1494-1F7A-4E3A-8BDE-F32069DAEB9F",e.ReferencePanelSubgridControl="02D4264B-47E2-4B4C-AA95-F439F3F4D458",e.ReferencePanelQuickViewControl="B68B05F0-A46D-43F8-843B-917920AF806A",e.KBEditorControl="F94DB24F-263D-44A7-B38E-A35E9854812B",e.LinkControl="DFDF1CDE-837B-4AC9-98CF-AC74361FD89D"})(S||(S={}));Dl={[S.WebResourceHTMLControl]:"WebResource",[S.WebResourceImageControl]:"WebResource",[S.IframeControl]:"IFRAME",[S.SearchWidgetControl]:"Search widget",[S.SubgridControl]:"Subgrid",[S.TimelineControl]:"Timeline",[S.QuickViewControl]:"QuickviewControl"}});var Jn=g((Oj,Fb)=>{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{}}}),Rb=function(){return yo};Object.setPrototypeOf(Rb,yo);Fb.exports=Rb});var dt,zr,xb,Lb,Bi=I(()=>{"use strict";dt="cds-designer-models",zr="FormCustomControl",xb="FormCell",Lb="Form"});var $i,pt,bo=I(()=>{"use strict";$i=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}},pt=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 Qn,Np=I(()=>{"use strict";bo();K();Qn=class e{static lockedFieldCount=new pt;static dependencyFieldCount=new pt;static getNecessaryLookUpTable(t){switch(t){case vr.DependencyFieldTable:return e.dependencyFieldCount;case vr.LockedFieldTable:return e.lockedFieldCount}}static initCanvasLockedFieldLookUp(t){switch(t){case vr.DependencyFieldTable:e.dependencyFieldCount=new pt;case vr.LockedFieldTable:e.lockedFieldCount=new pt}}}});var Il,kb=I(()=>{"use strict";Me();xe();K();He();Il=class extends H{constructor(t){super(v.controlDescription,t)}get forControl(){let t=this.getProperty(f.ForControl);return N.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new P(t))}set forControl(t){this.setProperty(f.ForControl,`{${t.ToString()}}`)}get customControls(){return this.getChildren(v.customControl)}set customControls(t){this.deleteAllChildren();for(let r of t)this.addChild(r)}get DefaultControlClassId(){for(let t of this.customControls)if(!N.IsNullOrUndefined(t.id))return t.id;return null}get DefaultCustomControl(){for(let t of this.customControls)if(!N.IsNullOrUndefined(t.id))return t;return null}get DefaultCustomControls(){let t=[];for(let r of this.customControls)N.IsNullOrUndefined(r.id)||t.push(r);return t}async toJSON(t){let r=await this.getCustomControlsJSON(t);return r?{UniqueId:this.forControl.guidString,CustomControls:r,VersionNumber:0,OverallVersionNumber:0}:null}async getCustomControlsJSON(t){if(this.customControls){let r=[];for(let n of this.customControls){let i=await n.toJSON(t);i&&r.push(i)}return r}return null}}});var Ub,Bb,ft,_,Mb,wn,Xn,qi,Dp,Ip,Vi=I(()=>{"use strict";Ub={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"},Bb={GroupDefinition:"GroupDefinition"},ft={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"})(_||(_={}));(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"})(Mb||(Mb={}));(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"})(Xn||(Xn={}));(function(e){e[e.Bound=0]="Bound",e[e.Input=1]="Input",e[e.Output=2]="Output"})(qi||(qi={}));Dp=[_.LookupCustomer,_.LookupOwner,_.LookupPartyList,_.LookupRegarding,_.LookupSimple],Ip=[_.WholeNone,_.WholeDuration,_.WholeLanguage,_.WholeTimeZone,_.FP,_.Decimal]});function Wr(){return yr||(yr=window._makerConfig,yr&&window?.location?.search?.indexOf("useProductionConfig")>-1&&(yr={...yr,region:"prod",graphQLEndpoint:"https://graph.make.powerapps.com/"}),yr?.region==="prod"&&(yr={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/"}}},...yr}),yr||{aadClientId:"a8f7a65c-f5ba-4859-b2d6-df772c264e9d",location:"cus",region:"test",publicPath:"/",graphQLEndpoint:"https://graph.make.test.powerapps.com/"})}var yr,_l=I(()=>{"use strict";});function $b(e,t,r){if(!e)return Pl.has(e)||(window._ppux?.log?.("PPUX/Geo/NonExistent",{eventType:"Trace",team:"Shell",severity:"Error",errorCode:"GeoIsEmpty"}),Pl.add("")),!1;if(e){if(e=e.toLowerCase(),Pl.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}}),Pl.add(e),!1}return!0}function eM(e){return $b(e,_p,"Location dictionary")?_p[e.toLowerCase()]:"us"}function tM(){let e=Wr().location.toLowerCase();return $b(e,_p,"Current location dictionary")?e:"us"}var Pl,_p,jj,qb=I(()=>{"use strict";_l();Pl=new Set,_p={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"};jj=eM(tM())});var L,Jj,Vb=I(()=>{"use strict";L={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"},Jj={[L.USWest]:{geoName:"us",regionShortName:"wus"},[L.USCentral]:{geoName:"us",regionShortName:"cus"},[L.USEast]:{geoName:"us",regionShortName:"eus"},[L.USEast2]:{geoName:"us",regionShortName:"eus2"},[L.USWestCentral]:{geoName:"us",regionShortName:"wcus"},[L.USWest2]:{geoName:"us",regionShortName:"wus2"},[L.USSouthCentral]:{geoName:"br",regionShortName:"scus"},[L.BrazilSouth]:{geoName:"br",regionShortName:"sbr"},[L.UKSouth]:{geoName:"uk",regionShortName:"suk"},[L.UKWest]:{geoName:"uk",regionShortName:"wuk"},[L.JapanEast]:{geoName:"jp",regionShortName:"ejp"},[L.JapanWest]:{geoName:"jp",regionShortName:"wjp"},[L.IndiaCentral]:{geoName:"in",regionShortName:"cin"},[L.IndiaSouth]:{geoName:"in",regionShortName:"sin"},[L.ItalyNorth]:{geoName:"it",regionShortName:"nit"},[L.GermanyWestCentral]:{geoName:"de",regionShortName:"wcde"},[L.GermanyNorth]:{geoName:"de",regionShortName:"nde"},[L.EuropeNorth]:{geoName:"eu",regionShortName:"neu"},[L.EuropeWest]:{geoName:"eu",regionShortName:"weu"},[L.AustraliaEast]:{geoName:"au",regionShortName:"eau"},[L.AustraliaSouthEast]:{geoName:"au",regionShortName:"seau"},[L.AsiaSouthEast]:{geoName:"as",regionShortName:"seas"},[L.AsiaEast]:{geoName:"as",regionShortName:"eas"},[L.CanadaCentral]:{geoName:"ca",regionShortName:"cca"},[L.CanadaEast]:{geoName:"ca",regionShortName:"eca"},[L.SouthAfricaNorth]:{geoName:"za",regionShortName:"nza"},[L.SouthAfricaWest]:{geoName:"za",regionShortName:"wza"},[L.FranceCentral]:{geoName:"fr",regionShortName:"cfr"},[L.FranceSouth]:{geoName:"fr",regionShortName:"sfr"},[L.UAENorth]:{geoName:"ae",regionShortName:"nae"},[L.UAECentral]:{geoName:"ae",regionShortName:"cae"},[L.SwedenCentral]:{geoName:"se",regionShortName:"cse"},[L.SwitzerlandNorth]:{geoName:"ch",regionShortName:"nch"},[L.SwitzerlandWest]:{geoName:"ch",regionShortName:"wch"},[L.NorwayEast]:{geoName:"no",regionShortName:"eno"},[L.NorwayWest]:{geoName:"no",regionShortName:"wno"},[L.KoreaCentral]:{geoName:"kr",regionShortName:"ckr"},[L.KoreaSouth]:{geoName:"kr",regionShortName:"skr"},[L.SingaporeSouthEast]:{geoName:"sg",regionShortName:"seas"},[L.PolandCentral]:{geoName:"pl",regionShortName:"cpl"},[L.QatarCentral]:{geoName:"qa",regionShortName:"cqa"},[L.NewZealandNorth]:{geoName:"nz",regionShortName:"nnz"},[L.GovernmentUSTexas]:{geoName:"us",regionShortName:"ugtx"},[L.GovernmentUSVirginia]:{geoName:"us",regionShortName:"ugva"},[L.GovernmentUSDodCentral]:{regionShortName:"udc"},[L.GovernmentUSDodEast]:{regionShortName:"ude"},[L.ChinaEast]:{regionShortName:"cne"},[L.ChinaEast2]:{regionShortName:"cne2"},[L.ChinaEast3]:{regionShortName:"cne3"},[L.ChinaNorth]:{regionShortName:"cnn"},[L.ChinaNorth2]:{regionShortName:"cnn2"},[L.ChinaNorth3]:{regionShortName:"cnn3"},[L.UssecEast]:{geoName:"us",regionShortName:"erx"},[L.UssecWest]:{geoName:"us",regionShortName:"wrx"},[L.UsnatEast]:{geoName:"us",regionShortName:"eex"},[L.UsnatWest]:{geoName:"us",regionShortName:"wex"}}});var Gb=I(()=>{"use strict";_l();});var wo=I(()=>{"use strict";_l();qb();Vb();Gb();});function Ao(e,t){return zb?zb.isOverridden(e,t):{overridden:!1}}var zb,Co=I(()=>{"use strict";});var Pp=I(()=>{"use strict";wo();Co();});function rM(e,t){let{region:r}=Wr();return()=>{let n=e.settings[t];if(n.allowOverrides){let s=Ao(e.packageName,t);if(s.overridden)return typeof s.value=="string"?nM(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 nM(e){return isNaN(Number(e))?e==="true"?!0:e==="false"?!1:e:Number(e)}function iM(e){let t=e.packageName;if(Tl.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=>Op(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=>!Rl(i))){let i=`error parsing settings config for package ${t}, setting ${r} has invalid region`;throw console.error(i),new Error(i)}})}function So(e){iM(e);let t={};return Object.keys(e.settings).forEach(r=>{t[r]={enumerable:!0,get:rM(e,r)}}),Tl.set(e.packageName,e),Object.defineProperties({},t)}function Tp(e,t){return Tl.has(e)?!!Tl.get(e).settings[t]:!1}var Tl,Ol=I(()=>{"use strict";wo();Co();Rp();Eo();Tl=new Map});function Wb(e,t){let{region:r}=Wr();return()=>{let n=Ao(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 aM(e){let t=e.packageName;if(Fl.has(t)){let r="feature gates has already been created for this package";throw console.error(r),new Error(r)}if(Object.keys(e.features).some(r=>Tp(t,r))){let r=`error parsing feature gates config for package ${t}, a setting with the same name exists`;throw console.error(r),new Error(r)}Object.keys(e.features).forEach(r=>{if(Object.keys(e.features[r].enabledFor).some(i=>!Rl(i))){let i=`error parsing feature gates config for package ${t}, feature ${r} has invalid region`;throw console.error(i),new Error(i)}})}function Fp(e){aM(e);let t={};Object.keys(e.features).forEach(i=>{t[i]={enumerable:!0,configurable:!0,get:Wb(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:Wb(e,a.toString())}}),Object.defineProperties(r,i),n.clear()}},Fl.set(e.packageName,e),Object.defineProperties(r,t)}function Op(e,t){return Fl.has(e)?!!Fl.get(e).features[t]:!1}var Fl,Rp=I(()=>{"use strict";wo();Eo();Co();Ol();Fl=new Map});var Hb=g((bH,jb)=>{"use strict";jb.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 Xb=g(xp=>{"use strict";var oM=Object.prototype.hasOwnProperty,sM;function Jb(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch{return null}}function Qb(e){try{return encodeURIComponent(e)}catch{return null}}function lM(e){for(var t=/([^=?#&]+)=?([^&]*)/g,r={},n;n=t.exec(e);){var i=Jb(n[1]),a=Jb(n[2]);i===null||a===null||i in r||(r[i]=a)}return r}function uM(e,t){t=t||"";var r=[],n,i;typeof t!="string"&&(t="?");for(i in e)if(oM.call(e,i)){if(n=e[i],!n&&(n===null||n===sM||isNaN(n))&&(n=""),i=Qb(i),n=Qb(n),i===null||n===null)continue;r.push(i+"="+n)}return r.length?t+r.join("&"):""}xp.stringify=uM;xp.parse=lM});var Mp=g((AH,rw)=>{"use strict";var Yb=Hb(),xl=Xb(),Zb=/[\n\r\t]/g,cM=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,dM=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,pM=/^[a-zA-Z]:/,fM=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;function kp(e){return(e||"").toString().replace(fM,"")}var Lp=[["#","hash"],["?","query"],function(t,r){return br(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]],Kb={hash:1,query:1};function ew(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 wr(unescape(e.pathname),{});else if(i==="string"){n=new wr(e,{});for(a in Kb)delete n[a]}else if(i==="object"){for(a in e)a in Kb||(n[a]=e[a]);n.slashes===void 0&&(n.slashes=cM.test(e.href))}return n}function br(e){return e==="file:"||e==="ftp:"||e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function tw(e,t){e=kp(e),e=e.replace(Zb,""),t=t||{};var r=dM.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)):br(n)?s=r[4]:n?i&&(s=s.slice(2)):o>=2&&br(t.protocol)&&(s=r[4]),{protocol:n,slashes:i||br(n),slashesCount:o,rest:s}}function mM(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 wr(e,t,r){if(e=kp(e),e=e.replace(Zb,""),!(this instanceof wr))return new wr(e,t,r);var n,i,a,o,s,l,u=Lp.slice(),c=typeof t,d=this,p=0;for(c!=="object"&&c!=="string"&&(r=t,t=null),r&&typeof r!="function"&&(r=xl.parse),t=ew(t),i=tw(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||pM.test(e))||!i.slashes&&(i.protocol||i.slashesCount<2||!br(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=mM(d.pathname,t.pathname)),d.pathname.charAt(0)!=="/"&&br(d.protocol)&&(d.pathname="/"+d.pathname),Yb(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:"&&br(d.protocol)&&d.host?d.protocol+"//"+d.host:"null",d.href=d.toString()}function hM(e,t,r){var n=this;switch(e){case"query":typeof t=="string"&&t.length&&(t=(r||xl.parse)(t)),n[e]=t;break;case"port":n[e]=t,Yb(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<Lp.length;o++){var s=Lp[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:"&&br(n.protocol)&&n.host?n.protocol+"//"+n.host:"null",n.href=n.toString(),n}function gM(e){(!e||typeof e!="function")&&(e=xl.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||br(r.protocol)?"//":"");return r.username?(a+=r.username,r.password&&(a+=":"+r.password),a+="@"):r.password?(a+=":"+r.password,a+="@"):r.protocol!=="file:"&&br(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}wr.prototype={set:hM,toString:gM};wr.extractProtocol=tw;wr.location=ew;wr.trimLeft=kp;wr.qs=xl;rw.exports=wr});var vM,nw=I(()=>{"use strict";vM=se(Mp());});function Up(e,t,r){let n=Object.keys(r).sort();if(n.length===0)throw new Error(`ECS feature has no properties: ${e}.${t}`);let i=`ecs.${e}.${t}`;return n.length===1?`${i}.${n[0]}`:`${i}.{${n.join(";")}}`}var Ll=I(()=>{"use strict";});var Bp,$p,qp=I(()=>{"use strict";Ll();Bp=class{features=new Map;register(t,r){let n=Up(r,t.teamName,t.fallback),i={clientName:r,teamName:t.teamName,fullName:n,description:t.description,owners:t.owners,ecsURL:t.ecsURL,createdOn:t.createdOn,fallbackConfig:t.fallback,feature:t,displayTeam:t.displayTeam,tags:t.tags,category:t.category};this.features.set(n,i)}getAll(){return Array.from(this.features.values())}get(t){return this.features.get(t)}has(t){return this.features.has(t)}getByClient(t){return this.getAll().filter(r=>r.clientName===t)}getByTeam(t){return this.getAll().filter(r=>r.teamName===t)}search(t){let r=t.toLowerCase();return this.getAll().filter(n=>n.fullName.toLowerCase().includes(r)||n.description?.toLowerCase().includes(r)||n.teamName.toLowerCase().includes(r)||n.clientName.toLowerCase().includes(r))}getClientNames(){let t=new Set;return this.features.forEach(r=>t.add(r.clientName)),Array.from(t)}getTeamNames(){let t=new Set;return this.features.forEach(r=>t.add(r.teamName)),Array.from(t)}clear(){this.features.clear()}},$p=new Bp});var Vp=I(()=>{"use strict";});function Rl(e){return yM.has(e)}var yM,Eo=I(()=>{"use strict";Pp();Rp();Ol();Co();Pp();nw();qp();Ll();Vp();yM=new Set(["tie","test","prod","preview","preprod","gov","high","dod","mooncake","ex","rx"])});var bM,iw=I(()=>{"use strict";Eo();bM=So({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 kl,O,k,Kn,Gi,Ml,aw,ow,Gp,No=I(()=>{"use strict";bo();kl=class{name;constructor(t){this.name=t}toString(){return this.name}getName(){return this.name}getDisplayNameResourceKey(){return Gp.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"})(O||(O={}));(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"})(k||(k={}));Kn=class extends kl{constructor(t){super(t)}static get None(){return"None"}static get SystemRequired(){return"SystemRequired"}static get ApplicationRequired(){return"ApplicationRequired"}static get Recommended(){return"Recommended"}},Gi=class e extends kl{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?Ml.Persistent:parseInt(Ml[this.name])}};(function(e){e[e.Persistent=0]="Persistent",e[e.Calculated=1]="Calculated",e[e.Rollup=2]="Rollup"})(Ml||(Ml={}));(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"})(aw||(aw={}));(function(e){e[e.Attribute=0]="Attribute",e[e.Organization=1]="Organization",e[e.Currency=2]="Currency"})(ow||(ow={}));Gp=class e{static resourceKeyMap=e.initResourceKeyMap();static initResourceKeyMap(){let t=new $i;return t.add(O.TwoOptions,"SystemCustomization.type.bit.label"),t.add(O.Customer,"SystemCustomization.type.customer.label"),t.add(O.CustomerType,"SystemCustomization.type.customer.label"),t.add(O.DateTime,"SystemCustomization.type.datetime.label"),t.add(O.DecimalNumber,"SystemCustomization.type.decimal.label"),t.add(O.FloatingPointNumber,"SystemCustomization.type.float.label"),t.add(O.WholeNumber,"SystemCustomization.type.int.label"),t.add(O.LookupType,"SystemCustomization.type.lookup.label"),t.add(O.Lookup,"SystemCustomization.type.lookup.label"),t.add(O.MultipleLineofText,"SystemCustomization.type.ntext.label"),t.add(O.Currency,"SystemCustomization.type.money.label"),t.add(O.Owner,"SystemCustomization.type.owner.label"),t.add(O.OwnerType,"SystemCustomization.type.owner.label"),t.add(O.PartyList,"SystemCustomization.type.partylist.label"),t.add(O.PartyListType,"SystemCustomization.type.partylist.label"),t.add(O.OptionSet,"SystemCustomization.type.picklist.label"),t.add(O.State,"SystemCustomization.type.state.label"),t.add(O.Status,"SystemCustomization.type.status.label"),t.add(O.SingleLineofText,"SystemCustomization.type.nvarchar.label"),t.add(O.UniqueIdentifier,"SystemCustomization.type.uniqueidentifier.label"),t.add(O.UniqueIdentifierType,"SystemCustomization.type.uniqueidentifiertype.label"),t.add(O.CalendarRulesType,"SystemCustomization.type.calendarrules.label"),t.add(O.VirtualType,"SystemCustomization.type.virtual.label"),t.add(O.BigInt,"SystemCustomization.type.bigint.label"),t.add(O.ManagedPropertyType,"SystemCustomization.type.managedproperty.label"),t.add(O.EntityNameType,"SystemCustomization.type.entityname.label"),t.add(O.Image,"SystemCustomization.type.image.label"),t.add(O.MultiSelectOptionSet,"SystemCustomization.type.multiselectpicklist.label"),t.add(O.PrimaryNameAttributeType,"SystemCustomization.type.primaryname.label"),t.add(O.LookupType,"SystemCustomization.type.lookuptype.label"),t.add(O.Subject,"SystemCustomization.type.subject.label"),t.add(k.Email,"SystemCustomization.String.Format.email"),t.add(k.Text,"SystemCustomization.String.Format.text"),t.add(k.TextArea,"SystemCustomization.String.Format.textarea"),t.add(k.Url,"SystemCustomization.String.Format.url"),t.add(k.TickerSymbol,"SystemCustomization.String.Format.tickersymbol"),t.add(k.PhoneticGuide,"SystemCustomization.String.Format.phoneticguide"),t.add(k.VersionNumber,"SystemCustomization.String.Format.versionnumber"),t.add(k.Phone,"SystemCustomization.String.Format.phone"),t.add(k.None,"SystemCustomization.Integer.Format."),t.add(k.Duration,"SystemCustomization.Integer.Format.duration"),t.add(k.TimeZone,"SystemCustomization.Integer.Format.timezone"),t.add(k.Language,"SystemCustomization.Integer.Format.language"),t.add(k.Locale,"SystemCustomization.Integer.Format.language"),t.add(k.DateOnly,"SystemCustomization.DateTime.Format.date"),t.add(k.DateAndTime,"SystemCustomization.DateTime.Format.datetime"),t.add(k.Regarding,"SystemCustomization.Lookup.Format.regarding"),t.add(Gi.Persistent,"SystemCustomization.String.Source.persistent"),t.add(Gi.Calculated,"SystemCustomization.String.Source.calculated"),t.add(Gi.Rollup,"SystemCustomization.String.Source.rollup"),t.add(Gi.None,"SystemCustomization.String.Source.none"),t}static getDisplayNameResourceKey(t){return e.resourceKeyMap.getValue(t)}}});var cw,Wp,zi,Yn,zp,Ul,Wi,jr,be,sw,lw,uw,rr=I(()=>{"use strict";cw={ThreeEqColumn_FirstColumn:34,ThreeEqColumn_SecondColumn:33,ThreeEqColumn_ThirdColumn:33,FiveEqColumn:20},Wp={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"})(zi||(zi={}));(function(e){e.Left="Left",e.Right="Right",e.Center="Center"})(Yn||(Yn={}));(function(e){e[e.Mobile=0]="Mobile",e[e.Tablet=1]="Tablet",e[e.Web=2]="Web"})(zp||(zp={}));Ul=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"})(Wi||(Wi={}));jr=class{static StartTag="<"},be={ShowLabel:"true",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_",labelAlignment:Yn.Left,labelPosition:Wi.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"})(sw||(sw={}));(function(e){e.TabWithLockedFieldRemoval="TabWithLockedFieldRemoval",e.SectionWithLockedFieldRemoval="SectionWithLockedFieldRemoval",e.LockedSectionRemoval="LockedSectionRemoval",e.LockedFieldRemoval="LockedFieldRemoval",e.RequiredFieldRemoval="RequiredFieldRemoval",e.LastRemainingTab="LastRemainingTab",e.UnknownRemoval="UnknownRemoval"})(lw||(lw={}));(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"})(uw||(uw={}))});var jp,dw=I(()=>{"use strict";(function(e){e.DefaultValue="defaultValue",e.Loaded="loaded"})(jp||(jp={}))});var mw,wM,pw,bJ,wJ,Do,fw,AJ,CJ,hw=I(()=>{"use strict";mw=se(Jn());xe();Bi();iw();No();rr();Vi();K();wM=se(Mn());dw();(function(e){e.Model="Model",e.Canvas="Canvas",e.CustomPages="CustomPages"})(pw||(pw={}));bJ={Read:Xn.Read,Edit:Xn.Edit,Both:Xn.Both,Container:Xn.Container},wJ={input:qi.Input,bound:qi.Bound,output:qi.Output};(function(e){e[e.dataset=0]="dataset",e[e.property=1]="property",e[e.groups=2]="groups",e[e.group=3]="group"})(Do||(Do={}));(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"})(fw||(fw={}));AJ=new Set([_.Currency,_.Decimal,_.FP,_.Multiple,_.SingleLineEmail,_.SingleLinePhone,_.SingleLineText,_.SingleLineTextArea,_.SingleLineURL,_.SingleLineTickerSymbol,_.WholeNone,_.WholeDuration,_.WholeLanguage,_.WholeTimeZone,_.Enum,_.LookupSimple,_.LookupCustomer,_.LookupOwner,_.LookupPartyList,_.LookupRegarding,_.TwoOptions,_.Boolean,_.PowerBIReport,_.DateAndTimeDateAndTime,_.DateAndTimeDateOnly,_.OptionSet,_.MultiSelectOptionSet,_.CardForm]),CJ={numbers:[_.WholeNone,_.FP,_.Decimal,_.Currency],text:[_.SingleLineText,_.SingleLineTextArea,_.Multiple],lookup:[_.LookupSimple,_.LookupCustomer,_.LookupOwner,_.LookupPartyList,_.LookupRegarding],dates:[_.DateAndTimeDateOnly,_.DateAndTimeDateAndTime],allFields:[_.TwoOptions,_.DateAndTimeDateOnly,_.DateAndTimeDateAndTime,_.FP,_.Decimal,_.WholeNone,_.WholeDuration,_.WholeTimeZone,_.WholeLanguage,_.LookupSimple,_.LookupCustomer,_.LookupOwner,_.LookupPartyList,_.LookupRegarding,_.Multiple,_.OptionSet,_.SingleLineText,_.SingleLineTextArea,_.SingleLineEmail,_.SingleLineURL,_.SingleLineTickerSymbol,_.SingleLinePhone]}});var nr,Bl,gw=I(()=>{"use strict";nr=se(Jn());Me();xe();ot();Bi();Vi();hw();No();K();He();rr();Bl=class extends H{constructor(t){super(v.customControl,t)}customControlId;get id(){let t=this.getProperty(f.id);return N.IsNullOrUndefined(t)?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new P(t.substr(1,t.length-2)):new P(t)}getParameters(){let t=new Map,r=this.getAllChildren();if(r&&r.length!==0&&r[0]){let n=r[0].getAllChildren();if(n!=null){for(let i of n)if(i&&i.getAllChildren().length>0){let a=i.getNodeName();t.get(a)?t.get(a).push(i):t.set(a,[i])}}}return t}getFormComponentValueByParameterName(t){let r=this.getParameters()?.get(ft.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===ft.name)?.value}getParameterChildrenValues(t,r,n){if(this.isDataSet(t)){let i=r.find(u=>u.key===ft.name)?.value,a={Name:i,Type:_.Grid,Columns:[]},l=this.getParameters().get(ft.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===f.static&&a.value==="true"){r=!0;break}}return r}get name(){return this.getProperty(f.Name)}get formFactor(){return this.getProperty(f.formFactor)}set formFactor(t){this.setProperty(f.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(jr.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:Bb.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===Do.dataset?a.get(ft.dataset)?.some(m=>this.getDatasetName(m)===d)||r.push({Name:d,Value:{Name:d,Columns:[],Type:_.Grid}}):c.propertyType===Do.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,nr.trackInfoTrace)(dt,{eventName:`${zr}/parametersToJSON`,eventData:{message:`Configuration metadata for custom control parameter ${o} is not available for custom control : ${this.name}.`}}),r=[];break}}}else(0,nr.trackErrorTrace)(dt,{eventName:`${zr}/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,nr.trackErrorTrace)(dt,{eventName:`${zr}/parametersToJSON`,eventData:{message:"Custom Control Manifest not found"}},new Error(`No custom control manifest found for ${this.name}`))}catch(n){(0,nr.trackErrorTrace)(dt,{eventName:`${zr}/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===ft.name)?.value;if(a)return this.getParameterChildrenValues(t,r);{let s=new Error(`No dataset manifest info for ${o}`);(0,nr.trackErrorTrace)(dt,{eventName:`${zr}/parameterJSON`,eventData:{message:"Missing custom control manifest dataset info"}},s)}}else{let a=n,o=r&&r.find(l=>l.key===f.Type),s=a&&!a.ofTypeGroup.every(l=>!Dp.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(f.bindAttribute),p=await i.formModelService.loadLookupModel(d),m=p.lookupColumn,h=this.getLookupDataTypeFromAttributeMetadata(m);return{Name:t,Type:h,Usage:l,Static:u,Primary:c,EntityName:p.primaryTableName,Value:d,ViewId:this.getFormComponentValueByParameterName(Ub.DefaultViewId),TargetEntityType:m.targets[0],FilterRelationshipName:this.getFormComponentValueByParameterName(f.FilterRelationshipName),AvailableViewIds:this.getFormComponentValueByParameterName(f.AvailableViewIds),DependentAttributeName:this.getFormComponentValueByParameterName(f.DependentAttributeName),DependentAttributeType:this.getFormComponentValueByParameterName(f.DependentAttributeType),AllowFilterOff:T.IsStrictTrue(this.getFormComponentValueByParameterName(f.AllowFilterOff)),DisableQuickFind:T.IsStrictTrue(this.getFormComponentValueByParameterName(f.DisableQuickFind)),EnableViewPicker:!T.IsStrictTrue(this.getFormComponentValueByParameterName(f.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,nr.trackErrorTrace)(dt,{eventName:`${zr}/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 m=o.value;return{Type:m,Static:u,Usage:l,Value:this.isNumberTypeProperty(a,m)&&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,nr.trackErrorTrace)(dt,{eventName:`${zr}/parameterJSON`,eventData:{message:"Missing property type info"}},p)}else{let l=new Error(`No property manifest info for ${t}`);(0,nr.trackWarningTrace)(dt,{eventName:`${zr}/parameterJSON`,eventData:{message:"Missing custom control manifest property info"}},l)}}return null}getLookupDataTypeFromAttributeMetadata(t){let{attributeType:r,format:n}=t;switch(r){case O.Customer:return _.LookupCustomer;case O.Owner:return _.LookupOwner;case O.PartyList:return _.LookupPartyList;default:return n===k.Regarding?_.LookupRegarding:_.LookupSimple}}isLookupType(t){return Dp.includes(t)}isNumberTypeProperty(t,r){return Ip.includes(r)||t.ofTypeGroup.some(n=>Ip.includes(n))}isDataSet(t){return ft.dataset===t}isGroups(t){return!!t[0].getAllProperties().find(n=>n.key==="isGroup"&&n.value==="true")}}});var V,Hp=I(()=>{"use strict";V=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 R,ji,Be,$l=I(()=>{"use strict";Me();bo();xe();ot();No();Hn();Hp();rr();R=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"}},ji=class{static get RelationshipAssistant(){return"3ff9a528-dd50-4aca-8f10-2e5ed73513ad"}static get PredictiveLeadScoring(){return"6f503f2a-d033-4106-b62c-f8f2e5f01a57"}},Be=class e{static FieldControlIds=e.initializeFieldControls();static UnboundControlIds=e.initializeUnboundControls();static ControlsAllowedForReferencePanel=e.initializeReferencePanelControls();static ControlsAllowedForFooter=e.initializeFooterControls();static CustomControlIdMap=new pt;static initializeFieldControls(){let t=new pt,r=e.getControlName(O.SingleLineofText,k.Phone);t.add(r,new P(R.PhoneNumberControl));let n=e.getControlName(O.SingleLineofText,k.TextArea);t.add(n,new P(R.TextAreaControl));let i=e.getControlName(O.SingleLineofText,k.Text);t.add(i,new P(R.TextBoxControl));let a=e.getControlName(O.SingleLineofText,k.Email);t.add(a,new P(R.EmailAddressControl));let o=e.getControlName(O.SingleLineofText,k.Url);t.add(o,new P(R.UrlControl));let s=e.getControlName(O.SingleLineofText,k.TickerSymbol);t.add(s,new P(R.TickerControl));let l=e.getControlName(O.SingleLineofText,k.PhoneticGuide);t.add(l,new P(R.TextBoxControl));let u=e.getControlName(O.WholeNumber,k.Duration);t.add(u,new P(R.DurationControl));let c=e.getControlName(O.WholeNumber,k.Language);t.add(c,new P(R.LanguagePickerControl));let d=e.getControlName(O.WholeNumber,k.TimeZone);t.add(d,new P(R.TimeZonePicklistControl));let p=e.getControlName(O.WholeNumber,k.None);t.add(p,new P(R.IntegerControl));let m=e.getControlName(O.DateTime,k.DateOnly);t.add(m,new P(R.DateTimeControl));let h=e.getControlName(O.DateTime,k.DateAndTime);t.add(h,new P(R.DateTimeControl));let w=e.getControlName(O.LookupType,k.None);t.add(w,new P(R.LookupControl));let b=e.getControlName(O.CustomerType,k.None);t.add(b,new P(R.LookupControl));let E=e.getControlName(O.FloatingPointNumber,k.None);t.add(E,new P(R.FloatControl));let D=e.getControlName(O.DecimalNumber,k.None);t.add(D,new P(R.DecimalControl));let F=e.getControlName(O.Currency,k.None);t.add(F,new P(R.MoneyControl));let x=e.getControlName(O.MultipleLineofText,k.None);t.add(x,new P(R.TextAreaControl));let q=e.getControlName(O.MultipleLineofText,k.Text);t.add(q,new P(R.TextAreaControl));let G=e.getControlName(O.MultipleLineofText,k.TextArea);t.add(G,new P(R.TextAreaControl));let M=e.getControlName(O.MultipleLineofText,k.Email);t.add(M,new P(R.EmailBodyControl));let U=e.getControlName(O.OptionSet,k.None);t.add(U,new P(R.PicklistControl));let B=e.getControlName(O.TwoOptions,k.None);t.add(B,new P(R.RadioControl));let W=e.getControlName(O.Image,k.None);t.add(W,new P(R.WebResourceImageControl));let $=e.getControlName(O.Image,k.None);t.add($,new P(R.WebResourceHtmlControl));let Se=e.getControlName(O.TwoOptions,"Radio");t.add(Se,new P(R.RadioControl));let ve=e.getControlName(O.TwoOptions,"CheckBox");t.add(ve,new P(R.CheckBoxControl));let Ve=e.getControlName(O.TwoOptions,"List");t.add(Ve,new P(R.PicklistControl));let Ke=e.getControlName(O.State,k.None);t.add(Ke,new P(R.PicklistControl));let de=e.getControlName(O.Status,k.None);t.add(de,new P(R.PicklistStatusControl));let gt=e.getControlName(O.OwnerType,k.None);t.add(gt,new P(R.LookupControl));let oc=e.getControlName(O.PartyListType,k.None);t.add(oc,new P(R.PartyListControl));let nP=e.getControlName(O.LookupType,k.Regarding);t.add(nP,new P(R.RegardingControl));let iP=e.getControlName(O.MultiSelectOptionSet,k.None);return t.add(iP,new P(R.ChoicesControl)),t}static getControlName(t,r){return t+"_"+r}static getControlIdByTypeAndFormat(t,r){let n=e.getControlName(t.toString(),r.toString());return e.FieldControlIds.containsKey(n)?e.FieldControlIds.getValue(n):null}static getTypeAndFormatByControlOrUniqueId(t){for(let r in e.FieldControlIds.getKeys())if(e.FieldControlIds.getValue(e.FieldControlIds.getKeys()[r]).guidString.toLowerCase()===t)return e.FieldControlIds.getKeys()[r]}static getControlDataTypeByControlOrUniqueId(t){if(!N.IsNullOrEmptyGuid(t)){let r=e.getTypeAndFormatByControlOrUniqueId(t.guidString.toLowerCase());return r=N.IsNullOrUndefined(r)?e.getUnboundControlNameFromIdentifier(t):r.substring(0,r.indexOf("_")),r}return null}static isCustomControl(t){return N.IsNullOrUndefined(t.control)||N.IsNullOrUndefined(t.control.ClassId)||t.control.ClassId.guidString===R.CustomControl}static initializeUnboundControls(){let t=new pt;return t.add(R.ACIControl,V.ACIControl),t.add(R.IframeControl,V.IframeControl),t.add(R.SearchWidgetControl,V.SearchWidgetControl),t.add(R.MapsControl,V.MapsControl),t.add(R.QuickFormCollectionControl,V.QuickFormCollectionControl),t.add(R.GridControl,V.SubGridControl),t.add(R.WebResourceImageControl,V.WebResourceImageControl),t.add(R.WebResourceHtmlControl,V.WebResourceHtmlControl),t.add(R.ReferencePanelSearchWidget,V.SearchWidgetControl),t.add(R.ReferencePanelQuickFormCollectionControl,V.QuickFormCollectionControl),t.add(R.ReferencePanelSubgridControl,V.SubGridControl),t.add(R.TimerControl,V.TimerControl),t.add(R.TimeLineControl,V.NotesControl),t.add(R.TimeLineControlUC,V.NotesControl),t.add(R.SocialInsightControl,V.SocialInsightControl),t.add(ji.RelationshipAssistant,V.CustomControl),t}static initializeReferencePanelControls(){let t=new pt;return t.add(R.IframeControl,V.IframeControl),t.add(R.ReferencePanelSearchWidget,V.SearchWidgetControl),t.add(R.ReferencePanelQuickFormCollectionControl,V.QuickFormCollectionControl),t.add(R.ReferencePanelSubgridControl,V.SubGridControl),t.add(R.WebResourceHtmlControl,V.WebResourceHtmlControl),t.add(R.WebResourceImageControl,V.WebResourceHtmlControl),t}static initializeFooterControls(){let t=new $i;return t.add(zi.IFRAME,!0),t.add(zi.SPACER,!0),t.add(zi.WEB_RESOURCE_HTML,!0),t}static isUnboundFormControl(t){if(N.IsNullOrUndefined(t)||N.IsNullOrUndefined(t.control)||N.IsNullOrUndefined(t.control.ClassId))return!1;let r=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.containsKey(r.guidString)}static isReferencePanelSection(t){return!N.IsNullOrUndefined(t)&&!N.IsNullOrUndefined(t.Name)&&t.Name.indexOf(be.referencePanelNamePrefix)===0}static isUnboundFormControlByIdentifier(t){return N.IsNullOrUndefined(t)||N.IsNullOrUndefined(t.guidString)?!1:e.UnboundControlIds.containsKey(t.guidString)}static getUnboundFormControlName(t){let r=T.EmptyString;if(N.IsNullOrUndefined(t)||N.IsNullOrUndefined(t.control)||N.IsNullOrUndefined(t.control.ClassId))return r;let n=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.getValue(n.guidString).toString()}static getUnboundControlNameFromIdentifier(t){return N.IsNullOrUndefined(t)||N.IsNullOrUndefined(t.guidString)?T.EmptyString:e.UnboundControlIds.getValue(t.guidString).toString()}static isSpacerControl(t){return t===R.SpacerControl}static GetRowSpan(t){let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===R.CustomControl&&!N.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}switch(e.UnboundControlIds.getValue(r.guidString)){case V.IframeControl:case V.ACIControl:case V.SocialInsightControl:return 6;case V.SubGridControl:case V.CustomControl:return 4;case V.WebResourceImageControl:return 15;case V.WebResourceHtmlControl:return 15;case V.MapsControl:return 8;case V.SearchWidgetControl:return 10;case V.NotesControl:case V.TimeLineControl:return 15;case V.TimerControl:return 2;default:}}static isLookUpControl(t){return!N.IsNullOrUndefined(t)&&t.ClassId.guidString===R.LookupControl}static isRelationshipAssistantOrLeadScoringControl(t){return!N.IsNullOrUndefined(t)&&e.isRelationshipAssistantOrLeadScoring(t.UniqueId)}static isRelationshipAssistantOrLeadScoring(t){return!N.IsNullOrUndefined(t)&&(t.guidString===ji.RelationshipAssistant||t.guidString===ji.PredictiveLeadScoring)}static isRelationshipAssistantControl(t){return!N.IsNullOrUndefined(t)&&e.isRelationshipAssistant(t.UniqueId)}static isRelationshipAssistant(t){return!N.IsNullOrUndefined(t)&&t.guidString===ji.RelationshipAssistant}static getUniqueIdentifierForControl(t){if(N.IsNullOrUndefined(t))return null;let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===R.CustomControl&&!N.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}return r}}});var ql,vw=I(()=>{"use strict";ql=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 Zn,Hi,yw,bw,An,ww,Aw,Jp=I(()=>{"use strict";(function(e){e[e.Center=0]="Center",e[e.Left=1]="Left",e[e.Right=2]="Right"})(Zn||(Zn={}));(function(e){e[e.Left=0]="Left",e[e.Top=1]="Top"})(Hi||(Hi={}));(function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle"})(yw||(yw={}));(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"})(bw||(bw={}));(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"})(An||(An={}));(function(e){e[e.None=0]="None",e[e.SystemRequired=1]="SystemRequired",e[e.ApplicationRequired=2]="ApplicationRequired",e[e.Recommended=3]="Recommended"})(ww||(ww={}));(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"})(Aw||(Aw={}))});var Ji,Cw=I(()=>{"use strict";Eo();Ji=Fp({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 Sw(e){return{...e,extractConfig:t=>AM(t,Object.keys(e.fallback))}}function AM(e,t){let r={};for(let n of t)typeof e[n]<"u"&&(r[n]=e[n]);return r}var Qp=I(()=>{"use strict";});var Xp=g((XJ,Nw)=>{var Io=new Proxy(function(){return Io},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Io},apply:function(){return Io},construct:function(){return{}}}),Ew=function(){return Io};Object.setPrototypeOf(Ew,Io);Nw.exports=Ew});var _w=g((KJ,Iw)=>{var _o=new Proxy(function(){return _o},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:_o},apply:function(){return _o},construct:function(){return{}}}),Dw=function(){return _o};Object.setPrototypeOf(Dw,_o);Iw.exports=Dw});var Kp=g((YJ,Tw)=>{var Po=new Proxy(function(){return Po},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Po},apply:function(){return Po},construct:function(){return{}}}),Pw=function(){return Po};Object.setPrototypeOf(Pw,Po);Tw.exports=Pw});var Rw=g((ZJ,Ow)=>{function CM(){this.__data__=[],this.size=0}Ow.exports=CM});var Qi=g((eQ,Fw)=>{function SM(e,t){return e===t||e!==e&&t!==t}Fw.exports=SM});var To=g((tQ,xw)=>{var EM=Qi();function NM(e,t){for(var r=e.length;r--;)if(EM(e[r][0],t))return r;return-1}xw.exports=NM});var kw=g((rQ,Lw)=>{var DM=To(),IM=Array.prototype,_M=IM.splice;function PM(e){var t=this.__data__,r=DM(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():_M.call(t,r,1),--this.size,!0}Lw.exports=PM});var Uw=g((nQ,Mw)=>{var TM=To();function OM(e){var t=this.__data__,r=TM(t,e);return r<0?void 0:t[r][1]}Mw.exports=OM});var $w=g((iQ,Bw)=>{var RM=To();function FM(e){return RM(this.__data__,e)>-1}Bw.exports=FM});var Vw=g((aQ,qw)=>{var xM=To();function LM(e,t){var r=this.__data__,n=xM(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}qw.exports=LM});var Oo=g((oQ,Gw)=>{var kM=Rw(),MM=kw(),UM=Uw(),BM=$w(),$M=Vw();function Xi(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])}}Xi.prototype.clear=kM;Xi.prototype.delete=MM;Xi.prototype.get=UM;Xi.prototype.has=BM;Xi.prototype.set=$M;Gw.exports=Xi});var Ww=g((sQ,zw)=>{var qM=Oo();function VM(){this.__data__=new qM,this.size=0}zw.exports=VM});var Hw=g((lQ,jw)=>{function GM(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}jw.exports=GM});var Qw=g((uQ,Jw)=>{function zM(e){return this.__data__.get(e)}Jw.exports=zM});var Kw=g((cQ,Xw)=>{function WM(e){return this.__data__.has(e)}Xw.exports=WM});var Yp=g((dQ,Yw)=>{var jM=typeof global=="object"&&global&&global.Object===Object&&global;Yw.exports=jM});var ir=g((pQ,Zw)=>{var HM=Yp(),JM=typeof self=="object"&&self&&self.Object===Object&&self,QM=HM||JM||Function("return this")();Zw.exports=QM});var Ro=g((fQ,eA)=>{var XM=ir(),KM=XM.Symbol;eA.exports=KM});var iA=g((mQ,nA)=>{var tA=Ro(),rA=Object.prototype,YM=rA.hasOwnProperty,ZM=rA.toString,Fo=tA?tA.toStringTag:void 0;function eU(e){var t=YM.call(e,Fo),r=e[Fo];try{e[Fo]=void 0;var n=!0}catch{}var i=ZM.call(e);return n&&(t?e[Fo]=r:delete e[Fo]),i}nA.exports=eU});var oA=g((hQ,aA)=>{var tU=Object.prototype,rU=tU.toString;function nU(e){return rU.call(e)}aA.exports=nU});var ei=g((gQ,uA)=>{var sA=Ro(),iU=iA(),aU=oA(),oU="[object Null]",sU="[object Undefined]",lA=sA?sA.toStringTag:void 0;function lU(e){return e==null?e===void 0?sU:oU:lA&&lA in Object(e)?iU(e):aU(e)}uA.exports=lU});var Hr=g((vQ,cA)=>{function uU(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}cA.exports=uU});var Vl=g((yQ,dA)=>{var cU=ei(),dU=Hr(),pU="[object AsyncFunction]",fU="[object Function]",mU="[object GeneratorFunction]",hU="[object Proxy]";function gU(e){if(!dU(e))return!1;var t=cU(e);return t==fU||t==mU||t==pU||t==hU}dA.exports=gU});var fA=g((bQ,pA)=>{var vU=ir(),yU=vU["__core-js_shared__"];pA.exports=yU});var gA=g((wQ,hA)=>{var Zp=fA(),mA=(function(){var e=/[^.]+$/.exec(Zp&&Zp.keys&&Zp.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function bU(e){return!!mA&&mA in e}hA.exports=bU});var ef=g((AQ,vA)=>{var wU=Function.prototype,AU=wU.toString;function CU(e){if(e!=null){try{return AU.call(e)}catch{}try{return e+""}catch{}}return""}vA.exports=CU});var bA=g((CQ,yA)=>{var SU=Vl(),EU=gA(),NU=Hr(),DU=ef(),IU=/[\\^$.*+?()[\]{}|]/g,_U=/^\[object .+?Constructor\]$/,PU=Function.prototype,TU=Object.prototype,OU=PU.toString,RU=TU.hasOwnProperty,FU=RegExp("^"+OU.call(RU).replace(IU,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function xU(e){if(!NU(e)||EU(e))return!1;var t=SU(e)?FU:_U;return t.test(DU(e))}yA.exports=xU});var AA=g((SQ,wA)=>{function LU(e,t){return e?.[t]}wA.exports=LU});var Cn=g((EQ,CA)=>{var kU=bA(),MU=AA();function UU(e,t){var r=MU(e,t);return kU(r)?r:void 0}CA.exports=UU});var Gl=g((NQ,SA)=>{var BU=Cn(),$U=ir(),qU=BU($U,"Map");SA.exports=qU});var xo=g((DQ,EA)=>{var VU=Cn(),GU=VU(Object,"create");EA.exports=GU});var IA=g((IQ,DA)=>{var NA=xo();function zU(){this.__data__=NA?NA(null):{},this.size=0}DA.exports=zU});var PA=g((_Q,_A)=>{function WU(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}_A.exports=WU});var OA=g((PQ,TA)=>{var jU=xo(),HU="__lodash_hash_undefined__",JU=Object.prototype,QU=JU.hasOwnProperty;function XU(e){var t=this.__data__;if(jU){var r=t[e];return r===HU?void 0:r}return QU.call(t,e)?t[e]:void 0}TA.exports=XU});var FA=g((TQ,RA)=>{var KU=xo(),YU=Object.prototype,ZU=YU.hasOwnProperty;function eB(e){var t=this.__data__;return KU?t[e]!==void 0:ZU.call(t,e)}RA.exports=eB});var LA=g((OQ,xA)=>{var tB=xo(),rB="__lodash_hash_undefined__";function nB(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=tB&&t===void 0?rB:t,this}xA.exports=nB});var MA=g((RQ,kA)=>{var iB=IA(),aB=PA(),oB=OA(),sB=FA(),lB=LA();function Ki(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])}}Ki.prototype.clear=iB;Ki.prototype.delete=aB;Ki.prototype.get=oB;Ki.prototype.has=sB;Ki.prototype.set=lB;kA.exports=Ki});var $A=g((FQ,BA)=>{var UA=MA(),uB=Oo(),cB=Gl();function dB(){this.size=0,this.__data__={hash:new UA,map:new(cB||uB),string:new UA}}BA.exports=dB});var VA=g((xQ,qA)=>{function pB(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}qA.exports=pB});var Lo=g((LQ,GA)=>{var fB=VA();function mB(e,t){var r=e.__data__;return fB(t)?r[typeof t=="string"?"string":"hash"]:r.map}GA.exports=mB});var WA=g((kQ,zA)=>{var hB=Lo();function gB(e){var t=hB(this,e).delete(e);return this.size-=t?1:0,t}zA.exports=gB});var HA=g((MQ,jA)=>{var vB=Lo();function yB(e){return vB(this,e).get(e)}jA.exports=yB});var QA=g((UQ,JA)=>{var bB=Lo();function wB(e){return bB(this,e).has(e)}JA.exports=wB});var KA=g((BQ,XA)=>{var AB=Lo();function CB(e,t){var r=AB(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}XA.exports=CB});var zl=g(($Q,YA)=>{var SB=$A(),EB=WA(),NB=HA(),DB=QA(),IB=KA();function Yi(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])}}Yi.prototype.clear=SB;Yi.prototype.delete=EB;Yi.prototype.get=NB;Yi.prototype.has=DB;Yi.prototype.set=IB;YA.exports=Yi});var eC=g((qQ,ZA)=>{var _B=Oo(),PB=Gl(),TB=zl(),OB=200;function RB(e,t){var r=this.__data__;if(r instanceof _B){var n=r.__data__;if(!PB||n.length<OB-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new TB(n)}return r.set(e,t),this.size=r.size,this}ZA.exports=RB});var tf=g((VQ,tC)=>{var FB=Oo(),xB=Ww(),LB=Hw(),kB=Qw(),MB=Kw(),UB=eC();function Zi(e){var t=this.__data__=new FB(e);this.size=t.size}Zi.prototype.clear=xB;Zi.prototype.delete=LB;Zi.prototype.get=kB;Zi.prototype.has=MB;Zi.prototype.set=UB;tC.exports=Zi});var nC=g((GQ,rC)=>{var BB="__lodash_hash_undefined__";function $B(e){return this.__data__.set(e,BB),this}rC.exports=$B});var aC=g((zQ,iC)=>{function qB(e){return this.__data__.has(e)}iC.exports=qB});var sC=g((WQ,oC)=>{var VB=zl(),GB=nC(),zB=aC();function Wl(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new VB;++t<r;)this.add(e[t])}Wl.prototype.add=Wl.prototype.push=GB;Wl.prototype.has=zB;oC.exports=Wl});var uC=g((jQ,lC)=>{function WB(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}lC.exports=WB});var dC=g((HQ,cC)=>{function jB(e,t){return e.has(t)}cC.exports=jB});var rf=g((JQ,pC)=>{var HB=sC(),JB=uC(),QB=dC(),XB=1,KB=2;function YB(e,t,r,n,i,a){var o=r&XB,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,m=r&KB?new HB:void 0;for(a.set(e,t),a.set(t,e);++d<s;){var h=e[d],w=t[d];if(n)var b=o?n(w,h,d,t,e,a):n(h,w,d,e,t,a);if(b!==void 0){if(b)continue;p=!1;break}if(m){if(!JB(t,function(E,D){if(!QB(m,D)&&(h===E||i(h,E,r,n,a)))return m.push(D)})){p=!1;break}}else if(!(h===w||i(h,w,r,n,a))){p=!1;break}}return a.delete(e),a.delete(t),p}pC.exports=YB});var nf=g((QQ,fC)=>{var ZB=ir(),e$=ZB.Uint8Array;fC.exports=e$});var hC=g((XQ,mC)=>{function t$(e){var t=-1,r=Array(e.size);return e.forEach(function(n,i){r[++t]=[i,n]}),r}mC.exports=t$});var vC=g((KQ,gC)=>{function r$(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n}),r}gC.exports=r$});var CC=g((YQ,AC)=>{var yC=Ro(),bC=nf(),n$=Qi(),i$=rf(),a$=hC(),o$=vC(),s$=1,l$=2,u$="[object Boolean]",c$="[object Date]",d$="[object Error]",p$="[object Map]",f$="[object Number]",m$="[object RegExp]",h$="[object Set]",g$="[object String]",v$="[object Symbol]",y$="[object ArrayBuffer]",b$="[object DataView]",wC=yC?yC.prototype:void 0,af=wC?wC.valueOf:void 0;function w$(e,t,r,n,i,a,o){switch(r){case b$:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case y$:return!(e.byteLength!=t.byteLength||!a(new bC(e),new bC(t)));case u$:case c$:case f$:return n$(+e,+t);case d$:return e.name==t.name&&e.message==t.message;case m$:case g$:return e==t+"";case p$:var s=a$;case h$:var l=n&s$;if(s||(s=o$),e.size!=t.size&&!l)return!1;var u=o.get(e);if(u)return u==t;n|=l$,o.set(e,t);var c=i$(s(e),s(t),n,i,a,o);return o.delete(e),c;case v$:if(af)return af.call(e)==af.call(t)}return!1}AC.exports=w$});var EC=g((ZQ,SC)=>{function A$(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}SC.exports=A$});var Sn=g((eX,NC)=>{var C$=Array.isArray;NC.exports=C$});var IC=g((tX,DC)=>{var S$=EC(),E$=Sn();function N$(e,t,r){var n=t(e);return E$(e)?n:S$(n,r(e))}DC.exports=N$});var PC=g((rX,_C)=>{function D$(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}_C.exports=D$});var OC=g((nX,TC)=>{function I$(){return[]}TC.exports=I$});var xC=g((iX,FC)=>{var _$=PC(),P$=OC(),T$=Object.prototype,O$=T$.propertyIsEnumerable,RC=Object.getOwnPropertySymbols,R$=RC?function(e){return e==null?[]:(e=Object(e),_$(RC(e),function(t){return O$.call(e,t)}))}:P$;FC.exports=R$});var kC=g((aX,LC)=>{function F$(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}LC.exports=F$});var En=g((oX,MC)=>{function x$(e){return e!=null&&typeof e=="object"}MC.exports=x$});var BC=g((sX,UC)=>{var L$=ei(),k$=En(),M$="[object Arguments]";function U$(e){return k$(e)&&L$(e)==M$}UC.exports=U$});var of=g((lX,VC)=>{var $C=BC(),B$=En(),qC=Object.prototype,$$=qC.hasOwnProperty,q$=qC.propertyIsEnumerable,V$=$C((function(){return arguments})())?$C:function(e){return B$(e)&&$$.call(e,"callee")&&!q$.call(e,"callee")};VC.exports=V$});var zC=g((uX,GC)=>{function G$(){return!1}GC.exports=G$});var jl=g((ko,ea)=>{var z$=ir(),W$=zC(),HC=typeof ko=="object"&&ko&&!ko.nodeType&&ko,WC=HC&&typeof ea=="object"&&ea&&!ea.nodeType&&ea,j$=WC&&WC.exports===HC,jC=j$?z$.Buffer:void 0,H$=jC?jC.isBuffer:void 0,J$=H$||W$;ea.exports=J$});var Hl=g((cX,JC)=>{var Q$=9007199254740991,X$=/^(?:0|[1-9]\d*)$/;function K$(e,t){var r=typeof e;return t=t??Q$,!!t&&(r=="number"||r!="symbol"&&X$.test(e))&&e>-1&&e%1==0&&e<t}JC.exports=K$});var sf=g((dX,QC)=>{var Y$=9007199254740991;function Z$(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=Y$}QC.exports=Z$});var KC=g((pX,XC)=>{var eq=ei(),tq=sf(),rq=En(),nq="[object Arguments]",iq="[object Array]",aq="[object Boolean]",oq="[object Date]",sq="[object Error]",lq="[object Function]",uq="[object Map]",cq="[object Number]",dq="[object Object]",pq="[object RegExp]",fq="[object Set]",mq="[object String]",hq="[object WeakMap]",gq="[object ArrayBuffer]",vq="[object DataView]",yq="[object Float32Array]",bq="[object Float64Array]",wq="[object Int8Array]",Aq="[object Int16Array]",Cq="[object Int32Array]",Sq="[object Uint8Array]",Eq="[object Uint8ClampedArray]",Nq="[object Uint16Array]",Dq="[object Uint32Array]",he={};he[yq]=he[bq]=he[wq]=he[Aq]=he[Cq]=he[Sq]=he[Eq]=he[Nq]=he[Dq]=!0;he[nq]=he[iq]=he[gq]=he[aq]=he[vq]=he[oq]=he[sq]=he[lq]=he[uq]=he[cq]=he[dq]=he[pq]=he[fq]=he[mq]=he[hq]=!1;function Iq(e){return rq(e)&&tq(e.length)&&!!he[eq(e)]}XC.exports=Iq});var ZC=g((fX,YC)=>{function _q(e){return function(t){return e(t)}}YC.exports=_q});var tS=g((Mo,ta)=>{var Pq=Yp(),eS=typeof Mo=="object"&&Mo&&!Mo.nodeType&&Mo,Uo=eS&&typeof ta=="object"&&ta&&!ta.nodeType&&ta,Tq=Uo&&Uo.exports===eS,lf=Tq&&Pq.process,Oq=(function(){try{var e=Uo&&Uo.require&&Uo.require("util").types;return e||lf&&lf.binding&&lf.binding("util")}catch{}})();ta.exports=Oq});var Jl=g((mX,iS)=>{var Rq=KC(),Fq=ZC(),rS=tS(),nS=rS&&rS.isTypedArray,xq=nS?Fq(nS):Rq;iS.exports=xq});var uf=g((hX,aS)=>{var Lq=kC(),kq=of(),Mq=Sn(),Uq=jl(),Bq=Hl(),$q=Jl(),qq=Object.prototype,Vq=qq.hasOwnProperty;function Gq(e,t){var r=Mq(e),n=!r&&kq(e),i=!r&&!n&&Uq(e),a=!r&&!n&&!i&&$q(e),o=r||n||i||a,s=o?Lq(e.length,String):[],l=s.length;for(var u in e)(t||Vq.call(e,u))&&!(o&&(u=="length"||i&&(u=="offset"||u=="parent")||a&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||Bq(u,l)))&&s.push(u);return s}aS.exports=Gq});var Ql=g((gX,oS)=>{var zq=Object.prototype;function Wq(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||zq;return e===r}oS.exports=Wq});var cf=g((vX,sS)=>{function jq(e,t){return function(r){return e(t(r))}}sS.exports=jq});var uS=g((yX,lS)=>{var Hq=cf(),Jq=Hq(Object.keys,Object);lS.exports=Jq});var dS=g((bX,cS)=>{var Qq=Ql(),Xq=uS(),Kq=Object.prototype,Yq=Kq.hasOwnProperty;function Zq(e){if(!Qq(e))return Xq(e);var t=[];for(var r in Object(e))Yq.call(e,r)&&r!="constructor"&&t.push(r);return t}cS.exports=Zq});var Bo=g((wX,pS)=>{var e3=Vl(),t3=sf();function r3(e){return e!=null&&t3(e.length)&&!e3(e)}pS.exports=r3});var mS=g((AX,fS)=>{var n3=uf(),i3=dS(),a3=Bo();function o3(e){return a3(e)?n3(e):i3(e)}fS.exports=o3});var gS=g((CX,hS)=>{var s3=IC(),l3=xC(),u3=mS();function c3(e){return s3(e,u3,l3)}hS.exports=c3});var bS=g((SX,yS)=>{var vS=gS(),d3=1,p3=Object.prototype,f3=p3.hasOwnProperty;function m3(e,t,r,n,i,a){var o=r&d3,s=vS(e),l=s.length,u=vS(t),c=u.length;if(l!=c&&!o)return!1;for(var d=l;d--;){var p=s[d];if(!(o?p in t:f3.call(t,p)))return!1}var m=a.get(e),h=a.get(t);if(m&&h)return m==t&&h==e;var w=!0;a.set(e,t),a.set(t,e);for(var b=o;++d<l;){p=s[d];var E=e[p],D=t[p];if(n)var F=o?n(D,E,p,t,e,a):n(E,D,p,e,t,a);if(!(F===void 0?E===D||i(E,D,r,n,a):F)){w=!1;break}b||(b=p=="constructor")}if(w&&!b){var x=e.constructor,q=t.constructor;x!=q&&"constructor"in e&&"constructor"in t&&!(typeof x=="function"&&x instanceof x&&typeof q=="function"&&q instanceof q)&&(w=!1)}return a.delete(e),a.delete(t),w}yS.exports=m3});var AS=g((EX,wS)=>{var h3=Cn(),g3=ir(),v3=h3(g3,"DataView");wS.exports=v3});var SS=g((NX,CS)=>{var y3=Cn(),b3=ir(),w3=y3(b3,"Promise");CS.exports=w3});var NS=g((DX,ES)=>{var A3=Cn(),C3=ir(),S3=A3(C3,"Set");ES.exports=S3});var IS=g((IX,DS)=>{var E3=Cn(),N3=ir(),D3=E3(N3,"WeakMap");DS.exports=D3});var LS=g((_X,xS)=>{var df=AS(),pf=Gl(),ff=SS(),mf=NS(),hf=IS(),FS=ei(),ra=ef(),_S="[object Map]",I3="[object Object]",PS="[object Promise]",TS="[object Set]",OS="[object WeakMap]",RS="[object DataView]",_3=ra(df),P3=ra(pf),T3=ra(ff),O3=ra(mf),R3=ra(hf),ti=FS;(df&&ti(new df(new ArrayBuffer(1)))!=RS||pf&&ti(new pf)!=_S||ff&&ti(ff.resolve())!=PS||mf&&ti(new mf)!=TS||hf&&ti(new hf)!=OS)&&(ti=function(e){var t=FS(e),r=t==I3?e.constructor:void 0,n=r?ra(r):"";if(n)switch(n){case _3:return RS;case P3:return _S;case T3:return PS;case O3:return TS;case R3:return OS}return t});xS.exports=ti});var GS=g((PX,VS)=>{var gf=tf(),F3=rf(),x3=CC(),L3=bS(),kS=LS(),MS=Sn(),US=jl(),k3=Jl(),M3=1,BS="[object Arguments]",$S="[object Array]",Xl="[object Object]",U3=Object.prototype,qS=U3.hasOwnProperty;function B3(e,t,r,n,i,a){var o=MS(e),s=MS(t),l=o?$S:kS(e),u=s?$S:kS(t);l=l==BS?Xl:l,u=u==BS?Xl:u;var c=l==Xl,d=u==Xl,p=l==u;if(p&&US(e)){if(!US(t))return!1;o=!0,c=!1}if(p&&!c)return a||(a=new gf),o||k3(e)?F3(e,t,r,n,i,a):x3(e,t,l,r,n,i,a);if(!(r&M3)){var m=c&&qS.call(e,"__wrapped__"),h=d&&qS.call(t,"__wrapped__");if(m||h){var w=m?e.value():e,b=h?t.value():t;return a||(a=new gf),i(w,b,r,n,a)}}return p?(a||(a=new gf),L3(e,t,r,n,i,a)):!1}VS.exports=B3});var HS=g((TX,jS)=>{var $3=GS(),zS=En();function WS(e,t,r,n,i){return e===t?!0:e==null||t==null||!zS(e)&&!zS(t)?e!==e&&t!==t:$3(e,t,r,n,WS,i)}jS.exports=WS});var QS=g((OX,JS)=>{var q3=HS();function V3(e,t){return q3(e,t)}JS.exports=V3});var vf=g((RX,XS)=>{var G3=Cn(),z3=(function(){try{var e=G3(Object,"defineProperty");return e({},"",{}),e}catch{}})();XS.exports=z3});var Kl=g((FX,YS)=>{var KS=vf();function W3(e,t,r){t=="__proto__"&&KS?KS(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}YS.exports=W3});var yf=g((xX,ZS)=>{var j3=Kl(),H3=Qi();function J3(e,t,r){(r!==void 0&&!H3(e[t],r)||r===void 0&&!(t in e))&&j3(e,t,r)}ZS.exports=J3});var tE=g((LX,eE)=>{function Q3(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}}eE.exports=Q3});var nE=g((kX,rE)=>{var X3=tE(),K3=X3();rE.exports=K3});var lE=g(($o,na)=>{var Y3=ir(),sE=typeof $o=="object"&&$o&&!$o.nodeType&&$o,iE=sE&&typeof na=="object"&&na&&!na.nodeType&&na,Z3=iE&&iE.exports===sE,aE=Z3?Y3.Buffer:void 0,oE=aE?aE.allocUnsafe:void 0;function e4(e,t){if(t)return e.slice();var r=e.length,n=oE?oE(r):new e.constructor(r);return e.copy(n),n}na.exports=e4});var dE=g((MX,cE)=>{var uE=nf();function t4(e){var t=new e.constructor(e.byteLength);return new uE(t).set(new uE(e)),t}cE.exports=t4});var fE=g((UX,pE)=>{var r4=dE();function n4(e,t){var r=t?r4(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}pE.exports=n4});var hE=g((BX,mE)=>{function i4(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}mE.exports=i4});var yE=g(($X,vE)=>{var a4=Hr(),gE=Object.create,o4=(function(){function e(){}return function(t){if(!a4(t))return{};if(gE)return gE(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}})();vE.exports=o4});var bf=g((qX,bE)=>{var s4=cf(),l4=s4(Object.getPrototypeOf,Object);bE.exports=l4});var AE=g((VX,wE)=>{var u4=yE(),c4=bf(),d4=Ql();function p4(e){return typeof e.constructor=="function"&&!d4(e)?u4(c4(e)):{}}wE.exports=p4});var SE=g((GX,CE)=>{var f4=Bo(),m4=En();function h4(e){return m4(e)&&f4(e)}CE.exports=h4});var DE=g((zX,NE)=>{var g4=ei(),v4=bf(),y4=En(),b4="[object Object]",w4=Function.prototype,A4=Object.prototype,EE=w4.toString,C4=A4.hasOwnProperty,S4=EE.call(Object);function E4(e){if(!y4(e)||g4(e)!=b4)return!1;var t=v4(e);if(t===null)return!0;var r=C4.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&EE.call(r)==S4}NE.exports=E4});var wf=g((WX,IE)=>{function N4(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}IE.exports=N4});var Af=g((jX,_E)=>{var D4=Kl(),I4=Qi(),_4=Object.prototype,P4=_4.hasOwnProperty;function T4(e,t,r){var n=e[t];(!(P4.call(e,t)&&I4(n,r))||r===void 0&&!(t in e))&&D4(e,t,r)}_E.exports=T4});var TE=g((HX,PE)=>{var O4=Af(),R4=Kl();function F4(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?R4(r,s,l):O4(r,s,l)}return r}PE.exports=F4});var RE=g((JX,OE)=>{function x4(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}OE.exports=x4});var xE=g((QX,FE)=>{var L4=Hr(),k4=Ql(),M4=RE(),U4=Object.prototype,B4=U4.hasOwnProperty;function $4(e){if(!L4(e))return M4(e);var t=k4(e),r=[];for(var n in e)n=="constructor"&&(t||!B4.call(e,n))||r.push(n);return r}FE.exports=$4});var Cf=g((XX,LE)=>{var q4=uf(),V4=xE(),G4=Bo();function z4(e){return G4(e)?q4(e,!0):V4(e)}LE.exports=z4});var ME=g((KX,kE)=>{var W4=TE(),j4=Cf();function H4(e){return W4(e,j4(e))}kE.exports=H4});var GE=g((YX,VE)=>{var UE=yf(),J4=lE(),Q4=fE(),X4=hE(),K4=AE(),BE=of(),$E=Sn(),Y4=SE(),Z4=jl(),e5=Vl(),t5=Hr(),r5=DE(),n5=Jl(),qE=wf(),i5=ME();function a5(e,t,r,n,i,a,o){var s=qE(e,r),l=qE(t,r),u=o.get(l);if(u){UE(e,r,u);return}var c=a?a(s,l,r+"",e,t,o):void 0,d=c===void 0;if(d){var p=$E(l),m=!p&&Z4(l),h=!p&&!m&&n5(l);c=l,p||m||h?$E(s)?c=s:Y4(s)?c=X4(s):m?(d=!1,c=J4(l,!0)):h?(d=!1,c=Q4(l,!0)):c=[]:r5(l)||BE(l)?(c=s,BE(s)?c=i5(s):(!t5(s)||e5(s))&&(c=K4(l))):d=!1}d&&(o.set(l,c),i(c,l,n,a,o),o.delete(l)),UE(e,r,c)}VE.exports=a5});var Sf=g((ZX,WE)=>{var o5=tf(),s5=yf(),l5=nE(),u5=GE(),c5=Hr(),d5=Cf(),p5=wf();function zE(e,t,r,n,i){e!==t&&l5(t,function(a,o){if(i||(i=new o5),c5(a))u5(e,t,o,r,zE,n,i);else{var s=n?n(p5(e,o),a,o+"",e,t,i):void 0;s===void 0&&(s=a),s5(e,o,s)}},d5)}WE.exports=zE});var Ef=g((eK,jE)=>{function f5(e){return e}jE.exports=f5});var JE=g((tK,HE)=>{function m5(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)}HE.exports=m5});var KE=g((rK,XE)=>{var h5=JE(),QE=Math.max;function g5(e,t,r){return t=QE(t===void 0?e.length-1:t,0),function(){for(var n=arguments,i=-1,a=QE(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),h5(e,this,s)}}XE.exports=g5});var ZE=g((nK,YE)=>{function v5(e){return function(){return e}}YE.exports=v5});var rN=g((iK,tN)=>{var y5=ZE(),eN=vf(),b5=Ef(),w5=eN?function(e,t){return eN(e,"toString",{configurable:!0,enumerable:!1,value:y5(t),writable:!0})}:b5;tN.exports=w5});var iN=g((aK,nN)=>{var A5=800,C5=16,S5=Date.now;function E5(e){var t=0,r=0;return function(){var n=S5(),i=C5-(n-r);if(r=n,i>0){if(++t>=A5)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}nN.exports=E5});var oN=g((oK,aN)=>{var N5=rN(),D5=iN(),I5=D5(N5);aN.exports=I5});var lN=g((sK,sN)=>{var _5=Ef(),P5=KE(),T5=oN();function O5(e,t){return T5(P5(e,t,_5),e+"")}sN.exports=O5});var cN=g((lK,uN)=>{var R5=Qi(),F5=Bo(),x5=Hl(),L5=Hr();function k5(e,t,r){if(!L5(r))return!1;var n=typeof t;return(n=="number"?F5(r)&&x5(t,r.length):n=="string"&&t in r)?R5(r[t],e):!1}uN.exports=k5});var Nf=g((uK,dN)=>{var M5=lN(),U5=cN();function B5(e){return M5(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&&U5(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})}dN.exports=B5});var fN=g((cK,pN)=>{var $5=Sf(),q5=Nf(),V5=q5(function(e,t,r,n){$5(e,t,r,n)});pN.exports=V5});var Bt,qo=I(()=>{"use strict";(function(e){e[e.NotLoaded=0]="NotLoaded",e[e.Initialized=1]="Initialized",e[e.ConfigsLoaded=2]="ConfigsLoaded",e[e.Error=3]="Error"})(Bt||(Bt={}))});function hN(e,t,r="PROD"){let n=i=>`ShellSettings_ECS_ClientCache_${e}_${mN.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 mN,G5,gN=I(()=>{"use strict";mN=se(Kp()),G5=se(Xp());});var Df,vN=I(()=>{"use strict";Ol();Df=So({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 bN,wN,AN,CN,If,z5,Yl,yN,_f=I(()=>{"use strict";bN=se(Xp()),wN=se(_w()),AN=se(Kp()),CN=se(QS()),If=se(fN());qo();gN();vN();z5=60*1e3,Yl=class{clientName;logger;ecsEndpoint;resolveLoadingPromise;loadingPromise=new Promise(t=>this.resolveLoadingPromise=t);_status=Bt.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"?Df.prodEcsEndpoint:Df.integrationEcsEndpoint}client=new wN.default;init=async({clientVersion:t,getFilters:r,cacheStorage:n=bN.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:[AN.EcsConfigType.Default],hosts:[this.ecsEndpoint],initialAppActiveState:!0,getEcsParameters:o,databaseInterface:hN(this.clientName,n,this.endpointType),...a}),this.client.requestUpdate(),this._status===Bt.NotLoaded&&(this._status=Bt.Initialized)}catch(s){this._status=Bt.Error,this.resolveLoadingPromise(),this.logEvent("FeaturesClient/initializationFailed",{ecsClientName:this.clientName,error:s},"Error")}i&&window.setInterval(()=>this.client.requestUpdate(),i*z5)};getConfig=t=>{let r=this.getMergedClientConfigByTeamName(t.teamName),n=r?t.extractConfig(r):{};return(0,If.default)({},t.fallback,n,t.override,yN)};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,CN.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,If.default)({},this.client.getConfig()?.config,this.clientConfigOverride,yN);getMergedClientConfigByTeamName=t=>this.getMergedClientConfig()?.[t];handleConfigUpdated=()=>{let t=this.client.getConfig();if(t===void 0)return;this.resolveLoadingPromise(),this._status=Bt.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})}},yN=(e,t)=>{if(Array.isArray(t))return t}});var EN=g((bK,SN)=>{"use strict";var W5=()=>{let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e};SN.exports=W5});var Pf=g((wK,DN)=>{var Vo=new Proxy(function(){return Vo},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Vo},apply:function(){return Vo},construct:function(){return{}}}),NN=function(){return Vo};Object.setPrototypeOf(NN,Vo);DN.exports=NN});var PN=g((AK,_N)=>{var Go=new Proxy(function(){return Go},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Go},apply:function(){return Go},construct:function(){return{}}}),IN=function(){return Go};Object.setPrototypeOf(IN,Go);_N.exports=IN});var kN=g((CK,LN)=>{"use strict";var Tf=PN(),j5={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},H5={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},J5={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},FN={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},Of={};Of[Tf.ForwardRef]=J5;Of[Tf.Memo]=FN;function TN(e){return Tf.isMemo(e)?FN:Of[e.$$typeof]||j5}var Q5=Object.defineProperty,X5=Object.getOwnPropertyNames,ON=Object.getOwnPropertySymbols,K5=Object.getOwnPropertyDescriptor,Y5=Object.getPrototypeOf,RN=Object.prototype;function xN(e,t,r){if(typeof t!="string"){if(RN){var n=Y5(t);n&&n!==RN&&xN(e,n,r)}var i=X5(t);ON&&(i=i.concat(ON(t)));for(var a=TN(e),o=TN(t),s=0;s<i.length;++s){var l=i[s];if(!H5[l]&&!(r&&r[l])&&!(o&&o[l])&&!(a&&a[l])){var u=K5(t,l);try{Q5(e,l,u)}catch{}}}}return e}LN.exports=xN});function UN(e,t,r){let[n,i]=(0,ia.useState)(e.getConfig(t));return(0,ia.useEffect)(()=>{if(!r?.subscribe&&e.status===Bt.ConfigsLoaded)return;let a=e.subscribe(t,o=>{i(o),r?.subscribe||a.unsubscribe()});return a?.unsubscribe},[]),n}function BN(e){return function(t,r){return UN(e,t,r)}}function $N(e,t,r,n){let i=a=>{let o=UN(e,t,n),s={...a,...o};return ia.default.createElement(r,{...s})};return(0,MN.default)(i,r),i.displayName=`WithFeature(${r.name})`,i}function qN(e,t,r,n){return t.reduce((i,a)=>$N(e,a,i,n),r)}function VN(e){return function(t,r,n){return $N(e,t,r,n)}}var MN,ia,Rf=I(()=>{"use strict";MN=se(kN()),ia=se(Pf());qo();});var zN=g((NK,GN)=>{var Z5=Sf(),eV=Nf(),tV=eV(function(e,t,r){Z5(e,t,r)});GN.exports=tV});var Zl=g((DK,WN)=>{var rV=ei(),nV=En(),iV="[object Symbol]";function aV(e){return typeof e=="symbol"||nV(e)&&rV(e)==iV}WN.exports=aV});var HN=g((IK,jN)=>{var oV=Sn(),sV=Zl(),lV=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,uV=/^\w*$/;function cV(e,t){if(oV(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||sV(e)?!0:uV.test(e)||!lV.test(e)||t!=null&&e in Object(t)}jN.exports=cV});var XN=g((_K,QN)=>{var JN=zl(),dV="Expected a function";function Ff(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(dV);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(Ff.Cache||JN),r}Ff.Cache=JN;QN.exports=Ff});var YN=g((PK,KN)=>{var pV=XN(),fV=500;function mV(e){var t=pV(e,function(n){return r.size===fV&&r.clear(),n}),r=t.cache;return t}KN.exports=mV});var eD=g((TK,ZN)=>{var hV=YN(),gV=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,vV=/\\(\\)?/g,yV=hV(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(gV,function(r,n,i,a){t.push(i?a.replace(vV,"$1"):n||r)}),t});ZN.exports=yV});var rD=g((OK,tD)=>{function bV(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}tD.exports=bV});var lD=g((RK,sD)=>{var nD=Ro(),wV=rD(),AV=Sn(),CV=Zl(),SV=1/0,iD=nD?nD.prototype:void 0,aD=iD?iD.toString:void 0;function oD(e){if(typeof e=="string")return e;if(AV(e))return wV(e,oD)+"";if(CV(e))return aD?aD.call(e):"";var t=e+"";return t=="0"&&1/e==-SV?"-0":t}sD.exports=oD});var cD=g((FK,uD)=>{var EV=lD();function NV(e){return e==null?"":EV(e)}uD.exports=NV});var pD=g((xK,dD)=>{var DV=Sn(),IV=HN(),_V=eD(),PV=cD();function TV(e,t){return DV(e)?e:IV(e,t)?[e]:_V(PV(e))}dD.exports=TV});var mD=g((LK,fD)=>{var OV=Zl(),RV=1/0;function FV(e){if(typeof e=="string"||OV(e))return e;var t=e+"";return t=="0"&&1/e==-RV?"-0":t}fD.exports=FV});var vD=g((kK,gD)=>{var xV=Af(),LV=pD(),kV=Hl(),hD=Hr(),MV=mD();function UV(e,t,r,n){if(!hD(e))return e;t=LV(t,e);for(var i=-1,a=t.length,o=a-1,s=e;s!=null&&++i<a;){var l=MV(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=hD(c)?c:kV(t[i+1])?[]:{})}xV(s,l,u),s=s[l]}return e}gD.exports=UV});var bD=g((MK,yD)=>{var BV=vD();function $V(e,t,r){return e==null?e:BV(e,t,r)}yD.exports=$V});function SD(e){let{query:t}=(0,CD.default)(window.location.href,!0);return VV(e,t),e}function VV(e,t){let r=qV+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+ED,u={};if(a===r)u=s;else if(a.startsWith(l)){let c=a.substring(l.length);(0,AD.default)(u,c,s)}(0,wD.default)(i,u)}catch{}}),Object.keys(i).length>0&&e.overrideClientConfig(i)}var wD,AD,CD,ED,qV,ND=I(()=>{"use strict";wD=se(zN()),AD=se(bD()),CD=se(Mp());ED=".",qV="ecs"+ED});function tu(e,t,r){let n=SD(new Yl(e,t,r));function i(a){(0,eu.useEffect)(()=>{n.init(a)},[])}return{featuresClient:n,createFeature:zV(n),useFeaturesClientInitParams:i,withFeatures:(a,o,s)=>qN(n,a,o,s)}}function zV(e){let t=BN(e),r=VN(e);return function(i){let a=Sw(i);return a.getConfig=()=>e.getConfig(a),a.isLoaded=()=>e.status===Bt.ConfigsLoaded,$p.register(a,e.clientName),{useFeature:o=>t(a,o),withFeature:(o,s)=>r(a,o,s),feature:a}}}var GV,eu,xf=I(()=>{"use strict";GV=se(EN()),eu=se(Pf());Qp();_f();qo();Rf();ND();qp();});var DD=I(()=>{"use strict";Qp();_f();xf();qo();Rf();Ll();Vp();});function ru(e){return{logEvent:(t,r,n)=>{switch(n){case"Error":(0,aa.trackErrorTrace)(e,{eventName:t,eventData:r});break;case"Warning":(0,aa.trackWarningTrace)(e,{eventName:t,eventData:r});break;default:(0,aa.trackInfoTrace)(e,{eventName:t,eventData:r});break}}}}var aa,Lf=I(()=>{"use strict";aa=se(Jn());});var nY,iY,aY,ID=I(()=>{"use strict";DD();Lf();({featuresClient:nY,createFeature:iY,useFeaturesClientInitParams:aY}=tu("PowerApps-Shell-Test",ru("shell-features")))});var TD=g((sY,PD)=>{var zo=new Proxy(function(){return zo},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:zo},apply:function(){return zo},construct:function(){return{}}}),_D=function(){return zo};Object.setPrototypeOf(_D,zo);PD.exports=_D});var WV,jV,OD=I(()=>{"use strict";wo();WV=se(TD()),jV=se(Jn());});var RD=I(()=>{"use strict";ID();Lf();OD();});var gY,oa,vY,FD=I(()=>{"use strict";RD();xf();({featuresClient:gY,createFeature:oa,useFeaturesClientInitParams:vY}=tu("PowerApps-MakerPortal",ru("powerapps-features")))});var xD,LD,AY,CY,SY,EY,kf=I(()=>{"use strict";Cw();FD();({feature:xD}=oa({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:Ji.enableAutoInsertionOfCellInRow}})),{feature:LD}=oa({teamName:"MakerPortal",owners:["aansu"],description:"Enable the one grid events for form designer",createdOn:"08/21/2024",fallback:{enableOneGridEventsForFormDesigner:Ji.enableOneGridEvents}}),{feature:AY}=oa({teamName:"MakerPortal",owners:["adekulkarni"],description:"Disables PBI components and cleans them up from the form",createdOn:"01/03/2023",fallback:{enableFallbackFormTemplate:Ji.disablePBIComponents}}),{feature:CY}=oa({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:Ji.enableAgentResponse}}),{feature:SY,useFeature:EY}=oa({teamName:"MakerPortal",owners:["aansu"],description:"Enables delayed localization of custom control",createdOn:"06/08/2025",fallback:{enableDelayedLocalizationForCustomControls:Ji.enableDelayedLocalizationForCustomControls}})});var UD=g((DY,MD)=>{var Wo=new Proxy(function(){return Wo},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Wo},apply:function(){return Wo},construct:function(){return{}}}),kD=function(){return Wo};Object.setPrototypeOf(kD,Wo);MD.exports=kD});var st,Nn=I(()=>{"use strict";Me();xe();ot();$l();K();He();st=class extends H{static HighestUsedIndexByClass=new Map;get colspan(){let t=this.getProperty(f.colspan);return N.IsNullOrUndefined(t)?null:parseInt(t,10)}set colspan(t){N.IsNullOrUndefined(t)||this.setProperty(f.colspan,String(t))}constructor(t,r){super(t,r)}get id(){let t=this.getProperty(f.id);return t==null?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new P(t.substr(1,t.length-2)):new P(t)}set id(t){this.setProperty(f.id,`{${t.ToString()}}`)}set labelId(t){this.setProperty(f.labelId,`{${t.ToString()}}`)}get labelId(){let t=this.getProperty(f.labelId);return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new P(t.substr(1,t.length-2)):new P(t)}get Name(){return this.getProperty(f.Name)}set Name(t){this.setProperty(f.Name,t)}setDisplayName(t,r){for(let i of this.getAllLabels())if(+i.getProperty(f.languagecode)===r){i.setProperty(f.description,t);return}let n=new H(v.formLabel,null);n.setProperty(f.description,t),n.setProperty(f.languagecode,String(r)),this.addGrandChild("labels",n)}getDisplayName(t){for(let r of this.getAllLabels())if(+r.getProperty(f.languagecode)===t)return r.getProperty(f.description)}getAllLabels(){let t=this.getChildren("labels");return t.length!==1?[]:t[0].getChildren("label")}get isLocked(){return+this.getProperty(f.locklevel)==1}set isLocked(t){!this.IsUnboundControl&&this.setProperty(f.locklevel,t?"1":"0")}get availableforphone(){return this.getProcessedValue(f.availableforphone)}set availableforphone(t){N.IsNullOrUndefined(t)||!this.IsAllowedUBCForAvailableOnPhone()||this.setProperty(f.availableforphone,String(t))}get visible(){return this.getProcessedValue(f.visible)}set visible(t){N.IsNullOrUndefined(t)||!this.IsAllowedUBCForVisibleByDefault()||this.setProperty(f.visible,String(t))}isLockLevelSettable(){return!this.IsUnboundControl}get showlabel(){return this.getProcessedValue(f.showlabel)}set showlabel(t){N.IsNullOrUndefined(t)||this.setProperty(f.showlabel,String(t))}isAvailableForPhoneSettable(){return this.IsAllowedUBCForAvailableOnPhone()}isVisibleSettable(){return this.IsAllowedUBCForVisibleByDefault()}getProcessedValue(t){let r=this.getProperty(t);return N.IsNullOrUndefined(r)||this.getProperty(t)==="true"}get readonly(){let t=this.getFirstChild(v.formControl);return t?t.disabled:!1}set readonly(t){let r=this.getFirstChild(v.formControl);r&&(r.disabled=t)}get allowfilteroff(){let t=this.getFirstChild(v.formControl);if(t)return t.getParam(f.AllowFilterOff)==="true"}set allowfilteroff(t){let r=this.getFirstChild(v.formControl);r&&!this.IsUnboundControl&&r.setParameter(f.AllowFilterOff,t)}get autoresolve(){let t=this.getFirstChild(v.formControl);if(t)return t.getParam(f.AutoResolve)==="true"}set autoresolve(t){let r=this.getFirstChild(v.formControl);r&&!this.IsUnboundControl&&r.setParameter(f.AutoResolve,t)}get defaultviewid(){let t=this.getFirstChild(v.formControl);return t?t.getParam(f.DefaultViewId):T.EmptyString}set defaultviewid(t){let r=this.getFirstChild(v.formControl);r&&!this.IsUnboundControl&&r.setParameter(f.DefaultViewId,t)}get dependentattributename(){let t=this.getFirstChild(v.formControl);return t?t.getParam(f.DependentAttributeName):T.EmptyString}set dependentattributename(t){let r=this.getFirstChild(v.formControl);r&&!this.IsUnboundControl&&r.setParameter(f.DependentAttributeName,t)}get dependentattributetype(){let t=this.getFirstChild(v.formControl);return t?t.getParam(f.DependentAttributeType):T.EmptyString}set dependentattributetype(t){let r=this.getFirstChild(v.formControl);r&&!this.IsUnboundControl&&r.setParameter(f.DependentAttributeType,t)}get disablequickfind(){let t=this.getFirstChild(v.formControl);if(t)return t.getParam(f.DisableQuickFind)==="true"}set disablequickfind(t){let r=this.getFirstChild(v.formControl);r&&!this.IsUnboundControl&&r.setParameter(f.DisableQuickFind,t)}get disableviewpicker(){let t=this.getFirstChild(v.formControl);if(t)return t.getParam(f.DisableViewPicker)==="true"}set disableviewpicker(t){let r=this.getFirstChild(v.formControl);r&&!this.IsUnboundControl&&r.setParameter(f.DisableViewPicker,t)}get filterrelationshipname(){let t=this.getFirstChild(v.formControl);return t?t.getParam(f.FilterRelationshipName):T.EmptyString}set filterrelationshipname(t){let r=this.getFirstChild(v.formControl);r&&!this.IsUnboundControl&&r.setParameter(f.FilterRelationshipName,t)}get availableviewids(){let t=this.getFirstChild(v.formControl);return t?t.getParam(f.AvailableViewIds):T.EmptyString}set availableviewids(t){let r=this.getFirstChild(v.formControl);r&&!this.IsUnboundControl&&r.setParameter(f.AvailableViewIds,t)}get IsUnboundControl(){let t=this.getFirstChild(v.formControl);if(t&&t.ClassId){let r=Be.getUniqueIdentifierForControl(t);return!N.IsNullOrUndefined(r)&&Be.isUnboundFormControlByIdentifier(r)}else return!1}IsAllowedUBCForAvailableOnPhone(){let t=this.getFirstChild(v.formControl);if(t){let n=Be.getUniqueIdentifierForControl(t).guidString,i=n===R.GridControl||n===R.TimeLineControl||n===R.TimeLineControlUC;return this.IsUnboundControl?i:!0}return this.NodeName===v.formSection||this.NodeName===v.formTab}IsAllowedUBCForVisibleByDefault(){let t=this.getFirstChild(v.formControl);if(t){let n=Be.getUniqueIdentifierForControl(t).guidString,i=n===R.MapsControl||n===R.WebResourceHtmlControl||n===R.WebResourceImageControl||n===R.IframeControl||n===R.SocialInsightControl;return this.IsUnboundControl?i:!0}else return!0}get events(){let t=this.getChildren(v.formEvents);return t.length===1?t[0].getAllChildren():[]}addEvent(t){this.addGrandChild(v.formEvents,t)}getUsedNodeNameSet(t){return null}getHighestIndexById(t,r){return null}}});var sa,Mf=I(()=>{"use strict";ot();K();He();sa=class extends H{constructor(t,r){super(v.dependency,t),T.IsNullOrEmpty(r)||this.setDefaultProperties(r)}set id(t){this.setProperty(f.id,t)}get id(){return this.getProperty(f.id)}setDefaultProperties(t){this.id=t}}});var BD,la,Uf=I(()=>{"use strict";xe();Mf();K();He();Nn();(function(e){e[e.Form=0]="Form",e[e.Cell=1]="Cell",e[e.Tab=2]="Tab",e[e.Control=3]="Control"})(BD||(BD={}));la=class extends st{constructor(t,r){super(v.formEvent,t),r&&(this.eventName=r,this.application="false",this.active="false")}set eventName(t){this.setProperty(f.Name,t)}get eventName(){return this.getProperty(f.Name)}set application(t){this.setProperty(f.application,t)}get application(){return this.getProperty(f.application)}set attribute(t){this.setProperty(f.EventAttribute,t)}get attribute(){return this.getProperty(f.EventAttribute)}set relationship(t){this.setProperty(f.Relationship,t)}get relationship(){return this.getProperty(f.Relationship)}set control(t){this.setProperty(f.Control,t)}get control(){return this.getProperty(f.Control)}set active(t){this.setProperty(f.EventActive,t)}get active(){return this.getProperty(f.EventActive)}getAllHandlers(){let t=this.getChildren(v.EventHandlers);return t&&t.length?t[0].getChildren(v.handler):[]}getAllDependencies(){let t=this.getChildren(v.formDependencies);return t.length===0?[]:t[0].getAllChildren()}setDependencies(t){let r=this.getFirstChild(v.formDependencies);if(N.IsNullOrUndefined(r)){if(t.length===0)return;this.addChild(new H(v.formDependencies,this)),r=this.getFirstChild(v.formDependencies)}if(t.length===0)r.getParentNode().deleteChild(r);else{r.deleteAllChildren();for(let n of t)r.addChild(new sa(r,n.toString()))}}}});var ar,jo=I(()=>{"use strict";Me();bo();xe();Hn();K();He();rr();ar=class extends H{previewVersion;constructor(t){super(v.formControl,t)}updatePreview(){this.previewVersion=Date.now()}get ClassId(){let t=this.getProperty(f.classid);return t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new P(t)}set ClassId(t){this.setProperty(f.classid,`{${t.ToString()}}`)}get dataFieldName(){return this.getProperty(f.datafieldname)}set dataFieldName(t){this.setProperty(f.datafieldname,t)}set id(t){this.setProperty(f.id,t)}get id(){return this.getProperty(f.id)}get UniqueId(){let t=this.getProperty(f.uniqueid);return N.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new P(t))}set UniqueId(t){this.setProperty(f.uniqueid,`{${t.ToString()}}`)}get isRequired(){return this.getProperty(f.isRequired)==="true"}set isRequired(t){N.IsNullOrUndefined(t)||this.setProperty(f.isRequired,String(t))}get disableMru(){return this.getParam(f.DisableMru)==="true"}set disableMru(t){N.IsNullOrUndefined(t)||this.setParameter(f.DisableMru,t)}get useMFDForCreate(){return this.getParam(f.UseMFDForCreate)==="true"}set useMFDForCreate(t){N.IsNullOrUndefined(t)||this.setParameter(f.UseMFDForCreate,t)}get useMFDForEdit(){return this.getParam(f.UseMFDForEdit)==="true"}set useMFDForEdit(t){N.IsNullOrUndefined(t)||this.setParameter(f.UseMFDForEdit,t)}get disabled(){return this.getProperty(f.disabled)==="true"}set disabled(t){N.IsNullOrUndefined(t)||this.setProperty(f.disabled,String(t))}get indicationOfSubgrid(){return this.getProperty(f.indicationOfSubgrid)==="true"}set indicationOfSubgrid(t){this.setProperty(f.indicationOfSubgrid,String(t))}getAllParameters(){let t=new pt,r=this.getFirstChild(f.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=(jr.StartTag+r).toString(),a=this.parametersNode;if(a){let o=a.findFirst(s=>s&&s.getNodeName()===t);if(o)if(n){this.deleteFirstGrandChildOfName(v.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)===jr.StartTag?a.substring(1):a}}}return null}get parametersNode(){let t=this.getChildren(f.parameters);return t.length===0?null:t[0]}async serializeParameters(t,r){let n=new pt;switch(this.ClassId.guidString.toUpperCase()){case S.LookupControl:if(t&&t.getKeys())if(t.getKeys().forEach(o=>{n.add(o,this.getParam(o))}),t&&t.containsKey("DefaultViewId")){let o=this.getParam("DefaultViewId").replace("{","").replace("}","");n.upsert("DefaultViewId",o)}else{let o=this.getParent(),s=await r.formModelService.lookupControlService.populateDefaultView(this,o.getParentForm().entityName);s&&s.id&&n.upsert("DefaultViewId",s.id.replace("{","").replace("}",""))}break;default:t&&t.getKeys()&&t.getKeys().forEach(o=>{n.add(o,this.getParam(o))});break}let i=n.getInternalObject(),a=[];for(let o in i)i.hasOwnProperty(o)&&a.push({Name:o,Value:i[o]});return a}getIsUnbound(){return this.getProperty(f.isUnbound)==="true"}getAttributeTypeFromClassId(t){if(t)switch(t.toUpperCase()){case S.BooleanControl:case S.CheckboxControl:return 0;case S.DateTimeControl:return 2;case S.DecimalControl:return 3;case S.FloatingNumberControl:return 4;case S.IntegerControl:case S.DurationControl:case S.LanguageControl:case S.TimezoneControl:return 5;case S.LookupControl:return 6;case S.CurrencyControl:return 8;case S.PartyListControl:return 10;case S.ChoiceControl:case S.RelationshipRoleChoiceControl:return 11;case S.ChoiceStatusControl:return 13;case S.TextAreaControl:case S.TextboxControl:case S.LabelControl:case S.EmailAddressControl:case S.UrlControl:case S.TickerControl:case S.ButtonControl:case S.PhoneNumberControl:return 14;case S.ChoicesControl:return 24;default:return}return 14}async toJSON(t){let r=this.getParent(),n=t&&t.formModelService&&t.formModelService.getFormType()===Ue.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 ua,Bf=I(()=>{"use strict";ot();Vi();jo();K();He();ua=class extends ar{constructor(t){super(t)}get targetEntityType(){return this.getParam(f.targetEntityType)||T.EmptyString}set targetEntityType(t){this.setParameter(f.targetEntityType,t)}get viewId(){return T.StripBraces(this.getParam(f.viewId))||T.EmptyString}set viewId(t){this.setParameter(f.viewId,T.AddBraces(t))}get viewIds(){return this.getParam(f.viewIds)||T.EmptyString}set viewIds(t){this.setParameter(f.viewIds,t)}get relationshipName(){return this.getParam(f.RelationshipName)||T.EmptyString}set relationshipName(t){this.setParameter(f.RelationshipName,t)}get isUserView(){return T.IsStrictTrue(this.getParam(f.isUserView))}set isUserView(t){this.setParameter(f.isUserView,t.toString())}get enableViewPicker(){return T.IsStrictTrue(this.getParam(f.enableViewPicker))}set enableViewPicker(t){this.setParameter(f.enableViewPicker,t)}get autoExpand(){return this.getParent().autoexpand&&this.getParam(f.autoExpand)===f.Auto}set autoExpand(t){let r=this.getParent();this.setParameter(f.autoExpand,t?f.Auto:f.Fixed),r.autoexpand=t}get recordsPerPage(){return this.getParam(f.recordsPerPage)?Number(this.getParam(f.recordsPerPage)):Number(f.RecordsPerPageRAControlDefault)}set recordsPerPage(t){this.setParameter(f.recordsPerPage,String(t))}get enableQuickFind(){return T.IsStrictTrue(this.getParam(f.enableQuickFind))}set enableQuickFind(t){this.setParameter(f.enableQuickFind,t)}get teamTemplateId(){return T.StripBraces(this.getParam(f.teamTemplateId))||T.EmptyString}set teamTemplateId(t){this.setParameter(f.teamTemplateId,T.AddBraces(t))}get chartId(){return this.getParam(f.visualizationId)||T.EmptyString}set chartId(t){this.setParameter(f.visualizationId,t)}get enableChartPicker(){return T.IsStrictTrue(this.getParam(f.enableChartPicker))}set enableChartPicker(t){this.setParameter(f.enableChartPicker,t)}get chartGridMode(){switch(this.getParam(f.chartGridMode)){case Ut.Chart:return Ut.Chart;case Ut.Grid:return Ut.Grid;default:return Ut.All}}set chartGridMode(t){this.setParameter(f.chartGridMode,t)}updateChartGridMode(t){t?this.chartGridMode=Ut.Chart:this.chartGridMode=this.enableChartPicker?Ut.All:Ut.Grid}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case f.targetEntityType:n.getAllChildren()[0].setNodeName("<"+r.targetEntityType);break;case f.viewId:n.getAllChildren()[0].setNodeName("<"+T.AddBraces(r.viewId));break;case f.isUserView:n.getAllChildren()[0].setNodeName("<"+r.isUserView);break;case f.enableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.enableViewPicker);break;case f.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(ft.dataset)?n[i].getParameters().get(ft.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 ca,$f=I(()=>{"use strict";ot();Vi();jo();K();ca=class extends ar{constructor(t){super(t)}get defaultViewId(){return T.StripBraces(this.getParam(f.DefaultViewId))||T.EmptyString}set defaultViewId(t){this.setParameter(f.DefaultViewId,T.AddBraces(t))}get autoResolve(){return T.IsStrictTrue(this.getParam(f.AutoResolve))}set autoResolve(t){this.setParameter(f.AutoResolve,t)}get disableQuickFind(){return T.IsStrictTrue(this.getParam(f.DisableQuickFind))}set disableQuickFind(t){this.setParameter(f.DisableQuickFind,t)}get disableViewPicker(){return T.IsStrictTrue(this.getParam(f.DisableViewPicker))}set disableViewPicker(t){this.setParameter(f.DisableViewPicker,t)}get allowFilterOff(){return T.IsStrictTrue(this.getParam(f.AllowFilterOff))}set allowFilterOff(t){this.setParameter(f.AllowFilterOff,t)}get disableMru(){return T.IsStrictTrue(this.getParam(f.DisableMru))}set disableMru(t){this.setParameter(f.DisableMru,t)}get dependentAttributeName(){return this.getParam(f.DependentAttributeName)||T.EmptyString}set dependentAttributeName(t){this.setParameter(f.DependentAttributeName,t)}get dependentAttributeType(){return this.getParam(f.DependentAttributeType)||T.EmptyString}set dependentAttributeType(t){this.setParameter(f.DependentAttributeType,t)}get filterRelationshipName(){return this.getParam(f.FilterRelationshipName)||T.EmptyString}set filterRelationshipName(t){this.setParameter(f.FilterRelationshipName,t)}get availableViewIds(){return this.getParam(f.AvailableViewIds)||T.EmptyString}set availableViewIds(t){this.setParameter(f.AvailableViewIds,t)}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case f.datafieldname:case f.bindAttribute:n.getAllChildren()[0].setNodeName("<"+r.dataFieldName);break;case f.DefaultViewId:n.getAllChildren()[0].setNodeName("<"+T.AddBraces(r.defaultViewId));break;case f.AllowFilterOff:n.getAllChildren()[0].setNodeName("<"+r.allowFilterOff);break;case f.DisableQuickFind:n.getAllChildren()[0].setNodeName("<"+r.disableQuickFind);break;case f.DisableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.disableViewPicker);break;case f.FilterRelationshipName:n.getAllChildren()[0].setNodeName("<"+r.filterRelationshipName);break;case f.DependentAttributeName:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeName);break;case f.DependentAttributeType:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeType);break;case f.AvailableViewIds:n.getAllChildren()[0].setNodeName("<"+r.availableViewIds);break;case f.DisableMru:n.getAllChildren()[0].setNodeName("<"+r.disableMru);break;case f.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(ft.value)?n[i].getParameters().get(ft.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 $D,qf,Et,Ho=I(()=>{"use strict";$D=se(UD());Nn();K();xe();Me();Uf();jo();$l();Hp();Np();rr();Hn();Bi();Bf();$f();Vf();No();qf="_",Et=class e extends st{fieldPlaceholder;fieldRequiredLevel;isNewField;cellColType;dependentFields=[];constructor(t){super(v.formCell,t),this.isNewField=!1}get cellType(){return this.cellColType}set cellType(t){this.cellColType=t}setDefaultProperties(t){this.showlabel=t,this.isLocked=!1,N.IsNullOrUndefined(this.getProperty(f.id))&&(this.id=new P(P.NewGuid()))}addControl(t,r,n,i,a,o,s){n instanceof ar?this.addChild(n):n instanceof P&&this.addChild(this.getControlWithControlSpecificProperties(t,r,n,i,a,o,s))}removeControl(){return this.deleteChild(this.control)>=0}get isIndependent(){if(!N.IsNullOrUndefined(this.control))return N.IsNullOrUndefined(this.control.dataFieldName)?N.IsNullOrUndefined(this.control.id)?!0:!Qn.dependencyFieldCount.containsKey(this.control.id):!Qn.dependencyFieldCount.containsKey(this.control.dataFieldName)}createOnLoadEvent(){this.addEvent(new la(this,vo.onLoad))}get dependencies(){let t=this.getChildren(v.formEvents);for(let r of t){let n=r.getChildren(v.formEvent);for(let i of n)this.buildDependencyList(i,this.dependentFields)}return this.dependentFields}getNextAvailableControlName(t,r,n,i){let a;if(i&&Dl[i])a=Dl[i].replace(/ /g,qf)+qf;else{a="Control_";let u=new Error("Control class id does not exist or is undefined");(0,$D.trackErrorTrace)(dt,{eventName:`${xb}/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,f.isUnbound,"true"),e.prototype.setProperty.call(t,f.isRequired,"false")}getControlWithControlSpecificProperties(t,r,n,i,a,o,s){let l;a===$t.Grid?(l=new ua(this),l.indicationOfSubgrid=!0):a===$t.Lookup?l=new ca(this):l=new ar(this);let u=n.guidString,c=o||this.getNextAvailableControlName(t,i,this.getUsedNodeNameSet(t),u);if(e.prototype.setProperty.call(l,f.id,c),l.ClassId=n,!N.IsNullOrUndefined(s)&&(l.UniqueId=s),!o&&r)this.getUnboundControlProperties(l);else{let d=Be.getUniqueIdentifierForControl(l);N.IsNullOrUndefined(d)||(Be.getControlDataTypeByControlOrUniqueId(d)===V.QuickFormCollectionControl||!Be.isUnboundFormControlByIdentifier(d)?a!==$t.Grid&&o&&u!==S.IframeControl&&u!==S.SubgridControl&&u!==S.ReferencePanelSubgridControl&&(l.dataFieldName=o,e.prototype.setProperty.call(l,f.disabled,"false")):(this.rowspan=Be.GetRowSpan(l),(Be.getControlDataTypeByControlOrUniqueId(d)===V.NotesControl||Be.getControlDataTypeByControlOrUniqueId(d)===V.TimeLineControl)&&(e.prototype.setProperty.call(l,f.disabled,"false"),l.id=V.NotesControl)),(Be.getUnboundControlNameFromIdentifier(n)===V.SubGridControl||Be.getUnboundControlNameFromIdentifier(n)===V.NotesControl||Be.getUnboundControlNameFromIdentifier(n)===V.TimeLineControl)&&(this.availableforphone=!0))}return l}buildDependencyList(t,r){if(N.IsNullOrUndefined(t))return;let n=t.getAllChildren();for(let i of n){let a=i.getAllChildren();for(let o of a){let s=o.GetPropertyByParameter(f.id);o.getNodeName()===v.dependency&&s?r.push(s):this.buildDependencyList(o,r)}}}get control(){return this.getFirstChild(v.formControl)}set rowspan(t){this.setProperty(f.rowspan,String(t))}get rowspan(){let t=this.getProperty(f.rowspan);return N.IsNullOrUndefined(t)?1:parseInt(t,10)}set autoexpand(t){this.setProperty(f.auto,String(t))}get autoexpand(){return this.getProperty(f.auto)==="true"}set colspan(t){let r=Number(Wp.ONE_COLUMN),n=Number(Wp.FOUR_COLUMN);N.IsNullOrUndefined(t)||t>n||t<r||this.setProperty(f.colspan,String(t))}get colspan(){let t=this.getProperty(f.colspan);return N.IsNullOrUndefined(t)?1:parseInt(t,10)}getParentRow(){return this.getAncestor(v.formRow)}getParentSection(){return this.getAncestor(v.formSection)}getParentTab(){return this.getAncestor(v.formTab)}getParentForm(){return this.getAncestor(v.form)}isInHeader(){let t=this.getAncestor(v.formHeader);return!N.IsNullOrUndefined(t)}isInFooter(){let t=this.getAncestor(v.formFooter);return!N.IsNullOrUndefined(t)}isEmpty(){return N.IsNullOrUndefined(this.control)&&!this.IsUserSpacer}getHeaderFooter(){return this.isInHeader()?this.getAncestor(v.formHeader):this.isInFooter()?this.getAncestor(v.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(f.userspacer);return N.IsNullOrUndefined(t)?!1:t==="true"}SetUserSpacer(){this.setProperty(f.userspacer,"true")}ClearUserSpacer(){this.setProperty(f.userspacer,"false")}get columns(){let t=this.getProperty(f.columnName);return N.IsNullOrUndefined(t)?null:parseInt(t,10)}getColumnLayoutValue(t){let r;switch(t){case Ce.TWO_COLUMN:r="11";break;case Ce.THREE_COLUMN:r="111";break;case Ce.FOUR_COLUMN:r="1111";break;default:r="1"}return r}findRowIndexByCellId(t){let r=this.getParentRow().cells.indexOf(this);for(let n=0;n<t.rows.length;n++)if(!N.IsNullOrUndefined(t.rows[n].cells[r])&&this.id.ToString()===t.rows[n].cells[r].id.ToString())return n;return-1}setAutoExpandDetailsForTab(){let t=this.getParentTab();N.IsNullOrUndefined(t)||(t.autoExpandCell=this,t.tabContainsAutoExpandControl=!0)}isCellRequiredOrLocked(t,r,n){let i=this.getParentForm();if(this?.control){if(this.IsUserSpacer)return!1;{if(this.isLocked||r().has(this.control.dataFieldName))return!0;let a=i.isDuplicateCell(this,n),o=this.getRequiredLevel(t);if((o===Kn.ApplicationRequired||o===Kn.SystemRequired)&&!a||this.isCellLockedByExternal(t)&&!a)return!0}}return!1}getRequiredLevel(t){return!this.control?.dataFieldName||!this.control?.id||this.IsNewField||!this.control?.ClassId?Kn.None:t.getEntityAttributeByName(this.control.dataFieldName)?.requiredLevel?.toString()??Kn.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()===v.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()===v.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)===qf&&(r++,n=parseInt(t.substr(r,t.length-r),10)),n}}});var da,Gf=I(()=>{"use strict";ot();K();He();da=class extends H{isInternal;constructor(t,r,n,i){super(v.library,t),this.isInternal=!!i,T.IsNullOrEmpty(n)||(this.name=r,this.libraryUniqueId=n)}get libraryUniqueId(){let t=this.getProperty(f.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(f.libraryUniqueId,t)}get name(){return this.getProperty(f.libraryName)}set name(t){this.setProperty(f.libraryName,t)}get displayName(){return this.getProperty(f.displayName)}set displayName(t){this.setProperty(f.displayName,t)}get description(){return this.getProperty(f.description)}set description(t){this.setProperty(f.description,t)}}});var ri,zf=I(()=>{"use strict";xe();Ho();K();He();ri=class extends H{isRowAddedOnDragOver;constructor(t){super(v.formRow,t)}addCell(t){this.addChild(t)}appendCells(t){for(let r of t)this.addChild(r)}updateCell(t,r){return this.updateChild(t,r)}removeCell(t){return N.IsNullOrUndefined(t)?!1:this.deleteChild(t)>=0}insertCellAtIndex(t,r){return N.IsNullOrUndefined(t)?!1:(this.insertChildAtIndex(t,r),!0)}isEmpty(){return!this.cells||this.cells.every(t=>t.isEmpty())}getParentSection(){return this.getAncestor(v.formSection)}insertPaddingCellAtIndex(t){let r=new Et(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(v.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 HV(e){switch(e){case Yn.Left:return Zn.Left;case Yn.Right:return Zn.Right;case Yn.Center:return Zn.Center;default:return Zn.Left}}function JV(e){switch(e){case Wi.Left:return Hi.Left;case Wi.Top:return Hi.Top;default:return Hi.Left}}function qD(e){switch(e){case 1:return 1;case 2:return 11;case 3:return 111;case 4:return 1111;default:return 1}}var QV,Ar,Jo=I(()=>{"use strict";Jp();Me();xe();ot();kf();Ho();K();rr();Nn();zf();QV=115,Ar=class e extends st{colSpan=1;constructor(t,r){super(t,r)}getSectionType(){let t;switch(this.columns){case 1:t=Ce.ONE_COLUMN;break;case 11:t=Ce.TWO_COLUMN;break;case 111:t=Ce.THREE_COLUMN;break;case 1111:t=Ce.FOUR_COLUMN;break;default:t=this.colSpan-1}return t}setUniqueName(){let t=this.getParentTab(),r=be.namePrefix;if(t){let n=t.Name,i=t.TotalSectionsCount+1;r=n+be.namePrefix+i.toString()}else r+=Math.floor(Math.random()*1e3);this.setProperty(f.Name,r)}initializeDefaultProperties(t,r,n){if(n===Ce.REFERENCE_PANEL){this.addProperty(f.rowheight,"25");let i=`${be.referencePanelNamePrefix}${P.NewGuid()}${be.namePrefix}`;this.addProperty(f.Name,i)}else this.setUniqueName();if(this.addProperty(f.id,new P(P.NewGuid()).guidString),this.addProperty(f.IsUserDefined,be.IsUserDefined),this.addProperty(f.locklevel,be.LockLevel),this.addProperty(f.showlabel,be.ShowLabel),this.addProperty(f.showbar,be.ShowBar),this.addProperty(f.layout,be.Layout),this.addProperty(f.Fieldlabelalignment,be.labelAlignment),this.addProperty(f.Fieldlabelposition,be.labelPosition),N.IsNullOrUndefined(n))this.addProperty(f.columnName,be.columns);else{let i=this.getColumnLayoutValue(n);this.addProperty(f.columnName,i)}this.addProperty(f.LabelWidth,be.LabelWidth),this.setDisplayName(r,t)}getColumnLayoutValue(t){let r;switch(t){case Ce.TWO_COLUMN:r="11";break;case Ce.THREE_COLUMN:r="111";break;case Ce.FOUR_COLUMN:r="1111";break;default:r="1"}return r}getNumberOfColumns(){return e.getNumericColumnLayoutValue(this.columns)}static getNumericColumnLayoutValue(t){switch(t){case 1:return 1;case 11:return 2;case 111:return 3;case 1111:return 4;default:throw new Error("Unexpected Section Layout Value.")}}getColumnCountValue(){let t=0;return N.IsNullOrUndefined(this.columns)?t=this.ColSpan:this.columns.toString().split(T.EmptyString).forEach(r=>{t+=parseInt(r,10)}),t}get ColSpan(){return this.colSpan}initializeRow(t){if(t>0&&t<5){let r=new ri(null);if(this.addGrandChild(v.formRows,r),xD.getConfig().enableAutoInsertionOfCellInRow)for(let n=0;n<t;n++){let i=new Et(r);i.setDefaultProperties(!1),r.addCell(i)}}}initialize(t,r,n){this.initializeDefaultProperties(t,r,n),n===Ce.REFERENCE_PANEL&&(n=Ce.ONE_COLUMN),this.initializeRow(n+1)}setColSpan(t){this.colSpan=t}appendRow(t){this.addGrandChild(v.formRows,t)}insertRowAtIndex(t,r){this.addGrandChildAtIndex(v.formRows,t,r)}insertRowsAtIndex(t,r){if(t&&t.length>0)for(let n=0;n<t.length;n++)this.addGrandChildAtIndex(v.formRows,t[n],r+n)}indexOfRow(t){return this.rows.indexOf(t)}deleteRow(t){return this.deleteFirstGrandChildOfName(v.formRows,t)}deleteRows(t,r){this.deleteGrandChildren(v.formRows,t,r)}get rows(){return this.getRows()}getRows(){let t=this.getChildren(v.formRows);return t.length===0?[]:t[0].getChildren(v.formRow)}get columns(){let t=this.getProperty(f.columnName),r=N.IsNullOrUndefined(t)?NaN:parseInt(t,10);if(isNaN(r)){let n=1;for(let i of this.rows)n=Math.max(n,i.cells.length);return qD(n)}return r}set columns(t){N.IsNullOrUndefined(t)||this.setProperty(f.columnName,String(t))}get rowHeight(){let t=this.getProperty(f.rowheight);return N.IsNullOrUndefined(t)?null:parseInt(t,10)}set rowHeight(t){this.setProperty(f.rowheight,String(t))}set autoexpand(t){this.setProperty(f.autoExpand.toLowerCase(),String(t))}get autoexpand(){return this.getProperty(f.autoExpand.toLowerCase())==="true"}get isUserDefined(){return+this.getProperty(f.IsUserDefined)!=0}set isUserDefined(t){t?this.setProperty(f.IsUserDefined,"1"):this.setProperty(f.IsUserDefined,"0")}getParentColumn(){return this.getAncestor(v.formColumn)}getParentTab(){return this.getAncestor(v.formTab)}get hasMultiColumnRow(){return this.getColumnCountValue()>1}get showlabel(){return this.getProperty(f.showlabel)==="true"}set showlabel(t){N.IsNullOrUndefined(t)||this.setProperty(f.showlabel,String(t))}get fieldLabelAlignment(){let t=be.labelAlignment,r=this.getProperty(f.Fieldlabelalignment);return N.IsNullOrUndefined(r)?t:r}set fieldLabelAlignment(t){N.IsNullOrUndefined(t)||this.setProperty(f.Fieldlabelalignment,t)}get fieldLabelPosition(){let t=this.getProperty(f.Fieldlabelposition);return N.IsNullOrUndefined(t)?be.labelPosition:t}set fieldLabelPosition(t){N.IsNullOrUndefined(t)||this.setProperty(f.Fieldlabelposition,String(t))}get showbar(){return this.getProperty(f.showbar)==="true"}set showbar(t){N.IsNullOrUndefined(t)||this.setProperty(f.showbar,String(t))}get labelwidth(){let t=+this.getProperty(f.LabelWidth);return t===0?QV:t}set labelwidth(t){N.IsNullOrUndefined(t)||t>283&&t<57||this.setProperty(f.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:HV(this.fieldLabelAlignment),Position:JV(this.fieldLabelPosition)},Columns:qD(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()===v.formSection){let i=n;i.Name&&!T.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}isReferencePanelSection(){return!N.IsNullOrUndefined(this)&&!N.IsNullOrUndefined(this.Name)&&this.Name.indexOf(be.referencePanelNamePrefix)===0}getAllMultiRowCells(){return this.findAll(t=>{if(t.getNodeName()===v.formCell){let r=t;return!r.isEmpty()&&r.rowspan>1}return!1})}isHeaderOrFooterSection(){return this.NodeName===v.formFooter||this.NodeName===v.formHeader}}});var Dn,nu=I(()=>{"use strict";K();He();Jo();Dn=class e extends H{constructor(t){super(v.formColumn,t)}initializeDefaultProperties(t){this.addProperty(f.width,t.toString()+"%")}insertSectionAtIndex(t,r){this.addGrandChildAtIndex(v.formSections,t,r)}static createAndInitNewSection(t,r,n){let i=new Ar(v.formSection,null);return i.initialize(t,r,n),i}addSectionAtIndex(t,r){this.addGrandChildAtIndex(v.formSections,t,r)}initialize(t,r,n,i=Ce.ONE_COLUMN){this.initializeDefaultProperties(t);let a=e.createAndInitNewSection(r,n,i);this.addSectionAtIndex(a,this.sections.length),a.setUniqueName()}get parentTab(){return this.getAncestor(v.formTab)}get sections(){let t=this.getChildren("sections");return t.length!==1?[]:t[0].getChildren(v.formSection)}get width(){return this.getProperty(f.width)}set width(t){this.setProperty(f.width,t)}deleteSection(t){return this.deleteFirstGrandChildOfName(v.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(f.Name),Id:this.getProperty(f.id),Label:null,ShowLabel:!1,Visible:!0,LabelId:null,PreviewId:this.getProperty(f.id),Sections:await this.getSectionsJSON(t),Width:this.width}}}});var iu,VD=I(()=>{"use strict";Me();K();rr();Jo();iu=class extends Ar{initializeNavArea(t,r,n){this.initializeNavAreaProps(t,r,n)}get AreaName(){return this.Name}initializeNavAreaProps(t,r,n){this.addProperty(f.Name,n),this.addProperty(f.id,new P(P.NewGuid()).guidString),this.addProperty(f.columnName,be.columns),this.setDisplayName(r,t)}}});var au,GD=I(()=>{"use strict";nu();K();VD();au=class extends Dn{addAndIntializeNavBarSection(t,r,n,i){let a=new iu(v.formSection,null);return a.initializeNavArea(t,r,i),this.addGrandChildAtIndex(v.formSections,a,n),a}}});var Jr,ou=I(()=>{"use strict";Me();xe();ot();nu();K();He();Nn();Jr=class extends st{tabContainsAutoExpandControl;autoExpandCell;constructor(t,r){super(v.formTab,t),this.tabContainsAutoExpandControl=!1}getParentForm(){return this.getAncestor(v.form)}getTabLayoutType(){let t;switch(this.columns.length){case 1:t=Ae.ONE_COLUMN;break;case 2:if(parseInt(this.columns[0].width,10)===50&&parseInt(this.columns[1].width,10)===50){t=Ae.TWO_COLUMN_EQUAL;break}if(parseInt(this.columns[0].width,10)===67&&parseInt(this.columns[1].width,10)===33){t=Ae.TWO_COLUMN_WIDER_LEFT;break}if(parseInt(this.columns[0].width,10)===34&&parseInt(this.columns[1].width,10)===66){t=Ae.TWO_COLUMN_WIDER_RIGHT;break}t=Ae.TWO_COLUMN_CUSTOM_LAYOUT;break;case 3:if(parseInt(this.columns[0].width,10)===34&&parseInt(this.columns[1].width,10)===33&&parseInt(this.columns[2].width,10)===33){t=Ae.THREE_COLUMN_EQUAL;break}if(parseInt(this.columns[0].width,10)===28&&parseInt(this.columns[1].width,10)===44&&parseInt(this.columns[2].width,10)===28){t=Ae.THREE_COLUMN_WIDER_MID;break}t=Ae.THREE_COLUMN_CUSTOM_LAYOUT;break;default:}return t}initializeProperties(t,r,n){this.addProperty(f.Name,bn.namePrefix+t.toString()),this.addProperty(f.id,new P(P.NewGuid()).guidString),this.addProperty(f.IsUserDefined,bn.IsUserDefined),this.addProperty(f.locklevel,bn.LockLevel),this.addProperty(f.showlabel,bn.ShowLabel),this.setDisplayName(n,r)}get TotalSectionsCount(){let t=0;for(let r of this.columns)t+=r.sections.length;return t}initializeColumns(t,r,n,i=Ce.ONE_COLUMN,a=!0,o){let s=this.getChildren(v.formColumns)[0],l=[];switch(t){case Ae.ONE_COLUMN:l.push(100);break;case Ae.TWO_COLUMN_EQUAL:l.push(50),l.push(50);break;case Ae.TWO_COLUMN_WIDER_LEFT:l.push(67),l.push(33);break;case Ae.TWO_COLUMN_WIDER_RIGHT:l.push(34),l.push(66);break;case Ae.THREE_COLUMN_EQUAL:l.push(34),l.push(33),l.push(33);break;case Ae.THREE_COLUMN_WIDER_MID:l.push(28),l.push(44),l.push(28);break;default:}for(let u of l){let c=new Dn(s);c.initialize(u,r,n,i),this.addGrandChild(v.formColumns,c)}}initialize(t,r,n,i,a,o=Ce.ONE_COLUMN,s=!0,l){this.addChild(new H(v.formColumns,this)),this.initializeProperties(r,n,i),this.initializeColumns(t,n,a,o,s,l)}get columns(){let t=this.getChildren(v.formColumns);return t.length!==1?[]:t[0].getChildren(v.formColumn)}get expanded(){return this.getProcessedValue(f.expanded)}set expanded(t){N.IsNullOrUndefined(t)||this.setProperty(f.expanded,String(t))}get groupName(){return this.getProperty(f.groupName)}get contentType(){return this.getProperty(f.contentType)}set contentType(t){this.setProperty(f.contentType,t)}insertNewColumnAtIndex(t,r,n,i,a){t.initialize(n,i,a),this.addGrandChildAtIndex(v.formColumns,t,r)}insertColumnAtIndex(t,r){this.addGrandChildAtIndex(v.formColumns,t,r)}deleteColumn(t){return this.deleteFirstGrandChildOfName(v.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()===v.formTab){let i=n;i.Name&&!T.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}}});var ni,Wf=I(()=>{"use strict";Me();K();He();rr();GD();ou();ni=class extends Jr{constructor(t,r,n){super(t,Ae.THREE_COLUMN_EQUAL),this.setDisplayName(r,n),this.id=new P(P.NewGuid())}initializeDefaultProps(){this.addChild(new H(v.formColumns,this)),this.initializeFiveColumns()}get columns(){let t=this.getChildren("columns");return t.length!==1?[]:t[0].getChildren(v.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<Ul.FIVE_COLUMN;t++){let r=new au(this.getChildren(v.formColumns)[0]);r.initializeDefaultProperties(cw.FiveEqColumn),this.addGrandChild(v.formColumns,r)}}}});function KV(e){switch(e){case Ue.Main:return An.Main;case Ue.QuickCreate:return An.QuickCreate;case Ue.QuickViewForm:return An.Quick;case Ue.Dialog:return An.Dialog;default:return An.None}}function YV(e,t){if(t===Ue.Main){if(e)switch(e.toLowerCase()){case"low":return yn.Low;case"highreadonlyvalues":return yn.HighReadOnlyValues;default:return yn.HighWithControls}return yn.Low}}var lu,XV,su,zD=I(()=>{"use strict";vw();lu=se(Jn());Jp();xe();ot();Bi();kf();K();Vi();pp();Hn();Ho();K();Nn();Gf();Wf();ou();XV="1920";su=class e extends st{_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(v.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 Cl,this._metadataChangeEvent=new ql}get FormLibraries(){let t=this.getFirstChild(v.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 Et).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 Et){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()===v.internalLibraries),r=[],n="src";return t.length>0&&(r=t.map(i=>{let a=i.GetPropertyByParameter(n).replace("$webresource:",""),o=new da(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,lu.trackErrorTrace)(Lb,{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 T.IsNullOrEmpty(this.getProperty(f.ShowImage))?!0:this.getProperty(f.ShowImage)!=="false"}set ShowImagecheck(t){t?this.setProperty(f.ShowImage,String(t)):this.setProperty(f.ShowImage,"false")}get ShowNavigation(){return T.IsNullOrEmpty(this.getProperty(f.ShowNavigationbar))?!0:this.getProperty(f.ShowNavigationbar)!=="false"}set ShowNavigation(t){t?this.setProperty(f.ShowNavigationbar,String(t)):this.setProperty(f.ShowNavigationbar,"false")}get MaxWidth(){return T.IsNullOrEmpty(this.getProperty(f.MaxWidth))?XV:this.getProperty(f.MaxWidth)}set MaxWidth(t){this.setProperty(f.MaxWidth,t)}get headerDensityType(){return this.getProperty(f.HeaderDensityType)}set headerDensityType(t){t&&this.formType===Ue.Main?this.setProperty(f.HeaderDensityType,t):this.formType!==Ue.Main&&this.headerDensityType&&this.removeProperty(f.HeaderDensityType)}IsMainOrQuickCreateForm(){return this.formType===Ue.Main||this.formType===Ue.QuickCreate}get FormPresentation(){return this._formPresentation}get LanguageCode(){return this._langCode}set LanguageCode(t){this._langCode=t}get header(){let t=this.getChildren(v.formHeader);return t.length!==1?null:t[0]}set header(t){N.IsNullOrUndefined(t)||(this.deleteChild(this.header),this.addChild(t))}getAllDependencies(){return this.getChildren(v.quickFormDependencies).length===0?[]:this.ConvertModelToArray(this.getChildren(v.quickFormDependencies)[0].getAllChildren())}ConvertModelToArray(t){let r=[];return N.IsNullOrUndefined(t)||t.forEach(n=>{r.push(n.id)}),r}get footer(){let t=this.getChildren(v.formFooter);return t.length!==1?null:t[0]}set footer(t){N.IsNullOrUndefined(t)||(this.deleteChild(this.footer),this.addChild(t))}createAndInitNewTab(t,r,n){let i=new Jr(null,t),a=this.getNextTabCounter(this.tabs.length+1);return i.initialize(t,a,this.LanguageCode,r,n),i}addTabAtIndex(t,r){this.addGrandChildAtIndex(v.formTabs,t,r)}createAndInitNewTabWithMarginalControl(t,r,n,i,a){let o=new Jr(null,Ae.ONE_COLUMN),s=this.getNextTabCounter(this.tabs.length+1);o.initialize(Ae.ONE_COLUMN,s,this.LanguageCode,r,n,a,!1),this.addGrandChildAtIndex(v.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===bn.namePrefix+t.toString())return this.getNextTabCounter(t+1);return t}get allTabs(){let t=this.getChildren(v.formTabs);return t.length!==1?[]:t[0].getChildren(v.formTab)}get CanvasNavigationTab(){if(this.tabs.length>0){let t=this.tabs[this.tabs.length-1];if(t instanceof ni)return t}return null}get NavigationNode(){let t=this.getChildren(v.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(v.formTabs,t)}insertTabAtIndex(t,r){this.addGrandChildAtIndex(v.formTabs,t,r)}insertRelatedTab(t){let r=this.getAllGrandChildren(v.formTabs);if(!N.IsNullOrUndefined(r)){let n=r.length;this.insertTabAtIndex(t,n)}}get isfooterPresent(){return this.getChildren(v.formFooter).length>0}get displayCondition(){let t=this.getChildren(v.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(v.formTabs).indexOf(t)}get ControlDescriptions(){return this.getAllGrandChildren(v.controlDescriptions)}addControlDescriptionNode(t){this.addGrandChild(v.controlDescriptions,t)}deleteControlDescByForControlId(t){let r=this.getControlDescriptionByForControl(t);N.IsNullOrUndefined(r)||this.deleteFirstGrandChildOfName(v.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 Et))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 Et&&i.control&&t.control&&a&&i.control.dataFieldName===t.control.dataFieldName})}isCellEditableGridControl(t){return!t?.control?.indicationOfSubgrid||t.control.ClassId.guidString.toUpperCase()!==S.CustomControl?!1:this.cellHasCustomControlWithName(t,wn.EditableGridControl)||LD.getConfig()?.enableOneGridEventsForFormDesigner&&this.cellHasCustomControlWithName(t,wn.PowerAppsOneGrid)}isCellCanvasAppControl(t){return t?.control?.ClassId.guidString.toUpperCase()===S.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()===v.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 ni)){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,lu.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===Ue.Main?{HeaderDensity:YV(this.headerDensityType,this.formType)}:{},InlineEditGridRow:[],InlineQuickForms:[],QuickFormEntities:[],EventHandlers:[],LinkControlSections:[],FormType:KV(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 uu,jf,WD=I(()=>{"use strict";Me();xe();K();He();Nn();uu=class extends st{constructor(t){super(v.formDisplayConditions,t)}get Order(){let t=this.getProperty(f.Order);return N.IsNullOrUndefined(t)?null:parseInt(t,10)}set Order(t){this.setProperty(f.Order,t.toString())}get FallbackForm(){return this.getProperty(f.FallbackForm)==="true"}set FallbackForm(t){this.setProperty(f.FallbackForm,t.toString())}addRoles(t){this.deleteAllChildren();for(let r=0;r<t.length;r++)this.addChild(t[r])}isRoleEveryone(){return!!(this.getChildren(v.formEveryOne)&&this.getChildren(v.formEveryOne)[0])}setRoleEveryone(){this.deleteAllChildren(),this.addChild(new jf(this))}},jf=class extends H{constructor(t){super(v.formEveryOne,t)}}});var cu,jD=I(()=>{"use strict";K();He();cu=class extends H{constructor(t,r){super(v.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(f.HandlerUniqueId)}set HandlerUniqueID(t){this.setProperty(f.HandlerUniqueId,t)}get FunctionName(){return this.getProperty(f.functionName)}set FunctionName(t){this.setProperty(f.functionName,t)}get LibraryName(){return this.getProperty(f.libraryNameEventHandler)}set LibraryName(t){this.setProperty(f.libraryNameEventHandler,t)}get Enabled(){return this.getProperty(f.enabledForField)}set Enabled(t){this.setProperty(f.enabledForField,t)}get PassExecutionContext(){return this.getProperty(f.passExecutionContext)}set PassExecutionContext(t){this.setProperty(f.passExecutionContext,t)}get Parameters(){return this.getProperty(f.parameters)}set Parameters(t){this.setProperty(f.parameters,t)}}});var pa,Hf=I(()=>{"use strict";K();Jo();pa=class extends Ar{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(v.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 Qo,HD=I(()=>{"use strict";K();Hf();Qo=class extends pa{_customFooter;constructor(t,r){super(v.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 Xo,JD=I(()=>{"use strict";K();Hf();Xo=class extends pa{_customHeader;constructor(t,r){super(v.formHeader,t),this._customHeader=r}get customHeader(){return this._customHeader}set customHeader(t){this._customHeader=t}get showCommandBar(){return this.getProcessedValue(f.showCommandBar)}set showCommandBar(t){t!=null&&this.setProperty(f.showCommandBar,String(t))}get showBody(){return this.getProcessedValue(f.showBody)}set showBody(t){t!=null&&this.setProperty(f.showBody,String(t))}get showTabNavigator(){return this.getProcessedValue(f.showTabNavigator)}set showTabNavigator(t){t!=null&&this.setProperty(f.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 Nt,ii=I(()=>{"use strict";Me();ot();K();Nn();Nt=class e extends st{constructor(t,r){super(t,r)}getTitle(t){for(let r of this.getAllTitles())if(+r.getProperty(f.LCID)===t)return r.getProperty(f.text);return null}getAllTitles(){let t=this.getChildren(v.Titles);return t.length===0?[]:t[0].getChildren(v.Title)}setTitle(t,r){for(let i of this.getAllTitles())if(+i.getProperty(f.LCID)===r){i.setProperty(f.text,t);return}let n=new e(v.Title,null);n.setProperty(f.text,t),n.setProperty(f.LCID,String(r)),this.addGrandChild(v.Titles,n)}get Sequence(){return+this.getProperty(f.Sequence)}set Sequence(t){this.setProperty(f.Sequence,t.toString())}get Area(){return this.getProperty(f.Area)}set Area(t){this.setProperty(f.Area,t)}set Id(t){this.setProperty(f.Id,t)}get Id(){return this.getProperty(f.Id)}get id(){return new P(this.Id??"",!0)}set id(t){this.Id=t.guidString}get Show(){return!0}get Icon(){return this.getProperty(f.icon)}set Icon(t){t=t||T.EmptyString,this.setProperty(f.icon,t)}updateCommonProperties(t,r){this.Area=t.Area,this.Sequence=t.Sequence,this.setTitle(t.getDisplayName(r),r)}}});var Ko,QD=I(()=>{"use strict";(function(e){e[e.NavLinkNotAvailable=-1]="NavLinkNotAvailable",e[e.NavLinkIdConflict=-2]="NavLinkIdConflict",e[e.NavBarNotAvailable=-3]="NavBarNotAvailable"})(Ko||(Ko={}))});var du,XD=I(()=>{"use strict";xe();K();ii();QD();du=class extends Nt{constructor(t){super(v.formNavBar,t)}addChildElement(t){this.addChild(t)}getAllActiveNavBarChildren(){return this.getAllChildren().filter(n=>n.Show)}getAllInActiveActiveNavBarChildren(){return this.getAllChildren().filter(n=>!n.Show)}get AllRelationShipItems(){return this.getChildren("NavBarByRelationshipItem")}get AllNavLinkItems(){return this.getChildren("NavBarItem")}removeNavLink(t){let r=this.getNavBarLinkItemById(t);return N.IsNullOrUndefined(r)?Ko.NavLinkNotAvailable:r.length===1?this.deleteChild(r[0]):Ko.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 ge,ZV,KD,hte,fa,Jf=I(()=>{"use strict";Me();K();ii();(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"})(ge||(ge={}));ZV=new Map([[ge.Info,"Info"],[ge.Sales,"Sales"],[ge.Service,"Service"],[ge.Marketing,"Marketing"],[ge.ProcessCenter,"ProcessCenter"]]),KD=new Map([["Info",ge.Info],["Sales",ge.Sales],["Service",ge.Service],["Marketing",ge.Marketing],["ProcessCenter",ge.ProcessCenter]]),hte=new Map([[ge.Info,9e3],[ge.Sales,9200],[ge.Service,9400],[ge.Marketing,9600],[ge.ProcessCenter,9800],[ge.InternetMarketing,1e4],[ge.Async,10200]]),fa=class extends Nt{constructor(t,r){super(v.formNavBarArea,r)}setDefaultPropertiesByType(t,r,n){this.AreaId=ZV.get(t);let i=n?.(`navBarArea.title.${this.AreaId}`)??this.AreaId;this.setTitle(i,r)}get ParentNavigation(){return this.getAncestor(v.formNavigation)}get AreaId(){return this.getProperty(f.Id)}set AreaId(t){this.setProperty(f.Id,t)}get id(){return new P(this.AreaId??"",!0)}set id(t){this.AreaId=t.guidString}async toJSON(t){return{Id:this.AreaId,Titles:[{LCID:t.langCode,Text:this.getTitle(t.langCode)}],PreviewId:this.AreaId}}}});var ma,Qf=I(()=>{"use strict";K();ii();ma=class extends Nt{constructor(t,r){super(v.formNavBarAreas,r)}get AllNavBarAreaItems(){return this.getChildren(v.formNavBarArea)}get ParentNavigation(){return this.getAncestor(v.formNavigation)}addNavBarArea(t){this.addChild(t)}}});var pu,YD=I(()=>{"use strict";xe();K();ii();pu=class extends Nt{RelationshipNameUCIRuntime;constructor(t){super(v.formNavBarByRelationshipItem,t)}get RelationshipName(){return this.getProperty(f.RelationshipName)}set RelationshipName(t){this.setProperty(f.RelationshipName,t)}set Show(t){this.setProperty(f.Show,String(t))}get Show(){let t=this.getProperty(f.Show);return N.IsNullOrUndefined(t)||t==="true"}get TitleResourceId(){return this.getProperty(f.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 fu,ZD=I(()=>{"use strict";K();ii();fu=class extends Nt{constructor(t){super(v.formNavBarItem,t)}get Url(){return this.getProperty(f.url)}set Url(t){this.setProperty(f.url,t)}}});var mu,e2=I(()=>{"use strict";Me();K();Jf();Qf();ii();mu=class extends Nt{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(v.formNavBarAreas)}setDefaultNavBarAreas(t,r){let n=[ge.Info,ge.Sales,ge.Service,ge.Marketing,ge.ProcessCenter];if(this.navBarAreas){let i=this.navBarAreas?.AllNavBarAreaItems;if(i&&i.length>0){let a=new Set(i.map(o=>KD.get(o.AreaId)));n=n.filter(o=>!a.has(o))}}else{let i=new ma(v.formNavBarAreas,this);i.isTransient=!0,this.addChild(i)}return n.length>0?(n.forEach(i=>{let a=new fa(v.formNavBarArea,this.navBarAreas);a.setDefaultPropertiesByType(i,t,r),this.navBarAreas.addNavBarArea(a)}),!0):!1}get navBar(){return this.getFirstChild(v.formNavBar)}get id(){return new P(Ep,!0)}replaceNavAreaToGivenIndex(t,r){this.navBarAreas?.AllNavBarAreaItems.indexOf(r)!==-1&&(this.deleteFirstGrandChildOfName(v.formNavBarAreas,r),this.addGrandChildAtIndex(v.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 t2={};Rr(t2,{ControlType:()=>$t,DeserializationService:()=>Yf,DeserializationServiceScope:()=>Kf,DeserializedFormElementNode:()=>Dt});var Xf,Dt,Kf,$t,Yf,Vf=I(()=>{"use strict";Xf=se(Jn());Me();xe();ot();Bi();Np();Hn();kb();gw();$l();zD();Ho();nu();jo();Mf();K();K();WD();He();rr();Uf();jD();HD();Bf();$f();JD();Gf();zf();Jo();ou();XD();Jf();Qf();YD();ZD();e2();Dt=class extends H{constructor(t,r){super(t,r)}insertProperty(t,r){this.addProperty(t,r)}insertChild(t){this.addChild(t)}},Kf="DeserializationService";(function(e){e.Grid="Grid",e.Lookup="Lookup",e.Base="Base"})($t||($t={}));Yf=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 m="";throw d.length===0?m="FormXml has no form node.":m="FormXml has multiple form nodes.",(0,Xf.trackErrorTrace)(dt,{eventName:Kf,eventData:{error:m}}),new Error(m)}let p=this.createFormModel(d.item(0),r,n,i,a,o,s,l,u,c);return N.IsNullOrUndefined(p.displayCondition)&&s!==Ue.Dialog&&this.appendDefaultDisplayCondition(p),p}upsertFieldCount(t,r){let n=Qn.getNecessaryLookUpTable(r),i=1;n.containsKey(t)&&(i+=n.getValue(t)),n.upsert(t,i)}appendDefaultDisplayCondition(t){let r='<DisplayConditions Order="0" FallbackForm="true"><Everyone/></DisplayConditions>';if(!N.IsNullOrUndefined(t)){let n=N.ParseXml(r);n!==null&&this.populateElementChildren(t,n.childNodes)}}createFormModel(t,r,n,i,a,o,s,l,u,c){let d=new su(r,n,i,a,o,s,l,u,c);return this.populateElementProperties(d,t.attributes),this.populateElementChildren(d,t.childNodes),s===Ue.Main&&(this.insertHeaderFooterElementProperties(v.formHeader,d,d.header),this.insertHeaderFooterElementProperties(v.formFooter,d,d.footer)),d}insertHeaderFooterElementProperties(t,r,n){if(N.IsNullOrUndefined(n)){let i=t===v.formHeader?new Xo(r,!0):new Qo(r,!0);Dt.prototype.insertProperty.call(i,f.id,"{"+P.NewGuid()+"}"),Dt.prototype.insertProperty.call(i,f.Fieldlabelposition,"Top"),Dt.prototype.insertProperty.call(i,f.columnName,be.MarginalControlColumns),Dt.prototype.insertProperty.call(i,f.LabelWidth,be.LabelWidth),Dt.prototype.insertProperty.call(i,f.Fieldlabelalignment,"Left");let a=null,o=new ri(a);for(let s=0;s<i.maxColumns;s++){let l=new Et(o);Dt.prototype.insertProperty.call(l,f.id,"{"+P.NewGuid()+"}"),l.setDisplayName(T.EmptyString,this.lcid),Dt.prototype.insertProperty.call(l,f.showlabel,"false"),o.addCell(l)}i.appendRow(o),t===v.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 Dt(`<${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,Xf.trackErrorTrace)(dt,{eventName:Kf,eventData:{error:n}}),new Error(n)}for(let n=0;n<r.length;n++){let i=r.item(n);i&&(Dt.prototype.insertProperty.call(t,i.name,i.value),t.getNodeName()===v.formCell&&i.name===f.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&&Dt.prototype.insertChild.call(t,a)}}createModelNode(t,r){switch(t.nodeName){case v.form:throw new Error("Form node shouldn't be created using this method");case v.formTab:return new Jr(r);case v.formColumn:return new Dn(r);case v.formHeader:return new Xo(r,!1);case v.formFooter:return new Qo(r,!1);case v.formSection:return new Ar(v.formSection,r);case v.formRow:return new ri(r);case v.formCell:return new Et(r);case v.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===f.indicationOfSubgrid&&l.value==="true"||l.name===f.classid&&(l.value?.toLocaleUpperCase()===`{${S.SubgridControl}}`||l.value?.toLocaleUpperCase()===`{${S.ReferencePanelSubgridControl}}`))a=$t.Grid;else if(l.name===f.classid&&l.value?.toLocaleUpperCase()===`{${S.LookupControl}}`)a=$t.Lookup;else if(l.name===f.classid&&l.value?.toLocaleUpperCase()===`{${S.CustomControl}}`)for(let u=0;u<i?.length;u++)i[u].nodeName===f.DefaultViewId&&(a=$t.Lookup)}return a===$t.Grid?new ua(r):a===$t.Lookup?new ca(r):new ar(r);case v.formEvent:return new la(r,T.EmptyString);case v.dependency:return this.populateDependencyTable(t),new sa(r,T.EmptyString);case v.Handler:let o=[];return new cu(o,r);case v.formNavigation:return new mu(t.nodeName,r);case v.formNavBarArea:return new fa(t.nodeName,r);case v.formNavBarAreas:return new ma(t.nodeName,r);case v.formNavBar:return new du(r);case v.formNavBarByRelationshipItem:return new pu(r);case v.formNavBarItem:return new fu(r);case v.formDisplayConditions:return new uu(r);case v.library:return new da(r,T.EmptyString,T.EmptyString);case v.controlDescription:return new Il(r);case v.customControl:return this.populateCustomControlConfigurationId(t),new Bl(r);default:return new Dt(t.nodeName,r)}}populateDependencyTable(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);i.name===f.id&&this.upsertFieldCount(i.value,vr.DependencyFieldTable)}}populateCustomControlConfigurationId(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);if(i.name===f.id){let a=new P(i.value.substr(1,i.value.length-2));for(let o=0;o<t.parentNode.attributes.length;o++){let s=t.parentNode.attributes.item(o);if(s.name===f.ForControl){let l=s.value.substr(1,i.value.length-2);Be.CustomControlIdMap.upsert(l,a);break}}break}}}}});var r2={};Rr(r2,{SerializationService:()=>Zf,SerializationServiceScope:()=>e9,SerializedFormElementNode:()=>ha});var e9,ha,Zf,n2=I(()=>{"use strict";ot();He();rr();Wf();e9="SerializationService",ha=class extends H{fetchNodeName(){return this.getNodeName()}enumerateProperties(){return this.getAllProperties()}enumerateChildren(){return this.getAllChildren()}},Zf=class{langCode;constructor(t){this.langCode=t}serializeFormXmlNode(t){let r=ha.prototype.fetchNodeName.call(t);if(r.charAt(0)===jr.StartTag)return T.EscapeXml(r.substr(1),!1);if(t.isTransient&&!t.isDirty())return T.EmptyString;let n=ha.prototype.enumerateProperties.call(t),i=ha.prototype.enumerateChildren.call(t);if(!(t instanceof ni)){let a=`<${r}`;if(n.length!==0&&(a+=` ${this.getPropertiesString(n)}`),i.length===0)a+=" />";else{let o=T.EmptyString;for(let s of i)o+=this.serializeFormXmlNode(s);a+=`>${o}</${r}>`}return a}return T.EmptyString}getPropertiesString(t){let r=T.EmptyString;return t.forEach((n,i)=>{i!==0&&(r+=" "),r+=`${n.key}="${T.EscapeXml(n.value,!0)}"`}),r}}});var In=g(hu=>{"use strict";Object.defineProperty(hu,"__esModule",{value:!0});hu.installDomShim=void 0;var i2=yl(),a2=!1,t9={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 r9(){if(a2)return;let e=globalThis;typeof e.DOMParser>"u"&&(e.DOMParser=i2.DOMParser),typeof e.XMLSerializer>"u"&&(e.XMLSerializer=i2.XMLSerializer),typeof e.Node>"u"&&(e.Node=t9),a2=!0}hu.installDomShim=r9});var C2=g(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.classIdForAttributeType=It.QUICK_VIEW_CLASS_ID=It.NOTES_CLASS_ID=It.SUBGRID_CLASS_ID=It.formRegistration=It.FormAdapter=void 0;var qt=(Me(),Fr(Ib)),n9=(xe(),Fr(_b)),i9=(He(),Fr(Tb)),lt=(K(),Fr(Pb)),Le=(Hn(),Fr(Ob)),a9=(Vf(),Fr(t2)),o9=(n2(),Fr(r2)),$e=mn(),o2=Yt(),ai=ur(),s9=Ud(),d2=yt(),nm=ee(),p2=In(),f2=Ei(),l9={[lt.FormType.Main]:"Main",[lt.FormType.QuickCreate]:"QuickCreate",[lt.FormType.QuickViewForm]:"QuickView",[lt.FormType.Card]:"Card"},em={Main:lt.FormType.Main,QuickCreate:lt.FormType.QuickCreate,QuickView:lt.FormType.QuickViewForm,Card:lt.FormType.Card},u9=new Map(Object.entries(Le.ControlClassId).map(([e,t])=>[String(t).toUpperCase(),e]));function m2(e){var t;return e&&(t=u9.get(e.toUpperCase()))!==null&&t!==void 0?t:"Unknown"}function Yo(e){return e.getAllProperties().map(t=>[t.key,t.value])}function oi(e){let t=new Map;for(let r of e.getAllProperties())t.has(r.key)||t.set(r.key,r.value);return t}function h2(e,t){return e.getAllChildren().find(r=>r.getNodeName()===t)}function im(e,t){var r,n;let i=h2(e,"labels");if(!i)return"";let a=i.getAllChildren().filter(s=>s.getNodeName()==="label"),o=(r=a.find(s=>oi(s).get("languagecode")===String(t)))!==null&&r!==void 0?r:a[0];return o&&(n=oi(o).get("description"))!==null&&n!==void 0?n:""}function c9(e){let t=h2(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 g2(e){return/^1+$/.test(e)&&e.length>=1&&e.length<=4?e.length:1}function tm(e){let t=Math.min(Math.max(Math.trunc(e),1),4);return"1".repeat(t)}function Zo(e){return String(e??"").replace(/[{}]/g,"")}function rm(e){return`{${Zo(e)}}`}function s2(e,t){if(e===void 0||e==="")return t;let r=Number(e);return Number.isNaN(r)?t:r}function vu(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,$e.rawFromNode)(u)})}),i<0)return{modeled:[],bag:{a:Yo(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,$e.rawFromNode)(u)})}),{modeled:s,bag:{a:Yo(e),c:a,w:{n:o.getNodeName(),a:Yo(o),c:l}}}}function v2(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,$e.rawFromNode)(a)})}),{modeled:n,bag:{a:Yo(e),c:i}}}function d9(e,t){let{modeled:r,bag:n}=vu(e,"tabs","tab");return{tabs:r.map(i=>p9(i,t)),bag:n}}function p9(e,t){var r,n;let i=oi(e),{modeled:a,bag:o}=vu(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:im(e,t),expanded:i.get("expanded")==="true",visible:i.has("visible")?i.get("visible")==="true":!0,columns:a.map(s=>f9(s,t)),bag:o}}function f9(e,t){let r=oi(e),{modeled:n,bag:i}=vu(e,"sections","section");return{width:r.get("width"),sections:n.map(a=>m9(a,t)),bag:i}}function m9(e,t){var r,n,i;let a=oi(e),{modeled:o,bag:s}=vu(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:im(e,t),visible:a.has("visible")?a.get("visible")==="true":!0,showLabel:a.get("showlabel")==="true",columns:g2((i=a.get("columns"))!==null&&i!==void 0?i:"1"),rows:o.map(l=>h9(l,t)),bag:s}}function h9(e,t){let{modeled:r,bag:n}=v2(e,"cell",!1);return{cells:r.map(i=>g9(i,t)),bag:n}}function g9(e,t){var r;let n=oi(e),{modeled:i,bag:a}=v2(e,"control",!0),o=im(e,t),s=n.get("showlabel")==="true",l=i[0]?v9(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:s2(n.get("colspan"),1),rowspan:s2(n.get("rowspan"),1),control:l,bag:a}}function v9(e,t,r){var n,i;let a=oi(e),o=Zo((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:m2(o),isRequired:a.get("isrequired")==="true",isReadOnly:a.get("disabled")==="true",label:t,showLabel:r,parameters:c9(e),bag:{a:Yo(e),c:e.getAllChildren().map((l,u)=>({i:u,node:(0,$e.rawFromNode)(l)}))}}}function ga(e){return e.a.length===0&&e.c.length===0&&!e.w}function y2(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function si(e,t){var r;let n=new Set(e.a.map(o=>o[0])),i=ga(e),a=[];for(let o of t)if(n.has(o.key)){let s=(r=y2(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,$e.mergeAttrs)(e.a,a)}var _n=(e,t)=>({key:e,matches:r=>r===t,render:()=>t,absentDefault:""}),Pn=(e,t,r=!1)=>({key:e,matches:n=>n==="true"===t,render:()=>String(t),absentDefault:String(r)}),l2=(e,t,r=1)=>({key:e,matches:n=>Number(n)===t,render:()=>String(t),absentDefault:String(r)});function am(e,t){return{n:"labels",a:[],c:[{n:"label",a:[["description",e],["languagecode",String(t)]],c:[]}]}}function b2(e){return{n:"parameters",a:[],c:Object.keys(e).map(t=>({n:(0,nm.assertXmlName)(t,"Form control parameter name"),a:[],c:[{n:`<${e[t]}`,a:[],c:[]}]}))}}function y9(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 b9(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 om(e,t,r){let n=e.c.findIndex(a=>a.node.n==="labels");if(n<0||y9(e.c[n].node,r)===t)return e;let i=b9(e.c[n].node,t,r);return{...e,c:e.c.map((a,o)=>o===n?{...a,node:i}:a)}}function w9(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 A9(e,t){let r=Object.keys(e),n=Object.keys(t);return r.length===n.length&&r.every(i=>e[i]===t[i])}function C9(e,t){return e.a.some(r=>r[0]===t)?{...e,a:e.a.filter(r=>r[0]!==t)}:e}function S9(e,t){let r=e.c.findIndex(i=>i.node.n==="parameters");if(r<0||A9(w9(e.c[r].node),t))return e;let n=b2(t);return{...e,c:e.c.map((i,a)=>a===r?{...i,node:n}:i)}}function yu(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,$e.spliceChildren)(e.w.c,r)};return(0,$e.spliceChildren)(e.c,[o])}let i=n(),a={n:t,a:[],c:r};return e.c.length===0?[...i,a]:(0,$e.spliceChildren)(e.c,[...i,a])}function E9(e,t){let r=e.tabs.map(n=>N9(n,t));return{n:"form",a:si(e.bag,[]),c:e.tabs.length===0&&ga(e.bag)?[]:yu(e.bag,"tabs",r,()=>[])}}function N9(e,t){let r=[_n("id",e.id),_n("name",e.name),Pn("expanded",e.expanded),Pn("visible",e.visible,!0)],n=e.columns.map(a=>D9(a,t)),i=om(e.bag,e.label,t);return{n:"tab",a:si(i,r),c:yu(i,"columns",n,()=>e.label?[am(e.label,t)]:[])}}function D9(e,t){let r=e.width!==void 0?[_n("width",e.width)]:[],n=e.sections.map(i=>I9(i,t));return{n:"column",a:si(e.bag,r),c:yu(e.bag,"sections",n,()=>[])}}function I9(e,t){let r=[_n("id",e.id),_n("name",e.name),Pn("showlabel",e.showLabel),Pn("visible",e.visible,!0),{key:"columns",matches:a=>g2(a)===e.columns,render:()=>tm(e.columns),absentDefault:tm(1)}],n=e.rows.map(a=>_9(a,t)),i=om(e.bag,e.label,t);return{n:"section",a:si(i,r),c:yu(i,"rows",n,()=>e.label?[am(e.label,t)]:[])}}function _9(e,t){let r=e.cells.map(n=>P9(n,t));return{n:"row",a:si(e.bag,[]),c:ga(e.bag)?r:(0,$e.assembleChildren)(e.bag,r)}}function P9(e,t){let r=e.control?e.control.showLabel:y2(e.bag,"showlabel")==="true",n=[_n("id",e.id),Pn("showlabel",r),Pn("visible",e.visible,!0),l2("colspan",e.colspan),l2("rowspan",e.rowspan)],i=e.control?[T9(e.control)]:[],a;if(ga(e.bag))a=[...e.control&&e.control.label?[am(e.control.label,t)]:[],...i];else{let o=e.control?om(e.bag,e.control.label,t):e.bag;a=(0,$e.assembleChildren)(o,i)}return{n:"cell",a:si(e.bag,n),c:a}}function T9(e){let t=[_n("id",e.id),{key:"classid",matches:i=>Zo(i)===e.classId,render:()=>rm(e.classId),absentDefault:""}];e.fieldName!==null&&t.push(_n("datafieldname",e.fieldName)),t.push(Pn("disabled",e.isReadOnly)),t.push(Pn("isrequired",e.isRequired));let r=e.fieldName===null?C9(e.bag,"datafieldname"):e.bag,n;return ga(r)?n=Object.keys(e.parameters).length>0?[b2(e.parameters)]:[]:n=(0,$e.assembleChildren)(S9(r,e.parameters),[]),{n:"control",a:si(r,t),c:n}}var O9={make:(e,t)=>new i9.FormElementNode(e,t),setProp:(e,t,r)=>e.setProperty(t,r),addChild:(e,t)=>e.addChild(t)};function u2(e,t,r){(0,p2.installDomShim)();let n=F9(e,r),i=(0,$e.rebuildRaw)(E9(n,t),O9,null);return new o9.SerializationService(t).serializeFormXmlNode(i)}function R9(e){return JSON.parse(JSON.stringify(e))}function F9(e,t){var r;let n=R9(e);n.bag||(n.bag=(0,$e.emptyBag)()),q9(n.bag),t&&x9(n,t);for(let i of(r=n.tabs)!==null&&r!==void 0?r:[])L9(i);return n}function x9(e,t){var r;let n=(r=e.entityLogicalName)!==null&&r!==void 0?r:"";w2(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=A2(s.attributeType)))})}function w2(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 L9(e){e.id||(e.id=qt.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)k9(t);e.bag||(e.bag=(0,$e.emptyBag)())}function k9(e){e.sections||(e.sections=[]);for(let t of e.sections)M9(t);e.bag||(e.bag=(0,$e.emptyBag)()),e.width===void 0&&ga(e.bag)&&(e.width="100%")}function M9(e){e.id||(e.id=qt.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)U9(t);e.bag||(e.bag=(0,$e.emptyBag)())}function U9(e){e.cells||(e.cells=[]);for(let t of e.cells)B9(t);e.bag||(e.bag=(0,$e.emptyBag)())}function B9(e){e.id||(e.id=qt.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&&$9(e.control),e.bag||(e.bag=(0,$e.emptyBag)())}function $9(e){var t;e.id||(e.id=qt.Guid.NewGuid()),e.classId===void 0&&(e.classId=String(Le.ControlClassId.TextboxControl)),e.fieldName===void 0&&(e.fieldName=null),e.type===void 0&&(e.type=e.fieldName?"Field":m2(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,nm.assertXmlName)(r,"Form control parameter name");e.bag||(e.bag=(0,$e.emptyBag)())}function q9(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"&&!c2(a,"handlerUniqueId")&&a.a.push(["handlerUniqueId",rm(qt.Guid.NewGuid())])}}else if(r.n==="formLibraries")for(let n of r.c)n.n==="Library"&&!c2(n,"libraryUniqueId")&&n.a.push(["libraryUniqueId",rm(qt.Guid.NewGuid())])}}var gu=class{constructor(t=f2.DEFAULT_LCID){this.lcid=t}toArtifact(t,r){var n,i,a;let{tabs:o,bag:s}=d9(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=l9[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:u2(t,this.lcid),formid:t.id||qt.Guid.NewGuid(),objecttypecode:t.entityLogicalName,type:em[t.formType],name:t.name,uniquename:t.name,description:(r=t.description)!==null&&r!==void 0?r:"",formpresentation:lt.FormPresentation.AirForm,formactivationstate:t.status==="Active"?lt.FormActivationState.Active:lt.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:qt.Guid.NewGuid(),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:u2(t,this.lcid,n),name:t.name,type:em[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 w2(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 m=t.tabs&&t.tabs.length>0?void 0:X9(this.lcid),h=m!==void 0?m:t.tabs.map(E=>V9(E,this.lcid)).join(""),w=this.deserialize({formxml:`<form><tabs>${h}</tabs></form>`,formid:t.id||qt.Guid.NewGuid(),objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",type:em[(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:lt.FormPresentation.AirForm,formactivationstate:((s=t.status)!==null&&s!==void 0?s:"Active")==="Active"?lt.FormActivationState.Active:lt.FormActivationState.InActive}),b=this.toArtifact(w,t.description);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,d2.assignMissingIds)(t)}validate(t){return Y9(t)}deserialize(t){(0,p2.installDomShim)();let r=n9.ScriptUtilities.ParseXml(t.formxml),n=new a9.DeserializationService(this.lcid).deSerializeFormXml(r,new qt.Guid(t.formid),t.objecttypecode,lt.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===lt.FormActivationState.InActive?"Inactive":"Active"}};It.FormAdapter=gu;function or(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function sm(e,t){return e?`<labels><label description="${or(e)}" languagecode="${t}" /></labels>`:""}function lm(e){return e&&e.length>0?Zo(e):(0,d2.newId)()}function V9(e,t){var r,n,i,a;let o=(r=e.columns)!==null&&r!==void 0?r:[],s=(o.length>0?o:[Q9()]).map(l=>G9(l,t)).join("");return`<tab id="{${or(lm(e.id))}}" name="${or((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}">${sm(e.label,t)}<columns>${s}</columns></tab>`}function G9(e,t){var r,n;let i=((r=e.sections)!==null&&r!==void 0?r:[]).map(a=>z9(a,t)).join("");return`<column width="${or((n=e.width)!==null&&n!==void 0?n:"100%")}"><sections>${i}</sections></column>`}function z9(e,t){var r,n,i,a,o;let s=((r=e.rows)!==null&&r!==void 0?r:[]).map(l=>W9(l,t)).join("");return`<section id="{${or(lm(e.id))}}" name="${or((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="${tm((o=e.columns)!==null&&o!==void 0?o:1)}">${sm(e.label,t)}<rows>${s}</rows></section>`}function W9(e,t){var r;return`<row>${((r=e.cells)!==null&&r!==void 0?r:[]).map(n=>j9(n,t)).join("")}</row>`}function j9(e,t){var r,n,i,a,o,s;let l=e.control,u=l?sm((n=(r=l.label)!==null&&r!==void 0?r:l.fieldName)!==null&&n!==void 0?n:"",t):"",c=l?H9(l):"";return`<cell id="{${or(lm(e.id))}}" showlabel="${l?(i=l.showLabel)!==null&&i!==void 0?i:!0:!1}" visible="${(a=e.visible)!==null&&a!==void 0?a:!0}" colspan="${(o=e.colspan)!==null&&o!==void 0?o:1}" rowspan="${(s=e.rowspan)!==null&&s!==void 0?s:1}">${u}${c}</cell>`}function H9(e){var t,r,n;let i=e.fieldName?` datafieldname="${or(e.fieldName)}"`:"",a=J9(e.parameters),o=e.classId?Zo(e.classId):String(Le.ControlClassId.TextboxControl);return`<control id="${or((t=e.id)!==null&&t!==void 0?t:"")}" classid="{${or(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 J9(e){let t=Object.keys(e??{});return t.length===0?"":(t.forEach(n=>(0,nm.assertXmlName)(n,"Form control parameter name")),`<parameters>${t.map(n=>`<${n}>${or(e[n])}</${n}>`).join("")}</parameters>`)}function Q9(){return{width:"100%",sections:[],bag:{a:[],c:[]}}}function X9(e){return`<tab id="{${qt.Guid.NewGuid()}}" name="tab_general" expanded="true" visible="true"><labels><label description="General" languagecode="${e}" /></labels><columns><column width="100%"><sections><section id="{${qt.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 K9(e=f2.DEFAULT_LCID){return{adapter:new gu(e),api:s9.formApi,languageSensitive:!0,publish:(t,r,n)=>(0,o2.publishBoundEntity)(t,n),publishScope:(t,r)=>(0,o2.boundEntityPublishScope)(r)}}It.formRegistration=K9;function Y9(e){let t=[];return(0,ai.childObjects)(e,"tabs","","tab",t).forEach(({node:n,index:i})=>{(0,ai.childObjects)(n,"columns",`/tabs/${i}`,"column",t).forEach(({node:o,index:s})=>{let l=`/tabs/${i}/columns/${s}`;(0,ai.childObjects)(o,"sections",l,"section",t).forEach(({node:c,index:d})=>{let p=`${l}/sections/${d}`;(0,ai.childObjects)(c,"rows",p,"row",t).forEach(({node:h,index:w})=>{let b=`${p}/rows/${w}`;(0,ai.childObjects)(h,"cells",b,"cell",t).forEach(({node:D,index:F})=>{let x=D.control;x!=null&&!(0,ai.isJsonObject)(x)&&t.push((0,ai.issue)(`${b}/cells/${F}/control`,"control-must-be-object-or-null",`a cell control must be a JSON object or null, got ${typeof x}`))})})})})}),t}It.SUBGRID_CLASS_ID=Le.ControlClassId.SubgridControl;It.NOTES_CLASS_ID=Le.ControlClassId.TimelineControl;It.QUICK_VIEW_CLASS_ID=Le.ControlClassId.QuickViewControl;var Z9={Lookup:String(Le.ControlClassId.LookupControl),Customer:String(Le.ControlClassId.LookupControl),Owner:String(Le.ControlClassId.LookupControl),PartyList:String(Le.ControlClassId.PartyListControl),Boolean:String(Le.ControlClassId.BooleanControl),DateTime:String(Le.ControlClassId.DateTimeControl),Decimal:String(Le.ControlClassId.DecimalControl),Double:String(Le.ControlClassId.FloatingNumberControl),Money:String(Le.ControlClassId.CurrencyControl),Integer:String(Le.ControlClassId.IntegerControl),BigInt:String(Le.ControlClassId.IntegerControl),Memo:String(Le.ControlClassId.TextAreaControl),String:String(Le.ControlClassId.TextboxControl)},e8="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE";function A2(e){return e==="Picklist"||e==="State"||e==="Status"?e8:e&&Z9[e]||String(Le.ControlClassId.TextboxControl)}It.classIdForAttributeType=A2;function c2(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}});var um=g(va=>{"use strict";Object.defineProperty(va,"__esModule",{value:!0});va.viewApi=va.findDefaultViews=void 0;var E2=Kt(),Vt=ye(),Qr=ee(),t8="savedqueryid,name,description,fetchxml,layoutxml,querytype,returnedtypecode,isdefault",r8="savedqueryid,name,returnedtypecode,querytype,isdefault";async function n8(e,t,r={}){var n;let i=new Set(((n=r.excludeViewIds)!==null&&n!==void 0?n:[]).filter(Boolean)),a=`returnedtypecode eq '${(0,Qr.odataLiteral)(t)}' and querytype eq 0`,o=`/savedqueries${(0,Qr.odataQuery)([["$select","savedqueryid,name,isdefault"],["$filter",a]])}`;return(await(0,E2.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:"")}})}va.findDefaultViews=n8;async function i8(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,Qr.odataLiteral)(t)}')${(0,Qr.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 S2(e,t,r){if(!r||!/<grid\b/.test(t)||/<grid[^>]*\bobject=/.test(t))return t;let n=await i8(e,r);return n===void 0?t:t.replace(/<grid\b/,`<grid object="${n}"`)}va.viewApi={async get(e,t){let n=`/savedqueries(${(0,Qr.normalizeGuid)(t,"id")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Qr.odataQuery)([["$select",t8]]),i=(0,Vt.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,Vt.readEtag)(i)}},async list(e,t){let r=`/savedqueries${(0,Qr.odataQuery)([["$select",r8],["$filter",t?.entityLogicalName?`returnedtypecode eq '${(0,Qr.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,E2.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,Vt.echoWrite)("savedqueryid"),a=`/savedqueries${i.query}`,o=await S2(e,n.layoutxml,n.returnedtypecode),s=(0,Vt.ensureSuccess)(await e.post(a,(0,Vt.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,Vt.resolveCreatedId)(s,"savedqueryid","view",r),etag:(0,Vt.readEtag)(s)}},async update(e,t,r,n){let i=r,a=(0,Qr.normalizeGuid)(t,"id"),o=(0,Vt.echoWrite)("savedqueryid",{"If-Match":(0,Vt.requireEtag)(n,"view",a)}),s=`/savedqueries(${a})${o.query}`,l=await S2(e,i.layoutxml,i.returnedtypecode),u=(0,Vt.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,Vt.readEtag)(u)}},delete(e,t){return(0,Vt.deleteRecord)(e,"savedqueries",t)}}});var M2=g(ba=>{"use strict";Object.defineProperty(ba,"__esModule",{value:!0});ba.viewRegistration=ba.ViewAdapter=void 0;var ya=ur(),cm=mn(),li=Gn(),N2=Yt(),a8=um(),dm=In(),o8=yt(),P2=100,bu=class{toArtifact(t){var r,n,i,a,o,s,l,u;(0,dm.installDomShim)();let c=(r=t.fetchxml)!==null&&r!==void 0?r:"",d=(n=t.layoutxml)!==null&&n!==void 0?n:"",p=(0,li.parseXmlRoot)(c,"<fetch/>"),m=(0,li.parseXmlRoot)(d,"<grid/>");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:s8(p),queryType:(l=t.querytype)!==null&&l!==void 0?l:0,isDefault:(u=t.isdefault)!==null&&u!==void 0?u:!1,columns:O2(m,p),filters:x2(p),sort:F2(p),fetchBag:c?(0,li.projectElementBag)(p):void 0,layoutBag:d?(0,li.projectElementBag)(m):void 0}}fromArtifact(t){(0,dm.installDomShim)();let{fetchxml:r,layoutxml:n}=D2(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,dm.installDomShim)();let{fetchxml:s,layoutxml:l}=D2(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,o8.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:[]}}assignMissingIds(t){return t}validate(t){let r=[],n=t;(0,ya.childObjects)(n,"columns","","column",r),(0,ya.childObjects)(n,"sort","","sort",r);let i=n.filters;return i!=null&&((0,ya.isJsonObject)(i)?T2(i,"/filters",r):r.push((0,ya.issue)("/filters","filters-must-be-object",`filters must be a JSON object, got ${typeof i}`))),r}};ba.ViewAdapter=bu;function T2(e,t,r){(0,ya.childObjects)(e,"conditions",t,"condition",r),(0,ya.childObjects)(e,"groups",t,"filterGroup",r).forEach(({node:i,index:a})=>T2(i,`${t}/groups/${a}`,r))}function s8(e){var t;let r=e.getElementsByTagName("entity")[0];return(t=r?.getAttribute("name"))!==null&&t!==void 0?t:""}function O2(e,t){var r;let n=R2(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)?P2:c,order:o},p=n.get(u);p&&(d.relatedEntity=p),o+=1,a.push(d)}return a}function R2(e){var t;let r=new Map,n=e.getElementsByTagName("link-entity");for(let i=0;i<n.length;i+=1){let a=n[i],o=a.getAttribute("name");if(!o)continue;let s=a.getElementsByTagName("attribute");for(let l=0;l<s.length;l+=1){let u=s[l],c=(t=u.getAttribute("alias"))!==null&&t!==void 0?t:u.getAttribute("name");c&&r.set(c,o)}}return r}function F2(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"})}}return n}function x2(e){let t=e.getElementsByTagName("entity")[0],r={type:"and",conditions:[],groups:[]};if(!t)return r;let n=Gt(t,"filter").filter(i=>!L2(i)).map(k2);return n.length===0?r:n.length===1?n[0]:{type:"and",conditions:[],groups:n}}function L2(e){if(Gt(e,"filter").length>0)return!1;let t=Gt(e,"condition");return t.length===0?!1:t.some(r=>r.getAttribute("isquickfindfields")==="1"||Gt(r,"value").length>0)}function k2(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),i.push(c)}else l.tagName==="filter"&&a.push(k2(l))}return{type:n,conditions:i,groups:a}}function Gt(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 D2(e){let t=l8(e.columns);if(!I2(e.fetchBag)||!I2(e.layoutBag))return{fetchxml:y8({...e,columns:t}),layoutxml:b8({...e,columns:t},`${e.entityLogicalName}id`)};let r=new DOMParser().parseFromString("<root/>","text/xml"),n=_2(e.fetchBag,"fetch",r),i=_2(e.layoutBag,"grid",r),a=O2(i,n),o=!pm(t,a),s=!pm(e.sort,F2(n)),l=!pm(e.filters,x2(n));return o&&(u8(r,n,t,a),f8(r,i,t)),s&&g8(r,n,e.sort),l&&v8(r,n,e.filters),{fetchxml:(0,li.serializeNode)(n),layoutxml:(0,li.serializeNode)(i)}}function l8(e){return(e??[]).map((t,r)=>{var n,i;return{name:String(t.name).toLowerCase(),width:(n=t.width)!==null&&n!==void 0?n:P2,order:(i=t.order)!==null&&i!==void 0?i:r,...t.relatedEntity?{relatedEntity:t.relatedEntity}:{}}})}function I2(e){return!!e&&(e.c.length>0||e.a.length>0)}function _2(e,t,r){let n={n:t,a:(0,cm.mergeAttrs)(e.a,[]),c:(0,cm.spliceChildren)(e.c,[])};return(0,cm.rebuildRaw)(n,(0,li.domEngine)(r),null)}function u8(e,t,r,n){var i;let a=t.getElementsByTagName("entity")[0];if(!a)return;let o=new Set(r.map(u=>{var c;return`${(c=u.relatedEntity)!==null&&c!==void 0?c:""}:${u.name}`}));for(let u of n)o.has(`${(i=u.relatedEntity)!==null&&i!==void 0?i:""}:${u.name}`)||c8(a,u);let s=R2(t),l=new Set(Gt(a,"attribute").map(u=>u.getAttribute("name")).filter(u=>!!u));for(let u of[...r].sort((c,d)=>c.order-d.order))if(u.relatedEntity){if(s.get(u.name)===u.relatedEntity)continue;let c=d8(e,a,u.relatedEntity),d=e.createElement("attribute");d.setAttribute("name",u.name),c.appendChild(d),s.set(u.name,u.relatedEntity)}else{if(l.has(u.name))continue;let c=e.createElement("attribute");c.setAttribute("name",u.name),p8(a,c),l.add(u.name)}}function c8(e,t){var r;if(t.relatedEntity){for(let n of Gt(e,"link-entity"))if(n.getAttribute("name")===t.relatedEntity){for(let i of Gt(n,"attribute"))if(((r=i.getAttribute("alias"))!==null&&r!==void 0?r:i.getAttribute("name"))===t.name){n.removeChild(i);return}}return}for(let n of Gt(e,"attribute"))if(n.getAttribute("name")===t.name){e.removeChild(n);return}}function d8(e,t,r){for(let i of Gt(t,"link-entity"))if(i.getAttribute("name")===r)return i;let n=e.createElement("link-entity");return n.setAttribute("name",r),t.appendChild(n),n}function p8(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 f8(e,t,r){let n=t.getElementsByTagName("row")[0];if(!n)return;let i=[...r].sort((s,l)=>s.order-l.order),a=m8(n);if(h8(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 m8(e){return Gt(e,"cell").filter(t=>!!t.getAttribute("name")&&t.getAttribute("ishidden")!=="1")}function h8(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 g8(e,t,r){let n=t.getElementsByTagName("entity")[0];if(n){for(let i of Gt(n,"order"))n.removeChild(i);for(let i of r){let a=e.createElement("order");a.setAttribute("attribute",i.attribute),a.setAttribute("descending",String(i.descending)),n.appendChild(a)}}}function v8(e,t,r){let n=t.getElementsByTagName("entity")[0];if(n){for(let i of Gt(n,"filter"))L2(i)||n.removeChild(i);(r.conditions.length>0||r.groups.length>0)&&n.appendChild(fm(e,r))}}function pm(e,t){return JSON.stringify(e)===JSON.stringify(t)}function y8(e){let t=new DOMParser().parseFromString("<fetch/>","text/xml"),r=t.documentElement;r.setAttribute("version","1.0"),r.setAttribute("mapping","logical");let n=t.createElement("entity");n.setAttribute("name",e.entityLogicalName),r.appendChild(n);let i=new Map;for(let a of[...e.columns].sort((o,s)=>o.order-s.order)){let o=t.createElement("attribute");if(o.setAttribute("name",a.name),a.relatedEntity){let s=i.get(a.relatedEntity);s||(s=t.createElement("link-entity"),s.setAttribute("name",a.relatedEntity),n.appendChild(s),i.set(a.relatedEntity,s)),s.appendChild(o)}else n.appendChild(o)}for(let a of e.sort){let o=t.createElement("order");o.setAttribute("attribute",a.attribute),o.setAttribute("descending",String(a.descending)),n.appendChild(o)}return(e.filters.conditions.length>0||e.filters.groups.length>0)&&n.appendChild(fm(t,e.filters)),new XMLSerializer().serializeToString(t)}function fm(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.value!==void 0&&i.setAttribute("value",n.value),r.appendChild(i)}for(let n of t.groups)r.appendChild(fm(e,n));return r}function b8(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 w8(){return{adapter:new bu,api:a8.viewApi,publish:(e,t,r)=>(0,N2.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,N2.boundEntityPublishScope)(t)}}ba.viewRegistration=w8});var J2=g(Tn=>{"use strict";Object.defineProperty(Tn,"__esModule",{value:!0});Tn.appRegistration=Tn.AppAdapter=Tn.HEADER_NAV_BOOLEAN_RULE=void 0;var Xr=ur(),Je=mn(),ts=Gn(),A8=Yt(),C8=al(),mm=el(),hm=In(),S8=yt(),E8=ee(),G2=Ei(),N8=ie(),z2=rl();Object.defineProperty(Tn,"HEADER_NAV_BOOLEAN_RULE",{enumerable:!0,get:function(){return z2.HEADER_NAV_BOOLEAN_RULE}});var Cu="7.0.0.0",U2=`<SiteMap IntroducedVersion="${Cu}"></SiteMap>`,D8="/_imgs/imagestrips/transparent_spacer.gif",I8="/_imgs/TableIconsFluentV9/document_one_page_sparkle.svg",_8=["Entity","Url","DefaultDashboard","Page","GenPageId"],es="sitemapId",B2="sitemapName",P8="sitemapNameUnique";function $2(e,t,r){if(e===void 0)return r;if(typeof e!="boolean")throw new N8.ValidationError("app",t,[W2(e)]);return e}function W2(e){return(0,Xr.issue)("/headerAndNavigationRefresh",z2.HEADER_NAV_BOOLEAN_RULE,`headerAndNavigationRefresh must be a boolean, got ${typeof e}`)}function T8(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,E8.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 Su=class{constructor(t=G2.DEFAULT_LCID){this.lcid=t}toArtifact(t){let{bag:r,modeledEls:n}=wu(t,"Area");return{id:"",name:"",uniqueName:"",description:"",siteMap:{areas:n.map(i=>this.areaToJson(i)),bag:r},bag:(0,Je.emptyBag)()}}fromArtifact(t){(0,hm.installDomShim)();let r=this.assignMissingIds(JSON.parse(JSON.stringify(t))),n=new DOMParser().parseFromString("<root/>","text/xml"),i=this.rootToRaw(r);return(0,Je.rebuildRaw)(i,(0,ts.domEngine)(n),null)}fromApiResponse(t){var r,n,i,a,o,s,l,u,c,d;(0,hm.installDomShim)();let p=t??{},m=(r=p.$sitemap)!==null&&r!==void 0?r:p,h=(0,ts.parseXmlRoot)((n=m.sitemapxml)!==null&&n!==void 0?n:U2,U2),w=this.toArtifact(h);return w.id=(i=p.appmoduleid)!==null&&i!==void 0?i:"",w.name=(a=p.name)!==null&&a!==void 0?a:"",w.uniqueName=(o=p.uniquename)!==null&&o!==void 0?o:"",w.description=(s=p.description)!==null&&s!==void 0?s:"",w.bag={a:[[es,(u=(l=m.sitemapid)!==null&&l!==void 0?l:p._sitemapid_value)!==null&&u!==void 0?u:""],[B2,(c=m.sitemapname)!==null&&c!==void 0?c:""],[P8,(d=m.sitemapnameunique)!==null&&d!==void 0?d:""]],c:[]},w}toApiPayload(t){var r,n,i,a,o,s,l,u,c,d,p,m,h,w,b;(0,hm.installDomShim)();let E=(0,ts.serializeNode)(this.fromArtifact(t)),D=[],F=[];for(let q of(n=(r=t.siteMap)===null||r===void 0?void 0:r.areas)!==null&&n!==void 0?n:[])for(let G of(i=q.groups)!==null&&i!==void 0?i:[])for(let M of(a=G.subAreas)!==null&&a!==void 0?a:[])M.type==="Entity"&&M.entity?D.push(M.entity):M.type==="DashBoard"&&M.dashboardId&&F.push(M.dashboardId);let x=(o=t.bag)!==null&&o!==void 0?o:(0,Je.emptyBag)();return{sitemapId:(s=V2(x,es))!==null&&s!==void 0?s:"",sitemapxml:E,sitemapname:V2(x,B2)||t.name,appModuleId:t.id,appModuleName:t.name,appModuleDescription:t.description,appModuleUniqueName:t.uniqueName,...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},...t.headerAndNavigationRefresh===void 0?{}:{appSettings:{[mm.HEADER_AND_NAVIGATION_REFRESH]:$2(t.headerAndNavigationRefresh,(l=t.id)!==null&&l!==void 0?l:"(unknown)",!0)?mm.APP_SETTING_ON:mm.APP_SETTING_OFF}},...typeof t.published=="boolean"?{published:t.published}:{},entities:D,components:{forms:(c=(u=t.components)===null||u===void 0?void 0:u.forms)!==null&&c!==void 0?c:[],views:(p=(d=t.components)===null||d===void 0?void 0:d.views)!==null&&p!==void 0?p:[],charts:(h=(m=t.components)===null||m===void 0?void 0:m.charts)!==null&&h!==void 0?h:[],dashboards:[...(b=(w=t.components)===null||w===void 0?void 0:w.dashboards)!==null&&b!==void 0?b:[],...F]}}}createDefault(t){var r,n,i,a,o,s;let l=!((r=t.siteMap)===null||r===void 0)&&r.areas&&t.siteMap.areas.length>0?t.siteMap.areas:[{id:"",title:"Area",groups:[{id:"",title:"Group",subAreas:[]}]}];return{id:(n=t.id)!==null&&n!==void 0?n:(0,S8.newId)(),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:"",siteMap:{areas:l},...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},headerAndNavigationRefresh:$2(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(ym):Array.isArray(r.areas)?r.areas.forEach(ym):Array.isArray(r.groups)?ym(r):Array.isArray(r.subAreas)?H2(r):"type"in r&&Eu(r,"subarea"),t}validate(t){let r=[],n=t.published;n!==void 0&&typeof n!="boolean"&&r.push((0,Xr.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(W2(a)),i==null)return r;if(!(0,Xr.isJsonObject)(i))return r.push((0,Xr.issue)("/siteMap","sitemap-must-be-object",`siteMap must be a JSON object, got ${typeof i}`)),r;let o=(0,Xr.childObjects)(i,"areas","/siteMap","area",r),s=new Map;return o.forEach(({node:l,index:u})=>{let c=`/siteMap/areas/${u}`;(0,Xr.childObjects)(l,"groups",c,"group",r).forEach(({node:p,index:m})=>{let h=`${c}/groups/${m}`;(0,Xr.childObjects)(p,"subAreas",h,"subArea",r).forEach(({node:b,index:E})=>{let D=`${h}/subAreas/${E}`;(0,Xr.optionalEnum)(b,"type",["Entity","URL","DashBoard","CustomPage","GenPage"],D,"subarea-type-invalid",r);let F=T8(b);if(!F)return;let x=s.get(F);if(x===void 0){s.set(F,D);return}r.push((0,Xr.issue)(D,"subarea-duplicate-target",`the sitemap already navigates to this target at ${x}; a duplicate SubArea would pin it twice and a single removeElement would leave one behind`))})})}),r}applyServerIdentity(t,r){let n=r[es];if(!n)return;t.bag||(t.bag=(0,Je.emptyBag)());let i=t.bag.a.find(a=>a[0]===es);i?i[1]=n:t.bag.a.push([es,n])}areaToJson(t){var r;let{bag:n,modeledEls:i}=wu(t,"Group"),a={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:gm(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}=wu(t,"SubArea");return{id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:gm(t,this.lcid),subAreas:i.map(a=>this.subAreaToJson(a)),bag:n}}subAreaToJson(t){var r;let{bag:n}=wu(t,null),i=O8(t),a={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",type:i,title:gm(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!==D8&&(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,Je.emptyBag)(),l=Au(o)?[["IntroducedVersion",Cu]]:[],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,Je.mergeAttrs)(o.a,l),c:(0,Je.spliceChildren)(o.c,u)}}areaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,Je.emptyBag)(),i=Au(n),a=[];t.id&&a.push(["Id",t.id]),i&&a.push(["ShowGroups","true"],["ResourceId","SitemapDesigner.NewTitle"],["DescriptionResourceId","SitemapDesigner.NewTitle"],["IntroducedVersion",Cu]),t.icon!==void 0&&a.push(["Icon",t.icon]),t.vectorIcon!==void 0&&a.push(["VectorIcon",t.vectorIcon]);let o=t.groups.map(l=>this.groupToRaw(l)),s=vm((0,Je.spliceChildren)(n.c,o),t.title,i,this.lcid);return{n:"Area",a:(0,Je.mergeAttrs)(n.a,a),c:s}}groupToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,Je.emptyBag)(),i=Au(n),a=[];t.id&&a.push(["Id",t.id]),i&&a.push(["ResourceId","SitemapDesigner.NewGroup"],["DescriptionResourceId","SitemapDesigner.NewGroup"],["ToolTipResourseId","SitemapDesigner.Unknown"],["IntroducedVersion",Cu],["IsProfile","false"]);let o=t.subAreas.map(l=>this.subAreaToRaw(l)),s=vm((0,Je.spliceChildren)(n.c,o),t.title,i,this.lcid);return{n:"Group",a:(0,Je.mergeAttrs)(n.a,a),c:s}}subAreaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,Je.emptyBag)(),i=Au(n),a=F8(n.a,t.type),o=[];t.id&&o.push(["Id",t.id]),L8(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]),t.vectorIcon!==void 0?o.push(["VectorIcon",t.vectorIcon]):t.type==="GenPage"&&!R8(a,"VectorIcon")&&o.push(["VectorIcon",I8]);let s=vm((0,Je.spliceChildren)(n.c,[]),t.title,i,this.lcid);return{n:"SubArea",a:(0,Je.mergeAttrs)(a,o),c:s}}};Tn.AppAdapter=Su;function wu(e,t){let r=(0,ts.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,Je.rawFromNode)((0,ts.nodeLikeFromDom)(l))}),o+=1)}return{bag:{a:r,c:n},modeledEls:i}}function q2(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 gm(e,t){var r;let n=q2(e,"Titles")[0];if(!n)return"";let a=q2(n,"Title").find(o=>o.getAttribute("LCID")===String(t));return a&&(r=a.getAttribute("Title"))!==null&&r!==void 0?r:""}function O8(e){return e.getAttribute("GenPageId")?"GenPage":e.getAttribute("Entity")?"Entity":e.getAttribute("Page")?"CustomPage":e.getAttribute("DefaultDashboard")?"DashBoard":"URL"}function Au(e){return e.a.length===0&&e.c.length===0}function R8(e,t){return e.some(([r])=>r===t)}function V2(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function F8(e,t){let r=x8(t);return e.filter(([n])=>!_8.includes(n)||r.has(n)).map(n=>[n[0],n[1]])}function x8(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 L8(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 vm(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]=k8(e[i],t,n),a}return r?[M8(t,n),...e]:e}function k8(e,t,r){let n=!1,i=e.c.map(a=>!n&&a.n==="Title"&&U8(a,"LCID")===String(r)?(n=!0,{n:a.n,a:(0,Je.mergeAttrs)(a.a,[["Title",t]]),c:a.c}):a);return n||i.unshift(j2(t,r)),{n:e.n,a:e.a.map(a=>[a[0],a[1]]),c:i}}function M8(e,t){return{n:"Titles",a:[],c:[j2(e,t)]}}function j2(e,t){return{n:"Title",a:[["LCID",String(t)],["Title",e]],c:[]}}function U8(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function B8(e){let t="0123456789abcdef",r="";for(let n=0;n<e;n+=1)r+=t[Math.floor(Math.random()*t.length)];return r}function Eu(e,t){e&&(typeof e.id!="string"||e.id.length===0)&&(e.id=`${t}_${B8(8)}`)}function ym(e){var t;Eu(e,"area");for(let r of(t=e.groups)!==null&&t!==void 0?t:[])H2(r)}function H2(e){var t;Eu(e,"group");for(let r of(t=e.subAreas)!==null&&t!==void 0?t:[])Eu(r,"subarea")}function $8(e=G2.DEFAULT_LCID){return{adapter:new Su(e),api:C8.appApi,languageSensitive:!0,publish:(t,r)=>(0,A8.publishAppModule)(t,r),publishScope:t=>({envelope:"appmodule",targetIds:[t]})}}Tn.appRegistration=$8});var Q2={};Rr(Q2,{ActionType:()=>wm,AppActionOrigin:()=>_m,AppActionVisibilityType:()=>Im,ButtonType:()=>Cm,CannotUpdateAppActionColumns:()=>q8,Context:()=>Em,IconType:()=>Am,Location:()=>Sm,OnClickEventType:()=>Dm,Scope:()=>Nm,VisibilityType:()=>bm});var bm,wm,Am,Cm,Sm,Em,Nm,Dm,Im,_m,q8,X2=I(()=>{"use strict";(function(e){e[e.NotSupported=0]="NotSupported",e[e.Show=1]="Show",e[e.ClassicRules=2]="ClassicRules",e[e.Expression=3]="Expression"})(bm||(bm={}));(function(e){e[e.NotSupported=0]="NotSupported",e[e.None=1]="None",e[e.JavaScript=2]="JavaScript",e[e.Expression=3]="Expression"})(wm||(wm={}));(function(e){e[e.NoIcon=0]="NoIcon",e[e.UseIcon=1]="UseIcon",e[e.UseWebResource=2]="UseWebResource"})(Am||(Am={}));(function(e){e[e.Standard=0]="Standard",e[e.Dropdown=1]="Dropdown",e[e.Split=2]="Split",e[e.Group=3]="Group"})(Cm||(Cm={}));(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"})(Sm||(Sm={}));(function(e){e[e.All=0]="All",e[e.Entity=1]="Entity"})(Em||(Em={}));(function(e){e[e.App=0]="App",e[e.Entity=1]="Entity",e[e.Global=2]="Global"})(Nm||(Nm={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.JavaScript=2]="JavaScript"})(Dm||(Dm={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.ClassicRules=2]="ClassicRules"})(Im||(Im={}));(function(e){e[e.Default=0]="Default",e[e.Migrated=1]="Migrated",e[e.MigratedClone=2]="MigratedClone"})(_m||(_m={}));q8=["appactionid","appmoduleid","context","contextvalue","location","name","type","uniquename","isdisabled","origin"]});var Y2=g(Nu=>{"use strict";Object.defineProperty(Nu,"__esModule",{value:!0});Nu.commandApi=void 0;var Rt=ye(),V8=ie(),zt=ee(),G8="OnClickEventJavaScriptWebResourceId($select=name,webresourceid),IconWebResourceId($select=name,webresourceid)";async function Pm(e,t){let r=`/EntityDefinitions(LogicalName='${(0,zt.odataLiteral)(t)}')${(0,zt.odataQuery)([["$select","MetadataId"]])}`,i=(0,Rt.ensureSuccess)(await e.get(r),e.apiUrl(r)).body,a=i?.MetadataId;return a?(0,zt.normalizeGuid)(a,"entityMetadataId"):""}Nu.commandApi={async get(e,t){var r;let n=t,i=await Pm(e,n),a=i?`_contextentity_value eq ${i}`:`contextvalue eq '${(0,zt.odataLiteral)(n)}'`,o=`/appactions${(0,zt.odataQuery)([["$expand",G8],["$filter",a]])}`,s=(0,Rt.ensureSuccess)(await e.get(o),e.apiUrl(o)),l=s.body,u=(r=l?.value)!==null&&r!==void 0?r:[],c={entityLogicalName:n,entityMetadataId:i,appActions:u},d={};for(let p of u){let m=typeof p.appactionid=="string"?p.appactionid:void 0;if(m){let h=p["@odata.etag"];d[(0,zt.normalizeGuid)(m,"appactionid")]=typeof h=="string"?h:null}}return{raw:c,etag:(0,Rt.readEtag)(s),memberEtags:d}},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 Pm(e,r.entityLogicalName);return K2(e,{...r,entityMetadataId:n},!1)},async update(e,t,r,n,i){return K2(e,r,!0,i)},async delete(e,t){var r,n;let i=await Pm(e,t),a=i?`_contextentity_value eq ${i}`:`contextvalue eq '${(0,zt.odataLiteral)(t)}'`,o=`/appactions${(0,zt.odataQuery)([["$select","appactionid"],["$filter",a]])}`,l=(n=(r=(0,Rt.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[];for(let u of l)u.appactionid&&await(0,Rt.deleteRecord)(e,"appactions",u.appactionid)}};async function K2(e,t,r,n){let i=t.entityMetadataId?(0,zt.normalizeGuid)(t.entityMetadataId,"entityMetadataId"):"",a=W8(t.rows),o={};try{await z8(e,t,a,i,r,n,o)}catch(s){throw(0,V8.withPartialTokens)(s,{memberEtags:o})}return{id:t.entityLogicalName,etag:null,memberEtags:o}}async function z8(e,t,r,n,i,a,o){var s,l,u;for(let c of r)if(i&&c.exists){let d=(0,zt.normalizeGuid)(c.appactionid,"id"),p=(s=a?.[d])!==null&&s!==void 0?s:c.etag,m=(0,Rt.echoWrite)("appactionid",p?{"If-Match":p}:void 0),h=`/appactions(${d})${m.query}`,w=(0,Rt.ensureSuccess)(await e.patch(h,c.body,m.options),e.apiUrl(h));o[d]=(0,Rt.readEtag)(w)}else{let d=(0,Rt.echoWrite)("appactionid"),p=`/appactions${d.query}`,m={...c.body};n&&m["[email protected]"]===void 0&&(m["[email protected]"]=`/entities(${n})`);let h=(0,Rt.ensureSuccess)(await e.post(p,m,d.options),e.apiUrl(p)),w=(0,Rt.readCreatedId)(h,"appactionid");w&&(o[(0,zt.normalizeGuid)(w,"appactionid")]=(0,Rt.readEtag)(h))}for(let c of[...(l=t.deletedRowIds)!==null&&l!==void 0?l:[]].reverse()){let d=(0,zt.normalizeGuid)(c,"id");await(0,Rt.deleteRecord)(e,"appactions",d,(u=a?.[d])!==null&&u!==void 0?u:void 0),delete o[d]}}function W8(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 fI=g(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});wa.commandRegistration=wa.CommandAdapter=void 0;var qe=(X2(),Fr(Q2)),Z2=Yt(),Wt=ur(),j8=Y2(),tI=yt(),Aa=ee(),Om="$ClientSvg:",Rm=".svg",H8=2,J8=1,Q8=1,rI="entityMetadataId",X8=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"]),Du=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 m of l){let h=typeof m._parentappactionid_value=="string"&&m._parentappactionid_value?m._parentappactionid_value:"",w=(i=c.get(h))!==null&&i!==void 0?i:[];w.push(m),c.set(h,w)}let d=new Map;for(let m of(a=c.get(""))!==null&&a!==void 0?a:[]){let h=t6(m.location),w=(o=d.get(h))!==null&&o!==void 0?o:[];w.push(m),d.set(h,w)}let p=[];for(let[m,h]of d)p.push({location:m,groups:Y8(h,c,sI(m),u)});return{id:u,entityLogicalName:u,commandBars:e6(p),bag:{a:[[rI,(s=t.entityMetadataId)!==null&&s!==void 0?s:""]]}}}fromArtifact(t){return{entityLogicalName:t.entityLogicalName,entityMetadataId:xm(t),appActions:Tm(t).map(r=>r.row)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t,r){let n=new Set(r?Tm(r).map(l=>l.appactionid):[]),i=Tm(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?f6(l.row):pI(l.row)}}),s=[...n].filter(l=>!a.has(l));return{entityLogicalName:t.entityLogicalName,entityMetadataId:xm(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,tI.assignMissingIds)(t)}validate(t){let r=[];return(0,Wt.childObjects)(t,"commandBars","","commandBar",r).forEach(({node:i,index:a})=>{let o=`/commandBars/${a}`;(0,Wt.optionalEnum)(i,"location",["MainTab","ContextualTab","HomeTab"],o,"bar-location-invalid",r),(0,Wt.childObjects)(i,"groups",o,"group",r).forEach(({node:l,index:u})=>{let c=`${o}/groups/${u}`;(0,Wt.optionalGuidId)(l,"id",c,"group-id-invalid",r),nI((0,Wt.childObjects)(l,"controls",c,"control",r),`${c}/controls`,r)})}),r}};wa.CommandAdapter=Du;function nI(e,t,r){e.forEach(({node:n,index:i})=>{let a=`${t}/${i}`;(0,Wt.optionalGuidId)(n,"id",a,"control-id-invalid",r),(0,Wt.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,Wt.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,Wt.isJsonObject)(n.action)?(0,Wt.optionalEnum)(n.action,"type",["javascript"],`${a}/action`,"action-type-invalid",r):r.push((0,Wt.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,Wt.childObjects)(n,"children",a,"control",r);s.length>0&&nI(s,`${a}/children`,r)})}function iI(e){return{a:Object.entries(e)}}function K8(e){return Object.fromEntries(e.a)}function Fm(e,t){if(e){for(let[r,n]of e.a)if(r===t)return n}}function xm(e){let t=Fm(e.bag,rI);return typeof t=="string"?t:""}function Y8(e,t,r,n){var i,a;let o=[],s=[];for(let l of _u(e))l.type===qe.ButtonType.Group?o.push({id:oI(l.name,n),title:typeof l.grouptitle=="string"?l.grouptitle:"",controls:_u((a=t.get((i=l.appactionid)!==null&&i!==void 0?i:""))!==null&&a!==void 0?a:[]).map(u=>Iu(u,t,r,n)),bag:iI(l)}):s.push(Iu(l,t,r,n));return s.length>0&&o.unshift({id:(0,tI.newId)(),title:"",controls:s}),o}function Iu(e,t,r,n){var i,a,o,s;let l=oI(e.name,n),u={id:l,type:r6(e.type),label:typeof e.buttonlabeltext=="string"?e.buttonlabeltext:"",command:typeof e.appactionid=="string"?e.appactionid:l,bag:iI(e)},c=aI(e);c&&(u.icon=c);let d=Z8(e);d&&(u.action=d),typeof e.hidden=="boolean"&&(u.hidden=e.hidden),typeof e.isdisabled=="boolean"&&(u.disabled=e.isdisabled),typeof e.location=="number"&&e.location!==r&&(u.location=e.location);let p=t.get((i=e.appactionid)!==null&&i!==void 0?i:"");if(p&&p.length>0){let m=[];for(let h of _u(p))if(h.type===qe.ButtonType.Group){u.flyoutGroupId=(a=h.appactionid)!==null&&a!==void 0?a:void 0;for(let w of _u((s=t.get((o=h.appactionid)!==null&&o!==void 0?o:""))!==null&&s!==void 0?s:[]))m.push(Iu(w,t,r,n))}else m.push(Iu(h,t,r,n));u.children=m}return u}function aI(e){var t;if(!((t=e.IconWebResourceId)===null||t===void 0)&&t.name)return e.IconWebResourceId.name;if(e.fonticon)return e.fonticon.startsWith(Om)?e.fonticon.slice(Om.length)+Rm:e.fonticon}function Z8(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 eI(e){return typeof e.sequence=="number"?e.sequence:typeof e.buttonsequencepriority=="number"?e.buttonsequencepriority:0}function _u(e){return[...e].sort((t,r)=>eI(t)-eI(r))}function e6(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 oI(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 t6(e){switch(e){case qe.Location.Form:case qe.Location.QuickForm:return"MainTab";case qe.Location.HomePageGrid:case qe.Location.Dashboard:return"HomeTab";default:return"ContextualTab"}}function sI(e){switch(e){case"MainTab":return qe.Location.Form;case"HomeTab":return qe.Location.HomePageGrid;default:return qe.Location.SubGridStandard}}function r6(e){switch(e){case qe.ButtonType.Dropdown:return"FlyoutAnchor";case qe.ButtonType.Split:return"SplitButton";default:return"Button"}}function n6(e){switch(e){case"FlyoutAnchor":return qe.ButtonType.Dropdown;case"SplitButton":return qe.ButtonType.Split;default:return qe.ButtonType.Standard}}function i6(e){var t;return e.bag&&e.bag.a.length>0?!0:((t=e.title)!==null&&t!==void 0?t:"").length>0}function lI(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 Tm(e,t=new Set){var r,n,i,a;let o=[],s=xm(e);for(let l of(r=e.commandBars)!==null&&r!==void 0?r:[]){let u=sI(l.location),c=((n=l.groups)!==null&&n!==void 0?n:[]).flatMap(m=>{var h;return(h=m.controls)!==null&&h!==void 0?h:[]}),d=c.length>0&&c.every(m=>!lI(m,t)),p=0;for(let m of(i=l.groups)!==null&&i!==void 0?i:[]){let h;if(i6(m)){let w=o6(m,u,void 0,e,s);o.push(w),h=w.appactionid}for(let w of(a=m.controls)!==null&&a!==void 0?a:[])uI(w,u,h,e,s,o,d?p:void 0,t),p+=1}}return o}function uI(e,t,r,n,i,a,o,s=new Set){var l;let u=a6(e,t,r,n,i,o);a.push(u);let c=(l=e.children)!==null&&l!==void 0?l:[];if(c.length===0)return;let d=e.flyoutGroupId||p6(u.appactionid);a.push(s6(d,t,u.appactionid,n,i));let p=c.every(m=>!lI(m,s));for(let[m,h]of c.entries())uI(h,t,d,n,i,a,p?m:void 0,s)}function a6(e,t,r,n,i,a){let o=cI(e,t,r,n,i),s=o.row;a!==void 0&&typeof s.sequence!="number"&&(s.sequence=a);let l=aI(s);return e.location!==void 0&&(s.location=e.location),s.type=n6(e.type),s.buttonlabeltext=e.label,l6(s,e.icon,l),c6(s,e.action),u6(s),e.hidden!==void 0&&(s.hidden=e.hidden),e.disabled!==void 0&&(s.isdisabled=e.disabled),{...o,row:s}}function o6(e,t,r,n,i){let a=cI(e,t,r,n,i);return a.row.type=qe.ButtonType.Group,a.row.grouptitle=e.title,a}function s6(e,t,r,n,i){let a=dI(e,t,n,i);return a["[email protected]"]=`/appactions(${(0,Aa.normalizeGuid)(r,"Command flyout group id")})`,a.type=qe.ButtonType.Group,a.grouptitle===void 0&&(a.grouptitle=""),a.isgrouptitlehidden=!0,{appactionid:e,exists:!1,etag:null,row:a}}function cI(e,t,r,n,i){let a,o,s,l;if(e.bag&&e.bag.a.length>0){a=K8(e.bag),o=!0;let u=Fm(e.bag,"@odata.etag");s=typeof u=="string"?u:null;let c=Fm(e.bag,"appactionid");l=typeof c=="string"&&c?c:e.id}else l=e.id,a=dI(l,t,n,i),o=!1,s=null;return r&&(a["[email protected]"]=`/appactions(${(0,Aa.normalizeGuid)(r,"Command parent appaction id")})`),{appactionid:l,exists:o,etag:s,row:a}}function dI(e,t,r,n){let i={appactionid:e,name:`${e}!${e.replace(/-/g,"").slice(0,32)}`,uniquename:"",location:t,context:qe.Context.Entity,contextvalue:r.entityLogicalName,scope:qe.Scope.Entity};return n&&(i["[email protected]"]=`/entities(${(0,Aa.normalizeGuid)(n,"Command context entity metadata id")})`),i}function l6(e,t,r){if(t===r){let n=e._iconwebresourceid_value;typeof n=="string"&&n&&!e.fonticon&&(e["[email protected]"]=`/webresourceset(${(0,Aa.normalizeGuid)(n,"Command icon web resource id")})`);return}if(t===void 0){e.fonticon="",e.IconWebResourceId=null;return}e.fonticon=t.toLowerCase().endsWith(Rm)?Om+t.slice(0,t.length-Rm.length):t,e.IconWebResourceId=null}function u6(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,Aa.normalizeGuid)(a,`Command ${i}`);e[`${i}@odata.bind`]=`/canvasapps(${o})`};e.onclickeventtype===J8&&t("_onclickeventformulacomponentlibraryid_value","OnClickEventFormulaComponentLibraryId");let r=e.visibilitytype;(!r||r===Q8)&&t("_visibilityformulacomponentlibraryid_value","VisibilityFormulaComponentLibraryId")}function c6(e,t){if(!(!t||t.type!=="javascript")){if(e.onclickeventtype=H8,t.webResourceId){let r=(0,Aa.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 d6(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 p6(e){let t="";for(let r=0;r<4;r+=1)t+=d6(`${r}:flyout-group:${e}`).toString(16).padStart(8,"0");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20,32)}`}function pI(e){let t={...e};for(let r of X8)delete t[r];return t}function f6(e){let t=pI(e);for(let r of qe.CannotUpdateAppActionColumns)delete t[r];return t}function m6(){return{adapter:new Du,api:j8.commandApi,publish:(e,t,r)=>(0,Z2.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,Z2.boundEntityPublishScope)(t)}}wa.commandRegistration=m6});var mI=g(Pu=>{"use strict";Object.defineProperty(Pu,"__esModule",{value:!0});Pu.chartApi=void 0;var h6=Kt(),jt=ye(),rs=ee(),g6="savedqueryvisualizationid,name,description,primaryentitytypecode,datadescription,presentationdescription,charttype,type,isdefault",v6="savedqueryvisualizationid,name,primaryentitytypecode,charttype,isdefault";Pu.chartApi={async get(e,t){let n=`/savedqueryvisualizations(${(0,rs.normalizeGuid)(t,"id")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,rs.odataQuery)([["$select",g6]]),i=(0,jt.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,jt.readEtag)(i)}},async list(e,t){let r=`/savedqueryvisualizations${(0,rs.odataQuery)([["$select",v6],["$filter",t?.entityLogicalName?`primaryentitytypecode eq '${(0,rs.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,h6.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,jt.echoWrite)("savedqueryvisualizationid"),a=`/savedqueryvisualizations${i.query}`,o=(0,jt.ensureSuccess)(await e.post(a,(0,jt.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,jt.resolveCreatedId)(o,"savedqueryvisualizationid","chart",r),etag:(0,jt.readEtag)(o)}},async update(e,t,r,n){let i=r,a=(0,rs.normalizeGuid)(t,"id"),o=(0,jt.echoWrite)("savedqueryvisualizationid",{"If-Match":(0,jt.requireEtag)(n,"chart",a)}),s=`/savedqueryvisualizations(${a})${o.query}`,l=(0,jt.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,jt.readEtag)(l)}},delete(e,t){return(0,jt.deleteRecord)(e,"savedqueryvisualizations",t)}}});var TI=g(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});Ca.chartRegistration=Ca.ChartAdapter=void 0;var Lm=mn(),hI=ur(),Kr=Gn(),gI=Yt(),y6=mI(),km=In(),b6=yt(),w6=["Column","StackedColumn","StackedColumn100","Bar","StackedBar","StackedBar100","Area","StackedArea","StackedArea100","Line","Pie","Doughnut","Funnel","Tag"],A6=new Map(w6.map(e=>[e.toLowerCase(),e]));function wI(e){var t;return e&&(t=A6.get(e.toLowerCase()))!==null&&t!==void 0?t:"Column"}function C6(){return'<Chart Palette="BrightPastel"><Series><Series ChartType="Column" ChartArea="Default" /></Series><ChartAreas><ChartArea Name="Default" /></ChartAreas><Legends><Legend Name="Default" /></Legends></Chart>'}function S6(e){var t,r;let n=e.entityLogicalName,i=e.series.map((u,c)=>({alias:`agg_${c}`,series:u})),a=e.categories.map((u,c)=>({alias:`grp_${c}`,category:u})),o=i.map(u=>`<attribute alias="${u.alias}" name="${ns(u.series.attribute)}" aggregate="${ns(u.series.aggregate)}" />`).join("")+a.map(u=>`<attribute alias="${u.alias}" name="${ns(u.category.attribute)}" groupby="true"${u.category.dateGrouping?` dategrouping="${ns(u.category.dateGrouping)}"`:""} />`).join(""),s=i.map(u=>`<measure alias="${u.alias}" />`).join(""),l=(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="${ns(n)}">${o}</entity></fetch></fetchcollection><categorycollection><category alias="${l}"><measurecollection>${s}</measurecollection></category></categorycollection></datadefinition>`}var Tu=class{toArtifact(t){var r,n,i,a,o,s,l;(0,km.installDomShim)();let u=(r=t.datadescription)!==null&&r!==void 0?r:"",c=(n=t.presentationdescription)!==null&&n!==void 0?n:"",d=(0,Kr.parseXmlRoot)(u,"<datadefinition/>"),p=(0,Kr.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:AI(p),isDefault:(l=t.isdefault)!==null&&l!==void 0?l:!1,series:EI(d),categories:NI(d),presentation:CI(p),dataBag:u?(0,Kr.projectElementBag)(d):void 0,presentationBag:c?(0,Kr.projectElementBag)(p):void 0,rowBag:E6(t.charttype,t.type)}}fromArtifact(t){(0,km.installDomShim)();let{datadescription:r,presentationdescription:n}=N6(t);return{savedqueryvisualizationid:t.id,name:t.name,description:t.description,primaryentitytypecode:t.entityLogicalName,datadescription:r,presentationdescription:n,charttype:vI(t.rowBag,"charttype"),type:vI(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,km.installDomShim)();let u=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,b6.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,hI.childObjects)(n,"series","","series",r),(0,hI.childObjects)(n,"categories","","category",r),r}};Ca.ChartAdapter=Tu;function E6(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 vI(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 AI(e){let t=e.getElementsByTagName("Series");for(let r=0;r<t.length;r+=1)if(t[r].getAttribute("ChartType"))return wI(t[r].getAttribute("ChartType"));return"Column"}function CI(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 Ou(e){return e.getElementsByTagName("fetch")[0]}function SI(e){var t;let r=new Map;if(!e)return r;let n=e.getElementsByTagName("link-entity");for(let i=0;i<n.length;i+=1){let a=n[i],o=a.getAttribute("name");if(!o)continue;let s=a.getElementsByTagName("attribute");for(let l=0;l<s.length;l+=1){let u=s[l],c=(t=u.getAttribute("alias"))!==null&&t!==void 0?t:u.getAttribute("name");c&&r.set(c,o)}}return r}function EI(e){let t=Ou(e);if(!t)return[];let r=SI(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=wI(c));let d=o.getAttribute("alias");d&&(u.alias=d);let p=d??l,m=r.get(p);m&&(u.relatedEntity=m),i.push(u)}return i}function NI(e){var t;let r=Ou(e);if(!r)return[];let n=SI(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,m=n.get(p);m&&(u.relatedEntity=m),a.push(u)}return a}function N6(e){if(!yI(e.dataBag)||!yI(e.presentationBag))return{datadescription:S6(e),presentationdescription:W6(e)};let t=new DOMParser().parseFromString("<root/>","text/xml"),r=bI(e.dataBag,"datadefinition",t),n=bI(e.presentationBag,"Chart",t);return Mm(e.series,EI(r))||(I6(t,r,e.series),D6(t,n,e.series.length,e.chartType)),Mm(e.categories,NI(r))||_6(t,r,e.categories),e.chartType!==AI(n)&&_I(n,e.chartType),Mm(e.presentation,CI(n))||PI(n,e.presentation),{datadescription:(0,Kr.serializeNode)(r),presentationdescription:(0,Kr.serializeNode)(n)}}function yI(e){return!!e&&(e.c.length>0||e.a.length>0)}function D6(e,t,r,n){let i,a=t.childNodes;for(let l=0;l<a.length;l+=1)if(a[l].nodeType===1&&a[l].tagName==="Series"){i=a[l];break}i||(i=e.createElement("Series"),t.insertBefore(i,t.firstChild));let o=[],s=i.childNodes;for(let l=0;l<s.length;l+=1)s[l].nodeType===1&&s[l].tagName==="Series"&&o.push(s[l]);for(let l=o.length;l<r;l+=1){let u=e.createElement("Series");u.setAttribute("ChartType",n),i.appendChild(u)}for(let l=r;l<o.length;l+=1)i.removeChild(o[l])}function bI(e,t,r){let n={n:t,a:(0,Lm.mergeAttrs)(e.a,[]),c:(0,Lm.spliceChildren)(e.c,[])};return(0,Lm.rebuildRaw)(n,(0,Kr.domEngine)(r),null)}function I6(e,t,r){let n=Ou(t),i=n?.getElementsByTagName("entity")[0];!n||!i||DI(e,t,i,L6(n),r,M6,{aliasPrefix:"aggregate_column",addRef:O6,removeRef:x6})}function _6(e,t,r){let n=Ou(t),i=n?.getElementsByTagName("entity")[0];!n||!i||DI(e,t,i,k6(n),r,U6,{aliasPrefix:"groupby_column",addRef:R6,removeRef:F6})}function DI(e,t,r,n,i,a,o){let s=new Map;for(let p of n){let m=p.getAttribute("alias");m&&s.set(m,p)}let l=new Set,u=[];for(let p of i){let m=p.alias?s.get(p.alias):void 0;m&&!l.has(m)?(a(m,p),l.add(m)):u.push(p)}let c=n.filter(p=>!l.has(p)),d=0;for(let p of u)if(d<c.length){let m=c[d];a(m,p),l.add(m),d+=1}else{let m=e.createElement("attribute"),h=p.alias||T6(t,o.aliasPrefix);m.setAttribute("alias",h),a(m,p),B6(e,r,m,p.relatedEntity),o.addRef(e,t,h)}for(let p of n)if(!l.has(p)){let m=p.getAttribute("alias");m&&o.removeRef(t,m),q6(p)}}function P6(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 T6(e,t){let r=P6(e);if(!r.has(t))return t;for(let n=2;;n+=1){let i=`${t}_${n}`;if(!r.has(i))return i}}function II(e,t){let r=t.getElementsByTagName("categorycollection")[0];if(r)return r;let n=e.createElement("categorycollection");return t.appendChild(n),n}function O6(e,t,r){let n=II(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 R6(e,t,r){let n=II(e,t),i=e.createElement("category");i.setAttribute("alias",r),n.appendChild(i)}function F6(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 x6(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"&&!G6(o)&&((r=o.parentNode)===null||r===void 0||r.removeChild(o))}}function L6(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 k6(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 M6(e,t){e.setAttribute("name",t.attribute),e.setAttribute("aggregate",t.aggregate),t.seriesType&&e.setAttribute("charttype",t.seriesType)}function U6(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 B6(e,t,r,n){n?$6(e,t,n).appendChild(r):t.appendChild(r)}function $6(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 q6(e){let t=e.parentNode;if(t&&(t.removeChild(e),t.tagName==="link-entity"&&!V6(t))){let r=t.parentNode;r&&r.removeChild(t)}}function V6(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 G6(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1)if(t[r].nodeType===1)return!0;return!1}function _I(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(!z6(r[i])){r[i].setAttribute("ChartType",t);return}}}function z6(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 PI(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 W6(e){let t=(0,Kr.parseXmlRoot)(C6(),"<Chart/>");return _I(t,e.chartType),PI(t,e.presentation),(0,Kr.serializeNode)(t)}function Mm(e,t){return JSON.stringify(e)===JSON.stringify(t)}function ns(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function j6(){return{adapter:new Tu,api:y6.chartApi,publish:(e,t,r)=>(0,gI.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,gI.boundEntityPublishScope)(t)}}Ca.chartRegistration=j6});var OI=g(Ru=>{"use strict";Object.defineProperty(Ru,"__esModule",{value:!0});Ru.dashboardApi=void 0;var H6=Kt(),Ht=ye(),is=ee(),J6="formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber",Q6="formid,name,type,objecttypecode",X6=0,K6=10;Ru.dashboardApi={async get(e,t){let n=`/systemforms(${(0,is.normalizeGuid)(t,"id")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,is.odataQuery)([["$select",J6]]),i=(0,Ht.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,Ht.readEtag)(i)}},async list(e,t){let r=[`(type eq ${X6} or type eq ${K6})`];t?.entityLogicalName&&r.push(`objecttypecode eq '${(0,is.odataLiteral)(t.entityLogicalName)}'`);let n=`/systemforms${(0,is.odataQuery)([["$select",Q6],["$filter",r.join(" and ")]])}`;return(await(0,H6.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,Ht.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,Ht.ensureSuccess)(await e.post(a,(0,Ht.withClientMintedId)(o,"formid",r),i.options),e.apiUrl(a));return{id:(0,Ht.resolveCreatedId)(s,"formid","dashboard",r),etag:(0,Ht.readEtag)(s)}},async update(e,t,r,n){let i=r,a=(0,is.normalizeGuid)(t,"id"),o=(0,Ht.echoWrite)("formid",{"If-Match":(0,Ht.requireEtag)(n,"dashboard",a)}),s=`/systemforms(${a})${o.query}`,l=(0,Ht.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,Ht.readEtag)(l)}},delete(e,t){return(0,Ht.deleteRecord)(e,"systemforms",t)}}});var GI=g(Cr=>{"use strict";Object.defineProperty(Cr,"__esModule",{value:!0});Cr.dashboardRegistration=Cr.TILE_CLASS_ID=Cr.DashboardAdapter=void 0;var os=mn(),Jt=Gn(),Um=Yt(),as=ur(),Y6=OI(),Bm=In(),ui=yt(),MI=ee(),UI=Ei(),RI="0",$m="10",Z6=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"]]),eG="{3FF9A528-DD50-4ACA-8F10-2E5ED73513AD}",xu=class{constructor(t=UI.DEFAULT_LCID){this.lcid=t}toArtifact(t){var r,n,i,a;(0,Bm.installDomShim)();let o=(r=t.formxml)!==null&&r!==void 0?r:"",s=(0,Jt.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:tG(t.type),entityLogicalName:t.objecttypecode?t.objecttypecode:null,enabledForMobile:!!t.istabletenabled,layoutType:rG(s),components:FI(s,this.lcid),bag:(0,Jt.projectElementBag)(s)}}fromArtifact(t){var r;return(0,Bm.installDomShim)(),{formid:t.id,name:t.name,description:t.description,type:t.dashboardType==="Interactive"?$m:RI,objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",istabletenabled:t.enabledForMobile,formxml:xI(t,this.lcid)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t){return{name:t.name,description:t.description,formxml:xI(t,this.lcid),istabletenabled:t.enabledForMobile,type:t.dashboardType==="Interactive"?$m:RI,objecttypecode:t.entityLogicalName}}createDefault(t){var r,n,i,a,o,s,l,u;(0,Bm.installDomShim)();let c=(0,Jt.parseXmlRoot)(hG(),"<form/>");return{id:(r=t.id)!==null&&r!==void 0?r:(0,ui.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:FI(c,this.lcid),bag:(0,Jt.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,ui.newId)())}return t}validate(t){let r=[],n=(0,as.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,as.isJsonObject)(u)&&r.push((0,as.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,as.isJsonObject)(a.position)){let l=ss(a.position);i.has(l)?r.push((0,as.issue)(`${s}/position`,"component-position-collision",`two components occupy the same dashboard position (${l}); move one to a free cell`)):i.add(l)}}),r}};Cr.DashboardAdapter=xu;function tG(e){return String(e??"")===$m?"Interactive":"Standard"}function rG(e){var t;let r=(t=e?.getAttribute("formLayout"))!==null&&t!==void 0?t:e?.getAttribute("layoutType"),n=parseInt(r??"",10);return Number.isNaN(n)?0:n}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 FI(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)=>{nG(c,{tabIndex:a,columnIndex:l,sectionIndex:d},r,t)})})}),r}function nG(e,t,r,n){Q(e,"rows").flatMap(a=>Q(a,"row")).forEach((a,o)=>{Q(a,"cell").forEach((s,l)=>{let u=iG(s,{...t,rowIndex:o,cellIndex:l},n);u&&r.push(u)})})}function iG(e,t,r){var n,i,a;let o=qI((n=e.getAttribute("id"))!==null&&n!==void 0?n:"");if(o.toLowerCase().startsWith("spacer"))return null;let s=Q(e,"control")[0];if(!s)return null;let l=(i=s.getAttribute("classid"))!==null&&i!==void 0?i:"",u=sG(s),c=lG(l,u,s),d=aG(s);return{id:(a=s.getAttribute("id"))!==null&&a!==void 0?a:o,type:c,name:$I(e,r),classId:l,position:t,colspan:qm(e,"colspan",1),rowspan:qm(e,"rowspan",1),parameters:u,bag:(0,Jt.projectElementBag)(e),...d?{icProperties:d}:{}}}function BI(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 aG(e){let t=BI(e);return t?(0,Jt.serializeNode)(t):void 0}function oG(e,t,r){let n=BI(t);if(!r){n&&t.removeChild(n);return}let i=new DOMParser().parseFromString(r,"text/xml").documentElement,a=(0,os.rebuildRaw)((0,os.rawFromNode)((0,Jt.nodeLikeFromDom)(i)),(0,Jt.domEngine)(e),null);n&&(0,Jt.serializeNode)(n)===(0,Jt.serializeNode)(a)||(n?t.replaceChild(a,n):t.appendChild(a))}function $I(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 sG(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 lG(e,t,r){var n;let i=Z6.get(e.toUpperCase());return i?i==="chart"?t.ChartGridMode==="Chart"?"chart":"list":i==="assistant"&&((n=r.getAttribute("uniqueid"))!==null&&n!==void 0?n:"").toUpperCase()===eG?"assistant":i:"unknown"}function qm(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 qI(e){return e.replace(/^\{/,"").replace(/\}$/,"")}function uG(e,t){let r={n:"form",a:(0,os.mergeAttrs)(e.bag.a,[]),c:(0,os.spliceChildren)(e.bag.c,[])};return(0,os.rebuildRaw)(r,(0,Jt.domEngine)(t),null)}function xI(e,t){let r=new DOMParser().parseFromString("<root/>","text/xml"),n=uG(e,r);return pG(r,n,e.components,t),cG(r,n,e.components,t),(0,Jt.serializeNode)(n)}function cG(e,t,r,n){let i=VI(t);for(let a of r)i.has(ss(a.position))||dG(e,t,a,n)}function dG(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=gG(t,e,l);for(let W of Q(u,"row"))Q(W,"cell").some($=>Q($,"control").length>0)||u.removeChild(W);let c=r.classId||Cr.TILE_CLASS_ID[r.type]||Cr.TILE_CLASS_ID.iframe,d=r.rowspan&&r.rowspan>0?r.rowspan:4,p=r.bag&&LI(r.bag,"id")?String(LI(r.bag,"id")):Fu((0,ui.newId)()),m=r.id?Fu(r.id):Fu((0,ui.newId)()),h=u.parentNode,w=Math.max(1,parseInt(h&&h.getAttribute&&h.getAttribute("columns")||"1",10)||1),b=Math.min(Math.max(1,r.colspan&&r.colspan>0?r.colspan:1),w),E=Q(u,"row"),D=E[E.length-1],F=D?Q(D,"cell").reduce((W,$)=>W+qm($,"colspan",1),0):0;(!D||F+b>w)&&(D=e.createElement("row"),u.appendChild(D));let x=e.createElement("cell");x.setAttribute("id",p),x.setAttribute("colspan",String(b)),x.setAttribute("rowspan",String(d)),x.setAttribute("showlabel","true");let q=e.createElement("labels"),G=e.createElement("label");G.setAttribute("description",(o=r.name)!==null&&o!==void 0?o:""),G.setAttribute("languagecode",String(n)),q.appendChild(G),x.appendChild(q);let M=e.createElement("control");M.setAttribute("id",m),M.setAttribute("classid",Fu(c));let U=e.createElement("parameters"),B=(s=r.parameters)!==null&&s!==void 0?s:{};for(let W of Object.keys(B)){let $=(0,MI.createSafeXmlElement)(e,W,"dashboard tile parameter");$.textContent=B[W],U.appendChild($)}M.appendChild(U),x.appendChild(M),D.appendChild(x)}function LI(e,t){if(!e)return;let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function pG(e,t,r,n){var i;let a=VI(t),o=new Set(r.map(s=>ss(s.position)));for(let s of r){let l=a.get(ss(s.position));if(!l)continue;let u=Q(l,"control")[0];u&&(fG(e,l,s.name,n),mG(e,u,s.parameters),kI(l,"colspan",s.colspan),kI(l,"rowspan",s.rowspan),s.icProperties!==void 0&&oG(e,u,s.icProperties))}for(let[s,l]of a)o.has(s)||(i=l.parentNode)===null||i===void 0||i.removeChild(l)}function VI(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,m)=>{Q(p,"cell").forEach((h,w)=>{var b;qI((b=h.getAttribute("id"))!==null&&b!==void 0?b:"").toLowerCase().startsWith("spacer")||Q(h,"control")[0]&&t.set(ss({tabIndex:i,columnIndex:s,sectionIndex:c,rowIndex:m,cellIndex:w}),h)})})})})}),t}function ss(e){let t=e??{};return`${t.tabIndex}.${t.columnIndex}.${t.sectionIndex}.${t.rowIndex}.${t.cellIndex}`}function fG(e,t,r,n){if(r===$I(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 mG(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,MI.createSafeXmlElement)(e,l,"dashboard component parameter");d.textContent=u,a.appendChild(d)}}}function kI(e,t,r){var n;((n=e.getAttribute(t))!==null&&n!==void 0?n:"")!==String(r)&&e.setAttribute(t,String(r))}function hG(e=2){let t=`{${(0,ui.newId)()}}`,r=`{${(0,ui.newId)()}}`,n=`{${(0,ui.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>`}Cr.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 Fu(e){return`{${e.replace(/[{}]/g,"")}}`}function gG(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 vG(e=UI.DEFAULT_LCID){return{adapter:new xu(e),api:Y6.dashboardApi,languageSensitive:!0,publish:(t,r,n)=>n?.entityLogicalName?(0,Um.publishBoundEntity)(t,n):(0,Um.publishDashboardById)(t,r),publishScope:(t,r)=>r?.entityLogicalName?(0,Um.boundEntityPublishScope)(r):{envelope:"dashboard",targetIds:[t]}}}Cr.dashboardRegistration=vG});var QI=g(ku=>{"use strict";Object.defineProperty(ku,"__esModule",{value:!0});ku.genPageApi=void 0;var JI=Kt(),De=ye(),_t=ee(),Sr=ie(),On="uxagentprojects",Ea="uxagentprojectfiles",Sa="uxagentprojectid",Er="uxagentprojectfileid",Lu=`${Sa},name`,yG=`${Er},filename,filetype`;async function Vm(e,t,r,n){var i;let a=`/${t}(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,_t.odataQuery)([["$select",n]]),o=(0,De.ensureSuccess)(await e.get(a),e.apiUrl(a));return{row:(i=o.body)!==null&&i!==void 0?i:{},etag:(0,De.readEtag)(o)}}async function bG(e,t){let r=`/${Ea}(${t})/filecontent/$value`,n=await e.get(r);if(n.status===404)return{status:"unavailable",reason:"unpublished"};(0,De.ensureSuccess)(n,e.apiUrl(r));let i=n.body;if(i instanceof Uint8Array||Buffer.isBuffer(i))return{status:"available",data:Buffer.from(i).toString("base64")};if(i instanceof ArrayBuffer)return{status:"available",data:Buffer.from(new Uint8Array(i)).toString("base64")};if(typeof i=="string")return{status:"available",data:Buffer.from(i,"utf8").toString("base64")};throw new Sr.SdkError("GENPAGE_CONTENT_UNREADABLE",`Read the content of file '${t}' but the injected HttpClient returned a body this SDK cannot encode (${typeof i}). Return the response as a string, Uint8Array, Buffer, or ArrayBuffer; a byte-returning transport is required to round-trip non-UTF8 assets.`)}async function wG(e,t,r,n){if(!e.supportsBinaryPatch)throw new Sr.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED",`Refusing to push generative-page file '${t}': its content cannot be written because the injected HttpClient does not implement patchRaw(). A Dataverse File column is not writable through a JSON body, so saving the row without its bytes would report success for a page whose source never uploaded.`);let i=`/${Ea}(${t})/filecontent`,a=new Uint8Array(Buffer.from(n,"base64"));(0,_t.assertNoControlChars)(r,"generative-page file name"),(0,De.ensureSuccess)(await e.patchRaw(i,a,{headers:{"Content-Type":"application/octet-stream","Content-Length":String(a.byteLength),"x-ms-file-name":r}}),e.apiUrl(i))}async function Gm(e,t){let r=`/${Ea}/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()`+(0,_t.odataQuery)([["$select",yG],["$filter",`_${Sa}_value eq ${t}`]]);return(await(0,JI.collectPages)(e,r,"fetchArtifact('genPage')")).map(i=>({row:i,etag:typeof i["@odata.etag"]=="string"?i["@odata.etag"]:null}))}async function zI(e,t,r){var n;let{etag:i}=await Vm(e,On,t,Lu),a={};for(let{row:l,etag:u}of await Gm(e,t))a[(0,_t.normalizeGuid)(String((n=l[Er])!==null&&n!==void 0?n:""),Er)]=u;let o=Object.keys(a),s=!i||o.length!==r.size||o.some(l=>!r.has(l))||Object.values(a).some(l=>!l);return{etag:i,memberEtags:a,mismatch:s}}function WI(e,t){return t.mismatch?{etag:null,memberEtags:{},warnings:[`Generative page '${e}' was written, but its files changed on the server while the write was in progress, so the new concurrency tokens cannot be trusted. The local baseline is now unusable: re-fetch the page before editing it again \u2014 the next push will refuse rather than overwrite blind.`]}:{etag:t.etag,memberEtags:t.memberEtags}}ku.genPageApi={async get(e,t){var r;let n=(0,_t.normalizeGuid)(t,"id"),{row:i,etag:a}=await Vm(e,On,n,Lu),o=await Gm(e,n),s={},l=[];for(let{row:u,etag:c}of o){let d=(0,_t.normalizeGuid)(String((r=u[Er])!==null&&r!==void 0?r:""),Er);s[d]=c;let p=await bG(e,d);l.push({...u,content:p})}return{raw:{project:i,files:l},etag:a,memberEtags:s}},async list(e,t){let r=`/${On}/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()`+(0,_t.odataQuery)([["$select",Lu]]);return(await(0,JI.collectPages)(e,r,"listArtifacts('genPage')")).map(i=>{var a,o;return{type:"genPage",id:String((a=i[Sa])!==null&&a!==void 0?a:""),name:String((o=i.name)!==null&&o!==void 0?o:""),isDirty:!1}})},async create(e,t,r){let n=t;jI(e,n);let i=`/${On}`,a=(0,De.ensureSuccess)(await e.post(i,(0,De.withClientMintedId)({name:n.name},Sa,r)),e.apiUrl(i)),o=(0,De.resolveCreatedId)(a,Sa,"generative page",r),s=new Set;for(let l of n.files){let u=await HI(e,o,l,!0);s.add((0,_t.normalizeGuid)(u.id,"file id"))}try{return{id:o,...WI(o,await zI(e,o,s))}}catch(l){return{id:o,etag:null,memberEtags:{},warnings:[`The generative page was created, but re-reading its concurrency tokens failed (${l instanceof Error?l.message:String(l)}). The local baseline is unusable: re-fetch the page before editing it \u2014 the next push will refuse rather than overwrite blind.`]}}},async update(e,t,r,n,i){let a=r,o=(0,_t.normalizeGuid)(t,"id");jI(e,a);let s=await Gm(e,o),{etag:l}=await Vm(e,On,o,Lu);if(n&&l&&n!==l)throw new Sr.SdkError(De.VERSION_CONFLICT_CODE,`Generative page '${o}' changed on the server after it was fetched (baseline ${n}, server ${l}) \u2014 another writer edited it. A page row accepts no If-Match validator, so this push would silently overwrite them. Re-fetch the page and re-apply the edit.`);if(!n||!l)throw new Sr.SdkError(De.VERSION_CONFLICT_CODE,`Cannot verify generative page '${o}' before writing: ${n?"the server did not return the page's current token":"no baseline token was recorded"}. This entity accepts no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);let u=new Set(s.map(({row:m})=>{var h;return(0,_t.normalizeGuid)(String((h=m[Er])!==null&&h!==void 0?h:""),Er)})),c=new Set(a.files.map(m=>(0,_t.normalizeGuid)(m.id,"file id")));if(!i)throw new Sr.SdkError(De.VERSION_CONFLICT_CODE,`Cannot verify the files of generative page '${o}' before writing: no child baseline was recorded. These rows accept no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);let d=new Set(Object.keys(i).map(m=>m.toLowerCase()));{for(let h of c)if(!u.has(h)&&d.has(h))throw new Sr.SdkError(De.VERSION_CONFLICT_CODE,`Generative-page file '${h}' existed when this page was fetched but is gone from the server now \u2014 another writer deleted it. Refusing to recreate it, because a blind re-create would undo that delete and, for an unpublished page, restore the row WITHOUT its content. Re-fetch the page and re-apply the edit.`);for(let h of u)if(!d.has(h))throw new Sr.SdkError(De.VERSION_CONFLICT_CODE,`Generative-page file '${h}' 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 m=new Map(s.map(({row:h,etag:w})=>{var b;return[(0,_t.normalizeGuid)(String((b=h[Er])!==null&&b!==void 0?b:""),Er),w]}));for(let[h,w]of Object.entries(i??{})){let b=h.toLowerCase();if(!u.has(b))continue;let E=m.get(b);if(!w||!E)throw new Sr.SdkError(De.VERSION_CONFLICT_CODE,`Cannot verify generative-page file '${b}' before writing: ${w?"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(w!==E)throw new Sr.SdkError(De.VERSION_CONFLICT_CODE,`Generative-page file '${b}' changed on the server after this page was fetched (baseline ${w}, server ${E}) \u2014 another writer edited it. A file row accepts no If-Match validator, so this push would silently overwrite that change. Re-fetch the page and re-apply the edit.`)}}let p=`/${On}(${o})`;(0,De.ensureSuccess)(await e.patch(p,{name:a.name},{headers:{"If-Match":"*"}}),e.apiUrl(p));for(let m of a.files){let h=(0,_t.normalizeGuid)(m.id,"file id");await HI(e,o,m,!u.has(h))}for(let m of u)c.has(m)||await(0,De.deleteRecord)(e,Ea,m);try{return{id:o,...WI(o,await zI(e,o,c))}}catch(m){return{id:o,etag:null,memberEtags:{},warnings:[`The generative page was written, but re-reading its concurrency tokens failed (${m instanceof Error?m.message:String(m)}). The local baseline is now unusable: re-fetch the page before editing it again \u2014 the next push will refuse rather than overwrite blind.`]}}},delete(e,t){return(0,De.deleteRecord)(e,On,t)}};function jI(e,t){var r;if(((r=t.files)!==null&&r!==void 0?r:[]).some(i=>i.content.status==="available")&&!e.supportsBinaryPatch)throw new Sr.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED","Refusing to write this generative page: it has file content to upload, but the injected HttpClient does not implement patchRaw(). A Dataverse File column is not writable through a JSON body, so proceeding would create the page and its rows and then fail, leaving a page whose source never uploaded.")}async function HI(e,t,r,n){let i=(0,_t.normalizeGuid)(r.id,"file id"),a;if(n){let o=`/${Ea}`,s=(0,De.ensureSuccess)(await e.post(o,(0,De.withClientMintedId)({filename:r.name,filetype:r.fileType,[`${Sa}@odata.bind`]:`/${On}(${t})`},Er,i)),e.apiUrl(o));a=(0,De.readEtag)(s)}else{let o=`/${Ea}(${i})`,s=(0,De.ensureSuccess)(await e.patch(o,{filename:r.name,filetype:r.fileType},{headers:{"If-Match":"*"}}),e.apiUrl(o));a=(0,De.readEtag)(s)}return r.content.status==="available"&&await wG(e,i,r.name,r.content.data),{id:i,etag:a}}});var ZI=g(Da=>{"use strict";Object.defineProperty(Da,"__esModule",{value:!0});Da.genPageRegistration=Da.GenPageAdapter=void 0;var AG=QI(),CG=Yt(),Rn=ur(),YI=yt(),XI=2e8;function KI(e){return typeof e=="string"&&e.trim()!==""?e:(0,YI.newId)()}function Na(e){return(0,Rn.isJsonObject)(e)?e:{}}function SG(e){let t=Na(e);return t.status==="available"&&typeof t.data=="string"?{status:"available",data:t.data}:{status:"unavailable",reason:"unpublished"}}var Mu=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var r,n;let i=t,a=Na(i?.project),o=Array.isArray(i?.files)?i.files:[];return{id:String((r=a.uxagentprojectid)!==null&&r!==void 0?r:""),name:String((n=a.name)!==null&&n!==void 0?n:""),files:o.map(s=>{var l,u,c;let d=Na(s);return{id:String((l=d.uxagentprojectfileid)!==null&&l!==void 0?l:""),name:String((u=d.filename)!==null&&u!==void 0?u:""),fileType:Number((c=d.filetype)!==null&&c!==void 0?c:XI),content:SG(d.content)}})}}toApiPayload(t){var r;return{name:t.name,files:((r=t.files)!==null&&r!==void 0?r:[]).map(n=>({id:n.id,name:n.name,fileType:n.fileType,content:n.content}))}}createDefault(t){var r,n;return{id:KI(t.id),name:(r=t.name)!==null&&r!==void 0?r:"New page",files:((n=t.files)!==null&&n!==void 0?n:[]).map(i=>{var a,o,s;return{id:KI(i.id),name:(a=i.name)!==null&&a!==void 0?a:"index.tsx",fileType:(o=i.fileType)!==null&&o!==void 0?o:XI,content:(s=i.content)!==null&&s!==void 0?s:{status:"available",data:""}}})}}assignMissingIds(t){let r=Na(t);return(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,YI.newId)()),r}validate(t){let r=[],n=t.files;if(n!==void 0&&!Array.isArray(n))return r.push((0,Rn.issue)("/files","files-must-be-array",`files must be an array, got ${typeof n}`)),r;let i=new Map;return(Array.isArray(n)?n:[]).forEach((a,o)=>{let s=`/files/${o}`,l=Na(a),u=typeof l.id=="string"?l.id.trim().toLowerCase():"";if(u==="")r.push((0,Rn.issue)(s,"file-id-required","a generative-page file needs an id"));else{let m=i.get(u);m!==void 0?r.push((0,Rn.issue)(s,"file-id-duplicate",`two files share the id '${l.id}' (also at /files/${m}); a file's id is its identity, so a duplicate makes an edit ambiguous`)):i.set(u,o)}let c=typeof l.name=="string"?l.name:"";(c===""||/[\u0000-\u001F\u007F]/.test(c)||/[\\/]/.test(c))&&r.push((0,Rn.issue)(s+"/name","file-name-invalid",`a file name must be a non-empty single path segment with no control characters or path separators (it is sent as an HTTP header on upload); got '${c}'`));let d=l.content;if(d===void 0){r.push((0,Rn.issue)(s+"/content","file-content-required","content is required: omitting it is indistinguishable from an empty file, and the two have opposite effects on the next push"));return}let p=Na(d);p.status==="available"?typeof p.data!="string"&&r.push((0,Rn.issue)(s+"/content/data","file-content-data-invalid","available content needs base64 `data`")):p.status!=="unavailable"&&r.push((0,Rn.issue)(s+"/content/status","file-content-status-invalid",`content.status must be 'available' or 'unavailable', got ${String(p.status)}`))}),r}};Da.GenPageAdapter=Mu;function EG(){return{adapter:new Mu,api:AG.genPageApi,publish:(e,t)=>(0,CG.publishGenPageById)(e,t),publishScope:e=>({envelope:"uxagentproject",targetIds:[e]})}}Da.genPageRegistration=EG});var t_=g(Bu=>{"use strict";Object.defineProperty(Bu,"__esModule",{value:!0});Bu.reconcileBpfSecurityRoles=void 0;var Uu=ye(),zm=ee(),NG="Global",e_={create:"Create",read:"Read",write:"Write",delete:"Delete"};async function DG(e,t){var r,n;let i=`/EntityDefinitions(LogicalName='${t}')?$select=LogicalName,Privileges`,o=(n=(r=(0,Uu.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(e_).forEach(u=>{let c=o.find(d=>d.PrivilegeType===e_[u]);if(c){let d=(0,zm.normalizeGuid)(c.PrivilegeId,"PrivilegeId");s[u]=d,l.add(d)}}),{byAccess:s,all:l}}async function IG(e,t){var r,n;let i=`/RetrieveRolePrivilegesRole(RoleId=${t})`,o=(n=(r=(0,Uu.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,zm.normalizeGuid)(s.PrivilegeId,"PrivilegeId")))}async function _G(e,t,r){if(r.length===0)return;let n={Privileges:r.map(a=>({Depth:NG,PrivilegeId:a}))},i=`/roles(${t})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;(0,Uu.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function PG(e,t,r){let n={Privilege:{"@odata.type":"Microsoft.Dynamics.CRM.privilege",privilegeid:r}},i=`/roles(${t})/Microsoft.Dynamics.CRM.RemovePrivilegeRole`;(0,Uu.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function TG(e,t,r){var n;if(!r||r.length===0)return;let i=await DG(e,t.toLowerCase());for(let a of r){let o=(0,zm.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 IG(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 _G(e,o,c);for(let p of d)await PG(e,o,p)}}Bu.reconcileBpfSecurityRoles=TG});var o_=g(qu=>{"use strict";Object.defineProperty(qu,"__esModule",{value:!0});qu.bpfApi=void 0;var Fn=Mn(),OG=Kt(),Qt=ye(),Nr=ee(),RG=t_(),$u={"Content-Type":"application/json",Accept:"application/json"},FG=`category eq ${Fn.WorkflowCategory.BusinessProcessFlow} and type eq ${Fn.WorkflowTypeCode.Definition} and businessprocesstype eq ${Fn.BusinessProcessType.BusinessFlow}`,xG="workflowid,name,description,primaryentity,statecode,category,type,businessprocesstype,processorder",LG="workflowid,name,uniquename,description,primaryentity,statecode,statuscode,category,type,businessprocesstype,processorder,xaml,clientdata",kG=["xaml","name","description","processorder"];async function r_(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,RG.reconcileBpfSecurityRoles)(e,n,t.securityRoles)}async function Wm(e,t,r){var n;if(r==="Draft")return null;let i=(0,Nr.normalizeGuid)(t,"workflowid"),a={statecode:Fn.StateCode.Activated,statuscode:Fn.StatusCode.Activated},o=`/workflows(${i})`,s=(0,Qt.ensureSuccess)(await e.patch(o,a,{headers:$u}),e.apiUrl(o));return(n=(0,Qt.readEtag)(s))!==null&&n!==void 0?n:await a_(e,i)}async function a_(e,t){let r=`/workflows(${t})${(0,Nr.odataQuery)([["$select","workflowid"]])}`,n=await e.get(r);return n.status>=200&&n.status<300?(0,Qt.readEtag)(n):null}async function MG(e,t){var r;let n=`/workflows(${t})${(0,Nr.odataQuery)([["$select","statecode"]])}`,i=await e.get(n);if(i.status<200||i.status>=300)return null;let a=(r=i.body)===null||r===void 0?void 0:r.statecode;return a==null?null:Number(a)}async function n_(e,t,r){if(await MG(e,t)!==Fn.StateCode.Activated)return!1;let n={statecode:Fn.StateCode.Draft,statuscode:Fn.StatusCode.Draft},i=`/workflows(${t})`,a={...$u};return r&&(a["If-Match"]=r),(0,Qt.ensureSuccess)(await e.patch(i,n,{headers:a}),e.apiUrl(i)),!0}async function i_(e,t){try{await Wm(e,t,"Active")}catch{}}function UG(e){let t={};for(let r of kG)e[r]!==void 0&&(t[r]=e[r]);return t}qu.bpfApi={async get(e,t){let n=`/workflows(${(0,Nr.normalizeGuid)(t,"id")})${(0,Nr.odataQuery)([["$select",LG]])}`,i=(0,Qt.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,Qt.readEtag)(i)}},async list(e,t){let r=[FG];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,Nr.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,Nr.odataQuery)([["$select",xG],["$filter",r.join(" and ")]])}`;return(await(0,OG.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,Nr.normalizeGuid)(r.record.workflowid,"workflowid"),i="/workflows",a=(0,Qt.ensureSuccess)(await e.post(i,r.record,{headers:$u}),e.apiUrl(i)),o=null;try{o=await Wm(e,n,r.status),await r_(e,r)}catch(s){try{await(0,Qt.deleteRecord)(e,"workflows",n)}catch{}throw s}return{id:n,etag:o??(0,Qt.readEtag)(a)}},async update(e,t,r,n){var i;let a=r,o=(0,Nr.normalizeGuid)(t,"id"),s=await n_(e,o,n);try{let l=`/workflows(${o})`,u={...$u};n&&!s&&(u["If-Match"]=n);let c=(0,Qt.ensureSuccess)(await e.patch(l,UG(a.record),{headers:u}),e.apiUrl(l)),d=await Wm(e,o,a.status);return await r_(e,a),{id:o,etag:(i=d??(0,Qt.readEtag)(c))!==null&&i!==void 0?i:await a_(e,o)}}catch(l){throw s&&await i_(e,o),l}},async delete(e,t){let r=(0,Nr.normalizeGuid)(t,"id"),n=await n_(e,r,null);try{await(0,Qt.deleteRecord)(e,"workflows",r)}catch(i){throw n&&await i_(e,r),i}}}});var G_=g(Pa=>{"use strict";Object.defineProperty(Pa,"__esModule",{value:!0});Pa.bpfRegistration=Pa.BpfAdapter=void 0;var Ia=ys(),BG=yl(),Vu=Mn(),$G=o_(),jm=mn(),ci=Gn(),b_=In(),Ft=ur(),xn=yt(),Dr=ie(),qG=100,Jm='<?xml version="1.0" encoding="utf-16"?>',s_=1033,w_="mxswa:Workflow",VG="mxswa:ActivityReference.Properties",GG="mcwo:StepLabel",zG="mcwb:Control",l_="mcwb:Control.ControlDisplayName",A_="mcwb:Control.DataFieldName",C_="DataFieldName",u_="ControlDisplayName",S_="Literal",Gu="x:Null",c_="x:String",Qm="x:Key",Xm="DisplayName",Wu="Activities",WG="StepLabels",E_="StageId",N_="StageCategory",D_="NextStageId",I_="ProcessStepId",Km="IsProcessRequired",__="EntityComposite",P_="StageComposite",T_="StepComposite";function Hm(e){return(0,Ft.isJsonObject)(e)?e:{}}function Ir(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 di(e,t){var r;return(r=Ir(e).find(n=>n.tagName===t))!==null&&r!==void 0?r:null}function _r(e){return di(e,VG)}function mt(e,t){var r;return(r=Ir(e).find(n=>n.getAttribute(Qm)===t))!==null&&r!==void 0?r:null}function _a(e,t){var r;return((r=e.getAttribute("AssemblyQualifiedName"))!==null&&r!==void 0?r:"").includes(t)}function Zr(e){var t;return!e||!e.firstChild?"":(t=e.firstChild.nodeValue)!==null&&t!==void 0?t:""}function O_(e,t,r){e.firstChild?e.firstChild.nodeValue=r:e.appendChild(t.createTextNode(r))}function ls(e){var t;let r=(t=e.getAttribute(Xm))!==null&&t!==void 0?t:"",n=r.indexOf(": ");return n>=0?r.slice(n+2):r}function R_(e,t){var r;let n=(r=e.getAttribute(Xm))!==null&&r!==void 0?r:"",i=n.indexOf(": ");e.setAttribute(Xm,i>=0?n.slice(0,i+2)+t:t)}function F_(e,t){let r=mt(e,WG),n=di(r,GG);n&&n.setAttribute("Description",t)}function jG(e){let t=mt(e,N_);if(!t||t.tagName===Gu)return;let r=Zr(t).trim();return r===""?void 0:Number(r)}function HG(e){let t=mt(e,D_);if(!t||t.tagName===Gu)return;let r=Zr(t).trim();return r===""?void 0:r}function x_(e){let t=L_(e);if(!t)return;let r=M_(t,C_,A_);return r===""?void 0:r}function Ym(e,t){let r=Ir(e);for(;r.length>0;){let n=r.pop();if(n.tagName===t)return n;for(let i of Ir(n))r.push(i)}return null}function L_(e){let t=mt(_r(e),Wu);return t?Ym(t,zG):null}function k_(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 M_(e,t,r){var n;return k_(e,t)?(n=e.getAttribute(t))!==null&&n!==void 0?n:"":YG(e,r)}function d_(e,t,r,n){if(k_(e,t)){e.setAttribute(t,n);return}if(di(e,r)){JG(e,r,n);return}throw new Dr.InvalidArgumentError(`BPF step control exposes neither a '${t}' attribute nor a <${r}> wrapper to bind a column`)}function JG(e,t,r){let n=di(e,t),i=n?Ym(n,S_):null;i&&i.setAttribute("Value",r)}function U_(e){return ls(e)}function ju(e){let t=di(e,w_),r=[];for(let n of Ir(t).filter(i=>_a(i,__))){let i=mt(_r(n),Wu);for(let a of Ir(i).filter(o=>_a(o,P_)))r.push({el:a,entity:U_(n)})}return r}function Zm(e){let t=mt(_r(e),Wu);return Ir(t).filter(r=>_a(r,T_))}function QG(e){let t=_r(e),r=Zr(mt(t,Km)).trim().toLowerCase(),n=x_(e),i={id:Zr(mt(t,I_)),name:ls(e)};return n!==void 0&&(i.fieldName=n),r==="true"&&(i.required=!0),i}function XG(e,t){let r=_r(e),n=jG(r),i=HG(r),a={id:Zr(mt(r,E_)),name:ls(e),entityLogicalName:t,steps:Zm(e).map(QG)};return n!==void 0&&(a.category=n),i!==void 0&&(a.nextStageId=i),a}function KG(e){return ju(e).map(({el:t,entity:r})=>XG(t,r))}function Yr(e){return new Dr.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 YG(e,t){var r;let n=di(e,t),i=n?Ym(n,S_):null;return(r=i?.getAttribute("Value"))!==null&&r!==void 0?r:""}function eh(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(eh(e,s)):s.nodeType===3&&n.appendChild(e.createTextNode((r=s.nodeValue)!==null&&r!==void 0?r:""))}return n}function B_(e){return mt(_r(e),Wu)}function ZG(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,xn.newId)(),{body:o}=Hu(th(i,(0,Ia.v4)(),t.id,a));return eh(e,ju((0,ci.parseXmlRoot)(o,"<Activity/>"))[0].el)}function e7(e,t){let{body:r}=Hu(th("account",(0,Ia.v4)(),(0,Ia.v4)(),t.id));return eh(e,Zm(ju((0,ci.parseXmlRoot)(r,"<Activity/>"))[0].el)[0])}function $_(e,t){for(;e.firstChild;)e.removeChild(e.firstChild);for(let r of t)e.appendChild(r)}function q_(e,t,r,n){let i=mt(e,r);if(!i||!i.parentNode){if(n!==void 0&&n!=="")throw Yr(`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!==Gu){let s=t.createElement(Gu);s.setAttribute(Qm,r),a.replaceChild(s,i)}return}if(i.tagName===c_){Zr(i)!==n&&O_(i,t,n);return}let o=t.createElement(c_);o.setAttribute(Qm,r),o.appendChild(t.createTextNode(n)),a.replaceChild(o,i)}function t7(e,t,r){q_(e,t,N_,r===void 0?void 0:String(r))}function r7(e,t,r){q_(e,t,D_,r)}function V_(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 p_(e){return Zr(mt(_r(e),E_))}function f_(e){return Zr(mt(_r(e),I_))}function m_(e,t,r){var n,i,a,o;let s=_r(e);r.name!==ls(e)&&(R_(e,r.name),F_(s,r.name));let l=Zr(mt(s,Km)).trim().toLowerCase()==="true";if(((n=r.required)!==null&&n!==void 0?n:!1)!==l){let u=mt(s,Km);u&&O_(u,t,r.required?"True":"False")}if(((i=r.fieldName)!==null&&i!==void 0?i:"")!==((a=x_(e))!==null&&a!==void 0?a:"")){let u=L_(e);if(!u)throw new Dr.InvalidArgumentError("BPF step has no <mcwb:Control> element to bind a column to");let c=(o=r.fieldName)!==null&&o!==void 0?o:"";d_(u,C_,A_,c),c!==""&&M_(u,u_,l_)===""&&d_(u,u_,l_,c)}}function h_(e,t,r,n){var i;let a=_r(e);if(!a)throw new Dr.InvalidArgumentError("BPF stage composite has no <\u2026ActivityReference.Properties>");if(r.name!==ls(e)&&(R_(e,r.name),F_(a,r.name)),t7(a,t,r.category),r7(a,t,n),r.relationshipName&&r.relationshipName.trim()!=="")throw Yr("a stage relationship / table change (multi-table authoring)");if(r.actions&&r.actions.length>0||r.branch)throw Yr("stage actions or conditional branching");let o=B_(e);if(!o)throw new Dr.InvalidArgumentError("BPF stage has no [Activities] collection");let s=(i=r.steps)!==null&&i!==void 0?i:[];if(s.length===0)throw new Dr.InvalidArgumentError(`BPF stage '${r.name}' must have at least one step`);let l=Zm(e);if(V_(l,s.map(d=>d.id),f_)){l.forEach((d,p)=>m_(d,t,s[p]));return}let u=new Map(l.map(d=>[f_(d),d]));if(Ir(o).some(d=>!_a(d,T_)))throw Yr("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:e7(t,d)});$_(o,c),c.forEach((d,p)=>m_(d,t,s[p]))}function n7(e,t,r){let n=di(e,w_);if(!n)throw new Dr.InvalidArgumentError("BPF xaml has no <mxswa:Workflow> root activity");if(r.globalActions&&r.globalActions.length>0)throw Yr("global (process-completed/abandoned) actions");if(!r.stages||r.stages.length===0)throw new Dr.InvalidArgumentError("a BPF must have at least one stage");let i=ju(e),a=i.map(p=>p.el);if(V_(a,r.stages.map(p=>p.id),p_)){i.forEach(({el:p,entity:m},h)=>{let w=r.stages[h];if(w.entityLogicalName&&w.entityLogicalName.trim()!==""&&w.entityLogicalName!==m)throw Yr(`changing a stage's table ('${w.entityLogicalName}' vs the process's '${m}')`);h_(p,t,w,w.nextStageId)});return}let o=Ir(n).filter(p=>_a(p,__));if(o.length!==1)throw Yr("adding, removing or reordering stages on a multi-table process");let s=o[0],l=U_(s),u=B_(s);if(!u)throw new Dr.InvalidArgumentError("BPF primary entity composite has no [Activities] collection");if(Ir(u).some(p=>!_a(p,P_)))throw Yr("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 Yr(`a stage on a different table ('${p.entityLogicalName}') than the process primary ('${l}')`);let c=new Map(a.map(p=>[p_(p),p])),d=r.stages.map(p=>{var m;return(m=c.get(p.id))!==null&&m!==void 0?m:ZG(t,p,l)});$_(u,d),d.forEach((p,m)=>{let h=m<d.length-1?r.stages[m+1].id:void 0;h_(p,t,r.stages[m],h)})}function Hu(e){let t=e.match(/^<\?xml[^>]*\?>\s*/),r=t?t[0]:"";return{prolog:r,body:e.slice(r.length)}}function i7(e){var t,r,n,i,a,o;(0,b_.installDomShim)();let s=(t=e.bag)===null||t===void 0?void 0:t.xaml;if(s){let p=new BG.DOMParser().parseFromString("<root/>","text/xml"),m={n:"Activity",a:(0,jm.mergeAttrs)(s.a,[]),c:(0,jm.spliceChildren)(s.c,[])};return{root:(0,jm.rebuildRaw)(m,(0,ci.domEngine)(p),null),prolog:(n=(r=e.bag)===null||r===void 0?void 0:r.xamlProlog)!==null&&n!==void 0?n:Jm,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=th(e.entityLogicalName,(0,Ia.v4)(),l?.id&&l.id.trim()!==""?l.id:(0,Ia.v4)(),u?.id&&u.id.trim()!==""?u.id:(0,Ia.v4)()),{body:d}=Hu(c);return{root:(0,ci.parseXmlRoot)(d,"<Activity/>"),prolog:Jm,eol:"lf"}}function a7(e){let{root:t,prolog:r,eol:n}=i7(e);n7(t,t.ownerDocument,e);let i=(0,ci.serializeNode)(t);return n==="crlf"&&(i=i.replace(/\n/g,`\r-`)),r+i}function o7(e){return e.uniqueName&&e.uniqueName.trim()!==""?e.uniqueName:`new_${(e.name||"businessprocessflow").toLowerCase().replace(/[^a-z0-9]/g,"")||"businessprocessflow"}`}var zu=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var r,n;(0,b_.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}=Hu(a),u=(0,ci.parseXmlRoot)(l,"<Activity/>");o.stages=KG(u),o.bag={xaml:(0,ci.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,xn.newId)(),name:t.name,uniquename:o7(t),primaryentity:t.entityLogicalName,xaml:a7(t),category:Vu.WorkflowCategory.BusinessProcessFlow,type:Vu.WorkflowTypeCode.Definition,businessprocesstype:Vu.BusinessProcessType.BusinessFlow,scope:Vu.WorkflowScope.Organization,processorder:(r=t.order)!==null&&r!==void 0?r:qG};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 Dr.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(v_):[v_({id:(0,xn.newId)(),name:"New Stage",steps:[]})],o={id:t.id&&t.id.trim()!==""?t.id:(0,xn.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=Hm(t);(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,xn.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,Ft.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,Ft.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=Hm(l),p=typeof d.id=="string"?d.id.trim():"";p===""?r.push((0,Ft.issue)(`${c}/id`,"stage-id-required","a stage needs an id")):o.has(p.toLowerCase())?r.push((0,Ft.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 m=Array.isArray(l.steps)?l.steps:[];m.length===0&&r.push((0,Ft.issue)(`${c}/steps`,"stage-needs-step","a BPF stage must have at least one step")),m.length>30&&r.push((0,Ft.issue)(`${c}/steps`,"too-many-steps",`a stage allows at most 30 steps, got ${m.length}`));let h=new Map;m.forEach((w,b)=>{let E=`${c}/steps/${b}`,D=typeof Hm(w).id=="string"?w.id.trim():"";D===""?r.push((0,Ft.issue)(`${E}/id`,"step-id-required","a step needs an id")):h.has(D.toLowerCase())?r.push((0,Ft.issue)(`${E}/id`,"step-id-duplicate",`two steps in this stage share the id '${w.id}'`)):h.set(D.toLowerCase(),b)}),l.branch&&!g_(i,l.branch.nextStageId)&&r.push((0,Ft.issue)(`${c}/branch/nextStageId`,"branch-target-unknown",`branch nextStageId '${l.branch.nextStageId}' does not match any stage id`)),typeof l.nextStageId=="string"&&l.nextStageId!==""&&!g_(i,l.nextStageId)&&r.push((0,Ft.issue)(`${c}/nextStageId`,"next-stage-unknown",`nextStageId '${l.nextStageId}' does not match any stage id`))}),a.size>5&&r.push((0,Ft.issue)("/stages","too-many-tables",`a BPF spans at most 5 tables, got ${a.size}`));let s=s7(i);return s>=0&&r.push((0,Ft.issue)(`/stages/${s}/nextStageId`,"next-stage-cycle","the stage nextStageId links form a cycle; the flow must be acyclic")),r}};Pa.BpfAdapter=zu;function s7(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 g_(e,t){return e.some(r=>r.id===t)}function v_(e){var t,r;let n=e.steps&&e.steps.length>0?e.steps.map(y_):[y_({id:(0,xn.newId)(),name:"New Step"})],i={id:e.id&&e.id.trim()!==""?e.id:(0,xn.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 y_(e){var t;let r={id:e.id&&e.id.trim()!==""?e.id:(0,xn.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 th(e,t,r,n){return`${Jm}<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="${s_}" /></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="${s_}" /></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 l7(){return{adapter:new zu,api:$G.bpfApi,languageSensitive:!0}}Pa.bpfRegistration=l7});var z_=g(Ju=>{"use strict";Object.defineProperty(Ju,"__esModule",{value:!0});Ju.buildRegistrations=void 0;var u7=C2(),c7=M2(),d7=yd(),p7=J2(),f7=fI(),m7=TI(),h7=GI(),g7=ZI(),v7=G_();function y7(e){let t=new Map;return t.set("form",(0,u7.formRegistration)(e)),t.set("view",(0,c7.viewRegistration)()),t.set("businessRule",(0,d7.businessRuleRegistration)()),t.set("app",(0,p7.appRegistration)(e)),t.set("command",(0,f7.commandRegistration)()),t.set("chart",(0,m7.chartRegistration)()),t.set("dashboard",(0,h7.dashboardRegistration)(e)),t.set("genPage",(0,g7.genPageRegistration)()),t.set("bpf",(0,v7.bpfRegistration)()),t}Ju.buildRegistrations=y7});var Z_=g(ke=>{"use strict";Object.defineProperty(ke,"__esModule",{value:!0});ke.removeRowSummary=ke.configureRowSummary=ke.buildGptDynamicPrompt=ke.setAppAiFeatures=ke.getAiReadiness=ke.saveSettingValue=ke.retrieveSetting=ke.AI_GATE=void 0;var sr=ye(),Qe=ee(),W_=yt(),en=ie();ke.AI_GATE={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabled",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"EnableNLGridSearch",nlChart:"NLChartVisualizationSetting",summaries:"EnableFormInsights",m365:"m365copilotmodelappenabled"};var b7={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabledOnByDefault",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"NLGridSearchSetting",nlChart:"NLChartDataVisualizationSetting",m365:"m365copilotmodelappenabled"},w7={formFill:{enabled:"2",disabled:"1"},formFillSuggestions:{enabled:"2",disabled:"1"},formFillSmartPaste:{enabled:"2",disabled:"1"},formFillFiles:{enabled:"2",disabled:"1"}};function Q_(e){return w7[e]}var Qu=1e6;function A7(e,t){let r=Q_(t),n=()=>{throw new en.InvalidArgumentError(`setAppAiFeatures: '${t}' must be a boolean or an integer between 0 and ${Qu} (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>Qu?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(Qu).length||Number(s)>Qu?n():s}}return n()}function C7(e,t){let r=Q_(t);return r?e===r.enabled:e!=="0"}async function S7(e,t){var r,n,i;let a=`/appmodules${(0,Qe.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,Qe.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 E7(e,t){var r,n;let i=`/appmodules${(0,Qe.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,Qe.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 j_=new WeakMap;async function N7(e,t){var r,n,i;let a=j_.get(e);if(a||(a=new Map,j_.set(e,a)),a.has(t))return a.get(t);let o=`/settingdefinitions${(0,Qe.odataQuery)([["$select","settingdefinitionid"],["$filter",`uniquename eq '${(0,Qe.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 D7(e,t,r){var n,i;let a=await N7(e,r);if(!t||!a)return;let o=`/appsettings${(0,Qe.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 I7=4,_7=500,H_=20,J_=3e4;function P7(e){if(e===void 0)return I7;if(!Number.isFinite(e))throw new en.InvalidArgumentError(`setAppAiFeatures: verifyAttempts must be a finite integer between 1 and ${H_}; got ${e}.`);return Math.min(H_,Math.max(1,Math.floor(e)))}function T7(e){if(e===void 0)return _7;if(!Number.isFinite(e))throw new en.InvalidArgumentError(`setAppAiFeatures: verifyDelayMs must be a finite number between 0 and ${J_}; got ${e}.`);return Math.min(J_,Math.max(0,Math.floor(e)))}function O7(e){return e>0?new Promise(t=>setTimeout(t,e)):Promise.resolve()}async function R7(e,t,r,n,i,a,o){let s,l,u,c=!1;for(let d=0;d<a;d+=1){d>0&&await O7(o*d);let p;try{let m=await t();m?(p=await D7(e,m,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(m){p=void 0,u=m.message}c=p!==void 0,l=p?.exists;try{s=(await Xu(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 X_(e,t){return t===2?String(e).toLowerCase()==="true":e!=null&&e!=="0"&&e!==""}async function Xu(e,t,r={}){var n,i;let a=[`SettingName='${(0,Qe.odataPathLiteral)(t)}'`];r.appUniqueName&&a.push(`AppUniqueName='${(0,Qe.odataPathLiteral)(r.appUniqueName)}'`);let o=`/RetrieveSetting(${a.join(",")})`,l=(i=(n=(0,sr.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}}ke.retrieveSetting=Xu;async function K_(e,t,r,n={}){let i={SettingName:t,Value:r};n.appUniqueName&&(i.AppUniqueName=n.appUniqueName),n.solutionUniqueName&&(i.SolutionUniqueName=n.solutionUniqueName),(0,sr.ensureSuccess)(await e.post("/SaveSettingValue",i),e.apiUrl("/SaveSettingValue"))}ke.saveSettingValue=K_;async function F7(e,t={}){let r={};for(let[n,i]of Object.entries(ke.AI_GATE)){let{value:a,dataType:o}=await Xu(e,i,t);r[n]={enabled:X_(a,o),setting:i,value:a}}return r}ke.getAiReadiness=F7;async function x7(e,t,r,n={}){var i,a,o;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 s=P7(n.verifyAttempts),l=T7(n.verifyDelayMs),u=[];for(let[b,E]of Object.entries(r)){if(E===void 0)continue;let D=b7[b];D&&u.push({feature:b,setting:D,requestedValue:A7(E,b)})}let c=[],d=n.appModuleId?(0,Qe.normalizeGuid)(n.appModuleId,"appModuleId"):void 0;if(d){let b=await E7(e,t);if(b&&(0,Qe.normalizeGuid)(b,"appModuleId")!==d)throw new en.InvalidArgumentError(`setAppAiFeatures: appModuleId '${d}' does not belong to app '${t}' (which resolves to '${b}'). Settings are written by unique name, so verifying against a different app would report success for a write that never landed.`)}let p,m=async()=>d||(p||(p=await S7(e,t)),p),h=new Map,w=async b=>{let E=ke.AI_GATE[b];if(E){if(!h.has(E)){let{value:D,dataType:F}=await Xu(e,E);h.set(E,{enabled:X_(D,F),setting:E,value:D})}return h.get(E)}};for(let{feature:b,setting:E,requestedValue:D}of u)try{if(C7(D,b)){let q=await w(b);if(!q?.enabled){c.push({feature:b,setting:E,requestedValue:D,status:"skipped",reason:`the org readiness gate '${(i=q?.setting)!==null&&i!==void 0?i:b}' is off, so the feature cannot be enabled for this app`});continue}}await K_(e,E,D,{appUniqueName:t,solutionUniqueName:n.solutionUniqueName});let F=await R7(e,m,t,E,D,s,l),x={feature:b,setting:E,requestedValue:D,effectiveValue:F.effectiveValue,appOverrideExists:F.appOverrideExists};F.result==="proven"?c.push({...x,status:"applied"}):F.result==="absent"?c.push({...x,status:"notPersisted",reason:`the write reported success but no app-scope override holding '${D}' was observed for '${E}' after ${s} attempt(s) \u2014 it reads '${(a=F.effectiveValue)!==null&&a!==void 0?a:""}' for this app (Dataverse can accept an app-scope write without storing it)`}):c.push({...x,status:"unverified",reason:`the write was issued but could not be confirmed: ${(o=F.reason)!==null&&o!==void 0?o:"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(F){c.push({feature:b,setting:E,requestedValue:D,status:"failed",reason:F.message})}return{applied:c.filter(b=>b.status==="applied").map(b=>b.feature),skipped:c.filter(b=>b.status==="skipped").map(b=>b.feature),notPersisted:c.filter(b=>b.status==="notPersisted").map(b=>b.feature),unverified:c.filter(b=>b.status==="unverified").map(b=>b.feature),failed:c.filter(b=>b.status==="failed").map(b=>b.feature),outcomes:c}}ke.setAppAiFeatures=x7;var L7="GptPowerPrompt",k7='{ "consumptionSource": "Api", "partnerSource": "AIBuilder", "consumptionSourceVersion": "GptApiClient"}';function Y_(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:""}}ke.buildGptDynamicPrompt=Y_;async function M7(e,t){var r,n;let i=`/EntityDefinitions(LogicalName='${(0,Qe.odataPathLiteral)(t)}')${(0,Qe.odataQuery)([["$select","MetadataId"]])}`;return(n=(r=(0,sr.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||r===void 0?void 0:r.MetadataId)!==null&&n!==void 0?n:""}async function U7(e,t,r={}){var n,i,a,o,s;let l=`ais_RowSummary_${t.entityLogicalName}`,u=`/aiskillconfigs${(0,Qe.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,Qe.odataLiteral)(l)}'`],["$top",1]])}`,c=((i=(n=(0,sr.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,Qe.odataQuery)([["$select","msdyn_aitemplateid"],["$filter",`msdyn_uniquename eq '${L7}'`],["$top",1]])}`,p=((s=(o=(a=(0,sr.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,m=(0,W_.newId)(),h=(0,W_.newId)(),w=JSON.stringify(Y_(t)),b={ModelId:m,RunConfigurationId:h,ModelName:`${t.entityLogicalName} row summary`,TemplateId:p,CustomConfiguration:w,Source:k7,RunConfiguration:""};(0,sr.ensureSuccess)(await e.post("/AIModelPublish",b),e.apiUrl("/AIModelPublish"));try{let E=await M7(e,t.entityLogicalName),D={uniquename:l,description:`${t.entityLogicalName} row summary`,"[email protected]":`/entities(${E})`,"[email protected]":`/msdyn_aimodels(${m})`,aiskill:"RowSummary"},F=(0,sr.ensureSuccess)(await e.post("/aiskillconfigs",D),e.apiUrl("/aiskillconfigs")),x=(0,sr.requireCreatedId)(F,"aiskillconfigid","row-summary skill");return{modelId:m,aiSkillConfigId:x}}catch(E){try{await e.delete(`/msdyn_aimodels(${m})`)}catch{}throw E}}ke.configureRowSummary=U7;async function B7(e,t){var r,n;let i=`ais_RowSummary_${t.entityLogicalName}`,a=`/aiskillconfigs${(0,Qe.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,Qe.odataLiteral)(i)}'`],["$top",1]])}`,o=((n=(r=(0,sr.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,sr.ensureSuccess)(await e.delete(s),e.apiUrl(s)),o._aimodel_value){let l=`/msdyn_aimodels(${o._aimodel_value})`;(0,sr.ensureSuccess)(await e.delete(l),e.apiUrl(l))}}ke.removeRowSummary=B7});var e1=g(Ta=>{"use strict";Object.defineProperty(Ta,"__esModule",{value:!0});Ta.findArtifact=Ta.resolveArtifact=void 0;var ht=ee(),tn=Ys(),$7=al(),q7=ye(),V7=ie();async function G7(e,t,r){var n,i,a,o,s,l,u,c,d,p,m,h;switch(t){case"app":{let w=(0,$7.unpublishedAppModulesQuery)("appmoduleid,name,appmoduleidunique",`uniquename eq '${(0,ht.odataLiteral)((n=r.uniqueName)!==null&&n!==void 0?n:"")}'`,1),E=(i=(0,q7.ensureSuccess)(await e.get(w),e.apiUrl(w)).body)===null||i===void 0?void 0:i.value,D=E&&E[0];return D?[{id:String(D.appmoduleid),name:String(D.name),appModuleIdUnique:String(D.appmoduleidunique)}]:[]}case"dashboard":return(await(0,tn.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,ht.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 w=await(0,tn.queryRecords)(e,"appaction",{select:["appactionid","buttonlabeltext"],filter:`contextvalue eq '${(0,ht.odataLiteral)((o=r.entity)!==null&&o!==void 0?o:"")}'`,top:1});return w&&w.length?[{id:String(r.entity),entity:String(r.entity)}]:[]}case"form":return(await(0,tn.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,ht.odataLiteral)((s=r.name)!==null&&s!==void 0?s:"")}' and objecttypecode eq '${(0,ht.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,tn.queryRecords)(e,"savedqueryvisualization",{select:["savedqueryvisualizationid","name"],filter:`name eq '${(0,ht.odataLiteral)((u=r.name)!==null&&u!==void 0?u:"")}' and primaryentitytypecode eq '${(0,ht.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,tn.queryRecords)(e,"savedquery",{select:["savedqueryid","name"],filter:`name eq '${(0,ht.odataLiteral)((d=r.name)!==null&&d!==void 0?d:"")}' and returnedtypecode eq '${(0,ht.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,tn.queryRecords)(e,"webresource",{select:["webresourceid","name"],filter:`name eq '${(0,ht.odataLiteral)((m=r.name)!==null&&m!==void 0?m:"")}'`,top:1})||[]).map(b=>({id:String(b.webresourceid),name:String(b.name)}));case"solution":return(await(0,tn.queryRecords)(e,"solution",{select:["solutionid","uniquename"],filter:`uniquename eq '${(0,ht.odataLiteral)((h=r.uniqueName)!==null&&h!==void 0?h:"")}'`,top:1})||[]).map(b=>({id:String(b.solutionid),name:String(b.uniquename)}));default:return[]}}Ta.resolveArtifact=G7;async function z7(e,t,r){var n,i,a,o,s;let l=(0,ht.odataLiteral)((n=r.name)!==null&&n!==void 0?n:""),u=(0,ht.odataLiteral)((i=r.entity)!==null&&i!==void 0?i:"");if(t==="command"){let h=await(0,tn.queryRecords)(e,"appaction",{select:["appactionid"],filter:`contextvalue eq '${(0,ht.odataLiteral)((a=r.entity)!==null&&a!==void 0?a:"")}'`,top:1});return h&&h.length?String(r.entity):null}let c=W7(t,l,u,r),d=t!=="app",p=await(0,tn.queryRecords)(e,c.set,{select:[c.idField],filter:c.filter,top:d?2:1});if(d&&p&&p.length>1)throw new V7.AmbiguousArtifactError(t,(s=(o=r.name)!==null&&o!==void 0?o:r.uniqueName)!==null&&s!==void 0?s:"",p.length);let m=p&&p[0]&&p[0][c.idField];return m!=null?String(m):null}Ta.findArtifact=z7;function W7(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,ht.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 r1=g(Yu=>{"use strict";Object.defineProperty(Yu,"__esModule",{value:!0});Yu.seedRecordGraph=void 0;var t1=Ys(),j7=Ws(),Ku=ee(),H7=ie();async function J7(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,j7.resolveEntitySetName)(e,p)),c={},d=p=>{var m;return(m=c[p])!==null&&m!==void 0?m:l[p]};for(let p of t){let m=p.entityLogical.toLowerCase(),h=(a=p.matchOn)===null||a===void 0?void 0:a.toLowerCase(),w=[];for(let G of p.records){let M={...G.body};for(let U of(o=G.binds)!==null&&o!==void 0?o:[]){let B=U.parentEntity.toLowerCase(),W=(s=d(B))===null||s===void 0?void 0:s[U.parentIndex];if(!W)throw new H7.InvalidArgumentError(`Cannot resolve bind '${U.navProperty}' on a '${m}' record: parent '${U.parentEntity}'[${U.parentIndex}] has no created id. Seed the parent group before the child, or supply it via options.createdIds.`);let $=(0,Ku.assertODataName)(await u(B),`entity set for parent '${U.parentEntity}'`),Se=(0,Ku.normalizeGuid)(W,`parent id for bind '${U.navProperty}'`);M[`${U.navProperty}@odata.bind`]=`/${$}(${Se})`}w.push(M)}let b=h?w.map(G=>{let M=G[h];return M!=null&&M!==""?String(M):null}):w.map(()=>null),E=new Map;if(h){let G=(0,Ku.assertODataName)(h,"RecordGraph matchOn key"),M=[...new Set(b.filter(U=>U!==null))];if(M.length){let U=M.map(W=>`${G} eq '${(0,Ku.odataLiteral)(W)}'`).join(" or "),B=await(0,t1.queryRecords)(e,m,{select:[G,`${m}id`],filter:U,top:5e3});for(let W of B??[]){let $=W[G];$!=null&&E.set(String($).toLowerCase(),String(W[`${m}id`]))}}}let D=[],F=new Map,x=w.map((G,M)=>{let U=b[M];if(U&&E.has(U.toLowerCase()))return null;if(U){let B=U.toLowerCase(),W=F.get(B);if(W!==void 0)return W;let $=D.push(G)-1;return F.set(B,$),$}return D.push(G)-1}),q=D.length?await(0,t1.createRecordsBulk)(e,m,D):[];c[m]=w.map((G,M)=>{let U=b[M];return U&&E.has(U.toLowerCase())?E.get(U.toLowerCase()):q[x[M]]})}return{createdIds:c}}Yu.seedRecordGraph=J7});var d1=g(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.getEntityPrivileges=Pt.deleteSecurityRole=Pt.createPersonaRole=Pt.createSecurityRole=Pt.SDK_ROLE_MARKER=void 0;var Pr=ye(),nt=ee(),Xt=ie(),Zu={read:"Read",create:"Create",write:"Write",delete:"Delete",append:"Append",appendTo:"AppendTo",assign:"Assign",share:"Share"},l1={user:"Basic",businessUnit:"Local",parentChild:"Deep",organization:"Global"},n1={user:1,businessUnit:2,parentChild:3,organization:4},rh={user:"CanBeBasic",businessUnit:"CanBeLocal",parentChild:"CanBeDeep",organization:"CanBeGlobal"};Pt.SDK_ROLE_MARKER="Authored by @maker-studio/cds-maker-sdk (persona/security role).";function Q7(e){return Object.prototype.hasOwnProperty.call(Zu,e)?Zu[e]:void 0}function X7(e){return Object.prototype.hasOwnProperty.call(l1,e)}var i1=new WeakMap,a1=new WeakMap;async function u1(e,t){var r,n;(0,nt.assertODataName)(t,"entity logical name");let i=i1.get(e);i||(i=new Map,i1.set(e,i));let a=i.get(t);if(a)return a;let o=`/EntityDefinitions(LogicalName='${(0,nt.odataPathLiteral)(t)}')${(0,nt.odataQuery)([["$select","LogicalName,Privileges"]])}`,l=(n=(r=(0,Pr.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 Xt.InvalidArgumentError(`Entity '${t}' exposes no privileges (unknown or non-securable entity).`);return i.set(t,l),l}async function K7(e){var t,r,n;let i=a1.get(e);if(i)return i;let a=`/businessunits${(0,nt.odataQuery)([["$select","businessunitid"],["$filter","_parentbusinessunitid_value eq null"],["$top",1]])}`,l=(n=((r=(t=(0,Pr.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 Xt.InvalidArgumentError("Could not resolve the root business unit.");let u=(0,nt.normalizeGuid)(l,"businessUnitId");return a1.set(e,u),u}async function Y7(e,t){var r;let n=new Map;for(let i of t){if(!i.access||i.access.length===0)throw new Xt.InvalidArgumentError(`Entity '${i.entity}' privilege request has no access levels.`);let a=(r=i.scope)!==null&&r!==void 0?r:"user";if(!X7(a))throw new Xt.InvalidArgumentError(`Unknown privilege scope '${a}' for entity '${i.entity}'.`);let o=await u1(e,i.entity);for(let s of i.access){let l=Q7(s);if(!l)throw new Xt.InvalidArgumentError(`Unknown access level '${s}' for entity '${i.entity}'.`);let u=o.find(h=>h.PrivilegeType===l);if(!u)throw new Xt.InvalidArgumentError(`Entity '${i.entity}' does not support '${s}' access.`);let c=rh[a];if(u[c]===!1)throw new Xt.InvalidArgumentError(`Privilege '${u.Name}' on '${i.entity}' does not support the '${a}' scope.`);let d=(0,nt.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 h=[...p.entities].sort().join(", ");throw new Xt.InvalidArgumentError(`Entities '${h}' 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=n1[a]>n1[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 Z7(e,t,r,n){if(r.length===0&&!n)return;let i={Privileges:r.map(o=>({Depth:l1[o.scope],PrivilegeId:o.privilegeId}))},a=`/roles(${t})/Microsoft.Dynamics.CRM.ReplacePrivilegesRole`;(0,Pr.ensureSuccess)(await e.post(a,i),e.apiUrl(a))}async function o1(e,t,r,n,i){var a,o;let s=`/${t}(${r})/${n}${(0,nt.odataQuery)([["$select","roleid"],["$filter",`roleid eq ${i}`]])}`;return((o=(a=(0,Pr.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 ez(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,nt.normalizeGuid)(l,"teamId");if(!await o1(e,"teams",u,"teamroles_association",t)){let c=`/teams(${u})/teamroles_association/$ref`;(0,Pr.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,nt.normalizeGuid)(l,"userId");if(!await o1(e,"systemusers",u,"systemuserroles_association",t)){let c=`/systemusers(${u})/systemuserroles_association/$ref`;(0,Pr.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}o.push(u)}return{teams:a,users:o}}async function s1(e,t,r){var n,i;let a=`/roles${(0,nt.odataQuery)([["$select","roleid,description,ismanaged"],["$filter",`name eq '${(0,nt.odataLiteral)(t)}' and _businessunitid_value eq ${r}`]])}`,l=((i=(n=(0,Pr.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:"")===Pt.SDK_ROLE_MARKER};if(l.some(d=>!u(d)))throw new Xt.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 Xt.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,nt.normalizeGuid)(c,"roleId"):void 0}function tz(e){var t,r;return{teams:((t=e?.teams)!==null&&t!==void 0?t:[]).map(n=>(0,nt.normalizeGuid)(n,"teamId")),users:((r=e?.users)!==null&&r!==void 0?r:[]).map(n=>(0,nt.normalizeGuid)(n,"userId"))}}function rz(e){return e.map(t=>({entity:t.entity,privilegeName:t.privilegeName,privilegeType:t.privilegeType,scope:t.scope}))}async function c1(e,t){var r,n;let i=(r=t.name)===null||r===void 0?void 0:r.trim();if(!i)throw new Xt.InvalidArgumentError("createSecurityRole: a non-empty role name is required.");let a=t.businessUnitId?(0,nt.normalizeGuid)(t.businessUnitId,"businessUnitId"):await K7(e),o=await Y7(e,(n=t.privileges)!==null&&n!==void 0?n:[]),s=tz(t.assignTo),l=await s1(e,i,a),u=l!==void 0;if(!l){let d="/roles",p={name:i,description:Pt.SDK_ROLE_MARKER,"[email protected]":`/businessunits(${a})`};try{let m=(0,Pr.ensureSuccess)(await e.post(d,p),e.apiUrl(d));l=(0,nt.normalizeGuid)((0,Pr.requireCreatedId)(m,"roleid","role"),"roleId")}catch(m){let h;try{h=await s1(e,i,a)}catch{h=void 0}if(!h)throw m;l=h}}await Z7(e,l,o,u);let c=await ez(e,l,s);return{roleId:l,name:i,reused:u,appliedPrivileges:rz(o),assignedTeams:c.teams,assignedUsers:c.users}}Pt.createSecurityRole=c1;async function nz(e,t){var r,n;let i=(r=t.persona)===null||r===void 0?void 0:r.trim();if(!i)throw new Xt.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 c1(e,{name:i,businessUnitId:t.businessUnitId,privileges:a,assignTo:t.assignTo})}Pt.createPersonaRole=nz;async function iz(e,t){let n=`/roles(${(0,nt.normalizeGuid)(t,"roleId")})`;(0,Pr.ensureSuccess)(await e.delete(n),e.apiUrl(n))}Pt.deleteSecurityRole=iz;var az=new Map(Object.keys(Zu).map(e=>[Zu[e],e]));async function oz(e,t){return(await u1(e,t)).map(n=>{let i=Object.keys(rh).filter(o=>n[rh[o]]!==!1),a=az.get(n.PrivilegeType);return{name:n.Name,privilegeId:n.PrivilegeId,privilegeType:n.PrivilegeType,...a?{access:a}:{},scopes:i}})}Pt.getEntityPrivileges=oz});var v1=g(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.createMakerSdk=Or.MakerSdk=Or.ALREADY_EXISTS_CODE=void 0;var p1=Ec(),sz=yd(),ce=ie(),rn=xs(),lz=pv(),f1=hv(),uz=Av(),cz=$v(),nh=qv(),Xe=Ws(),m1=Ud(),nn=Ys(),ec=hy(),Oa=el(),dz=rl(),ut=Cy(),pz=Hd(),fz=z_(),mz=In(),hz=yt(),gz=Ei(),Ln=hd(),h1=Cd(),vz=3e5,Tr=ye(),kn=ee(),Ra=Z_(),g1=e1(),yz=r1(),bz=um(),tc=d1();Or.ALREADY_EXISTS_CODE="ARTIFACT_ALREADY_EXISTS";var nc=class{constructor(t){var r,n;this.artifactLocks=new Map,(0,mz.installDomShim)(),this.languageCode=(r=t.languageCode)!==null&&r!==void 0?r:gz.DEFAULT_LCID,this.cacheStalenessMs=(n=t.cacheStalenessMs)!==null&&n!==void 0?n:vz,this.workspace=new f1.WorkspaceManager(t.workspacePath,t.instanceUrl),this.versions=new uz.VersionManager(this.workspace),this.dataverse=new cz.DataverseClient(t.instanceUrl,t.httpClient,t.solutionUniqueName),this.registrations=(0,fz.buildRegistrations)(this.languageCode)}initWorkspace(){this.workspace.init()}getManifest(){return this.workspace.getManifest()}cleanWorkspace(){this.workspace.clean()}withArtifactLock(t,r,n){var i;let a=`${t}\0${(0,f1.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&&this.versions.isDirty(t,r)){let p=(a=(i=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 ce.LocalEditsWouldBeLostError(t,r,p,l);let m=this.workspace.readArtifact(t,r);if(m){let h=this.versions.getMeta(t,r);if(h&&!h.etag&&l){if(!(0,h1.deepEqual)(h.snapshot,d))throw new ce.LocalEditsWouldBeLostError(t,r,p,l);this.versions.storeMeta(t,r,{...h,etag:l,fetchedAt:(0,Tr.nowIso)()})}return(0,Ln.cloneJson)(m)}}return this.workspace.writeArtifact(t,r,d),this.versions.storeMeta(t,r,{etag:l,languageCode:this.languageCode,fetchedAt:(0,Tr.nowIso)(),snapshot:(0,Ln.cloneJson)(d),...u?{memberEtags:u}:{},...c?{siblingEtags:c}:{}}),(0,Ln.cloneJson)(d)}async fetchArtifactList(t,r){return this.requireRegistration(t,"fetchArtifactList").api.list(this.dataverse,r)}async fetchSolution(t){var r;let n=await(0,ut.fetchSolutionComponents)(this.dataverse,t),i=[],a=[];for(let o of n)try{let s=await this.resolveComponentType(o);if(!s){a.push({componentId:o.objectId,componentType:o.componentType,workflowCategory:o.workflowCategory,reason:"unsupported"});continue}let l=await this.fetchArtifact(s,o.objectId);i.push({type:s,id:o.objectId,name:typeof l.name=="string"?l.name:(r=o.displayName)!==null&&r!==void 0?r:o.objectId,entityLogicalName:typeof l.entityLogicalName=="string"?l.entityLogicalName:void 0,lastFetched:(0,Tr.nowIso)(),isDirty:!1})}catch(s){a.push({componentId:o.objectId,componentType:o.componentType,workflowCategory:o.workflowCategory,reason:"failed",error:rc(s)})}return this.workspace.updateManifest({lastSyncAt:(0,Tr.nowIso)()}),{summaries:i,skipped:a}}async fetchEntityMetadata(t){let r=await(0,nh.fetchEntityMetadataFromApi)(this.dataverse,t);return this.workspace.writeEntityMetadata(t,r),r}findTables(t,r){return(0,nh.findTables)(this.dataverse,t,r)}findColumns(t,r,n){return(0,nh.findColumns)(this.dataverse,t,r,n)}createTable(t){return(0,Xe.createTable)(this.dataverse,t)}createColumn(t,r){return(0,Xe.createColumn)(this.dataverse,t,r)}createColumns(t,r){return(0,Xe.createColumns)(this.dataverse,t,r)}updateColumn(t,r,n){return(0,Xe.updateColumn)(this.dataverse,t,r,n)}deleteColumn(t,r){return(0,Xe.deleteColumn)(this.dataverse,t,r)}setFormSecurityRoles(t,r){return(0,m1.setFormSecurityRoles)(this.dataverse,t,r)}getFormSecurityRoles(t){return(0,m1.getFormSecurityRoles)(this.dataverse,t)}validateBusinessRule(t,r){return new sz.BusinessRuleAdapter().semanticIssues(t,r)}setColumnVisualization(t,r,n){return(0,Xe.setColumnVisualization)(this.dataverse,t,r,n)}getColumnVisualization(t,r){return(0,Xe.getColumnVisualization)(this.dataverse,t,r)}createCustomerColumn(t,r){return(0,Xe.createCustomerColumn)(this.dataverse,t,r)}insertStatusValue(t,r){return(0,Xe.insertStatusValue)(this.dataverse,t,r)}updateTable(t,r){return(0,Xe.updateTable)(this.dataverse,t,r)}async setEntityIcon(t,r){if(await(0,Xe.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,kn.xmlText)(t)}</entity></entities></importexportxml>`;(0,Tr.ensureSuccess)(await this.dataverse.post("/PublishXml",{ParameterXml:n}),this.dataverse.apiUrl("/PublishXml"))}}createAlternateKey(t,r){return(0,Xe.createAlternateKey)(this.dataverse,t,r)}deleteAlternateKey(t,r){return(0,Xe.deleteAlternateKey)(this.dataverse,t,r)}createRelationship(t){return(0,Xe.createRelationship)(this.dataverse,t)}deleteRelationship(t){return(0,Xe.deleteRelationship)(this.dataverse,t)}createGlobalOptionSet(t){return(0,Xe.createGlobalOptionSet)(this.dataverse,t)}deleteGlobalOptionSet(t){return(0,Xe.deleteGlobalOptionSet)(this.dataverse,t)}deleteTable(t){return(0,Xe.deleteTable)(this.dataverse,t)}createSecurityRole(t){return(0,tc.createSecurityRole)(this.dataverse,t)}createPersonaRole(t){return(0,tc.createPersonaRole)(this.dataverse,t)}deleteSecurityRole(t){return(0,tc.deleteSecurityRole)(this.dataverse,t)}getEntityPrivileges(t){return(0,tc.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,yz.seedRecordGraph)(this.dataverse,t,r)}resolveArtifact(t,r){return(0,g1.resolveArtifact)(this.dataverse,t,r)}findArtifact(t,r){return(0,g1.findArtifact)(this.dataverse,t,r)}async deleteAppCascade(t,r){let n=await(0,pz.deleteAppCascade)(this.dataverse,t,r),i=(0,kn.normalizeGuid)(t,"appModuleId");return this.workspace.readArtifact("app",i)&&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,ec.createWebResource)(this.dataverse,t)}updateWebResource(t,r){return(0,ec.updateWebResource)(this.dataverse,t,r)}getWebResource(t){return(0,ec.getWebResource)(this.dataverse,t)}deleteWebResource(t){return(0,ec.deleteWebResource)(this.dataverse,t)}getAppSettings(t){return(0,Oa.readAppSettings)(this.dataverse,t)}setAppSetting(t,r,n){return(0,Oa.setAppSetting)(this.dataverse,t,r,n)}setHeaderAndNavigationRefresh(t,r){if(typeof r!="boolean")throw new ce.ValidationError("app",t,[{pointer:"/headerAndNavigationRefresh",rule:dz.HEADER_NAV_BOOLEAN_RULE,message:`enabled must be a boolean, got ${typeof r}`}]);return(0,Oa.setAppSetting)(this.dataverse,t,Oa.HEADER_AND_NAVIGATION_REFRESH,r?Oa.APP_SETTING_ON:Oa.APP_SETTING_OFF)}getSolution(t){return(0,ut.getSolution)(this.dataverse,t)}createPublisher(t){return(0,ut.createPublisher)(this.dataverse,t)}createSolution(t){return(0,ut.createSolution)(this.dataverse,t)}setSolutionVersion(t,r){return(0,ut.setSolutionVersion)(this.dataverse,t,r)}addSolutionComponent(t){return(0,ut.addSolutionComponent)(this.dataverse,t)}removeSolutionComponent(t,r,n){return(0,ut.removeSolutionComponent)(this.dataverse,t,r,n)}exportSolution(t){return(0,ut.exportSolution)(this.dataverse,t)}importSolution(t){return(0,ut.importSolution)(this.dataverse,t)}deleteSolution(t){return(0,ut.deleteSolution)(this.dataverse,t)}async getArtifact(t,r){return this.withArtifactLock(t,r,()=>this.getArtifactUnlocked(t,r))}async getArtifactUnlocked(t,r){return(0,Ln.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 ce.StaleArtifactError(t,r,n);return this.readLocal(t,r)}readLocal(t,r){let n=this.workspace.readArtifact(t,r);if(!n)throw new ce.ArtifactNotFoundError(t,r);return n}async revalidateIfStale(t,r){let n=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(this.versions.isDirty(t,r))return"skipped";let o=this.workspace.readArtifact(t,r);await this.fetchArtifactUnlocked(t,r);let s=this.workspace.readArtifact(t,r);return(0,h1.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=rn.JsonPointer.resolve(i,n);if(a===void 0)throw new ce.PathNotFoundError(t,r,n);return a})}async findElements(t,r,n){return this.withArtifactLock(t,r,async()=>(0,lz.findElements)(await this.getArtifactUnlocked(t,r),n))}listArtifacts(t,r){return this.workspace.listArtifacts(t,r).map(n=>({...n,isDirty:this.versions.isDirty(n.type,n.id)}))}getEntityMetadata(t){let r=this.workspace.readEntityMetadata(t);if(!r)throw new ce.ArtifactNotFoundError("entityMetadata",t);return r}getFieldMetadata(t,r){let i=this.getEntityMetadata(t).attributes.find(a=>a.logicalName===r);if(!i)throw new ce.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=rn.JsonPointer.resolve(a,n);if(o===void 0)throw new ce.PathNotFoundError(t,r,n);let s=ic(o)&&ic(i)?{...o,...i}:i;return rn.JsonPointer.set(a,n,(0,Ln.cloneJson)(s)),this.assertStructurallyValid(t,r,a,n),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=rn.JsonPointer.resolve(o,n);if(s===void 0)throw new ce.PathNotFoundError(t,r,n);if(!Array.isArray(s))throw new ce.ValidationError(t,r,n,"parent must be an array");let l=this.assignMissingIds(t,(0,Ln.cloneJson)(i)),u=Cz(s,a?.position);return s.splice(u,0,l),this.assertStructurallyValid(t,r,o,n),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=rn.JsonPointer.resolve(s,n);if(l===void 0)throw new ce.PathNotFoundError(t,r,n);let u=rn.JsonPointer.resolve(s,i);if(u===void 0)throw new ce.PathNotFoundError(t,r,i);if(!Array.isArray(u))throw new ce.ValidationError(t,r,i,"move target must be an array");if(i===n||i.startsWith(`${n}/`))throw new ce.ValidationError(t,r,i,"cannot move an element into its own subtree");rn.JsonPointer.remove(s,n);let c=(o=a?.index)!==null&&o!==void 0?o:u.length;return u.splice(Math.max(0,Math.min(c,u.length)),0,l),this.assertStructurallyValid(t,r,s,i),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(rn.JsonPointer.resolve(i,n)===void 0)throw new ce.PathNotFoundError(t,r,n);return rn.JsonPointer.remove(i,n),this.assertStructurallyValid(t,r,i,Az(n)),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 ce.ValidationError(t,r,u)}retrieveSetting(t,r){return(0,Ra.retrieveSetting)(this.dataverse,t,r)}saveSettingValue(t,r,n){return(0,Ra.saveSettingValue)(this.dataverse,t,r,n)}getAiReadiness(t){return(0,Ra.getAiReadiness)(this.dataverse,t)}setAppAiFeatures(t,r,n){return(0,Ra.setAppAiFeatures)(this.dataverse,t,r,n)}configureRowSummary(t,r){return(0,Ra.configureRowSummary)(this.dataverse,t,r)}removeRowSummary(t){return(0,Ra.removeRowSummary)(this.dataverse,t)}async enrichDefaultViews(t,r,n={}){let i=await(0,bz.findDefaultViews)(this.dataverse,t,n);for(let a of i)await this.fetchArtifact("view",a.id),await this.updateElement("view",a.id,"/columns",r),await this.pushArtifact("view",a.id);return i.length&&await this.publishArtifact("view",i[0].id),{updated:i.map(a=>a.id)}}createArtifact(t,r){let n=this.requireRegistration(t,"createArtifact"),i=n.adapter.assignMissingIds(n.adapter.createDefault(r)),a=i.id;if(!a)throw new ce.ValidationError(t,"(new)","/id","created artifact must have an id");return this.workspace.writeArtifact(t,a,i),(0,Ln.cloneJson)(i)}deleteArtifact(t,r){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),this.workspace.readArtifact(t,r)&&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:rc(u)},...s?{publishScope:s}:{}}}if(!n?.verify)return{type:t,id:r,shipped:!1,publish:{kind:"submitted"},...s?{publishScope:s}:{}};let l=await this.verifyPublished(t,r);return{type:t,id:r,shipped:l.kind==="verified",publish:l,...s?{publishScope:s}:{}}}async verifyPublished(t,r){if(t!=="app")return{kind:"unverifiable",reason:`published-projection verification is not characterised for '${t}'; the publish was submitted`};try{let n=`/appmodules(${(0,kn.normalizeGuid)(r,"id")})${(0,kn.odataQuery)([["$select","appmoduleid"]])}`,i=await this.dataverse.get(n);return i.status>=200&&i.status<300?{kind:"verified"}:{kind:"unverifiable",reason:`the published projection answered HTTP ${i.status}`}}catch(n){return{kind:"unverifiable",reason:rc(n).message}}}async pushArtifact(t,r){return this.withArtifactLock(t,r,()=>this.pushArtifactUnlocked(t,r))}async pushArtifactUnlocked(t,r){var n,i,a,o,s,l;let u=this.requireRegistration(t,"pushArtifact"),c=this.readLocal(t,r),d=this.versions.getMeta(t,r);this.assertLanguageMatches(t,r,d,u);let p=await this.buildMetadataContext(u.adapter,c),m=u.adapter.toApiPayload(c,d?.snapshot,p);try{let h=d?await u.api.update(this.dataverse,r,m,d.etag,d.memberEtags,d.siblingEtags):await this.createWithMintedId(u,t,r,m),w=r;return d||(h.serverIdentity&&u.adapter.applyServerIdentity&&u.adapter.applyServerIdentity(c,h.serverIdentity),h.id&&h.id!==r&&(c.id=h.id,this.workspace.deleteArtifact(t,r),w=h.id),this.workspace.writeArtifact(t,w,c)),this.versions.storeMeta(t,w,{etag:h.etag,languageCode:this.languageCode,fetchedAt:(0,Tr.nowIso)(),snapshot:(0,Ln.cloneJson)(c),...h.memberEtags?{memberEtags:h.memberEtags}:{},...h.siblingEtags?{siblingEtags:h.siblingEtags}:{}}),{type:t,id:w,saved:!0,shipped:!1,publish:(n=h.publish)!==null&&n!==void 0?n:{kind:"notRequested"},...h.publish&&h.publish.kind!=="notRequested"?(()=>{var b;let E=(b=u.publishScope)===null||b===void 0?void 0:b.call(u,w,c);return E?{publishScope:E}:{}})():{},...h.warnings&&h.warnings.length>0?{warnings:h.warnings}:{}}}catch(h){let w=(0,ce.readPartialTokens)(h);if(w&&d){let b={...(i=d.memberEtags)!==null&&i!==void 0?i:{},...(a=w.memberEtags)!==null&&a!==void 0?a:{}},E={...(o=d.siblingEtags)!==null&&o!==void 0?o:{},...(s=w.siblingEtags)!==null&&s!==void 0?s:{}};this.versions.storeMeta(t,r,{...d,...Object.keys(b).length>0?{memberEtags:b}:{},...Object.keys(E).length>0?{siblingEtags:E}:{}})}if(h instanceof ce.SdkError&&h.code===Or.ALREADY_EXISTS_CODE)return{type:t,id:r,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:h};if(h instanceof ce.SdkError&&h.code===p1.WFOM_API_UNAVAILABLE_CODE)return{type:t,id:r,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:h};if(h instanceof ce.SdkError&&h.code===p1.BUSINESS_RULE_LEFT_DEACTIVATED_CODE)return{type:t,id:r,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:h};if(h instanceof ce.SdkError&&h.code===Tr.VERSION_CONFLICT_CODE)return{type:t,id:r,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:new ce.VersionConflictError(t,r,(l=d?.etag)!==null&&l!==void 0?l:null,null,h.message)};throw h}}assertLanguageMatches(t,r,n,i){if(i?.languageSensitive&&!(n?.languageCode===void 0||n.languageCode===this.languageCode))throw new ce.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}.`)}async createWithMintedId(t,r,n,i){try{return await t.api.create(this.dataverse,i,n)}catch(a){throw!(a instanceof ce.SdkError)||a.code!==Tr.VERSION_CONFLICT_CODE?a:new ce.SdkError(Or.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}') to adopt the existing record's identity, etag and snapshot, then push again \u2014 that push will be a conditional update. This is not done automatically because the only recovery available here would be an UNCONDITIONAL overwrite, which would destroy any edit made to the record in the meantime.`)}}async buildMetadataContext(t,r){var n,i;let a=(i=(n=t.metadataNeeds)===null||n===void 0?void 0:n.call(t,r))!==null&&i!==void 0?i:[];if(a.length===0)return;let o=new Set(a.map(s=>s.entityLogicalName).filter(s=>!!s));for(let s of o)if(!this.workspace.readEntityMetadata(s))try{await this.fetchEntityMetadata(s)}catch{}return{resolveField:(s,l)=>{let u=this.workspace.readEntityMetadata(s),c=u?.attributes.find(d=>d.logicalName===l);return c?{displayName:c.displayName,attributeType:c.attributeType}:void 0}}}async pushAll(){let t=this.getDirtyArtifacts(),r=[];for(let n of t)try{r.push(await this.pushArtifact(n.type,n.id))}catch(i){r.push({type:n.type,id:n.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:rc(i)})}return r}getDirtyArtifacts(){return this.workspace.listArtifacts().filter(t=>this.versions.isDirty(t.type,t.id)).map(t=>({...t,isDirty:!0}))}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,hz.assignMissingIds)(r)}async resolveComponentType(t){switch(t.componentType){case ut.SolutionComponentType.SavedQuery:return"view";case ut.SolutionComponentType.SavedQueryVisualization:return"chart";case ut.SolutionComponentType.AppModule:return"app";case ut.SolutionComponentType.UxAgentProject:return"genPage";case ut.SolutionComponentType.Workflow:return t.workflowCategory===2?"businessRule":t.workflowCategory===4&&await this.isBusinessFlowWorkflow(t.objectId)?"bpf":void 0;case ut.SolutionComponentType.SystemForm:return await this.isDashboardForm(t.objectId)?"dashboard":"form";default:return}}async isDashboardForm(t){let n=`/systemforms(${(0,kn.normalizeGuid)(t,"formId")})${(0,kn.odataQuery)([["$select","type"]])}`,i=(0,Tr.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,kn.normalizeGuid)(t,"workflowId")})${(0,kn.odataQuery)([["$select","businessprocesstype"]])}`,i=(0,Tr.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 ce.NotImplementedError(r,`no adapter registered for artifact type '${t}'`);return n}};Or.MakerSdk=nc;function wz(e){return new nc(e)}Or.createMakerSdk=wz;function rc(e){return e instanceof Error?e:new Error(String(e))}function ic(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Az(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function Cz(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=>ic(i)&&i.id===t.before);return n<0?e.length:n}let r=e.findIndex(n=>ic(n)&&n.id===t.after);return r<0?e.length:r+1}});var y1=g(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});ac.ARTIFACT_TYPES=void 0;ac.ARTIFACT_TYPES=["form","view","businessRule","app","command","chart","dashboard","genPage","bpf"]});var w1=g(b1=>{"use strict";Object.defineProperty(b1,"__esModule",{value:!0})});var C1=g(A1=>{"use strict";Object.defineProperty(A1,"__esModule",{value:!0})});var E1=g(S1=>{"use strict";Object.defineProperty(S1,"__esModule",{value:!0})});var D1=g(N1=>{"use strict";Object.defineProperty(N1,"__esModule",{value:!0})});var _1=g(I1=>{"use strict";Object.defineProperty(I1,"__esModule",{value:!0})});var T1=g(P1=>{"use strict";Object.defineProperty(P1,"__esModule",{value:!0})});var R1=g(O1=>{"use strict";Object.defineProperty(O1,"__esModule",{value:!0})});var x1=g(F1=>{"use strict";Object.defineProperty(F1,"__esModule",{value:!0})});var k1=g(L1=>{"use strict";Object.defineProperty(L1,"__esModule",{value:!0})});var U1=g(M1=>{"use strict";Object.defineProperty(M1,"__esModule",{value:!0})});var $1=g(B1=>{"use strict";Object.defineProperty(B1,"__esModule",{value:!0})});var V1=g(q1=>{"use strict";Object.defineProperty(q1,"__esModule",{value:!0})});var z1=g(G1=>{"use strict";Object.defineProperty(G1,"__esModule",{value:!0})});var j1=g(W1=>{"use strict";Object.defineProperty(W1,"__esModule",{value:!0})});var J1=g(H1=>{"use strict";Object.defineProperty(H1,"__esModule",{value:!0})});var X1=g(Q1=>{"use strict";Object.defineProperty(Q1,"__esModule",{value:!0})});var Y1=g(K1=>{"use strict";Object.defineProperty(K1,"__esModule",{value:!0})});var eP=g(Z1=>{"use strict";Object.defineProperty(Z1,"__esModule",{value:!0})});var rP=g(tP=>{"use strict";Object.defineProperty(tP,"__esModule",{value:!0})});var Sz=exports&&exports.__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]})),Ie=exports&&exports.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&Sz(t,e,r)};Object.defineProperty(exports,"__esModule",{value:!0});exports.createMakerSdk=void 0;var Ez=v1();Object.defineProperty(exports,"createMakerSdk",{enumerable:!0,get:function(){return Ez.createMakerSdk}});Ie(y1(),exports);Ie(w1(),exports);Ie(C1(),exports);Ie(E1(),exports);Ie(D1(),exports);Ie(_1(),exports);Ie(T1(),exports);Ie(R1(),exports);Ie(x1(),exports);Ie(k1(),exports);Ie(U1(),exports);Ie($1(),exports);Ie(V1(),exports);Ie(rl(),exports);Ie(z1(),exports);Ie(j1(),exports);Ie(J1(),exports);Ie(X1(),exports);Ie(Y1(),exports);Ie(eP(),exports);Ie(rP(),exports);Ie(ie(),exports);+`)}function Tb(e){this.options=e||{locator:{}}}Tb.prototype.parseFromString=function(e,t){var r=this.options,n=new jk,i=r.domBuilder||new vo,a=r.errorHandler,o=r.locator,s=r.xmlns||{},l=/\/x?html?$/.test(t),u=l?Nb.HTML_ENTITIES:Nb.XML_ENTITIES;o&&i.setDocumentLocator(o),n.errorHandler=Hk(a,i,o),n.domBuilder=r.domBuilder||i,l&&(s[""]=Db.HTML),s.xml=s.xml||Db.XML;var c=r.normalizeLineEndings||Pb;return e&&typeof e=="string"?n.parse(c(e),s,u):n.errorHandler.error("invalid doc source"),i.doc};function Hk(e,t,r){if(!e){if(t instanceof vo)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+pp(r))}||function(){}}return a("warning"),a("error"),a("fatalError"),n}function vo(){this.cdata=!1}function Ui(e,t){t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber}vo.prototype={startDocument:function(){this.doc=new zk().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;vl(this,a),this.currentElement=a,this.locator&&Ui(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&&Ui(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&&Ui(this.locator,r),vl(this,r)},ignorableWhitespace:function(e,t,r){},characters:function(e,t,r){if(e=Ib.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&&Ui(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=Ib.apply(this,arguments);var n=this.doc.createComment(e);this.locator&&Ui(this.locator,n),vl(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&&Ui(this.locator,i),vl(this,i),this.doc.doctype=i}},warning:function(e){console.warn("[xmldom warning] "+e,pp(this.locator))},error:function(e){console.error("[xmldom error] "+e,pp(this.locator))},fatalError:function(e){throw new Wk(e,this.locator)}};function pp(e){if(e)return`+@`+(e.systemId||"")+"#[line:"+e.lineNumber+",col:"+e.columnNumber+"]"}function Ib(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){vo.prototype[e]=function(){return null}});function vl(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}yl.__DOMHandler=vo;yl.normalizeLineEndings=Pb;yl.DOMParser=Tb});var wl=g(bl=>{var Rb=up();bl.DOMImplementation=Rb.DOMImplementation;bl.XMLSerializer=Rb.XMLSerializer;bl.DOMParser=Ob().DOMParser});var Xd=g(Bi=>{"use strict";Object.defineProperty(Bi,"__esModule",{value:!0});Bi.deleteAppCascade=Bi.collectGenPageIds=void 0;var Qk=sl(),Jk=ie(),fp=ee(),Xk=wl();function Fb(e){let t=[],r=s=>l=>t.push(`${s}: ${l}`),i=new Xk.DOMParser({errorHandler:{warning:r("warning"),error:r("error"),fatalError:r("fatalError")}}).parseFromString(e,"text/xml").documentElement;if(!i||t.length>0)throw new Jk.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,fp.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}Bi.collectGenPageIds=Fb;async function Kk(e,t,r){let n=(0,fp.normalizeGuid)(t,"appModuleId");(0,fp.normalizeGuid)(r,"appModuleIdUnique");let i=[],a=[],o=[];await(0,Qk.deleteAppResolvingOnce)(e,n,l=>{l!==void 0&&o.push(...Fb(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}}Bi.deleteAppCascade=Kk});var xb={};Rr(xb,{Guid:()=>P});var P,Ue=I(()=>{"use strict";P=class e{guidString;guid;static get EmptyGuid(){return new e("00000000-0000-0000-0000-000000000000")}static NewGuid(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var r=Math.random()*16|0,n=t=="x"?r:r&3|8;return n.toString(16)})}constructor(t,r=!1){this.guidString=t;let n=new RegExp("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$");(r||n.test(t))&&(this.guid=t)}ToString(){return this.guid}}});var T,ot=I(()=>{"use strict";Le();T=class e{static get EmptyString(){return""}static IsTrue(t){let r=!1;return r=t&&(this.IsStrictTrue(t)||this.IsYes(t)),r}static IsStrictTrue(t){let r=!1;return t&&(r=t.toLowerCase()==="true"),r}static IsYes(t){return t.toLowerCase()==="yes"||t.toLowerCase()==="y"}static get WhiteSpace(){return/ /g}static get EnglishAndNumericCharacters(){return/([a-z0-9A-Z]+)/g}static get ValidIdExpression(){return/([a-z0-9A-Z_]+)/g}static IsNullOrEmpty(t){return t==null||t==null||t==""}static Format(t,r){return e.IsNullOrEmpty(t)?t:t.replace(/\{\{|\}\}|\{(\d+)\}/g,function(n,i){return n=="{{"?"{":n=="}}"?"}":r[i]})}static EndsWithString(t,r){return t.indexOf(r,t.length-r.length)!==-1}static IsBlankString(t){return t.replace(/\s/g,"").length==0}static EscapeXml(t,r){let n=t;return this.IsNullOrEmpty(n)||(n=n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),r&&(n=n.replace(/"/g,""").replace(/'/g,"'"))),n}static EscapeDomId(t){return t.replace(".","\\.")}static ToSnakeCase(t){let r=e.EmptyString;for(let n=0;n<t.length;n++)n!==0&&t[n]==t[n].toUpperCase()&&(r+="-"),r+=t[n].toLowerCase();return r}static GetSnakeCaseMarkup(t,r){let n="<"+this.ToSnakeCase(t);if(!E.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 E.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 Lb={};Rr(Lb,{ScriptUtilities:()=>E});var E,Le=I(()=>{"use strict";Ue();ot();E=class e{static IsNullOrUndefined(t){return t==null||t===void 0}static IsMacMachine(){return navigator.platform.indexOf("Mac")!==-1}static IsNullOrEmptyGuid(t){return T.IsNullOrEmpty(t.ToString())?!0:P.EmptyGuid.ToString()===t.ToString()}static IsNullOrUndefinedNested(t,r){return r.split(".").every(i=>typeof t!="object"||t==null||!(i in t)||t[i]==null?!1:(t=t[i],!0))}static ParseXml(t){return new DOMParser().parseFromString(t,"text/xml")}static IsWellFormedXml(t){return!e.ParseXml(t).querySelector("parsererror")}static getNamedItemValue(t,r){let n=t.getNamedItem(r);return e.IsNullOrUndefined(n)?null:n.value}static getBooleanValue(t,r){let n=e.getNamedItemValue(t,r);return e.IsNullOrUndefined(n)?null:T.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 Al,Cl,jn,Sl,mp,El,hp=I(()=>{"use strict";(function(e){e[e.FormElementNodeChange=0]="FormElementNodeChange",e[e.FormElementAttributeChange=1]="FormElementAttributeChange"})(Al||(Al={}));Cl=class{type;targetNode;constructor(t,r){this.type=t,this.targetNode=r}},jn=class extends Cl{key;oldValue;newValue;constructor(t,r,n,i){super(Al.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)}},Sl=class extends Cl{property;oldValue;newValue;constructor(t,r,n,i){super(Al.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)}},mp=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()})}},El=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 mp(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 kb={};Rr(kb,{ChartGridMode:()=>Bt,ColumnLayoutWidths:()=>rM,ComponentCategory:()=>Dl,ComponentType:()=>gp,ControlLayoutTypes:()=>Sp,DisplayConditionsInfo:()=>eM,ElementNames:()=>v,ElementProperties:()=>m,ElementType:()=>yp,EntityAttributeProperty:()=>bp,EventType:()=>yo,FormActivationState:()=>Cp,FormCanvasServiceScope:()=>mM,FormDesignerSideBarTab:()=>vp,FormPresentation:()=>wp,FormState:()=>Nl,FormType:()=>Be,HeaderDensityType:()=>yn,LookUpTable:()=>yr,MORE_TAB_PREFIX:()=>iM,NavBarChildElementType:()=>Ap,PREVIEW_ID_HEADER_FLYOUT:()=>lM,PREVIEW_ID_HEADER_OVERFLOW_BUTTON:()=>cM,PREVIEW_ID_NAVIGATION_AREA:()=>oM,PREVIEW_ID_QUICKCREATE_ROOT:()=>pM,PREVIEW_ID_TAB:()=>dM,PREVIEW_ID_TAB_LIST:()=>uM,PREVIEW_ID_TAB_PANEL:()=>sM,PropertyModelKeys:()=>Dp,PropertyModelSectionKeys:()=>nM,RELATED_TAB_ID:()=>Ip,RELATED_TAB_PREFIX:()=>aM,SectionDefaultProperties:()=>tM,SectionLayoutTypes:()=>Se,TabContentType:()=>Ep,TabDefaultProperties:()=>bn,TabLayoutTypes:()=>Ce,TelemetryPropertyNames:()=>fM,UnboundControlPropertyKeys:()=>Np,compositeAddressFields:()=>Zk,compositeFieldNames:()=>Ot,compositeFields:()=>Yk});var Be,gp,vp,v,m,yp,Ot,Yk,Zk,bp,yr,Nl,yn,wp,eM,Ap,Cp,Ce,tM,bn,Se,Sp,Ep,rM,Np,Dp,nM,yo,Bt,Ip,iM,aM,oM,sM,lM,uM,cM,dM,pM,fM,Dl,mM,K=I(()=>{"use strict";(function(e){e[e.Dashboard=0]="Dashboard",e[e.AppointmentBook=1]="AppointmentBook",e[e.Main=2]="Main",e[e.MiniCampaignBO=3]="MiniCampaignBO",e[e.Preview=4]="Preview",e[e.MobileExpress=5]="MobileExpress",e[e.QuickViewForm=6]="QuickViewForm",e[e.QuickCreate=7]="QuickCreate",e[e.Dialog=8]="Dialog",e[e.TaskFlowForm=9]="TaskFlowForm",e[e.InteractionCentricDashboard=10]="InteractionCentricDashboard",e[e.Card=11]="Card",e[e.MainInteractiveExperience=12]="MainInteractiveExperience",e[e.Other=100]="Other",e[e.MainBackup=101]="MainBackup",e[e.AppointmentBookBackup=102]="AppointmentBookBackup",e[e.PowerBIDashboard=103]="PowerBIDashboard"})(Be||(Be={}));(function(e){e[e.Form=0]="Form",e[e.Dialog=1]="Dialog"})(gp||(gp={}));(function(e){e[e.Components=0]="Components",e[e.Properties=1]="Properties",e[e.Relationship=2]="Relationship",e[e.BusinessRules=3]="BusinessRules"})(vp||(vp={}));(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"})(v||(v={}));m={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"})(yp||(yp={}));Ot={fullname:"fullname",yomifullname:"yomifullname",address1_composite:"address1_composite",address2_composite:"address2_composite",address3_composite:"address3_composite",billto:"billto_composite",shipto:"shipto_composite"},Yk=[Ot.fullname,Ot.yomifullname,Ot.address1_composite,Ot.address2_composite,Ot.address3_composite,Ot.billto,Ot.shipto],Zk=[Ot.address1_composite,Ot.address2_composite,Ot.address3_composite,Ot.billto,Ot.shipto];(function(e){e[e.IsValidForForm=0]="IsValidForForm",e[e.IsValidForCreate=1]="IsValidForCreate"})(bp||(bp={}));(function(e){e[e.DependencyFieldTable=0]="DependencyFieldTable",e[e.LockedFieldTable=1]="LockedFieldTable"})(yr||(yr={}));(function(e){e[e.Published=0]="Published",e[e.Draft=1]="Draft",e[e.New=2]="New",e[e.SaveAs=3]="SaveAs"})(Nl||(Nl={}));(function(e){e.Low="Low",e.HighReadOnlyValues="HighReadOnlyValues",e.HighWithControls="HighWithControls"})(yn||(yn={}));(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(wp||(wp={}));eM={TopOrderFormId:"topOrderFormId",NextDisplayOrder:"nextDisplayOrder"};(function(e){e[e.NavBarRelationShipItem=0]="NavBarRelationShipItem",e[e.NavBarItem=1]="NavBarItem"})(Ap||(Ap={}));(function(e){e[e.InActive=0]="InActive",e[e.Active=1]="Active"})(Cp||(Cp={}));(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"})(Ce||(Ce={}));tM={ShowLabel:"false",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_"},bn={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"})(Se||(Se={}));(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"})(Sp||(Sp={}));(function(e){e.cardSections="cardSections",e.singleComponent="singleComponent",e.default="default",e.expandAvailableSpace="expandAvailableSpace"})(Ep||(Ep={}));rM={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"})(Np||(Np={}));(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"})(Dp||(Dp={}));nM={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"})(yo||(yo={}));(function(e){e.All="All",e.Chart="Chart",e.Grid="Grid"})(Bt||(Bt={}));Ip="tab_related3b554255-7717-4d17-bb7f-9936fb1e75ca",iM="more_tab_",aM="related_tab_",oM="preview_id_navigation_area",sM="tab-section",lM="headerFieldsFlyout",uM="tablist",cM="header_overflowButton",dM="tab",pM="quickCreateRoot",fM={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"})(Dl||(Dl={}));mM="CellCanvasServiceScope"});var Mb={};Rr(Mb,{Attribute:()=>Il,FormElementNode:()=>j});var Il,j,Qe=I(()=>{"use strict";Le();ot();hp();K();Ue();Il=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-${P.NewGuid()}`}getProperty(t){for(let r of this.properties)if(r.key===t)return r.value;return null}getNodeId(){return this.nodeId}getNodeName(){return this.nodeName}setNodeName(t){this.trackObjectPropertyChange("nodeName",t)}get NodeName(){return this.getNodeName()}getAllProperties(){return this.properties}replaceAttributeValue(t,r){this.properties.find(n=>n===t)&&(t.value=r)}replaceObjectPropertyValue(t,r){this[t]=r}getAllChildren(){return this.childrenNodes}getParentNode(){return this.parentNode}visit(t){let r=!1;if(t){r=!!t(this);let n=this.childrenNodes;if(!r&&n)for(let i=0;!r&&i<n.length;i++)r=n[i].visit(t)}return r}findAll(t){let r=[];return t&&this.visit(n=>{t(n)&&r.push(n)}),r}findFirst(t){let r=null;return t&&this.visit(n=>{if(t(n))return r=n,!0}),r}raiseMetadataChange(t){let r=this.getAncestor(v.form);r&&r.raiseMetadataChange(t)}trackPropertyAddition(t,r){this.trackPropertyCollectionChange(()=>{this.properties.push(new Il(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 jn(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 jn(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 jn(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 Sl(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 jn(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){E.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(E.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:T.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=E.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 v.formCell:let t=this.getAncestor(v.formSection);return t||(t=this.getAncestor(v.formHeader),t)||(t=this.getAncestor(v.formFooter),t)?t:null;case v.formSection:return this.getAncestor(v.formTab);case v.formTab:return this.getAncestor(v.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(v.form);return t?t.changeTracker():null}}});var Ub={};Rr(Ub,{ControlClassId:()=>S,ControlNamePrefixes:()=>_l,getControlDisplayNames:()=>hM});function hM(e){return{[S.AccessPrivilegeControl]:e("controls.controlNames.accessPrivilege"),[S.AccessTeamTablePickerControl]:e("controls.controlNames.accessTeamTablePicker"),[S.ACIControl]:e("controls.controlNames.aci"),[S.ActivitiesContainerControl]:e("controls.controlNames.activitiesContainer"),[S.ActivitiesWallControl]:e("controls.controlNames.activitiesWall"),[S.AppliedFiltersControl]:e("controls.controlNames.appliedFilters"),[S.ArticleContentControl]:e("controls.controlNames.articleContent"),[S.BooleanControl]:e("controls.controlNames.twoOption"),[S.ButtonControl]:e("controls.controlNames.button"),[S.CheckboxControl]:e("controls.controlNames.checkbox"),[S.CompositionLinkControl]:e("controls.controlNames.compositionLink"),[S.ConnectionControl]:e("controls.controlNames.connection"),[S.ConnectionRoleObjectTypeListControl]:e("controls.controlNames.connectionRoleObjectTypeList"),[S.CoverageChoiceControl]:e("controls.controlNames.coverageChoice"),[S.DashboardControl]:e("controls.controlNames.dashboard"),[S.DynamicPropertyListControl]:e("controls.controlNames.dynamicPropertyList"),[S.EditFilterControl]:e("controls.controlNames.editFilter"),[S.ErrorStatusControl]:e("controls.controlNames.errorStatus"),[S.GlobalFilterControl]:e("controls.controlNames.globalFilter"),[S.HiddenInputControl]:e("controls.controlNames.hiddenInput"),[S.KBViewerControl]:e("controls.controlNames.kbViewer"),[S.LabelControl]:e("controls.controlNames.label"),[S.MailMergeLanguagePickerControl]:e("controls.controlNames.mailMergeLanguagePicker"),[S.MapLinkControl]:e("controls.controlNames.mapLink"),[S.OrgInsightsControl]:e("controls.controlNames.orgInsights"),[S.ChoiceLookupControl]:e("controls.controlNames.choiceLookup"),[S.PowerBIControl]:e("controls.controlNames.powerBI"),[S.ProcessControl]:e("controls.controlNames.process"),[S.RelatedInformationControl]:e("controls.controlNames.relatedInformation"),[S.RelationshipRoleChoiceControl]:e("controls.controlNames.relationshipRoleChoice"),[S.ReportControl]:e("controls.controlNames.report"),[S.StreamsControl]:e("controls.controlNames.streams"),[S.WebResourceSilverlightControl]:e("controls.controlNames.webResourceSilverlight"),[S.CurrencyControl]:e("controls.controlNames.currency"),[S.DateTimeControl]:e("controls.controlNames.dateAndTime"),[S.DecimalControl]:e("controls.controlNames.decimal"),[S.DurationControl]:e("controls.controlNames.duration"),[S.EmailAddressControl]:e("controls.controlNames.email"),[S.FileControl]:e("controls.controlNames.file"),[S.FloatingNumberControl]:e("controls.controlNames.floatingNumber"),[S.IframeControl]:e("controls.controlNames.iframe"),[S.ImageControl]:e("controls.controlNames.image"),[S.LookupControl]:e("controls.controlNames.lookup"),[S.MapsControl]:e("controls.controlNames.maps"),[S.PhoneNumberControl]:e("controls.controlNames.phoneNumber"),[S.ChoiceControl]:e("controls.controlNames.choice"),[S.QuickViewControl]:e("controls.controlNames.quickView"),[S.QuickFormControl]:e("controls.controlNames.quickForm"),[S.CustomControl]:e("controls.controlNames.customControl"),[S.SearchWidgetControl]:e("controls.controlNames.searchWidget"),[S.SocialInsightsControl]:e("controls.controlNames.socialInsights"),[S.SubgridControl]:e("controls.controlNames.subgrid"),[S.TextAreaControl]:e("controls.controlNames.textArea"),[S.TextboxControl]:e("controls.controlNames.textBox"),[S.TickerControl]:e("controls.controlNames.ticker"),[S.UrlControl]:e("controls.controlNames.url"),[S.WebResourceHTMLControl]:e("controls.controlNames.webResourceHTML"),[S.WebResourceImageControl]:e("controls.controlNames.webResourceImage"),[S.IntegerControl]:e("controls.controlNames.integer"),[S.TimerControl]:e("controls.controlNames.timer"),[S.TimelineControl]:e("controls.controlNames.timeline"),[S.EmailBodyControl]:e("controls.controlNames.emailBody"),[S.PartyListControl]:e("controls.controlNames.partyList"),[S.TimezoneControl]:e("controls.controlNames.timezone"),[S.LanguageControl]:e("controls.controlNames.language"),[S.ChoiceStatusControl]:e("controls.controlNames.choiceStatus"),[S.ChoicesControl]:e("controls.controlNames.choices"),[S.RegardingControl]:e("controls.controlNames.regarding"),[S.EmailEngagementActionsControl]:e("controls.controlNames.emailEngagementActions"),[S.EmailRecipientActivityControl]:e("controls.controlNames.emailRecipientActivity"),[S.ReferencePanelSearchWidgetControl]:e("controls.controlNames.referencePanelSearchWidget"),[S.ReferencePanelQuickViewControl]:e("controls.controlNames.referencePanelQuickView"),[S.ReferencePanelSubgridControl]:e("controls.controlNames.referencePanelSubgrid"),[S.KBEditorControl]:e("controls.controlNames.KBEditor"),[S.LinkControl]:e("controls.controlNames.link")}}var S,_l,Hn=I(()=>{"use strict";(function(e){e.AccessPrivilegeControl="F93A31B2-99AC-4084-8EC2-D4027C31369A",e.AccessTeamTablePickerControl="3f4e2a56-f102-4b4d-ab9c-f1574ca5bfda",e.ACIControl="C8BFBBEF-6851-4401-A0CC-7450062FE085",e.ActivitiesContainerControl="C72511AB-84E5-4FB7-A543-25B4FC01E83E",e.ActivitiesWallControl="6636847D-B74D-4994-B55A-A6FAF97ECEA2",e.AppliedFiltersControl="9C310A73-A360-42C5-8943-47A06F1B51EA",e.ArticleContentControl="F02EF977-2564-4B9A-B2F0-DF083D8A019B",e.BooleanControl="67FAC785-CD58-4F9F-ABB3-4B7DDC6ED5ED",e.ButtonControl="00AD73DA-BD4D-49C6-88A8-2F4F4CAD4A20",e.CheckboxControl="B0C6723A-8503-4FD7-BB28-C8A06AC933C2",e.CompositionLinkControl="DB1284EF-9FFC-4E99-B382-0CC082FE2364",e.ConnectionControl="3246F906-1F71-45F7-B11F-D7BE0F9D04C9",e.ConnectionRoleObjectTypeListControl="821ACF1A-7E46-4A0C-965D-FE14A57D78C7",e.CoverageChoiceControl="4168A05C-D857-46AF-8457-5BB47EB04EA1",e.DashboardControl="D2561F53-B292-42D9-B222-478E40FFE29F",e.DynamicPropertyListControl="6896F004-B17A-4202-861E-8B7EA2080E0B",e.EditFilterControl="1479835F-F852-4679-B864-C6892A2844C9",e.ErrorStatusControl="F4C16ECA-CA81-4E39-9448-834B8378721E",e.GlobalFilterControl="FFF0E632-9D7B-4F21-BBC1-05D1567AD144",e.HiddenInputControl="5546E6CD-394C-4BEE-94A8-4425E17EF6C6",e.KBViewerControl="A62B6FA9-169E-406C-B1AA-EAB828CB6026",e.LabelControl="39354E4A-5015-4D74-8031-EA9EB73A1322",e.MailMergeLanguagePickerControl="B634828E-C390-444A-AFE6-E07315D9D970",e.MapLinkControl="91DC0675-C8B9-4421-B1E0-261CEBF02BAC",e.OrgInsightsControl="76b9e25e-695e-4fef-ac69-f05cfa96739c",e.ChoiceLookupControl="2305e33a-bad3-4022-9e15-1856cf218333",e.PowerBIControl="8C54228C-1B25-4909-A12A-F2B968BB0D62",e.ProcessControl="06E9F7AF-1F54-4681-8EEC-1E21A1CEB465",e.RelatedInformationControl="163B90A6-EB64-49D2-9DF8-3C84A4F0A0F8",e.RelationshipRoleChoiceControl="5F986642-5961-4D9F-AB5E-643D71E231E9",e.ReportControl="A28F441B-916C-4865-87FD-0C5D53BD59C9",e.StreamsControl="EE9078C8-6946-4E2C-B8F8-35E65F4BE6A8",e.WebResourceSilverlightControl="080677DB-86EC-4544-AC42-F927E74B491F",e.CurrencyControl="533B9E00-756B-4312-95A0-DC888637AC78",e.CustomControl="F9A8A302-114E-466A-B582-6771B2AE0D92",e.DateTimeControl="5B773807-9FB2-42DB-97C3-7A91EFF8ADFF",e.DecimalControl="C3EFE0C3-0EC6-42BE-8349-CBD9079DFD8E",e.DurationControl="AA987274-CE4E-4271-A803-66164311A958",e.EmailAddressControl="ADA2203E-B4CD-49BE-9DDF-234642B43B52",e.EmailBodyControl="6F3FB987-393B-4D2D-859F-9D0F0349B6AD",e.EmailEngagementActionsControl="F454228D-1D25-4319-E12F-D27968BC0234",e.EmailRecipientActivityControl="26E9760F-7454-40DE-BB07-F6DCCCB82040",e.FileControl="0A7FF475-B016-4687-9CE5-042BFDBD6519",e.FloatingNumberControl="0D2C745A-E5A8-4C8F-BA63-C6D3BB604660",e.IframeControl="FD2A7985-3187-444E-908D-6624B21F69C0",e.ImageControl="7E548B0D-209C-477B-9DCD-F0F44472381D",e.LanguageControl="671A9387-CA5A-4D1E-8AB7-06E39DDCF6B5",e.LookupControl="270BD3DB-D9AF-4782-9025-509E298DEC0A",e.MapsControl="62B0DF79-0464-470F-8AF7-4483CFEA0C7D",e.ChoicesControl="4AA28AB7-9C13-4F57-A73D-AD894D048B5F",e.IntegerControl="C6D124CA-7EDA-4A60-AEA9-7FB8D318B68F",e.PartyListControl="CBFB742C-14E7-4A17-96BB-1A13F7F64AA2",e.PhoneNumberControl="8C10015A-B339-4982-9474-A95FE05631A5",e.ChoiceControl="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE",e.ChoiceStatusControl="5D68B988-0661-4DB2-BC3E-17598AD3BE6C",e.QuickViewControl="5C5600E0-1D6E-4205-A272-BE80DA87FD42",e.QuickFormControl="69AF7DCA-2E3B-4EE7-9201-0DA731DD2413",e.RegardingControl="F3015350-44A2-4AA0-97B5-00166532B5E9",e.SearchWidgetControl="E616A57F-20E0-4534-8662-A101B5DDF4E0",e.SocialInsightsControl="86B9E25E-695E-4FEF-AC69-F05CFA96739C",e.SubgridControl="E7A81278-8635-4D9E-8D4D-59480B391C5B",e.TextAreaControl="E0DECE4B-6FC8-4A8F-A065-082708572369",e.TextboxControl="4273EDBD-AC1D-40D3-9FB2-095C621B552D",e.TickerControl="1E1FC551-F7A8-43AF-AC34-A8DC35C7B6D4",e.TimerControl="9C5CA0A1-AB4D-4781-BE7E-8DFBE867B87E",e.TimelineControl="06375649-C143-495E-A496-C962E5B4488E",e.TimezoneControl="7C624A0B-F59E-493D-9583-638D34759266",e.UrlControl="71716B6C-711E-476C-8AB8-5D11542BFB47",e.WebResourceHTMLControl="9FDF5F91-88B1-47F4-AD53-C11EFC01A01D",e.WebResourceImageControl="587CDF98-C1D5-4BDE-8473-14A0BC7644A7",e.ReferencePanelSearchWidgetControl="7CCD1494-1F7A-4E3A-8BDE-F32069DAEB9F",e.ReferencePanelSubgridControl="02D4264B-47E2-4B4C-AA95-F439F3F4D458",e.ReferencePanelQuickViewControl="B68B05F0-A46D-43F8-843B-917920AF806A",e.KBEditorControl="F94DB24F-263D-44A7-B38E-A35E9854812B",e.LinkControl="DFDF1CDE-837B-4AC9-98CF-AC74361FD89D"})(S||(S={}));_l={[S.WebResourceHTMLControl]:"WebResource",[S.WebResourceImageControl]:"WebResource",[S.IframeControl]:"IFRAME",[S.SearchWidgetControl]:"Search widget",[S.SubgridControl]:"Subgrid",[S.TimelineControl]:"Timeline",[S.QuickViewControl]:"QuickviewControl"}});var Qn=g((zj,$b)=>{var bo=new Proxy(function(){return bo},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:bo},apply:function(){return bo},construct:function(){return{}}}),Bb=function(){return bo};Object.setPrototypeOf(Bb,bo);$b.exports=Bb});var pt,zr,qb,Vb,$i=I(()=>{"use strict";pt="cds-designer-models",zr="FormCustomControl",qb="FormCell",Vb="Form"});var qi,ft,wo=I(()=>{"use strict";qi=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}},ft=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 Jn,_p=I(()=>{"use strict";wo();K();Jn=class e{static lockedFieldCount=new ft;static dependencyFieldCount=new ft;static getNecessaryLookUpTable(t){switch(t){case yr.DependencyFieldTable:return e.dependencyFieldCount;case yr.LockedFieldTable:return e.lockedFieldCount}}static initCanvasLockedFieldLookUp(t){switch(t){case yr.DependencyFieldTable:e.dependencyFieldCount=new ft;case yr.LockedFieldTable:e.lockedFieldCount=new ft}}}});var Pl,Gb=I(()=>{"use strict";Ue();Le();K();Qe();Pl=class extends j{constructor(t){super(v.controlDescription,t)}get forControl(){let t=this.getProperty(m.ForControl);return E.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new P(t))}set forControl(t){this.setProperty(m.ForControl,`{${t.ToString()}}`)}get customControls(){return this.getChildren(v.customControl)}set customControls(t){this.deleteAllChildren();for(let r of t)this.addChild(r)}get DefaultControlClassId(){for(let t of this.customControls)if(!E.IsNullOrUndefined(t.id))return t.id;return null}get DefaultCustomControl(){for(let t of this.customControls)if(!E.IsNullOrUndefined(t.id))return t;return null}get DefaultCustomControls(){let t=[];for(let r of this.customControls)E.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 Wb,jb,mt,_,zb,wn,Xn,Vi,Pp,Tp,Gi=I(()=>{"use strict";Wb={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"},jb={GroupDefinition:"GroupDefinition"},mt={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"})(_||(_={}));(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"})(zb||(zb={}));(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"})(Xn||(Xn={}));(function(e){e[e.Bound=0]="Bound",e[e.Input=1]="Input",e[e.Output=2]="Output"})(Vi||(Vi={}));Pp=[_.LookupCustomer,_.LookupOwner,_.LookupPartyList,_.LookupRegarding,_.LookupSimple],Tp=[_.WholeNone,_.WholeDuration,_.WholeLanguage,_.WholeTimeZone,_.FP,_.Decimal]});function Wr(){return br||(br=window._makerConfig,br&&window?.location?.search?.indexOf("useProductionConfig")>-1&&(br={...br,region:"prod",graphQLEndpoint:"https://graph.make.powerapps.com/"}),br?.region==="prod"&&(br={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/"}}},...br}),br||{aadClientId:"a8f7a65c-f5ba-4859-b2d6-df772c264e9d",location:"cus",region:"test",publicPath:"/",graphQLEndpoint:"https://graph.make.test.powerapps.com/"})}var br,Tl=I(()=>{"use strict";});function Hb(e,t,r){if(!e)return Ol.has(e)||(window._ppux?.log?.("PPUX/Geo/NonExistent",{eventType:"Trace",team:"Shell",severity:"Error",errorCode:"GeoIsEmpty"}),Ol.add("")),!1;if(e){if(e=e.toLowerCase(),Ol.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}}),Ol.add(e),!1}return!0}function gM(e){return Hb(e,Op,"Location dictionary")?Op[e.toLowerCase()]:"us"}function vM(){let e=Wr().location.toLowerCase();return Hb(e,Op,"Current location dictionary")?e:"us"}var Ol,Op,aH,Qb=I(()=>{"use strict";Tl();Ol=new Set,Op={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"};aH=gM(vM())});var L,sH,Jb=I(()=>{"use strict";L={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"},sH={[L.USWest]:{geoName:"us",regionShortName:"wus"},[L.USCentral]:{geoName:"us",regionShortName:"cus"},[L.USEast]:{geoName:"us",regionShortName:"eus"},[L.USEast2]:{geoName:"us",regionShortName:"eus2"},[L.USWestCentral]:{geoName:"us",regionShortName:"wcus"},[L.USWest2]:{geoName:"us",regionShortName:"wus2"},[L.USSouthCentral]:{geoName:"br",regionShortName:"scus"},[L.BrazilSouth]:{geoName:"br",regionShortName:"sbr"},[L.UKSouth]:{geoName:"uk",regionShortName:"suk"},[L.UKWest]:{geoName:"uk",regionShortName:"wuk"},[L.JapanEast]:{geoName:"jp",regionShortName:"ejp"},[L.JapanWest]:{geoName:"jp",regionShortName:"wjp"},[L.IndiaCentral]:{geoName:"in",regionShortName:"cin"},[L.IndiaSouth]:{geoName:"in",regionShortName:"sin"},[L.ItalyNorth]:{geoName:"it",regionShortName:"nit"},[L.GermanyWestCentral]:{geoName:"de",regionShortName:"wcde"},[L.GermanyNorth]:{geoName:"de",regionShortName:"nde"},[L.EuropeNorth]:{geoName:"eu",regionShortName:"neu"},[L.EuropeWest]:{geoName:"eu",regionShortName:"weu"},[L.AustraliaEast]:{geoName:"au",regionShortName:"eau"},[L.AustraliaSouthEast]:{geoName:"au",regionShortName:"seau"},[L.AsiaSouthEast]:{geoName:"as",regionShortName:"seas"},[L.AsiaEast]:{geoName:"as",regionShortName:"eas"},[L.CanadaCentral]:{geoName:"ca",regionShortName:"cca"},[L.CanadaEast]:{geoName:"ca",regionShortName:"eca"},[L.SouthAfricaNorth]:{geoName:"za",regionShortName:"nza"},[L.SouthAfricaWest]:{geoName:"za",regionShortName:"wza"},[L.FranceCentral]:{geoName:"fr",regionShortName:"cfr"},[L.FranceSouth]:{geoName:"fr",regionShortName:"sfr"},[L.UAENorth]:{geoName:"ae",regionShortName:"nae"},[L.UAECentral]:{geoName:"ae",regionShortName:"cae"},[L.SwedenCentral]:{geoName:"se",regionShortName:"cse"},[L.SwitzerlandNorth]:{geoName:"ch",regionShortName:"nch"},[L.SwitzerlandWest]:{geoName:"ch",regionShortName:"wch"},[L.NorwayEast]:{geoName:"no",regionShortName:"eno"},[L.NorwayWest]:{geoName:"no",regionShortName:"wno"},[L.KoreaCentral]:{geoName:"kr",regionShortName:"ckr"},[L.KoreaSouth]:{geoName:"kr",regionShortName:"skr"},[L.SingaporeSouthEast]:{geoName:"sg",regionShortName:"seas"},[L.PolandCentral]:{geoName:"pl",regionShortName:"cpl"},[L.QatarCentral]:{geoName:"qa",regionShortName:"cqa"},[L.NewZealandNorth]:{geoName:"nz",regionShortName:"nnz"},[L.GovernmentUSTexas]:{geoName:"us",regionShortName:"ugtx"},[L.GovernmentUSVirginia]:{geoName:"us",regionShortName:"ugva"},[L.GovernmentUSDodCentral]:{regionShortName:"udc"},[L.GovernmentUSDodEast]:{regionShortName:"ude"},[L.ChinaEast]:{regionShortName:"cne"},[L.ChinaEast2]:{regionShortName:"cne2"},[L.ChinaEast3]:{regionShortName:"cne3"},[L.ChinaNorth]:{regionShortName:"cnn"},[L.ChinaNorth2]:{regionShortName:"cnn2"},[L.ChinaNorth3]:{regionShortName:"cnn3"},[L.UssecEast]:{geoName:"us",regionShortName:"erx"},[L.UssecWest]:{geoName:"us",regionShortName:"wrx"},[L.UsnatEast]:{geoName:"us",regionShortName:"eex"},[L.UsnatWest]:{geoName:"us",regionShortName:"wex"}}});var Xb=I(()=>{"use strict";Tl();});var Ao=I(()=>{"use strict";Tl();Qb();Jb();Xb();});function Co(e,t){return Kb?Kb.isOverridden(e,t):{overridden:!1}}var Kb,So=I(()=>{"use strict";});var Rp=I(()=>{"use strict";Ao();So();});function yM(e,t){let{region:r}=Wr();return()=>{let n=e.settings[t];if(n.allowOverrides){let s=Co(e.packageName,t);if(s.overridden)return typeof s.value=="string"?bM(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 bM(e){return isNaN(Number(e))?e==="true"?!0:e==="false"?!1:e:Number(e)}function wM(e){let t=e.packageName;if(Rl.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=>xp(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=>!xl(i))){let i=`error parsing settings config for package ${t}, setting ${r} has invalid region`;throw console.error(i),new Error(i)}})}function Eo(e){wM(e);let t={};return Object.keys(e.settings).forEach(r=>{t[r]={enumerable:!0,get:yM(e,r)}}),Rl.set(e.packageName,e),Object.defineProperties({},t)}function Fp(e,t){return Rl.has(e)?!!Rl.get(e).settings[t]:!1}var Rl,Fl=I(()=>{"use strict";Ao();So();Lp();No();Rl=new Map});function Yb(e,t){let{region:r}=Wr();return()=>{let n=Co(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 AM(e){let t=e.packageName;if(Ll.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=>Fp(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=>!xl(i))){let i=`error parsing feature gates config for package ${t}, feature ${r} has invalid region`;throw console.error(i),new Error(i)}})}function kp(e){AM(e);let t={};Object.keys(e.features).forEach(i=>{t[i]={enumerable:!0,configurable:!0,get:Yb(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:Yb(e,a.toString())}}),Object.defineProperties(r,i),n.clear()}},Ll.set(e.packageName,e),Object.defineProperties(r,t)}function xp(e,t){return Ll.has(e)?!!Ll.get(e).features[t]:!1}var Ll,Lp=I(()=>{"use strict";Ao();No();So();Fl();Ll=new Map});var ew=g((RH,Zb)=>{"use strict";Zb.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 nw=g(Mp=>{"use strict";var CM=Object.prototype.hasOwnProperty,SM;function tw(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch{return null}}function rw(e){try{return encodeURIComponent(e)}catch{return null}}function EM(e){for(var t=/([^=?#&]+)=?([^&]*)/g,r={},n;n=t.exec(e);){var i=tw(n[1]),a=tw(n[2]);i===null||a===null||i in r||(r[i]=a)}return r}function NM(e,t){t=t||"";var r=[],n,i;typeof t!="string"&&(t="?");for(i in e)if(CM.call(e,i)){if(n=e[i],!n&&(n===null||n===SM||isNaN(n))&&(n=""),i=rw(i),n=rw(n),i===null||n===null)continue;r.push(i+"="+n)}return r.length?t+r.join("&"):""}Mp.stringify=NM;Mp.parse=EM});var $p=g((xH,uw)=>{"use strict";var aw=ew(),kl=nw(),ow=/[\n\r\t]/g,DM=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,IM=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,_M=/^[a-zA-Z]:/,PM=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;function Bp(e){return(e||"").toString().replace(PM,"")}var Up=[["#","hash"],["?","query"],function(t,r){return wr(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]],iw={hash:1,query:1};function sw(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 Ar(unescape(e.pathname),{});else if(i==="string"){n=new Ar(e,{});for(a in iw)delete n[a]}else if(i==="object"){for(a in e)a in iw||(n[a]=e[a]);n.slashes===void 0&&(n.slashes=DM.test(e.href))}return n}function wr(e){return e==="file:"||e==="ftp:"||e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function lw(e,t){e=Bp(e),e=e.replace(ow,""),t=t||{};var r=IM.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)):wr(n)?s=r[4]:n?i&&(s=s.slice(2)):o>=2&&wr(t.protocol)&&(s=r[4]),{protocol:n,slashes:i||wr(n),slashesCount:o,rest:s}}function TM(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 Ar(e,t,r){if(e=Bp(e),e=e.replace(ow,""),!(this instanceof Ar))return new Ar(e,t,r);var n,i,a,o,s,l,u=Up.slice(),c=typeof t,d=this,p=0;for(c!=="object"&&c!=="string"&&(r=t,t=null),r&&typeof r!="function"&&(r=kl.parse),t=sw(t),i=lw(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||_M.test(e))||!i.slashes&&(i.protocol||i.slashesCount<2||!wr(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=TM(d.pathname,t.pathname)),d.pathname.charAt(0)!=="/"&&wr(d.protocol)&&(d.pathname="/"+d.pathname),aw(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:"&&wr(d.protocol)&&d.host?d.protocol+"//"+d.host:"null",d.href=d.toString()}function OM(e,t,r){var n=this;switch(e){case"query":typeof t=="string"&&t.length&&(t=(r||kl.parse)(t)),n[e]=t;break;case"port":n[e]=t,aw(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<Up.length;o++){var s=Up[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:"&&wr(n.protocol)&&n.host?n.protocol+"//"+n.host:"null",n.href=n.toString(),n}function RM(e){(!e||typeof e!="function")&&(e=kl.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||wr(r.protocol)?"//":"");return r.username?(a+=r.username,r.password&&(a+=":"+r.password),a+="@"):r.password?(a+=":"+r.password,a+="@"):r.protocol!=="file:"&&wr(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}Ar.prototype={set:OM,toString:RM};Ar.extractProtocol=lw;Ar.location=sw;Ar.trimLeft=Bp;Ar.qs=kl;uw.exports=Ar});var FM,cw=I(()=>{"use strict";FM=se($p());});function qp(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 Ml=I(()=>{"use strict";});var Vp,Gp,zp=I(()=>{"use strict";Ml();Vp=class{features=new Map;register(t,r){let n=qp(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()}},Gp=new Vp});var Wp=I(()=>{"use strict";});function xl(e){return xM.has(e)}var xM,No=I(()=>{"use strict";Rp();Lp();Fl();So();Rp();cw();zp();Ml();Wp();xM=new Set(["tie","test","prod","preview","preprod","gov","high","dod","mooncake","ex","rx"])});var LM,dw=I(()=>{"use strict";No();LM=Eo({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 Ul,O,k,Kn,zi,Bl,pw,fw,jp,Do=I(()=>{"use strict";wo();Ul=class{name;constructor(t){this.name=t}toString(){return this.name}getName(){return this.name}getDisplayNameResourceKey(){return jp.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"})(O||(O={}));(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"})(k||(k={}));Kn=class extends Ul{constructor(t){super(t)}static get None(){return"None"}static get SystemRequired(){return"SystemRequired"}static get ApplicationRequired(){return"ApplicationRequired"}static get Recommended(){return"Recommended"}},zi=class e extends Ul{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?Bl.Persistent:parseInt(Bl[this.name])}};(function(e){e[e.Persistent=0]="Persistent",e[e.Calculated=1]="Calculated",e[e.Rollup=2]="Rollup"})(Bl||(Bl={}));(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"})(pw||(pw={}));(function(e){e[e.Attribute=0]="Attribute",e[e.Organization=1]="Organization",e[e.Currency=2]="Currency"})(fw||(fw={}));jp=class e{static resourceKeyMap=e.initResourceKeyMap();static initResourceKeyMap(){let t=new qi;return t.add(O.TwoOptions,"SystemCustomization.type.bit.label"),t.add(O.Customer,"SystemCustomization.type.customer.label"),t.add(O.CustomerType,"SystemCustomization.type.customer.label"),t.add(O.DateTime,"SystemCustomization.type.datetime.label"),t.add(O.DecimalNumber,"SystemCustomization.type.decimal.label"),t.add(O.FloatingPointNumber,"SystemCustomization.type.float.label"),t.add(O.WholeNumber,"SystemCustomization.type.int.label"),t.add(O.LookupType,"SystemCustomization.type.lookup.label"),t.add(O.Lookup,"SystemCustomization.type.lookup.label"),t.add(O.MultipleLineofText,"SystemCustomization.type.ntext.label"),t.add(O.Currency,"SystemCustomization.type.money.label"),t.add(O.Owner,"SystemCustomization.type.owner.label"),t.add(O.OwnerType,"SystemCustomization.type.owner.label"),t.add(O.PartyList,"SystemCustomization.type.partylist.label"),t.add(O.PartyListType,"SystemCustomization.type.partylist.label"),t.add(O.OptionSet,"SystemCustomization.type.picklist.label"),t.add(O.State,"SystemCustomization.type.state.label"),t.add(O.Status,"SystemCustomization.type.status.label"),t.add(O.SingleLineofText,"SystemCustomization.type.nvarchar.label"),t.add(O.UniqueIdentifier,"SystemCustomization.type.uniqueidentifier.label"),t.add(O.UniqueIdentifierType,"SystemCustomization.type.uniqueidentifiertype.label"),t.add(O.CalendarRulesType,"SystemCustomization.type.calendarrules.label"),t.add(O.VirtualType,"SystemCustomization.type.virtual.label"),t.add(O.BigInt,"SystemCustomization.type.bigint.label"),t.add(O.ManagedPropertyType,"SystemCustomization.type.managedproperty.label"),t.add(O.EntityNameType,"SystemCustomization.type.entityname.label"),t.add(O.Image,"SystemCustomization.type.image.label"),t.add(O.MultiSelectOptionSet,"SystemCustomization.type.multiselectpicklist.label"),t.add(O.PrimaryNameAttributeType,"SystemCustomization.type.primaryname.label"),t.add(O.LookupType,"SystemCustomization.type.lookuptype.label"),t.add(O.Subject,"SystemCustomization.type.subject.label"),t.add(k.Email,"SystemCustomization.String.Format.email"),t.add(k.Text,"SystemCustomization.String.Format.text"),t.add(k.TextArea,"SystemCustomization.String.Format.textarea"),t.add(k.Url,"SystemCustomization.String.Format.url"),t.add(k.TickerSymbol,"SystemCustomization.String.Format.tickersymbol"),t.add(k.PhoneticGuide,"SystemCustomization.String.Format.phoneticguide"),t.add(k.VersionNumber,"SystemCustomization.String.Format.versionnumber"),t.add(k.Phone,"SystemCustomization.String.Format.phone"),t.add(k.None,"SystemCustomization.Integer.Format."),t.add(k.Duration,"SystemCustomization.Integer.Format.duration"),t.add(k.TimeZone,"SystemCustomization.Integer.Format.timezone"),t.add(k.Language,"SystemCustomization.Integer.Format.language"),t.add(k.Locale,"SystemCustomization.Integer.Format.language"),t.add(k.DateOnly,"SystemCustomization.DateTime.Format.date"),t.add(k.DateAndTime,"SystemCustomization.DateTime.Format.datetime"),t.add(k.Regarding,"SystemCustomization.Lookup.Format.regarding"),t.add(zi.Persistent,"SystemCustomization.String.Source.persistent"),t.add(zi.Calculated,"SystemCustomization.String.Source.calculated"),t.add(zi.Rollup,"SystemCustomization.String.Source.rollup"),t.add(zi.None,"SystemCustomization.String.Source.none"),t}static getDisplayNameResourceKey(t){return e.resourceKeyMap.getValue(t)}}});var vw,Qp,Wi,Yn,Hp,$l,ji,jr,we,mw,hw,gw,rr=I(()=>{"use strict";vw={ThreeEqColumn_FirstColumn:34,ThreeEqColumn_SecondColumn:33,ThreeEqColumn_ThirdColumn:33,FiveEqColumn:20},Qp={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"})(Wi||(Wi={}));(function(e){e.Left="Left",e.Right="Right",e.Center="Center"})(Yn||(Yn={}));(function(e){e[e.Mobile=0]="Mobile",e[e.Tablet=1]="Tablet",e[e.Web=2]="Web"})(Hp||(Hp={}));$l=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"})(ji||(ji={}));jr=class{static StartTag="<"},we={ShowLabel:"true",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_",labelAlignment:Yn.Left,labelPosition:ji.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"})(mw||(mw={}));(function(e){e.TabWithLockedFieldRemoval="TabWithLockedFieldRemoval",e.SectionWithLockedFieldRemoval="SectionWithLockedFieldRemoval",e.LockedSectionRemoval="LockedSectionRemoval",e.LockedFieldRemoval="LockedFieldRemoval",e.RequiredFieldRemoval="RequiredFieldRemoval",e.LastRemainingTab="LastRemainingTab",e.UnknownRemoval="UnknownRemoval"})(hw||(hw={}));(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"})(gw||(gw={}))});var Jp,yw=I(()=>{"use strict";(function(e){e.DefaultValue="defaultValue",e.Loaded="loaded"})(Jp||(Jp={}))});var Aw,kM,bw,RQ,FQ,Io,ww,xQ,LQ,Cw=I(()=>{"use strict";Aw=se(Qn());Le();$i();dw();Do();rr();Gi();K();kM=se(Mn());yw();(function(e){e.Model="Model",e.Canvas="Canvas",e.CustomPages="CustomPages"})(bw||(bw={}));RQ={Read:Xn.Read,Edit:Xn.Edit,Both:Xn.Both,Container:Xn.Container},FQ={input:Vi.Input,bound:Vi.Bound,output:Vi.Output};(function(e){e[e.dataset=0]="dataset",e[e.property=1]="property",e[e.groups=2]="groups",e[e.group=3]="group"})(Io||(Io={}));(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"})(ww||(ww={}));xQ=new Set([_.Currency,_.Decimal,_.FP,_.Multiple,_.SingleLineEmail,_.SingleLinePhone,_.SingleLineText,_.SingleLineTextArea,_.SingleLineURL,_.SingleLineTickerSymbol,_.WholeNone,_.WholeDuration,_.WholeLanguage,_.WholeTimeZone,_.Enum,_.LookupSimple,_.LookupCustomer,_.LookupOwner,_.LookupPartyList,_.LookupRegarding,_.TwoOptions,_.Boolean,_.PowerBIReport,_.DateAndTimeDateAndTime,_.DateAndTimeDateOnly,_.OptionSet,_.MultiSelectOptionSet,_.CardForm]),LQ={numbers:[_.WholeNone,_.FP,_.Decimal,_.Currency],text:[_.SingleLineText,_.SingleLineTextArea,_.Multiple],lookup:[_.LookupSimple,_.LookupCustomer,_.LookupOwner,_.LookupPartyList,_.LookupRegarding],dates:[_.DateAndTimeDateOnly,_.DateAndTimeDateAndTime],allFields:[_.TwoOptions,_.DateAndTimeDateOnly,_.DateAndTimeDateAndTime,_.FP,_.Decimal,_.WholeNone,_.WholeDuration,_.WholeTimeZone,_.WholeLanguage,_.LookupSimple,_.LookupCustomer,_.LookupOwner,_.LookupPartyList,_.LookupRegarding,_.Multiple,_.OptionSet,_.SingleLineText,_.SingleLineTextArea,_.SingleLineEmail,_.SingleLineURL,_.SingleLineTickerSymbol,_.SingleLinePhone]}});var nr,ql,Sw=I(()=>{"use strict";nr=se(Qn());Ue();Le();ot();$i();Gi();Cw();Do();K();Qe();rr();ql=class extends j{constructor(t){super(v.customControl,t)}customControlId;get id(){let t=this.getProperty(m.id);return E.IsNullOrUndefined(t)?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new P(t.substr(1,t.length-2)):new P(t)}getParameters(){let t=new Map,r=this.getAllChildren();if(r&&r.length!==0&&r[0]){let n=r[0].getAllChildren();if(n!=null){for(let i of n)if(i&&i.getAllChildren().length>0){let a=i.getNodeName();t.get(a)?t.get(a).push(i):t.set(a,[i])}}}return t}getFormComponentValueByParameterName(t){let r=this.getParameters()?.get(mt.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===mt.name)?.value}getParameterChildrenValues(t,r,n){if(this.isDataSet(t)){let i=r.find(u=>u.key===mt.name)?.value,a={Name:i,Type:_.Grid,Columns:[]},l=this.getParameters().get(mt.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===m.static&&a.value==="true"){r=!0;break}}return r}get name(){return this.getProperty(m.Name)}get formFactor(){return this.getProperty(m.formFactor)}set formFactor(t){this.setProperty(m.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(jr.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:jb.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===Io.dataset?a.get(mt.dataset)?.some(f=>this.getDatasetName(f)===d)||r.push({Name:d,Value:{Name:d,Columns:[],Type:_.Grid}}):c.propertyType===Io.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,nr.trackInfoTrace)(pt,{eventName:`${zr}/parametersToJSON`,eventData:{message:`Configuration metadata for custom control parameter ${o} is not available for custom control : ${this.name}.`}}),r=[];break}}}else(0,nr.trackErrorTrace)(pt,{eventName:`${zr}/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,nr.trackErrorTrace)(pt,{eventName:`${zr}/parametersToJSON`,eventData:{message:"Custom Control Manifest not found"}},new Error(`No custom control manifest found for ${this.name}`))}catch(n){(0,nr.trackErrorTrace)(pt,{eventName:`${zr}/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===mt.name)?.value;if(a)return this.getParameterChildrenValues(t,r);{let s=new Error(`No dataset manifest info for ${o}`);(0,nr.trackErrorTrace)(pt,{eventName:`${zr}/parameterJSON`,eventData:{message:"Missing custom control manifest dataset info"}},s)}}else{let a=n,o=r&&r.find(l=>l.key===m.Type),s=a&&!a.ofTypeGroup.every(l=>!Pp.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(m.bindAttribute),p=await i.formModelService.loadLookupModel(d),f=p.lookupColumn,h=this.getLookupDataTypeFromAttributeMetadata(f);return{Name:t,Type:h,Usage:l,Static:u,Primary:c,EntityName:p.primaryTableName,Value:d,ViewId:this.getFormComponentValueByParameterName(Wb.DefaultViewId),TargetEntityType:f.targets[0],FilterRelationshipName:this.getFormComponentValueByParameterName(m.FilterRelationshipName),AvailableViewIds:this.getFormComponentValueByParameterName(m.AvailableViewIds),DependentAttributeName:this.getFormComponentValueByParameterName(m.DependentAttributeName),DependentAttributeType:this.getFormComponentValueByParameterName(m.DependentAttributeType),AllowFilterOff:T.IsStrictTrue(this.getFormComponentValueByParameterName(m.AllowFilterOff)),DisableQuickFind:T.IsStrictTrue(this.getFormComponentValueByParameterName(m.DisableQuickFind)),EnableViewPicker:!T.IsStrictTrue(this.getFormComponentValueByParameterName(m.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,nr.trackErrorTrace)(pt,{eventName:`${zr}/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,nr.trackErrorTrace)(pt,{eventName:`${zr}/parameterJSON`,eventData:{message:"Missing property type info"}},p)}else{let l=new Error(`No property manifest info for ${t}`);(0,nr.trackWarningTrace)(pt,{eventName:`${zr}/parameterJSON`,eventData:{message:"Missing custom control manifest property info"}},l)}}return null}getLookupDataTypeFromAttributeMetadata(t){let{attributeType:r,format:n}=t;switch(r){case O.Customer:return _.LookupCustomer;case O.Owner:return _.LookupOwner;case O.PartyList:return _.LookupPartyList;default:return n===k.Regarding?_.LookupRegarding:_.LookupSimple}}isLookupType(t){return Pp.includes(t)}isNumberTypeProperty(t,r){return Tp.includes(r)||t.ofTypeGroup.some(n=>Tp.includes(n))}isDataSet(t){return mt.dataset===t}isGroups(t){return!!t[0].getAllProperties().find(n=>n.key==="isGroup"&&n.value==="true")}}});var q,Xp=I(()=>{"use strict";q=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 R,Hi,$e,Vl=I(()=>{"use strict";Ue();wo();Le();ot();Do();Hn();Xp();rr();R=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"}},Hi=class{static get RelationshipAssistant(){return"3ff9a528-dd50-4aca-8f10-2e5ed73513ad"}static get PredictiveLeadScoring(){return"6f503f2a-d033-4106-b62c-f8f2e5f01a57"}},$e=class e{static FieldControlIds=e.initializeFieldControls();static UnboundControlIds=e.initializeUnboundControls();static ControlsAllowedForReferencePanel=e.initializeReferencePanelControls();static ControlsAllowedForFooter=e.initializeFooterControls();static CustomControlIdMap=new ft;static initializeFieldControls(){let t=new ft,r=e.getControlName(O.SingleLineofText,k.Phone);t.add(r,new P(R.PhoneNumberControl));let n=e.getControlName(O.SingleLineofText,k.TextArea);t.add(n,new P(R.TextAreaControl));let i=e.getControlName(O.SingleLineofText,k.Text);t.add(i,new P(R.TextBoxControl));let a=e.getControlName(O.SingleLineofText,k.Email);t.add(a,new P(R.EmailAddressControl));let o=e.getControlName(O.SingleLineofText,k.Url);t.add(o,new P(R.UrlControl));let s=e.getControlName(O.SingleLineofText,k.TickerSymbol);t.add(s,new P(R.TickerControl));let l=e.getControlName(O.SingleLineofText,k.PhoneticGuide);t.add(l,new P(R.TextBoxControl));let u=e.getControlName(O.WholeNumber,k.Duration);t.add(u,new P(R.DurationControl));let c=e.getControlName(O.WholeNumber,k.Language);t.add(c,new P(R.LanguagePickerControl));let d=e.getControlName(O.WholeNumber,k.TimeZone);t.add(d,new P(R.TimeZonePicklistControl));let p=e.getControlName(O.WholeNumber,k.None);t.add(p,new P(R.IntegerControl));let f=e.getControlName(O.DateTime,k.DateOnly);t.add(f,new P(R.DateTimeControl));let h=e.getControlName(O.DateTime,k.DateAndTime);t.add(h,new P(R.DateTimeControl));let y=e.getControlName(O.LookupType,k.None);t.add(y,new P(R.LookupControl));let w=e.getControlName(O.CustomerType,k.None);t.add(w,new P(R.LookupControl));let N=e.getControlName(O.FloatingPointNumber,k.None);t.add(N,new P(R.FloatControl));let D=e.getControlName(O.DecimalNumber,k.None);t.add(D,new P(R.DecimalControl));let x=e.getControlName(O.Currency,k.None);t.add(x,new P(R.MoneyControl));let F=e.getControlName(O.MultipleLineofText,k.None);t.add(F,new P(R.TextAreaControl));let X=e.getControlName(O.MultipleLineofText,k.Text);t.add(X,new P(R.TextAreaControl));let V=e.getControlName(O.MultipleLineofText,k.TextArea);t.add(V,new P(R.TextAreaControl));let M=e.getControlName(O.MultipleLineofText,k.Email);t.add(M,new P(R.EmailBodyControl));let U=e.getControlName(O.OptionSet,k.None);t.add(U,new P(R.PicklistControl));let B=e.getControlName(O.TwoOptions,k.None);t.add(B,new P(R.RadioControl));let z=e.getControlName(O.Image,k.None);t.add(z,new P(R.WebResourceImageControl));let $=e.getControlName(O.Image,k.None);t.add($,new P(R.WebResourceHtmlControl));let Ee=e.getControlName(O.TwoOptions,"Radio");t.add(Ee,new P(R.RadioControl));let ye=e.getControlName(O.TwoOptions,"CheckBox");t.add(ye,new P(R.CheckBoxControl));let Ge=e.getControlName(O.TwoOptions,"List");t.add(Ge,new P(R.PicklistControl));let Ze=e.getControlName(O.State,k.None);t.add(Ze,new P(R.PicklistControl));let pe=e.getControlName(O.Status,k.None);t.add(pe,new P(R.PicklistStatusControl));let vt=e.getControlName(O.OwnerType,k.None);t.add(vt,new P(R.LookupControl));let lc=e.getControlName(O.PartyListType,k.None);t.add(lc,new P(R.PartyListControl));let fP=e.getControlName(O.LookupType,k.Regarding);t.add(fP,new P(R.RegardingControl));let mP=e.getControlName(O.MultiSelectOptionSet,k.None);return t.add(mP,new P(R.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(!E.IsNullOrEmptyGuid(t)){let r=e.getTypeAndFormatByControlOrUniqueId(t.guidString.toLowerCase());return r=E.IsNullOrUndefined(r)?e.getUnboundControlNameFromIdentifier(t):r.substring(0,r.indexOf("_")),r}return null}static isCustomControl(t){return E.IsNullOrUndefined(t.control)||E.IsNullOrUndefined(t.control.ClassId)||t.control.ClassId.guidString===R.CustomControl}static initializeUnboundControls(){let t=new ft;return t.add(R.ACIControl,q.ACIControl),t.add(R.IframeControl,q.IframeControl),t.add(R.SearchWidgetControl,q.SearchWidgetControl),t.add(R.MapsControl,q.MapsControl),t.add(R.QuickFormCollectionControl,q.QuickFormCollectionControl),t.add(R.GridControl,q.SubGridControl),t.add(R.WebResourceImageControl,q.WebResourceImageControl),t.add(R.WebResourceHtmlControl,q.WebResourceHtmlControl),t.add(R.ReferencePanelSearchWidget,q.SearchWidgetControl),t.add(R.ReferencePanelQuickFormCollectionControl,q.QuickFormCollectionControl),t.add(R.ReferencePanelSubgridControl,q.SubGridControl),t.add(R.TimerControl,q.TimerControl),t.add(R.TimeLineControl,q.NotesControl),t.add(R.TimeLineControlUC,q.NotesControl),t.add(R.SocialInsightControl,q.SocialInsightControl),t.add(Hi.RelationshipAssistant,q.CustomControl),t}static initializeReferencePanelControls(){let t=new ft;return t.add(R.IframeControl,q.IframeControl),t.add(R.ReferencePanelSearchWidget,q.SearchWidgetControl),t.add(R.ReferencePanelQuickFormCollectionControl,q.QuickFormCollectionControl),t.add(R.ReferencePanelSubgridControl,q.SubGridControl),t.add(R.WebResourceHtmlControl,q.WebResourceHtmlControl),t.add(R.WebResourceImageControl,q.WebResourceHtmlControl),t}static initializeFooterControls(){let t=new qi;return t.add(Wi.IFRAME,!0),t.add(Wi.SPACER,!0),t.add(Wi.WEB_RESOURCE_HTML,!0),t}static isUnboundFormControl(t){if(E.IsNullOrUndefined(t)||E.IsNullOrUndefined(t.control)||E.IsNullOrUndefined(t.control.ClassId))return!1;let r=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.containsKey(r.guidString)}static isReferencePanelSection(t){return!E.IsNullOrUndefined(t)&&!E.IsNullOrUndefined(t.Name)&&t.Name.indexOf(we.referencePanelNamePrefix)===0}static isUnboundFormControlByIdentifier(t){return E.IsNullOrUndefined(t)||E.IsNullOrUndefined(t.guidString)?!1:e.UnboundControlIds.containsKey(t.guidString)}static getUnboundFormControlName(t){let r=T.EmptyString;if(E.IsNullOrUndefined(t)||E.IsNullOrUndefined(t.control)||E.IsNullOrUndefined(t.control.ClassId))return r;let n=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.getValue(n.guidString).toString()}static getUnboundControlNameFromIdentifier(t){return E.IsNullOrUndefined(t)||E.IsNullOrUndefined(t.guidString)?T.EmptyString:e.UnboundControlIds.getValue(t.guidString).toString()}static isSpacerControl(t){return t===R.SpacerControl}static GetRowSpan(t){let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===R.CustomControl&&!E.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}switch(e.UnboundControlIds.getValue(r.guidString)){case q.IframeControl:case q.ACIControl:case q.SocialInsightControl:return 6;case q.SubGridControl:case q.CustomControl:return 4;case q.WebResourceImageControl:return 15;case q.WebResourceHtmlControl:return 15;case q.MapsControl:return 8;case q.SearchWidgetControl:return 10;case q.NotesControl:case q.TimeLineControl:return 15;case q.TimerControl:return 2;default:}}static isLookUpControl(t){return!E.IsNullOrUndefined(t)&&t.ClassId.guidString===R.LookupControl}static isRelationshipAssistantOrLeadScoringControl(t){return!E.IsNullOrUndefined(t)&&e.isRelationshipAssistantOrLeadScoring(t.UniqueId)}static isRelationshipAssistantOrLeadScoring(t){return!E.IsNullOrUndefined(t)&&(t.guidString===Hi.RelationshipAssistant||t.guidString===Hi.PredictiveLeadScoring)}static isRelationshipAssistantControl(t){return!E.IsNullOrUndefined(t)&&e.isRelationshipAssistant(t.UniqueId)}static isRelationshipAssistant(t){return!E.IsNullOrUndefined(t)&&t.guidString===Hi.RelationshipAssistant}static getUniqueIdentifierForControl(t){if(E.IsNullOrUndefined(t))return null;let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===R.CustomControl&&!E.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}return r}}});var Gl,Ew=I(()=>{"use strict";Gl=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 Zn,Qi,Nw,Dw,An,Iw,_w,Kp=I(()=>{"use strict";(function(e){e[e.Center=0]="Center",e[e.Left=1]="Left",e[e.Right=2]="Right"})(Zn||(Zn={}));(function(e){e[e.Left=0]="Left",e[e.Top=1]="Top"})(Qi||(Qi={}));(function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle"})(Nw||(Nw={}));(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"})(Dw||(Dw={}));(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"})(An||(An={}));(function(e){e[e.None=0]="None",e[e.SystemRequired=1]="SystemRequired",e[e.ApplicationRequired=2]="ApplicationRequired",e[e.Recommended=3]="Recommended"})(Iw||(Iw={}));(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"})(_w||(_w={}))});var Ji,Pw=I(()=>{"use strict";No();Ji=kp({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 Tw(e){return{...e,extractConfig:t=>MM(t,Object.keys(e.fallback))}}function MM(e,t){let r={};for(let n of t)typeof e[n]<"u"&&(r[n]=e[n]);return r}var Yp=I(()=>{"use strict";});var Zp=g((uJ,Rw)=>{var _o=new Proxy(function(){return _o},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:_o},apply:function(){return _o},construct:function(){return{}}}),Ow=function(){return _o};Object.setPrototypeOf(Ow,_o);Rw.exports=Ow});var Lw=g((cJ,xw)=>{var Po=new Proxy(function(){return Po},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Po},apply:function(){return Po},construct:function(){return{}}}),Fw=function(){return Po};Object.setPrototypeOf(Fw,Po);xw.exports=Fw});var ef=g((dJ,Mw)=>{var To=new Proxy(function(){return To},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:To},apply:function(){return To},construct:function(){return{}}}),kw=function(){return To};Object.setPrototypeOf(kw,To);Mw.exports=kw});var Bw=g((pJ,Uw)=>{function UM(){this.__data__=[],this.size=0}Uw.exports=UM});var Xi=g((fJ,$w)=>{function BM(e,t){return e===t||e!==e&&t!==t}$w.exports=BM});var Oo=g((mJ,qw)=>{var $M=Xi();function qM(e,t){for(var r=e.length;r--;)if($M(e[r][0],t))return r;return-1}qw.exports=qM});var Gw=g((hJ,Vw)=>{var VM=Oo(),GM=Array.prototype,zM=GM.splice;function WM(e){var t=this.__data__,r=VM(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():zM.call(t,r,1),--this.size,!0}Vw.exports=WM});var Ww=g((gJ,zw)=>{var jM=Oo();function HM(e){var t=this.__data__,r=jM(t,e);return r<0?void 0:t[r][1]}zw.exports=HM});var Hw=g((vJ,jw)=>{var QM=Oo();function JM(e){return QM(this.__data__,e)>-1}jw.exports=JM});var Jw=g((yJ,Qw)=>{var XM=Oo();function KM(e,t){var r=this.__data__,n=XM(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}Qw.exports=KM});var Ro=g((bJ,Xw)=>{var YM=Bw(),ZM=Gw(),eU=Ww(),tU=Hw(),rU=Jw();function Ki(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])}}Ki.prototype.clear=YM;Ki.prototype.delete=ZM;Ki.prototype.get=eU;Ki.prototype.has=tU;Ki.prototype.set=rU;Xw.exports=Ki});var Yw=g((wJ,Kw)=>{var nU=Ro();function iU(){this.__data__=new nU,this.size=0}Kw.exports=iU});var eA=g((AJ,Zw)=>{function aU(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}Zw.exports=aU});var rA=g((CJ,tA)=>{function oU(e){return this.__data__.get(e)}tA.exports=oU});var iA=g((SJ,nA)=>{function sU(e){return this.__data__.has(e)}nA.exports=sU});var tf=g((EJ,aA)=>{var lU=typeof global=="object"&&global&&global.Object===Object&&global;aA.exports=lU});var ir=g((NJ,oA)=>{var uU=tf(),cU=typeof self=="object"&&self&&self.Object===Object&&self,dU=uU||cU||Function("return this")();oA.exports=dU});var Fo=g((DJ,sA)=>{var pU=ir(),fU=pU.Symbol;sA.exports=fU});var dA=g((IJ,cA)=>{var lA=Fo(),uA=Object.prototype,mU=uA.hasOwnProperty,hU=uA.toString,xo=lA?lA.toStringTag:void 0;function gU(e){var t=mU.call(e,xo),r=e[xo];try{e[xo]=void 0;var n=!0}catch{}var i=hU.call(e);return n&&(t?e[xo]=r:delete e[xo]),i}cA.exports=gU});var fA=g((_J,pA)=>{var vU=Object.prototype,yU=vU.toString;function bU(e){return yU.call(e)}pA.exports=bU});var ei=g((PJ,gA)=>{var mA=Fo(),wU=dA(),AU=fA(),CU="[object Null]",SU="[object Undefined]",hA=mA?mA.toStringTag:void 0;function EU(e){return e==null?e===void 0?SU:CU:hA&&hA in Object(e)?wU(e):AU(e)}gA.exports=EU});var Hr=g((TJ,vA)=>{function NU(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}vA.exports=NU});var zl=g((OJ,yA)=>{var DU=ei(),IU=Hr(),_U="[object AsyncFunction]",PU="[object Function]",TU="[object GeneratorFunction]",OU="[object Proxy]";function RU(e){if(!IU(e))return!1;var t=DU(e);return t==PU||t==TU||t==_U||t==OU}yA.exports=RU});var wA=g((RJ,bA)=>{var FU=ir(),xU=FU["__core-js_shared__"];bA.exports=xU});var SA=g((FJ,CA)=>{var rf=wA(),AA=(function(){var e=/[^.]+$/.exec(rf&&rf.keys&&rf.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function LU(e){return!!AA&&AA in e}CA.exports=LU});var nf=g((xJ,EA)=>{var kU=Function.prototype,MU=kU.toString;function UU(e){if(e!=null){try{return MU.call(e)}catch{}try{return e+""}catch{}}return""}EA.exports=UU});var DA=g((LJ,NA)=>{var BU=zl(),$U=SA(),qU=Hr(),VU=nf(),GU=/[\\^$.*+?()[\]{}|]/g,zU=/^\[object .+?Constructor\]$/,WU=Function.prototype,jU=Object.prototype,HU=WU.toString,QU=jU.hasOwnProperty,JU=RegExp("^"+HU.call(QU).replace(GU,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function XU(e){if(!qU(e)||$U(e))return!1;var t=BU(e)?JU:zU;return t.test(VU(e))}NA.exports=XU});var _A=g((kJ,IA)=>{function KU(e,t){return e?.[t]}IA.exports=KU});var Cn=g((MJ,PA)=>{var YU=DA(),ZU=_A();function eB(e,t){var r=ZU(e,t);return YU(r)?r:void 0}PA.exports=eB});var Wl=g((UJ,TA)=>{var tB=Cn(),rB=ir(),nB=tB(rB,"Map");TA.exports=nB});var Lo=g((BJ,OA)=>{var iB=Cn(),aB=iB(Object,"create");OA.exports=aB});var xA=g(($J,FA)=>{var RA=Lo();function oB(){this.__data__=RA?RA(null):{},this.size=0}FA.exports=oB});var kA=g((qJ,LA)=>{function sB(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}LA.exports=sB});var UA=g((VJ,MA)=>{var lB=Lo(),uB="__lodash_hash_undefined__",cB=Object.prototype,dB=cB.hasOwnProperty;function pB(e){var t=this.__data__;if(lB){var r=t[e];return r===uB?void 0:r}return dB.call(t,e)?t[e]:void 0}MA.exports=pB});var $A=g((GJ,BA)=>{var fB=Lo(),mB=Object.prototype,hB=mB.hasOwnProperty;function gB(e){var t=this.__data__;return fB?t[e]!==void 0:hB.call(t,e)}BA.exports=gB});var VA=g((zJ,qA)=>{var vB=Lo(),yB="__lodash_hash_undefined__";function bB(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=vB&&t===void 0?yB:t,this}qA.exports=bB});var zA=g((WJ,GA)=>{var wB=xA(),AB=kA(),CB=UA(),SB=$A(),EB=VA();function Yi(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])}}Yi.prototype.clear=wB;Yi.prototype.delete=AB;Yi.prototype.get=CB;Yi.prototype.has=SB;Yi.prototype.set=EB;GA.exports=Yi});var HA=g((jJ,jA)=>{var WA=zA(),NB=Ro(),DB=Wl();function IB(){this.size=0,this.__data__={hash:new WA,map:new(DB||NB),string:new WA}}jA.exports=IB});var JA=g((HJ,QA)=>{function _B(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}QA.exports=_B});var ko=g((QJ,XA)=>{var PB=JA();function TB(e,t){var r=e.__data__;return PB(t)?r[typeof t=="string"?"string":"hash"]:r.map}XA.exports=TB});var YA=g((JJ,KA)=>{var OB=ko();function RB(e){var t=OB(this,e).delete(e);return this.size-=t?1:0,t}KA.exports=RB});var eC=g((XJ,ZA)=>{var FB=ko();function xB(e){return FB(this,e).get(e)}ZA.exports=xB});var rC=g((KJ,tC)=>{var LB=ko();function kB(e){return LB(this,e).has(e)}tC.exports=kB});var iC=g((YJ,nC)=>{var MB=ko();function UB(e,t){var r=MB(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}nC.exports=UB});var jl=g((ZJ,aC)=>{var BB=HA(),$B=YA(),qB=eC(),VB=rC(),GB=iC();function Zi(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])}}Zi.prototype.clear=BB;Zi.prototype.delete=$B;Zi.prototype.get=qB;Zi.prototype.has=VB;Zi.prototype.set=GB;aC.exports=Zi});var sC=g((eX,oC)=>{var zB=Ro(),WB=Wl(),jB=jl(),HB=200;function QB(e,t){var r=this.__data__;if(r instanceof zB){var n=r.__data__;if(!WB||n.length<HB-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new jB(n)}return r.set(e,t),this.size=r.size,this}oC.exports=QB});var af=g((tX,lC)=>{var JB=Ro(),XB=Yw(),KB=eA(),YB=rA(),ZB=iA(),e$=sC();function ea(e){var t=this.__data__=new JB(e);this.size=t.size}ea.prototype.clear=XB;ea.prototype.delete=KB;ea.prototype.get=YB;ea.prototype.has=ZB;ea.prototype.set=e$;lC.exports=ea});var cC=g((rX,uC)=>{var t$="__lodash_hash_undefined__";function r$(e){return this.__data__.set(e,t$),this}uC.exports=r$});var pC=g((nX,dC)=>{function n$(e){return this.__data__.has(e)}dC.exports=n$});var mC=g((iX,fC)=>{var i$=jl(),a$=cC(),o$=pC();function Hl(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new i$;++t<r;)this.add(e[t])}Hl.prototype.add=Hl.prototype.push=a$;Hl.prototype.has=o$;fC.exports=Hl});var gC=g((aX,hC)=>{function s$(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}hC.exports=s$});var yC=g((oX,vC)=>{function l$(e,t){return e.has(t)}vC.exports=l$});var of=g((sX,bC)=>{var u$=mC(),c$=gC(),d$=yC(),p$=1,f$=2;function m$(e,t,r,n,i,a){var o=r&p$,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&f$?new u$:void 0;for(a.set(e,t),a.set(t,e);++d<s;){var h=e[d],y=t[d];if(n)var w=o?n(y,h,d,t,e,a):n(h,y,d,e,t,a);if(w!==void 0){if(w)continue;p=!1;break}if(f){if(!c$(t,function(N,D){if(!d$(f,D)&&(h===N||i(h,N,r,n,a)))return f.push(D)})){p=!1;break}}else if(!(h===y||i(h,y,r,n,a))){p=!1;break}}return a.delete(e),a.delete(t),p}bC.exports=m$});var sf=g((lX,wC)=>{var h$=ir(),g$=h$.Uint8Array;wC.exports=g$});var CC=g((uX,AC)=>{function v$(e){var t=-1,r=Array(e.size);return e.forEach(function(n,i){r[++t]=[i,n]}),r}AC.exports=v$});var EC=g((cX,SC)=>{function y$(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n}),r}SC.exports=y$});var PC=g((dX,_C)=>{var NC=Fo(),DC=sf(),b$=Xi(),w$=of(),A$=CC(),C$=EC(),S$=1,E$=2,N$="[object Boolean]",D$="[object Date]",I$="[object Error]",_$="[object Map]",P$="[object Number]",T$="[object RegExp]",O$="[object Set]",R$="[object String]",F$="[object Symbol]",x$="[object ArrayBuffer]",L$="[object DataView]",IC=NC?NC.prototype:void 0,lf=IC?IC.valueOf:void 0;function k$(e,t,r,n,i,a,o){switch(r){case L$:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case x$:return!(e.byteLength!=t.byteLength||!a(new DC(e),new DC(t)));case N$:case D$:case P$:return b$(+e,+t);case I$:return e.name==t.name&&e.message==t.message;case T$:case R$:return e==t+"";case _$:var s=A$;case O$:var l=n&S$;if(s||(s=C$),e.size!=t.size&&!l)return!1;var u=o.get(e);if(u)return u==t;n|=E$,o.set(e,t);var c=w$(s(e),s(t),n,i,a,o);return o.delete(e),c;case F$:if(lf)return lf.call(e)==lf.call(t)}return!1}_C.exports=k$});var OC=g((pX,TC)=>{function M$(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}TC.exports=M$});var Sn=g((fX,RC)=>{var U$=Array.isArray;RC.exports=U$});var xC=g((mX,FC)=>{var B$=OC(),$$=Sn();function q$(e,t,r){var n=t(e);return $$(e)?n:B$(n,r(e))}FC.exports=q$});var kC=g((hX,LC)=>{function V$(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}LC.exports=V$});var UC=g((gX,MC)=>{function G$(){return[]}MC.exports=G$});var qC=g((vX,$C)=>{var z$=kC(),W$=UC(),j$=Object.prototype,H$=j$.propertyIsEnumerable,BC=Object.getOwnPropertySymbols,Q$=BC?function(e){return e==null?[]:(e=Object(e),z$(BC(e),function(t){return H$.call(e,t)}))}:W$;$C.exports=Q$});var GC=g((yX,VC)=>{function J$(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}VC.exports=J$});var En=g((bX,zC)=>{function X$(e){return e!=null&&typeof e=="object"}zC.exports=X$});var jC=g((wX,WC)=>{var K$=ei(),Y$=En(),Z$="[object Arguments]";function eq(e){return Y$(e)&&K$(e)==Z$}WC.exports=eq});var uf=g((AX,JC)=>{var HC=jC(),tq=En(),QC=Object.prototype,rq=QC.hasOwnProperty,nq=QC.propertyIsEnumerable,iq=HC((function(){return arguments})())?HC:function(e){return tq(e)&&rq.call(e,"callee")&&!nq.call(e,"callee")};JC.exports=iq});var KC=g((CX,XC)=>{function aq(){return!1}XC.exports=aq});var Ql=g((Mo,ta)=>{var oq=ir(),sq=KC(),eS=typeof Mo=="object"&&Mo&&!Mo.nodeType&&Mo,YC=eS&&typeof ta=="object"&&ta&&!ta.nodeType&&ta,lq=YC&&YC.exports===eS,ZC=lq?oq.Buffer:void 0,uq=ZC?ZC.isBuffer:void 0,cq=uq||sq;ta.exports=cq});var Jl=g((SX,tS)=>{var dq=9007199254740991,pq=/^(?:0|[1-9]\d*)$/;function fq(e,t){var r=typeof e;return t=t??dq,!!t&&(r=="number"||r!="symbol"&&pq.test(e))&&e>-1&&e%1==0&&e<t}tS.exports=fq});var cf=g((EX,rS)=>{var mq=9007199254740991;function hq(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=mq}rS.exports=hq});var iS=g((NX,nS)=>{var gq=ei(),vq=cf(),yq=En(),bq="[object Arguments]",wq="[object Array]",Aq="[object Boolean]",Cq="[object Date]",Sq="[object Error]",Eq="[object Function]",Nq="[object Map]",Dq="[object Number]",Iq="[object Object]",_q="[object RegExp]",Pq="[object Set]",Tq="[object String]",Oq="[object WeakMap]",Rq="[object ArrayBuffer]",Fq="[object DataView]",xq="[object Float32Array]",Lq="[object Float64Array]",kq="[object Int8Array]",Mq="[object Int16Array]",Uq="[object Int32Array]",Bq="[object Uint8Array]",$q="[object Uint8ClampedArray]",qq="[object Uint16Array]",Vq="[object Uint32Array]",ge={};ge[xq]=ge[Lq]=ge[kq]=ge[Mq]=ge[Uq]=ge[Bq]=ge[$q]=ge[qq]=ge[Vq]=!0;ge[bq]=ge[wq]=ge[Rq]=ge[Aq]=ge[Fq]=ge[Cq]=ge[Sq]=ge[Eq]=ge[Nq]=ge[Dq]=ge[Iq]=ge[_q]=ge[Pq]=ge[Tq]=ge[Oq]=!1;function Gq(e){return yq(e)&&vq(e.length)&&!!ge[gq(e)]}nS.exports=Gq});var oS=g((DX,aS)=>{function zq(e){return function(t){return e(t)}}aS.exports=zq});var lS=g((Uo,ra)=>{var Wq=tf(),sS=typeof Uo=="object"&&Uo&&!Uo.nodeType&&Uo,Bo=sS&&typeof ra=="object"&&ra&&!ra.nodeType&&ra,jq=Bo&&Bo.exports===sS,df=jq&&Wq.process,Hq=(function(){try{var e=Bo&&Bo.require&&Bo.require("util").types;return e||df&&df.binding&&df.binding("util")}catch{}})();ra.exports=Hq});var Xl=g((IX,dS)=>{var Qq=iS(),Jq=oS(),uS=lS(),cS=uS&&uS.isTypedArray,Xq=cS?Jq(cS):Qq;dS.exports=Xq});var pf=g((_X,pS)=>{var Kq=GC(),Yq=uf(),Zq=Sn(),e3=Ql(),t3=Jl(),r3=Xl(),n3=Object.prototype,i3=n3.hasOwnProperty;function a3(e,t){var r=Zq(e),n=!r&&Yq(e),i=!r&&!n&&e3(e),a=!r&&!n&&!i&&r3(e),o=r||n||i||a,s=o?Kq(e.length,String):[],l=s.length;for(var u in e)(t||i3.call(e,u))&&!(o&&(u=="length"||i&&(u=="offset"||u=="parent")||a&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||t3(u,l)))&&s.push(u);return s}pS.exports=a3});var Kl=g((PX,fS)=>{var o3=Object.prototype;function s3(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||o3;return e===r}fS.exports=s3});var ff=g((TX,mS)=>{function l3(e,t){return function(r){return e(t(r))}}mS.exports=l3});var gS=g((OX,hS)=>{var u3=ff(),c3=u3(Object.keys,Object);hS.exports=c3});var yS=g((RX,vS)=>{var d3=Kl(),p3=gS(),f3=Object.prototype,m3=f3.hasOwnProperty;function h3(e){if(!d3(e))return p3(e);var t=[];for(var r in Object(e))m3.call(e,r)&&r!="constructor"&&t.push(r);return t}vS.exports=h3});var $o=g((FX,bS)=>{var g3=zl(),v3=cf();function y3(e){return e!=null&&v3(e.length)&&!g3(e)}bS.exports=y3});var AS=g((xX,wS)=>{var b3=pf(),w3=yS(),A3=$o();function C3(e){return A3(e)?b3(e):w3(e)}wS.exports=C3});var SS=g((LX,CS)=>{var S3=xC(),E3=qC(),N3=AS();function D3(e){return S3(e,N3,E3)}CS.exports=D3});var DS=g((kX,NS)=>{var ES=SS(),I3=1,_3=Object.prototype,P3=_3.hasOwnProperty;function T3(e,t,r,n,i,a){var o=r&I3,s=ES(e),l=s.length,u=ES(t),c=u.length;if(l!=c&&!o)return!1;for(var d=l;d--;){var p=s[d];if(!(o?p in t:P3.call(t,p)))return!1}var f=a.get(e),h=a.get(t);if(f&&h)return f==t&&h==e;var y=!0;a.set(e,t),a.set(t,e);for(var w=o;++d<l;){p=s[d];var N=e[p],D=t[p];if(n)var x=o?n(D,N,p,t,e,a):n(N,D,p,e,t,a);if(!(x===void 0?N===D||i(N,D,r,n,a):x)){y=!1;break}w||(w=p=="constructor")}if(y&&!w){var F=e.constructor,X=t.constructor;F!=X&&"constructor"in e&&"constructor"in t&&!(typeof F=="function"&&F instanceof F&&typeof X=="function"&&X instanceof X)&&(y=!1)}return a.delete(e),a.delete(t),y}NS.exports=T3});var _S=g((MX,IS)=>{var O3=Cn(),R3=ir(),F3=O3(R3,"DataView");IS.exports=F3});var TS=g((UX,PS)=>{var x3=Cn(),L3=ir(),k3=x3(L3,"Promise");PS.exports=k3});var RS=g((BX,OS)=>{var M3=Cn(),U3=ir(),B3=M3(U3,"Set");OS.exports=B3});var xS=g(($X,FS)=>{var $3=Cn(),q3=ir(),V3=$3(q3,"WeakMap");FS.exports=V3});var VS=g((qX,qS)=>{var mf=_S(),hf=Wl(),gf=TS(),vf=RS(),yf=xS(),$S=ei(),na=nf(),LS="[object Map]",G3="[object Object]",kS="[object Promise]",MS="[object Set]",US="[object WeakMap]",BS="[object DataView]",z3=na(mf),W3=na(hf),j3=na(gf),H3=na(vf),Q3=na(yf),ti=$S;(mf&&ti(new mf(new ArrayBuffer(1)))!=BS||hf&&ti(new hf)!=LS||gf&&ti(gf.resolve())!=kS||vf&&ti(new vf)!=MS||yf&&ti(new yf)!=US)&&(ti=function(e){var t=$S(e),r=t==G3?e.constructor:void 0,n=r?na(r):"";if(n)switch(n){case z3:return BS;case W3:return LS;case j3:return kS;case H3:return MS;case Q3:return US}return t});qS.exports=ti});var XS=g((VX,JS)=>{var bf=af(),J3=of(),X3=PC(),K3=DS(),GS=VS(),zS=Sn(),WS=Ql(),Y3=Xl(),Z3=1,jS="[object Arguments]",HS="[object Array]",Yl="[object Object]",e4=Object.prototype,QS=e4.hasOwnProperty;function t4(e,t,r,n,i,a){var o=zS(e),s=zS(t),l=o?HS:GS(e),u=s?HS:GS(t);l=l==jS?Yl:l,u=u==jS?Yl:u;var c=l==Yl,d=u==Yl,p=l==u;if(p&&WS(e)){if(!WS(t))return!1;o=!0,c=!1}if(p&&!c)return a||(a=new bf),o||Y3(e)?J3(e,t,r,n,i,a):X3(e,t,l,r,n,i,a);if(!(r&Z3)){var f=c&&QS.call(e,"__wrapped__"),h=d&&QS.call(t,"__wrapped__");if(f||h){var y=f?e.value():e,w=h?t.value():t;return a||(a=new bf),i(y,w,r,n,a)}}return p?(a||(a=new bf),K3(e,t,r,n,i,a)):!1}JS.exports=t4});var eE=g((GX,ZS)=>{var r4=XS(),KS=En();function YS(e,t,r,n,i){return e===t?!0:e==null||t==null||!KS(e)&&!KS(t)?e!==e&&t!==t:r4(e,t,r,n,YS,i)}ZS.exports=YS});var rE=g((zX,tE)=>{var n4=eE();function i4(e,t){return n4(e,t)}tE.exports=i4});var wf=g((WX,nE)=>{var a4=Cn(),o4=(function(){try{var e=a4(Object,"defineProperty");return e({},"",{}),e}catch{}})();nE.exports=o4});var Zl=g((jX,aE)=>{var iE=wf();function s4(e,t,r){t=="__proto__"&&iE?iE(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}aE.exports=s4});var Af=g((HX,oE)=>{var l4=Zl(),u4=Xi();function c4(e,t,r){(r!==void 0&&!u4(e[t],r)||r===void 0&&!(t in e))&&l4(e,t,r)}oE.exports=c4});var lE=g((QX,sE)=>{function d4(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}}sE.exports=d4});var cE=g((JX,uE)=>{var p4=lE(),f4=p4();uE.exports=f4});var hE=g((qo,ia)=>{var m4=ir(),mE=typeof qo=="object"&&qo&&!qo.nodeType&&qo,dE=mE&&typeof ia=="object"&&ia&&!ia.nodeType&&ia,h4=dE&&dE.exports===mE,pE=h4?m4.Buffer:void 0,fE=pE?pE.allocUnsafe:void 0;function g4(e,t){if(t)return e.slice();var r=e.length,n=fE?fE(r):new e.constructor(r);return e.copy(n),n}ia.exports=g4});var yE=g((XX,vE)=>{var gE=sf();function v4(e){var t=new e.constructor(e.byteLength);return new gE(t).set(new gE(e)),t}vE.exports=v4});var wE=g((KX,bE)=>{var y4=yE();function b4(e,t){var r=t?y4(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}bE.exports=b4});var CE=g((YX,AE)=>{function w4(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}AE.exports=w4});var NE=g((ZX,EE)=>{var A4=Hr(),SE=Object.create,C4=(function(){function e(){}return function(t){if(!A4(t))return{};if(SE)return SE(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}})();EE.exports=C4});var Cf=g((eK,DE)=>{var S4=ff(),E4=S4(Object.getPrototypeOf,Object);DE.exports=E4});var _E=g((tK,IE)=>{var N4=NE(),D4=Cf(),I4=Kl();function _4(e){return typeof e.constructor=="function"&&!I4(e)?N4(D4(e)):{}}IE.exports=_4});var TE=g((rK,PE)=>{var P4=$o(),T4=En();function O4(e){return T4(e)&&P4(e)}PE.exports=O4});var FE=g((nK,RE)=>{var R4=ei(),F4=Cf(),x4=En(),L4="[object Object]",k4=Function.prototype,M4=Object.prototype,OE=k4.toString,U4=M4.hasOwnProperty,B4=OE.call(Object);function $4(e){if(!x4(e)||R4(e)!=L4)return!1;var t=F4(e);if(t===null)return!0;var r=U4.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&OE.call(r)==B4}RE.exports=$4});var Sf=g((iK,xE)=>{function q4(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}xE.exports=q4});var Ef=g((aK,LE)=>{var V4=Zl(),G4=Xi(),z4=Object.prototype,W4=z4.hasOwnProperty;function j4(e,t,r){var n=e[t];(!(W4.call(e,t)&&G4(n,r))||r===void 0&&!(t in e))&&V4(e,t,r)}LE.exports=j4});var ME=g((oK,kE)=>{var H4=Ef(),Q4=Zl();function J4(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?Q4(r,s,l):H4(r,s,l)}return r}kE.exports=J4});var BE=g((sK,UE)=>{function X4(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}UE.exports=X4});var qE=g((lK,$E)=>{var K4=Hr(),Y4=Kl(),Z4=BE(),e5=Object.prototype,t5=e5.hasOwnProperty;function r5(e){if(!K4(e))return Z4(e);var t=Y4(e),r=[];for(var n in e)n=="constructor"&&(t||!t5.call(e,n))||r.push(n);return r}$E.exports=r5});var Nf=g((uK,VE)=>{var n5=pf(),i5=qE(),a5=$o();function o5(e){return a5(e)?n5(e,!0):i5(e)}VE.exports=o5});var zE=g((cK,GE)=>{var s5=ME(),l5=Nf();function u5(e){return s5(e,l5(e))}GE.exports=u5});var XE=g((dK,JE)=>{var WE=Af(),c5=hE(),d5=wE(),p5=CE(),f5=_E(),jE=uf(),HE=Sn(),m5=TE(),h5=Ql(),g5=zl(),v5=Hr(),y5=FE(),b5=Xl(),QE=Sf(),w5=zE();function A5(e,t,r,n,i,a,o){var s=QE(e,r),l=QE(t,r),u=o.get(l);if(u){WE(e,r,u);return}var c=a?a(s,l,r+"",e,t,o):void 0,d=c===void 0;if(d){var p=HE(l),f=!p&&h5(l),h=!p&&!f&&b5(l);c=l,p||f||h?HE(s)?c=s:m5(s)?c=p5(s):f?(d=!1,c=c5(l,!0)):h?(d=!1,c=d5(l,!0)):c=[]:y5(l)||jE(l)?(c=s,jE(s)?c=w5(s):(!v5(s)||g5(s))&&(c=f5(l))):d=!1}d&&(o.set(l,c),i(c,l,n,a,o),o.delete(l)),WE(e,r,c)}JE.exports=A5});var Df=g((pK,YE)=>{var C5=af(),S5=Af(),E5=cE(),N5=XE(),D5=Hr(),I5=Nf(),_5=Sf();function KE(e,t,r,n,i){e!==t&&E5(t,function(a,o){if(i||(i=new C5),D5(a))N5(e,t,o,r,KE,n,i);else{var s=n?n(_5(e,o),a,o+"",e,t,i):void 0;s===void 0&&(s=a),S5(e,o,s)}},I5)}YE.exports=KE});var If=g((fK,ZE)=>{function P5(e){return e}ZE.exports=P5});var tN=g((mK,eN)=>{function T5(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)}eN.exports=T5});var iN=g((hK,nN)=>{var O5=tN(),rN=Math.max;function R5(e,t,r){return t=rN(t===void 0?e.length-1:t,0),function(){for(var n=arguments,i=-1,a=rN(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),O5(e,this,s)}}nN.exports=R5});var oN=g((gK,aN)=>{function F5(e){return function(){return e}}aN.exports=F5});var uN=g((vK,lN)=>{var x5=oN(),sN=wf(),L5=If(),k5=sN?function(e,t){return sN(e,"toString",{configurable:!0,enumerable:!1,value:x5(t),writable:!0})}:L5;lN.exports=k5});var dN=g((yK,cN)=>{var M5=800,U5=16,B5=Date.now;function $5(e){var t=0,r=0;return function(){var n=B5(),i=U5-(n-r);if(r=n,i>0){if(++t>=M5)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}cN.exports=$5});var fN=g((bK,pN)=>{var q5=uN(),V5=dN(),G5=V5(q5);pN.exports=G5});var hN=g((wK,mN)=>{var z5=If(),W5=iN(),j5=fN();function H5(e,t){return j5(W5(e,t,z5),e+"")}mN.exports=H5});var vN=g((AK,gN)=>{var Q5=Xi(),J5=$o(),X5=Jl(),K5=Hr();function Y5(e,t,r){if(!K5(r))return!1;var n=typeof t;return(n=="number"?J5(r)&&X5(t,r.length):n=="string"&&t in r)?Q5(r[t],e):!1}gN.exports=Y5});var _f=g((CK,yN)=>{var Z5=hN(),eV=vN();function tV(e){return Z5(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&&eV(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})}yN.exports=tV});var wN=g((SK,bN)=>{var rV=Df(),nV=_f(),iV=nV(function(e,t,r,n){rV(e,t,r,n)});bN.exports=iV});var $t,Vo=I(()=>{"use strict";(function(e){e[e.NotLoaded=0]="NotLoaded",e[e.Initialized=1]="Initialized",e[e.ConfigsLoaded=2]="ConfigsLoaded",e[e.Error=3]="Error"})($t||($t={}))});function CN(e,t,r="PROD"){let n=i=>`ShellSettings_ECS_ClientCache_${e}_${AN.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 AN,aV,SN=I(()=>{"use strict";AN=se(ef()),aV=se(Zp());});var Pf,EN=I(()=>{"use strict";Fl();Pf=Eo({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 DN,IN,_N,PN,Tf,oV,eu,NN,Of=I(()=>{"use strict";DN=se(Zp()),IN=se(Lw()),_N=se(ef()),PN=se(rE()),Tf=se(wN());Vo();SN();EN();oV=60*1e3,eu=class{clientName;logger;ecsEndpoint;resolveLoadingPromise;loadingPromise=new Promise(t=>this.resolveLoadingPromise=t);_status=$t.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"?Pf.prodEcsEndpoint:Pf.integrationEcsEndpoint}client=new IN.default;init=async({clientVersion:t,getFilters:r,cacheStorage:n=DN.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:[_N.EcsConfigType.Default],hosts:[this.ecsEndpoint],initialAppActiveState:!0,getEcsParameters:o,databaseInterface:CN(this.clientName,n,this.endpointType),...a}),this.client.requestUpdate(),this._status===$t.NotLoaded&&(this._status=$t.Initialized)}catch(s){this._status=$t.Error,this.resolveLoadingPromise(),this.logEvent("FeaturesClient/initializationFailed",{ecsClientName:this.clientName,error:s},"Error")}i&&window.setInterval(()=>this.client.requestUpdate(),i*oV)};getConfig=t=>{let r=this.getMergedClientConfigByTeamName(t.teamName),n=r?t.extractConfig(r):{};return(0,Tf.default)({},t.fallback,n,t.override,NN)};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,PN.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,Tf.default)({},this.client.getConfig()?.config,this.clientConfigOverride,NN);getMergedClientConfigByTeamName=t=>this.getMergedClientConfig()?.[t];handleConfigUpdated=()=>{let t=this.client.getConfig();if(t===void 0)return;this.resolveLoadingPromise(),this._status=$t.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})}},NN=(e,t)=>{if(Array.isArray(t))return t}});var ON=g((RK,TN)=>{"use strict";var sV=()=>{let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e};TN.exports=sV});var Rf=g((FK,FN)=>{var Go=new Proxy(function(){return Go},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Go},apply:function(){return Go},construct:function(){return{}}}),RN=function(){return Go};Object.setPrototypeOf(RN,Go);FN.exports=RN});var kN=g((xK,LN)=>{var zo=new Proxy(function(){return zo},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:zo},apply:function(){return zo},construct:function(){return{}}}),xN=function(){return zo};Object.setPrototypeOf(xN,zo);LN.exports=xN});var GN=g((LK,VN)=>{"use strict";var Ff=kN(),lV={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},uV={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},cV={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},$N={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},xf={};xf[Ff.ForwardRef]=cV;xf[Ff.Memo]=$N;function MN(e){return Ff.isMemo(e)?$N:xf[e.$$typeof]||lV}var dV=Object.defineProperty,pV=Object.getOwnPropertyNames,UN=Object.getOwnPropertySymbols,fV=Object.getOwnPropertyDescriptor,mV=Object.getPrototypeOf,BN=Object.prototype;function qN(e,t,r){if(typeof t!="string"){if(BN){var n=mV(t);n&&n!==BN&&qN(e,n,r)}var i=pV(t);UN&&(i=i.concat(UN(t)));for(var a=MN(e),o=MN(t),s=0;s<i.length;++s){var l=i[s];if(!uV[l]&&!(r&&r[l])&&!(o&&o[l])&&!(a&&a[l])){var u=fV(t,l);try{dV(e,l,u)}catch{}}}}return e}VN.exports=qN});function WN(e,t,r){let[n,i]=(0,aa.useState)(e.getConfig(t));return(0,aa.useEffect)(()=>{if(!r?.subscribe&&e.status===$t.ConfigsLoaded)return;let a=e.subscribe(t,o=>{i(o),r?.subscribe||a.unsubscribe()});return a?.unsubscribe},[]),n}function jN(e){return function(t,r){return WN(e,t,r)}}function HN(e,t,r,n){let i=a=>{let o=WN(e,t,n),s={...a,...o};return aa.default.createElement(r,{...s})};return(0,zN.default)(i,r),i.displayName=`WithFeature(${r.name})`,i}function QN(e,t,r,n){return t.reduce((i,a)=>HN(e,a,i,n),r)}function JN(e){return function(t,r,n){return HN(e,t,r,n)}}var zN,aa,Lf=I(()=>{"use strict";zN=se(GN()),aa=se(Rf());Vo();});var KN=g((UK,XN)=>{var hV=Df(),gV=_f(),vV=gV(function(e,t,r){hV(e,t,r)});XN.exports=vV});var tu=g((BK,YN)=>{var yV=ei(),bV=En(),wV="[object Symbol]";function AV(e){return typeof e=="symbol"||bV(e)&&yV(e)==wV}YN.exports=AV});var eD=g(($K,ZN)=>{var CV=Sn(),SV=tu(),EV=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,NV=/^\w*$/;function DV(e,t){if(CV(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||SV(e)?!0:NV.test(e)||!EV.test(e)||t!=null&&e in Object(t)}ZN.exports=DV});var nD=g((qK,rD)=>{var tD=jl(),IV="Expected a function";function kf(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(IV);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(kf.Cache||tD),r}kf.Cache=tD;rD.exports=kf});var aD=g((VK,iD)=>{var _V=nD(),PV=500;function TV(e){var t=_V(e,function(n){return r.size===PV&&r.clear(),n}),r=t.cache;return t}iD.exports=TV});var sD=g((GK,oD)=>{var OV=aD(),RV=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,FV=/\\(\\)?/g,xV=OV(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(RV,function(r,n,i,a){t.push(i?a.replace(FV,"$1"):n||r)}),t});oD.exports=xV});var uD=g((zK,lD)=>{function LV(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}lD.exports=LV});var hD=g((WK,mD)=>{var cD=Fo(),kV=uD(),MV=Sn(),UV=tu(),BV=1/0,dD=cD?cD.prototype:void 0,pD=dD?dD.toString:void 0;function fD(e){if(typeof e=="string")return e;if(MV(e))return kV(e,fD)+"";if(UV(e))return pD?pD.call(e):"";var t=e+"";return t=="0"&&1/e==-BV?"-0":t}mD.exports=fD});var vD=g((jK,gD)=>{var $V=hD();function qV(e){return e==null?"":$V(e)}gD.exports=qV});var bD=g((HK,yD)=>{var VV=Sn(),GV=eD(),zV=sD(),WV=vD();function jV(e,t){return VV(e)?e:GV(e,t)?[e]:zV(WV(e))}yD.exports=jV});var AD=g((QK,wD)=>{var HV=tu(),QV=1/0;function JV(e){if(typeof e=="string"||HV(e))return e;var t=e+"";return t=="0"&&1/e==-QV?"-0":t}wD.exports=JV});var ED=g((JK,SD)=>{var XV=Ef(),KV=bD(),YV=Jl(),CD=Hr(),ZV=AD();function e9(e,t,r,n){if(!CD(e))return e;t=KV(t,e);for(var i=-1,a=t.length,o=a-1,s=e;s!=null&&++i<a;){var l=ZV(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=CD(c)?c:YV(t[i+1])?[]:{})}XV(s,l,u),s=s[l]}return e}SD.exports=e9});var DD=g((XK,ND)=>{var t9=ED();function r9(e,t,r){return e==null?e:t9(e,t,r)}ND.exports=r9});function TD(e){let{query:t}=(0,PD.default)(window.location.href,!0);return i9(e,t),e}function i9(e,t){let r=n9+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+OD,u={};if(a===r)u=s;else if(a.startsWith(l)){let c=a.substring(l.length);(0,_D.default)(u,c,s)}(0,ID.default)(i,u)}catch{}}),Object.keys(i).length>0&&e.overrideClientConfig(i)}var ID,_D,PD,OD,n9,RD=I(()=>{"use strict";ID=se(KN()),_D=se(DD()),PD=se($p());OD=".",n9="ecs"+OD});function nu(e,t,r){let n=TD(new eu(e,t,r));function i(a){(0,ru.useEffect)(()=>{n.init(a)},[])}return{featuresClient:n,createFeature:o9(n),useFeaturesClientInitParams:i,withFeatures:(a,o,s)=>QN(n,a,o,s)}}function o9(e){let t=jN(e),r=JN(e);return function(i){let a=Tw(i);return a.getConfig=()=>e.getConfig(a),a.isLoaded=()=>e.status===$t.ConfigsLoaded,Gp.register(a,e.clientName),{useFeature:o=>t(a,o),withFeature:(o,s)=>r(a,o,s),feature:a}}}var a9,ru,Mf=I(()=>{"use strict";a9=se(ON()),ru=se(Rf());Yp();Of();Vo();Lf();RD();zp();});var FD=I(()=>{"use strict";Yp();Of();Mf();Vo();Lf();Ml();Wp();});function iu(e){return{logEvent:(t,r,n)=>{switch(n){case"Error":(0,oa.trackErrorTrace)(e,{eventName:t,eventData:r});break;case"Warning":(0,oa.trackWarningTrace)(e,{eventName:t,eventData:r});break;default:(0,oa.trackInfoTrace)(e,{eventName:t,eventData:r});break}}}}var oa,Uf=I(()=>{"use strict";oa=se(Qn());});var gY,vY,yY,xD=I(()=>{"use strict";FD();Uf();({featuresClient:gY,createFeature:vY,useFeaturesClientInitParams:yY}=nu("PowerApps-Shell-Test",iu("shell-features")))});var MD=g((wY,kD)=>{var Wo=new Proxy(function(){return Wo},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Wo},apply:function(){return Wo},construct:function(){return{}}}),LD=function(){return Wo};Object.setPrototypeOf(LD,Wo);kD.exports=LD});var s9,l9,UD=I(()=>{"use strict";Ao();s9=se(MD()),l9=se(Qn());});var BD=I(()=>{"use strict";xD();Uf();UD();});var PY,sa,TY,$D=I(()=>{"use strict";BD();Mf();({featuresClient:PY,createFeature:sa,useFeaturesClientInitParams:TY}=nu("PowerApps-MakerPortal",iu("powerapps-features")))});var qD,VD,xY,LY,kY,MY,Bf=I(()=>{"use strict";Pw();$D();({feature:qD}=sa({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:Ji.enableAutoInsertionOfCellInRow}})),{feature:VD}=sa({teamName:"MakerPortal",owners:["aansu"],description:"Enable the one grid events for form designer",createdOn:"08/21/2024",fallback:{enableOneGridEventsForFormDesigner:Ji.enableOneGridEvents}}),{feature:xY}=sa({teamName:"MakerPortal",owners:["adekulkarni"],description:"Disables PBI components and cleans them up from the form",createdOn:"01/03/2023",fallback:{enableFallbackFormTemplate:Ji.disablePBIComponents}}),{feature:LY}=sa({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:Ji.enableAgentResponse}}),{feature:kY,useFeature:MY}=sa({teamName:"MakerPortal",owners:["aansu"],description:"Enables delayed localization of custom control",createdOn:"06/08/2025",fallback:{enableDelayedLocalizationForCustomControls:Ji.enableDelayedLocalizationForCustomControls}})});var WD=g((BY,zD)=>{var jo=new Proxy(function(){return jo},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:jo},apply:function(){return jo},construct:function(){return{}}}),GD=function(){return jo};Object.setPrototypeOf(GD,jo);zD.exports=GD});var st,Nn=I(()=>{"use strict";Ue();Le();ot();Vl();K();Qe();st=class extends j{static HighestUsedIndexByClass=new Map;get colspan(){let t=this.getProperty(m.colspan);return E.IsNullOrUndefined(t)?null:parseInt(t,10)}set colspan(t){E.IsNullOrUndefined(t)||this.setProperty(m.colspan,String(t))}constructor(t,r){super(t,r)}get id(){let t=this.getProperty(m.id);return t==null?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new P(t.substr(1,t.length-2)):new P(t)}set id(t){this.setProperty(m.id,`{${t.ToString()}}`)}set labelId(t){this.setProperty(m.labelId,`{${t.ToString()}}`)}get labelId(){let t=this.getProperty(m.labelId);return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new P(t.substr(1,t.length-2)):new P(t)}get Name(){return this.getProperty(m.Name)}set Name(t){this.setProperty(m.Name,t)}setDisplayName(t,r){for(let i of this.getAllLabels())if(+i.getProperty(m.languagecode)===r){i.setProperty(m.description,t);return}let n=new j(v.formLabel,null);n.setProperty(m.description,t),n.setProperty(m.languagecode,String(r)),this.addGrandChild("labels",n)}getDisplayName(t){for(let r of this.getAllLabels())if(+r.getProperty(m.languagecode)===t)return r.getProperty(m.description)}getAllLabels(){let t=this.getChildren("labels");return t.length!==1?[]:t[0].getChildren("label")}get isLocked(){return+this.getProperty(m.locklevel)==1}set isLocked(t){!this.IsUnboundControl&&this.setProperty(m.locklevel,t?"1":"0")}get availableforphone(){return this.getProcessedValue(m.availableforphone)}set availableforphone(t){E.IsNullOrUndefined(t)||!this.IsAllowedUBCForAvailableOnPhone()||this.setProperty(m.availableforphone,String(t))}get visible(){return this.getProcessedValue(m.visible)}set visible(t){E.IsNullOrUndefined(t)||!this.IsAllowedUBCForVisibleByDefault()||this.setProperty(m.visible,String(t))}isLockLevelSettable(){return!this.IsUnboundControl}get showlabel(){return this.getProcessedValue(m.showlabel)}set showlabel(t){E.IsNullOrUndefined(t)||this.setProperty(m.showlabel,String(t))}isAvailableForPhoneSettable(){return this.IsAllowedUBCForAvailableOnPhone()}isVisibleSettable(){return this.IsAllowedUBCForVisibleByDefault()}getProcessedValue(t){let r=this.getProperty(t);return E.IsNullOrUndefined(r)||this.getProperty(t)==="true"}get readonly(){let t=this.getFirstChild(v.formControl);return t?t.disabled:!1}set readonly(t){let r=this.getFirstChild(v.formControl);r&&(r.disabled=t)}get allowfilteroff(){let t=this.getFirstChild(v.formControl);if(t)return t.getParam(m.AllowFilterOff)==="true"}set allowfilteroff(t){let r=this.getFirstChild(v.formControl);r&&!this.IsUnboundControl&&r.setParameter(m.AllowFilterOff,t)}get autoresolve(){let t=this.getFirstChild(v.formControl);if(t)return t.getParam(m.AutoResolve)==="true"}set autoresolve(t){let r=this.getFirstChild(v.formControl);r&&!this.IsUnboundControl&&r.setParameter(m.AutoResolve,t)}get defaultviewid(){let t=this.getFirstChild(v.formControl);return t?t.getParam(m.DefaultViewId):T.EmptyString}set defaultviewid(t){let r=this.getFirstChild(v.formControl);r&&!this.IsUnboundControl&&r.setParameter(m.DefaultViewId,t)}get dependentattributename(){let t=this.getFirstChild(v.formControl);return t?t.getParam(m.DependentAttributeName):T.EmptyString}set dependentattributename(t){let r=this.getFirstChild(v.formControl);r&&!this.IsUnboundControl&&r.setParameter(m.DependentAttributeName,t)}get dependentattributetype(){let t=this.getFirstChild(v.formControl);return t?t.getParam(m.DependentAttributeType):T.EmptyString}set dependentattributetype(t){let r=this.getFirstChild(v.formControl);r&&!this.IsUnboundControl&&r.setParameter(m.DependentAttributeType,t)}get disablequickfind(){let t=this.getFirstChild(v.formControl);if(t)return t.getParam(m.DisableQuickFind)==="true"}set disablequickfind(t){let r=this.getFirstChild(v.formControl);r&&!this.IsUnboundControl&&r.setParameter(m.DisableQuickFind,t)}get disableviewpicker(){let t=this.getFirstChild(v.formControl);if(t)return t.getParam(m.DisableViewPicker)==="true"}set disableviewpicker(t){let r=this.getFirstChild(v.formControl);r&&!this.IsUnboundControl&&r.setParameter(m.DisableViewPicker,t)}get filterrelationshipname(){let t=this.getFirstChild(v.formControl);return t?t.getParam(m.FilterRelationshipName):T.EmptyString}set filterrelationshipname(t){let r=this.getFirstChild(v.formControl);r&&!this.IsUnboundControl&&r.setParameter(m.FilterRelationshipName,t)}get availableviewids(){let t=this.getFirstChild(v.formControl);return t?t.getParam(m.AvailableViewIds):T.EmptyString}set availableviewids(t){let r=this.getFirstChild(v.formControl);r&&!this.IsUnboundControl&&r.setParameter(m.AvailableViewIds,t)}get IsUnboundControl(){let t=this.getFirstChild(v.formControl);if(t&&t.ClassId){let r=$e.getUniqueIdentifierForControl(t);return!E.IsNullOrUndefined(r)&&$e.isUnboundFormControlByIdentifier(r)}else return!1}IsAllowedUBCForAvailableOnPhone(){let t=this.getFirstChild(v.formControl);if(t){let n=$e.getUniqueIdentifierForControl(t).guidString,i=n===R.GridControl||n===R.TimeLineControl||n===R.TimeLineControlUC;return this.IsUnboundControl?i:!0}return this.NodeName===v.formSection||this.NodeName===v.formTab}IsAllowedUBCForVisibleByDefault(){let t=this.getFirstChild(v.formControl);if(t){let n=$e.getUniqueIdentifierForControl(t).guidString,i=n===R.MapsControl||n===R.WebResourceHtmlControl||n===R.WebResourceImageControl||n===R.IframeControl||n===R.SocialInsightControl;return this.IsUnboundControl?i:!0}else return!0}get events(){let t=this.getChildren(v.formEvents);return t.length===1?t[0].getAllChildren():[]}addEvent(t){this.addGrandChild(v.formEvents,t)}getUsedNodeNameSet(t){return null}getHighestIndexById(t,r){return null}}});var la,$f=I(()=>{"use strict";ot();K();Qe();la=class extends j{constructor(t,r){super(v.dependency,t),T.IsNullOrEmpty(r)||this.setDefaultProperties(r)}set id(t){this.setProperty(m.id,t)}get id(){return this.getProperty(m.id)}setDefaultProperties(t){this.id=t}}});var jD,ua,qf=I(()=>{"use strict";Le();$f();K();Qe();Nn();(function(e){e[e.Form=0]="Form",e[e.Cell=1]="Cell",e[e.Tab=2]="Tab",e[e.Control=3]="Control"})(jD||(jD={}));ua=class extends st{constructor(t,r){super(v.formEvent,t),r&&(this.eventName=r,this.application="false",this.active="false")}set eventName(t){this.setProperty(m.Name,t)}get eventName(){return this.getProperty(m.Name)}set application(t){this.setProperty(m.application,t)}get application(){return this.getProperty(m.application)}set attribute(t){this.setProperty(m.EventAttribute,t)}get attribute(){return this.getProperty(m.EventAttribute)}set relationship(t){this.setProperty(m.Relationship,t)}get relationship(){return this.getProperty(m.Relationship)}set control(t){this.setProperty(m.Control,t)}get control(){return this.getProperty(m.Control)}set active(t){this.setProperty(m.EventActive,t)}get active(){return this.getProperty(m.EventActive)}getAllHandlers(){let t=this.getChildren(v.EventHandlers);return t&&t.length?t[0].getChildren(v.handler):[]}getAllDependencies(){let t=this.getChildren(v.formDependencies);return t.length===0?[]:t[0].getAllChildren()}setDependencies(t){let r=this.getFirstChild(v.formDependencies);if(E.IsNullOrUndefined(r)){if(t.length===0)return;this.addChild(new j(v.formDependencies,this)),r=this.getFirstChild(v.formDependencies)}if(t.length===0)r.getParentNode().deleteChild(r);else{r.deleteAllChildren();for(let n of t)r.addChild(new la(r,n.toString()))}}}});var ar,Ho=I(()=>{"use strict";Ue();wo();Le();Hn();K();Qe();rr();ar=class extends j{previewVersion;constructor(t){super(v.formControl,t)}updatePreview(){this.previewVersion=Date.now()}get ClassId(){let t=this.getProperty(m.classid);return t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new P(t)}set ClassId(t){this.setProperty(m.classid,`{${t.ToString()}}`)}get dataFieldName(){return this.getProperty(m.datafieldname)}set dataFieldName(t){this.setProperty(m.datafieldname,t)}set id(t){this.setProperty(m.id,t)}get id(){return this.getProperty(m.id)}get UniqueId(){let t=this.getProperty(m.uniqueid);return E.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new P(t))}set UniqueId(t){this.setProperty(m.uniqueid,`{${t.ToString()}}`)}get isRequired(){return this.getProperty(m.isRequired)==="true"}set isRequired(t){E.IsNullOrUndefined(t)||this.setProperty(m.isRequired,String(t))}get disableMru(){return this.getParam(m.DisableMru)==="true"}set disableMru(t){E.IsNullOrUndefined(t)||this.setParameter(m.DisableMru,t)}get useMFDForCreate(){return this.getParam(m.UseMFDForCreate)==="true"}set useMFDForCreate(t){E.IsNullOrUndefined(t)||this.setParameter(m.UseMFDForCreate,t)}get useMFDForEdit(){return this.getParam(m.UseMFDForEdit)==="true"}set useMFDForEdit(t){E.IsNullOrUndefined(t)||this.setParameter(m.UseMFDForEdit,t)}get disabled(){return this.getProperty(m.disabled)==="true"}set disabled(t){E.IsNullOrUndefined(t)||this.setProperty(m.disabled,String(t))}get indicationOfSubgrid(){return this.getProperty(m.indicationOfSubgrid)==="true"}set indicationOfSubgrid(t){this.setProperty(m.indicationOfSubgrid,String(t))}getAllParameters(){let t=new ft,r=this.getFirstChild(m.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=(jr.StartTag+r).toString(),a=this.parametersNode;if(a){let o=a.findFirst(s=>s&&s.getNodeName()===t);if(o)if(n){this.deleteFirstGrandChildOfName(v.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)===jr.StartTag?a.substring(1):a}}}return null}get parametersNode(){let t=this.getChildren(m.parameters);return t.length===0?null:t[0]}async serializeParameters(t,r){let n=new ft;switch(this.ClassId.guidString.toUpperCase()){case S.LookupControl:if(t&&t.getKeys())if(t.getKeys().forEach(o=>{n.add(o,this.getParam(o))}),t&&t.containsKey("DefaultViewId")){let o=this.getParam("DefaultViewId").replace("{","").replace("}","");n.upsert("DefaultViewId",o)}else{let o=this.getParent(),s=await r.formModelService.lookupControlService.populateDefaultView(this,o.getParentForm().entityName);s&&s.id&&n.upsert("DefaultViewId",s.id.replace("{","").replace("}",""))}break;default:t&&t.getKeys()&&t.getKeys().forEach(o=>{n.add(o,this.getParam(o))});break}let i=n.getInternalObject(),a=[];for(let o in i)i.hasOwnProperty(o)&&a.push({Name:o,Value:i[o]});return a}getIsUnbound(){return this.getProperty(m.isUnbound)==="true"}getAttributeTypeFromClassId(t){if(t)switch(t.toUpperCase()){case S.BooleanControl:case S.CheckboxControl:return 0;case S.DateTimeControl:return 2;case S.DecimalControl:return 3;case S.FloatingNumberControl:return 4;case S.IntegerControl:case S.DurationControl:case S.LanguageControl:case S.TimezoneControl:return 5;case S.LookupControl:return 6;case S.CurrencyControl:return 8;case S.PartyListControl:return 10;case S.ChoiceControl:case S.RelationshipRoleChoiceControl:return 11;case S.ChoiceStatusControl:return 13;case S.TextAreaControl:case S.TextboxControl:case S.LabelControl:case S.EmailAddressControl:case S.UrlControl:case S.TickerControl:case S.ButtonControl:case S.PhoneNumberControl:return 14;case S.ChoicesControl:return 24;default:return}return 14}async toJSON(t){let r=this.getParent(),n=t&&t.formModelService&&t.formModelService.getFormType()===Be.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 ca,Vf=I(()=>{"use strict";ot();Gi();Ho();K();Qe();ca=class extends ar{constructor(t){super(t)}get targetEntityType(){return this.getParam(m.targetEntityType)||T.EmptyString}set targetEntityType(t){this.setParameter(m.targetEntityType,t)}get viewId(){return T.StripBraces(this.getParam(m.viewId))||T.EmptyString}set viewId(t){this.setParameter(m.viewId,T.AddBraces(t))}get viewIds(){return this.getParam(m.viewIds)||T.EmptyString}set viewIds(t){this.setParameter(m.viewIds,t)}get relationshipName(){return this.getParam(m.RelationshipName)||T.EmptyString}set relationshipName(t){this.setParameter(m.RelationshipName,t)}get isUserView(){return T.IsStrictTrue(this.getParam(m.isUserView))}set isUserView(t){this.setParameter(m.isUserView,t.toString())}get enableViewPicker(){return T.IsStrictTrue(this.getParam(m.enableViewPicker))}set enableViewPicker(t){this.setParameter(m.enableViewPicker,t)}get autoExpand(){return this.getParent().autoexpand&&this.getParam(m.autoExpand)===m.Auto}set autoExpand(t){let r=this.getParent();this.setParameter(m.autoExpand,t?m.Auto:m.Fixed),r.autoexpand=t}get recordsPerPage(){return this.getParam(m.recordsPerPage)?Number(this.getParam(m.recordsPerPage)):Number(m.RecordsPerPageRAControlDefault)}set recordsPerPage(t){this.setParameter(m.recordsPerPage,String(t))}get enableQuickFind(){return T.IsStrictTrue(this.getParam(m.enableQuickFind))}set enableQuickFind(t){this.setParameter(m.enableQuickFind,t)}get teamTemplateId(){return T.StripBraces(this.getParam(m.teamTemplateId))||T.EmptyString}set teamTemplateId(t){this.setParameter(m.teamTemplateId,T.AddBraces(t))}get chartId(){return this.getParam(m.visualizationId)||T.EmptyString}set chartId(t){this.setParameter(m.visualizationId,t)}get enableChartPicker(){return T.IsStrictTrue(this.getParam(m.enableChartPicker))}set enableChartPicker(t){this.setParameter(m.enableChartPicker,t)}get chartGridMode(){switch(this.getParam(m.chartGridMode)){case Bt.Chart:return Bt.Chart;case Bt.Grid:return Bt.Grid;default:return Bt.All}}set chartGridMode(t){this.setParameter(m.chartGridMode,t)}updateChartGridMode(t){t?this.chartGridMode=Bt.Chart:this.chartGridMode=this.enableChartPicker?Bt.All:Bt.Grid}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case m.targetEntityType:n.getAllChildren()[0].setNodeName("<"+r.targetEntityType);break;case m.viewId:n.getAllChildren()[0].setNodeName("<"+T.AddBraces(r.viewId));break;case m.isUserView:n.getAllChildren()[0].setNodeName("<"+r.isUserView);break;case m.enableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.enableViewPicker);break;case m.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(mt.dataset)?n[i].getParameters().get(mt.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 da,Gf=I(()=>{"use strict";ot();Gi();Ho();K();da=class extends ar{constructor(t){super(t)}get defaultViewId(){return T.StripBraces(this.getParam(m.DefaultViewId))||T.EmptyString}set defaultViewId(t){this.setParameter(m.DefaultViewId,T.AddBraces(t))}get autoResolve(){return T.IsStrictTrue(this.getParam(m.AutoResolve))}set autoResolve(t){this.setParameter(m.AutoResolve,t)}get disableQuickFind(){return T.IsStrictTrue(this.getParam(m.DisableQuickFind))}set disableQuickFind(t){this.setParameter(m.DisableQuickFind,t)}get disableViewPicker(){return T.IsStrictTrue(this.getParam(m.DisableViewPicker))}set disableViewPicker(t){this.setParameter(m.DisableViewPicker,t)}get allowFilterOff(){return T.IsStrictTrue(this.getParam(m.AllowFilterOff))}set allowFilterOff(t){this.setParameter(m.AllowFilterOff,t)}get disableMru(){return T.IsStrictTrue(this.getParam(m.DisableMru))}set disableMru(t){this.setParameter(m.DisableMru,t)}get dependentAttributeName(){return this.getParam(m.DependentAttributeName)||T.EmptyString}set dependentAttributeName(t){this.setParameter(m.DependentAttributeName,t)}get dependentAttributeType(){return this.getParam(m.DependentAttributeType)||T.EmptyString}set dependentAttributeType(t){this.setParameter(m.DependentAttributeType,t)}get filterRelationshipName(){return this.getParam(m.FilterRelationshipName)||T.EmptyString}set filterRelationshipName(t){this.setParameter(m.FilterRelationshipName,t)}get availableViewIds(){return this.getParam(m.AvailableViewIds)||T.EmptyString}set availableViewIds(t){this.setParameter(m.AvailableViewIds,t)}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case m.datafieldname:case m.bindAttribute:n.getAllChildren()[0].setNodeName("<"+r.dataFieldName);break;case m.DefaultViewId:n.getAllChildren()[0].setNodeName("<"+T.AddBraces(r.defaultViewId));break;case m.AllowFilterOff:n.getAllChildren()[0].setNodeName("<"+r.allowFilterOff);break;case m.DisableQuickFind:n.getAllChildren()[0].setNodeName("<"+r.disableQuickFind);break;case m.DisableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.disableViewPicker);break;case m.FilterRelationshipName:n.getAllChildren()[0].setNodeName("<"+r.filterRelationshipName);break;case m.DependentAttributeName:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeName);break;case m.DependentAttributeType:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeType);break;case m.AvailableViewIds:n.getAllChildren()[0].setNodeName("<"+r.availableViewIds);break;case m.DisableMru:n.getAllChildren()[0].setNodeName("<"+r.disableMru);break;case m.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(mt.value)?n[i].getParameters().get(mt.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 HD,zf,Nt,Qo=I(()=>{"use strict";HD=se(WD());Nn();K();Le();Ue();qf();Ho();Vl();Xp();_p();rr();Hn();$i();Vf();Gf();Wf();Do();zf="_",Nt=class e extends st{fieldPlaceholder;fieldRequiredLevel;isNewField;cellColType;dependentFields=[];constructor(t){super(v.formCell,t),this.isNewField=!1}get cellType(){return this.cellColType}set cellType(t){this.cellColType=t}setDefaultProperties(t){this.showlabel=t,this.isLocked=!1,E.IsNullOrUndefined(this.getProperty(m.id))&&(this.id=new P(P.NewGuid()))}addControl(t,r,n,i,a,o,s){n instanceof ar?this.addChild(n):n instanceof P&&this.addChild(this.getControlWithControlSpecificProperties(t,r,n,i,a,o,s))}removeControl(){return this.deleteChild(this.control)>=0}get isIndependent(){if(!E.IsNullOrUndefined(this.control))return E.IsNullOrUndefined(this.control.dataFieldName)?E.IsNullOrUndefined(this.control.id)?!0:!Jn.dependencyFieldCount.containsKey(this.control.id):!Jn.dependencyFieldCount.containsKey(this.control.dataFieldName)}createOnLoadEvent(){this.addEvent(new ua(this,yo.onLoad))}get dependencies(){let t=this.getChildren(v.formEvents);for(let r of t){let n=r.getChildren(v.formEvent);for(let i of n)this.buildDependencyList(i,this.dependentFields)}return this.dependentFields}getNextAvailableControlName(t,r,n,i){let a;if(i&&_l[i])a=_l[i].replace(/ /g,zf)+zf;else{a="Control_";let u=new Error("Control class id does not exist or is undefined");(0,HD.trackErrorTrace)(pt,{eventName:`${qb}/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,m.isUnbound,"true"),e.prototype.setProperty.call(t,m.isRequired,"false")}getControlWithControlSpecificProperties(t,r,n,i,a,o,s){let l;a===qt.Grid?(l=new ca(this),l.indicationOfSubgrid=!0):a===qt.Lookup?l=new da(this):l=new ar(this);let u=n.guidString,c=o||this.getNextAvailableControlName(t,i,this.getUsedNodeNameSet(t),u);if(e.prototype.setProperty.call(l,m.id,c),l.ClassId=n,!E.IsNullOrUndefined(s)&&(l.UniqueId=s),!o&&r)this.getUnboundControlProperties(l);else{let d=$e.getUniqueIdentifierForControl(l);E.IsNullOrUndefined(d)||($e.getControlDataTypeByControlOrUniqueId(d)===q.QuickFormCollectionControl||!$e.isUnboundFormControlByIdentifier(d)?a!==qt.Grid&&o&&u!==S.IframeControl&&u!==S.SubgridControl&&u!==S.ReferencePanelSubgridControl&&(l.dataFieldName=o,e.prototype.setProperty.call(l,m.disabled,"false")):(this.rowspan=$e.GetRowSpan(l),($e.getControlDataTypeByControlOrUniqueId(d)===q.NotesControl||$e.getControlDataTypeByControlOrUniqueId(d)===q.TimeLineControl)&&(e.prototype.setProperty.call(l,m.disabled,"false"),l.id=q.NotesControl)),($e.getUnboundControlNameFromIdentifier(n)===q.SubGridControl||$e.getUnboundControlNameFromIdentifier(n)===q.NotesControl||$e.getUnboundControlNameFromIdentifier(n)===q.TimeLineControl)&&(this.availableforphone=!0))}return l}buildDependencyList(t,r){if(E.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(m.id);o.getNodeName()===v.dependency&&s?r.push(s):this.buildDependencyList(o,r)}}}get control(){return this.getFirstChild(v.formControl)}set rowspan(t){this.setProperty(m.rowspan,String(t))}get rowspan(){let t=this.getProperty(m.rowspan);return E.IsNullOrUndefined(t)?1:parseInt(t,10)}set autoexpand(t){this.setProperty(m.auto,String(t))}get autoexpand(){return this.getProperty(m.auto)==="true"}set colspan(t){let r=Number(Qp.ONE_COLUMN),n=Number(Qp.FOUR_COLUMN);E.IsNullOrUndefined(t)||t>n||t<r||this.setProperty(m.colspan,String(t))}get colspan(){let t=this.getProperty(m.colspan);return E.IsNullOrUndefined(t)?1:parseInt(t,10)}getParentRow(){return this.getAncestor(v.formRow)}getParentSection(){return this.getAncestor(v.formSection)}getParentTab(){return this.getAncestor(v.formTab)}getParentForm(){return this.getAncestor(v.form)}isInHeader(){let t=this.getAncestor(v.formHeader);return!E.IsNullOrUndefined(t)}isInFooter(){let t=this.getAncestor(v.formFooter);return!E.IsNullOrUndefined(t)}isEmpty(){return E.IsNullOrUndefined(this.control)&&!this.IsUserSpacer}getHeaderFooter(){return this.isInHeader()?this.getAncestor(v.formHeader):this.isInFooter()?this.getAncestor(v.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(m.userspacer);return E.IsNullOrUndefined(t)?!1:t==="true"}SetUserSpacer(){this.setProperty(m.userspacer,"true")}ClearUserSpacer(){this.setProperty(m.userspacer,"false")}get columns(){let t=this.getProperty(m.columnName);return E.IsNullOrUndefined(t)?null:parseInt(t,10)}getColumnLayoutValue(t){let r;switch(t){case Se.TWO_COLUMN:r="11";break;case Se.THREE_COLUMN:r="111";break;case Se.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(!E.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();E.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===Kn.ApplicationRequired||o===Kn.SystemRequired)&&!a||this.isCellLockedByExternal(t)&&!a)return!0}}return!1}getRequiredLevel(t){return!this.control?.dataFieldName||!this.control?.id||this.IsNewField||!this.control?.ClassId?Kn.None:t.getEntityAttributeByName(this.control.dataFieldName)?.requiredLevel?.toString()??Kn.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()===v.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()===v.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)===zf&&(r++,n=parseInt(t.substr(r,t.length-r),10)),n}}});var pa,jf=I(()=>{"use strict";ot();K();Qe();pa=class extends j{isInternal;constructor(t,r,n,i){super(v.library,t),this.isInternal=!!i,T.IsNullOrEmpty(n)||(this.name=r,this.libraryUniqueId=n)}get libraryUniqueId(){let t=this.getProperty(m.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(m.libraryUniqueId,t)}get name(){return this.getProperty(m.libraryName)}set name(t){this.setProperty(m.libraryName,t)}get displayName(){return this.getProperty(m.displayName)}set displayName(t){this.setProperty(m.displayName,t)}get description(){return this.getProperty(m.description)}set description(t){this.setProperty(m.description,t)}}});var ri,Hf=I(()=>{"use strict";Le();Qo();K();Qe();ri=class extends j{isRowAddedOnDragOver;constructor(t){super(v.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 E.IsNullOrUndefined(t)?!1:this.deleteChild(t)>=0}insertCellAtIndex(t,r){return E.IsNullOrUndefined(t)?!1:(this.insertChildAtIndex(t,r),!0)}isEmpty(){return!this.cells||this.cells.every(t=>t.isEmpty())}getParentSection(){return this.getAncestor(v.formSection)}insertPaddingCellAtIndex(t){let r=new Nt(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(v.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 u9(e){switch(e){case Yn.Left:return Zn.Left;case Yn.Right:return Zn.Right;case Yn.Center:return Zn.Center;default:return Zn.Left}}function c9(e){switch(e){case ji.Left:return Qi.Left;case ji.Top:return Qi.Top;default:return Qi.Left}}function QD(e){switch(e){case 1:return 1;case 2:return 11;case 3:return 111;case 4:return 1111;default:return 1}}var d9,Cr,Jo=I(()=>{"use strict";Kp();Ue();Le();ot();Bf();Qo();K();rr();Nn();Hf();d9=115,Cr=class e extends st{colSpan=1;constructor(t,r){super(t,r)}getSectionType(){let t;switch(this.columns){case 1:t=Se.ONE_COLUMN;break;case 11:t=Se.TWO_COLUMN;break;case 111:t=Se.THREE_COLUMN;break;case 1111:t=Se.FOUR_COLUMN;break;default:t=this.colSpan-1}return t}setUniqueName(){let t=this.getParentTab(),r=we.namePrefix;if(t){let n=t.Name,i=t.TotalSectionsCount+1;r=n+we.namePrefix+i.toString()}else r+=Math.floor(Math.random()*1e3);this.setProperty(m.Name,r)}initializeDefaultProperties(t,r,n){if(n===Se.REFERENCE_PANEL){this.addProperty(m.rowheight,"25");let i=`${we.referencePanelNamePrefix}${P.NewGuid()}${we.namePrefix}`;this.addProperty(m.Name,i)}else this.setUniqueName();if(this.addProperty(m.id,new P(P.NewGuid()).guidString),this.addProperty(m.IsUserDefined,we.IsUserDefined),this.addProperty(m.locklevel,we.LockLevel),this.addProperty(m.showlabel,we.ShowLabel),this.addProperty(m.showbar,we.ShowBar),this.addProperty(m.layout,we.Layout),this.addProperty(m.Fieldlabelalignment,we.labelAlignment),this.addProperty(m.Fieldlabelposition,we.labelPosition),E.IsNullOrUndefined(n))this.addProperty(m.columnName,we.columns);else{let i=this.getColumnLayoutValue(n);this.addProperty(m.columnName,i)}this.addProperty(m.LabelWidth,we.LabelWidth),this.setDisplayName(r,t)}getColumnLayoutValue(t){let r;switch(t){case Se.TWO_COLUMN:r="11";break;case Se.THREE_COLUMN:r="111";break;case Se.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 E.IsNullOrUndefined(this.columns)?t=this.ColSpan:this.columns.toString().split(T.EmptyString).forEach(r=>{t+=parseInt(r,10)}),t}get ColSpan(){return this.colSpan}initializeRow(t){if(t>0&&t<5){let r=new ri(null);if(this.addGrandChild(v.formRows,r),qD.getConfig().enableAutoInsertionOfCellInRow)for(let n=0;n<t;n++){let i=new Nt(r);i.setDefaultProperties(!1),r.addCell(i)}}}initialize(t,r,n){this.initializeDefaultProperties(t,r,n),n===Se.REFERENCE_PANEL&&(n=Se.ONE_COLUMN),this.initializeRow(n+1)}setColSpan(t){this.colSpan=t}appendRow(t){this.addGrandChild(v.formRows,t)}insertRowAtIndex(t,r){this.addGrandChildAtIndex(v.formRows,t,r)}insertRowsAtIndex(t,r){if(t&&t.length>0)for(let n=0;n<t.length;n++)this.addGrandChildAtIndex(v.formRows,t[n],r+n)}indexOfRow(t){return this.rows.indexOf(t)}deleteRow(t){return this.deleteFirstGrandChildOfName(v.formRows,t)}deleteRows(t,r){this.deleteGrandChildren(v.formRows,t,r)}get rows(){return this.getRows()}getRows(){let t=this.getChildren(v.formRows);return t.length===0?[]:t[0].getChildren(v.formRow)}get columns(){let t=this.getProperty(m.columnName),r=E.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 QD(n)}return r}set columns(t){E.IsNullOrUndefined(t)||this.setProperty(m.columnName,String(t))}get rowHeight(){let t=this.getProperty(m.rowheight);return E.IsNullOrUndefined(t)?null:parseInt(t,10)}set rowHeight(t){this.setProperty(m.rowheight,String(t))}set autoexpand(t){this.setProperty(m.autoExpand.toLowerCase(),String(t))}get autoexpand(){return this.getProperty(m.autoExpand.toLowerCase())==="true"}get isUserDefined(){return+this.getProperty(m.IsUserDefined)!=0}set isUserDefined(t){t?this.setProperty(m.IsUserDefined,"1"):this.setProperty(m.IsUserDefined,"0")}getParentColumn(){return this.getAncestor(v.formColumn)}getParentTab(){return this.getAncestor(v.formTab)}get hasMultiColumnRow(){return this.getColumnCountValue()>1}get showlabel(){return this.getProperty(m.showlabel)==="true"}set showlabel(t){E.IsNullOrUndefined(t)||this.setProperty(m.showlabel,String(t))}get fieldLabelAlignment(){let t=we.labelAlignment,r=this.getProperty(m.Fieldlabelalignment);return E.IsNullOrUndefined(r)?t:r}set fieldLabelAlignment(t){E.IsNullOrUndefined(t)||this.setProperty(m.Fieldlabelalignment,t)}get fieldLabelPosition(){let t=this.getProperty(m.Fieldlabelposition);return E.IsNullOrUndefined(t)?we.labelPosition:t}set fieldLabelPosition(t){E.IsNullOrUndefined(t)||this.setProperty(m.Fieldlabelposition,String(t))}get showbar(){return this.getProperty(m.showbar)==="true"}set showbar(t){E.IsNullOrUndefined(t)||this.setProperty(m.showbar,String(t))}get labelwidth(){let t=+this.getProperty(m.LabelWidth);return t===0?d9:t}set labelwidth(t){E.IsNullOrUndefined(t)||t>283&&t<57||this.setProperty(m.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:u9(this.fieldLabelAlignment),Position:c9(this.fieldLabelPosition)},Columns:QD(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()===v.formSection){let i=n;i.Name&&!T.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}isReferencePanelSection(){return!E.IsNullOrUndefined(this)&&!E.IsNullOrUndefined(this.Name)&&this.Name.indexOf(we.referencePanelNamePrefix)===0}getAllMultiRowCells(){return this.findAll(t=>{if(t.getNodeName()===v.formCell){let r=t;return!r.isEmpty()&&r.rowspan>1}return!1})}isHeaderOrFooterSection(){return this.NodeName===v.formFooter||this.NodeName===v.formHeader}}});var Dn,au=I(()=>{"use strict";K();Qe();Jo();Dn=class e extends j{constructor(t){super(v.formColumn,t)}initializeDefaultProperties(t){this.addProperty(m.width,t.toString()+"%")}insertSectionAtIndex(t,r){this.addGrandChildAtIndex(v.formSections,t,r)}static createAndInitNewSection(t,r,n){let i=new Cr(v.formSection,null);return i.initialize(t,r,n),i}addSectionAtIndex(t,r){this.addGrandChildAtIndex(v.formSections,t,r)}initialize(t,r,n,i=Se.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(v.formTab)}get sections(){let t=this.getChildren("sections");return t.length!==1?[]:t[0].getChildren(v.formSection)}get width(){return this.getProperty(m.width)}set width(t){this.setProperty(m.width,t)}deleteSection(t){return this.deleteFirstGrandChildOfName(v.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(m.Name),Id:this.getProperty(m.id),Label:null,ShowLabel:!1,Visible:!0,LabelId:null,PreviewId:this.getProperty(m.id),Sections:await this.getSectionsJSON(t),Width:this.width}}}});var ou,JD=I(()=>{"use strict";Ue();K();rr();Jo();ou=class extends Cr{initializeNavArea(t,r,n){this.initializeNavAreaProps(t,r,n)}get AreaName(){return this.Name}initializeNavAreaProps(t,r,n){this.addProperty(m.Name,n),this.addProperty(m.id,new P(P.NewGuid()).guidString),this.addProperty(m.columnName,we.columns),this.setDisplayName(r,t)}}});var su,XD=I(()=>{"use strict";au();K();JD();su=class extends Dn{addAndIntializeNavBarSection(t,r,n,i){let a=new ou(v.formSection,null);return a.initializeNavArea(t,r,i),this.addGrandChildAtIndex(v.formSections,a,n),a}}});var Qr,lu=I(()=>{"use strict";Ue();Le();ot();au();K();Qe();Nn();Qr=class extends st{tabContainsAutoExpandControl;autoExpandCell;constructor(t,r){super(v.formTab,t),this.tabContainsAutoExpandControl=!1}getParentForm(){return this.getAncestor(v.form)}getTabLayoutType(){let t;switch(this.columns.length){case 1:t=Ce.ONE_COLUMN;break;case 2:if(parseInt(this.columns[0].width,10)===50&&parseInt(this.columns[1].width,10)===50){t=Ce.TWO_COLUMN_EQUAL;break}if(parseInt(this.columns[0].width,10)===67&&parseInt(this.columns[1].width,10)===33){t=Ce.TWO_COLUMN_WIDER_LEFT;break}if(parseInt(this.columns[0].width,10)===34&&parseInt(this.columns[1].width,10)===66){t=Ce.TWO_COLUMN_WIDER_RIGHT;break}t=Ce.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=Ce.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=Ce.THREE_COLUMN_WIDER_MID;break}t=Ce.THREE_COLUMN_CUSTOM_LAYOUT;break;default:}return t}initializeProperties(t,r,n){this.addProperty(m.Name,bn.namePrefix+t.toString()),this.addProperty(m.id,new P(P.NewGuid()).guidString),this.addProperty(m.IsUserDefined,bn.IsUserDefined),this.addProperty(m.locklevel,bn.LockLevel),this.addProperty(m.showlabel,bn.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=Se.ONE_COLUMN,a=!0,o){let s=this.getChildren(v.formColumns)[0],l=[];switch(t){case Ce.ONE_COLUMN:l.push(100);break;case Ce.TWO_COLUMN_EQUAL:l.push(50),l.push(50);break;case Ce.TWO_COLUMN_WIDER_LEFT:l.push(67),l.push(33);break;case Ce.TWO_COLUMN_WIDER_RIGHT:l.push(34),l.push(66);break;case Ce.THREE_COLUMN_EQUAL:l.push(34),l.push(33),l.push(33);break;case Ce.THREE_COLUMN_WIDER_MID:l.push(28),l.push(44),l.push(28);break;default:}for(let u of l){let c=new Dn(s);c.initialize(u,r,n,i),this.addGrandChild(v.formColumns,c)}}initialize(t,r,n,i,a,o=Se.ONE_COLUMN,s=!0,l){this.addChild(new j(v.formColumns,this)),this.initializeProperties(r,n,i),this.initializeColumns(t,n,a,o,s,l)}get columns(){let t=this.getChildren(v.formColumns);return t.length!==1?[]:t[0].getChildren(v.formColumn)}get expanded(){return this.getProcessedValue(m.expanded)}set expanded(t){E.IsNullOrUndefined(t)||this.setProperty(m.expanded,String(t))}get groupName(){return this.getProperty(m.groupName)}get contentType(){return this.getProperty(m.contentType)}set contentType(t){this.setProperty(m.contentType,t)}insertNewColumnAtIndex(t,r,n,i,a){t.initialize(n,i,a),this.addGrandChildAtIndex(v.formColumns,t,r)}insertColumnAtIndex(t,r){this.addGrandChildAtIndex(v.formColumns,t,r)}deleteColumn(t){return this.deleteFirstGrandChildOfName(v.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()===v.formTab){let i=n;i.Name&&!T.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}}});var ni,Qf=I(()=>{"use strict";Ue();K();Qe();rr();XD();lu();ni=class extends Qr{constructor(t,r,n){super(t,Ce.THREE_COLUMN_EQUAL),this.setDisplayName(r,n),this.id=new P(P.NewGuid())}initializeDefaultProps(){this.addChild(new j(v.formColumns,this)),this.initializeFiveColumns()}get columns(){let t=this.getChildren("columns");return t.length!==1?[]:t[0].getChildren(v.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<$l.FIVE_COLUMN;t++){let r=new su(this.getChildren(v.formColumns)[0]);r.initializeDefaultProperties(vw.FiveEqColumn),this.addGrandChild(v.formColumns,r)}}}});function f9(e){switch(e){case Be.Main:return An.Main;case Be.QuickCreate:return An.QuickCreate;case Be.QuickViewForm:return An.Quick;case Be.Dialog:return An.Dialog;default:return An.None}}function m9(e,t){if(t===Be.Main){if(e)switch(e.toLowerCase()){case"low":return yn.Low;case"highreadonlyvalues":return yn.HighReadOnlyValues;default:return yn.HighWithControls}return yn.Low}}var cu,p9,uu,KD=I(()=>{"use strict";Ew();cu=se(Qn());Kp();Le();ot();$i();Bf();K();Gi();hp();Hn();Qo();K();Nn();jf();Qf();lu();p9="1920";uu=class e extends st{_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(v.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 El,this._metadataChangeEvent=new Gl}get FormLibraries(){let t=this.getFirstChild(v.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 Nt).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 Nt){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()===v.internalLibraries),r=[],n="src";return t.length>0&&(r=t.map(i=>{let a=i.GetPropertyByParameter(n).replace("$webresource:",""),o=new pa(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,cu.trackErrorTrace)(Vb,{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 T.IsNullOrEmpty(this.getProperty(m.ShowImage))?!0:this.getProperty(m.ShowImage)!=="false"}set ShowImagecheck(t){t?this.setProperty(m.ShowImage,String(t)):this.setProperty(m.ShowImage,"false")}get ShowNavigation(){return T.IsNullOrEmpty(this.getProperty(m.ShowNavigationbar))?!0:this.getProperty(m.ShowNavigationbar)!=="false"}set ShowNavigation(t){t?this.setProperty(m.ShowNavigationbar,String(t)):this.setProperty(m.ShowNavigationbar,"false")}get MaxWidth(){return T.IsNullOrEmpty(this.getProperty(m.MaxWidth))?p9:this.getProperty(m.MaxWidth)}set MaxWidth(t){this.setProperty(m.MaxWidth,t)}get headerDensityType(){return this.getProperty(m.HeaderDensityType)}set headerDensityType(t){t&&this.formType===Be.Main?this.setProperty(m.HeaderDensityType,t):this.formType!==Be.Main&&this.headerDensityType&&this.removeProperty(m.HeaderDensityType)}IsMainOrQuickCreateForm(){return this.formType===Be.Main||this.formType===Be.QuickCreate}get FormPresentation(){return this._formPresentation}get LanguageCode(){return this._langCode}set LanguageCode(t){this._langCode=t}get header(){let t=this.getChildren(v.formHeader);return t.length!==1?null:t[0]}set header(t){E.IsNullOrUndefined(t)||(this.deleteChild(this.header),this.addChild(t))}getAllDependencies(){return this.getChildren(v.quickFormDependencies).length===0?[]:this.ConvertModelToArray(this.getChildren(v.quickFormDependencies)[0].getAllChildren())}ConvertModelToArray(t){let r=[];return E.IsNullOrUndefined(t)||t.forEach(n=>{r.push(n.id)}),r}get footer(){let t=this.getChildren(v.formFooter);return t.length!==1?null:t[0]}set footer(t){E.IsNullOrUndefined(t)||(this.deleteChild(this.footer),this.addChild(t))}createAndInitNewTab(t,r,n){let i=new Qr(null,t),a=this.getNextTabCounter(this.tabs.length+1);return i.initialize(t,a,this.LanguageCode,r,n),i}addTabAtIndex(t,r){this.addGrandChildAtIndex(v.formTabs,t,r)}createAndInitNewTabWithMarginalControl(t,r,n,i,a){let o=new Qr(null,Ce.ONE_COLUMN),s=this.getNextTabCounter(this.tabs.length+1);o.initialize(Ce.ONE_COLUMN,s,this.LanguageCode,r,n,a,!1),this.addGrandChildAtIndex(v.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===bn.namePrefix+t.toString())return this.getNextTabCounter(t+1);return t}get allTabs(){let t=this.getChildren(v.formTabs);return t.length!==1?[]:t[0].getChildren(v.formTab)}get CanvasNavigationTab(){if(this.tabs.length>0){let t=this.tabs[this.tabs.length-1];if(t instanceof ni)return t}return null}get NavigationNode(){let t=this.getChildren(v.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(v.formTabs,t)}insertTabAtIndex(t,r){this.addGrandChildAtIndex(v.formTabs,t,r)}insertRelatedTab(t){let r=this.getAllGrandChildren(v.formTabs);if(!E.IsNullOrUndefined(r)){let n=r.length;this.insertTabAtIndex(t,n)}}get isfooterPresent(){return this.getChildren(v.formFooter).length>0}get displayCondition(){let t=this.getChildren(v.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(v.formTabs).indexOf(t)}get ControlDescriptions(){return this.getAllGrandChildren(v.controlDescriptions)}addControlDescriptionNode(t){this.addGrandChild(v.controlDescriptions,t)}deleteControlDescByForControlId(t){let r=this.getControlDescriptionByForControl(t);E.IsNullOrUndefined(r)||this.deleteFirstGrandChildOfName(v.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 Nt))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 Nt&&i.control&&t.control&&a&&i.control.dataFieldName===t.control.dataFieldName})}isCellEditableGridControl(t){return!t?.control?.indicationOfSubgrid||t.control.ClassId.guidString.toUpperCase()!==S.CustomControl?!1:this.cellHasCustomControlWithName(t,wn.EditableGridControl)||VD.getConfig()?.enableOneGridEventsForFormDesigner&&this.cellHasCustomControlWithName(t,wn.PowerAppsOneGrid)}isCellCanvasAppControl(t){return t?.control?.ClassId.guidString.toUpperCase()===S.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()===v.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 ni)){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,cu.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===Be.Main?{HeaderDensity:m9(this.headerDensityType,this.formType)}:{},InlineEditGridRow:[],InlineQuickForms:[],QuickFormEntities:[],EventHandlers:[],LinkControlSections:[],FormType:f9(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 du,Jf,YD=I(()=>{"use strict";Ue();Le();K();Qe();Nn();du=class extends st{constructor(t){super(v.formDisplayConditions,t)}get Order(){let t=this.getProperty(m.Order);return E.IsNullOrUndefined(t)?null:parseInt(t,10)}set Order(t){this.setProperty(m.Order,t.toString())}get FallbackForm(){return this.getProperty(m.FallbackForm)==="true"}set FallbackForm(t){this.setProperty(m.FallbackForm,t.toString())}addRoles(t){this.deleteAllChildren();for(let r=0;r<t.length;r++)this.addChild(t[r])}isRoleEveryone(){return!!(this.getChildren(v.formEveryOne)&&this.getChildren(v.formEveryOne)[0])}setRoleEveryone(){this.deleteAllChildren(),this.addChild(new Jf(this))}},Jf=class extends j{constructor(t){super(v.formEveryOne,t)}}});var pu,ZD=I(()=>{"use strict";K();Qe();pu=class extends j{constructor(t,r){super(v.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(m.HandlerUniqueId)}set HandlerUniqueID(t){this.setProperty(m.HandlerUniqueId,t)}get FunctionName(){return this.getProperty(m.functionName)}set FunctionName(t){this.setProperty(m.functionName,t)}get LibraryName(){return this.getProperty(m.libraryNameEventHandler)}set LibraryName(t){this.setProperty(m.libraryNameEventHandler,t)}get Enabled(){return this.getProperty(m.enabledForField)}set Enabled(t){this.setProperty(m.enabledForField,t)}get PassExecutionContext(){return this.getProperty(m.passExecutionContext)}set PassExecutionContext(t){this.setProperty(m.passExecutionContext,t)}get Parameters(){return this.getProperty(m.parameters)}set Parameters(t){this.setProperty(m.parameters,t)}}});var fa,Xf=I(()=>{"use strict";K();Jo();fa=class extends Cr{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(v.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 Xo,e2=I(()=>{"use strict";K();Xf();Xo=class extends fa{_customFooter;constructor(t,r){super(v.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 Ko,t2=I(()=>{"use strict";K();Xf();Ko=class extends fa{_customHeader;constructor(t,r){super(v.formHeader,t),this._customHeader=r}get customHeader(){return this._customHeader}set customHeader(t){this._customHeader=t}get showCommandBar(){return this.getProcessedValue(m.showCommandBar)}set showCommandBar(t){t!=null&&this.setProperty(m.showCommandBar,String(t))}get showBody(){return this.getProcessedValue(m.showBody)}set showBody(t){t!=null&&this.setProperty(m.showBody,String(t))}get showTabNavigator(){return this.getProcessedValue(m.showTabNavigator)}set showTabNavigator(t){t!=null&&this.setProperty(m.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 Dt,ii=I(()=>{"use strict";Ue();ot();K();Nn();Dt=class e extends st{constructor(t,r){super(t,r)}getTitle(t){for(let r of this.getAllTitles())if(+r.getProperty(m.LCID)===t)return r.getProperty(m.text);return null}getAllTitles(){let t=this.getChildren(v.Titles);return t.length===0?[]:t[0].getChildren(v.Title)}setTitle(t,r){for(let i of this.getAllTitles())if(+i.getProperty(m.LCID)===r){i.setProperty(m.text,t);return}let n=new e(v.Title,null);n.setProperty(m.text,t),n.setProperty(m.LCID,String(r)),this.addGrandChild(v.Titles,n)}get Sequence(){return+this.getProperty(m.Sequence)}set Sequence(t){this.setProperty(m.Sequence,t.toString())}get Area(){return this.getProperty(m.Area)}set Area(t){this.setProperty(m.Area,t)}set Id(t){this.setProperty(m.Id,t)}get Id(){return this.getProperty(m.Id)}get id(){return new P(this.Id??"",!0)}set id(t){this.Id=t.guidString}get Show(){return!0}get Icon(){return this.getProperty(m.icon)}set Icon(t){t=t||T.EmptyString,this.setProperty(m.icon,t)}updateCommonProperties(t,r){this.Area=t.Area,this.Sequence=t.Sequence,this.setTitle(t.getDisplayName(r),r)}}});var Yo,r2=I(()=>{"use strict";(function(e){e[e.NavLinkNotAvailable=-1]="NavLinkNotAvailable",e[e.NavLinkIdConflict=-2]="NavLinkIdConflict",e[e.NavBarNotAvailable=-3]="NavBarNotAvailable"})(Yo||(Yo={}))});var fu,n2=I(()=>{"use strict";Le();K();ii();r2();fu=class extends Dt{constructor(t){super(v.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 E.IsNullOrUndefined(r)?Yo.NavLinkNotAvailable:r.length===1?this.deleteChild(r[0]):Yo.NavLinkIdConflict}getRelationShipItemsByArea(t){let r=this.AllRelationShipItems,n=[];for(let i of r)i.Area===t&&i.Show===!0&&n.push(i);return n}getNavBarRelationShipItemsByNavId(t){return this.AllRelationShipItems.filter(n=>n.Id===t)}getNavBarLinkItemById(t){let r=this.AllNavLinkItems.filter(n=>n.Id===t);return r.length>0?r:null}getAllActiveChildrenForGivenArea(t){let r=this.getAllChildren(),n=[];for(let i of r)i.Area===t&&i.Show&&n.push(i);return n}}});var ve,h9,i2,_te,ma,Kf=I(()=>{"use strict";Ue();K();ii();(function(e){e.Info="_NA_Info",e.Sales="_NA_SFA",e.Service="_NA_CS",e.Marketing="_NA_MA",e.InternetMarketing="_NA_IMA",e.ProcessCenter="_NA_PROC",e.Async="_NA_AO"})(ve||(ve={}));h9=new Map([[ve.Info,"Info"],[ve.Sales,"Sales"],[ve.Service,"Service"],[ve.Marketing,"Marketing"],[ve.ProcessCenter,"ProcessCenter"]]),i2=new Map([["Info",ve.Info],["Sales",ve.Sales],["Service",ve.Service],["Marketing",ve.Marketing],["ProcessCenter",ve.ProcessCenter]]),_te=new Map([[ve.Info,9e3],[ve.Sales,9200],[ve.Service,9400],[ve.Marketing,9600],[ve.ProcessCenter,9800],[ve.InternetMarketing,1e4],[ve.Async,10200]]),ma=class extends Dt{constructor(t,r){super(v.formNavBarArea,r)}setDefaultPropertiesByType(t,r,n){this.AreaId=h9.get(t);let i=n?.(`navBarArea.title.${this.AreaId}`)??this.AreaId;this.setTitle(i,r)}get ParentNavigation(){return this.getAncestor(v.formNavigation)}get AreaId(){return this.getProperty(m.Id)}set AreaId(t){this.setProperty(m.Id,t)}get id(){return new P(this.AreaId??"",!0)}set id(t){this.AreaId=t.guidString}async toJSON(t){return{Id:this.AreaId,Titles:[{LCID:t.langCode,Text:this.getTitle(t.langCode)}],PreviewId:this.AreaId}}}});var ha,Yf=I(()=>{"use strict";K();ii();ha=class extends Dt{constructor(t,r){super(v.formNavBarAreas,r)}get AllNavBarAreaItems(){return this.getChildren(v.formNavBarArea)}get ParentNavigation(){return this.getAncestor(v.formNavigation)}addNavBarArea(t){this.addChild(t)}}});var mu,a2=I(()=>{"use strict";Le();K();ii();mu=class extends Dt{RelationshipNameUCIRuntime;constructor(t){super(v.formNavBarByRelationshipItem,t)}get RelationshipName(){return this.getProperty(m.RelationshipName)}set RelationshipName(t){this.setProperty(m.RelationshipName,t)}set Show(t){this.setProperty(m.Show,String(t))}get Show(){let t=this.getProperty(m.Show);return E.IsNullOrUndefined(t)||t==="true"}get TitleResourceId(){return this.getProperty(m.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 hu,o2=I(()=>{"use strict";K();ii();hu=class extends Dt{constructor(t){super(v.formNavBarItem,t)}get Url(){return this.getProperty(m.url)}set Url(t){this.setProperty(m.url,t)}}});var gu,s2=I(()=>{"use strict";Ue();K();Kf();Yf();ii();gu=class extends Dt{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(v.formNavBarAreas)}setDefaultNavBarAreas(t,r){let n=[ve.Info,ve.Sales,ve.Service,ve.Marketing,ve.ProcessCenter];if(this.navBarAreas){let i=this.navBarAreas?.AllNavBarAreaItems;if(i&&i.length>0){let a=new Set(i.map(o=>i2.get(o.AreaId)));n=n.filter(o=>!a.has(o))}}else{let i=new ha(v.formNavBarAreas,this);i.isTransient=!0,this.addChild(i)}return n.length>0?(n.forEach(i=>{let a=new ma(v.formNavBarArea,this.navBarAreas);a.setDefaultPropertiesByType(i,t,r),this.navBarAreas.addNavBarArea(a)}),!0):!1}get navBar(){return this.getFirstChild(v.formNavBar)}get id(){return new P(Ip,!0)}replaceNavAreaToGivenIndex(t,r){this.navBarAreas?.AllNavBarAreaItems.indexOf(r)!==-1&&(this.deleteFirstGrandChildOfName(v.formNavBarAreas,r),this.addGrandChildAtIndex(v.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 l2={};Rr(l2,{ControlType:()=>qt,DeserializationService:()=>tm,DeserializationServiceScope:()=>em,DeserializedFormElementNode:()=>It});var Zf,It,em,qt,tm,Wf=I(()=>{"use strict";Zf=se(Qn());Ue();Le();ot();$i();_p();Hn();Gb();Sw();Vl();KD();Qo();au();Ho();$f();K();K();YD();Qe();rr();qf();ZD();e2();Vf();Gf();t2();jf();Hf();Jo();lu();n2();Kf();Yf();a2();o2();s2();It=class extends j{constructor(t,r){super(t,r)}insertProperty(t,r){this.addProperty(t,r)}insertChild(t){this.addChild(t)}},em="DeserializationService";(function(e){e.Grid="Grid",e.Lookup="Lookup",e.Base="Base"})(qt||(qt={}));tm=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,Zf.trackErrorTrace)(pt,{eventName:em,eventData:{error:f}}),new Error(f)}let p=this.createFormModel(d.item(0),r,n,i,a,o,s,l,u,c);return E.IsNullOrUndefined(p.displayCondition)&&s!==Be.Dialog&&this.appendDefaultDisplayCondition(p),p}upsertFieldCount(t,r){let n=Jn.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(!E.IsNullOrUndefined(t)){let n=E.ParseXml(r);n!==null&&this.populateElementChildren(t,n.childNodes)}}createFormModel(t,r,n,i,a,o,s,l,u,c){let d=new uu(r,n,i,a,o,s,l,u,c);return this.populateElementProperties(d,t.attributes),this.populateElementChildren(d,t.childNodes),s===Be.Main&&(this.insertHeaderFooterElementProperties(v.formHeader,d,d.header),this.insertHeaderFooterElementProperties(v.formFooter,d,d.footer)),d}insertHeaderFooterElementProperties(t,r,n){if(E.IsNullOrUndefined(n)){let i=t===v.formHeader?new Ko(r,!0):new Xo(r,!0);It.prototype.insertProperty.call(i,m.id,"{"+P.NewGuid()+"}"),It.prototype.insertProperty.call(i,m.Fieldlabelposition,"Top"),It.prototype.insertProperty.call(i,m.columnName,we.MarginalControlColumns),It.prototype.insertProperty.call(i,m.LabelWidth,we.LabelWidth),It.prototype.insertProperty.call(i,m.Fieldlabelalignment,"Left");let a=null,o=new ri(a);for(let s=0;s<i.maxColumns;s++){let l=new Nt(o);It.prototype.insertProperty.call(l,m.id,"{"+P.NewGuid()+"}"),l.setDisplayName(T.EmptyString,this.lcid),It.prototype.insertProperty.call(l,m.showlabel,"false"),o.addCell(l)}i.appendRow(o),t===v.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 It(`<${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,Zf.trackErrorTrace)(pt,{eventName:em,eventData:{error:n}}),new Error(n)}for(let n=0;n<r.length;n++){let i=r.item(n);i&&(It.prototype.insertProperty.call(t,i.name,i.value),t.getNodeName()===v.formCell&&i.name===m.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&&It.prototype.insertChild.call(t,a)}}createModelNode(t,r){switch(t.nodeName){case v.form:throw new Error("Form node shouldn't be created using this method");case v.formTab:return new Qr(r);case v.formColumn:return new Dn(r);case v.formHeader:return new Ko(r,!1);case v.formFooter:return new Xo(r,!1);case v.formSection:return new Cr(v.formSection,r);case v.formRow:return new ri(r);case v.formCell:return new Nt(r);case v.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===m.indicationOfSubgrid&&l.value==="true"||l.name===m.classid&&(l.value?.toLocaleUpperCase()===`{${S.SubgridControl}}`||l.value?.toLocaleUpperCase()===`{${S.ReferencePanelSubgridControl}}`))a=qt.Grid;else if(l.name===m.classid&&l.value?.toLocaleUpperCase()===`{${S.LookupControl}}`)a=qt.Lookup;else if(l.name===m.classid&&l.value?.toLocaleUpperCase()===`{${S.CustomControl}}`)for(let u=0;u<i?.length;u++)i[u].nodeName===m.DefaultViewId&&(a=qt.Lookup)}return a===qt.Grid?new ca(r):a===qt.Lookup?new da(r):new ar(r);case v.formEvent:return new ua(r,T.EmptyString);case v.dependency:return this.populateDependencyTable(t),new la(r,T.EmptyString);case v.Handler:let o=[];return new pu(o,r);case v.formNavigation:return new gu(t.nodeName,r);case v.formNavBarArea:return new ma(t.nodeName,r);case v.formNavBarAreas:return new ha(t.nodeName,r);case v.formNavBar:return new fu(r);case v.formNavBarByRelationshipItem:return new mu(r);case v.formNavBarItem:return new hu(r);case v.formDisplayConditions:return new du(r);case v.library:return new pa(r,T.EmptyString,T.EmptyString);case v.controlDescription:return new Pl(r);case v.customControl:return this.populateCustomControlConfigurationId(t),new ql(r);default:return new It(t.nodeName,r)}}populateDependencyTable(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);i.name===m.id&&this.upsertFieldCount(i.value,yr.DependencyFieldTable)}}populateCustomControlConfigurationId(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);if(i.name===m.id){let a=new P(i.value.substr(1,i.value.length-2));for(let o=0;o<t.parentNode.attributes.length;o++){let s=t.parentNode.attributes.item(o);if(s.name===m.ForControl){let l=s.value.substr(1,i.value.length-2);$e.CustomControlIdMap.upsert(l,a);break}}break}}}}});var u2={};Rr(u2,{SerializationService:()=>rm,SerializationServiceScope:()=>g9,SerializedFormElementNode:()=>ga});var g9,ga,rm,c2=I(()=>{"use strict";ot();Qe();rr();Qf();g9="SerializationService",ga=class extends j{fetchNodeName(){return this.getNodeName()}enumerateProperties(){return this.getAllProperties()}enumerateChildren(){return this.getAllChildren()}},rm=class{langCode;constructor(t){this.langCode=t}serializeFormXmlNode(t){let r=ga.prototype.fetchNodeName.call(t);if(r.charAt(0)===jr.StartTag)return T.EscapeXml(r.substr(1),!1);if(t.isTransient&&!t.isDirty())return T.EmptyString;let n=ga.prototype.enumerateProperties.call(t),i=ga.prototype.enumerateChildren.call(t);if(!(t instanceof ni)){let a=`<${r}`;if(n.length!==0&&(a+=` ${this.getPropertiesString(n)}`),i.length===0)a+=" />";else{let o=T.EmptyString;for(let s of i)o+=this.serializeFormXmlNode(s);a+=`>${o}</${r}>`}return a}return T.EmptyString}getPropertiesString(t){let r=T.EmptyString;return t.forEach((n,i)=>{i!==0&&(r+=" "),r+=`${n.key}="${T.EscapeXml(n.value,!0)}"`}),r}}});var In=g(vu=>{"use strict";Object.defineProperty(vu,"__esModule",{value:!0});vu.installDomShim=void 0;var d2=wl(),p2=!1,v9={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 y9(){if(p2)return;let e=globalThis;typeof e.DOMParser>"u"&&(e.DOMParser=d2.DOMParser),typeof e.XMLSerializer>"u"&&(e.XMLSerializer=d2.XMLSerializer),typeof e.Node>"u"&&(e.Node=v9),p2=!0}vu.installDomShim=y9});var P2=g(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.classIdForAttributeType=_t.QUICK_VIEW_CLASS_ID=_t.NOTES_CLASS_ID=_t.SUBGRID_CLASS_ID=_t.formRegistration=_t.FormAdapter=void 0;var Vt=(Ue(),Fr(xb)),b9=(Le(),Fr(Lb)),w9=(Qe(),Fr(Mb)),lt=(K(),Fr(kb)),ke=(Hn(),Fr(Ub)),A9=(Wf(),Fr(l2)),C9=(c2(),Fr(u2)),qe=mn(),f2=Yt(),ai=cr(),S9=qd(),y2=bt(),om=ee(),b2=In(),w2=Ni(),E9={[lt.FormType.Main]:"Main",[lt.FormType.QuickCreate]:"QuickCreate",[lt.FormType.QuickViewForm]:"QuickView",[lt.FormType.Card]:"Card"},nm={Main:lt.FormType.Main,QuickCreate:lt.FormType.QuickCreate,QuickView:lt.FormType.QuickViewForm,Card:lt.FormType.Card},N9=new Map(Object.entries(ke.ControlClassId).map(([e,t])=>[String(t).toUpperCase(),e]));function A2(e){var t;return e&&(t=N9.get(e.toUpperCase()))!==null&&t!==void 0?t:"Unknown"}function Zo(e){return e.getAllProperties().map(t=>[t.key,t.value])}function oi(e){let t=new Map;for(let r of e.getAllProperties())t.has(r.key)||t.set(r.key,r.value);return t}function C2(e,t){return e.getAllChildren().find(r=>r.getNodeName()===t)}function sm(e,t){var r,n;let i=C2(e,"labels");if(!i)return"";let a=i.getAllChildren().filter(s=>s.getNodeName()==="label"),o=(r=a.find(s=>oi(s).get("languagecode")===String(t)))!==null&&r!==void 0?r:a[0];return o&&(n=oi(o).get("description"))!==null&&n!==void 0?n:""}function D9(e){let t=C2(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 S2(e){return/^1+$/.test(e)&&e.length>=1&&e.length<=4?e.length:1}function im(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 am(e){return`{${es(e)}}`}function m2(e,t){if(e===void 0||e==="")return t;let r=Number(e);return Number.isNaN(r)?t:r}function bu(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,qe.rawFromNode)(u)})}),i<0)return{modeled:[],bag:{a:Zo(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,qe.rawFromNode)(u)})}),{modeled:s,bag:{a:Zo(e),c:a,w:{n:o.getNodeName(),a:Zo(o),c:l}}}}function E2(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,qe.rawFromNode)(a)})}),{modeled:n,bag:{a:Zo(e),c:i}}}function I9(e,t){let{modeled:r,bag:n}=bu(e,"tabs","tab");return{tabs:r.map(i=>_9(i,t)),bag:n}}function _9(e,t){var r,n;let i=oi(e),{modeled:a,bag:o}=bu(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:sm(e,t),expanded:i.get("expanded")==="true",visible:i.has("visible")?i.get("visible")==="true":!0,columns:a.map(s=>P9(s,t)),bag:o}}function P9(e,t){let r=oi(e),{modeled:n,bag:i}=bu(e,"sections","section");return{width:r.get("width"),sections:n.map(a=>T9(a,t)),bag:i}}function T9(e,t){var r,n,i;let a=oi(e),{modeled:o,bag:s}=bu(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:sm(e,t),visible:a.has("visible")?a.get("visible")==="true":!0,showLabel:a.get("showlabel")==="true",columns:S2((i=a.get("columns"))!==null&&i!==void 0?i:"1"),rows:o.map(l=>O9(l,t)),bag:s}}function O9(e,t){let{modeled:r,bag:n}=E2(e,"cell",!1);return{cells:r.map(i=>R9(i,t)),bag:n}}function R9(e,t){var r;let n=oi(e),{modeled:i,bag:a}=E2(e,"control",!0),o=sm(e,t),s=n.get("showlabel")==="true",l=i[0]?F9(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:m2(n.get("colspan"),1),rowspan:m2(n.get("rowspan"),1),control:l,bag:a}}function F9(e,t,r){var n,i;let a=oi(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:A2(o),isRequired:a.get("isrequired")==="true",isReadOnly:a.get("disabled")==="true",label:t,showLabel:r,parameters:D9(e),bag:{a:Zo(e),c:e.getAllChildren().map((l,u)=>({i:u,node:(0,qe.rawFromNode)(l)}))}}}function va(e){return e.a.length===0&&e.c.length===0&&!e.w}function N2(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function si(e,t){var r;let n=new Set(e.a.map(o=>o[0])),i=va(e),a=[];for(let o of t)if(n.has(o.key)){let s=(r=N2(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,qe.mergeAttrs)(e.a,a)}var _n=(e,t)=>({key:e,matches:r=>r===t,render:()=>t,absentDefault:""}),Pn=(e,t,r=!1)=>({key:e,matches:n=>n==="true"===t,render:()=>String(t),absentDefault:String(r)}),h2=(e,t,r=1)=>({key:e,matches:n=>Number(n)===t,render:()=>String(t),absentDefault:String(r)});function lm(e,t){return{n:"labels",a:[],c:[{n:"label",a:[["description",e],["languagecode",String(t)]],c:[]}]}}function D2(e){return{n:"parameters",a:[],c:Object.keys(e).map(t=>({n:(0,om.assertXmlName)(t,"Form control parameter name"),a:[],c:[{n:`<${e[t]}`,a:[],c:[]}]}))}}function x9(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 L9(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 um(e,t,r){let n=e.c.findIndex(a=>a.node.n==="labels");if(n<0||x9(e.c[n].node,r)===t)return e;let i=L9(e.c[n].node,t,r);return{...e,c:e.c.map((a,o)=>o===n?{...a,node:i}:a)}}function k9(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 M9(e,t){let r=Object.keys(e),n=Object.keys(t);return r.length===n.length&&r.every(i=>e[i]===t[i])}function U9(e,t){return e.a.some(r=>r[0]===t)?{...e,a:e.a.filter(r=>r[0]!==t)}:e}function B9(e,t){let r=e.c.findIndex(i=>i.node.n==="parameters");if(r<0||M9(k9(e.c[r].node),t))return e;let n=D2(t);return{...e,c:e.c.map((i,a)=>a===r?{...i,node:n}:i)}}function wu(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,qe.spliceChildren)(e.w.c,r)};return(0,qe.spliceChildren)(e.c,[o])}let i=n(),a={n:t,a:[],c:r};return e.c.length===0?[...i,a]:(0,qe.spliceChildren)(e.c,[...i,a])}function $9(e,t){let r=e.tabs.map(n=>q9(n,t));return{n:"form",a:si(e.bag,[]),c:e.tabs.length===0&&va(e.bag)?[]:wu(e.bag,"tabs",r,()=>[])}}function q9(e,t){let r=[_n("id",e.id),_n("name",e.name),Pn("expanded",e.expanded),Pn("visible",e.visible,!0)],n=e.columns.map(a=>V9(a,t)),i=um(e.bag,e.label,t);return{n:"tab",a:si(i,r),c:wu(i,"columns",n,()=>e.label?[lm(e.label,t)]:[])}}function V9(e,t){let r=e.width!==void 0?[_n("width",e.width)]:[],n=e.sections.map(i=>G9(i,t));return{n:"column",a:si(e.bag,r),c:wu(e.bag,"sections",n,()=>[])}}function G9(e,t){let r=[_n("id",e.id),_n("name",e.name),Pn("showlabel",e.showLabel),Pn("visible",e.visible,!0),{key:"columns",matches:a=>S2(a)===e.columns,render:()=>im(e.columns),absentDefault:im(1)}],n=e.rows.map(a=>z9(a,t)),i=um(e.bag,e.label,t);return{n:"section",a:si(i,r),c:wu(i,"rows",n,()=>e.label?[lm(e.label,t)]:[])}}function z9(e,t){let r=e.cells.map(n=>W9(n,t));return{n:"row",a:si(e.bag,[]),c:va(e.bag)?r:(0,qe.assembleChildren)(e.bag,r)}}function W9(e,t){let r=e.control?e.control.showLabel:N2(e.bag,"showlabel")==="true",n=[_n("id",e.id),Pn("showlabel",r),Pn("visible",e.visible,!0),h2("colspan",e.colspan),h2("rowspan",e.rowspan)],i=e.control?[j9(e.control)]:[],a;if(va(e.bag))a=[...e.control&&e.control.label?[lm(e.control.label,t)]:[],...i];else{let o=e.control?um(e.bag,e.control.label,t):e.bag;a=(0,qe.assembleChildren)(o,i)}return{n:"cell",a:si(e.bag,n),c:a}}function j9(e){let t=[_n("id",e.id),{key:"classid",matches:i=>es(i)===e.classId,render:()=>am(e.classId),absentDefault:""}];e.fieldName!==null&&t.push(_n("datafieldname",e.fieldName)),t.push(Pn("disabled",e.isReadOnly)),t.push(Pn("isrequired",e.isRequired));let r=e.fieldName===null?U9(e.bag,"datafieldname"):e.bag,n;return va(r)?n=Object.keys(e.parameters).length>0?[D2(e.parameters)]:[]:n=(0,qe.assembleChildren)(B9(r,e.parameters),[]),{n:"control",a:si(r,t),c:n}}var H9={make:(e,t)=>new w9.FormElementNode(e,t),setProp:(e,t,r)=>e.setProperty(t,r),addChild:(e,t)=>e.addChild(t)};function g2(e,t,r){(0,b2.installDomShim)();let n=J9(e,r),i=(0,qe.rebuildRaw)($9(n,t),H9,null);return new C9.SerializationService(t).serializeFormXmlNode(i)}function Q9(e){return JSON.parse(JSON.stringify(e))}function J9(e,t){var r;let n=Q9(e);n.bag||(n.bag=(0,qe.emptyBag)()),n8(n.bag),t&&X9(n,t);for(let i of(r=n.tabs)!==null&&r!==void 0?r:[])K9(i);return n}function X9(e,t){var r;let n=(r=e.entityLogicalName)!==null&&r!==void 0?r:"";I2(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=_2(s.attributeType)))})}function I2(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 K9(e){e.id||(e.id=Vt.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)Y9(t);e.bag||(e.bag=(0,qe.emptyBag)())}function Y9(e){e.sections||(e.sections=[]);for(let t of e.sections)Z9(t);e.bag||(e.bag=(0,qe.emptyBag)()),e.width===void 0&&va(e.bag)&&(e.width="100%")}function Z9(e){e.id||(e.id=Vt.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)e8(t);e.bag||(e.bag=(0,qe.emptyBag)())}function e8(e){e.cells||(e.cells=[]);for(let t of e.cells)t8(t);e.bag||(e.bag=(0,qe.emptyBag)())}function t8(e){e.id||(e.id=Vt.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&&r8(e.control),e.bag||(e.bag=(0,qe.emptyBag)())}function r8(e){var t;e.id||(e.id=Vt.Guid.NewGuid()),e.classId===void 0&&(e.classId=String(ke.ControlClassId.TextboxControl)),e.fieldName===void 0&&(e.fieldName=null),e.type===void 0&&(e.type=e.fieldName?"Field":A2(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,om.assertXmlName)(r,"Form control parameter name");e.bag||(e.bag=(0,qe.emptyBag)())}function n8(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"&&!v2(a,"handlerUniqueId")&&a.a.push(["handlerUniqueId",am(Vt.Guid.NewGuid())])}}else if(r.n==="formLibraries")for(let n of r.c)n.n==="Library"&&!v2(n,"libraryUniqueId")&&n.a.push(["libraryUniqueId",am(Vt.Guid.NewGuid())])}}var yu=class{constructor(t=w2.DEFAULT_LCID){this.lcid=t}toArtifact(t,r){var n,i,a;let{tabs:o,bag:s}=I9(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=E9[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:g2(t,this.lcid),formid:t.id||Vt.Guid.NewGuid(),objecttypecode:t.entityLogicalName,type:nm[t.formType],name:t.name,uniquename:t.name,description:(r=t.description)!==null&&r!==void 0?r:"",formpresentation:lt.FormPresentation.AirForm,formactivationstate:t.status==="Active"?lt.FormActivationState.Active:lt.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:Vt.Guid.NewGuid(),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:g2(t,this.lcid,n),name:t.name,type:nm[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 I2(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:p8(this.lcid),h=f!==void 0?f:t.tabs.map(N=>i8(N,this.lcid)).join(""),y=this.deserialize({formxml:`<form><tabs>${h}</tabs></form>`,formid:t.id||Vt.Guid.NewGuid(),objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",type:nm[(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:lt.FormPresentation.AirForm,formactivationstate:((s=t.status)!==null&&s!==void 0?s:"Active")==="Active"?lt.FormActivationState.Active:lt.FormActivationState.InActive}),w=this.toArtifact(y,t.description);return{id:(l=t.id)!==null&&l!==void 0?l:w.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:w.tabs,bag:w.bag}}assignMissingIds(t){return(0,y2.assignMissingIds)(t)}validate(t){return m8(t)}deserialize(t){(0,b2.installDomShim)();let r=b9.ScriptUtilities.ParseXml(t.formxml),n=new A9.DeserializationService(this.lcid).deSerializeFormXml(r,new Vt.Guid(t.formid),t.objecttypecode,lt.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===lt.FormActivationState.InActive?"Inactive":"Active"}};_t.FormAdapter=yu;function or(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function cm(e,t){return e?`<labels><label description="${or(e)}" languagecode="${t}" /></labels>`:""}function dm(e){return e&&e.length>0?es(e):(0,y2.newId)()}function i8(e,t){var r,n,i,a;let o=(r=e.columns)!==null&&r!==void 0?r:[],s=(o.length>0?o:[d8()]).map(l=>a8(l,t)).join("");return`<tab id="{${or(dm(e.id))}}" name="${or((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}">${cm(e.label,t)}<columns>${s}</columns></tab>`}function a8(e,t){var r,n;let i=((r=e.sections)!==null&&r!==void 0?r:[]).map(a=>o8(a,t)).join("");return`<column width="${or((n=e.width)!==null&&n!==void 0?n:"100%")}"><sections>${i}</sections></column>`}function o8(e,t){var r,n,i,a,o;let s=((r=e.rows)!==null&&r!==void 0?r:[]).map(l=>s8(l,t)).join("");return`<section id="{${or(dm(e.id))}}" name="${or((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="${im((o=e.columns)!==null&&o!==void 0?o:1)}">${cm(e.label,t)}<rows>${s}</rows></section>`}function s8(e,t){var r;return`<row>${((r=e.cells)!==null&&r!==void 0?r:[]).map(n=>l8(n,t)).join("")}</row>`}function l8(e,t){var r,n,i,a,o,s;let l=e.control,u=l?cm((n=(r=l.label)!==null&&r!==void 0?r:l.fieldName)!==null&&n!==void 0?n:"",t):"",c=l?u8(l):"";return`<cell id="{${or(dm(e.id))}}" showlabel="${l?(i=l.showLabel)!==null&&i!==void 0?i:!0:!1}" visible="${(a=e.visible)!==null&&a!==void 0?a:!0}" colspan="${(o=e.colspan)!==null&&o!==void 0?o:1}" rowspan="${(s=e.rowspan)!==null&&s!==void 0?s:1}">${u}${c}</cell>`}function u8(e){var t,r,n;let i=e.fieldName?` datafieldname="${or(e.fieldName)}"`:"",a=c8(e.parameters),o=e.classId?es(e.classId):String(ke.ControlClassId.TextboxControl);return`<control id="${or((t=e.id)!==null&&t!==void 0?t:"")}" classid="{${or(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 c8(e){let t=Object.keys(e??{});return t.length===0?"":(t.forEach(n=>(0,om.assertXmlName)(n,"Form control parameter name")),`<parameters>${t.map(n=>`<${n}>${or(e[n])}</${n}>`).join("")}</parameters>`)}function d8(){return{width:"100%",sections:[],bag:{a:[],c:[]}}}function p8(e){return`<tab id="{${Vt.Guid.NewGuid()}}" name="tab_general" expanded="true" visible="true"><labels><label description="General" languagecode="${e}" /></labels><columns><column width="100%"><sections><section id="{${Vt.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 f8(e=w2.DEFAULT_LCID){return{adapter:new yu(e),api:S9.formApi,languageSensitive:!0,publish:(t,r,n)=>(0,f2.publishBoundEntity)(t,n),publishScope:(t,r)=>(0,f2.boundEntityPublishScope)(r)}}_t.formRegistration=f8;function m8(e){let t=[];return(0,ai.childObjects)(e,"tabs","","tab",t).forEach(({node:n,index:i})=>{(0,ai.childObjects)(n,"columns",`/tabs/${i}`,"column",t).forEach(({node:o,index:s})=>{let l=`/tabs/${i}/columns/${s}`;(0,ai.childObjects)(o,"sections",l,"section",t).forEach(({node:c,index:d})=>{let p=`${l}/sections/${d}`;(0,ai.childObjects)(c,"rows",p,"row",t).forEach(({node:h,index:y})=>{let w=`${p}/rows/${y}`;(0,ai.childObjects)(h,"cells",w,"cell",t).forEach(({node:D,index:x})=>{let F=D.control;F!=null&&!(0,ai.isJsonObject)(F)&&t.push((0,ai.issue)(`${w}/cells/${x}/control`,"control-must-be-object-or-null",`a cell control must be a JSON object or null, got ${typeof F}`))})})})})}),t}_t.SUBGRID_CLASS_ID=ke.ControlClassId.SubgridControl;_t.NOTES_CLASS_ID=ke.ControlClassId.TimelineControl;_t.QUICK_VIEW_CLASS_ID=ke.ControlClassId.QuickViewControl;var h8={Lookup:String(ke.ControlClassId.LookupControl),Customer:String(ke.ControlClassId.LookupControl),Owner:String(ke.ControlClassId.LookupControl),PartyList:String(ke.ControlClassId.PartyListControl),Boolean:String(ke.ControlClassId.BooleanControl),DateTime:String(ke.ControlClassId.DateTimeControl),Decimal:String(ke.ControlClassId.DecimalControl),Double:String(ke.ControlClassId.FloatingNumberControl),Money:String(ke.ControlClassId.CurrencyControl),Integer:String(ke.ControlClassId.IntegerControl),BigInt:String(ke.ControlClassId.IntegerControl),Memo:String(ke.ControlClassId.TextAreaControl),String:String(ke.ControlClassId.TextboxControl)},g8="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE";function _2(e){return e==="Picklist"||e==="State"||e==="Status"?g8:e&&h8[e]||String(ke.ControlClassId.TextboxControl)}_t.classIdForAttributeType=_2;function v2(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}});var pm=g(ya=>{"use strict";Object.defineProperty(ya,"__esModule",{value:!0});ya.viewApi=ya.findDefaultViews=void 0;var O2=Kt(),Gt=be(),Jr=ee(),v8="savedqueryid,name,description,fetchxml,layoutxml,querytype,returnedtypecode,isdefault",y8="savedqueryid,name,returnedtypecode,querytype,isdefault";async function b8(e,t,r={}){var n;let i=new Set(((n=r.excludeViewIds)!==null&&n!==void 0?n:[]).filter(Boolean)),a=`returnedtypecode eq '${(0,Jr.odataLiteral)(t)}' and querytype eq 0`,o=`/savedqueries${(0,Jr.odataQuery)([["$select","savedqueryid,name,isdefault"],["$filter",a]])}`;return(await(0,O2.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:"")}})}ya.findDefaultViews=b8;async function w8(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,Jr.odataLiteral)(t)}')${(0,Jr.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 T2(e,t,r){if(!r||!/<grid\b/.test(t)||/<grid[^>]*\bobject=/.test(t))return t;let n=await w8(e,r);return n===void 0?t:t.replace(/<grid\b/,`<grid object="${n}"`)}ya.viewApi={async get(e,t){let n=`/savedqueries(${(0,Jr.normalizeGuid)(t,"id")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Jr.odataQuery)([["$select",v8]]),i=(0,Gt.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,Gt.readEtag)(i)}},async list(e,t){let r=`/savedqueries${(0,Jr.odataQuery)([["$select",y8],["$filter",t?.entityLogicalName?`returnedtypecode eq '${(0,Jr.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,O2.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,Gt.echoWrite)("savedqueryid"),a=`/savedqueries${i.query}`,o=await T2(e,n.layoutxml,n.returnedtypecode),s=(0,Gt.ensureSuccess)(await e.post(a,(0,Gt.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,Gt.resolveCreatedId)(s,"savedqueryid","view",r),etag:(0,Gt.readEtag)(s)}},async update(e,t,r,n){let i=r,a=(0,Jr.normalizeGuid)(t,"id"),o=(0,Gt.echoWrite)("savedqueryid",{"If-Match":(0,Gt.requireEtag)(n,"view",a)}),s=`/savedqueries(${a})${o.query}`,l=await T2(e,i.layoutxml,i.returnedtypecode),u=(0,Gt.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,Gt.readEtag)(u)}},delete(e,t){return(0,Gt.deleteRecord)(e,"savedqueries",t)}}});var z2=g(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});wa.viewRegistration=wa.ViewAdapter=void 0;var ba=cr(),fm=mn(),li=Gn(),R2=Yt(),A8=pm(),mm=In(),C8=bt(),k2=100,Au=class{toArtifact(t){var r,n,i,a,o,s,l,u;(0,mm.installDomShim)();let c=(r=t.fetchxml)!==null&&r!==void 0?r:"",d=(n=t.layoutxml)!==null&&n!==void 0?n:"",p=(0,li.parseXmlRoot)(c,"<fetch/>"),f=(0,li.parseXmlRoot)(d,"<grid/>");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:S8(p),queryType:(l=t.querytype)!==null&&l!==void 0?l:0,isDefault:(u=t.isdefault)!==null&&u!==void 0?u:!1,columns:U2(f,p),filters:q2(p),sort:$2(p),fetchBag:c?(0,li.projectElementBag)(p):void 0,layoutBag:d?(0,li.projectElementBag)(f):void 0}}fromArtifact(t){(0,mm.installDomShim)();let{fetchxml:r,layoutxml:n}=F2(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,mm.installDomShim)();let{fetchxml:s,layoutxml:l}=F2(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,C8.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:[]}}assignMissingIds(t){return t}validate(t){let r=[],n=t;(0,ba.childObjects)(n,"columns","","column",r),(0,ba.childObjects)(n,"sort","","sort",r);let i=n.filters;return i!=null&&((0,ba.isJsonObject)(i)?M2(i,"/filters",r):r.push((0,ba.issue)("/filters","filters-must-be-object",`filters must be a JSON object, got ${typeof i}`))),r}};wa.ViewAdapter=Au;function M2(e,t,r){(0,ba.childObjects)(e,"conditions",t,"condition",r),(0,ba.childObjects)(e,"groups",t,"filterGroup",r).forEach(({node:i,index:a})=>M2(i,`${t}/groups/${a}`,r))}function S8(e){var t;let r=e.getElementsByTagName("entity")[0];return(t=r?.getAttribute("name"))!==null&&t!==void 0?t:""}function U2(e,t){var r;let n=B2(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)?k2:c,order:o},p=n.get(u);p&&(d.relatedEntity=p),o+=1,a.push(d)}return a}function B2(e){var t;let r=new Map,n=e.getElementsByTagName("link-entity");for(let i=0;i<n.length;i+=1){let a=n[i],o=a.getAttribute("name");if(!o)continue;let s=a.getElementsByTagName("attribute");for(let l=0;l<s.length;l+=1){let u=s[l],c=(t=u.getAttribute("alias"))!==null&&t!==void 0?t:u.getAttribute("name");c&&r.set(c,o)}}return r}function $2(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"})}}return n}function q2(e){let t=e.getElementsByTagName("entity")[0],r={type:"and",conditions:[],groups:[]};if(!t)return r;let n=zt(t,"filter").filter(i=>!V2(i)).map(G2);return n.length===0?r:n.length===1?n[0]:{type:"and",conditions:[],groups:n}}function V2(e){if(zt(e,"filter").length>0)return!1;let t=zt(e,"condition");return t.length===0?!1:t.some(r=>r.getAttribute("isquickfindfields")==="1"||zt(r,"value").length>0)}function G2(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),i.push(c)}else l.tagName==="filter"&&a.push(G2(l))}return{type:n,conditions:i,groups:a}}function zt(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 F2(e){let t=E8(e.columns);if(!x2(e.fetchBag)||!x2(e.layoutBag))return{fetchxml:x8({...e,columns:t}),layoutxml:L8({...e,columns:t},`${e.entityLogicalName}id`)};let r=new DOMParser().parseFromString("<root/>","text/xml"),n=L2(e.fetchBag,"fetch",r),i=L2(e.layoutBag,"grid",r),a=U2(i,n),o=!hm(t,a),s=!hm(e.sort,$2(n)),l=!hm(e.filters,q2(n));return o&&(N8(r,n,t,a),P8(r,i,t)),s&&R8(r,n,e.sort),l&&F8(r,n,e.filters),{fetchxml:(0,li.serializeNode)(n),layoutxml:(0,li.serializeNode)(i)}}function E8(e){return(e??[]).map((t,r)=>{var n,i;return{name:String(t.name).toLowerCase(),width:(n=t.width)!==null&&n!==void 0?n:k2,order:(i=t.order)!==null&&i!==void 0?i:r,...t.relatedEntity?{relatedEntity:t.relatedEntity}:{}}})}function x2(e){return!!e&&(e.c.length>0||e.a.length>0)}function L2(e,t,r){let n={n:t,a:(0,fm.mergeAttrs)(e.a,[]),c:(0,fm.spliceChildren)(e.c,[])};return(0,fm.rebuildRaw)(n,(0,li.domEngine)(r),null)}function N8(e,t,r,n){var i;let a=t.getElementsByTagName("entity")[0];if(!a)return;let o=new Set(r.map(u=>{var c;return`${(c=u.relatedEntity)!==null&&c!==void 0?c:""}:${u.name}`}));for(let u of n)o.has(`${(i=u.relatedEntity)!==null&&i!==void 0?i:""}:${u.name}`)||D8(a,u);let s=B2(t),l=new Set(zt(a,"attribute").map(u=>u.getAttribute("name")).filter(u=>!!u));for(let u of[...r].sort((c,d)=>c.order-d.order))if(u.relatedEntity){if(s.get(u.name)===u.relatedEntity)continue;let c=I8(e,a,u.relatedEntity),d=e.createElement("attribute");d.setAttribute("name",u.name),c.appendChild(d),s.set(u.name,u.relatedEntity)}else{if(l.has(u.name))continue;let c=e.createElement("attribute");c.setAttribute("name",u.name),_8(a,c),l.add(u.name)}}function D8(e,t){var r;if(t.relatedEntity){for(let n of zt(e,"link-entity"))if(n.getAttribute("name")===t.relatedEntity){for(let i of zt(n,"attribute"))if(((r=i.getAttribute("alias"))!==null&&r!==void 0?r:i.getAttribute("name"))===t.name){n.removeChild(i);return}}return}for(let n of zt(e,"attribute"))if(n.getAttribute("name")===t.name){e.removeChild(n);return}}function I8(e,t,r){for(let i of zt(t,"link-entity"))if(i.getAttribute("name")===r)return i;let n=e.createElement("link-entity");return n.setAttribute("name",r),t.appendChild(n),n}function _8(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 P8(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(O8(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 zt(e,"cell").filter(t=>!!t.getAttribute("name")&&t.getAttribute("ishidden")!=="1")}function O8(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){for(let i of zt(n,"order"))n.removeChild(i);for(let i of r){let a=e.createElement("order");a.setAttribute("attribute",i.attribute),a.setAttribute("descending",String(i.descending)),n.appendChild(a)}}}function F8(e,t,r){let n=t.getElementsByTagName("entity")[0];if(n){for(let i of zt(n,"filter"))V2(i)||n.removeChild(i);(r.conditions.length>0||r.groups.length>0)&&n.appendChild(gm(e,r))}}function hm(e,t){return JSON.stringify(e)===JSON.stringify(t)}function x8(e){let t=new DOMParser().parseFromString("<fetch/>","text/xml"),r=t.documentElement;r.setAttribute("version","1.0"),r.setAttribute("mapping","logical");let n=t.createElement("entity");n.setAttribute("name",e.entityLogicalName),r.appendChild(n);let i=new Map;for(let a of[...e.columns].sort((o,s)=>o.order-s.order)){let o=t.createElement("attribute");if(o.setAttribute("name",a.name),a.relatedEntity){let s=i.get(a.relatedEntity);s||(s=t.createElement("link-entity"),s.setAttribute("name",a.relatedEntity),n.appendChild(s),i.set(a.relatedEntity,s)),s.appendChild(o)}else n.appendChild(o)}for(let a of e.sort){let o=t.createElement("order");o.setAttribute("attribute",a.attribute),o.setAttribute("descending",String(a.descending)),n.appendChild(o)}return(e.filters.conditions.length>0||e.filters.groups.length>0)&&n.appendChild(gm(t,e.filters)),new XMLSerializer().serializeToString(t)}function gm(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.value!==void 0&&i.setAttribute("value",n.value),r.appendChild(i)}for(let n of t.groups)r.appendChild(gm(e,n));return r}function L8(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 k8(){return{adapter:new Au,api:A8.viewApi,publish:(e,t,r)=>(0,R2.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,R2.boundEntityPublishScope)(t)}}wa.viewRegistration=k8});var nI=g(Tn=>{"use strict";Object.defineProperty(Tn,"__esModule",{value:!0});Tn.appRegistration=Tn.AppAdapter=Tn.HEADER_NAV_BOOLEAN_RULE=void 0;var Xr=cr(),Je=mn(),rs=Gn(),M8=Yt(),U8=sl(),vm=rl(),ym=In(),B8=bt(),$8=ee(),Y2=Ni(),q8=ie(),Z2=il();Object.defineProperty(Tn,"HEADER_NAV_BOOLEAN_RULE",{enumerable:!0,get:function(){return Z2.HEADER_NAV_BOOLEAN_RULE}});var Nu="7.0.0.0",W2=`<SiteMap IntroducedVersion="${Nu}"></SiteMap>`,j2="/_imgs/imagestrips/transparent_spacer.gif",H2="/_imgs/TableIconsFluentV9/document_one_page_sparkle.svg",V8=["Entity","Url","DefaultDashboard","Page","GenPageId"],ts="sitemapId",Q2="sitemapName",G8="sitemapNameUnique";function J2(e,t,r){if(e===void 0)return r;if(typeof e!="boolean")throw new q8.ValidationError("app",t,[eI(e)]);return e}function eI(e){return(0,Xr.issue)("/headerAndNavigationRefresh",Z2.HEADER_NAV_BOOLEAN_RULE,`headerAndNavigationRefresh must be a boolean, got ${typeof e}`)}function z8(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,$8.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 Du=class{constructor(t=Y2.DEFAULT_LCID){this.lcid=t}toArtifact(t){let{bag:r,modeledEls:n}=Cu(t,"Area");return{id:"",name:"",uniqueName:"",description:"",siteMap:{areas:n.map(i=>this.areaToJson(i)),bag:r},bag:(0,Je.emptyBag)()}}fromArtifact(t){(0,ym.installDomShim)();let r=this.assignMissingIds(JSON.parse(JSON.stringify(t))),n=new DOMParser().parseFromString("<root/>","text/xml"),i=this.rootToRaw(r);return(0,Je.rebuildRaw)(i,(0,rs.domEngine)(n),null)}fromApiResponse(t){var r,n,i,a,o,s,l,u,c,d;(0,ym.installDomShim)();let p=t??{},f=(r=p.$sitemap)!==null&&r!==void 0?r:p,h=(0,rs.parseXmlRoot)((n=f.sitemapxml)!==null&&n!==void 0?n:W2,W2),y=this.toArtifact(h);return y.id=(i=p.appmoduleid)!==null&&i!==void 0?i:"",y.name=(a=p.name)!==null&&a!==void 0?a:"",y.uniqueName=(o=p.uniquename)!==null&&o!==void 0?o:"",y.description=(s=p.description)!==null&&s!==void 0?s:"",y.bag={a:[[ts,(u=(l=f.sitemapid)!==null&&l!==void 0?l:p._sitemapid_value)!==null&&u!==void 0?u:""],[Q2,(c=f.sitemapname)!==null&&c!==void 0?c:""],[G8,(d=f.sitemapnameunique)!==null&&d!==void 0?d:""]],c:[]},y}toApiPayload(t){var r,n,i,a,o,s,l,u,c,d,p,f,h,y,w;(0,ym.installDomShim)();let N=(0,rs.serializeNode)(this.fromArtifact(t)),D=[],x=[];for(let X of(n=(r=t.siteMap)===null||r===void 0?void 0:r.areas)!==null&&n!==void 0?n:[])for(let V of(i=X.groups)!==null&&i!==void 0?i:[])for(let M of(a=V.subAreas)!==null&&a!==void 0?a:[])M.type==="Entity"&&M.entity?D.push(M.entity):M.type==="DashBoard"&&M.dashboardId&&x.push(M.dashboardId);let F=(o=t.bag)!==null&&o!==void 0?o:(0,Je.emptyBag)();return{sitemapId:(s=K2(F,ts))!==null&&s!==void 0?s:"",sitemapxml:N,sitemapname:K2(F,Q2)||t.name,appModuleId:t.id,appModuleName:t.name,appModuleDescription:t.description,appModuleUniqueName:t.uniqueName,...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},...t.headerAndNavigationRefresh===void 0?{}:{appSettings:{[vm.HEADER_AND_NAVIGATION_REFRESH]:J2(t.headerAndNavigationRefresh,(l=t.id)!==null&&l!==void 0?l:"(unknown)",!0)?vm.APP_SETTING_ON:vm.APP_SETTING_OFF}},...typeof t.published=="boolean"?{published:t.published}:{},entities:D,components:{forms:(c=(u=t.components)===null||u===void 0?void 0:u.forms)!==null&&c!==void 0?c:[],views:(p=(d=t.components)===null||d===void 0?void 0:d.views)!==null&&p!==void 0?p:[],charts:(h=(f=t.components)===null||f===void 0?void 0:f.charts)!==null&&h!==void 0?h:[],dashboards:[...(w=(y=t.components)===null||y===void 0?void 0:y.dashboards)!==null&&w!==void 0?w:[],...x]}}}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:[]}]}];return{id:(n=t.id)!==null&&n!==void 0?n:(0,B8.newId)(),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:"",siteMap:{areas:l},...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},headerAndNavigationRefresh:J2(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(Am):Array.isArray(r.areas)?r.areas.forEach(Am):Array.isArray(r.groups)?Am(r):Array.isArray(r.subAreas)?rI(r):"type"in r&&Iu(r,"subarea"),t}validate(t){let r=[],n=t.published;n!==void 0&&typeof n!="boolean"&&r.push((0,Xr.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(eI(a)),i==null)return r;if(!(0,Xr.isJsonObject)(i))return r.push((0,Xr.issue)("/siteMap","sitemap-must-be-object",`siteMap must be a JSON object, got ${typeof i}`)),r;let o=(0,Xr.childObjects)(i,"areas","/siteMap","area",r),s=new Map;return o.forEach(({node:l,index:u})=>{let c=`/siteMap/areas/${u}`;(0,Xr.childObjects)(l,"groups",c,"group",r).forEach(({node:p,index:f})=>{let h=`${c}/groups/${f}`;(0,Xr.childObjects)(p,"subAreas",h,"subArea",r).forEach(({node:w,index:N})=>{let D=`${h}/subAreas/${N}`;(0,Xr.optionalEnum)(w,"type",["Entity","URL","DashBoard","CustomPage","GenPage"],D,"subarea-type-invalid",r);let x=z8(w);if(!x)return;let F=s.get(x);if(F===void 0){s.set(x,D);return}r.push((0,Xr.issue)(D,"subarea-duplicate-target",`the sitemap already navigates to this target at ${F}; 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,Je.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}=Cu(t,"Group"),a={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:bm(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}=Cu(t,"SubArea");return{id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:bm(t,this.lcid),subAreas:i.map(a=>this.subAreaToJson(a)),bag:n}}subAreaToJson(t){var r;let{bag:n}=Cu(t,null),i=W8(t),a={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",type:i,title:bm(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!==j2&&(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,Je.emptyBag)(),l=Su(o)?[["IntroducedVersion",Nu]]:[],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,Je.mergeAttrs)(o.a,l),c:(0,Je.spliceChildren)(o.c,u)}}areaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,Je.emptyBag)(),i=Su(n),a=[],o=[];t.id&&a.push(["Id",t.id]),i&&a.push(["ShowGroups","true"],["ResourceId","SitemapDesigner.NewTitle"],["DescriptionResourceId","SitemapDesigner.NewTitle"],["IntroducedVersion",Nu]),t.icon!==void 0?a.push(["Icon",t.icon]):Eu(n.a,"Icon")&&o.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):Eu(n.a,"VectorIcon")&&o.push("VectorIcon");let s=t.groups.map(u=>this.groupToRaw(u)),l=wm((0,Je.spliceChildren)(n.c,s),t.title,i,this.lcid);return{n:"Area",a:(0,Je.mergeAttrs)(n.a,a,o),c:l}}groupToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,Je.emptyBag)(),i=Su(n),a=[];t.id&&a.push(["Id",t.id]),i&&a.push(["ResourceId","SitemapDesigner.NewGroup"],["DescriptionResourceId","SitemapDesigner.NewGroup"],["ToolTipResourseId","SitemapDesigner.Unknown"],["IntroducedVersion",Nu],["IsProfile","false"]);let o=t.subAreas.map(l=>this.subAreaToRaw(l)),s=wm((0,Je.spliceChildren)(n.c,o),t.title,i,this.lcid);return{n:"Group",a:(0,Je.mergeAttrs)(n.a,a),c:s}}subAreaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,Je.emptyBag)(),i=Su(n),a=H8(n.a,t.type),o=[],s=[];t.id&&o.push(["Id",t.id]),J8(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]):Eu(a,"Icon",j2)&&s.push("Icon"),t.vectorIcon!==void 0?o.push(["VectorIcon",t.vectorIcon]):Eu(a,"VectorIcon")?t.type==="GenPage"?o.push(["VectorIcon",H2]):s.push("VectorIcon"):t.type==="GenPage"&&!j8(a,"VectorIcon")&&o.push(["VectorIcon",H2]);let l=wm((0,Je.spliceChildren)(n.c,[]),t.title,i,this.lcid);return{n:"SubArea",a:(0,Je.mergeAttrs)(a,o,s),c:l}}};Tn.AppAdapter=Du;function Cu(e,t){let r=(0,rs.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,Je.rawFromNode)((0,rs.nodeLikeFromDom)(l))}),o+=1)}return{bag:{a:r,c:n},modeledEls:i}}function X2(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 bm(e,t){var r;let n=X2(e,"Titles")[0];if(!n)return"";let a=X2(n,"Title").find(o=>o.getAttribute("LCID")===String(t));return a&&(r=a.getAttribute("Title"))!==null&&r!==void 0?r:""}function W8(e){return e.getAttribute("GenPageId")?"GenPage":e.getAttribute("Entity")?"Entity":e.getAttribute("Page")?"CustomPage":e.getAttribute("DefaultDashboard")?"DashBoard":"URL"}function Su(e){return e.a.length===0&&e.c.length===0}function j8(e,t){return e.some(([r])=>r===t)}function Eu(e,t,r){let n=e.find(([a])=>a===t),i=n?.[1];return!!i&&i!==r}function K2(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function H8(e,t){let r=Q8(t);return e.filter(([n])=>!V8.includes(n)||r.has(n)).map(n=>[n[0],n[1]])}function Q8(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 J8(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 wm(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]=X8(e[i],t,n),a}return r?[K8(t,n),...e]:e}function X8(e,t,r){let n=!1,i=e.c.map(a=>!n&&a.n==="Title"&&Y8(a,"LCID")===String(r)?(n=!0,{n:a.n,a:(0,Je.mergeAttrs)(a.a,[["Title",t]]),c:a.c}):a);return n||i.unshift(tI(t,r)),{n:e.n,a:e.a.map(a=>[a[0],a[1]]),c:i}}function K8(e,t){return{n:"Titles",a:[],c:[tI(e,t)]}}function tI(e,t){return{n:"Title",a:[["LCID",String(t)],["Title",e]],c:[]}}function Y8(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function Z8(e){let t="0123456789abcdef",r="";for(let n=0;n<e;n+=1)r+=t[Math.floor(Math.random()*t.length)];return r}function Iu(e,t){e&&(typeof e.id!="string"||e.id.length===0)&&(e.id=`${t}_${Z8(8)}`)}function Am(e){var t;Iu(e,"area");for(let r of(t=e.groups)!==null&&t!==void 0?t:[])rI(r)}function rI(e){var t;Iu(e,"group");for(let r of(t=e.subAreas)!==null&&t!==void 0?t:[])Iu(r,"subarea")}function e6(e=Y2.DEFAULT_LCID){return{adapter:new Du(e),api:U8.appApi,languageSensitive:!0,publish:(t,r)=>(0,M8.publishAppModule)(t,r),publishScope:t=>({envelope:"appmodule",targetIds:[t]})}}Tn.appRegistration=e6});var iI={};Rr(iI,{ActionType:()=>Sm,AppActionOrigin:()=>Om,AppActionVisibilityType:()=>Tm,ButtonType:()=>Nm,CannotUpdateAppActionColumns:()=>t6,Context:()=>Im,IconType:()=>Em,Location:()=>Dm,OnClickEventType:()=>Pm,Scope:()=>_m,VisibilityType:()=>Cm});var Cm,Sm,Em,Nm,Dm,Im,_m,Pm,Tm,Om,t6,aI=I(()=>{"use strict";(function(e){e[e.NotSupported=0]="NotSupported",e[e.Show=1]="Show",e[e.ClassicRules=2]="ClassicRules",e[e.Expression=3]="Expression"})(Cm||(Cm={}));(function(e){e[e.NotSupported=0]="NotSupported",e[e.None=1]="None",e[e.JavaScript=2]="JavaScript",e[e.Expression=3]="Expression"})(Sm||(Sm={}));(function(e){e[e.NoIcon=0]="NoIcon",e[e.UseIcon=1]="UseIcon",e[e.UseWebResource=2]="UseWebResource"})(Em||(Em={}));(function(e){e[e.Standard=0]="Standard",e[e.Dropdown=1]="Dropdown",e[e.Split=2]="Split",e[e.Group=3]="Group"})(Nm||(Nm={}));(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"})(Dm||(Dm={}));(function(e){e[e.All=0]="All",e[e.Entity=1]="Entity"})(Im||(Im={}));(function(e){e[e.App=0]="App",e[e.Entity=1]="Entity",e[e.Global=2]="Global"})(_m||(_m={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.JavaScript=2]="JavaScript"})(Pm||(Pm={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.ClassicRules=2]="ClassicRules"})(Tm||(Tm={}));(function(e){e[e.Default=0]="Default",e[e.Migrated=1]="Migrated",e[e.MigratedClone=2]="MigratedClone"})(Om||(Om={}));t6=["appactionid","appmoduleid","context","contextvalue","location","name","type","uniquename","isdisabled","origin"]});var sI=g(_u=>{"use strict";Object.defineProperty(_u,"__esModule",{value:!0});_u.commandApi=void 0;var Rt=be(),r6=ie(),Wt=ee(),n6="OnClickEventJavaScriptWebResourceId($select=name,webresourceid),IconWebResourceId($select=name,webresourceid)";async function Rm(e,t){let r=`/EntityDefinitions(LogicalName='${(0,Wt.odataLiteral)(t)}')${(0,Wt.odataQuery)([["$select","MetadataId"]])}`,i=(0,Rt.ensureSuccess)(await e.get(r),e.apiUrl(r)).body,a=i?.MetadataId;return a?(0,Wt.normalizeGuid)(a,"entityMetadataId"):""}_u.commandApi={async get(e,t){var r;let n=t,i=await Rm(e,n),a=i?`_contextentity_value eq ${i}`:`contextvalue eq '${(0,Wt.odataLiteral)(n)}'`,o=`/appactions${(0,Wt.odataQuery)([["$expand",n6],["$filter",a]])}`,s=(0,Rt.ensureSuccess)(await e.get(o),e.apiUrl(o)),l=s.body,u=(r=l?.value)!==null&&r!==void 0?r:[],c={entityLogicalName:n,entityMetadataId:i,appActions:u},d={};for(let p of u){let f=typeof p.appactionid=="string"?p.appactionid:void 0;if(f){let h=p["@odata.etag"];d[(0,Wt.normalizeGuid)(f,"appactionid")]=typeof h=="string"?h:null}}return{raw:c,etag:(0,Rt.readEtag)(s),memberEtags:d}},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 Rm(e,r.entityLogicalName);return oI(e,{...r,entityMetadataId:n},!1)},async update(e,t,r,n,i){return oI(e,r,!0,i)},async delete(e,t){var r,n;let i=await Rm(e,t),a=i?`_contextentity_value eq ${i}`:`contextvalue eq '${(0,Wt.odataLiteral)(t)}'`,o=`/appactions${(0,Wt.odataQuery)([["$select","appactionid"],["$filter",a]])}`,l=(n=(r=(0,Rt.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[];for(let u of l)u.appactionid&&await(0,Rt.deleteRecord)(e,"appactions",u.appactionid)}};async function oI(e,t,r,n){let i=t.entityMetadataId?(0,Wt.normalizeGuid)(t.entityMetadataId,"entityMetadataId"):"",a=a6(t.rows),o={};try{await i6(e,t,a,i,r,n,o)}catch(s){throw(0,r6.withPartialTokens)(s,{memberEtags:o})}return{id:t.entityLogicalName,etag:null,memberEtags:o}}async function i6(e,t,r,n,i,a,o){var s,l,u;for(let c of r)if(i&&c.exists){let d=(0,Wt.normalizeGuid)(c.appactionid,"id"),p=(s=a?.[d])!==null&&s!==void 0?s:c.etag,f=(0,Rt.echoWrite)("appactionid",p?{"If-Match":p}:void 0),h=`/appactions(${d})${f.query}`,y=(0,Rt.ensureSuccess)(await e.patch(h,c.body,f.options),e.apiUrl(h));o[d]=(0,Rt.readEtag)(y)}else{let d=(0,Rt.echoWrite)("appactionid"),p=`/appactions${d.query}`,f={...c.body};n&&f["[email protected]"]===void 0&&(f["[email protected]"]=`/entities(${n})`);let h=(0,Rt.ensureSuccess)(await e.post(p,f,d.options),e.apiUrl(p)),y=(0,Rt.readCreatedId)(h,"appactionid");y&&(o[(0,Wt.normalizeGuid)(y,"appactionid")]=(0,Rt.readEtag)(h))}for(let c of[...(l=t.deletedRowIds)!==null&&l!==void 0?l:[]].reverse()){let d=(0,Wt.normalizeGuid)(c,"id");await(0,Rt.deleteRecord)(e,"appactions",d,(u=a?.[d])!==null&&u!==void 0?u:void 0),delete o[d]}}function a6(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 CI=g(Aa=>{"use strict";Object.defineProperty(Aa,"__esModule",{value:!0});Aa.commandRegistration=Aa.CommandAdapter=void 0;var Ve=(aI(),Fr(iI)),lI=Yt(),jt=cr(),o6=sI(),cI=bt(),Ca=ee(),xm="$ClientSvg:",Lm=".svg",s6=2,l6=1,u6=1,dI="entityMetadataId",c6=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"]),Pu=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 h=typeof f._parentappactionid_value=="string"&&f._parentappactionid_value?f._parentappactionid_value:"",y=(i=c.get(h))!==null&&i!==void 0?i:[];y.push(f),c.set(h,y)}let d=new Map;for(let f of(a=c.get(""))!==null&&a!==void 0?a:[]){let h=h6(f.location),y=(o=d.get(h))!==null&&o!==void 0?o:[];y.push(f),d.set(h,y)}let p=[];for(let[f,h]of d)p.push({location:f,groups:p6(h,c,gI(f),u)});return{id:u,entityLogicalName:u,commandBars:m6(p),bag:{a:[[dI,(s=t.entityMetadataId)!==null&&s!==void 0?s:""]]}}}fromArtifact(t){return{entityLogicalName:t.entityLogicalName,entityMetadataId:Mm(t),appActions:Fm(t).map(r=>r.row)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t,r){let n=new Set(r?Fm(r).map(l=>l.appactionid):[]),i=Fm(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?I6(l.row):AI(l.row)}}),s=[...n].filter(l=>!a.has(l));return{entityLogicalName:t.entityLogicalName,entityMetadataId:Mm(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,cI.assignMissingIds)(t)}validate(t){let r=[];return(0,jt.childObjects)(t,"commandBars","","commandBar",r).forEach(({node:i,index:a})=>{let o=`/commandBars/${a}`;(0,jt.optionalEnum)(i,"location",["MainTab","ContextualTab","HomeTab"],o,"bar-location-invalid",r),(0,jt.childObjects)(i,"groups",o,"group",r).forEach(({node:l,index:u})=>{let c=`${o}/groups/${u}`;(0,jt.optionalGuidId)(l,"id",c,"group-id-invalid",r),pI((0,jt.childObjects)(l,"controls",c,"control",r),`${c}/controls`,r)})}),r}};Aa.CommandAdapter=Pu;function pI(e,t,r){e.forEach(({node:n,index:i})=>{let a=`${t}/${i}`;(0,jt.optionalGuidId)(n,"id",a,"control-id-invalid",r),(0,jt.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,jt.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,jt.isJsonObject)(n.action)?(0,jt.optionalEnum)(n.action,"type",["javascript"],`${a}/action`,"action-type-invalid",r):r.push((0,jt.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,jt.childObjects)(n,"children",a,"control",r);s.length>0&&pI(s,`${a}/children`,r)})}function fI(e){return{a:Object.entries(e)}}function d6(e){return Object.fromEntries(e.a)}function km(e,t){if(e){for(let[r,n]of e.a)if(r===t)return n}}function Mm(e){let t=km(e.bag,dI);return typeof t=="string"?t:""}function p6(e,t,r,n){var i,a;let o=[],s=[];for(let l of Ou(e))l.type===Ve.ButtonType.Group?o.push({id:hI(l.name,n),title:typeof l.grouptitle=="string"?l.grouptitle:"",controls:Ou((a=t.get((i=l.appactionid)!==null&&i!==void 0?i:""))!==null&&a!==void 0?a:[]).map(u=>Tu(u,t,r,n)),bag:fI(l)}):s.push(Tu(l,t,r,n));return s.length>0&&o.unshift({id:(0,cI.newId)(),title:"",controls:s}),o}function Tu(e,t,r,n){var i,a,o,s;let l=hI(e.name,n),u={id:l,type:g6(e.type),label:typeof e.buttonlabeltext=="string"?e.buttonlabeltext:"",command:typeof e.appactionid=="string"?e.appactionid:l,bag:fI(e)},c=mI(e);c&&(u.icon=c);let d=f6(e);d&&(u.action=d),typeof e.hidden=="boolean"&&(u.hidden=e.hidden),typeof e.isdisabled=="boolean"&&(u.disabled=e.isdisabled),typeof e.location=="number"&&e.location!==r&&(u.location=e.location);let p=t.get((i=e.appactionid)!==null&&i!==void 0?i:"");if(p&&p.length>0){let f=[];for(let h of Ou(p))if(h.type===Ve.ButtonType.Group){u.flyoutGroupId=(a=h.appactionid)!==null&&a!==void 0?a:void 0;for(let y of Ou((s=t.get((o=h.appactionid)!==null&&o!==void 0?o:""))!==null&&s!==void 0?s:[]))f.push(Tu(y,t,r,n))}else f.push(Tu(h,t,r,n));u.children=f}return u}function mI(e){var t;if(!((t=e.IconWebResourceId)===null||t===void 0)&&t.name)return e.IconWebResourceId.name;if(e.fonticon)return e.fonticon.startsWith(xm)?e.fonticon.slice(xm.length)+Lm:e.fonticon}function f6(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 uI(e){return typeof e.sequence=="number"?e.sequence:typeof e.buttonsequencepriority=="number"?e.buttonsequencepriority:0}function Ou(e){return[...e].sort((t,r)=>uI(t)-uI(r))}function m6(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 hI(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 h6(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 gI(e){switch(e){case"MainTab":return Ve.Location.Form;case"HomeTab":return Ve.Location.HomePageGrid;default:return Ve.Location.SubGridStandard}}function g6(e){switch(e){case Ve.ButtonType.Dropdown:return"FlyoutAnchor";case Ve.ButtonType.Split:return"SplitButton";default:return"Button"}}function v6(e){switch(e){case"FlyoutAnchor":return Ve.ButtonType.Dropdown;case"SplitButton":return Ve.ButtonType.Split;default:return Ve.ButtonType.Standard}}function y6(e){var t;return e.bag&&e.bag.a.length>0?!0:((t=e.title)!==null&&t!==void 0?t:"").length>0}function vI(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 Fm(e,t=new Set){var r,n,i,a;let o=[],s=Mm(e);for(let l of(r=e.commandBars)!==null&&r!==void 0?r:[]){let u=gI(l.location),c=((n=l.groups)!==null&&n!==void 0?n:[]).flatMap(f=>{var h;return(h=f.controls)!==null&&h!==void 0?h:[]}),d=c.length>0&&c.every(f=>!vI(f,t)),p=0;for(let f of(i=l.groups)!==null&&i!==void 0?i:[]){let h;if(y6(f)){let y=w6(f,u,void 0,e,s);o.push(y),h=y.appactionid}for(let y of(a=f.controls)!==null&&a!==void 0?a:[])yI(y,u,h,e,s,o,d?p:void 0,t),p+=1}}return o}function yI(e,t,r,n,i,a,o,s=new Set){var l;let u=b6(e,t,r,n,i,o);a.push(u);let c=(l=e.children)!==null&&l!==void 0?l:[];if(c.length===0)return;let d=e.flyoutGroupId||D6(u.appactionid);a.push(A6(d,t,u.appactionid,n,i));let p=c.every(f=>!vI(f,s));for(let[f,h]of c.entries())yI(h,t,d,n,i,a,p?f:void 0,s)}function b6(e,t,r,n,i,a){let o=bI(e,t,r,n,i),s=o.row;a!==void 0&&typeof s.sequence!="number"&&(s.sequence=a);let l=mI(s);return e.location!==void 0&&(s.location=e.location),s.type=v6(e.type),s.buttonlabeltext=e.label,C6(s,e.icon,l),E6(s,e.action),S6(s),e.hidden!==void 0&&(s.hidden=e.hidden),e.disabled!==void 0&&(s.isdisabled=e.disabled),{...o,row:s}}function w6(e,t,r,n,i){let a=bI(e,t,r,n,i);return a.row.type=Ve.ButtonType.Group,a.row.grouptitle=e.title,a}function A6(e,t,r,n,i){let a=wI(e,t,n,i);return a["[email protected]"]=`/appactions(${(0,Ca.normalizeGuid)(r,"Command flyout group id")})`,a.type=Ve.ButtonType.Group,a.grouptitle===void 0&&(a.grouptitle=""),a.isgrouptitlehidden=!0,{appactionid:e,exists:!1,etag:null,row:a}}function bI(e,t,r,n,i){let a,o,s,l;if(e.bag&&e.bag.a.length>0){a=d6(e.bag),o=!0;let u=km(e.bag,"@odata.etag");s=typeof u=="string"?u:null;let c=km(e.bag,"appactionid");l=typeof c=="string"&&c?c:e.id}else l=e.id,a=wI(l,t,n,i),o=!1,s=null;return r&&(a["[email protected]"]=`/appactions(${(0,Ca.normalizeGuid)(r,"Command parent appaction id")})`),{appactionid:l,exists:o,etag:s,row:a}}function wI(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,Ca.normalizeGuid)(n,"Command context entity metadata id")})`),i}function C6(e,t,r){if(t===r){let n=e._iconwebresourceid_value;typeof n=="string"&&n&&!e.fonticon&&(e["[email protected]"]=`/webresourceset(${(0,Ca.normalizeGuid)(n,"Command icon web resource id")})`);return}if(t===void 0){e.fonticon="",e.IconWebResourceId=null;return}e.fonticon=t.toLowerCase().endsWith(Lm)?xm+t.slice(0,t.length-Lm.length):t,e.IconWebResourceId=null}function S6(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,Ca.normalizeGuid)(a,`Command ${i}`);e[`${i}@odata.bind`]=`/canvasapps(${o})`};e.onclickeventtype===l6&&t("_onclickeventformulacomponentlibraryid_value","OnClickEventFormulaComponentLibraryId");let r=e.visibilitytype;(!r||r===u6)&&t("_visibilityformulacomponentlibraryid_value","VisibilityFormulaComponentLibraryId")}function E6(e,t){if(!(!t||t.type!=="javascript")){if(e.onclickeventtype=s6,t.webResourceId){let r=(0,Ca.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 N6(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 D6(e){let t="";for(let r=0;r<4;r+=1)t+=N6(`${r}:flyout-group:${e}`).toString(16).padStart(8,"0");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20,32)}`}function AI(e){let t={...e};for(let r of c6)delete t[r];return t}function I6(e){let t=AI(e);for(let r of Ve.CannotUpdateAppActionColumns)delete t[r];return t}function _6(){return{adapter:new Pu,api:o6.commandApi,publish:(e,t,r)=>(0,lI.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,lI.boundEntityPublishScope)(t)}}Aa.commandRegistration=_6});var SI=g(Ru=>{"use strict";Object.defineProperty(Ru,"__esModule",{value:!0});Ru.chartApi=void 0;var P6=Kt(),Ht=be(),ns=ee(),T6="savedqueryvisualizationid,name,description,primaryentitytypecode,datadescription,presentationdescription,charttype,type,isdefault",O6="savedqueryvisualizationid,name,primaryentitytypecode,charttype,isdefault";Ru.chartApi={async get(e,t){let n=`/savedqueryvisualizations(${(0,ns.normalizeGuid)(t,"id")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,ns.odataQuery)([["$select",T6]]),i=(0,Ht.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,Ht.readEtag)(i)}},async list(e,t){let r=`/savedqueryvisualizations${(0,ns.odataQuery)([["$select",O6],["$filter",t?.entityLogicalName?`primaryentitytypecode eq '${(0,ns.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,P6.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,Ht.echoWrite)("savedqueryvisualizationid"),a=`/savedqueryvisualizations${i.query}`,o=(0,Ht.ensureSuccess)(await e.post(a,(0,Ht.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,Ht.resolveCreatedId)(o,"savedqueryvisualizationid","chart",r),etag:(0,Ht.readEtag)(o)}},async update(e,t,r,n){let i=r,a=(0,ns.normalizeGuid)(t,"id"),o=(0,Ht.echoWrite)("savedqueryvisualizationid",{"If-Match":(0,Ht.requireEtag)(n,"chart",a)}),s=`/savedqueryvisualizations(${a})${o.query}`,l=(0,Ht.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,Ht.readEtag)(l)}},delete(e,t){return(0,Ht.deleteRecord)(e,"savedqueryvisualizations",t)}}});var BI=g(Sa=>{"use strict";Object.defineProperty(Sa,"__esModule",{value:!0});Sa.chartRegistration=Sa.ChartAdapter=void 0;var Um=mn(),EI=cr(),Kr=Gn(),NI=Yt(),R6=SI(),Bm=In(),F6=bt(),x6=["Column","StackedColumn","StackedColumn100","Bar","StackedBar","StackedBar100","Area","StackedArea","StackedArea100","Line","Pie","Doughnut","Funnel","Tag"],L6=new Map(x6.map(e=>[e.toLowerCase(),e]));function PI(e){var t;return e&&(t=L6.get(e.toLowerCase()))!==null&&t!==void 0?t:"Column"}function k6(){return'<Chart Palette="BrightPastel"><Series><Series ChartType="Column" ChartArea="Default" /></Series><ChartAreas><ChartArea Name="Default" /></ChartAreas><Legends><Legend Name="Default" /></Legends></Chart>'}function M6(e){var t,r;let n=e.entityLogicalName,i=e.series.map((u,c)=>({alias:`agg_${c}`,series:u})),a=e.categories.map((u,c)=>({alias:`grp_${c}`,category:u})),o=i.map(u=>`<attribute alias="${u.alias}" name="${is(u.series.attribute)}" aggregate="${is(u.series.aggregate)}" />`).join("")+a.map(u=>`<attribute alias="${u.alias}" name="${is(u.category.attribute)}" groupby="true"${u.category.dateGrouping?` dategrouping="${is(u.category.dateGrouping)}"`:""} />`).join(""),s=i.map(u=>`<measure alias="${u.alias}" />`).join(""),l=(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="${is(n)}">${o}</entity></fetch></fetchcollection><categorycollection><category alias="${l}"><measurecollection>${s}</measurecollection></category></categorycollection></datadefinition>`}var Fu=class{toArtifact(t){var r,n,i,a,o,s,l;(0,Bm.installDomShim)();let u=(r=t.datadescription)!==null&&r!==void 0?r:"",c=(n=t.presentationdescription)!==null&&n!==void 0?n:"",d=(0,Kr.parseXmlRoot)(u,"<datadefinition/>"),p=(0,Kr.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:TI(p),isDefault:(l=t.isdefault)!==null&&l!==void 0?l:!1,series:FI(d),categories:xI(d),presentation:OI(p),dataBag:u?(0,Kr.projectElementBag)(d):void 0,presentationBag:c?(0,Kr.projectElementBag)(p):void 0,rowBag:U6(t.charttype,t.type)}}fromArtifact(t){(0,Bm.installDomShim)();let{datadescription:r,presentationdescription:n}=B6(t);return{savedqueryvisualizationid:t.id,name:t.name,description:t.description,primaryentitytypecode:t.entityLogicalName,datadescription:r,presentationdescription:n,charttype:DI(t.rowBag,"charttype"),type:DI(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,Bm.installDomShim)();let u=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,F6.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,EI.childObjects)(n,"series","","series",r),(0,EI.childObjects)(n,"categories","","category",r),r}};Sa.ChartAdapter=Fu;function U6(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 DI(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 TI(e){let t=e.getElementsByTagName("Series");for(let r=0;r<t.length;r+=1)if(t[r].getAttribute("ChartType"))return PI(t[r].getAttribute("ChartType"));return"Column"}function OI(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 xu(e){return e.getElementsByTagName("fetch")[0]}function RI(e){var t;let r=new Map;if(!e)return r;let n=e.getElementsByTagName("link-entity");for(let i=0;i<n.length;i+=1){let a=n[i],o=a.getAttribute("name");if(!o)continue;let s=a.getElementsByTagName("attribute");for(let l=0;l<s.length;l+=1){let u=s[l],c=(t=u.getAttribute("alias"))!==null&&t!==void 0?t:u.getAttribute("name");c&&r.set(c,o)}}return r}function FI(e){let t=xu(e);if(!t)return[];let r=RI(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=PI(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 xI(e){var t;let r=xu(e);if(!r)return[];let n=RI(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 B6(e){if(!II(e.dataBag)||!II(e.presentationBag))return{datadescription:M6(e),presentationdescription:aG(e)};let t=new DOMParser().parseFromString("<root/>","text/xml"),r=_I(e.dataBag,"datadefinition",t),n=_I(e.presentationBag,"Chart",t);return $m(e.series,FI(r))||(q6(t,r,e.series),$6(t,n,e.series.length,e.chartType)),$m(e.categories,xI(r))||V6(t,r,e.categories),e.chartType!==TI(n)&&MI(n,e.chartType),$m(e.presentation,OI(n))||UI(n,e.presentation),{datadescription:(0,Kr.serializeNode)(r),presentationdescription:(0,Kr.serializeNode)(n)}}function II(e){return!!e&&(e.c.length>0||e.a.length>0)}function $6(e,t,r,n){let i,a=t.childNodes;for(let l=0;l<a.length;l+=1)if(a[l].nodeType===1&&a[l].tagName==="Series"){i=a[l];break}i||(i=e.createElement("Series"),t.insertBefore(i,t.firstChild));let o=[],s=i.childNodes;for(let l=0;l<s.length;l+=1)s[l].nodeType===1&&s[l].tagName==="Series"&&o.push(s[l]);for(let l=o.length;l<r;l+=1){let u=e.createElement("Series");u.setAttribute("ChartType",n),i.appendChild(u)}for(let l=r;l<o.length;l+=1)i.removeChild(o[l])}function _I(e,t,r){let n={n:t,a:(0,Um.mergeAttrs)(e.a,[]),c:(0,Um.spliceChildren)(e.c,[])};return(0,Um.rebuildRaw)(n,(0,Kr.domEngine)(r),null)}function q6(e,t,r){let n=xu(t),i=n?.getElementsByTagName("entity")[0];!n||!i||LI(e,t,i,J6(n),r,K6,{aliasPrefix:"aggregate_column",addRef:W6,removeRef:Q6})}function V6(e,t,r){let n=xu(t),i=n?.getElementsByTagName("entity")[0];!n||!i||LI(e,t,i,X6(n),r,Y6,{aliasPrefix:"groupby_column",addRef:j6,removeRef:H6})}function LI(e,t,r,n,i,a,o){let s=new Map;for(let p of n){let f=p.getAttribute("alias");f&&s.set(f,p)}let l=new Set,u=[];for(let p of i){let f=p.alias?s.get(p.alias):void 0;f&&!l.has(f)?(a(f,p),l.add(f)):u.push(p)}let c=n.filter(p=>!l.has(p)),d=0;for(let p of u)if(d<c.length){let f=c[d];a(f,p),l.add(f),d+=1}else{let f=e.createElement("attribute"),h=p.alias||z6(t,o.aliasPrefix);f.setAttribute("alias",h),a(f,p),Z6(e,r,f,p.relatedEntity),o.addRef(e,t,h)}for(let p of n)if(!l.has(p)){let f=p.getAttribute("alias");f&&o.removeRef(t,f),tG(p)}}function G6(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 z6(e,t){let r=G6(e);if(!r.has(t))return t;for(let n=2;;n+=1){let i=`${t}_${n}`;if(!r.has(i))return i}}function kI(e,t){let r=t.getElementsByTagName("categorycollection")[0];if(r)return r;let n=e.createElement("categorycollection");return t.appendChild(n),n}function W6(e,t,r){let n=kI(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 j6(e,t,r){let n=kI(e,t),i=e.createElement("category");i.setAttribute("alias",r),n.appendChild(i)}function H6(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 Q6(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"&&!nG(o)&&((r=o.parentNode)===null||r===void 0||r.removeChild(o))}}function J6(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 X6(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 K6(e,t){e.setAttribute("name",t.attribute),e.setAttribute("aggregate",t.aggregate),t.seriesType&&e.setAttribute("charttype",t.seriesType)}function Y6(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 Z6(e,t,r,n){n?eG(e,t,n).appendChild(r):t.appendChild(r)}function eG(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 tG(e){let t=e.parentNode;if(t&&(t.removeChild(e),t.tagName==="link-entity"&&!rG(t))){let r=t.parentNode;r&&r.removeChild(t)}}function rG(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 nG(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1)if(t[r].nodeType===1)return!0;return!1}function MI(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(!iG(r[i])){r[i].setAttribute("ChartType",t);return}}}function iG(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 UI(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 aG(e){let t=(0,Kr.parseXmlRoot)(k6(),"<Chart/>");return MI(t,e.chartType),UI(t,e.presentation),(0,Kr.serializeNode)(t)}function $m(e,t){return JSON.stringify(e)===JSON.stringify(t)}function is(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function oG(){return{adapter:new Fu,api:R6.chartApi,publish:(e,t,r)=>(0,NI.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,NI.boundEntityPublishScope)(t)}}Sa.chartRegistration=oG});var $I=g(Lu=>{"use strict";Object.defineProperty(Lu,"__esModule",{value:!0});Lu.dashboardApi=void 0;var sG=Kt(),Qt=be(),as=ee(),lG="formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber",uG="formid,name,type,objecttypecode",cG=0,dG=10;Lu.dashboardApi={async get(e,t){let n=`/systemforms(${(0,as.normalizeGuid)(t,"id")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,as.odataQuery)([["$select",lG]]),i=(0,Qt.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,Qt.readEtag)(i)}},async list(e,t){let r=[`(type eq ${cG} or type eq ${dG})`];t?.entityLogicalName&&r.push(`objecttypecode eq '${(0,as.odataLiteral)(t.entityLogicalName)}'`);let n=`/systemforms${(0,as.odataQuery)([["$select",uG],["$filter",r.join(" and ")]])}`;return(await(0,sG.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,Qt.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,Qt.ensureSuccess)(await e.post(a,(0,Qt.withClientMintedId)(o,"formid",r),i.options),e.apiUrl(a));return{id:(0,Qt.resolveCreatedId)(s,"formid","dashboard",r),etag:(0,Qt.readEtag)(s)}},async update(e,t,r,n){let i=r,a=(0,as.normalizeGuid)(t,"id"),o=(0,Qt.echoWrite)("formid",{"If-Match":(0,Qt.requireEtag)(n,"dashboard",a)}),s=`/systemforms(${a})${o.query}`,l=(0,Qt.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,Qt.readEtag)(l)}},delete(e,t){return(0,Qt.deleteRecord)(e,"systemforms",t)}}});var YI=g(Sr=>{"use strict";Object.defineProperty(Sr,"__esModule",{value:!0});Sr.dashboardRegistration=Sr.TILE_CLASS_ID=Sr.DashboardAdapter=void 0;var ss=mn(),Jt=Gn(),qm=Yt(),os=cr(),pG=$I(),Vm=In(),ui=bt(),jI=ee(),HI=Ni(),qI="0",Gm="10",fG=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"]]),mG="{3FF9A528-DD50-4ACA-8F10-2E5ED73513AD}",Mu=class{constructor(t=HI.DEFAULT_LCID){this.lcid=t}toArtifact(t){var r,n,i,a;(0,Vm.installDomShim)();let o=(r=t.formxml)!==null&&r!==void 0?r:"",s=(0,Jt.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:hG(t.type),entityLogicalName:t.objecttypecode?t.objecttypecode:null,enabledForMobile:!!t.istabletenabled,layoutType:gG(s),components:VI(s,this.lcid),bag:(0,Jt.projectElementBag)(s)}}fromArtifact(t){var r;return(0,Vm.installDomShim)(),{formid:t.id,name:t.name,description:t.description,type:t.dashboardType==="Interactive"?Gm:qI,objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",istabletenabled:t.enabledForMobile,formxml:GI(t,this.lcid)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t){return{name:t.name,description:t.description,formxml:GI(t,this.lcid),istabletenabled:t.enabledForMobile,type:t.dashboardType==="Interactive"?Gm:qI,objecttypecode:t.entityLogicalName}}createDefault(t){var r,n,i,a,o,s,l,u;(0,Vm.installDomShim)();let c=(0,Jt.parseXmlRoot)(PG(),"<form/>");return{id:(r=t.id)!==null&&r!==void 0?r:(0,ui.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:VI(c,this.lcid),bag:(0,Jt.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,ui.newId)())}return t}validate(t){let r=[],n=(0,os.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,os.isJsonObject)(u)&&r.push((0,os.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,os.isJsonObject)(a.position)){let l=ls(a.position);i.has(l)?r.push((0,os.issue)(`${s}/position`,"component-position-collision",`two components occupy the same dashboard position (${l}); move one to a free cell`)):i.add(l)}}),r}};Sr.DashboardAdapter=Mu;function hG(e){return String(e??"")===Gm?"Interactive":"Standard"}function gG(e){var t;let r=(t=e?.getAttribute("formLayout"))!==null&&t!==void 0?t:e?.getAttribute("layoutType"),n=parseInt(r??"",10);return Number.isNaN(n)?0:n}function J(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 VI(e,t){let r=[];return J(e,"tabs").flatMap(i=>J(i,"tab")).forEach((i,a)=>{J(i,"columns").flatMap(s=>J(s,"column")).forEach((s,l)=>{J(s,"sections").flatMap(c=>J(c,"section")).forEach((c,d)=>{vG(c,{tabIndex:a,columnIndex:l,sectionIndex:d},r,t)})})}),r}function vG(e,t,r,n){J(e,"rows").flatMap(a=>J(a,"row")).forEach((a,o)=>{J(a,"cell").forEach((s,l)=>{let u=yG(s,{...t,rowIndex:o,cellIndex:l},n);u&&r.push(u)})})}function yG(e,t,r){var n,i,a;let o=XI((n=e.getAttribute("id"))!==null&&n!==void 0?n:"");if(o.toLowerCase().startsWith("spacer"))return null;let s=J(e,"control")[0];if(!s)return null;let l=(i=s.getAttribute("classid"))!==null&&i!==void 0?i:"",u=AG(s),c=CG(l,u,s),d=bG(s);return{id:(a=s.getAttribute("id"))!==null&&a!==void 0?a:o,type:c,name:JI(e,r),classId:l,position:t,colspan:zm(e,"colspan",1),rowspan:zm(e,"rowspan",1),parameters:u,bag:(0,Jt.projectElementBag)(e),...d?{icProperties:d}:{}}}function QI(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 bG(e){let t=QI(e);return t?(0,Jt.serializeNode)(t):void 0}function wG(e,t,r){let n=QI(t);if(!r){n&&t.removeChild(n);return}let i=new DOMParser().parseFromString(r,"text/xml").documentElement,a=(0,ss.rebuildRaw)((0,ss.rawFromNode)((0,Jt.nodeLikeFromDom)(i)),(0,Jt.domEngine)(e),null);n&&(0,Jt.serializeNode)(n)===(0,Jt.serializeNode)(a)||(n?t.replaceChild(a,n):t.appendChild(a))}function JI(e,t){var r,n;let i=J(e,"labels")[0];if(!i)return"";let a=J(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 AG(e){var t;let r={},n=J(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 CG(e,t,r){var n;let i=fG.get(e.toUpperCase());return i?i==="chart"?t.ChartGridMode==="Chart"?"chart":"list":i==="assistant"&&((n=r.getAttribute("uniqueid"))!==null&&n!==void 0?n:"").toUpperCase()===mG?"assistant":i:"unknown"}function zm(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 XI(e){return e.replace(/^\{/,"").replace(/\}$/,"")}function SG(e,t){let r={n:"form",a:(0,ss.mergeAttrs)(e.bag.a,[]),c:(0,ss.spliceChildren)(e.bag.c,[])};return(0,ss.rebuildRaw)(r,(0,Jt.domEngine)(t),null)}function GI(e,t){let r=new DOMParser().parseFromString("<root/>","text/xml"),n=SG(e,r);return DG(r,n,e.components,t),EG(r,n,e.components,t),(0,Jt.serializeNode)(n)}function EG(e,t,r,n){let i=KI(t);for(let a of r)i.has(ls(a.position))||NG(e,t,a,n)}function NG(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=TG(t,e,l);for(let z of J(u,"row"))J(z,"cell").some($=>J($,"control").length>0)||u.removeChild(z);let c=r.classId||Sr.TILE_CLASS_ID[r.type]||Sr.TILE_CLASS_ID.iframe,d=r.rowspan&&r.rowspan>0?r.rowspan:4,p=r.bag&&zI(r.bag,"id")?String(zI(r.bag,"id")):ku((0,ui.newId)()),f=r.id?ku(r.id):ku((0,ui.newId)()),h=u.parentNode,y=Math.max(1,parseInt(h&&h.getAttribute&&h.getAttribute("columns")||"1",10)||1),w=Math.min(Math.max(1,r.colspan&&r.colspan>0?r.colspan:1),y),N=J(u,"row"),D=N[N.length-1],x=D?J(D,"cell").reduce((z,$)=>z+zm($,"colspan",1),0):0;(!D||x+w>y)&&(D=e.createElement("row"),u.appendChild(D));let F=e.createElement("cell");F.setAttribute("id",p),F.setAttribute("colspan",String(w)),F.setAttribute("rowspan",String(d)),F.setAttribute("showlabel","true");let X=e.createElement("labels"),V=e.createElement("label");V.setAttribute("description",(o=r.name)!==null&&o!==void 0?o:""),V.setAttribute("languagecode",String(n)),X.appendChild(V),F.appendChild(X);let M=e.createElement("control");M.setAttribute("id",f),M.setAttribute("classid",ku(c));let U=e.createElement("parameters"),B=(s=r.parameters)!==null&&s!==void 0?s:{};for(let z of Object.keys(B)){let $=(0,jI.createSafeXmlElement)(e,z,"dashboard tile parameter");$.textContent=B[z],U.appendChild($)}M.appendChild(U),F.appendChild(M),D.appendChild(F)}function zI(e,t){if(!e)return;let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function DG(e,t,r,n){var i;let a=KI(t),o=new Set(r.map(s=>ls(s.position)));for(let s of r){let l=a.get(ls(s.position));if(!l)continue;let u=J(l,"control")[0];u&&(IG(e,l,s.name,n),_G(e,u,s.parameters),WI(l,"colspan",s.colspan),WI(l,"rowspan",s.rowspan),s.icProperties!==void 0&&wG(e,u,s.icProperties))}for(let[s,l]of a)o.has(s)||(i=l.parentNode)===null||i===void 0||i.removeChild(l)}function KI(e){let t=new Map;return J(e,"tabs").flatMap(n=>J(n,"tab")).forEach((n,i)=>{J(n,"columns").flatMap(o=>J(o,"column")).forEach((o,s)=>{J(o,"sections").flatMap(u=>J(u,"section")).forEach((u,c)=>{J(u,"rows").flatMap(p=>J(p,"row")).forEach((p,f)=>{J(p,"cell").forEach((h,y)=>{var w;XI((w=h.getAttribute("id"))!==null&&w!==void 0?w:"").toLowerCase().startsWith("spacer")||J(h,"control")[0]&&t.set(ls({tabIndex:i,columnIndex:s,sectionIndex:c,rowIndex:f,cellIndex:y}),h)})})})})}),t}function ls(e){let t=e??{};return`${t.tabIndex}.${t.columnIndex}.${t.sectionIndex}.${t.rowIndex}.${t.cellIndex}`}function IG(e,t,r,n){if(r===JI(t,n))return;let i=J(t,"labels")[0];i||(i=e.createElement("labels"),t.appendChild(i));let a=J(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 _G(e,t,r){var n;if(!r)return;let i=Object.keys(r);if(i.length===0)return;let a=J(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,jI.createSafeXmlElement)(e,l,"dashboard component parameter");d.textContent=u,a.appendChild(d)}}}function WI(e,t,r){var n;((n=e.getAttribute(t))!==null&&n!==void 0?n:"")!==String(r)&&e.setAttribute(t,String(r))}function PG(e=2){let t=`{${(0,ui.newId)()}}`,r=`{${(0,ui.newId)()}}`,n=`{${(0,ui.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>`}Sr.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 ku(e){return`{${e.replace(/[{}]/g,"")}}`}function TG(e,t,r){var n;let i=J(e,"tabs").flatMap(u=>J(u,"tab"))[0];if(!i)throw new Error("addDashboardTile: dashboard formxml has no <tab>");let a=J(i,"columns").flatMap(u=>J(u,"column"))[0];if(!a)throw new Error("addDashboardTile: dashboard formxml has no <column>");let o=J(a,"sections").flatMap(u=>J(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=J(s,"rows")[0];return l||(l=t.createElement("rows"),s.appendChild(l)),l}function OG(e=HI.DEFAULT_LCID){return{adapter:new Mu(e),api:pG.dashboardApi,languageSensitive:!0,publish:(t,r,n)=>n?.entityLogicalName?(0,qm.publishBoundEntity)(t,n):(0,qm.publishDashboardById)(t,r),publishScope:(t,r)=>r?.entityLogicalName?(0,qm.boundEntityPublishScope)(r):{envelope:"dashboard",targetIds:[t]}}}Sr.dashboardRegistration=OG});var i_=g(Bu=>{"use strict";Object.defineProperty(Bu,"__esModule",{value:!0});Bu.genPageApi=void 0;var n_=Kt(),Ie=be(),Pt=ee(),Er=ie(),On="uxagentprojects",Na="uxagentprojectfiles",Ea="uxagentprojectid",Nr="uxagentprojectfileid",Uu=`${Ea},name`,RG=`${Nr},filename,filetype`;async function Wm(e,t,r,n){var i;let a=`/${t}(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Pt.odataQuery)([["$select",n]]),o=(0,Ie.ensureSuccess)(await e.get(a),e.apiUrl(a));return{row:(i=o.body)!==null&&i!==void 0?i:{},etag:(0,Ie.readEtag)(o)}}async function FG(e,t){let r=`/${Na}(${t})/filecontent/$value`,n=await e.get(r);if(n.status===404)return{status:"unavailable",reason:"unpublished"};(0,Ie.ensureSuccess)(n,e.apiUrl(r));let i=n.body;if(i instanceof Uint8Array||Buffer.isBuffer(i))return{status:"available",data:Buffer.from(i).toString("base64")};if(i instanceof ArrayBuffer)return{status:"available",data:Buffer.from(new Uint8Array(i)).toString("base64")};if(typeof i=="string")return{status:"available",data:Buffer.from(i,"utf8").toString("base64")};throw new Er.SdkError("GENPAGE_CONTENT_UNREADABLE",`Read the content of file '${t}' but the injected HttpClient returned a body this SDK cannot encode (${typeof i}). Return the response as a string, Uint8Array, Buffer, or ArrayBuffer; a byte-returning transport is required to round-trip non-UTF8 assets.`)}async function xG(e,t,r,n){if(!e.supportsBinaryPatch)throw new Er.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED",`Refusing to push generative-page file '${t}': its content cannot be written because the injected HttpClient does not implement patchRaw(). A Dataverse File column is not writable through a JSON body, so saving the row without its bytes would report success for a page whose source never uploaded.`);let i=`/${Na}(${t})/filecontent`,a=new Uint8Array(Buffer.from(n,"base64"));(0,Pt.assertNoControlChars)(r,"generative-page file name"),(0,Ie.ensureSuccess)(await e.patchRaw(i,a,{headers:{"Content-Type":"application/octet-stream","Content-Length":String(a.byteLength),"x-ms-file-name":r}}),e.apiUrl(i))}async function jm(e,t){let r=`/${Na}/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()`+(0,Pt.odataQuery)([["$select",RG],["$filter",`_${Ea}_value eq ${t}`]]);return(await(0,n_.collectPages)(e,r,"fetchArtifact('genPage')")).map(i=>({row:i,etag:typeof i["@odata.etag"]=="string"?i["@odata.etag"]:null}))}async function ZI(e,t,r){var n;let{etag:i}=await Wm(e,On,t,Uu),a={};for(let{row:l,etag:u}of await jm(e,t))a[(0,Pt.normalizeGuid)(String((n=l[Nr])!==null&&n!==void 0?n:""),Nr)]=u;let o=Object.keys(a),s=!i||o.length!==r.size||o.some(l=>!r.has(l))||Object.values(a).some(l=>!l);return{etag:i,memberEtags:a,mismatch:s}}function e_(e,t){return t.mismatch?{etag:null,memberEtags:{},warnings:[`Generative page '${e}' was written, but its files changed on the server while the write was in progress, so the new concurrency tokens cannot be trusted. The local baseline is now unusable: re-fetch the page before editing it again \u2014 the next push will refuse rather than overwrite blind.`]}:{etag:t.etag,memberEtags:t.memberEtags}}Bu.genPageApi={async get(e,t){var r;let n=(0,Pt.normalizeGuid)(t,"id"),{row:i,etag:a}=await Wm(e,On,n,Uu),o=await jm(e,n),s={},l=[];for(let{row:u,etag:c}of o){let d=(0,Pt.normalizeGuid)(String((r=u[Nr])!==null&&r!==void 0?r:""),Nr);s[d]=c;let p=await FG(e,d);l.push({...u,content:p})}return{raw:{project:i,files:l},etag:a,memberEtags:s}},async list(e,t){let r=`/${On}/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()`+(0,Pt.odataQuery)([["$select",Uu]]);return(await(0,n_.collectPages)(e,r,"listArtifacts('genPage')")).map(i=>{var a,o;return{type:"genPage",id:String((a=i[Ea])!==null&&a!==void 0?a:""),name:String((o=i.name)!==null&&o!==void 0?o:""),isDirty:!1}})},async create(e,t,r){let n=t;t_(e,n);let i=`/${On}`,a=(0,Ie.ensureSuccess)(await e.post(i,(0,Ie.withClientMintedId)({name:n.name},Ea,r)),e.apiUrl(i)),o=(0,Ie.resolveCreatedId)(a,Ea,"generative page",r),s=new Set;for(let l of n.files){let u=await r_(e,o,l,!0);s.add((0,Pt.normalizeGuid)(u.id,"file id"))}try{return{id:o,...e_(o,await ZI(e,o,s))}}catch(l){return{id:o,etag:null,memberEtags:{},warnings:[`The generative page was created, but re-reading its concurrency tokens failed (${l instanceof Error?l.message:String(l)}). The local baseline is unusable: re-fetch the page before editing it \u2014 the next push will refuse rather than overwrite blind.`]}}},async update(e,t,r,n,i){let a=r,o=(0,Pt.normalizeGuid)(t,"id");t_(e,a);let s=await jm(e,o),{etag:l}=await Wm(e,On,o,Uu);if(n&&l&&n!==l)throw new Er.SdkError(Ie.VERSION_CONFLICT_CODE,`Generative page '${o}' changed on the server after it was fetched (baseline ${n}, server ${l}) \u2014 another writer edited it. A page row accepts no If-Match validator, so this push would silently overwrite them. Re-fetch the page and re-apply the edit.`);if(!n||!l)throw new Er.SdkError(Ie.VERSION_CONFLICT_CODE,`Cannot verify generative page '${o}' before writing: ${n?"the server did not return the page's current token":"no baseline token was recorded"}. This entity accepts no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);let u=new Set(s.map(({row:f})=>{var h;return(0,Pt.normalizeGuid)(String((h=f[Nr])!==null&&h!==void 0?h:""),Nr)})),c=new Set(a.files.map(f=>(0,Pt.normalizeGuid)(f.id,"file id")));if(!i)throw new Er.SdkError(Ie.VERSION_CONFLICT_CODE,`Cannot verify the files of generative page '${o}' before writing: no child baseline was recorded. These rows accept no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);let d=new Set(Object.keys(i).map(f=>f.toLowerCase()));{for(let h of c)if(!u.has(h)&&d.has(h))throw new Er.SdkError(Ie.VERSION_CONFLICT_CODE,`Generative-page file '${h}' existed when this page was fetched but is gone from the server now \u2014 another writer deleted it. Refusing to recreate it, because a blind re-create would undo that delete and, for an unpublished page, restore the row WITHOUT its content. Re-fetch the page and re-apply the edit.`);for(let h of u)if(!d.has(h))throw new Er.SdkError(Ie.VERSION_CONFLICT_CODE,`Generative-page file '${h}' is on the server but absent from this page's baseline \u2014 another writer added it after the page was fetched, so its contents cannot be verified. Refusing to write over or delete it. Re-fetch the page so the addition is part of your baseline.`);let f=new Map(s.map(({row:h,etag:y})=>{var w;return[(0,Pt.normalizeGuid)(String((w=h[Nr])!==null&&w!==void 0?w:""),Nr),y]}));for(let[h,y]of Object.entries(i??{})){let w=h.toLowerCase();if(!u.has(w))continue;let N=f.get(w);if(!y||!N)throw new Er.SdkError(Ie.VERSION_CONFLICT_CODE,`Cannot verify generative-page file '${w}' before writing: ${y?"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(y!==N)throw new Er.SdkError(Ie.VERSION_CONFLICT_CODE,`Generative-page file '${w}' changed on the server after this page was fetched (baseline ${y}, server ${N}) \u2014 another writer edited it. A file row accepts no If-Match validator, so this push would silently overwrite that change. Re-fetch the page and re-apply the edit.`)}}let p=`/${On}(${o})`;(0,Ie.ensureSuccess)(await e.patch(p,{name:a.name},{headers:{"If-Match":"*"}}),e.apiUrl(p));for(let f of a.files){let h=(0,Pt.normalizeGuid)(f.id,"file id");await r_(e,o,f,!u.has(h))}for(let f of u)c.has(f)||await(0,Ie.deleteRecord)(e,Na,f);try{return{id:o,...e_(o,await ZI(e,o,c))}}catch(f){return{id:o,etag:null,memberEtags:{},warnings:[`The generative page was written, but re-reading its concurrency tokens failed (${f instanceof Error?f.message:String(f)}). The local baseline is now unusable: re-fetch the page before editing it again \u2014 the next push will refuse rather than overwrite blind.`]}}},delete(e,t){return(0,Ie.deleteRecord)(e,On,t)}};function t_(e,t){var r;if(((r=t.files)!==null&&r!==void 0?r:[]).some(i=>i.content.status==="available")&&!e.supportsBinaryPatch)throw new Er.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED","Refusing to write this generative page: it has file content to upload, but the injected HttpClient does not implement patchRaw(). A Dataverse File column is not writable through a JSON body, so proceeding would create the page and its rows and then fail, leaving a page whose source never uploaded.")}async function r_(e,t,r,n){let i=(0,Pt.normalizeGuid)(r.id,"file id"),a;if(n){let o=`/${Na}`,s=(0,Ie.ensureSuccess)(await e.post(o,(0,Ie.withClientMintedId)({filename:r.name,filetype:r.fileType,[`${Ea}@odata.bind`]:`/${On}(${t})`},Nr,i)),e.apiUrl(o));a=(0,Ie.readEtag)(s)}else{let o=`/${Na}(${i})`,s=(0,Ie.ensureSuccess)(await e.patch(o,{filename:r.name,filetype:r.fileType},{headers:{"If-Match":"*"}}),e.apiUrl(o));a=(0,Ie.readEtag)(s)}return r.content.status==="available"&&await xG(e,i,r.name,r.content.data),{id:i,etag:a}}});var l_=g(Ia=>{"use strict";Object.defineProperty(Ia,"__esModule",{value:!0});Ia.genPageRegistration=Ia.GenPageAdapter=void 0;var LG=i_(),kG=Yt(),Rn=cr(),s_=bt(),a_=2e8;function o_(e){return typeof e=="string"&&e.trim()!==""?e:(0,s_.newId)()}function Da(e){return(0,Rn.isJsonObject)(e)?e:{}}function MG(e){let t=Da(e);return t.status==="available"&&typeof t.data=="string"?{status:"available",data:t.data}:{status:"unavailable",reason:"unpublished"}}var $u=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var r,n;let i=t,a=Da(i?.project),o=Array.isArray(i?.files)?i.files:[];return{id:String((r=a.uxagentprojectid)!==null&&r!==void 0?r:""),name:String((n=a.name)!==null&&n!==void 0?n:""),files:o.map(s=>{var l,u,c;let d=Da(s);return{id:String((l=d.uxagentprojectfileid)!==null&&l!==void 0?l:""),name:String((u=d.filename)!==null&&u!==void 0?u:""),fileType:Number((c=d.filetype)!==null&&c!==void 0?c:a_),content:MG(d.content)}})}}toApiPayload(t){var r;return{name:t.name,files:((r=t.files)!==null&&r!==void 0?r:[]).map(n=>({id:n.id,name:n.name,fileType:n.fileType,content:n.content}))}}createDefault(t){var r,n;return{id:o_(t.id),name:(r=t.name)!==null&&r!==void 0?r:"New page",files:((n=t.files)!==null&&n!==void 0?n:[]).map(i=>{var a,o,s;return{id:o_(i.id),name:(a=i.name)!==null&&a!==void 0?a:"index.tsx",fileType:(o=i.fileType)!==null&&o!==void 0?o:a_,content:(s=i.content)!==null&&s!==void 0?s:{status:"available",data:""}}})}}assignMissingIds(t){let r=Da(t);return(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,s_.newId)()),r}validate(t){let r=[],n=t.files;if(n!==void 0&&!Array.isArray(n))return r.push((0,Rn.issue)("/files","files-must-be-array",`files must be an array, got ${typeof n}`)),r;let i=new Map;return(Array.isArray(n)?n:[]).forEach((a,o)=>{let s=`/files/${o}`,l=Da(a),u=typeof l.id=="string"?l.id.trim().toLowerCase():"";if(u==="")r.push((0,Rn.issue)(s,"file-id-required","a generative-page file needs an id"));else{let f=i.get(u);f!==void 0?r.push((0,Rn.issue)(s,"file-id-duplicate",`two files share the id '${l.id}' (also at /files/${f}); a file's id is its identity, so a duplicate makes an edit ambiguous`)):i.set(u,o)}let c=typeof l.name=="string"?l.name:"";(c===""||/[\u0000-\u001F\u007F]/.test(c)||/[\\/]/.test(c))&&r.push((0,Rn.issue)(s+"/name","file-name-invalid",`a file name must be a non-empty single path segment with no control characters or path separators (it is sent as an HTTP header on upload); got '${c}'`));let d=l.content;if(d===void 0){r.push((0,Rn.issue)(s+"/content","file-content-required","content is required: omitting it is indistinguishable from an empty file, and the two have opposite effects on the next push"));return}let p=Da(d);p.status==="available"?typeof p.data!="string"&&r.push((0,Rn.issue)(s+"/content/data","file-content-data-invalid","available content needs base64 `data`")):p.status!=="unavailable"&&r.push((0,Rn.issue)(s+"/content/status","file-content-status-invalid",`content.status must be 'available' or 'unavailable', got ${String(p.status)}`))}),r}};Ia.GenPageAdapter=$u;function UG(){return{adapter:new $u,api:LG.genPageApi,publish:(e,t)=>(0,kG.publishGenPageById)(e,t),publishScope:e=>({envelope:"uxagentproject",targetIds:[e]})}}Ia.genPageRegistration=UG});var c_=g(Vu=>{"use strict";Object.defineProperty(Vu,"__esModule",{value:!0});Vu.reconcileBpfSecurityRoles=void 0;var qu=be(),Hm=ee(),BG="Global",u_={create:"Create",read:"Read",write:"Write",delete:"Delete"};async function $G(e,t){var r,n;let i=`/EntityDefinitions(LogicalName='${t}')?$select=LogicalName,Privileges`,o=(n=(r=(0,qu.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(u_).forEach(u=>{let c=o.find(d=>d.PrivilegeType===u_[u]);if(c){let d=(0,Hm.normalizeGuid)(c.PrivilegeId,"PrivilegeId");s[u]=d,l.add(d)}}),{byAccess:s,all:l}}async function qG(e,t){var r,n;let i=`/RetrieveRolePrivilegesRole(RoleId=${t})`,o=(n=(r=(0,qu.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,Hm.normalizeGuid)(s.PrivilegeId,"PrivilegeId")))}async function VG(e,t,r){if(r.length===0)return;let n={Privileges:r.map(a=>({Depth:BG,PrivilegeId:a}))},i=`/roles(${t})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;(0,qu.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function GG(e,t,r){let n={Privilege:{"@odata.type":"Microsoft.Dynamics.CRM.privilege",privilegeid:r}},i=`/roles(${t})/Microsoft.Dynamics.CRM.RemovePrivilegeRole`;(0,qu.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function zG(e,t,r){var n;if(!r||r.length===0)return;let i=await $G(e,t.toLowerCase());for(let a of r){let o=(0,Hm.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 qG(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 VG(e,o,c);for(let p of d)await GG(e,o,p)}}Vu.reconcileBpfSecurityRoles=zG});var h_=g(zu=>{"use strict";Object.defineProperty(zu,"__esModule",{value:!0});zu.bpfApi=void 0;var Fn=Mn(),WG=Kt(),Xt=be(),Dr=ee(),jG=c_(),Gu={"Content-Type":"application/json",Accept:"application/json"},HG=`category eq ${Fn.WorkflowCategory.BusinessProcessFlow} and type eq ${Fn.WorkflowTypeCode.Definition} and businessprocesstype eq ${Fn.BusinessProcessType.BusinessFlow}`,QG="workflowid,name,description,primaryentity,statecode,category,type,businessprocesstype,processorder",JG="workflowid,name,uniquename,description,primaryentity,statecode,statuscode,category,type,businessprocesstype,processorder,xaml,clientdata",XG=["xaml","name","description","processorder"];async function d_(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,jG.reconcileBpfSecurityRoles)(e,n,t.securityRoles)}async function Qm(e,t,r){var n;if(r==="Draft")return null;let i=(0,Dr.normalizeGuid)(t,"workflowid"),a={statecode:Fn.StateCode.Activated,statuscode:Fn.StatusCode.Activated},o=`/workflows(${i})`,s=(0,Xt.ensureSuccess)(await e.patch(o,a,{headers:Gu}),e.apiUrl(o));return(n=(0,Xt.readEtag)(s))!==null&&n!==void 0?n:await m_(e,i)}async function m_(e,t){let r=`/workflows(${t})${(0,Dr.odataQuery)([["$select","workflowid"]])}`,n=await e.get(r);return n.status>=200&&n.status<300?(0,Xt.readEtag)(n):null}async function KG(e,t){var r;let n=`/workflows(${t})${(0,Dr.odataQuery)([["$select","statecode"]])}`,i=await e.get(n);if(i.status<200||i.status>=300)return null;let a=(r=i.body)===null||r===void 0?void 0:r.statecode;return a==null?null:Number(a)}async function p_(e,t,r){if(await KG(e,t)!==Fn.StateCode.Activated)return!1;let n={statecode:Fn.StateCode.Draft,statuscode:Fn.StatusCode.Draft},i=`/workflows(${t})`,a={...Gu};return r&&(a["If-Match"]=r),(0,Xt.ensureSuccess)(await e.patch(i,n,{headers:a}),e.apiUrl(i)),!0}async function f_(e,t){try{await Qm(e,t,"Active")}catch{}}function YG(e){let t={};for(let r of XG)e[r]!==void 0&&(t[r]=e[r]);return t}zu.bpfApi={async get(e,t){let n=`/workflows(${(0,Dr.normalizeGuid)(t,"id")})${(0,Dr.odataQuery)([["$select",JG]])}`,i=(0,Xt.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,Xt.readEtag)(i)}},async list(e,t){let r=[HG];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,Dr.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,Dr.odataQuery)([["$select",QG],["$filter",r.join(" and ")]])}`;return(await(0,WG.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,Dr.normalizeGuid)(r.record.workflowid,"workflowid"),i="/workflows",a=(0,Xt.ensureSuccess)(await e.post(i,r.record,{headers:Gu}),e.apiUrl(i)),o=null;try{o=await Qm(e,n,r.status),await d_(e,r)}catch(s){try{await(0,Xt.deleteRecord)(e,"workflows",n)}catch{}throw s}return{id:n,etag:o??(0,Xt.readEtag)(a)}},async update(e,t,r,n){var i;let a=r,o=(0,Dr.normalizeGuid)(t,"id"),s=await p_(e,o,n);try{let l=`/workflows(${o})`,u={...Gu};n&&!s&&(u["If-Match"]=n);let c=(0,Xt.ensureSuccess)(await e.patch(l,YG(a.record),{headers:u}),e.apiUrl(l)),d=await Qm(e,o,a.status);return await d_(e,a),{id:o,etag:(i=d??(0,Xt.readEtag)(c))!==null&&i!==void 0?i:await m_(e,o)}}catch(l){throw s&&await f_(e,o),l}},async delete(e,t){let r=(0,Dr.normalizeGuid)(t,"id"),n=await p_(e,r,null);try{await(0,Xt.deleteRecord)(e,"workflows",r)}catch(i){throw n&&await f_(e,r),i}}}});var Y_=g(Ta=>{"use strict";Object.defineProperty(Ta,"__esModule",{value:!0});Ta.bpfRegistration=Ta.BpfAdapter=void 0;var _a=ws(),ZG=wl(),Wu=Mn(),e7=h_(),Jm=mn(),ci=Gn(),__=In(),Ft=cr(),xn=bt(),Ir=ie(),t7=100,Km='<?xml version="1.0" encoding="utf-16"?>',g_=1033,P_="mxswa:Workflow",r7="mxswa:ActivityReference.Properties",n7="mcwo:StepLabel",i7="mcwb:Control",v_="mcwb:Control.ControlDisplayName",T_="mcwb:Control.DataFieldName",O_="DataFieldName",y_="ControlDisplayName",R_="Literal",ju="x:Null",b_="x:String",Ym="x:Key",Zm="DisplayName",Qu="Activities",a7="StepLabels",F_="StageId",x_="StageCategory",L_="NextStageId",k_="ProcessStepId",eh="IsProcessRequired",M_="EntityComposite",U_="StageComposite",B_="StepComposite";function Xm(e){return(0,Ft.isJsonObject)(e)?e:{}}function _r(e){if(!e)return[];let t=[],r=e.childNodes;for(let n=0;n<r.length;n+=1){let i=r[n];i.nodeType===1&&t.push(i)}return t}function di(e,t){var r;return(r=_r(e).find(n=>n.tagName===t))!==null&&r!==void 0?r:null}function Pr(e){return di(e,r7)}function ht(e,t){var r;return(r=_r(e).find(n=>n.getAttribute(Ym)===t))!==null&&r!==void 0?r:null}function Pa(e,t){var r;return((r=e.getAttribute("AssemblyQualifiedName"))!==null&&r!==void 0?r:"").includes(t)}function Zr(e){var t;return!e||!e.firstChild?"":(t=e.firstChild.nodeValue)!==null&&t!==void 0?t:""}function $_(e,t,r){e.firstChild?e.firstChild.nodeValue=r:e.appendChild(t.createTextNode(r))}function us(e){var t;let r=(t=e.getAttribute(Zm))!==null&&t!==void 0?t:"",n=r.indexOf(": ");return n>=0?r.slice(n+2):r}function q_(e,t){var r;let n=(r=e.getAttribute(Zm))!==null&&r!==void 0?r:"",i=n.indexOf(": ");e.setAttribute(Zm,i>=0?n.slice(0,i+2)+t:t)}function V_(e,t){let r=ht(e,a7),n=di(r,n7);n&&n.setAttribute("Description",t)}function o7(e){let t=ht(e,x_);if(!t||t.tagName===ju)return;let r=Zr(t).trim();return r===""?void 0:Number(r)}function s7(e){let t=ht(e,L_);if(!t||t.tagName===ju)return;let r=Zr(t).trim();return r===""?void 0:r}function G_(e){let t=z_(e);if(!t)return;let r=j_(t,O_,T_);return r===""?void 0:r}function th(e,t){let r=_r(e);for(;r.length>0;){let n=r.pop();if(n.tagName===t)return n;for(let i of _r(n))r.push(i)}return null}function z_(e){let t=ht(Pr(e),Qu);return t?th(t,i7):null}function W_(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 j_(e,t,r){var n;return W_(e,t)?(n=e.getAttribute(t))!==null&&n!==void 0?n:"":p7(e,r)}function w_(e,t,r,n){if(W_(e,t)){e.setAttribute(t,n);return}if(di(e,r)){l7(e,r,n);return}throw new Ir.InvalidArgumentError(`BPF step control exposes neither a '${t}' attribute nor a <${r}> wrapper to bind a column`)}function l7(e,t,r){let n=di(e,t),i=n?th(n,R_):null;i&&i.setAttribute("Value",r)}function H_(e){return us(e)}function Ju(e){let t=di(e,P_),r=[];for(let n of _r(t).filter(i=>Pa(i,M_))){let i=ht(Pr(n),Qu);for(let a of _r(i).filter(o=>Pa(o,U_)))r.push({el:a,entity:H_(n)})}return r}function rh(e){let t=ht(Pr(e),Qu);return _r(t).filter(r=>Pa(r,B_))}function u7(e){let t=Pr(e),r=Zr(ht(t,eh)).trim().toLowerCase(),n=G_(e),i={id:Zr(ht(t,k_)),name:us(e)};return n!==void 0&&(i.fieldName=n),r==="true"&&(i.required=!0),i}function c7(e,t){let r=Pr(e),n=o7(r),i=s7(r),a={id:Zr(ht(r,F_)),name:us(e),entityLogicalName:t,steps:rh(e).map(u7)};return n!==void 0&&(a.category=n),i!==void 0&&(a.nextStageId=i),a}function d7(e){return Ju(e).map(({el:t,entity:r})=>c7(t,r))}function Yr(e){return new Ir.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 p7(e,t){var r;let n=di(e,t),i=n?th(n,R_):null;return(r=i?.getAttribute("Value"))!==null&&r!==void 0?r:""}function nh(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(nh(e,s)):s.nodeType===3&&n.appendChild(e.createTextNode((r=s.nodeValue)!==null&&r!==void 0?r:""))}return n}function Q_(e){return ht(Pr(e),Qu)}function f7(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,xn.newId)(),{body:o}=Xu(ih(i,(0,_a.v4)(),t.id,a));return nh(e,Ju((0,ci.parseXmlRoot)(o,"<Activity/>"))[0].el)}function m7(e,t){let{body:r}=Xu(ih("account",(0,_a.v4)(),(0,_a.v4)(),t.id));return nh(e,rh(Ju((0,ci.parseXmlRoot)(r,"<Activity/>"))[0].el)[0])}function J_(e,t){for(;e.firstChild;)e.removeChild(e.firstChild);for(let r of t)e.appendChild(r)}function X_(e,t,r,n){let i=ht(e,r);if(!i||!i.parentNode){if(n!==void 0&&n!=="")throw Yr(`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!==ju){let s=t.createElement(ju);s.setAttribute(Ym,r),a.replaceChild(s,i)}return}if(i.tagName===b_){Zr(i)!==n&&$_(i,t,n);return}let o=t.createElement(b_);o.setAttribute(Ym,r),o.appendChild(t.createTextNode(n)),a.replaceChild(o,i)}function h7(e,t,r){X_(e,t,x_,r===void 0?void 0:String(r))}function g7(e,t,r){X_(e,t,L_,r)}function K_(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 A_(e){return Zr(ht(Pr(e),F_))}function C_(e){return Zr(ht(Pr(e),k_))}function S_(e,t,r){var n,i,a,o;let s=Pr(e);r.name!==us(e)&&(q_(e,r.name),V_(s,r.name));let l=Zr(ht(s,eh)).trim().toLowerCase()==="true";if(((n=r.required)!==null&&n!==void 0?n:!1)!==l){let u=ht(s,eh);u&&$_(u,t,r.required?"True":"False")}if(((i=r.fieldName)!==null&&i!==void 0?i:"")!==((a=G_(e))!==null&&a!==void 0?a:"")){let u=z_(e);if(!u)throw new Ir.InvalidArgumentError("BPF step has no <mcwb:Control> element to bind a column to");let c=(o=r.fieldName)!==null&&o!==void 0?o:"";w_(u,O_,T_,c),c!==""&&j_(u,y_,v_)===""&&w_(u,y_,v_,c)}}function E_(e,t,r,n){var i;let a=Pr(e);if(!a)throw new Ir.InvalidArgumentError("BPF stage composite has no <\u2026ActivityReference.Properties>");if(r.name!==us(e)&&(q_(e,r.name),V_(a,r.name)),h7(a,t,r.category),g7(a,t,n),r.relationshipName&&r.relationshipName.trim()!=="")throw Yr("a stage relationship / table change (multi-table authoring)");if(r.actions&&r.actions.length>0||r.branch)throw Yr("stage actions or conditional branching");let o=Q_(e);if(!o)throw new Ir.InvalidArgumentError("BPF stage has no [Activities] collection");let s=(i=r.steps)!==null&&i!==void 0?i:[];if(s.length===0)throw new Ir.InvalidArgumentError(`BPF stage '${r.name}' must have at least one step`);let l=rh(e);if(K_(l,s.map(d=>d.id),C_)){l.forEach((d,p)=>S_(d,t,s[p]));return}let u=new Map(l.map(d=>[C_(d),d]));if(_r(o).some(d=>!Pa(d,B_)))throw Yr("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:m7(t,d)});J_(o,c),c.forEach((d,p)=>S_(d,t,s[p]))}function v7(e,t,r){let n=di(e,P_);if(!n)throw new Ir.InvalidArgumentError("BPF xaml has no <mxswa:Workflow> root activity");if(r.globalActions&&r.globalActions.length>0)throw Yr("global (process-completed/abandoned) actions");if(!r.stages||r.stages.length===0)throw new Ir.InvalidArgumentError("a BPF must have at least one stage");let i=Ju(e),a=i.map(p=>p.el);if(K_(a,r.stages.map(p=>p.id),A_)){i.forEach(({el:p,entity:f},h)=>{let y=r.stages[h];if(y.entityLogicalName&&y.entityLogicalName.trim()!==""&&y.entityLogicalName!==f)throw Yr(`changing a stage's table ('${y.entityLogicalName}' vs the process's '${f}')`);E_(p,t,y,y.nextStageId)});return}let o=_r(n).filter(p=>Pa(p,M_));if(o.length!==1)throw Yr("adding, removing or reordering stages on a multi-table process");let s=o[0],l=H_(s),u=Q_(s);if(!u)throw new Ir.InvalidArgumentError("BPF primary entity composite has no [Activities] collection");if(_r(u).some(p=>!Pa(p,U_)))throw Yr("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 Yr(`a stage on a different table ('${p.entityLogicalName}') than the process primary ('${l}')`);let c=new Map(a.map(p=>[A_(p),p])),d=r.stages.map(p=>{var f;return(f=c.get(p.id))!==null&&f!==void 0?f:f7(t,p,l)});J_(u,d),d.forEach((p,f)=>{let h=f<d.length-1?r.stages[f+1].id:void 0;E_(p,t,r.stages[f],h)})}function Xu(e){let t=e.match(/^<\?xml[^>]*\?>\s*/),r=t?t[0]:"";return{prolog:r,body:e.slice(r.length)}}function y7(e){var t,r,n,i,a,o;(0,__.installDomShim)();let s=(t=e.bag)===null||t===void 0?void 0:t.xaml;if(s){let p=new ZG.DOMParser().parseFromString("<root/>","text/xml"),f={n:"Activity",a:(0,Jm.mergeAttrs)(s.a,[]),c:(0,Jm.spliceChildren)(s.c,[])};return{root:(0,Jm.rebuildRaw)(f,(0,ci.domEngine)(p),null),prolog:(n=(r=e.bag)===null||r===void 0?void 0:r.xamlProlog)!==null&&n!==void 0?n:Km,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=ih(e.entityLogicalName,(0,_a.v4)(),l?.id&&l.id.trim()!==""?l.id:(0,_a.v4)(),u?.id&&u.id.trim()!==""?u.id:(0,_a.v4)()),{body:d}=Xu(c);return{root:(0,ci.parseXmlRoot)(d,"<Activity/>"),prolog:Km,eol:"lf"}}function b7(e){let{root:t,prolog:r,eol:n}=y7(e);v7(t,t.ownerDocument,e);let i=(0,ci.serializeNode)(t);return n==="crlf"&&(i=i.replace(/\n/g,`\r+`)),r+i}function w7(e){return e.uniqueName&&e.uniqueName.trim()!==""?e.uniqueName:`new_${(e.name||"businessprocessflow").toLowerCase().replace(/[^a-z0-9]/g,"")||"businessprocessflow"}`}var Hu=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var r,n;(0,__.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}=Xu(a),u=(0,ci.parseXmlRoot)(l,"<Activity/>");o.stages=d7(u),o.bag={xaml:(0,ci.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,xn.newId)(),name:t.name,uniquename:w7(t),primaryentity:t.entityLogicalName,xaml:b7(t),category:Wu.WorkflowCategory.BusinessProcessFlow,type:Wu.WorkflowTypeCode.Definition,businessprocesstype:Wu.BusinessProcessType.BusinessFlow,scope:Wu.WorkflowScope.Organization,processorder:(r=t.order)!==null&&r!==void 0?r:t7};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 Ir.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(D_):[D_({id:(0,xn.newId)(),name:"New Stage",steps:[]})],o={id:t.id&&t.id.trim()!==""?t.id:(0,xn.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=Xm(t);(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,xn.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,Ft.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,Ft.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=Xm(l),p=typeof d.id=="string"?d.id.trim():"";p===""?r.push((0,Ft.issue)(`${c}/id`,"stage-id-required","a stage needs an id")):o.has(p.toLowerCase())?r.push((0,Ft.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,Ft.issue)(`${c}/steps`,"stage-needs-step","a BPF stage must have at least one step")),f.length>30&&r.push((0,Ft.issue)(`${c}/steps`,"too-many-steps",`a stage allows at most 30 steps, got ${f.length}`));let h=new Map;f.forEach((y,w)=>{let N=`${c}/steps/${w}`,D=typeof Xm(y).id=="string"?y.id.trim():"";D===""?r.push((0,Ft.issue)(`${N}/id`,"step-id-required","a step needs an id")):h.has(D.toLowerCase())?r.push((0,Ft.issue)(`${N}/id`,"step-id-duplicate",`two steps in this stage share the id '${y.id}'`)):h.set(D.toLowerCase(),w)}),l.branch&&!N_(i,l.branch.nextStageId)&&r.push((0,Ft.issue)(`${c}/branch/nextStageId`,"branch-target-unknown",`branch nextStageId '${l.branch.nextStageId}' does not match any stage id`)),typeof l.nextStageId=="string"&&l.nextStageId!==""&&!N_(i,l.nextStageId)&&r.push((0,Ft.issue)(`${c}/nextStageId`,"next-stage-unknown",`nextStageId '${l.nextStageId}' does not match any stage id`))}),a.size>5&&r.push((0,Ft.issue)("/stages","too-many-tables",`a BPF spans at most 5 tables, got ${a.size}`));let s=A7(i);return s>=0&&r.push((0,Ft.issue)(`/stages/${s}/nextStageId`,"next-stage-cycle","the stage nextStageId links form a cycle; the flow must be acyclic")),r}};Ta.BpfAdapter=Hu;function A7(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 N_(e,t){return e.some(r=>r.id===t)}function D_(e){var t,r;let n=e.steps&&e.steps.length>0?e.steps.map(I_):[I_({id:(0,xn.newId)(),name:"New Step"})],i={id:e.id&&e.id.trim()!==""?e.id:(0,xn.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 I_(e){var t;let r={id:e.id&&e.id.trim()!==""?e.id:(0,xn.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 ih(e,t,r,n){return`${Km}<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="${g_}" /></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="${g_}" /></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 C7(){return{adapter:new Hu,api:e7.bpfApi,languageSensitive:!0}}Ta.bpfRegistration=C7});var Z_=g(Ku=>{"use strict";Object.defineProperty(Ku,"__esModule",{value:!0});Ku.buildRegistrations=void 0;var S7=P2(),E7=z2(),N7=wd(),D7=nI(),I7=CI(),_7=BI(),P7=YI(),T7=l_(),O7=Y_();function R7(e){let t=new Map;return t.set("form",(0,S7.formRegistration)(e)),t.set("view",(0,E7.viewRegistration)()),t.set("businessRule",(0,N7.businessRuleRegistration)()),t.set("app",(0,D7.appRegistration)(e)),t.set("command",(0,I7.commandRegistration)()),t.set("chart",(0,_7.chartRegistration)()),t.set("dashboard",(0,P7.dashboardRegistration)(e)),t.set("genPage",(0,T7.genPageRegistration)()),t.set("bpf",(0,O7.bpfRegistration)()),t}Ku.buildRegistrations=R7});var l1=g(Re=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.removeRowSummary=Re.configureRowSummary=Re.buildGptDynamicPrompt=Re.setAppAiFeatures=Re.getAiReadiness=Re.saveSettingValue=Re.retrieveSetting=Re.AI_GATE=void 0;var sr=be(),Xe=ee(),e1=bt(),en=ie();Re.AI_GATE={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabled",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"EnableNLGridSearch",nlChart:"NLChartVisualizationSetting",summaries:"EnableFormInsights",m365:"m365copilotmodelappenabled"};var i1={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabledOnByDefault",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"NLGridSearchSetting",nlChart:"NLChartDataVisualizationSetting",m365:"m365copilotmodelappenabled"},F7=new Set(Object.entries(Re.AI_GATE).filter(([e,t])=>i1[e]===t).map(([e])=>e)),x7={formFill:{enabled:"2",disabled:"1"},formFillSuggestions:{enabled:"2",disabled:"1"},formFillSmartPaste:{enabled:"2",disabled:"1"},formFillFiles:{enabled:"2",disabled:"1"}};function ah(e){return x7[e]}var Yu=1e6;function L7(e,t){let r=ah(t),n=()=>{throw new en.InvalidArgumentError(`setAppAiFeatures: '${t}' must be a boolean or an integer between 0 and ${Yu} (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>Yu?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(Yu).length||Number(s)>Yu?n():s}}return n()}function k7(e,t){let r=ah(t);return r?e===r.enabled:e!=="0"}async function M7(e,t){var r,n,i;let a=`/appmodules${(0,Xe.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,Xe.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 U7(e,t){var r,n;let i=`/appmodules${(0,Xe.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,Xe.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 t1=new WeakMap;async function B7(e,t){var r,n,i;let a=t1.get(e);if(a||(a=new Map,t1.set(e,a)),a.has(t))return a.get(t);let o=`/settingdefinitions${(0,Xe.odataQuery)([["$select","settingdefinitionid"],["$filter",`uniquename eq '${(0,Xe.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 $7(e,t,r){var n,i;let a=await B7(e,r);if(!t||!a)return;let o=`/appsettings${(0,Xe.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 q7=4,V7=500,r1=20,n1=3e4;function G7(e){if(e===void 0)return q7;if(!Number.isFinite(e))throw new en.InvalidArgumentError(`setAppAiFeatures: verifyAttempts must be a finite integer between 1 and ${r1}; got ${e}.`);return Math.min(r1,Math.max(1,Math.floor(e)))}function z7(e){if(e===void 0)return V7;if(!Number.isFinite(e))throw new en.InvalidArgumentError(`setAppAiFeatures: verifyDelayMs must be a finite number between 0 and ${n1}; got ${e}.`);return Math.min(n1,Math.max(0,Math.floor(e)))}function W7(e){return e>0?new Promise(t=>setTimeout(t,e)):Promise.resolve()}async function j7(e,t,r,n,i,a,o){let s,l,u,c=!1;for(let d=0;d<a;d+=1){d>0&&await W7(o*d);let p;try{let f=await t();f?(p=await $7(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 Zu(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 a1(e,t,r){if(t===2)return String(e).toLowerCase()==="true";let n=r?ah(r):void 0;return n?e===n.enabled:e!=null&&e!=="0"&&e!==""}async function Zu(e,t,r={}){var n,i;let a=[`SettingName='${(0,Xe.odataPathLiteral)(t)}'`];r.appUniqueName&&a.push(`AppUniqueName='${(0,Xe.odataPathLiteral)(r.appUniqueName)}'`);let o=`/RetrieveSetting(${a.join(",")})`,l=(i=(n=(0,sr.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}}Re.retrieveSetting=Zu;async function o1(e,t,r,n={}){let i={SettingName:t,Value:r};n.appUniqueName&&(i.AppUniqueName=n.appUniqueName),n.solutionUniqueName&&(i.SolutionUniqueName=n.solutionUniqueName),(0,sr.ensureSuccess)(await e.post("/SaveSettingValue",i),e.apiUrl("/SaveSettingValue"))}Re.saveSettingValue=o1;async function H7(e,t={}){let r={};for(let[n,i]of Object.entries(Re.AI_GATE)){let{value:a,dataType:o}=await Zu(e,i,t);r[n]={enabled:a1(a,o,n),setting:i,value:a}}return r}Re.getAiReadiness=H7;async function Q7(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=G7(n.verifyAttempts),s=z7(n.verifyDelayMs),l=[];for(let[y,w]of Object.entries(r)){if(w===void 0)continue;let N=i1[y];N&&l.push({feature:y,setting:N,requestedValue:L7(w,y)})}let u=[],c=n.appModuleId?(0,Xe.normalizeGuid)(n.appModuleId,"appModuleId"):void 0;if(c){let y=await U7(e,t);if(y&&(0,Xe.normalizeGuid)(y,"appModuleId")!==c)throw new en.InvalidArgumentError(`setAppAiFeatures: appModuleId '${c}' does not belong to app '${t}' (which resolves to '${y}'). 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 M7(e,t)),d),f=new Map,h=async y=>{if(F7.has(y))return;let w=Re.AI_GATE[y];if(w){if(!f.has(w))try{let{value:N,dataType:D}=await Zu(e,w);f.set(w,{enabled:a1(N,D,y),setting:w,value:N})}catch{f.set(w,void 0)}return f.get(w)}};for(let{feature:y,setting:w,requestedValue:N}of l)try{await o1(e,w,N,{appUniqueName:t,solutionUniqueName:n.solutionUniqueName});let D=await j7(e,p,t,w,N,o,s),x={feature:y,setting:w,requestedValue:N,effectiveValue:D.effectiveValue,appOverrideExists:D.appOverrideExists};if(D.result==="proven")u.push({...x,status:"applied"});else if(D.result==="absent"){let F=k7(N,y)?await h(y):void 0;F&&!F.enabled?u.push({...x,status:"skipped",reason:`the write was issued and no app-scope override holding '${N}' was observed for '${w}' after ${o} attempt(s); the org readiness gate '${F.setting}' reads '${F.value}', so an environment admin must enable it before this app can turn the feature on`}):u.push({...x,status:"notPersisted",reason:`the write reported success but no app-scope override holding '${N}' was observed for '${w}' after ${o} attempt(s) \u2014 it reads '${(i=D.effectiveValue)!==null&&i!==void 0?i:""}' for this app (Dataverse can accept an app-scope write without storing it)`})}else u.push({...x,status:"unverified",reason:`the write was issued but could not be confirmed: ${(a=D.reason)!==null&&a!==void 0?a:"the app-scope override row could not be read"}. The value may or may not be in force \u2014 verify manually before relying on it.`})}catch(D){u.push({feature:y,setting:w,requestedValue:N,status:"failed",reason:D.message})}return{applied:u.filter(y=>y.status==="applied").map(y=>y.feature),skipped:u.filter(y=>y.status==="skipped").map(y=>y.feature),notPersisted:u.filter(y=>y.status==="notPersisted").map(y=>y.feature),unverified:u.filter(y=>y.status==="unverified").map(y=>y.feature),failed:u.filter(y=>y.status==="failed").map(y=>y.feature),outcomes:u}}Re.setAppAiFeatures=Q7;var J7="GptPowerPrompt",X7='{ "consumptionSource": "Api", "partnerSource": "AIBuilder", "consumptionSourceVersion": "GptApiClient"}';function s1(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:""}}Re.buildGptDynamicPrompt=s1;async function K7(e,t){var r,n;let i=`/EntityDefinitions(LogicalName='${(0,Xe.odataPathLiteral)(t)}')${(0,Xe.odataQuery)([["$select","MetadataId"]])}`;return(n=(r=(0,sr.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||r===void 0?void 0:r.MetadataId)!==null&&n!==void 0?n:""}async function Y7(e,t,r={}){var n,i,a,o,s;let l=`ais_RowSummary_${t.entityLogicalName}`,u=`/aiskillconfigs${(0,Xe.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,Xe.odataLiteral)(l)}'`],["$top",1]])}`,c=((i=(n=(0,sr.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,Xe.odataQuery)([["$select","msdyn_aitemplateid"],["$filter",`msdyn_uniquename eq '${J7}'`],["$top",1]])}`,p=((s=(o=(a=(0,sr.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,e1.newId)(),h=(0,e1.newId)(),y=JSON.stringify(s1(t)),w={ModelId:f,RunConfigurationId:h,ModelName:`${t.entityLogicalName} row summary`,TemplateId:p,CustomConfiguration:y,Source:X7,RunConfiguration:""};(0,sr.ensureSuccess)(await e.post("/AIModelPublish",w),e.apiUrl("/AIModelPublish"));try{let N=await K7(e,t.entityLogicalName),D={uniquename:l,description:`${t.entityLogicalName} row summary`,"[email protected]":`/entities(${N})`,"[email protected]":`/msdyn_aimodels(${f})`,aiskill:"RowSummary"},x=(0,sr.ensureSuccess)(await e.post("/aiskillconfigs",D),e.apiUrl("/aiskillconfigs")),F=(0,sr.requireCreatedId)(x,"aiskillconfigid","row-summary skill");return{modelId:f,aiSkillConfigId:F}}catch(N){try{await e.delete(`/msdyn_aimodels(${f})`)}catch{}throw N}}Re.configureRowSummary=Y7;async function Z7(e,t){var r,n;let i=`ais_RowSummary_${t.entityLogicalName}`,a=`/aiskillconfigs${(0,Xe.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,Xe.odataLiteral)(i)}'`],["$top",1]])}`,o=((n=(r=(0,sr.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,sr.ensureSuccess)(await e.delete(s),e.apiUrl(s)),o._aimodel_value){let l=`/msdyn_aimodels(${o._aimodel_value})`;(0,sr.ensureSuccess)(await e.delete(l),e.apiUrl(l))}}Re.removeRowSummary=Z7});var u1=g(Oa=>{"use strict";Object.defineProperty(Oa,"__esModule",{value:!0});Oa.findArtifact=Oa.resolveArtifact=void 0;var gt=ee(),tn=el(),ez=sl(),tz=be(),rz=ie();async function nz(e,t,r){var n,i,a,o,s,l,u,c,d,p,f,h;switch(t){case"app":{let y=(0,ez.unpublishedAppModulesQuery)("appmoduleid,name,appmoduleidunique",`uniquename eq '${(0,gt.odataLiteral)((n=r.uniqueName)!==null&&n!==void 0?n:"")}'`,1),N=(i=(0,tz.ensureSuccess)(await e.get(y),e.apiUrl(y)).body)===null||i===void 0?void 0:i.value,D=N&&N[0];return D?[{id:String(D.appmoduleid),name:String(D.name),appModuleIdUnique:String(D.appmoduleidunique)}]:[]}case"dashboard":return(await(0,tn.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,gt.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 y=await(0,tn.queryRecords)(e,"appaction",{select:["appactionid","buttonlabeltext"],filter:`contextvalue eq '${(0,gt.odataLiteral)((o=r.entity)!==null&&o!==void 0?o:"")}'`,top:1});return y&&y.length?[{id:String(r.entity),entity:String(r.entity)}]:[]}case"form":return(await(0,tn.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,gt.odataLiteral)((s=r.name)!==null&&s!==void 0?s:"")}' and objecttypecode eq '${(0,gt.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,tn.queryRecords)(e,"savedqueryvisualization",{select:["savedqueryvisualizationid","name"],filter:`name eq '${(0,gt.odataLiteral)((u=r.name)!==null&&u!==void 0?u:"")}' and primaryentitytypecode eq '${(0,gt.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,tn.queryRecords)(e,"savedquery",{select:["savedqueryid","name"],filter:`name eq '${(0,gt.odataLiteral)((d=r.name)!==null&&d!==void 0?d:"")}' and returnedtypecode eq '${(0,gt.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,tn.queryRecords)(e,"webresource",{select:["webresourceid","name"],filter:`name eq '${(0,gt.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,tn.queryRecords)(e,"solution",{select:["solutionid","uniquename"],filter:`uniquename eq '${(0,gt.odataLiteral)((h=r.uniqueName)!==null&&h!==void 0?h:"")}'`,top:1})||[]).map(w=>({id:String(w.solutionid),name:String(w.uniquename)}));default:return[]}}Oa.resolveArtifact=nz;async function iz(e,t,r){var n,i,a,o,s;let l=(0,gt.odataLiteral)((n=r.name)!==null&&n!==void 0?n:""),u=(0,gt.odataLiteral)((i=r.entity)!==null&&i!==void 0?i:"");if(t==="command"){let h=await(0,tn.queryRecords)(e,"appaction",{select:["appactionid"],filter:`contextvalue eq '${(0,gt.odataLiteral)((a=r.entity)!==null&&a!==void 0?a:"")}'`,top:1});return h&&h.length?String(r.entity):null}let c=az(t,l,u,r),d=t!=="app",p=await(0,tn.queryRecords)(e,c.set,{select:[c.idField],filter:c.filter,top:d?2:1});if(d&&p&&p.length>1)throw new rz.AmbiguousArtifactError(t,(s=(o=r.name)!==null&&o!==void 0?o:r.uniqueName)!==null&&s!==void 0?s:"",p.length);let f=p&&p[0]&&p[0][c.idField];return f!=null?String(f):null}Oa.findArtifact=iz;function az(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,gt.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 d1=g(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});tc.seedRecordGraph=void 0;var c1=el(),oz=Hs(),ec=ee(),sz=ie();async function lz(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,oz.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(),h=(a=p.matchOn)===null||a===void 0?void 0:a.toLowerCase(),y=[];for(let V of p.records){let M={...V.body};for(let U of(o=V.binds)!==null&&o!==void 0?o:[]){let B=U.parentEntity.toLowerCase(),z=(s=d(B))===null||s===void 0?void 0:s[U.parentIndex];if(!z)throw new sz.InvalidArgumentError(`Cannot resolve bind '${U.navProperty}' on a '${f}' record: parent '${U.parentEntity}'[${U.parentIndex}] has no created id. Seed the parent group before the child, or supply it via options.createdIds.`);let $=(0,ec.assertODataName)(await u(B),`entity set for parent '${U.parentEntity}'`),Ee=(0,ec.normalizeGuid)(z,`parent id for bind '${U.navProperty}'`);M[`${U.navProperty}@odata.bind`]=`/${$}(${Ee})`}y.push(M)}let w=h?y.map(V=>{let M=V[h];return M!=null&&M!==""?String(M):null}):y.map(()=>null),N=new Map;if(h){let V=(0,ec.assertODataName)(h,"RecordGraph matchOn key"),M=[...new Set(w.filter(U=>U!==null))];if(M.length){let U=M.map(z=>`${V} eq '${(0,ec.odataLiteral)(z)}'`).join(" or "),B=await(0,c1.queryRecords)(e,f,{select:[V,`${f}id`],filter:U,top:5e3});for(let z of B??[]){let $=z[V];$!=null&&N.set(String($).toLowerCase(),String(z[`${f}id`]))}}}let D=[],x=new Map,F=y.map((V,M)=>{let U=w[M];if(U&&N.has(U.toLowerCase()))return null;if(U){let B=U.toLowerCase(),z=x.get(B);if(z!==void 0)return z;let $=D.push(V)-1;return x.set(B,$),$}return D.push(V)-1}),X=D.length?await(0,c1.createRecordsBulk)(e,f,D):[];c[f]=y.map((V,M)=>{let U=w[M];return U&&N.has(U.toLowerCase())?N.get(U.toLowerCase()):X[F[M]]})}return{createdIds:c}}tc.seedRecordGraph=lz});var A1=g(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.getEntityPrivileges=ut.addEntityPrivilegesToRole=ut.deleteSecurityRole=ut.createPersonaRole=ut.createSecurityRole=ut.SDK_ROLE_MARKER=void 0;var lr=be(),Ke=ee(),xt=ie(),rc={read:"Read",create:"Create",write:"Write",delete:"Delete",append:"Append",appendTo:"AppendTo",assign:"Assign",share:"Share"},sh={user:"Basic",businessUnit:"Local",parentChild:"Deep",organization:"Global"},p1={user:1,businessUnit:2,parentChild:3,organization:4},oh={user:"CanBeBasic",businessUnit:"CanBeLocal",parentChild:"CanBeDeep",organization:"CanBeGlobal"};ut.SDK_ROLE_MARKER="Authored by @maker-studio/cds-maker-sdk (persona/security role).";function uz(e){return Object.prototype.hasOwnProperty.call(rc,e)?rc[e]:void 0}function cz(e){return Object.prototype.hasOwnProperty.call(sh,e)}var f1=new WeakMap,m1=new WeakMap;async function v1(e,t){var r,n;(0,Ke.assertODataName)(t,"entity logical name");let i=f1.get(e);i||(i=new Map,f1.set(e,i));let a=i.get(t);if(a)return a;let o=`/EntityDefinitions(LogicalName='${(0,Ke.odataPathLiteral)(t)}')${(0,Ke.odataQuery)([["$select","LogicalName,Privileges"]])}`,l=(n=(r=(0,lr.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 xt.InvalidArgumentError(`Entity '${t}' exposes no privileges (unknown or non-securable entity).`);return i.set(t,l),l}async function dz(e){var t,r,n;let i=m1.get(e);if(i)return i;let a=`/businessunits${(0,Ke.odataQuery)([["$select","businessunitid"],["$filter","_parentbusinessunitid_value eq null"],["$top",1]])}`,l=(n=((r=(t=(0,lr.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 xt.InvalidArgumentError("Could not resolve the root business unit.");let u=(0,Ke.normalizeGuid)(l,"businessUnitId");return m1.set(e,u),u}async function y1(e,t){var r;let n=new Map;for(let i of t){if(!i.access||i.access.length===0)throw new xt.InvalidArgumentError(`Entity '${i.entity}' privilege request has no access levels.`);let a=(r=i.scope)!==null&&r!==void 0?r:"user";if(!cz(a))throw new xt.InvalidArgumentError(`Unknown privilege scope '${a}' for entity '${i.entity}'.`);let o=await v1(e,i.entity);for(let s of i.access){let l=uz(s);if(!l)throw new xt.InvalidArgumentError(`Unknown access level '${s}' for entity '${i.entity}'.`);let u=o.find(h=>h.PrivilegeType===l);if(!u)throw new xt.InvalidArgumentError(`Entity '${i.entity}' does not support '${s}' access.`);let c=oh[a];if(u[c]===!1)throw new xt.InvalidArgumentError(`Privilege '${u.Name}' on '${i.entity}' does not support the '${a}' scope.`);let d=(0,Ke.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 h=[...p.entities].sort().join(", ");throw new xt.InvalidArgumentError(`Entities '${h}' 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=p1[a]>p1[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 pz(e,t,r,n){if(r.length===0&&!n)return;let i={Privileges:r.map(o=>({Depth:sh[o.scope],PrivilegeId:o.privilegeId}))},a=`/roles(${t})/Microsoft.Dynamics.CRM.ReplacePrivilegesRole`;(0,lr.ensureSuccess)(await e.post(a,i),e.apiUrl(a))}async function h1(e,t,r,n,i){var a,o;let s=`/${t}(${r})/${n}${(0,Ke.odataQuery)([["$select","roleid"],["$filter",`roleid eq ${i}`]])}`;return((o=(a=(0,lr.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 fz(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,Ke.normalizeGuid)(l,"teamId");if(!await h1(e,"teams",u,"teamroles_association",t)){let c=`/teams(${u})/teamroles_association/$ref`;(0,lr.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,Ke.normalizeGuid)(l,"userId");if(!await h1(e,"systemusers",u,"systemuserroles_association",t)){let c=`/systemusers(${u})/systemuserroles_association/$ref`;(0,lr.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}o.push(u)}return{teams:a,users:o}}async function g1(e,t,r){var n,i;let a=`/roles${(0,Ke.odataQuery)([["$select","roleid,description,ismanaged"],["$filter",`name eq '${(0,Ke.odataLiteral)(t)}' and _businessunitid_value eq ${r}`]])}`,l=((i=(n=(0,lr.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:"")===ut.SDK_ROLE_MARKER};if(l.some(d=>!u(d)))throw new xt.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 xt.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,Ke.normalizeGuid)(c,"roleId"):void 0}function mz(e){var t,r;return{teams:((t=e?.teams)!==null&&t!==void 0?t:[]).map(n=>(0,Ke.normalizeGuid)(n,"teamId")),users:((r=e?.users)!==null&&r!==void 0?r:[]).map(n=>(0,Ke.normalizeGuid)(n,"userId"))}}function b1(e){return e.map(t=>({entity:t.entity,privilegeName:t.privilegeName,privilegeType:t.privilegeType,scope:t.scope}))}async function w1(e,t){var r,n;let i=(r=t.name)===null||r===void 0?void 0:r.trim();if(!i)throw new xt.InvalidArgumentError("createSecurityRole: a non-empty role name is required.");let a=t.businessUnitId?(0,Ke.normalizeGuid)(t.businessUnitId,"businessUnitId"):await dz(e),o=await y1(e,(n=t.privileges)!==null&&n!==void 0?n:[]),s=mz(t.assignTo),l=await g1(e,i,a),u=l!==void 0;if(!l){let d="/roles",p={name:i,description:ut.SDK_ROLE_MARKER,"[email protected]":`/businessunits(${a})`};try{let f=(0,lr.ensureSuccess)(await e.post(d,p),e.apiUrl(d));l=(0,Ke.normalizeGuid)((0,lr.requireCreatedId)(f,"roleid","role"),"roleId")}catch(f){let h;try{h=await g1(e,i,a)}catch{h=void 0}if(!h)throw f;l=h}}await pz(e,l,o,u);let c=await fz(e,l,s);return{roleId:l,name:i,reused:u,appliedPrivileges:b1(o),assignedTeams:c.teams,assignedUsers:c.users}}ut.createSecurityRole=w1;async function hz(e,t){var r,n;let i=(r=t.persona)===null||r===void 0?void 0:r.trim();if(!i)throw new xt.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 w1(e,{name:i,businessUnitId:t.businessUnitId,privileges:a,assignTo:t.assignTo})}ut.createPersonaRole=hz;async function gz(e,t){let n=`/roles(${(0,Ke.normalizeGuid)(t,"roleId")})`;(0,lr.ensureSuccess)(await e.delete(n),e.apiUrl(n))}ut.deleteSecurityRole=gz;async function vz(e,t,r){let n=(0,Ke.normalizeGuid)(t,"roleId");if(r.length===0)throw new xt.InvalidArgumentError("addEntityPrivilegesToRole requires at least one entity privilege (an empty grant would be a silent no-op).");let i=await y1(e,r),a={Privileges:i.map(s=>({Depth:sh[s.scope],PrivilegeId:s.privilegeId}))},o=`/roles(${n})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;return(0,lr.ensureSuccess)(await e.post(o,a),e.apiUrl(o)),b1(i)}ut.addEntityPrivilegesToRole=vz;var yz=new Map(Object.keys(rc).map(e=>[rc[e],e]));async function bz(e,t){return(await v1(e,t)).map(n=>{let i=Object.keys(oh).filter(o=>n[oh[o]]!==!1),a=yz.get(n.PrivilegeType);return{name:n.Name,privilegeId:n.PrivilegeId,privilegeType:n.PrivilegeType,...a?{access:a}:{},scopes:i}})}ut.getEntityPrivileges=bz});var I1=g(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.createMakerSdk=Or.MakerSdk=Or.ALREADY_EXISTS_CODE=void 0;var C1=Dc(),wz=wd(),ce=ie(),rn=ks(),Az=vv(),S1=wv(),Cz=Dv(),Sz=Wv(),lh=jv(),Ye=Hs(),E1=qd(),nn=el(),nc=Cy(),Ra=rl(),Ez=il(),ct=Py(),Nz=Xd(),Dz=Z_(),Iz=In(),_z=bt(),Pz=Ni(),Ln=vd(),N1=Nd(),Tz=3e5,Tr=be(),kn=ee(),Fa=l1(),D1=u1(),Oz=d1(),Rz=pm(),cs=A1();Or.ALREADY_EXISTS_CODE="ARTIFACT_ALREADY_EXISTS";var ac=class{constructor(t){var r,n;this.artifactLocks=new Map,(0,Iz.installDomShim)(),this.languageCode=(r=t.languageCode)!==null&&r!==void 0?r:Pz.DEFAULT_LCID,this.cacheStalenessMs=(n=t.cacheStalenessMs)!==null&&n!==void 0?n:Tz,this.workspace=new S1.WorkspaceManager(t.workspacePath,t.instanceUrl),this.versions=new Cz.VersionManager(this.workspace),this.dataverse=new Sz.DataverseClient(t.instanceUrl,t.httpClient,t.solutionUniqueName),this.registrations=(0,Dz.buildRegistrations)(this.languageCode)}initWorkspace(){this.workspace.init()}getManifest(){return this.workspace.getManifest()}cleanWorkspace(){this.workspace.clean()}withArtifactLock(t,r,n){var i;let a=`${t}\0${(0,S1.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&&this.versions.isDirty(t,r)){let p=(a=(i=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 ce.LocalEditsWouldBeLostError(t,r,p,l);let f=this.workspace.readArtifact(t,r);if(f){let h=this.versions.getMeta(t,r);if(h&&!h.etag&&l){if(!(0,N1.deepEqual)(h.snapshot,d))throw new ce.LocalEditsWouldBeLostError(t,r,p,l);this.versions.storeMeta(t,r,{...h,etag:l,fetchedAt:(0,Tr.nowIso)()})}return(0,Ln.cloneJson)(f)}}return this.workspace.writeArtifact(t,r,d),this.versions.storeMeta(t,r,{etag:l,languageCode:this.languageCode,fetchedAt:(0,Tr.nowIso)(),snapshot:(0,Ln.cloneJson)(d),...u?{memberEtags:u}:{},...c?{siblingEtags:c}:{}}),(0,Ln.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,ct.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,Tr.nowIso)(),isDirty:!1})}catch(s){a.push({componentId:o.objectId,componentType:o.componentType,workflowCategory:o.workflowCategory,reason:"failed",error:ic(s)})}return this.workspace.updateManifest({lastSyncAt:(0,Tr.nowIso)()}),{summaries:i,skipped:a}}async fetchEntityMetadata(t){let r=await(0,lh.fetchEntityMetadataFromApi)(this.dataverse,t);return this.workspace.writeEntityMetadata(t,r),r}findTables(t,r){return(0,lh.findTables)(this.dataverse,t,r)}findColumns(t,r,n){return(0,lh.findColumns)(this.dataverse,t,r,n)}createTable(t){return(0,Ye.createTable)(this.dataverse,t)}createColumn(t,r){return(0,Ye.createColumn)(this.dataverse,t,r)}createColumns(t,r){return(0,Ye.createColumns)(this.dataverse,t,r)}updateColumn(t,r,n){return(0,Ye.updateColumn)(this.dataverse,t,r,n)}deleteColumn(t,r){return(0,Ye.deleteColumn)(this.dataverse,t,r)}setFormSecurityRoles(t,r){return(0,E1.setFormSecurityRoles)(this.dataverse,t,r)}getFormSecurityRoles(t){return(0,E1.getFormSecurityRoles)(this.dataverse,t)}validateBusinessRule(t,r){return new wz.BusinessRuleAdapter().semanticIssues(t,r)}setColumnVisualization(t,r,n){return(0,Ye.setColumnVisualization)(this.dataverse,t,r,n)}getColumnVisualization(t,r){return(0,Ye.getColumnVisualization)(this.dataverse,t,r)}createCustomerColumn(t,r){return(0,Ye.createCustomerColumn)(this.dataverse,t,r)}insertStatusValue(t,r){return(0,Ye.insertStatusValue)(this.dataverse,t,r)}updateTable(t,r){return(0,Ye.updateTable)(this.dataverse,t,r)}async setEntityIcon(t,r){if(await(0,Ye.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,kn.xmlText)(t)}</entity></entities></importexportxml>`;(0,Tr.ensureSuccess)(await this.dataverse.post("/PublishXml",{ParameterXml:n}),this.dataverse.apiUrl("/PublishXml"))}}createAlternateKey(t,r){return(0,Ye.createAlternateKey)(this.dataverse,t,r)}deleteAlternateKey(t,r){return(0,Ye.deleteAlternateKey)(this.dataverse,t,r)}createRelationship(t){return(0,Ye.createRelationship)(this.dataverse,t)}deleteRelationship(t){return(0,Ye.deleteRelationship)(this.dataverse,t)}createGlobalOptionSet(t){return(0,Ye.createGlobalOptionSet)(this.dataverse,t)}deleteGlobalOptionSet(t){return(0,Ye.deleteGlobalOptionSet)(this.dataverse,t)}deleteTable(t){return(0,Ye.deleteTable)(this.dataverse,t)}createSecurityRole(t){return(0,cs.createSecurityRole)(this.dataverse,t)}createPersonaRole(t){return(0,cs.createPersonaRole)(this.dataverse,t)}deleteSecurityRole(t){return(0,cs.deleteSecurityRole)(this.dataverse,t)}addEntityPrivilegesToRole(t,r){return(0,cs.addEntityPrivilegesToRole)(this.dataverse,t,r)}getEntityPrivileges(t){return(0,cs.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,Oz.seedRecordGraph)(this.dataverse,t,r)}resolveArtifact(t,r){return(0,D1.resolveArtifact)(this.dataverse,t,r)}findArtifact(t,r){return(0,D1.findArtifact)(this.dataverse,t,r)}async deleteAppCascade(t,r){let n=await(0,Nz.deleteAppCascade)(this.dataverse,t,r),i=(0,kn.normalizeGuid)(t,"appModuleId");return this.workspace.readArtifact("app",i)&&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,nc.createWebResource)(this.dataverse,t)}updateWebResource(t,r){return(0,nc.updateWebResource)(this.dataverse,t,r)}getWebResource(t){return(0,nc.getWebResource)(this.dataverse,t)}deleteWebResource(t){return(0,nc.deleteWebResource)(this.dataverse,t)}getAppSettings(t){return(0,Ra.readAppSettings)(this.dataverse,t)}setAppSetting(t,r,n){return(0,Ra.setAppSetting)(this.dataverse,t,r,n)}setHeaderAndNavigationRefresh(t,r){if(typeof r!="boolean")throw new ce.ValidationError("app",t,[{pointer:"/headerAndNavigationRefresh",rule:Ez.HEADER_NAV_BOOLEAN_RULE,message:`enabled must be a boolean, got ${typeof r}`}]);return(0,Ra.setAppSetting)(this.dataverse,t,Ra.HEADER_AND_NAVIGATION_REFRESH,r?Ra.APP_SETTING_ON:Ra.APP_SETTING_OFF)}getSolution(t){return(0,ct.getSolution)(this.dataverse,t)}createPublisher(t){return(0,ct.createPublisher)(this.dataverse,t)}createSolution(t){return(0,ct.createSolution)(this.dataverse,t)}setSolutionVersion(t,r){return(0,ct.setSolutionVersion)(this.dataverse,t,r)}addSolutionComponent(t){return(0,ct.addSolutionComponent)(this.dataverse,t)}removeSolutionComponent(t,r,n){return(0,ct.removeSolutionComponent)(this.dataverse,t,r,n)}exportSolution(t){return(0,ct.exportSolution)(this.dataverse,t)}importSolution(t){return(0,ct.importSolution)(this.dataverse,t)}deleteSolution(t){return(0,ct.deleteSolution)(this.dataverse,t)}async getArtifact(t,r){return this.withArtifactLock(t,r,()=>this.getArtifactUnlocked(t,r))}async getArtifactUnlocked(t,r){return(0,Ln.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 ce.StaleArtifactError(t,r,n);return this.readLocal(t,r)}readLocal(t,r){let n=this.workspace.readArtifact(t,r);if(!n)throw new ce.ArtifactNotFoundError(t,r);return n}async revalidateIfStale(t,r){let n=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(this.versions.isDirty(t,r))return"skipped";let o=this.workspace.readArtifact(t,r);await this.fetchArtifactUnlocked(t,r);let s=this.workspace.readArtifact(t,r);return(0,N1.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=rn.JsonPointer.resolve(i,n);if(a===void 0)throw new ce.PathNotFoundError(t,r,n);return a})}async findElements(t,r,n){return this.withArtifactLock(t,r,async()=>(0,Az.findElements)(await this.getArtifactUnlocked(t,r),n))}listArtifacts(t,r){return this.workspace.listArtifacts(t,r).map(n=>({...n,isDirty:this.versions.isDirty(n.type,n.id)}))}getEntityMetadata(t){let r=this.workspace.readEntityMetadata(t);if(!r)throw new ce.ArtifactNotFoundError("entityMetadata",t);return r}getFieldMetadata(t,r){let i=this.getEntityMetadata(t).attributes.find(a=>a.logicalName===r);if(!i)throw new ce.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=rn.JsonPointer.resolve(a,n);if(o===void 0)throw new ce.PathNotFoundError(t,r,n);let s=oc(o)&&oc(i)?{...o,...i}:i;return rn.JsonPointer.set(a,n,(0,Ln.cloneJson)(s)),this.assertStructurallyValid(t,r,a,n),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=rn.JsonPointer.resolve(o,n);if(s===void 0)throw new ce.PathNotFoundError(t,r,n);if(!Array.isArray(s))throw new ce.ValidationError(t,r,n,"parent must be an array");let l=this.assignMissingIds(t,(0,Ln.cloneJson)(i)),u=Lz(s,a?.position);return s.splice(u,0,l),this.assertStructurallyValid(t,r,o,n),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=rn.JsonPointer.resolve(s,n);if(l===void 0)throw new ce.PathNotFoundError(t,r,n);let u=rn.JsonPointer.resolve(s,i);if(u===void 0)throw new ce.PathNotFoundError(t,r,i);if(!Array.isArray(u))throw new ce.ValidationError(t,r,i,"move target must be an array");if(i===n||i.startsWith(`${n}/`))throw new ce.ValidationError(t,r,i,"cannot move an element into its own subtree");rn.JsonPointer.remove(s,n);let c=(o=a?.index)!==null&&o!==void 0?o:u.length;return u.splice(Math.max(0,Math.min(c,u.length)),0,l),this.assertStructurallyValid(t,r,s,i),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(rn.JsonPointer.resolve(i,n)===void 0)throw new ce.PathNotFoundError(t,r,n);return rn.JsonPointer.remove(i,n),this.assertStructurallyValid(t,r,i,xz(n)),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 ce.ValidationError(t,r,u)}retrieveSetting(t,r){return(0,Fa.retrieveSetting)(this.dataverse,t,r)}saveSettingValue(t,r,n){return(0,Fa.saveSettingValue)(this.dataverse,t,r,n)}getAiReadiness(t){return(0,Fa.getAiReadiness)(this.dataverse,t)}setAppAiFeatures(t,r,n){return(0,Fa.setAppAiFeatures)(this.dataverse,t,r,n)}configureRowSummary(t,r){return(0,Fa.configureRowSummary)(this.dataverse,t,r)}removeRowSummary(t){return(0,Fa.removeRowSummary)(this.dataverse,t)}async enrichDefaultViews(t,r,n={}){let i=await(0,Rz.findDefaultViews)(this.dataverse,t,n);for(let a of i)await this.fetchArtifact("view",a.id),await this.updateElement("view",a.id,"/columns",r),await this.pushArtifact("view",a.id);return i.length&&await this.publishArtifact("view",i[0].id),{updated:i.map(a=>a.id)}}createArtifact(t,r){let n=this.requireRegistration(t,"createArtifact"),i=n.adapter.assignMissingIds(n.adapter.createDefault(r)),a=i.id;if(!a)throw new ce.ValidationError(t,"(new)","/id","created artifact must have an id");return this.workspace.writeArtifact(t,a,i),(0,Ln.cloneJson)(i)}deleteArtifact(t,r){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),this.workspace.readArtifact(t,r)&&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:ic(u)},...s?{publishScope:s}:{}}}if(!n?.verify)return{type:t,id:r,shipped:!1,publish:{kind:"submitted"},...s?{publishScope:s}:{}};let l=await this.verifyPublished(t,r);return{type:t,id:r,shipped:l.kind==="verified",publish:l,...s?{publishScope:s}:{}}}async verifyPublished(t,r){if(t!=="app")return{kind:"unverifiable",reason:`published-projection verification is not characterised for '${t}'; the publish was submitted`};try{let n=`/appmodules(${(0,kn.normalizeGuid)(r,"id")})${(0,kn.odataQuery)([["$select","appmoduleid"]])}`,i=await this.dataverse.get(n);return i.status>=200&&i.status<300?{kind:"verified"}:{kind:"unverifiable",reason:`the published projection answered HTTP ${i.status}`}}catch(n){return{kind:"unverifiable",reason:ic(n).message}}}async pushArtifact(t,r){return this.withArtifactLock(t,r,()=>this.pushArtifactUnlocked(t,r))}async pushArtifactUnlocked(t,r){var n,i,a,o,s,l;let u=this.requireRegistration(t,"pushArtifact"),c=this.readLocal(t,r),d=this.versions.getMeta(t,r);this.assertLanguageMatches(t,r,d,u);let p=await this.buildMetadataContext(u.adapter,c),f=u.adapter.toApiPayload(c,d?.snapshot,p);try{let h=d?await u.api.update(this.dataverse,r,f,d.etag,d.memberEtags,d.siblingEtags):await this.createWithMintedId(u,t,r,f),y=r;return d||(h.serverIdentity&&u.adapter.applyServerIdentity&&u.adapter.applyServerIdentity(c,h.serverIdentity),h.id&&h.id!==r&&(c.id=h.id,this.workspace.deleteArtifact(t,r),y=h.id),this.workspace.writeArtifact(t,y,c)),this.versions.storeMeta(t,y,{etag:h.etag,languageCode:this.languageCode,fetchedAt:(0,Tr.nowIso)(),snapshot:(0,Ln.cloneJson)(c),...h.memberEtags?{memberEtags:h.memberEtags}:{},...h.siblingEtags?{siblingEtags:h.siblingEtags}:{}}),{type:t,id:y,saved:!0,shipped:!1,publish:(n=h.publish)!==null&&n!==void 0?n:{kind:"notRequested"},...h.publish&&h.publish.kind!=="notRequested"?(()=>{var w;let N=(w=u.publishScope)===null||w===void 0?void 0:w.call(u,y,c);return N?{publishScope:N}:{}})():{},...h.warnings&&h.warnings.length>0?{warnings:h.warnings}:{}}}catch(h){let y=(0,ce.readPartialTokens)(h);if(y&&d){let w={...(i=d.memberEtags)!==null&&i!==void 0?i:{},...(a=y.memberEtags)!==null&&a!==void 0?a:{}},N={...(o=d.siblingEtags)!==null&&o!==void 0?o:{},...(s=y.siblingEtags)!==null&&s!==void 0?s:{}};this.versions.storeMeta(t,r,{...d,...Object.keys(w).length>0?{memberEtags:w}:{},...Object.keys(N).length>0?{siblingEtags:N}:{}})}if(h instanceof ce.SdkError&&h.code===Or.ALREADY_EXISTS_CODE)return{type:t,id:r,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:h};if(h instanceof ce.SdkError&&h.code===C1.WFOM_API_UNAVAILABLE_CODE)return{type:t,id:r,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:h};if(h instanceof ce.SdkError&&h.code===C1.BUSINESS_RULE_LEFT_DEACTIVATED_CODE)return{type:t,id:r,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:h};if(h instanceof ce.SdkError&&h.code===Tr.VERSION_CONFLICT_CODE)return{type:t,id:r,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:new ce.VersionConflictError(t,r,(l=d?.etag)!==null&&l!==void 0?l:null,null,h.message)};throw h}}assertLanguageMatches(t,r,n,i){if(i?.languageSensitive&&!(n?.languageCode===void 0||n.languageCode===this.languageCode))throw new ce.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}.`)}async createWithMintedId(t,r,n,i){try{return await t.api.create(this.dataverse,i,n)}catch(a){throw!(a instanceof ce.SdkError)||a.code!==Tr.VERSION_CONFLICT_CODE?a:new ce.SdkError(Or.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}') to adopt the existing record's identity, etag and snapshot, then push again \u2014 that push will be a conditional update. This is not done automatically because the only recovery available here would be an UNCONDITIONAL overwrite, which would destroy any edit made to the record in the meantime.`)}}async buildMetadataContext(t,r){var n,i;let a=(i=(n=t.metadataNeeds)===null||n===void 0?void 0:n.call(t,r))!==null&&i!==void 0?i:[];if(a.length===0)return;let o=new Set(a.map(s=>s.entityLogicalName).filter(s=>!!s));for(let s of o)if(!this.workspace.readEntityMetadata(s))try{await this.fetchEntityMetadata(s)}catch{}return{resolveField:(s,l)=>{let u=this.workspace.readEntityMetadata(s),c=u?.attributes.find(d=>d.logicalName===l);return c?{displayName:c.displayName,attributeType:c.attributeType}:void 0}}}async pushAll(){let t=this.getDirtyArtifacts(),r=[];for(let n of t)try{r.push(await this.pushArtifact(n.type,n.id))}catch(i){r.push({type:n.type,id:n.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:ic(i)})}return r}getDirtyArtifacts(){return this.workspace.listArtifacts().filter(t=>this.versions.isDirty(t.type,t.id)).map(t=>({...t,isDirty:!0}))}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,_z.assignMissingIds)(r)}async resolveComponentType(t){switch(t.componentType){case ct.SolutionComponentType.SavedQuery:return"view";case ct.SolutionComponentType.SavedQueryVisualization:return"chart";case ct.SolutionComponentType.AppModule:return"app";case ct.SolutionComponentType.UxAgentProject:return"genPage";case ct.SolutionComponentType.Workflow:return t.workflowCategory===2?"businessRule":t.workflowCategory===4&&await this.isBusinessFlowWorkflow(t.objectId)?"bpf":void 0;case ct.SolutionComponentType.SystemForm:return await this.isDashboardForm(t.objectId)?"dashboard":"form";default:return}}async isDashboardForm(t){let n=`/systemforms(${(0,kn.normalizeGuid)(t,"formId")})${(0,kn.odataQuery)([["$select","type"]])}`,i=(0,Tr.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,kn.normalizeGuid)(t,"workflowId")})${(0,kn.odataQuery)([["$select","businessprocesstype"]])}`,i=(0,Tr.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 ce.NotImplementedError(r,`no adapter registered for artifact type '${t}'`);return n}};Or.MakerSdk=ac;function Fz(e){return new ac(e)}Or.createMakerSdk=Fz;function ic(e){return e instanceof Error?e:new Error(String(e))}function oc(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function xz(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function Lz(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=>oc(i)&&i.id===t.before);return n<0?e.length:n}let r=e.findIndex(n=>oc(n)&&n.id===t.after);return r<0?e.length:r+1}});var _1=g(sc=>{"use strict";Object.defineProperty(sc,"__esModule",{value:!0});sc.ARTIFACT_TYPES=void 0;sc.ARTIFACT_TYPES=["form","view","businessRule","app","command","chart","dashboard","genPage","bpf"]});var T1=g(P1=>{"use strict";Object.defineProperty(P1,"__esModule",{value:!0})});var R1=g(O1=>{"use strict";Object.defineProperty(O1,"__esModule",{value:!0})});var x1=g(F1=>{"use strict";Object.defineProperty(F1,"__esModule",{value:!0})});var k1=g(L1=>{"use strict";Object.defineProperty(L1,"__esModule",{value:!0})});var U1=g(M1=>{"use strict";Object.defineProperty(M1,"__esModule",{value:!0})});var $1=g(B1=>{"use strict";Object.defineProperty(B1,"__esModule",{value:!0})});var V1=g(q1=>{"use strict";Object.defineProperty(q1,"__esModule",{value:!0})});var z1=g(G1=>{"use strict";Object.defineProperty(G1,"__esModule",{value:!0})});var j1=g(W1=>{"use strict";Object.defineProperty(W1,"__esModule",{value:!0})});var Q1=g(H1=>{"use strict";Object.defineProperty(H1,"__esModule",{value:!0})});var X1=g(J1=>{"use strict";Object.defineProperty(J1,"__esModule",{value:!0})});var Y1=g(K1=>{"use strict";Object.defineProperty(K1,"__esModule",{value:!0})});var eP=g(Z1=>{"use strict";Object.defineProperty(Z1,"__esModule",{value:!0})});var rP=g(tP=>{"use strict";Object.defineProperty(tP,"__esModule",{value:!0})});var iP=g(nP=>{"use strict";Object.defineProperty(nP,"__esModule",{value:!0})});var oP=g(aP=>{"use strict";Object.defineProperty(aP,"__esModule",{value:!0})});var lP=g(sP=>{"use strict";Object.defineProperty(sP,"__esModule",{value:!0})});var cP=g(uP=>{"use strict";Object.defineProperty(uP,"__esModule",{value:!0})});var pP=g(dP=>{"use strict";Object.defineProperty(dP,"__esModule",{value:!0})});var kz=exports&&exports.__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=exports&&exports.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&kz(t,e,r)};Object.defineProperty(exports,"__esModule",{value:!0});exports.createMakerSdk=void 0;var Mz=I1();Object.defineProperty(exports,"createMakerSdk",{enumerable:!0,get:function(){return Mz.createMakerSdk}});_e(_1(),exports);_e(T1(),exports);_e(R1(),exports);_e(x1(),exports);_e(k1(),exports);_e(U1(),exports);_e($1(),exports);_e(V1(),exports);_e(z1(),exports);_e(j1(),exports);_e(Q1(),exports);_e(X1(),exports);_e(Y1(),exports);_e(il(),exports);_e(eP(),exports);_e(rP(),exports);_e(iP(),exports);_e(oP(),exports);_e(lP(),exports);_e(cP(),exports);_e(pP(),exports);_e(ie(),exports);diff --git a/plugins/model-apps/scripts/verify-model-app.js b/plugins/model-apps/scripts/verify-model-app.jsindex 1b5445434..d39c052ca 100644--- a/plugins/model-apps/scripts/verify-model-app.js+++ b/plugins/model-apps/scripts/verify-model-app.js@@ -25,11 +25,12 @@ function makeProvision(env, workspaceDir) {fs.mkdirSync(workspaceDir, { recursive: true });const sdk = createMakerSdk({ workspacePath: workspaceDir, instanceUrl: env, httpClient });sdk.initWorkspace();- // The httpClient is returned alongside the SDK because one read has no SDK surface: the role- // privilege check needs `EntityDefinitions(...)?$select=Privileges`, and `fetchEntityMetadata`- // projects that field away (see the `entityPrivileges` reader below). The caller must also pass- // the org URL to `readerFor` — this client takes FULL absolute request URLs, not paths.- return { sdk, httpClient };+ // Only the SDK is returned. The raw `httpClient` used to come back with it because the role+ // privilege check had no SDK surface to read `EntityDefinitions(...)?$select=Privileges`; the+ // vendored bundle now exposes `getEntityPrivileges`, so that escape hatch is gone. Handing the+ // raw transport back with no caller is worse than useless — it advertises a bypass of the SDK+ // that this file deliberately no longer takes.+ return sdk;}// Resolve the app's sitemap XML: appmodule (by unique name) -> appmodulecomponents (type 62) ->@@ -139,50 +140,34 @@ function readerFor(sdk, appUnique, opts) {};// entityPrivileges(logical): the privilege set a table exposes, as [{ PrivilegeId, PrivilegeType, ... }].- // Read from the SAME source the SDK resolves against when it WRITES the role —- // `EntityDefinitions(LogicalName='x')?$select=Privileges` — so the comparison cannot disagree with- // the write about which PrivilegeId means "Read on account".+ // Read through the SDK's `getEntityPrivileges`, which resolves the SAME source the SDK uses when it+ // WRITES a role, so the comparison cannot disagree with the write about which PrivilegeId means+ // "Read on account".//- // Deliberately NOT `sdk.fetchEntityMetadata`: that returns a PROJECTED, camelCased shape- // ({logicalName, displayName, entitySetName, attributes, relationships}) which drops `Privileges`- // entirely, so routing through it would silently report every privilege as unreadable.+ // This used to be a raw `httpClient` read of `EntityDefinitions(LogicalName='x')?$select=Privileges`,+ // because the SDK had no privilege READ at all — it could create and delete roles but never see what+ // a table exposes — and `fetchEntityMetadata` PROJECTS `Privileges` away permanently by design (its+ // `$select` never asks for them, and it is a disk-cached best-effort projection, the wrong contract+ // for a security read). That escape hatch is now retired: the vendored bundle carries the dedicated+ // method, which is the condition AGENTS.md set for making this switch.//- // The projection's omission is PERMANENT by design — its `$select` never asks for `Privileges`,- // and the SDK pins that with a guardrail test asserting the projection must not surface them even- // when the server returns them. That projection is disk-cached and documents its enrichments as- // best-effort, which is the wrong contract for a security read. Verified against the vendored- // bundle: feeding it a response that DOES carry `Privileges` still yields a projection without them.+ // Two shape differences the mapping below absorbs:+ // * The SDK returns camelCase `{ name, privilegeId, privilegeType, access?, scopes }`; the pure+ // comparison in lib/role-privileges.js reads Dataverse's PascalCase `{ Name, PrivilegeId,+ // PrivilegeType }`, which is also what the eventual `ReplacePrivilegesRole` payload speaks. The+ // comparison keeps the wire vocabulary and the adaptation happens here, at the seam.+ // * The SDK THROWS for a table that exposes no privileges (an unknown or non-securable table is an+ // error, not an answer) where the raw read returned null. verify-spec wraps every call site in a+ // try/catch and reports an unreadable entity as a FINDING, so both land in the same fail-closed+ // place — an absent privilege set is never read as "nothing missing".//- // TODO: the SDK is gaining a dedicated `getEntityPrivileges(logicalName)` — the privilege READ it- // previously lacked (it could create/delete roles but never read what a table exposes). Switch to- // it once the vendored bundle carries it, and drop this raw read. Note the SDK returns camelCased- // `{ name, privilegeId, privilegeType }` and throws when a table exposes none, where this returns- // PascalCase rows and `null`; `compareRolePrivileges` reads the PascalCase shape today, and- // verify-spec already treats a throw as a per-entity finding, so the swap is a mapping change plus- // a bundle bump — not a behaviour change.- //- // The URL must be ABSOLUTE and carry the `/api/data/v9.2` prefix. `createAzHttpClient` is the raw- // transport the SDK drives, so it receives full request URLs and enforces a same-origin check by- // parsing the argument with `new URL(url)` — a relative path throws there ("Refusing to send the- // Dataverse token to a non-absolute URL") rather than resolving against the org. That failure is- // caught per-entity in verify-spec, so a relative URL would not crash: it would silently report- // EVERY entity's privileges as unreadable and fail the role-privileges check on every live run.- //- // Wired only when BOTH the org URL and the raw client are available. When they are not, the reader- // is ABSENT rather than broken, which makes verify-spec skip the role-privileges check entirely- // (it requires both `rolePrivileges` and `entityPrivileges` to be functions) instead of reporting a- // false failure.- if (opts.httpClient && opts.envUrl) {- const apiRoot = `${String(opts.envUrl).replace(/\/+$/, '')}/api/data/v9.2`;- // Returns null on any non-2xx — verify-spec turns that into a finding rather than a pass.- base.entityPrivileges = async (logical) => {- const name = String(logical).toLowerCase();- const url = `${apiRoot}/EntityDefinitions(LogicalName='${odataLit(name)}')?$select=LogicalName,Privileges`;- const res = await opts.httpClient.get(url);- if (!res || res.status < 200 || res.status >= 300) return null;- return (res.body && res.body.Privileges) || null;- };- }+ // Still conditional on a wired SDK for the same reason as before: when the reader cannot be built+ // it must be ABSENT rather than broken, so verify-spec skips the role-privileges check entirely+ // (it requires both `rolePrivileges` and `entityPrivileges`) instead of reporting a false failure.+ base.entityPrivileges = async (logical) => {+ const rows = await sdk.getEntityPrivileges(String(logical).toLowerCase());+ return (rows || []).map((p) => ({ Name: p.name, PrivilegeId: p.privilegeId, PrivilegeType: p.privilegeType }));+ };// Only expose page-authority readers when a genpageCli is wired — absent it, verifySpec fails closed// for a page-bearing spec (Imp7/C6: missing methods → unableToRun).@@ -263,9 +248,9 @@ async function main() {const v = validateAppSpec(spec, { profile: 'deploy' });if (!v.ok) { emitResult(false, { ok: false, errors: v.errors }); return; }const workspaceDir = workspaceArg || path.join(path.dirname(specPath), '.maker-workspace');- const { sdk, httpClient } = makeProvision(env, workspaceDir);+ const sdk = makeProvision(env, workspaceDir);const genpageCli = makeGenpageCli(env);- const r = await verifySpec(spec, readerFor(sdk, appUniqueName(spec), { genpageCli, workspaceDir, httpClient, envUrl: env }));+ const r = await verifySpec(spec, readerFor(sdk, appUniqueName(spec), { genpageCli, workspaceDir }));// 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.mdindex 072d2da83..f357d6ad5 100644--- a/plugins/model-apps/skills/app-builder/SKILL.md+++ b/plugins/model-apps/skills/app-builder/SKILL.md@@ -349,7 +349,7 @@ The check is best-effort: if that read fails the build proceeds unchanged.The App Spec field `languageCode` pins the same value across runs. It now covers the **whole** build:data-model labels, and form, dashboard and sitemap labels — the SDK serializers that used to hardcode-1033 take the authoring language as an option ([#455](https://github.com/microsoft/power-platform-skills/issues/455)).+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